@ultimat3/auth 31.9.0 → 31.11.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/CLAUDE.md +9 -2
- package/README.md +24 -8
- package/package.json +4 -4
- package/src/adapter.ts +18 -0
- package/src/auth.ts +2 -3
- package/src/authorization-server-clients.ts +21 -1
- package/src/authorization-server-errors.ts +16 -0
- package/src/builtin-adapter-rows.ts +114 -0
- package/src/builtin-adapter.ts +32 -92
- package/src/errors.ts +3 -0
- package/src/index.ts +2 -0
- package/src/memory-adapter.ts +8 -0
- package/src/session-user.ts +34 -0
- package/src/session.ts +20 -2
- package/src/tables.ts +20 -5
package/CLAUDE.md
CHANGED
|
@@ -66,6 +66,9 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
|
|
|
66
66
|
`OAuthGrantContext`; never a second userinfo reader. Full rule: `docs/history/auth.md`.
|
|
67
67
|
- **`verifySession` writes at most once per `idleSlideMs`** (default `idleTtlMs / 20`). Never cache
|
|
68
68
|
the USER row — `authenticate` re-reads it every request so a revoked role bites on the next one.
|
|
69
|
+
It reads it in ONE statement with the session (`getSessionWithUser`, optional on the seam,
|
|
70
|
+
`session-user.ts`); the checks are `admitSession`, one copy for both paths. Pinned at 1 by
|
|
71
|
+
`authenticate-statements.test.ts`.
|
|
69
72
|
In `observed`, `null` is an ANSWER (clears the stored value) and `undefined` is silence.
|
|
70
73
|
- A user's `scopes` column reaches `Actor.scopes`.
|
|
71
74
|
- Every revocation takes a `reason` and logs `auth.revocation` before it runs.
|
|
@@ -153,6 +156,9 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
|
|
|
153
156
|
- **`memoryTotpReplayGuard`'s table is bounded and the eviction ORDER is the guarantee.** Full rule: `docs/history/auth.md`.
|
|
154
157
|
- **Passkeys are verified by hand** (`passkey-*.ts`, `cbor.ts`, `cose-key.ts`): UV required, exact
|
|
155
158
|
origin, compare-and-set counter, single-use challenges. †
|
|
159
|
+
- **Every client registration is screened in `storeClient`**, the route's and `registerClient`'s
|
|
160
|
+
alike: a list value that is empty or holds whitespace is `X_AUTH_CLIENT_INVALID` (the Postgres
|
|
161
|
+
store space-joins each list). The route answers RFC 7591 JSON first.
|
|
156
162
|
- **SAML = `samlIdentityProvider`**, no dependency: assertion signature required, one assertion,
|
|
157
163
|
metadata keys only, replay via `auth.totpReplay`, `trustEmail: true` needs `emailDomains`.
|
|
158
164
|
|
|
@@ -163,8 +169,9 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
|
|
|
163
169
|
| `auth.ts` | `defineAuth`, entity schemas, `login`/`register`/`authenticate`/`logout`. Suites: `auth.test.ts` (credential flow), `auth-config.test.ts` (defaults, refusals), `auth-lockout.test.ts` (tenant and address buckets) |
|
|
164
170
|
| `policy-bridge.ts` | the one funnel: identity → `Actor`, all four `ActorKind`s |
|
|
165
171
|
| `session.ts` | two expiries, rotation, revocation, device list, the cookie |
|
|
166
|
-
| `adapter.ts` | the seam; `builtin-adapter.ts` (Postgres) + `memory-adapter.ts` |
|
|
167
|
-
| `
|
|
172
|
+
| `adapter.ts` | the seam; `builtin-adapter.ts` (Postgres, its row readers in `builtin-adapter-rows.ts`) + `memory-adapter.ts` |
|
|
173
|
+
| `session-user.ts` | token → admitted session + its user: one join when the adapter has `getSessionWithUser`, else two reads |
|
|
174
|
+
| `tables.ts` (`./schema`) | every auth table the boot applies — `AUTH_TABLES`, the limiter and TOTP DDL, and `authorization-server-schema.ts` re-exported. `x_auth_lockouts` renders through db's `tableDdl` from `AUTH_LOCKOUTS_STORAGE` (logged, stated). A LEAF: it imports nothing else but `@ultimat3/db` (`schema-subpath.test.ts`), so `FRAMEWORK_SCHEMA` keeps the barrel off `ROLE=migrate` (`MIGRATE_CEILING`). The per-table constants stay module-private (removed from the API in 22.0.0). Also on `.` |
|
|
168
175
|
| `adapter-subpath.ts` | `@ultimat3/auth/adapter`: the `authLimiter`/`totpReplay`/`authServerStore` port types, their installers and resets, and `installKdfGate` |
|
|
169
176
|
| `authorization-server-installed.ts` | the `authServerStore` slot: `authorizationServer()` with no `store` reads it per CALL (never captured: `runtime.ts` may build the server first); empty, Postgres over the ambient pool |
|
|
170
177
|
| `builtin-adapter-violation.ts` | a Postgres unique violation on an auth table → `authUniqueViolation` |
|
package/README.md
CHANGED
|
@@ -666,7 +666,10 @@ redeem it: client, PKCE verifier, `redirect_uri` and `resource` are checked on `
|
|
|
666
666
|
replay revocation. `pollDevice(hash, clientId, at)` stamps only the issuing client's poll. A client
|
|
667
667
|
authenticates only with its registered `token_endpoint_auth_method` (the other is `invalid_client`),
|
|
668
668
|
and gets refresh tokens only if its `grantTypes` list `refresh_token` (else refreshing is
|
|
669
|
-
`unauthorized_client`).
|
|
669
|
+
`unauthorized_client`). `registerClient` — the app's own path — refuses a redirect URI, grant,
|
|
670
|
+
scope or resource that is empty or holds whitespace (`X_AUTH_CLIENT_INVALID`, naming the field):
|
|
671
|
+
the Postgres store keeps each list space-joined, so such a value would read back as a different
|
|
672
|
+
list. Full table and the rule each test holds:
|
|
670
673
|
[wiki Auth](https://github.com/developerz-ai/ultimate/wiki/Auth#authorization-server).
|
|
671
674
|
|
|
672
675
|
| File | Job |
|
|
@@ -729,8 +732,12 @@ would not. Normalisation happens once, above the seam, in `normaliseEmail` (`ema
|
|
|
729
732
|
lowercase, nothing else. Call it before `findUserByEmail`/`createUser` in any login route of your
|
|
730
733
|
own, and key any bucket of your own with it — `accountKey` does.
|
|
731
734
|
|
|
732
|
-
Every member of the seam is required
|
|
733
|
-
refusal
|
|
735
|
+
Every member of the seam is required — an adapter missing one is a compile error, never a runtime
|
|
736
|
+
refusal — except `getSessionWithUser(id)` (`As of 2026-11`): the session and its user in ONE read,
|
|
737
|
+
`{ session, user | null }` or `null`. `authenticate` uses it when present and makes the two reads
|
|
738
|
+
it replaces (`getSession`, then `findUserById`) when not, so an adapter written before it still
|
|
739
|
+
binds. Both shipped adapters carry it; `authAdapterConformance` holds one that does to answering
|
|
740
|
+
exactly what the two reads answer.
|
|
734
741
|
|
|
735
742
|
`x_users` gained two columns in 1.3.0 — `scopes text[]` and `external_id text unique` — plus an
|
|
736
743
|
`org_id` index.
|
|
@@ -745,10 +752,13 @@ should be deleted. They are still not `entity()` declarations, so `x db gen` doe
|
|
|
745
752
|
|
|
746
753
|
**Read the DDL from `@ultimat3/auth/schema`, a leaf — `As of 2026-11-10`.** It exports
|
|
747
754
|
`AUTH_TABLES`, `AUTH_TABLE_NAMES`, `AUTH_SERVER_TABLES`, `SQL_AUTH_SERVER_TABLES`,
|
|
748
|
-
`SQL_AUTH_LIMIT_TABLES` and `
|
|
749
|
-
|
|
750
|
-
from
|
|
751
|
-
|
|
755
|
+
`SQL_AUTH_LIMIT_TABLES`, `SQL_TOTP_REPLAY_TABLE` and `AUTH_LOCKOUTS_STORAGE`, and imports no auth
|
|
756
|
+
runtime: 2 auth modules, not the barrel's 106, plus `@ultimat3/db`, whose `tableDdl` renders
|
|
757
|
+
`x_auth_lockouts` from `AUTH_LOCKOUTS_STORAGE` — `tableStorage('x_auth_lockouts', { unlogged: false })`,
|
|
758
|
+
LOGGED and stated, so every boot's `alter … set logged` converges a hand `set unlogged` and drift
|
|
759
|
+
compares the same value against `pg_class` (`As of 2026-11-11`). `FRAMEWORK_SCHEMA` reads the leaf
|
|
760
|
+
and already loads db, which took `ROLE=migrate` from 977 modules to 873. The `.` barrel exports the
|
|
761
|
+
same seven values, so a caller that also needs `postgresAuthAdapter` or a store keeps one import.
|
|
752
762
|
|
|
753
763
|
```ts
|
|
754
764
|
import { AUTH_TABLE_NAMES, AUTH_TABLES } from '@ultimat3/auth/schema';
|
|
@@ -767,8 +777,14 @@ changed IP or user agent is still written immediately, because that is the row a
|
|
|
767
777
|
an incident review read. The trade is bounded and explicit: idle expiry is now precise to within
|
|
768
778
|
one `idleSlideMs`.
|
|
769
779
|
|
|
780
|
+
**One statement per authenticated request** on `postgresAuthAdapter` (`As of 2026-11-11`, was 2):
|
|
781
|
+
`getSessionWithUser` joins `x_sessions` to `x_users` by the session id, and the secret half and
|
|
782
|
+
both clocks are checked on the row it returns exactly as `verifySession` checks them
|
|
783
|
+
(`admitSession`, one copy). A request that slides the idle window adds the one write above.
|
|
784
|
+
Counted on PGlite by `authenticate-statements.test.ts`.
|
|
785
|
+
|
|
770
786
|
**Revocation is unaffected, and deliberately so.** `authenticate` re-reads the *user* row on every
|
|
771
|
-
request
|
|
787
|
+
request — in that same join — so a revoked role takes effect on the very next one with no token-expiry lag — a better
|
|
772
788
|
property than any claims-in-a-JWT design. Throttling the session write is safe; caching the user
|
|
773
789
|
row would not be, and nothing does.
|
|
774
790
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/auth",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.11.0",
|
|
4
4
|
"description": "Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -50,8 +50,8 @@
|
|
|
50
50
|
"test": "bun test"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@ultimat3/core": "31.
|
|
54
|
-
"@ultimat3/db": "31.
|
|
55
|
-
"@ultimat3/schema": "31.
|
|
53
|
+
"@ultimat3/core": "31.11.0",
|
|
54
|
+
"@ultimat3/db": "31.11.0",
|
|
55
|
+
"@ultimat3/schema": "31.11.0"
|
|
56
56
|
}
|
|
57
57
|
}
|
package/src/adapter.ts
CHANGED
|
@@ -336,4 +336,22 @@ export interface AuthAdapter
|
|
|
336
336
|
* the full adapter rather than on `SessionStore`.
|
|
337
337
|
*/
|
|
338
338
|
deleteSessionsForOrg(orgId: string): Promise<number>;
|
|
339
|
+
/**
|
|
340
|
+
* One session and the user it belongs to, in ONE read — what `authenticate` runs on every
|
|
341
|
+
* request, where `getSession` then `findUserById` is two sequential round trips. `null` when
|
|
342
|
+
* the session is unknown; `user: null` when the session outlived its user. The user row is read
|
|
343
|
+
* fresh by every call, never cached: a disable must refuse the very next request.
|
|
344
|
+
*
|
|
345
|
+
* Optional, unlike the rest of the seam: absent, `authenticate` makes the two reads it replaces,
|
|
346
|
+
* so an adapter written before it still binds. `authAdapterConformance` holds one that has it to
|
|
347
|
+
* answering exactly what those two reads answer. Spans two tables, so it sits here, beside the
|
|
348
|
+
* org sweep, rather than on `SessionStore`.
|
|
349
|
+
*/
|
|
350
|
+
getSessionWithUser?(id: string): Promise<SessionWithUser | null>;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** What `getSessionWithUser` answers for a session that exists. */
|
|
354
|
+
export interface SessionWithUser {
|
|
355
|
+
readonly session: AuthSession;
|
|
356
|
+
readonly user: AuthUser | null;
|
|
339
357
|
}
|
package/src/auth.ts
CHANGED
|
@@ -42,8 +42,8 @@ import {
|
|
|
42
42
|
type SessionPolicy,
|
|
43
43
|
type SessionRuntime,
|
|
44
44
|
sessionCookie,
|
|
45
|
-
verifySession,
|
|
46
45
|
} from './session';
|
|
46
|
+
import { verifySessionWithUser } from './session-user';
|
|
47
47
|
import { sha256Hex } from './tokens';
|
|
48
48
|
|
|
49
49
|
// The projections safe to hand to a client or an MCP tool: no password hash, no TOTP secret,
|
|
@@ -396,8 +396,7 @@ export async function login(auth: Auth, input: LoginInput): Promise<LoginResult>
|
|
|
396
396
|
*/
|
|
397
397
|
export async function authenticate(auth: Auth, token: string | null): Promise<PolicyActor> {
|
|
398
398
|
if (token === null || token.length === 0) return resolveActor({ kind: 'anonymous' });
|
|
399
|
-
const session = await
|
|
400
|
-
const user = await auth.adapter.findUserById(session.userId);
|
|
399
|
+
const { session, user } = await verifySessionWithUser(auth.sessions, auth.adapter, token);
|
|
401
400
|
if (user === null || user.disabledAt !== null) {
|
|
402
401
|
await auth.adapter.deleteSession(session.id);
|
|
403
402
|
throw sessionUnknown();
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { logger, stringField, timingSafeEqual } from '@ultimat3/core';
|
|
7
7
|
import { outbound } from '@ultimat3/core/outbound';
|
|
8
8
|
import type { ResolvedAuthServerConfig } from './authorization-server-config';
|
|
9
|
+
import { type ClientListField, clientInvalid } from './authorization-server-errors';
|
|
9
10
|
import type {
|
|
10
11
|
AuthServerClient,
|
|
11
12
|
AuthServerGrant,
|
|
@@ -153,11 +154,30 @@ export interface RegisteredClient {
|
|
|
153
154
|
readonly clientSecret: string | null;
|
|
154
155
|
}
|
|
155
156
|
|
|
156
|
-
/**
|
|
157
|
+
/**
|
|
158
|
+
* What every registration must pass, whoever registers: each list value is ONE non-empty,
|
|
159
|
+
* whitespace-free string, or the space-joined store reads it back as a different list. The route
|
|
160
|
+
* screens the wire first and answers RFC 7591 errors; an app's `registerClient` meets this one.
|
|
161
|
+
*/
|
|
162
|
+
function screenLists(input: RegisterClientInput): void {
|
|
163
|
+
const lists: readonly (readonly [ClientListField, readonly string[] | undefined])[] = [
|
|
164
|
+
['redirectUris', input.redirectUris],
|
|
165
|
+
['grantTypes', input.grantTypes],
|
|
166
|
+
['scopes', input.scopes],
|
|
167
|
+
['resources', input.resources],
|
|
168
|
+
];
|
|
169
|
+
for (const [field, values] of lists) {
|
|
170
|
+
const bad = values?.find((value) => value === '' || /\s/.test(value));
|
|
171
|
+
if (bad !== undefined) throw clientInvalid(field, bad);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Screened here, before the secret is minted or the row written, for every caller alike. */
|
|
157
176
|
export async function storeClient(
|
|
158
177
|
config: ResolvedAuthServerConfig,
|
|
159
178
|
input: RegisterClientInput,
|
|
160
179
|
): Promise<RegisteredClient> {
|
|
180
|
+
screenLists(input);
|
|
161
181
|
const method = input.authMethod ?? 'none';
|
|
162
182
|
const clientSecret = method === 'none' ? null : randomToken(32);
|
|
163
183
|
const client: AuthServerClient = {
|
|
@@ -21,3 +21,19 @@ export const grantDisabled = (grantType: string): AuthError =>
|
|
|
21
21
|
cause: `a client asked for grant_type ${renderCauseValue(grantType)}, which authorizationServer({ grants }) does not enable`,
|
|
22
22
|
fix: "authorizationServer({ grants: ['authorization_code', 'refresh_token', '<grant>'] }) # with its lifetime — or the client uses an enabled grant",
|
|
23
23
|
});
|
|
24
|
+
|
|
25
|
+
/** The lists of `RegisterClientInput` a value can be refused from. */
|
|
26
|
+
export type ClientListField = 'redirectUris' | 'grantTypes' | 'scopes' | 'resources';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 422: `registerClient` was handed a value the store cannot hold as one value. The Postgres store
|
|
30
|
+
* keeps each list as space-joined text, so whitespace inside a value reads back as two values, and
|
|
31
|
+
* an empty one reads back as none — a redirect or a scope nobody registered.
|
|
32
|
+
*/
|
|
33
|
+
export const clientInvalid = (field: ClientListField, value: string): AuthError =>
|
|
34
|
+
new AuthError({
|
|
35
|
+
code: 'X_AUTH_CLIENT_INVALID',
|
|
36
|
+
cause: `registerClient({ ${field} }) holds ${renderCauseValue(value)}, which is empty or has whitespace inside, and the store keeps each list as space-joined text, so it would read back as a different list`,
|
|
37
|
+
fix: `server.registerClient({ name, ${field}: ['<one value per element, no whitespace>'] }) # split a space-separated string into its values before registering`,
|
|
38
|
+
meta: { field },
|
|
39
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Single responsibility: `x_*` rows as they arrive from the driver — `unknown` values under
|
|
2
|
+
// snake_case names — read into the domain objects `PostgresAuthAdapter` answers with. Typed
|
|
3
|
+
// readers, no `any`: a renamed column reads as its empty value here and fails a round-trip test,
|
|
4
|
+
// never as a silent `undefined`.
|
|
5
|
+
|
|
6
|
+
import type {
|
|
7
|
+
AuthAccount,
|
|
8
|
+
AuthApiKeyRecord,
|
|
9
|
+
AuthSession,
|
|
10
|
+
AuthUser,
|
|
11
|
+
AuthVerification,
|
|
12
|
+
} from './adapter';
|
|
13
|
+
|
|
14
|
+
export type Row = Readonly<Record<string, unknown>>;
|
|
15
|
+
|
|
16
|
+
const textOrNull = (row: Row, key: string): string | null => {
|
|
17
|
+
const value = row[key];
|
|
18
|
+
return typeof value === 'string' ? value : null;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const text = (row: Row, key: string): string => textOrNull(row, key) ?? '';
|
|
22
|
+
|
|
23
|
+
const flag = (row: Row, key: string): boolean => row[key] === true;
|
|
24
|
+
|
|
25
|
+
const list = (row: Row, key: string): readonly string[] => {
|
|
26
|
+
const value = row[key];
|
|
27
|
+
if (!Array.isArray(value)) return [];
|
|
28
|
+
return value.filter((item): item is string => typeof item === 'string');
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const dateOrNull = (row: Row, key: string): Date | null => {
|
|
32
|
+
const value = row[key];
|
|
33
|
+
if (value instanceof Date) return value;
|
|
34
|
+
if (typeof value === 'string' || typeof value === 'number') {
|
|
35
|
+
const parsed = new Date(value);
|
|
36
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const date = (row: Row, key: string): Date => dateOrNull(row, key) ?? new Date(0);
|
|
42
|
+
|
|
43
|
+
export const toUser = (row: Row): AuthUser => ({
|
|
44
|
+
id: text(row, 'id'),
|
|
45
|
+
email: text(row, 'email'),
|
|
46
|
+
emailVerifiedAt: dateOrNull(row, 'email_verified_at'),
|
|
47
|
+
passwordHash: textOrNull(row, 'password_hash'),
|
|
48
|
+
orgId: textOrNull(row, 'org_id'),
|
|
49
|
+
roles: list(row, 'roles'),
|
|
50
|
+
permissions: list(row, 'permissions'),
|
|
51
|
+
scopes: list(row, 'scopes'),
|
|
52
|
+
mfaSecret: textOrNull(row, 'mfa_secret'),
|
|
53
|
+
recoveryCodeHashes: list(row, 'recovery_code_hashes'),
|
|
54
|
+
externalId: textOrNull(row, 'external_id'),
|
|
55
|
+
disabledAt: dateOrNull(row, 'disabled_at'),
|
|
56
|
+
createdAt: date(row, 'created_at'),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
export const toSession = (row: Row): AuthSession => ({
|
|
60
|
+
id: text(row, 'id'),
|
|
61
|
+
userId: text(row, 'user_id'),
|
|
62
|
+
tokenHash: text(row, 'token_hash'),
|
|
63
|
+
createdAt: date(row, 'created_at'),
|
|
64
|
+
absoluteExpiresAt: date(row, 'absolute_expires_at'),
|
|
65
|
+
lastSeenAt: date(row, 'last_seen_at'),
|
|
66
|
+
ip: textOrNull(row, 'ip'),
|
|
67
|
+
userAgent: textOrNull(row, 'user_agent'),
|
|
68
|
+
mfaSatisfied: flag(row, 'mfa_satisfied'),
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
export const toAccount = (row: Row): AuthAccount => ({
|
|
72
|
+
id: text(row, 'id'),
|
|
73
|
+
userId: text(row, 'user_id'),
|
|
74
|
+
provider: text(row, 'provider'),
|
|
75
|
+
providerAccountId: text(row, 'provider_account_id'),
|
|
76
|
+
accessToken: textOrNull(row, 'access_token'),
|
|
77
|
+
refreshToken: textOrNull(row, 'refresh_token'),
|
|
78
|
+
expiresAt: dateOrNull(row, 'expires_at'),
|
|
79
|
+
createdAt: date(row, 'created_at'),
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
export const toVerification = (row: Row): AuthVerification => ({
|
|
83
|
+
id: text(row, 'id'),
|
|
84
|
+
purpose: text(row, 'purpose'),
|
|
85
|
+
identifier: text(row, 'identifier'),
|
|
86
|
+
tokenHash: text(row, 'token_hash'),
|
|
87
|
+
expiresAt: date(row, 'expires_at'),
|
|
88
|
+
consumedAt: dateOrNull(row, 'consumed_at'),
|
|
89
|
+
createdAt: date(row, 'created_at'),
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
export const toApiKey = (row: Row): AuthApiKeyRecord => ({
|
|
93
|
+
id: text(row, 'id'),
|
|
94
|
+
prefix: text(row, 'prefix'),
|
|
95
|
+
keyHash: text(row, 'key_hash'),
|
|
96
|
+
userId: textOrNull(row, 'user_id'),
|
|
97
|
+
orgId: textOrNull(row, 'org_id'),
|
|
98
|
+
scopes: list(row, 'scopes'),
|
|
99
|
+
lastUsedAt: dateOrNull(row, 'last_used_at'),
|
|
100
|
+
expiresAt: dateOrNull(row, 'expires_at'),
|
|
101
|
+
revokedAt: dateOrNull(row, 'revoked_at'),
|
|
102
|
+
createdAt: date(row, 'created_at'),
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The columns of `row` whose names start with `prefix`, under their bare names: one side of a join
|
|
107
|
+
* whose two tables share column names (`id`, `created_at`), aliased apart in the select list.
|
|
108
|
+
*/
|
|
109
|
+
export const unprefixed = (row: Row, prefix: string): Row =>
|
|
110
|
+
Object.fromEntries(
|
|
111
|
+
Object.entries(row)
|
|
112
|
+
.filter(([key]) => key.startsWith(prefix))
|
|
113
|
+
.map(([key, value]) => [key.slice(prefix.length), value]),
|
|
114
|
+
);
|
package/src/builtin-adapter.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Single responsibility: the one blessed `AuthAdapter`, backed by Postgres through
|
|
2
2
|
// `@ultimat3/db`. The `DbClient` is injected (defaulting to `db()`) so tests and the CLI can
|
|
3
3
|
// drive it without a database. Rows arrive as `unknown` and are read through the small typed
|
|
4
|
-
// readers
|
|
4
|
+
// readers in `builtin-adapter-rows.ts` — no `any`, and a renamed column fails a round trip.
|
|
5
5
|
|
|
6
6
|
import { type Clock, systemClock } from '@ultimat3/core';
|
|
7
7
|
import { type DbClient, db, sql } from '@ultimat3/db';
|
|
@@ -15,105 +15,25 @@ import type {
|
|
|
15
15
|
CreateUserInput,
|
|
16
16
|
PasskeyStore,
|
|
17
17
|
SessionPatch,
|
|
18
|
+
SessionWithUser,
|
|
18
19
|
StoredMfaSecret,
|
|
19
20
|
UserPatch,
|
|
20
21
|
UserQuery,
|
|
21
22
|
} from './adapter';
|
|
23
|
+
import {
|
|
24
|
+
type Row,
|
|
25
|
+
text,
|
|
26
|
+
toAccount,
|
|
27
|
+
toApiKey,
|
|
28
|
+
toSession,
|
|
29
|
+
toUser,
|
|
30
|
+
toVerification,
|
|
31
|
+
unprefixed,
|
|
32
|
+
} from './builtin-adapter-rows';
|
|
22
33
|
import { usersUniqueViolation } from './builtin-adapter-violation';
|
|
23
34
|
import { authWriteFailed } from './errors';
|
|
24
35
|
import { postgresPasskeyStore } from './passkey-postgres';
|
|
25
36
|
|
|
26
|
-
type Row = Readonly<Record<string, unknown>>;
|
|
27
|
-
|
|
28
|
-
const textOrNull = (row: Row, key: string): string | null => {
|
|
29
|
-
const value = row[key];
|
|
30
|
-
return typeof value === 'string' ? value : null;
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
const text = (row: Row, key: string): string => textOrNull(row, key) ?? '';
|
|
34
|
-
|
|
35
|
-
const flag = (row: Row, key: string): boolean => row[key] === true;
|
|
36
|
-
|
|
37
|
-
const list = (row: Row, key: string): readonly string[] => {
|
|
38
|
-
const value = row[key];
|
|
39
|
-
if (!Array.isArray(value)) return [];
|
|
40
|
-
return value.filter((item): item is string => typeof item === 'string');
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
const dateOrNull = (row: Row, key: string): Date | null => {
|
|
44
|
-
const value = row[key];
|
|
45
|
-
if (value instanceof Date) return value;
|
|
46
|
-
if (typeof value === 'string' || typeof value === 'number') {
|
|
47
|
-
const parsed = new Date(value);
|
|
48
|
-
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
49
|
-
}
|
|
50
|
-
return null;
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
const date = (row: Row, key: string): Date => dateOrNull(row, key) ?? new Date(0);
|
|
54
|
-
|
|
55
|
-
const toUser = (row: Row): AuthUser => ({
|
|
56
|
-
id: text(row, 'id'),
|
|
57
|
-
email: text(row, 'email'),
|
|
58
|
-
emailVerifiedAt: dateOrNull(row, 'email_verified_at'),
|
|
59
|
-
passwordHash: textOrNull(row, 'password_hash'),
|
|
60
|
-
orgId: textOrNull(row, 'org_id'),
|
|
61
|
-
roles: list(row, 'roles'),
|
|
62
|
-
permissions: list(row, 'permissions'),
|
|
63
|
-
scopes: list(row, 'scopes'),
|
|
64
|
-
mfaSecret: textOrNull(row, 'mfa_secret'),
|
|
65
|
-
recoveryCodeHashes: list(row, 'recovery_code_hashes'),
|
|
66
|
-
externalId: textOrNull(row, 'external_id'),
|
|
67
|
-
disabledAt: dateOrNull(row, 'disabled_at'),
|
|
68
|
-
createdAt: date(row, 'created_at'),
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
const toSession = (row: Row): AuthSession => ({
|
|
72
|
-
id: text(row, 'id'),
|
|
73
|
-
userId: text(row, 'user_id'),
|
|
74
|
-
tokenHash: text(row, 'token_hash'),
|
|
75
|
-
createdAt: date(row, 'created_at'),
|
|
76
|
-
absoluteExpiresAt: date(row, 'absolute_expires_at'),
|
|
77
|
-
lastSeenAt: date(row, 'last_seen_at'),
|
|
78
|
-
ip: textOrNull(row, 'ip'),
|
|
79
|
-
userAgent: textOrNull(row, 'user_agent'),
|
|
80
|
-
mfaSatisfied: flag(row, 'mfa_satisfied'),
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
const toAccount = (row: Row): AuthAccount => ({
|
|
84
|
-
id: text(row, 'id'),
|
|
85
|
-
userId: text(row, 'user_id'),
|
|
86
|
-
provider: text(row, 'provider'),
|
|
87
|
-
providerAccountId: text(row, 'provider_account_id'),
|
|
88
|
-
accessToken: textOrNull(row, 'access_token'),
|
|
89
|
-
refreshToken: textOrNull(row, 'refresh_token'),
|
|
90
|
-
expiresAt: dateOrNull(row, 'expires_at'),
|
|
91
|
-
createdAt: date(row, 'created_at'),
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
const toVerification = (row: Row): AuthVerification => ({
|
|
95
|
-
id: text(row, 'id'),
|
|
96
|
-
purpose: text(row, 'purpose'),
|
|
97
|
-
identifier: text(row, 'identifier'),
|
|
98
|
-
tokenHash: text(row, 'token_hash'),
|
|
99
|
-
expiresAt: date(row, 'expires_at'),
|
|
100
|
-
consumedAt: dateOrNull(row, 'consumed_at'),
|
|
101
|
-
createdAt: date(row, 'created_at'),
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
const toApiKey = (row: Row): AuthApiKeyRecord => ({
|
|
105
|
-
id: text(row, 'id'),
|
|
106
|
-
prefix: text(row, 'prefix'),
|
|
107
|
-
keyHash: text(row, 'key_hash'),
|
|
108
|
-
userId: textOrNull(row, 'user_id'),
|
|
109
|
-
orgId: textOrNull(row, 'org_id'),
|
|
110
|
-
scopes: list(row, 'scopes'),
|
|
111
|
-
lastUsedAt: dateOrNull(row, 'last_used_at'),
|
|
112
|
-
expiresAt: dateOrNull(row, 'expires_at'),
|
|
113
|
-
revokedAt: dateOrNull(row, 'revoked_at'),
|
|
114
|
-
createdAt: date(row, 'created_at'),
|
|
115
|
-
});
|
|
116
|
-
|
|
117
37
|
/**
|
|
118
38
|
* A patch column is written as `case when <set> then <value> else <column> end` rather than
|
|
119
39
|
* assembled into dynamic SQL: `null` stays a meaningful value ("clear this field") and the
|
|
@@ -333,6 +253,26 @@ export class PostgresAuthAdapter implements AuthAdapter {
|
|
|
333
253
|
where user_id in (select id from x_users where org_id = ${orgId})`);
|
|
334
254
|
}
|
|
335
255
|
|
|
256
|
+
/**
|
|
257
|
+
* The session's columns aliased `s_*`, because both tables have an `id` and a `created_at`; the
|
|
258
|
+
* user's arrive under their own names. A left join, so a session that outlived its user still
|
|
259
|
+
* comes back — `authenticate` deletes it, exactly as it does after the two-read path.
|
|
260
|
+
*/
|
|
261
|
+
async getSessionWithUser(id: string): Promise<SessionWithUser | null> {
|
|
262
|
+
const row = await this.#db.one<Row>(sql`
|
|
263
|
+
select s.id as s_id, s.user_id as s_user_id, s.token_hash as s_token_hash,
|
|
264
|
+
s.created_at as s_created_at, s.absolute_expires_at as s_absolute_expires_at,
|
|
265
|
+
s.last_seen_at as s_last_seen_at, s.ip as s_ip, s.user_agent as s_user_agent,
|
|
266
|
+
s.mfa_satisfied as s_mfa_satisfied, u.*
|
|
267
|
+
from x_sessions s left join x_users u on u.id = s.user_id
|
|
268
|
+
where s.id = ${id}`);
|
|
269
|
+
if (row === null) return null;
|
|
270
|
+
return {
|
|
271
|
+
session: toSession(unprefixed(row, 's_')),
|
|
272
|
+
user: row['id'] === null || row['id'] === undefined ? null : toUser(row),
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
336
276
|
async deleteSessionsCreatedBefore(before: Date): Promise<number> {
|
|
337
277
|
return await this.#db.execute(sql`delete from x_sessions where created_at < ${before}`);
|
|
338
278
|
}
|
package/src/errors.ts
CHANGED
|
@@ -42,6 +42,7 @@ export const AUTH_OWNED_ERROR_CODES = [
|
|
|
42
42
|
'X_SAML_RESPONSE_INVALID',
|
|
43
43
|
'X_SAML_METADATA_INVALID',
|
|
44
44
|
'X_IDENTITY_PROVIDER_UNKNOWN',
|
|
45
|
+
'X_AUTH_CLIENT_INVALID',
|
|
45
46
|
] as const;
|
|
46
47
|
|
|
47
48
|
/**
|
|
@@ -107,6 +108,8 @@ export const AUTH_ERROR_TITLES: Readonly<Record<AuthOwnedErrorCode, string>> = {
|
|
|
107
108
|
X_SAML_METADATA_INVALID:
|
|
108
109
|
'saml IdP metadata has no entity id, HTTP-Redirect sign-on endpoint or signing certificate',
|
|
109
110
|
X_IDENTITY_PROVIDER_UNKNOWN: 'the URL named an identity provider the sso routes were not given',
|
|
111
|
+
X_AUTH_CLIENT_INVALID:
|
|
112
|
+
'an oauth client was registered with a list value the store cannot hold as one value',
|
|
110
113
|
};
|
|
111
114
|
|
|
112
115
|
// Registered unconditionally, in one call: a second package claiming a code auth owns has to fail
|
package/src/index.ts
CHANGED
|
@@ -19,6 +19,7 @@ export type {
|
|
|
19
19
|
PasskeyStore,
|
|
20
20
|
SessionPatch,
|
|
21
21
|
SessionStore,
|
|
22
|
+
SessionWithUser,
|
|
22
23
|
StoredMfaSecret,
|
|
23
24
|
UserPatch,
|
|
24
25
|
UserStore,
|
|
@@ -417,6 +418,7 @@ export { authSubjectTarget } from './subject-target';
|
|
|
417
418
|
|
|
418
419
|
/** Also `@ultimat3/auth/schema`, the leaf a schema reader imports instead of this barrel. */
|
|
419
420
|
export {
|
|
421
|
+
AUTH_LOCKOUTS_STORAGE,
|
|
420
422
|
AUTH_SERVER_TABLES,
|
|
421
423
|
AUTH_TABLE_NAMES,
|
|
422
424
|
AUTH_TABLES,
|
package/src/memory-adapter.ts
CHANGED
|
@@ -13,6 +13,7 @@ import type {
|
|
|
13
13
|
CreateUserInput,
|
|
14
14
|
PasskeyStore,
|
|
15
15
|
SessionPatch,
|
|
16
|
+
SessionWithUser,
|
|
16
17
|
StoredMfaSecret,
|
|
17
18
|
UserPatch,
|
|
18
19
|
UserQuery,
|
|
@@ -258,6 +259,13 @@ export class MemoryAuthAdapter implements AuthAdapter {
|
|
|
258
259
|
}
|
|
259
260
|
|
|
260
261
|
/** Joins through the user map, which is what the Postgres adapter's subselect does. */
|
|
262
|
+
async getSessionWithUser(id: string): Promise<SessionWithUser | null> {
|
|
263
|
+
const session = this.#sessions.get(id);
|
|
264
|
+
return session === undefined
|
|
265
|
+
? null
|
|
266
|
+
: { session, user: this.#users.get(session.userId) ?? null };
|
|
267
|
+
}
|
|
268
|
+
|
|
261
269
|
async deleteSessionsForOrg(orgId: string): Promise<number> {
|
|
262
270
|
const members = new Set(
|
|
263
271
|
[...this.#users.values()].filter((user) => user.orgId === orgId).map((user) => user.id),
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Single responsibility: a session token to its live session AND its user, in the fewest reads the
|
|
2
|
+
// adapter allows — one join when it has `getSessionWithUser`, else `verifySession` then
|
|
3
|
+
// `findUserById`. Admission is `admitSession` either way; whether the user may act is the caller's.
|
|
4
|
+
|
|
5
|
+
import type { AuthAdapter, AuthSession, AuthUser } from './adapter';
|
|
6
|
+
import { sessionUnknown } from './errors';
|
|
7
|
+
import { admitSession, parseSessionToken, type SessionRuntime, verifySession } from './session';
|
|
8
|
+
|
|
9
|
+
export interface VerifiedSession {
|
|
10
|
+
readonly session: AuthSession;
|
|
11
|
+
/** `null` when the session outlived its user — the caller deletes the session and refuses. */
|
|
12
|
+
readonly user: AuthUser | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The user is read only once the session is admitted on the two-read path, and on the join it is
|
|
17
|
+
* read in the same statement but handed back only after admission: a forged or expired token
|
|
18
|
+
* never yields a user either way.
|
|
19
|
+
*/
|
|
20
|
+
export async function verifySessionWithUser(
|
|
21
|
+
runtime: SessionRuntime,
|
|
22
|
+
adapter: AuthAdapter,
|
|
23
|
+
token: string,
|
|
24
|
+
): Promise<VerifiedSession> {
|
|
25
|
+
if (adapter.getSessionWithUser === undefined) {
|
|
26
|
+
const session = await verifySession(runtime, token);
|
|
27
|
+
return { session, user: await adapter.findUserById(session.userId) };
|
|
28
|
+
}
|
|
29
|
+
const parsed = parseSessionToken(token);
|
|
30
|
+
if (parsed === null) throw sessionUnknown();
|
|
31
|
+
const joined = await adapter.getSessionWithUser(parsed.id);
|
|
32
|
+
const session = await admitSession(runtime, parsed.secret, joined?.session ?? null);
|
|
33
|
+
return { session, user: joined?.user ?? null };
|
|
34
|
+
}
|
package/src/session.ts
CHANGED
|
@@ -182,9 +182,27 @@ export async function verifySession(
|
|
|
182
182
|
): Promise<AuthSession> {
|
|
183
183
|
const parsed = parseSessionToken(token);
|
|
184
184
|
if (parsed === null) throw sessionUnknown();
|
|
185
|
-
|
|
185
|
+
return await admitSession(
|
|
186
|
+
runtime,
|
|
187
|
+
parsed.secret,
|
|
188
|
+
await runtime.store.getSession(parsed.id),
|
|
189
|
+
observed,
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* `verifySession` on a row already read — by `getSession`, or by the join `authenticate` prefers
|
|
195
|
+
* (`session-user.ts`). One copy of the checks, so the two reads cannot admit different sessions:
|
|
196
|
+
* the secret half, both clocks, then the slide.
|
|
197
|
+
*/
|
|
198
|
+
export async function admitSession(
|
|
199
|
+
runtime: SessionRuntime,
|
|
200
|
+
secret: string,
|
|
201
|
+
session: AuthSession | null,
|
|
202
|
+
observed?: { readonly ip?: string | null | undefined; readonly userAgent?: string | null },
|
|
203
|
+
): Promise<AuthSession> {
|
|
186
204
|
if (session === null) throw sessionUnknown();
|
|
187
|
-
if (!timingSafeEqual(sha256Hex(
|
|
205
|
+
if (!timingSafeEqual(sha256Hex(secret), session.tokenHash)) throw sessionUnknown();
|
|
188
206
|
|
|
189
207
|
const now = runtime.clock.now();
|
|
190
208
|
const expiry = sessionExpiry(session, runtime.policy, now);
|
package/src/tables.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Single responsibility: every auth table the boot applies, and nothing else — shipped as the LEAF
|
|
2
2
|
// `@ultimat3/auth/schema`, so `@ultimat3/cli`'s `FRAMEWORK_SCHEMA` reads the DDL in every role
|
|
3
|
-
// (`ROLE=migrate` first) without the barrel. Imports
|
|
4
|
-
//
|
|
3
|
+
// (`ROLE=migrate` first) without the barrel. Imports its sibling leaf and db's `tableDdl`, nothing
|
|
4
|
+
// more (`schema-subpath.test.ts`). Strings: what auth stores is verifiable by reading, never trusting.
|
|
5
5
|
//
|
|
6
6
|
// `AUTH_TABLES` is the DDL `PostgresAuthAdapter` expects, upgrades of an older table included.
|
|
7
7
|
// There is nothing to paste into a migration: the per-table exports and `X_USERS_MIGRATION_1_3`
|
|
@@ -29,6 +29,8 @@
|
|
|
29
29
|
// through its own `linkAccount` has somewhere to put them, and so an existing deployment needs
|
|
30
30
|
// no migration to stop.
|
|
31
31
|
|
|
32
|
+
import { type TableStorage, tableDdl, tableStorage } from '@ultimat3/db';
|
|
33
|
+
|
|
32
34
|
const X_USERS_TABLE = `create table if not exists x_users (
|
|
33
35
|
id uuid primary key,
|
|
34
36
|
email text not null unique,
|
|
@@ -180,6 +182,17 @@ export const AUTH_TABLE_NAMES: readonly string[] = Object.freeze([
|
|
|
180
182
|
'x_passkey_evidence',
|
|
181
183
|
]);
|
|
182
184
|
|
|
185
|
+
/**
|
|
186
|
+
* How `x_auth_lockouts` is STORED: LOGGED, stated rather than left to the default, so drift
|
|
187
|
+
* catches a hand `set unlogged` and every boot's `alter … set logged` converges one. A crash must
|
|
188
|
+
* never forget a lockout — that forgetting IS the spray it exists to stop (`x_rate_limit` may be
|
|
189
|
+
* unlogged: a refilled bucket is one free burst, never a bypass). `@ultimat3/cli`'s framework
|
|
190
|
+
* schema compares this same value against `pg_class`.
|
|
191
|
+
*/
|
|
192
|
+
export const AUTH_LOCKOUTS_STORAGE: TableStorage = tableStorage('x_auth_lockouts', {
|
|
193
|
+
unlogged: false,
|
|
194
|
+
});
|
|
195
|
+
|
|
183
196
|
/**
|
|
184
197
|
* `postgresAuthLimiter`'s table (`rate-limit-postgres.ts`).
|
|
185
198
|
*
|
|
@@ -198,12 +211,14 @@ export const AUTH_TABLE_NAMES: readonly string[] = Object.freeze([
|
|
|
198
211
|
* and writes this table as it always did, so a lockout holds on both sides of a rolling deploy.
|
|
199
212
|
*/
|
|
200
213
|
export const SQL_AUTH_LIMIT_TABLES = `
|
|
201
|
-
|
|
214
|
+
${tableDdl(
|
|
215
|
+
AUTH_LOCKOUTS_STORAGE,
|
|
216
|
+
`
|
|
202
217
|
key text primary key,
|
|
203
218
|
locked_until_ms bigint not null,
|
|
204
219
|
attempts_ms bigint[] not null default '{}',
|
|
205
|
-
admitted boolean not null default true
|
|
206
|
-
)
|
|
220
|
+
admitted boolean not null default true`,
|
|
221
|
+
)}
|
|
207
222
|
|
|
208
223
|
alter table x_auth_lockouts add column if not exists attempts_ms bigint[] not null default '{}';
|
|
209
224
|
alter table x_auth_lockouts add column if not exists admitted boolean not null default true;
|