@dxv-systems/dxv-sso 0.1.0 → 0.1.1
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/README.md +214 -214
- package/package.json +59 -59
package/README.md
CHANGED
|
@@ -1,214 +1,214 @@
|
|
|
1
|
-
# @dxv-systems/dxv-sso
|
|
2
|
-
|
|
3
|
-
Sign in with DXV for DXV apps.
|
|
4
|
-
|
|
5
|
-
The DXV Platform is the OpenID Connect provider. This package is the app's side, the relying party. It is built on [`openid-client`](https://github.com/panva/openid-client) v6. It holds the whole connection to the provider:
|
|
6
|
-
|
|
7
|
-
- the authorization request;
|
|
8
|
-
- the transaction cookie;
|
|
9
|
-
- the code exchange and every ID token check;
|
|
10
|
-
- refresh-token revalidation;
|
|
11
|
-
- RP-initiated logout.
|
|
12
|
-
|
|
13
|
-
The app keeps everything that depends on its own data: linking a DXV account to an app user, sessions, roles, audit and the screens.
|
|
14
|
-
|
|
15
|
-
## What it checks
|
|
16
|
-
|
|
17
|
-
- **Issuer, pinned exactly.** The `issuer` you configure must equal the provider's discovered `issuer` character for character, trailing slash included. Every ID token's `iss` must equal it too.
|
|
18
|
-
- **RFC 9207 `iss`.** The callback must carry `iss`, and it must equal the issuer. A callback without it is refused.
|
|
19
|
-
- **`state`, `nonce` and PKCE (S256).** All three are made fresh per sign-in and kept in the transaction cookie.
|
|
20
|
-
- **Audience.** `aud` must be this client alone. `azp`, when present, must be this client.
|
|
21
|
-
- **Signature algorithms.** The allowlist is ES256, EdDSA and Ed25519. Set `idTokenSigningAlg` to pin the one the provider registered for your client.
|
|
22
|
-
- **Clock skew.** The tolerance is 30 seconds for `exp`, `iat` and `auth_time`.
|
|
23
|
-
- **`max_age`.** When `start` asks for one, `auth_time` must be recent enough. `auth_time` is always required.
|
|
24
|
-
- **Client authentication.** The app signs `private_key_jwt` assertions with its own P-256 (ES256) or Ed25519 key. No client secret exists.
|
|
25
|
-
- **Scopes.** The request asks for `openid email profile offline_access`, with `prompt=consent` so the provider issues a refresh token. The provider shows no consent screen.
|
|
26
|
-
|
|
27
|
-
## Configuration
|
|
28
|
-
|
|
29
|
-
```ts
|
|
30
|
-
import { createDxvSso } from "@dxv-systems/dxv-sso";
|
|
31
|
-
|
|
32
|
-
const sso = createDxvSso({
|
|
33
|
-
issuer: process.env.DXV_SSO_ISSUER!,
|
|
34
|
-
clientId: process.env.DXV_SSO_CLIENT_ID!,
|
|
35
|
-
privateJwk: JSON.parse(process.env.DXV_SSO_PRIVATE_JWK!),
|
|
36
|
-
redirectUri: "https://app.example.com/auth/dxv/callback",
|
|
37
|
-
postLogoutRedirectUri: "https://app.example.com/",
|
|
38
|
-
cookieSecret: process.env.DXV_SSO_COOKIE_SECRET!,
|
|
39
|
-
idTokenSigningAlg: "ES256",
|
|
40
|
-
});
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
| Option | Meaning |
|
|
44
|
-
|---|---|
|
|
45
|
-
| `issuer` | The provider's issuer, exactly as it publishes it. |
|
|
46
|
-
| `clientId` | The client id the provider registered for this app. |
|
|
47
|
-
| `privateJwk` | The app's private key as a JWK (P-256 or Ed25519, with `d`; `kid` is sent in the assertion header). The provider holds the public half. |
|
|
48
|
-
| `redirectUri` | The registered callback URL. Its path is also the transaction cookie's `Path`. |
|
|
49
|
-
| `postLogoutRedirectUri` | A registered post-logout URL. |
|
|
50
|
-
| `cookieSecret` | A secret of at least 32 characters that signs the transaction cookie (HMAC-SHA256). To rotate it, pass a list: the first secret signs, and all of them verify. |
|
|
51
|
-
| `idTokenSigningAlg` | Optional: `ES256`, `EdDSA` or `Ed25519`. Without it, all three are allowed. |
|
|
52
|
-
| `cookieName` | Optional. Defaults to `dxv_sso_tx`. |
|
|
53
|
-
| `allowInsecureHttp` | Optional, for local tests only: allows `http:` URLs. |
|
|
54
|
-
| `fetch` | Optional, for tests: the fetch used for every provider request. |
|
|
55
|
-
|
|
56
|
-
`createDxvSso` checks the configuration at once and throws `DxvSsoError` with code `configuration`. Discovery runs at the first call and is cached. A failed discovery is retried at the next call.
|
|
57
|
-
|
|
58
|
-
## Integrating into an app (Express)
|
|
59
|
-
|
|
60
|
-
```ts
|
|
61
|
-
app.get("/auth/dxv/start", async (req, res) => {
|
|
62
|
-
const { url, setCookie } = await sso.start({ returnTo: String(req.query.returnTo ?? "/") });
|
|
63
|
-
res.append("Set-Cookie", setCookie);
|
|
64
|
-
res.redirect(url);
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
app.get("/auth/dxv/callback", async (req, res) => {
|
|
68
|
-
res.append("Set-Cookie", sso.clearCookie);
|
|
69
|
-
try {
|
|
70
|
-
const signIn = await sso.callback(req);
|
|
71
|
-
const user = await linkAccount(signIn);
|
|
72
|
-
req.session.regenerate((error) => {
|
|
73
|
-
if (error) return res.status(500).end();
|
|
74
|
-
req.session.userId = user.id;
|
|
75
|
-
req.session.dxv = { sub: signIn.sub, refreshToken: signIn.refreshToken, idToken: signIn.idToken, checkedAt: Date.now() };
|
|
76
|
-
res.redirect(signIn.returnTo);
|
|
77
|
-
});
|
|
78
|
-
} catch (error) {
|
|
79
|
-
log.warn("dxv sign-in failed", error);
|
|
80
|
-
res.redirect("/login?error=dxv");
|
|
81
|
-
}
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
app.post("/logout", async (req, res) => {
|
|
85
|
-
const url = await sso.logoutUrl({ idTokenHint: req.session.dxv?.idToken });
|
|
86
|
-
req.session.destroy(() => res.redirect(url));
|
|
87
|
-
});
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
### `start({ acrValues?, maxAge?, prompt?, returnTo? })`
|
|
91
|
-
|
|
92
|
-
`start` returns the authorization URL and `setCookie`, a `Set-Cookie` header value for the transaction cookie. The cookie has these properties:
|
|
93
|
-
|
|
94
|
-
- It holds `state`, `nonce`, the PKCE verifier and `returnTo`.
|
|
95
|
-
- It is signed and httpOnly, with SameSite=Lax.
|
|
96
|
-
- Its path is the callback path, so no other route receives it.
|
|
97
|
-
- It lives 10 minutes, and the expiry inside the signed value is checked too.
|
|
98
|
-
- It is single-use: the callback response clears it, and the code it belongs to can be redeemed only once.
|
|
99
|
-
|
|
100
|
-
Do not store the transaction in the pre-login session. The session is regenerated after sign-in, and a pre-login session can be fixated by an attacker.
|
|
101
|
-
|
|
102
|
-
`returnTo` must be a path on this site (`/…`). Anything else, such as `//host`, `https://…` or a backslash, becomes `/`. `prompt: "login"` asks the provider to authenticate the person again. `acrValues` asks for `urn:dxv:acr:mfa` or `urn:dxv:acr:pwd`. Check the `acr` you get back yourself before you give access that needs MFA.
|
|
103
|
-
|
|
104
|
-
Only one sign-in per browser runs at a time. A second `start` in another tab replaces the cookie, and the first tab's callback then fails with `state_mismatch`.
|
|
105
|
-
|
|
106
|
-
### `callback(req)`
|
|
107
|
-
|
|
108
|
-
`callback` takes the request at the redirect URI: anything with `originalUrl` or `url`, and `headers.cookie`, such as an Express or Node request. It returns:
|
|
109
|
-
|
|
110
|
-
```ts
|
|
111
|
-
{
|
|
112
|
-
sub, iss, email, email_verified, name, platform_role, mfa_stamp,
|
|
113
|
-
amr, acr, auth_time, refreshToken, idToken, returnTo
|
|
114
|
-
}
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
`email`, `name`, `platform_role`, `mfa_stamp` and `acr` are `null` when the ID token does not carry them.
|
|
118
|
-
|
|
119
|
-
**Regenerate the session after `callback`.** Start a new session id before you store the user in it (`req.session.regenerate` in express-session). Without this, an attacker who planted a session id before sign-in owns the signed-in session.
|
|
120
|
-
|
|
121
|
-
Always send `sso.clearCookie`, on success and on failure.
|
|
122
|
-
|
|
123
|
-
### `revalidate(refreshToken, expected?)`
|
|
124
|
-
|
|
125
|
-
`revalidate` uses the refresh token, and the provider runs its account checks again. It returns one of two results:
|
|
126
|
-
|
|
127
|
-
- `{ status: "active", ...claims, refreshToken, idToken }` with fresh claims and the **rotated** refresh token. Store the new token at once: the old one is spent.
|
|
128
|
-
- `{ status: "revoked", error, description }` when the provider answers `invalid_grant`. The account was suspended or removed, the grant was revoked, or the token was used twice. End the app session.
|
|
129
|
-
|
|
130
|
-
Network errors and other provider errors throw `DxvSsoError`. Keep the session and try again later. Pass `{ sub }` to make sure the token still belongs to the same person.
|
|
131
|
-
|
|
132
|
-
**Run `revalidate` single-flight per identity.** Refresh tokens rotate, and the provider treats a second use of a spent token as theft and revokes the whole grant. Two parallel requests that both refresh the same token sign the person out. Use one in-flight promise per `sub` within a process, and a lock (for example a Postgres advisory lock or a conditional update on the stored token) across processes.
|
|
133
|
-
|
|
134
|
-
Revalidate at least every **5 minutes for operators** (`platform_role: "operator"`) and every **15 minutes for everyone else**. Do it when a request arrives and the last check is older than that.
|
|
135
|
-
|
|
136
|
-
```ts
|
|
137
|
-
const inFlight = new Map<string, Promise<RevalidateResult>>();
|
|
138
|
-
function revalidateOnce(sub: string, refreshToken: string) {
|
|
139
|
-
let pending = inFlight.get(sub);
|
|
140
|
-
if (!pending) {
|
|
141
|
-
pending = sso.revalidate(refreshToken, { sub }).finally(() => inFlight.delete(sub));
|
|
142
|
-
inFlight.set(sub, pending);
|
|
143
|
-
}
|
|
144
|
-
return pending;
|
|
145
|
-
}
|
|
146
|
-
```
|
|
147
|
-
|
|
148
|
-
### `logoutUrl({ idTokenHint?, state? })`
|
|
149
|
-
|
|
150
|
-
`logoutUrl` returns the provider's end-session URL, with `client_id` and the configured `post_logout_redirect_uri`, for RP-initiated logout. Destroy the app session first, then redirect. Logout at the provider does not revoke the refresh token.
|
|
151
|
-
|
|
152
|
-
## Linking accounts
|
|
153
|
-
|
|
154
|
-
- **Link on `(iss, sub)`, never on email.** Store both on the app user. `sub` is stable, but an email address can change owner.
|
|
155
|
-
- **Email is a hint, not proof.** When a DXV account signs in for the first time and an app user exists with the same email, do not link them automatically. Offer the link, and link only after the person proves they own the app account, for example with its password. After that, the `(iss, sub)` link is the only key.
|
|
156
|
-
- **Rights come from the app.** `platform_role` says what the person is on the DXV Platform. Map it to app rights on purpose, and re-read it at every revalidation.
|
|
157
|
-
- **`mfa_stamp` changes when the person's second factor changes.** Compare it with the stored value at revalidation if the app cares.
|
|
158
|
-
|
|
159
|
-
## Errors
|
|
160
|
-
|
|
161
|
-
`DxvSsoError` has a `code`:
|
|
162
|
-
|
|
163
|
-
| Code | Meaning |
|
|
164
|
-
|---|---|
|
|
165
|
-
| `configuration` | The configuration is wrong, or discovery failed or showed another issuer. |
|
|
166
|
-
| `transaction_missing` | No transaction cookie: the sign-in was not started in this browser, or the cookie was already used. |
|
|
167
|
-
| `transaction_invalid` | The cookie is malformed or has a bad signature. |
|
|
168
|
-
| `transaction_expired` | More than 10 minutes passed since `start`. |
|
|
169
|
-
| `state_mismatch` | The callback belongs to another sign-in. |
|
|
170
|
-
| `issuer_mismatch` | The callback `iss` is missing or wrong. |
|
|
171
|
-
| `provider_error` | The provider refused. `providerError` holds `error` and `description`. |
|
|
172
|
-
| `invalid_response` | A token check failed: nonce, audience, azp, algorithm, signature, expiry, `max_age` or subject. |
|
|
173
|
-
|
|
174
|
-
Show the person a general message. Log the code and message for operators.
|
|
175
|
-
|
|
176
|
-
## Testing
|
|
177
|
-
|
|
178
|
-
`@dxv-systems/dxv-sso/testing` contains a fake DXV identity provider that runs in memory:
|
|
179
|
-
|
|
180
|
-
```ts
|
|
181
|
-
import { createFakeDxvIdp, generateClientKey } from "@dxv-systems/dxv-sso/testing";
|
|
182
|
-
|
|
183
|
-
const { privateJwk, publicJwk } = generateClientKey();
|
|
184
|
-
const idp = createFakeDxvIdp({ issuer, clientId, clientPublicJwk: publicJwk, redirectUri });
|
|
185
|
-
const sso = createDxvSso({ issuer, clientId, privateJwk, redirectUri, postLogoutRedirectUri, cookieSecret, fetch: idp.fetch });
|
|
186
|
-
|
|
187
|
-
const { url, setCookie } = await sso.start();
|
|
188
|
-
const back = new URL(idp.signIn(url, { sub: "u1", email: "a@example.test", platform_role: "operator" }));
|
|
189
|
-
const signIn = await sso.callback({ url: back.pathname + back.search, headers: { cookie: setCookie.split(";")[0] } });
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
The fake behaves like the real provider in these ways:
|
|
193
|
-
|
|
194
|
-
- It checks the `private_key_jwt` assertion, the PKCE verifier and the redirect URI.
|
|
195
|
-
- Codes are single-use.
|
|
196
|
-
- It sends `iss` on the callback.
|
|
197
|
-
- It issues a refresh token only for `offline_access` with `prompt=consent`.
|
|
198
|
-
- Refresh tokens rotate, and replaying one revokes the grant.
|
|
199
|
-
|
|
200
|
-
With the fake, a test can:
|
|
201
|
-
|
|
202
|
-
- change an account's claims with `update(sub, claims)`;
|
|
203
|
-
- refuse an account with `refuse(sub, reason)`, so `revalidate` returns `revoked`;
|
|
204
|
-
- sign with `alg: "EdDSA"` or `"Ed25519"`;
|
|
205
|
-
- tamper with `signIn(url, account, { callbackIss, idTokenIssuer, idTokenAudience, idTokenAzp, idTokenNonce })`.
|
|
206
|
-
|
|
207
|
-
## Bundling
|
|
208
|
-
|
|
209
|
-
`openid-client` v6 is ESM-only. This package is CommonJS and loads it with a real dynamic `import()`, which the build checks. An app that bundles to CommonJS with esbuild works either way:
|
|
210
|
-
|
|
211
|
-
- it can bundle `openid-client` in;
|
|
212
|
-
- it can leave `openid-client` external, and Node then loads it as ESM at run time.
|
|
213
|
-
|
|
214
|
-
Both ways are tested.
|
|
1
|
+
# @dxv-systems/dxv-sso
|
|
2
|
+
|
|
3
|
+
Sign in with DXV for DXV apps.
|
|
4
|
+
|
|
5
|
+
The DXV Platform is the OpenID Connect provider. This package is the app's side, the relying party. It is built on [`openid-client`](https://github.com/panva/openid-client) v6. It holds the whole connection to the provider:
|
|
6
|
+
|
|
7
|
+
- the authorization request;
|
|
8
|
+
- the transaction cookie;
|
|
9
|
+
- the code exchange and every ID token check;
|
|
10
|
+
- refresh-token revalidation;
|
|
11
|
+
- RP-initiated logout.
|
|
12
|
+
|
|
13
|
+
The app keeps everything that depends on its own data: linking a DXV account to an app user, sessions, roles, audit and the screens.
|
|
14
|
+
|
|
15
|
+
## What it checks
|
|
16
|
+
|
|
17
|
+
- **Issuer, pinned exactly.** The `issuer` you configure must equal the provider's discovered `issuer` character for character, trailing slash included. Every ID token's `iss` must equal it too.
|
|
18
|
+
- **RFC 9207 `iss`.** The callback must carry `iss`, and it must equal the issuer. A callback without it is refused.
|
|
19
|
+
- **`state`, `nonce` and PKCE (S256).** All three are made fresh per sign-in and kept in the transaction cookie.
|
|
20
|
+
- **Audience.** `aud` must be this client alone. `azp`, when present, must be this client.
|
|
21
|
+
- **Signature algorithms.** The allowlist is ES256, EdDSA and Ed25519. Set `idTokenSigningAlg` to pin the one the provider registered for your client.
|
|
22
|
+
- **Clock skew.** The tolerance is 30 seconds for `exp`, `iat` and `auth_time`.
|
|
23
|
+
- **`max_age`.** When `start` asks for one, `auth_time` must be recent enough. `auth_time` is always required.
|
|
24
|
+
- **Client authentication.** The app signs `private_key_jwt` assertions with its own P-256 (ES256) or Ed25519 key. No client secret exists.
|
|
25
|
+
- **Scopes.** The request asks for `openid email profile offline_access`, with `prompt=consent` so the provider issues a refresh token. The provider shows no consent screen.
|
|
26
|
+
|
|
27
|
+
## Configuration
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { createDxvSso } from "@dxv-systems/dxv-sso";
|
|
31
|
+
|
|
32
|
+
const sso = createDxvSso({
|
|
33
|
+
issuer: process.env.DXV_SSO_ISSUER!,
|
|
34
|
+
clientId: process.env.DXV_SSO_CLIENT_ID!,
|
|
35
|
+
privateJwk: JSON.parse(process.env.DXV_SSO_PRIVATE_JWK!),
|
|
36
|
+
redirectUri: "https://app.example.com/auth/dxv/callback",
|
|
37
|
+
postLogoutRedirectUri: "https://app.example.com/",
|
|
38
|
+
cookieSecret: process.env.DXV_SSO_COOKIE_SECRET!,
|
|
39
|
+
idTokenSigningAlg: "ES256",
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
| Option | Meaning |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `issuer` | The provider's issuer, exactly as it publishes it. |
|
|
46
|
+
| `clientId` | The client id the provider registered for this app. |
|
|
47
|
+
| `privateJwk` | The app's private key as a JWK (P-256 or Ed25519, with `d`; `kid` is sent in the assertion header). The provider holds the public half. |
|
|
48
|
+
| `redirectUri` | The registered callback URL. Its path is also the transaction cookie's `Path`. |
|
|
49
|
+
| `postLogoutRedirectUri` | A registered post-logout URL. |
|
|
50
|
+
| `cookieSecret` | A secret of at least 32 characters that signs the transaction cookie (HMAC-SHA256). To rotate it, pass a list: the first secret signs, and all of them verify. |
|
|
51
|
+
| `idTokenSigningAlg` | Optional: `ES256`, `EdDSA` or `Ed25519`. Without it, all three are allowed. |
|
|
52
|
+
| `cookieName` | Optional. Defaults to `dxv_sso_tx`. |
|
|
53
|
+
| `allowInsecureHttp` | Optional, for local tests only: allows `http:` URLs. |
|
|
54
|
+
| `fetch` | Optional, for tests: the fetch used for every provider request. |
|
|
55
|
+
|
|
56
|
+
`createDxvSso` checks the configuration at once and throws `DxvSsoError` with code `configuration`. Discovery runs at the first call and is cached. A failed discovery is retried at the next call.
|
|
57
|
+
|
|
58
|
+
## Integrating into an app (Express)
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
app.get("/auth/dxv/start", async (req, res) => {
|
|
62
|
+
const { url, setCookie } = await sso.start({ returnTo: String(req.query.returnTo ?? "/") });
|
|
63
|
+
res.append("Set-Cookie", setCookie);
|
|
64
|
+
res.redirect(url);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
app.get("/auth/dxv/callback", async (req, res) => {
|
|
68
|
+
res.append("Set-Cookie", sso.clearCookie);
|
|
69
|
+
try {
|
|
70
|
+
const signIn = await sso.callback(req);
|
|
71
|
+
const user = await linkAccount(signIn);
|
|
72
|
+
req.session.regenerate((error) => {
|
|
73
|
+
if (error) return res.status(500).end();
|
|
74
|
+
req.session.userId = user.id;
|
|
75
|
+
req.session.dxv = { sub: signIn.sub, refreshToken: signIn.refreshToken, idToken: signIn.idToken, checkedAt: Date.now() };
|
|
76
|
+
res.redirect(signIn.returnTo);
|
|
77
|
+
});
|
|
78
|
+
} catch (error) {
|
|
79
|
+
log.warn("dxv sign-in failed", error);
|
|
80
|
+
res.redirect("/login?error=dxv");
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
app.post("/logout", async (req, res) => {
|
|
85
|
+
const url = await sso.logoutUrl({ idTokenHint: req.session.dxv?.idToken });
|
|
86
|
+
req.session.destroy(() => res.redirect(url));
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### `start({ acrValues?, maxAge?, prompt?, returnTo? })`
|
|
91
|
+
|
|
92
|
+
`start` returns the authorization URL and `setCookie`, a `Set-Cookie` header value for the transaction cookie. The cookie has these properties:
|
|
93
|
+
|
|
94
|
+
- It holds `state`, `nonce`, the PKCE verifier and `returnTo`.
|
|
95
|
+
- It is signed and httpOnly, with SameSite=Lax.
|
|
96
|
+
- Its path is the callback path, so no other route receives it.
|
|
97
|
+
- It lives 10 minutes, and the expiry inside the signed value is checked too.
|
|
98
|
+
- It is single-use: the callback response clears it, and the code it belongs to can be redeemed only once.
|
|
99
|
+
|
|
100
|
+
Do not store the transaction in the pre-login session. The session is regenerated after sign-in, and a pre-login session can be fixated by an attacker.
|
|
101
|
+
|
|
102
|
+
`returnTo` must be a path on this site (`/…`). Anything else, such as `//host`, `https://…` or a backslash, becomes `/`. `prompt: "login"` asks the provider to authenticate the person again. `acrValues` asks for `urn:dxv:acr:mfa` or `urn:dxv:acr:pwd`. Check the `acr` you get back yourself before you give access that needs MFA.
|
|
103
|
+
|
|
104
|
+
Only one sign-in per browser runs at a time. A second `start` in another tab replaces the cookie, and the first tab's callback then fails with `state_mismatch`.
|
|
105
|
+
|
|
106
|
+
### `callback(req)`
|
|
107
|
+
|
|
108
|
+
`callback` takes the request at the redirect URI: anything with `originalUrl` or `url`, and `headers.cookie`, such as an Express or Node request. It returns:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
{
|
|
112
|
+
sub, iss, email, email_verified, name, platform_role, mfa_stamp,
|
|
113
|
+
amr, acr, auth_time, refreshToken, idToken, returnTo
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`email`, `name`, `platform_role`, `mfa_stamp` and `acr` are `null` when the ID token does not carry them.
|
|
118
|
+
|
|
119
|
+
**Regenerate the session after `callback`.** Start a new session id before you store the user in it (`req.session.regenerate` in express-session). Without this, an attacker who planted a session id before sign-in owns the signed-in session.
|
|
120
|
+
|
|
121
|
+
Always send `sso.clearCookie`, on success and on failure.
|
|
122
|
+
|
|
123
|
+
### `revalidate(refreshToken, expected?)`
|
|
124
|
+
|
|
125
|
+
`revalidate` uses the refresh token, and the provider runs its account checks again. It returns one of two results:
|
|
126
|
+
|
|
127
|
+
- `{ status: "active", ...claims, refreshToken, idToken }` with fresh claims and the **rotated** refresh token. Store the new token at once: the old one is spent.
|
|
128
|
+
- `{ status: "revoked", error, description }` when the provider answers `invalid_grant`. The account was suspended or removed, the grant was revoked, or the token was used twice. End the app session.
|
|
129
|
+
|
|
130
|
+
Network errors and other provider errors throw `DxvSsoError`. Keep the session and try again later. Pass `{ sub }` to make sure the token still belongs to the same person.
|
|
131
|
+
|
|
132
|
+
**Run `revalidate` single-flight per identity.** Refresh tokens rotate, and the provider treats a second use of a spent token as theft and revokes the whole grant. Two parallel requests that both refresh the same token sign the person out. Use one in-flight promise per `sub` within a process, and a lock (for example a Postgres advisory lock or a conditional update on the stored token) across processes.
|
|
133
|
+
|
|
134
|
+
Revalidate at least every **5 minutes for operators** (`platform_role: "operator"`) and every **15 minutes for everyone else**. Do it when a request arrives and the last check is older than that.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
const inFlight = new Map<string, Promise<RevalidateResult>>();
|
|
138
|
+
function revalidateOnce(sub: string, refreshToken: string) {
|
|
139
|
+
let pending = inFlight.get(sub);
|
|
140
|
+
if (!pending) {
|
|
141
|
+
pending = sso.revalidate(refreshToken, { sub }).finally(() => inFlight.delete(sub));
|
|
142
|
+
inFlight.set(sub, pending);
|
|
143
|
+
}
|
|
144
|
+
return pending;
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### `logoutUrl({ idTokenHint?, state? })`
|
|
149
|
+
|
|
150
|
+
`logoutUrl` returns the provider's end-session URL, with `client_id` and the configured `post_logout_redirect_uri`, for RP-initiated logout. Destroy the app session first, then redirect. Logout at the provider does not revoke the refresh token.
|
|
151
|
+
|
|
152
|
+
## Linking accounts
|
|
153
|
+
|
|
154
|
+
- **Link on `(iss, sub)`, never on email.** Store both on the app user. `sub` is stable, but an email address can change owner.
|
|
155
|
+
- **Email is a hint, not proof.** When a DXV account signs in for the first time and an app user exists with the same email, do not link them automatically. Offer the link, and link only after the person proves they own the app account, for example with its password. After that, the `(iss, sub)` link is the only key.
|
|
156
|
+
- **Rights come from the app.** `platform_role` says what the person is on the DXV Platform. Map it to app rights on purpose, and re-read it at every revalidation.
|
|
157
|
+
- **`mfa_stamp` changes when the person's second factor changes.** Compare it with the stored value at revalidation if the app cares.
|
|
158
|
+
|
|
159
|
+
## Errors
|
|
160
|
+
|
|
161
|
+
`DxvSsoError` has a `code`:
|
|
162
|
+
|
|
163
|
+
| Code | Meaning |
|
|
164
|
+
|---|---|
|
|
165
|
+
| `configuration` | The configuration is wrong, or discovery failed or showed another issuer. |
|
|
166
|
+
| `transaction_missing` | No transaction cookie: the sign-in was not started in this browser, or the cookie was already used. |
|
|
167
|
+
| `transaction_invalid` | The cookie is malformed or has a bad signature. |
|
|
168
|
+
| `transaction_expired` | More than 10 minutes passed since `start`. |
|
|
169
|
+
| `state_mismatch` | The callback belongs to another sign-in. |
|
|
170
|
+
| `issuer_mismatch` | The callback `iss` is missing or wrong. |
|
|
171
|
+
| `provider_error` | The provider refused. `providerError` holds `error` and `description`. |
|
|
172
|
+
| `invalid_response` | A token check failed: nonce, audience, azp, algorithm, signature, expiry, `max_age` or subject. |
|
|
173
|
+
|
|
174
|
+
Show the person a general message. Log the code and message for operators.
|
|
175
|
+
|
|
176
|
+
## Testing
|
|
177
|
+
|
|
178
|
+
`@dxv-systems/dxv-sso/testing` contains a fake DXV identity provider that runs in memory:
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
import { createFakeDxvIdp, generateClientKey } from "@dxv-systems/dxv-sso/testing";
|
|
182
|
+
|
|
183
|
+
const { privateJwk, publicJwk } = generateClientKey();
|
|
184
|
+
const idp = createFakeDxvIdp({ issuer, clientId, clientPublicJwk: publicJwk, redirectUri });
|
|
185
|
+
const sso = createDxvSso({ issuer, clientId, privateJwk, redirectUri, postLogoutRedirectUri, cookieSecret, fetch: idp.fetch });
|
|
186
|
+
|
|
187
|
+
const { url, setCookie } = await sso.start();
|
|
188
|
+
const back = new URL(idp.signIn(url, { sub: "u1", email: "a@example.test", platform_role: "operator" }));
|
|
189
|
+
const signIn = await sso.callback({ url: back.pathname + back.search, headers: { cookie: setCookie.split(";")[0] } });
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The fake behaves like the real provider in these ways:
|
|
193
|
+
|
|
194
|
+
- It checks the `private_key_jwt` assertion, the PKCE verifier and the redirect URI.
|
|
195
|
+
- Codes are single-use.
|
|
196
|
+
- It sends `iss` on the callback.
|
|
197
|
+
- It issues a refresh token only for `offline_access` with `prompt=consent`.
|
|
198
|
+
- Refresh tokens rotate, and replaying one revokes the grant.
|
|
199
|
+
|
|
200
|
+
With the fake, a test can:
|
|
201
|
+
|
|
202
|
+
- change an account's claims with `update(sub, claims)`;
|
|
203
|
+
- refuse an account with `refuse(sub, reason)`, so `revalidate` returns `revoked`;
|
|
204
|
+
- sign with `alg: "EdDSA"` or `"Ed25519"`;
|
|
205
|
+
- tamper with `signIn(url, account, { callbackIss, idTokenIssuer, idTokenAudience, idTokenAzp, idTokenNonce })`.
|
|
206
|
+
|
|
207
|
+
## Bundling
|
|
208
|
+
|
|
209
|
+
`openid-client` v6 is ESM-only. This package is CommonJS and loads it with a real dynamic `import()`, which the build checks. An app that bundles to CommonJS with esbuild works either way:
|
|
210
|
+
|
|
211
|
+
- it can bundle `openid-client` in;
|
|
212
|
+
- it can leave `openid-client` external, and Node then loads it as ESM at run time.
|
|
213
|
+
|
|
214
|
+
Both ways are tested.
|
package/package.json
CHANGED
|
@@ -1,59 +1,59 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@dxv-systems/dxv-sso",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Sign in with DXV for DXV apps: the OpenID Connect relying party on openid-client (private_key_jwt, PKCE, nonce, RFC 9207 iss, pinned issuer and algorithms), a signed single-use transaction cookie, refresh-token revalidation with a typed revoked result, RP-initiated logout, and a fake identity provider under ./testing.",
|
|
5
|
-
"keywords": [
|
|
6
|
-
"dxv",
|
|
7
|
-
"oidc",
|
|
8
|
-
"openid-connect",
|
|
9
|
-
"sso",
|
|
10
|
-
"relying-party"
|
|
11
|
-
],
|
|
12
|
-
"engines": {
|
|
13
|
-
"node": ">=20.19.0"
|
|
14
|
-
},
|
|
15
|
-
"exports": {
|
|
16
|
-
".": {
|
|
17
|
-
"types": "./dist/index.d.ts",
|
|
18
|
-
"default": "./dist/index.js"
|
|
19
|
-
},
|
|
20
|
-
"./testing": {
|
|
21
|
-
"types": "./dist/testing.d.ts",
|
|
22
|
-
"default": "./dist/testing.js"
|
|
23
|
-
}
|
|
24
|
-
},
|
|
25
|
-
"main": "./dist/index.js",
|
|
26
|
-
"types": "./dist/index.d.ts",
|
|
27
|
-
"files": [
|
|
28
|
-
"dist"
|
|
29
|
-
],
|
|
30
|
-
"sideEffects": false,
|
|
31
|
-
"scripts": {
|
|
32
|
-
"build": "tsc && node scripts/check-dist-imports.cjs",
|
|
33
|
-
"test": "vitest run",
|
|
34
|
-
"test:watch": "vitest",
|
|
35
|
-
"prepublishOnly": "npm run build"
|
|
36
|
-
},
|
|
37
|
-
"dependencies": {
|
|
38
|
-
"openid-client": "^6.9.1"
|
|
39
|
-
},
|
|
40
|
-
"devDependencies": {
|
|
41
|
-
"@dxv-systems/mcp-oauth": "0.9.2",
|
|
42
|
-
"@electric-sql/pglite": "^0.5.8",
|
|
43
|
-
"@types/express": "^5.0.6",
|
|
44
|
-
"@types/node": "^20.19.0",
|
|
45
|
-
"esbuild": "^0.28.2",
|
|
46
|
-
"express": "^5.3.0",
|
|
47
|
-
"typescript": "^5.6.0",
|
|
48
|
-
"vitest": "^4.1.11"
|
|
49
|
-
},
|
|
50
|
-
"repository": {
|
|
51
|
-
"type": "git",
|
|
52
|
-
"url": "git+https://github.com/dxv-systems/dxv-packages.git",
|
|
53
|
-
"directory": "packages/dxv-sso"
|
|
54
|
-
},
|
|
55
|
-
"publishConfig": {
|
|
56
|
-
"access": "public"
|
|
57
|
-
},
|
|
58
|
-
"license": "MIT"
|
|
59
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@dxv-systems/dxv-sso",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Sign in with DXV for DXV apps: the OpenID Connect relying party on openid-client (private_key_jwt, PKCE, nonce, RFC 9207 iss, pinned issuer and algorithms), a signed single-use transaction cookie, refresh-token revalidation with a typed revoked result, RP-initiated logout, and a fake identity provider under ./testing.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"dxv",
|
|
7
|
+
"oidc",
|
|
8
|
+
"openid-connect",
|
|
9
|
+
"sso",
|
|
10
|
+
"relying-party"
|
|
11
|
+
],
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=20.19.0"
|
|
14
|
+
},
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./testing": {
|
|
21
|
+
"types": "./dist/testing.d.ts",
|
|
22
|
+
"default": "./dist/testing.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"main": "./dist/index.js",
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"files": [
|
|
28
|
+
"dist"
|
|
29
|
+
],
|
|
30
|
+
"sideEffects": false,
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc && node scripts/check-dist-imports.cjs",
|
|
33
|
+
"test": "vitest run",
|
|
34
|
+
"test:watch": "vitest",
|
|
35
|
+
"prepublishOnly": "npm run build"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"openid-client": "^6.9.1"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@dxv-systems/mcp-oauth": "0.9.2",
|
|
42
|
+
"@electric-sql/pglite": "^0.5.8",
|
|
43
|
+
"@types/express": "^5.0.6",
|
|
44
|
+
"@types/node": "^20.19.0",
|
|
45
|
+
"esbuild": "^0.28.2",
|
|
46
|
+
"express": "^5.3.0",
|
|
47
|
+
"typescript": "^5.6.0",
|
|
48
|
+
"vitest": "^4.1.11"
|
|
49
|
+
},
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/dxv-systems/dxv-packages.git",
|
|
53
|
+
"directory": "packages/dxv-sso"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
},
|
|
58
|
+
"license": "MIT"
|
|
59
|
+
}
|