@allodium/auth 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -84,6 +84,31 @@ session is actually gone (a 500 with cookies intact otherwise); and a POST from
84
84
  that is neither this host nor allowlisted, or with a body not typed as JSON, is refused
85
85
  — CORS headers say who may read a response, not who may send a request.
86
86
 
87
+ ## Machine callers
88
+
89
+ A job runner, another service, an agent's tooling, a deploy script: no cookie jar, and
90
+ the usual answer is one shared secret in an environment variable that nobody can rotate,
91
+ scope, revoke or attribute. Instead, a row per token:
92
+
93
+ ```ts
94
+ import { createApiTokens } from '@allodium/auth';
95
+
96
+ const tokens = createApiTokens(pool, { prefix: 'myapp_' }); // table api_tokens, see dev/seed/008
97
+
98
+ const { token } = await tokens.mint({ label: 'nightly invoicing', userId }); // shown ONCE
99
+ const service = await tokens.mint({ label: 'the deploy box', roles: ['deployer'] }); // no user: its roles alone
100
+
101
+ // In actorFor, before the cookie:
102
+ const t = await tokens.resolve(request); // Authorization: Bearer …, or null
103
+ if (t) return t.userId ? grants.actorFor(t.userId, claims) : { userId: null, roles: t.roles, claims: {} };
104
+ ```
105
+
106
+ The database holds only a SHA-256 digest. `resolve` answers null the same way for a
107
+ missing header, a wrong prefix, an unknown, expired or revoked token, and touches
108
+ `last_used_at` at most once a minute. A service token has no user, so a grant on "your
109
+ own rows" denies it — a service owns none. Bearer requests carry no cookies, so the
110
+ cross-site check on writes does not apply to them: a curl is not a cross-site form.
111
+
87
112
  ## Grants
88
113
 
89
114
  ```ts
@@ -98,7 +123,17 @@ policy.can(PUBLIC_ACTOR, 'orders', 'read');
98
123
  ```
99
124
 
100
125
  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
126
+ claim the app supplied, and a missing claim **denies**. A predicate's column may be a
127
+ **path through foreign keys** when the owner lives on another table — the tasks whose
128
+ project belongs to this client:
129
+
130
+ ```json
131
+ [{ "column": "project_id.client_id", "op": "eq", "value": "$actor.clientId" }]
132
+ ```
133
+
134
+ Each segment but the last must be a foreign-key column on the table it is on; the
135
+ admin runtime follows them through the live catalog and compiles one subquery per hop.
136
+ A path the catalog cannot follow refuses the whole operation rather than widening it. So does a filter that cannot be
102
137
  read — `{}` where `[]` was meant — which refuses the whole grant rather than quietly
103
138
  widening it to every row. `policy.problems` lists what was refused and why. A
104
139
  `super_admin` role bypasses the model by name and holds no rows.
package/dist/index.d.ts CHANGED
@@ -24,4 +24,5 @@ export { firstForwardedIp } from './ip.js';
24
24
  export { createAccessPolicy, PUBLIC_ACTOR, PUBLIC_ROLE, ACTIONS, type Actor, type Action, type Grant, type GrantPredicate, type AccessDecision, type AccessPolicy, type AccessPolicyOptions, } from './access.js';
25
25
  export { createGrantLoader, type GrantLoader, type GrantLoaderOptions, } from './grants.js';
26
26
  export { createAuthRoutes, headerCookieSetter, readCookie, type AuthRoutes, type AuthRoutesOptions, type AuthUserRow, } from './routes.js';
27
+ export { createApiTokens, type ApiTokenStore, type ApiTokenStoreOptions, type ApiTokenIdentity, type ApiTokenRow, } from './tokens.js';
27
28
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;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"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;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;AACrB,OAAO,EACL,eAAe,EACf,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACrB,KAAK,WAAW,GACjB,MAAM,aAAa,CAAC"}
package/dist/index.js CHANGED
@@ -24,4 +24,5 @@ export { firstForwardedIp } from './ip.js';
24
24
  export { createAccessPolicy, PUBLIC_ACTOR, PUBLIC_ROLE, ACTIONS, } from './access.js';
25
25
  export { createGrantLoader, } from './grants.js';
26
26
  export { createAuthRoutes, headerCookieSetter, readCookie, } from './routes.js';
27
+ export { createApiTokens, } from './tokens.js';
27
28
  //# 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;;;;;;;;;;;;;;;GAeG;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"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;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;AACrB,OAAO,EACL,eAAe,GAKhB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,87 @@
1
+ import type { Queryable } from './grants.js';
2
+ /**
3
+ * API tokens — how a machine caller becomes an actor.
4
+ *
5
+ * Sessions are for browsers. A job runner, another service, an agent's MCP, a
6
+ * deploy script: none of them has a cookie jar, and the usual answer is one
7
+ * shared secret in an environment variable compared with `!==`, which is a
8
+ * credential nobody can rotate, scope, revoke or attribute. This is the
9
+ * alternative: a row per token, the SECRET STORED AS A DIGEST and shown exactly
10
+ * once at minting, a label that says what holds it, an expiry, a revocation,
11
+ * and a `last_used_at` that says whether it is still in use.
12
+ *
13
+ * A token resolves to an IDENTITY — a user, or a set of roles on its own — and
14
+ * the application turns that into an actor exactly as it does for a session:
15
+ * roles from the token when it carries them, otherwise the user's own through
16
+ * the grant loader; claims from wherever the app gets them. The grant model
17
+ * then treats the caller like anyone else. A service token has no user, so a
18
+ * grant on "your own rows" ($actor.userId) denies it, which is the right
19
+ * answer: a service has no own rows.
20
+ *
21
+ * Tokens carry a recognisable prefix so a leaked one can be found by a secret
22
+ * scanner and so a resolve can refuse a non-token without touching the
23
+ * database. The lookup is by SHA-256 digest, so the database compares digests
24
+ * of 32 random bytes, and nothing about equality timing says anything useful
25
+ * about the token.
26
+ *
27
+ * Required table (see dev/seed/008-api-tokens.sql for the DDL):
28
+ * id uuid, label, token_hash char(64) unique, user_id uuid null,
29
+ * roles text[], created_at, expires_at null, last_used_at null, revoked_at null
30
+ */
31
+ export interface ApiTokenIdentity {
32
+ id: string;
33
+ label: string;
34
+ /** The user this token acts as, or null for a service token that acts as its roles alone. */
35
+ userId: string | null;
36
+ /** Role keys the token carries. Empty means "the user's own roles" — resolve those through the grant loader. */
37
+ roles: string[];
38
+ }
39
+ export interface ApiTokenRow extends ApiTokenIdentity {
40
+ createdAt: string;
41
+ expiresAt: string | null;
42
+ lastUsedAt: string | null;
43
+ revokedAt: string | null;
44
+ }
45
+ export interface ApiTokenStoreOptions {
46
+ /** Default "api_tokens". */
47
+ table?: string;
48
+ /** Column names, when they differ from the seed's. */
49
+ columns?: Partial<Record<'id' | 'label' | 'tokenHash' | 'userId' | 'roles' | 'createdAt' | 'expiresAt' | 'lastUsedAt' | 'revokedAt', string>>;
50
+ /** What every token starts with. Default "ak_". Pick one unique to your app so a leak is attributable. */
51
+ prefix?: string;
52
+ /** How often a token's last_used_at is written. Default 60 s: a token used in a tight loop must not write on every call. */
53
+ touchEveryMs?: number;
54
+ }
55
+ export interface ApiTokenStore {
56
+ /** Does this look like one of our tokens? Prefix only; no database. */
57
+ isToken(value: unknown): boolean;
58
+ /**
59
+ * Create a token. The returned `token` is the only time the secret exists in
60
+ * plaintext — show it once, store nothing but the digest.
61
+ */
62
+ mint(args: {
63
+ label: string;
64
+ userId?: string | null;
65
+ roles?: string[];
66
+ expiresAt?: Date | string | null;
67
+ }): Promise<{
68
+ id: string;
69
+ token: string;
70
+ }>;
71
+ /**
72
+ * The identity behind a bearer token, or null. Takes a Request (reads
73
+ * `Authorization: Bearer …`) or the token itself. Null for a missing header,
74
+ * a wrong prefix, an unknown, expired or revoked token — all the same answer,
75
+ * so the response cannot say which.
76
+ */
77
+ resolve(from: Request | string): Promise<ApiTokenIdentity | null>;
78
+ /** Revoke by id. True if a live token was revoked. */
79
+ revoke(id: string): Promise<boolean>;
80
+ /** Tokens, newest first. Never the digest. */
81
+ list(opts?: {
82
+ userId?: string | null;
83
+ includeRevoked?: boolean;
84
+ }): Promise<ApiTokenRow[]>;
85
+ }
86
+ export declare function createApiTokens(db: Queryable, opts?: ApiTokenStoreOptions): ApiTokenStore;
87
+ //# sourceMappingURL=tokens.d.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C;QAAC,SAAS,CAAC,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAClJ;;;;;OAKG;IACH,OAAO,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC;IAClE,sDAAsD;IACtD,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACrC,8CAA8C;IAC9C,IAAI,CAAC,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,cAAc,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;CAC3F;AAKD,wBAAgB,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,GAAE,oBAAyB,GAAG,aAAa,CA4F7F"}
package/dist/tokens.js ADDED
@@ -0,0 +1,85 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ const sha256 = (t) => createHash('sha256').update(t).digest('hex');
3
+ const ident = (n) => '"' + n.replaceAll('"', '""') + '"';
4
+ export function createApiTokens(db, opts = {}) {
5
+ const table = ident(opts.table ?? 'api_tokens');
6
+ const prefix = opts.prefix ?? 'ak_';
7
+ const touchEveryMs = opts.touchEveryMs ?? 60_000;
8
+ const c = {
9
+ id: 'id',
10
+ label: 'label',
11
+ tokenHash: 'token_hash',
12
+ userId: 'user_id',
13
+ roles: 'roles',
14
+ createdAt: 'created_at',
15
+ expiresAt: 'expires_at',
16
+ lastUsedAt: 'last_used_at',
17
+ revokedAt: 'revoked_at',
18
+ ...(opts.columns ?? {}),
19
+ };
20
+ const col = (k) => ident(c[k]);
21
+ const touched = new Map();
22
+ const isToken = (value) => typeof value === 'string' && value.startsWith(prefix) && value.length > prefix.length + 16;
23
+ const bearer = (request) => {
24
+ const m = /^\s*Bearer\s+(\S+)\s*$/i.exec(request.headers.get('authorization') ?? '');
25
+ return m ? m[1] : null;
26
+ };
27
+ const toRow = (r) => ({
28
+ id: String(r[c.id]),
29
+ label: String(r[c.label]),
30
+ userId: r[c.userId] === null || r[c.userId] === undefined ? null : String(r[c.userId]),
31
+ roles: Array.isArray(r[c.roles]) ? r[c.roles].map(String) : [],
32
+ createdAt: String(r[c.createdAt]),
33
+ expiresAt: r[c.expiresAt] === null || r[c.expiresAt] === undefined ? null : String(r[c.expiresAt]),
34
+ lastUsedAt: r[c.lastUsedAt] === null || r[c.lastUsedAt] === undefined ? null : String(r[c.lastUsedAt]),
35
+ revokedAt: r[c.revokedAt] === null || r[c.revokedAt] === undefined ? null : String(r[c.revokedAt]),
36
+ });
37
+ const columnsSansDigest = ['id', 'label', 'userId', 'roles', 'createdAt', 'expiresAt', 'lastUsedAt', 'revokedAt'].map(col).join(', ');
38
+ return {
39
+ isToken,
40
+ async mint(args) {
41
+ const token = prefix + randomBytes(32).toString('base64url');
42
+ const expires = args.expiresAt instanceof Date ? args.expiresAt.toISOString() : (args.expiresAt ?? null);
43
+ const res = await db.query(`insert into ${table} (${col('label')}, ${col('tokenHash')}, ${col('userId')}, ${col('roles')}, ${col('expiresAt')}) values ($1, $2, $3, $4, $5) returning ${col('id')} as id`, [args.label, sha256(token), args.userId ?? null, args.roles ?? [], expires]);
44
+ return { id: String(res.rows[0].id), token };
45
+ },
46
+ async resolve(from) {
47
+ const token = typeof from === 'string' ? from : bearer(from);
48
+ if (!isToken(token))
49
+ return null;
50
+ const res = await db.query(`select ${columnsSansDigest} from ${table}
51
+ where ${col('tokenHash')} = $1 and ${col('revokedAt')} is null and (${col('expiresAt')} is null or ${col('expiresAt')} > now()) limit 1`, [sha256(token)]);
52
+ const row = res.rows[0];
53
+ if (!row)
54
+ return null;
55
+ const found = toRow(row);
56
+ const last = touched.get(found.id) ?? 0;
57
+ if (Date.now() - last > touchEveryMs) {
58
+ touched.set(found.id, Date.now());
59
+ // Bookkeeping must never fail the request it describes.
60
+ await db.query(`update ${table} set ${col('lastUsedAt')} = now() where ${col('id')} = $1`, [found.id]).catch(() => { });
61
+ }
62
+ return { id: found.id, label: found.label, userId: found.userId, roles: found.roles };
63
+ },
64
+ async revoke(id) {
65
+ const res = await db.query(`update ${table} set ${col('revokedAt')} = now() where ${col('id')} = $1 and ${col('revokedAt')} is null`, [id]);
66
+ touched.delete(id);
67
+ return (res.rowCount ?? 0) > 0;
68
+ },
69
+ async list(o = {}) {
70
+ const where = [];
71
+ const params = [];
72
+ if (o.userId !== undefined) {
73
+ if (o.userId === null)
74
+ where.push(`${col('userId')} is null`);
75
+ else
76
+ where.push(`${col('userId')} = $${params.push(o.userId)}`);
77
+ }
78
+ if (!o.includeRevoked)
79
+ where.push(`${col('revokedAt')} is null`);
80
+ const res = await db.query(`select ${columnsSansDigest} from ${table}${where.length ? ' where ' + where.join(' and ') : ''} order by ${col('createdAt')} desc`, params);
81
+ return res.rows.map(toRow);
82
+ },
83
+ };
84
+ }
85
+ //# sourceMappingURL=tokens.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokens.js","sourceRoot":"","sources":["../src/tokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAiFtD,MAAM,MAAM,GAAG,CAAC,CAAS,EAAU,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACnF,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,GAAG,CAAC;AAEjE,MAAM,UAAU,eAAe,CAAC,EAAa,EAAE,OAA6B,EAAE;IAC5E,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,K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GED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allodium/auth",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "First-party auth you own: argon2id passwords, a session store with rotating refresh and cross-surface scoping, the four auth routes, role and row-level grants, reset and state tokens, rate limiting, act-as.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -24,7 +24,7 @@
24
24
  "scripts": {
25
25
  "build": "tsc -p tsconfig.json",
26
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 && node test/loader.mjs"
27
+ "test": "node test/act-as.mjs && node test/access.mjs && node test/grants.mjs && node test/routes.mjs && node test/loader.mjs && node test/tokens.mjs"
28
28
  },
29
29
  "engines": {
30
30
  "node": ">=20"