@allodium/auth 0.1.0 → 0.2.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 +21 -0
- package/README.md +103 -0
- package/dist/access.d.ts +105 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +101 -0
- package/dist/access.js.map +1 -0
- package/dist/actAs.d.ts +100 -0
- package/dist/actAs.d.ts.map +1 -0
- package/dist/actAs.js +127 -0
- package/dist/actAs.js.map +1 -0
- package/dist/grants.d.ts +53 -0
- package/dist/grants.d.ts.map +1 -0
- package/dist/grants.js +84 -0
- package/dist/grants.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/routes.d.ts +93 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +201 -0
- package/dist/routes.js.map +1 -0
- package/package.json +10 -3
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,103 @@
|
|
|
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
|
+
| **[Act as](../../docs/act-as.md)** | `createActAs` — resolve the app as another user for testing and support, without replacing your session. |
|
|
30
|
+
|
|
31
|
+
## Sessions in one screen
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { createSessionStore, createSessionCookies } from '@allodium/auth';
|
|
35
|
+
|
|
36
|
+
export const sessions = createSessionStore({
|
|
37
|
+
db, // your Drizzle instance
|
|
38
|
+
table: sessionsTable, // your sessions table
|
|
39
|
+
users: usersTable,
|
|
40
|
+
isUserActive: (u) => u.status === 'active',
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const minted = await sessions.mint(user.id, { origin: 'web' });
|
|
44
|
+
const who = await sessions.resolve(accessToken, { origin: { equals: 'web' } });
|
|
45
|
+
const next = await sessions.refresh(refreshToken); // single-use; races have one winner
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The refresh rotation consumes the old token in the same statement that issues the new
|
|
49
|
+
one, so two tabs refreshing simultaneously produce exactly one winner rather than two
|
|
50
|
+
valid sessions or zero.
|
|
51
|
+
|
|
52
|
+
## Act as (user switching)
|
|
53
|
+
|
|
54
|
+
A superadmin resolves the whole application as somebody else — one bar, no logging out.
|
|
55
|
+
Read [docs/act-as.md](../../docs/act-as.md) before wiring it; the security model has
|
|
56
|
+
five properties and they are load-bearing.
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
export const actAs = createActAs({
|
|
60
|
+
secret: () => process.env.AUTH_SECRET!,
|
|
61
|
+
enabled: () => process.env.ACT_AS_ENABLED, // unset: on in dev, off in prod
|
|
62
|
+
isDevelopment: () => process.env.NODE_ENV !== 'production',
|
|
63
|
+
canActAs: (u) => u.role === 'super_admin',
|
|
64
|
+
loadUser: (id) => findUser(id),
|
|
65
|
+
userId: (u) => u.id,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// Hook the ONE function your app reads identity from:
|
|
69
|
+
export async function getCurrentUser() {
|
|
70
|
+
const real = await sessions.resolve(accessToken);
|
|
71
|
+
return (await actAs.resolve(real, ticketCookie)).user;
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Defaults lean safe: off in production, staff cannot be impersonated, and the ticket
|
|
76
|
+
expires in 8 hours.
|
|
77
|
+
|
|
78
|
+
## Design notes
|
|
79
|
+
|
|
80
|
+
**Factories, not singletons.** Nothing here reads `process.env`. Where a value is
|
|
81
|
+
env-driven, pass a thunk (`() => process.env.X`) so it keeps call-time semantics rather
|
|
82
|
+
than being captured at import.
|
|
83
|
+
|
|
84
|
+
**Peer dependencies.** `argon2`, `pg` and `drizzle-orm` are peers, never bundled — you
|
|
85
|
+
control the versions, and there is no chance of two copies of the driver.
|
|
86
|
+
|
|
87
|
+
**Directus-compatible hashes.** `verifyPassword` accepts hashes written by Directus, so
|
|
88
|
+
a migration off it needs zero forced password resets. That compatibility is deliberate
|
|
89
|
+
and tested.
|
|
90
|
+
|
|
91
|
+
## Testing
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
node packages/auth/test/integration.mjs # 36 checks, needs DATABASE_URL
|
|
95
|
+
node packages/auth/test/act-as.mjs # 42 checks, no database needed
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The integration battery runs against a real PostgreSQL because that is where the
|
|
99
|
+
semantics live — an atomic rotation that works against a mock proves nothing.
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
MIT. No CLA. The software is free forever; that is what the name means.
|
package/dist/access.d.ts
ADDED
|
@@ -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,MAAM,YAAY,GAAU,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;AAoCrG,gEAAgE;AAChE,S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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"}
|
package/dist/actAs.d.ts
ADDED
|
@@ -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,gBAAgB,GAChB,gBAAgB,GAChB,gBAAgB,GAChB,MAAM,CAAC;AAEX,MAAM,WAAW,UAAU,CAAC,KAAK;IAC/B,2FAA2F;IAC3F,IAAI,EAAE,KAAK,GAAG,IAAI,CAAC;IACnB,kEAAkE;IAClE,IAAI,EAAE,KAAK,GAAG,IAAI,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;IAChB,MAAM,EAAE,KAAK,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,SAAS,CAAC;IAChB,+EAA+E;IAC/E,OAAO,CAAC,EAAE,YAAY,CAAC;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,GAAG,QAAQ,CAAC;IAC9C,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,EAAE,EAAE,IA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AA;KAAE,GAAG;QAAE,EAAE,EAAE,KAAK,CAAC;QAAC,OAAO,EAAE,YAAY,CAAA;KAAE,CAAC,CAAC;IAErI;;;OAGG;IACH,OAAO,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAE3F;;;OAGG;IACH,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IAE/D,mEAAmE;IACnE,aAAa,IAAI;QAAE,QAAQ,EAAE,IAAI,CAAC;QAAC,QAAQ,EAAE,KAAK,CAAC;QAAC,IAAI,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAEjG,kEAAkE;IAClE,kBAAkB,IAAI;QAAE,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,WA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a,EAAE,GAAG,EAAE,CAAC,CAAC;YACpB,QAAQ,EAAE,IAAI;YACd,QAAQ,EAAE,KAAK;YACf,IAAI,EAAE,GAAG;YACT,MAAM,EAAE,aAAa,EAAE;YACvB,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC;SAC/B,CAAC;QACF,kBAAkB,EAAE,GAAG,EAAE,CAAC,CAAC;YACzB,QAAQ,EAAE,IAAI;YACd,QAAQ,EAAE,KAAK;YACf,IAAI,EAAE,GAAG;YACT,MAAM,EAAE,aAAa,EAAE;YACvB,MAAM,EAAE,CAAC;SACV,CAAC;KACH,CAAC;AACJ,CAAC"}
|
package/dist/grants.d.ts
ADDED
|
@@ -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;AA+BD,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,GAAE,kBAAuB,GAAG,WAAW,CA4D3F"}
|
package/dist/grants.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { createAccessPolicy } from './access.js';
|
|
2
|
+
const ident = (n) => '"' + n.replaceAll('"', '""') + '"';
|
|
3
|
+
/** row_filter arrives as jsonb; anything that is not an array of predicates is ignored loudly. */
|
|
4
|
+
function parseFilter(raw, where, problems) {
|
|
5
|
+
if (raw === null || raw === undefined)
|
|
6
|
+
return undefined;
|
|
7
|
+
const value = typeof raw === 'string' ? safeParse(raw) : raw;
|
|
8
|
+
if (!Array.isArray(value)) {
|
|
9
|
+
problems.push(`${where}: row_filter is not an array of predicates — ignored, so this grant covers EVERY row.`);
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
const out = [];
|
|
13
|
+
for (const p of value) {
|
|
14
|
+
if (!p || typeof p !== 'object' || typeof p.column !== 'string') {
|
|
15
|
+
problems.push(`${where}: a row_filter entry has no "column" — ignored.`);
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
out.push(p);
|
|
19
|
+
}
|
|
20
|
+
return out.length ? out : undefined;
|
|
21
|
+
}
|
|
22
|
+
function safeParse(s) {
|
|
23
|
+
try {
|
|
24
|
+
return JSON.parse(s);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function createGrantLoader(db, opts = {}) {
|
|
31
|
+
const rolesTable = opts.rolesTable ?? 'roles';
|
|
32
|
+
const grantsTable = opts.grantsTable ?? 'role_permissions';
|
|
33
|
+
const userRolesTable = opts.userRolesTable ?? 'user_roles';
|
|
34
|
+
const ttl = opts.ttlMs ?? 30_000;
|
|
35
|
+
let cache = null;
|
|
36
|
+
async function load() {
|
|
37
|
+
if (cache && Date.now() - cache.at < ttl)
|
|
38
|
+
return cache;
|
|
39
|
+
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,
|
|
40
|
+
${ /* row_filter is newer than the table; tolerate its absence */''}
|
|
41
|
+
to_jsonb(g) -> 'row_filter' as row_filter
|
|
42
|
+
from ${ident(grantsTable)} g
|
|
43
|
+
join ${ident(rolesTable)} r on r.id = g.role_id
|
|
44
|
+
order by r.key, g.table_name`);
|
|
45
|
+
const problems = [];
|
|
46
|
+
const grants = res.rows.map((row) => ({
|
|
47
|
+
role: String(row.role),
|
|
48
|
+
table: String(row.table_name),
|
|
49
|
+
create: !!row.can_create,
|
|
50
|
+
read: !!row.can_read,
|
|
51
|
+
update: !!row.can_update,
|
|
52
|
+
delete: !!row.can_delete,
|
|
53
|
+
...(() => {
|
|
54
|
+
const f = parseFilter(row.row_filter, `${row.role} on ${row.table_name}`, problems);
|
|
55
|
+
return f ? { rowFilter: f } : {};
|
|
56
|
+
})(),
|
|
57
|
+
}));
|
|
58
|
+
cache = { at: Date.now(), grants, problems };
|
|
59
|
+
return cache;
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
async grants() {
|
|
63
|
+
return (await load()).grants;
|
|
64
|
+
},
|
|
65
|
+
async policy() {
|
|
66
|
+
const { grants, problems } = await load();
|
|
67
|
+
const policy = createAccessPolicy(grants, { superuserRoles: opts.superuserRoles });
|
|
68
|
+
// Loading problems and configuration problems are the same kind of thing to
|
|
69
|
+
// whoever has to fix them, so they arrive in one list.
|
|
70
|
+
return { ...policy, problems: [...problems, ...policy.problems] };
|
|
71
|
+
},
|
|
72
|
+
async rolesFor(userId) {
|
|
73
|
+
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]);
|
|
74
|
+
return res.rows.map((r) => r.key);
|
|
75
|
+
},
|
|
76
|
+
async actorFor(userId, claims = {}) {
|
|
77
|
+
return { userId, roles: await this.rolesFor(userId), claims };
|
|
78
|
+
},
|
|
79
|
+
refresh() {
|
|
80
|
+
cache = null;
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
//# 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,CAA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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
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
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
|
|
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"}
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
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 whatever the cookie jar holds, always succeeds. */
|
|
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
|
+
export declare function createAuthRoutes(opts: AuthRoutesOptions): AuthRoutes;
|
|
93
|
+
//# 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,cAAc,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD;;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;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;AAID,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,iBAAiB,GAAG,UAAU,CAmJpE"}
|
package/dist/routes.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
/* ------------------------------- factory ------------------------------- */
|
|
65
|
+
export function createAuthRoutes(opts) {
|
|
66
|
+
const activeStatuses = opts.activeStatuses ?? ['active'];
|
|
67
|
+
const perEmail = opts.limits?.perEmail ?? 5;
|
|
68
|
+
const perIp = opts.limits?.perIp ?? 20;
|
|
69
|
+
const windowMs = opts.limits?.windowMs ?? 15 * 60_000;
|
|
70
|
+
const originAllowed = (origin) => {
|
|
71
|
+
if (!opts.allowOrigins)
|
|
72
|
+
return false;
|
|
73
|
+
return typeof opts.allowOrigins === 'function' ? opts.allowOrigins(origin) : opts.allowOrigins.includes(origin);
|
|
74
|
+
};
|
|
75
|
+
/** CORS headers for a request, or nothing when it is same-origin or not allowed. */
|
|
76
|
+
const cors = (request) => {
|
|
77
|
+
const origin = request.headers.get('origin');
|
|
78
|
+
if (!origin || !originAllowed(origin))
|
|
79
|
+
return {};
|
|
80
|
+
return {
|
|
81
|
+
// The exact origin, never "*": a wildcard is ignored when credentials are
|
|
82
|
+
// in play, and these endpoints are nothing but credentials.
|
|
83
|
+
'Access-Control-Allow-Origin': origin,
|
|
84
|
+
'Access-Control-Allow-Credentials': 'true',
|
|
85
|
+
Vary: 'Origin',
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
const json = (request, body, status = 200, cookieHeaders) => {
|
|
89
|
+
const headers = new Headers({ 'Content-Type': 'application/json', ...cors(request) });
|
|
90
|
+
cookieHeaders?.applyTo(headers);
|
|
91
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
92
|
+
};
|
|
93
|
+
const clientIp = (request) => firstForwardedIp(request.headers.get('x-forwarded-for')) ?? request.headers.get('x-real-ip') ?? null;
|
|
94
|
+
async function body(request) {
|
|
95
|
+
try {
|
|
96
|
+
const parsed = await request.json();
|
|
97
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return {};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
preflight(request) {
|
|
105
|
+
const headers = new Headers({
|
|
106
|
+
...cors(request),
|
|
107
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
108
|
+
'Access-Control-Allow-Headers': 'Content-Type',
|
|
109
|
+
'Access-Control-Max-Age': '600',
|
|
110
|
+
});
|
|
111
|
+
return new Response(null, { status: 204, headers });
|
|
112
|
+
},
|
|
113
|
+
async login(request) {
|
|
114
|
+
const { email, password } = (await body(request));
|
|
115
|
+
if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {
|
|
116
|
+
return json(request, { error: 'Email and password are required' }, 400);
|
|
117
|
+
}
|
|
118
|
+
const ip = clientIp(request);
|
|
119
|
+
if (opts.rateLimit) {
|
|
120
|
+
// Per email AND per IP: per-email alone lets one host walk a user list,
|
|
121
|
+
// per-IP alone lets a botnet grind one account.
|
|
122
|
+
const emailOk = opts.rateLimit(`login:email:${email.toLowerCase()}`, perEmail, windowMs);
|
|
123
|
+
const ipOk = ip ? opts.rateLimit(`login:ip:${ip}`, perIp, windowMs) : true;
|
|
124
|
+
if (!emailOk || !ipOk)
|
|
125
|
+
return json(request, { error: 'Too many attempts. Try again later.' }, 429);
|
|
126
|
+
}
|
|
127
|
+
const user = await opts.findUserByEmail(email);
|
|
128
|
+
// Verify against a real digest even when the account does not exist, so an
|
|
129
|
+
// unknown email costs the same time as a wrong password. Skipping this is
|
|
130
|
+
// how a login endpoint becomes an account-enumeration oracle.
|
|
131
|
+
const digest = user?.passwordHash ?? DUMMY_ARGON2ID_HASH;
|
|
132
|
+
const correct = await verifyPassword(digest, password);
|
|
133
|
+
if (!user || !user.passwordHash || !correct) {
|
|
134
|
+
return json(request, { error: 'Those details do not match an account' }, 401);
|
|
135
|
+
}
|
|
136
|
+
// Status failures ARE distinguishable, deliberately: the person typed the
|
|
137
|
+
// right password, and "your account is suspended" is the only answer that
|
|
138
|
+
// lets them do anything about it. It reveals nothing they did not prove.
|
|
139
|
+
if (user.status != null && !activeStatuses.includes(user.status)) {
|
|
140
|
+
return json(request, { error: `This account is ${user.status}`, status: user.status }, 403);
|
|
141
|
+
}
|
|
142
|
+
const minted = await opts.sessions.mint({
|
|
143
|
+
userId: user.id,
|
|
144
|
+
origin: opts.origin,
|
|
145
|
+
ip,
|
|
146
|
+
userAgent: request.headers.get('user-agent'),
|
|
147
|
+
});
|
|
148
|
+
const jar = headerCookieSetter();
|
|
149
|
+
opts.cookies.set(jar.setter, {
|
|
150
|
+
accessToken: minted.accessToken,
|
|
151
|
+
refreshToken: minted.refreshToken,
|
|
152
|
+
expiresAtMs: Date.now() + minted.expires,
|
|
153
|
+
});
|
|
154
|
+
const row = await opts.sessions.resolveUser(minted.accessToken, { origin: { equals: opts.origin } });
|
|
155
|
+
return json(request, { user: row ? opts.toPublicUser(row) : null, expires: minted.expires }, 200, jar);
|
|
156
|
+
},
|
|
157
|
+
async logout(request) {
|
|
158
|
+
const accessToken = readCookie(request, opts.cookies.names.access);
|
|
159
|
+
const refreshToken = readCookie(request, opts.cookies.names.refresh);
|
|
160
|
+
// Best effort, and 200 regardless: a logout that fails leaves someone
|
|
161
|
+
// believing they are signed out when they are not, which is worse than a
|
|
162
|
+
// revoke that was already unnecessary.
|
|
163
|
+
await opts.sessions.revoke({ accessToken, refreshToken }).catch(() => { });
|
|
164
|
+
const jar = headerCookieSetter();
|
|
165
|
+
opts.cookies.clear(jar.setter);
|
|
166
|
+
return json(request, { ok: true }, 200, jar);
|
|
167
|
+
},
|
|
168
|
+
async refresh(request) {
|
|
169
|
+
const refreshToken = readCookie(request, opts.cookies.names.refresh);
|
|
170
|
+
if (!refreshToken)
|
|
171
|
+
return json(request, { error: 'No session' }, 401);
|
|
172
|
+
const minted = await opts.sessions.rotate(refreshToken);
|
|
173
|
+
// A 401 here means the token is genuinely spent or unknown. Cookies are NOT
|
|
174
|
+
// cleared: of two concurrent refreshes exactly one wins by design, and
|
|
175
|
+
// clearing on the loser would sign out a perfectly good session.
|
|
176
|
+
if (!minted)
|
|
177
|
+
return json(request, { error: 'Session expired' }, 401);
|
|
178
|
+
const jar = headerCookieSetter();
|
|
179
|
+
opts.cookies.set(jar.setter, {
|
|
180
|
+
accessToken: minted.accessToken,
|
|
181
|
+
refreshToken: minted.refreshToken,
|
|
182
|
+
expiresAtMs: Date.now() + minted.expires,
|
|
183
|
+
});
|
|
184
|
+
return json(request, { expires: minted.expires }, 200, jar);
|
|
185
|
+
},
|
|
186
|
+
async me(request) {
|
|
187
|
+
const accessToken = readCookie(request, opts.cookies.names.access);
|
|
188
|
+
if (!accessToken)
|
|
189
|
+
return json(request, { error: 'Not signed in' }, 401);
|
|
190
|
+
// Scoped to this surface: a cookie lifted from the admin origin and replayed
|
|
191
|
+
// at the site resolves to nothing, which is the point of storing an origin.
|
|
192
|
+
const row = await opts.sessions.resolveUser(accessToken, { origin: { equals: opts.origin } });
|
|
193
|
+
if (!row)
|
|
194
|
+
return json(request, { error: 'Not signed in' }, 401);
|
|
195
|
+
const user = opts.toPublicUser(row);
|
|
196
|
+
const actor = opts.actorFor ? await opts.actorFor(String(row.id)) : undefined;
|
|
197
|
+
return json(request, actor === undefined ? { user } : { user, actor }, 200);
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
//# 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,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AA+E3C,6EAA6E;AAE7E,MAAM,IAAI,GAA2B;IACnC,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,SAAS;IACjB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;CACnB,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB;IAChC,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,OAAO;QACL,MAAM,EAAE;YACN,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,UAAmC,EAAE;gBAC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AAK,EAAE,eAAe,EAAE,EAAE,GAAG,CAAC,CAAC;YAEhE,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;YACpC,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAE,GAAwB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YACpG,OAAO,IAAI,CAAC,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,GAAG,CAAC,CAAC;QAC9E,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@allodium/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "First-party auth you own: argon2 passwords, session store, rotating refresh, OIDC, WebAuthn passkeys, reset emails, tenant membership.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/glossydev/allodium.git",
|
|
9
|
+
"directory": "packages/auth"
|
|
10
|
+
},
|
|
6
11
|
"type": "module",
|
|
7
12
|
"main": "./dist/index.js",
|
|
8
13
|
"types": "./dist/index.d.ts",
|
|
@@ -10,14 +15,16 @@
|
|
|
10
15
|
".": {
|
|
11
16
|
"types": "./dist/index.d.ts",
|
|
12
17
|
"import": "./dist/index.js"
|
|
13
|
-
}
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
14
20
|
},
|
|
15
21
|
"files": [
|
|
16
22
|
"dist"
|
|
17
23
|
],
|
|
18
24
|
"scripts": {
|
|
19
25
|
"build": "tsc -p tsconfig.json",
|
|
20
|
-
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
26
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
27
|
+
"test": "node test/act-as.mjs && node test/access.mjs && node test/grants.mjs && node test/routes.mjs"
|
|
21
28
|
},
|
|
22
29
|
"engines": {
|
|
23
30
|
"node": ">=20"
|