@smplcty/auth 0.6.4 → 1.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.
- package/README.md +186 -201
- package/dist/create-session.d.ts +10 -9
- package/dist/create-session.d.ts.map +1 -1
- package/dist/create-session.js +16 -18
- package/dist/create-session.js.map +1 -1
- package/dist/errors.d.ts +19 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +23 -5
- package/dist/errors.js.map +1 -1
- package/dist/find-user-by-communication-method.d.ts.map +1 -1
- package/dist/find-user-by-communication-method.js +4 -0
- package/dist/find-user-by-communication-method.js.map +1 -1
- package/dist/get-user-role-names.d.ts.map +1 -1
- package/dist/get-user-role-names.js +2 -0
- package/dist/get-user-role-names.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -6
- package/dist/index.js.map +1 -1
- package/dist/internal/hash-token.d.ts +16 -0
- package/dist/internal/hash-token.d.ts.map +1 -0
- package/dist/internal/hash-token.js +21 -0
- package/dist/internal/hash-token.js.map +1 -0
- package/dist/methods/errors.d.ts +37 -0
- package/dist/methods/errors.d.ts.map +1 -0
- package/dist/methods/errors.js +48 -0
- package/dist/methods/errors.js.map +1 -0
- package/dist/methods/oidc/index.d.ts +65 -0
- package/dist/methods/oidc/index.d.ts.map +1 -0
- package/dist/methods/oidc/index.js +76 -0
- package/dist/methods/oidc/index.js.map +1 -0
- package/dist/methods/router.d.ts +39 -0
- package/dist/methods/router.d.ts.map +1 -0
- package/dist/methods/router.js +153 -0
- package/dist/methods/router.js.map +1 -0
- package/dist/methods/twilio/index.d.ts +44 -0
- package/dist/methods/twilio/index.d.ts.map +1 -0
- package/dist/methods/twilio/index.js +77 -0
- package/dist/methods/twilio/index.js.map +1 -0
- package/dist/methods/types.d.ts +124 -0
- package/dist/methods/types.d.ts.map +1 -0
- package/dist/methods/types.js +2 -0
- package/dist/methods/types.js.map +1 -0
- package/dist/revoke-session.d.ts +20 -15
- package/dist/revoke-session.d.ts.map +1 -1
- package/dist/revoke-session.js +66 -20
- package/dist/revoke-session.js.map +1 -1
- package/dist/scope/flat-tenant.d.ts +36 -0
- package/dist/scope/flat-tenant.d.ts.map +1 -0
- package/dist/scope/flat-tenant.js +60 -0
- package/dist/scope/flat-tenant.js.map +1 -0
- package/dist/set-helpers.d.ts +44 -53
- package/dist/set-helpers.d.ts.map +1 -1
- package/dist/set-helpers.js +67 -68
- package/dist/set-helpers.js.map +1 -1
- package/dist/touch-session.d.ts +13 -0
- package/dist/touch-session.d.ts.map +1 -0
- package/dist/touch-session.js +28 -0
- package/dist/touch-session.js.map +1 -0
- package/dist/types.d.ts +59 -18
- package/dist/types.d.ts.map +1 -1
- package/dist/validate-session.d.ts +15 -14
- package/dist/validate-session.d.ts.map +1 -1
- package/dist/validate-session.js +28 -27
- package/dist/validate-session.js.map +1 -1
- package/dist/with-service-context.d.ts +15 -12
- package/dist/with-service-context.d.ts.map +1 -1
- package/dist/with-service-context.js +34 -30
- package/dist/with-service-context.js.map +1 -1
- package/dist/with-session.d.ts +22 -16
- package/dist/with-session.d.ts.map +1 -1
- package/dist/with-session.js +67 -63
- package/dist/with-session.js.map +1 -1
- package/package.json +32 -2
- package/schema/functions/current_user_id.yaml +18 -0
- package/schema/functions/resolve_session.yaml +42 -23
- package/schema/post/0001-backfill-audit-by.sql +15 -0
- package/schema/tables/auth_domains.yaml +43 -0
- package/schema/tables/communication_channels.yaml +5 -1
- package/schema/tables/dev_otp_enrollments.yaml +1 -0
- package/schema/tables/roles.yaml +43 -7
- package/schema/tables/sessions.yaml +10 -0
- package/schema/tables/tenants.yaml +24 -1
- package/schema/tables/user_communication_methods.yaml +5 -1
- package/schema/tables/user_roles.yaml +1 -0
- package/schema/tables/users.yaml +27 -0
- package/dist/with-transaction.d.ts +0 -31
- package/dist/with-transaction.d.ts.map +0 -1
- package/dist/with-transaction.js +0 -49
- 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
|
|
3
|
+
Robust, type-safe **stateful-session** authentication primitives for PostgreSQL apps using Row-Level Security.
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@smplcty/auth)
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
|
|
8
8
|
## Why
|
|
9
9
|
|
|
10
|
-
|
|
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
|
-
|
|
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
|
-
|
|
14
|
+
Every request sets four **identity GUCs** on its transaction-bound connection, transaction-scoped so they can't leak across requests:
|
|
17
15
|
|
|
18
|
-
|
|
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,
|
|
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, {
|
|
36
|
-
// ctx = { userId,
|
|
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
|
|
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` |
|
|
49
|
-
| `SessionExpiredError` | session
|
|
50
|
-
| `
|
|
51
|
-
| `InvalidInputError` |
|
|
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
|
|
58
|
+
All errors extend `AuthError` and carry a `code`:
|
|
54
59
|
|
|
55
60
|
```ts
|
|
56
61
|
try {
|
|
57
|
-
await withSession(pool, {
|
|
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,164 @@ try {
|
|
|
63
68
|
}
|
|
64
69
|
```
|
|
65
70
|
|
|
66
|
-
##
|
|
71
|
+
## Authorization scope (app-owned)
|
|
67
72
|
|
|
68
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,
|
|
113
|
+
import { withTransaction, setIdentityContext } from '@smplcty/auth';
|
|
87
114
|
|
|
88
115
|
await withTransaction(pool, async (client) => {
|
|
89
|
-
await
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
-
|
|
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
|
-
##
|
|
128
|
+
## Session lifecycle
|
|
104
129
|
|
|
105
|
-
`createSession`, `validateSession`, `revokeSession`, and `findUserByCommunicationMethod`
|
|
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
|
-
|
|
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 = {
|
|
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
|
|
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
|
|
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
|
|
148
|
-
return { allow: true, principalId: String(
|
|
149
|
-
} catch
|
|
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
|
-
###
|
|
167
|
+
### Revocation & activity
|
|
155
168
|
|
|
156
169
|
```ts
|
|
157
|
-
|
|
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 (pluggable)
|
|
179
|
+
|
|
180
|
+
A `MethodHandler` models a two-phase flow (`initiate` → send OTP / redirect; `complete` → verify → resolved user). The router is **tenant-centric**: the app resolves the tenant from the request sub-domain (`tenants.slug`), the router lists that tenant's IdPs and dispatches the chosen one by `auth_domains.integration_type`. A tenant has **0..N** IdPs (mergers, mixed workforces, multi-domain orgs), so:
|
|
181
|
+
|
|
182
|
+
- **0 IdPs** → OTP only.
|
|
183
|
+
- **1 IdP** → straight redirect, no sign-in form.
|
|
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.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import { createMethodRouter } from '@smplcty/auth';
|
|
190
|
+
import { oidcHandler } from '@smplcty/auth/oidc'; // optional peer: @smplcty/oidc
|
|
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
|
+
handlers: { oidc: oidcHandler() }, // org-bound, by integration_type
|
|
197
|
+
otpHandler: twilioVerifyHandler({ client: createTwilioVerifyClient(cfg) }), // user-bound, tenant-gated
|
|
198
|
+
});
|
|
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: opts.authDomains (buttons) + an OTP form iff opts.otpAllowed
|
|
204
|
+
|
|
205
|
+
// OIDC — user clicked the "Microsoft" button (auth_domain_id 1):
|
|
206
|
+
const { redirectUrl } = await router.initiate(1);
|
|
207
|
+
// ...on callback, the app loads the auth_domain it stored against `state`:
|
|
208
|
+
const user = await router.complete(1, idToken);
|
|
209
|
+
|
|
210
|
+
// OTP (only when opts.otpAllowed):
|
|
211
|
+
await router.initiateOtp({ tenantId: opts.tenantId, identifier: phone });
|
|
212
|
+
const user2 = await router.completeOtp({ tenantId: opts.tenantId, identifier: phone, credential: code });
|
|
158
213
|
|
|
159
|
-
await
|
|
214
|
+
const session = await createSession(pool, {
|
|
215
|
+
userCommunicationMethodId: user.userCommunicationMethodId,
|
|
216
|
+
ttl: '30 days',
|
|
217
|
+
});
|
|
160
218
|
```
|
|
161
219
|
|
|
162
|
-
|
|
220
|
+
Auth **core** depends on neither `jose` nor Twilio — the handler subpaths do, as **optional peers**. A password-only app installs neither. OIDC is org-bound (reads `auth_domains`); Twilio Verify is user-bound (phone/email) and integrates the [dev-OTP](#developer-otp--for-devs-whose-phones-cant-receive-sms) fallback automatically.
|
|
221
|
+
|
|
222
|
+
**What stays app-side:** parsing the request `Host` → slug, the chooser/redirect UI, and the OIDC login-state store (the `state`/`nonce`/PKCE verifier persisted across the redirect). The full OIDC authorization-code flow (authorization-URL building, PKCE, token exchange) is being added to `@smplcty/oidc`; today `oidcHandler.initiate` builds the redirect from the `auth_domains` config and `complete` verifies the returned `id_token`.
|
|
163
223
|
|
|
164
224
|
## Developer OTP — for devs whose phones can't receive SMS
|
|
165
225
|
|
|
166
226
|
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
227
|
|
|
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
|
|
228
|
+
`@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
229
|
|
|
170
230
|
### How the codes are distinguished from Twilio codes
|
|
171
231
|
|
|
@@ -277,7 +337,7 @@ WHERE cc.name = 'phone' AND ucm.code = '${phone}';
|
|
|
277
337
|
`);
|
|
278
338
|
```
|
|
279
339
|
|
|
280
|
-
|
|
340
|
+
The script generates a fresh secret, prints a scannable QR code, and gives you the SQL to run against your database.
|
|
281
341
|
|
|
282
342
|
### Revoking a dev's enrollment
|
|
283
343
|
|
|
@@ -291,24 +351,24 @@ WHERE user_communication_method_id = (
|
|
|
291
351
|
);
|
|
292
352
|
```
|
|
293
353
|
|
|
294
|
-
The next
|
|
354
|
+
The next verify call for that user will fall through to Twilio as if they were never enrolled.
|
|
295
355
|
|
|
296
356
|
### Why per-dev TOTP instead of a shared bypass code?
|
|
297
357
|
|
|
298
|
-
|
|
358
|
+
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.
|
|
359
|
+
|
|
360
|
+
## Roles & privileges
|
|
361
|
+
|
|
362
|
+
One `roles` table, one `user_roles` assignment, a flag:
|
|
299
363
|
|
|
300
|
-
|
|
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 |
|
|
364
|
+
- `is_privilege = false` — selectable **mode/persona** roles. These drive the role switcher and become `app.active_role`. One should be marked `is_default`.
|
|
365
|
+
- `is_privilege = true` — always-on **capability flags**. Every privilege the user holds is exported in `app.privileges`.
|
|
308
366
|
|
|
309
|
-
|
|
367
|
+
`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
368
|
|
|
311
|
-
|
|
369
|
+
### Typed roles
|
|
370
|
+
|
|
371
|
+
By default `roleName` is `string`. For autocomplete and typo detection, write a thin wrapper:
|
|
312
372
|
|
|
313
373
|
```ts
|
|
314
374
|
// src/lib/auth.ts
|
|
@@ -322,160 +382,85 @@ import {
|
|
|
322
382
|
export type RoleName = 'user' | 'settings' | 'security';
|
|
323
383
|
export type SessionContext = BaseContext<RoleName>;
|
|
324
384
|
|
|
325
|
-
export
|
|
385
|
+
export function withSession<T>(
|
|
326
386
|
pool: Pool,
|
|
327
|
-
auth: {
|
|
387
|
+
auth: { token: string; roleName?: RoleName },
|
|
328
388
|
fn: (client: PoolClient, ctx: SessionContext) => Promise<T>,
|
|
389
|
+
options?: Parameters<typeof baseWithSession<RoleName, T>>[3],
|
|
329
390
|
): Promise<T> {
|
|
330
|
-
return baseWithSession<RoleName, T>(pool, auth, fn);
|
|
391
|
+
return baseWithSession<RoleName, T>(pool, auth, fn, options);
|
|
331
392
|
}
|
|
332
393
|
|
|
333
394
|
export * from '@smplcty/auth';
|
|
334
395
|
```
|
|
335
396
|
|
|
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
397
|
## Logging
|
|
349
398
|
|
|
350
|
-
|
|
399
|
+
The library logs nothing by default. Pass a logger to `withSession`:
|
|
351
400
|
|
|
352
401
|
```ts
|
|
353
|
-
import { withSession } from '@smplcty/auth';
|
|
354
402
|
import pino from 'pino';
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
await withSession(pool, { sessionId, roleName: 'user' }, fn, { logger });
|
|
403
|
+
const logger = pino();
|
|
404
|
+
await withSession(pool, { token, roleName: 'user' }, fn, { logger });
|
|
359
405
|
```
|
|
360
406
|
|
|
361
|
-
The `Logger` interface matches pino's
|
|
362
|
-
|
|
363
|
-
If you don't pass a logger, the library is silent.
|
|
407
|
+
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
408
|
|
|
365
409
|
## Required database schema
|
|
366
410
|
|
|
367
|
-
|
|
411
|
+
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
412
|
|
|
369
413
|
```
|
|
370
414
|
@smplcty/auth/schema/
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
415
|
+
├── tables/
|
|
416
|
+
│ ├── users.yaml # + audit; seeds the app-init service user (id 1)
|
|
417
|
+
│ ├── tenants.yaml # + audit; slug (sub-domain), allow_otp (SSO-only switch)
|
|
418
|
+
│ ├── roles.yaml # + audit; seeds 'user' (default), 'settings', 'security'
|
|
419
|
+
│ ├── user_roles.yaml # + audit; tenant_id NULL = wildcard / all tenants
|
|
420
|
+
│ ├── communication_channels.yaml
|
|
421
|
+
│ ├── user_communication_methods.yaml
|
|
422
|
+
│ ├── auth_domains.yaml # + audit; tenant's IdP(s), 1:N, resolved by id (display_name = button)
|
|
423
|
+
│ ├── sessions.yaml # PK = token hash; last_seen_at; geo
|
|
424
|
+
│ └── dev_otp_enrollments.yaml
|
|
425
|
+
├── functions/
|
|
426
|
+
│ ├── resolve_session.yaml # pure resolver (SECURITY DEFINER)
|
|
427
|
+
│ └── current_user_id.yaml # reads app.actor_id
|
|
428
|
+
└── post/
|
|
429
|
+
└── 0001-backfill-audit-by.sql # attributes seeded rows to app-init before NOT NULL tighten
|
|
381
430
|
```
|
|
382
431
|
|
|
383
|
-
|
|
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)
|
|
432
|
+
### Consuming with [`@smplcty/schema-flow`](https://www.npmjs.com/package/@smplcty/schema-flow)
|
|
388
433
|
|
|
389
|
-
|
|
434
|
+
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
435
|
|
|
391
|
-
```
|
|
392
|
-
|
|
393
|
-
|
|
436
|
+
```yaml
|
|
437
|
+
default:
|
|
438
|
+
imports:
|
|
439
|
+
- package: '@smplcty/schema-std' # generic mixins, parameterized to users / user_id / app.actor_id
|
|
440
|
+
- package: '@smplcty/auth' # identity/tenant/auth_domains tables + resolve_session/current_user_id
|
|
394
441
|
```
|
|
395
442
|
|
|
396
|
-
|
|
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
|
-
```
|
|
443
|
+
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
444
|
|
|
457
|
-
|
|
445
|
+
### Soft delete
|
|
458
446
|
|
|
459
|
-
The library
|
|
447
|
+
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
448
|
|
|
461
|
-
|
|
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'` |
|
|
449
|
+
### Functions the library calls
|
|
467
450
|
|
|
468
|
-
|
|
451
|
+
| Function | Role |
|
|
452
|
+
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
453
|
+
| `resolve_session(hash)` | SECURITY DEFINER **pure resolver** → `{ user_id, expires_at, roles[], default_role, privileges[] }`; validates nothing (validation/role-selection live in `withSession`) |
|
|
454
|
+
| `current_user_id()` | reads `app.actor_id` — the join key app RLS/scope functions should use |
|
|
469
455
|
|
|
470
456
|
## Security model
|
|
471
457
|
|
|
472
|
-
- Every parameterized
|
|
473
|
-
- Session
|
|
474
|
-
-
|
|
475
|
-
- `withSession` validates
|
|
476
|
-
-
|
|
477
|
-
-
|
|
478
|
-
- No transitive runtime dependencies — only `pg` as a peer dependency.
|
|
458
|
+
- Every query parameterized — no string interpolation in the library.
|
|
459
|
+
- **Session tokens hashed at rest** (SHA-256); the raw 256-bit token is returned once and never stored. A DB leak exposes only hashes.
|
|
460
|
+
- Identity GUCs set via `set_config($1, $2, true)`, transaction-scoped — injection and cross-request leakage are impossible.
|
|
461
|
+
- `withSession` validates existence, expiry/revocation, and role membership before running the callback. Fails closed.
|
|
462
|
+
- Force sign-off is a row update (per-session, per-user, or per-tenant); role/privilege changes apply on the next request.
|
|
463
|
+
- Auth core has no `jose`/Twilio dependency; method handlers are opt-in subpaths with optional peers.
|
|
479
464
|
|
|
480
465
|
## License
|
|
481
466
|
|
package/dist/create-session.d.ts
CHANGED
|
@@ -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,
|
|
7
|
-
* calling this
|
|
8
|
-
*
|
|
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
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
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;
|
|
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"}
|