@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,104 @@
|
|
|
1
|
+
import { newId, isUuid, columnFor, deleteInBatches } from '../db.js';
|
|
2
|
+
|
|
3
|
+
const COLUMNS = {
|
|
4
|
+
code: 'code',
|
|
5
|
+
clientId: 'client_id',
|
|
6
|
+
userId: 'user_id',
|
|
7
|
+
redirectUri: 'redirect_uri',
|
|
8
|
+
scopes: 'scopes',
|
|
9
|
+
codeChallenge: 'code_challenge',
|
|
10
|
+
codeChallengeMethod: 'code_challenge_method',
|
|
11
|
+
nonce: 'nonce',
|
|
12
|
+
authTime: 'auth_time',
|
|
13
|
+
expiresAt: 'expires_at',
|
|
14
|
+
sessionJti: 'session_jti',
|
|
15
|
+
sessionEpoch: 'session_epoch',
|
|
16
|
+
consentVersion: 'consent_version',
|
|
17
|
+
used: 'used',
|
|
18
|
+
usedAt: 'used_at',
|
|
19
|
+
reuseDetectedAt: 'reuse_detected_at',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** @implements {import('../../interfaces.js').AuthorizationCodeRepository} */
|
|
23
|
+
export class PgAuthorizationCodeRepository {
|
|
24
|
+
constructor(pool) {
|
|
25
|
+
this.pool = pool;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async create(input) {
|
|
29
|
+
if (!isUuid(input.userId)) throw new Error('@okeav/idp-pg: an authorization code needs a user id');
|
|
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_authorization_codes'));
|
|
35
|
+
values.push(value);
|
|
36
|
+
}
|
|
37
|
+
await this.pool.query(
|
|
38
|
+
`INSERT INTO idp_authorization_codes (${columns.join(', ')}) VALUES (${columns.map((_, i) => `$${i + 1}`).join(', ')})`,
|
|
39
|
+
values,
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Atomic find + mark used: a code is exchanged exactly once, even by concurrent requests. */
|
|
44
|
+
async consumeByCodeHash(hash) {
|
|
45
|
+
if (!hash) return null;
|
|
46
|
+
const now = new Date();
|
|
47
|
+
const { rows: [row] } = await this.pool.query(
|
|
48
|
+
`UPDATE idp_authorization_codes SET used = true, used_at = $2, updated_at = now()
|
|
49
|
+
WHERE code = $1 AND used = false AND expires_at > $2 RETURNING *`,
|
|
50
|
+
[hash, now],
|
|
51
|
+
);
|
|
52
|
+
return mapCode(row);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A code already redeemed (reuse detection). Null for an unknown or unused code. */
|
|
56
|
+
async findUsedByCodeHash(hash) {
|
|
57
|
+
if (!hash) return null;
|
|
58
|
+
const { rows: [row] } = await this.pool.query('SELECT * FROM idp_authorization_codes WHERE code = $1 AND used = true', [hash]);
|
|
59
|
+
return mapCode(row);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Flags a redeemed code as presented again — read back by the redemption still in flight. */
|
|
63
|
+
async markReused(hash) {
|
|
64
|
+
if (!hash) return;
|
|
65
|
+
await this.pool.query(
|
|
66
|
+
'UPDATE idp_authorization_codes SET reuse_detected_at = $2, updated_at = now() WHERE code = $1 AND used = true',
|
|
67
|
+
[hash, new Date()],
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Deletes expired codes. A redeemed code is kept until it expires (reuse detection reads it), and
|
|
73
|
+
* one flagged as reused a while longer — at least an hour past expiry.
|
|
74
|
+
*/
|
|
75
|
+
async pruneExpired() {
|
|
76
|
+
return deleteInBatches(this.pool, 'idp_authorization_codes',
|
|
77
|
+
`expires_at < $1 AND (reuse_detected_at IS NULL OR expires_at < $1 - interval '1 hour')`, [new Date()]);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function mapCode(row) {
|
|
82
|
+
if (!row) return null;
|
|
83
|
+
return {
|
|
84
|
+
id: row.id,
|
|
85
|
+
code: row.code,
|
|
86
|
+
clientId: row.client_id,
|
|
87
|
+
userId: row.user_id,
|
|
88
|
+
redirectUri: row.redirect_uri,
|
|
89
|
+
scopes: row.scopes ?? [],
|
|
90
|
+
codeChallenge: row.code_challenge,
|
|
91
|
+
codeChallengeMethod: row.code_challenge_method,
|
|
92
|
+
nonce: row.nonce,
|
|
93
|
+
authTime: row.auth_time,
|
|
94
|
+
expiresAt: row.expires_at,
|
|
95
|
+
used: row.used,
|
|
96
|
+
usedAt: row.used_at,
|
|
97
|
+
sessionJti: row.session_jti,
|
|
98
|
+
sessionEpoch: row.session_epoch,
|
|
99
|
+
consentVersion: row.consent_version,
|
|
100
|
+
reuseDetectedAt: row.reuse_detected_at,
|
|
101
|
+
createdAt: row.created_at,
|
|
102
|
+
updatedAt: row.updated_at,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { newId, isUuid } from '../db.js';
|
|
2
|
+
|
|
3
|
+
/** @implements {import('../../interfaces.js').ConsentRepository} */
|
|
4
|
+
export class PgConsentRepository {
|
|
5
|
+
constructor(pool) {
|
|
6
|
+
this.pool = pool;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Grants (or re-grants) consent; every grant increments `version`. Resolves the consent after the write. */
|
|
10
|
+
async upsert(userId, clientId, scopes) {
|
|
11
|
+
if (!isUuid(userId)) throw new Error('@okeav/idp-pg: a consent needs a user id');
|
|
12
|
+
const { rows: [row] } = await this.pool.query(
|
|
13
|
+
`INSERT INTO idp_consents (id, user_id, client_id, scopes, granted_at, version)
|
|
14
|
+
VALUES ($1, $2, $3, $4, $5, 1)
|
|
15
|
+
ON CONFLICT (user_id, client_id) DO UPDATE SET
|
|
16
|
+
scopes = EXCLUDED.scopes, granted_at = EXCLUDED.granted_at, is_revoked = false, revoked_at = NULL,
|
|
17
|
+
version = idp_consents.version + 1, updated_at = now()
|
|
18
|
+
RETURNING *`,
|
|
19
|
+
[newId(), userId, clientId, scopes ?? [], new Date()],
|
|
20
|
+
);
|
|
21
|
+
return mapConsent(row);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async find(userId, clientId) {
|
|
25
|
+
if (!isUuid(userId)) return null;
|
|
26
|
+
const { rows: [row] } = await this.pool.query(
|
|
27
|
+
'SELECT * FROM idp_consents WHERE user_id = $1 AND client_id = $2 AND is_revoked = false',
|
|
28
|
+
[userId, clientId],
|
|
29
|
+
);
|
|
30
|
+
return mapConsent(row);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async listForUser(userId) {
|
|
34
|
+
if (!isUuid(userId)) return [];
|
|
35
|
+
const { rows } = await this.pool.query(
|
|
36
|
+
'SELECT * FROM idp_consents WHERE user_id = $1 AND is_revoked = false AND revoked_at IS NULL ORDER BY granted_at DESC',
|
|
37
|
+
[userId],
|
|
38
|
+
);
|
|
39
|
+
return rows.map(mapConsent);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Revokes consent; increments `version`, so a code issued under the old consent is refused. */
|
|
43
|
+
async revoke(userId, clientId) {
|
|
44
|
+
if (!isUuid(userId)) return;
|
|
45
|
+
await this.pool.query(
|
|
46
|
+
`UPDATE idp_consents SET is_revoked = true, revoked_at = $3, version = version + 1, updated_at = now()
|
|
47
|
+
WHERE user_id = $1 AND client_id = $2`,
|
|
48
|
+
[userId, clientId, new Date()],
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function mapConsent(row) {
|
|
54
|
+
if (!row) return null;
|
|
55
|
+
return {
|
|
56
|
+
id: row.id,
|
|
57
|
+
userId: row.user_id,
|
|
58
|
+
clientId: row.client_id,
|
|
59
|
+
scopes: row.scopes ?? [],
|
|
60
|
+
grantedAt: row.granted_at,
|
|
61
|
+
expiresAt: row.expires_at,
|
|
62
|
+
revokedAt: row.revoked_at,
|
|
63
|
+
isRevoked: row.is_revoked,
|
|
64
|
+
version: row.version,
|
|
65
|
+
createdAt: row.created_at,
|
|
66
|
+
updatedAt: row.updated_at,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { newId, isUuid } from '../db.js';
|
|
2
|
+
|
|
3
|
+
/** WebAuthn / passkey credentials. @implements {import('../../interfaces.js').CredentialRepository} */
|
|
4
|
+
export class PgCredentialRepository {
|
|
5
|
+
constructor(pool) {
|
|
6
|
+
this.pool = pool;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async create({ userId, credentialId, publicKey, counter = 0, transports = [], deviceType = 'singleDevice', backedUp = false, name = null }) {
|
|
10
|
+
if (!isUuid(userId)) throw new Error('@okeav/idp-pg: a credential needs a user id');
|
|
11
|
+
const { rows: [row] } = await this.pool.query(
|
|
12
|
+
`INSERT INTO idp_credentials (id, user_id, credential_id, public_key, counter, transports, device_type, backed_up, name)
|
|
13
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *`,
|
|
14
|
+
[newId(), userId, credentialId, publicKey, counter ?? 0, transports ?? [], deviceType ?? 'singleDevice', Boolean(backedUp), name ?? null],
|
|
15
|
+
);
|
|
16
|
+
return mapCredential(row);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async findByCredentialId(credentialId) {
|
|
20
|
+
if (!credentialId) return null;
|
|
21
|
+
const { rows: [row] } = await this.pool.query('SELECT * FROM idp_credentials WHERE credential_id = $1', [credentialId]);
|
|
22
|
+
return mapCredential(row);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async findByUserId(userId) {
|
|
26
|
+
if (!isUuid(userId)) return [];
|
|
27
|
+
const { rows } = await this.pool.query('SELECT * FROM idp_credentials WHERE user_id = $1 ORDER BY created_at, id', [userId]);
|
|
28
|
+
return rows.map(mapCredential);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Stores the authenticator's new signature counter only if it moved forward (an authenticator without
|
|
33
|
+
* a counter reports 0 every time, which may stay 0). Atomic: of two concurrent uses of one signed
|
|
34
|
+
* assertion only one gets through. Resolves whether this call did.
|
|
35
|
+
*/
|
|
36
|
+
async updateCounter(credentialId, newCounter) {
|
|
37
|
+
const { rowCount } = await this.pool.query(
|
|
38
|
+
`UPDATE idp_credentials SET counter = $2, last_used_at = $3, updated_at = now()
|
|
39
|
+
WHERE credential_id = $1 AND (CASE WHEN $2::bigint > 0 THEN counter < $2::bigint ELSE counter = 0 END)`,
|
|
40
|
+
[credentialId, newCounter, new Date()],
|
|
41
|
+
);
|
|
42
|
+
return rowCount === 1;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Scoped to the owner. Resolves whether a credential was deleted. */
|
|
46
|
+
async deleteByCredentialId(credentialId, userId) {
|
|
47
|
+
if (!isUuid(userId)) return false;
|
|
48
|
+
const { rowCount } = await this.pool.query('DELETE FROM idp_credentials WHERE credential_id = $1 AND user_id = $2', [credentialId, userId]);
|
|
49
|
+
return rowCount === 1;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async countForUser(userId) {
|
|
53
|
+
if (!isUuid(userId)) return 0;
|
|
54
|
+
const { rows: [{ count }] } = await this.pool.query('SELECT count(*)::int AS count FROM idp_credentials WHERE user_id = $1', [userId]);
|
|
55
|
+
return count;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function mapCredential(row) {
|
|
60
|
+
if (!row) return null;
|
|
61
|
+
return {
|
|
62
|
+
id: row.id,
|
|
63
|
+
user: row.user_id,
|
|
64
|
+
credentialId: row.credential_id,
|
|
65
|
+
publicKey: row.public_key,
|
|
66
|
+
counter: Number(row.counter),
|
|
67
|
+
transports: row.transports ?? [],
|
|
68
|
+
deviceType: row.device_type,
|
|
69
|
+
backedUp: row.backed_up,
|
|
70
|
+
name: row.name,
|
|
71
|
+
lastUsedAt: row.last_used_at,
|
|
72
|
+
createdAt: row.created_at,
|
|
73
|
+
updatedAt: row.updated_at,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { newId, setClauses, columnFor } from '../db.js';
|
|
2
|
+
|
|
3
|
+
const COLUMNS = {
|
|
4
|
+
name: 'name',
|
|
5
|
+
slug: 'slug',
|
|
6
|
+
clientId: 'client_id',
|
|
7
|
+
clientSecretHash: 'client_secret_hash',
|
|
8
|
+
clientType: 'client_type',
|
|
9
|
+
redirectUris: 'redirect_uris',
|
|
10
|
+
postLogoutRedirectUris: 'post_logout_redirect_uris',
|
|
11
|
+
allowedScopes: 'allowed_scopes',
|
|
12
|
+
allowedGrants: 'allowed_grants',
|
|
13
|
+
accessTokenTTL: 'access_token_ttl',
|
|
14
|
+
refreshTokenTTL: 'refresh_token_ttl',
|
|
15
|
+
idTokenTTL: 'id_token_ttl',
|
|
16
|
+
logoUrl: 'logo_url',
|
|
17
|
+
websiteUrl: 'website_url',
|
|
18
|
+
privacyPolicyUrl: 'privacy_policy_url',
|
|
19
|
+
termsOfServiceUrl: 'terms_of_service_url',
|
|
20
|
+
supportEmail: 'support_email',
|
|
21
|
+
status: 'status',
|
|
22
|
+
metadata: 'metadata',
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Every column but the secret's hash: no query here selects that unless asked (no SELECT *). */
|
|
26
|
+
const PUBLIC_COLUMNS = ['id', 'created_at', 'updated_at', ...Object.values(COLUMNS).filter((c) => c !== 'client_secret_hash')].join(', ');
|
|
27
|
+
|
|
28
|
+
/** @implements {import('../../interfaces.js').OAuthClientRepository} */
|
|
29
|
+
export class PgOAuthClientRepository {
|
|
30
|
+
constructor(pool) {
|
|
31
|
+
this.pool = pool;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async create(input) {
|
|
35
|
+
const columns = ['id'];
|
|
36
|
+
const values = [newId()];
|
|
37
|
+
for (const [key, value] of Object.entries(input)) {
|
|
38
|
+
if (value === undefined) continue;
|
|
39
|
+
columns.push(columnFor(COLUMNS, key, 'idp_oauth_clients'));
|
|
40
|
+
values.push(encode(key, value));
|
|
41
|
+
}
|
|
42
|
+
const { rows: [row] } = await this.pool.query(
|
|
43
|
+
`INSERT INTO idp_oauth_clients (${columns.join(', ')}) VALUES (${columns.map((_, i) => `$${i + 1}`).join(', ')}) RETURNING ${PUBLIC_COLUMNS}`,
|
|
44
|
+
values,
|
|
45
|
+
);
|
|
46
|
+
return mapClient(row);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async findByClientId(clientId, { includeSecret = false } = {}) {
|
|
50
|
+
if (!clientId) return null;
|
|
51
|
+
const { rows: [row] } = await this.pool.query(
|
|
52
|
+
`SELECT ${PUBLIC_COLUMNS}${includeSecret ? ', client_secret_hash' : ''} FROM idp_oauth_clients WHERE client_id = $1`,
|
|
53
|
+
[clientId],
|
|
54
|
+
);
|
|
55
|
+
return mapClient(row);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async findBySlug(slug) {
|
|
59
|
+
if (!slug) return null;
|
|
60
|
+
const { rows: [row] } = await this.pool.query(`SELECT ${PUBLIC_COLUMNS} FROM idp_oauth_clients WHERE slug = $1`, [slug]);
|
|
61
|
+
return mapClient(row);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async updateByClientId(clientId, patch) {
|
|
65
|
+
if (!clientId) return null;
|
|
66
|
+
const { sets, values } = setClauses(patch, COLUMNS, 'idp_oauth_clients', 1, encode);
|
|
67
|
+
const { rows: [row] } = await this.pool.query(
|
|
68
|
+
`UPDATE idp_oauth_clients SET ${[...sets, 'updated_at = now()'].join(', ')} WHERE client_id = $1 RETURNING ${PUBLIC_COLUMNS}`,
|
|
69
|
+
[clientId, ...values],
|
|
70
|
+
);
|
|
71
|
+
return mapClient(row);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async listMany({ skip = 0, limit = 20 } = {}) {
|
|
75
|
+
const { rows } = await this.pool.query(
|
|
76
|
+
`SELECT ${PUBLIC_COLUMNS} FROM idp_oauth_clients ORDER BY created_at, id OFFSET $1 LIMIT $2`,
|
|
77
|
+
[skip, limit],
|
|
78
|
+
);
|
|
79
|
+
return rows.map(mapClient);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async countAll() {
|
|
83
|
+
const { rows: [{ count }] } = await this.pool.query('SELECT count(*)::int AS count FROM idp_oauth_clients');
|
|
84
|
+
return count;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Normalised as idp-core's Mongo model does: names trimmed, slugs trimmed and lower-cased. */
|
|
89
|
+
function encode(key, value) {
|
|
90
|
+
if (key === 'metadata') return JSON.stringify(value ?? {});
|
|
91
|
+
if (key === 'name' && typeof value === 'string') return value.trim();
|
|
92
|
+
if (key === 'slug' && typeof value === 'string') return value.trim().toLowerCase();
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function mapClient(row) {
|
|
97
|
+
if (!row) return null;
|
|
98
|
+
return {
|
|
99
|
+
id: row.id,
|
|
100
|
+
name: row.name,
|
|
101
|
+
slug: row.slug,
|
|
102
|
+
clientId: row.client_id,
|
|
103
|
+
...(row.client_secret_hash !== undefined ? { clientSecretHash: row.client_secret_hash } : {}),
|
|
104
|
+
clientType: row.client_type,
|
|
105
|
+
redirectUris: row.redirect_uris ?? [],
|
|
106
|
+
postLogoutRedirectUris: row.post_logout_redirect_uris ?? [],
|
|
107
|
+
allowedScopes: row.allowed_scopes ?? [],
|
|
108
|
+
allowedGrants: row.allowed_grants ?? [],
|
|
109
|
+
accessTokenTTL: row.access_token_ttl,
|
|
110
|
+
refreshTokenTTL: row.refresh_token_ttl,
|
|
111
|
+
idTokenTTL: row.id_token_ttl,
|
|
112
|
+
logoUrl: row.logo_url,
|
|
113
|
+
websiteUrl: row.website_url,
|
|
114
|
+
privacyPolicyUrl: row.privacy_policy_url,
|
|
115
|
+
termsOfServiceUrl: row.terms_of_service_url,
|
|
116
|
+
supportEmail: row.support_email,
|
|
117
|
+
status: row.status,
|
|
118
|
+
metadata: row.metadata ?? {},
|
|
119
|
+
createdAt: row.created_at,
|
|
120
|
+
updatedAt: row.updated_at,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { newId } from '../db.js';
|
|
2
|
+
|
|
3
|
+
const PUBLISHABLE = ['ACTIVE', 'ROTATING'];
|
|
4
|
+
|
|
5
|
+
/** @implements {import('../../interfaces.js').ServiceKeyRepository} */
|
|
6
|
+
export class PgServiceKeyRepository {
|
|
7
|
+
constructor(pool) {
|
|
8
|
+
this.pool = pool;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Idempotent upsert by kid — re-registering just refreshes it. A REVOKED kid is never brought back:
|
|
13
|
+
* resolves null and changes nothing (every service re-registers at boot; a revoked key must stay
|
|
14
|
+
* revoked). Times are the database's clock at the moment of the write, so `registeredAt` orders
|
|
15
|
+
* concurrent first registrations of a name the way the inserts actually happened.
|
|
16
|
+
*/
|
|
17
|
+
async upsertByKid({ kid, name, publicKey, region }) {
|
|
18
|
+
const { rows: [row] } = await this.pool.query(
|
|
19
|
+
`INSERT INTO idp_service_keys (id, kid, name, public_key, status, region, registered_at, last_seen_at, status_changed_at)
|
|
20
|
+
VALUES ($1, $2, $3, $4, 'ACTIVE', $5, clock_timestamp(), clock_timestamp(), clock_timestamp())
|
|
21
|
+
ON CONFLICT (kid) DO UPDATE SET
|
|
22
|
+
name = EXCLUDED.name, public_key = EXCLUDED.public_key, status = 'ACTIVE', region = EXCLUDED.region,
|
|
23
|
+
last_seen_at = clock_timestamp(), status_changed_at = clock_timestamp(), updated_at = now()
|
|
24
|
+
WHERE idp_service_keys.status <> 'REVOKED'
|
|
25
|
+
RETURNING *`,
|
|
26
|
+
[newId(), kid, name, publicKey, region || 'global'],
|
|
27
|
+
);
|
|
28
|
+
return mapKey(row);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One key by kid, whatever its status. */
|
|
32
|
+
async findByKid(kid) {
|
|
33
|
+
if (!kid) return null;
|
|
34
|
+
const { rows: [row] } = await this.pool.query('SELECT * FROM idp_service_keys WHERE kid = $1', [kid]);
|
|
35
|
+
return mapKey(row);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One publishable key by kid — an indexed read for verification. */
|
|
39
|
+
async findPublishableByKid(kid) {
|
|
40
|
+
if (!kid) return null;
|
|
41
|
+
const { rows: [row] } = await this.pool.query('SELECT * FROM idp_service_keys WHERE kid = $1 AND status = ANY($2)', [kid, PUBLISHABLE]);
|
|
42
|
+
return mapKey(row);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Sets a key's status; with `expectedStatus`, only from that status (atomically). Null if nothing changed. */
|
|
46
|
+
async setStatusByKid(kid, status, { expectedStatus } = {}) {
|
|
47
|
+
const { rows: [row] } = await this.pool.query(
|
|
48
|
+
`UPDATE idp_service_keys SET status = $2, status_changed_at = $3, updated_at = now()
|
|
49
|
+
WHERE kid = $1 AND ($4::text IS NULL OR status = $4) RETURNING *`,
|
|
50
|
+
[kid, status, new Date(), expectedStatus ?? null],
|
|
51
|
+
);
|
|
52
|
+
return mapKey(row);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async listPublishable() {
|
|
56
|
+
const { rows } = await this.pool.query('SELECT * FROM idp_service_keys WHERE status = ANY($1) ORDER BY registered_at, kid', [PUBLISHABLE]);
|
|
57
|
+
return rows.map(mapKey);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function mapKey(row) {
|
|
62
|
+
if (!row) return null;
|
|
63
|
+
return {
|
|
64
|
+
id: row.id,
|
|
65
|
+
name: row.name,
|
|
66
|
+
kid: row.kid,
|
|
67
|
+
publicKey: row.public_key,
|
|
68
|
+
status: row.status,
|
|
69
|
+
region: row.region,
|
|
70
|
+
registeredAt: row.registered_at,
|
|
71
|
+
lastSeenAt: row.last_seen_at,
|
|
72
|
+
statusChangedAt: row.status_changed_at,
|
|
73
|
+
createdAt: row.created_at,
|
|
74
|
+
updatedAt: row.updated_at,
|
|
75
|
+
};
|
|
76
|
+
}
|