@krizaka/auth 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,6 +42,10 @@ An external identity attaches to an existing account **only when the address is
42
42
 
43
43
  > `postgresAccounts` was the first name of `dbAccounts`; it stays as a `@deprecated` alias for one minor and leaves in the next major.
44
44
 
45
+ ## A signed-in visitor never sees the public side
46
+
47
+ In the product's `proxy.ts` (Web `Request`/`Response`, no framework): `landingRedirect(request, { cookie, landing: ["/", "/fr", "/en"], home })` answers 307 to the home with `Cache-Control: private, no-store` and `Vary: Cookie` when the session cookie exists on a landing route, else `null`. `sessionHint(response, request, { cookie, secure })` keeps the readable `kz-session=1` flag in step with the cookie (never the token), so the static pages stay the same for everyone and `NavBarSession` of `@krizaka/ui` draws the signed-in placeholder on its first paint. Both read the cookie as a hint only: the page and the API still resolve the session.
48
+
45
49
  ## Sessions, passwords, addresses and the administration's locks
46
50
 
47
51
  What Yomizaka, Akinaza, Kachizaka and Yororis each copied (`password.ts`, `client-ip.ts`, `session.ts`, the admin gate of `access.ts`) is here once. Each piece is a function of its inputs: the product reads its environment and its framework, and passes values.
package/dist/index.d.ts CHANGED
@@ -273,6 +273,31 @@ declare function createFederatedSignIn({ links, accounts, clock }: FederatedSign
273
273
  };
274
274
  type FederatedSignIn = ReturnType<typeof createFederatedSignIn>;
275
275
 
276
+ /** The readable flag the proxy keeps next to the HttpOnly session cookie: « a session cookie exists », value `1`, never the token. */
277
+ declare const SESSION_HINT_COOKIE = "kz-session";
278
+ /** Where a signed-in visitor of the landing route goes. */
279
+ interface LandingRule {
280
+ /** The product's session cookie name (`yomizaka_session`). */
281
+ cookie: string;
282
+ /** The landing routes (`["/", "/fr", "/en"]`): exact paths, a trailing slash tolerated. */
283
+ landing: readonly string[];
284
+ /** The signed-in start page, or a function of the request (the language of the address). */
285
+ home: string | ((request: Request) => string);
286
+ }
287
+ /**
288
+ * The landing route with a session cookie answers 307 to the home before any HTML: private, never stored, varying with the
289
+ * cookie. `null` for everything else (a signed-out visitor, another page, a write).
290
+ */
291
+ declare function landingRedirect(request: Request, rule: LandingRule): Response | null;
292
+ /**
293
+ * Keeps the hint flag in step with the session cookie on any response (pages stay static: the proxy runs on every request,
294
+ * the HTML is the same for everyone). Sets it when the session cookie exists, clears it when it is gone, else touches nothing.
295
+ */
296
+ declare function sessionHint<T extends Response>(response: T, request: Request, options: {
297
+ cookie: string;
298
+ secure: boolean;
299
+ }): T;
300
+
276
301
  /**
277
302
  * The SQL of version 1 of the accounts tables, for a product that runs it by hand (idempotent).
278
303
  * @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.
@@ -502,4 +527,4 @@ declare function parseExternalIdentity(body: unknown): ExternalIdentity;
502
527
  */
503
528
  declare function usersIdentityProvider({ baseUrl, appUrl, fetch }: UsersFederationOptions): IdentityProvider;
504
529
 
505
- export { ADMIN_REFUSAL, type AccountDeps, AccountError, type AccountProfile, type AccountService, type AdminDecision, type AdminGateInput, type AdminRefusal, type ClientIpRules, type DbSessionStoreOptions, EMAIL_CHANGE_TTL_HOURS, ExternalIdentity, FEDERATED_REFUSAL, type FederatedAccounts, type FederatedRefusal, type FederatedSignIn, type FederatedSignInDeps, type FederatedSignInResult, type Fetcher, IdentityLinkStore, IdentityProvider, type Invitation, type Mail, type MailLink, type Member, NewSession, PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH, PASSWORD_RESET_MAX_MINUTES, PASSWORD_RESET_MIN_MINUTES, PASSWORD_RESET_TTL_MINUTES, type ProfilePatch, ROLES_CODE, type RoleModel, type Roles, type RolesCode, type RolesDeps, RolesError, type RolesQuery, SessionStore, type SessionSummary, type Theme, type UsersFederationOptions, accountsMigration, accountsSchema, allowedIps, can, clientIp, createFederatedSignIn, createRoles, dbAccounts, dbSessionStore, decoyHash, defineRoles, emailChangeMail, emailChangeToken, hashPassword, identityLinksSchema, ipAllowed, isEmailChangeToken, isLinkToken, linkToken, memorySessionStore, parseExternalIdentity, passwordProblem, passwordResetMail, postgresAccounts, requireAdmin, rolesMigration, rolesSchema, sessionsSchema, usersIdentityProvider, verifyPassword };
530
+ export { ADMIN_REFUSAL, type AccountDeps, AccountError, type AccountProfile, type AccountService, type AdminDecision, type AdminGateInput, type AdminRefusal, type ClientIpRules, type DbSessionStoreOptions, EMAIL_CHANGE_TTL_HOURS, ExternalIdentity, FEDERATED_REFUSAL, type FederatedAccounts, type FederatedRefusal, type FederatedSignIn, type FederatedSignInDeps, type FederatedSignInResult, type Fetcher, IdentityLinkStore, IdentityProvider, type Invitation, type LandingRule, type Mail, type MailLink, type Member, NewSession, PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH, PASSWORD_RESET_MAX_MINUTES, PASSWORD_RESET_MIN_MINUTES, PASSWORD_RESET_TTL_MINUTES, type ProfilePatch, ROLES_CODE, type RoleModel, type Roles, type RolesCode, type RolesDeps, RolesError, type RolesQuery, SESSION_HINT_COOKIE, SessionStore, type SessionSummary, type Theme, type UsersFederationOptions, accountsMigration, accountsSchema, allowedIps, can, clientIp, createFederatedSignIn, createRoles, dbAccounts, dbSessionStore, decoyHash, defineRoles, emailChangeMail, emailChangeToken, hashPassword, identityLinksSchema, ipAllowed, isEmailChangeToken, isLinkToken, landingRedirect, linkToken, memorySessionStore, parseExternalIdentity, passwordProblem, passwordResetMail, postgresAccounts, requireAdmin, rolesMigration, rolesSchema, sessionHint, sessionsSchema, usersIdentityProvider, verifyPassword };
package/dist/index.js CHANGED
@@ -106,6 +106,34 @@ function createFederatedSignIn({ links, accounts, clock }) {
106
106
  };
107
107
  }
108
108
 
109
+ // src/landing.ts
110
+ var SESSION_HINT_COOKIE = "kz-session";
111
+ var cookieValue = (headers, name) => {
112
+ const prefix = `${name}=`;
113
+ return headers.get("cookie")?.split(";").map((part) => part.trim()).find((part) => part.startsWith(prefix))?.slice(prefix.length);
114
+ };
115
+ var trimmed = (path) => {
116
+ let end = path.length;
117
+ while (end > 1 && path.charCodeAt(end - 1) === 47) end--;
118
+ return path.slice(0, end);
119
+ };
120
+ function landingRedirect(request, rule) {
121
+ if (request.method !== "GET" && request.method !== "HEAD") return null;
122
+ if (!cookieValue(request.headers, rule.cookie)) return null;
123
+ const url = new URL(request.url);
124
+ if (!rule.landing.some((path) => trimmed(path) === trimmed(url.pathname))) return null;
125
+ const home = typeof rule.home === "function" ? rule.home(request) : rule.home;
126
+ return new Response(null, { status: 307, headers: { Location: new URL(home, url).toString(), "Cache-Control": "private, no-store", Vary: "Cookie" } });
127
+ }
128
+ function sessionHint(response, request, options) {
129
+ const session = Boolean(cookieValue(request.headers, options.cookie));
130
+ const flagged = cookieValue(request.headers, SESSION_HINT_COOKIE) === "1";
131
+ const base = `${SESSION_HINT_COOKIE}=${session ? "1" : ""}; Path=/; SameSite=Lax${options.secure ? "; Secure" : ""}`;
132
+ if (session && !flagged) response.headers.append("Set-Cookie", base);
133
+ else if (!session && cookieValue(request.headers, SESSION_HINT_COOKIE) !== void 0) response.headers.append("Set-Cookie", `${base}; Max-Age=0`);
134
+ return response;
135
+ }
136
+
109
137
  // src/migration.ts
110
138
  var IDENT = /^[a-z_][a-z0-9_]{0,62}$/;
111
139
  var ident = (name) => {
@@ -438,6 +466,7 @@ export {
438
466
  PASSWORD_RESET_TTL_MINUTES,
439
467
  ROLES_CODE,
440
468
  RolesError,
469
+ SESSION_HINT_COOKIE,
441
470
  accountsMigration,
442
471
  accountsSchema,
443
472
  allowedIps,
@@ -462,6 +491,7 @@ export {
462
491
  isFederatedProvider,
463
492
  isLinkToken,
464
493
  isLocalReturn,
494
+ landingRedirect,
465
495
  linkToken,
466
496
  memoryIdentityLinks,
467
497
  memoryIdentityProvider,
@@ -475,6 +505,7 @@ export {
475
505
  rolesMigration,
476
506
  rolesSchema,
477
507
  sessionCookie,
508
+ sessionHint,
478
509
  sessionTokenOf,
479
510
  sessionsSchema,
480
511
  usersIdentityProvider,
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/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","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\";\nimport { promisify } from \"node:util\";\n\nconst scrypt = promisify(crypto.scrypt) as (password: string, salt: Buffer, keylen: number, options: crypto.ScryptOptions) => Promise<Buffer>;\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\n/**\n * Roles per scope (a shop, a workspace), as DATA: a model says which roles exist, which permissions each holds and who may hand which\n * role to whom. The code asks `can(role, \"invoices:write\")`, never `if (role === \"owner\")`. One person may belong to several scopes, with\n * a role in each. Membership and invitations live in the product's PostgreSQL (see `rolesMigration`).\n */\nexport interface RoleModel<Role extends string = string, Permission extends string = string> {\n roles: readonly Role[];\n permissions: Record<Role, readonly Permission[]>;\n /** For each role, the roles it may invite, change and remove (the owner's, typically, is every role). */\n manages: Record<Role, readonly Role[]>;\n}\n\nexport const defineRoles = <const Role extends string, const Permission extends string>(model: RoleModel<Role, Permission>): RoleModel<Role, Permission> => model;\n\nexport const can = <Role extends string, Permission extends string>(model: RoleModel<Role, Permission>, role: Role | null | undefined, permission: Permission): boolean => !!role && model.permissions[role].includes(permission);\n\nexport const ROLES_CODE = {\n forbidden: \"FORBIDDEN\",\n notMember: \"NOT_A_MEMBER\",\n unknownRole: \"UNKNOWN_ROLE\",\n lastOwner: \"LAST_OWNER\",\n notAllowed: \"ROLE_NOT_ALLOWED\",\n inviteInvalid: \"INVITE_INVALID\",\n inviteWrongAccount: \"INVITE_WRONG_ACCOUNT\",\n} as const;\nexport type RolesCode = (typeof ROLES_CODE)[keyof typeof ROLES_CODE];\nconst STATUS: Record<RolesCode, number> = { FORBIDDEN: 403, NOT_A_MEMBER: 404, UNKNOWN_ROLE: 400, LAST_OWNER: 409, ROLE_NOT_ALLOWED: 403, INVITE_INVALID: 400, INVITE_WRONG_ACCOUNT: 403 };\n\nexport class RolesError extends Error {\n readonly status: number;\n constructor(readonly code: RolesCode) {\n super(code);\n this.name = \"RolesError\";\n this.status = STATUS[code];\n }\n}\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, `krizaka-users answered ${response.status}`);\n return parseExternalIdentity(await response.json());\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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iBAAiB,oBAAoB,OAAO,QAAQ,CAAC,EAAE;AACrI,UAAI,CAAC,cAAc,QAAQ,EAAG,OAAM,IAAI,gBAAgB,gBAAgB,WAAW,oCAAoC;AACvH,YAAM,QAAQ,OAAO,WAAW;AAChC,YAAM,QAAQ,IAAI,gBAAgB,EAAE,WAAW,GAAG,GAAG,GAAG,QAAQ,IAAI,MAAM,CAAC;AAC3E,UAAI,QAAQ,eAAe;AACzB,cAAM,IAAI,kBAAkB,QAAQ,aAAa;AACjD,cAAM,IAAI,yBAAyB,MAAM;AAAA,MAC3C;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,IAAK,OAAM,IAAI,gBAAgB,gBAAgB,aAAa,wBAAwB;AAC7L,UAAI,CAAC,SAAS,GAAI,OAAM,IAAI,gBAAgB,gBAAgB,aAAa,0BAA0B,SAAS,MAAM,EAAE;AACpH,aAAO,sBAAsB,MAAM,SAAS,KAAK,CAAC;AAAA,IACpD;AAAA,EACF;AACF;","names":["crypto","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 => (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\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 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 return new Response(null, { status: 307, headers: { Location: new URL(home, url).toString(), \"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\";\nimport { promisify } from \"node:util\";\n\nconst scrypt = promisify(crypto.scrypt) as (password: string, salt: Buffer, keylen: number, options: crypto.ScryptOptions) => Promise<Buffer>;\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\n/**\n * Roles per scope (a shop, a workspace), as DATA: a model says which roles exist, which permissions each holds and who may hand which\n * role to whom. The code asks `can(role, \"invoices:write\")`, never `if (role === \"owner\")`. One person may belong to several scopes, with\n * a role in each. Membership and invitations live in the product's PostgreSQL (see `rolesMigration`).\n */\nexport interface RoleModel<Role extends string = string, Permission extends string = string> {\n roles: readonly Role[];\n permissions: Record<Role, readonly Permission[]>;\n /** For each role, the roles it may invite, change and remove (the owner's, typically, is every role). */\n manages: Record<Role, readonly Role[]>;\n}\n\nexport const defineRoles = <const Role extends string, const Permission extends string>(model: RoleModel<Role, Permission>): RoleModel<Role, Permission> => model;\n\nexport const can = <Role extends string, Permission extends string>(model: RoleModel<Role, Permission>, role: Role | null | undefined, permission: Permission): boolean => !!role && model.permissions[role].includes(permission);\n\nexport const ROLES_CODE = {\n forbidden: \"FORBIDDEN\",\n notMember: \"NOT_A_MEMBER\",\n unknownRole: \"UNKNOWN_ROLE\",\n lastOwner: \"LAST_OWNER\",\n notAllowed: \"ROLE_NOT_ALLOWED\",\n inviteInvalid: \"INVITE_INVALID\",\n inviteWrongAccount: \"INVITE_WRONG_ACCOUNT\",\n} as const;\nexport type RolesCode = (typeof ROLES_CODE)[keyof typeof ROLES_CODE];\nconst STATUS: Record<RolesCode, number> = { FORBIDDEN: 403, NOT_A_MEMBER: 404, UNKNOWN_ROLE: 400, LAST_OWNER: 409, ROLE_NOT_ALLOWED: 403, INVITE_INVALID: 400, INVITE_WRONG_ACCOUNT: 403 };\n\nexport class RolesError extends Error {\n readonly status: number;\n constructor(readonly code: RolesCode) {\n super(code);\n this.name = \"RolesError\";\n this.status = STATUS[code];\n }\n}\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, `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,SAAuC,OAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,MAAM,cAAc,SAAS,IAAI,EAAE,IAAI,OAAO,QAAQ,KAAK;AACtK,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;AACpB;;;ACnDA,IAAM,OAAO;AACb,IAAM,OAAO;AACb,SAAS,KAAK,OAAwB;AACpC,SAAQ,KAAK,KAAK,KAAK,KAAK,MAAM,MAAM,GAAG,EAAE,MAAM,CAAC,MAAM,OAAO,CAAC,KAAK,GAAG,KAAO,MAAM,SAAS,GAAG,KAAK,KAAK,KAAK,KAAK;AACzH;AAeO,SAAS,SAAS,SAAkB,QAAuB,CAAC,GAAkB;AACnF,QA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AAgB,aAAa,0BAA0B,SAAS,MAAM,EAAE;AACpH,aAAO,sBAAsB,MAAM,SAAS,KAAK,CAAC;AAAA,IACpD;AAAA,EACF;AACF;","names":["crypto","crypto","crypto","ident"]}
package/dist/testkit.js CHANGED
@@ -56,7 +56,7 @@ function identityProviderContract(name, make) {
56
56
  }
57
57
  function identityLinkStoreContract(name, make, account) {
58
58
  const NOW2 = /* @__PURE__ */ new Date("2026-10-26T12:00:00Z");
59
- const subject = () => `sub-${Math.random().toString(36).slice(2)}`;
59
+ const subject = () => `sub-${randomUUID()}`;
60
60
  it(`${name}: finds a linked identity, and nothing else`, async () => {
61
61
  const store = await make();
62
62
  const sub = subject();
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/testkit.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nimport { expect, it } from \"vitest\";\n\nimport { type ExternalIdentity, FederationError, type IdentityProvider, pkceChallenge } from \"./federation\";\nimport { IdentityLinkError, type IdentityLinkStore } from \"./identity-links\";\nimport type { SessionStore } from \"./sessions\";\n\n/** What an `IdentityProvider` adapter is run against: the provider, and a way to make the far side hand out a one-time code. */\nexport interface ProviderHarness {\n provider: IdentityProvider;\n /** The identity the far side vouches for, as a one-time code the person comes back with (bound to a PKCE challenge when one is given). */\n issue(identity: ExternalIdentity, challenge?: string): string | Promise<string>;\n}\n\nexport const PERSON: ExternalIdentity = { issuer: \"https://accounts.google.com\", subject: \"1234567890\", email: \"eric@example.com\", emailVerified: true, name: \"Éric\" };\n\n/** What every IdentityProvider adapter must do: the same behaviour behind the same port. */\nexport function identityProviderContract(name: string, make: () => ProviderHarness | Promise<ProviderHarness>) {\n it(`${name}: starts a sign-in for each provider and keeps the state`, async () => {\n const { provider } = await make();\n for (const which of [\"google\", \"apple\", \"facebook\"] as const) {\n const started = await provider.start(which, \"/fr/account\");\n expect(started.url).toContain(which);\n expect(started.state.length).toBeGreaterThan(5);\n }\n const a = await provider.start(\"google\", \"/\");\n const b = await provider.start(\"google\", \"/\");\n expect(a.state).not.toBe(b.state);\n });\n\n it(`${name}: refuses an unknown provider`, async () => {\n const { provider } = await make();\n await expect(provider.start(\"myspace\" as never, \"/\")).rejects.toMatchObject({ code: \"UNKNOWN_PROVIDER\" });\n });\n\n it(`${name}: refuses a return address that leaves the product`, async () => {\n const { provider } = await make();\n for (const bad of [\"https://evil.example/\", \"//evil.example\", \"javascript:alert(1)\", \"/ok\\\\evil\", \"relative\", \"/a\\nb\"]) {\n await expect(provider.start(\"google\", bad), bad).rejects.toMatchObject({ code: \"BAD_RETURN_TO\" });\n }\n });\n\n it(`${name}: exchanges a one-time code for the verified identity`, async () => {\n const { provider, issue } = await make();\n expect(await provider.complete(await issue(PERSON))).toEqual(PERSON);\n });\n\n it(`${name}: a code works once`, async () => {\n const { provider, issue } = await make();\n const code = await issue(PERSON);\n await provider.complete(code);\n await expect(provider.complete(code)).rejects.toMatchObject({ code: \"INVALID_CODE\" });\n });\n\n it(`${name}: an unknown code is refused`, async () => {\n const { provider } = await make();\n const error = await provider.complete(\"nope\").catch((e: unknown) => e);\n expect(error).toBeInstanceOf(FederationError);\n expect(error).toMatchObject({ code: \"INVALID_CODE\" });\n });\n\n it(`${name}: a PKCE flow needs the verifier that made the challenge`, async () => {\n const { provider, issue } = await make();\n const verifier = \"v\".repeat(64);\n await expect(provider.complete(await issue(PERSON, pkceChallenge(verifier)))).rejects.toMatchObject({ code: \"INVALID_CODE\" });\n await expect(provider.complete(await issue(PERSON, pkceChallenge(verifier)), { codeVerifier: \"w\".repeat(64) })).rejects.toMatchObject({ code: \"INVALID_CODE\" });\n expect(await provider.complete(await issue(PERSON, pkceChallenge(verifier)), { codeVerifier: verifier })).toEqual(PERSON);\n });\n}\n\n/** What every IdentityLinkStore adapter must do. `account(n)` gives an account id the adapter accepts. */\nexport function identityLinkStoreContract(name: string, make: () => IdentityLinkStore | Promise<IdentityLinkStore>, account: (n: number) => string | Promise<string>) {\n const NOW = new Date(\"2026-10-26T12:00:00Z\");\n const subject = () => `sub-${Math.random().toString(36).slice(2)}`;\n\n it(`${name}: finds a linked identity, and nothing else`, async () => {\n const store = await make();\n const sub = subject();\n expect(await store.find(\"google\", sub)).toBeNull();\n const id = await account(1);\n await store.link(id, \"google\", sub, NOW);\n expect(await store.find(\"google\", sub)).toBe(id);\n expect(await store.find(\"apple\", sub)).toBeNull();\n });\n\n it(`${name}: linking twice to the same account is harmless`, async () => {\n const store = await make();\n const id = await account(2);\n const sub = subject();\n await store.link(id, \"google\", sub, NOW);\n await store.link(id, \"google\", sub, new Date(\"2026-10-27T12:00:00Z\"));\n expect((await store.list(id)).filter((r) => r.subject === sub)).toHaveLength(1);\n });\n\n it(`${name}: an identity belongs to one account only`, async () => {\n const store = await make();\n const sub = subject();\n await store.link(await account(3), \"google\", sub, NOW);\n await expect(store.link(await account(4), \"google\", sub, NOW)).rejects.toBeInstanceOf(IdentityLinkError);\n expect(await store.find(\"google\", sub)).toBe(await account(3));\n });\n\n it(`${name}: lists an account's identities, oldest first, and unlinks one`, async () => {\n const store = await make();\n const id = await account(5);\n const [a, b] = [subject(), subject()];\n await store.link(id, \"apple\", b, new Date(\"2026-10-27T12:00:00Z\"));\n await store.link(id, \"google\", a, NOW);\n expect((await store.list(id)).map((r) => r.subject)).toEqual([a, b]);\n expect(await store.unlink(await account(6), \"google\", a)).toBe(false);\n expect(await store.unlink(id, \"google\", a)).toBe(true);\n expect(await store.unlink(id, \"google\", a)).toBe(false);\n expect(await store.find(\"google\", a)).toBeNull();\n });\n}\n\n/** What a `SessionStore` adapter is run against: the store, an active account of the product, and a way to suspend it. */\nexport interface SessionStoreHarness {\n /** The store; the account it carries is `{ id }`. */\n store: SessionStore<{ id: string }>;\n /** An active account's id (the same `n` gives the same account). */\n account(n: number): string | Promise<string>;\n /** Suspends the account: its sessions no longer sign anybody in. */\n suspend(accountId: string): void | Promise<void>;\n}\n\nconst NOW = new Date(\"2026-10-26T12:00:00Z\");\nconst hours = (h: number) => {\n const at = new Date(NOW);\n at.setUTCHours(at.getUTCHours() + h);\n return at;\n};\nconst hashOf = () => `contract-hash-${randomUUID()}`;\n\n/** What every `SessionStore` adapter must do: the same behaviour behind the same port. */\nexport function sessionStoreContract(name: string, make: () => SessionStoreHarness | Promise<SessionStoreHarness>) {\n it(`${name}: finds a session by its hash with its account, until it expires`, async () => {\n const { store, account } = await make();\n const accountId = await account(1);\n const tokenHash = hashOf();\n await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: \"203.0.113.7\", userAgent: \"test\" });\n const found = await store.find(tokenHash, hours(1));\n expect(found?.account).toEqual({ id: accountId });\n expect(found?.id).toBeTruthy();\n expect(await store.find(tokenHash, hours(24))).toBeNull();\n expect(await store.find(tokenHash, hours(48))).toBeNull();\n });\n\n it(`${name}: knows no session for an unknown hash`, async () => {\n const { store } = await make();\n expect(await store.find(\"nope\", NOW)).toBeNull();\n });\n\n it(`${name}: deletes a session, and only that one`, async () => {\n const { store, account } = await make();\n const accountId = await account(2);\n const a = hashOf();\n const b = hashOf();\n await store.insert({ accountId, tokenHash: a, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });\n await store.insert({ accountId, tokenHash: b, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });\n await store.delete(a);\n expect(await store.find(a, NOW)).toBeNull();\n expect((await store.find(b, NOW))?.account.id).toBe(accountId);\n await store.delete(a); // twice: safe\n });\n\n it(`${name}: a suspended account signs nobody in, at once`, async () => {\n const { store, account, suspend } = await make();\n const accountId = await account(3);\n const tokenHash = hashOf();\n await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });\n expect(await store.find(tokenHash, NOW)).not.toBeNull();\n await suspend(accountId);\n expect(await store.find(tokenHash, NOW)).toBeNull();\n });\n\n it(`${name}: refuses the same hash twice`, async () => {\n const { store, account } = await make();\n const accountId = await account(4);\n const tokenHash = hashOf();\n await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });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AAY;AACtE,UAAM,EAAE,OAAO,SAAS,QAAQ,IAAI,MAAM,KAAK;AAC/C,UAAM,YAAY,MAAM,QAAQ,CAAC;AACjC,UAAM,YAAY,OAAO;AACzB,UAAM,MAAM,OAAO,EAAE,WAAW,WAAW,WAAW,KAAK,WAAW,MAAM,EAAE,GAAG,IAAI,MAAM,WAAW,KAAK,CAAC;AAC5G,WAAO,MAAM,MAAM,KAAK,WAAW,GAAG,CAAC,EAAE,IAAI,SAAS;AACtD,UAAM,QAAQ,SAAS;AACvB,WAAO,MAAM,MAAM,KAAK,WAAW,GAAG,CAAC,EAAE,SAAS;AAAA,EACpD,CAAC;AAED,KAAG,GAAG,IAAI,iCAAiC,YAAY;AACrD,UAAM,EAAE,OAAO,QAAQ,IAAI,MAAM,KAAK;AACtC,UAAM,YAAY,MAAM,QAAQ,CAAC;AACjC,UAAM,YAAY,OAAO;AACzB,UAAM,MAAM,OAAO,EAAE,WAAW,WAAW,WAAW,KAAK,WAAW,MAAM,EAAE,GAAG,IAAI,MAAM,WAAW,KAAK,CAAC;AAC5G,UAAM,OAAO,MAAM,OAAO,EAAE,WAAW,WAAW,WAAW,KAAK,WAAW,MAAM,EAAE,GAAG,IAAI,MAAM,WAAW,KAAK,CAAC,CAAC,EAAE,QAAQ,QAAQ;AAAA,EACxI,CAAC;AACH;","names":["NOW"]}
1
+ {"version":3,"sources":["../src/testkit.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nimport { expect, it } from \"vitest\";\n\nimport { type ExternalIdentity, FederationError, type IdentityProvider, pkceChallenge } from \"./federation\";\nimport { IdentityLinkError, type IdentityLinkStore } from \"./identity-links\";\nimport type { SessionStore } from \"./sessions\";\n\n/** What an `IdentityProvider` adapter is run against: the provider, and a way to make the far side hand out a one-time code. */\nexport interface ProviderHarness {\n provider: IdentityProvider;\n /** The identity the far side vouches for, as a one-time code the person comes back with (bound to a PKCE challenge when one is given). */\n issue(identity: ExternalIdentity, challenge?: string): string | Promise<string>;\n}\n\nexport const PERSON: ExternalIdentity = { issuer: \"https://accounts.google.com\", subject: \"1234567890\", email: \"eric@example.com\", emailVerified: true, name: \"Éric\" };\n\n/** What every IdentityProvider adapter must do: the same behaviour behind the same port. */\nexport function identityProviderContract(name: string, make: () => ProviderHarness | Promise<ProviderHarness>) {\n it(`${name}: starts a sign-in for each provider and keeps the state`, async () => {\n const { provider } = await make();\n for (const which of [\"google\", \"apple\", \"facebook\"] as const) {\n const started = await provider.start(which, \"/fr/account\");\n expect(started.url).toContain(which);\n expect(started.state.length).toBeGreaterThan(5);\n }\n const a = await provider.start(\"google\", \"/\");\n const b = await provider.start(\"google\", \"/\");\n expect(a.state).not.toBe(b.state);\n });\n\n it(`${name}: refuses an unknown provider`, async () => {\n const { provider } = await make();\n await expect(provider.start(\"myspace\" as never, \"/\")).rejects.toMatchObject({ code: \"UNKNOWN_PROVIDER\" });\n });\n\n it(`${name}: refuses a return address that leaves the product`, async () => {\n const { provider } = await make();\n for (const bad of [\"https://evil.example/\", \"//evil.example\", \"javascript:alert(1)\", \"/ok\\\\evil\", \"relative\", \"/a\\nb\"]) {\n await expect(provider.start(\"google\", bad), bad).rejects.toMatchObject({ code: \"BAD_RETURN_TO\" });\n }\n });\n\n it(`${name}: exchanges a one-time code for the verified identity`, async () => {\n const { provider, issue } = await make();\n expect(await provider.complete(await issue(PERSON))).toEqual(PERSON);\n });\n\n it(`${name}: a code works once`, async () => {\n const { provider, issue } = await make();\n const code = await issue(PERSON);\n await provider.complete(code);\n await expect(provider.complete(code)).rejects.toMatchObject({ code: \"INVALID_CODE\" });\n });\n\n it(`${name}: an unknown code is refused`, async () => {\n const { provider } = await make();\n const error = await provider.complete(\"nope\").catch((e: unknown) => e);\n expect(error).toBeInstanceOf(FederationError);\n expect(error).toMatchObject({ code: \"INVALID_CODE\" });\n });\n\n it(`${name}: a PKCE flow needs the verifier that made the challenge`, async () => {\n const { provider, issue } = await make();\n const verifier = \"v\".repeat(64);\n await expect(provider.complete(await issue(PERSON, pkceChallenge(verifier)))).rejects.toMatchObject({ code: \"INVALID_CODE\" });\n await expect(provider.complete(await issue(PERSON, pkceChallenge(verifier)), { codeVerifier: \"w\".repeat(64) })).rejects.toMatchObject({ code: \"INVALID_CODE\" });\n expect(await provider.complete(await issue(PERSON, pkceChallenge(verifier)), { codeVerifier: verifier })).toEqual(PERSON);\n });\n}\n\n/** What every IdentityLinkStore adapter must do. `account(n)` gives an account id the adapter accepts. */\nexport function identityLinkStoreContract(name: string, make: () => IdentityLinkStore | Promise<IdentityLinkStore>, account: (n: number) => string | Promise<string>) {\n const NOW = new Date(\"2026-10-26T12:00:00Z\");\n const subject = () => `sub-${randomUUID()}`;\n\n it(`${name}: finds a linked identity, and nothing else`, async () => {\n const store = await make();\n const sub = subject();\n expect(await store.find(\"google\", sub)).toBeNull();\n const id = await account(1);\n await store.link(id, \"google\", sub, NOW);\n expect(await store.find(\"google\", sub)).toBe(id);\n expect(await store.find(\"apple\", sub)).toBeNull();\n });\n\n it(`${name}: linking twice to the same account is harmless`, async () => {\n const store = await make();\n const id = await account(2);\n const sub = subject();\n await store.link(id, \"google\", sub, NOW);\n await store.link(id, \"google\", sub, new Date(\"2026-10-27T12:00:00Z\"));\n expect((await store.list(id)).filter((r) => r.subject === sub)).toHaveLength(1);\n });\n\n it(`${name}: an identity belongs to one account only`, async () => {\n const store = await make();\n const sub = subject();\n await store.link(await account(3), \"google\", sub, NOW);\n await expect(store.link(await account(4), \"google\", sub, NOW)).rejects.toBeInstanceOf(IdentityLinkError);\n expect(await store.find(\"google\", sub)).toBe(await account(3));\n });\n\n it(`${name}: lists an account's identities, oldest first, and unlinks one`, async () => {\n const store = await make();\n const id = await account(5);\n const [a, b] = [subject(), subject()];\n await store.link(id, \"apple\", b, new Date(\"2026-10-27T12:00:00Z\"));\n await store.link(id, \"google\", a, NOW);\n expect((await store.list(id)).map((r) => r.subject)).toEqual([a, b]);\n expect(await store.unlink(await account(6), \"google\", a)).toBe(false);\n expect(await store.unlink(id, \"google\", a)).toBe(true);\n expect(await store.unlink(id, \"google\", a)).toBe(false);\n expect(await store.find(\"google\", a)).toBeNull();\n });\n}\n\n/** What a `SessionStore` adapter is run against: the store, an active account of the product, and a way to suspend it. */\nexport interface SessionStoreHarness {\n /** The store; the account it carries is `{ id }`. */\n store: SessionStore<{ id: string }>;\n /** An active account's id (the same `n` gives the same account). */\n account(n: number): string | Promise<string>;\n /** Suspends the account: its sessions no longer sign anybody in. */\n suspend(accountId: string): void | Promise<void>;\n}\n\nconst NOW = new Date(\"2026-10-26T12:00:00Z\");\nconst hours = (h: number) => {\n const at = new Date(NOW);\n at.setUTCHours(at.getUTCHours() + h);\n return at;\n};\nconst hashOf = () => `contract-hash-${randomUUID()}`;\n\n/** What every `SessionStore` adapter must do: the same behaviour behind the same port. */\nexport function sessionStoreContract(name: string, make: () => SessionStoreHarness | Promise<SessionStoreHarness>) {\n it(`${name}: finds a session by its hash with its account, until it expires`, async () => {\n const { store, account } = await make();\n const accountId = await account(1);\n const tokenHash = hashOf();\n await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: \"203.0.113.7\", userAgent: \"test\" });\n const found = await store.find(tokenHash, hours(1));\n expect(found?.account).toEqual({ id: accountId });\n expect(found?.id).toBeTruthy();\n expect(await store.find(tokenHash, hours(24))).toBeNull();\n expect(await store.find(tokenHash, hours(48))).toBeNull();\n });\n\n it(`${name}: knows no session for an unknown hash`, async () => {\n const { store } = await make();\n expect(await store.find(\"nope\", NOW)).toBeNull();\n });\n\n it(`${name}: deletes a session, and only that one`, async () => {\n const { store, account } = await make();\n const accountId = await account(2);\n const a = hashOf();\n const b = hashOf();\n await store.insert({ accountId, tokenHash: a, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });\n await store.insert({ accountId, tokenHash: b, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });\n await store.delete(a);\n expect(await store.find(a, NOW)).toBeNull();\n expect((await store.find(b, NOW))?.account.id).toBe(accountId);\n await store.delete(a); // twice: safe\n });\n\n it(`${name}: a suspended account signs nobody in, at once`, async () => {\n const { store, account, suspend } = await make();\n const accountId = await account(3);\n const tokenHash = hashOf();\n await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });\n expect(await store.find(tokenHash, NOW)).not.toBeNull();\n await suspend(accountId);\n expect(await store.find(tokenHash, NOW)).toBeNull();\n });\n\n it(`${name}: refuses the same hash twice`, async () => {\n const { store, account } = await make();\n const accountId = await account(4);\n const tokenHash = hashOf();\n await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });\n await expect(store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null })).rejects.toThrow();\n });\n}\n"],"mappings":";;;;;;;AAAA,SAAS,kBAAkB;AAE3B,SAAS,QAAQ,UAAU;AAapB,IAAM,SAA2B,EAAE,QAAQ,+BAA+B,SAAS,cAAc,OAAO,oBAAoB,eAAe,MAAM,MAAM,UAAO;AAG9J,SAAS,yBAAyB,MAAc,MAAwD;AAC7G,KAAG,GAAG,IAAI,4DAA4D,YAAY;AAChF,UAAM,EAAE,SAAS,IAAI,MAAM,KAAK;AAChC,eAAW,SAAS,CAAC,UAAU,SAAS,UAAU,GAAY;AAC5D,YAAM,UAAU,MAAM,SAAS,MAAM,OAAO,aAAa;AACzD,aAAO,QAAQ,GAAG,EAAE,UAAU,KAAK;AACnC,aAAO,QAAQ,MAAM,MAAM,EAAE,gBAAgB,CAAC;AAAA,IAChD;AACA,UAAM,IAAI,MAAM,SAAS,MAAM,UAAU,GAAG;AAC5C,UAAM,IAAI,MAAM,SAAS,MAAM,UAAU,GAAG;AAC5C,WAAO,EAAE,KAAK,EAAE,IAAI,KAAK,EAAE,KAAK;AAAA,EAClC,CAAC;AAED,KAAG,GAAG,IAAI,iCAAiC,YAAY;AACrD,UAAM,EAAE,SAAS,IAAI,MAAM,KAAK;AAChC,UAAM,OAAO,SAAS,MAAM,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name": "@krizaka/auth",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "The account of a Krizaka product — name, language, theme, avatar, e-mail change by link with the verified flag, password, sessions with sign-out of the others, data export, deletion — behind a port, with a PostgreSQL adapter and its migration. Each product keeps its own accounts; no framework, no wall clock, no mail vendor.",
5
5
  "keywords": [
6
6
  "krizaka",
@@ -52,8 +52,8 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "date-fns": "^4.4.0",
55
- "@krizaka/settings": "^0.4.0",
56
- "@krizaka/db": "^0.2.0"
55
+ "@krizaka/db": "^0.2.0",
56
+ "@krizaka/settings": "^0.5.0"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": ">=4",
@@ -76,7 +76,7 @@
76
76
  "typescript": "^5.9.3",
77
77
  "vitest": "^4.1.11",
78
78
  "zod": "^4.6.7",
79
- "@krizaka/config": "^0.8.1"
79
+ "@krizaka/config": "^0.14.0"
80
80
  },
81
81
  "scripts": {
82
82
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",