@coffre/conformance 0.0.0 → 0.1.0

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.
package/src/idp/idp.ts ADDED
@@ -0,0 +1,331 @@
1
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
+ import { exportJWK, generateKeyPair, SignJWT, type JWK, type CryptoKey } from 'jose';
3
+
4
+ import { AuthorizationServer } from './authorize.ts';
5
+ import { FakeGitHub } from './github.ts';
6
+ import type { Route } from './http.ts';
7
+ import { OidcProvider } from './oidc.ts';
8
+ import {
9
+ defaultGitHubAccount,
10
+ defaultSubject,
11
+ displayName,
12
+ gitHubEmails,
13
+ normalizeEmail,
14
+ PERSONAS,
15
+ type GitHubAccount,
16
+ type GitHubAccountPatch,
17
+ } from './people.ts';
18
+
19
+ export interface DevIdpClient {
20
+ clientId: string;
21
+ clientSecret: string;
22
+ /** Matched exactly. */
23
+ redirectUris: readonly string[];
24
+ }
25
+
26
+ export interface RegisteredClient extends DevIdpClient {
27
+ /** Accept any http://127.0.0.1 or http://localhost redirect URI, on any port. */
28
+ anyLoopbackRedirect: boolean;
29
+ }
30
+
31
+ export interface DevIdpOptions {
32
+ /** Registered alongside the built-in `coffre-local` client. */
33
+ clients?: readonly DevIdpClient[];
34
+ /** Skip the persona page when the request carries a login hint. For tests. */
35
+ autoApprove?: boolean;
36
+ }
37
+
38
+ /** Built in, so local dev needs no registration step. */
39
+ export const DEFAULT_CLIENT = Object.freeze({
40
+ clientId: 'coffre-local',
41
+ clientSecret: 'coffre-local-secret',
42
+ });
43
+
44
+ /**
45
+ * A local stand-in for the identity providers coffre trusts.
46
+ *
47
+ * For Cloudflare Access, it generates a keypair, serves a JWKS at the same
48
+ * `cdn-cgi` path Access uses, and mints Access-shaped tokens. It is also an
49
+ * OpenID Connect provider (under `/oauth`) signing with the same key, and an
50
+ * imitation of GitHub's OAuth apps and REST API (under `/github`). The
51
+ * point is that the code under test runs its real remote code paths against
52
+ * real HTTP endpoints -- local mode is a different implementation of the same
53
+ * interface, never a branch that skips verification.
54
+ */
55
+ export class DevIdp {
56
+ #server: Server | null = null;
57
+ #port = 0;
58
+ #clients = new Map<string, RegisteredClient>();
59
+ #subjects = new Map<string, string>();
60
+ #gitHubAccounts = new Map<string, GitHubAccount>();
61
+ #routes: Route[];
62
+
63
+ privateKey!: CryptoKey;
64
+ publicJwk!: JWK;
65
+ readonly kid = 'dev-idp-key-1';
66
+
67
+ /** Used by the /dev/mint convenience endpoint when no aud is supplied. */
68
+ defaultAudience = 'coffre-local-dev-aud';
69
+
70
+ /** Fixed port for the standalone dev server; 0 (ephemeral) in tests. */
71
+ listenPort = 0;
72
+
73
+ /** See {@link DevIdpOptions.autoApprove}. */
74
+ autoApprove: boolean;
75
+
76
+ constructor(options: DevIdpOptions = {}) {
77
+ this.autoApprove = options.autoApprove ?? false;
78
+ this.#clients.set(DEFAULT_CLIENT.clientId, {
79
+ ...DEFAULT_CLIENT,
80
+ redirectUris: [],
81
+ anyLoopbackRedirect: true,
82
+ });
83
+ for (const client of options.clients ?? []) this.registerClient(client);
84
+
85
+ const authz = new AuthorizationServer(this);
86
+ this.#routes = [...new OidcProvider(this, authz).routes(), ...new FakeGitHub(this, authz).routes()];
87
+ }
88
+
89
+ get origin(): string {
90
+ if (this.#port === 0) throw new Error('DevIdp is not started');
91
+ return `http://127.0.0.1:${this.#port}`;
92
+ }
93
+
94
+ /** Matches the Cloudflare Access team-domain issuer shape. */
95
+ get issuer(): string {
96
+ return this.origin;
97
+ }
98
+
99
+ /** Access publishes its keys under this exact path. */
100
+ get jwksUrl(): string {
101
+ return `${this.origin}/cdn-cgi/access/certs`;
102
+ }
103
+
104
+ async start(): Promise<void> {
105
+ const { privateKey, publicKey } = await generateKeyPair('RS256', { extractable: true });
106
+ this.privateKey = privateKey;
107
+ this.publicJwk = { ...(await exportJWK(publicKey)), kid: this.kid, alg: 'RS256', use: 'sig' };
108
+
109
+ this.#server = createServer((req, res) => {
110
+ // Dev-only: stands in for `cloudflared access login`. Cloudflare Access
111
+ // has no equivalent endpoint -- in production the browser SSO flow issues
112
+ // the token and the CLI reads it via cloudflared.
113
+ if (req.url?.startsWith('/dev/mint')) {
114
+ const url = new URL(req.url, this.origin);
115
+ const audience = url.searchParams.get('aud') ?? this.defaultAudience;
116
+ const email = url.searchParams.get('email');
117
+ const commonName = url.searchParams.get('common_name');
118
+
119
+ // Callers choose their own lifetime. The web UI asks for a working
120
+ // day, because a token minted for the default 15 minutes turned every
121
+ // local session into a sign-in every quarter of an hour. Left
122
+ // unspecified so the default still applies to everything else.
123
+ const requested = Number(url.searchParams.get('expires_in'));
124
+ const expiresIn =
125
+ Number.isInteger(requested) && requested > 0 ? requested : undefined;
126
+
127
+ const minted = commonName
128
+ ? this.mintServiceToken({ audience, commonName, expiresIn })
129
+ : this.mintUserToken({ audience, email: email ?? 'admin@acme.example', expiresIn });
130
+
131
+ minted.then((token) => {
132
+ res.writeHead(200, { 'content-type': 'application/json' });
133
+ res.end(JSON.stringify({ token }));
134
+ });
135
+ return;
136
+ }
137
+ if (req.url === '/cdn-cgi/access/certs') {
138
+ res.writeHead(200, { 'content-type': 'application/json' });
139
+ res.end(JSON.stringify({ keys: [this.publicJwk] }));
140
+ return;
141
+ }
142
+ this.#dispatch(req, res);
143
+ });
144
+
145
+ await new Promise<void>((resolve) => {
146
+ this.#server!.listen(this.listenPort, '127.0.0.1', () => {
147
+ const address = this.#server!.address();
148
+ if (address === null || typeof address === 'string') throw new Error('no port');
149
+ this.#port = address.port;
150
+ resolve();
151
+ });
152
+ });
153
+ }
154
+
155
+ async stop(): Promise<void> {
156
+ if (!this.#server) return;
157
+ await new Promise<void>((resolve) => this.#server!.close(() => resolve()));
158
+ this.#server = null;
159
+ this.#port = 0;
160
+ }
161
+
162
+ registerClient(client: DevIdpClient): void {
163
+ this.#clients.set(client.clientId, {
164
+ clientId: client.clientId,
165
+ clientSecret: client.clientSecret,
166
+ redirectUris: [...client.redirectUris],
167
+ anyLoopbackRedirect: false,
168
+ });
169
+ }
170
+
171
+ client(clientId: string): RegisteredClient | undefined {
172
+ return this.#clients.get(clientId);
173
+ }
174
+
175
+ /** The OIDC `sub` for an email: derived, unless {@link setSubject} overrode it. */
176
+ subjectFor(email: string): string {
177
+ const normalized = normalizeEmail(email);
178
+ return this.#subjects.get(normalized) ?? defaultSubject(normalized);
179
+ }
180
+
181
+ /**
182
+ * From now on, whoever signs in with this email gets this subject. Simulates
183
+ * an address being recycled to a new person: same email, different account.
184
+ */
185
+ setSubject(email: string, subject: string): void {
186
+ this.#subjects.set(normalizeEmail(email), subject);
187
+ }
188
+
189
+ /** The fake GitHub account that signs in with this email. */
190
+ gitHubUserFor(email: string): GitHubAccount {
191
+ const normalized = normalizeEmail(email);
192
+ return this.#gitHubAccounts.get(normalized) ?? defaultGitHubAccount(normalized);
193
+ }
194
+
195
+ /**
196
+ * From now on, whoever picks this email on the fake GitHub gets this account,
197
+ * patched over the current one. A new `id` simulates a recycled address;
198
+ * `emails` can add several, unverified ones included; `orgs` sets memberships.
199
+ */
200
+ setGitHubUser(email: string, patch: GitHubAccountPatch): void {
201
+ const current = this.gitHubUserFor(email);
202
+ this.#gitHubAccounts.set(normalizeEmail(email), {
203
+ id: patch.id ?? current.id,
204
+ login: patch.login ?? current.login,
205
+ name: patch.name ?? current.name,
206
+ emails: patch.emails ? gitHubEmails(patch.emails) : current.emails,
207
+ orgs: patch.orgs ? [...patch.orgs] : current.orgs,
208
+ });
209
+ }
210
+
211
+ /** The email that signs in as a GitHub login, for GitHub's `login` hint. */
212
+ emailForGitHubLogin(login: string): string | undefined {
213
+ const wanted = login.toLowerCase();
214
+ for (const [email, account] of this.#gitHubAccounts) {
215
+ if (account.login.toLowerCase() === wanted) return email;
216
+ }
217
+ return PERSONAS.find((p) => this.gitHubUserFor(p.email).login.toLowerCase() === wanted)?.email;
218
+ }
219
+
220
+ /** An OIDC ID token, as the token endpoint issues it. */
221
+ async mintIdToken(opts: {
222
+ clientId: string;
223
+ email: string;
224
+ nonce?: string;
225
+ authTime?: number;
226
+ expiresIn?: number;
227
+ }): Promise<string> {
228
+ const email = normalizeEmail(opts.email);
229
+ return this.#sign(
230
+ {
231
+ sub: this.subjectFor(email),
232
+ auth_time: opts.authTime ?? Math.floor(Date.now() / 1000),
233
+ ...(opts.nonce !== undefined && { nonce: opts.nonce }),
234
+ email,
235
+ email_verified: true,
236
+ name: displayName(email),
237
+ },
238
+ { audience: opts.clientId, expiresIn: opts.expiresIn ?? 600 },
239
+ );
240
+ }
241
+
242
+ /** Mint a token shaped like an Access identity (human) token. */
243
+ async mintUserToken(opts: {
244
+ audience: string;
245
+ email?: string;
246
+ sub?: string;
247
+ issuer?: string;
248
+ expiresIn?: number;
249
+ notBefore?: number;
250
+ key?: CryptoKey;
251
+ }): Promise<string> {
252
+ return this.#sign(
253
+ {
254
+ email: opts.email ?? 'admin@acme.example',
255
+ sub: opts.sub ?? '0f9a1c2e-1111-2222-3333-444455556666',
256
+ identity_nonce: 'devnonce',
257
+ },
258
+ opts,
259
+ );
260
+ }
261
+
262
+ /**
263
+ * Mint a token shaped like an Access *service token*.
264
+ *
265
+ * Deliberately faithful to the real thing: no email claim at all, and an
266
+ * empty sub. Code that reads `claims.email` to identify the caller produces
267
+ * `undefined` here, which is how machine callers end up in the audit log
268
+ * with no actor.
269
+ */
270
+ async mintServiceToken(opts: {
271
+ audience: string;
272
+ commonName?: string;
273
+ issuer?: string;
274
+ expiresIn?: number;
275
+ key?: CryptoKey;
276
+ }): Promise<string> {
277
+ return this.#sign(
278
+ {
279
+ sub: '',
280
+ common_name: opts.commonName ?? 'e367826f93b8d71185e03fe518aff3b4.access',
281
+ },
282
+ opts,
283
+ );
284
+ }
285
+
286
+ #dispatch(req: IncomingMessage, res: ServerResponse): void {
287
+ const url = new URL(req.url ?? '/', this.origin);
288
+ const matches = this.#routes.filter((route) =>
289
+ typeof route.path === 'string' ? route.path === url.pathname : route.path.test(url.pathname),
290
+ );
291
+ if (matches.length === 0) {
292
+ res.writeHead(404).end();
293
+ return;
294
+ }
295
+ const route = matches.find((r) => r.method === req.method);
296
+ if (!route) {
297
+ res.writeHead(405, { allow: matches.map((r) => r.method).join(', ') }).end();
298
+ return;
299
+ }
300
+ route.handler(req, res, url).catch((error: unknown) => {
301
+ console.error(error);
302
+ if (!res.headersSent) res.writeHead(500);
303
+ res.end();
304
+ });
305
+ }
306
+
307
+ async #sign(
308
+ claims: Record<string, unknown>,
309
+ opts: {
310
+ audience: string;
311
+ issuer?: string;
312
+ expiresIn?: number;
313
+ notBefore?: number;
314
+ key?: CryptoKey;
315
+ },
316
+ ): Promise<string> {
317
+ const now = Math.floor(Date.now() / 1000);
318
+ const expiresIn = opts.expiresIn ?? 900;
319
+
320
+ const jwt = new SignJWT(claims)
321
+ .setProtectedHeader({ alg: 'RS256', kid: this.kid })
322
+ .setIssuedAt(now)
323
+ .setIssuer(opts.issuer ?? this.issuer)
324
+ .setAudience(opts.audience)
325
+ .setExpirationTime(now + expiresIn);
326
+
327
+ if (opts.notBefore !== undefined) jwt.setNotBefore(now + opts.notBefore);
328
+
329
+ return jwt.sign(opts.key ?? this.privateKey);
330
+ }
331
+ }
@@ -0,0 +1,5 @@
1
+ // A stand-in for the identity providers coffre trusts: Cloudflare Access, an
2
+ // OpenID Connect provider and GitHub. The suite signs its personas in through
3
+ // it; the dev loop and the tests use it too.
4
+ export { DEFAULT_CLIENT, DevIdp, type DevIdpClient, type DevIdpOptions, type RegisteredClient } from './idp.ts';
5
+ export { PERSONAS, type GitHubAccount, type GitHubAccountPatch, type Persona } from './people.ts';
@@ -0,0 +1,209 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+
3
+ import type { AuthorizationServer, Flavor } from './authorize.ts';
4
+ import { authorizationToken, readParams, repeatedParam, sendJson, type Route } from './http.ts';
5
+ import type { DevIdp, RegisteredClient } from './idp.ts';
6
+ import { displayName } from './people.ts';
7
+
8
+ const ACCESS_TOKEN_TTL = 3600;
9
+
10
+ /**
11
+ * A small OpenID Connect provider: authorization code flow with PKCE,
12
+ * confidential clients, userinfo. Enough for a generic OIDC client to run
13
+ * its real code path end to end.
14
+ */
15
+ export class OidcProvider {
16
+ #idp: DevIdp;
17
+ #authz: AuthorizationServer;
18
+ readonly flavor: Flavor;
19
+
20
+ constructor(idp: DevIdp, authz: AuthorizationServer) {
21
+ this.#idp = idp;
22
+ this.#authz = authz;
23
+ this.flavor = {
24
+ name: 'oidc',
25
+ path: '/oauth/authorize',
26
+ label: 'coffre dev IdP · OpenID Connect',
27
+ codeTtl: 60,
28
+ issuer: () => idp.issuer,
29
+ parse(params) {
30
+ const responseType = params.get('response_type');
31
+ if (!responseType) return { error: 'invalid_request', description: 'response_type is required' };
32
+ if (responseType !== 'code') {
33
+ return { error: 'unsupported_response_type', description: 'only response_type=code is supported' };
34
+ }
35
+ const scope = (params.get('scope') ?? '').split(' ').filter(Boolean);
36
+ if (!scope.includes('openid')) return { error: 'invalid_scope', description: 'scope must include openid' };
37
+ return {
38
+ scope: [...new Set(scope)],
39
+ nonce: params.get('nonce') ?? undefined,
40
+ hint: params.get('login_hint') ?? undefined,
41
+ };
42
+ },
43
+ denied: { error_description: 'The user denied the request' },
44
+ };
45
+ }
46
+
47
+ routes(): Route[] {
48
+ return [
49
+ {
50
+ method: 'GET',
51
+ path: '/.well-known/openid-configuration',
52
+ handler: async (_req, res) => sendJson(res, 200, this.#discovery()),
53
+ },
54
+ ...this.#authz.routes(this.flavor),
55
+ { method: 'POST', path: '/oauth/token', handler: (req, res) => this.#token(req, res) },
56
+ { method: 'GET', path: '/oauth/userinfo', handler: async (req, res) => this.#userinfo(req, res) },
57
+ ];
58
+ }
59
+
60
+ #discovery() {
61
+ const origin = this.#idp.origin;
62
+ return {
63
+ issuer: this.#idp.issuer,
64
+ authorization_endpoint: `${origin}/oauth/authorize`,
65
+ token_endpoint: `${origin}/oauth/token`,
66
+ userinfo_endpoint: `${origin}/oauth/userinfo`,
67
+ jwks_uri: this.#idp.jwksUrl,
68
+ response_types_supported: ['code'],
69
+ response_modes_supported: ['query'],
70
+ grant_types_supported: ['authorization_code'],
71
+ subject_types_supported: ['public'],
72
+ id_token_signing_alg_values_supported: ['RS256'],
73
+ code_challenge_methods_supported: ['S256'],
74
+ token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
75
+ scopes_supported: ['openid', 'email', 'profile'],
76
+ claims_supported: ['iss', 'sub', 'aud', 'iat', 'exp', 'auth_time', 'nonce', 'email', 'email_verified', 'name'],
77
+ authorization_response_iss_parameter_supported: true,
78
+ };
79
+ }
80
+
81
+ /** RFC 6749 §4.1.3, errors per §5.2. */
82
+ async #token(req: IncomingMessage, res: ServerResponse): Promise<void> {
83
+ const fail = (status: number, error: string, description: string, headers: Record<string, string> = {}) =>
84
+ sendJson(res, status, { error, error_description: description }, { 'cache-control': 'no-store', ...headers });
85
+
86
+ const params = await readParams(req);
87
+ if (params === null) return fail(400, 'invalid_request', 'expected an application/x-www-form-urlencoded body');
88
+ const repeated = repeatedParam(params);
89
+ if (repeated) return fail(400, 'invalid_request', `parameter ${repeated} is repeated`);
90
+
91
+ const auth = this.#authenticate(req, params);
92
+ if ('error' in auth) {
93
+ if (auth.error !== 'invalid_client') return fail(400, auth.error, auth.description);
94
+ return fail(401, auth.error, auth.description, { 'www-authenticate': 'Basic realm="dev-idp"' });
95
+ }
96
+
97
+ const grantType = params.get('grant_type');
98
+ if (grantType !== 'authorization_code') {
99
+ return fail(400, grantType ? 'unsupported_grant_type' : 'invalid_request', 'grant_type must be authorization_code');
100
+ }
101
+ const code = params.get('code');
102
+ const redirectUri = params.get('redirect_uri');
103
+ const codeVerifier = params.get('code_verifier');
104
+ if (!code || !redirectUri || !codeVerifier) {
105
+ return fail(400, 'invalid_request', 'code, redirect_uri and code_verifier are required');
106
+ }
107
+
108
+ const result = this.#authz.exchange('oidc', {
109
+ client: auth.client,
110
+ code,
111
+ redirectUri,
112
+ codeVerifier,
113
+ accessTokenTtl: ACCESS_TOKEN_TTL,
114
+ });
115
+ if (!result.ok) {
116
+ const description = {
117
+ invalid_code: 'the code is invalid, expired, already used, or was issued to another client',
118
+ redirect_uri_mismatch: 'redirect_uri does not match the authorization request',
119
+ invalid_verifier: 'code_verifier does not match the code_challenge',
120
+ }[result.error];
121
+ return fail(400, 'invalid_grant', description);
122
+ }
123
+
124
+ const { grant } = result;
125
+ const idToken = await this.#idp.mintIdToken({
126
+ clientId: grant.clientId,
127
+ email: grant.email,
128
+ nonce: grant.nonce,
129
+ authTime: grant.authTime,
130
+ });
131
+ sendJson(
132
+ res,
133
+ 200,
134
+ {
135
+ access_token: result.accessToken,
136
+ token_type: 'Bearer',
137
+ expires_in: result.expiresIn,
138
+ id_token: idToken,
139
+ scope: grant.scope.join(' '),
140
+ },
141
+ { 'cache-control': 'no-store', pragma: 'no-cache' },
142
+ );
143
+ }
144
+
145
+ /** client_secret_basic or client_secret_post, never both (RFC 6749 §2.3). */
146
+ #authenticate(
147
+ req: IncomingMessage,
148
+ params: URLSearchParams,
149
+ ): { client: RegisteredClient } | { error: string; description: string } {
150
+ const basic = authorizationToken(req, ['basic']);
151
+ let clientId: string | null;
152
+ let clientSecret: string | null;
153
+
154
+ if (basic !== undefined) {
155
+ if (params.has('client_secret')) {
156
+ return { error: 'invalid_request', description: 'use one client authentication method' };
157
+ }
158
+ // §2.3.1: both halves are form-encoded before base64.
159
+ const decoded = Buffer.from(basic, 'base64').toString('utf8');
160
+ const colon = decoded.indexOf(':');
161
+ if (colon < 0) return { error: 'invalid_client', description: 'malformed Basic credentials' };
162
+ try {
163
+ const formDecode = (s: string) => decodeURIComponent(s.replaceAll('+', ' '));
164
+ clientId = formDecode(decoded.slice(0, colon));
165
+ clientSecret = formDecode(decoded.slice(colon + 1));
166
+ } catch {
167
+ return { error: 'invalid_client', description: 'malformed Basic credentials' };
168
+ }
169
+ const bodyId = params.get('client_id');
170
+ if (bodyId !== null && bodyId !== clientId) {
171
+ return { error: 'invalid_client', description: 'client_id does not match the credentials' };
172
+ }
173
+ } else {
174
+ clientId = params.get('client_id');
175
+ clientSecret = params.get('client_secret');
176
+ }
177
+
178
+ if (!clientId || !clientSecret) return { error: 'invalid_client', description: 'client authentication is required' };
179
+ const client = this.#idp.client(clientId);
180
+ if (!client || client.clientSecret !== clientSecret) {
181
+ return { error: 'invalid_client', description: 'unknown client or wrong secret' };
182
+ }
183
+ return { client };
184
+ }
185
+
186
+ #userinfo(req: IncomingMessage, res: ServerResponse): void {
187
+ const token = authorizationToken(req, ['bearer']);
188
+ if (token === undefined) {
189
+ return sendJson(res, 401, { error: 'invalid_request' }, { 'www-authenticate': 'Bearer realm="dev-idp"' });
190
+ }
191
+ const grant = this.#authz.grantFor('oidc', token);
192
+ if (!grant) {
193
+ return sendJson(res, 401, { error: 'invalid_token' }, {
194
+ 'www-authenticate': 'Bearer realm="dev-idp", error="invalid_token"',
195
+ });
196
+ }
197
+ sendJson(
198
+ res,
199
+ 200,
200
+ {
201
+ sub: this.#idp.subjectFor(grant.email),
202
+ email: grant.email,
203
+ email_verified: true,
204
+ name: displayName(grant.email),
205
+ },
206
+ { 'cache-control': 'no-store' },
207
+ );
208
+ }
209
+ }
@@ -0,0 +1,107 @@
1
+ import { escapeHtml } from './http.ts';
2
+ import { PERSONAS } from './people.ts';
3
+
4
+ const STYLE = `
5
+ :root { color-scheme: light dark; --fg: #1c1c1e; --muted: #6b6b70; --line: #dcdce0;
6
+ --bg: #fafafa; --card: #fff; --accent: #2f5bd3; --danger: #b3261e; }
7
+ @media (prefers-color-scheme: dark) { :root { --fg: #ececee; --muted: #9a9aa2;
8
+ --line: #34343a; --bg: #151517; --card: #1d1d20; --accent: #8aa8ff; --danger: #ff8a80; } }
9
+ * { box-sizing: border-box; }
10
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: var(--bg);
11
+ color: var(--fg); font: 15px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; }
12
+ main { width: min(440px, calc(100vw - 32px)); margin: 32px 0; }
13
+ .eyebrow { margin: 0; color: var(--muted); font-size: 13px; }
14
+ h1 { margin: 4px 0 6px; font-size: 20px; font-weight: 600; }
15
+ p { margin: 0 0 16px; color: var(--muted); }
16
+ code { font: 13px ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--fg); word-break: break-all; }
17
+ ul { list-style: none; margin: 0 0 16px; padding: 0; border: 1px solid var(--line);
18
+ border-radius: 8px; background: var(--card); overflow: hidden; }
19
+ li + li { border-top: 1px solid var(--line); }
20
+ button { font: inherit; cursor: pointer; }
21
+ .persona { all: unset; box-sizing: border-box; display: grid; grid-template-columns: 1fr auto;
22
+ width: 100%; padding: 10px 14px; cursor: pointer; }
23
+ .persona:hover, .persona:focus-visible { background: color-mix(in srgb, var(--accent) 8%, transparent); }
24
+ .persona:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
25
+ .persona small { grid-column: 1; color: var(--muted); }
26
+ .persona em { grid-row: 1 / span 2; grid-column: 2; align-self: center; font-style: normal;
27
+ font-size: 12px; color: var(--muted); }
28
+ .other { display: flex; gap: 8px; margin-bottom: 12px; }
29
+ input { flex: 1; min-width: 0; font: inherit; padding: 7px 10px; color: var(--fg);
30
+ background: var(--card); border: 1px solid var(--line); border-radius: 6px; }
31
+ .primary { padding: 7px 14px; border: 0; border-radius: 6px; background: var(--accent); color: var(--bg); }
32
+ .deny { padding: 0; border: 0; background: none; color: var(--muted); text-decoration: underline; }
33
+ .error { color: var(--danger); }
34
+ `;
35
+
36
+ function layout(title: string, body: string): string {
37
+ return `<!doctype html>
38
+ <html lang="en">
39
+ <head>
40
+ <meta charset="utf-8">
41
+ <meta name="viewport" content="width=device-width, initial-scale=1">
42
+ <title>${escapeHtml(title)}</title>
43
+ <style>${STYLE}</style>
44
+ </head>
45
+ <body><main>
46
+ ${body}
47
+ </main></body>
48
+ </html>
49
+ `;
50
+ }
51
+
52
+ function hiddenInputs(params: URLSearchParams): string {
53
+ return [...params]
54
+ .map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`)
55
+ .join('');
56
+ }
57
+
58
+ export function consentPage(opts: {
59
+ label: string;
60
+ action: string;
61
+ clientId: string;
62
+ redirectUri: string;
63
+ scope: readonly string[];
64
+ /** The original request parameters, re-validated when the form comes back. */
65
+ carry: URLSearchParams;
66
+ hint?: string;
67
+ message?: string;
68
+ }): string {
69
+ const carry = hiddenInputs(opts.carry);
70
+ const personas = PERSONAS.map(
71
+ (p) => `<li><button class="persona" name="email" value="${escapeHtml(p.email)}">
72
+ <span>${escapeHtml(p.name)}</span><small>${escapeHtml(p.email)}</small><em>${escapeHtml(p.note)}</em>
73
+ </button></li>`,
74
+ ).join('\n');
75
+ const scope = opts.scope.length > 0 ? opts.scope.join(' ') : '(none)';
76
+
77
+ return layout(
78
+ `Sign in to ${opts.clientId}`,
79
+ `<p class="eyebrow">${escapeHtml(opts.label)}</p>
80
+ <h1>Sign in to <code>${escapeHtml(opts.clientId)}</code></h1>
81
+ <p>Returns to <code>${escapeHtml(opts.redirectUri)}</code><br>with scope <code>${escapeHtml(scope)}</code></p>
82
+ ${opts.message ? `<p class="error">${escapeHtml(opts.message)}</p>` : ''}
83
+ <form method="post" action="${escapeHtml(opts.action)}">${carry}
84
+ <ul>
85
+ ${personas}
86
+ </ul>
87
+ </form>
88
+ <form method="post" action="${escapeHtml(opts.action)}" class="other">${carry}
89
+ <input type="email" name="email" required placeholder="someone@example.com" aria-label="Another email" value="${escapeHtml(opts.hint ?? '')}">
90
+ <button class="primary">Continue</button>
91
+ </form>
92
+ <form method="post" action="${escapeHtml(opts.action)}">${carry}
93
+ <button class="deny" name="deny" value="1">Deny access</button>
94
+ </form>`,
95
+ );
96
+ }
97
+
98
+ /** For requests that cannot safely be sent back to the client. */
99
+ export function errorPage(label: string, message: string): string {
100
+ return layout(
101
+ 'Sign-in error',
102
+ `<p class="eyebrow">${escapeHtml(label)}</p>
103
+ <h1>This sign-in request is invalid</h1>
104
+ <p class="error">${escapeHtml(message)}</p>
105
+ <p>The client was not redirected back, because it or its redirect URI could not be trusted.</p>`,
106
+ );
107
+ }