Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,3 @@ dist/
.env.local
*.log
.DS_Store
.mailcp/
86 changes: 70 additions & 16 deletions src/account-storage.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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<string, EmailAccount> = 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 {
Expand All @@ -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 {
Expand All @@ -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;
}
Expand Down
102 changes: 77 additions & 25 deletions src/gmail-oauth-flow.ts
Original file line number Diff line number Diff line change
@@ -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/"];
Expand All @@ -14,15 +14,40 @@ interface AuthResult {
error?: string;
}

export function escapeHtml(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}

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<string> {
const result = manual ? await this.startManualFlow() : await this.startAuthFlow();
if (!result.success) {
Expand All @@ -36,11 +61,14 @@ export class GmailOAuthFlow {

private async startManualFlow(): Promise<AuthResult> {
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:");
Expand All @@ -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;
Expand All @@ -72,11 +109,13 @@ export class GmailOAuthFlow {
}

private startAuthFlow(): Promise<AuthResult> {
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();
Expand All @@ -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...");
Expand All @@ -118,37 +155,52 @@ export class GmailOAuthFlow {
}

private async handleCallback(
query: any,
searchParams: URLSearchParams,
expectedState: string,
res: http.ServerResponse,
resolve: (result: AuthResult) => void,
): Promise<void> {
if (query.error) {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<html><body><h1>Authorization cancelled</h1></body></html>");
const receivedState = searchParams.get("state");
if (!verifyOAuthState(expectedState, receivedState)) {
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
res.end(
"<html><body><h1>Invalid OAuth state</h1><p>State verification failed. Please retry authorization.</p></body></html>",
);
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(`<html><body><h1>Authorization cancelled</h1><p>${escapeHtml(error)}</p></body></html>`);
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("<html><body><h1>No authorization code</h1></body></html>");
this.cleanup();
resolve({ success: false, error: "No authorization code" });
return;
}

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("<html><body><h1>Success!</h1><p>You can close this window.</p></body></html>");
this.cleanup();
resolve({ success: true, refreshToken: tokens.refresh_token || undefined });
} catch (e) {
res.writeHead(500, { "Content-Type": "text/html" });
res.end(`<html><body><h1>Error</h1><p>${e instanceof Error ? e.message : e}</p></body></html>`);
const message = e instanceof Error ? e.message : String(e);
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
res.end(`<html><body><h1>Error</h1><p>${escapeHtml(message)}</p></body></html>`);
this.cleanup();
resolve({ success: false, error: e instanceof Error ? e.message : String(e) });
resolve({ success: false, error: message });
}
}

Expand All @@ -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" });
}
}
Loading
Loading