peppa/packages/testkit/src/mock-oauth-service.ts
peppa-bot c83454889c
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/test test: success за 1416с
peppa-ci / ci (pull_request) Successful in 26m6s
PEP-252: вход в сервисы через OAuth (Google, GitHub) — поверх свежей main
Ядро (обновление токенов, «Войти заново», отзыв в сервисе), экран «Подключения»,
тексты ru/kk/en, мок и тесты. Пересобрано на main после PEP-251/258:
миграция теперь 0033_access_hub_oauth, маскировка ответа — connectionKeyForms
от текущего токена, проверка подключений принимает notify вместе с drivers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:00:23 +00:00

203 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Mock OAuth service (PEP-252) for Access Hub sign-in tests and checks without real Google/GitHub
// clients. Follows each provider's contract:
// google — GET /auth (consents at once → redirect with code+state), POST /token (authorization_code
// with PKCE S256, refresh_token: same refresh token, new access), POST /revoke (token=…),
// resources GET /v4/spreadsheets/<id>, GET /calendar/v3/calendars/<id>/events (Bearer + matching scope);
// github — GET /login/oauth/authorize, POST /login/oauth/access_token (errors as 200 + `error`,
// refresh rotates the refresh token), DELETE /applications/<client_id>/grant (basic client
// auth, JSON {access_token}), resources GET /user, GET /repos/<o>/<r>.
// `revokeAll()` is the person revoking FORGE in the service's settings; `expireAccess()` ages tokens.
// Standalone: `mock-oauth-service google|github [port]`.
import { createHash, randomUUID } from "node:crypto";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
export type MockOAuthKind = "google" | "github";
interface Access {
scopes: string[];
expiresAt: number | null;
refresh: string | null;
}
export class MockOAuthService {
readonly kind: MockOAuthKind;
clientId: string;
clientSecret: string;
/** Lifetime of an access token, seconds; null — never expires (GitHub OAuth app). */
expiresIn: number | null;
/** GitHub (expiring user tokens) gives a new refresh token on each refresh and kills the old one. */
rotateRefresh: boolean;
/** Scopes the person ticks on the consent screen; null — all asked. */
consentScopes: string[] | null = null;
/** The person presses «Cancel». */
deny = false;
/** 503 on token and revoke calls. */
down = false;
readonly codes = new Map<string, { redirectUri: string; challenge: string; scopes: string[] }>();
readonly access = new Map<string, Access>();
readonly refresh = new Map<string, { scopes: string[] }>();
/** For assertions: what reached the service. */
readonly seen: { authorize: URLSearchParams[]; token: URLSearchParams[]; revoked: string[]; api: Array<{ path: string; auth: string }> } = { authorize: [], token: [], revoked: [], api: [] };
private server: Server | null = null;
constructor(kind: MockOAuthKind) {
this.kind = kind;
this.clientId = `mock-${kind}-client`;
this.clientSecret = `mock-${kind}-secret`;
this.expiresIn = kind === "google" ? 3599 : 28800;
this.rotateRefresh = kind === "github";
}
async start(port = 0): Promise<string> {
this.server = createServer((req, res) => void this.handle(req, res).catch(() => this.send(res, 500, { error: "server_error" })));
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()));
}
/** The person revoked FORGE in the service: every token dies. */
revokeAll(): void {
this.access.clear();
this.refresh.clear();
}
/** Every access token is expired now (refresh tokens stay alive). */
expireAccess(): void {
for (const a of this.access.values()) a.expiresAt = Date.now() - 1000;
}
private send(res: ServerResponse, code: number, body: unknown) {
res.writeHead(code, { "content-type": "application/json" });
res.end(code === 204 ? undefined : JSON.stringify(body));
}
private paths() {
return this.kind === "google" ? { authorize: "/auth", token: "/token" } : { authorize: "/login/oauth/authorize", token: "/login/oauth/access_token" };
}
private issue(scopes: string[], refresh: string | null) {
const token = `${this.kind === "github" ? "gho_" : "ya29."}${randomUUID().replace(/-/g, "")}`;
this.access.set(token, { scopes, expiresAt: this.expiresIn == null ? null : Date.now() + this.expiresIn * 1000, refresh });
return token;
}
private tokenAnswer(access: string, refresh: string | null, scopes: string[]) {
const a: Record<string, unknown> = { access_token: access, token_type: "bearer", scope: scopes.join(this.kind === "github" ? "," : " ") };
if (this.expiresIn != null) a.expires_in = this.expiresIn;
if (refresh) a.refresh_token = refresh;
return a;
}
private tokenError(res: ServerResponse, error: string) {
// GitHub answers errors with 200; Google with 400 (401 for a bad client).
this.send(res, this.kind === "github" ? 200 : error === "invalid_client" ? 401 : 400, { error });
}
private async body(req: IncomingMessage): Promise<string> {
let raw = "";
for await (const chunk of req) raw += chunk;
return raw;
}
private async handle(req: IncomingMessage, res: ServerResponse) {
const u = new URL(req.url ?? "/", "http://mock");
const method = req.method ?? "GET";
const p = this.paths();
if (method === "GET" && u.pathname === p.authorize) {
const q = u.searchParams;
this.seen.authorize.push(q);
if (q.get("client_id") !== this.clientId || q.get("response_type") !== "code" || q.get("code_challenge_method") !== "S256" || !q.get("code_challenge") || !q.get("redirect_uri") || !q.get("state")) return this.send(res, 400, { error: "invalid_request" });
const back = new URL(q.get("redirect_uri")!);
back.searchParams.set("state", q.get("state")!);
if (this.deny) back.searchParams.set("error", "access_denied");
else {
const asked = (q.get("scope") ?? "").split(/\s+/).filter(Boolean);
const code = randomUUID();
this.codes.set(code, { redirectUri: q.get("redirect_uri")!, challenge: q.get("code_challenge")!, scopes: this.consentScopes ?? asked });
back.searchParams.set("code", code);
}
res.writeHead(302, { location: back.toString() });
return res.end();
}
if (method === "POST" && u.pathname === p.token) {
if (this.down) return this.send(res, 503, { error: "unavailable" });
const f = new URLSearchParams(await this.body(req));
this.seen.token.push(f);
if (f.get("client_id") !== this.clientId || f.get("client_secret") !== this.clientSecret) return this.tokenError(res, "invalid_client");
if (f.get("grant_type") === "authorization_code") {
const grant = this.codes.get(f.get("code") ?? "");
this.codes.delete(f.get("code") ?? ""); // one use
if (!grant || f.get("redirect_uri") !== grant.redirectUri) return this.tokenError(res, this.kind === "github" ? "bad_verification_code" : "invalid_grant");
if (createHash("sha256").update(f.get("code_verifier") ?? "").digest("base64url") !== grant.challenge) return this.tokenError(res, "invalid_grant");
const refresh = this.expiresIn == null ? null : `rt_${randomUUID().replace(/-/g, "")}`;
if (refresh) this.refresh.set(refresh, { scopes: grant.scopes });
return this.send(res, 200, this.tokenAnswer(this.issue(grant.scopes, refresh), refresh, grant.scopes));
}
if (f.get("grant_type") === "refresh_token") {
const old = f.get("refresh_token") ?? "";
const r = this.refresh.get(old);
if (!r) return this.tokenError(res, this.kind === "github" ? "bad_refresh_token" : "invalid_grant");
let refresh = old;
if (this.rotateRefresh) {
this.refresh.delete(old);
refresh = `rt_${randomUUID().replace(/-/g, "")}`;
this.refresh.set(refresh, r);
}
// Google doesn't resend its refresh token.
return this.send(res, 200, this.tokenAnswer(this.issue(r.scopes, refresh), this.rotateRefresh ? refresh : null, r.scopes));
}
return this.tokenError(res, "unsupported_grant_type");
}
if (this.kind === "google" && method === "POST" && u.pathname === "/revoke") {
if (this.down) return this.send(res, 503, { error: "unavailable" });
const token = new URLSearchParams(await this.body(req)).get("token") ?? "";
this.seen.revoked.push(token);
const known = this.refresh.has(token) || this.access.has(token);
// Revoking a refresh token revokes the whole grant.
for (const [k, a] of this.access) if (k === token || a.refresh === token) this.access.delete(k);
this.refresh.delete(token);
return known ? this.send(res, 200, {}) : this.send(res, 400, { error: "invalid_token" });
}
if (this.kind === "github" && method === "DELETE" && u.pathname === `/applications/${this.clientId}/grant`) {
if (this.down) return this.send(res, 503, { message: "unavailable" });
if (req.headers.authorization !== `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64")}`) return this.send(res, 401, { message: "Requires authentication" });
const token = (JSON.parse((await this.body(req)) || "{}") as { access_token?: string }).access_token ?? "";
this.seen.revoked.push(token);
if (!this.access.has(token)) return this.send(res, 404, { message: "Not Found" });
this.revokeAll();
return this.send(res, 204, null);
}
// Resources: only a live access token with a suitable scope.
const auth = String(req.headers.authorization ?? "");
this.seen.api.push({ path: u.pathname, auth });
const a = this.access.get(auth.replace(/^Bearer /i, ""));
if (!a || (a.expiresAt != null && a.expiresAt <= Date.now())) return this.send(res, 401, this.kind === "github" ? { message: "Bad credentials" } : { error: { code: 401, status: "UNAUTHENTICATED" } });
if (this.kind === "google" && method === "GET" && u.pathname.startsWith("/v4/spreadsheets/")) {
if (!a.scopes.some((s) => /\/spreadsheets(\.readonly)?$/.test(s))) return this.send(res, 403, { error: { code: 403, status: "PERMISSION_DENIED" } });
const id = u.pathname.split("/")[3]!;
if (id === "forge-key-check") return this.send(res, 404, { error: { code: 404, status: "NOT_FOUND" } });
return this.send(res, 200, { spreadsheetId: id, properties: { title: "Продажи" }, values: [["Месяц", "Сумма"], ["Ноябрь", "120"]] });
}
if (this.kind === "google" && method === "GET" && /^\/calendar\/v3\/calendars\/[^/]+\/events$/.test(u.pathname)) {
if (!a.scopes.some((s) => /\/calendar(\.readonly|\.events)?$/.test(s))) return this.send(res, 403, { error: { code: 403, status: "PERMISSION_DENIED" } });
if (u.pathname.includes("forge-key-check")) return this.send(res, 404, { error: { code: 404, status: "NOT_FOUND" } });
return this.send(res, 200, { kind: "calendar#events", items: [{ summary: "Встреча с поставщиком" }] });
}
if (this.kind === "github" && method === "GET" && u.pathname === "/user") return this.send(res, 200, { login: "mock-anna", id: 1001 });
if (this.kind === "github" && method === "GET" && /^\/repos\/[^/]+\/[^/]+$/.test(u.pathname)) return this.send(res, 200, { full_name: u.pathname.slice(7), private: true });
this.send(res, 404, { error: "not_found" });
}
}
if (import.meta.main) {
const kind = (process.argv[2] === "github" ? "github" : "google") as MockOAuthKind;
const s = new MockOAuthService(kind);
const url = await s.start(Number(process.argv[3] ?? process.env.MOCK_PORT ?? 3105));
const K = kind.toUpperCase();
console.log(`mock-oauth-service ${kind} (TEST ONLY): PEPPA_OAUTH_${K}_BASE=${url} PEPPA_OAUTH_${K}_CLIENT_ID=${s.clientId} PEPPA_OAUTH_${K}_CLIENT_SECRET=${s.clientSecret}`);
}