@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,160 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
import { runMigrations, assertMigrationsApplied } from './migrations/run-migrations.js';
|
|
3
|
+
import { PgUserRepository } from './repositories/user.repository.js';
|
|
4
|
+
import { PgSessionRepository } from './repositories/session.repository.js';
|
|
5
|
+
import { PgAuthorizationCodeRepository } from './repositories/authorization-code.repository.js';
|
|
6
|
+
import { PgConsentRepository } from './repositories/consent.repository.js';
|
|
7
|
+
import { PgOAuthClientRepository } from './repositories/oauth-client.repository.js';
|
|
8
|
+
import { PgVerificationTokenRepository } from './repositories/verification-token.repository.js';
|
|
9
|
+
import { PgServiceKeyRepository } from './repositories/service-key.repository.js';
|
|
10
|
+
import { PgCredentialRepository } from './repositories/credential.repository.js';
|
|
11
|
+
import { PgAttemptCounterRepository } from './repositories/attempt-counter.repository.js';
|
|
12
|
+
|
|
13
|
+
/** The oldest PostgreSQL this package is tested against and whose SQL it uses. */
|
|
14
|
+
export const MIN_POSTGRES_VERSION = 14;
|
|
15
|
+
|
|
16
|
+
const MIGRATION_MODES = ['verify', 'apply', 'skip'];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Resolves the options `initIdentityProvider({ postgres })` takes into a validated shape. Throws on
|
|
20
|
+
* anything unusable — before connecting.
|
|
21
|
+
*/
|
|
22
|
+
export function resolvePostgresOptions(options) {
|
|
23
|
+
if (!options || typeof options !== 'object') {
|
|
24
|
+
throw new Error('@okeav/idp-pg: config.postgres is required — { connectionString } or { pool }');
|
|
25
|
+
}
|
|
26
|
+
const { pool, connectionString, migrations = 'verify', pruneIntervalSeconds = 3600, poolConfig = {} } = options;
|
|
27
|
+
const unknown = Object.keys(options).filter((k) => !['pool', 'connectionString', 'migrations', 'pruneIntervalSeconds', 'poolConfig'].includes(k));
|
|
28
|
+
if (unknown.length) throw new Error(`@okeav/idp-pg: unknown config.postgres option(s): ${unknown.join(', ')}`);
|
|
29
|
+
if (pool && (connectionString || Object.keys(poolConfig).length)) {
|
|
30
|
+
throw new Error('@okeav/idp-pg: config.postgres takes either `pool` (yours) or `connectionString`/`poolConfig` (one is created) — not both');
|
|
31
|
+
}
|
|
32
|
+
if (pool && typeof pool.query !== 'function') throw new Error('@okeav/idp-pg: config.postgres.pool must be a pg.Pool');
|
|
33
|
+
if (!pool && !connectionString && !poolConfig.host && !poolConfig.connectionString) {
|
|
34
|
+
throw new Error('@okeav/idp-pg: config.postgres needs a connectionString (or a pool)');
|
|
35
|
+
}
|
|
36
|
+
if (!MIGRATION_MODES.includes(migrations)) {
|
|
37
|
+
throw new Error(`@okeav/idp-pg: config.postgres.migrations must be one of ${MIGRATION_MODES.join(', ')} (got ${migrations})`);
|
|
38
|
+
}
|
|
39
|
+
if (!Number.isInteger(pruneIntervalSeconds) || (pruneIntervalSeconds !== 0 && pruneIntervalSeconds < 60)) {
|
|
40
|
+
throw new Error(`@okeav/idp-pg: config.postgres.pruneIntervalSeconds must be 0 (off) or an integer >= 60 (got ${pruneIntervalSeconds})`);
|
|
41
|
+
}
|
|
42
|
+
return { pool, connectionString, migrations, pruneIntervalSeconds, poolConfig };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The PostgreSQL store: every repository of the storage contract, plus
|
|
47
|
+
* `databaseTime()` (the clock-skew guard's reference), `pruneExpired()` and `close()`.
|
|
48
|
+
*
|
|
49
|
+
* @param {object} options - see resolvePostgresOptions / README
|
|
50
|
+
* @param {{ hashEmail: (email: string) => string, normalizeEmail: (email: string) => string }} emailDeps
|
|
51
|
+
* @param {{ logger?: object }} [context]
|
|
52
|
+
*/
|
|
53
|
+
export async function createPostgresStorage(options, emailDeps, { logger = console } = {}) {
|
|
54
|
+
const resolved = resolvePostgresOptions(options);
|
|
55
|
+
const ownsPool = !resolved.pool;
|
|
56
|
+
const pool = resolved.pool ?? new pg.Pool({
|
|
57
|
+
application_name: 'idp-pg',
|
|
58
|
+
...resolved.poolConfig,
|
|
59
|
+
...(resolved.connectionString ? { connectionString: resolved.connectionString } : {}),
|
|
60
|
+
});
|
|
61
|
+
// An idle connection that dies (failover, network) emits 'error' on the pool; unhandled, that
|
|
62
|
+
// event would crash the process. The pool replaces the connection — log it and carry on.
|
|
63
|
+
const onPoolError = (err) => logger.error?.({ err }, '@okeav/idp-pg: idle PostgreSQL connection failed (the pool replaces it)');
|
|
64
|
+
if (ownsPool) pool.on('error', onPoolError);
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
await assertServerVersion(pool);
|
|
68
|
+
if (resolved.migrations === 'apply') await runMigrations(pool);
|
|
69
|
+
if (resolved.migrations !== 'skip') {
|
|
70
|
+
const { unknown } = await assertMigrationsApplied(pool);
|
|
71
|
+
if (unknown.length) {
|
|
72
|
+
logger.warn?.({ migrations: unknown }, '@okeav/idp-pg: the database has migrations this version does not know (migrated by a newer version) — run the newer version');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
} catch (err) {
|
|
76
|
+
if (ownsPool) await pool.end().catch(() => {});
|
|
77
|
+
throw err;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const repositories = {
|
|
81
|
+
userRepository: new PgUserRepository(pool, emailDeps),
|
|
82
|
+
sessionRepository: new PgSessionRepository(pool),
|
|
83
|
+
authorizationCodeRepository: new PgAuthorizationCodeRepository(pool),
|
|
84
|
+
consentRepository: new PgConsentRepository(pool),
|
|
85
|
+
oauthClientRepository: new PgOAuthClientRepository(pool),
|
|
86
|
+
verificationTokenRepository: new PgVerificationTokenRepository(pool),
|
|
87
|
+
serviceKeyRepository: new PgServiceKeyRepository(pool),
|
|
88
|
+
credentialRepository: new PgCredentialRepository(pool),
|
|
89
|
+
attemptCounterRepository: new PgAttemptCounterRepository(pool),
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/** Deletes every expired row (Postgres has no TTL index). Resolves the count per table group. */
|
|
93
|
+
async function pruneExpired() {
|
|
94
|
+
const result = {};
|
|
95
|
+
for (const [name, repo] of Object.entries(repositories)) {
|
|
96
|
+
if (typeof repo.pruneExpired === 'function') result[name] = (await repo.pruneExpired()).deletedCount;
|
|
97
|
+
}
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const pruner = startPruner(pruneExpired, resolved.pruneIntervalSeconds, logger);
|
|
102
|
+
let closed = false;
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
pool,
|
|
106
|
+
...repositories,
|
|
107
|
+
pruneExpired,
|
|
108
|
+
/** The database server's clock — every app server's clock is checked against it. */
|
|
109
|
+
async databaseTime() {
|
|
110
|
+
const { rows: [row] } = await pool.query('SELECT clock_timestamp() AS time');
|
|
111
|
+
return { time: row.time };
|
|
112
|
+
},
|
|
113
|
+
async close() {
|
|
114
|
+
if (closed) return;
|
|
115
|
+
closed = true;
|
|
116
|
+
await pruner.stop();
|
|
117
|
+
if (ownsPool) await pool.end(); // a pool passed in is the app's to end
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function assertServerVersion(pool) {
|
|
123
|
+
const { rows: [row] } = await pool.query('SHOW server_version_num');
|
|
124
|
+
const major = Math.floor(Number(row.server_version_num) / 10000);
|
|
125
|
+
if (!(major >= MIN_POSTGRES_VERSION)) {
|
|
126
|
+
throw new Error(`@okeav/idp-pg: PostgreSQL ${MIN_POSTGRES_VERSION} or later is required (this server is ${major})`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Prunes every `intervalSeconds` (with up to 10% jitter, so a fleet of instances doesn't run in step);
|
|
132
|
+
* never two runs at once; the timer doesn't keep the process alive. `stop()` waits for a run in flight.
|
|
133
|
+
*/
|
|
134
|
+
function startPruner(prune, intervalSeconds, logger) {
|
|
135
|
+
if (!intervalSeconds) return { stop: async () => {} };
|
|
136
|
+
let running = null;
|
|
137
|
+
let timer = null;
|
|
138
|
+
let stopped = false;
|
|
139
|
+
const schedule = () => {
|
|
140
|
+
const delay = intervalSeconds * 1000 * (1 + Math.random() * 0.1);
|
|
141
|
+
timer = setTimeout(run, delay);
|
|
142
|
+
timer.unref?.();
|
|
143
|
+
};
|
|
144
|
+
const run = async () => {
|
|
145
|
+
running = prune()
|
|
146
|
+
.then((deleted) => logger.debug?.({ deleted }, '@okeav/idp-pg: pruned expired rows'))
|
|
147
|
+
.catch((err) => logger.error?.({ err }, '@okeav/idp-pg: pruning expired rows failed (retried next interval)'))
|
|
148
|
+
.finally(() => { running = null; });
|
|
149
|
+
await running;
|
|
150
|
+
if (!stopped) schedule();
|
|
151
|
+
};
|
|
152
|
+
schedule();
|
|
153
|
+
return {
|
|
154
|
+
async stop() {
|
|
155
|
+
stopped = true;
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
await running;
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const SQL_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), 'sql');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Session-level advisory lock held for the whole of `runMigrations`, so concurrent callers (several
|
|
10
|
+
* instances migrating at boot) apply each file once. The ASCII bytes of "okeavidp" as a signed 64-bit
|
|
11
|
+
* integer — a string, since it doesn't fit in a JS number.
|
|
12
|
+
*/
|
|
13
|
+
export const MIGRATION_LOCK_KEY = '8028622229990892656';
|
|
14
|
+
|
|
15
|
+
/** The bundled migrations, in order: `[{ filename, sql, checksum }]`. */
|
|
16
|
+
export async function bundledMigrations() {
|
|
17
|
+
const files = (await fs.readdir(SQL_DIR)).filter((f) => /^\d{4}_[\w-]+\.sql$/.test(f)).sort();
|
|
18
|
+
return Promise.all(files.map(async (filename) => {
|
|
19
|
+
const sql = await fs.readFile(path.join(SQL_DIR, filename), 'utf8');
|
|
20
|
+
return { filename, sql, checksum: checksumOf(sql) };
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Line endings don't count: a checkout with CRLF must match one with LF. */
|
|
25
|
+
function checksumOf(sql) {
|
|
26
|
+
return crypto.createHash('sha256').update(sql.replace(/\r\n/g, '\n')).digest('hex');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Applies every bundled migration not yet applied to this database, in order, each in its own
|
|
31
|
+
* transaction, recorded in `idp_schema_migrations` with its checksum. Safe to run from several
|
|
32
|
+
* instances at once (an advisory lock serialises them; a waiting caller finds nothing left to do).
|
|
33
|
+
* Refuses to run if an already-applied migration's file has changed since it was applied.
|
|
34
|
+
*
|
|
35
|
+
* Point it at a direct or session-mode connection: through a transaction-mode pooler (PgBouncer
|
|
36
|
+
* `pool_mode=transaction`) a session-level advisory lock is not reliable.
|
|
37
|
+
*
|
|
38
|
+
* @param {import('pg').Pool} pool
|
|
39
|
+
* @returns {Promise<string[]>} the filenames applied by this call
|
|
40
|
+
*/
|
|
41
|
+
export async function runMigrations(pool) {
|
|
42
|
+
const migrations = await bundledMigrations();
|
|
43
|
+
const client = await pool.connect();
|
|
44
|
+
let lockHeld = false;
|
|
45
|
+
let broken;
|
|
46
|
+
try {
|
|
47
|
+
await client.query('SELECT pg_advisory_lock($1::bigint)', [MIGRATION_LOCK_KEY]);
|
|
48
|
+
lockHeld = true;
|
|
49
|
+
return await applyPending(client, migrations);
|
|
50
|
+
} finally {
|
|
51
|
+
if (lockHeld) {
|
|
52
|
+
await client.query('SELECT pg_advisory_unlock($1::bigint)', [MIGRATION_LOCK_KEY]).catch((err) => { broken = err; });
|
|
53
|
+
}
|
|
54
|
+
// Releasing with an error destroys the connection — which also drops a lock we failed to release.
|
|
55
|
+
client.release(broken);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function applyPending(client, migrations) {
|
|
60
|
+
await client.query(`
|
|
61
|
+
CREATE TABLE IF NOT EXISTS idp_schema_migrations (
|
|
62
|
+
filename TEXT PRIMARY KEY,
|
|
63
|
+
checksum TEXT NOT NULL,
|
|
64
|
+
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
65
|
+
)
|
|
66
|
+
`);
|
|
67
|
+
// Read only once the lock is held: another instance may have just applied some of these.
|
|
68
|
+
const { rows } = await client.query('SELECT filename, checksum FROM idp_schema_migrations');
|
|
69
|
+
const applied = new Map(rows.map((r) => [r.filename, r.checksum]));
|
|
70
|
+
assertUnchanged(migrations, applied);
|
|
71
|
+
|
|
72
|
+
const newlyApplied = [];
|
|
73
|
+
for (const { filename, sql, checksum } of migrations) {
|
|
74
|
+
if (applied.has(filename)) continue;
|
|
75
|
+
try {
|
|
76
|
+
await client.query('BEGIN');
|
|
77
|
+
await client.query(sql);
|
|
78
|
+
await client.query('INSERT INTO idp_schema_migrations (filename, checksum) VALUES ($1, $2)', [filename, checksum]);
|
|
79
|
+
await client.query('COMMIT');
|
|
80
|
+
} catch (err) {
|
|
81
|
+
await client.query('ROLLBACK').catch(() => {});
|
|
82
|
+
throw new Error(`@okeav/idp-pg: migration ${filename} failed: ${err.message}`, { cause: err });
|
|
83
|
+
}
|
|
84
|
+
newlyApplied.push(filename);
|
|
85
|
+
}
|
|
86
|
+
return newlyApplied;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function assertUnchanged(migrations, applied) {
|
|
90
|
+
const changed = migrations.filter((m) => applied.has(m.filename) && applied.get(m.filename) !== m.checksum).map((m) => m.filename);
|
|
91
|
+
if (changed.length) {
|
|
92
|
+
throw new Error(`@okeav/idp-pg: applied migration(s) changed since they were applied: ${changed.join(', ')} — a released migration must never be edited; add a new one instead`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Throws, naming what's wrong, unless every bundled migration is applied unchanged. Read-only — the
|
|
98
|
+
* startup check behind `postgres.migrations: 'verify'`. Resolves the applied migrations this version
|
|
99
|
+
* doesn't know (the database was migrated by a newer version — e.g. during a rollback): the caller
|
|
100
|
+
* warns about those rather than refusing to start.
|
|
101
|
+
*
|
|
102
|
+
* @param {import('pg').Pool | import('pg').PoolClient} db
|
|
103
|
+
* @returns {Promise<{ unknown: string[] }>}
|
|
104
|
+
*/
|
|
105
|
+
export async function assertMigrationsApplied(db) {
|
|
106
|
+
const migrations = await bundledMigrations();
|
|
107
|
+
let rows;
|
|
108
|
+
try {
|
|
109
|
+
({ rows } = await db.query('SELECT filename, checksum FROM idp_schema_migrations'));
|
|
110
|
+
} catch (err) {
|
|
111
|
+
if (err?.code !== '42P01') throw err; // undefined_table
|
|
112
|
+
throw new Error("@okeav/idp-pg: this database has no idp schema yet — run runMigrations() first (or set postgres.migrations: 'apply')", { cause: err });
|
|
113
|
+
}
|
|
114
|
+
const applied = new Map(rows.map((r) => [r.filename, r.checksum]));
|
|
115
|
+
assertUnchanged(migrations, applied);
|
|
116
|
+
const missing = migrations.filter((m) => !applied.has(m.filename)).map((m) => m.filename);
|
|
117
|
+
if (missing.length) {
|
|
118
|
+
throw new Error(`@okeav/idp-pg: this database is missing migration(s) ${missing.join(', ')} — run runMigrations() first (or set postgres.migrations: 'apply')`);
|
|
119
|
+
}
|
|
120
|
+
const known = new Set(migrations.map((m) => m.filename));
|
|
121
|
+
return { unknown: rows.map((r) => r.filename).filter((f) => !known.has(f)) };
|
|
122
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
-- @okeav/idp-pg — schema (the storage contract of @okeav/idp-core 0.4).
|
|
2
|
+
--
|
|
3
|
+
-- Primary keys are application-generated UUIDs (crypto.randomUUID()), so no extension
|
|
4
|
+
-- (pgcrypto / uuid-ossp) is needed: some managed hosts restrict CREATE EXTENSION.
|
|
5
|
+
-- Requires PostgreSQL 14 or later.
|
|
6
|
+
--
|
|
7
|
+
-- Guarantees idp-core's security rests on are constraints here, not conventions:
|
|
8
|
+
-- * one account per email (blind index), one account per external identity
|
|
9
|
+
-- * one row per refresh-token hash, per authorization-code hash, per WebAuthn credential
|
|
10
|
+
-- * at most one live password-reset / magic link per user (idp_verification_tokens_one_link)
|
|
11
|
+
-- * deleting a user deletes everything that belongs to it (ON DELETE CASCADE)
|
|
12
|
+
|
|
13
|
+
CREATE TABLE idp_users (
|
|
14
|
+
id UUID PRIMARY KEY,
|
|
15
|
+
email TEXT NOT NULL,
|
|
16
|
+
-- HMAC of the normalised address (config.security.emailHashPepper): the lookup key.
|
|
17
|
+
email_hash TEXT NOT NULL UNIQUE,
|
|
18
|
+
password_hash TEXT,
|
|
19
|
+
status TEXT NOT NULL DEFAULT 'PENDING_VERIFICATION'
|
|
20
|
+
CHECK (status IN ('ACTIVE', 'DISABLED', 'INVITED', 'LOCKED', 'PENDING_VERIFICATION', 'SUSPENDED', 'DELETED')),
|
|
21
|
+
last_login_at TIMESTAMPTZ,
|
|
22
|
+
password_changed_at TIMESTAMPTZ,
|
|
23
|
+
-- "Revoke all sessions" counter (see idp-core's session-family.js): a counter, not a time, so the
|
|
24
|
+
-- comparison never depends on app-server clocks agreeing.
|
|
25
|
+
session_epoch INTEGER NOT NULL DEFAULT 0,
|
|
26
|
+
sessions_revoked_at TIMESTAMPTZ,
|
|
27
|
+
sessions_revoked_except_family TEXT,
|
|
28
|
+
registration_contested BOOLEAN NOT NULL DEFAULT false,
|
|
29
|
+
failed_login_attempts INTEGER NOT NULL DEFAULT 0,
|
|
30
|
+
lock_until TIMESTAMPTZ,
|
|
31
|
+
mfa_enabled BOOLEAN NOT NULL DEFAULT false,
|
|
32
|
+
mfa_secret TEXT,
|
|
33
|
+
mfa_temp_secret TEXT,
|
|
34
|
+
-- The last TOTP time step accepted: a code is never accepted twice (claimTotpStep).
|
|
35
|
+
mfa_last_totp_step BIGINT,
|
|
36
|
+
profile_first_name TEXT,
|
|
37
|
+
profile_last_name TEXT,
|
|
38
|
+
profile_display_name TEXT,
|
|
39
|
+
profile_avatar_url TEXT,
|
|
40
|
+
profile_locale TEXT NOT NULL DEFAULT 'en',
|
|
41
|
+
profile_zoneinfo TEXT,
|
|
42
|
+
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
43
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
44
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
45
|
+
);
|
|
46
|
+
CREATE INDEX idp_users_status_idx ON idp_users (status);
|
|
47
|
+
CREATE INDEX idp_users_created_idx ON idp_users (created_at, id);
|
|
48
|
+
|
|
49
|
+
CREATE TABLE idp_user_external_providers (
|
|
50
|
+
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
51
|
+
user_id UUID NOT NULL REFERENCES idp_users (id) ON DELETE CASCADE,
|
|
52
|
+
provider TEXT NOT NULL,
|
|
53
|
+
provider_id TEXT NOT NULL,
|
|
54
|
+
email TEXT,
|
|
55
|
+
connected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
56
|
+
UNIQUE (provider, provider_id)
|
|
57
|
+
);
|
|
58
|
+
CREATE INDEX idp_user_external_providers_user_idx ON idp_user_external_providers (user_id);
|
|
59
|
+
|
|
60
|
+
-- MFA recovery codes (HMACs), in the order they were issued.
|
|
61
|
+
CREATE TABLE idp_user_recovery_codes (
|
|
62
|
+
user_id UUID NOT NULL REFERENCES idp_users (id) ON DELETE CASCADE,
|
|
63
|
+
position SMALLINT NOT NULL,
|
|
64
|
+
code_hash TEXT NOT NULL,
|
|
65
|
+
used_at TIMESTAMPTZ,
|
|
66
|
+
PRIMARY KEY (user_id, position)
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
-- One row per refresh token: the authoritative session / revocation state.
|
|
70
|
+
CREATE TABLE idp_sessions (
|
|
71
|
+
id UUID PRIMARY KEY,
|
|
72
|
+
user_id UUID NOT NULL REFERENCES idp_users (id) ON DELETE CASCADE,
|
|
73
|
+
token_hash TEXT NOT NULL UNIQUE,
|
|
74
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
75
|
+
kid TEXT NOT NULL,
|
|
76
|
+
-- Equals the paired access token's jti (per-request session check).
|
|
77
|
+
jti TEXT NOT NULL,
|
|
78
|
+
revoked_at TIMESTAMPTZ,
|
|
79
|
+
-- 'rotated' marks a refresh token replaced by a refresh: that is how a replay is recognised.
|
|
80
|
+
revoke_reason TEXT,
|
|
81
|
+
-- Set on every row of a family revoked as a whole (reuse detected).
|
|
82
|
+
family_revoked_at TIMESTAMPTZ,
|
|
83
|
+
device_info TEXT,
|
|
84
|
+
device_fingerprint TEXT,
|
|
85
|
+
ip_address TEXT,
|
|
86
|
+
kind TEXT CHECK (kind IN ('first_party', 'oauth2')),
|
|
87
|
+
auth_time TIMESTAMPTZ,
|
|
88
|
+
family_id TEXT,
|
|
89
|
+
family_created_at TIMESTAMPTZ,
|
|
90
|
+
session_epoch INTEGER NOT NULL DEFAULT 0,
|
|
91
|
+
claims JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
92
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
93
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
94
|
+
);
|
|
95
|
+
CREATE INDEX idp_sessions_jti_idx ON idp_sessions (jti);
|
|
96
|
+
CREATE INDEX idp_sessions_user_live_idx ON idp_sessions (user_id, revoked_at, expires_at);
|
|
97
|
+
CREATE INDEX idp_sessions_user_created_idx ON idp_sessions (user_id, created_at DESC);
|
|
98
|
+
CREATE INDEX idp_sessions_family_idx ON idp_sessions (family_id) WHERE family_id IS NOT NULL;
|
|
99
|
+
CREATE INDEX idp_sessions_user_device_idx ON idp_sessions (user_id, device_fingerprint) WHERE device_fingerprint IS NOT NULL;
|
|
100
|
+
CREATE INDEX idp_sessions_client_live_idx ON idp_sessions ((claims ->> 'clientId')) WHERE revoked_at IS NULL;
|
|
101
|
+
CREATE INDEX idp_sessions_expires_idx ON idp_sessions (expires_at);
|
|
102
|
+
|
|
103
|
+
-- Write-only audit trail, one row per issued access token. Never read for authorization.
|
|
104
|
+
CREATE TABLE idp_access_token_audit (
|
|
105
|
+
id UUID PRIMARY KEY,
|
|
106
|
+
user_id UUID NOT NULL REFERENCES idp_users (id) ON DELETE CASCADE,
|
|
107
|
+
token_hash TEXT NOT NULL,
|
|
108
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
109
|
+
kid TEXT NOT NULL,
|
|
110
|
+
jti TEXT NOT NULL,
|
|
111
|
+
ip_address TEXT,
|
|
112
|
+
device_info TEXT,
|
|
113
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
114
|
+
);
|
|
115
|
+
CREATE INDEX idp_access_token_audit_user_idx ON idp_access_token_audit (user_id);
|
|
116
|
+
CREATE INDEX idp_access_token_audit_expires_idx ON idp_access_token_audit (expires_at);
|
|
117
|
+
|
|
118
|
+
CREATE TABLE idp_authorization_codes (
|
|
119
|
+
id UUID PRIMARY KEY,
|
|
120
|
+
-- The code's HMAC (named `code` like idp-core's field).
|
|
121
|
+
code TEXT NOT NULL UNIQUE,
|
|
122
|
+
client_id TEXT NOT NULL,
|
|
123
|
+
user_id UUID NOT NULL REFERENCES idp_users (id) ON DELETE CASCADE,
|
|
124
|
+
redirect_uri TEXT NOT NULL,
|
|
125
|
+
scopes TEXT[] NOT NULL DEFAULT '{}',
|
|
126
|
+
code_challenge TEXT,
|
|
127
|
+
code_challenge_method TEXT CHECK (code_challenge_method IN ('S256', 'plain')),
|
|
128
|
+
nonce TEXT,
|
|
129
|
+
auth_time TIMESTAMPTZ,
|
|
130
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
131
|
+
used BOOLEAN NOT NULL DEFAULT false,
|
|
132
|
+
used_at TIMESTAMPTZ,
|
|
133
|
+
-- The access-token session that authorized the code, the user's session epoch and the consent's
|
|
134
|
+
-- version at issue: a sign-out or consent change before redemption refuses the code.
|
|
135
|
+
session_jti TEXT,
|
|
136
|
+
session_epoch INTEGER NOT NULL DEFAULT 0,
|
|
137
|
+
consent_version INTEGER,
|
|
138
|
+
reuse_detected_at TIMESTAMPTZ,
|
|
139
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
140
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
141
|
+
);
|
|
142
|
+
CREATE INDEX idp_authorization_codes_expires_idx ON idp_authorization_codes (expires_at);
|
|
143
|
+
|
|
144
|
+
CREATE TABLE idp_consents (
|
|
145
|
+
id UUID PRIMARY KEY,
|
|
146
|
+
user_id UUID NOT NULL REFERENCES idp_users (id) ON DELETE CASCADE,
|
|
147
|
+
client_id TEXT NOT NULL,
|
|
148
|
+
scopes TEXT[] NOT NULL DEFAULT '{}',
|
|
149
|
+
granted_at TIMESTAMPTZ,
|
|
150
|
+
expires_at TIMESTAMPTZ,
|
|
151
|
+
revoked_at TIMESTAMPTZ,
|
|
152
|
+
is_revoked BOOLEAN NOT NULL DEFAULT false,
|
|
153
|
+
-- Incremented by every grant and revocation (a code carries the version it was issued under).
|
|
154
|
+
version INTEGER NOT NULL DEFAULT 0,
|
|
155
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
156
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
157
|
+
UNIQUE (user_id, client_id)
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
CREATE TABLE idp_oauth_clients (
|
|
161
|
+
id UUID PRIMARY KEY,
|
|
162
|
+
name TEXT NOT NULL,
|
|
163
|
+
slug TEXT NOT NULL UNIQUE,
|
|
164
|
+
client_id TEXT NOT NULL UNIQUE,
|
|
165
|
+
-- Never selected unless asked for ({ includeSecret: true }) — no query here uses SELECT *.
|
|
166
|
+
client_secret_hash TEXT NOT NULL,
|
|
167
|
+
client_type TEXT NOT NULL DEFAULT 'confidential' CHECK (client_type IN ('confidential', 'public')),
|
|
168
|
+
redirect_uris TEXT[] NOT NULL DEFAULT '{}',
|
|
169
|
+
post_logout_redirect_uris TEXT[] NOT NULL DEFAULT '{}',
|
|
170
|
+
allowed_scopes TEXT[] NOT NULL DEFAULT '{}',
|
|
171
|
+
allowed_grants TEXT[] NOT NULL DEFAULT '{}'
|
|
172
|
+
CHECK (allowed_grants <@ ARRAY['authorization_code', 'client_credentials', 'refresh_token']::TEXT[]),
|
|
173
|
+
access_token_ttl INTEGER NOT NULL DEFAULT 3600,
|
|
174
|
+
refresh_token_ttl INTEGER NOT NULL DEFAULT 2592000,
|
|
175
|
+
id_token_ttl INTEGER NOT NULL DEFAULT 3600,
|
|
176
|
+
logo_url TEXT,
|
|
177
|
+
website_url TEXT,
|
|
178
|
+
privacy_policy_url TEXT,
|
|
179
|
+
terms_of_service_url TEXT,
|
|
180
|
+
support_email TEXT,
|
|
181
|
+
status TEXT NOT NULL DEFAULT 'PENDING_APPROVAL' CHECK (status IN ('ACTIVE', 'INACTIVE', 'SUSPENDED', 'PENDING_APPROVAL')),
|
|
182
|
+
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
183
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
184
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
185
|
+
);
|
|
186
|
+
CREATE INDEX idp_oauth_clients_created_idx ON idp_oauth_clients (created_at, id);
|
|
187
|
+
|
|
188
|
+
CREATE TABLE idp_verification_tokens (
|
|
189
|
+
id UUID PRIMARY KEY,
|
|
190
|
+
kind TEXT NOT NULL CHECK (kind IN ('password_reset', 'email_verification', 'magic_link')),
|
|
191
|
+
user_id UUID NOT NULL REFERENCES idp_users (id) ON DELETE CASCADE,
|
|
192
|
+
token_hash TEXT NOT NULL,
|
|
193
|
+
-- email_verification only: the 6-digit code's HMAC (null once the per-address code cap is reached).
|
|
194
|
+
verification_code TEXT,
|
|
195
|
+
-- email_verification only: the password this registration activates.
|
|
196
|
+
password_hash TEXT,
|
|
197
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
198
|
+
used_at TIMESTAMPTZ,
|
|
199
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
200
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
201
|
+
);
|
|
202
|
+
CREATE INDEX idp_verification_tokens_hash_idx ON idp_verification_tokens (kind, token_hash);
|
|
203
|
+
CREATE INDEX idp_verification_tokens_user_idx ON idp_verification_tokens (user_id, kind);
|
|
204
|
+
CREATE INDEX idp_verification_tokens_expires_idx ON idp_verification_tokens (expires_at);
|
|
205
|
+
-- One live password-reset / magic link per user (replaceForUser). Email verification may have
|
|
206
|
+
-- several (one per competing registration).
|
|
207
|
+
CREATE UNIQUE INDEX idp_verification_tokens_one_link ON idp_verification_tokens (kind, user_id)
|
|
208
|
+
WHERE kind IN ('password_reset', 'magic_link');
|
|
209
|
+
|
|
210
|
+
-- Public halves of the service-mesh signing keys.
|
|
211
|
+
CREATE TABLE idp_service_keys (
|
|
212
|
+
id UUID PRIMARY KEY,
|
|
213
|
+
name TEXT NOT NULL,
|
|
214
|
+
kid TEXT NOT NULL UNIQUE,
|
|
215
|
+
public_key TEXT NOT NULL,
|
|
216
|
+
status TEXT NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'ROTATING', 'RETIRED', 'REVOKED')),
|
|
217
|
+
region TEXT NOT NULL DEFAULT 'global',
|
|
218
|
+
registered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
219
|
+
last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
220
|
+
-- Bounds how long a ROTATING key still verifies.
|
|
221
|
+
status_changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
222
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
223
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
224
|
+
);
|
|
225
|
+
CREATE INDEX idp_service_keys_status_idx ON idp_service_keys (status, name);
|
|
226
|
+
|
|
227
|
+
-- WebAuthn / passkey credentials.
|
|
228
|
+
CREATE TABLE idp_credentials (
|
|
229
|
+
id UUID PRIMARY KEY,
|
|
230
|
+
user_id UUID NOT NULL REFERENCES idp_users (id) ON DELETE CASCADE,
|
|
231
|
+
credential_id TEXT NOT NULL UNIQUE,
|
|
232
|
+
public_key TEXT NOT NULL,
|
|
233
|
+
counter BIGINT NOT NULL DEFAULT 0 CHECK (counter >= 0),
|
|
234
|
+
transports TEXT[] NOT NULL DEFAULT '{}',
|
|
235
|
+
device_type TEXT NOT NULL DEFAULT 'singleDevice' CHECK (device_type IN ('singleDevice', 'multiDevice')),
|
|
236
|
+
backed_up BOOLEAN NOT NULL DEFAULT false,
|
|
237
|
+
name TEXT,
|
|
238
|
+
last_used_at TIMESTAMPTZ,
|
|
239
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
240
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
241
|
+
);
|
|
242
|
+
CREATE INDEX idp_credentials_user_idx ON idp_credentials (user_id);
|
|
243
|
+
|
|
244
|
+
-- Fixed-window failure counters with a lock (MFA, password, verification-code budgets), shared by
|
|
245
|
+
-- every app instance. `expires_at`: when the row stops mattering (pruneExpired).
|
|
246
|
+
CREATE TABLE idp_attempt_counters (
|
|
247
|
+
key TEXT PRIMARY KEY,
|
|
248
|
+
count INTEGER NOT NULL,
|
|
249
|
+
window_expires_at TIMESTAMPTZ NOT NULL,
|
|
250
|
+
locked_until TIMESTAMPTZ,
|
|
251
|
+
expires_at TIMESTAMPTZ NOT NULL
|
|
252
|
+
);
|
|
253
|
+
CREATE INDEX idp_attempt_counters_expires_idx ON idp_attempt_counters (expires_at);
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { deleteInBatches } from '../db.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Fixed-window failure counters with a lock (MFA, password, verification-code budgets). Every method is
|
|
5
|
+
* one statement, and all time arithmetic uses the database's clock, so every app instance agrees on
|
|
6
|
+
* window and lock boundaries.
|
|
7
|
+
*
|
|
8
|
+
* @implements {import('../../interfaces.js').AttemptCounterRepository}
|
|
9
|
+
*/
|
|
10
|
+
export class PgAttemptCounterRepository {
|
|
11
|
+
constructor(pool) {
|
|
12
|
+
this.pool = pool;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async get(key) {
|
|
16
|
+
const { rows: [row] } = await this.pool.query(
|
|
17
|
+
'SELECT count, window_expires_at, locked_until FROM idp_attempt_counters WHERE key = $1',
|
|
18
|
+
[key],
|
|
19
|
+
);
|
|
20
|
+
return mapCounter(row);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Atomic: INSERT … ON CONFLICT DO UPDATE takes the row lock, so concurrent failures for one key are
|
|
25
|
+
* serialised and each sees a distinct count. A record starts over (count 1, new window, no lock) when
|
|
26
|
+
* its window has run out or a lock it had has expired — never while a lock is still active. Reaching
|
|
27
|
+
* `max` with no lock set locks it for `lockSeconds`. (In DO UPDATE, `c.` is the row before the update.)
|
|
28
|
+
*/
|
|
29
|
+
async recordFailure(key, { max, windowSeconds, lockSeconds }) {
|
|
30
|
+
const { rows: [row] } = await this.pool.query(
|
|
31
|
+
`INSERT INTO idp_attempt_counters AS c (key, count, window_expires_at, locked_until, expires_at)
|
|
32
|
+
VALUES ($1, 1, now() + make_interval(secs => $3),
|
|
33
|
+
CASE WHEN 1 >= $2 THEN now() + make_interval(secs => $4) END,
|
|
34
|
+
now() + make_interval(secs => GREATEST($3, $4)))
|
|
35
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
36
|
+
count = CASE WHEN ${FRESH} THEN 1 ELSE c.count + 1 END,
|
|
37
|
+
window_expires_at = CASE WHEN ${FRESH} THEN now() + make_interval(secs => $3) ELSE c.window_expires_at END,
|
|
38
|
+
locked_until = CASE
|
|
39
|
+
WHEN ${FRESH} THEN (CASE WHEN 1 >= $2 THEN now() + make_interval(secs => $4) END)
|
|
40
|
+
WHEN c.locked_until IS NULL AND c.count + 1 >= $2 THEN now() + make_interval(secs => $4)
|
|
41
|
+
ELSE c.locked_until
|
|
42
|
+
END,
|
|
43
|
+
expires_at = now() + make_interval(secs => GREATEST($3, $4))
|
|
44
|
+
RETURNING count, window_expires_at, locked_until`,
|
|
45
|
+
[key, max, windowSeconds, lockSeconds],
|
|
46
|
+
);
|
|
47
|
+
return mapCounter(row);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async reset(key) {
|
|
51
|
+
await this.pool.query('DELETE FROM idp_attempt_counters WHERE key = $1', [key]);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async pruneExpired() {
|
|
55
|
+
return deleteInBatches(this.pool, 'idp_attempt_counters', 'expires_at < now()');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** "Start over": no lock still active, and the window has ended or a (now expired) lock was set. */
|
|
60
|
+
const FRESH = `((c.locked_until IS NULL OR c.locked_until <= now()) AND (c.window_expires_at <= now() OR c.locked_until IS NOT NULL))`;
|
|
61
|
+
|
|
62
|
+
function mapCounter(row) {
|
|
63
|
+
if (!row) return null;
|
|
64
|
+
return { count: row.count, windowExpiresAt: row.window_expires_at, lockedUntil: row.locked_until };
|
|
65
|
+
}
|