@coffre/conformance 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,325 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import type { ServerResponse } from 'node:http';
3
+
4
+ import { readParams, redirect, repeatedParam, sendHtml, type Route } from './http.ts';
5
+ import type { DevIdp, RegisteredClient } from './idp.ts';
6
+ import { consentPage, errorPage } from './pages.ts';
7
+ import { isEmail, normalizeEmail } from './people.ts';
8
+
9
+ /**
10
+ * What differs between the OIDC and GitHub authorization endpoints. The rest
11
+ * -- client and redirect checks, PKCE, the persona page, codes and tokens --
12
+ * is one implementation.
13
+ */
14
+ export interface Flavor {
15
+ name: 'oidc' | 'github';
16
+ /** The authorization endpoint; the persona page posts back to it. */
17
+ path: string;
18
+ /** Shown above the page title. */
19
+ label: string;
20
+ /** Seconds a code stays redeemable. */
21
+ codeTtl: number;
22
+ /** Adds RFC 9207 `iss` to every response when set. GitHub sends none. */
23
+ issuer: (() => string) | null;
24
+ /** Checks the flavor's own parameters; returns an RFC 6749 error or what they ask for. */
25
+ parse(params: URLSearchParams): FlavorRequest | { error: string; description: string };
26
+ /** Extra response parameters when the person clicks "Deny". */
27
+ denied: Record<string, string>;
28
+ }
29
+
30
+ export interface FlavorRequest {
31
+ scope: string[];
32
+ nonce?: string;
33
+ /** Who the client suggests signing in; an email once resolved. */
34
+ hint?: string;
35
+ }
36
+
37
+ /** An approved request: who signed in, for which client, with what. */
38
+ export interface Grant {
39
+ flavor: Flavor['name'];
40
+ clientId: string;
41
+ redirectUri: string;
42
+ scope: string[];
43
+ nonce?: string;
44
+ codeChallenge: string;
45
+ email: string;
46
+ /** Seconds since the epoch. */
47
+ authTime: number;
48
+ }
49
+
50
+ interface CodeRecord {
51
+ grant: Grant;
52
+ expiresAt: number;
53
+ used: boolean;
54
+ accessToken?: string;
55
+ }
56
+
57
+ interface TokenRecord {
58
+ grant: Grant;
59
+ expiresAt: number;
60
+ }
61
+
62
+ type Parsed =
63
+ | { kind: 'ok'; client: RegisteredClient; redirectUri: string; state: string; codeChallenge: string; request: FlavorRequest }
64
+ // The client or its redirect URI is not trusted: say so on a page, never redirect.
65
+ | { kind: 'untrusted'; message: string }
66
+ // Trusted redirect URI, bad request: report it back to the client.
67
+ | { kind: 'error'; redirectUri: string; state?: string; error: string; description: string };
68
+
69
+ export type ExchangeResult =
70
+ | { ok: true; grant: Grant; accessToken: string; expiresIn: number }
71
+ | { ok: false; error: 'invalid_code' | 'redirect_uri_mismatch' | 'invalid_verifier' };
72
+
73
+ export function randomToken(): string {
74
+ return randomBytes(32).toString('base64url');
75
+ }
76
+
77
+ /**
78
+ * The built-in client accepts any loopback URI, because local dev ports vary;
79
+ * every other redirect URI must match a registered one exactly.
80
+ */
81
+ export function allowsRedirect(client: RegisteredClient, uri: string): boolean {
82
+ if (client.redirectUris.includes(uri)) return true;
83
+ if (!client.anyLoopbackRedirect) return false;
84
+ let url: URL;
85
+ try {
86
+ url = new URL(uri);
87
+ } catch {
88
+ return false;
89
+ }
90
+ return (
91
+ url.protocol === 'http:' &&
92
+ (url.hostname === '127.0.0.1' || url.hostname === 'localhost') &&
93
+ url.username === '' &&
94
+ url.password === '' &&
95
+ !uri.includes('#')
96
+ );
97
+ }
98
+
99
+ /** RFC 7636 §4.6, S256 only. */
100
+ function verifies(verifier: string, challenge: string): boolean {
101
+ if (!/^[A-Za-z0-9\-._~]{43,128}$/.test(verifier)) return false;
102
+ return createHash('sha256').update(verifier).digest('base64url') === challenge;
103
+ }
104
+
105
+ /** Codes and the access tokens they turn into, for both flavors. In memory only. */
106
+ export class AuthorizationServer {
107
+ #idp: DevIdp;
108
+ #codes = new Map<string, CodeRecord>();
109
+ #tokens = new Map<string, TokenRecord>();
110
+
111
+ constructor(idp: DevIdp) {
112
+ this.#idp = idp;
113
+ }
114
+
115
+ /** The GET (show the page, or auto-approve) and POST (the page's answer) routes. */
116
+ routes(flavor: Flavor): Route[] {
117
+ return [
118
+ {
119
+ method: 'GET',
120
+ path: flavor.path,
121
+ handler: async (_req, res, url) => {
122
+ const parsed = this.#parse(flavor, url.searchParams);
123
+ if (parsed.kind !== 'ok') return this.#fail(flavor, res, parsed);
124
+
125
+ const hint = parsed.request.hint;
126
+ if (this.#idp.autoApprove && hint !== undefined && isEmail(hint)) {
127
+ return redirect(res, this.#approve(flavor, parsed, normalizeEmail(hint)));
128
+ }
129
+ this.#page(flavor, res, 200, parsed, url.searchParams);
130
+ },
131
+ },
132
+ {
133
+ method: 'POST',
134
+ path: flavor.path,
135
+ handler: async (req, res) => {
136
+ const params = await readParams(req);
137
+ if (params === null) {
138
+ return sendHtml(res, 400, errorPage(flavor.label, 'The form could not be read.'));
139
+ }
140
+ const email = normalizeEmail(params.get('email') ?? '');
141
+ const deny = params.has('deny');
142
+ params.delete('email');
143
+ params.delete('deny');
144
+
145
+ // The carried parameters came back through the browser: check them again.
146
+ const parsed = this.#parse(flavor, params);
147
+ if (parsed.kind !== 'ok') return this.#fail(flavor, res, parsed);
148
+
149
+ if (deny) {
150
+ return redirect(
151
+ res,
152
+ this.#location(flavor, parsed.redirectUri, {
153
+ error: 'access_denied',
154
+ ...flavor.denied,
155
+ state: parsed.state,
156
+ }),
157
+ );
158
+ }
159
+ if (!isEmail(email)) {
160
+ return this.#page(flavor, res, 400, parsed, params, 'Pick a persona or enter an email address.');
161
+ }
162
+ redirect(res, this.#approve(flavor, parsed, email));
163
+ },
164
+ },
165
+ ];
166
+ }
167
+
168
+ /**
169
+ * Redeem a code. Codes are single-use even when the attempt fails, and
170
+ * presenting a spent code revokes the token it produced (RFC 6749 §4.1.2).
171
+ */
172
+ exchange(
173
+ flavor: Flavor['name'],
174
+ opts: {
175
+ client: RegisteredClient;
176
+ code: string;
177
+ /** Undefined skips the check (GitHub makes the parameter optional). */
178
+ redirectUri: string | undefined;
179
+ codeVerifier: string;
180
+ accessTokenTtl: number;
181
+ accessTokenPrefix?: string;
182
+ },
183
+ ): ExchangeResult {
184
+ this.#sweep();
185
+ const record = this.#codes.get(opts.code);
186
+ if (!record || record.grant.flavor !== flavor) return { ok: false, error: 'invalid_code' };
187
+ if (record.used) {
188
+ if (record.accessToken) this.#tokens.delete(record.accessToken);
189
+ this.#codes.delete(opts.code);
190
+ return { ok: false, error: 'invalid_code' };
191
+ }
192
+ record.used = true;
193
+
194
+ const { grant } = record;
195
+ if (grant.clientId !== opts.client.clientId) return { ok: false, error: 'invalid_code' };
196
+ if (opts.redirectUri !== undefined && opts.redirectUri !== grant.redirectUri) {
197
+ return { ok: false, error: 'redirect_uri_mismatch' };
198
+ }
199
+ if (!verifies(opts.codeVerifier, grant.codeChallenge)) return { ok: false, error: 'invalid_verifier' };
200
+
201
+ const accessToken = (opts.accessTokenPrefix ?? '') + randomToken();
202
+ record.accessToken = accessToken;
203
+ this.#tokens.set(accessToken, { grant, expiresAt: Date.now() + opts.accessTokenTtl * 1000 });
204
+ return { ok: true, grant, accessToken, expiresIn: opts.accessTokenTtl };
205
+ }
206
+
207
+ /** The grant behind a live access token of this flavor. */
208
+ grantFor(flavor: Flavor['name'], accessToken: string): Grant | undefined {
209
+ const record = this.#tokens.get(accessToken);
210
+ if (!record || record.grant.flavor !== flavor || record.expiresAt <= Date.now()) return undefined;
211
+ return record.grant;
212
+ }
213
+
214
+ #parse(flavor: Flavor, params: URLSearchParams): Parsed {
215
+ const repeated = repeatedParam(params);
216
+ if (repeated) return { kind: 'untrusted', message: `Parameter ${repeated} is repeated.` };
217
+
218
+ const clientId = params.get('client_id');
219
+ if (!clientId) return { kind: 'untrusted', message: 'client_id is missing.' };
220
+ const client = this.#idp.client(clientId);
221
+ if (!client) return { kind: 'untrusted', message: `Unknown client ${clientId}.` };
222
+
223
+ const redirectUri = params.get('redirect_uri');
224
+ if (!redirectUri) return { kind: 'untrusted', message: 'redirect_uri is missing.' };
225
+ if (!allowsRedirect(client, redirectUri)) {
226
+ return { kind: 'untrusted', message: `${redirectUri} is not a redirect URI registered for ${clientId}.` };
227
+ }
228
+
229
+ const fail = (error: string, description: string): Parsed => ({
230
+ kind: 'error',
231
+ redirectUri,
232
+ state: params.get('state') ?? undefined,
233
+ error,
234
+ description,
235
+ });
236
+
237
+ const request = flavor.parse(params);
238
+ if ('error' in request) return fail(request.error, request.description);
239
+
240
+ // Required here even where GitHub only recommends them, so a client that
241
+ // drops CSRF or PKCE protection fails its tests rather than production.
242
+ const state = params.get('state');
243
+ if (!state) return fail('invalid_request', 'state is required');
244
+ const method = params.get('code_challenge_method');
245
+ const codeChallenge = params.get('code_challenge');
246
+ if (!codeChallenge) return fail('invalid_request', 'code_challenge is required');
247
+ if (method !== 'S256') return fail('invalid_request', 'code_challenge_method must be S256');
248
+ if (!/^[A-Za-z0-9_-]{43}$/.test(codeChallenge)) {
249
+ return fail('invalid_request', 'code_challenge must be a base64url SHA-256 digest');
250
+ }
251
+
252
+ return { kind: 'ok', client, redirectUri, state, codeChallenge, request };
253
+ }
254
+
255
+ #fail(flavor: Flavor, res: ServerResponse, parsed: Exclude<Parsed, { kind: 'ok' }>): void {
256
+ if (parsed.kind === 'untrusted') return sendHtml(res, 400, errorPage(flavor.label, parsed.message));
257
+ redirect(
258
+ res,
259
+ this.#location(flavor, parsed.redirectUri, {
260
+ error: parsed.error,
261
+ error_description: parsed.description,
262
+ state: parsed.state,
263
+ }),
264
+ );
265
+ }
266
+
267
+ #page(
268
+ flavor: Flavor,
269
+ res: ServerResponse,
270
+ status: number,
271
+ parsed: Extract<Parsed, { kind: 'ok' }>,
272
+ carry: URLSearchParams,
273
+ message?: string,
274
+ ): void {
275
+ sendHtml(
276
+ res,
277
+ status,
278
+ consentPage({
279
+ label: flavor.label,
280
+ action: flavor.path,
281
+ clientId: parsed.client.clientId,
282
+ redirectUri: parsed.redirectUri,
283
+ scope: parsed.request.scope,
284
+ carry,
285
+ hint: parsed.request.hint,
286
+ message,
287
+ }),
288
+ );
289
+ }
290
+
291
+ #approve(flavor: Flavor, parsed: Extract<Parsed, { kind: 'ok' }>, email: string): string {
292
+ this.#sweep();
293
+ const code = randomToken();
294
+ this.#codes.set(code, {
295
+ grant: {
296
+ flavor: flavor.name,
297
+ clientId: parsed.client.clientId,
298
+ redirectUri: parsed.redirectUri,
299
+ scope: parsed.request.scope,
300
+ nonce: parsed.request.nonce,
301
+ codeChallenge: parsed.codeChallenge,
302
+ email,
303
+ authTime: Math.floor(Date.now() / 1000),
304
+ },
305
+ expiresAt: Date.now() + flavor.codeTtl * 1000,
306
+ used: false,
307
+ });
308
+ return this.#location(flavor, parsed.redirectUri, { code, state: parsed.state });
309
+ }
310
+
311
+ #location(flavor: Flavor, redirectUri: string, params: Record<string, string | undefined>): string {
312
+ const url = new URL(redirectUri);
313
+ for (const [name, value] of Object.entries(params)) {
314
+ if (value !== undefined) url.searchParams.set(name, value);
315
+ }
316
+ if (flavor.issuer) url.searchParams.set('iss', flavor.issuer());
317
+ return url.href;
318
+ }
319
+
320
+ #sweep(): void {
321
+ const now = Date.now();
322
+ for (const [code, record] of this.#codes) if (record.expiresAt <= now) this.#codes.delete(code);
323
+ for (const [token, record] of this.#tokens) if (record.expiresAt <= now) this.#tokens.delete(token);
324
+ }
325
+ }
@@ -0,0 +1,207 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+
3
+ import type { AuthorizationServer, Flavor, Grant } from './authorize.ts';
4
+ import { authorizationToken, readParams, sendJson, type Route } from './http.ts';
5
+ import type { DevIdp } from './idp.ts';
6
+ import { isEmail, normalizeEmail, sha256Hex, type GitHubAccount } from './people.ts';
7
+
8
+ // Coffre is configured with a web base URL (https://github.com in production)
9
+ // and an API base URL (https://api.github.com); locally these two prefixes.
10
+ const WEB = '/github';
11
+ const API = '/github/api';
12
+
13
+ const DOCS = 'https://docs.github.com/rest';
14
+ const TROUBLESHOOTING = 'https://docs.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors';
15
+
16
+ /**
17
+ * Enough of GitHub's OAuth apps and REST API for coffre's GitHub sign-in:
18
+ * the web flow, the authenticated user, their emails, and org membership.
19
+ * GitHub is not an OIDC provider, and its token endpoint has quirks a
20
+ * standard OAuth client trips on; this imitates them rather than smoothing
21
+ * them over.
22
+ */
23
+ export class FakeGitHub {
24
+ #idp: DevIdp;
25
+ #authz: AuthorizationServer;
26
+ readonly flavor: Flavor;
27
+
28
+ constructor(idp: DevIdp, authz: AuthorizationServer) {
29
+ this.#idp = idp;
30
+ this.#authz = authz;
31
+ // https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps
32
+ this.flavor = {
33
+ name: 'github',
34
+ path: `${WEB}/login/oauth/authorize`,
35
+ label: 'coffre dev IdP · fake GitHub',
36
+ // "The code expires after 10 minutes."
37
+ codeTtl: 600,
38
+ issuer: null,
39
+ parse(params) {
40
+ // Requested space-delimited; commas have long been accepted too.
41
+ const scope = (params.get('scope') ?? '').split(/[\s,]+/).filter(Boolean);
42
+ // GitHub's own hint is `login`, a username; login_hint is ours, an email.
43
+ const login = params.get('login') ?? undefined;
44
+ const hint =
45
+ params.get('login_hint') ??
46
+ (login === undefined || isEmail(login) ? login : idp.emailForGitHubLogin(login));
47
+ return { scope: [...new Set(scope)], hint };
48
+ },
49
+ denied: {
50
+ error_description: 'The user has denied your application access.',
51
+ error_uri: 'https://docs.github.com/apps/managing-oauth-apps/troubleshooting-authorization-request-errors/#access-denied',
52
+ },
53
+ };
54
+ }
55
+
56
+ routes(): Route[] {
57
+ return [
58
+ ...this.#authz.routes(this.flavor),
59
+ { method: 'POST', path: `${WEB}/login/oauth/access_token`, handler: (req, res) => this.#accessToken(req, res) },
60
+ { method: 'GET', path: `${API}/user`, handler: async (req, res) => this.#user(req, res) },
61
+ { method: 'GET', path: `${API}/user/emails`, handler: async (req, res) => this.#emails(req, res) },
62
+ {
63
+ method: 'GET',
64
+ path: new RegExp(`^${API}/user/memberships/orgs/[^/]+$`),
65
+ handler: async (req, res, url) => this.#membership(req, res, decodeURIComponent(url.pathname.split('/').pop()!)),
66
+ },
67
+ ];
68
+ }
69
+
70
+ /**
71
+ * The quirks: JSON only when asked for with `Accept`, form-encoded
72
+ * otherwise; errors are HTTP 200 with an `error` field; scopes come back
73
+ * comma-separated.
74
+ * https://docs.github.com/en/apps/oauth-apps/maintaining-oauth-apps/troubleshooting-oauth-app-access-token-request-errors
75
+ */
76
+ async #accessToken(req: IncomingMessage, res: ServerResponse): Promise<void> {
77
+ const reply = (body: Record<string, string>) => {
78
+ if ((req.headers.accept ?? '').includes('application/json')) return sendJson(res, 200, body);
79
+ res.writeHead(200, { 'content-type': 'application/x-www-form-urlencoded; charset=utf-8' });
80
+ res.end(new URLSearchParams(body).toString());
81
+ };
82
+ const fail = (error: string, description: string) =>
83
+ reply({ error, error_description: description, error_uri: `${TROUBLESHOOTING}#${error.replaceAll('_', '-')}` });
84
+
85
+ const params = (await readParams(req)) ?? new URLSearchParams();
86
+ let clientId = params.get('client_id');
87
+ let clientSecret = params.get('client_secret');
88
+ const basic = authorizationToken(req, ['basic']);
89
+ if (basic !== undefined && clientSecret === null) {
90
+ const decoded = Buffer.from(basic, 'base64').toString('utf8');
91
+ const colon = decoded.indexOf(':');
92
+ clientId = decoded.slice(0, colon);
93
+ clientSecret = decoded.slice(colon + 1);
94
+ }
95
+ const client = clientId ? this.#idp.client(clientId) : undefined;
96
+ if (!client || client.clientSecret !== clientSecret) {
97
+ return fail('incorrect_client_credentials', 'The client_id and/or client_secret passed are incorrect.');
98
+ }
99
+
100
+ const result = this.#authz.exchange('github', {
101
+ client,
102
+ code: params.get('code') ?? '',
103
+ redirectUri: params.get('redirect_uri') ?? undefined,
104
+ codeVerifier: params.get('code_verifier') ?? '',
105
+ // OAuth app tokens do not expire unless the app opts in.
106
+ accessTokenTtl: Infinity,
107
+ accessTokenPrefix: 'gho_',
108
+ });
109
+ if (!result.ok) {
110
+ if (result.error === 'redirect_uri_mismatch') {
111
+ return fail('redirect_uri_mismatch', 'The redirect_uri MUST match the registered callback URL for this application.');
112
+ }
113
+ return fail('bad_verification_code', 'The code passed is incorrect or expired.');
114
+ }
115
+ reply({ access_token: result.accessToken, token_type: 'bearer', scope: result.grant.scope.join(',') });
116
+ }
117
+
118
+ /** https://docs.github.com/en/rest/users/users#get-the-authenticated-user */
119
+ #user(req: IncomingMessage, res: ServerResponse): void {
120
+ const auth = this.#authenticate(req, res);
121
+ if (!auth) return;
122
+ const { account } = auth;
123
+ const publicEmail = account.emails.find((e) => e.primary && e.visibility === 'public');
124
+ this.#json(res, auth.grant, 200, {
125
+ login: account.login,
126
+ id: account.id,
127
+ node_id: `U_dev${account.id}`,
128
+ html_url: `${this.#idp.origin}${WEB}/${account.login}`,
129
+ type: 'User',
130
+ site_admin: false,
131
+ name: account.name,
132
+ email: publicEmail?.email ?? null,
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Needs `user:email` (or `user`). Without it GitHub answers 404, not 403.
138
+ * https://docs.github.com/en/rest/users/emails#list-email-addresses-for-the-authenticated-user
139
+ */
140
+ #emails(req: IncomingMessage, res: ServerResponse): void {
141
+ const auth = this.#authenticate(req, res);
142
+ if (!auth) return;
143
+ if (!this.#hasScope(auth.grant, ['user:email', 'user'])) return this.#notFound(res, auth.grant);
144
+ this.#json(res, auth.grant, 200, auth.account.emails);
145
+ }
146
+
147
+ /**
148
+ * Needs `read:org` (implied by `write:org`, `admin:org` and `user`), else 403;
149
+ * 404 when the user is not a member.
150
+ * https://docs.github.com/en/rest/orgs/members#get-an-organization-membership-for-the-authenticated-user
151
+ * https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
152
+ */
153
+ #membership(req: IncomingMessage, res: ServerResponse, org: string): void {
154
+ const auth = this.#authenticate(req, res);
155
+ if (!auth) return;
156
+ if (!this.#hasScope(auth.grant, ['read:org', 'write:org', 'admin:org', 'user'])) {
157
+ return this.#json(res, auth.grant, 403, {
158
+ message: 'You need at least read:org scope or user scope to read organization memberships.',
159
+ documentation_url: DOCS,
160
+ });
161
+ }
162
+ const login = auth.account.orgs.find((o) => o.toLowerCase() === org.toLowerCase());
163
+ if (!login) return this.#notFound(res, auth.grant);
164
+
165
+ const api = `${this.#idp.origin}${API}`;
166
+ this.#json(res, auth.grant, 200, {
167
+ url: `${api}/orgs/${login}/memberships/${auth.account.login}`,
168
+ state: 'active',
169
+ role: 'member',
170
+ organization_url: `${api}/orgs/${login}`,
171
+ organization: {
172
+ login,
173
+ id: 2_000_000 + Number.parseInt(sha256Hex(`github-org:${login.toLowerCase()}`).slice(0, 7), 16),
174
+ url: `${api}/orgs/${login}`,
175
+ },
176
+ user: { login: auth.account.login, id: auth.account.id, type: 'User' },
177
+ });
178
+ }
179
+
180
+ /** `Bearer` or GitHub's older `token` scheme; 401 otherwise. */
181
+ #authenticate(req: IncomingMessage, res: ServerResponse): { grant: Grant; account: GitHubAccount } | undefined {
182
+ const token = authorizationToken(req, ['bearer', 'token']);
183
+ if (token === undefined) {
184
+ sendJson(res, 401, { message: 'Requires authentication', documentation_url: DOCS });
185
+ return undefined;
186
+ }
187
+ const grant = this.#authz.grantFor('github', token);
188
+ if (!grant) {
189
+ sendJson(res, 401, { message: 'Bad credentials', documentation_url: DOCS });
190
+ return undefined;
191
+ }
192
+ return { grant, account: this.#idp.gitHubUserFor(normalizeEmail(grant.email)) };
193
+ }
194
+
195
+ #hasScope(grant: Grant, accepted: readonly string[]): boolean {
196
+ return grant.scope.some((s) => accepted.includes(s));
197
+ }
198
+
199
+ /** Every authenticated response lists the token's scopes, as GitHub's do. */
200
+ #json(res: ServerResponse, grant: Grant, status: number, body: unknown): void {
201
+ sendJson(res, status, body, { 'x-oauth-scopes': grant.scope.join(', ') });
202
+ }
203
+
204
+ #notFound(res: ServerResponse, grant: Grant): void {
205
+ this.#json(res, grant, 404, { message: 'Not Found', documentation_url: DOCS });
206
+ }
207
+ }
@@ -0,0 +1,97 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+
3
+ export type Handler = (req: IncomingMessage, res: ServerResponse, url: URL) => Promise<void>;
4
+
5
+ export interface Route {
6
+ method: 'GET' | 'POST';
7
+ path: string | RegExp;
8
+ handler: Handler;
9
+ }
10
+
11
+ export function sendJson(
12
+ res: ServerResponse,
13
+ status: number,
14
+ body: unknown,
15
+ headers: Record<string, string> = {},
16
+ ): void {
17
+ res.writeHead(status, { 'content-type': 'application/json', ...headers });
18
+ res.end(JSON.stringify(body));
19
+ }
20
+
21
+ export function sendHtml(res: ServerResponse, status: number, html: string): void {
22
+ res.writeHead(status, {
23
+ 'content-type': 'text/html; charset=utf-8',
24
+ // Everything is inline; nothing else may load. No form-action: browsers
25
+ // apply it to the redirect that follows a submission, which is the point.
26
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'",
27
+ 'x-frame-options': 'DENY',
28
+ 'cache-control': 'no-store',
29
+ });
30
+ res.end(html);
31
+ }
32
+
33
+ export function redirect(res: ServerResponse, location: string): void {
34
+ res.writeHead(302, { location, 'cache-control': 'no-store' });
35
+ res.end();
36
+ }
37
+
38
+ export function escapeHtml(value: string): string {
39
+ return value
40
+ .replaceAll('&', '&amp;')
41
+ .replaceAll('<', '&lt;')
42
+ .replaceAll('>', '&gt;')
43
+ .replaceAll('"', '&quot;')
44
+ .replaceAll("'", '&#39;');
45
+ }
46
+
47
+ /**
48
+ * Read a form or JSON body as parameters. Returns null for a body that does
49
+ * not parse, so callers can answer with their own protocol's error shape.
50
+ */
51
+ export async function readParams(req: IncomingMessage): Promise<URLSearchParams | null> {
52
+ const chunks: Buffer[] = [];
53
+ let size = 0;
54
+ for await (const chunk of req) {
55
+ size += (chunk as Buffer).length;
56
+ if (size > 64 * 1024) return null;
57
+ chunks.push(chunk as Buffer);
58
+ }
59
+ const body = Buffer.concat(chunks).toString('utf8');
60
+ const type = (req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase();
61
+
62
+ if (type === 'application/json') {
63
+ try {
64
+ const parsed: unknown = JSON.parse(body);
65
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null;
66
+ const params = new URLSearchParams();
67
+ for (const [key, value] of Object.entries(parsed)) {
68
+ if (typeof value === 'string') params.set(key, value);
69
+ }
70
+ return params;
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+ if (type === 'application/x-www-form-urlencoded') return new URLSearchParams(body);
76
+ return null;
77
+ }
78
+
79
+ /** RFC 6749 §3.1: request parameters must not be included more than once. */
80
+ export function repeatedParam(params: URLSearchParams): string | undefined {
81
+ const seen = new Set<string>();
82
+ for (const key of params.keys()) {
83
+ if (seen.has(key)) return key;
84
+ seen.add(key);
85
+ }
86
+ return undefined;
87
+ }
88
+
89
+ /** The token from `Authorization: <scheme> <token>`, for any of the given schemes. */
90
+ export function authorizationToken(
91
+ req: IncomingMessage,
92
+ schemes: readonly string[],
93
+ ): string | undefined {
94
+ const match = /^(\S+) +(\S+)$/.exec(req.headers.authorization ?? '');
95
+ if (!match || !schemes.includes(match[1]!.toLowerCase())) return undefined;
96
+ return match[2];
97
+ }