@allodium/auth 0.3.1 → 0.5.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,90 @@ 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
+ ## Optional entry points
88
+
89
+ Two flows every application rewrites, shipped as separate imports so a project that wants
90
+ neither loads neither. Each takes the decisions as callbacks and owns the ceremony.
91
+
92
+ ### Password reset — `@allodium/auth/reset`
93
+
94
+ ```ts
95
+ import { createResetRoutes } from '@allodium/auth/reset';
96
+
97
+ export const reset = createResetRoutes({
98
+ tokens: createResetTokens({ secret: () => process.env.AUTH_SECRET }),
99
+ sessions,
100
+ findUserByEmail, findUserById, // → { id, email, passwordHash, status }
101
+ setPasswordHash: (id, hash) => db.update(...), // the one write it makes
102
+ resetUrl: (token) => `${SITE}/reset?token=${encodeURIComponent(token)}`,
103
+ sendMail: ({ to, resetUrl, user }) => mailer.send(...), // your provider, your template
104
+ rateLimit: createRateLimiter(),
105
+ });
106
+ // POST /api/auth/reset/request { email } → always 200
107
+ // POST /api/auth/reset { token, password } → 200 | 400 weak | 401 not valid | 403 inactive
108
+ ```
109
+
110
+ The request endpoint answers identically whether or not the email exists and does not
111
+ wait for the mail to send, so timing says nothing either. A token is keyed on the
112
+ user's current hash, so it dies the moment the password changes; every session is
113
+ revoked in the same breath, because a reset that leaves an intruder's session alive has
114
+ not reset anything.
115
+
116
+ ### OpenID sign-in — `@allodium/auth/oidc`
117
+
118
+ ```ts
119
+ import { createOidcLogin, GOOGLE_ISSUER } from '@allodium/auth/oidc';
120
+
121
+ export const google = createOidcLogin({
122
+ issuer: GOOGLE_ISSUER,
123
+ clientId: process.env.GOOGLE_CLIENT_ID!,
124
+ clientSecret: () => process.env.GOOGLE_CLIENT_SECRET!,
125
+ redirectUri: `${SITE}/api/auth/google/callback`,
126
+ stateSecret: () => process.env.AUTH_SECRET!,
127
+ authParams: { prompt: 'select_account' },
128
+ onIdentity: async (claims) => findOrCreateUser(claims), // THE decision; null refuses
129
+ sessions, cookies, origin: 'site',
130
+ successRedirect: '/account',
131
+ failureRedirect: '/login', // gets ?error=<reason>
132
+ });
133
+ // GET /api/auth/google → google.start(req)
134
+ // GET /api/auth/google/callback → google.callback(req)
135
+ ```
136
+
137
+ Endpoints come from the provider's discovery document (or name them). The state is
138
+ signed into an HttpOnly cookie with a nonce, so a callback is bound to the browser that
139
+ started the flow. The identity token is **verified**, not trusted: signature against
140
+ the provider's published keys (refetched once on an unknown key id), issuer, audience,
141
+ expiry and nonce, and `email_verified` unless you say otherwise. Refusals redirect with
142
+ a reason — `state`, `token`, `unverified-email`, `not-registered`, `inactive` — and
143
+ never mint a session. Passkeys are planned as `@allodium/auth/passkeys` on the same
144
+ pattern, over an optional WebAuthn peer.
145
+
146
+ ## Machine callers
147
+
148
+ A job runner, another service, an agent's tooling, a deploy script: no cookie jar, and
149
+ the usual answer is one shared secret in an environment variable that nobody can rotate,
150
+ scope, revoke or attribute. Instead, a row per token:
151
+
152
+ ```ts
153
+ import { createApiTokens } from '@allodium/auth';
154
+
155
+ const tokens = createApiTokens(pool, { prefix: 'myapp_' }); // table api_tokens, see dev/seed/008
156
+
157
+ const { token } = await tokens.mint({ label: 'nightly invoicing', userId }); // shown ONCE
158
+ const service = await tokens.mint({ label: 'the deploy box', roles: ['deployer'] }); // no user: its roles alone
159
+
160
+ // In actorFor, before the cookie:
161
+ const t = await tokens.resolve(request); // Authorization: Bearer …, or null
162
+ if (t) return t.userId ? grants.actorFor(t.userId, claims) : { userId: null, roles: t.roles, claims: {} };
163
+ ```
164
+
165
+ The database holds only a SHA-256 digest. `resolve` answers null the same way for a
166
+ missing header, a wrong prefix, an unknown, expired or revoked token, and touches
167
+ `last_used_at` at most once a minute. A service token has no user, so a grant on "your
168
+ own rows" denies it — a service owns none. Bearer requests carry no cookies, so the
169
+ cross-site check on writes does not apply to them: a curl is not a cross-site form.
170
+
87
171
  ## Grants
88
172
 
89
173
  ```ts
@@ -98,7 +182,17 @@ policy.can(PUBLIC_ACTOR, 'orders', 'read');
98
182
  ```
99
183
 
100
184
  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
185
+ claim the app supplied, and a missing claim **denies**. A predicate's column may be a
186
+ **path through foreign keys** when the owner lives on another table — the tasks whose
187
+ project belongs to this client:
188
+
189
+ ```json
190
+ [{ "column": "project_id.client_id", "op": "eq", "value": "$actor.clientId" }]
191
+ ```
192
+
193
+ Each segment but the last must be a foreign-key column on the table it is on; the
194
+ admin runtime follows them through the live catalog and compiles one subquery per hop.
195
+ A path the catalog cannot follow refuses the whole operation rather than widening it. So does a filter that cannot be
102
196
  read — `{}` where `[]` was meant — which refuses the whole grant rather than quietly
103
197
  widening it to every row. `policy.problems` lists what was refused and why. A
104
198
  `super_admin` role bypasses the model by name and holds no rows.
package/dist/http.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The little HTTP plumbing the route factories share: an origin allowlist,
3
+ * CORS headers for a request, a JSON response that carries cookies, and a
4
+ * redirect that does the same. Kept here so the optional entry points
5
+ * (./reset, ./oidc) do not each grow their own copy.
6
+ */
7
+ export type AllowOrigins = string[] | ((origin: string) => boolean) | undefined;
8
+ export declare const originAllowedBy: (allow: AllowOrigins) => (origin: string) => boolean;
9
+ /** CORS headers for a request, or nothing when it is same-origin or not allowed. Exact origin, never "*". */
10
+ export declare function corsHeaders(request: Request, allow: AllowOrigins): Record<string, string>;
11
+ export interface CookieJar {
12
+ applyTo(headers: Headers): void;
13
+ }
14
+ export declare function jsonResponse(request: Request, allow: AllowOrigins, body: unknown, status?: number, jar?: CookieJar): Response;
15
+ export declare function redirectResponse(location: string, jar?: CookieJar): Response;
16
+ export declare function preflightResponse(request: Request, allow: AllowOrigins, methods: string): Response;
17
+ /** The first client IP, from the proxy header or nothing. */
18
+ export declare function clientIp(request: Request): string | null;
19
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,MAAM,YAAY,GAAG,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,SAAS,CAAC;AAEhF,eAAO,MAAM,eAAe,GACzB,OAAO,YAAY,MACnB,QAAQ,MAAM,KAAG,OACiE,CAAC;AAEtF,6GAA6G;AAC7G,wBAAgB,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAIzF;AAED,MAAM,WAAW,SAAS;IACxB,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;CACjC;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,SAAM,EAAE,GAAG,CAAC,EAAE,SAAS,GAAG,QAAQ,CAI1H;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,SAAS,GAAG,QAAQ,CAI5E;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,GAAG,QAAQ,CAKlG;AAED,6DAA6D;AAC7D,wBAAgB,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAOxD"}
package/dist/http.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The little HTTP plumbing the route factories share: an origin allowlist,
3
+ * CORS headers for a request, a JSON response that carries cookies, and a
4
+ * redirect that does the same. Kept here so the optional entry points
5
+ * (./reset, ./oidc) do not each grow their own copy.
6
+ */
7
+ export const originAllowedBy = (allow) => (origin) => !!allow && (typeof allow === 'function' ? allow(origin) : allow.includes(origin));
8
+ /** CORS headers for a request, or nothing when it is same-origin or not allowed. Exact origin, never "*". */
9
+ export function corsHeaders(request, allow) {
10
+ const origin = request.headers.get('origin');
11
+ if (!origin || !originAllowedBy(allow)(origin))
12
+ return {};
13
+ return { 'Access-Control-Allow-Origin': origin, 'Access-Control-Allow-Credentials': 'true', Vary: 'Origin' };
14
+ }
15
+ export function jsonResponse(request, allow, body, status = 200, jar) {
16
+ const headers = new Headers({ 'Content-Type': 'application/json', ...corsHeaders(request, allow) });
17
+ jar?.applyTo(headers);
18
+ return new Response(JSON.stringify(body), { status, headers });
19
+ }
20
+ export function redirectResponse(location, jar) {
21
+ const headers = new Headers({ Location: location });
22
+ jar?.applyTo(headers);
23
+ return new Response(null, { status: 302, headers });
24
+ }
25
+ export function preflightResponse(request, allow, methods) {
26
+ return new Response(null, {
27
+ status: 204,
28
+ headers: { ...corsHeaders(request, allow), 'Access-Control-Allow-Methods': methods, 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '600' },
29
+ });
30
+ }
31
+ /** The first client IP, from the proxy header or nothing. */
32
+ export function clientIp(request) {
33
+ const fwd = request.headers.get('x-forwarded-for');
34
+ if (fwd) {
35
+ const first = fwd.split(',')[0]?.trim();
36
+ if (first)
37
+ return first;
38
+ }
39
+ return request.headers.get('x-real-ip') ?? null;
40
+ }
41
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,MAAM,CAAC,MAAM,eAAe,GAC1B,CAAC,KAAmB,EAAE,EAAE,CACxB,CAAC,MAAc,EAAW,EAAE,CAC1B,CAAC,CAAC,KAAK,IAAI,CAAC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAA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CAAC,IAAI,EAAE;QACxB,MAAM,EAAE,GAAG;QACX,OAAO,EAAE,EAAE,GAAG,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,8BAA8B,EAAE,OAAO,EAAE,8BAA8B,EAAE,cAAc,EAAE,wBAAwB,EAAE,KAAK,EAAE;KACtK,CAAC,CAAC;AACL,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,QAAQ,CAAC,OAAgB;IACvC,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IACnD,IAAI,GAAG,EAAE,CAAC;QACR,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC;QACxC,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC;IAC1B,CAAC;IACD,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC;AAClD,CAAC"}
package/dist/index.d.ts CHANGED
@@ -10,9 +10,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
12
  * plus an "act as" user switcher that hooks your one identity seam.
13
- * OpenID sign-in, passkeys and password-reset routes are planned as separate entry
14
- * points (@allodium/auth/oidc, /passkeys, /reset) so a project that wants none of
15
- * them installs none of them. They are not in this version.
13
+ * OpenID sign-in (./oidc) and password-reset routes (./reset) are separate entry
14
+ * points so a project that wants neither loads neither; passkeys (./passkeys) will
15
+ * follow on the same pattern, over an optional WebAuthn peer.
16
16
  */
17
17
  export { hashPassword, verifyPassword, DUMMY_ARGON2ID_HASH } from './passwords.js';
18
18
  export { createRateLimiter, type RateLimiter } from './rateLimit.js';
@@ -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
@@ -10,9 +10,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
12
  * plus an "act as" user switcher that hooks your one identity seam.
13
- * OpenID sign-in, passkeys and password-reset routes are planned as separate entry
14
- * points (@allodium/auth/oidc, /passkeys, /reset) so a project that wants none of
15
- * them installs none of them. They are not in this version.
13
+ * OpenID sign-in (./oidc) and password-reset routes (./reset) are separate entry
14
+ * points so a project that wants neither loads neither; passkeys (./passkeys) will
15
+ * follow on the same pattern, over an optional WebAuthn peer.
16
16
  */
17
17
  export { hashPassword, verifyPassword, DUMMY_ARGON2ID_HASH } from './passwords.js';
18
18
  export { createRateLimiter } from './rateLimit.js';
@@ -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"}
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,121 @@
1
+ import type { SessionStore } from './sessions.js';
2
+ import type { SessionCookies } from './cookies.js';
3
+ /**
4
+ * @allodium/auth/oidc — sign in with an OpenID Connect provider (Google, and
5
+ * anything else that publishes a discovery document), written once.
6
+ *
7
+ * The ceremony is the same everywhere and the mistakes are the same
8
+ * everywhere: a state that is not bound to the browser that started the
9
+ * flow, a token exchange that trusts the response, and — the common one — an
10
+ * identity token whose SIGNATURE is never checked, on the grounds that it
11
+ * arrived over TLS from the provider. It did; but the thing that decides who
12
+ * you are has to be verified, not trusted, and the provider publishes its
13
+ * keys precisely so that you can. This verifies: signature against the
14
+ * provider's current keys, issuer, audience, expiry, and the nonce this
15
+ * browser was handed when the flow began.
16
+ *
17
+ * What stays yours is the one real decision, `onIdentity`: given verified
18
+ * claims, which of your users is this — found, created, or refused. The
19
+ * package never touches your users table.
20
+ *
21
+ * Optional entry point: import from '@allodium/auth/oidc'.
22
+ */
23
+ export interface OidcClaims {
24
+ iss: string;
25
+ sub: string;
26
+ aud: string | string[];
27
+ exp: number;
28
+ iat?: number;
29
+ nonce?: string;
30
+ email?: string;
31
+ email_verified?: boolean;
32
+ name?: string;
33
+ given_name?: string;
34
+ family_name?: string;
35
+ picture?: string;
36
+ hd?: string;
37
+ [claim: string]: unknown;
38
+ }
39
+ export type OidcFailure = 'provider' | 'state' | 'exchange' | 'token' | 'unverified-email' | 'not-registered' | 'inactive';
40
+ export type OidcEvent = {
41
+ type: 'started';
42
+ } | {
43
+ type: 'signed-in';
44
+ userId: string;
45
+ sub: string;
46
+ } | {
47
+ type: 'refused';
48
+ reason: OidcFailure;
49
+ detail?: string;
50
+ sub?: string;
51
+ };
52
+ export interface OidcLoginOptions {
53
+ /** The provider's issuer, exactly as it appears in its tokens — "https://accounts.google.com". */
54
+ issuer: string;
55
+ clientId: string;
56
+ clientSecret: string | (() => string);
57
+ /** The absolute URL of your callback route, registered with the provider. */
58
+ redirectUri: string;
59
+ /** Default "openid email profile". */
60
+ scope?: string;
61
+ /** Extra authorization parameters — `{ prompt: 'select_account' }`, `{ hd: 'example.com' }`. */
62
+ authParams?: Record<string, string>;
63
+ /** Skip discovery by naming the endpoints yourself. */
64
+ endpoints?: {
65
+ authorization: string;
66
+ token: string;
67
+ jwks: string;
68
+ };
69
+ /** Signs the state cookie. Any long random string. */
70
+ stateSecret: string | (() => string);
71
+ /** How long a started flow stays valid. Default 10 minutes. */
72
+ stateTtlMs?: number;
73
+ /** Default "oidc_state". Scope it per surface if two flows can share a host. */
74
+ stateCookie?: string;
75
+ /** Secure attribute on the state cookie. Default: true unless redirectUri is http. */
76
+ cookieSecure?: boolean | (() => boolean);
77
+ /** Refuse a token whose email_verified is not true. Default true. Set false only for a provider that never sends it. */
78
+ requireVerifiedEmail?: boolean;
79
+ /**
80
+ * THE decision: which of your users these verified claims are. Find them by
81
+ * `sub` (stable) or by email, create them if that is your policy, or return
82
+ * null to refuse. Whatever you return is signed in.
83
+ */
84
+ onIdentity(claims: OidcClaims, ctx: {
85
+ request: Request;
86
+ }): Promise<{
87
+ id: string;
88
+ status?: string | null;
89
+ } | null>;
90
+ sessions: Pick<SessionStore, 'mint'>;
91
+ cookies: SessionCookies;
92
+ /** The surface the session belongs to — same value your other routes use. */
93
+ origin: string;
94
+ /** Statuses allowed to sign in. Defaults to ['active']. */
95
+ activeStatuses?: string[];
96
+ /** Where to send the browser after signing in. */
97
+ successRedirect: string | ((user: {
98
+ id: string;
99
+ }) => string);
100
+ /** Where to send it when the flow fails. A string gets `?error=<reason>`; a function gets the reason. */
101
+ failureRedirect: string | ((reason: OidcFailure) => string);
102
+ /** Injectable for tests. Default globalThis.fetch. */
103
+ fetch?: typeof fetch;
104
+ /** Clock skew tolerated on exp/iat, in seconds. Default 60. */
105
+ clockToleranceSec?: number;
106
+ /** How long fetched provider keys are kept. Default 10 minutes; an unknown key id refetches once regardless. */
107
+ jwksTtlMs?: number;
108
+ onEvent?(event: OidcEvent): void;
109
+ }
110
+ export interface OidcLogin {
111
+ /** GET — begins the flow: sets the state cookie, redirects to the provider. */
112
+ start(request: Request): Promise<Response>;
113
+ /** GET — the provider's return: verifies everything, signs the user in, redirects. */
114
+ callback(request: Request): Promise<Response>;
115
+ /** Verify an identity token on its own. Throws with a reason when it does not verify. */
116
+ verifyIdToken(idToken: string, expectedNonce?: string): Promise<OidcClaims>;
117
+ }
118
+ /** Google, for the common case: `createOidcLogin({ issuer: GOOGLE_ISSUER, ... })`. */
119
+ export declare const GOOGLE_ISSUER = "https://accounts.google.com";
120
+ export declare function createOidcLogin(opts: OidcLoginOptions): OidcLogin;
121
+ //# sourceMappingURL=oidc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc.d.ts","sourceRoot":"","sources":["../src/oidc.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAInD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACvB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,IAAI,CAAC,EAAE,MAAM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O,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC9C,yFAAyF;IACzF,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC7E;AAED,sFAAsF;AACtF,eAAO,MAAM,aAAa,gCAAgC,CAAC;AAoB3D,wBAAgB,eAAe,CAAC,IAAI,EAAE,gBAAgB,GAAG,SAAS,CAwMjE"}
package/dist/oidc.js ADDED
@@ -0,0 +1,228 @@
1
+ import { createPublicKey, randomBytes, verify as verifySignature } from 'node:crypto';
2
+ import { makeStateToken, readStateToken } from './signedTokens.js';
3
+ import { headerCookieSetter, readCookie } from './routes.js';
4
+ import { clientIp, redirectResponse } from './http.js';
5
+ /** Google, for the common case: `createOidcLogin({ issuer: GOOGLE_ISSUER, ... })`. */
6
+ export const GOOGLE_ISSUER = 'https://accounts.google.com';
7
+ const b64url = (s) => Buffer.from(s, 'base64url');
8
+ const decodeJson = (s) => {
9
+ try {
10
+ const v = JSON.parse(b64url(s).toString('utf8'));
11
+ return v && typeof v === 'object' ? v : null;
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ };
17
+ export function createOidcLogin(opts) {
18
+ const fetchFn = opts.fetch ?? globalThis.fetch;
19
+ const scope = opts.scope ?? 'openid email profile';
20
+ const stateTtlMs = opts.stateTtlMs ?? 10 * 60_000;
21
+ const stateCookie = opts.stateCookie ?? 'oidc_state';
22
+ const tolerance = opts.clockToleranceSec ?? 60;
23
+ const jwksTtlMs = opts.jwksTtlMs ?? 10 * 60_000;
24
+ const activeStatuses = opts.activeStatuses ?? ['active'];
25
+ const requireVerifiedEmail = opts.requireVerifiedEmail ?? true;
26
+ const secret = () => (typeof opts.stateSecret === 'function' ? opts.stateSecret() : opts.stateSecret);
27
+ const clientSecret = () => (typeof opts.clientSecret === 'function' ? opts.clientSecret() : opts.clientSecret);
28
+ const cookieSecure = () => typeof opts.cookieSecure === 'function' ? opts.cookieSecure() : (opts.cookieSecure ?? !opts.redirectUri.startsWith('http://'));
29
+ const emit = (e) => {
30
+ try {
31
+ opts.onEvent?.(e);
32
+ }
33
+ catch {
34
+ /* an observer must never break the flow it observes */
35
+ }
36
+ };
37
+ /* ------------------------------ discovery ------------------------------ */
38
+ let endpoints = opts.endpoints ? Promise.resolve(opts.endpoints) : null;
39
+ const discover = () => {
40
+ if (!endpoints) {
41
+ endpoints = (async () => {
42
+ const url = opts.issuer.replace(/\/$/, '') + '/.well-known/openid-configuration';
43
+ const res = await fetchFn(url);
44
+ if (!res.ok)
45
+ throw new Error(`discovery failed: ${res.status}`);
46
+ const doc = (await res.json());
47
+ const pick = (k) => {
48
+ const v = doc[k];
49
+ if (typeof v !== 'string')
50
+ throw new Error(`discovery document has no ${k}`);
51
+ return v;
52
+ };
53
+ return { authorization: pick('authorization_endpoint'), token: pick('token_endpoint'), jwks: pick('jwks_uri') };
54
+ })().catch((e) => {
55
+ endpoints = null; // try again next time rather than caching a failure
56
+ throw e;
57
+ });
58
+ }
59
+ return endpoints;
60
+ };
61
+ /* -------------------------------- keys --------------------------------- */
62
+ let keys = null;
63
+ async function loadKeys(force = false) {
64
+ if (!force && keys && Date.now() - keys.at < jwksTtlMs)
65
+ return keys;
66
+ const { jwks } = await discover();
67
+ const res = await fetchFn(jwks);
68
+ if (!res.ok)
69
+ throw new Error(`jwks fetch failed: ${res.status}`);
70
+ const doc = (await res.json());
71
+ const byKid = new Map();
72
+ const all = [];
73
+ for (const jwk of doc.keys ?? []) {
74
+ if (jwk.use && jwk.use !== 'sig')
75
+ continue;
76
+ try {
77
+ const key = createPublicKey({ key: jwk, format: 'jwk' });
78
+ all.push(key);
79
+ if (jwk.kid)
80
+ byKid.set(jwk.kid, key);
81
+ }
82
+ catch {
83
+ /* a key we cannot import is a key we cannot verify with */
84
+ }
85
+ }
86
+ keys = { at: Date.now(), byKid, all };
87
+ return keys;
88
+ }
89
+ async function verifyIdToken(idToken, expectedNonce) {
90
+ const parts = idToken.split('.');
91
+ if (parts.length !== 3)
92
+ throw new Error('not a JWT');
93
+ const header = decodeJson(parts[0]);
94
+ const payload = decodeJson(parts[1]);
95
+ if (!header || !payload)
96
+ throw new Error('malformed JWT');
97
+ const alg = header.alg;
98
+ if (alg !== 'RS256' && alg !== 'ES256')
99
+ throw new Error(`unsupported alg ${String(alg)}`);
100
+ const kid = typeof header.kid === 'string' ? header.kid : undefined;
101
+ // The key by id, refetching once if the provider has rotated since we last looked.
102
+ let loaded = await loadKeys();
103
+ let candidates = kid ? (loaded.byKid.has(kid) ? [loaded.byKid.get(kid)] : []) : loaded.all;
104
+ if (!candidates.length && kid) {
105
+ loaded = await loadKeys(true);
106
+ candidates = loaded.byKid.has(kid) ? [loaded.byKid.get(kid)] : [];
107
+ }
108
+ if (!candidates.length)
109
+ throw new Error('no key to verify with');
110
+ const data = Buffer.from(`${parts[0]}.${parts[1]}`);
111
+ const sig = b64url(parts[2]);
112
+ const good = candidates.some((key) => alg === 'RS256' ? verifySignature('sha256', data, key, sig) : verifySignature('sha256', data, { key, dsaEncoding: 'ieee-p1363' }, sig));
113
+ if (!good)
114
+ throw new Error('bad signature');
115
+ const claims = payload;
116
+ const issuer = opts.issuer.replace(/\/$/, '');
117
+ const iss = typeof claims.iss === 'string' ? claims.iss.replace(/\/$/, '') : '';
118
+ // Google issues both forms; both mean Google.
119
+ if (iss !== issuer && iss !== issuer.replace(/^https:\/\//, '') && `https://${iss}` !== issuer)
120
+ throw new Error('wrong issuer');
121
+ const auds = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
122
+ if (!auds.includes(opts.clientId))
123
+ throw new Error('wrong audience');
124
+ if (typeof claims.azp === 'string' && claims.azp !== opts.clientId)
125
+ throw new Error('wrong authorized party');
126
+ const now = Date.now() / 1000;
127
+ if (typeof claims.exp !== 'number' || claims.exp + tolerance < now)
128
+ throw new Error('expired');
129
+ if (typeof claims.iat === 'number' && claims.iat - tolerance > now)
130
+ throw new Error('issued in the future');
131
+ if (typeof claims.sub !== 'string' || !claims.sub)
132
+ throw new Error('no subject');
133
+ if (expectedNonce !== undefined && claims.nonce !== expectedNonce)
134
+ throw new Error('nonce mismatch');
135
+ return claims;
136
+ }
137
+ /* ------------------------------- cookies ------------------------------- */
138
+ const setState = (jar, value) => jar.setter.set(stateCookie, value, { httpOnly: true, sameSite: 'lax', path: '/', maxAge: Math.ceil(stateTtlMs / 1000), secure: cookieSecure() });
139
+ const clearState = (jar) => jar.setter.set(stateCookie, '', { httpOnly: true, sameSite: 'lax', path: '/', maxAge: 0, secure: cookieSecure() });
140
+ const failTo = (reason) => {
141
+ if (typeof opts.failureRedirect === 'function')
142
+ return opts.failureRedirect(reason);
143
+ const u = new URL(opts.failureRedirect, opts.redirectUri);
144
+ u.searchParams.set('error', reason);
145
+ return u.toString();
146
+ };
147
+ return {
148
+ verifyIdToken,
149
+ async start() {
150
+ const { authorization } = await discover();
151
+ const state = randomBytes(16).toString('base64url');
152
+ const nonce = randomBytes(16).toString('base64url');
153
+ const jar = headerCookieSetter();
154
+ setState(jar, makeStateToken(secret(), `${state}.${nonce}`, stateTtlMs));
155
+ const u = new URL(authorization);
156
+ u.searchParams.set('response_type', 'code');
157
+ u.searchParams.set('client_id', opts.clientId);
158
+ u.searchParams.set('redirect_uri', opts.redirectUri);
159
+ u.searchParams.set('scope', scope);
160
+ u.searchParams.set('state', state);
161
+ u.searchParams.set('nonce', nonce);
162
+ for (const [k, v] of Object.entries(opts.authParams ?? {}))
163
+ u.searchParams.set(k, v);
164
+ emit({ type: 'started' });
165
+ return redirectResponse(u.toString(), jar);
166
+ },
167
+ async callback(request) {
168
+ const jar = headerCookieSetter();
169
+ clearState(jar); // one flow per cookie, whatever happens next
170
+ const fail = (reason, detail, sub) => {
171
+ emit({ type: 'refused', reason, detail, sub });
172
+ return redirectResponse(failTo(reason), jar);
173
+ };
174
+ const q = new URL(request.url).searchParams;
175
+ if (q.get('error'))
176
+ return fail('provider', q.get('error') ?? undefined);
177
+ const code = q.get('code');
178
+ const state = q.get('state');
179
+ if (!code || !state)
180
+ return fail('provider', 'no code');
181
+ // The state must match the one THIS browser was handed, signed and
182
+ // unexpired. It binds the callback to the start, which is what stops a
183
+ // login being forced onto a browser that never asked for one.
184
+ const cookie = readCookie(request, stateCookie);
185
+ const stored = cookie ? readStateToken(secret(), cookie) : null;
186
+ const [expectedState, nonce] = stored ? stored.split('.') : [null, null];
187
+ if (!expectedState || expectedState !== state || !nonce)
188
+ return fail('state');
189
+ const { token: tokenEndpoint } = await discover();
190
+ let idToken;
191
+ try {
192
+ const res = await fetchFn(tokenEndpoint, {
193
+ method: 'POST',
194
+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
195
+ body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: opts.redirectUri, client_id: opts.clientId, client_secret: clientSecret() }),
196
+ });
197
+ if (!res.ok)
198
+ return fail('exchange', String(res.status));
199
+ const tokens = (await res.json());
200
+ if (typeof tokens.id_token !== 'string')
201
+ return fail('exchange', 'no id_token');
202
+ idToken = tokens.id_token;
203
+ }
204
+ catch (e) {
205
+ return fail('exchange', e instanceof Error ? e.message : String(e));
206
+ }
207
+ let claims;
208
+ try {
209
+ claims = await verifyIdToken(idToken, nonce);
210
+ }
211
+ catch (e) {
212
+ return fail('token', e instanceof Error ? e.message : String(e));
213
+ }
214
+ if (requireVerifiedEmail && claims.email_verified !== true)
215
+ return fail('unverified-email', undefined, claims.sub);
216
+ const user = await opts.onIdentity(claims, { request });
217
+ if (!user)
218
+ return fail('not-registered', undefined, claims.sub);
219
+ if (user.status != null && !activeStatuses.includes(user.status))
220
+ return fail('inactive', user.status, claims.sub);
221
+ const minted = await opts.sessions.mint({ userId: user.id, origin: opts.origin, ip: clientIp(request), userAgent: request.headers.get('user-agent') });
222
+ opts.cookies.set(jar.setter, { accessToken: minted.accessToken, refreshToken: minted.refreshToken, expiresAtMs: Date.now() + minted.expires });
223
+ emit({ type: 'signed-in', userId: user.id, sub: claims.sub });
224
+ return redirectResponse(typeof opts.successRedirect === 'function' ? opts.successRedirect(user) : opts.successRedirect, jar);
225
+ },
226
+ };
227
+ }
228
+ //# sourceMappingURL=oidc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc.js","sourceRoot":"","sources":["../src/oidc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,IAAI,eAAe,EAAkB,MAAM,aAAa,CAAC;AACtG,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGnE,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AA+GvD,sFAAsF;AACtF,MAAM,CAAC,MAAM,aAAa,GAAG,6BAA6B,CAAC;AAU3D,MAAM,MAAM,GAAG,CAAC,CAAS,EAAU,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC;AAClE,MAAM,UAAU,GAAG,CAAC,CAAS,EAAkC,EAAE;IAC/D,IAAI,CAAC;QACH,MAAM,CAAC,GAAY,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1D,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAE,CAA6B,CAAC,CAAC,CAAC,IAAI,CAAC;IAC5E,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,UAAU,eAAe,CAAC,IAAsB;IACpD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC;IAC/C,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,sBAAsB,CAAC;IACnD,MAAM,UAAU,GAAG,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IAAI,CAAC,eAAe,EAAE,GAAG,CAAC,CAAC;QAC/H,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,91 @@
1
+ import type { ResetTokens } from './signedTokens.js';
2
+ import type { SessionStore } from './sessions.js';
3
+ import type { RateLimiter } from './rateLimit.js';
4
+ import { type AllowOrigins } from './http.js';
5
+ /**
6
+ * @allodium/auth/reset — the two password-reset routes, written once.
7
+ *
8
+ * Every application rewrites these, and the rewrite is where the mistakes
9
+ * come back: a request endpoint that answers differently for an unknown
10
+ * email and so lists your users; a token that outlives the password it was
11
+ * issued against; sessions that survive the reset that was meant to lock an
12
+ * intruder out. The ceremony here gets those right. What stays yours is every
13
+ * decision: how a user is found, where the hash is stored, what the email
14
+ * says and how it is sent, and where the link points.
15
+ *
16
+ * Optional entry point: import from '@allodium/auth/reset'. A project that
17
+ * does not want it does not load it.
18
+ */
19
+ /** The row your lookups return. Nothing else about your schema is assumed. */
20
+ export interface ResetUserRow {
21
+ id: string;
22
+ email: string;
23
+ /** argon2id digest. Null for an account with no password (SSO-only): such an account cannot reset one. */
24
+ passwordHash: string | null;
25
+ status?: string | null;
26
+ }
27
+ export type ResetEvent = {
28
+ type: 'requested';
29
+ email: string;
30
+ eligible: boolean;
31
+ } | {
32
+ type: 'sent';
33
+ userId: string;
34
+ } | {
35
+ type: 'send-failed';
36
+ userId: string;
37
+ error: unknown;
38
+ } | {
39
+ type: 'reset';
40
+ userId: string;
41
+ } | {
42
+ type: 'refused';
43
+ reason: 'invalid-token' | 'inactive' | 'weak-password';
44
+ userId?: string;
45
+ };
46
+ export interface ResetRoutesOptions {
47
+ /** `createResetTokens(...)` — keyed on the user's current hash, so a reset kills every outstanding token. */
48
+ tokens: ResetTokens;
49
+ /** For revoking every session once the password changes. */
50
+ sessions: Pick<SessionStore, 'revokeAllForUser'>;
51
+ findUserByEmail(email: string): Promise<ResetUserRow | null>;
52
+ findUserById(id: string): Promise<ResetUserRow | null>;
53
+ /** Store the new argon2id digest — the one write this flow makes to your users table. */
54
+ setPasswordHash(userId: string, passwordHash: string): Promise<void>;
55
+ /** Where the link in the email points, given the token. */
56
+ resetUrl(token: string): string;
57
+ /**
58
+ * Deliver the link. Called only for an active account that has a password,
59
+ * and NOT awaited before the response: a slow mail server must not make a
60
+ * known email answer slower than an unknown one. Failures reach `onEvent`.
61
+ */
62
+ sendMail(args: {
63
+ to: string;
64
+ user: ResetUserRow;
65
+ resetUrl: string;
66
+ token: string;
67
+ }): Promise<void>;
68
+ /** Statuses that may reset. Defaults to ['active']. */
69
+ activeStatuses?: string[];
70
+ /** Default 10. Length is the only rule enforced here; composition rules are yours. */
71
+ minPasswordLength?: number;
72
+ /** Throttle for the request endpoint, keyed per email AND per IP. */
73
+ rateLimit?: RateLimiter;
74
+ limits?: {
75
+ perEmail?: number;
76
+ perIp?: number;
77
+ windowMs?: number;
78
+ };
79
+ allowOrigins?: AllowOrigins;
80
+ onEvent?(event: ResetEvent): void;
81
+ }
82
+ export interface ResetRoutes {
83
+ /** POST { email } — always 200, so the endpoint cannot say which emails exist. */
84
+ request(request: Request): Promise<Response>;
85
+ /** POST { token, password } — 200 on success; 400 for a weak password; 401 for a token that is not valid; 403 for an account that may not sign in. */
86
+ reset(request: Request): Promise<Response>;
87
+ /** OPTIONS — CORS preflight. */
88
+ preflight(request: Request): Response;
89
+ }
90
+ export declare function createResetRoutes(opts: ResetRoutesOptions): ResetRoutes;
91
+ //# sourceMappingURL=reset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reset.d.ts","sourceRoot":"","sources":["../src/reset.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD,OAAO,EAA8D,KAAK,YAAY,EAAE,MAAM,WAAW,CAAC;AAE1G;;;;;;;;;;;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AC;IAChC;;;;OAIG;IACH,QAAQ,CAAC,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,YAAY,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnG,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,sFAAsF;IACtF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qEAAqE;IACrE,SAAS,CAAC,EAAE,WAAW,CAAC;IACxB,MAAM,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAClE,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,OAAO,CAAC,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAAC;CACnC;AAED,MAAM,WAAW,WAAW;IAC1B,kFAAkF;IAClF,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC7C,sJAAsJ;IACtJ,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC3C,gCAAgC;IAChC,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,QAAQ,CAAC;CACvC;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,GAAG,WAAW,CAiGvE"}
package/dist/reset.js ADDED
@@ -0,0 +1,100 @@
1
+ import { hashPassword } from './passwords.js';
2
+ import { crossSiteWrite } from './routes.js';
3
+ import { clientIp, jsonResponse, originAllowedBy, preflightResponse } from './http.js';
4
+ export function createResetRoutes(opts) {
5
+ const activeStatuses = opts.activeStatuses ?? ['active'];
6
+ const minLength = opts.minPasswordLength ?? 10;
7
+ const perEmail = opts.limits?.perEmail ?? 3;
8
+ const perIp = opts.limits?.perIp ?? 10;
9
+ const windowMs = opts.limits?.windowMs ?? 60 * 60_000;
10
+ const originAllowed = originAllowedBy(opts.allowOrigins);
11
+ const json = (request, body, status = 200) => jsonResponse(request, opts.allowOrigins, body, status);
12
+ const emit = (e) => {
13
+ try {
14
+ opts.onEvent?.(e);
15
+ }
16
+ catch {
17
+ /* an observer must never break the flow it observes */
18
+ }
19
+ };
20
+ async function body(request) {
21
+ try {
22
+ const parsed = await request.json();
23
+ return parsed && typeof parsed === 'object' ? parsed : {};
24
+ }
25
+ catch {
26
+ return {};
27
+ }
28
+ }
29
+ const isActive = (user) => user.status == null || activeStatuses.includes(user.status);
30
+ return {
31
+ preflight: (request) => preflightResponse(request, opts.allowOrigins, 'POST, OPTIONS'),
32
+ async request(request) {
33
+ const refused = crossSiteWrite(request, originAllowed);
34
+ if (refused)
35
+ return json(request, { error: refused.message }, refused.status);
36
+ const { email } = (await body(request));
37
+ if (typeof email !== 'string' || !email.trim())
38
+ return json(request, { error: 'Email is required' }, 400);
39
+ const normalized = email.trim().toLowerCase();
40
+ if (opts.rateLimit) {
41
+ const ip = clientIp(request);
42
+ const emailOk = opts.rateLimit(`reset:email:${normalized}`, perEmail, windowMs);
43
+ const ipOk = ip ? opts.rateLimit(`reset:ip:${ip}`, perIp, windowMs) : true;
44
+ if (!emailOk || !ipOk)
45
+ return json(request, { error: 'Too many attempts. Try again later.' }, 429);
46
+ }
47
+ // The answer is the same whether or not the account exists. Only the
48
+ // email differs, and it goes to the address that was typed, which
49
+ // reveals nothing to the person typing.
50
+ const user = await opts.findUserByEmail(normalized);
51
+ const eligible = !!user && !!user.passwordHash && isActive(user);
52
+ emit({ type: 'requested', email: normalized, eligible });
53
+ if (user && eligible) {
54
+ const token = opts.tokens.make({ id: user.id, password: user.passwordHash });
55
+ void opts
56
+ .sendMail({ to: user.email, user, resetUrl: opts.resetUrl(token), token })
57
+ .then(() => emit({ type: 'sent', userId: user.id }))
58
+ .catch((error) => emit({ type: 'send-failed', userId: user.id, error }));
59
+ }
60
+ return json(request, { ok: true });
61
+ },
62
+ async reset(request) {
63
+ const refused = crossSiteWrite(request, originAllowed);
64
+ if (refused)
65
+ return json(request, { error: refused.message }, refused.status);
66
+ const { token, password } = (await body(request));
67
+ if (typeof token !== 'string' || !token || typeof password !== 'string')
68
+ return json(request, { error: 'Token and password are required' }, 400);
69
+ if (password.length < minLength) {
70
+ emit({ type: 'refused', reason: 'weak-password' });
71
+ return json(request, { error: `Password must be at least ${minLength} characters` }, 400);
72
+ }
73
+ // One answer for every way a token can be wrong — malformed, unknown user,
74
+ // bad signature, expired, already used — so the response does not say which.
75
+ const invalid = () => {
76
+ emit({ type: 'refused', reason: 'invalid-token' });
77
+ return json(request, { error: 'This reset link is not valid. Request a new one.' }, 401);
78
+ };
79
+ const payload = opts.tokens.decode(token);
80
+ if (!payload)
81
+ return invalid();
82
+ const user = await opts.findUserById(payload.u);
83
+ if (!user || !opts.tokens.verify(token, { password: user.passwordHash }))
84
+ return invalid();
85
+ if (!isActive(user)) {
86
+ // They proved they hold the link; "suspended" is the only answer that
87
+ // lets them do anything about it, and reveals nothing they did not prove.
88
+ emit({ type: 'refused', reason: 'inactive', userId: user.id });
89
+ return json(request, { error: `This account is ${user.status}`, status: user.status }, 403);
90
+ }
91
+ await opts.setPasswordHash(user.id, await hashPassword(password));
92
+ // The token died with the old hash. The sessions die here: a reset that
93
+ // leaves an intruder's session alive has not reset anything.
94
+ await opts.sessions.revokeAllForUser(user.id);
95
+ emit({ type: 'reset', userId: user.id });
96
+ return json(request, { ok: true });
97
+ },
98
+ };
99
+ }
100
+ //# sourceMappingURL=reset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reset.js","sourceRoot":"","sources":["../src/reset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAI9C,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,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C,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC;gBAAE,OAAO,OAAO,EAAE,CAAC;YAC3F,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;gBACpB,sEAAsE;gBACtE,0EAA0E;gBAC1E,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC;gBAC/D,OAAO,IAAI,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,mBAAmB,IAAI,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,EAAE,GAAG,CAAC,CAAC;YAC9F,CAAC;YAED,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE,EAAE,MAAM,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;YAClE,wEAAwE;YACxE,6DAA6D;YAC7D,MAAM,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YAC9C,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC;YACzC,OAAO,IAAI,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;QACrC,CAAC;KACF,CAAC;AACJ,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.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokens.d.ts","sourceRoot":"","sources":["../src/tokens.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,6FAA6F;IAC7F,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,gHAAgH;IAChH,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,MAAM,WAAW,WAAY,SAAQ,gBAAgB;IACnD,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAA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F;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,KAAK,IAAI,YAAY,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,CAAC;IACpC,MAAM,YAAY,GAAG,IAAI,CAAC,YAAY,IAAI,MAAM,CAAC;IACjD,MAAM,CAAC,GAAG;QACR,EAAE,EAAE,IAAI;QACR,KAAK,EAAE,OAAO;QACd,SAAS,EAAE,YAAY;QACvB,MAAM,EAAE,SAAS;QACjB,KAAK,EAAE,OAAO;QACd,SAAS,EAAE,YAAY;QACvB,SAAS,EAAE,YAAY;QACvB,UAAU,EAAE,cAAc;QAC1B,SAAS,EAAE,YAAY;QACvB,GAAG,CAAC,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;KACxB,CAAC;IACF,MAAM,GAAG,GAAG,CAAC,CAAiB,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;I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,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;;oBACzD,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YAClE,CAAC;YACD,IAAI,CAAC,CAAC,CAAC,cAAc;gBAAE,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;YACjE,MAAM,GAAG,GAAG,MAAM,EAAE,CAAC,KAAK,CACxB,UAAU,iBAAiB,SAAS,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,aAAa,GAAG,CAAC,WAAW,CAAC,OAAO,EACnI,MAAM,CACP,CAAC;YACF,OAAQ,GAAG,CAAC,IAAkC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC5D,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allodium/auth",
3
- "version": "0.3.1",
3
+ "version": "0.5.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": {
@@ -16,6 +16,14 @@
16
16
  "types": "./dist/index.d.ts",
17
17
  "import": "./dist/index.js"
18
18
  },
19
+ "./reset": {
20
+ "types": "./dist/reset.d.ts",
21
+ "import": "./dist/reset.js"
22
+ },
23
+ "./oidc": {
24
+ "types": "./dist/oidc.d.ts",
25
+ "import": "./dist/oidc.js"
26
+ },
19
27
  "./package.json": "./package.json"
20
28
  },
21
29
  "files": [
@@ -24,7 +32,7 @@
24
32
  "scripts": {
25
33
  "build": "tsc -p tsconfig.json",
26
34
  "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"
35
+ "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 && node test/reset.mjs && node test/oidc.mjs"
28
36
  },
29
37
  "engines": {
30
38
  "node": ">=20"