@smplcty/auth 0.6.3 → 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 +198 -223
- package/dist/create-session.d.ts +10 -9
- package/dist/create-session.d.ts.map +1 -1
- package/dist/create-session.js +18 -23
- package/dist/create-session.js.map +1 -1
- package/dist/dev-otp.d.ts.map +1 -1
- package/dist/dev-otp.js +4 -10
- package/dist/dev-otp.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 +8 -1
- 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 +10 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -7
- 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 -74
- 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 -39
- 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 -66
- package/dist/with-session.js.map +1 -1
- package/package.json +53 -4
- 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,64 +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(
|
|
36
|
-
|
|
37
|
-
{
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const { rows } = await client.query('SELECT * FROM widgets');
|
|
41
|
-
return rows;
|
|
42
|
-
}
|
|
43
|
-
);
|
|
40
|
+
const widgets = await withSession(pool, { token, roleName: 'user' }, async (client, ctx) => {
|
|
41
|
+
// ctx = { userId, activeRole, roles, privileges }
|
|
42
|
+
const { rows } = await client.query('SELECT * FROM widgets');
|
|
43
|
+
return rows;
|
|
44
|
+
});
|
|
44
45
|
```
|
|
45
46
|
|
|
46
|
-
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.
|
|
47
48
|
|
|
48
49
|
### Errors thrown by `withSession`
|
|
49
50
|
|
|
50
|
-
| Error
|
|
51
|
-
|
|
52
|
-
| `SessionNotFoundError` |
|
|
53
|
-
| `SessionExpiredError`
|
|
54
|
-
| `
|
|
55
|
-
| `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 |
|
|
56
57
|
|
|
57
|
-
All errors extend `AuthError` and
|
|
58
|
+
All errors extend `AuthError` and carry a `code`:
|
|
58
59
|
|
|
59
60
|
```ts
|
|
60
61
|
try {
|
|
61
|
-
await withSession(pool, {
|
|
62
|
+
await withSession(pool, { token, roleName: 'user' }, fn);
|
|
62
63
|
} catch (err) {
|
|
63
64
|
if (err instanceof AuthError && err.code === 'SESSION_EXPIRED') {
|
|
64
65
|
// redirect to login
|
|
@@ -67,115 +68,164 @@ try {
|
|
|
67
68
|
}
|
|
68
69
|
```
|
|
69
70
|
|
|
70
|
-
##
|
|
71
|
+
## Authorization scope (app-owned)
|
|
71
72
|
|
|
72
|
-
|
|
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:
|
|
73
74
|
|
|
74
75
|
```ts
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
+
```
|
|
82
83
|
|
|
83
|
-
|
|
84
|
-
await setSessionId(client, sessionId);
|
|
85
|
-
await setRoleName(client, 'user');
|
|
86
|
-
await setTenantIds(client, [1, 2, 3]);
|
|
87
|
-
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:
|
|
88
85
|
|
|
89
|
-
|
|
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
|
|
90
105
|
});
|
|
91
106
|
```
|
|
92
107
|
|
|
93
|
-
|
|
108
|
+
## Low-level usage — `withTransaction` + identity setters
|
|
109
|
+
|
|
110
|
+
For migrating existing code, tests, or unusual cases. `withTransaction` is re-exported from `@smplcty/db`.
|
|
94
111
|
|
|
95
112
|
```ts
|
|
96
|
-
import { withTransaction,
|
|
113
|
+
import { withTransaction, setIdentityContext } from '@smplcty/auth';
|
|
97
114
|
|
|
98
115
|
await withTransaction(pool, async (client) => {
|
|
99
|
-
await
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
116
|
+
await setIdentityContext(client, {
|
|
117
|
+
actorId: 42,
|
|
118
|
+
sessionId: tokenHash,
|
|
119
|
+
activeRole: 'user',
|
|
120
|
+
privileges: ['can_export'],
|
|
104
121
|
});
|
|
105
122
|
return client.query('SELECT * FROM widgets');
|
|
106
123
|
});
|
|
107
124
|
```
|
|
108
125
|
|
|
109
|
-
|
|
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.
|
|
110
127
|
|
|
111
|
-
|
|
128
|
+
## Session lifecycle
|
|
112
129
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
`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.
|
|
116
131
|
|
|
117
132
|
### `findUserByCommunicationMethod`
|
|
118
133
|
|
|
119
134
|
```ts
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
const lookup = await findUserByCommunicationMethod(db, {
|
|
123
|
-
channel: 'email',
|
|
124
|
-
code: 'alice@example.com',
|
|
125
|
-
});
|
|
126
|
-
if (!lookup) {
|
|
127
|
-
// user not registered
|
|
128
|
-
return;
|
|
129
|
-
}
|
|
130
|
-
// lookup = { userId, userCommunicationMethodId }
|
|
135
|
+
const lookup = await findUserByCommunicationMethod(db, { channel: 'email', code: 'alice@example.com' });
|
|
136
|
+
// lookup = { userId, userCommunicationMethodId } | null
|
|
131
137
|
```
|
|
132
138
|
|
|
133
139
|
### `createSession`
|
|
134
140
|
|
|
135
141
|
```ts
|
|
136
|
-
import { createSession } from '@smplcty/auth';
|
|
137
|
-
|
|
138
142
|
const session = await createSession(db, {
|
|
139
143
|
userCommunicationMethodId: lookup.userCommunicationMethodId,
|
|
140
144
|
ttl: '30 days',
|
|
141
145
|
ip: req.ip,
|
|
142
146
|
geo: { country: 'US', region: 'CA' },
|
|
143
147
|
});
|
|
144
|
-
// session = {
|
|
148
|
+
// session = { token, userId, createdAt, expiresAt }
|
|
149
|
+
setCookie('session', session.token); // raw token to the client, ONCE
|
|
145
150
|
```
|
|
146
151
|
|
|
147
|
-
`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.
|
|
148
153
|
|
|
149
154
|
### `validateSession`
|
|
150
155
|
|
|
151
|
-
For authorizers
|
|
156
|
+
For authorizers / "is this token alive?" checks. Returns `SessionInfo` (`{ userId, createdAt, expiresAt, lastSeenAt }`) or throws. Sets no GUCs.
|
|
152
157
|
|
|
153
158
|
```ts
|
|
154
|
-
import { validateSession, SessionExpiredError } from '@smplcty/auth';
|
|
155
|
-
|
|
156
159
|
try {
|
|
157
|
-
const
|
|
158
|
-
return { allow: true, principalId: String(
|
|
159
|
-
} catch
|
|
160
|
+
const info = await validateSession(db, token);
|
|
161
|
+
return { allow: true, principalId: String(info.userId) };
|
|
162
|
+
} catch {
|
|
160
163
|
return { allow: false };
|
|
161
164
|
}
|
|
162
165
|
```
|
|
163
166
|
|
|
164
|
-
###
|
|
167
|
+
### Revocation & activity
|
|
165
168
|
|
|
166
169
|
```ts
|
|
167
|
-
|
|
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);
|
|
168
209
|
|
|
169
|
-
|
|
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 });
|
|
213
|
+
|
|
214
|
+
const session = await createSession(pool, {
|
|
215
|
+
userCommunicationMethodId: user.userCommunicationMethodId,
|
|
216
|
+
ttl: '30 days',
|
|
217
|
+
});
|
|
170
218
|
```
|
|
171
219
|
|
|
172
|
-
|
|
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`.
|
|
173
223
|
|
|
174
224
|
## Developer OTP — for devs whose phones can't receive SMS
|
|
175
225
|
|
|
176
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.
|
|
177
227
|
|
|
178
|
-
`@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.)
|
|
179
229
|
|
|
180
230
|
### How the codes are distinguished from Twilio codes
|
|
181
231
|
|
|
@@ -191,7 +241,9 @@ When a user is enrolled in dev OTP, you don't need to send them an SMS at all
|
|
|
191
241
|
import { findUserByCommunicationMethod, isDevOtpEnrolled } from '@smplcty/auth';
|
|
192
242
|
import { createTwilioVerifyClient } from '@smplcty/twilio';
|
|
193
243
|
|
|
194
|
-
const twilio = createTwilioVerifyClient({
|
|
244
|
+
const twilio = createTwilioVerifyClient({
|
|
245
|
+
/* ... */
|
|
246
|
+
});
|
|
195
247
|
|
|
196
248
|
// Sign-in send handler:
|
|
197
249
|
const lookup = await findUserByCommunicationMethod(db, { channel: 'phone', code: phone });
|
|
@@ -219,7 +271,9 @@ return ok();
|
|
|
219
271
|
import { verifyDevOtp, createSession, findUserByCommunicationMethod } from '@smplcty/auth';
|
|
220
272
|
import { createTwilioVerifyClient } from '@smplcty/twilio';
|
|
221
273
|
|
|
222
|
-
const twilio = createTwilioVerifyClient({
|
|
274
|
+
const twilio = createTwilioVerifyClient({
|
|
275
|
+
/* ... */
|
|
276
|
+
});
|
|
223
277
|
|
|
224
278
|
// Sign-in verify handler:
|
|
225
279
|
const lookup = await findUserByCommunicationMethod(db, { channel: 'phone', code: phone });
|
|
@@ -245,6 +299,7 @@ return badRequest('Invalid code');
|
|
|
245
299
|
```
|
|
246
300
|
|
|
247
301
|
`verifyDevOtp` returns `false` (does not throw) when:
|
|
302
|
+
|
|
248
303
|
- The user has no row in `dev_otp_enrollments`
|
|
249
304
|
- The submitted code doesn't match a TOTP for the stored secret within the ±30s tolerance window
|
|
250
305
|
- The stored secret is malformed (caught and treated as a non-match)
|
|
@@ -262,8 +317,8 @@ There's no shipped CLI — at the team sizes this library is designed for, manua
|
|
|
262
317
|
import { generateDevOtpSecret, getDevOtpEnrollmentUri } from '@smplcty/auth';
|
|
263
318
|
import qrcode from 'qrcode'; // pnpm add -D qrcode
|
|
264
319
|
|
|
265
|
-
const phone = process.argv[2];
|
|
266
|
-
const label = process.argv[3];
|
|
320
|
+
const phone = process.argv[2]; // e.g. '+15558675309'
|
|
321
|
+
const label = process.argv[3]; // e.g. 'sam@salez1.com'
|
|
267
322
|
const issuer = 'Salez1';
|
|
268
323
|
|
|
269
324
|
const secret = generateDevOtpSecret();
|
|
@@ -282,7 +337,7 @@ WHERE cc.name = 'phone' AND ucm.code = '${phone}';
|
|
|
282
337
|
`);
|
|
283
338
|
```
|
|
284
339
|
|
|
285
|
-
|
|
340
|
+
The script generates a fresh secret, prints a scannable QR code, and gives you the SQL to run against your database.
|
|
286
341
|
|
|
287
342
|
### Revoking a dev's enrollment
|
|
288
343
|
|
|
@@ -296,24 +351,24 @@ WHERE user_communication_method_id = (
|
|
|
296
351
|
);
|
|
297
352
|
```
|
|
298
353
|
|
|
299
|
-
The next
|
|
354
|
+
The next verify call for that user will fall through to Twilio as if they were never enrolled.
|
|
300
355
|
|
|
301
356
|
### Why per-dev TOTP instead of a shared bypass code?
|
|
302
357
|
|
|
303
|
-
|
|
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:
|
|
304
363
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
| Secret leak blast radius | Every dev account compromised | One dev account |
|
|
308
|
-
| Per-dev revocation | Rotate the shared secret + everyone re-syncs | Delete one row |
|
|
309
|
-
| Audit trail | None | `last_used_at` + `used_count` per enrollment |
|
|
310
|
-
| Brute-force resistance | 6-digit space, no rotation | 6-digit space, rotates every 30s |
|
|
311
|
-
| Source-code visible | Shared secret + bypass logic | Just the verification code path; secrets are per-dev in the DB |
|
|
312
|
-
| 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`.
|
|
313
366
|
|
|
314
|
-
|
|
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), ',')`.
|
|
315
368
|
|
|
316
|
-
|
|
369
|
+
### Typed roles
|
|
370
|
+
|
|
371
|
+
By default `roleName` is `string`. For autocomplete and typo detection, write a thin wrapper:
|
|
317
372
|
|
|
318
373
|
```ts
|
|
319
374
|
// src/lib/auth.ts
|
|
@@ -327,165 +382,85 @@ import {
|
|
|
327
382
|
export type RoleName = 'user' | 'settings' | 'security';
|
|
328
383
|
export type SessionContext = BaseContext<RoleName>;
|
|
329
384
|
|
|
330
|
-
export
|
|
385
|
+
export function withSession<T>(
|
|
331
386
|
pool: Pool,
|
|
332
|
-
auth: {
|
|
387
|
+
auth: { token: string; roleName?: RoleName },
|
|
333
388
|
fn: (client: PoolClient, ctx: SessionContext) => Promise<T>,
|
|
389
|
+
options?: Parameters<typeof baseWithSession<RoleName, T>>[3],
|
|
334
390
|
): Promise<T> {
|
|
335
|
-
return baseWithSession<RoleName, T>(pool, auth, fn);
|
|
391
|
+
return baseWithSession<RoleName, T>(pool, auth, fn, options);
|
|
336
392
|
}
|
|
337
393
|
|
|
338
394
|
export * from '@smplcty/auth';
|
|
339
395
|
```
|
|
340
396
|
|
|
341
|
-
Now everywhere in your app:
|
|
342
|
-
|
|
343
|
-
```ts
|
|
344
|
-
import { withSession, type RoleName } from './lib/auth';
|
|
345
|
-
|
|
346
|
-
await withSession(pool, { sessionId, roleName: 'user' }, async (client, ctx) => {
|
|
347
|
-
ctx.roles; // readonly RoleName[]
|
|
348
|
-
});
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
A typo in `roleName` becomes a compile error.
|
|
352
|
-
|
|
353
397
|
## Logging
|
|
354
398
|
|
|
355
|
-
|
|
399
|
+
The library logs nothing by default. Pass a logger to `withSession`:
|
|
356
400
|
|
|
357
401
|
```ts
|
|
358
|
-
import { withSession } from '@smplcty/auth';
|
|
359
402
|
import pino from 'pino';
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
await withSession(
|
|
364
|
-
pool,
|
|
365
|
-
{ sessionId, roleName: 'user' },
|
|
366
|
-
fn,
|
|
367
|
-
{ logger }
|
|
368
|
-
);
|
|
403
|
+
const logger = pino();
|
|
404
|
+
await withSession(pool, { token, roleName: 'user' }, fn, { logger });
|
|
369
405
|
```
|
|
370
406
|
|
|
371
|
-
The `Logger` interface matches pino's
|
|
372
|
-
|
|
373
|
-
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).
|
|
374
408
|
|
|
375
409
|
## Required database schema
|
|
376
410
|
|
|
377
|
-
|
|
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`.
|
|
378
412
|
|
|
379
413
|
```
|
|
380
414
|
@smplcty/auth/schema/
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
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
|
|
391
430
|
```
|
|
392
431
|
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
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.
|
|
396
|
-
|
|
397
|
-
### 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)
|
|
398
433
|
|
|
399
|
-
|
|
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):
|
|
400
435
|
|
|
401
|
-
```
|
|
402
|
-
|
|
403
|
-
|
|
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
|
|
404
441
|
```
|
|
405
442
|
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
### If you use any other migration tool (Drizzle, Prisma, hand-rolled SQL, …)
|
|
409
|
-
|
|
410
|
-
Translate the YAML manually. The equivalent DDL is:
|
|
411
|
-
|
|
412
|
-
```sql
|
|
413
|
-
CREATE TABLE tenants (
|
|
414
|
-
tenant_id SERIAL PRIMARY KEY,
|
|
415
|
-
name TEXT NOT NULL UNIQUE
|
|
416
|
-
);
|
|
417
|
-
|
|
418
|
-
CREATE TABLE roles (
|
|
419
|
-
role_id SERIAL PRIMARY KEY,
|
|
420
|
-
name TEXT NOT NULL UNIQUE
|
|
421
|
-
);
|
|
422
|
-
INSERT INTO roles (role_id, name) VALUES
|
|
423
|
-
(1, 'user'),
|
|
424
|
-
(2, 'settings'),
|
|
425
|
-
(3, 'security')
|
|
426
|
-
ON CONFLICT (role_id) DO NOTHING;
|
|
427
|
-
|
|
428
|
-
CREATE TABLE users (
|
|
429
|
-
user_id SERIAL PRIMARY KEY,
|
|
430
|
-
name TEXT
|
|
431
|
-
);
|
|
432
|
-
|
|
433
|
-
CREATE TABLE communication_channels (
|
|
434
|
-
communication_channel_id SERIAL PRIMARY KEY,
|
|
435
|
-
name TEXT NOT NULL UNIQUE
|
|
436
|
-
);
|
|
437
|
-
|
|
438
|
-
CREATE TABLE user_communication_methods (
|
|
439
|
-
user_communication_method_id SERIAL PRIMARY KEY,
|
|
440
|
-
user_id INT NOT NULL REFERENCES users(user_id),
|
|
441
|
-
communication_channel_id INT NOT NULL REFERENCES communication_channels(communication_channel_id),
|
|
442
|
-
code TEXT NOT NULL,
|
|
443
|
-
UNIQUE (communication_channel_id, code)
|
|
444
|
-
);
|
|
445
|
-
|
|
446
|
-
CREATE TABLE user_roles (
|
|
447
|
-
user_role_id SERIAL PRIMARY KEY,
|
|
448
|
-
user_id INT NOT NULL REFERENCES users(user_id),
|
|
449
|
-
role_id INT NOT NULL REFERENCES roles(role_id),
|
|
450
|
-
tenant_id INT REFERENCES tenants(tenant_id) -- NULL = global / all tenants
|
|
451
|
-
);
|
|
452
|
-
|
|
453
|
-
CREATE TABLE sessions (
|
|
454
|
-
session_id TEXT PRIMARY KEY,
|
|
455
|
-
user_communication_method_id INT NOT NULL REFERENCES user_communication_methods(user_communication_method_id),
|
|
456
|
-
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
457
|
-
expires_at TIMESTAMPTZ NOT NULL,
|
|
458
|
-
ip TEXT,
|
|
459
|
-
city TEXT,
|
|
460
|
-
region TEXT,
|
|
461
|
-
country TEXT,
|
|
462
|
-
latitude TEXT,
|
|
463
|
-
longitude TEXT
|
|
464
|
-
);
|
|
465
|
-
```
|
|
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.
|
|
466
444
|
|
|
467
|
-
|
|
445
|
+
### Soft delete
|
|
468
446
|
|
|
469
|
-
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`.)
|
|
470
448
|
|
|
471
|
-
|
|
472
|
-
|---|---|---|
|
|
473
|
-
| `app.session_id` | `setSessionId` / `setSessionContext` / `withSession` | text |
|
|
474
|
-
| `app.role_name` | `setRoleName` / `setSessionContext` / `withSession` | text |
|
|
475
|
-
| `app.tenant_ids` | `setTenantIds` / `setSessionContext` / `withSession` | comma-separated text (parsed into int[] in policies) |
|
|
476
|
-
| `app.all_tenants` | `setAllTenants` / `setSessionContext` / `withSession` | text `'true'` or `'false'` |
|
|
449
|
+
### Functions the library calls
|
|
477
450
|
|
|
478
|
-
|
|
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 |
|
|
479
455
|
|
|
480
456
|
## Security model
|
|
481
457
|
|
|
482
|
-
- Every parameterized
|
|
483
|
-
- Session
|
|
484
|
-
-
|
|
485
|
-
- `withSession` validates
|
|
486
|
-
-
|
|
487
|
-
-
|
|
488
|
-
- 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.
|
|
489
464
|
|
|
490
465
|
## License
|
|
491
466
|
|