@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
package/.env.example
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# ── Core ──────────────────────────────────────────────────────────────────
|
|
2
|
+
IDP_ISSUER=https://idp.example.com
|
|
3
|
+
|
|
4
|
+
# ── PostgreSQL (required) ─────────────────────────────────────────────────
|
|
5
|
+
# PostgreSQL 14+. Use sslmode=verify-full for anything not on localhost.
|
|
6
|
+
IDP_DATABASE_URL=postgres://idp:change-me@localhost:5432/idp
|
|
7
|
+
# verify (default: refuse to start on an out-of-date schema) | apply (migrate at startup) | skip
|
|
8
|
+
IDP_PG_MIGRATIONS=verify
|
|
9
|
+
# Expired sessions / codes / tokens / counters are deleted this often (0 = off).
|
|
10
|
+
IDP_PG_PRUNE_INTERVAL_SECONDS=3600
|
|
11
|
+
# pg pool size per instance.
|
|
12
|
+
IDP_PG_POOL_MAX=10
|
|
13
|
+
|
|
14
|
+
# ── Cache (optional — defaults to in-memory, single-instance only) ──────
|
|
15
|
+
# Set to "redis" for production / multi-instance deployments.
|
|
16
|
+
IDP_CACHE_ADAPTER=memory
|
|
17
|
+
IDP_REDIS_HOST=localhost
|
|
18
|
+
IDP_REDIS_PORT=6379
|
|
19
|
+
IDP_REDIS_USERNAME=
|
|
20
|
+
IDP_REDIS_PASSWORD=
|
|
21
|
+
# true for managed / non-local Redis.
|
|
22
|
+
IDP_REDIS_TLS=false
|
|
23
|
+
IDP_CACHE_KEY_PREFIX=idp:
|
|
24
|
+
|
|
25
|
+
# ── Signing keys (RS256). Accepts raw PEM or base64-encoded PEM ─────────
|
|
26
|
+
IDP_SIGNING_KEY_CURRENT_KID=change-me-uuid
|
|
27
|
+
IDP_SIGNING_KEY_CURRENT_PRIVATE_B64=
|
|
28
|
+
IDP_SIGNING_KEY_CURRENT_PUBLIC_B64=
|
|
29
|
+
IDP_SIGNING_KEY_PREVIOUS_KID=
|
|
30
|
+
IDP_SIGNING_KEY_PREVIOUS_PRIVATE_B64=
|
|
31
|
+
IDP_SIGNING_KEY_PREVIOUS_PUBLIC_B64=
|
|
32
|
+
|
|
33
|
+
# ── Cookies ───────────────────────────────────────────────────────────────
|
|
34
|
+
IDP_COOKIE_SECURE=true
|
|
35
|
+
IDP_COOKIE_SAME_SITE=lax
|
|
36
|
+
IDP_COOKIE_DOMAIN=
|
|
37
|
+
# Origins of your frontends that make cookie-authenticated requests (comma-separated). Cookie
|
|
38
|
+
# requests from any other origin are refused (CSRF). The issuer's own origin is always trusted.
|
|
39
|
+
IDP_COOKIE_TRUSTED_ORIGINS=
|
|
40
|
+
# auto (default): the refresh token is in JSON bodies only for non-browser clients — a browser
|
|
41
|
+
# request (Origin / Sec-Fetch-Site) gets it only as the httpOnly cookie. true: always. false: never.
|
|
42
|
+
IDP_COOKIE_REFRESH_TOKEN_IN_BODY=auto
|
|
43
|
+
|
|
44
|
+
# ── Security policy ───────────────────────────────────────────────────────
|
|
45
|
+
IDP_MAX_FAILED_LOGIN_ATTEMPTS=5
|
|
46
|
+
IDP_ACCOUNT_LOCK_DURATION_MS=1800000
|
|
47
|
+
IDP_BCRYPT_ROUNDS=12
|
|
48
|
+
# Blind-index pepper for email lookups. Non-rotating, back it up carefully —
|
|
49
|
+
# rotating it invalidates every existing user's email lookup hash.
|
|
50
|
+
# At least 32 random characters — `openssl rand -base64 48`.
|
|
51
|
+
IDP_EMAIL_HASH_PEPPER=
|
|
52
|
+
# Keys the hashes of refresh tokens, codes, links, recovery codes and client secrets at rest (a key per
|
|
53
|
+
# purpose is derived from it). At least 32 random characters, different from the pepper.
|
|
54
|
+
IDP_TOKEN_HASH_SECRET=
|
|
55
|
+
# Rotation: when you replace IDP_TOKEN_HASH_SECRET, move the old value here (comma-separated, newest
|
|
56
|
+
# first) so what was hashed under it still verifies — see docs/api/bootstrap-config.md.
|
|
57
|
+
IDP_PREVIOUS_TOKEN_HASH_SECRETS=
|
|
58
|
+
|
|
59
|
+
# ── MFA ────────────────────────────────────────────────────────────────────
|
|
60
|
+
IDP_MFA_ISSUER_LABEL=MyApp
|
|
61
|
+
IDP_MFA_RECOVERY_CODE_COUNT=10
|
|
62
|
+
# REQUIRED while MFA is enabled (the default): encrypts TOTP secrets at rest
|
|
63
|
+
# with AES-256-GCM. 32 random bytes, base64 — `openssl rand -base64 32`.
|
|
64
|
+
IDP_MFA_ENCRYPTION_KEY=
|
|
65
|
+
# Rotation: when you replace IDP_MFA_ENCRYPTION_KEY, move the old value here
|
|
66
|
+
# (comma-separated) so existing secrets still decrypt until re-encrypted.
|
|
67
|
+
IDP_MFA_PREVIOUS_ENCRYPTION_KEYS=
|
|
68
|
+
# Set false if this deployment doesn't use TOTP MFA at all (no key needed then).
|
|
69
|
+
IDP_MFA_ENABLED=true
|
|
70
|
+
# Refuse any secret still stored in plain text. Unset: true whenever a key is configured. Set false
|
|
71
|
+
# only while legacy plain-text secrets remain (run migrateMfaSecrets()).
|
|
72
|
+
IDP_MFA_REQUIRE_ENCRYPTED=
|
|
73
|
+
# Local development ONLY: store TOTP secrets unencrypted when no key is set.
|
|
74
|
+
IDP_MFA_ALLOW_PLAINTEXT=false
|
|
75
|
+
|
|
76
|
+
# ── Sessions ───────────────────────────────────────────────────────────────
|
|
77
|
+
# Check the token's session row on every authenticated request (one indexed
|
|
78
|
+
# lookup) so logout-all / password reset revoke access tokens on every
|
|
79
|
+
# instance immediately. Turning this off leaves them valid until they expire.
|
|
80
|
+
IDP_SESSION_VERIFY_ON_EACH_REQUEST=true
|
|
81
|
+
|
|
82
|
+
# ── OIDC ───────────────────────────────────────────────────────────────────
|
|
83
|
+
# Your "sign out?" page for RP-initiated logout. When set, a GET /session/end that needs the user's
|
|
84
|
+
# confirmation redirects here (forwarding client_id, state, ui_locales and logout_hint, never over a
|
|
85
|
+
# parameter already in this URL); the page POSTs them back to /session/end.
|
|
86
|
+
# https (http only for localhost), on the issuer's origin or one of IDP_COOKIE_TRUSTED_ORIGINS.
|
|
87
|
+
# Unset: that GET answers { "action": "logout_confirmation_required" }.
|
|
88
|
+
IDP_OIDC_END_SESSION_CONFIRMATION_URL=
|
|
89
|
+
|
|
90
|
+
# ── Clock skew ─────────────────────────────────────────────────────────────
|
|
91
|
+
# Token, code and lockout lifetimes use this server's clock, so it is checked against the
|
|
92
|
+
# database's: startup fails past the maximum (later checks log an error), a warning is logged past
|
|
93
|
+
# the warning level. Keep servers on NTP.
|
|
94
|
+
IDP_CLOCK_MAX_SKEW_SECONDS=30
|
|
95
|
+
IDP_CLOCK_WARN_SKEW_SECONDS=2
|
|
96
|
+
# How often the skew is re-measured (minimum 10).
|
|
97
|
+
IDP_CLOCK_CHECK_INTERVAL_SECONDS=600
|
|
98
|
+
|
|
99
|
+
# ── OAuth providers (omit any you don't use) ─────────────────────────────
|
|
100
|
+
IDP_SSO_GOOGLE_CLIENT_ID=
|
|
101
|
+
IDP_SSO_GOOGLE_CLIENT_SECRET=
|
|
102
|
+
IDP_SSO_MICROSOFT_CLIENT_ID=
|
|
103
|
+
IDP_SSO_MICROSOFT_CLIENT_SECRET=
|
|
104
|
+
# "common" (any Microsoft account) means account emails are NOT trusted for linking/sign-up —
|
|
105
|
+
# pin your own tenant ID here, or set IDP_SSO_MICROSOFT_TRUST_EMAIL=true knowingly.
|
|
106
|
+
IDP_SSO_MICROSOFT_TENANT=common
|
|
107
|
+
IDP_SSO_MICROSOFT_TRUST_EMAIL=false
|
|
108
|
+
IDP_SSO_GITHUB_CLIENT_ID=
|
|
109
|
+
IDP_SSO_GITHUB_CLIENT_SECRET=
|
|
110
|
+
IDP_SSO_APPLE_CLIENT_ID=
|
|
111
|
+
IDP_SSO_APPLE_TEAM_ID=
|
|
112
|
+
IDP_SSO_APPLE_KEY_ID=
|
|
113
|
+
IDP_SSO_APPLE_PRIVATE_KEY_B64=
|
|
114
|
+
IDP_SSO_LINKEDIN_CLIENT_ID=
|
|
115
|
+
IDP_SSO_LINKEDIN_CLIENT_SECRET=
|
|
116
|
+
# Required as soon as any provider above is set:
|
|
117
|
+
# absolute base URL providers redirect back to (<base>/sso/<provider>/callback)…
|
|
118
|
+
IDP_SSO_BASE_CALLBACK_URL=
|
|
119
|
+
# …and the origins SSO may send the browser back to (comma-separated, exact origins).
|
|
120
|
+
IDP_SSO_ALLOWED_REDIRECT_ORIGINS=
|
|
121
|
+
|
|
122
|
+
# ── Service mesh (optional — S2S / JWKS trust feature) ───────────────────
|
|
123
|
+
# Preferred: one registration secret per service — name=secret pairs, comma-separated.
|
|
124
|
+
IDP_S2S_BOOTSTRAP_SECRETS=
|
|
125
|
+
# Legacy shared secret: can register a new service name, never replace an existing service's key.
|
|
126
|
+
IDP_S2S_BOOTSTRAP_SECRET=
|
|
127
|
+
# token (default) | both | secret — "both"/"secret" accept an unverified x-service-name.
|
|
128
|
+
IDP_S2S_TOKEN_MODE=token
|
|
129
|
+
# This service's own name (the `aud` it expects on inbound service tokens).
|
|
130
|
+
IDP_S2S_OWN_SERVICE_NAME=
|
|
131
|
+
|
|
132
|
+
# ── Rate limiting (enabled by default) ───────────────────────────────────
|
|
133
|
+
# Per-rule thresholds (login/passwordReset/mfaChallenge/refreshToken/magicLink)
|
|
134
|
+
# have sensible defaults — see README "Rate limiting" — and are only
|
|
135
|
+
# overridable via code config, not env vars. Set to "redis" to reuse the
|
|
136
|
+
# cache adapter's Redis connection (if IDP_CACHE_ADAPTER=redis) automatically.
|
|
137
|
+
IDP_RATE_LIMIT_ENABLED=true
|
|
138
|
+
IDP_RATE_LIMIT_ADAPTER=memory
|
|
139
|
+
|
|
140
|
+
# ── Magic link (passwordless email login) ────────────────────────────────
|
|
141
|
+
# Set to false for invite-only apps — an unrecognized email then silently
|
|
142
|
+
# no-ops instead of signing someone up via magic link.
|
|
143
|
+
IDP_MAGIC_LINK_ALLOW_SIGNUP=true
|
|
144
|
+
|
|
145
|
+
# ── WebAuthn / passkeys (optional — omit to leave passkey routes disabled) ─
|
|
146
|
+
# rpID must be the *frontend's* registrable domain, not necessarily this
|
|
147
|
+
# API's own host.
|
|
148
|
+
IDP_WEBAUTHN_RP_ID=
|
|
149
|
+
IDP_WEBAUTHN_RP_NAME=MyApp
|
|
150
|
+
IDP_WEBAUTHN_ORIGIN=
|
|
151
|
+
|
|
152
|
+
# ── Outbound webhooks (optional — additive to the in-process hooks) ─────
|
|
153
|
+
# Single-endpoint convenience; configure config.webhooks.endpoints directly
|
|
154
|
+
# in code for multiple endpoints.
|
|
155
|
+
# https only (http only for localhost). The secret: at least 16 characters.
|
|
156
|
+
# Reset/magic-link tokens and verification codes are stripped from deliveries unless an endpoint
|
|
157
|
+
# sets includeCredentials (code config only).
|
|
158
|
+
IDP_WEBHOOK_URL=
|
|
159
|
+
IDP_WEBHOOK_SECRET=
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Each release names the `@okeav/idp-core` commit its identity-provider code is in step with. A
|
|
4
|
+
security fix in either package must be applied to the other.
|
|
5
|
+
|
|
6
|
+
## 0.1.0 — 2026-11-03
|
|
7
|
+
|
|
8
|
+
In step with `@okeav/idp-core` 0.4.0 at `f30273c`.
|
|
9
|
+
|
|
10
|
+
First release: the identity provider of `@okeav/idp-core` 0.4.0 on PostgreSQL, as a standalone
|
|
11
|
+
package — no dependency on `@okeav/idp-core`, `mongoose` or any MongoDB package.
|
|
12
|
+
|
|
13
|
+
### PostgreSQL store
|
|
14
|
+
|
|
15
|
+
- `config.postgres` (`connectionString` or `pool`, `poolConfig`, `migrations`,
|
|
16
|
+
`pruneIntervalSeconds`) replaces `config.mongo` / `config.storage`, which are refused. Validated
|
|
17
|
+
before anything connects. Environment: `IDP_DATABASE_URL` (or `DATABASE_URL`),
|
|
18
|
+
`IDP_PG_MIGRATIONS`, `IDP_PG_PRUNE_INTERVAL_SECONDS`, `IDP_PG_POOL_MAX`.
|
|
19
|
+
- Schema `0001_init.sql` for the 0.4.0 storage contract. Constraints carry the guarantees: unique
|
|
20
|
+
email blind index, one account per external identity, one row per refresh-token / code hash and
|
|
21
|
+
per passkey, at most one live password-reset / magic link per user, `ON DELETE CASCADE` from users.
|
|
22
|
+
- Every single-use operation is one atomic statement (refresh-token consume with row lock and
|
|
23
|
+
re-check, code redemption, verification codes and links, recovery codes, TOTP steps, passkey
|
|
24
|
+
counters, attempt counters); the login write is one transaction. Rotation windows, attempt
|
|
25
|
+
counters and service-key registration order use the database's clock; `databaseTime()` feeds the
|
|
26
|
+
clock-skew guard.
|
|
27
|
+
- Revoking a refresh-token family (reuse detected, end-session) tombstones the family first and then,
|
|
28
|
+
in a new snapshot, revokes every live row — so a successor inserted by a refresh in flight is
|
|
29
|
+
caught whichever side of the tombstone its check falls on.
|
|
30
|
+
- Strict writes: a field the store doesn't know is refused, never silently dropped. Ids that can't
|
|
31
|
+
be UUIDs find nothing (no 500s). Secrets are read only when asked for (`select: '+field'`); the
|
|
32
|
+
client-secret hash only with `includeSecret`.
|
|
33
|
+
- Migrations: `runMigrations()` (advisory-locked, checksummed — an edited migration is refused).
|
|
34
|
+
At startup `postgres.migrations`: `'verify'` (default — refuse an out-of-date or edited schema),
|
|
35
|
+
`'apply'`, `'skip'`. A database migrated by a newer version starts with a warning (rollbacks).
|
|
36
|
+
- Pruning of expired rows every `pruneIntervalSeconds` (default 3600, jittered, batched, never
|
|
37
|
+
overlapping); `storage.pruneExpired()` on demand. A code flagged as reused is kept an hour past
|
|
38
|
+
expiry.
|
|
39
|
+
- A pool the store creates survives idle-connection errors (logged) instead of crashing the process;
|
|
40
|
+
`storage.close()` stops pruning and the clock check and ends that pool (a pool passed in stays open).
|
|
41
|
+
- PostgreSQL 14 or later, checked at startup.
|
|
42
|
+
|
|
43
|
+
### Fixed (also present in `@okeav/idp-core` 0.4.0)
|
|
44
|
+
|
|
45
|
+
- `POST /oauth2/clients` dropped `postLogoutRedirectUris` given at registration (the schema accepted
|
|
46
|
+
them; the handler didn't store them).
|
|
47
|
+
|
|
48
|
+
### Removed (compared with `@okeav/idp-core`)
|
|
49
|
+
|
|
50
|
+
- The MongoDB storage, `config.mongo`, `config.storage.factory`, `MONGO_TRANSACTIONS_UNSUPPORTED`.
|
|
51
|
+
|
|
52
|
+
### Tests
|
|
53
|
+
|
|
54
|
+
- idp-core's suite, run against a real PostgreSQL server (embedded-postgres, or `IDP_PG_TEST_URL`),
|
|
55
|
+
a fresh database per test app.
|
|
56
|
+
- `test/postgres-store.test.js`: concurrency for every single-use operation (twenty connections
|
|
57
|
+
released at once onto a locked row — checked to fail when the row lock and re-check are removed),
|
|
58
|
+
migrations (concurrent runs, tampering, missing schema, newer schema), pruning, input validation.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Okeav
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,275 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @okeav/idp-pg
|
|
2
|
+
|
|
3
|
+
A standalone identity provider for Node.js/TypeScript backends on **PostgreSQL** — OAuth2/OIDC authorization server, password + MFA + WebAuthn/passkeys + magic-link + social login, session management, rate limiting, outbound webhooks, and service-to-service JWKS trust. Bring your own PostgreSQL (14 or later); everything else (Redis, a secrets vault) is optional.
|
|
4
|
+
|
|
5
|
+
Business-specific concepts (account types, roles, capability scopes) are deliberately **not** part of this package — it issues and verifies opaque `claims` on your behalf without ever interpreting them. Bring your own RBAC layer.
|
|
6
|
+
|
|
7
|
+
## Relationship to @okeav/idp-core
|
|
8
|
+
|
|
9
|
+
idp-pg is built from [`@okeav/idp-core`](https://github.com/okeav/idp) (0.4.0, commit `f30273c`) — the same identity provider, endpoints, tokens and security behaviour — with its MongoDB storage replaced by a native PostgreSQL store. It does **not** depend on idp-core or on any MongoDB package. idp-core's test suite runs here against a real PostgreSQL server, asserting the same behaviour.
|
|
10
|
+
|
|
11
|
+
The two packages are maintained side by side: a security fix in one must be applied to the other. `CHANGELOG.md` records the idp-core commit each release is in step with.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
Requires Node >= 20.
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @okeav/idp-pg
|
|
19
|
+
npm install express cookie-parser # peer dependencies you likely already have (express ^4.21.2 || ^5.1.0)
|
|
20
|
+
npm install ioredis # only for the Redis cache / rate-limiter adapters
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
Create the schema once, as a deploy step (or start with `postgres: { migrations: 'apply' }`):
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
import { runMigrations } from '@okeav/idp-pg';
|
|
29
|
+
await runMigrations(process.env.IDP_DATABASE_URL); // advisory-locked: safe from several instances
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
import express from 'express';
|
|
34
|
+
import { initIdentityProvider, buildRouter, cookieParser, configFromEnv, idpErrorHandler } from '@okeav/idp-pg';
|
|
35
|
+
|
|
36
|
+
const { storage } = await initIdentityProvider({
|
|
37
|
+
...configFromEnv(), // the IDP_* env vars in .env.example — IDP_DATABASE_URL, IDP_MFA_ENCRYPTION_KEY, …
|
|
38
|
+
hooks: {
|
|
39
|
+
// Not awaited by /register (so its timing can't reveal which addresses exist) — enqueue, don't block.
|
|
40
|
+
// verificationCode is null once the address has had 3 codes this code lifetime — always send the link.
|
|
41
|
+
onVerificationEmailRequested: async ({ email, verificationToken, verificationCode }) => {
|
|
42
|
+
const link = `https://app.example.com/verify-email?email=${encodeURIComponent(email)}&token=${encodeURIComponent(verificationToken)}`;
|
|
43
|
+
await sendEmail(email, verificationCode ? `Your code is ${verificationCode} — or open ${link}` : `Open ${link} to verify your address`);
|
|
44
|
+
},
|
|
45
|
+
resolveAuthContext: async (user) => ({ claims: { role: 'member' } }),
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const app = express();
|
|
50
|
+
app.set('trust proxy', 1); // behind one proxy hop — set your hop count or subnet, never `true`
|
|
51
|
+
app.use(cookieParser()); // before the router: cookie sessions and the SSO binding cookie need it
|
|
52
|
+
app.use(express.json());
|
|
53
|
+
app.use('/auth', buildRouter());
|
|
54
|
+
app.use(idpErrorHandler()); // after the router — see "Error handling" below
|
|
55
|
+
|
|
56
|
+
const server = app.listen(3000);
|
|
57
|
+
process.on('SIGTERM', () => server.close(() => storage.close()));
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`buildRouter()` mounts every surface by default except OAuth2 client administration
|
|
61
|
+
(`/oauth2/clients*`), which it mounts only behind your own admin middleware:
|
|
62
|
+
`buildRouter({ clientManagement: { middleware: [requireAdmin] } })`. `features: { sso: false, ... }`
|
|
63
|
+
leaves a surface (`magicLink`, `webauthn`, `sso`, `oauth2`, `oidc`, `serviceMesh`) unmounted. Every
|
|
64
|
+
response from the router carries `Cache-Control: no-store`, except the public discovery and key
|
|
65
|
+
documents. See `docs/api/router-and-schemas.md`. Every handler is also a named export, if you'd
|
|
66
|
+
rather mount them on your own router.
|
|
67
|
+
|
|
68
|
+
## Configuration
|
|
69
|
+
|
|
70
|
+
See `.env.example` for the environment variables and `types/index.d.ts` for the `IdpConfig` shape (`docs/api/bootstrap-config.md` documents both, with every default and startup check). Required:
|
|
71
|
+
|
|
72
|
+
- `issuer` — this IDP's URL, the JWT `iss` claim. `https` (plain `http` only for localhost, or with `NODE_ENV=development`).
|
|
73
|
+
- `postgres` — `{ connectionString }` or `{ pool }`, plus `migrations` (`'verify'` by default), `pruneIntervalSeconds`, `poolConfig`. See "Storage" below.
|
|
74
|
+
- `signingKeys.keys` — at least one `ACTIVE` RS256 keypair (PEM or base64 PEM), RSA ≥ 2048 bits.
|
|
75
|
+
- `security.emailHashPepper` — HMAC key for the email blind index; random, at least 32 characters, never rotated.
|
|
76
|
+
- `security.tokenHashSecret` — the secret the per-purpose HMAC keys for opaque tokens at rest are derived from; random, at least 32 characters, ≠ `emailHashPepper`. Rotate it through `security.previousTokenHashSecrets` — see `docs/api/bootstrap-config.md`.
|
|
77
|
+
- `mfa.encryptionKey` — the base64 of 32 bytes (`openssl rand -base64 32`); encrypts TOTP secrets at rest (AES-256-GCM). Required while `mfa.enabled` (default `true`).
|
|
78
|
+
- `sso.allowedRedirectOrigins` and `sso.baseCallbackUrl` — only once any `oauthProviders` entry is configured.
|
|
79
|
+
|
|
80
|
+
**`trust proxy`.** Per-IP rate limits key on `req.ip`. Behind a load balancer or reverse proxy, set Express's `trust proxy` to the hop count or the proxies' subnet — never `true`.
|
|
81
|
+
|
|
82
|
+
### Cache adapter
|
|
83
|
+
|
|
84
|
+
`config.cache.adapter` is `'memory'` (default) or `'redis'`.
|
|
85
|
+
|
|
86
|
+
- **memory** — zero config, but single-process only. State (revocation cache, SSO CSRF state, WebAuthn and OAuth2 consent challenges) is lost on restart and not shared across instances. Capped at 100k entries. Fine for local dev or a genuinely single-instance deployment; wrong for anything horizontally scaled.
|
|
87
|
+
- **redis** — set `config.cache.adapter = 'redis'` and `config.cache.redis = { host, port, username?, password?, tls? }` (`tls: true` for managed Redis or anything off the local network — startup warns about a remote host without it). Requires `ioredis` as a peer dependency; it's only `import()`-ed when this adapter is actually selected.
|
|
88
|
+
|
|
89
|
+
A custom cache adapter must implement an atomic `take(key)` (get-and-delete) alongside `get`/`set`/`del`/`expire` — it's what keeps single-use challenges single-use. See `docs/api/cache-interface.md`.
|
|
90
|
+
|
|
91
|
+
**Revocation checks fail closed regardless of adapter.** By default (`config.session.verifyOnEachRequest: true`) `authContextMiddleware` looks up the access token's session row by `jti` on every request — one indexed read — and rejects it (401 `TOKEN_REVOKED`) if the session is gone, revoked, or expired, so logout-all, password reset, and session revocation take effect on every instance at once. The cache is only a fast path in front of that: a cached revocation short-circuits, a cache error is logged and storage decides, and a storage error rejects with 503 `SESSION_STORE_UNAVAILABLE`. With `verifyOnEachRequest: false` (0.2.x behaviour) only the cache is checked: a cache *error* rejects with 503 `CACHE_UNAVAILABLE`, a *miss* means "not revoked", and access tokens survive logout-all and password reset/change until they expire (the cache only records single-session logouts/revocations, on the instance that handled them).
|
|
92
|
+
|
|
93
|
+
### Access tokens and `authContextMiddleware`
|
|
94
|
+
|
|
95
|
+
Access tokens are one of three kinds: `first-party` (issued by this IdP's own login flows, `aud` = the issuer), `oauth2-user` (issued to a third-party OAuth2 client for a user) and `oauth2-client` (`client_credentials`, no user). `authContextMiddleware()` and `verifyAccessToken()` accept only `first-party` by default — a token a user granted some relying party is never a credential for the IdP's own routes. A resource server that accepts OAuth2 tokens opts in and checks scopes itself:
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
app.get('/api/orders', authContextMiddleware({ accept: ['oauth2-user'] }), (req, res) => {
|
|
99
|
+
if (!req.auth.scopes?.includes('orders:read')) return res.status(403).end();
|
|
100
|
+
// req.auth = { userId, email, claims, tokenKind, clientId, scopes, tokenMeta: { issuedAt, expiresAt, jti, authTime } }
|
|
101
|
+
});
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`req.auth.userId` is `undefined` for `oauth2-client` tokens, and `authContextMiddleware` checks such a token against its client on every request — a deactivated client's machine tokens stop at once (401 `TOKEN_REVOKED`). `verifyAccessToken()` checks signature, issuer, expiry, type and kind/audience — **not** revocation; use `authContextMiddleware` where a logged-out session must stop working. `requireRecentAuth()` (mount after `authContextMiddleware`) answers 401 `REAUTHENTICATION_REQUIRED` unless the user actually logged in within `session.recentAuthMaxAgeSeconds` (default 15 minutes); the router uses it for passkey registration and deletion, MFA enrolment and account deletion. See `docs/api/middleware.md`.
|
|
105
|
+
|
|
106
|
+
**Cookie sessions and CSRF.** The access-token cookie is `__Host-access_token` (host-only, Secure, `Path=/` — a sibling subdomain can't plant it). The refresh-token cookie, `__Secure-refresh_token`, is scoped to `Path=<mount path>/session` — the only routes that read it (`/session/refresh`, `/session/logout`, `/session/logout/all`, `/session/end`) — so the long-lived token is sent nowhere else; since a path-scoped cookie can't be `__Host-`, the value used is the one whose keyed hash the host-only `__Host-refresh_binding` (`Path=/`) holds, and a sibling subdomain can't plant that binding — a planted refresh cookie is simply ignored. `cookies.sessionPath` pins the path when the router's mount path can be spelled several ways. With `cookies.domain` the cookies are `__Secure-…` domain cookies and a request carrying one twice is refused (400 `COOKIE_CONFLICT`); without Secure (development) they keep their plain names. An `Authorization: Bearer` header wins over the access-token cookie, and a refresh token in the body over the refresh cookie. A state-changing request authenticated by the session cookie must come from the issuer's origin or one of `cookies.trustedOrigins` (exact origins), or it gets 403 `CSRF_ORIGIN_REJECTED`. The endpoints that *set* or clear session cookies — `/login`, `/session/refresh`, `/session/logout`, `/mfa/verify`, `/magic-link/verify`, `/webauthn/authentication/verify`, `/webauthn/mfa/verify` — apply the same check to every browser request (login CSRF; `/session/refresh` checks it before reading any cookie), so a frontend on another origin must be listed even if it doesn't use cookies. `Authorization: Bearer` requests and non-browser clients (no `Origin`/`Sec-Fetch-Site`) are unaffected. The refresh token appears in JSON responses only for non-browser clients by default (`cookies.refreshTokenInBody: 'auto'`); `true` includes it for every request, `false` for none.
|
|
107
|
+
|
|
108
|
+
### Sessions
|
|
109
|
+
|
|
110
|
+
Each login starts a refresh-token *family*. `/session/refresh` rotates the token; a rotated token presented again after `session.refreshReuseGraceSeconds` (default 10 s — two tabs refreshing at once) revokes the whole family and emits `REFRESH_TOKEN_REUSE_DETECTED`. A family ends `session.absoluteLifetimeSeconds` (default 90 days) after its login however actively it's refreshed. First-party and OAuth2 refresh tokens are not interchangeable: `/session/refresh` accepts only first-party ones, the OAuth2 `refresh_token` grant only those issued to the calling client (a token presented at the wrong one is revoked). Every check runs before the token is consumed, so a refused refresh doesn't burn it. Enabling MFA signs out the account's other sessions. Races are closed after the fact: a refresh or code redemption re-checks the family's tombstone after inserting its row; every "sign out everywhere" increments the user's `sessionEpoch` before revoking, and a login, refresh or code redemption re-checks it after writing its row (a password reset or logout-all landing mid-login → 401 `TOKEN_REVOKED`); and an authorization code is refused if the session that authorized it was signed out before redemption (an ordinary refresh of that session doesn't void it), or if the consent changed since. These orderings use counters and the database's clock, never a comparison of app servers' clocks. Expiry (token `exp`, code, link and lockout lifetimes) does use each server's clock, so the skew is bounded: each server checks its clock against the database's at startup and every `clock.checkIntervalSeconds`, refusing to start past `clock.maxSkewSeconds` (default 30 s) — see `docs/api/bootstrap-config.md`. See `docs/api/password-email-auth.md`.
|
|
111
|
+
|
|
112
|
+
### Claims are opaque
|
|
113
|
+
|
|
114
|
+
`issueAccessToken({ sub, email, claims })` — `claims` is whatever object you pass. It comes back untouched as `req.auth.claims` after `authContextMiddleware`. This package never validates its shape, and ships no scope-matching or permission-checking logic — that's your application's job (or a separate RBAC package).
|
|
115
|
+
|
|
116
|
+
For login flows that mint a session on your behalf (password login, MFA-verify, SSO callback, magic-link verify, WebAuthn login), configure `hooks.resolveAuthContext(user, ctx)` to build that `claims` object — it's called right before the token is issued and defaults to `() => ({})` if you don't supply one.
|
|
117
|
+
|
|
118
|
+
Since 0.4.0 `POST /session/refresh` calls `resolveAuthContext(user, { isNewUser: false, method: 'refresh' })` again on every refresh (`config.session.reresolveClaimsOnRefresh`, default `true`), so a role change or suspension in your app takes effect within one access-token TTL. Keep the hook fast — it runs on every refresh. Set `reresolveClaimsOnRefresh: false` to carry the login-time `claims` forward instead; they then stay frozen for the whole session family (up to `session.absoluteLifetimeSeconds`).
|
|
119
|
+
|
|
120
|
+
The user record has a `metadata` object, but `POST /register` writes it only with `registration.acceptMetadata: true` — and then it's attacker-controlled, so never derive a role or tenant from it. Keep app data in your own collection (`docs/examples/consumer-managed-app-data.md`).
|
|
121
|
+
|
|
122
|
+
### Event hooks
|
|
123
|
+
|
|
124
|
+
All hooks are optional, default to no-ops, and are never thrown — a hook that throws is logged and swallowed, never breaks the request it's attached to. Each is awaited for at most `hookTimeoutMs` (default 10 s); after that the request carries on and the hook keeps running. On the endpoints that must not reveal whether an account exists (register, resend verification, forgot password, magic-link request) the email hooks are started but not awaited (resend verification and forgot password respond before even looking the address up) — in serverless runtimes, make them hand off quickly (enqueue rather than send inline).
|
|
125
|
+
|
|
126
|
+
| Hook | Fires on |
|
|
127
|
+
|---|---|
|
|
128
|
+
| `onAuditLog(event)` | Every audit-worthy action (login, logout, password change, MFA changes, OAuth2 grants, admin actions, SSO events, refresh-token reuse, etc.) — `event.action` identifies which one. |
|
|
129
|
+
| `onVerificationEmailRequested` | Registration (including re-registering a still-pending address) and resend-verification. `verificationCode` is `null` from the address's fourth email in a code lifetime — the template must then send only the link (`verificationToken`). |
|
|
130
|
+
| `onPasswordResetRequested` | Forgot-password. |
|
|
131
|
+
| `onPasswordChanged` | Password change/reset completed. |
|
|
132
|
+
| `onSuspiciousActivityDetected` | Password login locked after too many failed logins (once, when the lock starts). |
|
|
133
|
+
| `onNewDeviceLogin` | Login from a browser/OS combination not seen before for this user. |
|
|
134
|
+
| `onMagicLinkRequested` | Magic-link login requested — carries the raw token to embed in the emailed link. |
|
|
135
|
+
| `resolveAuthContext(user, ctx)` | Password login, MFA-verify, SSO callback, magic-link verify, WebAuthn login — builds the access token's `claims`. Also called on `/session/refresh` while `config.session.reresolveClaimsOnRefresh` is `true` (the default). Not wrapped: a throw fails the login. |
|
|
136
|
+
|
|
137
|
+
This package never talks to a message bus, SMTP server, or push provider directly — wire your own inside these hooks.
|
|
138
|
+
|
|
139
|
+
### Rate limiting
|
|
140
|
+
|
|
141
|
+
Request-rate limiting is enabled by default (`config.rateLimiting.enabled = true`) and is a distinct concern from `security.maxFailedLoginAttempts` (which locks one account's *password login* after N wrong passwords within `security.accountLockDurationMs`, for that long — the account stays `ACTIVE`, so refresh, magic link, passkeys, SSO and existing sessions keep working; signing in another way doesn't reset the count, a password reset does). Rate limiting instead throttles the *rate* of requests to the sensitive endpoints within a fixed window, regardless of whether individual requests succeed:
|
|
142
|
+
|
|
143
|
+
| Rule | Endpoint | Default limit |
|
|
144
|
+
|---|---|---|
|
|
145
|
+
| `login` | Login, per IP | 10 / 15 min |
|
|
146
|
+
| `loginByEmail` | Login, per address | 5 / 15 min |
|
|
147
|
+
| `passwordReset` | Password reset request, per IP | 3 / hour |
|
|
148
|
+
| `passwordResetByEmail` | Password reset request, per address | 3 / hour |
|
|
149
|
+
| `mfaChallenge` | MFA challenge verification, per IP | 5 / 15 min |
|
|
150
|
+
| `refreshToken` | Refresh token, per IP | 30 / min |
|
|
151
|
+
| `magicLink` | Magic-link request, per IP | 3 / hour |
|
|
152
|
+
| `magicLinkByEmail` | Magic-link request, per address | 3 / hour |
|
|
153
|
+
| `register` | Register and resend-verification, per IP | 10 / hour |
|
|
154
|
+
| `emailVerification` | Verify-email, per IP | 20 / 15 min |
|
|
155
|
+
| `verificationEmailByEmail` | Verification emails sent to one address | 3 / hour |
|
|
156
|
+
| `webauthnAuthentication` | Passkey login options + verify, per IP | 60 / 5 min |
|
|
157
|
+
| `oauth2Token` | `/oauth2/token`, `/token/revoke`, `/token/introspect`, per IP | 120 / min |
|
|
158
|
+
| `ssoInitiate` | `GET /sso/:provider`, per IP | 30 / 5 min |
|
|
159
|
+
| `serviceKeyRegistration` | `POST /internal/service-keys`, per IP | 20 / 15 min |
|
|
160
|
+
|
|
161
|
+
The MFA challenge limit covers both `/mfa/verify` and `/webauthn/mfa/verify`. Separately — and regardless of `rateLimiting.enabled` — per-**account** lockouts are counted in storage (the `attemptCounterRepository`), so they hold across instances and IPs: the password-login lockout (`security.maxFailedLoginAttempts`, default 5 wrong passwords per 30 min → password login locked for 30 min, every password answered 401 `INVALID_CREDENTIALS`; counted before bcrypt runs, failing closed), the MFA lockout (`config.mfa.lockout`, default 5 failed second-factor attempts in 15 min → locked for 15 min, 429 `MFA_LOCKED`), the email-verification **code** budgets (`security.verificationCodeLockout`, default 5 wrong codes per 24 h → 429 `VERIFICATION_LOCKED` for 24 h, never shorter than the code's lifetime — counted per verification ticket, which `/register` and `/register/resend-verification` hand out for the address, and per address for attempts without one, so a stranger's ticketless guesses don't spend the registrant's ticket budget; and at most `maxTotalFailedAttempts` (default 20) wrong codes per address a year in all — anyone's, so a stranger can switch an address to link-only; at most 3 codes are issued per address per code lifetime; codes aren't cleared and the emailed link always works), and the password-change lockout (`security.passwordChangeLockout`, default 5 wrong current passwords per hour → locked for an hour, 429 `PASSWORD_CHANGE_LOCKED`).
|
|
162
|
+
|
|
163
|
+
Override any rule under `config.rateLimiting.<rule>` — each takes `{ max, windowSeconds }` (positive integers). Set `config.rateLimiting.enabled = false` to disable entirely if you already rate-limit at a gateway/CDN layer (e.g. Cloudflare, an API gateway) covering every one of these endpoints — running it twice is redundant, not harmful, but the extra storage round-trip on every request is pure overhead if a layer in front of this service already enforces it.
|
|
164
|
+
|
|
165
|
+
Per-IP keys collapse IPv6 addresses to their /64; per-address keys use the email's keyed hash, so Redis and logs never hold email addresses. Uses the same adapter pattern as the cache layer: `config.rateLimiting.adapter` is `'memory'` (default, single-process, capped at 500k keys — when full, the oldest counters that haven't reached their limit are evicted (never an exhausted one), and a new key is refused — failing closed — only if every counter is exhausted) or `'redis'` (shares the cache adapter's Redis connection automatically if `config.cache.adapter` is also `'redis'`, otherwise set `config.rateLimiting.redis` separately — startup fails rather than connecting to an unconfigured localhost).
|
|
166
|
+
|
|
167
|
+
**Backend errors fail closed everywhere except refresh.** If the rate limiter's backend errors (Redis down, timeout), every limited request is rejected with 503 `RATE_LIMITER_UNAVAILABLE` — an attacker who can knock the limiter over must not get unlimited guesses. Refresh fails open: the error is logged and the request proceeds.
|
|
168
|
+
|
|
169
|
+
### Magic link (passwordless email login)
|
|
170
|
+
|
|
171
|
+
`requestMagicLinkHandler` / `verifyMagicLinkHandler` — a single-use, time-limited (`ttls.magicLink`, default 15 min) email link, built on the same `VerificationTokenRepository` as email verification and password reset (no separate storage). Requesting a link invalidates earlier ones, and requests are limited per IP and per address. Requesting a link for an unknown email creates a new `PENDING_VERIFICATION` user and fires `onMagicLinkRequested` with the raw token to embed in your emailed link — gated by `config.magicLink.allowSignupViaMagicLink` (default `true`; set `false` for invite-only apps where an unrecognized email should silently no-op instead of signing someone up). Activating an account by magic link discards any password or MFA state set before the address was proven.
|
|
172
|
+
|
|
173
|
+
Verifying the token goes through the exact same `resolveAuthContext` → session-issuance path as every other login method — there's no separate, weaker code path for magic-link sessions. For an account with MFA enabled, verify answers `{ mfaRequired: true, mfaChallengeToken, expiresIn }` instead of a session, exactly like password login; complete it at `/mfa/verify` or `/webauthn/mfa/verify`.
|
|
174
|
+
|
|
175
|
+
### WebAuthn / passkeys
|
|
176
|
+
|
|
177
|
+
Eight endpoints across four flows, all opt-in behind `config.webauthn.{rpID, rpName, origin}` (validated lazily on first use, not at `initIdentityProvider()` startup, so consumers who don't use passkeys never need to configure it). `rpID` must be the **frontend's** registrable domain — not necessarily this API's own hostname if the API lives on a subdomain.
|
|
178
|
+
|
|
179
|
+
| Flow | Endpoints | Auth required? |
|
|
180
|
+
|---|---|---|
|
|
181
|
+
| Register a passkey on an existing account | `generateRegistrationOptionsHandler`, `verifyRegistrationHandler` | Yes, and a recent login (`requireRecentAuth`) |
|
|
182
|
+
| Manage passkeys (`GET /me/passkeys`, `DELETE /me/passkeys/:credentialId`) | `listPasskeysHandler`, `deletePasskeyHandler` | Yes; delete also needs a recent login |
|
|
183
|
+
| Primary passwordless login | `generateAuthenticationOptionsHandler`, `verifyAuthenticationHandler` | No (rate limited per IP) |
|
|
184
|
+
| Passkey as an MFA second factor (alternative to TOTP) | `generateMfaWebauthnChallengeOptionsHandler`, `verifyMfaWebauthnChallengeHandler` | No (gated by a valid `mfaChallengeToken` instead) |
|
|
185
|
+
|
|
186
|
+
Primary login uses usernameless/discoverable credentials: `email` in the options request is ignored unless `config.webauthn.allowCredentialsByEmail: true` (listing an address's credential ids would reveal whether it has an account; with the flag on, unknown addresses get a stable decoy id). Primary login and registration require user verification; the MFA variant doesn't. Both the primary-login and MFA-second-factor verify handlers resolve through the same `resolveAuthContext` → session-issuance path as password/SSO/magic-link login. The MFA path additionally checks server-side that the verified credential actually belongs to the challenged user, and a discoverable assertion's `userHandle` must name the credential's owner.
|
|
187
|
+
|
|
188
|
+
Credentials are stored via the `CredentialRepository` interface (`src/storage/interfaces.js`) alongside the other seven — see "Storage" below.
|
|
189
|
+
|
|
190
|
+
### Outbound webhooks
|
|
191
|
+
|
|
192
|
+
Additive to the in-process hooks above — set `config.webhooks.endpoints = [{ url, secret, events?, includeCredentials? }, ...]` and every `onAuditLog`/named hook event *also* gets POSTed as a signed JSON payload (`resolveAuthContext` is excluded, since it's a data-returning callback rather than a one-way event). Leave `endpoints` empty (the default) to disable entirely. Each `url` must be `https` (`http` only for localhost) and each `secret` at least 16 characters — both checked at startup. `events` limits which events an endpoint receives.
|
|
193
|
+
|
|
194
|
+
**Credentials are stripped by default.** The `resetToken`, `magicLinkToken`, `verificationToken` and `verificationCode` fields are removed from deliveries unless the endpoint sets `includeCredentials: true` — set it only on the endpoint that actually sends those emails, since anyone with access to a receiver (or its logs) could otherwise take over accounts.
|
|
195
|
+
|
|
196
|
+
Each delivery is a fire-and-forget background operation — a webhook endpoint being slow, erroring, or completely unreachable never blocks or fails the auth request that triggered it, and webhooks are sent even when the in-process hook throws. Failed deliveries retry with exponential backoff (`config.webhooks.maxAttempts`, default 5; `config.webhooks.retryBaseDelayMs`, default 500ms, doubling each attempt) before being logged and dropped. Redirects are not followed. At most `config.webhooks.maxInFlight` (default 100) deliveries run at once; beyond that, events are dropped with a warning.
|
|
197
|
+
|
|
198
|
+
Request body:
|
|
199
|
+
|
|
200
|
+
```json
|
|
201
|
+
{ "id": "6f1c…", "event": "LOGIN", "payload": { "userId": "...", "email": "..." }, "timestamp": "2026-01-01T00:00:00.000Z" }
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Headers:
|
|
205
|
+
|
|
206
|
+
- `X-Idp-Event` — the event name (an `onAuditLog` action like `LOGIN`/`REGISTERED`/`PASSWORD_CHANGED`, or a named-hook event like `onMagicLinkRequested`).
|
|
207
|
+
- `X-Idp-Delivery` — the delivery id, also in the signed body as `id`. De-duplicate on the body's `id` (the header isn't signed).
|
|
208
|
+
- `X-Idp-Signature` — `t=<unix seconds>,v1=<hex HMAC-SHA256>`, computed over `` `${t}.${rawBody}` `` with your configured `secret` (Stripe-style signing).
|
|
209
|
+
|
|
210
|
+
Verify it on your receiving end with the exported `verifyWebhookSignature(secret, rawBody, signatureHeader)` helper — `rawBody` must be the exact, unparsed request body bytes/string (verify before you `JSON.parse`). During a secret rotation, pass an array of secrets (current and previous).
|
|
211
|
+
|
|
212
|
+
### Service-to-service JWKS trust
|
|
213
|
+
|
|
214
|
+
A differentiator kept from the source this was extracted from: any number of your own backend services can register an S2S signing keypair with this IDP (`initServiceIdentity`) and mint short-lived RS256 tokens to call each other (`mintServiceToken`), verified either in-process (`serviceContextMiddleware`, if the verifying service also runs this package) or over HTTP against `/.well-known/services-jwks.json` (`verifyServiceTokenRemote`, for services that don't).
|
|
215
|
+
|
|
216
|
+
Give each service its own registration credential with `serviceMesh.bootstrapSecrets: { billing: '<secret>', ... }` — it covers only that service's name and lets it rotate its key. The legacy shared `bootstrapSecret` can only register a name that has no key yet (otherwise 409 `SERVICE_NAME_TAKEN`) and never a name listed in `bootstrapSecrets` (403 `FORBIDDEN`). A revoked key stays revoked — registering it again answers 409 `SERVICE_KEY_REVOKED` — and a rotated-away key keeps verifying for `serviceMesh.rotationGraceSeconds` (default 3600) only. `serviceMesh.tokenMode` defaults to `'token'`; `requireServiceCallerMiddleware` refuses shared-secret callers unless `serviceMesh.allowLegacySecretCallers: true`. Service tokens without `exp`, living over 5 minutes, or with `iat` in the future are refused, and `revokeServiceKey(kid)` withdraws a key. See `docs/api/service-mesh.md`.
|
|
217
|
+
|
|
218
|
+
### SSO / social login
|
|
219
|
+
|
|
220
|
+
Google, GitHub, Microsoft (Entra ID — defaults to the `common` multitenant endpoint, supporting both work/school and personal Microsoft accounts), Apple, and LinkedIn. Configure whichever you use under `config.oauthProviders`, together with the required `config.sso.allowedRedirectOrigins` (exact origins the browser may be sent back to — `https`, or `http` only for localhost) and an absolute `https` `config.sso.baseCallbackUrl` (`http` only for localhost, or with `NODE_ENV=development`). Mount `cookie-parser` before the router: `GET /sso/:provider` sets a per-attempt binding cookie the callback requires (login-CSRF protection) — always host-only (`__Host-idp_sso_…` when Secure), whatever `cookies.domain` says. Google, Microsoft and GitHub use PKCE; Apple's `id_token` must carry this login's nonce. Provider calls time out after `sso.providerTimeoutMs` (default 10 s).
|
|
221
|
+
|
|
222
|
+
The callback is a **single step** — it resolves the identity, calls `hooks.resolveAuthContext`, and mints the full session directly. (An earlier two-step "exchange token" design existed in the source this was extracted from, purely because identity resolution and role/permission resolution lived in two different internal services there — not for any redirect-URI or CSRF-security reason. If you need that same split, implement it inside your own `resolveAuthContext`.) For an account with MFA enabled it instead redirects to `redirect_uri` with `#mfa_required=1&mfa_challenge_token=…&expires_in=…` in the fragment and sets no cookies — your frontend completes the challenge.
|
|
223
|
+
|
|
224
|
+
An account is created or linked by email only when the provider vouches for the address: Google, Apple and LinkedIn must assert `email_verified`, GitHub uses only the account's primary verified address, and Microsoft's address is trusted only when `oauthProviders.microsoft.tenant` names a single tenant (or with an explicit `trustEmail: true`). Otherwise the callback redirects with `error=email_not_verified`; a provider-side error redirects with `error=provider_error`. See `docs/api/sso-social-login.md`.
|
|
225
|
+
|
|
226
|
+
### Error handling
|
|
227
|
+
|
|
228
|
+
Every error this package throws on purpose is an `IdpError` (`{ code, httpStatus, status, statusCode, expose, message, cause? }`) passed to `next(err)`. The package never shapes an HTTP response body itself — mount the exported `idpErrorHandler()` after the router:
|
|
229
|
+
|
|
230
|
+
```js
|
|
231
|
+
app.use('/auth', buildRouter());
|
|
232
|
+
app.use(idpErrorHandler({ logger })); // logger optional — defaults to the one given to initIdentityProvider
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
It answers an `IdpError` below 500 with `{ error: code, message }`, malformed or oversized bodies with fixed 400/413 messages, and everything else with a bare 500 `{ error: 'INTERNAL_ERROR' }` (logged with `req.path` only — never the query string, which can carry tokens; hook errors are likewise logged by name and message only). If you write your own handler for a different envelope, keep the same rule — never echo the message of a non-`IdpError` (database and body-parser errors carry collection names, values and request bodies). See `ERROR_CODES` and `docs/api/errors.md` for the catalogue of codes you might see.
|
|
236
|
+
|
|
237
|
+
## Storage
|
|
238
|
+
|
|
239
|
+
Everything lives in PostgreSQL, in `idp_*` tables — `docs/api/postgres-storage.md` covers the schema, roles, TLS, backups and operations. In short:
|
|
240
|
+
|
|
241
|
+
- **Migrations** ship with the package and are applied by `runMigrations()` (a deploy step) or at startup with `postgres.migrations: 'apply'` — advisory-locked, so concurrent instances apply each file once, and checksummed, so an edited migration is refused. The default, `'verify'`, refuses to start on a schema that isn't current.
|
|
242
|
+
- **Every single-use operation is one atomic statement** (refresh-token rotation, code redemption, verification codes and links, recovery codes, TOTP steps, passkey counters, lockout counters); the login write is one transaction. The guarantees the security model rests on are database constraints: one account per email and per external identity, one live reset / magic link per user, one row per token hash.
|
|
243
|
+
- **Times that order events come from the database's clock**; the clock-skew guard keeps every server within `clock.maxSkewSeconds` of it.
|
|
244
|
+
- **Expired rows are pruned** by the IdP every `pruneIntervalSeconds` (default 1 h), in small batches — or call `storage.pruneExpired()` yourself.
|
|
245
|
+
- **After restoring a backup, end every session**: a restore brings revoked refresh tokens back (the SQL is in `docs/api/postgres-storage.md`).
|
|
246
|
+
|
|
247
|
+
Your app's own data goes in tables of its own beside `idp_*` (`docs/examples/consumer-managed-app-data.md`).
|
|
248
|
+
|
|
249
|
+
## Testing
|
|
250
|
+
|
|
251
|
+
```bash
|
|
252
|
+
npm test # starts a throwaway PostgreSQL (embedded-postgres: real server binaries) and runs every test file against it
|
|
253
|
+
IDP_PG_TEST_URL=postgres://postgres:pw@localhost:5432/postgres npm test # or against your server (a role that may CREATE DATABASE)
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Each test app gets a fresh database. `test/postgres-store.test.js` covers the store itself: concurrency (for every single-use operation, twenty connections released at once onto a locked row), migrations, pruning, and input it must not trip over.
|
|
257
|
+
|
|
258
|
+
## Known limitations
|
|
259
|
+
|
|
260
|
+
The four limitations listed in earlier 0.4.0 builds are resolved: the refresh cookie is scoped to `/session` (with a host-only binding cookie), clock skew is bounded against the database's clock, a stranger can no longer use up the registrant's verification-code attempts, and `prompt=login` needs a login made for that request. What remains:
|
|
261
|
+
|
|
262
|
+
- **Clock skew is bounded, not eliminated.** Expiry is still compared against each server's clock; the guard keeps every server within `clock.maxSkewSeconds` (default 30 s) of the database, so two servers can disagree by up to twice that.
|
|
263
|
+
- **A stranger can disable the code path for an address.** A registrant who enters the code where the ticket isn't available (another device, cookies cleared) spends the per-address budget, which a stranger who knows the address can use up — the code is then refused there until the lock expires (24 h by default). And `maxTotalFailedAttempts` (default 20) wrong codes from anyone, with or without tickets, disable codes for that address for a year. The emailed link always works, so verification emails must include it (`verificationToken`) — and from an address's fourth email in a code lifetime they carry only the link.
|
|
264
|
+
|
|
265
|
+
## What this package deliberately does not do
|
|
266
|
+
|
|
267
|
+
- No RBAC decisioning — no scope catalogue, no permission matcher. Bring your own.
|
|
268
|
+
- No message bus, SMTP, or push integration — use the hooks.
|
|
269
|
+
- No secrets-vault client — resolve your own config values before calling `initIdentityProvider()`.
|
|
270
|
+
- No QR-code rendering — `setupMfaHandler` returns the raw `otpauth://` URI.
|
|
271
|
+
- No pluggable storage — PostgreSQL only. (For MongoDB, use `@okeav/idp-core`.)
|
|
272
|
+
|
|
273
|
+
## License
|
|
274
|
+
|
|
275
|
+
MIT © Okeav
|
package/package.json
CHANGED
|
@@ -1,6 +1,78 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@okeav/idp-pg",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@okeav/idp-pg",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Standalone identity provider for Node.js on PostgreSQL — OAuth2/OIDC authorization server, password + MFA + passkeys + social login, session management and service-to-service JWKS trust. Built from @okeav/idp-core with a native PostgreSQL store.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Okeav",
|
|
8
|
+
"main": "./src/index.js",
|
|
9
|
+
"types": "./types/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./types/index.d.ts",
|
|
13
|
+
"import": "./src/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"src",
|
|
18
|
+
"types",
|
|
19
|
+
"README.md",
|
|
20
|
+
"CHANGELOG.md",
|
|
21
|
+
"LICENSE",
|
|
22
|
+
".env.example"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20.0.0"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"test": "node scripts/with-postgres.js node --test --test-timeout=180000"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@simplewebauthn/server": "^13.3.2",
|
|
32
|
+
"@types/pg": "^8.23.1",
|
|
33
|
+
"bcrypt": "^6.0.0",
|
|
34
|
+
"jsonwebtoken": "^9.0.3",
|
|
35
|
+
"otplib": "^13.4.1",
|
|
36
|
+
"pg": "^8.23.1",
|
|
37
|
+
"zod": "^4.6.7"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"cookie-parser": "^1.4.7",
|
|
41
|
+
"express": "^4.21.2 || ^5.1.0",
|
|
42
|
+
"ioredis": "^5.0.0"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/cookie-parser": "^1.4.10",
|
|
46
|
+
"@types/express": "^4.17.21",
|
|
47
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
48
|
+
"cookie-parser": "^1.4.7",
|
|
49
|
+
"embedded-postgres": "18.6.0-beta.19",
|
|
50
|
+
"express": "^4.21.2"
|
|
51
|
+
},
|
|
52
|
+
"keywords": [
|
|
53
|
+
"identity-provider",
|
|
54
|
+
"oauth2",
|
|
55
|
+
"oidc",
|
|
56
|
+
"authentication",
|
|
57
|
+
"postgres",
|
|
58
|
+
"postgresql",
|
|
59
|
+
"mfa",
|
|
60
|
+
"passkeys"
|
|
61
|
+
],
|
|
62
|
+
"peerDependenciesMeta": {
|
|
63
|
+
"ioredis": {
|
|
64
|
+
"optional": true
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
"repository": {
|
|
68
|
+
"type": "git",
|
|
69
|
+
"url": "git+https://github.com/okeav/idp-pg.git"
|
|
70
|
+
},
|
|
71
|
+
"bugs": {
|
|
72
|
+
"url": "https://github.com/okeav/idp-pg/issues"
|
|
73
|
+
},
|
|
74
|
+
"homepage": "https://github.com/okeav/idp-pg#readme",
|
|
75
|
+
"publishConfig": {
|
|
76
|
+
"access": "public"
|
|
77
|
+
}
|
|
78
|
+
}
|