Skip to content
Open
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
21 changes: 21 additions & 0 deletions src/services/auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, test } from "bun:test";

import { startAuthFlow } from "./auth.js";

describe("startAuthFlow", () => {
test("keeps waiting for the callback when the browser cannot be opened", async () => {
let authUrl = "";
const flow = startAuthFlow(5_000, async (url) => {
authUrl = url.toString();
throw new Error("spawn xdg-open ENOENT");
});

await new Promise((resolve) => setTimeout(resolve, 50));
const callback = new URL(new URL(authUrl).searchParams.get("callback")!);
callback.searchParams.set("state", "wrong");
const response = await fetch(callback);

expect(response.status).toBe(403);
expect(await flow).toEqual({ success: false, error: "Invalid auth state" });
});
});
9 changes: 3 additions & 6 deletions src/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export interface AuthResult {
error?: string;
}

export function startAuthFlow(timeoutMs = AUTH_TIMEOUT): Promise<AuthResult> {
export function startAuthFlow(timeoutMs = AUTH_TIMEOUT, open = openUrl): Promise<AuthResult> {
return new Promise((resolve) => {
let resolved = false;
const stateToken = randomBytes(16).toString("hex");
Expand Down Expand Up @@ -168,12 +168,9 @@ export function startAuthFlow(timeoutMs = AUTH_TIMEOUT): Promise<AuthResult> {

console.log("Opening browser for authentication...");
console.log(`If it doesn't open, visit: ${authUrl}`);
openUrl(authUrl).catch((error) => {
open(authUrl).catch((error) => {
if (!resolved) {
resolved = true;
clearTimeout(timer);
server.close();
resolve({ success: false, error: `Failed to open browser: ${error.message}` });
console.log(`Could not open a browser (${error.message}). Open the URL above to continue.`);
}
});
});
Expand Down