import { ApiService } from "../abstractions/api.service"; import { Forwarder } from "./forwarder"; import { ForwarderOptions } from "./forwarderOptions"; export class FastmailForwarder implements Forwarder { async generate(apiService: ApiService, options: ForwarderOptions): Promise { if (options.apiKey == null || options.apiKey === "") { throw "Invalid Fastmail API token."; } if (options?.fastmail.accountId == null || options.fastmail.accountId === "") { throw "Invalid Fastmail account ID."; } const requestInit: RequestInit = { redirect: "manual", cache: "no-store", method: "POST", headers: new Headers({ Authorization: "Bearer " + options.apiKey, "Content-Type": "application/json", }), }; const url = "https://api.fastmail.com/jmap/api/"; requestInit.body = JSON.stringify({ using: ["https://www.fastmail.com/dev/maskedemail", "urn:ietf:params:jmap:core"], methodCalls: [ [ "MaskedEmail/set", { accountId: "u" + options.fastmail.accountId, create: { "new-masked-email": { state: "enabled", description: (options.website != null ? options.website + " - " : "") + "Generated by Bitwarden", url: options.website, emailPrefix: options.fastmail.prefix, }, }, }, "0", ], ], }); const request = new Request(url, requestInit); const response = await apiService.nativeFetch(request); if (response.status === 200) { const json = await response.json(); if ( json.methodResponses != null && json.methodResponses.length > 0 && json.methodResponses[0].length > 0 ) { if (json.methodResponses[0][0] === "MaskedEmail/set") { return json.methodResponses[0][1]?.created?.["new-masked-email"]?.email; } else if (json.methodResponses[0][0] === "error") { throw "Fastmail error: " + json.methodResponses[0][1]?.description; } } } if (response.status === 401) { throw "Invalid Fastmail API token."; } throw "Unknown Fastmail error occurred."; } }