90 lines
4.3 KiB
TypeScript
90 lines
4.3 KiB
TypeScript
// Mock Google OAuth (PEP-90) for tests and checks without a Google Cloud client: GET /auth (the
|
|
// "user" consents at once and is redirected back with code+state), POST /token (checks client,
|
|
// redirect_uri, PKCE S256 and that the code is used once), GET /userinfo (OIDC profile).
|
|
// Standalone: `mock-google [port]` → GOOGLE_OAUTH_BASE=<printed url>.
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { createServer, type Server } from "node:http";
|
|
import type { AddressInfo } from "node:net";
|
|
|
|
export interface MockGoogleAccount {
|
|
sub: string;
|
|
email: string;
|
|
email_verified?: boolean;
|
|
name?: string;
|
|
}
|
|
|
|
interface Grant {
|
|
account: MockGoogleAccount;
|
|
redirectUri: string;
|
|
challenge: string;
|
|
}
|
|
|
|
export class MockGoogle {
|
|
/** Who consents on the next /auth. */
|
|
account: MockGoogleAccount = { sub: "g-1001", email: "anna.petrova@example.com", email_verified: true, name: "Anna Petrova" };
|
|
readonly codes = new Map<string, Grant>();
|
|
readonly tokens = new Map<string, MockGoogleAccount>();
|
|
/** What the platform sent to /auth and /token — for assertions. */
|
|
readonly seen: { auth: URLSearchParams[]; token: URLSearchParams[] } = { auth: [], token: [] };
|
|
clientId = "mock-google-client";
|
|
clientSecret = "mock-google-secret";
|
|
private server: Server | null = null;
|
|
|
|
async start(port = 0): Promise<string> {
|
|
this.server = createServer((req, res) => void this.handle(req.method ?? "GET", req.url ?? "/", req, res));
|
|
await new Promise<void>((r) => this.server!.listen(port, "127.0.0.1", r));
|
|
return `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
|
}
|
|
|
|
async stop(): Promise<void> {
|
|
await new Promise<void>((r) => (this.server ? this.server.close(() => r()) : r()));
|
|
}
|
|
|
|
private async handle(method: string, url: string, req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) {
|
|
const u = new URL(url, "http://mock");
|
|
const send = (code: number, body: unknown) => {
|
|
res.writeHead(code, { "Content-Type": "application/json" });
|
|
res.end(JSON.stringify(body));
|
|
};
|
|
if (method === "GET" && u.pathname === "/auth") {
|
|
const q = u.searchParams;
|
|
this.seen.auth.push(q);
|
|
if (q.get("client_id") !== this.clientId || q.get("response_type") !== "code" || q.get("code_challenge_method") !== "S256" || !q.get("redirect_uri") || !q.get("state")) {
|
|
return send(400, { error: "invalid_request" });
|
|
}
|
|
const code = randomUUID();
|
|
this.codes.set(code, { account: { ...this.account }, redirectUri: q.get("redirect_uri")!, challenge: q.get("code_challenge") ?? "" });
|
|
const back = new URL(q.get("redirect_uri")!);
|
|
back.searchParams.set("code", code);
|
|
back.searchParams.set("state", q.get("state")!);
|
|
res.writeHead(302, { Location: back.toString() });
|
|
return res.end();
|
|
}
|
|
if (method === "POST" && u.pathname === "/token") {
|
|
let raw = "";
|
|
for await (const chunk of req) raw += chunk;
|
|
const f = new URLSearchParams(raw);
|
|
this.seen.token.push(f);
|
|
const grant = this.codes.get(f.get("code") ?? "");
|
|
this.codes.delete(f.get("code") ?? ""); // one use
|
|
if (f.get("client_id") !== this.clientId || f.get("client_secret") !== this.clientSecret) return send(401, { error: "invalid_client" });
|
|
if (!grant || f.get("grant_type") !== "authorization_code" || f.get("redirect_uri") !== grant.redirectUri) return send(400, { error: "invalid_grant" });
|
|
if (createHash("sha256").update(f.get("code_verifier") ?? "").digest("base64url") !== grant.challenge) return send(400, { error: "invalid_grant" });
|
|
const token = randomUUID();
|
|
this.tokens.set(token, grant.account);
|
|
return send(200, { access_token: token, token_type: "Bearer", expires_in: 3600 });
|
|
}
|
|
if (method === "GET" && u.pathname === "/userinfo") {
|
|
const account = this.tokens.get((req.headers.authorization ?? "").replace(/^Bearer /, ""));
|
|
return account ? send(200, account) : send(401, { error: "invalid_token" });
|
|
}
|
|
send(404, { error: "not_found" });
|
|
}
|
|
}
|
|
|
|
if (import.meta.main) {
|
|
const g = new MockGoogle();
|
|
const url = await g.start(Number(process.argv[2] ?? process.env.MOCK_PORT ?? 3104));
|
|
console.log(`mock-google (TEST ONLY): GOOGLE_OAUTH_BASE=${url} GOOGLE_CLIENT_ID=${g.clientId} GOOGLE_CLIENT_SECRET=${g.clientSecret}`);
|
|
}
|