@krizaka/auth 0.13.0 → 0.13.2
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/README.md +1 -1
- package/dist/{chunk-5CFOMWBN.js → chunk-2QUHBEBL.js} +19 -7
- package/dist/chunk-2QUHBEBL.js.map +1 -0
- package/dist/{chunk-3CLSDLXB.js → chunk-34CFR7EE.js} +123 -30
- package/dist/chunk-34CFR7EE.js.map +1 -0
- package/dist/{chunk-G46LWJPQ.js → chunk-3MIBOYLS.js} +6 -2
- package/dist/{chunk-G46LWJPQ.js.map → chunk-3MIBOYLS.js.map} +1 -1
- package/dist/{chunk-2PWX2B4I.js → chunk-RWKBQE6N.js} +10 -2
- package/dist/chunk-RWKBQE6N.js.map +1 -0
- package/dist/client.js +2 -2
- package/dist/contract.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +124 -32
- package/dist/index.js.map +1 -1
- package/dist/{sessions-Btl3NgOB.d.ts → sessions-DZXjHjzd.d.ts} +1 -1
- package/dist/settings.js +6 -2
- package/dist/settings.js.map +1 -1
- package/dist/testkit.d.ts +1 -1
- package/dist/testkit.js +36 -8
- package/dist/testkit.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-2PWX2B4I.js.map +0 -1
- package/dist/chunk-3CLSDLXB.js.map +0 -1
- package/dist/chunk-5CFOMWBN.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
pkceChallenge,
|
|
15
15
|
rolesSchema,
|
|
16
16
|
sessionsSchema
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-2QUHBEBL.js";
|
|
18
18
|
import {
|
|
19
19
|
AccountError,
|
|
20
20
|
EMAIL_CHANGE_TTL_HOURS,
|
|
@@ -29,13 +29,13 @@ import {
|
|
|
29
29
|
linkToken,
|
|
30
30
|
passwordResetMail,
|
|
31
31
|
postgresAccounts
|
|
32
|
-
} from "./chunk-
|
|
32
|
+
} from "./chunk-34CFR7EE.js";
|
|
33
33
|
import {
|
|
34
34
|
ROLES_CODE,
|
|
35
35
|
RolesError,
|
|
36
36
|
can,
|
|
37
37
|
defineRoles
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-RWKBQE6N.js";
|
|
39
39
|
|
|
40
40
|
// src/admin-gate.ts
|
|
41
41
|
var ADMIN_REFUSAL = {
|
|
@@ -136,14 +136,18 @@ function landingRedirect(request, rule) {
|
|
|
136
136
|
const path = `${target.pathname}${target.search}${target.hash}`;
|
|
137
137
|
const base = rule.origin ? new URL(rule.origin).origin : null;
|
|
138
138
|
const location = base && new URL(home, base).origin === base ? new URL(home, base).href : path;
|
|
139
|
-
return new Response(null, {
|
|
139
|
+
return new Response(null, {
|
|
140
|
+
status: 307,
|
|
141
|
+
headers: { Location: location, "Cache-Control": "private, no-store", Vary: "Cookie" }
|
|
142
|
+
});
|
|
140
143
|
}
|
|
141
144
|
function sessionHint(response, request, options) {
|
|
142
145
|
const session = Boolean(cookieValue(request.headers, options.cookie));
|
|
143
146
|
const flagged = cookieValue(request.headers, SESSION_HINT_COOKIE) === "1";
|
|
144
147
|
const base = `${SESSION_HINT_COOKIE}=${session ? "1" : ""}; Path=/; SameSite=Lax${options.secure ? "; Secure" : ""}`;
|
|
145
148
|
if (session && !flagged) response.headers.append("Set-Cookie", base);
|
|
146
|
-
else if (!session && cookieValue(request.headers, SESSION_HINT_COOKIE) !== void 0)
|
|
149
|
+
else if (!session && cookieValue(request.headers, SESSION_HINT_COOKIE) !== void 0)
|
|
150
|
+
response.headers.append("Set-Cookie", `${base}; Max-Age=0`);
|
|
147
151
|
return response;
|
|
148
152
|
}
|
|
149
153
|
|
|
@@ -157,8 +161,14 @@ function accountsMigration(options = {}) {
|
|
|
157
161
|
return accountsSchema(options).migrations[0].sql({ schema: "public", tables: { accounts: "accounts" } });
|
|
158
162
|
}
|
|
159
163
|
function rolesMigration(roles, options = {}) {
|
|
160
|
-
const tables = {
|
|
161
|
-
|
|
164
|
+
const tables = {
|
|
165
|
+
owner: ident(options.ownerTable ?? "accounts"),
|
|
166
|
+
...options.scopeTable ? { scope: ident(options.scopeTable) } : {}
|
|
167
|
+
};
|
|
168
|
+
return rolesSchema(roles, { scoped: options.scopeTable !== void 0 }).migrations[0].sql({
|
|
169
|
+
schema: "public",
|
|
170
|
+
tables
|
|
171
|
+
});
|
|
162
172
|
}
|
|
163
173
|
|
|
164
174
|
// src/password.ts
|
|
@@ -188,7 +198,12 @@ async function verifyPassword(password, stored) {
|
|
|
188
198
|
const [scheme, n, r, p, salt, hash] = stored.split("$");
|
|
189
199
|
if (scheme !== "scrypt" || !salt || !hash || password.length > PASSWORD_MAX_LENGTH) return false;
|
|
190
200
|
const expected = Buffer.from(hash, "base64url");
|
|
191
|
-
const given = await scrypt(password, Buffer.from(salt, "base64url"), expected.length, {
|
|
201
|
+
const given = await scrypt(password, Buffer.from(salt, "base64url"), expected.length, {
|
|
202
|
+
N: Number(n),
|
|
203
|
+
r: Number(r),
|
|
204
|
+
p: Number(p),
|
|
205
|
+
maxmem: MAXMEM
|
|
206
|
+
});
|
|
192
207
|
return given.length === expected.length && crypto2.timingSafeEqual(given, expected);
|
|
193
208
|
}
|
|
194
209
|
var decoy;
|
|
@@ -205,10 +220,16 @@ function createRoles(deps) {
|
|
|
205
220
|
return role;
|
|
206
221
|
};
|
|
207
222
|
const newToken = deps.token ?? (() => `${deps.tokenPrefix}1.${crypto3.randomBytes(32).toString("base64url")}`);
|
|
208
|
-
const owners = (scopeId) => query("SELECT account_id FROM memberships WHERE scope_id = $1 AND role = $2", [
|
|
223
|
+
const owners = (scopeId) => query("SELECT account_id FROM memberships WHERE scope_id = $1 AND role = $2", [
|
|
224
|
+
scopeId,
|
|
225
|
+
ownerRole()
|
|
226
|
+
]);
|
|
209
227
|
const ownerRole = () => model.roles.find((r) => model.roles.every((x) => model.manages[r].includes(x) || x === r)) ?? model.roles[0];
|
|
210
228
|
async function roleOf(accountId, scopeId) {
|
|
211
|
-
const [row] = await query("SELECT role FROM memberships WHERE scope_id = $1 AND account_id = $2", [
|
|
229
|
+
const [row] = await query("SELECT role FROM memberships WHERE scope_id = $1 AND account_id = $2", [
|
|
230
|
+
scopeId,
|
|
231
|
+
accountId
|
|
232
|
+
]);
|
|
212
233
|
return row?.role ?? null;
|
|
213
234
|
}
|
|
214
235
|
return {
|
|
@@ -216,7 +237,10 @@ function createRoles(deps) {
|
|
|
216
237
|
roleOf,
|
|
217
238
|
/** Every scope the person belongs to, with their role in it. */
|
|
218
239
|
async scopesOf(accountId) {
|
|
219
|
-
return (await query(
|
|
240
|
+
return (await query(
|
|
241
|
+
"SELECT scope_id, role FROM memberships WHERE account_id = $1 ORDER BY created_at",
|
|
242
|
+
[accountId]
|
|
243
|
+
)).map((r) => ({ scopeId: r.scope_id, role: r.role }));
|
|
220
244
|
},
|
|
221
245
|
/** The person's role in the scope if it holds the permission; otherwise `NOT_A_MEMBER` (404: nothing tells the scope exists) or `FORBIDDEN`. */
|
|
222
246
|
async authorize(accountId, scopeId, permission) {
|
|
@@ -238,7 +262,13 @@ function createRoles(deps) {
|
|
|
238
262
|
"SELECT m.account_id, a.email, a.name, m.role, m.created_at FROM memberships m JOIN accounts a ON a.id = m.account_id WHERE m.scope_id = $1 ORDER BY m.created_at",
|
|
239
263
|
[scopeId]
|
|
240
264
|
);
|
|
241
|
-
return rows.map((r) => ({
|
|
265
|
+
return rows.map((r) => ({
|
|
266
|
+
accountId: r.account_id,
|
|
267
|
+
email: r.email,
|
|
268
|
+
name: r.name,
|
|
269
|
+
role: r.role,
|
|
270
|
+
since: r.created_at
|
|
271
|
+
}));
|
|
242
272
|
},
|
|
243
273
|
/** Changes someone's role. The actor must manage both the current and the new role; the last owner can never be demoted. */
|
|
244
274
|
async setRole(scopeId, actor, target, role) {
|
|
@@ -246,8 +276,10 @@ function createRoles(deps) {
|
|
|
246
276
|
const mine = await roleOf(actor.id, scopeId);
|
|
247
277
|
const current = await roleOf(target, scopeId);
|
|
248
278
|
if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);
|
|
249
|
-
if (!model.manages[mine].includes(current) || !model.manages[mine].includes(role))
|
|
250
|
-
|
|
279
|
+
if (!model.manages[mine].includes(current) || !model.manages[mine].includes(role))
|
|
280
|
+
throw new RolesError(ROLES_CODE.notAllowed);
|
|
281
|
+
if (current === ownerRole() && role !== current && (await owners(scopeId)).length <= 1)
|
|
282
|
+
throw new RolesError(ROLES_CODE.lastOwner);
|
|
251
283
|
await query("UPDATE memberships SET role = $3 WHERE scope_id = $1 AND account_id = $2", [scopeId, target, role]);
|
|
252
284
|
},
|
|
253
285
|
/** Removes someone from the scope (or leaves it, when the target is the actor). The last owner cannot go. */
|
|
@@ -266,22 +298,50 @@ function createRoles(deps) {
|
|
|
266
298
|
if (!mine) throw new RolesError(ROLES_CODE.notMember);
|
|
267
299
|
if (!model.manages[mine].includes(role)) throw new RolesError(ROLES_CODE.notAllowed);
|
|
268
300
|
const email = input.email.trim().toLowerCase();
|
|
269
|
-
await query("UPDATE invitations SET used_at = $3 WHERE scope_id = $1 AND email = $2 AND used_at IS NULL", [
|
|
301
|
+
await query("UPDATE invitations SET used_at = $3 WHERE scope_id = $1 AND email = $2 AND used_at IS NULL", [
|
|
302
|
+
scopeId,
|
|
303
|
+
email,
|
|
304
|
+
now
|
|
305
|
+
]);
|
|
270
306
|
const token = newToken();
|
|
271
307
|
const [row] = await query(
|
|
272
308
|
"INSERT INTO invitations (id, scope_id, email, role, token_hash, invited_by, created_at, expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, created_at, expires_at",
|
|
273
|
-
[
|
|
309
|
+
[
|
|
310
|
+
crypto3.randomUUID(),
|
|
311
|
+
scopeId,
|
|
312
|
+
email,
|
|
313
|
+
role,
|
|
314
|
+
deps.tokenHash(token),
|
|
315
|
+
actor.id,
|
|
316
|
+
now,
|
|
317
|
+
addHours(now, deps.inviteTtlHours)
|
|
318
|
+
]
|
|
274
319
|
);
|
|
275
|
-
return {
|
|
320
|
+
return {
|
|
321
|
+
token,
|
|
322
|
+
invitation: { id: row.id, email, role, createdAt: row.created_at, expiresAt: row.expires_at }
|
|
323
|
+
};
|
|
276
324
|
},
|
|
277
325
|
async pendingInvitations(scopeId, now) {
|
|
278
|
-
const rows = await query(
|
|
279
|
-
|
|
326
|
+
const rows = await query(
|
|
327
|
+
"SELECT id, email, role, created_at, expires_at FROM invitations WHERE scope_id = $1 AND used_at IS NULL AND expires_at > $2 ORDER BY created_at",
|
|
328
|
+
[scopeId, now]
|
|
329
|
+
);
|
|
330
|
+
return rows.map((r) => ({
|
|
331
|
+
id: r.id,
|
|
332
|
+
email: r.email,
|
|
333
|
+
role: r.role,
|
|
334
|
+
createdAt: r.created_at,
|
|
335
|
+
expiresAt: r.expires_at
|
|
336
|
+
}));
|
|
280
337
|
},
|
|
281
338
|
async revokeInvitation(scopeId, actor, invitationId, now) {
|
|
282
339
|
const mine = await roleOf(actor.id, scopeId);
|
|
283
340
|
if (!mine) throw new RolesError(ROLES_CODE.notMember);
|
|
284
|
-
const [row] = await query(
|
|
341
|
+
const [row] = await query(
|
|
342
|
+
"SELECT role FROM invitations WHERE id = $1 AND scope_id = $2 AND used_at IS NULL",
|
|
343
|
+
[invitationId, scopeId]
|
|
344
|
+
);
|
|
285
345
|
if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);
|
|
286
346
|
if (!model.manages[mine].includes(row.role)) throw new RolesError(ROLES_CODE.notAllowed);
|
|
287
347
|
await query("UPDATE invitations SET used_at = $2 WHERE id = $1", [invitationId, now]);
|
|
@@ -296,8 +356,15 @@ function createRoles(deps) {
|
|
|
296
356
|
if (row.email !== account.email.trim().toLowerCase()) throw new RolesError(ROLES_CODE.inviteWrongAccount);
|
|
297
357
|
await query("UPDATE invitations SET used_at = $2 WHERE id = $1", [row.id, now]);
|
|
298
358
|
const current = await roleOf(account.id, row.scope_id);
|
|
299
|
-
if (!current || model.manages[current].length < model.manages[row.role].length)
|
|
300
|
-
|
|
359
|
+
if (!current || model.manages[current].length < model.manages[row.role].length)
|
|
360
|
+
await query(
|
|
361
|
+
"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role",
|
|
362
|
+
[row.scope_id, account.id, row.role, row.invited_by, now]
|
|
363
|
+
);
|
|
364
|
+
return {
|
|
365
|
+
scopeId: row.scope_id,
|
|
366
|
+
role: !current || model.manages[current].length < model.manages[row.role].length ? row.role : current
|
|
367
|
+
};
|
|
301
368
|
}
|
|
302
369
|
};
|
|
303
370
|
}
|
|
@@ -308,7 +375,8 @@ var BODY = /^[A-Za-z0-9_-]{43}$/;
|
|
|
308
375
|
var PREFIX = /^[a-z]{1,4}$/;
|
|
309
376
|
var USER_AGENT_MAX = 300;
|
|
310
377
|
function createSessions(deps) {
|
|
311
|
-
if (!PREFIX.test(deps.tokenPrefix))
|
|
378
|
+
if (!PREFIX.test(deps.tokenPrefix))
|
|
379
|
+
throw new RangeError(`tokenPrefix must be 1 to 4 lower-case letters, got ${deps.tokenPrefix}`);
|
|
312
380
|
const head = `${deps.tokenPrefix}1.`;
|
|
313
381
|
const secret = () => typeof deps.secret === "function" ? deps.secret() : deps.secret;
|
|
314
382
|
const isToken = (value) => !!value && value.startsWith(head) && BODY.test(value.slice(head.length));
|
|
@@ -320,12 +388,20 @@ function createSessions(deps) {
|
|
|
320
388
|
tokenHash,
|
|
321
389
|
async create(accountId, meta) {
|
|
322
390
|
const days = typeof deps.sessionDays === "function" ? await deps.sessionDays() : deps.sessionDays;
|
|
323
|
-
if (!Number.isInteger(days) || days < 1)
|
|
391
|
+
if (!Number.isInteger(days) || days < 1)
|
|
392
|
+
throw new RangeError(`sessionDays must be a whole number of days from 1, got ${days}`);
|
|
324
393
|
const token = newToken();
|
|
325
394
|
const createdAt = deps.clock.now();
|
|
326
395
|
const expires = new Date(createdAt);
|
|
327
396
|
expires.setUTCHours(expires.getUTCHours() + days * 24);
|
|
328
|
-
await deps.store.insert({
|
|
397
|
+
await deps.store.insert({
|
|
398
|
+
accountId,
|
|
399
|
+
tokenHash: tokenHash(token),
|
|
400
|
+
createdAt,
|
|
401
|
+
expiresAt: expires,
|
|
402
|
+
ip: meta.ip,
|
|
403
|
+
userAgent: meta.userAgent?.slice(0, USER_AGENT_MAX) ?? null
|
|
404
|
+
});
|
|
329
405
|
return { token, expires };
|
|
330
406
|
},
|
|
331
407
|
async resolve(token) {
|
|
@@ -339,7 +415,15 @@ function createSessions(deps) {
|
|
|
339
415
|
};
|
|
340
416
|
}
|
|
341
417
|
function sessionCookie(token, expires, options) {
|
|
342
|
-
return {
|
|
418
|
+
return {
|
|
419
|
+
name: options.name,
|
|
420
|
+
value: token,
|
|
421
|
+
httpOnly: true,
|
|
422
|
+
secure: options.secure,
|
|
423
|
+
sameSite: "lax",
|
|
424
|
+
path: "/",
|
|
425
|
+
expires
|
|
426
|
+
};
|
|
343
427
|
}
|
|
344
428
|
function clearedSessionCookie(options, now) {
|
|
345
429
|
return sessionCookie("", now, options);
|
|
@@ -385,7 +469,10 @@ function dbSessionStore(query, options) {
|
|
|
385
469
|
const active = options.active ? ` AND a.${ident2(options.active.column)} = $3` : "";
|
|
386
470
|
return {
|
|
387
471
|
async insert(session) {
|
|
388
|
-
await query(
|
|
472
|
+
await query(
|
|
473
|
+
`INSERT INTO ${sessions} (account_id, token_hash, created_at, expires_at, ip, user_agent) VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
474
|
+
[session.accountId, session.tokenHash, session.createdAt, session.expiresAt, session.ip, session.userAgent]
|
|
475
|
+
);
|
|
389
476
|
},
|
|
390
477
|
async find(tokenHash, now) {
|
|
391
478
|
const params = [tokenHash, now];
|
|
@@ -412,7 +499,8 @@ function parseExternalIdentity(body) {
|
|
|
412
499
|
const o = body ?? {};
|
|
413
500
|
const issuer = text(o.issuer);
|
|
414
501
|
const subject = text(o.subject);
|
|
415
|
-
if (!issuer || !subject)
|
|
502
|
+
if (!issuer || !subject)
|
|
503
|
+
throw new FederationError(FEDERATION_CODE.unavailable, "krizaka-users answered without an issuer and a subject");
|
|
416
504
|
return { issuer, subject, email: text(o.email), emailVerified: o.email_verified === true, name: text(o.name) };
|
|
417
505
|
}
|
|
418
506
|
function usersIdentityProvider({ baseUrl, appUrl, fetch }) {
|
|
@@ -420,8 +508,10 @@ function usersIdentityProvider({ baseUrl, appUrl, fetch }) {
|
|
|
420
508
|
const app = appUrl.replace(/\/+$/, "");
|
|
421
509
|
return {
|
|
422
510
|
async start(provider, returnTo, options = {}) {
|
|
423
|
-
if (!isFederatedProvider(provider))
|
|
424
|
-
|
|
511
|
+
if (!isFederatedProvider(provider))
|
|
512
|
+
throw new FederationError(FEDERATION_CODE.unknownProvider, `Unknown provider ${String(provider)}`);
|
|
513
|
+
if (!isLocalReturn(returnTo))
|
|
514
|
+
throw new FederationError(FEDERATION_CODE.badReturn, "That return address is not allowed");
|
|
425
515
|
const state = crypto.randomUUID();
|
|
426
516
|
const query = new URLSearchParams({ return_to: `${app}${returnTo}`, state });
|
|
427
517
|
if (options.codeChallenge) {
|
|
@@ -436,8 +526,10 @@ function usersIdentityProvider({ baseUrl, appUrl, fetch }) {
|
|
|
436
526
|
headers: { "content-type": "application/json" },
|
|
437
527
|
body: JSON.stringify({ code, ...options.codeVerifier ? { code_verifier: options.codeVerifier } : {} })
|
|
438
528
|
});
|
|
439
|
-
if (response.status === 400 || response.status === 401 || response.status === 404 || response.status === 410)
|
|
440
|
-
|
|
529
|
+
if (response.status === 400 || response.status === 401 || response.status === 404 || response.status === 410)
|
|
530
|
+
throw new FederationError(FEDERATION_CODE.invalidCode, "That code is not valid");
|
|
531
|
+
if (!response.ok)
|
|
532
|
+
throw new FederationError(FEDERATION_CODE.unavailable, `krizaka-users answered ${response.status}`);
|
|
441
533
|
return parseExternalIdentity(await response.json());
|
|
442
534
|
}
|
|
443
535
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/admin-gate.ts","../src/client-ip.ts","../src/federated-sign-in.ts","../src/landing.ts","../src/migration.ts","../src/password.ts","../src/roles.ts","../src/sessions.ts","../src/sessions-memory.ts","../src/sessions-persistence.ts","../src/users-federation.ts"],"sourcesContent":["/**\n * The administration's locks, as one pure decision every product shares (it was copied in each product's `lib/access.ts`): a session,\n * the ADMIN role, and an address on the allowed list. A pure function of its inputs: the product reads the session and the address\n * and maps the verdict to its own answer.\n */\n\n/** Stable codes of a refusal. */\nexport const ADMIN_REFUSAL = {\n unauthenticated: \"UNAUTHENTICATED\",\n forbidden: \"FORBIDDEN\",\n ipNotAllowed: \"IP_NOT_ALLOWED\",\n notFound: \"NOT_FOUND\",\n} as const;\nexport type AdminRefusal = (typeof ADMIN_REFUSAL)[keyof typeof ADMIN_REFUSAL];\n\n/** The verdict: let in, or the status and code to answer. */\nexport type AdminDecision = { ok: true } | { ok: false; status: 401 | 403 | 404; code: AdminRefusal };\n\n/**\n * The list the administration's address lock reads, from the environment's value (`AUTH_ALLOWED_IPS`): an empty list is « nobody » in\n * production and « anybody » in development, so a forgotten setting never opens the console.\n * @param list the configured addresses\n * @returns the list to hand to `requireAdmin`, or null (anybody)\n */\nexport function allowedIps(list: readonly string[], options: { production: boolean }): readonly string[] | null {\n if (list.length > 0) return list;\n return options.production ? [] : null;\n}\n\n/** Whether an address may use the administration: `null` allowed means anybody, an empty list nobody, and a missing address is never allowed by a list. */\nexport function ipAllowed(ip: string | null, allowed: readonly string[] | null): boolean {\n if (allowed === null) return true;\n return !!ip && allowed.includes(ip);\n}\n\nexport interface AdminGateInput {\n /** The caller's session, or null when there is none. Only its account's role is read. */\n session: { account: { role: string } } | null;\n /** The caller's address (see `clientIp`). */\n ip: string | null;\n /** The addresses allowed (see `allowedIps`); null = anybody. */\n allowedIps: readonly string[] | null;\n /** `api` (default): 401 without a session, 403 with the reason. `page`: the administration does not announce itself, so every failed lock is a 404. */\n surface?: \"api\" | \"page\";\n /** The role that administers. Default `ADMIN`. */\n role?: string;\n}\n\n/**\n * The administration's three locks. The first that fails decides.\n * @returns `{ ok: true }`, or the status (401, 403 or 404 on a page) and the code to answer\n */\nexport function requireAdmin(input: AdminGateInput): AdminDecision {\n const page = input.surface === \"page\";\n const refuse = (status: 401 | 403, code: AdminRefusal): AdminDecision => (page ? { ok: false, status: 404, code: ADMIN_REFUSAL.notFound } : { ok: false, status, code });\n if (!input.session) return refuse(401, ADMIN_REFUSAL.unauthenticated);\n if (input.session.account.role !== (input.role ?? \"ADMIN\")) return refuse(403, ADMIN_REFUSAL.forbidden);\n if (!ipAllowed(input.ip, input.allowedIps)) return refuse(403, ADMIN_REFUSAL.ipNotAllowed);\n return { ok: true };\n}\n","/** How a deployment tells the client's address: the header its edge sets, and how many proxies append to `X-Forwarded-For`. */\nexport interface ClientIpRules {\n /** A header the edge sets and overwrites with the client's address (`do-connecting-ip` on DigitalOcean App Platform, `cf-connecting-ip` behind Cloudflare). Read first when present. */\n header?: string | undefined;\n /** How many trusted proxies append to `X-Forwarded-For`: 1 (the default) to 10. */\n trustedProxyHops?: number | undefined;\n}\n\nconst IPV4 = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\nconst IPV6 = /^[0-9a-f:]+(?:%\\w+)?$/i;\nfunction isIp(value: string): boolean {\n return (IPV4.test(value) && value.split(\".\").every((n) => Number(n) <= 255)) || (value.includes(\":\") && IPV6.test(value));\n}\n\n/**\n * The client's IP address, as far as this deployment can trust it. `X-Forwarded-For` is a list each proxy appends to: its LEFT end is\n * whatever the client sent (anyone can write `X-Forwarded-For: 1.2.3.4`), so a limit keyed on it is a limit the attacker chooses. The\n * address the last trusted proxy saw is read from the RIGHT:\n *\n * - the `header` the edge sets and overwrites, when present;\n * - otherwise the entry `trustedProxyHops` (default 1: one proxy) from the right of `X-Forwarded-For`, then `X-Real-IP`;\n * - otherwise null (local development without a proxy).\n *\n * The product reads its environment (`ABUSE_CLIENT_IP_HEADER`, `ABUSE_TRUSTED_PROXY_HOPS`) and passes the values: this function reads none.\n * @param headers the request's headers\n * @returns a valid IPv4 or IPv6 address, or null\n */\nexport function clientIp(headers: Headers, rules: ClientIpRules = {}): string | null {\n const custom = rules.header?.trim().toLowerCase();\n if (custom) {\n const value = headers.get(custom)?.split(\",\")[0]?.trim();\n if (value && isIp(value)) return value;\n }\n const hops = Math.max(1, Math.min(10, Number(rules.trustedProxyHops) || 1));\n const chain = (headers.get(\"x-forwarded-for\") ?? \"\")\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean);\n const fromRight = chain[chain.length - hops];\n if (fromRight && isIp(fromRight)) return fromRight;\n const real = headers.get(\"x-real-ip\")?.trim();\n if (real && isIp(real)) return real;\n return null;\n}\n","import type { ExternalIdentity } from \"./federation\";\nimport type { IdentityLinkStore } from \"./identity-links\";\n\n/** What federated sign-in needs from the product's accounts: no second user table, just a look-up and, when registration is open, a creation. */\nexport interface FederatedAccounts {\n /** The account that holds this address (lower case), and whether the product has verified it; null when none. */\n findByEmail(email: string): Promise<{ id: string; emailVerified: boolean } | null>;\n /** Creates an account for a person the provider vouches for (address verified, no password). Absent when registration is closed. */\n create?(identity: ExternalIdentity & { email: string }): Promise<string>;\n}\n\n/** Why a sign-in was refused: a stable code the product maps to its words. */\nexport const FEDERATED_REFUSAL = {\n /** The provider did not verify the address (or gave none): nothing is linked, nothing is created. */\n emailNotVerified: \"EMAIL_NOT_VERIFIED\",\n /** An account holds the address but the product never verified it: linking would let a stranger take it over. */\n accountEmailUnverified: \"ACCOUNT_EMAIL_UNVERIFIED\",\n /** No account, and registration is closed. */\n noAccount: \"NO_ACCOUNT\",\n} as const;\nexport type FederatedRefusal = (typeof FEDERATED_REFUSAL)[keyof typeof FEDERATED_REFUSAL];\n\nexport type FederatedSignInResult =\n /** `via`: `link` already linked, `linked` attached to the account of that address now, `created` a new account. */\n | { status: \"signed-in\"; accountId: string; via: \"link\" | \"linked\" | \"created\" }\n | { status: \"refused\"; code: FederatedRefusal };\n\nexport interface FederatedSignInDeps {\n links: IdentityLinkStore;\n accounts: FederatedAccounts;\n clock: { now(): Date };\n}\n\n/**\n * From a verified external identity to an account of the product. The rule that matters: an identity attaches to an EXISTING account\n * only when the address is verified on both sides — by the provider and by the product. Otherwise a stranger who registers at\n * Facebook with your address would sign in as you.\n */\nexport function createFederatedSignIn({ links, accounts, clock }: FederatedSignInDeps) {\n return {\n async signIn(identity: ExternalIdentity): Promise<FederatedSignInResult> {\n const known = await links.find(identity.issuer, identity.subject);\n if (known) return { status: \"signed-in\", accountId: known, via: \"link\" };\n\n const email = identity.email?.trim().toLowerCase();\n if (!email || !identity.emailVerified) return { status: \"refused\", code: FEDERATED_REFUSAL.emailNotVerified };\n\n const existing = await accounts.findByEmail(email);\n if (existing) {\n if (!existing.emailVerified) return { status: \"refused\", code: FEDERATED_REFUSAL.accountEmailUnverified };\n await links.link(existing.id, identity.issuer, identity.subject, clock.now());\n return { status: \"signed-in\", accountId: existing.id, via: \"linked\" };\n }\n\n if (!accounts.create) return { status: \"refused\", code: FEDERATED_REFUSAL.noAccount };\n const accountId = await accounts.create({ ...identity, email });\n await links.link(accountId, identity.issuer, identity.subject, clock.now());\n return { status: \"signed-in\", accountId, via: \"created\" };\n },\n };\n}\n\nexport type FederatedSignIn = ReturnType<typeof createFederatedSignIn>;\n","// The two proxy-side rules of « a signed-in person never sees the public side » (krizaka-ui#827), the same for every\n// product. Web-standard Request/Response only (a Next.js `proxy.ts` calls them). The cookie is a HINT: its presence\n// decides a redirect and a placeholder, never an authorization — the page and the API still resolve the session.\n\n/** The readable flag the proxy keeps next to the HttpOnly session cookie: « a session cookie exists », value `1`, never the token. */\nexport const SESSION_HINT_COOKIE = \"kz-session\";\n\nconst cookieValue = (headers: Headers, name: string): string | undefined => {\n const prefix = `${name}=`;\n return headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix))\n ?.slice(prefix.length);\n};\n\n/** Where a signed-in visitor of the landing route goes. */\nexport interface LandingRule {\n /** The product's session cookie name (`yomizaka_session`). */\n cookie: string;\n /** The landing routes (`[\"/\", \"/fr\", \"/en\"]`): exact paths, a trailing slash tolerated. */\n landing: readonly string[];\n /** The signed-in start page, or a function of the request (the language of the address). */\n home: string | ((request: Request) => string);\n /**\n * The product's own public origin (`https://dev.yomizaka.com`), from its declared environment (APP_URL), NEVER from the\n * request: `Host` and `x-forwarded-*` are client-controlled. With it the Location is absolute on that origin (what a\n * Next.js proxy accepts). Only the origin of the value is used. Optional outside production (the Location is then\n * relative); REQUIRED in production, where a missing origin throws instead of falling back to the request's headers.\n */\n origin?: string;\n}\n\n// Linear on any input (a loop, not a `/\\/+$/` regular expression: CodeQL js/polynomial-redos on the request path).\nconst trimmed = (path: string) => {\n let end = path.length;\n while (end > 1 && path.charCodeAt(end - 1) === 47) end--;\n return path.slice(0, end);\n};\n\n/**\n * The landing route with a session cookie answers 307 to the home before any HTML: private, never stored, varying with the\n * cookie. `null` for everything else (a signed-out visitor, another page, a write).\n */\nexport function landingRedirect(request: Request, rule: LandingRule): Response | null {\n // Fail loudly at the first request of a misconfigured deployment, signed in or not: never a silent fallback.\n if (!rule.origin && globalThis.process?.env?.NODE_ENV === \"production\") {\n throw new Error(\"landingRedirect: `origin` (the app's declared public URL) is required in production\");\n }\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return null;\n if (!cookieValue(request.headers, rule.cookie)) return null;\n const url = new URL(request.url);\n if (!rule.landing.some((path) => trimmed(path) === trimmed(url.pathname))) return null;\n const home = typeof rule.home === \"function\" ? rule.home(request) : rule.home;\n // Never built from the request's Host or scheme (client-controlled: host-header injection, open redirect). Relative by\n // default; absolute only on the origin the app configured, and a `home` that leaves that origin falls back to relative.\n const target = new URL(home, url);\n const path = `${target.pathname}${target.search}${target.hash}`;\n const base = rule.origin ? new URL(rule.origin).origin : null;\n const location = base && new URL(home, base).origin === base ? new URL(home, base).href : path;\n return new Response(null, { status: 307, headers: { Location: location, \"Cache-Control\": \"private, no-store\", Vary: \"Cookie\" } });\n}\n\n/**\n * Keeps the hint flag in step with the session cookie on any response (pages stay static: the proxy runs on every request,\n * the HTML is the same for everyone). Sets it when the session cookie exists, clears it when it is gone, else touches nothing.\n */\nexport function sessionHint<T extends Response>(response: T, request: Request, options: { cookie: string; secure: boolean }): T {\n const session = Boolean(cookieValue(request.headers, options.cookie));\n const flagged = cookieValue(request.headers, SESSION_HINT_COOKIE) === \"1\";\n const base = `${SESSION_HINT_COOKIE}=${session ? \"1\" : \"\"}; Path=/; SameSite=Lax${options.secure ? \"; Secure\" : \"\"}`;\n if (session && !flagged) response.headers.append(\"Set-Cookie\", base);\n else if (!session && cookieValue(request.headers, SESSION_HINT_COOKIE) !== undefined) response.headers.append(\"Set-Cookie\", `${base}; Max-Age=0`);\n return response;\n}\n","import { accountsSchema, rolesSchema } from \"./schema\";\n\nconst IDENT = /^[a-z_][a-z0-9_]{0,62}$/;\nconst ident = (name: string) => {\n if (!IDENT.test(name)) throw new Error(`not a safe SQL identifier: ${name}`);\n return name;\n};\n\n/**\n * The SQL of version 1 of the accounts tables, for a product that runs it by hand (idempotent).\n * @deprecated Use `accountsSchema` with `emitMigration` or `adoptMigration` from `@krizaka/db`: the SQL gets a version, a checksum and a marker. Removed in the next major.\n */\nexport function accountsMigration(options: { backfillVerified?: boolean } = {}): string {\n return accountsSchema(options).migrations[0]!.sql({ schema: \"public\", tables: { accounts: \"accounts\" } });\n}\n\n/**\n * The SQL of version 1 of the memberships and invitations tables, for a product that runs it by hand (idempotent).\n * @deprecated Use `rolesSchema` with `emitMigration` or `adoptMigration` from `@krizaka/db`. Removed in the next major.\n */\nexport function rolesMigration(roles: readonly string[], options: { ownerTable?: string; scopeTable?: string } = {}): string {\n const tables = { owner: ident(options.ownerTable ?? \"accounts\"), ...(options.scopeTable ? { scope: ident(options.scopeTable) } : {}) };\n return rolesSchema(roles, { scoped: options.scopeTable !== undefined }).migrations[0]!.sql({ schema: \"public\", tables });\n}\n","import crypto from \"node:crypto\";\n\n/** Called only when a password is hashed or checked: the module also loads in a browser bundle (the role model), where `crypto.scrypt` does not exist. */\nconst scrypt = (password: string, salt: Buffer, keylen: number, options: crypto.ScryptOptions): Promise<Buffer> =>\n new Promise((resolve, reject) => {\n crypto.scrypt(password, salt, keylen, options, (error, key) => (error ? reject(error) : resolve(key)));\n });\n\n/**\n * scrypt (N=2^15, r=8, p=1), a 16-byte salt, stored as `scrypt$N$r$p$salt$hash` (base64url). These are the parameters of the copies\n * the products carried (Yomizaka, Akinaza, Kachizaka, Yororis): a hash they stored verifies here, and one made here verifies there.\n */\n// @fixed: the cost of the algorithm is part of the stored format; changing it is a new scheme, not a setting\nconst N = 32768;\nconst R = 8;\nconst P = 1;\nconst KEYLEN = 32;\nconst MAXMEM = 64 * 1024 * 1024;\nconst OPTIONS = { N, r: R, p: P, maxmem: MAXMEM };\n\n/** The shortest password the products accept. */\n// @fixed: a security floor shared by every product, not a business parameter\nexport const PASSWORD_MIN_LENGTH = 12;\n/** The longest: a longer one is refused before any work is done (a very long password is a way to make the server spend time). */\n// @fixed: bounds the work a request can make the server do\nexport const PASSWORD_MAX_LENGTH = 256;\n\n/** Why a new password is refused, or null when its length is acceptable. */\nexport function passwordProblem(password: string): \"TOO_SHORT\" | \"TOO_LONG\" | null {\n if (password.length < PASSWORD_MIN_LENGTH) return \"TOO_SHORT\";\n if (password.length > PASSWORD_MAX_LENGTH) return \"TOO_LONG\";\n return null;\n}\n\n/**\n * Hashes a password with a fresh salt.\n * @returns `scrypt$N$r$p$salt$hash`\n */\nexport async function hashPassword(password: string): Promise<string> {\n const salt = crypto.randomBytes(16);\n const hash = await scrypt(password, salt, KEYLEN, OPTIONS);\n return `scrypt$${N}$${R}$${P}$${salt.toString(\"base64url\")}$${hash.toString(\"base64url\")}`;\n}\n\n/**\n * Checks a password against a stored hash, in constant time. A hash of another scheme, a malformed one or an over-long password is `false`.\n * The cost parameters are read from the stored value, so an older hash still verifies after the default changes.\n */\nexport async function verifyPassword(password: string, stored: string): Promise<boolean> {\n const [scheme, n, r, p, salt, hash] = stored.split(\"$\");\n if (scheme !== \"scrypt\" || !salt || !hash || password.length > PASSWORD_MAX_LENGTH) return false;\n const expected = Buffer.from(hash, \"base64url\");\n const given = await scrypt(password, Buffer.from(salt, \"base64url\"), expected.length, { N: Number(n), r: Number(r), p: Number(p), maxmem: MAXMEM });\n return given.length === expected.length && crypto.timingSafeEqual(given, expected);\n}\n\nlet decoy: Promise<string> | undefined;\n/** A hash to verify against when the address has no account: the same work, the same time, the same answer. */\nexport const decoyHash = (): Promise<string> => (decoy ??= hashPassword(crypto.randomBytes(24).toString(\"base64url\")));\n","import crypto from \"node:crypto\";\n\nimport type { Query } from \"@krizaka/db\";\nimport { addHours } from \"date-fns\";\n\nimport { can, type RoleModel,ROLES_CODE, RolesError } from \"./roles-model\";\n\nexport { can, defineRoles, type RoleModel, ROLES_CODE, type RolesCode, RolesError } from \"./roles-model\";\n\n/** The SQL executor the roles take: `@krizaka/db`'s `Query`. */\nexport type RolesQuery = Query;\n\nexport interface RolesDeps<Role extends string, Permission extends string> {\n query: RolesQuery;\n model: RoleModel<Role, Permission>;\n /** The invitation link's token prefix (`ai` → `ai1.<43>`) and how the product keeps a token (its keyed hash). */\n tokenPrefix: string;\n tokenHash: (token: string) => string;\n /** Hours an invitation stays valid. */\n inviteTtlHours: number;\n token?: () => string;\n}\n\nexport interface Member<Role extends string> {\n accountId: string;\n email: string;\n name: string | null;\n role: Role;\n since: Date;\n}\nexport interface Invitation<Role extends string> {\n id: string;\n email: string;\n role: Role;\n expiresAt: Date;\n createdAt: Date;\n}\n\n/** Who may do what in a scope, over the product's PostgreSQL. */\nexport function createRoles<Role extends string, Permission extends string>(deps: RolesDeps<Role, Permission>) {\n const { query, model } = deps;\n const known = (role: string): role is Role => (model.roles as readonly string[]).includes(role);\n const mustKnow = (role: string): Role => {\n if (!known(role)) throw new RolesError(ROLES_CODE.unknownRole);\n return role;\n };\n const newToken = deps.token ?? (() => `${deps.tokenPrefix}1.${crypto.randomBytes(32).toString(\"base64url\")}`);\n const owners = (scopeId: string) => query<{ account_id: string }>(\"SELECT account_id FROM memberships WHERE scope_id = $1 AND role = $2\", [scopeId, ownerRole()]);\n /** The role that cannot disappear: the first of the model that manages every role. */\n const ownerRole = (): Role => model.roles.find((r) => model.roles.every((x) => model.manages[r].includes(x) || x === r)) ?? model.roles[0]!;\n\n async function roleOf(accountId: string, scopeId: string): Promise<Role | null> {\n const [row] = await query<{ role: Role }>(\"SELECT role FROM memberships WHERE scope_id = $1 AND account_id = $2\", [scopeId, accountId]);\n return row?.role ?? null;\n }\n\n return {\n ownerRole,\n roleOf,\n\n /** Every scope the person belongs to, with their role in it. */\n async scopesOf(accountId: string): Promise<{ scopeId: string; role: Role }[]> {\n return (await query<{ scope_id: string; role: Role }>(\"SELECT scope_id, role FROM memberships WHERE account_id = $1 ORDER BY created_at\", [accountId])).map((r) => ({ scopeId: r.scope_id, role: r.role }));\n },\n\n /** The person's role in the scope if it holds the permission; otherwise `NOT_A_MEMBER` (404: nothing tells the scope exists) or `FORBIDDEN`. */\n async authorize(accountId: string, scopeId: string, permission: Permission): Promise<Role> {\n const role = await roleOf(accountId, scopeId);\n if (!role) throw new RolesError(ROLES_CODE.notMember);\n if (!can(model, role, permission)) throw new RolesError(ROLES_CODE.forbidden);\n return role;\n },\n\n /** Puts a person in a scope with a role (changing it if they are there): for a first owner, a seed, an accepted invitation. */\n async grant(scopeId: string, accountId: string, role: string, invitedBy: string | null, now: Date): Promise<void> {\n mustKnow(role);\n await query(\n \"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role\",\n [scopeId, accountId, role, invitedBy, now],\n );\n },\n\n async members(scopeId: string): Promise<Member<Role>[]> {\n const rows = await query<{ account_id: string; email: string; name: string | null; role: Role; created_at: Date }>(\n \"SELECT m.account_id, a.email, a.name, m.role, m.created_at FROM memberships m JOIN accounts a ON a.id = m.account_id WHERE m.scope_id = $1 ORDER BY m.created_at\",\n [scopeId],\n );\n return rows.map((r) => ({ accountId: r.account_id, email: r.email, name: r.name, role: r.role, since: r.created_at }));\n },\n\n /** Changes someone's role. The actor must manage both the current and the new role; the last owner can never be demoted. */\n async setRole(scopeId: string, actor: { id: string }, target: string, role: string): Promise<void> {\n mustKnow(role);\n const mine = await roleOf(actor.id, scopeId);\n const current = await roleOf(target, scopeId);\n if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);\n if (!model.manages[mine].includes(current) || !model.manages[mine].includes(role as Role)) throw new RolesError(ROLES_CODE.notAllowed);\n if (current === ownerRole() && role !== current && (await owners(scopeId)).length <= 1) throw new RolesError(ROLES_CODE.lastOwner);\n await query(\"UPDATE memberships SET role = $3 WHERE scope_id = $1 AND account_id = $2\", [scopeId, target, role]);\n },\n\n /** Removes someone from the scope (or leaves it, when the target is the actor). The last owner cannot go. */\n async remove(scopeId: string, actor: { id: string }, target: string): Promise<void> {\n const mine = await roleOf(actor.id, scopeId);\n const current = await roleOf(target, scopeId);\n if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);\n if (actor.id !== target && !model.manages[mine].includes(current)) throw new RolesError(ROLES_CODE.notAllowed);\n if (current === ownerRole() && (await owners(scopeId)).length <= 1) throw new RolesError(ROLES_CODE.lastOwner);\n await query(\"DELETE FROM memberships WHERE scope_id = $1 AND account_id = $2\", [scopeId, target]);\n },\n\n /** Invites an e-mail address with a role the actor manages. The token is in the answer once (the product mails it); only its hash is kept. A new invitation for the same address replaces the pending one. */\n async invite(scopeId: string, actor: { id: string }, input: { email: string; role: string }, now: Date): Promise<{ token: string; invitation: Invitation<Role> }> {\n const role = mustKnow(input.role);\n const mine = await roleOf(actor.id, scopeId);\n if (!mine) throw new RolesError(ROLES_CODE.notMember);\n if (!model.manages[mine].includes(role)) throw new RolesError(ROLES_CODE.notAllowed);\n const email = input.email.trim().toLowerCase();\n await query(\"UPDATE invitations SET used_at = $3 WHERE scope_id = $1 AND email = $2 AND used_at IS NULL\", [scopeId, email, now]);\n const token = newToken();\n const [row] = await query<{ id: string; created_at: Date; expires_at: Date }>(\n \"INSERT INTO invitations (id, scope_id, email, role, token_hash, invited_by, created_at, expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, created_at, expires_at\",\n [crypto.randomUUID(), scopeId, email, role, deps.tokenHash(token), actor.id, now, addHours(now, deps.inviteTtlHours)],\n );\n return { token, invitation: { id: row!.id, email, role, createdAt: row!.created_at, expiresAt: row!.expires_at } };\n },\n\n async pendingInvitations(scopeId: string, now: Date): Promise<Invitation<Role>[]> {\n const rows = await query<{ id: string; email: string; role: Role; created_at: Date; expires_at: Date }>(\"SELECT id, email, role, created_at, expires_at FROM invitations WHERE scope_id = $1 AND used_at IS NULL AND expires_at > $2 ORDER BY created_at\", [scopeId, now]);\n return rows.map((r) => ({ id: r.id, email: r.email, role: r.role, createdAt: r.created_at, expiresAt: r.expires_at }));\n },\n\n async revokeInvitation(scopeId: string, actor: { id: string }, invitationId: string, now: Date): Promise<void> {\n const mine = await roleOf(actor.id, scopeId);\n if (!mine) throw new RolesError(ROLES_CODE.notMember);\n const [row] = await query<{ role: Role }>(\"SELECT role FROM invitations WHERE id = $1 AND scope_id = $2 AND used_at IS NULL\", [invitationId, scopeId]);\n if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);\n if (!model.manages[mine].includes(row.role)) throw new RolesError(ROLES_CODE.notAllowed);\n await query(\"UPDATE invitations SET used_at = $2 WHERE id = $1\", [invitationId, now]);\n },\n\n /** The signed-in account takes the invitation: it must have been sent to this account's address; the link works once and expires. */\n async acceptInvitation(token: string, account: { id: string; email: string }, now: Date): Promise<{ scopeId: string; role: Role }> {\n const [row] = await query<{ id: string; scope_id: string; email: string; role: Role; invited_by: string | null }>(\n \"SELECT id, scope_id, email, role, invited_by FROM invitations WHERE token_hash = $1 AND used_at IS NULL AND expires_at > $2\",\n [deps.tokenHash(token), now],\n );\n if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);\n if (row.email !== account.email.trim().toLowerCase()) throw new RolesError(ROLES_CODE.inviteWrongAccount);\n await query(\"UPDATE invitations SET used_at = $2 WHERE id = $1\", [row.id, now]);\n const current = await roleOf(account.id, row.scope_id);\n // already in: keep the higher role (an invitation never demotes)\n if (!current || (model.manages[current].length < model.manages[row.role].length)) await query(\"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role\", [row.scope_id, account.id, row.role, row.invited_by, now]);\n return { scopeId: row.scope_id, role: (!current || model.manages[current].length < model.manages[row.role].length ? row.role : current) as Role };\n },\n };\n}\nexport type Roles<Role extends string = string, Permission extends string = string> = ReturnType<typeof createRoles<Role, Permission>>;\n","import crypto from \"node:crypto\";\n\nimport type { Clock } from \"@krizaka/db\";\n\n/**\n * Web sessions (the copies each product carried: Yomizaka `ys1.`, Akinaza `as1.`, Kachizaka `ks1.`). The cookie holds a random token\n * (`<prefix>1.` and 32 bytes); the store keeps only its keyed hash, so a leaked table opens nothing. The account is re-read on every\n * request (a suspension applies at once). The lifetime is the setting `auth.sessionDays`.\n */\n\n/** A live session and the account it signs in. `Account` is the product's own shape (id, e-mail, role, locale, name…). */\nexport interface Session<Account> {\n id: string;\n account: Account;\n}\n\n/** What a store keeps for a new session. */\nexport interface NewSession {\n accountId: string;\n tokenHash: string;\n createdAt: Date;\n expiresAt: Date;\n ip: string | null;\n userAgent: string | null;\n}\n\n/** Where sessions live. Adapters: the PostgreSQL store over the product's `sessions` table, and a memory one. */\nexport interface SessionStore<Account> {\n insert(session: NewSession): Promise<void>;\n /** The session of this hash, when it has not expired at `now` and its account is active; null otherwise. */\n find(tokenHash: string, now: Date): Promise<Session<Account> | null>;\n delete(tokenHash: string): Promise<void>;\n}\n\nexport interface SessionsDeps<Account> {\n store: SessionStore<Account>;\n clock: Clock;\n /** The product's token letters: `ys` makes `ys1.<43 characters>`. Lower-case letters, 1 to 4. */\n tokenPrefix: string;\n /** What keys the stored hash (`AUTH_SESSION_SECRET`). A function lets the product read its environment when it is needed. */\n secret: string | (() => string);\n /** Days a new session lives: the setting `auth.sessionDays`, read for each new session. */\n sessionDays: number | (() => number | Promise<number>);\n}\n\nexport interface Sessions<Account> {\n /** A fresh token: shaped `<prefix>1.<43>`, random, never stored (only its hash is). */\n newToken(): string;\n isToken(value: string | undefined): value is string;\n /** The keyed hash the store keeps for a token. */\n tokenHash(token: string): string;\n /** Opens a session: the token for the cookie (shown once) and when it expires. */\n create(accountId: string, meta: { ip: string | null; userAgent: string | null }): Promise<{ token: string; expires: Date }>;\n /** The session a token opens, or null (unknown, malformed, expired, account not active). */\n resolve(token: string | undefined): Promise<Session<Account> | null>;\n /** Ends the session of this token. A malformed token is ignored. */\n revoke(token: string | undefined): Promise<void>;\n}\n\nconst BODY = /^[A-Za-z0-9_-]{43}$/;\nconst PREFIX = /^[a-z]{1,4}$/;\nconst USER_AGENT_MAX = 300;\n\n/**\n * The sessions service of a product.\n * @param deps the store, the clock, the token letters, the secret and the lifetime\n * @throws RangeError for a token prefix that is not 1 to 4 lower-case letters, or a lifetime that is not a whole number of days from 1\n */\nexport function createSessions<Account>(deps: SessionsDeps<Account>): Sessions<Account> {\n if (!PREFIX.test(deps.tokenPrefix)) throw new RangeError(`tokenPrefix must be 1 to 4 lower-case letters, got ${deps.tokenPrefix}`);\n const head = `${deps.tokenPrefix}1.`;\n const secret = () => (typeof deps.secret === \"function\" ? deps.secret() : deps.secret);\n const isToken = (value: string | undefined): value is string => !!value && value.startsWith(head) && BODY.test(value.slice(head.length));\n const tokenHash = (token: string) => crypto.createHmac(\"sha256\", `session:${secret()}`).update(token).digest(\"hex\");\n const newToken = () => `${head}${crypto.randomBytes(32).toString(\"base64url\")}`;\n return {\n newToken,\n isToken,\n tokenHash,\n async create(accountId, meta) {\n const days = typeof deps.sessionDays === \"function\" ? await deps.sessionDays() : deps.sessionDays;\n if (!Number.isInteger(days) || days < 1) throw new RangeError(`sessionDays must be a whole number of days from 1, got ${days}`);\n const token = newToken();\n const createdAt = deps.clock.now();\n // days of 24 hours, not calendar days: the same instant whatever the server's time zone (the copies added 86 400 000 ms a day)\n const expires = new Date(createdAt);\n expires.setUTCHours(expires.getUTCHours() + days * 24);\n await deps.store.insert({ accountId, tokenHash: tokenHash(token), createdAt, expiresAt: expires, ip: meta.ip, userAgent: meta.userAgent?.slice(0, USER_AGENT_MAX) ?? null });\n return { token, expires };\n },\n async resolve(token) {\n if (!isToken(token)) return null;\n return deps.store.find(tokenHash(token), deps.clock.now());\n },\n async revoke(token) {\n if (!isToken(token)) return;\n await deps.store.delete(tokenHash(token));\n },\n };\n}\n\n/** The attributes of the session cookie, for the product's framework (`cookies().set(cookie)`, `NextResponse.cookies.set`…). */\nexport interface SessionCookie {\n name: string;\n value: string;\n httpOnly: true;\n secure: boolean;\n sameSite: \"lax\";\n path: \"/\";\n expires: Date;\n}\n\n/**\n * The session cookie: HttpOnly, SameSite=Lax, on the whole site, `Secure` where the product says (production).\n * @param options the cookie's name (`yomizaka_session`) and whether it is `Secure`\n */\nexport function sessionCookie(token: string, expires: Date, options: { name: string; secure: boolean }): SessionCookie {\n return { name: options.name, value: token, httpOnly: true, secure: options.secure, sameSite: \"lax\", path: \"/\", expires };\n}\n\n/** The same cookie, expired now: what signing out sets. */\nexport function clearedSessionCookie(options: { name: string; secure: boolean }, now: Date): SessionCookie {\n return sessionCookie(\"\", now, options);\n}\n\n/**\n * The session token of a request: the native apps' `Authorization: Bearer` (which wins over a stale cookie), else the web's cookie.\n * @param headers the request's headers\n * @param options the cookie's name; `bearer: false` for a product with no native app\n * @returns the raw token (not yet checked), or undefined\n */\nexport function sessionTokenOf(headers: Headers, options: { cookie: string; bearer?: boolean }): string | undefined {\n if (options.bearer !== false) {\n const bearer = /^bearer (\\S+)$/i.exec(headers.get(\"authorization\") ?? \"\")?.[1];\n if (bearer) return bearer;\n }\n const prefix = `${options.cookie}=`;\n return headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix))\n ?.slice(prefix.length);\n}\n","import type { NewSession, Session, SessionStore } from \"./sessions\";\n\n/**\n * An in-memory session store, for unit tests and demos. `accountOf` plays the accounts table: it answers the account of an id, or null\n * when it does not exist or is not active.\n */\nexport function memorySessionStore<Account>(accountOf: (accountId: string) => Account | null): SessionStore<Account> & { rows(): readonly NewSession[] } {\n const rows = new Map<string, NewSession & { id: string }>();\n let next = 0;\n return {\n async insert(session) {\n if (rows.has(session.tokenHash)) throw new Error(\"duplicate session token hash\");\n next += 1;\n rows.set(session.tokenHash, { ...session, id: `session-${next}` });\n },\n async find(tokenHash, now): Promise<Session<Account> | null> {\n const row = rows.get(tokenHash);\n if (!row || row.expiresAt.getTime() <= now.getTime()) return null;\n const account = accountOf(row.accountId);\n return account === null ? null : { id: row.id, account };\n },\n async delete(tokenHash) {\n rows.delete(tokenHash);\n },\n rows: () => [...rows.values()],\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { Session, SessionStore } from \"./sessions\";\n\nexport interface DbSessionStoreOptions<Account> {\n /** The product's session table. Default `sessions` (`id`, `account_id`, `token_hash` unique, `created_at`, `expires_at`, `ip`, `user_agent`). */\n sessions?: string;\n /** The product's account table. Default `accounts`. */\n accounts?: string;\n /** The account columns the session carries (`id`, `email`, `role`, `locale`, `name`…): all checked, all read in one query with the session. */\n columns: readonly string[];\n /** Builds the product's account from a row holding exactly `columns`. */\n toAccount: (row: Record<string, unknown>) => Account;\n /** An account that is not active signs nobody in (a suspension applies at once): the column and the value it must have (`status` = `ACTIVE`). */\n active?: { column: string; equals: string };\n}\n\n/**\n * The session store over the product's own tables (`sessions` joined to `accounts`): the declared tables and columns are checked by\n * `ident()` and nothing else reaches SQL. The expiry is compared with the clock's `now`, not the database's.\n * @param query the product's query\n * @param options the table names, the account columns and how the account is built\n * @throws DbError `DB_UNSAFE_IDENTIFIER` for a table or column name that is not a safe identifier\n */\nexport function dbSessionStore<Account>(query: Query, options: DbSessionStoreOptions<Account>): SessionStore<Account> {\n const sessions = ident(options.sessions ?? \"sessions\");\n const accounts = ident(options.accounts ?? \"accounts\");\n const columns = options.columns.map((column) => `a.${ident(column)}`).join(\", \");\n const active = options.active ? ` AND a.${ident(options.active.column)} = $3` : \"\";\n return {\n async insert(session) {\n await query(`INSERT INTO ${sessions} (account_id, token_hash, created_at, expires_at, ip, user_agent) VALUES ($1, $2, $3, $4, $5, $6)`, [session.accountId, session.tokenHash, session.createdAt, session.expiresAt, session.ip, session.userAgent]);\n },\n async find(tokenHash, now): Promise<Session<Account> | null> {\n const params: unknown[] = [tokenHash, now];\n if (options.active) params.push(options.active.equals);\n const [row] = await query<Record<string, unknown> & { session_id: string }>(\n `SELECT s.id AS session_id, ${columns} FROM ${sessions} s JOIN ${accounts} a ON a.id = s.account_id WHERE s.token_hash = $1 AND s.expires_at > $2${active}`,\n params,\n );\n if (!row) return null;\n const { session_id: id, ...account } = row;\n return { id, account: options.toAccount(account) };\n },\n async delete(tokenHash) {\n await query(`DELETE FROM ${sessions} WHERE token_hash = $1`, [tokenHash]);\n },\n };\n}\n","import { type CompleteOptions, type ExternalIdentity, type FederatedProvider, FEDERATION_CODE, FederationError, type IdentityProvider, isFederatedProvider, isLocalReturn, type StartedSignIn, type StartOptions } from \"./federation\";\n\n/** The `fetch` the adapter calls krizaka-users with (injected: no global, no network in tests). */\nexport type Fetcher = (url: string, init: { method: \"POST\"; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;\n\nexport interface UsersFederationOptions {\n /** The tenant host of the product: `https://auth.dev.akinaza.com`. */\n baseUrl: string;\n /** The product's public address: the start URL sends the person back to it, so `returnTo` is absolute from it. */\n appUrl: string;\n fetch: Fetcher;\n}\n\nconst START = (base: string, provider: FederatedProvider) => `${base}/api/v1/auth/web/${provider}/start`;\nconst EXCHANGE = (base: string) => `${base}/api/v1/auth/web/exchange`;\n\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Reads krizaka-users' answer into an identity; anything that is not a complete identity is refused. */\nexport function parseExternalIdentity(body: unknown): ExternalIdentity {\n const o = (body ?? {}) as Record<string, unknown>;\n const issuer = text(o.issuer);\n const subject = text(o.subject);\n if (!issuer || !subject) throw new FederationError(FEDERATION_CODE.unavailable, \"krizaka-users answered without an issuer and a subject\");\n return { issuer, subject, email: text(o.email), emailVerified: o.email_verified === true, name: text(o.name) };\n}\n\n/**\n * The adapter for krizaka-users (`auth.<product>` tenant host, krizaka/krizaka-users#31): `start` builds the tenant's start address,\n * `complete` exchanges the one-time code (and the PKCE verifier of a native app) for the verified identity.\n */\nexport function usersIdentityProvider({ baseUrl, appUrl, fetch }: UsersFederationOptions): IdentityProvider {\n const base = baseUrl.replace(/\\/+$/, \"\");\n const app = appUrl.replace(/\\/+$/, \"\");\n return {\n async start(provider, returnTo, options: StartOptions = {}): Promise<StartedSignIn> {\n if (!isFederatedProvider(provider)) throw new FederationError(FEDERATION_CODE.unknownProvider, `Unknown provider ${String(provider)}`);\n if (!isLocalReturn(returnTo)) throw new FederationError(FEDERATION_CODE.badReturn, \"That return address is not allowed\");\n const state = crypto.randomUUID();\n const query = new URLSearchParams({ return_to: `${app}${returnTo}`, state });\n if (options.codeChallenge) {\n query.set(\"code_challenge\", options.codeChallenge);\n query.set(\"code_challenge_method\", \"S256\");\n }\n return { url: `${START(base, provider)}?${query}`, state };\n },\n async complete(code, options: CompleteOptions = {}) {\n const response = await fetch(EXCHANGE(base), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ code, ...(options.codeVerifier ? { code_verifier: options.codeVerifier } : {}) }),\n });\n if (response.status === 400 || response.status === 401 || response.status === 404 || response.status === 410) throw new FederationError(FEDERATION_CODE.invalidCode, \"That code is not valid\");\n if (!response.ok) throw new FederationError(FEDERATION_CODE.unavailable, `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to","crypto","crypto","ident"]}
|
|
1
|
+
{"version":3,"sources":["../src/admin-gate.ts","../src/client-ip.ts","../src/federated-sign-in.ts","../src/landing.ts","../src/migration.ts","../src/password.ts","../src/roles.ts","../src/sessions.ts","../src/sessions-memory.ts","../src/sessions-persistence.ts","../src/users-federation.ts"],"sourcesContent":["/**\n * The administration's locks, as one pure decision every product shares (it was copied in each product's `lib/access.ts`): a session,\n * the ADMIN role, and an address on the allowed list. A pure function of its inputs: the product reads the session and the address\n * and maps the verdict to its own answer.\n */\n\n/** Stable codes of a refusal. */\nexport const ADMIN_REFUSAL = {\n unauthenticated: \"UNAUTHENTICATED\",\n forbidden: \"FORBIDDEN\",\n ipNotAllowed: \"IP_NOT_ALLOWED\",\n notFound: \"NOT_FOUND\",\n} as const;\nexport type AdminRefusal = (typeof ADMIN_REFUSAL)[keyof typeof ADMIN_REFUSAL];\n\n/** The verdict: let in, or the status and code to answer. */\nexport type AdminDecision = { ok: true } | { ok: false; status: 401 | 403 | 404; code: AdminRefusal };\n\n/**\n * The list the administration's address lock reads, from the environment's value (`AUTH_ALLOWED_IPS`): an empty list is « nobody » in\n * production and « anybody » in development, so a forgotten setting never opens the console.\n * @param list the configured addresses\n * @returns the list to hand to `requireAdmin`, or null (anybody)\n */\nexport function allowedIps(list: readonly string[], options: { production: boolean }): readonly string[] | null {\n if (list.length > 0) return list;\n return options.production ? [] : null;\n}\n\n/** Whether an address may use the administration: `null` allowed means anybody, an empty list nobody, and a missing address is never allowed by a list. */\nexport function ipAllowed(ip: string | null, allowed: readonly string[] | null): boolean {\n if (allowed === null) return true;\n return !!ip && allowed.includes(ip);\n}\n\nexport interface AdminGateInput {\n /** The caller's session, or null when there is none. Only its account's role is read. */\n session: { account: { role: string } } | null;\n /** The caller's address (see `clientIp`). */\n ip: string | null;\n /** The addresses allowed (see `allowedIps`); null = anybody. */\n allowedIps: readonly string[] | null;\n /** `api` (default): 401 without a session, 403 with the reason. `page`: the administration does not announce itself, so every failed lock is a 404. */\n surface?: \"api\" | \"page\";\n /** The role that administers. Default `ADMIN`. */\n role?: string;\n}\n\n/**\n * The administration's three locks. The first that fails decides.\n * @returns `{ ok: true }`, or the status (401, 403 or 404 on a page) and the code to answer\n */\nexport function requireAdmin(input: AdminGateInput): AdminDecision {\n const page = input.surface === \"page\";\n const refuse = (status: 401 | 403, code: AdminRefusal): AdminDecision =>\n page ? { ok: false, status: 404, code: ADMIN_REFUSAL.notFound } : { ok: false, status, code };\n if (!input.session) return refuse(401, ADMIN_REFUSAL.unauthenticated);\n if (input.session.account.role !== (input.role ?? \"ADMIN\")) return refuse(403, ADMIN_REFUSAL.forbidden);\n if (!ipAllowed(input.ip, input.allowedIps)) return refuse(403, ADMIN_REFUSAL.ipNotAllowed);\n return { ok: true };\n}\n","/** How a deployment tells the client's address: the header its edge sets, and how many proxies append to `X-Forwarded-For`. */\nexport interface ClientIpRules {\n /** A header the edge sets and overwrites with the client's address (`do-connecting-ip` on DigitalOcean App Platform, `cf-connecting-ip` behind Cloudflare). Read first when present. */\n header?: string | undefined;\n /** How many trusted proxies append to `X-Forwarded-For`: 1 (the default) to 10. */\n trustedProxyHops?: number | undefined;\n}\n\nconst IPV4 = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\nconst IPV6 = /^[0-9a-f:]+(?:%\\w+)?$/i;\nfunction isIp(value: string): boolean {\n return (\n (IPV4.test(value) && value.split(\".\").every((n) => Number(n) <= 255)) || (value.includes(\":\") && IPV6.test(value))\n );\n}\n\n/**\n * The client's IP address, as far as this deployment can trust it. `X-Forwarded-For` is a list each proxy appends to: its LEFT end is\n * whatever the client sent (anyone can write `X-Forwarded-For: 1.2.3.4`), so a limit keyed on it is a limit the attacker chooses. The\n * address the last trusted proxy saw is read from the RIGHT:\n *\n * - the `header` the edge sets and overwrites, when present;\n * - otherwise the entry `trustedProxyHops` (default 1: one proxy) from the right of `X-Forwarded-For`, then `X-Real-IP`;\n * - otherwise null (local development without a proxy).\n *\n * The product reads its environment (`ABUSE_CLIENT_IP_HEADER`, `ABUSE_TRUSTED_PROXY_HOPS`) and passes the values: this function reads none.\n * @param headers the request's headers\n * @returns a valid IPv4 or IPv6 address, or null\n */\nexport function clientIp(headers: Headers, rules: ClientIpRules = {}): string | null {\n const custom = rules.header?.trim().toLowerCase();\n if (custom) {\n const value = headers.get(custom)?.split(\",\")[0]?.trim();\n if (value && isIp(value)) return value;\n }\n const hops = Math.max(1, Math.min(10, Number(rules.trustedProxyHops) || 1));\n const chain = (headers.get(\"x-forwarded-for\") ?? \"\")\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean);\n const fromRight = chain[chain.length - hops];\n if (fromRight && isIp(fromRight)) return fromRight;\n const real = headers.get(\"x-real-ip\")?.trim();\n if (real && isIp(real)) return real;\n return null;\n}\n","import type { ExternalIdentity } from \"./federation\";\nimport type { IdentityLinkStore } from \"./identity-links\";\n\n/** What federated sign-in needs from the product's accounts: no second user table, just a look-up and, when registration is open, a creation. */\nexport interface FederatedAccounts {\n /** The account that holds this address (lower case), and whether the product has verified it; null when none. */\n findByEmail(email: string): Promise<{ id: string; emailVerified: boolean } | null>;\n /** Creates an account for a person the provider vouches for (address verified, no password). Absent when registration is closed. */\n create?(identity: ExternalIdentity & { email: string }): Promise<string>;\n}\n\n/** Why a sign-in was refused: a stable code the product maps to its words. */\nexport const FEDERATED_REFUSAL = {\n /** The provider did not verify the address (or gave none): nothing is linked, nothing is created. */\n emailNotVerified: \"EMAIL_NOT_VERIFIED\",\n /** An account holds the address but the product never verified it: linking would let a stranger take it over. */\n accountEmailUnverified: \"ACCOUNT_EMAIL_UNVERIFIED\",\n /** No account, and registration is closed. */\n noAccount: \"NO_ACCOUNT\",\n} as const;\nexport type FederatedRefusal = (typeof FEDERATED_REFUSAL)[keyof typeof FEDERATED_REFUSAL];\n\nexport type FederatedSignInResult =\n /** `via`: `link` already linked, `linked` attached to the account of that address now, `created` a new account. */\n | { status: \"signed-in\"; accountId: string; via: \"link\" | \"linked\" | \"created\" }\n | { status: \"refused\"; code: FederatedRefusal };\n\nexport interface FederatedSignInDeps {\n links: IdentityLinkStore;\n accounts: FederatedAccounts;\n clock: { now(): Date };\n}\n\n/**\n * From a verified external identity to an account of the product. The rule that matters: an identity attaches to an EXISTING account\n * only when the address is verified on both sides — by the provider and by the product. Otherwise a stranger who registers at\n * Facebook with your address would sign in as you.\n */\nexport function createFederatedSignIn({ links, accounts, clock }: FederatedSignInDeps) {\n return {\n async signIn(identity: ExternalIdentity): Promise<FederatedSignInResult> {\n const known = await links.find(identity.issuer, identity.subject);\n if (known) return { status: \"signed-in\", accountId: known, via: \"link\" };\n\n const email = identity.email?.trim().toLowerCase();\n if (!email || !identity.emailVerified) return { status: \"refused\", code: FEDERATED_REFUSAL.emailNotVerified };\n\n const existing = await accounts.findByEmail(email);\n if (existing) {\n if (!existing.emailVerified) return { status: \"refused\", code: FEDERATED_REFUSAL.accountEmailUnverified };\n await links.link(existing.id, identity.issuer, identity.subject, clock.now());\n return { status: \"signed-in\", accountId: existing.id, via: \"linked\" };\n }\n\n if (!accounts.create) return { status: \"refused\", code: FEDERATED_REFUSAL.noAccount };\n const accountId = await accounts.create({ ...identity, email });\n await links.link(accountId, identity.issuer, identity.subject, clock.now());\n return { status: \"signed-in\", accountId, via: \"created\" };\n },\n };\n}\n\nexport type FederatedSignIn = ReturnType<typeof createFederatedSignIn>;\n","// The two proxy-side rules of « a signed-in person never sees the public side » (krizaka-ui#827), the same for every\n// product. Web-standard Request/Response only (a Next.js `proxy.ts` calls them). The cookie is a HINT: its presence\n// decides a redirect and a placeholder, never an authorization — the page and the API still resolve the session.\n\n/** The readable flag the proxy keeps next to the HttpOnly session cookie: « a session cookie exists », value `1`, never the token. */\nexport const SESSION_HINT_COOKIE = \"kz-session\";\n\nconst cookieValue = (headers: Headers, name: string): string | undefined => {\n const prefix = `${name}=`;\n return headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix))\n ?.slice(prefix.length);\n};\n\n/** Where a signed-in visitor of the landing route goes. */\nexport interface LandingRule {\n /** The product's session cookie name (`yomizaka_session`). */\n cookie: string;\n /** The landing routes (`[\"/\", \"/fr\", \"/en\"]`): exact paths, a trailing slash tolerated. */\n landing: readonly string[];\n /** The signed-in start page, or a function of the request (the language of the address). */\n home: string | ((request: Request) => string);\n /**\n * The product's own public origin (`https://dev.yomizaka.com`), from its declared environment (APP_URL), NEVER from the\n * request: `Host` and `x-forwarded-*` are client-controlled. With it the Location is absolute on that origin (what a\n * Next.js proxy accepts). Only the origin of the value is used. Optional outside production (the Location is then\n * relative); REQUIRED in production, where a missing origin throws instead of falling back to the request's headers.\n */\n origin?: string;\n}\n\n// Linear on any input (a loop, not a `/\\/+$/` regular expression: CodeQL js/polynomial-redos on the request path).\nconst trimmed = (path: string) => {\n let end = path.length;\n while (end > 1 && path.charCodeAt(end - 1) === 47) end--;\n return path.slice(0, end);\n};\n\n/**\n * The landing route with a session cookie answers 307 to the home before any HTML: private, never stored, varying with the\n * cookie. `null` for everything else (a signed-out visitor, another page, a write).\n */\nexport function landingRedirect(request: Request, rule: LandingRule): Response | null {\n // Fail loudly at the first request of a misconfigured deployment, signed in or not: never a silent fallback.\n if (!rule.origin && globalThis.process?.env?.NODE_ENV === \"production\") {\n throw new Error(\"landingRedirect: `origin` (the app's declared public URL) is required in production\");\n }\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return null;\n if (!cookieValue(request.headers, rule.cookie)) return null;\n const url = new URL(request.url);\n if (!rule.landing.some((path) => trimmed(path) === trimmed(url.pathname))) return null;\n const home = typeof rule.home === \"function\" ? rule.home(request) : rule.home;\n // Never built from the request's Host or scheme (client-controlled: host-header injection, open redirect). Relative by\n // default; absolute only on the origin the app configured, and a `home` that leaves that origin falls back to relative.\n const target = new URL(home, url);\n const path = `${target.pathname}${target.search}${target.hash}`;\n const base = rule.origin ? new URL(rule.origin).origin : null;\n const location = base && new URL(home, base).origin === base ? new URL(home, base).href : path;\n return new Response(null, {\n status: 307,\n headers: { Location: location, \"Cache-Control\": \"private, no-store\", Vary: \"Cookie\" },\n });\n}\n\n/**\n * Keeps the hint flag in step with the session cookie on any response (pages stay static: the proxy runs on every request,\n * the HTML is the same for everyone). Sets it when the session cookie exists, clears it when it is gone, else touches nothing.\n */\nexport function sessionHint<T extends Response>(\n response: T,\n request: Request,\n options: { cookie: string; secure: boolean },\n): T {\n const session = Boolean(cookieValue(request.headers, options.cookie));\n const flagged = cookieValue(request.headers, SESSION_HINT_COOKIE) === \"1\";\n const base = `${SESSION_HINT_COOKIE}=${session ? \"1\" : \"\"}; Path=/; SameSite=Lax${options.secure ? \"; Secure\" : \"\"}`;\n if (session && !flagged) response.headers.append(\"Set-Cookie\", base);\n else if (!session && cookieValue(request.headers, SESSION_HINT_COOKIE) !== undefined)\n response.headers.append(\"Set-Cookie\", `${base}; Max-Age=0`);\n return response;\n}\n","import { accountsSchema, rolesSchema } from \"./schema\";\n\nconst IDENT = /^[a-z_][a-z0-9_]{0,62}$/;\nconst ident = (name: string) => {\n if (!IDENT.test(name)) throw new Error(`not a safe SQL identifier: ${name}`);\n return name;\n};\n\n/**\n * The SQL of version 1 of the accounts tables, for a product that runs it by hand (idempotent).\n * @deprecated Use `accountsSchema` with `emitMigration` or `adoptMigration` from `@krizaka/db`: the SQL gets a version, a checksum and a marker. Removed in the next major.\n */\nexport function accountsMigration(options: { backfillVerified?: boolean } = {}): string {\n return accountsSchema(options).migrations[0]!.sql({ schema: \"public\", tables: { accounts: \"accounts\" } });\n}\n\n/**\n * The SQL of version 1 of the memberships and invitations tables, for a product that runs it by hand (idempotent).\n * @deprecated Use `rolesSchema` with `emitMigration` or `adoptMigration` from `@krizaka/db`. Removed in the next major.\n */\nexport function rolesMigration(\n roles: readonly string[],\n options: { ownerTable?: string; scopeTable?: string } = {},\n): string {\n const tables = {\n owner: ident(options.ownerTable ?? \"accounts\"),\n ...(options.scopeTable ? { scope: ident(options.scopeTable) } : {}),\n };\n return rolesSchema(roles, { scoped: options.scopeTable !== undefined }).migrations[0]!.sql({\n schema: \"public\",\n tables,\n });\n}\n","import crypto from \"node:crypto\";\n\n/** Called only when a password is hashed or checked: the module also loads in a browser bundle (the role model), where `crypto.scrypt` does not exist. */\nconst scrypt = (password: string, salt: Buffer, keylen: number, options: crypto.ScryptOptions): Promise<Buffer> =>\n new Promise((resolve, reject) => {\n crypto.scrypt(password, salt, keylen, options, (error, key) => (error ? reject(error) : resolve(key)));\n });\n\n/**\n * scrypt (N=2^15, r=8, p=1), a 16-byte salt, stored as `scrypt$N$r$p$salt$hash` (base64url). These are the parameters of the copies\n * the products carried (Yomizaka, Akinaza): a hash they stored verifies here, and one made here verifies there.\n */\n// @fixed: the cost of the algorithm is part of the stored format; changing it is a new scheme, not a setting\nconst N = 32768;\nconst R = 8;\nconst P = 1;\nconst KEYLEN = 32;\nconst MAXMEM = 64 * 1024 * 1024;\nconst OPTIONS = { N, r: R, p: P, maxmem: MAXMEM };\n\n/** The shortest password the products accept. */\n// @fixed: a security floor shared by every product, not a business parameter\nexport const PASSWORD_MIN_LENGTH = 12;\n/** The longest: a longer one is refused before any work is done (a very long password is a way to make the server spend time). */\n// @fixed: bounds the work a request can make the server do\nexport const PASSWORD_MAX_LENGTH = 256;\n\n/** Why a new password is refused, or null when its length is acceptable. */\nexport function passwordProblem(password: string): \"TOO_SHORT\" | \"TOO_LONG\" | null {\n if (password.length < PASSWORD_MIN_LENGTH) return \"TOO_SHORT\";\n if (password.length > PASSWORD_MAX_LENGTH) return \"TOO_LONG\";\n return null;\n}\n\n/**\n * Hashes a password with a fresh salt.\n * @returns `scrypt$N$r$p$salt$hash`\n */\nexport async function hashPassword(password: string): Promise<string> {\n const salt = crypto.randomBytes(16);\n const hash = await scrypt(password, salt, KEYLEN, OPTIONS);\n return `scrypt$${N}$${R}$${P}$${salt.toString(\"base64url\")}$${hash.toString(\"base64url\")}`;\n}\n\n/**\n * Checks a password against a stored hash, in constant time. A hash of another scheme, a malformed one or an over-long password is `false`.\n * The cost parameters are read from the stored value, so an older hash still verifies after the default changes.\n */\nexport async function verifyPassword(password: string, stored: string): Promise<boolean> {\n const [scheme, n, r, p, salt, hash] = stored.split(\"$\");\n if (scheme !== \"scrypt\" || !salt || !hash || password.length > PASSWORD_MAX_LENGTH) return false;\n const expected = Buffer.from(hash, \"base64url\");\n const given = await scrypt(password, Buffer.from(salt, \"base64url\"), expected.length, {\n N: Number(n),\n r: Number(r),\n p: Number(p),\n maxmem: MAXMEM,\n });\n return given.length === expected.length && crypto.timingSafeEqual(given, expected);\n}\n\nlet decoy: Promise<string> | undefined;\n/** A hash to verify against when the address has no account: the same work, the same time, the same answer. */\nexport const decoyHash = (): Promise<string> => (decoy ??= hashPassword(crypto.randomBytes(24).toString(\"base64url\")));\n","import crypto from \"node:crypto\";\n\nimport type { Query } from \"@krizaka/db\";\nimport { addHours } from \"date-fns\";\n\nimport { can, type RoleModel, ROLES_CODE, RolesError } from \"./roles-model\";\n\nexport { can, defineRoles, type RoleModel, ROLES_CODE, type RolesCode, RolesError } from \"./roles-model\";\n\n/** The SQL executor the roles take: `@krizaka/db`'s `Query`. */\nexport type RolesQuery = Query;\n\nexport interface RolesDeps<Role extends string, Permission extends string> {\n query: RolesQuery;\n model: RoleModel<Role, Permission>;\n /** The invitation link's token prefix (`ai` → `ai1.<43>`) and how the product keeps a token (its keyed hash). */\n tokenPrefix: string;\n tokenHash: (token: string) => string;\n /** Hours an invitation stays valid. */\n inviteTtlHours: number;\n token?: () => string;\n}\n\nexport interface Member<Role extends string> {\n accountId: string;\n email: string;\n name: string | null;\n role: Role;\n since: Date;\n}\nexport interface Invitation<Role extends string> {\n id: string;\n email: string;\n role: Role;\n expiresAt: Date;\n createdAt: Date;\n}\n\n/** Who may do what in a scope, over the product's PostgreSQL. */\nexport function createRoles<Role extends string, Permission extends string>(deps: RolesDeps<Role, Permission>) {\n const { query, model } = deps;\n const known = (role: string): role is Role => (model.roles as readonly string[]).includes(role);\n const mustKnow = (role: string): Role => {\n if (!known(role)) throw new RolesError(ROLES_CODE.unknownRole);\n return role;\n };\n const newToken = deps.token ?? (() => `${deps.tokenPrefix}1.${crypto.randomBytes(32).toString(\"base64url\")}`);\n const owners = (scopeId: string) =>\n query<{ account_id: string }>(\"SELECT account_id FROM memberships WHERE scope_id = $1 AND role = $2\", [\n scopeId,\n ownerRole(),\n ]);\n /** The role that cannot disappear: the first of the model that manages every role. */\n const ownerRole = (): Role =>\n model.roles.find((r) => model.roles.every((x) => model.manages[r].includes(x) || x === r)) ?? model.roles[0]!;\n\n async function roleOf(accountId: string, scopeId: string): Promise<Role | null> {\n const [row] = await query<{ role: Role }>(\"SELECT role FROM memberships WHERE scope_id = $1 AND account_id = $2\", [\n scopeId,\n accountId,\n ]);\n return row?.role ?? null;\n }\n\n return {\n ownerRole,\n roleOf,\n\n /** Every scope the person belongs to, with their role in it. */\n async scopesOf(accountId: string): Promise<{ scopeId: string; role: Role }[]> {\n return (\n await query<{ scope_id: string; role: Role }>(\n \"SELECT scope_id, role FROM memberships WHERE account_id = $1 ORDER BY created_at\",\n [accountId],\n )\n ).map((r) => ({ scopeId: r.scope_id, role: r.role }));\n },\n\n /** The person's role in the scope if it holds the permission; otherwise `NOT_A_MEMBER` (404: nothing tells the scope exists) or `FORBIDDEN`. */\n async authorize(accountId: string, scopeId: string, permission: Permission): Promise<Role> {\n const role = await roleOf(accountId, scopeId);\n if (!role) throw new RolesError(ROLES_CODE.notMember);\n if (!can(model, role, permission)) throw new RolesError(ROLES_CODE.forbidden);\n return role;\n },\n\n /** Puts a person in a scope with a role (changing it if they are there): for a first owner, a seed, an accepted invitation. */\n async grant(scopeId: string, accountId: string, role: string, invitedBy: string | null, now: Date): Promise<void> {\n mustKnow(role);\n await query(\n \"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role\",\n [scopeId, accountId, role, invitedBy, now],\n );\n },\n\n async members(scopeId: string): Promise<Member<Role>[]> {\n const rows = await query<{\n account_id: string;\n email: string;\n name: string | null;\n role: Role;\n created_at: Date;\n }>(\n \"SELECT m.account_id, a.email, a.name, m.role, m.created_at FROM memberships m JOIN accounts a ON a.id = m.account_id WHERE m.scope_id = $1 ORDER BY m.created_at\",\n [scopeId],\n );\n return rows.map((r) => ({\n accountId: r.account_id,\n email: r.email,\n name: r.name,\n role: r.role,\n since: r.created_at,\n }));\n },\n\n /** Changes someone's role. The actor must manage both the current and the new role; the last owner can never be demoted. */\n async setRole(scopeId: string, actor: { id: string }, target: string, role: string): Promise<void> {\n mustKnow(role);\n const mine = await roleOf(actor.id, scopeId);\n const current = await roleOf(target, scopeId);\n if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);\n if (!model.manages[mine].includes(current) || !model.manages[mine].includes(role as Role))\n throw new RolesError(ROLES_CODE.notAllowed);\n if (current === ownerRole() && role !== current && (await owners(scopeId)).length <= 1)\n throw new RolesError(ROLES_CODE.lastOwner);\n await query(\"UPDATE memberships SET role = $3 WHERE scope_id = $1 AND account_id = $2\", [scopeId, target, role]);\n },\n\n /** Removes someone from the scope (or leaves it, when the target is the actor). The last owner cannot go. */\n async remove(scopeId: string, actor: { id: string }, target: string): Promise<void> {\n const mine = await roleOf(actor.id, scopeId);\n const current = await roleOf(target, scopeId);\n if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);\n if (actor.id !== target && !model.manages[mine].includes(current)) throw new RolesError(ROLES_CODE.notAllowed);\n if (current === ownerRole() && (await owners(scopeId)).length <= 1) throw new RolesError(ROLES_CODE.lastOwner);\n await query(\"DELETE FROM memberships WHERE scope_id = $1 AND account_id = $2\", [scopeId, target]);\n },\n\n /** Invites an e-mail address with a role the actor manages. The token is in the answer once (the product mails it); only its hash is kept. A new invitation for the same address replaces the pending one. */\n async invite(\n scopeId: string,\n actor: { id: string },\n input: { email: string; role: string },\n now: Date,\n ): Promise<{ token: string; invitation: Invitation<Role> }> {\n const role = mustKnow(input.role);\n const mine = await roleOf(actor.id, scopeId);\n if (!mine) throw new RolesError(ROLES_CODE.notMember);\n if (!model.manages[mine].includes(role)) throw new RolesError(ROLES_CODE.notAllowed);\n const email = input.email.trim().toLowerCase();\n await query(\"UPDATE invitations SET used_at = $3 WHERE scope_id = $1 AND email = $2 AND used_at IS NULL\", [\n scopeId,\n email,\n now,\n ]);\n const token = newToken();\n const [row] = await query<{ id: string; created_at: Date; expires_at: Date }>(\n \"INSERT INTO invitations (id, scope_id, email, role, token_hash, invited_by, created_at, expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, created_at, expires_at\",\n [\n crypto.randomUUID(),\n scopeId,\n email,\n role,\n deps.tokenHash(token),\n actor.id,\n now,\n addHours(now, deps.inviteTtlHours),\n ],\n );\n return {\n token,\n invitation: { id: row!.id, email, role, createdAt: row!.created_at, expiresAt: row!.expires_at },\n };\n },\n\n async pendingInvitations(scopeId: string, now: Date): Promise<Invitation<Role>[]> {\n const rows = await query<{ id: string; email: string; role: Role; created_at: Date; expires_at: Date }>(\n \"SELECT id, email, role, created_at, expires_at FROM invitations WHERE scope_id = $1 AND used_at IS NULL AND expires_at > $2 ORDER BY created_at\",\n [scopeId, now],\n );\n return rows.map((r) => ({\n id: r.id,\n email: r.email,\n role: r.role,\n createdAt: r.created_at,\n expiresAt: r.expires_at,\n }));\n },\n\n async revokeInvitation(scopeId: string, actor: { id: string }, invitationId: string, now: Date): Promise<void> {\n const mine = await roleOf(actor.id, scopeId);\n if (!mine) throw new RolesError(ROLES_CODE.notMember);\n const [row] = await query<{ role: Role }>(\n \"SELECT role FROM invitations WHERE id = $1 AND scope_id = $2 AND used_at IS NULL\",\n [invitationId, scopeId],\n );\n if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);\n if (!model.manages[mine].includes(row.role)) throw new RolesError(ROLES_CODE.notAllowed);\n await query(\"UPDATE invitations SET used_at = $2 WHERE id = $1\", [invitationId, now]);\n },\n\n /** The signed-in account takes the invitation: it must have been sent to this account's address; the link works once and expires. */\n async acceptInvitation(\n token: string,\n account: { id: string; email: string },\n now: Date,\n ): Promise<{ scopeId: string; role: Role }> {\n const [row] = await query<{ id: string; scope_id: string; email: string; role: Role; invited_by: string | null }>(\n \"SELECT id, scope_id, email, role, invited_by FROM invitations WHERE token_hash = $1 AND used_at IS NULL AND expires_at > $2\",\n [deps.tokenHash(token), now],\n );\n if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);\n if (row.email !== account.email.trim().toLowerCase()) throw new RolesError(ROLES_CODE.inviteWrongAccount);\n await query(\"UPDATE invitations SET used_at = $2 WHERE id = $1\", [row.id, now]);\n const current = await roleOf(account.id, row.scope_id);\n // already in: keep the higher role (an invitation never demotes)\n if (!current || model.manages[current].length < model.manages[row.role].length)\n await query(\n \"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role\",\n [row.scope_id, account.id, row.role, row.invited_by, now],\n );\n return {\n scopeId: row.scope_id,\n role: (!current || model.manages[current].length < model.manages[row.role].length ? row.role : current) as Role,\n };\n },\n };\n}\nexport type Roles<Role extends string = string, Permission extends string = string> = ReturnType<\n typeof createRoles<Role, Permission>\n>;\n","import crypto from \"node:crypto\";\n\nimport type { Clock } from \"@krizaka/db\";\n\n/**\n * Web sessions (the copies each product carried: Yomizaka `ys1.`, Akinaza `as1.`). The cookie holds a random token\n * (`<prefix>1.` and 32 bytes); the store keeps only its keyed hash, so a leaked table opens nothing. The account is re-read on every\n * request (a suspension applies at once). The lifetime is the setting `auth.sessionDays`.\n */\n\n/** A live session and the account it signs in. `Account` is the product's own shape (id, e-mail, role, locale, name…). */\nexport interface Session<Account> {\n id: string;\n account: Account;\n}\n\n/** What a store keeps for a new session. */\nexport interface NewSession {\n accountId: string;\n tokenHash: string;\n createdAt: Date;\n expiresAt: Date;\n ip: string | null;\n userAgent: string | null;\n}\n\n/** Where sessions live. Adapters: the PostgreSQL store over the product's `sessions` table, and a memory one. */\nexport interface SessionStore<Account> {\n insert(session: NewSession): Promise<void>;\n /** The session of this hash, when it has not expired at `now` and its account is active; null otherwise. */\n find(tokenHash: string, now: Date): Promise<Session<Account> | null>;\n delete(tokenHash: string): Promise<void>;\n}\n\nexport interface SessionsDeps<Account> {\n store: SessionStore<Account>;\n clock: Clock;\n /** The product's token letters: `ys` makes `ys1.<43 characters>`. Lower-case letters, 1 to 4. */\n tokenPrefix: string;\n /** What keys the stored hash (`AUTH_SESSION_SECRET`). A function lets the product read its environment when it is needed. */\n secret: string | (() => string);\n /** Days a new session lives: the setting `auth.sessionDays`, read for each new session. */\n sessionDays: number | (() => number | Promise<number>);\n}\n\nexport interface Sessions<Account> {\n /** A fresh token: shaped `<prefix>1.<43>`, random, never stored (only its hash is). */\n newToken(): string;\n isToken(value: string | undefined): value is string;\n /** The keyed hash the store keeps for a token. */\n tokenHash(token: string): string;\n /** Opens a session: the token for the cookie (shown once) and when it expires. */\n create(\n accountId: string,\n meta: { ip: string | null; userAgent: string | null },\n ): Promise<{ token: string; expires: Date }>;\n /** The session a token opens, or null (unknown, malformed, expired, account not active). */\n resolve(token: string | undefined): Promise<Session<Account> | null>;\n /** Ends the session of this token. A malformed token is ignored. */\n revoke(token: string | undefined): Promise<void>;\n}\n\nconst BODY = /^[A-Za-z0-9_-]{43}$/;\nconst PREFIX = /^[a-z]{1,4}$/;\nconst USER_AGENT_MAX = 300;\n\n/**\n * The sessions service of a product.\n * @param deps the store, the clock, the token letters, the secret and the lifetime\n * @throws RangeError for a token prefix that is not 1 to 4 lower-case letters, or a lifetime that is not a whole number of days from 1\n */\nexport function createSessions<Account>(deps: SessionsDeps<Account>): Sessions<Account> {\n if (!PREFIX.test(deps.tokenPrefix))\n throw new RangeError(`tokenPrefix must be 1 to 4 lower-case letters, got ${deps.tokenPrefix}`);\n const head = `${deps.tokenPrefix}1.`;\n const secret = () => (typeof deps.secret === \"function\" ? deps.secret() : deps.secret);\n const isToken = (value: string | undefined): value is string =>\n !!value && value.startsWith(head) && BODY.test(value.slice(head.length));\n const tokenHash = (token: string) => crypto.createHmac(\"sha256\", `session:${secret()}`).update(token).digest(\"hex\");\n const newToken = () => `${head}${crypto.randomBytes(32).toString(\"base64url\")}`;\n return {\n newToken,\n isToken,\n tokenHash,\n async create(accountId, meta) {\n const days = typeof deps.sessionDays === \"function\" ? await deps.sessionDays() : deps.sessionDays;\n if (!Number.isInteger(days) || days < 1)\n throw new RangeError(`sessionDays must be a whole number of days from 1, got ${days}`);\n const token = newToken();\n const createdAt = deps.clock.now();\n // days of 24 hours, not calendar days: the same instant whatever the server's time zone (the copies added 86 400 000 ms a day)\n const expires = new Date(createdAt);\n expires.setUTCHours(expires.getUTCHours() + days * 24);\n await deps.store.insert({\n accountId,\n tokenHash: tokenHash(token),\n createdAt,\n expiresAt: expires,\n ip: meta.ip,\n userAgent: meta.userAgent?.slice(0, USER_AGENT_MAX) ?? null,\n });\n return { token, expires };\n },\n async resolve(token) {\n if (!isToken(token)) return null;\n return deps.store.find(tokenHash(token), deps.clock.now());\n },\n async revoke(token) {\n if (!isToken(token)) return;\n await deps.store.delete(tokenHash(token));\n },\n };\n}\n\n/** The attributes of the session cookie, for the product's framework (`cookies().set(cookie)`, `NextResponse.cookies.set`…). */\nexport interface SessionCookie {\n name: string;\n value: string;\n httpOnly: true;\n secure: boolean;\n sameSite: \"lax\";\n path: \"/\";\n expires: Date;\n}\n\n/**\n * The session cookie: HttpOnly, SameSite=Lax, on the whole site, `Secure` where the product says (production).\n * @param options the cookie's name (`yomizaka_session`) and whether it is `Secure`\n */\nexport function sessionCookie(token: string, expires: Date, options: { name: string; secure: boolean }): SessionCookie {\n return {\n name: options.name,\n value: token,\n httpOnly: true,\n secure: options.secure,\n sameSite: \"lax\",\n path: \"/\",\n expires,\n };\n}\n\n/** The same cookie, expired now: what signing out sets. */\nexport function clearedSessionCookie(options: { name: string; secure: boolean }, now: Date): SessionCookie {\n return sessionCookie(\"\", now, options);\n}\n\n/**\n * The session token of a request: the native apps' `Authorization: Bearer` (which wins over a stale cookie), else the web's cookie.\n * @param headers the request's headers\n * @param options the cookie's name; `bearer: false` for a product with no native app\n * @returns the raw token (not yet checked), or undefined\n */\nexport function sessionTokenOf(headers: Headers, options: { cookie: string; bearer?: boolean }): string | undefined {\n if (options.bearer !== false) {\n const bearer = /^bearer (\\S+)$/i.exec(headers.get(\"authorization\") ?? \"\")?.[1];\n if (bearer) return bearer;\n }\n const prefix = `${options.cookie}=`;\n return headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix))\n ?.slice(prefix.length);\n}\n","import type { NewSession, Session, SessionStore } from \"./sessions\";\n\n/**\n * An in-memory session store, for unit tests and demos. `accountOf` plays the accounts table: it answers the account of an id, or null\n * when it does not exist or is not active.\n */\nexport function memorySessionStore<Account>(\n accountOf: (accountId: string) => Account | null,\n): SessionStore<Account> & { rows(): readonly NewSession[] } {\n const rows = new Map<string, NewSession & { id: string }>();\n let next = 0;\n return {\n async insert(session) {\n if (rows.has(session.tokenHash)) throw new Error(\"duplicate session token hash\");\n next += 1;\n rows.set(session.tokenHash, { ...session, id: `session-${next}` });\n },\n async find(tokenHash, now): Promise<Session<Account> | null> {\n const row = rows.get(tokenHash);\n if (!row || row.expiresAt.getTime() <= now.getTime()) return null;\n const account = accountOf(row.accountId);\n return account === null ? null : { id: row.id, account };\n },\n async delete(tokenHash) {\n rows.delete(tokenHash);\n },\n rows: () => [...rows.values()],\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { Session, SessionStore } from \"./sessions\";\n\nexport interface DbSessionStoreOptions<Account> {\n /** The product's session table. Default `sessions` (`id`, `account_id`, `token_hash` unique, `created_at`, `expires_at`, `ip`, `user_agent`). */\n sessions?: string;\n /** The product's account table. Default `accounts`. */\n accounts?: string;\n /** The account columns the session carries (`id`, `email`, `role`, `locale`, `name`…): all checked, all read in one query with the session. */\n columns: readonly string[];\n /** Builds the product's account from a row holding exactly `columns`. */\n toAccount: (row: Record<string, unknown>) => Account;\n /** An account that is not active signs nobody in (a suspension applies at once): the column and the value it must have (`status` = `ACTIVE`). */\n active?: { column: string; equals: string };\n}\n\n/**\n * The session store over the product's own tables (`sessions` joined to `accounts`): the declared tables and columns are checked by\n * `ident()` and nothing else reaches SQL. The expiry is compared with the clock's `now`, not the database's.\n * @param query the product's query\n * @param options the table names, the account columns and how the account is built\n * @throws DbError `DB_UNSAFE_IDENTIFIER` for a table or column name that is not a safe identifier\n */\nexport function dbSessionStore<Account>(query: Query, options: DbSessionStoreOptions<Account>): SessionStore<Account> {\n const sessions = ident(options.sessions ?? \"sessions\");\n const accounts = ident(options.accounts ?? \"accounts\");\n const columns = options.columns.map((column) => `a.${ident(column)}`).join(\", \");\n const active = options.active ? ` AND a.${ident(options.active.column)} = $3` : \"\";\n return {\n async insert(session) {\n await query(\n `INSERT INTO ${sessions} (account_id, token_hash, created_at, expires_at, ip, user_agent) VALUES ($1, $2, $3, $4, $5, $6)`,\n [session.accountId, session.tokenHash, session.createdAt, session.expiresAt, session.ip, session.userAgent],\n );\n },\n async find(tokenHash, now): Promise<Session<Account> | null> {\n const params: unknown[] = [tokenHash, now];\n if (options.active) params.push(options.active.equals);\n const [row] = await query<Record<string, unknown> & { session_id: string }>(\n `SELECT s.id AS session_id, ${columns} FROM ${sessions} s JOIN ${accounts} a ON a.id = s.account_id WHERE s.token_hash = $1 AND s.expires_at > $2${active}`,\n params,\n );\n if (!row) return null;\n const { session_id: id, ...account } = row;\n return { id, account: options.toAccount(account) };\n },\n async delete(tokenHash) {\n await query(`DELETE FROM ${sessions} WHERE token_hash = $1`, [tokenHash]);\n },\n };\n}\n","import {\n type CompleteOptions,\n type ExternalIdentity,\n type FederatedProvider,\n FEDERATION_CODE,\n FederationError,\n type IdentityProvider,\n isFederatedProvider,\n isLocalReturn,\n type StartedSignIn,\n type StartOptions,\n} from \"./federation\";\n\n/** The `fetch` the adapter calls krizaka-users with (injected: no global, no network in tests). */\nexport type Fetcher = (\n url: string,\n init: { method: \"POST\"; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;\n\nexport interface UsersFederationOptions {\n /** The tenant host of the product: `https://auth.dev.akinaza.com`. */\n baseUrl: string;\n /** The product's public address: the start URL sends the person back to it, so `returnTo` is absolute from it. */\n appUrl: string;\n fetch: Fetcher;\n}\n\nconst START = (base: string, provider: FederatedProvider) => `${base}/api/v1/auth/web/${provider}/start`;\nconst EXCHANGE = (base: string) => `${base}/api/v1/auth/web/exchange`;\n\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Reads krizaka-users' answer into an identity; anything that is not a complete identity is refused. */\nexport function parseExternalIdentity(body: unknown): ExternalIdentity {\n const o = (body ?? {}) as Record<string, unknown>;\n const issuer = text(o.issuer);\n const subject = text(o.subject);\n if (!issuer || !subject)\n throw new FederationError(FEDERATION_CODE.unavailable, \"krizaka-users answered without an issuer and a subject\");\n return { issuer, subject, email: text(o.email), emailVerified: o.email_verified === true, name: text(o.name) };\n}\n\n/**\n * The adapter for krizaka-users (`auth.<product>` tenant host, krizaka/krizaka-users#31): `start` builds the tenant's start address,\n * `complete` exchanges the one-time code (and the PKCE verifier of a native app) for the verified identity.\n */\nexport function usersIdentityProvider({ baseUrl, appUrl, fetch }: UsersFederationOptions): IdentityProvider {\n const base = baseUrl.replace(/\\/+$/, \"\");\n const app = appUrl.replace(/\\/+$/, \"\");\n return {\n async start(provider, returnTo, options: StartOptions = {}): Promise<StartedSignIn> {\n if (!isFederatedProvider(provider))\n throw new FederationError(FEDERATION_CODE.unknownProvider, `Unknown provider ${String(provider)}`);\n if (!isLocalReturn(returnTo))\n throw new FederationError(FEDERATION_CODE.badReturn, \"That return address is not allowed\");\n const state = crypto.randomUUID();\n const query = new URLSearchParams({ return_to: `${app}${returnTo}`, state });\n if (options.codeChallenge) {\n query.set(\"code_challenge\", options.codeChallenge);\n query.set(\"code_challenge_method\", \"S256\");\n }\n return { url: `${START(base, provider)}?${query}`, state };\n },\n async complete(code, options: CompleteOptions = {}) {\n const response = await fetch(EXCHANGE(base), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ code, ...(options.codeVerifier ? { code_verifier: options.codeVerifier } : {}) }),\n });\n if (response.status === 400 || response.status === 401 || response.status === 404 || response.status === 410)\n throw new FederationError(FEDERATION_CODE.invalidCode, \"That code is not valid\");\n if (!response.ok)\n throw new FederationError(FEDERATION_CODE.unavailable, `krizaka-users answered ${response.status}`);\n return parseExternalIdentity(await response.json());\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,IAAM,gBAAgB;AAAA,EAC3B,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,cAAc;AAAA,EACd,UAAU;AACZ;AAYO,SAAS,WAAW,MAAyB,SAA4D;AAC9G,MAAI,KAAK,SAAS,EAAG,QAAO;AAC5B,SAAO,QAAQ,aAAa,CAAC,IAAI;AACnC;AAGO,SAAS,UAAU,IAAmB,SAA4C;AACvF,MAAI,YAAY,KAAM,QAAO;AAC7B,SAAO,CAAC,CAAC,MAAM,QAAQ,SAAS,EAAE;AACpC;AAmBO,SAAS,aAAa,OAAsC;AACjE,QAAM,OAAO,MAAM,YAAY;AAC/B,QAAM,SAAS,CAAC,QAAmB,SACjC,OAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,MAAM,cAAc,SAAS,IAAI,EAAE,IAAI,OAAO,QAAQ,KAAK;AAC9F,MAAI,CAAC,MAAM,QAAS,QAAO,OAAO,KAAK,cAAc,eAAe;AACpE,MAAI,MAAM,QAAQ,QAAQ,UAAU,MAAM,QAAQ,SAAU,QAAO,OAAO,KAAK,cAAc,SAAS;AACtG,MAAI,CAAC,UAAU,MAAM,IAAI,MAAM,UAAU,EAAG,QAAO,OAAO,KAAK,cAAc,YAAY;AACzF,SAAO,EAAE,IAAI,KAAK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AC3C;AACA,aAAO,EAAE,KAAK,GAAG,MAAM,MAAM,QAAQ,CAAC,IAAI,KAAK,IAAI,MAAM;AAAA,IAC3D;AAAA,IACA,MAAM,SAAS,MAAM,UAA2B,CAAC,GAAG;AAClD,YAAM,WAAW,MAAM,MAAM,SAAS,IAAI,GAAG;AAAA,QAC3C,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,QAC9C,MAAM,KAAK,UAAU,EAAE,MAAM,GAAI,QAAQ,eAAe,EAAE,eAAe,QAAQ,aAAa,IAAI,CAAC,EAAG,CAAC;AAAA,MACzG,CAAC;AACD,UAAI,SAAS,WAAW,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW;AACvG,cAAM,IAAI,gBAAgB,gBAAgB,aAAa,wBAAwB;AACjF,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,gBAAgB,gBAAgB,aAAa,0BAA0B,SAAS,MAAM,EAAE;AACpG,aAAO,sBAAsB,MAAM,SAAS,KAAK,CAAC;AAAA,IACpD;AAAA,EACF;AACF;","names":["path","crypto","crypto","crypto","crypto","ident"]}
|
|
@@ -95,7 +95,7 @@ declare function identityLinksMigration(): string;
|
|
|
95
95
|
declare function dbIdentityLinks(query: Query): IdentityLinkStore;
|
|
96
96
|
|
|
97
97
|
/**
|
|
98
|
-
* Web sessions (the copies each product carried: Yomizaka `ys1.`, Akinaza `as1
|
|
98
|
+
* Web sessions (the copies each product carried: Yomizaka `ys1.`, Akinaza `as1.`). The cookie holds a random token
|
|
99
99
|
* (`<prefix>1.` and 32 bytes); the store keeps only its keyed hash, so a leaked table opens nothing. The account is re-read on every
|
|
100
100
|
* request (a suspension applies at once). The lifetime is the setting `auth.sessionDays`.
|
|
101
101
|
*/
|
package/dist/settings.js
CHANGED
|
@@ -2,14 +2,18 @@ import {
|
|
|
2
2
|
PASSWORD_RESET_MAX_MINUTES,
|
|
3
3
|
PASSWORD_RESET_MIN_MINUTES,
|
|
4
4
|
PASSWORD_RESET_TTL_MINUTES
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-34CFR7EE.js";
|
|
6
6
|
|
|
7
7
|
// src/settings.ts
|
|
8
8
|
import { integer } from "@krizaka/settings";
|
|
9
9
|
var authSettings = {
|
|
10
10
|
// @fixed: two weeks by default, as the products' copies had; the admin chooses between one day and ninety.
|
|
11
11
|
"auth.sessionDays": integer("auth", 14, { min: 1, max: 90, unit: "days" }),
|
|
12
|
-
"auth.passwordResetMinutes": integer("auth", PASSWORD_RESET_TTL_MINUTES, {
|
|
12
|
+
"auth.passwordResetMinutes": integer("auth", PASSWORD_RESET_TTL_MINUTES, {
|
|
13
|
+
min: PASSWORD_RESET_MIN_MINUTES,
|
|
14
|
+
max: PASSWORD_RESET_MAX_MINUTES,
|
|
15
|
+
unit: "minutes"
|
|
16
|
+
})
|
|
13
17
|
};
|
|
14
18
|
export {
|
|
15
19
|
authSettings
|