@okeav/idp-pg 0.0.0-stage → 0.1.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/.env.example +159 -0
- package/CHANGELOG.md +58 -0
- package/LICENSE +21 -0
- package/README.md +275 -3
- package/package.json +78 -6
- package/src/cache/cache-adapter.js +22 -0
- package/src/cache/index.js +68 -0
- package/src/cache/memory.adapter.js +85 -0
- package/src/cache/redis.adapter.js +96 -0
- package/src/config/console-logger.js +10 -0
- package/src/config/constants.js +178 -0
- package/src/config/defaults.js +100 -0
- package/src/config/from-env.js +150 -0
- package/src/config/init.js +286 -0
- package/src/config/state.js +22 -0
- package/src/errors/error-codes.js +97 -0
- package/src/errors/idp-error.js +75 -0
- package/src/hooks/index.js +85 -0
- package/src/index.js +167 -0
- package/src/magic-link/controller.js +129 -0
- package/src/magic-link/schemas.js +12 -0
- package/src/mfa/attempt-guard.js +48 -0
- package/src/mfa/controller.js +309 -0
- package/src/mfa/factor-store.js +37 -0
- package/src/mfa/memory-attempt-counter.js +58 -0
- package/src/mfa/schemas.js +11 -0
- package/src/mfa/secret-cipher.js +133 -0
- package/src/mfa/secrets.js +156 -0
- package/src/middleware/auth-context.middleware.js +149 -0
- package/src/middleware/cookie-parser.js +4 -0
- package/src/middleware/csrf.js +48 -0
- package/src/middleware/require-recent-auth.middleware.js +30 -0
- package/src/middleware/require-service-caller.middleware.js +32 -0
- package/src/middleware/service-context.middleware.js +70 -0
- package/src/middleware/validate-body.js +16 -0
- package/src/middleware/validate-query.js +22 -0
- package/src/oauth2/authorize.controller.js +233 -0
- package/src/oauth2/client-auth.js +77 -0
- package/src/oauth2/client.controller.js +122 -0
- package/src/oauth2/consent.controller.js +63 -0
- package/src/oauth2/login-challenge.js +50 -0
- package/src/oauth2/redirect-uri.js +25 -0
- package/src/oauth2/schemas.js +103 -0
- package/src/oauth2/token.controller.js +370 -0
- package/src/oidc/discovery.controller.js +36 -0
- package/src/oidc/end-session.controller.js +137 -0
- package/src/oidc/userinfo.controller.js +49 -0
- package/src/password-auth/controllers.js +927 -0
- package/src/password-auth/schemas.js +76 -0
- package/src/rate-limit/enforce.js +35 -0
- package/src/rate-limit/index.js +48 -0
- package/src/rate-limit/keys.js +36 -0
- package/src/rate-limit/memory.adapter.js +75 -0
- package/src/rate-limit/noop.adapter.js +14 -0
- package/src/rate-limit/rate-limiter.js +18 -0
- package/src/rate-limit/redis.adapter.js +71 -0
- package/src/routes/build-router.js +238 -0
- package/src/security/attempt-budget.js +47 -0
- package/src/security/clock-skew.js +63 -0
- package/src/service-mesh/key-status.js +22 -0
- package/src/service-mesh/local-key-lookup.js +12 -0
- package/src/service-mesh/remote-jwks-key-lookup.js +74 -0
- package/src/service-mesh/s2s-bootstrap.middleware.js +41 -0
- package/src/service-mesh/service-identity.client.js +89 -0
- package/src/service-mesh/service-key.controller.js +170 -0
- package/src/service-mesh/verify-service-token.js +75 -0
- package/src/signing/jwks.controller.js +30 -0
- package/src/signing/jwks.js +24 -0
- package/src/signing/key-registry.js +97 -0
- package/src/signing/token.service.js +336 -0
- package/src/sso/binding.js +30 -0
- package/src/sso/callback.controller.js +186 -0
- package/src/sso/initiate.controller.js +92 -0
- package/src/sso/providers.js +237 -0
- package/src/sso/schemas.js +7 -0
- package/src/storage/interfaces.js +178 -0
- package/src/storage/postgres/db.js +68 -0
- package/src/storage/postgres/index.js +160 -0
- package/src/storage/postgres/migrations/run-migrations.js +122 -0
- package/src/storage/postgres/migrations/sql/0001_init.sql +253 -0
- package/src/storage/postgres/repositories/attempt-counter.repository.js +65 -0
- package/src/storage/postgres/repositories/authorization-code.repository.js +104 -0
- package/src/storage/postgres/repositories/consent.repository.js +68 -0
- package/src/storage/postgres/repositories/credential.repository.js +75 -0
- package/src/storage/postgres/repositories/oauth-client.repository.js +122 -0
- package/src/storage/postgres/repositories/service-key.repository.js +76 -0
- package/src/storage/postgres/repositories/session.repository.js +290 -0
- package/src/storage/postgres/repositories/user.repository.js +328 -0
- package/src/storage/postgres/repositories/verification-token.repository.js +138 -0
- package/src/storage/postgres/run.js +22 -0
- package/src/utils/account-status.js +26 -0
- package/src/utils/cookies.js +129 -0
- package/src/utils/device-fingerprint.js +58 -0
- package/src/utils/email-hash.js +23 -0
- package/src/utils/oauth-client-credentials.js +51 -0
- package/src/utils/password.js +40 -0
- package/src/utils/safe-equal.js +12 -0
- package/src/utils/session-family.js +158 -0
- package/src/utils/session-kind.js +15 -0
- package/src/utils/url.js +17 -0
- package/src/webauthn/authentication.controller.js +126 -0
- package/src/webauthn/challenge-store.js +17 -0
- package/src/webauthn/config.js +25 -0
- package/src/webauthn/mfa.controller.js +119 -0
- package/src/webauthn/registration.controller.js +128 -0
- package/src/webauthn/schemas.js +41 -0
- package/src/webauthn/shared.js +63 -0
- package/src/webhooks/dispatcher.js +135 -0
- package/src/webhooks/sign.js +55 -0
- package/src/webhooks/wrap-hooks.js +51 -0
- package/types/index.d.ts +777 -0
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { newId, isUuid, withTransaction, columnFor, deleteInBatches } from '../db.js';
|
|
2
|
+
|
|
3
|
+
const COLUMNS = {
|
|
4
|
+
user: 'user_id',
|
|
5
|
+
tokenHash: 'token_hash',
|
|
6
|
+
expiresAt: 'expires_at',
|
|
7
|
+
kid: 'kid',
|
|
8
|
+
jti: 'jti',
|
|
9
|
+
revokedAt: 'revoked_at',
|
|
10
|
+
revokeReason: 'revoke_reason',
|
|
11
|
+
familyRevokedAt: 'family_revoked_at',
|
|
12
|
+
deviceInfo: 'device_info',
|
|
13
|
+
deviceFingerprint: 'device_fingerprint',
|
|
14
|
+
ipAddress: 'ip_address',
|
|
15
|
+
kind: 'kind',
|
|
16
|
+
authTime: 'auth_time',
|
|
17
|
+
familyId: 'family_id',
|
|
18
|
+
familyCreatedAt: 'family_created_at',
|
|
19
|
+
sessionEpoch: 'session_epoch',
|
|
20
|
+
claims: 'claims',
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** @implements {import('../../interfaces.js').SessionRepository} */
|
|
24
|
+
export class PgSessionRepository {
|
|
25
|
+
constructor(pool) {
|
|
26
|
+
this.pool = pool;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async createSession(input, db = this.pool) {
|
|
30
|
+
const columns = ['id'];
|
|
31
|
+
const values = [newId()];
|
|
32
|
+
for (const [key, value] of Object.entries(input)) {
|
|
33
|
+
if (value === undefined) continue;
|
|
34
|
+
columns.push(columnFor(COLUMNS, key, 'idp_sessions'));
|
|
35
|
+
values.push(key === 'claims' ? JSON.stringify(value ?? {}) : value);
|
|
36
|
+
}
|
|
37
|
+
const { rows: [row] } = await db.query(
|
|
38
|
+
`INSERT INTO idp_sessions (${columns.join(', ')}) VALUES (${columns.map((_, i) => `$${i + 1}`).join(', ')}) RETURNING *`,
|
|
39
|
+
values,
|
|
40
|
+
);
|
|
41
|
+
return mapSession(row);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The composite write behind every login: access-token audit row, session row and the user's
|
|
46
|
+
* lastLoginAt — one transaction.
|
|
47
|
+
*/
|
|
48
|
+
async createSessionForLogin({ accessTokenAudit, session, userId, lastLoginAt }) {
|
|
49
|
+
return withTransaction(this.pool, async (client) => {
|
|
50
|
+
if (accessTokenAudit) await insertAudit(client, accessTokenAudit);
|
|
51
|
+
const created = await this.createSession(session, client);
|
|
52
|
+
if (isUuid(userId)) {
|
|
53
|
+
await client.query(
|
|
54
|
+
'UPDATE idp_users SET last_login_at = $2, failed_login_attempts = 0, lock_until = NULL, updated_at = now() WHERE id = $1',
|
|
55
|
+
[userId, lastLoginAt ?? new Date()],
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
return created;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async findByRefreshTokenHash(hash) {
|
|
63
|
+
if (!hash) return null;
|
|
64
|
+
const { rows: [row] } = await this.pool.query('SELECT * FROM idp_sessions WHERE token_hash = $1', [hash]);
|
|
65
|
+
return mapSession(row);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The session an access token belongs to (its jti) — the per-request check; an indexed read. */
|
|
69
|
+
async findByJti(jti) {
|
|
70
|
+
if (!jti) return null;
|
|
71
|
+
const { rows: [row] } = await this.pool.query('SELECT * FROM idp_sessions WHERE jti = $1 ORDER BY created_at DESC LIMIT 1', [jti]);
|
|
72
|
+
return mapSession(row);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Atomic consume: of concurrent callers presenting one refresh token, exactly one gets the row (as it
|
|
77
|
+
* was BEFORE revocation). `revoked_at` is the database's clock — rotatedWithin measures with it too.
|
|
78
|
+
*/
|
|
79
|
+
async revokeByRefreshTokenHash(hash, { onlyIfActive = true, reason = 'revoked' } = {}) {
|
|
80
|
+
if (!hash) return null;
|
|
81
|
+
const { rows: [row] } = await this.pool.query(
|
|
82
|
+
`WITH target AS (
|
|
83
|
+
SELECT * FROM idp_sessions
|
|
84
|
+
WHERE token_hash = $1 AND revoked_at IS NULL AND ($3::boolean IS FALSE OR expires_at > $4)
|
|
85
|
+
FOR UPDATE
|
|
86
|
+
)
|
|
87
|
+
UPDATE idp_sessions s SET revoked_at = now(), revoke_reason = $2, updated_at = now()
|
|
88
|
+
FROM target WHERE s.id = target.id AND s.revoked_at IS NULL
|
|
89
|
+
RETURNING target.*`,
|
|
90
|
+
[hash, reason, onlyIfActive, new Date()],
|
|
91
|
+
);
|
|
92
|
+
return mapSession(row);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Whether this refresh token was rotated less than `seconds` ago — by the database's clock alone. */
|
|
96
|
+
async rotatedWithin(hash, seconds) {
|
|
97
|
+
if (!hash) return false;
|
|
98
|
+
const { rowCount } = await this.pool.query(
|
|
99
|
+
`SELECT 1 FROM idp_sessions
|
|
100
|
+
WHERE token_hash = $1 AND revoke_reason = 'rotated' AND revoked_at > now() - make_interval(secs => $2)`,
|
|
101
|
+
[hash, seconds],
|
|
102
|
+
);
|
|
103
|
+
return rowCount > 0;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Raises the recorded epoch of every row of the family to at least `epoch`. */
|
|
107
|
+
async raiseFamilyEpoch(familyId, epoch) {
|
|
108
|
+
if (!familyId) return;
|
|
109
|
+
await this.pool.query(
|
|
110
|
+
'UPDATE idp_sessions SET session_epoch = $2, updated_at = now() WHERE family_id = $1 AND session_epoch < $2',
|
|
111
|
+
[familyId, epoch],
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Revokes every live row of a family, and tombstones every row (live or not) so a refresh in flight
|
|
117
|
+
* finds out (isFamilyRevoked). Two statements, in this order, each committed on its own:
|
|
118
|
+
* 1. the tombstone — from its commit on, a refresh that inserts a successor and then checks
|
|
119
|
+
* isFamilyRevoked sees it;
|
|
120
|
+
* 2. the revocation, in a NEW snapshot — so it also catches a successor whose refresh checked
|
|
121
|
+
* before the tombstone was committed.
|
|
122
|
+
* (One statement can't do this: it sees only rows that existed when it started, and its tombstone
|
|
123
|
+
* is invisible until it commits — a successor inserted and checked meanwhile would survive.)
|
|
124
|
+
* Resolves the jtis revoked by this call.
|
|
125
|
+
*/
|
|
126
|
+
async revokeFamily(familyId, { reason = 'family_revoked' } = {}) {
|
|
127
|
+
if (!familyId) return { revokedCount: 0, jtis: [] };
|
|
128
|
+
const now = new Date();
|
|
129
|
+
await this.pool.query(
|
|
130
|
+
'UPDATE idp_sessions SET family_revoked_at = $2, updated_at = now() WHERE family_id = $1 AND family_revoked_at IS NULL',
|
|
131
|
+
[familyId, now],
|
|
132
|
+
);
|
|
133
|
+
const { rows } = await this.pool.query(
|
|
134
|
+
`UPDATE idp_sessions SET revoked_at = $2, revoke_reason = $3, family_revoked_at = COALESCE(family_revoked_at, $2), updated_at = now()
|
|
135
|
+
WHERE family_id = $1 AND revoked_at IS NULL
|
|
136
|
+
RETURNING jti`,
|
|
137
|
+
[familyId, now, reason],
|
|
138
|
+
);
|
|
139
|
+
return { revokedCount: rows.length, jtis: rows.map((r) => r.jti).filter(Boolean) };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Whether the family still has a live (unrevoked, unexpired) row. */
|
|
143
|
+
async isFamilyLive(familyId) {
|
|
144
|
+
if (!familyId) return false;
|
|
145
|
+
const { rowCount } = await this.pool.query(
|
|
146
|
+
'SELECT 1 FROM idp_sessions WHERE family_id = $1 AND revoked_at IS NULL AND expires_at > $2 LIMIT 1',
|
|
147
|
+
[familyId, new Date()],
|
|
148
|
+
);
|
|
149
|
+
return rowCount > 0;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Whether the family was revoked as a whole (revokeFamily). */
|
|
153
|
+
async isFamilyRevoked(familyId) {
|
|
154
|
+
if (!familyId) return false;
|
|
155
|
+
const { rowCount } = await this.pool.query(
|
|
156
|
+
'SELECT 1 FROM idp_sessions WHERE family_id = $1 AND family_revoked_at IS NOT NULL LIMIT 1',
|
|
157
|
+
[familyId],
|
|
158
|
+
);
|
|
159
|
+
return rowCount > 0;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Revokes one of the user's sessions by id (sessions list → "sign out this device"). */
|
|
163
|
+
async revokeById(id, userId) {
|
|
164
|
+
if (!isUuid(id) || !isUuid(userId)) return null;
|
|
165
|
+
const { rows: [row] } = await this.pool.query(
|
|
166
|
+
'UPDATE idp_sessions SET revoked_at = $3, updated_at = now() WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL RETURNING *',
|
|
167
|
+
[id, userId, new Date()],
|
|
168
|
+
);
|
|
169
|
+
return mapSession(row);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async revokeAllForUser(userId, { exceptTokenHash, exceptJti } = {}) {
|
|
173
|
+
if (!isUuid(userId)) return { revokedCount: 0 };
|
|
174
|
+
const { rowCount } = await this.pool.query(
|
|
175
|
+
`UPDATE idp_sessions SET revoked_at = $2, updated_at = now()
|
|
176
|
+
WHERE user_id = $1 AND revoked_at IS NULL
|
|
177
|
+
AND ($3::text IS NULL OR token_hash <> $3) AND ($4::text IS NULL OR jti <> $4)`,
|
|
178
|
+
[userId, new Date(), exceptTokenHash ?? null, exceptJti ?? null],
|
|
179
|
+
);
|
|
180
|
+
return { revokedCount: rowCount };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Revokes a client's live OAuth2 sessions — one user's, or every user's (client deactivated).
|
|
185
|
+
* Rows without a `kind` (none are written by this store) would be matched by their claims' shape.
|
|
186
|
+
*/
|
|
187
|
+
async revokeForClient(clientId, { userId } = {}) {
|
|
188
|
+
if (!clientId) return { revokedCount: 0, jtis: [] };
|
|
189
|
+
if (userId !== undefined && userId !== null && !isUuid(userId)) return { revokedCount: 0, jtis: [] };
|
|
190
|
+
const { rows } = await this.pool.query(
|
|
191
|
+
`UPDATE idp_sessions SET revoked_at = $3, revoke_reason = 'client_revoked', updated_at = now()
|
|
192
|
+
WHERE claims ->> 'clientId' = $1 AND revoked_at IS NULL
|
|
193
|
+
AND (kind = 'oauth2' OR (kind IS NULL AND jsonb_typeof(claims -> 'scopes') = 'array'))
|
|
194
|
+
AND ($2::uuid IS NULL OR user_id = $2)
|
|
195
|
+
RETURNING jti`,
|
|
196
|
+
[clientId, userId ?? null, new Date()],
|
|
197
|
+
);
|
|
198
|
+
return { revokedCount: rows.length, jtis: rows.map((r) => r.jti).filter(Boolean) };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async listActiveForUser(userId) {
|
|
202
|
+
if (!isUuid(userId)) return [];
|
|
203
|
+
const { rows } = await this.pool.query(
|
|
204
|
+
`SELECT id, ip_address, device_info, created_at, expires_at, token_hash FROM idp_sessions
|
|
205
|
+
WHERE user_id = $1 AND revoked_at IS NULL AND expires_at > $2 ORDER BY created_at DESC`,
|
|
206
|
+
[userId, new Date()],
|
|
207
|
+
);
|
|
208
|
+
return rows.map(mapListed);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async listHistoryForUser(userId, { limit = 20 } = {}) {
|
|
212
|
+
if (!isUuid(userId)) return [];
|
|
213
|
+
const { rows } = await this.pool.query(
|
|
214
|
+
`SELECT id, ip_address, device_info, created_at, expires_at, revoked_at, token_hash FROM idp_sessions
|
|
215
|
+
WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2`,
|
|
216
|
+
[userId, Math.min(Math.max(Number(limit) || 20, 1), 100)],
|
|
217
|
+
);
|
|
218
|
+
return rows.map(mapListed);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async existsForDevice(userId, fingerprint, rawDeviceInfo) {
|
|
222
|
+
if (!isUuid(userId)) return false;
|
|
223
|
+
const { rowCount } = await this.pool.query(
|
|
224
|
+
`SELECT 1 FROM idp_sessions
|
|
225
|
+
WHERE user_id = $1 AND (($2::text IS NOT NULL AND device_fingerprint = $2) OR device_info = $3) LIMIT 1`,
|
|
226
|
+
[userId, fingerprint || null, rawDeviceInfo ?? null],
|
|
227
|
+
);
|
|
228
|
+
return rowCount > 0;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Write-only audit trail of issued access tokens. */
|
|
232
|
+
async recordIssuedAccessToken(entry) {
|
|
233
|
+
await insertAudit(this.pool, entry);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** No TTL in Postgres: deletes expired sessions and audit rows (see pruneExpired in maintenance.js). */
|
|
237
|
+
async pruneExpired() {
|
|
238
|
+
const now = [new Date()];
|
|
239
|
+
const sessions = await deleteInBatches(this.pool, 'idp_sessions', 'expires_at < $1', now);
|
|
240
|
+
const audit = await deleteInBatches(this.pool, 'idp_access_token_audit', 'expires_at < $1', now);
|
|
241
|
+
return { deletedCount: sessions.deletedCount + audit.deletedCount };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function insertAudit(db, { user, tokenHash, expiresAt, kid, jti, ipAddress, deviceInfo }) {
|
|
246
|
+
if (!isUuid(user)) return; // a token for a non-user subject has no audit row (the FK would refuse it)
|
|
247
|
+
await db.query(
|
|
248
|
+
`INSERT INTO idp_access_token_audit (id, user_id, token_hash, expires_at, kid, jti, ip_address, device_info)
|
|
249
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
|
250
|
+
[newId(), user, tokenHash, expiresAt, kid, jti, ipAddress ?? null, deviceInfo ?? null],
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function mapSession(row) {
|
|
255
|
+
if (!row) return null;
|
|
256
|
+
return {
|
|
257
|
+
id: row.id,
|
|
258
|
+
user: row.user_id,
|
|
259
|
+
tokenHash: row.token_hash,
|
|
260
|
+
expiresAt: row.expires_at,
|
|
261
|
+
kid: row.kid,
|
|
262
|
+
jti: row.jti,
|
|
263
|
+
revokedAt: row.revoked_at,
|
|
264
|
+
revokeReason: row.revoke_reason ?? undefined,
|
|
265
|
+
familyRevokedAt: row.family_revoked_at,
|
|
266
|
+
deviceInfo: row.device_info,
|
|
267
|
+
deviceFingerprint: row.device_fingerprint,
|
|
268
|
+
ipAddress: row.ip_address,
|
|
269
|
+
kind: row.kind,
|
|
270
|
+
authTime: row.auth_time,
|
|
271
|
+
familyId: row.family_id,
|
|
272
|
+
familyCreatedAt: row.family_created_at,
|
|
273
|
+
sessionEpoch: row.session_epoch,
|
|
274
|
+
claims: row.claims ?? {},
|
|
275
|
+
createdAt: row.created_at,
|
|
276
|
+
updatedAt: row.updated_at,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function mapListed(row) {
|
|
281
|
+
return {
|
|
282
|
+
id: row.id,
|
|
283
|
+
ipAddress: row.ip_address,
|
|
284
|
+
deviceInfo: row.device_info,
|
|
285
|
+
createdAt: row.created_at,
|
|
286
|
+
expiresAt: row.expires_at,
|
|
287
|
+
...(row.revoked_at !== undefined ? { revokedAt: row.revoked_at } : {}),
|
|
288
|
+
tokenHash: row.token_hash,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { newId, isUuid, withTransaction, columnFor } from '../db.js';
|
|
2
|
+
|
|
3
|
+
/** Read only when asked for (`select: '+field'`), like idp-core's Mongo model (`select: false`). */
|
|
4
|
+
const HIDDEN_BY_DEFAULT = ['passwordHash', 'mfaSecret', 'mfaTempSecret', 'mfaLastTotpStep', 'mfaRecoveryCodes'];
|
|
5
|
+
|
|
6
|
+
const COLUMNS = {
|
|
7
|
+
passwordHash: 'password_hash',
|
|
8
|
+
status: 'status',
|
|
9
|
+
lastLoginAt: 'last_login_at',
|
|
10
|
+
passwordChangedAt: 'password_changed_at',
|
|
11
|
+
sessionsRevokedAt: 'sessions_revoked_at',
|
|
12
|
+
sessionsRevokedExceptFamily: 'sessions_revoked_except_family',
|
|
13
|
+
registrationContested: 'registration_contested',
|
|
14
|
+
failedLoginAttempts: 'failed_login_attempts',
|
|
15
|
+
lockUntil: 'lock_until',
|
|
16
|
+
mfaEnabled: 'mfa_enabled',
|
|
17
|
+
mfaSecret: 'mfa_secret',
|
|
18
|
+
mfaTempSecret: 'mfa_temp_secret',
|
|
19
|
+
mfaLastTotpStep: 'mfa_last_totp_step',
|
|
20
|
+
metadata: 'metadata',
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const PROFILE_COLUMNS = {
|
|
24
|
+
firstName: 'profile_first_name',
|
|
25
|
+
lastName: 'profile_last_name',
|
|
26
|
+
displayName: 'profile_display_name',
|
|
27
|
+
avatarUrl: 'profile_avatar_url',
|
|
28
|
+
locale: 'profile_locale',
|
|
29
|
+
zoneinfo: 'profile_zoneinfo',
|
|
30
|
+
};
|
|
31
|
+
/** Trimmed on write, as idp-core's Mongo model does. */
|
|
32
|
+
const TRIMMED_PROFILE_FIELDS = new Set(['firstName', 'lastName', 'displayName']);
|
|
33
|
+
|
|
34
|
+
const RECOVERY_CODE_USED = /^mfaRecoveryCodes\.(\d+)\.usedAt$/;
|
|
35
|
+
|
|
36
|
+
const SELECT_USER = `
|
|
37
|
+
SELECT u.*,
|
|
38
|
+
COALESCE((SELECT json_agg(json_build_object('provider', p.provider, 'providerId', p.provider_id, 'email', p.email, 'connectedAt', p.connected_at) ORDER BY p.id)
|
|
39
|
+
FROM idp_user_external_providers p WHERE p.user_id = u.id), '[]') AS external_providers,
|
|
40
|
+
COALESCE((SELECT json_agg(json_build_object('codeHash', r.code_hash, 'usedAt', r.used_at) ORDER BY r.position)
|
|
41
|
+
FROM idp_user_recovery_codes r WHERE r.user_id = u.id), '[]') AS recovery_codes
|
|
42
|
+
FROM idp_users u`;
|
|
43
|
+
|
|
44
|
+
/** @implements {import('../../interfaces.js').UserRepository} */
|
|
45
|
+
export class PgUserRepository {
|
|
46
|
+
constructor(pool, { hashEmail, normalizeEmail }) {
|
|
47
|
+
this.pool = pool;
|
|
48
|
+
this.hashEmail = hashEmail;
|
|
49
|
+
this.normalizeEmail = normalizeEmail;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async create(data) {
|
|
53
|
+
const { email, profile = {}, externalProviders = [], mfaRecoveryCodes, ...rest } = data;
|
|
54
|
+
const normalized = this.normalizeEmail(email);
|
|
55
|
+
if (!normalized) throw new Error('@okeav/idp-pg: a user needs an email');
|
|
56
|
+
const id = newId();
|
|
57
|
+
const columns = ['id', 'email', 'email_hash'];
|
|
58
|
+
const values = [id, normalized, this.hashEmail(normalized)];
|
|
59
|
+
for (const [key, value] of Object.entries(rest)) {
|
|
60
|
+
if (value === undefined) continue;
|
|
61
|
+
columns.push(columnFor(COLUMNS, key, 'idp_users'));
|
|
62
|
+
values.push(encodeColumn(key, value));
|
|
63
|
+
}
|
|
64
|
+
for (const [field, value] of Object.entries(profile ?? {})) {
|
|
65
|
+
if (value === undefined) continue;
|
|
66
|
+
columns.push(columnFor(PROFILE_COLUMNS, field, 'idp_users.profile'));
|
|
67
|
+
values.push(encodeProfile(field, value));
|
|
68
|
+
}
|
|
69
|
+
return withTransaction(this.pool, async (client) => {
|
|
70
|
+
await client.query(
|
|
71
|
+
`INSERT INTO idp_users (${columns.join(', ')}) VALUES (${columns.map((_, i) => `$${i + 1}`).join(', ')})`,
|
|
72
|
+
values,
|
|
73
|
+
);
|
|
74
|
+
for (const link of externalProviders) await insertLink(client, id, link);
|
|
75
|
+
if (Array.isArray(mfaRecoveryCodes)) await replaceRecoveryCodes(client, id, mfaRecoveryCodes);
|
|
76
|
+
return project(await loadUser(client, 'u.id = $1', [id]));
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async findById(id, opts = {}) {
|
|
81
|
+
if (!isUuid(id)) return null;
|
|
82
|
+
return project(await loadUser(this.pool, 'u.id = $1', [id]), opts.select);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async findByEmail(email, opts = {}) {
|
|
86
|
+
const normalized = this.normalizeEmail(email);
|
|
87
|
+
if (!normalized) return null;
|
|
88
|
+
return project(await loadUser(this.pool, 'u.email_hash = $1', [this.hashEmail(normalized)]), opts.select);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async findByExternalProvider(provider, providerId) {
|
|
92
|
+
return project(await loadUser(this.pool,
|
|
93
|
+
'u.id = (SELECT user_id FROM idp_user_external_providers WHERE provider = $1 AND provider_id = $2)', [provider, providerId]));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async updateById(id, patch, opts = {}) {
|
|
97
|
+
return this._update(id, patch, { select: opts.select });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Applies `patch` only while the user's status is still `status` (atomically); null if it changed. */
|
|
101
|
+
async updateByIdIfStatus(id, status, patch) {
|
|
102
|
+
return this._update(id, patch, { ifStatus: status });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async _update(id, patch, { ifStatus, select } = {}) {
|
|
106
|
+
if (!isUuid(id)) return null;
|
|
107
|
+
const { sets, values, recoveryCodes, recoveryCodesUsed } = this._splitPatch(patch);
|
|
108
|
+
return withTransaction(this.pool, async (client) => {
|
|
109
|
+
// One UPDATE takes the row lock and checks the condition; everything else happens under it.
|
|
110
|
+
const params = [id, ...values];
|
|
111
|
+
let where = 'id = $1';
|
|
112
|
+
if (ifStatus !== undefined) {
|
|
113
|
+
params.push(ifStatus);
|
|
114
|
+
where += ` AND status = $${params.length}`;
|
|
115
|
+
}
|
|
116
|
+
const { rowCount } = await client.query(`UPDATE idp_users SET ${[...sets, 'updated_at = now()'].join(', ')} WHERE ${where}`, params);
|
|
117
|
+
if (rowCount === 0) return null;
|
|
118
|
+
if (recoveryCodes) await replaceRecoveryCodes(client, id, recoveryCodes);
|
|
119
|
+
for (const { position, usedAt } of recoveryCodesUsed) {
|
|
120
|
+
await client.query('UPDATE idp_user_recovery_codes SET used_at = $3 WHERE user_id = $1 AND position = $2', [id, position, usedAt]);
|
|
121
|
+
}
|
|
122
|
+
return project(await loadUser(client, 'u.id = $1', [id]), select);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** A Mongo-style `$set` patch → column SETs (from $2) plus the recovery-code changes. */
|
|
127
|
+
_splitPatch(patch) {
|
|
128
|
+
const sets = [];
|
|
129
|
+
const values = [];
|
|
130
|
+
let recoveryCodes = null;
|
|
131
|
+
const recoveryCodesUsed = [];
|
|
132
|
+
const set = (column, value) => {
|
|
133
|
+
values.push(value);
|
|
134
|
+
sets.push(`${column} = $${values.length + 1}`);
|
|
135
|
+
};
|
|
136
|
+
for (const [key, value] of Object.entries(patch ?? {})) {
|
|
137
|
+
if (value === undefined) continue;
|
|
138
|
+
const used = key.match(RECOVERY_CODE_USED);
|
|
139
|
+
if (key === 'mfaRecoveryCodes') {
|
|
140
|
+
if (!Array.isArray(value)) throw new Error('@okeav/idp-pg: mfaRecoveryCodes must be an array');
|
|
141
|
+
recoveryCodes = value;
|
|
142
|
+
} else if (used) {
|
|
143
|
+
recoveryCodesUsed.push({ position: Number(used[1]), usedAt: value });
|
|
144
|
+
} else if (key === 'email') {
|
|
145
|
+
const normalized = this.normalizeEmail(value);
|
|
146
|
+
set('email', normalized);
|
|
147
|
+
set('email_hash', this.hashEmail(normalized));
|
|
148
|
+
} else if (key === 'profile') {
|
|
149
|
+
for (const [field, v] of Object.entries(value ?? {})) {
|
|
150
|
+
if (v !== undefined) set(columnFor(PROFILE_COLUMNS, field, 'idp_users.profile'), encodeProfile(field, v));
|
|
151
|
+
}
|
|
152
|
+
} else if (key.startsWith('profile.')) {
|
|
153
|
+
const field = key.slice('profile.'.length);
|
|
154
|
+
set(columnFor(PROFILE_COLUMNS, field, 'idp_users.profile'), encodeProfile(field, value));
|
|
155
|
+
} else {
|
|
156
|
+
set(columnFor(COLUMNS, key, 'idp_users'), encodeColumn(key, value));
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return { sets, values, recoveryCodes, recoveryCodesUsed };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* "Revoke all sessions": increments `sessionEpoch` atomically, recording the one family exempt from
|
|
164
|
+
* this bump. Resolves the new epoch (null for an unknown user).
|
|
165
|
+
*/
|
|
166
|
+
async bumpSessionEpoch(id, { exceptFamily = null } = {}) {
|
|
167
|
+
if (!isUuid(id)) return null;
|
|
168
|
+
const { rows: [row] } = await this.pool.query(
|
|
169
|
+
`UPDATE idp_users SET session_epoch = session_epoch + 1, sessions_revoked_at = $2, sessions_revoked_except_family = $3, updated_at = now()
|
|
170
|
+
WHERE id = $1 RETURNING session_epoch`,
|
|
171
|
+
[id, new Date(), exceptFamily],
|
|
172
|
+
);
|
|
173
|
+
return row ? row.session_epoch : null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async incrementFailedLoginAttempts(id) {
|
|
177
|
+
if (!isUuid(id)) return null;
|
|
178
|
+
const { rowCount } = await this.pool.query('UPDATE idp_users SET failed_login_attempts = failed_login_attempts + 1, updated_at = now() WHERE id = $1', [id]);
|
|
179
|
+
return rowCount ? this.findById(id) : null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Records `step` as the last accepted TOTP step — only if newer. Of two concurrent claims of one step, one wins. */
|
|
183
|
+
async claimTotpStep(id, step) {
|
|
184
|
+
if (!isUuid(id)) return false;
|
|
185
|
+
const { rowCount } = await this.pool.query(
|
|
186
|
+
'UPDATE idp_users SET mfa_last_totp_step = $2 WHERE id = $1 AND (mfa_last_totp_step IS NULL OR mfa_last_totp_step < $2)',
|
|
187
|
+
[id, step],
|
|
188
|
+
);
|
|
189
|
+
return rowCount === 1;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Spends one unused recovery code with this hash — atomically, so a code is spent once. */
|
|
193
|
+
async consumeRecoveryCode(id, codeHash) {
|
|
194
|
+
if (!isUuid(id)) return false;
|
|
195
|
+
const { rowCount } = await this.pool.query(
|
|
196
|
+
`UPDATE idp_user_recovery_codes SET used_at = $3
|
|
197
|
+
WHERE user_id = $1 AND position = (
|
|
198
|
+
SELECT position FROM idp_user_recovery_codes
|
|
199
|
+
WHERE user_id = $1 AND code_hash = $2 AND used_at IS NULL
|
|
200
|
+
ORDER BY position LIMIT 1 FOR UPDATE
|
|
201
|
+
) AND used_at IS NULL`,
|
|
202
|
+
[id, codeHash, new Date()],
|
|
203
|
+
);
|
|
204
|
+
return rowCount === 1;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async linkExternalProvider(id, link) {
|
|
208
|
+
if (!isUuid(id)) return null;
|
|
209
|
+
return withTransaction(this.pool, async (client) => {
|
|
210
|
+
await insertLink(client, id, link);
|
|
211
|
+
await client.query('UPDATE idp_users SET updated_at = now() WHERE id = $1', [id]);
|
|
212
|
+
return project(await loadUser(client, 'u.id = $1', [id]));
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async deleteById(id) {
|
|
217
|
+
if (!isUuid(id)) return;
|
|
218
|
+
await this.pool.query('DELETE FROM idp_users WHERE id = $1', [id]);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async countAll() {
|
|
222
|
+
const { rows: [{ count }] } = await this.pool.query('SELECT count(*)::int AS count FROM idp_users');
|
|
223
|
+
return count;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** A stable order, so paging (e.g. migrateMfaSecrets) sees every user once. */
|
|
227
|
+
async findMany({ skip = 0, limit = 20 } = {}) {
|
|
228
|
+
const { rows } = await this.pool.query(`${SELECT_USER} ORDER BY u.created_at, u.id OFFSET $1 LIMIT $2`, [skip, limit]);
|
|
229
|
+
return rows.map((row) => project(assemble(row)));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function loadUser(db, where, params) {
|
|
234
|
+
const { rows: [row] } = await db.query(`${SELECT_USER} WHERE ${where}`, params);
|
|
235
|
+
return row ? assemble(row) : null;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Links an external identity; one that's already linked to ANOTHER account is refused. */
|
|
239
|
+
async function insertLink(client, userId, { provider, providerId, email, connectedAt }) {
|
|
240
|
+
const { rows: [row] } = await client.query(
|
|
241
|
+
`INSERT INTO idp_user_external_providers (user_id, provider, provider_id, email, connected_at)
|
|
242
|
+
VALUES ($1, $2, $3, $4, $5)
|
|
243
|
+
ON CONFLICT (provider, provider_id) DO UPDATE SET provider = EXCLUDED.provider
|
|
244
|
+
RETURNING user_id`,
|
|
245
|
+
[userId, provider, providerId, email ?? null, connectedAt ?? new Date()],
|
|
246
|
+
);
|
|
247
|
+
if (row.user_id !== userId) throw new Error(`@okeav/idp-pg: this ${provider} identity is already linked to another account`);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function replaceRecoveryCodes(client, userId, codes) {
|
|
251
|
+
await client.query('DELETE FROM idp_user_recovery_codes WHERE user_id = $1', [userId]);
|
|
252
|
+
if (codes.length === 0) return;
|
|
253
|
+
await client.query(
|
|
254
|
+
`INSERT INTO idp_user_recovery_codes (user_id, position, code_hash, used_at)
|
|
255
|
+
SELECT $1, t.ord - 1, t.code_hash, t.used_at
|
|
256
|
+
FROM unnest($2::text[], $3::timestamptz[]) WITH ORDINALITY AS t(code_hash, used_at, ord)`,
|
|
257
|
+
[userId, codes.map((c) => c.codeHash), codes.map((c) => c.usedAt ?? null)],
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function encodeColumn(key, value) {
|
|
262
|
+
return key === 'metadata' ? JSON.stringify(value ?? {}) : value;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function encodeProfile(field, value) {
|
|
266
|
+
return TRIMMED_PROFILE_FIELDS.has(field) && typeof value === 'string' ? value.trim() : value;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const toDate = (v) => (v == null ? null : new Date(v));
|
|
270
|
+
|
|
271
|
+
function assemble(row) {
|
|
272
|
+
return {
|
|
273
|
+
id: row.id,
|
|
274
|
+
email: row.email,
|
|
275
|
+
emailHash: row.email_hash,
|
|
276
|
+
passwordHash: row.password_hash,
|
|
277
|
+
status: row.status,
|
|
278
|
+
lastLoginAt: row.last_login_at,
|
|
279
|
+
passwordChangedAt: row.password_changed_at,
|
|
280
|
+
sessionEpoch: row.session_epoch,
|
|
281
|
+
sessionsRevokedAt: row.sessions_revoked_at,
|
|
282
|
+
sessionsRevokedExceptFamily: row.sessions_revoked_except_family,
|
|
283
|
+
registrationContested: row.registration_contested,
|
|
284
|
+
failedLoginAttempts: row.failed_login_attempts,
|
|
285
|
+
lockUntil: row.lock_until,
|
|
286
|
+
mfaEnabled: row.mfa_enabled,
|
|
287
|
+
mfaSecret: row.mfa_secret,
|
|
288
|
+
mfaTempSecret: row.mfa_temp_secret,
|
|
289
|
+
mfaLastTotpStep: row.mfa_last_totp_step == null ? null : Number(row.mfa_last_totp_step),
|
|
290
|
+
mfaRecoveryCodes: row.recovery_codes.map((c) => ({ codeHash: c.codeHash, usedAt: toDate(c.usedAt) })),
|
|
291
|
+
externalProviders: row.external_providers.map((p) => ({ provider: p.provider, providerId: p.providerId, email: p.email, connectedAt: toDate(p.connectedAt) })),
|
|
292
|
+
profile: {
|
|
293
|
+
firstName: row.profile_first_name,
|
|
294
|
+
lastName: row.profile_last_name,
|
|
295
|
+
displayName: row.profile_display_name,
|
|
296
|
+
avatarUrl: row.profile_avatar_url,
|
|
297
|
+
locale: row.profile_locale,
|
|
298
|
+
zoneinfo: row.profile_zoneinfo,
|
|
299
|
+
},
|
|
300
|
+
metadata: row.metadata ?? {},
|
|
301
|
+
createdAt: row.created_at,
|
|
302
|
+
updatedAt: row.updated_at,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Applies a Mongoose-style `select` string, as idp-core uses it:
|
|
308
|
+
* - any bare field name: an inclusion list (`id` + exactly the named fields; `+` on a name is ignored);
|
|
309
|
+
* - only `+`/`-` tokens: the default projection, with hidden fields added back / visible ones removed.
|
|
310
|
+
* Without one, the hidden fields (secrets, recovery codes) are left out.
|
|
311
|
+
*/
|
|
312
|
+
export function project(user, select) {
|
|
313
|
+
if (!user) return null;
|
|
314
|
+
const tokens = (select ?? '').trim().split(/\s+/).filter(Boolean);
|
|
315
|
+
if (tokens.some((t) => !t.startsWith('+') && !t.startsWith('-'))) {
|
|
316
|
+
const picked = { id: user.id };
|
|
317
|
+
for (const t of tokens) {
|
|
318
|
+
const field = t.replace(/^[+-]/, '');
|
|
319
|
+
if (!t.startsWith('-')) picked[field] = user[field];
|
|
320
|
+
}
|
|
321
|
+
return picked;
|
|
322
|
+
}
|
|
323
|
+
const hidden = new Set(HIDDEN_BY_DEFAULT.filter((f) => !tokens.includes(`+${f}`)));
|
|
324
|
+
for (const t of tokens) if (t.startsWith('-')) hidden.add(t.slice(1));
|
|
325
|
+
const result = { ...user };
|
|
326
|
+
for (const field of hidden) delete result[field];
|
|
327
|
+
return result;
|
|
328
|
+
}
|