From 190bcaaa409e91efec2aa72a0c0ab6f571c9e914 Mon Sep 17 00:00:00 2001 From: Will McLemore Date: Wed, 25 Nov 2026 09:01:06 -0600 Subject: [PATCH] fix(security): harden MIME, attachment paths, OAuth flow, and token storage --- .gitignore | 1 - src/account-storage.ts | 86 ++++- src/gmail-oauth-flow.ts | 102 ++++-- src/gmail-service.ts | 490 +++++++++++++++++------------ src/types.ts | 1 - test/security-mime-storage.test.js | 480 ++++++++++++++++++++++++++++ 6 files changed, 917 insertions(+), 243 deletions(-) create mode 100644 test/security-mime-storage.test.js diff --git a/.gitignore b/.gitignore index b68daee..94362eb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,3 @@ dist/ .env.local *.log .DS_Store -.mailcp/ \ No newline at end of file diff --git a/src/account-storage.ts b/src/account-storage.ts index 869092b..a6a9a7a 100644 --- a/src/account-storage.ts +++ b/src/account-storage.ts @@ -1,12 +1,9 @@ +import * as crypto from "crypto"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; import type { EmailAccount } from "./types.js"; -const CONFIG_DIR = path.join(os.homedir(), ".gmcli"); -const ACCOUNTS_FILE = path.join(CONFIG_DIR, "accounts.json"); -const CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json"); - // Strip OAuth-app credentials (clientId/clientSecret) from a stored account. // Those values must come from env (Doppler) at runtime, not at-rest on disk. function sanitizeForStorage(account: EmailAccount): EmailAccount { @@ -15,35 +12,92 @@ function sanitizeForStorage(account: EmailAccount): EmailAccount { } export class AccountStorage { + private readonly configDir: string; + private readonly accountsFile: string; + private readonly credentialsFile: string; private accounts: Map = new Map(); - constructor() { + constructor(configDir?: string) { + this.configDir = configDir || path.join(os.homedir(), ".gmcli"); + this.accountsFile = path.join(this.configDir, "accounts.json"); + this.credentialsFile = path.join(this.configDir, "credentials.json"); this.ensureConfigDir(); this.loadAccounts(); } private ensureConfigDir(): void { - if (!fs.existsSync(CONFIG_DIR)) { - fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); + if (!fs.existsSync(this.configDir)) { + fs.mkdirSync(this.configDir, { recursive: true, mode: 0o700 }); } + fs.chmodSync(this.configDir, 0o700); } private loadAccounts(): void { - if (fs.existsSync(ACCOUNTS_FILE)) { + let raw: string; + try { + raw = fs.readFileSync(this.accountsFile, "utf8"); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code === "ENOENT") { + return; + } + throw new Error( + `Failed to read accounts file '${this.accountsFile}': ${err instanceof Error ? err.message : String(err)}`, + ); + } + + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (err) { + throw new Error( + `Failed to parse accounts file '${this.accountsFile}' as JSON (${err instanceof Error ? err.message : String(err)}). ` + + "Fix or back up and remove the corrupted file before modifying accounts.", + ); + } + + if (!Array.isArray(parsed)) { + throw new Error( + `Invalid accounts file '${this.accountsFile}': expected a JSON array of accounts. ` + + "Fix or back up and remove the corrupted file before modifying accounts.", + ); + } + + for (const account of parsed) { + if (!account || typeof account !== "object" || typeof (account as EmailAccount).email !== "string") { + throw new Error( + `Invalid account entry in '${this.accountsFile}'. ` + + "Fix or back up and remove the corrupted file before modifying accounts.", + ); + } + this.accounts.set((account as EmailAccount).email, account as EmailAccount); + } + } + + private writeJsonFileAtomic(targetFile: string, data: unknown): void { + this.ensureConfigDir(); + const tmpFile = path.join( + this.configDir, + `.${path.basename(targetFile)}.${process.pid}.${crypto.randomBytes(8).toString("hex")}.tmp`, + ); + try { + fs.writeFileSync(tmpFile, JSON.stringify(data, null, 2), { mode: 0o600 }); + fs.chmodSync(tmpFile, 0o600); + fs.renameSync(tmpFile, targetFile); + } catch (err) { try { - const data = JSON.parse(fs.readFileSync(ACCOUNTS_FILE, "utf8")); - for (const account of data) { - this.accounts.set(account.email, account); + if (fs.existsSync(tmpFile)) { + fs.unlinkSync(tmpFile); } } catch { - // Ignore + // Ignore cleanup errors } + throw err; } } private saveAccounts(): void { const sanitized = Array.from(this.accounts.values()).map(sanitizeForStorage); - fs.writeFileSync(ACCOUNTS_FILE, JSON.stringify(sanitized, null, 2), { mode: 0o600 }); + this.writeJsonFileAtomic(this.accountsFile, sanitized); } addAccount(account: EmailAccount): void { @@ -70,7 +124,7 @@ export class AccountStorage { } setCredentials(clientId: string, clientSecret: string): void { - fs.writeFileSync(CREDENTIALS_FILE, JSON.stringify({ clientId, clientSecret }, null, 2), { mode: 0o600 }); + this.writeJsonFileAtomic(this.credentialsFile, { clientId, clientSecret }); } getCredentials(): { clientId: string; clientSecret: string } | null { @@ -79,9 +133,9 @@ export class AccountStorage { if (envId && envSecret) { return { clientId: envId, clientSecret: envSecret }; } - if (!fs.existsSync(CREDENTIALS_FILE)) return null; + if (!fs.existsSync(this.credentialsFile)) return null; try { - return JSON.parse(fs.readFileSync(CREDENTIALS_FILE, "utf8")); + return JSON.parse(fs.readFileSync(this.credentialsFile, "utf8")); } catch { return null; } diff --git a/src/gmail-oauth-flow.ts b/src/gmail-oauth-flow.ts index db5569c..caa7eb0 100644 --- a/src/gmail-oauth-flow.ts +++ b/src/gmail-oauth-flow.ts @@ -1,8 +1,8 @@ import { spawn } from "child_process"; +import * as crypto from "crypto"; import * as http from "http"; import type { AddressInfo } from "net"; import * as readline from "readline"; -import * as url from "url"; import { OAuth2Client } from "google-auth-library"; const SCOPES = ["https://mail.google.com/"]; @@ -14,15 +14,40 @@ interface AuthResult { error?: string; } +export function escapeHtml(value: string): string { + return value + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +export function verifyOAuthState(expectedState: string, receivedState: string | null | undefined): boolean { + if (!expectedState || !receivedState) return false; + const expectedBuf = Buffer.from(expectedState, "utf8"); + const receivedBuf = Buffer.from(receivedState, "utf8"); + if (expectedBuf.length !== receivedBuf.length) return false; + return crypto.timingSafeEqual(expectedBuf, receivedBuf); +} + export class GmailOAuthFlow { + private readonly clientId: string; + private readonly clientSecret: string; private oauth2Client: OAuth2Client; private server: http.Server | null = null; private timeoutId: NodeJS.Timeout | null = null; constructor(clientId: string, clientSecret: string) { + this.clientId = clientId; + this.clientSecret = clientSecret; this.oauth2Client = new OAuth2Client(clientId, clientSecret); } + protected createOAuth2Client(redirectUri: string): OAuth2Client { + return new OAuth2Client(this.clientId, this.clientSecret, redirectUri); + } + async authorize(manual = false): Promise { const result = manual ? await this.startManualFlow() : await this.startAuthFlow(); if (!result.success) { @@ -36,11 +61,14 @@ export class GmailOAuthFlow { private async startManualFlow(): Promise { const redirectUri = "http://localhost:1"; - this.oauth2Client = new OAuth2Client(this.oauth2Client._clientId, this.oauth2Client._clientSecret, redirectUri); + const expectedState = crypto.randomBytes(24).toString("hex"); + this.oauth2Client = this.createOAuth2Client(redirectUri); const authUrl = this.oauth2Client.generateAuthUrl({ access_type: "offline", + prompt: "consent", scope: SCOPES, + state: expectedState, }); console.log("Visit this URL to authorize:"); @@ -56,8 +84,17 @@ export class GmailOAuthFlow { rl.question("Paste redirect URL: ", async (input) => { rl.close(); try { - const parsed = url.parse(input, true); - const code = parsed.query.code as string; + const parsed = new URL(input.trim()); + if (!verifyOAuthState(expectedState, parsed.searchParams.get("state"))) { + resolve({ success: false, error: "OAuth state mismatch" }); + return; + } + const error = parsed.searchParams.get("error"); + if (error) { + resolve({ success: false, error }); + return; + } + const code = parsed.searchParams.get("code"); if (!code) { resolve({ success: false, error: "No authorization code found in URL" }); return; @@ -72,11 +109,13 @@ export class GmailOAuthFlow { } private startAuthFlow(): Promise { + const expectedState = crypto.randomBytes(24).toString("hex"); + return new Promise((resolve) => { this.server = http.createServer((req, res) => { - const parsed = url.parse(req.url!, true); + const parsed = new URL(req.url || "/", "http://localhost"); if (parsed.pathname === "/") { - this.handleCallback(parsed.query, res, resolve); + void this.handleCallback(parsed.searchParams, expectedState, res, resolve); } else { res.writeHead(404); res.end(); @@ -87,15 +126,13 @@ export class GmailOAuthFlow { const port = (this.server!.address() as AddressInfo).port; const redirectUri = `http://localhost:${port}`; - this.oauth2Client = new OAuth2Client( - this.oauth2Client._clientId, - this.oauth2Client._clientSecret, - redirectUri, - ); + this.oauth2Client = this.createOAuth2Client(redirectUri); const authUrl = this.oauth2Client.generateAuthUrl({ access_type: "offline", + prompt: "consent", scope: SCOPES, + state: expectedState, }); console.log("Opening browser for Gmail authorization..."); @@ -118,20 +155,34 @@ export class GmailOAuthFlow { } private async handleCallback( - query: any, + searchParams: URLSearchParams, + expectedState: string, res: http.ServerResponse, resolve: (result: AuthResult) => void, ): Promise { - if (query.error) { - res.writeHead(200, { "Content-Type": "text/html" }); - res.end("

Authorization cancelled

"); + const receivedState = searchParams.get("state"); + if (!verifyOAuthState(expectedState, receivedState)) { + res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }); + res.end( + "

Invalid OAuth state

State verification failed. Please retry authorization.

", + ); + this.cleanup(); + resolve({ success: false, error: "OAuth state mismatch" }); + return; + } + + const error = searchParams.get("error"); + if (error) { + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); + res.end(`

Authorization cancelled

${escapeHtml(error)}

`); this.cleanup(); - resolve({ success: false, error: query.error }); + resolve({ success: false, error }); return; } - if (!query.code) { - res.writeHead(400, { "Content-Type": "text/html" }); + const code = searchParams.get("code"); + if (!code) { + res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }); res.end("

No authorization code

"); this.cleanup(); resolve({ success: false, error: "No authorization code" }); @@ -139,16 +190,17 @@ export class GmailOAuthFlow { } try { - const { tokens } = await this.oauth2Client.getToken(query.code as string); - res.writeHead(200, { "Content-Type": "text/html" }); + const { tokens } = await this.oauth2Client.getToken(code); + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end("

Success!

You can close this window.

"); this.cleanup(); resolve({ success: true, refreshToken: tokens.refresh_token || undefined }); } catch (e) { - res.writeHead(500, { "Content-Type": "text/html" }); - res.end(`

Error

${e instanceof Error ? e.message : e}

`); + const message = e instanceof Error ? e.message : String(e); + res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" }); + res.end(`

Error

${escapeHtml(message)}

`); this.cleanup(); - resolve({ success: false, error: e instanceof Error ? e.message : String(e) }); + resolve({ success: false, error: message }); } } @@ -163,8 +215,8 @@ export class GmailOAuthFlow { } } - private openBrowser(url: string): void { + private openBrowser(targetUrl: string): void { const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"; - spawn(cmd, [url], { detached: true, stdio: "ignore" }); + spawn(cmd, [targetUrl], { detached: true, stdio: "ignore" }); } } diff --git a/src/gmail-service.ts b/src/gmail-service.ts index 952a9d9..3d3fdcf 100644 --- a/src/gmail-service.ts +++ b/src/gmail-service.ts @@ -1,3 +1,4 @@ +import * as crypto from "crypto"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; @@ -147,9 +148,226 @@ export function canonicalReplySubject(requestedSubject: string, sourceSubject: s : requestedSubject; } +export const MAX_TOTAL_ATTACHMENT_BYTES = 25 * 1024 * 1024; +const MIME_ENCODED_WORD_PREFIX = "=?UTF-8?B?"; +const MIME_ENCODED_WORD_SUFFIX = "?="; +// 39 raw UTF-8 bytes => 52 base64 chars => 64-char encoded-word (<= 75 per RFC 2047, +// and <= 76 even on the first line with "Subject: "). +const MAX_ENCODED_WORD_UTF8_BYTES = 39; + +function assertNoCrlf(fieldName: string, value: string): void { + if (/[\r\n]/.test(value)) { + throw new Error(`Invalid ${fieldName}: must not contain CR or LF characters`); + } +} + export function encodeMimeHeader(value: string): string { + assertNoCrlf("header", value); if (/^[\x20-\x7e]*$/.test(value)) return value; - return `=?UTF-8?B?${Buffer.from(value, "utf8").toString("base64")}?=`; + + const words: string[] = []; + let chunk = ""; + let chunkBytes = 0; + + for (const char of value) { + const charBytes = Buffer.byteLength(char, "utf8"); + if (chunk && chunkBytes + charBytes > MAX_ENCODED_WORD_UTF8_BYTES) { + words.push( + `${MIME_ENCODED_WORD_PREFIX}${Buffer.from(chunk, "utf8").toString("base64")}${MIME_ENCODED_WORD_SUFFIX}`, + ); + chunk = char; + chunkBytes = charBytes; + } else { + chunk += char; + chunkBytes += charBytes; + } + } + + if (chunk) { + words.push( + `${MIME_ENCODED_WORD_PREFIX}${Buffer.from(chunk, "utf8").toString("base64")}${MIME_ENCODED_WORD_SUFFIX}`, + ); + } + + return words.join("\r\n "); +} + +export function sanitizeAttachmentHeaderFilename(filename: string): string { + const cleaned = filename + .replace(/[\r\n\0/]/g, "") + .trim() + .replace(/\\/g, "\\\\") + .replace(/"/g, '\\"'); + return cleaned || "attachment"; +} + +export function sanitizeInboundFilename(rawFilename: string): string { + const normalized = rawFilename.replace(/\\/g, "/"); + const base = path.posix + .basename(normalized) + .replace(/[\x00-\x1f\x7f]/g, "") + .trim() + .replace(/^\.+/, ""); + return base || "attachment"; +} + +function wrapBase64(base64: string, lineLength = 76): string { + if (base64.length <= lineLength) return base64; + const lines: string[] = []; + for (let i = 0; i < base64.length; i += lineLength) { + lines.push(base64.slice(i, i + lineLength)); + } + return lines.join("\r\n"); +} + +function getMimeType(filename: string): string { + const ext = path.extname(filename).toLowerCase(); + const mimeTypes: Record = { + ".pdf": "application/pdf", + ".doc": "application/msword", + ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".xls": "application/vnd.ms-excel", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".txt": "text/plain", + ".html": "text/html", + ".zip": "application/zip", + ".json": "application/json", + }; + return mimeTypes[ext] || "application/octet-stream"; +} + +export interface BuildRawMimeMessageInput { + from: string; + to: string[]; + subject: string; + body: string; + cc?: string[]; + bcc?: string[]; + inReplyTo?: string; + references?: string; + attachments?: string[]; + html?: boolean; +} + +export function validateAttachmentPaths(attachments: string[]): Array<{ filePath: string; size: number }> { + let totalBytes = 0; + const validated: Array<{ filePath: string; size: number }> = []; + + for (const filePath of attachments) { + assertNoCrlf("attachment filename", path.basename(filePath)); + let stat: fs.Stats; + try { + stat = fs.statSync(filePath); + } catch (e) { + const code = (e as NodeJS.ErrnoException)?.code; + if (code === "ENOENT") { + throw new Error(`Attachment file not found: ${filePath}`); + } + throw new Error(`Cannot read attachment '${filePath}': ${e instanceof Error ? e.message : String(e)}`); + } + if (!stat.isFile()) { + throw new Error(`Attachment path is not a regular file: ${filePath}`); + } + totalBytes += stat.size; + if (totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) { + throw new Error( + `Total attachment size (${totalBytes} bytes) exceeds Gmail's 25 MB limit (${MAX_TOTAL_ATTACHMENT_BYTES} bytes)`, + ); + } + validated.push({ filePath, size: stat.size }); + } + + return validated; +} + +export function buildRawMimeMessage(input: BuildRawMimeMessageInput): string { + assertNoCrlf("From header", input.from); + for (const recipient of input.to) { + assertNoCrlf("To header", recipient); + } + for (const recipient of input.cc || []) { + assertNoCrlf("Cc header", recipient); + } + for (const recipient of input.bcc || []) { + assertNoCrlf("Bcc header", recipient); + } + assertNoCrlf("Subject header", input.subject); + if (input.inReplyTo) { + assertNoCrlf("In-Reply-To header", input.inReplyTo); + } + if (input.references) { + assertNoCrlf("References header", input.references); + } + + const attachments = input.attachments || []; + const hasAttachments = attachments.length > 0; + if (hasAttachments) { + validateAttachmentPaths(attachments); + } + + const boundary = `boundary_${crypto.randomBytes(16).toString("hex")}`; + const contentType = input.html ? "text/html" : "text/plain"; + const encodedBody = wrapBase64(Buffer.from(input.body, "utf8").toString("base64")); + + const headers = [ + `From: ${input.from}`, + `To: ${input.to.join(", ")}`, + input.cc?.length ? `Cc: ${input.cc.join(", ")}` : "", + input.bcc?.length ? `Bcc: ${input.bcc.join(", ")}` : "", + `Subject: ${encodeMimeHeader(input.subject)}`, + input.inReplyTo ? `In-Reply-To: ${input.inReplyTo}` : "", + input.references ? `References: ${input.references}` : "", + "MIME-Version: 1.0", + hasAttachments + ? `Content-Type: multipart/mixed; boundary="${boundary}"` + : `Content-Type: ${contentType}; charset=UTF-8`, + hasAttachments ? "" : "Content-Transfer-Encoding: base64", + ].filter(Boolean); + + if (!hasAttachments) { + return `${headers.join("\r\n")}\r\n\r\n${encodedBody}`; + } + + const parts: string[] = []; + parts.push( + `--${boundary}\r\n` + + `Content-Type: ${contentType}; charset=UTF-8\r\n` + + "Content-Transfer-Encoding: base64\r\n\r\n" + + encodedBody, + ); + + let actualTotalBytes = 0; + for (const filePath of attachments) { + const rawFilename = path.basename(filePath); + assertNoCrlf("attachment filename", rawFilename); + const safeFilename = sanitizeAttachmentHeaderFilename(rawFilename); + assertNoCrlf("attachment filename", safeFilename); + + const fileContent = fs.readFileSync(filePath); + actualTotalBytes += fileContent.length; + if (actualTotalBytes > MAX_TOTAL_ATTACHMENT_BYTES) { + throw new Error( + `Total attachment size (${actualTotalBytes} bytes) exceeds Gmail's 25 MB limit (${MAX_TOTAL_ATTACHMENT_BYTES} bytes)`, + ); + } + + const base64Content = wrapBase64(fileContent.toString("base64")); + const mimeType = getMimeType(rawFilename); + + parts.push( + `--${boundary}\r\n` + + `Content-Type: ${mimeType}\r\n` + + "Content-Transfer-Encoding: base64\r\n" + + `Content-Disposition: attachment; filename="${safeFilename}"\r\n\r\n` + + base64Content, + ); + } + + return `${headers.join("\r\n")}\r\n\r\n${parts.join("\r\n")}\r\n--${boundary}--`; } export interface LabelOperationResult { @@ -159,9 +377,16 @@ export interface LabelOperationResult { } export class GmailService { - private accountStorage = new AccountStorage(); + private accountStorage: AccountStorage; + private attachmentDir: string; private gmailClients: Map = new Map(); + constructor(options: { configDir?: string; attachmentDir?: string } = {}) { + this.accountStorage = new AccountStorage(options.configDir); + this.attachmentDir = + options.attachmentDir || path.join(options.configDir || path.join(os.homedir(), ".gmcli"), "attachments"); + } + async addGmailAccount(email: string, clientId: string, clientSecret: string, manual = false): Promise { if (this.accountStorage.hasAccount(email)) { throw new Error(`Account '${email}' already exists`); @@ -220,7 +445,6 @@ export class GmailService { oauth2Client.setCredentials({ refresh_token: account.oauth2.refreshToken, - access_token: account.oauth2.accessToken, }); const gmail = google.gmail({ version: "v1", auth: oauth2Client }); @@ -286,7 +510,15 @@ export class GmailService { return thread; } - const attachmentMetadata: AttachmentDownloadTarget[] = (thread.messages || []).flatMap((message: GmailMessage) => + return this.downloadPartsForMessages(email, thread.messages || [], `thread ${threadId}`); + } + + private async downloadPartsForMessages( + email: string, + messages: GmailMessage[], + contextLabel: string, + ): Promise { + const attachmentMetadata: AttachmentDownloadTarget[] = messages.flatMap((message: GmailMessage) => collectAttachmentParts(message.payload).map((part: AttachmentPartInfo) => ({ messageId: message.id!, filename: part.filename, @@ -333,7 +565,7 @@ export class GmailService { if (attachmentMetadata.length > 0 && downloadedAttachments.length === 0) { console.error( - `[gmcli] Warning: attachment metadata listed ${attachmentMetadata.length} attachment(s), but none were downloaded for thread ${threadId}.`, + `[gmcli] Warning: attachment metadata listed ${attachmentMetadata.length} attachment(s), but none were downloaded for ${contextLabel}.`, ); } @@ -353,17 +585,25 @@ export class GmailService { const gmail = this.getGmailClient(email); const results: AttachmentDownloadResult[] = []; - const attachmentDir = path.join(os.homedir(), ".gmcli", "attachments"); - if (!fs.existsSync(attachmentDir)) { - fs.mkdirSync(attachmentDir, { recursive: true }); + const resolvedAttachmentDir = path.resolve(this.attachmentDir); + if (!fs.existsSync(resolvedAttachmentDir)) { + fs.mkdirSync(resolvedAttachmentDir, { recursive: true, mode: 0o700 }); } + fs.chmodSync(resolvedAttachmentDir, 0o700); for (const attachment of attachments) { try { const sourceKey = attachment.attachmentId?.substring(0, 8) || `part-${attachment.partPath.replace(/\./g, "-")}`; - const filename = `${attachment.messageId}_${sourceKey}_${attachment.filename}`; - const filePath = path.join(attachmentDir, filename); + const safeMessageId = attachment.messageId.replace(/[^A-Za-z0-9_-]/g, "_") || "msg"; + const safeSourceKey = sourceKey.replace(/[^A-Za-z0-9_-]/g, "_") || "part"; + const safeFilename = sanitizeInboundFilename(attachment.filename); + const filename = `${safeMessageId}_${safeSourceKey}_${safeFilename}`; + const filePath = path.resolve(resolvedAttachmentDir, filename); + + if (!filePath.startsWith(resolvedAttachmentDir + path.sep)) { + throw new Error(`Refusing to write attachment outside attachments directory: ${attachment.filename}`); + } if (attachment.inlineData) { const data = Buffer.from(attachment.inlineData, "base64url"); @@ -372,7 +612,8 @@ export class GmailService { continue; } - fs.writeFileSync(filePath, data); + fs.writeFileSync(filePath, data, { mode: 0o600 }); + fs.chmodSync(filePath, 0o600); results.push({ success: true, filename: attachment.filename, path: filePath, cached: false }); continue; } @@ -402,7 +643,8 @@ export class GmailService { }); const data = Buffer.from(response.data.data, "base64url"); - fs.writeFileSync(filePath, data); + fs.writeFileSync(filePath, data, { mode: 0o600 }); + fs.chmodSync(filePath, 0o600); results.push({ success: true, filename: attachment.filename, path: filePath, cached: false }); } catch (e) { @@ -864,6 +1106,9 @@ export class GmailService { html?: boolean; } = {}, ): Promise { + if (options.attachments?.length) { + validateAttachmentPaths(options.attachments); + } const gmail = this.getGmailClient(email); const { @@ -873,54 +1118,20 @@ export class GmailService { subject: messageSubject, } = await this.resolveReplyMetadata(gmail, subject, options); - const hasAttachments = options.attachments && options.attachments.length > 0; - const boundary = `boundary_${Date.now()}_${Math.random().toString(36).slice(2)}`; - const contentType = options.html ? "text/html" : "text/plain"; - - const headers = [ - `From: ${email}`, - `To: ${to.join(", ")}`, - options.cc?.length ? `Cc: ${options.cc.join(", ")}` : "", - options.bcc?.length ? `Bcc: ${options.bcc.join(", ")}` : "", - `Subject: ${encodeMimeHeader(messageSubject)}`, - inReplyTo ? `In-Reply-To: ${inReplyTo}` : "", - references ? `References: ${references}` : "", - "MIME-Version: 1.0", - hasAttachments - ? `Content-Type: multipart/mixed; boundary="${boundary}"` - : `Content-Type: ${contentType}; charset=UTF-8`, - ].filter(Boolean); - - let emailContent: string; - - if (hasAttachments) { - const parts: string[] = []; - - // Body part - parts.push(`--${boundary}\r\n` + `Content-Type: ${contentType}; charset=UTF-8\r\n\r\n` + body); - - // Attachment parts - for (const filePath of options.attachments!) { - const filename = path.basename(filePath); - const fileContent = fs.readFileSync(filePath); - const base64Content = fileContent.toString("base64"); - const mimeType = this.getMimeType(filename); - - parts.push( - `--${boundary}\r\n` + - `Content-Type: ${mimeType}\r\n` + - "Content-Transfer-Encoding: base64\r\n" + - `Content-Disposition: attachment; filename="${filename}"\r\n\r\n` + - base64Content, - ); - } - - emailContent = headers.join("\r\n") + "\r\n\r\n" + parts.join("\r\n") + `\r\n--${boundary}--`; - } else { - emailContent = headers.join("\r\n") + "\r\n\r\n" + body; - } + const emailContent = buildRawMimeMessage({ + from: email, + to, + subject: messageSubject, + body, + cc: options.cc, + bcc: options.bcc, + inReplyTo, + references, + attachments: options.attachments, + html: options.html, + }); - const encodedEmail = Buffer.from(emailContent).toString("base64url"); + const encodedEmail = Buffer.from(emailContent, "utf8").toString("base64url"); const response = await gmail.users.drafts.create({ userId: "me", @@ -932,51 +1143,6 @@ export class GmailService { return response.data; } - private getMimeType(filename: string): string { - const ext = path.extname(filename).toLowerCase(); - const mimeTypes: Record = { - ".pdf": "application/pdf", - ".doc": "application/msword", - ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - ".xls": "application/vnd.ms-excel", - ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - ".png": "image/png", - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".gif": "image/gif", - ".txt": "text/plain", - ".html": "text/html", - ".zip": "application/zip", - ".json": "application/json", - }; - return mimeTypes[ext] || "application/octet-stream"; - } - - async updateDraft(email: string, draftId: string, body: string): Promise { - const gmail = this.getGmailClient(email); - const draft = await this.getDraft(email, draftId); - const message = draft.message; - - if (!message) throw new Error("Draft message not found"); - - const existingRaw = message.raw ? Buffer.from(message.raw, "base64url").toString() : ""; - const headerEnd = existingRaw.indexOf("\n\n"); - const headers = headerEnd > 0 ? existingRaw.substring(0, headerEnd) : ""; - - const updatedEmail = `${headers}\n\n${body}`; - const encodedEmail = Buffer.from(updatedEmail).toString("base64url"); - - const response = await gmail.users.drafts.update({ - userId: "me", - id: draftId, - requestBody: { - message: { raw: encodedEmail, threadId: message.threadId }, - }, - }); - - return response.data; - } - async getDraft(email: string, draftId: string): Promise { const gmail = this.getGmailClient(email); const response = await gmail.users.drafts.get({ userId: "me", id: draftId }); @@ -1012,6 +1178,9 @@ export class GmailService { html?: boolean; } = {}, ): Promise { + if (options.attachments?.length) { + validateAttachmentPaths(options.attachments); + } const gmail = this.getGmailClient(email); const { @@ -1021,54 +1190,20 @@ export class GmailService { subject: messageSubject, } = await this.resolveReplyMetadata(gmail, subject, options); - const hasAttachments = options.attachments && options.attachments.length > 0; - const boundary = `boundary_${Date.now()}_${Math.random().toString(36).slice(2)}`; - const contentType = options.html ? "text/html" : "text/plain"; - - const headers = [ - `From: ${email}`, - `To: ${to.join(", ")}`, - options.cc?.length ? `Cc: ${options.cc.join(", ")}` : "", - options.bcc?.length ? `Bcc: ${options.bcc.join(", ")}` : "", - `Subject: ${encodeMimeHeader(messageSubject)}`, - inReplyTo ? `In-Reply-To: ${inReplyTo}` : "", - references ? `References: ${references}` : "", - "MIME-Version: 1.0", - hasAttachments - ? `Content-Type: multipart/mixed; boundary="${boundary}"` - : `Content-Type: ${contentType}; charset=UTF-8`, - ].filter(Boolean); - - let emailContent: string; - - if (hasAttachments) { - const parts: string[] = []; - - // Body part - parts.push(`--${boundary}\r\n` + `Content-Type: ${contentType}; charset=UTF-8\r\n\r\n` + body); - - // Attachment parts - for (const filePath of options.attachments!) { - const filename = path.basename(filePath); - const fileContent = fs.readFileSync(filePath); - const base64Content = fileContent.toString("base64"); - const mimeType = this.getMimeType(filename); - - parts.push( - `--${boundary}\r\n` + - `Content-Type: ${mimeType}\r\n` + - "Content-Transfer-Encoding: base64\r\n" + - `Content-Disposition: attachment; filename="${filename}"\r\n\r\n` + - base64Content, - ); - } - - emailContent = headers.join("\r\n") + "\r\n\r\n" + parts.join("\r\n") + `\r\n--${boundary}--`; - } else { - emailContent = headers.join("\r\n") + "\r\n\r\n" + body; - } + const emailContent = buildRawMimeMessage({ + from: email, + to, + subject: messageSubject, + body, + cc: options.cc, + bcc: options.bcc, + inReplyTo, + references, + attachments: options.attachments, + html: options.html, + }); - const encodedEmail = Buffer.from(emailContent).toString("base64url"); + const encodedEmail = Buffer.from(emailContent, "utf8").toString("base64url"); const response = await gmail.users.messages.send({ userId: "me", @@ -1081,58 +1216,13 @@ export class GmailService { async downloadMessageAttachments(email: string, messageId: string): Promise { const gmail = this.getGmailClient(email); const response = await gmail.users.messages.get({ userId: "me", id: messageId }); - const message = response.data; - - const attachmentMetadata: AttachmentDownloadTarget[] = collectAttachmentParts(message.payload).map( - (part: AttachmentPartInfo) => ({ - messageId, - filename: part.filename, - size: part.size, - mimeType: part.mimeType, - attachmentId: part.attachmentId, - inlineData: part.inlineData, - partPath: part.partPath, - }), - ); + const message: GmailMessage = response.data; - const attachmentsToDownload = attachmentMetadata.filter( - (part: AttachmentDownloadTarget) => part.attachmentId || part.inlineData, - ); - - const downloadResults = await this.downloadAttachments( + return this.downloadPartsForMessages( email, - attachmentsToDownload.map((att: AttachmentDownloadTarget) => ({ - messageId: att.messageId, - attachmentId: att.attachmentId, - inlineData: att.inlineData, - filename: att.filename, - partPath: att.partPath, - })), + [{ ...message, id: message.id || messageId }], + `message ${messageId}`, ); - - const downloadedAttachments: DownloadedAttachment[] = []; - for (let i = 0; i < attachmentsToDownload.length; i++) { - const attachment = attachmentsToDownload[i]; - const result = downloadResults[i]; - if (result.success && result.path) { - downloadedAttachments.push({ - messageId: attachment.messageId, - filename: attachment.filename, - path: result.path, - size: attachment.size, - mimeType: attachment.mimeType, - cached: result.cached || false, - }); - } - } - - if (attachmentMetadata.length > 0 && downloadedAttachments.length === 0) { - console.error( - `[gmcli] Warning: attachment metadata listed ${attachmentMetadata.length} attachment(s), but none were downloaded for message ${messageId}.`, - ); - } - - return downloadedAttachments; } private getHeaderValue(message: GmailMessage, headerName: string): string | undefined { diff --git a/src/types.ts b/src/types.ts index b7484fa..abac655 100644 --- a/src/types.ts +++ b/src/types.ts @@ -9,6 +9,5 @@ export interface EmailAccount { clientId?: string; clientSecret?: string; refreshToken: string; - accessToken?: string; }; } diff --git a/test/security-mime-storage.test.js b/test/security-mime-storage.test.js new file mode 100644 index 0000000..848b3f1 --- /dev/null +++ b/test/security-mime-storage.test.js @@ -0,0 +1,480 @@ +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import test from "node:test"; +import { AccountStorage } from "../dist/account-storage.js"; +import { GmailOAuthFlow, escapeHtml, verifyOAuthState } from "../dist/gmail-oauth-flow.js"; +import { + GmailService, + MAX_TOTAL_ATTACHMENT_BYTES, + buildRawMimeMessage, + encodeMimeHeader, + sanitizeAttachmentHeaderFilename, + sanitizeInboundFilename, +} from "../dist/gmail-service.js"; + +function withTempDir(fn) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "gmcli-pr1-test-")); + try { + return fn(dir); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +async function withTempDirAsync(fn) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "gmcli-pr1-test-")); + try { + return await fn(dir); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +function decodeRfc2047(encoded) { + // Per RFC 2047 Β§6.2, linear whitespace separating adjacent encoded-words is ignored. + const collapsed = encoded.replace(/\?=\r\n[ \t]+=\?/g, "?==?"); + return collapsed.replace(/=\?UTF-8\?B\?([A-Za-z0-9+/=]+)\?=/g, (_, b64) => + Buffer.from(b64, "base64").toString("utf8"), + ); +} + +test("dead code updateDraft is removed from GmailService", () => { + assert.equal(typeof GmailService.prototype.updateDraft, "undefined"); +}); + +test("buildRawMimeMessage rejects CRLF header injection across all header fields and attachment filenames", () => { + const base = { + from: "will@example.com", + to: ["buyer@example.com"], + subject: "Normal subject", + body: "Hello", + }; + + assert.throws(() => buildRawMimeMessage({ ...base, from: "will@example.com\r\nBcc: evil@example.com" }), /CR or LF/); + assert.throws( + () => buildRawMimeMessage({ ...base, to: ["buyer@example.com\r\nBcc: evil@example.com"] }), + /CR or LF/, + ); + assert.throws( + () => buildRawMimeMessage({ ...base, cc: ["ok@example.com", "bad@example.com\nX-Injected: 1"] }), + /CR or LF/, + ); + assert.throws(() => buildRawMimeMessage({ ...base, bcc: ["bad@example.com\rX-Injected: 1"] }), /CR or LF/); + assert.throws( + () => buildRawMimeMessage({ ...base, subject: "Hello\r\nBcc: evil@example.com" }), + /CR or LF/, + ); + assert.throws( + () => buildRawMimeMessage({ ...base, inReplyTo: "\r\nX-Bad: yes" }), + /CR or LF/, + ); + assert.throws( + () => buildRawMimeMessage({ ...base, references: "\n" }), + /CR or LF/, + ); + assert.throws(() => encodeMimeHeader("Line1\r\nLine2"), /CR or LF/); + + // Attachment filename CRLF injection (even on an actual file on disk) + withTempDir((dir) => { + const evilFile = path.join(dir, "invoice\nBcc: evil@example.com.pdf"); + fs.writeFileSync(evilFile, "pdf-bytes"); + assert.throws(() => buildRawMimeMessage({ ...base, attachments: [evilFile] }), /CR or LF/); + }); +}); + +test("encodeMimeHeader folds long UTF-8 subjects to <= 75 chars per encoded-word without corrupting multi-byte chars", () => { + const subjects = [ + "Auction update β€” McLemore Auction Company β€” Lot #1042 closing soon πŸŽ‰πŸ”₯ β€” Final reminder for all bidders!", + "β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”", + "πŸŽ‰".repeat(30), + `${"a".repeat(37)}β€”${"b".repeat(38)}πŸŽ‰${"c".repeat(36)}β€”end`, + ]; + + for (const subject of subjects) { + const encoded = encodeMimeHeader(subject); + const tokens = encoded.split("\r\n "); + assert.ok(tokens.length > 1, `expected multiple folded tokens for: ${subject}`); + for (const token of tokens) { + assert.match(token, /^=\?UTF-8\?B\?[A-Za-z0-9+/=]+\?=$/); + assert.ok(token.length <= 75, `encoded-word exceeded 75 chars (${token.length}): ${token}`); + // Each token must independently decode to valid UTF-8 with no U+FFFD replacement chars + const b64 = token.slice("=?UTF-8?B?".length, -"?=".length); + const decodedChunk = Buffer.from(b64, "base64").toString("utf8"); + assert.equal(decodedChunk.includes("\uFFFD"), false, `corrupted UTF-8 boundary in chunk: ${decodedChunk}`); + } + assert.equal(decodeRfc2047(encoded), subject); + } +}); + +test("buildRawMimeMessage wraps body and attachment base64 at 76 chars, handles UTF-8 HTML, and sanitizes filenames", () => { + withTempDir((dir) => { + const attachFile = path.join(dir, 'Q1 "Summary" \\ Report.txt'); + const attachBytes = Buffer.alloc(300, 0x41); // 300 bytes => 400 base64 chars => multiple 76-char lines + fs.writeFileSync(attachFile, attachBytes); + + const htmlBody = `

${"Long UTF-8 line β€” πŸŽ‰ ".repeat(20)}

`; + const raw = buildRawMimeMessage({ + from: "will@example.com", + to: ["buyer@example.com"], + subject: "HTML + attachment", + body: htmlBody, + attachments: [attachFile], + html: true, + }); + + // Verify random hex boundary (32 hex chars from 16 random bytes) + const boundaryMatch = raw.match(/Content-Type: multipart\/mixed; boundary="(boundary_[0-9a-f]{32})"/); + assert.ok(boundaryMatch, "expected crypto-random 16-byte hex MIME boundary"); + const boundary = boundaryMatch[1]; + + // Verify escaped attachment filename in Content-Disposition + assert.match( + raw, + /Content-Disposition: attachment; filename="Q1 \\"Summary\\" \\\\ Report\.txt"\r\n/, + ); + + // Verify every line in the raw MIME message respects RFC line wrapping + for (const line of raw.split("\r\n")) { + assert.ok(line.length <= 200, `unexpectedly long MIME line (${line.length}): ${line.slice(0, 80)}`); + } + + // Extract parts and verify 76-char wrapping + exact round-trip decoding + const parts = raw.split(`--${boundary}`).slice(1, -1); + assert.equal(parts.length, 2); + + const [bodyPart, attachPart] = parts; + assert.match(bodyPart, /Content-Type: text\/html; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n/); + const bodyB64Lines = bodyPart.split("\r\n\r\n")[1].trim().split("\r\n"); + assert.ok(bodyB64Lines.length > 1); + for (const line of bodyB64Lines) { + assert.ok(line.length <= 76, `body base64 line exceeded 76 chars: ${line.length}`); + } + assert.equal(Buffer.from(bodyB64Lines.join(""), "base64").toString("utf8"), htmlBody); + + const attachB64Lines = attachPart.split("\r\n\r\n")[1].trim().split("\r\n"); + assert.ok(attachB64Lines.length > 1); + for (const line of attachB64Lines) { + assert.ok(line.length <= 76, `attachment base64 line exceeded 76 chars: ${line.length}`); + } + assert.deepEqual(Buffer.from(attachB64Lines.join(""), "base64"), attachBytes); + }); +}); + +test("sanitizeAttachmentHeaderFilename strips control chars and path separators and escapes quotes/backslashes", () => { + assert.equal(sanitizeAttachmentHeaderFilename('a/b\0\r\n"c"\\d.pdf'), 'ab\\"c\\"\\\\d.pdf'); + assert.equal(sanitizeAttachmentHeaderFilename("\r\n\0/"), "attachment"); +}); + +test("buildRawMimeMessage and GmailService preflight-validate missing, directory, and >25MB attachments before API calls", async () => { + await withTempDirAsync(async (dir) => { + const missingPath = path.join(dir, "does-not-exist.pdf"); + const subDir = path.join(dir, "a-directory"); + fs.mkdirSync(subDir); + + // Create sparse file > 25 MB (uses negligible disk space on APFS/ext4) + const oversizePath = path.join(dir, "too-big.bin"); + const fd = fs.openSync(oversizePath, "w"); + try { + fs.ftruncateSync(fd, MAX_TOTAL_ATTACHMENT_BYTES + 1); + } finally { + fs.closeSync(fd); + } + + const base = { + from: "will@example.com", + to: ["buyer@example.com"], + subject: "Test", + body: "Body", + }; + + assert.throws(() => buildRawMimeMessage({ ...base, attachments: [missingPath] }), /not found/i); + assert.throws(() => buildRawMimeMessage({ ...base, attachments: [subDir] }), /not a regular file/i); + assert.throws(() => buildRawMimeMessage({ ...base, attachments: [oversizePath] }), /25 MB/); + + // Ensure Gmail API is never invoked when attachment validation fails + let apiCalled = false; + const fakeGmail = { + users: { + messages: { + get: async () => { + apiCalled = true; + throw new Error("should not be called"); + }, + send: async () => { + apiCalled = true; + throw new Error("should not be called"); + }, + }, + drafts: { + create: async () => { + apiCalled = true; + throw new Error("should not be called"); + }, + }, + }, + }; + + const service = new GmailService({ configDir: dir }); + service.gmailClients.set("will@example.com", fakeGmail); + + await assert.rejects( + () => + service.createDraft("will@example.com", ["buyer@example.com"], "Subj", "Body", { + attachments: [missingPath], + replyToMessageId: "msg-1", + }), + /not found/i, + ); + await assert.rejects( + () => + service.sendMessage("will@example.com", ["buyer@example.com"], "Subj", "Body", { + attachments: [oversizePath], + }), + /25 MB/, + ); + assert.equal(apiCalled, false); + }); +}); + +test("sanitizeInboundFilename blocks traversal, Windows separators, leading dots, and control chars", () => { + assert.equal(sanitizeInboundFilename("../../../../etc/passwd"), "passwd"); + assert.equal(sanitizeInboundFilename("..\\..\\evil.exe"), "evil.exe"); + assert.equal(sanitizeInboundFilename("nested/dir/report.pdf"), "report.pdf"); + assert.equal(sanitizeInboundFilename(".../.bashrc"), "bashrc"); + assert.equal(sanitizeInboundFilename(".."), "attachment"); + assert.equal(sanitizeInboundFilename(" "), "attachment"); + assert.equal(sanitizeInboundFilename("file\x00name\r\n.txt"), "filename.txt"); +}); + +test("downloadAttachments contains traversal filenames inside attachmentDir with 0700 dir and 0600 file perms", async () => { + await withTempDirAsync(async (dir) => { + const attachmentDir = path.join(dir, "attachments"); + fs.mkdirSync(attachmentDir, { mode: 0o755 }); + fs.chmodSync(attachmentDir, 0o755); + + const apiPayload = Buffer.from("api-attachment-content"); + const inlinePayload = Buffer.from("inline-attachment-content"); + + const fakeGmail = { + users: { + messages: { + get: async () => ({ + data: { + id: "msg-99", + payload: { + mimeType: "multipart/mixed", + parts: [ + { + filename: "../../../../etc/passwd", + mimeType: "application/octet-stream", + body: { attachmentId: "att123456789", size: apiPayload.length }, + }, + { + filename: "..\\..\\evil", + mimeType: "text/plain", + body: { data: inlinePayload.toString("base64url"), size: inlinePayload.length }, + }, + { + filename: "a/b/c/nested.pdf", + mimeType: "application/pdf", + body: { data: inlinePayload.toString("base64url"), size: inlinePayload.length }, + }, + ], + }, + }, + }), + attachments: { + get: async () => ({ + data: { data: apiPayload.toString("base64url"), size: apiPayload.length }, + }), + }, + }, + }, + }; + + const service = new GmailService({ configDir: dir, attachmentDir }); + service.gmailClients.set("will@example.com", fakeGmail); + + const downloaded = await service.downloadMessageAttachments("will@example.com", "msg-99"); + assert.equal(downloaded.length, 3); + + // Attachment directory permissions tightened to 0700 + const dirMode = fs.statSync(attachmentDir).mode & 0o777; + assert.equal(dirMode, 0o700); + + const resolvedDir = path.resolve(attachmentDir); + for (const item of downloaded) { + const resolvedPath = path.resolve(item.path); + assert.ok( + resolvedPath.startsWith(resolvedDir + path.sep), + `attachment escaped attachmentDir: ${resolvedPath}`, + ); + assert.equal(path.dirname(resolvedPath), resolvedDir); + const fileMode = fs.statSync(resolvedPath).mode & 0o777; + assert.equal(fileMode, 0o600); + } + + // Verify sanitized basenames + assert.ok(path.basename(downloaded[0].path).endsWith("_passwd")); + assert.ok(path.basename(downloaded[1].path).endsWith("_evil")); + assert.ok(path.basename(downloaded[2].path).endsWith("_nested.pdf")); + }); +}); + +test("AccountStorage enforces 0700/0600 permissions, atomic writes, ENOENT empty list, and loud error on corrupt JSON", () => { + withTempDir((dir) => { + const configDir = path.join(dir, "gmcli-config"); + fs.mkdirSync(configDir, { mode: 0o755 }); + fs.chmodSync(configDir, 0o755); + + // ENOENT -> empty accounts list, dir tightened to 0700 + const storage = new AccountStorage(configDir); + assert.deepEqual(storage.getAllAccounts(), []); + assert.equal(fs.statSync(configDir).mode & 0o777, 0o700); + + // Atomic write with 0600 permissions and stripped clientId/clientSecret + storage.addAccount({ + email: "will@example.com", + oauth2: { + clientId: "should-not-persist", + clientSecret: "secret-should-not-persist", + refreshToken: "refresh-123", + }, + }); + + const accountsFile = path.join(configDir, "accounts.json"); + assert.equal(fs.statSync(accountsFile).mode & 0o777, 0o600); + + // No stray temp files left behind + const entries = fs.readdirSync(configDir); + assert.deepEqual(entries, ["accounts.json"]); + + const saved = JSON.parse(fs.readFileSync(accountsFile, "utf8")); + assert.equal(saved.length, 1); + assert.equal(saved[0].email, "will@example.com"); + assert.equal(saved[0].oauth2.refreshToken, "refresh-123"); + assert.equal("clientId" in saved[0].oauth2, false); + assert.equal("clientSecret" in saved[0].oauth2, false); + + // Corrupt JSON throws loud, actionable error instead of silently returning [] + fs.writeFileSync(accountsFile, "{not valid json", { mode: 0o600 }); + assert.throws(() => new AccountStorage(configDir), /Failed to parse accounts file.*corrupted/i); + + // Non-array JSON also throws loudly + fs.writeFileSync(accountsFile, JSON.stringify({ email: "wrong-shape" }), { mode: 0o600 }); + assert.throws(() => new AccountStorage(configDir), /expected a JSON array/i); + }); +}); + +test("OAuth helpers escape HTML and verify CSRF state strictly", () => { + assert.equal( + escapeHtml(``), + "<script>alert("x" & 'y')</script>", + ); + assert.equal(verifyOAuthState("abc123", "abc123"), true); + assert.equal(verifyOAuthState("abc123", "abc124"), false); + assert.equal(verifyOAuthState("abc123", "abc12"), false); + assert.equal(verifyOAuthState("abc123", ""), false); + assert.equal(verifyOAuthState("abc123", null), false); + assert.equal(verifyOAuthState("", ""), false); +}); + +test("GmailOAuthFlow sends prompt=consent + CSRF state, rejects state mismatch, and escapes callback errors", async () => { + // 1. State mismatch rejects without calling getToken + { + let capturedAuthUrl = null; + let tokenCalled = false; + const flow = new GmailOAuthFlow("cid", "csec"); + flow.createOAuth2Client = (redirectUri) => ({ + generateAuthUrl: (opts) => { + const u = new URL("https://accounts.google.com/o/oauth2/v2/auth"); + u.searchParams.set("redirect_uri", redirectUri); + u.searchParams.set("access_type", opts.access_type); + u.searchParams.set("prompt", opts.prompt); + u.searchParams.set("state", opts.state); + return u.toString(); + }, + getToken: async () => { + tokenCalled = true; + return { tokens: { refresh_token: "should-not-happen" } }; + }, + }); + flow.openBrowser = (authUrl) => { + capturedAuthUrl = authUrl; + const parsedAuth = new URL(authUrl); + const redirectUri = parsedAuth.searchParams.get("redirect_uri"); + void fetch(`${redirectUri}/?code=abc&state=wrong-state`); + }; + + await assert.rejects(() => flow.authorize(false), /OAuth state mismatch/); + assert.equal(tokenCalled, false); + assert.ok(capturedAuthUrl); + const authParams = new URL(capturedAuthUrl).searchParams; + assert.equal(authParams.get("prompt"), "consent"); + assert.match(authParams.get("state") || "", /^[0-9a-f]{48}$/); + } + + // 2. Callback error message HTML is escaped (no reflected XSS) + { + let responseHtml = ""; + let responseStatus = 0; + const flow = new GmailOAuthFlow("cid", "csec"); + flow.createOAuth2Client = (redirectUri) => ({ + generateAuthUrl: (opts) => { + const u = new URL("https://accounts.google.com/o/oauth2/v2/auth"); + u.searchParams.set("redirect_uri", redirectUri); + u.searchParams.set("state", opts.state); + return u.toString(); + }, + getToken: async () => { + throw new Error(''); + }, + }); + flow.openBrowser = (authUrl) => { + const parsedAuth = new URL(authUrl); + const redirectUri = parsedAuth.searchParams.get("redirect_uri"); + const state = parsedAuth.searchParams.get("state"); + void fetch(`${redirectUri}/?code=abc&state=${state}`).then(async (res) => { + responseStatus = res.status; + responseHtml = await res.text(); + }); + }; + + await assert.rejects(() => flow.authorize(false), /onerror/); + // Wait a tick for fetch text promise to resolve + await new Promise((r) => setTimeout(r, 20)); + assert.equal(responseStatus, 500); + assert.equal(responseHtml.includes(" ({ + generateAuthUrl: (opts) => { + const u = new URL("https://accounts.google.com/o/oauth2/v2/auth"); + u.searchParams.set("redirect_uri", redirectUri); + u.searchParams.set("state", opts.state); + return u.toString(); + }, + getToken: async (code) => { + receivedCode = code; + return { tokens: { refresh_token: "fresh-refresh-token" } }; + }, + }); + flow.openBrowser = (authUrl) => { + const parsedAuth = new URL(authUrl); + const redirectUri = parsedAuth.searchParams.get("redirect_uri"); + const state = parsedAuth.searchParams.get("state"); + void fetch(`${redirectUri}/?code=good-code&state=${state}`); + }; + + const token = await flow.authorize(false); + assert.equal(token, "fresh-refresh-token"); + assert.equal(receivedCode, "good-code"); + } +});