@krizaka/auth 0.11.1 → 0.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -129,7 +129,8 @@ function landingRedirect(request, rule) {
|
|
|
129
129
|
const url = new URL(request.url);
|
|
130
130
|
if (!rule.landing.some((path) => trimmed(path) === trimmed(url.pathname))) return null;
|
|
131
131
|
const home = typeof rule.home === "function" ? rule.home(request) : rule.home;
|
|
132
|
-
|
|
132
|
+
const target = new URL(home, url);
|
|
133
|
+
return new Response(null, { status: 307, headers: { Location: `${target.pathname}${target.search}${target.hash}`, "Cache-Control": "private, no-store", Vary: "Cookie" } });
|
|
133
134
|
}
|
|
134
135
|
function sessionHint(response, request, options) {
|
|
135
136
|
const session = Boolean(cookieValue(request.headers, options.cookie));
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/admin-gate.ts","../src/client-ip.ts","../src/federated-sign-in.ts","../src/landing.ts","../src/migration.ts","../src/password.ts","../src/roles.ts","../src/sessions.ts","../src/sessions-memory.ts","../src/sessions-persistence.ts","../src/users-federation.ts"],"sourcesContent":["/**\n * The administration's locks, as one pure decision every product shares (it was copied in each product's `lib/access.ts`): a session,\n * the ADMIN role, and an address on the allowed list. A pure function of its inputs: the product reads the session and the address\n * and maps the verdict to its own answer.\n */\n\n/** Stable codes of a refusal. */\nexport const ADMIN_REFUSAL = {\n unauthenticated: \"UNAUTHENTICATED\",\n forbidden: \"FORBIDDEN\",\n ipNotAllowed: \"IP_NOT_ALLOWED\",\n notFound: \"NOT_FOUND\",\n} as const;\nexport type AdminRefusal = (typeof ADMIN_REFUSAL)[keyof typeof ADMIN_REFUSAL];\n\n/** The verdict: let in, or the status and code to answer. */\nexport type AdminDecision = { ok: true } | { ok: false; status: 401 | 403 | 404; code: AdminRefusal };\n\n/**\n * The list the administration's address lock reads, from the environment's value (`AUTH_ALLOWED_IPS`): an empty list is « nobody » in\n * production and « anybody » in development, so a forgotten setting never opens the console.\n * @param list the configured addresses\n * @returns the list to hand to `requireAdmin`, or null (anybody)\n */\nexport function allowedIps(list: readonly string[], options: { production: boolean }): readonly string[] | null {\n if (list.length > 0) return list;\n return options.production ? [] : null;\n}\n\n/** Whether an address may use the administration: `null` allowed means anybody, an empty list nobody, and a missing address is never allowed by a list. */\nexport function ipAllowed(ip: string | null, allowed: readonly string[] | null): boolean {\n if (allowed === null) return true;\n return !!ip && allowed.includes(ip);\n}\n\nexport interface AdminGateInput {\n /** The caller's session, or null when there is none. Only its account's role is read. */\n session: { account: { role: string } } | null;\n /** The caller's address (see `clientIp`). */\n ip: string | null;\n /** The addresses allowed (see `allowedIps`); null = anybody. */\n allowedIps: readonly string[] | null;\n /** `api` (default): 401 without a session, 403 with the reason. `page`: the administration does not announce itself, so every failed lock is a 404. */\n surface?: \"api\" | \"page\";\n /** The role that administers. Default `ADMIN`. */\n role?: string;\n}\n\n/**\n * The administration's three locks. The first that fails decides.\n * @returns `{ ok: true }`, or the status (401, 403 or 404 on a page) and the code to answer\n */\nexport function requireAdmin(input: AdminGateInput): AdminDecision {\n const page = input.surface === \"page\";\n const refuse = (status: 401 | 403, code: AdminRefusal): AdminDecision => (page ? { ok: false, status: 404, code: ADMIN_REFUSAL.notFound } : { ok: false, status, code });\n if (!input.session) return refuse(401, ADMIN_REFUSAL.unauthenticated);\n if (input.session.account.role !== (input.role ?? \"ADMIN\")) return refuse(403, ADMIN_REFUSAL.forbidden);\n if (!ipAllowed(input.ip, input.allowedIps)) return refuse(403, ADMIN_REFUSAL.ipNotAllowed);\n return { ok: true };\n}\n","/** How a deployment tells the client's address: the header its edge sets, and how many proxies append to `X-Forwarded-For`. */\nexport interface ClientIpRules {\n /** A header the edge sets and overwrites with the client's address (`do-connecting-ip` on DigitalOcean App Platform, `cf-connecting-ip` behind Cloudflare). Read first when present. */\n header?: string | undefined;\n /** How many trusted proxies append to `X-Forwarded-For`: 1 (the default) to 10. */\n trustedProxyHops?: number | undefined;\n}\n\nconst IPV4 = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\nconst IPV6 = /^[0-9a-f:]+(?:%\\w+)?$/i;\nfunction isIp(value: string): boolean {\n return (IPV4.test(value) && value.split(\".\").every((n) => Number(n) <= 255)) || (value.includes(\":\") && IPV6.test(value));\n}\n\n/**\n * The client's IP address, as far as this deployment can trust it. `X-Forwarded-For` is a list each proxy appends to: its LEFT end is\n * whatever the client sent (anyone can write `X-Forwarded-For: 1.2.3.4`), so a limit keyed on it is a limit the attacker chooses. The\n * address the last trusted proxy saw is read from the RIGHT:\n *\n * - the `header` the edge sets and overwrites, when present;\n * - otherwise the entry `trustedProxyHops` (default 1: one proxy) from the right of `X-Forwarded-For`, then `X-Real-IP`;\n * - otherwise null (local development without a proxy).\n *\n * The product reads its environment (`ABUSE_CLIENT_IP_HEADER`, `ABUSE_TRUSTED_PROXY_HOPS`) and passes the values: this function reads none.\n * @param headers the request's headers\n * @returns a valid IPv4 or IPv6 address, or null\n */\nexport function clientIp(headers: Headers, rules: ClientIpRules = {}): string | null {\n const custom = rules.header?.trim().toLowerCase();\n if (custom) {\n const value = headers.get(custom)?.split(\",\")[0]?.trim();\n if (value && isIp(value)) return value;\n }\n const hops = Math.max(1, Math.min(10, Number(rules.trustedProxyHops) || 1));\n const chain = (headers.get(\"x-forwarded-for\") ?? \"\")\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean);\n const fromRight = chain[chain.length - hops];\n if (fromRight && isIp(fromRight)) return fromRight;\n const real = headers.get(\"x-real-ip\")?.trim();\n if (real && isIp(real)) return real;\n return null;\n}\n","import type { ExternalIdentity } from \"./federation\";\nimport type { IdentityLinkStore } from \"./identity-links\";\n\n/** What federated sign-in needs from the product's accounts: no second user table, just a look-up and, when registration is open, a creation. */\nexport interface FederatedAccounts {\n /** The account that holds this address (lower case), and whether the product has verified it; null when none. */\n findByEmail(email: string): Promise<{ id: string; emailVerified: boolean } | null>;\n /** Creates an account for a person the provider vouches for (address verified, no password). Absent when registration is closed. */\n create?(identity: ExternalIdentity & { email: string }): Promise<string>;\n}\n\n/** Why a sign-in was refused: a stable code the product maps to its words. */\nexport const FEDERATED_REFUSAL = {\n /** The provider did not verify the address (or gave none): nothing is linked, nothing is created. */\n emailNotVerified: \"EMAIL_NOT_VERIFIED\",\n /** An account holds the address but the product never verified it: linking would let a stranger take it over. */\n accountEmailUnverified: \"ACCOUNT_EMAIL_UNVERIFIED\",\n /** No account, and registration is closed. */\n noAccount: \"NO_ACCOUNT\",\n} as const;\nexport type FederatedRefusal = (typeof FEDERATED_REFUSAL)[keyof typeof FEDERATED_REFUSAL];\n\nexport type FederatedSignInResult =\n /** `via`: `link` already linked, `linked` attached to the account of that address now, `created` a new account. */\n | { status: \"signed-in\"; accountId: string; via: \"link\" | \"linked\" | \"created\" }\n | { status: \"refused\"; code: FederatedRefusal };\n\nexport interface FederatedSignInDeps {\n links: IdentityLinkStore;\n accounts: FederatedAccounts;\n clock: { now(): Date };\n}\n\n/**\n * From a verified external identity to an account of the product. The rule that matters: an identity attaches to an EXISTING account\n * only when the address is verified on both sides — by the provider and by the product. Otherwise a stranger who registers at\n * Facebook with your address would sign in as you.\n */\nexport function createFederatedSignIn({ links, accounts, clock }: FederatedSignInDeps) {\n return {\n async signIn(identity: ExternalIdentity): Promise<FederatedSignInResult> {\n const known = await links.find(identity.issuer, identity.subject);\n if (known) return { status: \"signed-in\", accountId: known, via: \"link\" };\n\n const email = identity.email?.trim().toLowerCase();\n if (!email || !identity.emailVerified) return { status: \"refused\", code: FEDERATED_REFUSAL.emailNotVerified };\n\n const existing = await accounts.findByEmail(email);\n if (existing) {\n if (!existing.emailVerified) return { status: \"refused\", code: FEDERATED_REFUSAL.accountEmailUnverified };\n await links.link(existing.id, identity.issuer, identity.subject, clock.now());\n return { status: \"signed-in\", accountId: existing.id, via: \"linked\" };\n }\n\n if (!accounts.create) return { status: \"refused\", code: FEDERATED_REFUSAL.noAccount };\n const accountId = await accounts.create({ ...identity, email });\n await links.link(accountId, identity.issuer, identity.subject, clock.now());\n return { status: \"signed-in\", accountId, via: \"created\" };\n },\n };\n}\n\nexport type FederatedSignIn = ReturnType<typeof createFederatedSignIn>;\n","// The two proxy-side rules of « a signed-in person never sees the public side » (krizaka-ui#827), the same for every\n// product. Web-standard Request/Response only (a Next.js `proxy.ts` calls them). The cookie is a HINT: its presence\n// decides a redirect and a placeholder, never an authorization — the page and the API still resolve the session.\n\n/** The readable flag the proxy keeps next to the HttpOnly session cookie: « a session cookie exists », value `1`, never the token. */\nexport const SESSION_HINT_COOKIE = \"kz-session\";\n\nconst cookieValue = (headers: Headers, name: string): string | undefined => {\n const prefix = `${name}=`;\n return headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix))\n ?.slice(prefix.length);\n};\n\n/** Where a signed-in visitor of the landing route goes. */\nexport interface LandingRule {\n /** The product's session cookie name (`yomizaka_session`). */\n cookie: string;\n /** The landing routes (`[\"/\", \"/fr\", \"/en\"]`): exact paths, a trailing slash tolerated. */\n landing: readonly string[];\n /** The signed-in start page, or a function of the request (the language of the address). */\n home: string | ((request: Request) => string);\n}\n\n// Linear on any input (a loop, not a `/\\/+$/` regular expression: CodeQL js/polynomial-redos on the request path).\nconst trimmed = (path: string) => {\n let end = path.length;\n while (end > 1 && path.charCodeAt(end - 1) === 47) end--;\n return path.slice(0, end);\n};\n\n/**\n * The landing route with a session cookie answers 307 to the home before any HTML: private, never stored, varying with the\n * cookie. `null` for everything else (a signed-out visitor, another page, a write).\n */\nexport function landingRedirect(request: Request, rule: LandingRule): Response | null {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return null;\n if (!cookieValue(request.headers, rule.cookie)) return null;\n const url = new URL(request.url);\n if (!rule.landing.some((path) => trimmed(path) === trimmed(url.pathname))) return null;\n const home = typeof rule.home === \"function\" ? rule.home(request) : rule.home;\n return new Response(null, { status: 307, headers: { Location: new URL(home, url).toString(), \"Cache-Control\": \"private, no-store\", Vary: \"Cookie\" } });\n}\n\n/**\n * Keeps the hint flag in step with the session cookie on any response (pages stay static: the proxy runs on every request,\n * the HTML is the same for everyone). Sets it when the session cookie exists, clears it when it is gone, else touches nothing.\n */\nexport function sessionHint<T extends Response>(response: T, request: Request, options: { cookie: string; secure: boolean }): T {\n const session = Boolean(cookieValue(request.headers, options.cookie));\n const flagged = cookieValue(request.headers, SESSION_HINT_COOKIE) === \"1\";\n const base = `${SESSION_HINT_COOKIE}=${session ? \"1\" : \"\"}; Path=/; SameSite=Lax${options.secure ? \"; Secure\" : \"\"}`;\n if (session && !flagged) response.headers.append(\"Set-Cookie\", base);\n else if (!session && cookieValue(request.headers, SESSION_HINT_COOKIE) !== undefined) response.headers.append(\"Set-Cookie\", `${base}; Max-Age=0`);\n return response;\n}\n","import { accountsSchema, rolesSchema } from \"./schema\";\n\nconst IDENT = /^[a-z_][a-z0-9_]{0,62}$/;\nconst ident = (name: string) => {\n if (!IDENT.test(name)) throw new Error(`not a safe SQL identifier: ${name}`);\n return name;\n};\n\n/**\n * The SQL of version 1 of the accounts tables, for a product that runs it by hand (idempotent).\n * @deprecated Use `accountsSchema` with `emitMigration` or `adoptMigration` from `@krizaka/db`: the SQL gets a version, a checksum and a marker. Removed in the next major.\n */\nexport function accountsMigration(options: { backfillVerified?: boolean } = {}): string {\n return accountsSchema(options).migrations[0]!.sql({ schema: \"public\", tables: { accounts: \"accounts\" } });\n}\n\n/**\n * The SQL of version 1 of the memberships and invitations tables, for a product that runs it by hand (idempotent).\n * @deprecated Use `rolesSchema` with `emitMigration` or `adoptMigration` from `@krizaka/db`. Removed in the next major.\n */\nexport function rolesMigration(roles: readonly string[], options: { ownerTable?: string; scopeTable?: string } = {}): string {\n const tables = { owner: ident(options.ownerTable ?? \"accounts\"), ...(options.scopeTable ? { scope: ident(options.scopeTable) } : {}) };\n return rolesSchema(roles, { scoped: options.scopeTable !== undefined }).migrations[0]!.sql({ schema: \"public\", tables });\n}\n","import crypto from \"node:crypto\";\n\n/** Called only when a password is hashed or checked: the module also loads in a browser bundle (the role model), where `crypto.scrypt` does not exist. */\nconst scrypt = (password: string, salt: Buffer, keylen: number, options: crypto.ScryptOptions): Promise<Buffer> =>\n new Promise((resolve, reject) => {\n crypto.scrypt(password, salt, keylen, options, (error, key) => (error ? reject(error) : resolve(key)));\n });\n\n/**\n * scrypt (N=2^15, r=8, p=1), a 16-byte salt, stored as `scrypt$N$r$p$salt$hash` (base64url). These are the parameters of the copies\n * the products carried (Yomizaka, Akinaza, Kachizaka, Yororis): a hash they stored verifies here, and one made here verifies there.\n */\n// @fixed: the cost of the algorithm is part of the stored format; changing it is a new scheme, not a setting\nconst N = 32768;\nconst R = 8;\nconst P = 1;\nconst KEYLEN = 32;\nconst MAXMEM = 64 * 1024 * 1024;\nconst OPTIONS = { N, r: R, p: P, maxmem: MAXMEM };\n\n/** The shortest password the products accept. */\n// @fixed: a security floor shared by every product, not a business parameter\nexport const PASSWORD_MIN_LENGTH = 12;\n/** The longest: a longer one is refused before any work is done (a very long password is a way to make the server spend time). */\n// @fixed: bounds the work a request can make the server do\nexport const PASSWORD_MAX_LENGTH = 256;\n\n/** Why a new password is refused, or null when its length is acceptable. */\nexport function passwordProblem(password: string): \"TOO_SHORT\" | \"TOO_LONG\" | null {\n if (password.length < PASSWORD_MIN_LENGTH) return \"TOO_SHORT\";\n if (password.length > PASSWORD_MAX_LENGTH) return \"TOO_LONG\";\n return null;\n}\n\n/**\n * Hashes a password with a fresh salt.\n * @returns `scrypt$N$r$p$salt$hash`\n */\nexport async function hashPassword(password: string): Promise<string> {\n const salt = crypto.randomBytes(16);\n const hash = await scrypt(password, salt, KEYLEN, OPTIONS);\n return `scrypt$${N}$${R}$${P}$${salt.toString(\"base64url\")}$${hash.toString(\"base64url\")}`;\n}\n\n/**\n * Checks a password against a stored hash, in constant time. A hash of another scheme, a malformed one or an over-long password is `false`.\n * The cost parameters are read from the stored value, so an older hash still verifies after the default changes.\n */\nexport async function verifyPassword(password: string, stored: string): Promise<boolean> {\n const [scheme, n, r, p, salt, hash] = stored.split(\"$\");\n if (scheme !== \"scrypt\" || !salt || !hash || password.length > PASSWORD_MAX_LENGTH) return false;\n const expected = Buffer.from(hash, \"base64url\");\n const given = await scrypt(password, Buffer.from(salt, \"base64url\"), expected.length, { N: Number(n), r: Number(r), p: Number(p), maxmem: MAXMEM });\n return given.length === expected.length && crypto.timingSafeEqual(given, expected);\n}\n\nlet decoy: Promise<string> | undefined;\n/** A hash to verify against when the address has no account: the same work, the same time, the same answer. */\nexport const decoyHash = (): Promise<string> => (decoy ??= hashPassword(crypto.randomBytes(24).toString(\"base64url\")));\n","import crypto from \"node:crypto\";\n\nimport type { Query } from \"@krizaka/db\";\nimport { addHours } from \"date-fns\";\n\nimport { can, type RoleModel,ROLES_CODE, RolesError } from \"./roles-model\";\n\nexport { can, defineRoles, type RoleModel, ROLES_CODE, type RolesCode, RolesError } from \"./roles-model\";\n\n/** The SQL executor the roles take: `@krizaka/db`'s `Query`. */\nexport type RolesQuery = Query;\n\nexport interface RolesDeps<Role extends string, Permission extends string> {\n query: RolesQuery;\n model: RoleModel<Role, Permission>;\n /** The invitation link's token prefix (`ai` → `ai1.<43>`) and how the product keeps a token (its keyed hash). */\n tokenPrefix: string;\n tokenHash: (token: string) => string;\n /** Hours an invitation stays valid. */\n inviteTtlHours: number;\n token?: () => string;\n}\n\nexport interface Member<Role extends string> {\n accountId: string;\n email: string;\n name: string | null;\n role: Role;\n since: Date;\n}\nexport interface Invitation<Role extends string> {\n id: string;\n email: string;\n role: Role;\n expiresAt: Date;\n createdAt: Date;\n}\n\n/** Who may do what in a scope, over the product's PostgreSQL. */\nexport function createRoles<Role extends string, Permission extends string>(deps: RolesDeps<Role, Permission>) {\n const { query, model } = deps;\n const known = (role: string): role is Role => (model.roles as readonly string[]).includes(role);\n const mustKnow = (role: string): Role => {\n if (!known(role)) throw new RolesError(ROLES_CODE.unknownRole);\n return role;\n };\n const newToken = deps.token ?? (() => `${deps.tokenPrefix}1.${crypto.randomBytes(32).toString(\"base64url\")}`);\n const owners = (scopeId: string) => query<{ account_id: string }>(\"SELECT account_id FROM memberships WHERE scope_id = $1 AND role = $2\", [scopeId, ownerRole()]);\n /** The role that cannot disappear: the first of the model that manages every role. */\n const ownerRole = (): Role => model.roles.find((r) => model.roles.every((x) => model.manages[r].includes(x) || x === r)) ?? model.roles[0]!;\n\n async function roleOf(accountId: string, scopeId: string): Promise<Role | null> {\n const [row] = await query<{ role: Role }>(\"SELECT role FROM memberships WHERE scope_id = $1 AND account_id = $2\", [scopeId, accountId]);\n return row?.role ?? null;\n }\n\n return {\n ownerRole,\n roleOf,\n\n /** Every scope the person belongs to, with their role in it. */\n async scopesOf(accountId: string): Promise<{ scopeId: string; role: Role }[]> {\n return (await query<{ scope_id: string; role: Role }>(\"SELECT scope_id, role FROM memberships WHERE account_id = $1 ORDER BY created_at\", [accountId])).map((r) => ({ scopeId: r.scope_id, role: r.role }));\n },\n\n /** The person's role in the scope if it holds the permission; otherwise `NOT_A_MEMBER` (404: nothing tells the scope exists) or `FORBIDDEN`. */\n async authorize(accountId: string, scopeId: string, permission: Permission): Promise<Role> {\n const role = await roleOf(accountId, scopeId);\n if (!role) throw new RolesError(ROLES_CODE.notMember);\n if (!can(model, role, permission)) throw new RolesError(ROLES_CODE.forbidden);\n return role;\n },\n\n /** Puts a person in a scope with a role (changing it if they are there): for a first owner, a seed, an accepted invitation. */\n async grant(scopeId: string, accountId: string, role: string, invitedBy: string | null, now: Date): Promise<void> {\n mustKnow(role);\n await query(\n \"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role\",\n [scopeId, accountId, role, invitedBy, now],\n );\n },\n\n async members(scopeId: string): Promise<Member<Role>[]> {\n const rows = await query<{ account_id: string; email: string; name: string | null; role: Role; created_at: Date }>(\n \"SELECT m.account_id, a.email, a.name, m.role, m.created_at FROM memberships m JOIN accounts a ON a.id = m.account_id WHERE m.scope_id = $1 ORDER BY m.created_at\",\n [scopeId],\n );\n return rows.map((r) => ({ accountId: r.account_id, email: r.email, name: r.name, role: r.role, since: r.created_at }));\n },\n\n /** Changes someone's role. The actor must manage both the current and the new role; the last owner can never be demoted. */\n async setRole(scopeId: string, actor: { id: string }, target: string, role: string): Promise<void> {\n mustKnow(role);\n const mine = await roleOf(actor.id, scopeId);\n const current = await roleOf(target, scopeId);\n if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);\n if (!model.manages[mine].includes(current) || !model.manages[mine].includes(role as Role)) throw new RolesError(ROLES_CODE.notAllowed);\n if (current === ownerRole() && role !== current && (await owners(scopeId)).length <= 1) throw new RolesError(ROLES_CODE.lastOwner);\n await query(\"UPDATE memberships SET role = $3 WHERE scope_id = $1 AND account_id = $2\", [scopeId, target, role]);\n },\n\n /** Removes someone from the scope (or leaves it, when the target is the actor). The last owner cannot go. */\n async remove(scopeId: string, actor: { id: string }, target: string): Promise<void> {\n const mine = await roleOf(actor.id, scopeId);\n const current = await roleOf(target, scopeId);\n if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);\n if (actor.id !== target && !model.manages[mine].includes(current)) throw new RolesError(ROLES_CODE.notAllowed);\n if (current === ownerRole() && (await owners(scopeId)).length <= 1) throw new RolesError(ROLES_CODE.lastOwner);\n await query(\"DELETE FROM memberships WHERE scope_id = $1 AND account_id = $2\", [scopeId, target]);\n },\n\n /** Invites an e-mail address with a role the actor manages. The token is in the answer once (the product mails it); only its hash is kept. A new invitation for the same address replaces the pending one. */\n async invite(scopeId: string, actor: { id: string }, input: { email: string; role: string }, now: Date): Promise<{ token: string; invitation: Invitation<Role> }> {\n const role = mustKnow(input.role);\n const mine = await roleOf(actor.id, scopeId);\n if (!mine) throw new RolesError(ROLES_CODE.notMember);\n if (!model.manages[mine].includes(role)) throw new RolesError(ROLES_CODE.notAllowed);\n const email = input.email.trim().toLowerCase();\n await query(\"UPDATE invitations SET used_at = $3 WHERE scope_id = $1 AND email = $2 AND used_at IS NULL\", [scopeId, email, now]);\n const token = newToken();\n const [row] = await query<{ id: string; created_at: Date; expires_at: Date }>(\n \"INSERT INTO invitations (id, scope_id, email, role, token_hash, invited_by, created_at, expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, created_at, expires_at\",\n [crypto.randomUUID(), scopeId, email, role, deps.tokenHash(token), actor.id, now, addHours(now, deps.inviteTtlHours)],\n );\n return { token, invitation: { id: row!.id, email, role, createdAt: row!.created_at, expiresAt: row!.expires_at } };\n },\n\n async pendingInvitations(scopeId: string, now: Date): Promise<Invitation<Role>[]> {\n const rows = await query<{ id: string; email: string; role: Role; created_at: Date; expires_at: Date }>(\"SELECT id, email, role, created_at, expires_at FROM invitations WHERE scope_id = $1 AND used_at IS NULL AND expires_at > $2 ORDER BY created_at\", [scopeId, now]);\n return rows.map((r) => ({ id: r.id, email: r.email, role: r.role, createdAt: r.created_at, expiresAt: r.expires_at }));\n },\n\n async revokeInvitation(scopeId: string, actor: { id: string }, invitationId: string, now: Date): Promise<void> {\n const mine = await roleOf(actor.id, scopeId);\n if (!mine) throw new RolesError(ROLES_CODE.notMember);\n const [row] = await query<{ role: Role }>(\"SELECT role FROM invitations WHERE id = $1 AND scope_id = $2 AND used_at IS NULL\", [invitationId, scopeId]);\n if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);\n if (!model.manages[mine].includes(row.role)) throw new RolesError(ROLES_CODE.notAllowed);\n await query(\"UPDATE invitations SET used_at = $2 WHERE id = $1\", [invitationId, now]);\n },\n\n /** The signed-in account takes the invitation: it must have been sent to this account's address; the link works once and expires. */\n async acceptInvitation(token: string, account: { id: string; email: string }, now: Date): Promise<{ scopeId: string; role: Role }> {\n const [row] = await query<{ id: string; scope_id: string; email: string; role: Role; invited_by: string | null }>(\n \"SELECT id, scope_id, email, role, invited_by FROM invitations WHERE token_hash = $1 AND used_at IS NULL AND expires_at > $2\",\n [deps.tokenHash(token), now],\n );\n if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);\n if (row.email !== account.email.trim().toLowerCase()) throw new RolesError(ROLES_CODE.inviteWrongAccount);\n await query(\"UPDATE invitations SET used_at = $2 WHERE id = $1\", [row.id, now]);\n const current = await roleOf(account.id, row.scope_id);\n // already in: keep the higher role (an invitation never demotes)\n if (!current || (model.manages[current].length < model.manages[row.role].length)) await query(\"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role\", [row.scope_id, account.id, row.role, row.invited_by, now]);\n return { scopeId: row.scope_id, role: (!current || model.manages[current].length < model.manages[row.role].length ? row.role : current) as Role };\n },\n };\n}\nexport type Roles<Role extends string = string, Permission extends string = string> = ReturnType<typeof createRoles<Role, Permission>>;\n","import crypto from \"node:crypto\";\n\nimport type { Clock } from \"@krizaka/db\";\n\n/**\n * Web sessions (the copies each product carried: Yomizaka `ys1.`, Akinaza `as1.`, Kachizaka `ks1.`). The cookie holds a random token\n * (`<prefix>1.` and 32 bytes); the store keeps only its keyed hash, so a leaked table opens nothing. The account is re-read on every\n * request (a suspension applies at once). The lifetime is the setting `auth.sessionDays`.\n */\n\n/** A live session and the account it signs in. `Account` is the product's own shape (id, e-mail, role, locale, name…). */\nexport interface Session<Account> {\n id: string;\n account: Account;\n}\n\n/** What a store keeps for a new session. */\nexport interface NewSession {\n accountId: string;\n tokenHash: string;\n createdAt: Date;\n expiresAt: Date;\n ip: string | null;\n userAgent: string | null;\n}\n\n/** Where sessions live. Adapters: the PostgreSQL store over the product's `sessions` table, and a memory one. */\nexport interface SessionStore<Account> {\n insert(session: NewSession): Promise<void>;\n /** The session of this hash, when it has not expired at `now` and its account is active; null otherwise. */\n find(tokenHash: string, now: Date): Promise<Session<Account> | null>;\n delete(tokenHash: string): Promise<void>;\n}\n\nexport interface SessionsDeps<Account> {\n store: SessionStore<Account>;\n clock: Clock;\n /** The product's token letters: `ys` makes `ys1.<43 characters>`. Lower-case letters, 1 to 4. */\n tokenPrefix: string;\n /** What keys the stored hash (`AUTH_SESSION_SECRET`). A function lets the product read its environment when it is needed. */\n secret: string | (() => string);\n /** Days a new session lives: the setting `auth.sessionDays`, read for each new session. */\n sessionDays: number | (() => number | Promise<number>);\n}\n\nexport interface Sessions<Account> {\n /** A fresh token: shaped `<prefix>1.<43>`, random, never stored (only its hash is). */\n newToken(): string;\n isToken(value: string | undefined): value is string;\n /** The keyed hash the store keeps for a token. */\n tokenHash(token: string): string;\n /** Opens a session: the token for the cookie (shown once) and when it expires. */\n create(accountId: string, meta: { ip: string | null; userAgent: string | null }): Promise<{ token: string; expires: Date }>;\n /** The session a token opens, or null (unknown, malformed, expired, account not active). */\n resolve(token: string | undefined): Promise<Session<Account> | null>;\n /** Ends the session of this token. A malformed token is ignored. */\n revoke(token: string | undefined): Promise<void>;\n}\n\nconst BODY = /^[A-Za-z0-9_-]{43}$/;\nconst PREFIX = /^[a-z]{1,4}$/;\nconst USER_AGENT_MAX = 300;\n\n/**\n * The sessions service of a product.\n * @param deps the store, the clock, the token letters, the secret and the lifetime\n * @throws RangeError for a token prefix that is not 1 to 4 lower-case letters, or a lifetime that is not a whole number of days from 1\n */\nexport function createSessions<Account>(deps: SessionsDeps<Account>): Sessions<Account> {\n if (!PREFIX.test(deps.tokenPrefix)) throw new RangeError(`tokenPrefix must be 1 to 4 lower-case letters, got ${deps.tokenPrefix}`);\n const head = `${deps.tokenPrefix}1.`;\n const secret = () => (typeof deps.secret === \"function\" ? deps.secret() : deps.secret);\n const isToken = (value: string | undefined): value is string => !!value && value.startsWith(head) && BODY.test(value.slice(head.length));\n const tokenHash = (token: string) => crypto.createHmac(\"sha256\", `session:${secret()}`).update(token).digest(\"hex\");\n const newToken = () => `${head}${crypto.randomBytes(32).toString(\"base64url\")}`;\n return {\n newToken,\n isToken,\n tokenHash,\n async create(accountId, meta) {\n const days = typeof deps.sessionDays === \"function\" ? await deps.sessionDays() : deps.sessionDays;\n if (!Number.isInteger(days) || days < 1) throw new RangeError(`sessionDays must be a whole number of days from 1, got ${days}`);\n const token = newToken();\n const createdAt = deps.clock.now();\n // days of 24 hours, not calendar days: the same instant whatever the server's time zone (the copies added 86 400 000 ms a day)\n const expires = new Date(createdAt);\n expires.setUTCHours(expires.getUTCHours() + days * 24);\n await deps.store.insert({ accountId, tokenHash: tokenHash(token), createdAt, expiresAt: expires, ip: meta.ip, userAgent: meta.userAgent?.slice(0, USER_AGENT_MAX) ?? null });\n return { token, expires };\n },\n async resolve(token) {\n if (!isToken(token)) return null;\n return deps.store.find(tokenHash(token), deps.clock.now());\n },\n async revoke(token) {\n if (!isToken(token)) return;\n await deps.store.delete(tokenHash(token));\n },\n };\n}\n\n/** The attributes of the session cookie, for the product's framework (`cookies().set(cookie)`, `NextResponse.cookies.set`…). */\nexport interface SessionCookie {\n name: string;\n value: string;\n httpOnly: true;\n secure: boolean;\n sameSite: \"lax\";\n path: \"/\";\n expires: Date;\n}\n\n/**\n * The session cookie: HttpOnly, SameSite=Lax, on the whole site, `Secure` where the product says (production).\n * @param options the cookie's name (`yomizaka_session`) and whether it is `Secure`\n */\nexport function sessionCookie(token: string, expires: Date, options: { name: string; secure: boolean }): SessionCookie {\n return { name: options.name, value: token, httpOnly: true, secure: options.secure, sameSite: \"lax\", path: \"/\", expires };\n}\n\n/** The same cookie, expired now: what signing out sets. */\nexport function clearedSessionCookie(options: { name: string; secure: boolean }, now: Date): SessionCookie {\n return sessionCookie(\"\", now, options);\n}\n\n/**\n * The session token of a request: the native apps' `Authorization: Bearer` (which wins over a stale cookie), else the web's cookie.\n * @param headers the request's headers\n * @param options the cookie's name; `bearer: false` for a product with no native app\n * @returns the raw token (not yet checked), or undefined\n */\nexport function sessionTokenOf(headers: Headers, options: { cookie: string; bearer?: boolean }): string | undefined {\n if (options.bearer !== false) {\n const bearer = /^bearer (\\S+)$/i.exec(headers.get(\"authorization\") ?? \"\")?.[1];\n if (bearer) return bearer;\n }\n const prefix = `${options.cookie}=`;\n return headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix))\n ?.slice(prefix.length);\n}\n","import type { NewSession, Session, SessionStore } from \"./sessions\";\n\n/**\n * An in-memory session store, for unit tests and demos. `accountOf` plays the accounts table: it answers the account of an id, or null\n * when it does not exist or is not active.\n */\nexport function memorySessionStore<Account>(accountOf: (accountId: string) => Account | null): SessionStore<Account> & { rows(): readonly NewSession[] } {\n const rows = new Map<string, NewSession & { id: string }>();\n let next = 0;\n return {\n async insert(session) {\n if (rows.has(session.tokenHash)) throw new Error(\"duplicate session token hash\");\n next += 1;\n rows.set(session.tokenHash, { ...session, id: `session-${next}` });\n },\n async find(tokenHash, now): Promise<Session<Account> | null> {\n const row = rows.get(tokenHash);\n if (!row || row.expiresAt.getTime() <= now.getTime()) return null;\n const account = accountOf(row.accountId);\n return account === null ? null : { id: row.id, account };\n },\n async delete(tokenHash) {\n rows.delete(tokenHash);\n },\n rows: () => [...rows.values()],\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { Session, SessionStore } from \"./sessions\";\n\nexport interface DbSessionStoreOptions<Account> {\n /** The product's session table. Default `sessions` (`id`, `account_id`, `token_hash` unique, `created_at`, `expires_at`, `ip`, `user_agent`). */\n sessions?: string;\n /** The product's account table. Default `accounts`. */\n accounts?: string;\n /** The account columns the session carries (`id`, `email`, `role`, `locale`, `name`…): all checked, all read in one query with the session. */\n columns: readonly string[];\n /** Builds the product's account from a row holding exactly `columns`. */\n toAccount: (row: Record<string, unknown>) => Account;\n /** An account that is not active signs nobody in (a suspension applies at once): the column and the value it must have (`status` = `ACTIVE`). */\n active?: { column: string; equals: string };\n}\n\n/**\n * The session store over the product's own tables (`sessions` joined to `accounts`): the declared tables and columns are checked by\n * `ident()` and nothing else reaches SQL. The expiry is compared with the clock's `now`, not the database's.\n * @param query the product's query\n * @param options the table names, the account columns and how the account is built\n * @throws DbError `DB_UNSAFE_IDENTIFIER` for a table or column name that is not a safe identifier\n */\nexport function dbSessionStore<Account>(query: Query, options: DbSessionStoreOptions<Account>): SessionStore<Account> {\n const sessions = ident(options.sessions ?? \"sessions\");\n const accounts = ident(options.accounts ?? \"accounts\");\n const columns = options.columns.map((column) => `a.${ident(column)}`).join(\", \");\n const active = options.active ? ` AND a.${ident(options.active.column)} = $3` : \"\";\n return {\n async insert(session) {\n await query(`INSERT INTO ${sessions} (account_id, token_hash, created_at, expires_at, ip, user_agent) VALUES ($1, $2, $3, $4, $5, $6)`, [session.accountId, session.tokenHash, session.createdAt, session.expiresAt, session.ip, session.userAgent]);\n },\n async find(tokenHash, now): Promise<Session<Account> | null> {\n const params: unknown[] = [tokenHash, now];\n if (options.active) params.push(options.active.equals);\n const [row] = await query<Record<string, unknown> & { session_id: string }>(\n `SELECT s.id AS session_id, ${columns} FROM ${sessions} s JOIN ${accounts} a ON a.id = s.account_id WHERE s.token_hash = $1 AND s.expires_at > $2${active}`,\n params,\n );\n if (!row) return null;\n const { session_id: id, ...account } = row;\n return { id, account: options.toAccount(account) };\n },\n async delete(tokenHash) {\n await query(`DELETE FROM ${sessions} WHERE token_hash = $1`, [tokenHash]);\n },\n };\n}\n","import { type CompleteOptions, type ExternalIdentity, type FederatedProvider, FEDERATION_CODE, FederationError, type IdentityProvider, isFederatedProvider, isLocalReturn, type StartedSignIn, type StartOptions } from \"./federation\";\n\n/** The `fetch` the adapter calls krizaka-users with (injected: no global, no network in tests). */\nexport type Fetcher = (url: string, init: { method: \"POST\"; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;\n\nexport interface UsersFederationOptions {\n /** The tenant host of the product: `https://auth.dev.akinaza.com`. */\n baseUrl: string;\n /** The product's public address: the start URL sends the person back to it, so `returnTo` is absolute from it. */\n appUrl: string;\n fetch: Fetcher;\n}\n\nconst START = (base: string, provider: FederatedProvider) => `${base}/api/v1/auth/web/${provider}/start`;\nconst EXCHANGE = (base: string) => `${base}/api/v1/auth/web/exchange`;\n\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Reads krizaka-users' answer into an identity; anything that is not a complete identity is refused. */\nexport function parseExternalIdentity(body: unknown): ExternalIdentity {\n const o = (body ?? {}) as Record<string, unknown>;\n const issuer = text(o.issuer);\n const subject = text(o.subject);\n if (!issuer || !subject) throw new FederationError(FEDERATION_CODE.unavailable, \"krizaka-users answered without an issuer and a subject\");\n return { issuer, subject, email: text(o.email), emailVerified: o.email_verified === true, name: text(o.name) };\n}\n\n/**\n * The adapter for krizaka-users (`auth.<product>` tenant host, krizaka/krizaka-users#31): `start` builds the tenant's start address,\n * `complete` exchanges the one-time code (and the PKCE verifier of a native app) for the verified identity.\n */\nexport function usersIdentityProvider({ baseUrl, appUrl, fetch }: UsersFederationOptions): IdentityProvider {\n const base = baseUrl.replace(/\\/+$/, \"\");\n const app = appUrl.replace(/\\/+$/, \"\");\n return {\n async start(provider, returnTo, options: StartOptions = {}): Promise<StartedSignIn> {\n if (!isFederatedProvider(provider)) throw new FederationError(FEDERATION_CODE.unknownProvider, `Unknown provider ${String(provider)}`);\n if (!isLocalReturn(returnTo)) throw new FederationError(FEDERATION_CODE.badReturn, \"That return address is not allowed\");\n const state = crypto.randomUUID();\n const query = new URLSearchParams({ return_to: `${app}${returnTo}`, state });\n if (options.codeChallenge) {\n query.set(\"code_challenge\", options.codeChallenge);\n query.set(\"code_challenge_method\", \"S256\");\n }\n return { url: `${START(base, provider)}?${query}`, state };\n },\n async complete(code, options: CompleteOptions = {}) {\n const response = await fetch(EXCHANGE(base), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ code, ...(options.codeVerifier ? { code_verifier: options.codeVerifier } : {}) }),\n });\n if (response.status === 400 || response.status === 401 || response.status === 404 || response.status === 410) throw new FederationError(FEDERATION_CODE.invalidCode, \"That code is not valid\");\n if (!response.ok) throw new FederationError(FEDERATION_CODE.unavailable, `krizaka-users answered ${response.status}`);\n return parseExternalIdentity(await response.json());\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOO,IAAM,gBAAgB;AAAA,EAC3B,iBAAiB;AAAA,EACjB,WAAW;AAAA,EACX,cAAc;AAAA,EACd,UAAU;AACZ;AAYO,SAAS,WAAW,MAAyB,SAA4D;AAC9G,MAAI,KAAK,SAAS,EAAG,QAAO;AAC5B,SAAO,QAAQ,aAAa,CAAC,IAAI;AACnC;AAGO,SAAS,UAAU,IAAmB,SAA4C;AACvF,MAAI,YAAY,KAAM,QAAO;AAC7B,SAAO,CAAC,CAAC,MAAM,QAAQ,SAAS,EAAE;AACpC;AAmBO,SAAS,aAAa,OAAsC;AACjE,QAAM,OAAO,MAAM,YAAY;AAC/B,QAAM,SAAS,CAAC,QAAmB,SAAuC,OAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,MAAM,cAAc,SAAS,IAAI,EAAE,IAAI,OAAO,QAAQ,KAAK;AACtK,MAAI,CAAC,MAAM,QAAS,QAAO,OAAO,KAAK,cAAc,eAAe;AACpE,MAAI,MAAM,QAAQ,QAAQ,UAAU,MAAM,QAAQ,SAAU,QAAO,OAAO,KAAK,cAAc,SAAS;AACtG,MAAI,CAAC,UAAU,MAAM,IAAI,MAAM,UAAU,EAAG,QAAO,OAAO,KAAK,cAAc,YAAY;AACzF,SAAO,EAAE,IAAI,KAAK;AACpB;;;ACnDA,IAAM,OAAO;AACb,IAAM,OAAO;AACb,SAAS,KAAK,OAAwB;AACpC,SAAQ,KAAK,KAAK,KAAK,KAAK,MAAM,MAAM,GAAG,EAAE,MAAM,CAAC,MAAM,OAAO,CAAC,KAAK,GAAG,KAAO,MAAM,SAAS,GAAG,KAAK,KAAK,KAAK,KAAK;AACzH;AAeO,SAAS,SAAS,SAAkB,QAAuB,CAAC,GAAkB;AACnF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AgB,WAAW,oCAAoC;AACvH,YAAM,QAAQ,OAAO,WAAW;AAChC,YAAM,QAAQ,IAAI,gBAAgB,EAAE,WAAW,GAAG,GAAG,GAAG,QAAQ,IAAI,MAAM,CAAC;AAC3E,UAAI,QAAQ,eAAe;AACzB,cAAM,IAAI,kBAAkB,QAAQ,aAAa;AACjD,cAAM,IAAI,yBAAyB,MAAM;AAAA,MAC3C;AACA,aAAO,EAAE,KAAK,GAAG,MAAM,MAAM,QAAQ,CAAC,IAAI,KAAK,IAAI,MAAM;AAAA,IAC3D;AAAA,IACA,MAAM,SAAS,MAAM,UAA2B,CAAC,GAAG;AAClD,YAAM,WAAW,MAAM,MAAM,SAAS,IAAI,GAAG;AAAA,QAC3C,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,QAC9C,MAAM,KAAK,UAAU,EAAE,MAAM,GAAI,QAAQ,eAAe,EAAE,eAAe,QAAQ,aAAa,IAAI,CAAC,EAAG,CAAC;AAAA,MACzG,CAAC;AACD,UAAI,SAAS,WAAW,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,IAAK,OAAM,IAAI,gBAAgB,gBAAgB,aAAa,wBAAwB;AAC7L,UAAI,CAAC,SAAS,GAAI,OAAM,IAAI,gBAAgB,gBAAgB,aAAa,0BAA0B,SAAS,MAAM,EAAE;AACpH,aAAO,sBAAsB,MAAM,SAAS,KAAK,CAAC;AAAA,IACpD;AAAA,EACF;AACF;","names":["crypto","crypto","crypto","crypto","ident"]}
|
|
1
|
+
{"version":3,"sources":["../src/admin-gate.ts","../src/client-ip.ts","../src/federated-sign-in.ts","../src/landing.ts","../src/migration.ts","../src/password.ts","../src/roles.ts","../src/sessions.ts","../src/sessions-memory.ts","../src/sessions-persistence.ts","../src/users-federation.ts"],"sourcesContent":["/**\n * The administration's locks, as one pure decision every product shares (it was copied in each product's `lib/access.ts`): a session,\n * the ADMIN role, and an address on the allowed list. A pure function of its inputs: the product reads the session and the address\n * and maps the verdict to its own answer.\n */\n\n/** Stable codes of a refusal. */\nexport const ADMIN_REFUSAL = {\n unauthenticated: \"UNAUTHENTICATED\",\n forbidden: \"FORBIDDEN\",\n ipNotAllowed: \"IP_NOT_ALLOWED\",\n notFound: \"NOT_FOUND\",\n} as const;\nexport type AdminRefusal = (typeof ADMIN_REFUSAL)[keyof typeof ADMIN_REFUSAL];\n\n/** The verdict: let in, or the status and code to answer. */\nexport type AdminDecision = { ok: true } | { ok: false; status: 401 | 403 | 404; code: AdminRefusal };\n\n/**\n * The list the administration's address lock reads, from the environment's value (`AUTH_ALLOWED_IPS`): an empty list is « nobody » in\n * production and « anybody » in development, so a forgotten setting never opens the console.\n * @param list the configured addresses\n * @returns the list to hand to `requireAdmin`, or null (anybody)\n */\nexport function allowedIps(list: readonly string[], options: { production: boolean }): readonly string[] | null {\n if (list.length > 0) return list;\n return options.production ? [] : null;\n}\n\n/** Whether an address may use the administration: `null` allowed means anybody, an empty list nobody, and a missing address is never allowed by a list. */\nexport function ipAllowed(ip: string | null, allowed: readonly string[] | null): boolean {\n if (allowed === null) return true;\n return !!ip && allowed.includes(ip);\n}\n\nexport interface AdminGateInput {\n /** The caller's session, or null when there is none. Only its account's role is read. */\n session: { account: { role: string } } | null;\n /** The caller's address (see `clientIp`). */\n ip: string | null;\n /** The addresses allowed (see `allowedIps`); null = anybody. */\n allowedIps: readonly string[] | null;\n /** `api` (default): 401 without a session, 403 with the reason. `page`: the administration does not announce itself, so every failed lock is a 404. */\n surface?: \"api\" | \"page\";\n /** The role that administers. Default `ADMIN`. */\n role?: string;\n}\n\n/**\n * The administration's three locks. The first that fails decides.\n * @returns `{ ok: true }`, or the status (401, 403 or 404 on a page) and the code to answer\n */\nexport function requireAdmin(input: AdminGateInput): AdminDecision {\n const page = input.surface === \"page\";\n const refuse = (status: 401 | 403, code: AdminRefusal): AdminDecision => (page ? { ok: false, status: 404, code: ADMIN_REFUSAL.notFound } : { ok: false, status, code });\n if (!input.session) return refuse(401, ADMIN_REFUSAL.unauthenticated);\n if (input.session.account.role !== (input.role ?? \"ADMIN\")) return refuse(403, ADMIN_REFUSAL.forbidden);\n if (!ipAllowed(input.ip, input.allowedIps)) return refuse(403, ADMIN_REFUSAL.ipNotAllowed);\n return { ok: true };\n}\n","/** How a deployment tells the client's address: the header its edge sets, and how many proxies append to `X-Forwarded-For`. */\nexport interface ClientIpRules {\n /** A header the edge sets and overwrites with the client's address (`do-connecting-ip` on DigitalOcean App Platform, `cf-connecting-ip` behind Cloudflare). Read first when present. */\n header?: string | undefined;\n /** How many trusted proxies append to `X-Forwarded-For`: 1 (the default) to 10. */\n trustedProxyHops?: number | undefined;\n}\n\nconst IPV4 = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\nconst IPV6 = /^[0-9a-f:]+(?:%\\w+)?$/i;\nfunction isIp(value: string): boolean {\n return (IPV4.test(value) && value.split(\".\").every((n) => Number(n) <= 255)) || (value.includes(\":\") && IPV6.test(value));\n}\n\n/**\n * The client's IP address, as far as this deployment can trust it. `X-Forwarded-For` is a list each proxy appends to: its LEFT end is\n * whatever the client sent (anyone can write `X-Forwarded-For: 1.2.3.4`), so a limit keyed on it is a limit the attacker chooses. The\n * address the last trusted proxy saw is read from the RIGHT:\n *\n * - the `header` the edge sets and overwrites, when present;\n * - otherwise the entry `trustedProxyHops` (default 1: one proxy) from the right of `X-Forwarded-For`, then `X-Real-IP`;\n * - otherwise null (local development without a proxy).\n *\n * The product reads its environment (`ABUSE_CLIENT_IP_HEADER`, `ABUSE_TRUSTED_PROXY_HOPS`) and passes the values: this function reads none.\n * @param headers the request's headers\n * @returns a valid IPv4 or IPv6 address, or null\n */\nexport function clientIp(headers: Headers, rules: ClientIpRules = {}): string | null {\n const custom = rules.header?.trim().toLowerCase();\n if (custom) {\n const value = headers.get(custom)?.split(\",\")[0]?.trim();\n if (value && isIp(value)) return value;\n }\n const hops = Math.max(1, Math.min(10, Number(rules.trustedProxyHops) || 1));\n const chain = (headers.get(\"x-forwarded-for\") ?? \"\")\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean);\n const fromRight = chain[chain.length - hops];\n if (fromRight && isIp(fromRight)) return fromRight;\n const real = headers.get(\"x-real-ip\")?.trim();\n if (real && isIp(real)) return real;\n return null;\n}\n","import type { ExternalIdentity } from \"./federation\";\nimport type { IdentityLinkStore } from \"./identity-links\";\n\n/** What federated sign-in needs from the product's accounts: no second user table, just a look-up and, when registration is open, a creation. */\nexport interface FederatedAccounts {\n /** The account that holds this address (lower case), and whether the product has verified it; null when none. */\n findByEmail(email: string): Promise<{ id: string; emailVerified: boolean } | null>;\n /** Creates an account for a person the provider vouches for (address verified, no password). Absent when registration is closed. */\n create?(identity: ExternalIdentity & { email: string }): Promise<string>;\n}\n\n/** Why a sign-in was refused: a stable code the product maps to its words. */\nexport const FEDERATED_REFUSAL = {\n /** The provider did not verify the address (or gave none): nothing is linked, nothing is created. */\n emailNotVerified: \"EMAIL_NOT_VERIFIED\",\n /** An account holds the address but the product never verified it: linking would let a stranger take it over. */\n accountEmailUnverified: \"ACCOUNT_EMAIL_UNVERIFIED\",\n /** No account, and registration is closed. */\n noAccount: \"NO_ACCOUNT\",\n} as const;\nexport type FederatedRefusal = (typeof FEDERATED_REFUSAL)[keyof typeof FEDERATED_REFUSAL];\n\nexport type FederatedSignInResult =\n /** `via`: `link` already linked, `linked` attached to the account of that address now, `created` a new account. */\n | { status: \"signed-in\"; accountId: string; via: \"link\" | \"linked\" | \"created\" }\n | { status: \"refused\"; code: FederatedRefusal };\n\nexport interface FederatedSignInDeps {\n links: IdentityLinkStore;\n accounts: FederatedAccounts;\n clock: { now(): Date };\n}\n\n/**\n * From a verified external identity to an account of the product. The rule that matters: an identity attaches to an EXISTING account\n * only when the address is verified on both sides — by the provider and by the product. Otherwise a stranger who registers at\n * Facebook with your address would sign in as you.\n */\nexport function createFederatedSignIn({ links, accounts, clock }: FederatedSignInDeps) {\n return {\n async signIn(identity: ExternalIdentity): Promise<FederatedSignInResult> {\n const known = await links.find(identity.issuer, identity.subject);\n if (known) return { status: \"signed-in\", accountId: known, via: \"link\" };\n\n const email = identity.email?.trim().toLowerCase();\n if (!email || !identity.emailVerified) return { status: \"refused\", code: FEDERATED_REFUSAL.emailNotVerified };\n\n const existing = await accounts.findByEmail(email);\n if (existing) {\n if (!existing.emailVerified) return { status: \"refused\", code: FEDERATED_REFUSAL.accountEmailUnverified };\n await links.link(existing.id, identity.issuer, identity.subject, clock.now());\n return { status: \"signed-in\", accountId: existing.id, via: \"linked\" };\n }\n\n if (!accounts.create) return { status: \"refused\", code: FEDERATED_REFUSAL.noAccount };\n const accountId = await accounts.create({ ...identity, email });\n await links.link(accountId, identity.issuer, identity.subject, clock.now());\n return { status: \"signed-in\", accountId, via: \"created\" };\n },\n };\n}\n\nexport type FederatedSignIn = ReturnType<typeof createFederatedSignIn>;\n","// The two proxy-side rules of « a signed-in person never sees the public side » (krizaka-ui#827), the same for every\n// product. Web-standard Request/Response only (a Next.js `proxy.ts` calls them). The cookie is a HINT: its presence\n// decides a redirect and a placeholder, never an authorization — the page and the API still resolve the session.\n\n/** The readable flag the proxy keeps next to the HttpOnly session cookie: « a session cookie exists », value `1`, never the token. */\nexport const SESSION_HINT_COOKIE = \"kz-session\";\n\nconst cookieValue = (headers: Headers, name: string): string | undefined => {\n const prefix = `${name}=`;\n return headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix))\n ?.slice(prefix.length);\n};\n\n/** Where a signed-in visitor of the landing route goes. */\nexport interface LandingRule {\n /** The product's session cookie name (`yomizaka_session`). */\n cookie: string;\n /** The landing routes (`[\"/\", \"/fr\", \"/en\"]`): exact paths, a trailing slash tolerated. */\n landing: readonly string[];\n /** The signed-in start page, or a function of the request (the language of the address). */\n home: string | ((request: Request) => string);\n}\n\n// Linear on any input (a loop, not a `/\\/+$/` regular expression: CodeQL js/polynomial-redos on the request path).\nconst trimmed = (path: string) => {\n let end = path.length;\n while (end > 1 && path.charCodeAt(end - 1) === 47) end--;\n return path.slice(0, end);\n};\n\n/**\n * The landing route with a session cookie answers 307 to the home before any HTML: private, never stored, varying with the\n * cookie. `null` for everything else (a signed-out visitor, another page, a write).\n */\nexport function landingRedirect(request: Request, rule: LandingRule): Response | null {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return null;\n if (!cookieValue(request.headers, rule.cookie)) return null;\n const url = new URL(request.url);\n if (!rule.landing.some((path) => trimmed(path) === trimmed(url.pathname))) return null;\n const home = typeof rule.home === \"function\" ? rule.home(request) : rule.home;\n // Relative on purpose: behind a proxy or in CI `request.url` carries an internal scheme/host (https://localhost), and an absolute\n // Location would send the browser there. A relative Location keeps the origin the browser asked for.\n const target = new URL(home, url);\n return new Response(null, { status: 307, headers: { Location: `${target.pathname}${target.search}${target.hash}`, \"Cache-Control\": \"private, no-store\", Vary: \"Cookie\" } });\n}\n\n/**\n * Keeps the hint flag in step with the session cookie on any response (pages stay static: the proxy runs on every request,\n * the HTML is the same for everyone). Sets it when the session cookie exists, clears it when it is gone, else touches nothing.\n */\nexport function sessionHint<T extends Response>(response: T, request: Request, options: { cookie: string; secure: boolean }): T {\n const session = Boolean(cookieValue(request.headers, options.cookie));\n const flagged = cookieValue(request.headers, SESSION_HINT_COOKIE) === \"1\";\n const base = `${SESSION_HINT_COOKIE}=${session ? \"1\" : \"\"}; Path=/; SameSite=Lax${options.secure ? \"; Secure\" : \"\"}`;\n if (session && !flagged) response.headers.append(\"Set-Cookie\", base);\n else if (!session && cookieValue(request.headers, SESSION_HINT_COOKIE) !== undefined) response.headers.append(\"Set-Cookie\", `${base}; Max-Age=0`);\n return response;\n}\n","import { accountsSchema, rolesSchema } from \"./schema\";\n\nconst IDENT = /^[a-z_][a-z0-9_]{0,62}$/;\nconst ident = (name: string) => {\n if (!IDENT.test(name)) throw new Error(`not a safe SQL identifier: ${name}`);\n return name;\n};\n\n/**\n * The SQL of version 1 of the accounts tables, for a product that runs it by hand (idempotent).\n * @deprecated Use `accountsSchema` with `emitMigration` or `adoptMigration` from `@krizaka/db`: the SQL gets a version, a checksum and a marker. Removed in the next major.\n */\nexport function accountsMigration(options: { backfillVerified?: boolean } = {}): string {\n return accountsSchema(options).migrations[0]!.sql({ schema: \"public\", tables: { accounts: \"accounts\" } });\n}\n\n/**\n * The SQL of version 1 of the memberships and invitations tables, for a product that runs it by hand (idempotent).\n * @deprecated Use `rolesSchema` with `emitMigration` or `adoptMigration` from `@krizaka/db`. Removed in the next major.\n */\nexport function rolesMigration(roles: readonly string[], options: { ownerTable?: string; scopeTable?: string } = {}): string {\n const tables = { owner: ident(options.ownerTable ?? \"accounts\"), ...(options.scopeTable ? { scope: ident(options.scopeTable) } : {}) };\n return rolesSchema(roles, { scoped: options.scopeTable !== undefined }).migrations[0]!.sql({ schema: \"public\", tables });\n}\n","import crypto from \"node:crypto\";\n\n/** Called only when a password is hashed or checked: the module also loads in a browser bundle (the role model), where `crypto.scrypt` does not exist. */\nconst scrypt = (password: string, salt: Buffer, keylen: number, options: crypto.ScryptOptions): Promise<Buffer> =>\n new Promise((resolve, reject) => {\n crypto.scrypt(password, salt, keylen, options, (error, key) => (error ? reject(error) : resolve(key)));\n });\n\n/**\n * scrypt (N=2^15, r=8, p=1), a 16-byte salt, stored as `scrypt$N$r$p$salt$hash` (base64url). These are the parameters of the copies\n * the products carried (Yomizaka, Akinaza, Kachizaka, Yororis): a hash they stored verifies here, and one made here verifies there.\n */\n// @fixed: the cost of the algorithm is part of the stored format; changing it is a new scheme, not a setting\nconst N = 32768;\nconst R = 8;\nconst P = 1;\nconst KEYLEN = 32;\nconst MAXMEM = 64 * 1024 * 1024;\nconst OPTIONS = { N, r: R, p: P, maxmem: MAXMEM };\n\n/** The shortest password the products accept. */\n// @fixed: a security floor shared by every product, not a business parameter\nexport const PASSWORD_MIN_LENGTH = 12;\n/** The longest: a longer one is refused before any work is done (a very long password is a way to make the server spend time). */\n// @fixed: bounds the work a request can make the server do\nexport const PASSWORD_MAX_LENGTH = 256;\n\n/** Why a new password is refused, or null when its length is acceptable. */\nexport function passwordProblem(password: string): \"TOO_SHORT\" | \"TOO_LONG\" | null {\n if (password.length < PASSWORD_MIN_LENGTH) return \"TOO_SHORT\";\n if (password.length > PASSWORD_MAX_LENGTH) return \"TOO_LONG\";\n return null;\n}\n\n/**\n * Hashes a password with a fresh salt.\n * @returns `scrypt$N$r$p$salt$hash`\n */\nexport async function hashPassword(password: string): Promise<string> {\n const salt = crypto.randomBytes(16);\n const hash = await scrypt(password, salt, KEYLEN, OPTIONS);\n return `scrypt$${N}$${R}$${P}$${salt.toString(\"base64url\")}$${hash.toString(\"base64url\")}`;\n}\n\n/**\n * Checks a password against a stored hash, in constant time. A hash of another scheme, a malformed one or an over-long password is `false`.\n * The cost parameters are read from the stored value, so an older hash still verifies after the default changes.\n */\nexport async function verifyPassword(password: string, stored: string): Promise<boolean> {\n const [scheme, n, r, p, salt, hash] = stored.split(\"$\");\n if (scheme !== \"scrypt\" || !salt || !hash || password.length > PASSWORD_MAX_LENGTH) return false;\n const expected = Buffer.from(hash, \"base64url\");\n const given = await scrypt(password, Buffer.from(salt, \"base64url\"), expected.length, { N: Number(n), r: Number(r), p: Number(p), maxmem: MAXMEM });\n return given.length === expected.length && crypto.timingSafeEqual(given, expected);\n}\n\nlet decoy: Promise<string> | undefined;\n/** A hash to verify against when the address has no account: the same work, the same time, the same answer. */\nexport const decoyHash = (): Promise<string> => (decoy ??= hashPassword(crypto.randomBytes(24).toString(\"base64url\")));\n","import crypto from \"node:crypto\";\n\nimport type { Query } from \"@krizaka/db\";\nimport { addHours } from \"date-fns\";\n\nimport { can, type RoleModel,ROLES_CODE, RolesError } from \"./roles-model\";\n\nexport { can, defineRoles, type RoleModel, ROLES_CODE, type RolesCode, RolesError } from \"./roles-model\";\n\n/** The SQL executor the roles take: `@krizaka/db`'s `Query`. */\nexport type RolesQuery = Query;\n\nexport interface RolesDeps<Role extends string, Permission extends string> {\n query: RolesQuery;\n model: RoleModel<Role, Permission>;\n /** The invitation link's token prefix (`ai` → `ai1.<43>`) and how the product keeps a token (its keyed hash). */\n tokenPrefix: string;\n tokenHash: (token: string) => string;\n /** Hours an invitation stays valid. */\n inviteTtlHours: number;\n token?: () => string;\n}\n\nexport interface Member<Role extends string> {\n accountId: string;\n email: string;\n name: string | null;\n role: Role;\n since: Date;\n}\nexport interface Invitation<Role extends string> {\n id: string;\n email: string;\n role: Role;\n expiresAt: Date;\n createdAt: Date;\n}\n\n/** Who may do what in a scope, over the product's PostgreSQL. */\nexport function createRoles<Role extends string, Permission extends string>(deps: RolesDeps<Role, Permission>) {\n const { query, model } = deps;\n const known = (role: string): role is Role => (model.roles as readonly string[]).includes(role);\n const mustKnow = (role: string): Role => {\n if (!known(role)) throw new RolesError(ROLES_CODE.unknownRole);\n return role;\n };\n const newToken = deps.token ?? (() => `${deps.tokenPrefix}1.${crypto.randomBytes(32).toString(\"base64url\")}`);\n const owners = (scopeId: string) => query<{ account_id: string }>(\"SELECT account_id FROM memberships WHERE scope_id = $1 AND role = $2\", [scopeId, ownerRole()]);\n /** The role that cannot disappear: the first of the model that manages every role. */\n const ownerRole = (): Role => model.roles.find((r) => model.roles.every((x) => model.manages[r].includes(x) || x === r)) ?? model.roles[0]!;\n\n async function roleOf(accountId: string, scopeId: string): Promise<Role | null> {\n const [row] = await query<{ role: Role }>(\"SELECT role FROM memberships WHERE scope_id = $1 AND account_id = $2\", [scopeId, accountId]);\n return row?.role ?? null;\n }\n\n return {\n ownerRole,\n roleOf,\n\n /** Every scope the person belongs to, with their role in it. */\n async scopesOf(accountId: string): Promise<{ scopeId: string; role: Role }[]> {\n return (await query<{ scope_id: string; role: Role }>(\"SELECT scope_id, role FROM memberships WHERE account_id = $1 ORDER BY created_at\", [accountId])).map((r) => ({ scopeId: r.scope_id, role: r.role }));\n },\n\n /** The person's role in the scope if it holds the permission; otherwise `NOT_A_MEMBER` (404: nothing tells the scope exists) or `FORBIDDEN`. */\n async authorize(accountId: string, scopeId: string, permission: Permission): Promise<Role> {\n const role = await roleOf(accountId, scopeId);\n if (!role) throw new RolesError(ROLES_CODE.notMember);\n if (!can(model, role, permission)) throw new RolesError(ROLES_CODE.forbidden);\n return role;\n },\n\n /** Puts a person in a scope with a role (changing it if they are there): for a first owner, a seed, an accepted invitation. */\n async grant(scopeId: string, accountId: string, role: string, invitedBy: string | null, now: Date): Promise<void> {\n mustKnow(role);\n await query(\n \"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role\",\n [scopeId, accountId, role, invitedBy, now],\n );\n },\n\n async members(scopeId: string): Promise<Member<Role>[]> {\n const rows = await query<{ account_id: string; email: string; name: string | null; role: Role; created_at: Date }>(\n \"SELECT m.account_id, a.email, a.name, m.role, m.created_at FROM memberships m JOIN accounts a ON a.id = m.account_id WHERE m.scope_id = $1 ORDER BY m.created_at\",\n [scopeId],\n );\n return rows.map((r) => ({ accountId: r.account_id, email: r.email, name: r.name, role: r.role, since: r.created_at }));\n },\n\n /** Changes someone's role. The actor must manage both the current and the new role; the last owner can never be demoted. */\n async setRole(scopeId: string, actor: { id: string }, target: string, role: string): Promise<void> {\n mustKnow(role);\n const mine = await roleOf(actor.id, scopeId);\n const current = await roleOf(target, scopeId);\n if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);\n if (!model.manages[mine].includes(current) || !model.manages[mine].includes(role as Role)) throw new RolesError(ROLES_CODE.notAllowed);\n if (current === ownerRole() && role !== current && (await owners(scopeId)).length <= 1) throw new RolesError(ROLES_CODE.lastOwner);\n await query(\"UPDATE memberships SET role = $3 WHERE scope_id = $1 AND account_id = $2\", [scopeId, target, role]);\n },\n\n /** Removes someone from the scope (or leaves it, when the target is the actor). The last owner cannot go. */\n async remove(scopeId: string, actor: { id: string }, target: string): Promise<void> {\n const mine = await roleOf(actor.id, scopeId);\n const current = await roleOf(target, scopeId);\n if (!mine || !current) throw new RolesError(ROLES_CODE.notMember);\n if (actor.id !== target && !model.manages[mine].includes(current)) throw new RolesError(ROLES_CODE.notAllowed);\n if (current === ownerRole() && (await owners(scopeId)).length <= 1) throw new RolesError(ROLES_CODE.lastOwner);\n await query(\"DELETE FROM memberships WHERE scope_id = $1 AND account_id = $2\", [scopeId, target]);\n },\n\n /** Invites an e-mail address with a role the actor manages. The token is in the answer once (the product mails it); only its hash is kept. A new invitation for the same address replaces the pending one. */\n async invite(scopeId: string, actor: { id: string }, input: { email: string; role: string }, now: Date): Promise<{ token: string; invitation: Invitation<Role> }> {\n const role = mustKnow(input.role);\n const mine = await roleOf(actor.id, scopeId);\n if (!mine) throw new RolesError(ROLES_CODE.notMember);\n if (!model.manages[mine].includes(role)) throw new RolesError(ROLES_CODE.notAllowed);\n const email = input.email.trim().toLowerCase();\n await query(\"UPDATE invitations SET used_at = $3 WHERE scope_id = $1 AND email = $2 AND used_at IS NULL\", [scopeId, email, now]);\n const token = newToken();\n const [row] = await query<{ id: string; created_at: Date; expires_at: Date }>(\n \"INSERT INTO invitations (id, scope_id, email, role, token_hash, invited_by, created_at, expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, created_at, expires_at\",\n [crypto.randomUUID(), scopeId, email, role, deps.tokenHash(token), actor.id, now, addHours(now, deps.inviteTtlHours)],\n );\n return { token, invitation: { id: row!.id, email, role, createdAt: row!.created_at, expiresAt: row!.expires_at } };\n },\n\n async pendingInvitations(scopeId: string, now: Date): Promise<Invitation<Role>[]> {\n const rows = await query<{ id: string; email: string; role: Role; created_at: Date; expires_at: Date }>(\"SELECT id, email, role, created_at, expires_at FROM invitations WHERE scope_id = $1 AND used_at IS NULL AND expires_at > $2 ORDER BY created_at\", [scopeId, now]);\n return rows.map((r) => ({ id: r.id, email: r.email, role: r.role, createdAt: r.created_at, expiresAt: r.expires_at }));\n },\n\n async revokeInvitation(scopeId: string, actor: { id: string }, invitationId: string, now: Date): Promise<void> {\n const mine = await roleOf(actor.id, scopeId);\n if (!mine) throw new RolesError(ROLES_CODE.notMember);\n const [row] = await query<{ role: Role }>(\"SELECT role FROM invitations WHERE id = $1 AND scope_id = $2 AND used_at IS NULL\", [invitationId, scopeId]);\n if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);\n if (!model.manages[mine].includes(row.role)) throw new RolesError(ROLES_CODE.notAllowed);\n await query(\"UPDATE invitations SET used_at = $2 WHERE id = $1\", [invitationId, now]);\n },\n\n /** The signed-in account takes the invitation: it must have been sent to this account's address; the link works once and expires. */\n async acceptInvitation(token: string, account: { id: string; email: string }, now: Date): Promise<{ scopeId: string; role: Role }> {\n const [row] = await query<{ id: string; scope_id: string; email: string; role: Role; invited_by: string | null }>(\n \"SELECT id, scope_id, email, role, invited_by FROM invitations WHERE token_hash = $1 AND used_at IS NULL AND expires_at > $2\",\n [deps.tokenHash(token), now],\n );\n if (!row) throw new RolesError(ROLES_CODE.inviteInvalid);\n if (row.email !== account.email.trim().toLowerCase()) throw new RolesError(ROLES_CODE.inviteWrongAccount);\n await query(\"UPDATE invitations SET used_at = $2 WHERE id = $1\", [row.id, now]);\n const current = await roleOf(account.id, row.scope_id);\n // already in: keep the higher role (an invitation never demotes)\n if (!current || (model.manages[current].length < model.manages[row.role].length)) await query(\"INSERT INTO memberships (scope_id, account_id, role, invited_by, created_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (scope_id, account_id) DO UPDATE SET role = excluded.role\", [row.scope_id, account.id, row.role, row.invited_by, now]);\n return { scopeId: row.scope_id, role: (!current || model.manages[current].length < model.manages[row.role].length ? row.role : current) as Role };\n },\n };\n}\nexport type Roles<Role extends string = string, Permission extends string = string> = ReturnType<typeof createRoles<Role, Permission>>;\n","import crypto from \"node:crypto\";\n\nimport type { Clock } from \"@krizaka/db\";\n\n/**\n * Web sessions (the copies each product carried: Yomizaka `ys1.`, Akinaza `as1.`, Kachizaka `ks1.`). The cookie holds a random token\n * (`<prefix>1.` and 32 bytes); the store keeps only its keyed hash, so a leaked table opens nothing. The account is re-read on every\n * request (a suspension applies at once). The lifetime is the setting `auth.sessionDays`.\n */\n\n/** A live session and the account it signs in. `Account` is the product's own shape (id, e-mail, role, locale, name…). */\nexport interface Session<Account> {\n id: string;\n account: Account;\n}\n\n/** What a store keeps for a new session. */\nexport interface NewSession {\n accountId: string;\n tokenHash: string;\n createdAt: Date;\n expiresAt: Date;\n ip: string | null;\n userAgent: string | null;\n}\n\n/** Where sessions live. Adapters: the PostgreSQL store over the product's `sessions` table, and a memory one. */\nexport interface SessionStore<Account> {\n insert(session: NewSession): Promise<void>;\n /** The session of this hash, when it has not expired at `now` and its account is active; null otherwise. */\n find(tokenHash: string, now: Date): Promise<Session<Account> | null>;\n delete(tokenHash: string): Promise<void>;\n}\n\nexport interface SessionsDeps<Account> {\n store: SessionStore<Account>;\n clock: Clock;\n /** The product's token letters: `ys` makes `ys1.<43 characters>`. Lower-case letters, 1 to 4. */\n tokenPrefix: string;\n /** What keys the stored hash (`AUTH_SESSION_SECRET`). A function lets the product read its environment when it is needed. */\n secret: string | (() => string);\n /** Days a new session lives: the setting `auth.sessionDays`, read for each new session. */\n sessionDays: number | (() => number | Promise<number>);\n}\n\nexport interface Sessions<Account> {\n /** A fresh token: shaped `<prefix>1.<43>`, random, never stored (only its hash is). */\n newToken(): string;\n isToken(value: string | undefined): value is string;\n /** The keyed hash the store keeps for a token. */\n tokenHash(token: string): string;\n /** Opens a session: the token for the cookie (shown once) and when it expires. */\n create(accountId: string, meta: { ip: string | null; userAgent: string | null }): Promise<{ token: string; expires: Date }>;\n /** The session a token opens, or null (unknown, malformed, expired, account not active). */\n resolve(token: string | undefined): Promise<Session<Account> | null>;\n /** Ends the session of this token. A malformed token is ignored. */\n revoke(token: string | undefined): Promise<void>;\n}\n\nconst BODY = /^[A-Za-z0-9_-]{43}$/;\nconst PREFIX = /^[a-z]{1,4}$/;\nconst USER_AGENT_MAX = 300;\n\n/**\n * The sessions service of a product.\n * @param deps the store, the clock, the token letters, the secret and the lifetime\n * @throws RangeError for a token prefix that is not 1 to 4 lower-case letters, or a lifetime that is not a whole number of days from 1\n */\nexport function createSessions<Account>(deps: SessionsDeps<Account>): Sessions<Account> {\n if (!PREFIX.test(deps.tokenPrefix)) throw new RangeError(`tokenPrefix must be 1 to 4 lower-case letters, got ${deps.tokenPrefix}`);\n const head = `${deps.tokenPrefix}1.`;\n const secret = () => (typeof deps.secret === \"function\" ? deps.secret() : deps.secret);\n const isToken = (value: string | undefined): value is string => !!value && value.startsWith(head) && BODY.test(value.slice(head.length));\n const tokenHash = (token: string) => crypto.createHmac(\"sha256\", `session:${secret()}`).update(token).digest(\"hex\");\n const newToken = () => `${head}${crypto.randomBytes(32).toString(\"base64url\")}`;\n return {\n newToken,\n isToken,\n tokenHash,\n async create(accountId, meta) {\n const days = typeof deps.sessionDays === \"function\" ? await deps.sessionDays() : deps.sessionDays;\n if (!Number.isInteger(days) || days < 1) throw new RangeError(`sessionDays must be a whole number of days from 1, got ${days}`);\n const token = newToken();\n const createdAt = deps.clock.now();\n // days of 24 hours, not calendar days: the same instant whatever the server's time zone (the copies added 86 400 000 ms a day)\n const expires = new Date(createdAt);\n expires.setUTCHours(expires.getUTCHours() + days * 24);\n await deps.store.insert({ accountId, tokenHash: tokenHash(token), createdAt, expiresAt: expires, ip: meta.ip, userAgent: meta.userAgent?.slice(0, USER_AGENT_MAX) ?? null });\n return { token, expires };\n },\n async resolve(token) {\n if (!isToken(token)) return null;\n return deps.store.find(tokenHash(token), deps.clock.now());\n },\n async revoke(token) {\n if (!isToken(token)) return;\n await deps.store.delete(tokenHash(token));\n },\n };\n}\n\n/** The attributes of the session cookie, for the product's framework (`cookies().set(cookie)`, `NextResponse.cookies.set`…). */\nexport interface SessionCookie {\n name: string;\n value: string;\n httpOnly: true;\n secure: boolean;\n sameSite: \"lax\";\n path: \"/\";\n expires: Date;\n}\n\n/**\n * The session cookie: HttpOnly, SameSite=Lax, on the whole site, `Secure` where the product says (production).\n * @param options the cookie's name (`yomizaka_session`) and whether it is `Secure`\n */\nexport function sessionCookie(token: string, expires: Date, options: { name: string; secure: boolean }): SessionCookie {\n return { name: options.name, value: token, httpOnly: true, secure: options.secure, sameSite: \"lax\", path: \"/\", expires };\n}\n\n/** The same cookie, expired now: what signing out sets. */\nexport function clearedSessionCookie(options: { name: string; secure: boolean }, now: Date): SessionCookie {\n return sessionCookie(\"\", now, options);\n}\n\n/**\n * The session token of a request: the native apps' `Authorization: Bearer` (which wins over a stale cookie), else the web's cookie.\n * @param headers the request's headers\n * @param options the cookie's name; `bearer: false` for a product with no native app\n * @returns the raw token (not yet checked), or undefined\n */\nexport function sessionTokenOf(headers: Headers, options: { cookie: string; bearer?: boolean }): string | undefined {\n if (options.bearer !== false) {\n const bearer = /^bearer (\\S+)$/i.exec(headers.get(\"authorization\") ?? \"\")?.[1];\n if (bearer) return bearer;\n }\n const prefix = `${options.cookie}=`;\n return headers\n .get(\"cookie\")\n ?.split(\";\")\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix))\n ?.slice(prefix.length);\n}\n","import type { NewSession, Session, SessionStore } from \"./sessions\";\n\n/**\n * An in-memory session store, for unit tests and demos. `accountOf` plays the accounts table: it answers the account of an id, or null\n * when it does not exist or is not active.\n */\nexport function memorySessionStore<Account>(accountOf: (accountId: string) => Account | null): SessionStore<Account> & { rows(): readonly NewSession[] } {\n const rows = new Map<string, NewSession & { id: string }>();\n let next = 0;\n return {\n async insert(session) {\n if (rows.has(session.tokenHash)) throw new Error(\"duplicate session token hash\");\n next += 1;\n rows.set(session.tokenHash, { ...session, id: `session-${next}` });\n },\n async find(tokenHash, now): Promise<Session<Account> | null> {\n const row = rows.get(tokenHash);\n if (!row || row.expiresAt.getTime() <= now.getTime()) return null;\n const account = accountOf(row.accountId);\n return account === null ? null : { id: row.id, account };\n },\n async delete(tokenHash) {\n rows.delete(tokenHash);\n },\n rows: () => [...rows.values()],\n };\n}\n","import { ident, type Query } from \"@krizaka/db\";\n\nimport type { Session, SessionStore } from \"./sessions\";\n\nexport interface DbSessionStoreOptions<Account> {\n /** The product's session table. Default `sessions` (`id`, `account_id`, `token_hash` unique, `created_at`, `expires_at`, `ip`, `user_agent`). */\n sessions?: string;\n /** The product's account table. Default `accounts`. */\n accounts?: string;\n /** The account columns the session carries (`id`, `email`, `role`, `locale`, `name`…): all checked, all read in one query with the session. */\n columns: readonly string[];\n /** Builds the product's account from a row holding exactly `columns`. */\n toAccount: (row: Record<string, unknown>) => Account;\n /** An account that is not active signs nobody in (a suspension applies at once): the column and the value it must have (`status` = `ACTIVE`). */\n active?: { column: string; equals: string };\n}\n\n/**\n * The session store over the product's own tables (`sessions` joined to `accounts`): the declared tables and columns are checked by\n * `ident()` and nothing else reaches SQL. The expiry is compared with the clock's `now`, not the database's.\n * @param query the product's query\n * @param options the table names, the account columns and how the account is built\n * @throws DbError `DB_UNSAFE_IDENTIFIER` for a table or column name that is not a safe identifier\n */\nexport function dbSessionStore<Account>(query: Query, options: DbSessionStoreOptions<Account>): SessionStore<Account> {\n const sessions = ident(options.sessions ?? \"sessions\");\n const accounts = ident(options.accounts ?? \"accounts\");\n const columns = options.columns.map((column) => `a.${ident(column)}`).join(\", \");\n const active = options.active ? ` AND a.${ident(options.active.column)} = $3` : \"\";\n return {\n async insert(session) {\n await query(`INSERT INTO ${sessions} (account_id, token_hash, created_at, expires_at, ip, user_agent) VALUES ($1, $2, $3, $4, $5, $6)`, [session.accountId, session.tokenHash, session.createdAt, session.expiresAt, session.ip, session.userAgent]);\n },\n async find(tokenHash, now): Promise<Session<Account> | null> {\n const params: unknown[] = [tokenHash, now];\n if (options.active) params.push(options.active.equals);\n const [row] = await query<Record<string, unknown> & { session_id: string }>(\n `SELECT s.id AS session_id, ${columns} FROM ${sessions} s JOIN ${accounts} a ON a.id = s.account_id WHERE s.token_hash = $1 AND s.expires_at > $2${active}`,\n params,\n );\n if (!row) return null;\n const { session_id: id, ...account } = row;\n return { id, account: options.toAccount(account) };\n },\n async delete(tokenHash) {\n await query(`DELETE FROM ${sessions} WHERE token_hash = $1`, [tokenHash]);\n },\n };\n}\n","import { type CompleteOptions, type ExternalIdentity, type FederatedProvider, FEDERATION_CODE, FederationError, type IdentityProvider, isFederatedProvider, isLocalReturn, type StartedSignIn, type StartOptions } from \"./federation\";\n\n/** The `fetch` the adapter calls krizaka-users with (injected: no global, no network in tests). */\nexport type Fetcher = (url: string, init: { method: \"POST\"; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;\n\nexport interface UsersFederationOptions {\n /** The tenant host of the product: `https://auth.dev.akinaza.com`. */\n baseUrl: string;\n /** The product's public address: the start URL sends the person back to it, so `returnTo` is absolute from it. */\n appUrl: string;\n fetch: Fetcher;\n}\n\nconst START = (base: string, provider: FederatedProvider) => `${base}/api/v1/auth/web/${provider}/start`;\nconst EXCHANGE = (base: string) => `${base}/api/v1/auth/web/exchange`;\n\nconst text = (value: unknown): string | null => (typeof value === \"string\" && value.length > 0 ? value : null);\n\n/** Reads krizaka-users' answer into an identity; anything that is not a complete identity is refused. */\nexport function parseExternalIdentity(body: unknown): ExternalIdentity {\n const o = (body ?? {}) as Record<string, unknown>;\n const issuer = text(o.issuer);\n const subject = text(o.subject);\n if (!issuer || !subject) throw new FederationError(FEDERATION_CODE.unavailable, \"krizaka-users answered without an issuer and a subject\");\n return { issuer, subject, email: text(o.email), emailVerified: o.email_verified === true, name: text(o.name) };\n}\n\n/**\n * The adapter for krizaka-users (`auth.<product>` tenant host, krizaka/krizaka-users#31): `start` builds the tenant's start address,\n * `complete` exchanges the one-time code (and the PKCE verifier of a native app) for the verified identity.\n */\nexport function usersIdentityProvider({ baseUrl, appUrl, fetch }: UsersFederationOptions): IdentityProvider {\n const base = baseUrl.replace(/\\/+$/, \"\");\n const app = appUrl.replace(/\\/+$/, \"\");\n return {\n async start(provider, returnTo, options: StartOptions = {}): Promise<StartedSignIn> {\n if (!isFederatedProvider(provider)) throw new FederationError(FEDERATION_CODE.unknownProvider, `Unknown provider ${String(provider)}`);\n if (!isLocalReturn(returnTo)) throw new FederationError(FEDERATION_CODE.badReturn, \"That return address is not allowed\");\n const state = crypto.randomUUID();\n const query = new URLSearchParams({ return_to: `${app}${returnTo}`, state });\n if (options.codeChallenge) {\n query.set(\"code_challenge\", options.codeChallenge);\n query.set(\"code_challenge_method\", \"S256\");\n }\n return { url: `${START(base, provider)}?${query}`, state };\n },\n async complete(code, options: CompleteOptions = {}) {\n const response = await fetch(EXCHANGE(base), {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ code, ...(options.codeVerifier ? { code_verifier: options.codeVerifier } : {}) }),\n });\n if (response.status === 400 || response.status === 401 || response.status === 404 || response.status === 410) throw new FederationError(FEDERATION_CODE.invalidCode, \"That code is not valid\");\n if (!response.ok) throw new FederationError(FEDERATION_CODE.unavailable, `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,Q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,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","crypto","ident"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krizaka/auth",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.2",
|
|
4
4
|
"description": "The account of a Krizaka product — name, language, theme, avatar, e-mail change by link with the verified flag, password, sessions with sign-out of the others, data export, deletion — behind a port, with a PostgreSQL adapter and its migration. Each product keeps its own accounts; no framework, no wall clock, no mail vendor.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"krizaka",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"date-fns": "^4.4.0",
|
|
65
|
-
"@krizaka/db": "^0.3.
|
|
65
|
+
"@krizaka/db": "^0.3.1",
|
|
66
66
|
"@krizaka/settings": "^0.5.1"
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"typescript": "^5.9.3",
|
|
87
87
|
"vitest": "^4.1.11",
|
|
88
88
|
"zod": "^4.6.7",
|
|
89
|
-
"@krizaka/config": "^0.
|
|
89
|
+
"@krizaka/config": "^0.15.0"
|
|
90
90
|
},
|
|
91
91
|
"scripts": {
|
|
92
92
|
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
|