@krizaka/auth 0.8.0 → 0.9.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 +33 -0
- package/dist/chunk-3CLSDLXB.js +204 -0
- package/dist/chunk-3CLSDLXB.js.map +1 -0
- package/dist/{chunk-U5SDV7YV.js → chunk-5CFOMWBN.js} +25 -1
- package/dist/{chunk-U5SDV7YV.js.map → chunk-5CFOMWBN.js.map} +1 -1
- package/dist/contract.d.ts +46 -0
- package/dist/contract.js +27 -0
- package/dist/contract.js.map +1 -0
- package/dist/index.d.ts +136 -3
- package/dist/index.js +211 -188
- package/dist/index.js.map +1 -1
- package/dist/{identity-links-BI3DYE2I.d.ts → sessions-B9YKXs0i.d.ts} +97 -2
- package/dist/settings.d.ts +13 -0
- package/dist/settings.js +17 -0
- package/dist/settings.js.map +1 -0
- package/dist/testkit.d.ts +15 -2
- package/dist/testkit.js +62 -8
- package/dist/testkit.js.map +1 -1
- package/package.json +17 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/accounts.ts","../src/port.ts","../src/federated-sign-in.ts","../src/migration.ts","../src/roles.ts","../src/users-federation.ts"],"sourcesContent":["import crypto from \"node:crypto\";\n\nimport type { Query } from \"@krizaka/db\";\nimport { addHours, addMinutes } from \"date-fns\";\n\nimport { AccountError, type AccountProfile, type AccountService, type ProfilePatch, type SessionSummary, type Theme } from \"./port\";\n\n/** A SQL executor: `@krizaka/db`'s `Query`, which the product passes (its pool, or its transaction's client). */\nexport type { Query };\n\nexport interface Mail {\n to: string;\n /** The language of the mail (the person's). */\n locale: \"en\" | \"fr\";\n subject: string;\n text: string;\n /**\n * The link this mail carries, as data: a product that sends branded HTML (`@krizaka/email`: `passwordReset`, `emailChange`)\n * renders it from this instead of from `text`. Absent on a mail that is not a link.\n */\n link?: MailLink;\n}\n\n/** A mailed link: what it is for, where it goes, and how long it lives. */\nexport interface MailLink {\n kind: \"passwordReset\" | \"emailChange\";\n url: string;\n /** `passwordReset`: the lifetime in minutes. */\n minutes?: number;\n /** `emailChange`: the lifetime in hours. */\n hours?: number;\n}\n\nexport interface AccountDeps {\n query: Query;\n /**\n * Runs `work` in one transaction on one connection (BEGIN … COMMIT, rolled back when `work` throws) — the product's pool\n * knows how. The password reset runs under it: the account row is locked, the links retired and issued, the token claimed,\n * the password set and the sessions ended as one. Without it, the statements run one by one on `query` (one process, no\n * concurrent requests): give it in production.\n */\n transaction?: <T>(work: (query: Query) => Promise<T>) => Promise<T>;\n mail: (mail: Mail) => Promise<void>;\n /** `https://www.akinaza.com`: the e-mail change link is `<baseUrl>/<locale>/confirm-email?token=…`, the reset link `<baseUrl>/<locale>/reset-password?token=…`. */\n baseUrl: string;\n /** The product's name, in the words of the mail (« Akinaza »). */\n product: string;\n /** The product's token prefix, two or three letters (`ye1.` for Yomizaka: `ye`). The tokens are `<prefix>1.<43 base64url>`. */\n tokenPrefix: string;\n passwords: { hash: (password: string) => Promise<string>; verify: (password: string, stored: string) => Promise<boolean> };\n /** How a token is kept: the product's own keyed hash, the one its sessions use. */\n tokenHash: (token: string) => string;\n /**\n * How long a password reset link lives, in minutes: a whole number from 5 to 1440 (`PASSWORD_RESET_MIN_MINUTES`–`PASSWORD_RESET_MAX_MINUTES`),\n * default `PASSWORD_RESET_TTL_MINUTES` (30). The product reads it from its settings; the expiry and the mailed text both use it.\n * Out of range, `dbAccounts` throws.\n */\n passwordResetTtlMinutes?: number;\n /** Test seam: the token to issue. */\n token?: () => string;\n}\n\n// @fixed: the lifetime of an e-mail change link, a security parameter\nexport const EMAIL_CHANGE_TTL_HOURS = 24;\n/** The default lifetime of a password reset link, in minutes (`AccountDeps.passwordResetTtlMinutes` changes it). */\n// @fixed: the default lifetime of a password reset link, a security parameter\nexport const PASSWORD_RESET_TTL_MINUTES = 30;\n// @fixed: the shortest lifetime a product may set: a person must have time to open the mail\nexport const PASSWORD_RESET_MIN_MINUTES = 5;\n// @fixed: the longest lifetime a product may set: a day\nexport const PASSWORD_RESET_MAX_MINUTES = 1440;\n\nconst checkResetTtl = (minutes: number): number => {\n if (!Number.isInteger(minutes) || minutes < PASSWORD_RESET_MIN_MINUTES || minutes > PASSWORD_RESET_MAX_MINUTES) {\n throw new RangeError(`passwordResetTtlMinutes must be a whole number from ${PASSWORD_RESET_MIN_MINUTES} to ${PASSWORD_RESET_MAX_MINUTES}, got ${minutes}`);\n }\n return minutes;\n};\nconst NAME_MAX = 80;\nconst PASSWORD_MIN = 12;\nconst PASSWORD_MAX = 256;\nconst THEMES: readonly Theme[] = [\"light\", \"dark\", \"system\"];\n\n/** One format for every mailed link (an e-mail change, a password reset): the product's prefix, a version, 256 random bits. */\nexport const linkToken = (prefix: string) => `${prefix}1.${crypto.randomBytes(32).toString(\"base64url\")}`;\nexport const isLinkToken = (prefix: string, value: string | undefined | null): value is string => !!value && new RegExp(`^${prefix}1\\\\.[A-Za-z0-9_-]{43}$`).test(value);\nexport const emailChangeToken = linkToken;\nexport const isEmailChangeToken = isLinkToken;\n\nexport function passwordResetMail(product: string, locale: \"en\" | \"fr\", url: string, ttlMinutes: number = PASSWORD_RESET_TTL_MINUTES) {\n checkResetTtl(ttlMinutes);\n return locale === \"fr\"\n ? { subject: `Réinitialisez votre mot de passe — ${product}`, text: `Bonjour,\\n\\nPour choisir un nouveau mot de passe pour votre compte ${product}, ouvrez ce lien (valide ${ttlMinutes} min, une seule fois) :\\n${url}\\n\\nSi vous n'avez rien demandé, ignorez ce message : votre mot de passe ne change pas.\\n` }\n : { subject: `Reset your password — ${product}`, text: `Hello,\\n\\nTo choose a new password for your ${product} account, open this link (valid ${ttlMinutes} min, once):\\n${url}\\n\\nIf you did not ask for this, ignore this message: your password does not change.\\n` };\n}\n\nexport function emailChangeMail(product: string, locale: \"en\" | \"fr\", url: string) {\n return locale === \"fr\"\n ? { subject: `Confirmez votre nouvelle adresse — ${product}`, text: `Bonjour,\\n\\nPour utiliser cette adresse avec votre compte ${product}, confirmez-la en ouvrant ce lien (valide ${EMAIL_CHANGE_TTL_HOURS} h) :\\n${url}\\n\\nSi vous n'avez rien demandé, ignorez ce message : rien ne change.\\n` }\n : { subject: `Confirm your new address — ${product}`, text: `Hello,\\n\\nTo use this address with your ${product} account, confirm it by opening this link (valid ${EMAIL_CHANGE_TTL_HOURS} h):\\n${url}\\n\\nIf you did not ask for this, ignore this message: nothing changes.\\n` };\n}\n\n/** One « @ », something on each side, a dot inside the domain, no space — checked without a backtracking pattern. */\nconst looksLikeEmail = (address: string): boolean => {\n if (address.length > 320 || /\\s/.test(address)) return false;\n const at = address.indexOf(\"@\");\n if (at < 1 || at !== address.lastIndexOf(\"@\")) return false;\n const domain = address.slice(at + 1);\n const dot = domain.lastIndexOf(\".\");\n return dot > 0 && dot < domain.length - 1;\n};\n\nconst cleanName = (raw: string): string => {\n const name = raw.replace(/\\s+/g, \" \").trim();\n if (name.length > NAME_MAX) throw new AccountError(400, \"BAD_REQUEST\", `A name is at most ${NAME_MAX} characters`);\n return name;\n};\n\ninterface ProfileRow {\n id: string;\n email: string;\n name: string | null;\n locale: \"en\" | \"fr\";\n theme: Theme | null;\n avatar_seed: string | null;\n email_verified_at: Date | null;\n pending: string | null;\n}\n\n/** The adapter over the product's own PostgreSQL (`accounts`, `sessions`, `email_changes`, `password_resets`; see `accountsMigration`). */\nexport function dbAccounts(deps: AccountDeps): AccountService {\n const { query } = deps;\n const resetTtlMinutes = checkResetTtl(deps.passwordResetTtlMinutes ?? PASSWORD_RESET_TTL_MINUTES);\n const transaction = deps.transaction ?? (<T>(work: (q: Query) => Promise<T>) => work(query));\n const wrong = () => new AccountError(403, \"WRONG_PASSWORD\", \"The password is not right\");\n\n async function profileOf(id: string): Promise<AccountProfile> {\n const [row] = await query<ProfileRow>(\n `SELECT a.id, a.email, a.name, a.locale, a.theme, a.avatar_seed, a.email_verified_at,\n (SELECT c.new_email FROM email_changes c WHERE c.account_id = a.id AND c.used_at IS NULL AND c.expires_at > now() ORDER BY c.created_at DESC LIMIT 1) AS pending\n FROM accounts a WHERE a.id = $1`,\n [id],\n );\n if (!row) throw new AccountError(404, \"NOT_FOUND\", \"No such account\");\n return { id: row.id, email: row.email, name: row.name, locale: row.locale, theme: row.theme, avatarSeed: row.avatar_seed, emailVerified: !!row.email_verified_at, pendingEmail: row.pending };\n }\n\n async function confirmPassword(id: string, password: string): Promise<void> {\n const [row] = await query<{ password_hash: string | null }>(\"SELECT password_hash FROM accounts WHERE id = $1\", [id]);\n if (!row?.password_hash || password.length > PASSWORD_MAX || !(await deps.passwords.verify(password, row.password_hash))) throw wrong();\n }\n\n return {\n profile: profileOf,\n\n async updateProfile(id, patch: ProfilePatch) {\n const name = patch.name === undefined ? undefined : patch.name === null ? null : cleanName(patch.name);\n if (patch.avatarSeed && !/^[a-z0-9-]{1,40}$/.test(patch.avatarSeed)) throw new AccountError(400, \"BAD_REQUEST\", \"Not an avatar\");\n if (patch.theme && !THEMES.includes(patch.theme)) throw new AccountError(400, \"BAD_REQUEST\", \"Not a theme\");\n await query(\n `UPDATE accounts SET name = CASE WHEN $2::boolean THEN $3 ELSE name END, locale = COALESCE($4, locale),\n avatar_seed = CASE WHEN $5::boolean THEN $6 ELSE avatar_seed END, theme = CASE WHEN $7::boolean THEN $8 ELSE theme END WHERE id = $1`,\n [id, name !== undefined, name === \"\" ? null : (name ?? null), patch.locale ?? null, patch.avatarSeed !== undefined, patch.avatarSeed ?? null, patch.theme !== undefined, patch.theme ?? null],\n );\n return profileOf(id);\n },\n\n async requestEmailChange(id, input, now) {\n await confirmPassword(id, input.password);\n const address = input.newEmail.trim().toLowerCase();\n if (!looksLikeEmail(address)) throw new AccountError(400, \"BAD_REQUEST\", \"Not an e-mail address\");\n const [taken] = await query(\"SELECT 1 FROM accounts WHERE email = $1\", [address]);\n if (taken) return; // the same answer, no mail: the address is not disclosed\n const profile = await profileOf(id);\n await query(\"UPDATE email_changes SET used_at = $2 WHERE account_id = $1 AND used_at IS NULL\", [id, now]);\n const token = (deps.token ?? (() => emailChangeToken(deps.tokenPrefix)))();\n await query(\"INSERT INTO email_changes (account_id, new_email, token_hash, expires_at) VALUES ($1, $2, $3, $4)\", [id, address, deps.tokenHash(token), addHours(now, EMAIL_CHANGE_TTL_HOURS)]);\n const url = `${deps.baseUrl.replace(/\\/$/, \"\")}/${profile.locale}/confirm-email?token=${encodeURIComponent(token)}`;\n await deps.mail({ to: address, locale: profile.locale, ...emailChangeMail(deps.product, profile.locale, url), link: { kind: \"emailChange\", url, hours: EMAIL_CHANGE_TTL_HOURS } });\n },\n\n async confirmEmailChange(token, now) {\n if (!isEmailChangeToken(deps.tokenPrefix, token)) return \"INVALID\";\n const [row] = await query<{ account_id: string; new_email: string }>(\"UPDATE email_changes SET used_at = $2 WHERE token_hash = $1 AND used_at IS NULL AND expires_at > $2 RETURNING account_id, new_email\", [deps.tokenHash(token), now]);\n if (!row) return \"INVALID\";\n try {\n await query(\"UPDATE accounts SET email = $2, email_verified_at = $3 WHERE id = $1\", [row.account_id, row.new_email, now]);\n } catch {\n return \"INVALID\"; // taken in the meantime\n }\n return \"CHANGED\";\n },\n\n async changePassword(id, input, keepSessionId) {\n await confirmPassword(id, input.current);\n if (input.next.length < PASSWORD_MIN) throw new AccountError(400, \"PASSWORD_TOO_SHORT\", `At least ${PASSWORD_MIN} characters`);\n if (input.next.length > PASSWORD_MAX) throw new AccountError(400, \"PASSWORD_TOO_LONG\", `At most ${PASSWORD_MAX} characters`);\n await query(\"UPDATE accounts SET password_hash = $2 WHERE id = $1\", [id, await deps.passwords.hash(input.next)]);\n await query(\"DELETE FROM sessions WHERE account_id = $1 AND ($2::uuid IS NULL OR id <> $2::uuid)\", [id, keepSessionId ?? null]);\n },\n\n confirmPassword,\n\n async requestPasswordReset(email, now) {\n const address = email.trim().toLowerCase();\n if (!looksLikeEmail(address)) return; // the same answer: nothing is disclosed\n // One transaction, the account row locked: two requests at once leave one valid link — the later one. The mail goes after the commit.\n const issued = await transaction(async (q) => {\n const [row] = await q<{ id: string; locale: \"en\" | \"fr\" }>(\"SELECT id, locale FROM accounts WHERE email = $1 AND password_hash IS NOT NULL FOR UPDATE\", [address]);\n if (!row) return null;\n await q(\"UPDATE password_resets SET used_at = $2 WHERE account_id = $1 AND used_at IS NULL\", [row.id, now]);\n const token = (deps.token ?? (() => linkToken(deps.tokenPrefix)))();\n await q(\"INSERT INTO password_resets (account_id, token_hash, expires_at) VALUES ($1, $2, $3)\", [row.id, deps.tokenHash(token), addMinutes(now, resetTtlMinutes)]);\n return { token, locale: row.locale };\n });\n if (!issued) return;\n const url = `${deps.baseUrl.replace(/\\/$/, \"\")}/${issued.locale}/reset-password?token=${encodeURIComponent(issued.token)}`;\n await deps.mail({ to: address, locale: issued.locale, ...passwordResetMail(deps.product, issued.locale, url, resetTtlMinutes), link: { kind: \"passwordReset\", url, minutes: resetTtlMinutes } });\n },\n\n async resetPassword(token, next, now) {\n if (next.length < PASSWORD_MIN) throw new AccountError(400, \"PASSWORD_TOO_SHORT\", `At least ${PASSWORD_MIN} characters`);\n if (next.length > PASSWORD_MAX) throw new AccountError(400, \"PASSWORD_TOO_LONG\", `At most ${PASSWORD_MAX} characters`);\n if (!isLinkToken(deps.tokenPrefix, token)) return \"INVALID\";\n // One transaction: the link is claimed, the password set and every session ended as one — a failure leaves the link usable.\n return transaction(async (q) => {\n const [row] = await q<{ account_id: string }>(\"UPDATE password_resets SET used_at = $2 WHERE token_hash = $1 AND used_at IS NULL AND expires_at > $2 RETURNING account_id\", [deps.tokenHash(token), now]);\n if (!row) return \"INVALID\" as const;\n await q(\"UPDATE accounts SET password_hash = $2 WHERE id = $1\", [row.account_id, await deps.passwords.hash(next)]);\n await q(\"DELETE FROM sessions WHERE account_id = $1\", [row.account_id]);\n return \"CHANGED\" as const;\n });\n },\n\n async sessions(id, now, currentSessionId) {\n const rows = await query<{ id: string; created_at: Date; expires_at: Date; ip: string | null; user_agent: string | null }>(\"SELECT id, created_at, expires_at, ip, user_agent FROM sessions WHERE account_id = $1 AND expires_at > $2 ORDER BY created_at DESC\", [id, now]);\n return rows.map((r): SessionSummary => ({ id: r.id, createdAt: r.created_at, expiresAt: r.expires_at, ip: r.ip, userAgent: r.user_agent, current: r.id === currentSessionId }));\n },\n\n async signOutOthers(id, keepSessionId) {\n return (await query(\"DELETE FROM sessions WHERE account_id = $1 AND id <> $2::uuid RETURNING id\", [id, keepSessionId])).length;\n },\n\n async exportAccount(id, now, extra) {\n const profile = await profileOf(id);\n const live = await this.sessions(id, now);\n return { exportedAt: now.toISOString(), account: profile, sessions: live.map(({ current: _current, ...s }) => s), ...(extra ? await extra() : {}) };\n },\n\n async deleteAccount(id) {\n const rows = await query(\"DELETE FROM accounts WHERE id = $1 RETURNING id\", [id]);\n if (!rows.length) throw new AccountError(404, \"NOT_FOUND\", \"No such account\");\n },\n };\n}\n\n/** @deprecated The old name of `dbAccounts` (a name says what a thing does, not the technology). Removed in the next major. */\nexport const postgresAccounts = dbAccounts;\n","/**\n * The account PORT (ADR-0008 of Yomizaka, now shared). A product's account — name, language, theme, avatar, e-mail change with\n * verification, password (changed when signed in, or reset by a mailed link), sessions, export, deletion — behind one interface. Every product keeps its OWN accounts: no central\n * service, no runtime dependency between products.\n */\nexport type Theme = \"light\" | \"dark\" | \"system\";\n\nexport interface AccountProfile {\n id: string;\n email: string;\n name: string | null;\n locale: \"en\" | \"fr\";\n /** The theme the person chose; null = follow the device. */\n theme: Theme | null;\n /** A seed of the default avatars (the UI draws it); null = derived from the e-mail address. */\n avatarSeed: string | null;\n emailVerified: boolean;\n /** An address awaiting its verification link, if the person asked to change it. */\n pendingEmail: string | null;\n}\n\nexport interface ProfilePatch {\n name?: string | null;\n locale?: \"en\" | \"fr\";\n theme?: Theme | null;\n avatarSeed?: string | null;\n}\n\n/** A sign-in of the person: where from and when. Never the token. */\nexport interface SessionSummary {\n id: string;\n createdAt: Date;\n expiresAt: Date;\n ip: string | null;\n userAgent: string | null;\n current: boolean;\n}\n\nexport interface AccountService {\n profile(accountId: string): Promise<AccountProfile>;\n updateProfile(accountId: string, patch: ProfilePatch): Promise<AccountProfile>;\n /** Asks to change the address: the password is checked, a link is mailed to the NEW address. Answers the same whether or not it is already taken (no enumeration). */\n requestEmailChange(accountId: string, input: { newEmail: string; password: string }, now: Date): Promise<void>;\n /** Applies the change from the mailed link (single use, expires); the new address is verified by that very act. */\n confirmEmailChange(token: string, now: Date): Promise<\"CHANGED\" | \"INVALID\">;\n /** Changes the password (the current one is checked) and signs every other session out; `keepSessionId` stays. */\n changePassword(accountId: string, input: { current: string; next: string }, keepSessionId?: string): Promise<void>;\n /** Asks for a reset link, mailed (in the person's language) when an account with a password has this address; answers the same either way (no enumeration). */\n requestPasswordReset(email: string, now: Date): Promise<void>;\n /** Sets a new password from the mailed link — single use, expires — and signs every session out. The new password is checked before the link is used up. */\n resetPassword(token: string, next: string, now: Date): Promise<\"CHANGED\" | \"INVALID\">;\n /** Checks the password. Throws `AccountError(403, \"WRONG_PASSWORD\")`. */\n confirmPassword(accountId: string, password: string): Promise<void>;\n /** The person's live sign-ins, newest first; `currentSessionId` is flagged. */\n sessions(accountId: string, now: Date, currentSessionId?: string): Promise<SessionSummary[]>;\n /** Signs every other session out (and returns how many); `keepSessionId` stays. */\n signOutOthers(accountId: string, keepSessionId: string): Promise<number>;\n /** What the product keeps about the person, as one JSON-able document: the profile, the live sign-ins, and what `extra` adds. */\n exportAccount(accountId: string, now: Date, extra?: () => Promise<Record<string, unknown>>): Promise<Record<string, unknown>>;\n /** Deletes the identity: the account, its sessions and everything that hangs on it (the product erases its own data first). */\n deleteAccount(accountId: string): Promise<void>;\n}\n\nexport class AccountError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"AccountError\";\n }\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\";\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 { 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}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,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","addHours"]}
|
|
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,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,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,4 +1,4 @@
|
|
|
1
|
-
import { Query } from '@krizaka/db';
|
|
1
|
+
import { Query, Clock } from '@krizaka/db';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Federated sign-in (Google, Apple, Facebook, a native app's PKCE) delegated to krizaka-users, behind a PORT. The product keeps its
|
|
@@ -94,4 +94,99 @@ declare function identityLinksMigration(): string;
|
|
|
94
94
|
/** The store over the product's own database (`external_identities`; see `identityLinksMigration`). */
|
|
95
95
|
declare function dbIdentityLinks(query: Query): IdentityLinkStore;
|
|
96
96
|
|
|
97
|
-
|
|
97
|
+
/**
|
|
98
|
+
* Web sessions (the copies each product carried: Yomizaka `ys1.`, Akinaza `as1.`, Kachizaka `ks1.`). The cookie holds a random token
|
|
99
|
+
* (`<prefix>1.` and 32 bytes); the store keeps only its keyed hash, so a leaked table opens nothing. The account is re-read on every
|
|
100
|
+
* request (a suspension applies at once). The lifetime is the setting `auth.sessionDays`.
|
|
101
|
+
*/
|
|
102
|
+
/** A live session and the account it signs in. `Account` is the product's own shape (id, e-mail, role, locale, name…). */
|
|
103
|
+
interface Session<Account> {
|
|
104
|
+
id: string;
|
|
105
|
+
account: Account;
|
|
106
|
+
}
|
|
107
|
+
/** What a store keeps for a new session. */
|
|
108
|
+
interface NewSession {
|
|
109
|
+
accountId: string;
|
|
110
|
+
tokenHash: string;
|
|
111
|
+
createdAt: Date;
|
|
112
|
+
expiresAt: Date;
|
|
113
|
+
ip: string | null;
|
|
114
|
+
userAgent: string | null;
|
|
115
|
+
}
|
|
116
|
+
/** Where sessions live. Adapters: the PostgreSQL store over the product's `sessions` table, and a memory one. */
|
|
117
|
+
interface SessionStore<Account> {
|
|
118
|
+
insert(session: NewSession): Promise<void>;
|
|
119
|
+
/** The session of this hash, when it has not expired at `now` and its account is active; null otherwise. */
|
|
120
|
+
find(tokenHash: string, now: Date): Promise<Session<Account> | null>;
|
|
121
|
+
delete(tokenHash: string): Promise<void>;
|
|
122
|
+
}
|
|
123
|
+
interface SessionsDeps<Account> {
|
|
124
|
+
store: SessionStore<Account>;
|
|
125
|
+
clock: Clock;
|
|
126
|
+
/** The product's token letters: `ys` makes `ys1.<43 characters>`. Lower-case letters, 1 to 4. */
|
|
127
|
+
tokenPrefix: string;
|
|
128
|
+
/** What keys the stored hash (`AUTH_SESSION_SECRET`). A function lets the product read its environment when it is needed. */
|
|
129
|
+
secret: string | (() => string);
|
|
130
|
+
/** Days a new session lives: the setting `auth.sessionDays`, read for each new session. */
|
|
131
|
+
sessionDays: number | (() => number | Promise<number>);
|
|
132
|
+
}
|
|
133
|
+
interface Sessions<Account> {
|
|
134
|
+
/** A fresh token: shaped `<prefix>1.<43>`, random, never stored (only its hash is). */
|
|
135
|
+
newToken(): string;
|
|
136
|
+
isToken(value: string | undefined): value is string;
|
|
137
|
+
/** The keyed hash the store keeps for a token. */
|
|
138
|
+
tokenHash(token: string): string;
|
|
139
|
+
/** Opens a session: the token for the cookie (shown once) and when it expires. */
|
|
140
|
+
create(accountId: string, meta: {
|
|
141
|
+
ip: string | null;
|
|
142
|
+
userAgent: string | null;
|
|
143
|
+
}): Promise<{
|
|
144
|
+
token: string;
|
|
145
|
+
expires: Date;
|
|
146
|
+
}>;
|
|
147
|
+
/** The session a token opens, or null (unknown, malformed, expired, account not active). */
|
|
148
|
+
resolve(token: string | undefined): Promise<Session<Account> | null>;
|
|
149
|
+
/** Ends the session of this token. A malformed token is ignored. */
|
|
150
|
+
revoke(token: string | undefined): Promise<void>;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The sessions service of a product.
|
|
154
|
+
* @param deps the store, the clock, the token letters, the secret and the lifetime
|
|
155
|
+
* @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
|
|
156
|
+
*/
|
|
157
|
+
declare function createSessions<Account>(deps: SessionsDeps<Account>): Sessions<Account>;
|
|
158
|
+
/** The attributes of the session cookie, for the product's framework (`cookies().set(cookie)`, `NextResponse.cookies.set`…). */
|
|
159
|
+
interface SessionCookie {
|
|
160
|
+
name: string;
|
|
161
|
+
value: string;
|
|
162
|
+
httpOnly: true;
|
|
163
|
+
secure: boolean;
|
|
164
|
+
sameSite: "lax";
|
|
165
|
+
path: "/";
|
|
166
|
+
expires: Date;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The session cookie: HttpOnly, SameSite=Lax, on the whole site, `Secure` where the product says (production).
|
|
170
|
+
* @param options the cookie's name (`yomizaka_session`) and whether it is `Secure`
|
|
171
|
+
*/
|
|
172
|
+
declare function sessionCookie(token: string, expires: Date, options: {
|
|
173
|
+
name: string;
|
|
174
|
+
secure: boolean;
|
|
175
|
+
}): SessionCookie;
|
|
176
|
+
/** The same cookie, expired now: what signing out sets. */
|
|
177
|
+
declare function clearedSessionCookie(options: {
|
|
178
|
+
name: string;
|
|
179
|
+
secure: boolean;
|
|
180
|
+
}, now: Date): SessionCookie;
|
|
181
|
+
/**
|
|
182
|
+
* The session token of a request: the native apps' `Authorization: Bearer` (which wins over a stale cookie), else the web's cookie.
|
|
183
|
+
* @param headers the request's headers
|
|
184
|
+
* @param options the cookie's name; `bearer: false` for a product with no native app
|
|
185
|
+
* @returns the raw token (not yet checked), or undefined
|
|
186
|
+
*/
|
|
187
|
+
declare function sessionTokenOf(headers: Headers, options: {
|
|
188
|
+
cookie: string;
|
|
189
|
+
bearer?: boolean;
|
|
190
|
+
}): string | undefined;
|
|
191
|
+
|
|
192
|
+
export { type CompleteOptions as C, type ExternalIdentity as E, FEDERATED_PROVIDERS as F, type IdentityLinkStore as I, type NewSession as N, type SessionStore as S, type IdentityProvider as a, FEDERATION_CODE as b, type FederatedProvider as c, type FederationCode as d, FederationError as e, IdentityLinkError as f, type Session as g, type SessionCookie as h, type Sessions as i, type SessionsDeps as j, type StartOptions as k, type StartedSignIn as l, clearedSessionCookie as m, createSessions as n, dbIdentityLinks as o, identityLinksMigration as p, isFederatedProvider as q, isLocalReturn as r, memoryIdentityLinks as s, memoryIdentityProvider as t, pkceChallenge as u, sessionCookie as v, sessionTokenOf as w };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import * as _krizaka_settings from '@krizaka/settings';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The settings of « auth », a fragment the product adds to its registry (`@krizaka/auth/settings`): how long a session and a reset link
|
|
5
|
+
* live. The admin changes them without a redeploy; the product reads them and passes them to `createSessions({ sessionDays })` and
|
|
6
|
+
* `dbAccounts({ passwordResetTtlMinutes })`. Global scope only.
|
|
7
|
+
*/
|
|
8
|
+
declare const authSettings: {
|
|
9
|
+
readonly "auth.sessionDays": _krizaka_settings.Def<number>;
|
|
10
|
+
readonly "auth.passwordResetMinutes": _krizaka_settings.Def<number>;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export { authSettings };
|
package/dist/settings.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PASSWORD_RESET_MAX_MINUTES,
|
|
3
|
+
PASSWORD_RESET_MIN_MINUTES,
|
|
4
|
+
PASSWORD_RESET_TTL_MINUTES
|
|
5
|
+
} from "./chunk-3CLSDLXB.js";
|
|
6
|
+
|
|
7
|
+
// src/settings.ts
|
|
8
|
+
import { integer } from "@krizaka/settings";
|
|
9
|
+
var authSettings = {
|
|
10
|
+
// @fixed: two weeks by default, as the products' copies had; the admin chooses between one day and ninety.
|
|
11
|
+
"auth.sessionDays": integer("auth", 14, { min: 1, max: 90, unit: "days" }),
|
|
12
|
+
"auth.passwordResetMinutes": integer("auth", PASSWORD_RESET_TTL_MINUTES, { min: PASSWORD_RESET_MIN_MINUTES, max: PASSWORD_RESET_MAX_MINUTES, unit: "minutes" })
|
|
13
|
+
};
|
|
14
|
+
export {
|
|
15
|
+
authSettings
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=settings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/settings.ts"],"sourcesContent":["import { integer, type Registry } from \"@krizaka/settings\";\n\nimport { PASSWORD_RESET_MAX_MINUTES, PASSWORD_RESET_MIN_MINUTES, PASSWORD_RESET_TTL_MINUTES } from \"./accounts\";\n\n/**\n * The settings of « auth », a fragment the product adds to its registry (`@krizaka/auth/settings`): how long a session and a reset link\n * live. The admin changes them without a redeploy; the product reads them and passes them to `createSessions({ sessionDays })` and\n * `dbAccounts({ passwordResetTtlMinutes })`. Global scope only.\n */\nexport const authSettings = {\n // @fixed: two weeks by default, as the products' copies had; the admin chooses between one day and ninety.\n \"auth.sessionDays\": integer(\"auth\", 14, { min: 1, max: 90, unit: \"days\" }),\n \"auth.passwordResetMinutes\": integer(\"auth\", PASSWORD_RESET_TTL_MINUTES, { min: PASSWORD_RESET_MIN_MINUTES, max: PASSWORD_RESET_MAX_MINUTES, unit: \"minutes\" }),\n} as const satisfies Registry;\n"],"mappings":";;;;;;;AAAA,SAAS,eAA8B;AAShC,IAAM,eAAe;AAAA;AAAA,EAE1B,oBAAoB,QAAQ,QAAQ,IAAI,EAAE,KAAK,GAAG,KAAK,IAAI,MAAM,OAAO,CAAC;AAAA,EACzE,6BAA6B,QAAQ,QAAQ,4BAA4B,EAAE,KAAK,4BAA4B,KAAK,4BAA4B,MAAM,UAAU,CAAC;AAChK;","names":[]}
|
package/dist/testkit.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as ExternalIdentity, a as IdentityProvider, I as IdentityLinkStore } from './
|
|
1
|
+
import { E as ExternalIdentity, a as IdentityProvider, S as SessionStore, I as IdentityLinkStore } from './sessions-B9YKXs0i.js';
|
|
2
2
|
import '@krizaka/db';
|
|
3
3
|
|
|
4
4
|
/** What an `IdentityProvider` adapter is run against: the provider, and a way to make the far side hand out a one-time code. */
|
|
@@ -12,5 +12,18 @@ declare const PERSON: ExternalIdentity;
|
|
|
12
12
|
declare function identityProviderContract(name: string, make: () => ProviderHarness | Promise<ProviderHarness>): void;
|
|
13
13
|
/** What every IdentityLinkStore adapter must do. `account(n)` gives an account id the adapter accepts. */
|
|
14
14
|
declare function identityLinkStoreContract(name: string, make: () => IdentityLinkStore | Promise<IdentityLinkStore>, account: (n: number) => string | Promise<string>): void;
|
|
15
|
+
/** What a `SessionStore` adapter is run against: the store, an active account of the product, and a way to suspend it. */
|
|
16
|
+
interface SessionStoreHarness {
|
|
17
|
+
/** The store; the account it carries is `{ id }`. */
|
|
18
|
+
store: SessionStore<{
|
|
19
|
+
id: string;
|
|
20
|
+
}>;
|
|
21
|
+
/** An active account's id (the same `n` gives the same account). */
|
|
22
|
+
account(n: number): string | Promise<string>;
|
|
23
|
+
/** Suspends the account: its sessions no longer sign anybody in. */
|
|
24
|
+
suspend(accountId: string): void | Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
/** What every `SessionStore` adapter must do: the same behaviour behind the same port. */
|
|
27
|
+
declare function sessionStoreContract(name: string, make: () => SessionStoreHarness | Promise<SessionStoreHarness>): void;
|
|
15
28
|
|
|
16
|
-
export { PERSON, type ProviderHarness, identityLinkStoreContract, identityProviderContract };
|
|
29
|
+
export { PERSON, type ProviderHarness, type SessionStoreHarness, identityLinkStoreContract, identityProviderContract, sessionStoreContract };
|
package/dist/testkit.js
CHANGED
|
@@ -2,9 +2,10 @@ import {
|
|
|
2
2
|
FederationError,
|
|
3
3
|
IdentityLinkError,
|
|
4
4
|
pkceChallenge
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-5CFOMWBN.js";
|
|
6
6
|
|
|
7
7
|
// src/testkit.ts
|
|
8
|
+
import { randomUUID } from "crypto";
|
|
8
9
|
import { expect, it } from "vitest";
|
|
9
10
|
var PERSON = { issuer: "https://accounts.google.com", subject: "1234567890", email: "eric@example.com", emailVerified: true, name: "\xC9ric" };
|
|
10
11
|
function identityProviderContract(name, make) {
|
|
@@ -54,14 +55,14 @@ function identityProviderContract(name, make) {
|
|
|
54
55
|
});
|
|
55
56
|
}
|
|
56
57
|
function identityLinkStoreContract(name, make, account) {
|
|
57
|
-
const
|
|
58
|
+
const NOW2 = /* @__PURE__ */ new Date("2026-10-26T12:00:00Z");
|
|
58
59
|
const subject = () => `sub-${Math.random().toString(36).slice(2)}`;
|
|
59
60
|
it(`${name}: finds a linked identity, and nothing else`, async () => {
|
|
60
61
|
const store = await make();
|
|
61
62
|
const sub = subject();
|
|
62
63
|
expect(await store.find("google", sub)).toBeNull();
|
|
63
64
|
const id = await account(1);
|
|
64
|
-
await store.link(id, "google", sub,
|
|
65
|
+
await store.link(id, "google", sub, NOW2);
|
|
65
66
|
expect(await store.find("google", sub)).toBe(id);
|
|
66
67
|
expect(await store.find("apple", sub)).toBeNull();
|
|
67
68
|
});
|
|
@@ -69,15 +70,15 @@ function identityLinkStoreContract(name, make, account) {
|
|
|
69
70
|
const store = await make();
|
|
70
71
|
const id = await account(2);
|
|
71
72
|
const sub = subject();
|
|
72
|
-
await store.link(id, "google", sub,
|
|
73
|
+
await store.link(id, "google", sub, NOW2);
|
|
73
74
|
await store.link(id, "google", sub, /* @__PURE__ */ new Date("2026-10-27T12:00:00Z"));
|
|
74
75
|
expect((await store.list(id)).filter((r) => r.subject === sub)).toHaveLength(1);
|
|
75
76
|
});
|
|
76
77
|
it(`${name}: an identity belongs to one account only`, async () => {
|
|
77
78
|
const store = await make();
|
|
78
79
|
const sub = subject();
|
|
79
|
-
await store.link(await account(3), "google", sub,
|
|
80
|
-
await expect(store.link(await account(4), "google", sub,
|
|
80
|
+
await store.link(await account(3), "google", sub, NOW2);
|
|
81
|
+
await expect(store.link(await account(4), "google", sub, NOW2)).rejects.toBeInstanceOf(IdentityLinkError);
|
|
81
82
|
expect(await store.find("google", sub)).toBe(await account(3));
|
|
82
83
|
});
|
|
83
84
|
it(`${name}: lists an account's identities, oldest first, and unlinks one`, async () => {
|
|
@@ -85,7 +86,7 @@ function identityLinkStoreContract(name, make, account) {
|
|
|
85
86
|
const id = await account(5);
|
|
86
87
|
const [a, b] = [subject(), subject()];
|
|
87
88
|
await store.link(id, "apple", b, /* @__PURE__ */ new Date("2026-10-27T12:00:00Z"));
|
|
88
|
-
await store.link(id, "google", a,
|
|
89
|
+
await store.link(id, "google", a, NOW2);
|
|
89
90
|
expect((await store.list(id)).map((r) => r.subject)).toEqual([a, b]);
|
|
90
91
|
expect(await store.unlink(await account(6), "google", a)).toBe(false);
|
|
91
92
|
expect(await store.unlink(id, "google", a)).toBe(true);
|
|
@@ -93,9 +94,62 @@ function identityLinkStoreContract(name, make, account) {
|
|
|
93
94
|
expect(await store.find("google", a)).toBeNull();
|
|
94
95
|
});
|
|
95
96
|
}
|
|
97
|
+
var NOW = /* @__PURE__ */ new Date("2026-10-26T12:00:00Z");
|
|
98
|
+
var hours = (h) => {
|
|
99
|
+
const at = new Date(NOW);
|
|
100
|
+
at.setUTCHours(at.getUTCHours() + h);
|
|
101
|
+
return at;
|
|
102
|
+
};
|
|
103
|
+
var hashOf = () => `contract-hash-${randomUUID()}`;
|
|
104
|
+
function sessionStoreContract(name, make) {
|
|
105
|
+
it(`${name}: finds a session by its hash with its account, until it expires`, async () => {
|
|
106
|
+
const { store, account } = await make();
|
|
107
|
+
const accountId = await account(1);
|
|
108
|
+
const tokenHash = hashOf();
|
|
109
|
+
await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: "203.0.113.7", userAgent: "test" });
|
|
110
|
+
const found = await store.find(tokenHash, hours(1));
|
|
111
|
+
expect(found?.account).toEqual({ id: accountId });
|
|
112
|
+
expect(found?.id).toBeTruthy();
|
|
113
|
+
expect(await store.find(tokenHash, hours(24))).toBeNull();
|
|
114
|
+
expect(await store.find(tokenHash, hours(48))).toBeNull();
|
|
115
|
+
});
|
|
116
|
+
it(`${name}: knows no session for an unknown hash`, async () => {
|
|
117
|
+
const { store } = await make();
|
|
118
|
+
expect(await store.find("nope", NOW)).toBeNull();
|
|
119
|
+
});
|
|
120
|
+
it(`${name}: deletes a session, and only that one`, async () => {
|
|
121
|
+
const { store, account } = await make();
|
|
122
|
+
const accountId = await account(2);
|
|
123
|
+
const a = hashOf();
|
|
124
|
+
const b = hashOf();
|
|
125
|
+
await store.insert({ accountId, tokenHash: a, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });
|
|
126
|
+
await store.insert({ accountId, tokenHash: b, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });
|
|
127
|
+
await store.delete(a);
|
|
128
|
+
expect(await store.find(a, NOW)).toBeNull();
|
|
129
|
+
expect((await store.find(b, NOW))?.account.id).toBe(accountId);
|
|
130
|
+
await store.delete(a);
|
|
131
|
+
});
|
|
132
|
+
it(`${name}: a suspended account signs nobody in, at once`, async () => {
|
|
133
|
+
const { store, account, suspend } = await make();
|
|
134
|
+
const accountId = await account(3);
|
|
135
|
+
const tokenHash = hashOf();
|
|
136
|
+
await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });
|
|
137
|
+
expect(await store.find(tokenHash, NOW)).not.toBeNull();
|
|
138
|
+
await suspend(accountId);
|
|
139
|
+
expect(await store.find(tokenHash, NOW)).toBeNull();
|
|
140
|
+
});
|
|
141
|
+
it(`${name}: refuses the same hash twice`, async () => {
|
|
142
|
+
const { store, account } = await make();
|
|
143
|
+
const accountId = await account(4);
|
|
144
|
+
const tokenHash = hashOf();
|
|
145
|
+
await store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null });
|
|
146
|
+
await expect(store.insert({ accountId, tokenHash, createdAt: NOW, expiresAt: hours(24), ip: null, userAgent: null })).rejects.toThrow();
|
|
147
|
+
});
|
|
148
|
+
}
|
|
96
149
|
export {
|
|
97
150
|
PERSON,
|
|
98
151
|
identityLinkStoreContract,
|
|
99
|
-
identityProviderContract
|
|
152
|
+
identityProviderContract,
|
|
153
|
+
sessionStoreContract
|
|
100
154
|
};
|
|
101
155
|
//# sourceMappingURL=testkit.js.map
|
package/dist/testkit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/testkit.ts"],"sourcesContent":["import { expect, it } from \"vitest\";\n\nimport { type ExternalIdentity, FederationError, type IdentityProvider, pkceChallenge } from \"./federation\";\nimport { IdentityLinkError, type IdentityLinkStore } from \"./identity-links\";\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"],"mappings":";;;;;;;AAAA,SAAS,QAAQ,UAAU;AAYpB,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,CAA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AU,CAAC,CAAC,EAAE,KAAK,KAAK;AACpE,WAAO,MAAM,MAAM,OAAO,IAAI,UAAU,CAAC,CAAC,EAAE,KAAK,IAAI;AACrD,WAAO,MAAM,MAAM,OAAO,IAAI,UAAU,CAAC,CAAC,EAAE,KAAK,KAAK;AACtD,WAAO,MAAM,MAAM,KAAK,UAAU,CAAC,CAAC,EAAE,SAAS;AAAA,EACjD,CAAC;AACH;","names":[]}
|
|
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 });\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,IA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