@smplcty/auth 0.6.4 → 2.0.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.
Files changed (90) hide show
  1. package/README.md +187 -201
  2. package/dist/create-session.d.ts +10 -9
  3. package/dist/create-session.d.ts.map +1 -1
  4. package/dist/create-session.js +16 -18
  5. package/dist/create-session.js.map +1 -1
  6. package/dist/errors.d.ts +19 -4
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +23 -5
  9. package/dist/errors.js.map +1 -1
  10. package/dist/find-user-by-communication-method.d.ts.map +1 -1
  11. package/dist/find-user-by-communication-method.js +4 -0
  12. package/dist/find-user-by-communication-method.js.map +1 -1
  13. package/dist/get-user-role-names.d.ts.map +1 -1
  14. package/dist/get-user-role-names.js +2 -0
  15. package/dist/get-user-role-names.js.map +1 -1
  16. package/dist/index.d.ts +9 -5
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +12 -6
  19. package/dist/index.js.map +1 -1
  20. package/dist/internal/hash-token.d.ts +16 -0
  21. package/dist/internal/hash-token.d.ts.map +1 -0
  22. package/dist/internal/hash-token.js +21 -0
  23. package/dist/internal/hash-token.js.map +1 -0
  24. package/dist/methods/errors.d.ts +23 -0
  25. package/dist/methods/errors.d.ts.map +1 -0
  26. package/dist/methods/errors.js +28 -0
  27. package/dist/methods/errors.js.map +1 -0
  28. package/dist/methods/oidc/index.d.ts +92 -0
  29. package/dist/methods/oidc/index.d.ts.map +1 -0
  30. package/dist/methods/oidc/index.js +104 -0
  31. package/dist/methods/oidc/index.js.map +1 -0
  32. package/dist/methods/router.d.ts +19 -0
  33. package/dist/methods/router.d.ts.map +1 -0
  34. package/dist/methods/router.js +95 -0
  35. package/dist/methods/router.js.map +1 -0
  36. package/dist/methods/twilio/index.d.ts +44 -0
  37. package/dist/methods/twilio/index.d.ts.map +1 -0
  38. package/dist/methods/twilio/index.js +77 -0
  39. package/dist/methods/twilio/index.js.map +1 -0
  40. package/dist/methods/types.d.ts +106 -0
  41. package/dist/methods/types.d.ts.map +1 -0
  42. package/dist/methods/types.js +2 -0
  43. package/dist/methods/types.js.map +1 -0
  44. package/dist/revoke-session.d.ts +20 -15
  45. package/dist/revoke-session.d.ts.map +1 -1
  46. package/dist/revoke-session.js +66 -20
  47. package/dist/revoke-session.js.map +1 -1
  48. package/dist/scope/flat-tenant.d.ts +36 -0
  49. package/dist/scope/flat-tenant.d.ts.map +1 -0
  50. package/dist/scope/flat-tenant.js +60 -0
  51. package/dist/scope/flat-tenant.js.map +1 -0
  52. package/dist/set-helpers.d.ts +44 -53
  53. package/dist/set-helpers.d.ts.map +1 -1
  54. package/dist/set-helpers.js +67 -68
  55. package/dist/set-helpers.js.map +1 -1
  56. package/dist/touch-session.d.ts +13 -0
  57. package/dist/touch-session.d.ts.map +1 -0
  58. package/dist/touch-session.js +28 -0
  59. package/dist/touch-session.js.map +1 -0
  60. package/dist/types.d.ts +59 -18
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/validate-session.d.ts +15 -14
  63. package/dist/validate-session.d.ts.map +1 -1
  64. package/dist/validate-session.js +28 -27
  65. package/dist/validate-session.js.map +1 -1
  66. package/dist/with-service-context.d.ts +15 -12
  67. package/dist/with-service-context.d.ts.map +1 -1
  68. package/dist/with-service-context.js +34 -30
  69. package/dist/with-service-context.js.map +1 -1
  70. package/dist/with-session.d.ts +22 -16
  71. package/dist/with-session.d.ts.map +1 -1
  72. package/dist/with-session.js +67 -63
  73. package/dist/with-session.js.map +1 -1
  74. package/package.json +33 -2
  75. package/schema/functions/current_user_id.yaml +18 -0
  76. package/schema/functions/resolve_session.yaml +42 -23
  77. package/schema/post/0001-backfill-audit-by.sql +15 -0
  78. package/schema/tables/auth_domains.yaml +43 -0
  79. package/schema/tables/communication_channels.yaml +5 -1
  80. package/schema/tables/dev_otp_enrollments.yaml +1 -0
  81. package/schema/tables/roles.yaml +43 -7
  82. package/schema/tables/sessions.yaml +10 -0
  83. package/schema/tables/tenants.yaml +24 -1
  84. package/schema/tables/user_communication_methods.yaml +5 -1
  85. package/schema/tables/user_roles.yaml +1 -0
  86. package/schema/tables/users.yaml +27 -0
  87. package/dist/with-transaction.d.ts +0 -31
  88. package/dist/with-transaction.d.ts.map +0 -1
  89. package/dist/with-transaction.js +0 -49
  90. package/dist/with-transaction.js.map +0 -1
package/README.md CHANGED
@@ -1,60 +1,65 @@
1
1
  # @smplcty/auth
2
2
 
3
- Robust, type-safe session and role-based authentication primitives for PostgreSQL apps using Row-Level Security.
3
+ Robust, type-safe **stateful-session** authentication primitives for PostgreSQL apps using Row-Level Security.
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/@smplcty/auth.svg)](https://www.npmjs.com/package/@smplcty/auth)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
7
7
 
8
8
  ## Why
9
9
 
10
- Multi-tenant Postgres apps that use Row-Level Security need three things in every request:
10
+ The library owns **identity, sessions, roles/privileges, tenants, sign-in federation, and per-request context**. Each app owns only its **intra-tenant authorization scope** (its RLS model). See [`docs/v1-design.md`](docs/v1-design.md) for the full design.
11
11
 
12
- 1. A validated session attached to a real user.
13
- 2. A role for that session that gates which RLS policies apply.
14
- 3. A list of tenant IDs the session is allowed to see.
12
+ Stateful sessions (not JWT) because the requirements decide it: track sign-ins/activity, force immediate sign-off for a whole tenant, and make role/privilege changes take effect immediately. All three need per-request server authority — resolved in one indexed query folded into the RLS transaction every request already opens.
15
13
 
16
- These need to be set as session variables (`app.session_id`, `app.role_name`, `app.tenant_ids`, `app.all_tenants`) on a dedicated database connection, inside a transaction so they don't leak across requests.
14
+ Every request sets four **identity GUCs** on its transaction-bound connection, transaction-scoped so they can't leak across requests:
17
15
 
18
- `@smplcty/auth` makes that boring and safe. The high-level `withSession` does the whole dance in one call. The low-level `set*` helpers and `withTransaction` are there for migration and unusual cases.
16
+ | GUC | Meaning |
17
+ | ----------------- | -------------------------------------------------------------------- |
18
+ | `app.actor_id` | the acting user (human **or** service); `current_user_id()` reads it |
19
+ | `app.session_id` | the session hash, for correlation/audit |
20
+ | `app.active_role` | the chosen mode/persona role for the request |
21
+ | `app.privileges` | comma-separated capability flags the user holds |
22
+
23
+ Intra-tenant **scope** GUCs (tenant ids, region/plant, visible reps, …) are **not** in this contract — they're app-owned, set by a scope hook you supply (or a provided preset).
19
24
 
20
25
  ## Install
21
26
 
22
27
  ```sh
23
- pnpm add @smplcty/auth pg
28
+ pnpm add @smplcty/auth @smplcty/db pg
24
29
  ```
25
30
 
26
- `pg` is a peer dependency.
31
+ `pg` is a peer dependency; `@smplcty/db` provides the transaction primitive. Sign-in method handlers are opt-in subpaths with their own optional peers (see [Sign-in methods](#sign-in-methods-pluggable)).
27
32
 
28
33
  ## High-level usage — `withSession`
29
34
 
30
- The default API. Hand it a pool, an authenticated session, and a callback. It checks out a connection, opens a transaction, validates the session, sets all four session variables via parameterized `set_config`, runs your code, and commits (or rolls back on throw).
35
+ The default API. Hand it a pool, the raw session token, and a callback. It opens a `@smplcty/db` transaction, resolves and validates the session, picks the active role, sets the identity GUCs, runs your (optional) scope hook, runs your code, and commits — or rolls back on throw.
31
36
 
32
37
  ```ts
33
38
  import { withSession } from '@smplcty/auth';
34
39
 
35
- const widgets = await withSession(pool, { sessionId, roleName: 'user' }, async (client, ctx) => {
36
- // ctx = { userId, tenantIds, allTenants, roles }
40
+ const widgets = await withSession(pool, { token, roleName: 'user' }, async (client, ctx) => {
41
+ // ctx = { userId, activeRole, roles, privileges }
37
42
  const { rows } = await client.query('SELECT * FROM widgets');
38
43
  return rows;
39
44
  });
40
45
  ```
41
46
 
42
- If the session doesn't exist, is expired, or the user doesn't have the requested role, `withSession` throws **before** your callback runs. Your code never sees an invalid context.
47
+ Active-role selection happens in TypeScript: the requested `roleName` if given (must be one the user holds), else the user's **default** role, else none — a privilege-only request is not an error. If the session doesn't exist, is expired/revoked, or the requested role isn't held, `withSession` throws **before** your callback runs.
43
48
 
44
49
  ### Errors thrown by `withSession`
45
50
 
46
- | Error | When |
47
- | ---------------------- | ---------------------------------------------- |
48
- | `SessionNotFoundError` | sessionId doesn't match any row |
49
- | `SessionExpiredError` | session row exists but `expires_at` has passed |
50
- | `RoleNotAssignedError` | user does not have the requested role |
51
- | `InvalidInputError` | sessionId or roleName is empty / wrong type |
51
+ | Error | When |
52
+ | ---------------------- | --------------------------------------------- |
53
+ | `SessionNotFoundError` | token matches no session |
54
+ | `SessionExpiredError` | session has expired (or was revoked) |
55
+ | `RoleNotHeldError` | a requested `roleName` the user does not hold |
56
+ | `InvalidInputError` | `token` is empty / wrong type |
52
57
 
53
- All errors extend `AuthError` and have a `code` property:
58
+ All errors extend `AuthError` and carry a `code`:
54
59
 
55
60
  ```ts
56
61
  try {
57
- await withSession(pool, { sessionId, roleName: 'user' }, fn);
62
+ await withSession(pool, { token, roleName: 'user' }, fn);
58
63
  } catch (err) {
59
64
  if (err instanceof AuthError && err.code === 'SESSION_EXPIRED') {
60
65
  // redirect to login
@@ -63,109 +68,165 @@ try {
63
68
  }
64
69
  ```
65
70
 
66
- ## Low-level usage — `withTransaction` + `set*` helpers
71
+ ## Authorization scope (app-owned)
67
72
 
68
- For migrating existing code that has its own session-extraction logic, or for tests, or for any case where you need more control than `withSession` gives you.
73
+ `withSession` sets identity GUCs only. To set intra-tenant **scope** GUCs your RLS needs, pass a `scope` hook — it runs inside the request transaction, after the identity GUCs are set:
69
74
 
70
75
  ```ts
71
- import { withTransaction, setSessionId, setRoleName, setTenantIds, setAllTenants } from '@smplcty/auth';
76
+ await withSession(pool, { token, roleName: 'user' }, fn, {
77
+ scope: async (client, identity) => {
78
+ // identity = { userId, activeRole, roles, privileges }
79
+ // set whatever scope GUCs your RLS policies read
80
+ },
81
+ });
82
+ ```
72
83
 
73
- await withTransaction(pool, async (client) => {
74
- await setSessionId(client, sessionId);
75
- await setRoleName(client, 'user');
76
- await setTenantIds(client, [1, 2, 3]);
77
- await setAllTenants(client, false);
84
+ For the common flat multi-tenant case (the 0.6.x behavior), a ready-made preset ships at a subpath:
78
85
 
79
- return client.query('SELECT * FROM widgets');
86
+ ```ts
87
+ import { withSession } from '@smplcty/auth';
88
+ import { flatTenantScope } from '@smplcty/auth/flat-tenant';
89
+
90
+ const scope = flatTenantScope(); // sets app.tenant_ids + app.all_tenants from user_roles
91
+ await withSession(pool, { token, roleName: 'user' }, fn, { scope });
92
+ ```
93
+
94
+ Apps with a richer model (producer/region/plant, rep hierarchy) ship their own hook, or enforce scope "function-carried" (RLS policies call functions that read `current_user_id()`).
95
+
96
+ ## Background work — `withServiceContext`
97
+
98
+ Background writers (ingestion, workers, app-init) have no human session, but audit attribution is NOT NULL. Run them as a named **service principal** (a `users` row of `kind='service'`) so `app.actor_id` is set and writes are attributed:
99
+
100
+ ```ts
101
+ import { withServiceContext } from '@smplcty/auth';
102
+
103
+ await withServiceContext(pool, 'transform-worker', async (client) => {
104
+ await client.query('INSERT INTO metrics (...) VALUES (...)'); // audited to the service
80
105
  });
81
106
  ```
82
107
 
83
- Or all four at once:
108
+ ## Low-level usage — `withTransaction` + identity setters
109
+
110
+ For migrating existing code, tests, or unusual cases. `withTransaction` is re-exported from `@smplcty/db`.
84
111
 
85
112
  ```ts
86
- import { withTransaction, setSessionContext } from '@smplcty/auth';
113
+ import { withTransaction, setIdentityContext } from '@smplcty/auth';
87
114
 
88
115
  await withTransaction(pool, async (client) => {
89
- await setSessionContext(client, {
90
- sessionId,
91
- roleName: 'user',
92
- tenantIds: [1, 2, 3],
93
- allTenants: false,
116
+ await setIdentityContext(client, {
117
+ actorId: 42,
118
+ sessionId: tokenHash,
119
+ activeRole: 'user',
120
+ privileges: ['can_export'],
94
121
  });
95
122
  return client.query('SELECT * FROM widgets');
96
123
  });
97
124
  ```
98
125
 
99
- **Important contract:** every `set*` helper requires a `PoolClient` that is already inside an open transaction. The `withTransaction` wrapper guarantees that. If you try to pass a `Pool`, the type checker rejects it. The variables are set with **transaction scope** (`set_config(name, value, true)`) — they are automatically discarded when the transaction commits or rolls back, so cross-request leakage is impossible.
100
-
101
- The low-level helpers do **not** validate that the session exists or that the user has the role. If you need validation, use `withSession`. If you bypass `withSession`, validate session and role yourself before setting them.
126
+ Individual setters (`setActorId`, `setSessionId`, `setActiveRole`, `setPrivileges`, `setLocal`) and the `IDENTITY_GUC` name map are also exported. Every setter requires a `PoolClient` already inside a transaction; the variables are set transaction-scoped (`set_config(_, _, true)`) and discarded on COMMIT/ROLLBACK. The low-level setters do **not** validate the session — use `withSession` for that.
102
127
 
103
- ## Sign-in flow primitives
128
+ ## Session lifecycle
104
129
 
105
- `createSession`, `validateSession`, `revokeSession`, and `findUserByCommunicationMethod` are the helpers you need to build a sign-in / sign-out / authorizer flow. None of them are coupled to a specific OTP provider, identity model, or transport.
130
+ `createSession`, `validateSession`, `revokeSession`, `revokeUserSessions`, `revokeTenantSessions`, `touchSession`, and `findUserByCommunicationMethod` build sign-in / sign-out / activity / authorizer flows. None are coupled to a specific OTP provider, identity model, or transport.
106
131
 
107
132
  ### `findUserByCommunicationMethod`
108
133
 
109
134
  ```ts
110
- import { findUserByCommunicationMethod } from '@smplcty/auth';
111
-
112
- const lookup = await findUserByCommunicationMethod(db, {
113
- channel: 'email',
114
- code: 'alice@example.com',
115
- });
116
- if (!lookup) {
117
- // user not registered
118
- return;
119
- }
120
- // lookup = { userId, userCommunicationMethodId }
135
+ const lookup = await findUserByCommunicationMethod(db, { channel: 'email', code: 'alice@example.com' });
136
+ // lookup = { userId, userCommunicationMethodId } | null
121
137
  ```
122
138
 
123
139
  ### `createSession`
124
140
 
125
141
  ```ts
126
- import { createSession } from '@smplcty/auth';
127
-
128
142
  const session = await createSession(db, {
129
143
  userCommunicationMethodId: lookup.userCommunicationMethodId,
130
144
  ttl: '30 days',
131
145
  ip: req.ip,
132
146
  geo: { country: 'US', region: 'CA' },
133
147
  });
134
- // session = { sessionId, userId, createdAt, expiresAt }
148
+ // session = { token, userId, createdAt, expiresAt }
149
+ setCookie('session', session.token); // raw token to the client, ONCE
135
150
  ```
136
151
 
137
- `ttl` is a Postgres interval string, evaluated server-side via `now() + interval $ttl`. This means the expiration time has zero clock-skew between your app and the database.
152
+ A fresh opaque token (256 bits) is generated server-side; **only its SHA-256 hash is stored** (as the `sessions` primary key). `session.token` is the raw bearer credential — return it once and don't persist it. `ttl` is a Postgres interval evaluated server-side (`now() + interval $ttl`), so there's no app/DB clock skew.
138
153
 
139
154
  ### `validateSession`
140
155
 
141
- For authorizers and other "is this token alive?" checks. Returns the Session if valid, throws if not. Does not set any database context.
156
+ For authorizers / "is this token alive?" checks. Returns `SessionInfo` (`{ userId, createdAt, expiresAt, lastSeenAt }`) or throws. Sets no GUCs.
142
157
 
143
158
  ```ts
144
- import { validateSession, SessionExpiredError } from '@smplcty/auth';
145
-
146
159
  try {
147
- const session = await validateSession(db, sessionId);
148
- return { allow: true, principalId: String(session.userId) };
149
- } catch (err) {
160
+ const info = await validateSession(db, token);
161
+ return { allow: true, principalId: String(info.userId) };
162
+ } catch {
150
163
  return { allow: false };
151
164
  }
152
165
  ```
153
166
 
154
- ### `revokeSession`
167
+ ### Revocation & activity
155
168
 
156
169
  ```ts
157
- import { revokeSession } from '@smplcty/auth';
170
+ await revokeSession(db, token); // force sign-off of one session (idempotent)
171
+ await revokeUserSessions(db, userId); // sign off every session of a user
172
+ await revokeTenantSessions(db, tenantId); // tenant-wide sign-off
173
+ await touchSession(db, token); // record activity (last_seen_at); returns whether a live session matched
174
+ ```
175
+
176
+ Revoke is a **soft-revoke** — it sets `expires_at = now()`, so the row survives for audit but the session is locked out immediately. Role/privilege changes take effect on the next request automatically (nothing is baked into the token). `revokeTenantSessions` resolves membership from `user_roles.tenant_id` and deliberately spares wildcard (all-tenant) members like global admins.
177
+
178
+ ## Sign-in methods
179
+
180
+ Sign-in is **tenant-centric**: the app resolves the tenant from the request sub-domain (`tenants.slug`), and the router lists that tenant's IdPs. A tenant has **0..N** OIDC IdPs (mergers, mixed workforces, multi-domain orgs):
181
+
182
+ - **0 IdPs** → OTP only.
183
+ - **1 IdP** → straight redirect, no chooser.
184
+ - **N IdPs** → a chooser (one button per IdP, labeled `displayName`, valued by `auth_domain_id`).
185
+
186
+ The user-bound **OTP** path is gated by the tenant's `allow_otp` flag, **enforced in the router** (not just hidden in the UI) so an SSO-only tenant can't be bypassed. **OIDC** is handled by a dedicated `@smplcty/auth/oidc` handler (built on [`oauth4webapi`](https://github.com/panva/oauth4webapi)) — its `authorize`/`callback` shape is richer than the OTP two-phase, so it's driven directly rather than through the router. See [ADR-0001](docs/adr/0001-oidc-via-oauth4webapi.md).
187
+
188
+ ```ts
189
+ import { createMethodRouter } from '@smplcty/auth';
190
+ import { oidcHandler } from '@smplcty/auth/oidc'; // optional peer: oauth4webapi
191
+ import { twilioVerifyHandler } from '@smplcty/auth/twilio'; // optional peer: @smplcty/twilio
192
+ import { createTwilioVerifyClient } from '@smplcty/twilio';
193
+
194
+ const router = createMethodRouter({
195
+ db: pool,
196
+ otpHandler: twilioVerifyHandler({ client: createTwilioVerifyClient(cfg) }), // user-bound, tenant-gated
197
+ });
198
+ const oidc = oidcHandler({ clientSecret: (ad) => secrets.get(ad.tenantId) }); // secret from your store, NOT the DB
199
+
200
+ // Sign-in page — app parsed Host → 'acme':
201
+ const opts = await router.signInOptions({ tenantSlug: 'acme' });
202
+ // opts = { tenantId, authDomains: AuthDomain[], otpAllowed: boolean }
203
+ // render: a button per opts.authDomains + an OTP form iff opts.otpAllowed
204
+
205
+ // OIDC — user picked an IdP (an AuthDomain from opts.authDomains):
206
+ const { redirectUrl, loginState } = await oidc.initiate(authDomain);
207
+ // persist loginState (signed cookie keyed by loginState.state), redirect to redirectUrl...
208
+ // ...on the provider callback, hand back the stored loginState + the callback URL:
209
+ const user = await oidc.complete({ db: pool, authDomain, callbackUrl, loginState });
210
+
211
+ // OTP (only when opts.otpAllowed):
212
+ await router.initiateOtp({ tenantId: opts.tenantId, identifier: phone });
213
+ const user2 = await router.completeOtp({ tenantId: opts.tenantId, identifier: phone, credential: code });
158
214
 
159
- await revokeSession(db, sessionId); // idempotent — no error if already revoked
215
+ const session = await createSession(pool, {
216
+ userCommunicationMethodId: user.userCommunicationMethodId,
217
+ ttl: '30 days',
218
+ });
160
219
  ```
161
220
 
162
- Hard-deletes the session row.
221
+ Auth **core** depends on neither `oauth4webapi` nor Twilio — the handler subpaths do, as **optional peers**. A password-only app installs neither. OIDC is org-bound (`oauth4webapi` does discovery + PKCE + token exchange + `id_token` verification); Twilio Verify is user-bound (phone/email) and integrates the [dev-OTP](#developer-otp--for-devs-whose-phones-cant-receive-sms) fallback automatically.
222
+
223
+ **What stays app-side:** parsing the request `Host` → slug, the chooser/redirect UI, and the OIDC **login-state store** — `oidc.initiate` returns `loginState` (`state`/`nonce`/`codeVerifier`) for you to persist in a short-lived signed cookie keyed by `state`, and hand back to `oidc.complete`. The **`client_secret`** lives in your secret store (passed via the `clientSecret` resolver), **not** in `auth_domains` (which holds only `issuer`/`clientId`).
163
224
 
164
225
  ## Developer OTP — for devs whose phones can't receive SMS
165
226
 
166
227
  Twilio's Verify service doesn't deliver SMS to every carrier reliably (especially overseas, certain pre-paid carriers, and some VoIP numbers). Real-world projects need a way for developers to sign in even when SMS delivery is broken.
167
228
 
168
- `@smplcty/auth` ships per-developer TOTP enrollment for exactly this case. Each enrolled dev has their own time-based one-time password secret stored in `dev_otp_enrollments`, scanned into a standard authenticator app (1Password, Authy, Google Authenticator, etc.). The sign-in-verify handler tries the dev OTP first; if it doesn't match, it falls through to Twilio.
229
+ `@smplcty/auth` ships per-developer TOTP enrollment for exactly this case. Each enrolled dev has their own time-based one-time password secret stored in `dev_otp_enrollments`, scanned into a standard authenticator app (1Password, Authy, Google Authenticator, etc.). The verify side tries the dev OTP first; if it doesn't match, it falls through to Twilio. (The `twilioVerifyHandler` does this for you; the primitives below are for hand-rolled flows.)
169
230
 
170
231
  ### How the codes are distinguished from Twilio codes
171
232
 
@@ -277,7 +338,7 @@ WHERE cc.name = 'phone' AND ucm.code = '${phone}';
277
338
  `);
278
339
  ```
279
340
 
280
- Run it with `pnpm tsx scripts/enroll-dev.mts +15558675309 'Sam (iPhone)'`. The script generates a fresh secret, prints a scannable QR code, and gives you the SQL to run against your database.
341
+ The script generates a fresh secret, prints a scannable QR code, and gives you the SQL to run against your database.
281
342
 
282
343
  ### Revoking a dev's enrollment
283
344
 
@@ -291,24 +352,24 @@ WHERE user_communication_method_id = (
291
352
  );
292
353
  ```
293
354
 
294
- The next sign-in-verify call for that user will fall through to Twilio as if they were never enrolled.
355
+ The next verify call for that user will fall through to Twilio as if they were never enrolled.
295
356
 
296
357
  ### Why per-dev TOTP instead of a shared bypass code?
297
358
 
298
- Earlier versions of this codebase used a `DEV_PHONE_NUMBERS` + `DEV_VERIFICATION_CODE` env var pair where any dev phone, when paired with the magic env var code, bypassed Twilio. That design has several problems: a single static secret shared across all devs, no per-dev revocation, no audit trail, and the bypass mechanism baked into the source code as a recipe for "how to sign in without OTP." Per-dev TOTP fixes all of these:
359
+ A single static bypass code shared across all devs has a large blast radius, no per-dev revocation, and no audit trail, and bakes a "how to sign in without OTP" recipe into the source. Per-dev TOTP fixes all of these: one-account blast radius, delete-one-row revocation, a `last_used_at`/`used_count` audit trail per enrollment, codes that rotate every 30s, and a possession factor (the authenticator app on a specific device). Secrets live per-dev in the DB, not in source.
360
+
361
+ ## Roles & privileges
362
+
363
+ One `roles` table, one `user_roles` assignment, a flag:
299
364
 
300
- | Concern | Shared bypass code | Per-dev TOTP |
301
- | ------------------------ | -------------------------------------------- | -------------------------------------------------------------- |
302
- | Secret leak blast radius | Every dev account compromised | One dev account |
303
- | Per-dev revocation | Rotate the shared secret + everyone re-syncs | Delete one row |
304
- | Audit trail | None | `last_used_at` + `used_count` per enrollment |
305
- | Brute-force resistance | 6-digit space, no rotation | 6-digit space, rotates every 30s |
306
- | Source-code visible | Shared secret + bypass logic | Just the verification code path; secrets are per-dev in the DB |
307
- | Possession factor | Just env var knowledge | Authenticator app on a specific device |
365
+ - `is_privilege = false` — selectable **mode/persona** roles. These drive the role switcher and become `app.active_role`. One should be marked `is_default`.
366
+ - `is_privilege = true` — always-on **capability flags**. Every privilege the user holds is exported in `app.privileges`.
308
367
 
309
- ## Typed roles
368
+ `ctx.roles` is the selectable roles the user holds; `ctx.privileges` is their capability flags. RLS policies parse `app.privileges` with `string_to_array(current_setting('app.privileges', true), ',')`.
310
369
 
311
- By default `roleName` is typed as `string`, which works for any consumer. To get autocomplete and typo detection for your specific role names, write a thin wrapper in your application code:
370
+ ### Typed roles
371
+
372
+ By default `roleName` is `string`. For autocomplete and typo detection, write a thin wrapper:
312
373
 
313
374
  ```ts
314
375
  // src/lib/auth.ts
@@ -322,160 +383,85 @@ import {
322
383
  export type RoleName = 'user' | 'settings' | 'security';
323
384
  export type SessionContext = BaseContext<RoleName>;
324
385
 
325
- export async function withSession<T>(
386
+ export function withSession<T>(
326
387
  pool: Pool,
327
- auth: { sessionId: string; roleName: RoleName },
388
+ auth: { token: string; roleName?: RoleName },
328
389
  fn: (client: PoolClient, ctx: SessionContext) => Promise<T>,
390
+ options?: Parameters<typeof baseWithSession<RoleName, T>>[3],
329
391
  ): Promise<T> {
330
- return baseWithSession<RoleName, T>(pool, auth, fn);
392
+ return baseWithSession<RoleName, T>(pool, auth, fn, options);
331
393
  }
332
394
 
333
395
  export * from '@smplcty/auth';
334
396
  ```
335
397
 
336
- Now everywhere in your app:
337
-
338
- ```ts
339
- import { withSession, type RoleName } from './lib/auth';
340
-
341
- await withSession(pool, { sessionId, roleName: 'user' }, async (client, ctx) => {
342
- ctx.roles; // readonly RoleName[]
343
- });
344
- ```
345
-
346
- A typo in `roleName` becomes a compile error.
347
-
348
398
  ## Logging
349
399
 
350
- `@smplcty/auth` does not log anything by default. To get diagnostic logs, pass an optional logger to `withSession`:
400
+ The library logs nothing by default. Pass a logger to `withSession`:
351
401
 
352
402
  ```ts
353
- import { withSession } from '@smplcty/auth';
354
403
  import pino from 'pino';
355
-
356
- const logger = pino({ redact: ['*.sessionId', 'headers.authorization'] });
357
-
358
- await withSession(pool, { sessionId, roleName: 'user' }, fn, { logger });
404
+ const logger = pino();
405
+ await withSession(pool, { token, roleName: 'user' }, fn, { logger });
359
406
  ```
360
407
 
361
- The `Logger` interface matches pino's structured-logging shape (`(data, msg)`), so you can pass a pino logger directly with no adapter. The library never logs the session ID or any PII; it logs structural events like `'session validated'` with non-sensitive identifiers like `userId` and a hash prefix of the session ID.
362
-
363
- If you don't pass a logger, the library is silent.
408
+ The `Logger` interface matches pino's `(data, msg)` shape. The library never logs the raw token or PII — only structural events with safe identifiers (a hash fingerprint, `userId`, role).
364
409
 
365
410
  ## Required database schema
366
411
 
367
- This library reads and writes specific tables and session variables. It does **not** run migrations — you own your schema. The exact schema the library expects is shipped inside the package at `node_modules/@smplcty/auth/schema/`:
412
+ The library ships its schema as schema-flow YAML inside the package at `@smplcty/auth/schema/`. It does **not** run migrations — you own that. Generic mixins (`audit`, `soft_delete`) are **consumed from [`@smplcty/schema-std`](https://www.npmjs.com/package/@smplcty/schema-std)**, parameterized to auth's `users` table + `app.actor_id`.
368
413
 
369
414
  ```
370
415
  @smplcty/auth/schema/
371
- └── tables/
372
- ├── tenants.yaml
373
- ├── roles.yaml # includes inline seeds for the
374
- │ # canonical 'user', 'settings',
375
- │ # 'security' roles (IDs 1-3)
376
- ├── users.yaml
377
- ├── communication_channels.yaml
378
- ├── user_communication_methods.yaml
379
- ├── user_roles.yaml
380
- └── sessions.yaml
416
+ ├── tables/
417
+ │ ├── users.yaml # + audit; seeds the app-init service user (id 1)
418
+ │ ├── tenants.yaml # + audit; slug (sub-domain), allow_otp (SSO-only switch)
419
+ │ ├── roles.yaml # + audit; seeds 'user' (default), 'settings', 'security'
420
+ │ ├── user_roles.yaml # + audit; tenant_id NULL = wildcard / all tenants
421
+ │ ├── communication_channels.yaml
422
+ │ ├── user_communication_methods.yaml
423
+ │ ├── auth_domains.yaml # + audit; tenant's IdP(s), 1:N, resolved by id (display_name = button)
424
+ │ ├── sessions.yaml # PK = token hash; last_seen_at; geo
425
+ │ └── dev_otp_enrollments.yaml
426
+ ├── functions/
427
+ │ ├── resolve_session.yaml # pure resolver (SECURITY DEFINER)
428
+ │ └── current_user_id.yaml # reads app.actor_id
429
+ └── post/
430
+ └── 0001-backfill-audit-by.sql # attributes seeded rows to app-init before NOT NULL tighten
381
431
  ```
382
432
 
383
- These files **are** the schema. They are validated end-to-end by the library's own test suite on every release — if the library passes its tests, your database will accept them.
384
-
385
- The canonical role seeds are colocated with the table definition in `roles.yaml`. Role IDs 1-3 are reserved for the standard `'user'`, `'settings'`, `'security'` rows; consumers adding their own roles should use IDs >= 100. The library never references these IDs directly — it always looks up by name — so the IDs are just a stable convention for migration-time conflict detection.
386
-
387
- ### If you use [`@smplcty/schema-flow`](https://www.npmjs.com/package/@smplcty/schema-flow)
433
+ ### Consuming with [`@smplcty/schema-flow`](https://www.npmjs.com/package/@smplcty/schema-flow)
388
434
 
389
- Copy the shipped files into your own schema directory:
435
+ Import auth's schema and `@smplcty/schema-std` from your schema-flow config. See the reference [`schema-flow.config.yaml`](schema-flow.config.yaml):
390
436
 
391
- ```sh
392
- cp node_modules/@smplcty/auth/schema/tables/*.yaml schema/tables/
393
- npx @smplcty/schema-flow run
437
+ ```yaml
438
+ default:
439
+ imports:
440
+ - package: '@smplcty/schema-std' # generic mixins, parameterized to users / user_id / app.actor_id
441
+ - package: '@smplcty/auth' # identity/tenant/auth_domains tables + resolve_session/current_user_id
394
442
  ```
395
443
 
396
- You can edit the copies if you need additional columns (e.g. add a `last_seen_at` to `sessions`) — just keep the columns the library reads/writes intact.
397
-
398
- ### If you use any other migration tool (Drizzle, Prisma, hand-rolled SQL, …)
399
-
400
- Translate the YAML manually. The equivalent DDL is:
401
-
402
- ```sql
403
- CREATE TABLE tenants (
404
- tenant_id SERIAL PRIMARY KEY,
405
- name TEXT NOT NULL UNIQUE
406
- );
407
-
408
- CREATE TABLE roles (
409
- role_id SERIAL PRIMARY KEY,
410
- name TEXT NOT NULL UNIQUE
411
- );
412
- INSERT INTO roles (role_id, name) VALUES
413
- (1, 'user'),
414
- (2, 'settings'),
415
- (3, 'security')
416
- ON CONFLICT (role_id) DO NOTHING;
417
-
418
- CREATE TABLE users (
419
- user_id SERIAL PRIMARY KEY,
420
- name TEXT
421
- );
422
-
423
- CREATE TABLE communication_channels (
424
- communication_channel_id SERIAL PRIMARY KEY,
425
- name TEXT NOT NULL UNIQUE
426
- );
427
-
428
- CREATE TABLE user_communication_methods (
429
- user_communication_method_id SERIAL PRIMARY KEY,
430
- user_id INT NOT NULL REFERENCES users(user_id),
431
- communication_channel_id INT NOT NULL REFERENCES communication_channels(communication_channel_id),
432
- code TEXT NOT NULL,
433
- UNIQUE (communication_channel_id, code)
434
- );
435
-
436
- CREATE TABLE user_roles (
437
- user_role_id SERIAL PRIMARY KEY,
438
- user_id INT NOT NULL REFERENCES users(user_id),
439
- role_id INT NOT NULL REFERENCES roles(role_id),
440
- tenant_id INT REFERENCES tenants(tenant_id) -- NULL = global / all tenants
441
- );
442
-
443
- CREATE TABLE sessions (
444
- session_id TEXT PRIMARY KEY,
445
- user_communication_method_id INT NOT NULL REFERENCES user_communication_methods(user_communication_method_id),
446
- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
447
- expires_at TIMESTAMPTZ NOT NULL,
448
- ip TEXT,
449
- city TEXT,
450
- region TEXT,
451
- country TEXT,
452
- latitude TEXT,
453
- longitude TEXT
454
- );
455
- ```
444
+ The `audit` mixin makes `created_by`/`updated_by` NOT NULL, stamped from `app.actor_id`. Rows seeded during migration have no request actor, so the shipped `post/` script back-fills them to the seeded `app-init` service user (`users.user_id = 1`) before the NOT NULL tighten phase — see the config for details.
456
445
 
457
- The DDL above is kept in sync with the shipped YAML files by hand. If you're paranoid about drift between this snippet and what the library actually requires, copy the YAML files instead — they are the source of truth.
446
+ ### Soft delete
458
447
 
459
- The library also expects four custom Postgres session variables to be readable from your RLS policies:
448
+ Every table carries the `soft_delete` mixin (`deleted_at`). The library **honors** it — `resolve_session`, `validateSession`, `findUserByCommunicationMethod`, `getUserRoleNames`, and the flat-tenant preset all exclude soft-deleted rows — so a soft-deleted session, user, communication method, or role assignment stops taking effect immediately. Unique indexes are partial (`WHERE deleted_at IS NULL`) so a name/code can be reused after its row is archived. Setting/clearing `deleted_at` is a plain write your app owns; the library ships no delete setter. (Note: writing `deleted_at` on an _audited_ table goes through the audit trigger, so set `app.actor_id` first — e.g. inside `withSession`/`withServiceContext`.)
460
449
 
461
- | GUC | Set by | Type |
462
- | ----------------- | ----------------------------------------------------- | ---------------------------------------------------- |
463
- | `app.session_id` | `setSessionId` / `setSessionContext` / `withSession` | text |
464
- | `app.role_name` | `setRoleName` / `setSessionContext` / `withSession` | text |
465
- | `app.tenant_ids` | `setTenantIds` / `setSessionContext` / `withSession` | comma-separated text (parsed into int[] in policies) |
466
- | `app.all_tenants` | `setAllTenants` / `setSessionContext` / `withSession` | text `'true'` or `'false'` |
450
+ ### Functions the library calls
467
451
 
468
- These are set with **transaction scope** (`set_config(name, value, true)`) and discarded automatically on COMMIT or ROLLBACK.
452
+ | Function | Role |
453
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
454
+ | `resolve_session(hash)` | SECURITY DEFINER **pure resolver** → `{ user_id, expires_at, roles[], default_role, privileges[] }`; validates nothing (validation/role-selection live in `withSession`) |
455
+ | `current_user_id()` | reads `app.actor_id` — the join key app RLS/scope functions should use |
469
456
 
470
457
  ## Security model
471
458
 
472
- - Every parameterized query — no string interpolation anywhere in the library.
473
- - Session variables set via `set_config($1, $2, true)`, not `SET ... TO ...` with concatenation. SQL injection in session/role names is impossible.
474
- - Transaction scope on every session variable. Cross-request leaks are impossible.
475
- - `withSession` validates session existence, expiration, and role assignment before running the callback. Fails closed on any check.
476
- - `crypto.randomUUID()` for session IDs (122 bits of entropy).
477
- - No `console.*` calls in library code. PII in logs is the consumer's choice, not the library's default.
478
- - No transitive runtime dependencies — only `pg` as a peer dependency.
459
+ - Every query parameterized — no string interpolation in the library.
460
+ - **Session tokens hashed at rest** (SHA-256); the raw 256-bit token is returned once and never stored. A DB leak exposes only hashes.
461
+ - Identity GUCs set via `set_config($1, $2, true)`, transaction-scoped — injection and cross-request leakage are impossible.
462
+ - `withSession` validates existence, expiry/revocation, and role membership before running the callback. Fails closed.
463
+ - Force sign-off is a row update (per-session, per-user, or per-tenant); role/privilege changes apply on the next request.
464
+ - Auth core has no `jose`/Twilio dependency; method handlers are opt-in subpaths with optional peers.
479
465
 
480
466
  ## License
481
467
 
@@ -2,16 +2,16 @@ import type { CreateSessionInput, Queryable, Session } from './types.js';
2
2
  /**
3
3
  * Create a new session for an already-authenticated user.
4
4
  *
5
- * The caller is responsible for verifying the user's identity (via
6
- * Twilio Verify, OIDC callback, password check, or whatever) BEFORE
7
- * calling this function. `createSession` does not perform any
8
- * authentication of its own — it simply persists a session row and
9
- * returns the new session token.
5
+ * The caller is responsible for verifying the user's identity (via a
6
+ * `MethodHandler`, Twilio Verify, OIDC callback, password check, …)
7
+ * BEFORE calling this. `createSession` performs no authentication — it
8
+ * persists a session row and returns the new token.
10
9
  *
11
- * The session ID is generated server-side using `crypto.randomUUID()`
12
- * (122 bits of entropy). The expiration is computed server-side as
13
- * `now() + interval $ttl` so there is no clock skew between the app and
14
- * the database.
10
+ * A fresh opaque token (256 bits of entropy) is generated server-side;
11
+ * only its **SHA-256 hash** is stored, as the `sessions` primary key. The
12
+ * raw token is returned **once** in {@link Session.token} — hand it to the
13
+ * client and don't persist it. Expiration is computed server-side as
14
+ * `now() + interval $ttl` so there's no app/database clock skew.
15
15
  *
16
16
  * @example
17
17
  * ```ts
@@ -21,6 +21,7 @@ import type { CreateSessionInput, Queryable, Session } from './types.js';
21
21
  * ip: req.ip,
22
22
  * geo: { country: 'US', region: 'CA' },
23
23
  * });
24
+ * setCookie('session', session.token); // raw token to the client, once
24
25
  * ```
25
26
  *
26
27
  * @throws {InvalidInputError} If `ttl` is empty or `userCommunicationMethodId` is not a positive integer.
@@ -1 +1 @@
1
- {"version":3,"file":"create-session.d.ts","sourceRoot":"","sources":["../src/create-session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAoDzE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,aAAa,CAAC,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC,CA8C9F"}
1
+ {"version":3,"file":"create-session.d.ts","sourceRoot":"","sources":["../src/create-session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AA6CzE;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAsB,aAAa,CAAC,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC,CA+C9F"}