@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Adam Aronoff (GlossyDev)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,159 @@
1
+ # @allodium/auth
2
+
3
+ First-party authentication you own outright. Sessions, passwords, reset tokens, rate
4
+ limiting, and a user switcher — extracted from a production SaaS, not written for a
5
+ demo.
6
+
7
+ Every export is a **factory taking explicit config**. The package reads no environment
8
+ variables and imports no framework, so your app binds names, secrets and tables once
9
+ and re-exports. That is what makes it usable from a Next.js route handler, an Express
10
+ middleware, or a script.
11
+
12
+ ```bash
13
+ npm install @allodium/auth
14
+ # peers, which you almost certainly already have:
15
+ npm install argon2 pg drizzle-orm
16
+ ```
17
+
18
+ Requires Node 20+ and PostgreSQL.
19
+
20
+ ## What's in it
21
+
22
+ | | |
23
+ |---|---|
24
+ | **Passwords** | `hashPassword` / `verifyPassword` — argon2id, with a dummy hash for timing equalization so "no such user" and "wrong password" cost the same. |
25
+ | **Sessions** | `createSessionStore` — opaque tokens, sha256 at rest, single-use refresh rotation that is atomic under concurrency, sliding expiry, cross-surface origin scoping. |
26
+ | **Cookies** | `createSessionCookies` — the access/refresh/CSRF triple, with Domain-correct clearing (the bug where a cookie "won't delete" is almost always this). |
27
+ | **Reset tokens** | `createResetTokens` — stateless HMAC, keyed partly on the user's *current* password hash, so a successful reset invalidates every outstanding token with no bookkeeping. |
28
+ | **Rate limiting** | `createRateLimiter` — sliding window, in-process, fail-open. |
29
+ | **Routes** | `createAuthRoutes` — login, logout, refresh and me as Web `Request → Response` handlers, with the details that are easy to get wrong already right. |
30
+ | **Grants** | `createAccessPolicy` / `createGrantLoader` — role × table × action, with optional row filters (`customer_id = $actor.customerId`). What `@allodium/admin` enforces. |
31
+ | **[Act as](../../docs/act-as.md)** | `createActAs` — resolve the app as another user for testing and support, without replacing your session. |
32
+
33
+ ## Sessions in one screen
34
+
35
+ ```ts
36
+ import { createSessionStore, createSessionCookies } from '@allodium/auth';
37
+
38
+ export const sessions = createSessionStore({
39
+ db, // your Drizzle instance
40
+ sessions: sessionsTable, // your sessions table — the shape is in sessions.ts
41
+ users: usersTable,
42
+ accessPrefix: 'app_at_', // how these tokens are recognised; unique to your app
43
+ refreshPrefix: 'app_rt_',
44
+ isUserActive: (u) => u.status === 'active',
45
+ });
46
+
47
+ const minted = await sessions.mint({ userId: user.id, origin: 'web' });
48
+ const who = await sessions.resolveUser(accessToken, { origin: { equals: 'web' } });
49
+ const next = await sessions.rotate(refreshToken, { origin: { equals: 'web' } }); // single-use; races have one winner
50
+ await sessions.revoke({ accessToken, refreshToken }); // logout: by either token
51
+ ```
52
+
53
+ The refresh rotation consumes the old token in the same statement that issues the new
54
+ one, so two tabs refreshing simultaneously produce exactly one winner rather than two
55
+ valid sessions or zero. Rotation also refuses a session whose user is no longer active
56
+ and, when scoped, one minted for another surface — a suspended account cannot keep its
57
+ session alive by refreshing. Revocation matches **either** token, because after a
58
+ rotation in another tab the access cookie is stale while the refresh cookie is live, and
59
+ revoking by the first one found would delete nothing.
60
+
61
+ ## The four routes
62
+
63
+ ```ts
64
+ import { createAuthRoutes, createRateLimiter, readCookie, PUBLIC_ACTOR } from '@allodium/auth';
65
+
66
+ export const auth = createAuthRoutes({
67
+ sessions,
68
+ cookies: createSessionCookies({ names: { access: 'at', refresh: 'rt', expires: 'exp' }, maxAgeSec: 7 * 86400, secure: true }),
69
+ origin: 'web', // the surface these sessions belong to
70
+ findUserByEmail: (email) => /* { id, passwordHash, status } | null */,
71
+ toPublicUser: (row) => ({ id: row.id, email: row.email }), // REQUIRED: what /me may say
72
+ actorFor: (id) => grants.actorFor(id, claims), // optional: roles + claims on /me
73
+ rateLimit: createRateLimiter(),
74
+ allowOrigins: ['https://app.example.com'], // omit for same-origin
75
+ });
76
+
77
+ // Next.js: app/api/auth/[action]/route.ts → auth.login(req) / auth.logout(req) / auth.refresh(req) / auth.me(req)
78
+ ```
79
+
80
+ What they get right so you do not have to: a wrong password and an unknown email answer
81
+ identically, in the same time; `/me` returns only what `toPublicUser` says; a lost
82
+ refresh race does not clear the winner's cookies; logout clears cookies only once the
83
+ session is actually gone (a 500 with cookies intact otherwise); and a POST from an origin
84
+ that is neither this host nor allowlisted, or with a body not typed as JSON, is refused
85
+ — CORS headers say who may read a response, not who may send a request.
86
+
87
+ ## Grants
88
+
89
+ ```ts
90
+ const grants = createGrantLoader(pool); // reads roles / user_roles / role_permissions
91
+ const policy = await grants.policy(); // cached 30 s; grants.refresh() after editing
92
+ const actor = await grants.actorFor(userId, { customerId: 42 });
93
+
94
+ policy.can(actor, 'orders', 'read');
95
+ // → { allowed: true, scope: [{ column: 'customer_id', op: 'eq', value: 42 }], reason: '…' }
96
+ policy.can(PUBLIC_ACTOR, 'orders', 'read');
97
+ // → { allowed: false, scope: [], reason: 'no grant for read on orders (holding: public)' }
98
+ ```
99
+
100
+ A `row_filter` on a grant is a JSON array of predicates; `$actor.<claim>` substitutes a
101
+ claim the app supplied, and a missing claim **denies**. So does a filter that cannot be
102
+ read — `{}` where `[]` was meant — which refuses the whole grant rather than quietly
103
+ widening it to every row. `policy.problems` lists what was refused and why. A
104
+ `super_admin` role bypasses the model by name and holds no rows.
105
+
106
+ ## Act as (user switching)
107
+
108
+ A superadmin resolves the whole application as somebody else — one bar, no logging out.
109
+ Read [docs/act-as.md](../../docs/act-as.md) before wiring it; the security model has
110
+ five properties and they are load-bearing.
111
+
112
+ ```ts
113
+ export const actAs = createActAs({
114
+ secret: () => process.env.AUTH_SECRET!,
115
+ enabled: () => process.env.ACT_AS_ENABLED, // unset: on in dev, off in prod
116
+ isDevelopment: () => process.env.NODE_ENV !== 'production',
117
+ canActAs: (u) => u.role === 'super_admin',
118
+ loadUser: (id) => findUser(id),
119
+ userId: (u) => u.id,
120
+ });
121
+
122
+ // Hook the ONE function your app reads identity from:
123
+ export async function getCurrentUser() {
124
+ const real = await sessions.resolve(accessToken);
125
+ return (await actAs.resolve(real, ticketCookie)).user;
126
+ }
127
+ ```
128
+
129
+ Defaults lean safe: off in production, staff cannot be impersonated, and the ticket
130
+ expires in 8 hours.
131
+
132
+ ## Design notes
133
+
134
+ **Factories, not singletons.** Nothing here reads `process.env`. Where a value is
135
+ env-driven, pass a thunk (`() => process.env.X`) so it keeps call-time semantics rather
136
+ than being captured at import.
137
+
138
+ **Peer dependencies.** `argon2`, `pg` and `drizzle-orm` are peers, never bundled — you
139
+ control the versions, and there is no chance of two copies of the driver.
140
+
141
+ **Directus-compatible hashes.** `verifyPassword` accepts hashes written by Directus, so
142
+ a migration off it needs zero forced password resets. That compatibility is deliberate
143
+ and tested.
144
+
145
+ ## Testing
146
+
147
+ ```bash
148
+ npm test -w packages/auth # the whole battery; the database-backed files skip without DATABASE_URL
149
+ node packages/auth/test/integration.mjs # sessions, needs DATABASE_URL
150
+ node packages/auth/test/act-as.mjs # 42 checks, no database needed
151
+ node packages/auth/test/loader.mjs # the grant loader fails closed, no database needed
152
+ ```
153
+
154
+ The integration battery runs against a real PostgreSQL because that is where the
155
+ semantics live — an atomic rotation that works against a mock proves nothing.
156
+
157
+ ## License
158
+
159
+ MIT. No CLA. The software is free forever; that is what the name means.
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Who is asking, and what they may see.
3
+ *
4
+ * Authentication answers "who are you"; this answers "what does that let you
5
+ * touch". It lives beside the session store because both are about the principal,
6
+ * and because the content API and the admin API have to gate identically — one
7
+ * enforcement path, not two implementations that drift.
8
+ *
9
+ * Pure and synchronous on purpose: grants in, decision out. Loading grants is a
10
+ * database question and lives in `createGrantLoader`; enforcing a decision is a
11
+ * SQL question and lives in the resolver. Keeping the DECISION free of both is
12
+ * what makes the rules testable by reading them back, which matters more here
13
+ * than anywhere else in this codebase — a permission bug is silent and expensive.
14
+ */
15
+ export type Action = 'create' | 'read' | 'update' | 'delete';
16
+ export declare const ACTIONS: readonly Action[];
17
+ /**
18
+ * A predicate restricting which ROWS a grant covers.
19
+ *
20
+ * Structurally identical to `@allodium/admin`'s `Predicate`, and deliberately so:
21
+ * a grant's row filter is handed straight to the resolver's scope channel with no
22
+ * translation step. It is redeclared rather than imported because auth must not
23
+ * depend on admin — the content API needs this gate without the admin runtime.
24
+ * The two shapes have to stay compatible; that is a guard worth writing when the
25
+ * resolver is wired, not a comment worth trusting.
26
+ *
27
+ * `value` may reference the actor: `"$actor.customerId"` resolves from the
28
+ * actor's claims at decision time.
29
+ */
30
+ export interface GrantPredicate {
31
+ column: string;
32
+ op?: string;
33
+ value?: unknown;
34
+ }
35
+ /** One role's permission on one table. */
36
+ export interface Grant {
37
+ role: string;
38
+ table: string;
39
+ create: boolean;
40
+ read: boolean;
41
+ update: boolean;
42
+ delete: boolean;
43
+ /**
44
+ * Rows this grant covers. Absent or empty means every row.
45
+ *
46
+ * This is the half a table×action matrix cannot express — "a member sees their
47
+ * own orders" is a grant on `orders` restricted to `customer_id = $actor.customerId`.
48
+ */
49
+ rowFilter?: GrantPredicate[];
50
+ }
51
+ /**
52
+ * The principal a request runs as.
53
+ *
54
+ * `roles` is a SET, not a role: `users` is one table for staff and customers, and
55
+ * the seed's own comment says a person may hold several at once (staff who also
56
+ * shop). Grants therefore UNION across roles rather than resolving to one.
57
+ */
58
+ export interface Actor {
59
+ /** Null for anonymous — which is a real actor with real grants, not an absence. */
60
+ userId: string | null;
61
+ /** Role keys held. */
62
+ roles: string[];
63
+ /**
64
+ * Values a granted row filter may reference. `$actor.customerId` reads
65
+ * `claims.customerId`. The app supplies these: which column identifies "this
66
+ * person's rows" is domain knowledge, not something a library can infer.
67
+ */
68
+ claims: Record<string, unknown>;
69
+ }
70
+ export declare const PUBLIC_ROLE = "public";
71
+ /** Anonymous. Carries the public role, so unauthenticated access is granted, never assumed. */
72
+ export declare const PUBLIC_ACTOR: Actor;
73
+ export interface AccessDecision {
74
+ allowed: boolean;
75
+ /**
76
+ * Predicates to AND into the query. Empty means unrestricted — which is only
77
+ * ever the result of an unrestricted grant, never of a missing one.
78
+ */
79
+ scope: GrantPredicate[];
80
+ /** Why, in words. Goes in logs and refusal bodies; a denial should never be a mystery. */
81
+ reason: string;
82
+ }
83
+ export interface AccessPolicyOptions {
84
+ /**
85
+ * Roles that bypass the grant model entirely. Named rather than hardcoded, but
86
+ * defaulted, because a deployment that forgets to configure this should still
87
+ * have a working super_admin rather than a silently locked-out one.
88
+ *
89
+ * A superuser role holds ZERO grant rows deliberately: grants on it would be
90
+ * misleading, since it never consults them. That makes "no rows found" and "not
91
+ * permitted" the same shape in the data and completely different in meaning —
92
+ * so they must never share a code path.
93
+ */
94
+ superuserRoles?: string[];
95
+ }
96
+ export interface AccessPolicy {
97
+ /** May this actor do this to this table, and over which rows? */
98
+ can(actor: Actor, table: string, action: Action): AccessDecision;
99
+ /** Every grant that applies to an actor, for debugging and for the console to show. */
100
+ grantsFor(actor: Actor): Grant[];
101
+ /** Configuration this policy cannot honour — surfaced, never silently ignored. */
102
+ problems: string[];
103
+ }
104
+ export declare function createAccessPolicy(grants: Grant[], opts?: AccessPolicyOptions): AccessPolicy;
105
+ //# sourceMappingURL=access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,MAAM,MAAM,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAE7D,eAAO,MAAM,OAAO,EAAE,SAAS,MAAM,EAA2C,CAAC;AAEjF;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,0CAA0C;AAC1C,MAAM,WAAW,KAAK;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,OAAO,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,OAAO,CAAC;IAChB,MAAM,EAAE,OAAO,CAAC;IAChB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,cAAc,EAAE,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,MAAM,WAAW,KAAK;IACpB,mFAAmF;IACnF,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,sBAAsB;IACtB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAED,eAAO,MAAM,WAAW,WAAW,CAAC;AAEpC,+FAA+F;AAC/F,eAAO,MAAM,YAAY,EAAE,KAAyE,CAAC;AAErG,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAC;IACjB;;;OAGG;IACH,KAAK,EAAE,cAAc,EAAE,CAAC;IACxB,0FAA0F;IAC1F,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mBAAmB;IAClC;;;;;;;;;OASG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3B;AAED,MAAM,WAAW,YAAY;IAC3B,iEAAiE;IACjE,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,cAAc,CAAC;IACjE,uFAAuF;IACvF,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,KAAK,EAAE,CAAC;IACjC,kFAAkF;IAClF,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AA2BD,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,IAAI,GAAE,mBAAwB,GAAG,YAAY,CAyEhG"}
package/dist/access.js ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Who is asking, and what they may see.
3
+ *
4
+ * Authentication answers "who are you"; this answers "what does that let you
5
+ * touch". It lives beside the session store because both are about the principal,
6
+ * and because the content API and the admin API have to gate identically — one
7
+ * enforcement path, not two implementations that drift.
8
+ *
9
+ * Pure and synchronous on purpose: grants in, decision out. Loading grants is a
10
+ * database question and lives in `createGrantLoader`; enforcing a decision is a
11
+ * SQL question and lives in the resolver. Keeping the DECISION free of both is
12
+ * what makes the rules testable by reading them back, which matters more here
13
+ * than anywhere else in this codebase — a permission bug is silent and expensive.
14
+ */
15
+ export const ACTIONS = ['create', 'read', 'update', 'delete'];
16
+ export const PUBLIC_ROLE = 'public';
17
+ /** Anonymous. Carries the public role, so unauthenticated access is granted, never assumed. */
18
+ export const PUBLIC_ACTOR = Object.freeze({ userId: null, roles: [PUBLIC_ROLE], claims: {} });
19
+ /** Resolve `$actor.x` references against the actor's claims. */
20
+ function substitute(predicates, actor) {
21
+ const out = [];
22
+ for (const p of predicates) {
23
+ if (typeof p.value !== 'string' || !p.value.startsWith('$actor.')) {
24
+ out.push(p);
25
+ continue;
26
+ }
27
+ const claim = p.value.slice('$actor.'.length);
28
+ const value = claim === 'userId' ? actor.userId : actor.claims[claim];
29
+ // A claim the actor does not carry must DENY, never widen. Dropping the
30
+ // predicate would turn "your own orders" into "all orders" — the failure
31
+ // mode that makes row-level rules worse than none.
32
+ if (value === undefined || value === null)
33
+ return { ok: false, missing: claim };
34
+ out.push({ ...p, value });
35
+ }
36
+ return { ok: true, scope: out };
37
+ }
38
+ const sameFilter = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
39
+ export function createAccessPolicy(grants, opts = {}) {
40
+ const superuserRoles = opts.superuserRoles ?? ['super_admin'];
41
+ const problems = [];
42
+ for (const g of grants) {
43
+ if (superuserRoles.includes(g.role)) {
44
+ problems.push(`"${g.role}" is a superuser role and bypasses the grant model, but a grant on ${g.table} exists for it — it has no effect and reads as if it did.`);
45
+ }
46
+ }
47
+ const grantsFor = (actor) => grants.filter((g) => actor.roles.includes(g.role));
48
+ return {
49
+ problems,
50
+ grantsFor,
51
+ can(actor, table, action) {
52
+ const superRole = actor.roles.find((r) => superuserRoles.includes(r));
53
+ if (superRole) {
54
+ // Explicit branch, deliberately before any grant lookup: a superuser is
55
+ // allowed BECAUSE of the role, not because a search happened to find
56
+ // something. Sharing the "found grants" path would mean a query bug that
57
+ // returns nothing reads as "permitted" for exactly the wrong account.
58
+ return { allowed: true, scope: [], reason: `role "${superRole}" bypasses the permission model` };
59
+ }
60
+ const applicable = grants.filter((g) => actor.roles.includes(g.role) && g.table === table && g[action]);
61
+ if (!applicable.length) {
62
+ const held = actor.roles.length ? actor.roles.join(', ') : 'no roles';
63
+ return { allowed: false, scope: [], reason: `no grant for ${action} on ${table} (holding: ${held})` };
64
+ }
65
+ // The most permissive grant wins: holding two roles cannot leave you with
66
+ // less than either alone. One unrestricted grant therefore ends it.
67
+ const unrestricted = applicable.find((g) => !g.rowFilter?.length);
68
+ if (unrestricted) {
69
+ return { allowed: true, scope: [], reason: `"${unrestricted.role}" may ${action} all of ${table}` };
70
+ }
71
+ // Every applicable grant is row-restricted. Their union is an OR, and the
72
+ // scope channel is AND-only by design, so distinct filters cannot be
73
+ // combined without inventing a boolean tree the query layer will not take.
74
+ // Refuse rather than pick one and be quietly wrong in someone's favour.
75
+ const distinct = applicable.filter((g, i) => applicable.findIndex((o) => sameFilter(o.rowFilter, g.rowFilter)) === i);
76
+ if (distinct.length > 1) {
77
+ return {
78
+ allowed: false,
79
+ scope: [],
80
+ reason: `${distinct.map((g) => `"${g.role}"`).join(' and ')} each restrict ${action} on ${table} to different rows, and those cannot be combined — grant one of them the full table, or give them the same restriction`,
81
+ };
82
+ }
83
+ const chosen = distinct[0];
84
+ // "Its own rows" only if the filter actually references the actor. A grant
85
+ // restricted to published posts is not ownership, and a reason string that
86
+ // says it is will mislead whoever reads it in a log at 2am.
87
+ const owned = chosen.rowFilter.some((p) => typeof p.value === 'string' && p.value.startsWith('$actor.'));
88
+ const which = owned ? 'its own rows of' : 'some rows of';
89
+ const sub = substitute(chosen.rowFilter, actor);
90
+ if (!sub.ok) {
91
+ return {
92
+ allowed: false,
93
+ scope: [],
94
+ reason: `"${chosen.role}" may ${action} only ${which} ${table}, but this actor carries no "${sub.missing}" claim`,
95
+ };
96
+ }
97
+ return { allowed: true, scope: sub.scope, reason: `"${chosen.role}" may ${action} ${which} ${table}` };
98
+ },
99
+ };
100
+ }
101
+ //# sourceMappingURL=access.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.js","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,MAAM,CAAC,MAAM,OAAO,GAAsB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;AA0DjF,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC;AAEpC,+FAA+F;AAC/F,MAAM,CAAC,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G,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,kBAAkB,MAAM,OAAO,KAAK,wHAAwH;iBACxN,CAAC;YACJ,CAAC;YAED,MAAM,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;YAC3B,2EAA2E;YAC3E,2EAA2E;YAC3E,4DAA4D;YAC5D,MAAM,KAAK,GAAG,MAAM,CAAC,SAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,KAAK,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;YAC1G,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,cAAc,CAAC;YAEzD,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,CAAC,SAAU,EAAE,KAAK,CAAC,CAAC;YACjD,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;gBACZ,OAAO;oBACL,OAAO,EAAE,KAAK;oBACd,KAAK,EAAE,EAAE;oBACT,MAAM,EAAE,IAAI,MAAM,CAAC,IAAI,SAAS,MAAM,SAAS,KAAK,IAAI,KAAK,gCAAgC,GAAG,CAAC,OAAO,SAAS;iBAClH,CAAC;YACJ,CAAC;YACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,MAAM,CAAC,IAAI,SAAS,MAAM,IAAI,KAAK,IAAI,KAAK,EAAE,EAAE,CAAC;QACzG,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,100 @@
1
+ export type ActAsMode = 'full' | 'readonly';
2
+ /** Why an act-as request produced no impersonation. Surfaced, never swallowed. */
3
+ export type ActAsRefusal = 'disabled' | 'no-session' | 'invalid-ticket' | 'expired' | 'actor-mismatch' | 'not-authorized' | 'target-missing' | 'target-blocked' | 'self';
4
+ export interface ActAsState<TUser> {
5
+ /** The identity the application should use. The target when acting, else the real user. */
6
+ user: TUser | null;
7
+ /** Who is really signed in. Authority decisions must use THIS. */
8
+ real: TUser | null;
9
+ acting: boolean;
10
+ target: TUser | null;
11
+ mode: ActAsMode;
12
+ /** Set when a ticket was present but not honoured — show it, don't hide it. */
13
+ refusal?: ActAsRefusal;
14
+ }
15
+ export interface ActAsAuditEvent {
16
+ type: 'start' | 'stop' | 'refused' | 'active';
17
+ actorId: string | null;
18
+ targetId: string | null;
19
+ mode: ActAsMode;
20
+ refusal?: ActAsRefusal;
21
+ at: Date;
22
+ }
23
+ export interface CreateActAsOptions<TUser> {
24
+ /** HMAC key. A thunk keeps call-time semantics for env-driven config. */
25
+ secret: string | (() => string);
26
+ /**
27
+ * Master switch. Unset means ON in development and OFF in production, so an
28
+ * unconsidered deploy ships without it — the same posture as an unset allowlist.
29
+ * Pass `isDevelopment` for that default to work; without it, unset means OFF.
30
+ */
31
+ enabled?: () => boolean | string | undefined | null;
32
+ isDevelopment?: () => boolean;
33
+ /** May this user start an impersonation? Re-run on EVERY request. */
34
+ canActAs: (actor: TUser) => boolean | Promise<boolean>;
35
+ /**
36
+ * May this user be impersonated? Defaults to blocking anyone who can themselves
37
+ * act as others — i.e. staff — because impersonating staff is a bigger decision
38
+ * than impersonating a customer and should be opted into.
39
+ */
40
+ canBeTarget?: (target: TUser, actor: TUser) => boolean | Promise<boolean>;
41
+ /** Load a user by id. Your query, your shape. */
42
+ loadUser: (id: string) => Promise<TUser | null>;
43
+ /** How to read an id off your user object. */
44
+ userId: (user: TUser) => string;
45
+ /**
46
+ * Full or read-only for this actor. Default: full only for the top tier
47
+ * (whoever passes canActAs) — but see `readOnlyUnless` for a narrower rule.
48
+ */
49
+ mode?: (actor: TUser) => ActAsMode | Promise<ActAsMode>;
50
+ /** Ticket lifetime. Default 8 hours — a working day, not a standing grant. */
51
+ ttlMs?: number;
52
+ /** Called for every start, stop, refusal and active request. Write audit rows here. */
53
+ onAudit?: (event: ActAsAuditEvent) => void | Promise<void>;
54
+ }
55
+ export interface ActAs<TUser> {
56
+ /** Is the feature switched on right now? */
57
+ enabled(): boolean;
58
+ /**
59
+ * Mint a ticket. Returns the cookie VALUE; setting the cookie is the caller's
60
+ * job (see `cookieOptions`). Every guard runs here AND again on every resolve.
61
+ */
62
+ start(actor: TUser, targetId: string): Promise<{
63
+ ok: true;
64
+ ticket: string;
65
+ mode: ActAsMode;
66
+ } | {
67
+ ok: false;
68
+ refusal: ActAsRefusal;
69
+ }>;
70
+ /**
71
+ * Resolve effective identity. Give it the REAL session user and the raw cookie
72
+ * value; it returns who the app should behave as.
73
+ */
74
+ resolve(real: TUser | null, ticket: string | null | undefined): Promise<ActAsState<TUser>>;
75
+ /**
76
+ * Guard for write methods while read-only. Returns true when the request should
77
+ * be refused. Wire it into your middleware or your write helpers.
78
+ */
79
+ blocksWrite(state: ActAsState<TUser>, method: string): boolean;
80
+ /** Cookie attributes for the ticket — host-only, httpOnly, lax. */
81
+ cookieOptions(): {
82
+ httpOnly: true;
83
+ sameSite: 'lax';
84
+ path: '/';
85
+ secure: boolean;
86
+ maxAge: number;
87
+ };
88
+ /** Attributes that delete the ticket. Call this on logout too. */
89
+ clearCookieOptions(): {
90
+ httpOnly: true;
91
+ sameSite: 'lax';
92
+ path: '/';
93
+ secure: boolean;
94
+ maxAge: 0;
95
+ };
96
+ /** Suggested cookie name; use anything you like. */
97
+ readonly cookieName: string;
98
+ }
99
+ export declare function createActAs<TUser>(opts: CreateActAsOptions<TUser>): ActAs<TUser>;
100
+ //# sourceMappingURL=actAs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actAs.d.ts","sourceRoot":"","sources":["../src/actAs.ts"],"names":[],"mappings":"AA0DA,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,UAAU,CAAC;AAE5C,kFAAkF;AAClF,MAAM,MAAM,YAAY,GACpB,UAAU,GACV,YAAY,GACZ,gBAAgB,GAChB,SAAS,GACT,gBAAgB,GAChB,gBAA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AE,QAAQ,EAAE,IAAI,CAAC;QAAC,QAAQ,EAAE,KAAK,CAAC;QAAC,IAAI,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,CAAC,CAAA;KAAE,CAAC;IAEjG,oDAAoD;IACpD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B;AAID,wBAAgB,WAAW,CAAC,KAAK,EAAE,IAAI,EAAE,kBAAkB,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAkIhF"}
package/dist/actAs.js ADDED
@@ -0,0 +1,127 @@
1
+ import { signPayload, verifySignedPayload } from './signedTokens.js';
2
+ const DEFAULT_TTL_MS = 8 * 60 * 60 * 1000;
3
+ export function createActAs(opts) {
4
+ const secretOf = () => (typeof opts.secret === 'function' ? opts.secret() : opts.secret);
5
+ const ttl = opts.ttlMs ?? DEFAULT_TTL_MS;
6
+ const audit = (e) => {
7
+ try {
8
+ void opts.onAudit?.(e);
9
+ }
10
+ catch {
11
+ /* auditing must never break the request it describes */
12
+ }
13
+ };
14
+ function enabled() {
15
+ const raw = opts.enabled?.();
16
+ if (raw === undefined || raw === null || raw === '') {
17
+ // Unset: on in development, off everywhere else. Without isDevelopment we
18
+ // cannot tell, so we take the safe branch.
19
+ return opts.isDevelopment?.() ?? false;
20
+ }
21
+ if (typeof raw === 'boolean')
22
+ return raw;
23
+ const v = String(raw).toLowerCase();
24
+ return v === '1' || v === 'true' || v === 'yes' || v === 'on';
25
+ }
26
+ /** Default: you may not impersonate anyone who is themselves able to impersonate. */
27
+ const canBeTarget = async (target, actor) => {
28
+ if (opts.canBeTarget)
29
+ return opts.canBeTarget(target, actor);
30
+ return !(await opts.canActAs(target));
31
+ };
32
+ const modeFor = async (actor) => (opts.mode ? opts.mode(actor) : 'full');
33
+ async function start(actor, targetId) {
34
+ const actorId = opts.userId(actor);
35
+ const refuse = (refusal) => {
36
+ audit({ type: 'refused', actorId, targetId, mode: 'readonly', refusal, at: new Date() });
37
+ return { ok: false, refusal };
38
+ };
39
+ if (!enabled())
40
+ return refuse('disabled');
41
+ if (!(await opts.canActAs(actor)))
42
+ return refuse('not-authorized');
43
+ if (String(targetId) === actorId)
44
+ return refuse('self');
45
+ const target = await opts.loadUser(String(targetId));
46
+ if (!target)
47
+ return refuse('target-missing');
48
+ if (!(await canBeTarget(target, actor)))
49
+ return refuse('target-blocked');
50
+ const mode = await modeFor(actor);
51
+ const payload = {
52
+ t: opts.userId(target),
53
+ a: actorId,
54
+ m: mode === 'readonly' ? 'r' : 'f',
55
+ e: Math.floor((Date.now() + ttl) / 1000),
56
+ };
57
+ audit({ type: 'start', actorId, targetId: payload.t, mode, at: new Date() });
58
+ return { ok: true, ticket: signPayload(secretOf(), payload), mode };
59
+ }
60
+ async function resolve(real, ticket) {
61
+ const base = { user: real, real, acting: false, target: null, mode: 'full' };
62
+ if (!ticket)
63
+ return base;
64
+ if (!real)
65
+ return { ...base, refusal: 'no-session' };
66
+ const actorId = opts.userId(real);
67
+ // The master switch is checked HERE as well as at start, so flipping it off
68
+ // ends impersonations already in flight rather than only preventing new ones.
69
+ if (!enabled())
70
+ return { ...base, refusal: 'disabled' };
71
+ const payload = verifySignedPayload(secretOf(), ticket);
72
+ if (!payload || typeof payload.t !== 'string' || typeof payload.a !== 'string') {
73
+ return { ...base, refusal: 'invalid-ticket' };
74
+ }
75
+ if (typeof payload.e !== 'number' || payload.e * 1000 < Date.now()) {
76
+ return { ...base, refusal: 'expired' };
77
+ }
78
+ // Bound to the actor: a stolen cookie in someone else's browser does nothing.
79
+ if (payload.a !== actorId) {
80
+ audit({ type: 'refused', actorId, targetId: payload.t, mode: 'readonly', refusal: 'actor-mismatch', at: new Date() });
81
+ return { ...base, refusal: 'actor-mismatch' };
82
+ }
83
+ // THE re-check. Authority comes from the live session, never from the ticket.
84
+ if (!(await opts.canActAs(real))) {
85
+ audit({ type: 'refused', actorId, targetId: payload.t, mode: 'readonly', refusal: 'not-authorized', at: new Date() });
86
+ return { ...base, refusal: 'not-authorized' };
87
+ }
88
+ const target = await opts.loadUser(payload.t);
89
+ if (!target)
90
+ return { ...base, refusal: 'target-missing' };
91
+ if (!(await canBeTarget(target, real))) {
92
+ return { ...base, refusal: 'target-blocked' };
93
+ }
94
+ const mode = payload.m === 'r' ? 'readonly' : 'full';
95
+ audit({ type: 'active', actorId, targetId: payload.t, mode, at: new Date() });
96
+ return { user: target, real, acting: true, target, mode };
97
+ }
98
+ function blocksWrite(state, method) {
99
+ if (!state.acting || state.mode !== 'readonly')
100
+ return false;
101
+ const m = method.toUpperCase();
102
+ return m !== 'GET' && m !== 'HEAD' && m !== 'OPTIONS';
103
+ }
104
+ const secureCookies = () => !(opts.isDevelopment?.() ?? false);
105
+ return {
106
+ cookieName: 'allodium_act_as',
107
+ enabled,
108
+ start,
109
+ resolve,
110
+ blocksWrite,
111
+ cookieOptions: () => ({
112
+ httpOnly: true,
113
+ sameSite: 'lax',
114
+ path: '/',
115
+ secure: secureCookies(),
116
+ maxAge: Math.floor(ttl / 1000),
117
+ }),
118
+ clearCookieOptions: () => ({
119
+ httpOnly: true,
120
+ sameSite: 'lax',
121
+ path: '/',
122
+ secure: secureCookies(),
123
+ maxAge: 0,
124
+ }),
125
+ };
126
+ }
127
+ //# sourceMappingURL=actAs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actAs.js","sourceRoot":"","sources":["../src/actAs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAsKrE,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE1C,MAAM,UAAU,WAAW,CAAQ,IAA+B;IAChE,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,CAAC,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CA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