@allodium/auth 0.1.0 → 0.3.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.
@@ -0,0 +1,53 @@
1
+ import { type AccessPolicy, type Actor, type Grant } from './access.js';
2
+ /**
3
+ * Reading grants out of a database, and building the actor a request runs as.
4
+ *
5
+ * Separate from the gate itself because the gate must stay pure: rules you can
6
+ * read back without standing up Postgres. This half is the opinionated one — it
7
+ * assumes the roles / user_roles / role_permissions shape Allodium's own seed
8
+ * defines. Every table name is an option, and an application with a different
9
+ * schema can skip this file entirely and hand `createAccessPolicy` its own
10
+ * grants; the gate does not care where they came from.
11
+ *
12
+ * Grants are cached, because otherwise every request pays three queries to learn
13
+ * a matrix that changes when somebody edits it in the console — which is rare
14
+ * and, when it happens, is a `refresh()` away.
15
+ */
16
+ /** Anything pg-shaped: a Pool, a Client, a proxy. Same duck as the admin runtime's. */
17
+ export interface Queryable {
18
+ query(text: string, values?: unknown[]): Promise<{
19
+ rows: unknown[];
20
+ rowCount: number | null;
21
+ }>;
22
+ }
23
+ export interface GrantLoaderOptions {
24
+ /** Table holding role keys. Default "roles", keyed by "key". */
25
+ rolesTable?: string;
26
+ /** Table holding the matrix. Default "role_permissions". */
27
+ grantsTable?: string;
28
+ /** Join table of users to roles. Default "user_roles". */
29
+ userRolesTable?: string;
30
+ /** Roles that bypass the model. Passed straight to the policy. */
31
+ superuserRoles?: string[];
32
+ /** How long a loaded matrix stays good. Default 30s. */
33
+ ttlMs?: number;
34
+ }
35
+ export interface GrantLoader {
36
+ /** The matrix, cached. */
37
+ grants(): Promise<Grant[]>;
38
+ /** A policy over the current matrix. */
39
+ policy(): Promise<AccessPolicy>;
40
+ /** Role keys a user holds. Empty for an unknown user — which denies, it does not throw. */
41
+ rolesFor(userId: string): Promise<string[]>;
42
+ /**
43
+ * The actor for a signed-in user. `claims` are the app's to supply: which
44
+ * column identifies "this person's rows" is domain knowledge — a customer id
45
+ * here, a chapter id in ChapterHub — and a library that guessed would be wrong
46
+ * in a way nobody notices until it leaks.
47
+ */
48
+ actorFor(userId: string, claims?: Record<string, unknown>): Promise<Actor>;
49
+ /** Drop the cache — call after editing the matrix. */
50
+ refresh(): void;
51
+ }
52
+ export declare function createGrantLoader(db: Queryable, opts?: GrantLoaderOptions): GrantLoader;
53
+ //# sourceMappingURL=grants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grants.d.ts","sourceRoot":"","sources":["../src/grants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,YAAY,EAAE,KAAK,KAAK,EAAE,KAAK,KAAK,EAAuB,MAAM,aAAa,CAAC;AAEjH;;;;;;;;;;;;;GAaG;AAEH,uFAAuF;AACvF,MAAM,WAAW,SAAS;IACxB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAAC;CAChG;AAED,MAAM,WAAW,kBAAkB;IACjC,gEAAgE;IAChE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,0DAA0D;IAC1D,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,kEAAkE;IAClE,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,wDAAwD;IACxD,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,WAAW;IAC1B,0BAA0B;IAC1B,MAAM,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;IAC3B,wCAAwC;IACxC,MAAM,IAAI,OAAO,CAAC,YAAY,CAAC,CAAC;IAChC,2FAA2F;IAC3F,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC5C;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IAC3E,sDAAsD;IACtD,OAAO,IAAI,IAAI,CAAC;CACjB;AAyCD,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,GAAE,kBAAuB,GAAG,WAAW,CAiE3F"}
package/dist/grants.js ADDED
@@ -0,0 +1,100 @@
1
+ import { createAccessPolicy } from './access.js';
2
+ const ident = (n) => '"' + n.replaceAll('"', '""') + '"';
3
+ /**
4
+ * row_filter arrives as jsonb. Null or an empty array means every row; anything
5
+ * else must be an array of predicates that each name a column.
6
+ *
7
+ * A filter that cannot be read FAILS CLOSED: the whole grant is refused, not
8
+ * widened. The alternative — keep the grant and drop the filter — turns "the
9
+ * public may read published posts" into "the public may read every post" the
10
+ * moment somebody saves `{}` instead of `[]`, with nothing but a log line to say
11
+ * so. That is the failure mode row-level rules exist to prevent, and it is not
12
+ * one a warning is allowed to stand in for.
13
+ */
14
+ function parseFilter(raw, where, problems) {
15
+ if (raw === null || raw === undefined)
16
+ return { ok: true };
17
+ const value = typeof raw === 'string' ? safeParse(raw) : raw;
18
+ if (!Array.isArray(value)) {
19
+ problems.push(`${where}: row_filter is not an array of predicates — this grant is REFUSED until it is fixed.`);
20
+ return { ok: false };
21
+ }
22
+ const out = [];
23
+ for (const p of value) {
24
+ if (!p || typeof p !== 'object' || typeof p.column !== 'string' || !p.column.trim()) {
25
+ problems.push(`${where}: a row_filter entry has no "column" — this grant is REFUSED until it is fixed.`);
26
+ return { ok: false };
27
+ }
28
+ out.push(p);
29
+ }
30
+ return out.length ? { ok: true, filter: out } : { ok: true };
31
+ }
32
+ function safeParse(s) {
33
+ try {
34
+ return JSON.parse(s);
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ export function createGrantLoader(db, opts = {}) {
41
+ const rolesTable = opts.rolesTable ?? 'roles';
42
+ const grantsTable = opts.grantsTable ?? 'role_permissions';
43
+ const userRolesTable = opts.userRolesTable ?? 'user_roles';
44
+ const ttl = opts.ttlMs ?? 30_000;
45
+ let cache = null;
46
+ async function load() {
47
+ if (cache && Date.now() - cache.at < ttl)
48
+ return cache;
49
+ const res = await db.query(`select r.key as role, g.table_name, g.can_create, g.can_read, g.can_update, g.can_delete,
50
+ ${ /* row_filter is newer than the table; tolerate its absence */''}
51
+ to_jsonb(g) -> 'row_filter' as row_filter
52
+ from ${ident(grantsTable)} g
53
+ join ${ident(rolesTable)} r on r.id = g.role_id
54
+ order by r.key, g.table_name`);
55
+ const problems = [];
56
+ const grants = [];
57
+ for (const row of res.rows) {
58
+ const parsed = parseFilter(row.row_filter, `${row.role} on ${row.table_name}`, problems);
59
+ // A grant whose filter cannot be honoured is not loaded at all. With no
60
+ // grant, the policy denies — the same answer as if the row did not exist,
61
+ // which is the only safe reading of a row that cannot be understood.
62
+ if (!parsed.ok)
63
+ continue;
64
+ grants.push({
65
+ role: String(row.role),
66
+ table: String(row.table_name),
67
+ create: !!row.can_create,
68
+ read: !!row.can_read,
69
+ update: !!row.can_update,
70
+ delete: !!row.can_delete,
71
+ ...(parsed.filter ? { rowFilter: parsed.filter } : {}),
72
+ });
73
+ }
74
+ cache = { at: Date.now(), grants, problems };
75
+ return cache;
76
+ }
77
+ return {
78
+ async grants() {
79
+ return (await load()).grants;
80
+ },
81
+ async policy() {
82
+ const { grants, problems } = await load();
83
+ const policy = createAccessPolicy(grants, { superuserRoles: opts.superuserRoles });
84
+ // Loading problems and configuration problems are the same kind of thing to
85
+ // whoever has to fix them, so they arrive in one list.
86
+ return { ...policy, problems: [...problems, ...policy.problems] };
87
+ },
88
+ async rolesFor(userId) {
89
+ const res = await db.query(`select r.key from ${ident(userRolesTable)} ur join ${ident(rolesTable)} r on r.id = ur.role_id where ur.user_id = $1`, [userId]);
90
+ return res.rows.map((r) => r.key);
91
+ },
92
+ async actorFor(userId, claims = {}) {
93
+ return { userId, roles: await this.rolesFor(userId), claims };
94
+ },
95
+ refresh() {
96
+ cache = null;
97
+ },
98
+ };
99
+ }
100
+ //# sourceMappingURL=grants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grants.js","sourceRoot":"","sources":["../src/grants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAkE,MAAM,aAAa,CAAC;AAqDjH,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,GAAG,CAAC;AAEjE;;;;;;;;;;GAUG;AACH,SAAS,WAAW,CAAC,GAAY,EAAE,KAAa,EAAE,QAAkB;IAClE,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;IAC3D,MAAM,KAAK,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IAC7D,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,QAAQ,CAAC,IAAI,CAAC,GAAG,KAAK,uFAAuF,CAAC,CAAC;QAC/G,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IACvB,CAAC;IACD,MAAM,GAAG,GAAqB,EAAE,CAAC;IACjC,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAQ,CAAoB,CAAC,MAAM,KAAK,QAAQ,IAAI,CAAE,CAAoB,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;YAC5H,QAAQ,CAAC,IAAI,CAAC,GAAG,KAAK,iFAAiF,CAAC,CAAC;YACzG,OAAO,EAAE,EAAE,EAA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C,GAAG,QAAQ,EAAE,GAAG,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QACpE,CAAC;QACD,KAAK,CAAC,QAAQ,CAAC,MAAM;YACnB,MAAM,GAAG,GAAG,MAAM,EAAE,CAAC,KAAK,CACxB,qBAAqB,KAAK,CAAC,cAAc,CAAC,YAAY,KAAK,CAAC,UAAU,CAAC,+CAA+C,EACtH,CAAC,MAAM,CAAC,CACT,CAAC;YACF,OAAQ,GAAG,CAAC,IAA0B,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC3D,CAAC;QACD,KAAK,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,EAAE;YAChC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAChE,CAAC;QACD,OAAO;YACL,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;KACF,CAAC;AACJ,CAAC"}
package/dist/index.d.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * Everything is a factory taking explicit config — no env vars are read in here, no
11
11
  * framework imports. Your app binds names, secrets, and tables once and re-exports;
12
+ * plus an "act as" user switcher that hooks your one identity seam.
12
13
  * OIDC and WebAuthn ceremony helpers arrive in a later minor.
13
14
  */
14
15
  export { hashPassword, verifyPassword, DUMMY_ARGON2ID_HASH } from './passwords.js';
@@ -16,5 +17,9 @@ export { createRateLimiter, type RateLimiter } from './rateLimit.js';
16
17
  export { signPayload, verifySignedPayload, createResetTokens, makeStateToken, readStateToken, type ResetTokenPayload, type ResetTokens, } from './signedTokens.js';
17
18
  export { createSessionCookies, type SessionCookieNames, type SessionCookieBase, type CookieSetter, type SessionCookies, } from './cookies.js';
18
19
  export { createSessionStore, type SessionStore, type MintedSession, type OriginScope, } from './sessions.js';
20
+ export { createActAs, type ActAs, type ActAsState, type ActAsMode, type ActAsRefusal, type ActAsAuditEvent, type CreateActAsOptions, } from './actAs.js';
19
21
  export { firstForwardedIp } from './ip.js';
22
+ export { createAccessPolicy, PUBLIC_ACTOR, PUBLIC_ROLE, ACTIONS, type Actor, type Action, type Grant, type GrantPredicate, type AccessDecision, type AccessPolicy, type AccessPolicyOptions, } from './access.js';
23
+ export { createGrantLoader, type GrantLoader, type GrantLoaderOptions, } from './grants.js';
24
+ export { createAuthRoutes, headerCookieSetter, readCookie, type AuthRoutes, type AuthRoutesOptions, type AuthUserRow, } from './routes.js';
20
25
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,KAAK,iBAAiB,EACtB,KAAK,WAAW,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,YAAY,EACjB,KAAK,cAAc,GACpB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,EAClB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,WAAW,GACjB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,KAAK,iBAAiB,EACtB,KAAK,WAAW,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,YAAY,EACjB,KAAK,cAAc,GACpB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,EAClB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,WAAW,GACjB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,WAAW,EACX,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,kBAAkB,GACxB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,WAAW,EACX,OAAO,EACP,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,KAAK,EACV,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,mBAAmB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,KAAK,WAAW,EAChB,KAAK,kBAAkB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,UAAU,EACV,KAAK,UAAU,EACf,KAAK,iBAAiB,EACtB,KAAK,WAAW,GACjB,MAAM,aAAa,CAAC"}
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * Everything is a factory taking explicit config — no env vars are read in here, no
11
11
  * framework imports. Your app binds names, secrets, and tables once and re-exports;
12
+ * plus an "act as" user switcher that hooks your one identity seam.
12
13
  * OIDC and WebAuthn ceremony helpers arrive in a later minor.
13
14
  */
14
15
  export { hashPassword, verifyPassword, DUMMY_ARGON2ID_HASH } from './passwords.js';
@@ -16,5 +17,9 @@ export { createRateLimiter } from './rateLimit.js';
16
17
  export { signPayload, verifySignedPayload, createResetTokens, makeStateToken, readStateToken, } from './signedTokens.js';
17
18
  export { createSessionCookies, } from './cookies.js';
18
19
  export { createSessionStore, } from './sessions.js';
20
+ export { createActAs, } from './actAs.js';
19
21
  export { firstForwardedIp } from './ip.js';
22
+ export { createAccessPolicy, PUBLIC_ACTOR, PUBLIC_ROLE, ACTIONS, } from './access.js';
23
+ export { createGrantLoader, } from './grants.js';
24
+ export { createAuthRoutes, headerCookieSetter, readCookie, } from './routes.js';
20
25
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAoB,MAAM,gBAAgB,CAAC;AACrE,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,cAAc,GAGf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,GAKrB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,GAInB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAoB,MAAM,gBAAgB,CAAC;AACrE,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,cAAc,GAGf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,GAKrB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,GAInB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,WAAW,GAOZ,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,WAAW,EACX,OAAO,GAQR,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,GAGlB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,UAAU,GAIX,MAAM,aAAa,CAAC"}
@@ -0,0 +1,120 @@
1
+ import type { SessionStore } from './sessions.js';
2
+ import type { SessionCookies, CookieSetter } from './cookies.js';
3
+ import type { RateLimiter } from './rateLimit.js';
4
+ /**
5
+ * The four endpoints every app rewrites, written once.
6
+ *
7
+ * Login, logout, refresh and me are not interesting — which is exactly why they
8
+ * are worth shipping. Each one has two or three details that are easy to get
9
+ * wrong and silent when you do: a login that reveals which emails exist by
10
+ * returning faster for unknown ones; a /me that hands back the raw user row with
11
+ * its password hash; a refresh that clears the session on a network blip.
12
+ *
13
+ * Framework-free, like the rest of this package: these take a Web `Request` and
14
+ * return a Web `Response`, which is what a Next route handler, Hono, and a plain
15
+ * Node server with an adapter all speak. No env vars are read here.
16
+ */
17
+ /** The row your user lookup returns. Nothing else about your schema is assumed. */
18
+ export interface AuthUserRow {
19
+ id: string;
20
+ /** argon2id digest. Null for an account with no password (SSO-only) — always refused here. */
21
+ passwordHash: string | null;
22
+ /** Anything non-active refuses with a DISTINGUISHABLE reason; see the note on login. */
23
+ status?: string | null;
24
+ }
25
+ export interface AuthRoutesOptions {
26
+ sessions: SessionStore;
27
+ cookies: SessionCookies;
28
+ /**
29
+ * The surface these sessions belong to — "site", "admin". Stored on the session
30
+ * and used to scope resolution, so a cookie moved between surfaces resolves to
31
+ * nothing. This is the whole reason `origin` exists on the store.
32
+ */
33
+ origin: string;
34
+ /** Look up by email. Return null for unknown — the timing is equalised for you. */
35
+ findUserByEmail(email: string): Promise<AuthUserRow | null>;
36
+ /**
37
+ * What /me puts on the wire. REQUIRED, and required to be explicit.
38
+ *
39
+ * `resolveUser` hands back the raw database row, which on a users table means
40
+ * the password hash. Defaulting to "the row" would leak it from an endpoint
41
+ * whose entire job is to be called by a browser; defaulting to a guessed subset
42
+ * would be this library deciding what your users may see about themselves.
43
+ */
44
+ toPublicUser(row: Record<string, unknown>): unknown;
45
+ /** Statuses allowed to sign in. Defaults to ['active']. */
46
+ activeStatuses?: string[];
47
+ /** Optional: attach roles and claims to /me, from the grant loader. */
48
+ actorFor?(userId: string): Promise<unknown>;
49
+ /** Optional login throttle. Keyed per email AND per IP — see below. */
50
+ rateLimit?: RateLimiter;
51
+ limits?: {
52
+ perEmail?: number;
53
+ perIp?: number;
54
+ windowMs?: number;
55
+ };
56
+ /**
57
+ * Origins allowed to call these endpoints with credentials.
58
+ *
59
+ * A cross-origin browser client cannot read a response without
60
+ * Access-Control-Allow-Origin naming its exact origin, and cannot send cookies
61
+ * without Allow-Credentials — and the wildcard is forbidden in combination with
62
+ * credentials, so this must be an allowlist. Omit it for a same-origin app.
63
+ */
64
+ allowOrigins?: string[] | ((origin: string) => boolean);
65
+ }
66
+ export interface AuthRoutes {
67
+ /** POST — { email, password } */
68
+ login(request: Request): Promise<Response>;
69
+ /** POST — revokes the session by whatever the cookie jar holds. 500 with cookies intact if the revoke itself failed. */
70
+ logout(request: Request): Promise<Response>;
71
+ /** POST — single-use rotation of the refresh cookie. */
72
+ refresh(request: Request): Promise<Response>;
73
+ /** GET — the current user, or 401. */
74
+ me(request: Request): Promise<Response>;
75
+ /** OPTIONS — CORS preflight for any of the above. */
76
+ preflight(request: Request): Response;
77
+ }
78
+ /**
79
+ * A `CookieSetter` that writes into response headers.
80
+ *
81
+ * The cookie helper speaks the Next/`cookies()` shape — `set(name, value, opts)`
82
+ * — so bridging it to a Web Response means serialising here. Every cookie gets
83
+ * its own Set-Cookie header; folding them into one comma-separated value is a
84
+ * classic way to lose all but the first.
85
+ */
86
+ export declare function headerCookieSetter(): {
87
+ setter: CookieSetter;
88
+ applyTo(headers: Headers): void;
89
+ };
90
+ /** Read one cookie from a request. No dependency, and no need for a general parser. */
91
+ export declare function readCookie(request: Request, name: string): string | undefined;
92
+ /**
93
+ * Refuse a state-changing request that a browser sent from a site this app did
94
+ * not name — the cross-site request forgery check.
95
+ *
96
+ * CORS headers alone do not do this. They decide whether a script may READ the
97
+ * response; the request itself, cookies and all, has already reached the
98
+ * handler. SameSite cookies cover most of the gap, but not two surfaces on
99
+ * sibling subdomains, which are "same site" to a cookie and different origins
100
+ * to everything else — and that is exactly how a public site and its back
101
+ * office get deployed.
102
+ *
103
+ * Three cheap facts settle it. A browser always sends Origin on a cross-origin
104
+ * POST, so an Origin that is neither this host nor allowlisted is refused. A
105
+ * cross-site form cannot set `Content-Type: application/json` without a
106
+ * preflight, so a body typed as anything else is refused. And modern browsers
107
+ * label the request's provenance in Sec-Fetch-Site, which catches the case
108
+ * where Origin is absent. A request with no Origin, no provenance label and no
109
+ * body — curl, a server, a same-origin fetch — passes.
110
+ *
111
+ * Only the HOST of the origin is compared, not the scheme: behind a reverse
112
+ * proxy the handler sees http://host while the browser sent https://host, and
113
+ * refusing every write on that mismatch would be a very quiet outage.
114
+ */
115
+ export declare function crossSiteWrite(request: Request, originAllowed: (origin: string) => boolean): {
116
+ status: number;
117
+ message: string;
118
+ } | null;
119
+ export declare function createAuthRoutes(opts: AuthRoutesOptions): AuthRoutes;
120
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE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AC;IAC3C,wHAAwH;IACxH,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC5C,wDAAwD;IACxD,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC7C,sCAAsC;IACtC,EAAE,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACxC,qDAAqD;IACrD,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,QAAQ,CAAC;CACvC;AAcD;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,IAAI;IAAE,MAAM,EAAE,YAAY,CAAC;IAAC,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAA;CAAE,CAqB9F;AAED,uFAAuF;AACvF,wBAAgB,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAU7E;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAgBvI;AAID,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,iBAAiB,GAAG,UAAU,CAuKpE"}
package/dist/routes.js ADDED
@@ -0,0 +1,266 @@
1
+ import { verifyPassword, DUMMY_ARGON2ID_HASH } from './passwords.js';
2
+ import { firstForwardedIp } from './ip.js';
3
+ /* --------------------------- cookie plumbing --------------------------- */
4
+ const ATTR = {
5
+ httpOnly: 'HttpOnly',
6
+ secure: 'Secure',
7
+ sameSite: 'SameSite',
8
+ path: 'Path',
9
+ maxAge: 'Max-Age',
10
+ domain: 'Domain',
11
+ expires: 'Expires',
12
+ };
13
+ /**
14
+ * A `CookieSetter` that writes into response headers.
15
+ *
16
+ * The cookie helper speaks the Next/`cookies()` shape — `set(name, value, opts)`
17
+ * — so bridging it to a Web Response means serialising here. Every cookie gets
18
+ * its own Set-Cookie header; folding them into one comma-separated value is a
19
+ * classic way to lose all but the first.
20
+ */
21
+ export function headerCookieSetter() {
22
+ const jar = [];
23
+ return {
24
+ setter: {
25
+ set(name, value, options = {}) {
26
+ const parts = [`${name}=${encodeURIComponent(value)}`];
27
+ for (const [key, raw] of Object.entries(options)) {
28
+ if (raw === undefined || raw === null || raw === false)
29
+ continue;
30
+ const attr = ATTR[key];
31
+ if (!attr)
32
+ continue;
33
+ if (raw === true)
34
+ parts.push(attr);
35
+ else if (key === 'sameSite')
36
+ parts.push(`${attr}=${String(raw).charAt(0).toUpperCase()}${String(raw).slice(1)}`);
37
+ else
38
+ parts.push(`${attr}=${String(raw)}`);
39
+ }
40
+ jar.push(parts.join('; '));
41
+ },
42
+ },
43
+ applyTo(headers) {
44
+ for (const c of jar)
45
+ headers.append('Set-Cookie', c);
46
+ },
47
+ };
48
+ }
49
+ /** Read one cookie from a request. No dependency, and no need for a general parser. */
50
+ export function readCookie(request, name) {
51
+ const header = request.headers.get('cookie');
52
+ if (!header)
53
+ return undefined;
54
+ for (const part of header.split(';')) {
55
+ const eq = part.indexOf('=');
56
+ if (eq < 0)
57
+ continue;
58
+ if (part.slice(0, eq).trim() !== name)
59
+ continue;
60
+ return decodeURIComponent(part.slice(eq + 1).trim());
61
+ }
62
+ return undefined;
63
+ }
64
+ /**
65
+ * Refuse a state-changing request that a browser sent from a site this app did
66
+ * not name — the cross-site request forgery check.
67
+ *
68
+ * CORS headers alone do not do this. They decide whether a script may READ the
69
+ * response; the request itself, cookies and all, has already reached the
70
+ * handler. SameSite cookies cover most of the gap, but not two surfaces on
71
+ * sibling subdomains, which are "same site" to a cookie and different origins
72
+ * to everything else — and that is exactly how a public site and its back
73
+ * office get deployed.
74
+ *
75
+ * Three cheap facts settle it. A browser always sends Origin on a cross-origin
76
+ * POST, so an Origin that is neither this host nor allowlisted is refused. A
77
+ * cross-site form cannot set `Content-Type: application/json` without a
78
+ * preflight, so a body typed as anything else is refused. And modern browsers
79
+ * label the request's provenance in Sec-Fetch-Site, which catches the case
80
+ * where Origin is absent. A request with no Origin, no provenance label and no
81
+ * body — curl, a server, a same-origin fetch — passes.
82
+ *
83
+ * Only the HOST of the origin is compared, not the scheme: behind a reverse
84
+ * proxy the handler sees http://host while the browser sent https://host, and
85
+ * refusing every write on that mismatch would be a very quiet outage.
86
+ */
87
+ export function crossSiteWrite(request, originAllowed) {
88
+ const origin = request.headers.get('origin');
89
+ if (origin) {
90
+ let sameHost = false;
91
+ try {
92
+ sameHost = new URL(origin).host === new URL(request.url).host;
93
+ }
94
+ catch {
95
+ /* an unparseable Origin is not this host */
96
+ }
97
+ if (!sameHost && !originAllowed(origin))
98
+ return { status: 403, message: `Cross-origin request from ${origin} refused` };
99
+ }
100
+ else if (request.headers.get('sec-fetch-site') === 'cross-site') {
101
+ return { status: 403, message: 'Cross-site request refused' };
102
+ }
103
+ const type = request.headers.get('content-type');
104
+ if (type && !/^\s*application\/json\b/i.test(type))
105
+ return { status: 415, message: 'Expected application/json' };
106
+ return null;
107
+ }
108
+ /* ------------------------------- factory ------------------------------- */
109
+ export function createAuthRoutes(opts) {
110
+ const activeStatuses = opts.activeStatuses ?? ['active'];
111
+ const perEmail = opts.limits?.perEmail ?? 5;
112
+ const perIp = opts.limits?.perIp ?? 20;
113
+ const windowMs = opts.limits?.windowMs ?? 15 * 60_000;
114
+ const originAllowed = (origin) => {
115
+ if (!opts.allowOrigins)
116
+ return false;
117
+ return typeof opts.allowOrigins === 'function' ? opts.allowOrigins(origin) : opts.allowOrigins.includes(origin);
118
+ };
119
+ /** CORS headers for a request, or nothing when it is same-origin or not allowed. */
120
+ const cors = (request) => {
121
+ const origin = request.headers.get('origin');
122
+ if (!origin || !originAllowed(origin))
123
+ return {};
124
+ return {
125
+ // The exact origin, never "*": a wildcard is ignored when credentials are
126
+ // in play, and these endpoints are nothing but credentials.
127
+ 'Access-Control-Allow-Origin': origin,
128
+ 'Access-Control-Allow-Credentials': 'true',
129
+ Vary: 'Origin',
130
+ };
131
+ };
132
+ const json = (request, body, status = 200, cookieHeaders) => {
133
+ const headers = new Headers({ 'Content-Type': 'application/json', ...cors(request) });
134
+ cookieHeaders?.applyTo(headers);
135
+ return new Response(JSON.stringify(body), { status, headers });
136
+ };
137
+ const clientIp = (request) => firstForwardedIp(request.headers.get('x-forwarded-for')) ?? request.headers.get('x-real-ip') ?? null;
138
+ async function body(request) {
139
+ try {
140
+ const parsed = await request.json();
141
+ return parsed && typeof parsed === 'object' ? parsed : {};
142
+ }
143
+ catch {
144
+ return {};
145
+ }
146
+ }
147
+ return {
148
+ preflight(request) {
149
+ const headers = new Headers({
150
+ ...cors(request),
151
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
152
+ 'Access-Control-Allow-Headers': 'Content-Type',
153
+ 'Access-Control-Max-Age': '600',
154
+ });
155
+ return new Response(null, { status: 204, headers });
156
+ },
157
+ async login(request) {
158
+ // Login CSRF is real: a forged sign-in as the attacker's account puts the
159
+ // victim's later activity in a session the attacker can read.
160
+ const refused = crossSiteWrite(request, originAllowed);
161
+ if (refused)
162
+ return json(request, { error: refused.message }, refused.status);
163
+ const { email, password } = (await body(request));
164
+ if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {
165
+ return json(request, { error: 'Email and password are required' }, 400);
166
+ }
167
+ const ip = clientIp(request);
168
+ if (opts.rateLimit) {
169
+ // Per email AND per IP: per-email alone lets one host walk a user list,
170
+ // per-IP alone lets a botnet grind one account.
171
+ const emailOk = opts.rateLimit(`login:email:${email.toLowerCase()}`, perEmail, windowMs);
172
+ const ipOk = ip ? opts.rateLimit(`login:ip:${ip}`, perIp, windowMs) : true;
173
+ if (!emailOk || !ipOk)
174
+ return json(request, { error: 'Too many attempts. Try again later.' }, 429);
175
+ }
176
+ const user = await opts.findUserByEmail(email);
177
+ // Verify against a real digest even when the account does not exist, so an
178
+ // unknown email costs the same time as a wrong password. Skipping this is
179
+ // how a login endpoint becomes an account-enumeration oracle.
180
+ const digest = user?.passwordHash ?? DUMMY_ARGON2ID_HASH;
181
+ const correct = await verifyPassword(digest, password);
182
+ if (!user || !user.passwordHash || !correct) {
183
+ return json(request, { error: 'Those details do not match an account' }, 401);
184
+ }
185
+ // Status failures ARE distinguishable, deliberately: the person typed the
186
+ // right password, and "your account is suspended" is the only answer that
187
+ // lets them do anything about it. It reveals nothing they did not prove.
188
+ if (user.status != null && !activeStatuses.includes(user.status)) {
189
+ return json(request, { error: `This account is ${user.status}`, status: user.status }, 403);
190
+ }
191
+ const minted = await opts.sessions.mint({
192
+ userId: user.id,
193
+ origin: opts.origin,
194
+ ip,
195
+ userAgent: request.headers.get('user-agent'),
196
+ });
197
+ const jar = headerCookieSetter();
198
+ opts.cookies.set(jar.setter, {
199
+ accessToken: minted.accessToken,
200
+ refreshToken: minted.refreshToken,
201
+ expiresAtMs: Date.now() + minted.expires,
202
+ });
203
+ const row = await opts.sessions.resolveUser(minted.accessToken, { origin: { equals: opts.origin } });
204
+ return json(request, { user: row ? opts.toPublicUser(row) : null, expires: minted.expires }, 200, jar);
205
+ },
206
+ async logout(request) {
207
+ const refused = crossSiteWrite(request, originAllowed);
208
+ if (refused)
209
+ return json(request, { error: refused.message }, refused.status);
210
+ const accessToken = readCookie(request, opts.cookies.names.access);
211
+ const refreshToken = readCookie(request, opts.cookies.names.refresh);
212
+ // The cookies are cleared only once the session is gone. Clearing them over
213
+ // a revoke that failed would leave someone believing they are signed out
214
+ // while their session lives on in the database — the one outcome a logout
215
+ // must never produce. A failure here is a 500 with the cookies intact, so
216
+ // the person sees "try again" rather than a lie.
217
+ try {
218
+ await opts.sessions.revoke({ accessToken, refreshToken });
219
+ }
220
+ catch {
221
+ return json(request, { error: 'Sign-out did not complete — try again' }, 500);
222
+ }
223
+ const jar = headerCookieSetter();
224
+ opts.cookies.clear(jar.setter);
225
+ return json(request, { ok: true }, 200, jar);
226
+ },
227
+ async refresh(request) {
228
+ const refused = crossSiteWrite(request, originAllowed);
229
+ if (refused)
230
+ return json(request, { error: refused.message }, refused.status);
231
+ const refreshToken = readCookie(request, opts.cookies.names.refresh);
232
+ if (!refreshToken)
233
+ return json(request, { error: 'No session' }, 401);
234
+ // Scoped to this surface, as /me is: a refresh cookie carried over from
235
+ // the other surface must not rotate here and come back wearing this
236
+ // surface's cookie names.
237
+ const minted = await opts.sessions.rotate(refreshToken, { origin: { equals: opts.origin } });
238
+ // A 401 here means the token is genuinely spent or unknown. Cookies are NOT
239
+ // cleared: of two concurrent refreshes exactly one wins by design, and
240
+ // clearing on the loser would sign out a perfectly good session.
241
+ if (!minted)
242
+ return json(request, { error: 'Session expired' }, 401);
243
+ const jar = headerCookieSetter();
244
+ opts.cookies.set(jar.setter, {
245
+ accessToken: minted.accessToken,
246
+ refreshToken: minted.refreshToken,
247
+ expiresAtMs: Date.now() + minted.expires,
248
+ });
249
+ return json(request, { expires: minted.expires }, 200, jar);
250
+ },
251
+ async me(request) {
252
+ const accessToken = readCookie(request, opts.cookies.names.access);
253
+ if (!accessToken)
254
+ return json(request, { error: 'Not signed in' }, 401);
255
+ // Scoped to this surface: a cookie lifted from the admin origin and replayed
256
+ // at the site resolves to nothing, which is the point of storing an origin.
257
+ const row = await opts.sessions.resolveUser(accessToken, { origin: { equals: opts.origin } });
258
+ if (!row)
259
+ return json(request, { error: 'Not signed in' }, 401);
260
+ const user = opts.toPublicUser(row);
261
+ const actor = opts.actorFor ? await opts.actorFor(String(row.id)) : undefined;
262
+ return json(request, actor === undefined ? { user } : { user, actor }, 200);
263
+ },
264
+ };
265
+ }
266
+ //# sourceMappingURL=routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,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