@dxv-systems/dxv-sso 0.0.0-stage → 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 +213 -2
- package/dist/client.d.ts +82 -0
- package/dist/client.js +234 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +12 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +12 -0
- package/dist/testing.d.ts +43 -0
- package/dist/testing.js +219 -0
- package/dist/transaction.d.ts +18 -0
- package/dist/transaction.js +66 -0
- package/package.json +57 -4
package/README.md
CHANGED
|
@@ -1,3 +1,214 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dxv-systems/dxv-sso
|
|
2
2
|
|
|
3
|
-
|
|
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/dist/client.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export declare const DXV_SSO_SCOPES = "openid email profile offline_access";
|
|
2
|
+
export declare const ID_TOKEN_ALGORITHMS: readonly ["ES256", "EdDSA", "Ed25519"];
|
|
3
|
+
export type IdTokenAlgorithm = (typeof ID_TOKEN_ALGORITHMS)[number];
|
|
4
|
+
export declare const CLOCK_TOLERANCE_SECONDS = 30;
|
|
5
|
+
export interface DxvSsoPrivateJwk {
|
|
6
|
+
kty: string;
|
|
7
|
+
crv?: string;
|
|
8
|
+
x?: string;
|
|
9
|
+
y?: string;
|
|
10
|
+
d?: string;
|
|
11
|
+
kid?: string;
|
|
12
|
+
alg?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface DxvSsoConfig {
|
|
15
|
+
issuer: string;
|
|
16
|
+
clientId: string;
|
|
17
|
+
privateJwk: DxvSsoPrivateJwk;
|
|
18
|
+
redirectUri: string;
|
|
19
|
+
postLogoutRedirectUri: string;
|
|
20
|
+
cookieSecret: string | readonly string[];
|
|
21
|
+
idTokenSigningAlg?: IdTokenAlgorithm;
|
|
22
|
+
cookieName?: string;
|
|
23
|
+
allowInsecureHttp?: boolean;
|
|
24
|
+
fetch?: typeof fetch;
|
|
25
|
+
now?: () => number;
|
|
26
|
+
}
|
|
27
|
+
export interface StartOptions {
|
|
28
|
+
acrValues?: readonly string[];
|
|
29
|
+
maxAge?: number;
|
|
30
|
+
prompt?: "login";
|
|
31
|
+
returnTo?: string;
|
|
32
|
+
}
|
|
33
|
+
export interface StartResult {
|
|
34
|
+
url: string;
|
|
35
|
+
setCookie: string;
|
|
36
|
+
}
|
|
37
|
+
export interface CallbackRequest {
|
|
38
|
+
originalUrl?: string;
|
|
39
|
+
url?: string;
|
|
40
|
+
headers: {
|
|
41
|
+
cookie?: string | string[] | undefined;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export interface DxvIdentity {
|
|
45
|
+
sub: string;
|
|
46
|
+
iss: string;
|
|
47
|
+
email: string | null;
|
|
48
|
+
email_verified: boolean;
|
|
49
|
+
name: string | null;
|
|
50
|
+
platform_role: string | null;
|
|
51
|
+
mfa_stamp: string | null;
|
|
52
|
+
amr: string[];
|
|
53
|
+
acr: string | null;
|
|
54
|
+
auth_time: number;
|
|
55
|
+
}
|
|
56
|
+
export interface DxvSignIn extends DxvIdentity {
|
|
57
|
+
refreshToken: string;
|
|
58
|
+
idToken: string;
|
|
59
|
+
returnTo: string;
|
|
60
|
+
}
|
|
61
|
+
export type RevalidateResult = ({
|
|
62
|
+
status: "active";
|
|
63
|
+
refreshToken: string;
|
|
64
|
+
idToken: string;
|
|
65
|
+
} & DxvIdentity) | {
|
|
66
|
+
status: "revoked";
|
|
67
|
+
error: string;
|
|
68
|
+
description: string | null;
|
|
69
|
+
};
|
|
70
|
+
export interface DxvSso {
|
|
71
|
+
start(options?: StartOptions): Promise<StartResult>;
|
|
72
|
+
callback(req: CallbackRequest): Promise<DxvSignIn>;
|
|
73
|
+
revalidate(refreshToken: string, expected?: {
|
|
74
|
+
sub: string;
|
|
75
|
+
}): Promise<RevalidateResult>;
|
|
76
|
+
logoutUrl(options?: {
|
|
77
|
+
idTokenHint?: string;
|
|
78
|
+
state?: string;
|
|
79
|
+
}): Promise<string>;
|
|
80
|
+
readonly clearCookie: string;
|
|
81
|
+
}
|
|
82
|
+
export declare function createDxvSso(config: DxvSsoConfig): DxvSso;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CLOCK_TOLERANCE_SECONDS = exports.ID_TOKEN_ALGORITHMS = exports.DXV_SSO_SCOPES = void 0;
|
|
4
|
+
exports.createDxvSso = createDxvSso;
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
const transaction_1 = require("./transaction");
|
|
7
|
+
exports.DXV_SSO_SCOPES = "openid email profile offline_access";
|
|
8
|
+
exports.ID_TOKEN_ALGORITHMS = ["ES256", "EdDSA", "Ed25519"];
|
|
9
|
+
exports.CLOCK_TOLERANCE_SECONDS = 30;
|
|
10
|
+
const absoluteUrl = (where, value, allowHttp) => {
|
|
11
|
+
let url;
|
|
12
|
+
try {
|
|
13
|
+
url = new URL(value);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw new errors_1.DxvSsoError("configuration", `${where} must be an absolute URL.`);
|
|
17
|
+
}
|
|
18
|
+
if (url.protocol !== "https:" && !(allowHttp && url.protocol === "http:"))
|
|
19
|
+
throw new errors_1.DxvSsoError("configuration", `${where} must use https.`);
|
|
20
|
+
if (url.hash)
|
|
21
|
+
throw new errors_1.DxvSsoError("configuration", `${where} must not have a fragment.`);
|
|
22
|
+
return url;
|
|
23
|
+
};
|
|
24
|
+
const keyAlgorithm = (jwk) => {
|
|
25
|
+
if (typeof jwk?.d !== "string")
|
|
26
|
+
throw new errors_1.DxvSsoError("configuration", "privateJwk must be a private key (with d).");
|
|
27
|
+
if (jwk.kty === "EC" && jwk.crv === "P-256")
|
|
28
|
+
return { importParams: { name: "ECDSA", namedCurve: "P-256" }, alg: "ES256" };
|
|
29
|
+
if (jwk.kty === "OKP" && jwk.crv === "Ed25519")
|
|
30
|
+
return { importParams: { name: "Ed25519" }, alg: "Ed25519" };
|
|
31
|
+
throw new errors_1.DxvSsoError("configuration", "privateJwk must be a P-256 (ES256) or Ed25519 key.");
|
|
32
|
+
};
|
|
33
|
+
const safeReturnTo = (value) => {
|
|
34
|
+
if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || /[\\\u0000-\u001f\u007f]/.test(value))
|
|
35
|
+
return "/";
|
|
36
|
+
return value;
|
|
37
|
+
};
|
|
38
|
+
const optionalString = (value) => (typeof value === "string" ? value : null);
|
|
39
|
+
function identityOf(claims, issuer, clientId) {
|
|
40
|
+
if (claims.iss !== issuer)
|
|
41
|
+
throw new errors_1.DxvSsoError("issuer_mismatch", "The ID token was not issued by the configured issuer.");
|
|
42
|
+
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
43
|
+
if (aud.length !== 1 || aud[0] !== clientId)
|
|
44
|
+
throw new errors_1.DxvSsoError("invalid_response", "The ID token audience is not this client alone.");
|
|
45
|
+
if (claims.azp !== undefined && claims.azp !== clientId)
|
|
46
|
+
throw new errors_1.DxvSsoError("invalid_response", "The ID token azp is not this client.");
|
|
47
|
+
if (typeof claims.sub !== "string" || claims.sub.length === 0)
|
|
48
|
+
throw new errors_1.DxvSsoError("invalid_response", "The ID token has no sub.");
|
|
49
|
+
if (typeof claims.auth_time !== "number")
|
|
50
|
+
throw new errors_1.DxvSsoError("invalid_response", "The ID token has no auth_time.");
|
|
51
|
+
return {
|
|
52
|
+
sub: claims.sub,
|
|
53
|
+
iss: issuer,
|
|
54
|
+
email: optionalString(claims.email),
|
|
55
|
+
email_verified: claims.email_verified === true,
|
|
56
|
+
name: optionalString(claims.name),
|
|
57
|
+
platform_role: optionalString(claims.platform_role),
|
|
58
|
+
mfa_stamp: optionalString(claims.mfa_stamp),
|
|
59
|
+
amr: Array.isArray(claims.amr) ? claims.amr.filter((value) => typeof value === "string") : [],
|
|
60
|
+
acr: optionalString(claims.acr),
|
|
61
|
+
auth_time: claims.auth_time,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const headerAlg = (jwt) => {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(Buffer.from(jwt.split(".")[0], "base64url").toString("utf8")).alg;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
function createDxvSso(config) {
|
|
73
|
+
const allowHttp = config.allowInsecureHttp === true;
|
|
74
|
+
const issuerUrl = absoluteUrl("issuer", config.issuer, allowHttp);
|
|
75
|
+
const redirect = absoluteUrl("redirectUri", config.redirectUri, allowHttp);
|
|
76
|
+
absoluteUrl("postLogoutRedirectUri", config.postLogoutRedirectUri, allowHttp);
|
|
77
|
+
if (redirect.search)
|
|
78
|
+
throw new errors_1.DxvSsoError("configuration", "redirectUri must not have a query.");
|
|
79
|
+
if (typeof config.clientId !== "string" || config.clientId.length === 0)
|
|
80
|
+
throw new errors_1.DxvSsoError("configuration", "clientId is required.");
|
|
81
|
+
const secrets = typeof config.cookieSecret === "string" ? [config.cookieSecret] : [...(config.cookieSecret ?? [])];
|
|
82
|
+
if (secrets.length === 0 || secrets.some((secret) => typeof secret !== "string" || secret.length < 32))
|
|
83
|
+
throw new errors_1.DxvSsoError("configuration", "cookieSecret must be one or more secrets of at least 32 characters.");
|
|
84
|
+
if (config.idTokenSigningAlg !== undefined && !exports.ID_TOKEN_ALGORITHMS.includes(config.idTokenSigningAlg))
|
|
85
|
+
throw new errors_1.DxvSsoError("configuration", `idTokenSigningAlg must be one of ${exports.ID_TOKEN_ALGORITHMS.join(", ")}.`);
|
|
86
|
+
const { importParams } = keyAlgorithm(config.privateJwk);
|
|
87
|
+
const idTokenAlgs = config.idTokenSigningAlg ? [config.idTokenSigningAlg] : [...exports.ID_TOKEN_ALGORITHMS];
|
|
88
|
+
const now = config.now ?? Date.now;
|
|
89
|
+
const nowSeconds = () => Math.floor(now() / 1000);
|
|
90
|
+
const cookie = { name: config.cookieName ?? "dxv_sso_tx", path: redirect.pathname, secure: redirect.protocol === "https:" };
|
|
91
|
+
const clearCookie = (0, transaction_1.setCookieHeader)(cookie, "", 0);
|
|
92
|
+
let ready;
|
|
93
|
+
const setup = async () => {
|
|
94
|
+
const oidc = (await import("openid-client"));
|
|
95
|
+
const { d, kty, crv, x, y } = config.privateJwk;
|
|
96
|
+
const key = await crypto.subtle.importKey("jwk", { kty, crv, x, y, d }, importParams, false, ["sign"]);
|
|
97
|
+
const metadata = {
|
|
98
|
+
id_token_signed_response_alg: idTokenAlgs,
|
|
99
|
+
require_auth_time: true,
|
|
100
|
+
[oidc.clockTolerance]: exports.CLOCK_TOLERANCE_SECONDS,
|
|
101
|
+
};
|
|
102
|
+
const options = {
|
|
103
|
+
execute: allowHttp ? [oidc.allowInsecureRequests] : [],
|
|
104
|
+
...(config.fetch ? { [oidc.customFetch]: config.fetch } : {}),
|
|
105
|
+
};
|
|
106
|
+
let configuration;
|
|
107
|
+
try {
|
|
108
|
+
configuration = await oidc.discovery(issuerUrl, config.clientId, metadata, oidc.PrivateKeyJwt({ key, kid: config.privateJwk.kid }), options);
|
|
109
|
+
}
|
|
110
|
+
catch (cause) {
|
|
111
|
+
throw new errors_1.DxvSsoError("configuration", `Discovery at ${config.issuer} failed: ${cause.message}`, undefined, { cause });
|
|
112
|
+
}
|
|
113
|
+
const discovered = configuration.serverMetadata();
|
|
114
|
+
if (discovered.issuer !== config.issuer)
|
|
115
|
+
throw new errors_1.DxvSsoError("configuration", `The provider's issuer is ${discovered.issuer}, not the configured ${config.issuer}.`);
|
|
116
|
+
if (!discovered.end_session_endpoint)
|
|
117
|
+
throw new errors_1.DxvSsoError("configuration", "The provider offers no end_session_endpoint.");
|
|
118
|
+
return { oidc, configuration };
|
|
119
|
+
};
|
|
120
|
+
const discover = () => {
|
|
121
|
+
ready ?? (ready = setup().catch((error) => {
|
|
122
|
+
ready = undefined;
|
|
123
|
+
throw error;
|
|
124
|
+
}));
|
|
125
|
+
return ready;
|
|
126
|
+
};
|
|
127
|
+
const fail = (oidc, error) => {
|
|
128
|
+
if (error instanceof errors_1.DxvSsoError)
|
|
129
|
+
throw error;
|
|
130
|
+
if (error instanceof oidc.ResponseBodyError)
|
|
131
|
+
throw new errors_1.DxvSsoError("provider_error", `The provider refused: ${error.error}${error.error_description ? ` (${error.error_description})` : ""}`, { error: error.error, description: error.error_description }, { cause: error });
|
|
132
|
+
if (error instanceof oidc.AuthorizationResponseError)
|
|
133
|
+
throw new errors_1.DxvSsoError("provider_error", `The provider refused: ${error.error}`, { error: error.error, description: error.error_description }, { cause: error });
|
|
134
|
+
const detail = error?.cause instanceof Error ? error.cause : error;
|
|
135
|
+
throw new errors_1.DxvSsoError("invalid_response", `The provider's response failed validation: ${detail?.message ?? String(error)}`, undefined, { cause: error });
|
|
136
|
+
};
|
|
137
|
+
const checkedTokens = (tokens) => {
|
|
138
|
+
const claims = tokens.claims();
|
|
139
|
+
if (!tokens.id_token || !claims)
|
|
140
|
+
throw new errors_1.DxvSsoError("invalid_response", "The provider returned no ID token.");
|
|
141
|
+
if (!idTokenAlgs.includes(headerAlg(tokens.id_token)))
|
|
142
|
+
throw new errors_1.DxvSsoError("invalid_response", "The ID token is signed with an algorithm outside the allowlist.");
|
|
143
|
+
return { idToken: tokens.id_token, identity: identityOf(claims, config.issuer, config.clientId) };
|
|
144
|
+
};
|
|
145
|
+
return {
|
|
146
|
+
clearCookie,
|
|
147
|
+
async start(options = {}) {
|
|
148
|
+
if (options.prompt !== undefined && options.prompt !== "login")
|
|
149
|
+
throw new errors_1.DxvSsoError("configuration", 'prompt may only be "login".');
|
|
150
|
+
const { oidc, configuration } = await discover();
|
|
151
|
+
const state = oidc.randomState();
|
|
152
|
+
const nonce = oidc.randomNonce();
|
|
153
|
+
const verifier = oidc.randomPKCECodeVerifier();
|
|
154
|
+
const params = {
|
|
155
|
+
redirect_uri: config.redirectUri,
|
|
156
|
+
scope: exports.DXV_SSO_SCOPES,
|
|
157
|
+
response_type: "code",
|
|
158
|
+
code_challenge: await oidc.calculatePKCECodeChallenge(verifier),
|
|
159
|
+
code_challenge_method: "S256",
|
|
160
|
+
state,
|
|
161
|
+
nonce,
|
|
162
|
+
prompt: options.prompt === "login" ? "login consent" : "consent",
|
|
163
|
+
};
|
|
164
|
+
if (options.acrValues?.length)
|
|
165
|
+
params.acr_values = options.acrValues.join(" ");
|
|
166
|
+
if (options.maxAge !== undefined) {
|
|
167
|
+
if (!Number.isInteger(options.maxAge) || options.maxAge < 0)
|
|
168
|
+
throw new errors_1.DxvSsoError("configuration", "maxAge must be a whole number of seconds, 0 or more.");
|
|
169
|
+
params.max_age = String(options.maxAge);
|
|
170
|
+
}
|
|
171
|
+
const url = oidc.buildAuthorizationUrl(configuration, params);
|
|
172
|
+
const sealed = (0, transaction_1.sealTransaction)({ state, nonce, verifier, returnTo: safeReturnTo(options.returnTo), ...(options.maxAge !== undefined ? { maxAge: options.maxAge } : {}), expiresAt: nowSeconds() + transaction_1.TRANSACTION_TTL_SECONDS }, secrets);
|
|
173
|
+
return { url: url.href, setCookie: (0, transaction_1.setCookieHeader)(cookie, sealed, transaction_1.TRANSACTION_TTL_SECONDS) };
|
|
174
|
+
},
|
|
175
|
+
async callback(req) {
|
|
176
|
+
const transaction = (0, transaction_1.openTransaction)((0, transaction_1.readCookie)(req.headers?.cookie, cookie.name), secrets, nowSeconds());
|
|
177
|
+
const arrived = new URL(req.originalUrl ?? req.url ?? "", redirect);
|
|
178
|
+
if (arrived.pathname !== redirect.pathname)
|
|
179
|
+
throw new errors_1.DxvSsoError("invalid_response", "The callback did not arrive at the redirect URI.");
|
|
180
|
+
const current = new URL(redirect.href);
|
|
181
|
+
current.search = arrived.search;
|
|
182
|
+
const params = current.searchParams;
|
|
183
|
+
if (params.get("state") !== transaction.state)
|
|
184
|
+
throw new errors_1.DxvSsoError("state_mismatch", "The callback state does not belong to this browser's sign-in.");
|
|
185
|
+
if (params.get("iss") !== config.issuer)
|
|
186
|
+
throw new errors_1.DxvSsoError("issuer_mismatch", "The callback iss is not the configured issuer.");
|
|
187
|
+
const { oidc, configuration } = await discover();
|
|
188
|
+
if (params.has("error"))
|
|
189
|
+
throw new errors_1.DxvSsoError("provider_error", `The provider refused: ${params.get("error")}`, { error: params.get("error"), description: params.get("error_description") ?? undefined });
|
|
190
|
+
let tokens;
|
|
191
|
+
try {
|
|
192
|
+
tokens = await oidc.authorizationCodeGrant(configuration, current, {
|
|
193
|
+
pkceCodeVerifier: transaction.verifier,
|
|
194
|
+
expectedNonce: transaction.nonce,
|
|
195
|
+
expectedState: transaction.state,
|
|
196
|
+
idTokenExpected: true,
|
|
197
|
+
...(transaction.maxAge !== undefined ? { maxAge: transaction.maxAge } : {}),
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
return fail(oidc, error);
|
|
202
|
+
}
|
|
203
|
+
const { idToken, identity } = checkedTokens(tokens);
|
|
204
|
+
if (!tokens.refresh_token)
|
|
205
|
+
throw new errors_1.DxvSsoError("invalid_response", "The provider issued no refresh token (offline_access was not granted).");
|
|
206
|
+
return { ...identity, refreshToken: tokens.refresh_token, idToken, returnTo: transaction.returnTo };
|
|
207
|
+
},
|
|
208
|
+
async revalidate(refreshToken, expected) {
|
|
209
|
+
const { oidc, configuration } = await discover();
|
|
210
|
+
let tokens;
|
|
211
|
+
try {
|
|
212
|
+
tokens = await oidc.refreshTokenGrant(configuration, refreshToken);
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (error instanceof oidc.ResponseBodyError && error.error === "invalid_grant")
|
|
216
|
+
return { status: "revoked", error: error.error, description: error.error_description ?? null };
|
|
217
|
+
return fail(oidc, error);
|
|
218
|
+
}
|
|
219
|
+
const { idToken, identity } = checkedTokens(tokens);
|
|
220
|
+
if (expected && identity.sub !== expected.sub)
|
|
221
|
+
throw new errors_1.DxvSsoError("invalid_response", "The refreshed ID token is for another subject.");
|
|
222
|
+
return { status: "active", ...identity, refreshToken: tokens.refresh_token ?? refreshToken, idToken };
|
|
223
|
+
},
|
|
224
|
+
async logoutUrl(options = {}) {
|
|
225
|
+
const { oidc, configuration } = await discover();
|
|
226
|
+
const params = { client_id: config.clientId, post_logout_redirect_uri: config.postLogoutRedirectUri };
|
|
227
|
+
if (options.idTokenHint)
|
|
228
|
+
params.id_token_hint = options.idTokenHint;
|
|
229
|
+
if (options.state)
|
|
230
|
+
params.state = options.state;
|
|
231
|
+
return oidc.buildEndSessionUrl(configuration, params).href;
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type DxvSsoErrorCode = "configuration" | "transaction_missing" | "transaction_invalid" | "transaction_expired" | "state_mismatch" | "issuer_mismatch" | "provider_error" | "invalid_response";
|
|
2
|
+
export declare class DxvSsoError extends Error {
|
|
3
|
+
readonly code: DxvSsoErrorCode;
|
|
4
|
+
readonly providerError?: {
|
|
5
|
+
error: string;
|
|
6
|
+
description?: string;
|
|
7
|
+
} | undefined;
|
|
8
|
+
readonly name = "DxvSsoError";
|
|
9
|
+
constructor(code: DxvSsoErrorCode, message: string, providerError?: {
|
|
10
|
+
error: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
} | undefined, options?: {
|
|
13
|
+
cause?: unknown;
|
|
14
|
+
});
|
|
15
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DxvSsoError = void 0;
|
|
4
|
+
class DxvSsoError extends Error {
|
|
5
|
+
constructor(code, message, providerError, options) {
|
|
6
|
+
super(message, options);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.providerError = providerError;
|
|
9
|
+
this.name = "DxvSsoError";
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
exports.DxvSsoError = DxvSsoError;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { CLOCK_TOLERANCE_SECONDS, DXV_SSO_SCOPES, ID_TOKEN_ALGORITHMS, createDxvSso } from "./client";
|
|
2
|
+
export type { CallbackRequest, DxvIdentity, DxvSignIn, DxvSso, DxvSsoConfig, DxvSsoPrivateJwk, IdTokenAlgorithm, RevalidateResult, StartOptions, StartResult } from "./client";
|
|
3
|
+
export { DxvSsoError } from "./errors";
|
|
4
|
+
export type { DxvSsoErrorCode } from "./errors";
|
|
5
|
+
export { TRANSACTION_TTL_SECONDS } from "./transaction";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TRANSACTION_TTL_SECONDS = exports.DxvSsoError = exports.createDxvSso = exports.ID_TOKEN_ALGORITHMS = exports.DXV_SSO_SCOPES = exports.CLOCK_TOLERANCE_SECONDS = void 0;
|
|
4
|
+
var client_1 = require("./client");
|
|
5
|
+
Object.defineProperty(exports, "CLOCK_TOLERANCE_SECONDS", { enumerable: true, get: function () { return client_1.CLOCK_TOLERANCE_SECONDS; } });
|
|
6
|
+
Object.defineProperty(exports, "DXV_SSO_SCOPES", { enumerable: true, get: function () { return client_1.DXV_SSO_SCOPES; } });
|
|
7
|
+
Object.defineProperty(exports, "ID_TOKEN_ALGORITHMS", { enumerable: true, get: function () { return client_1.ID_TOKEN_ALGORITHMS; } });
|
|
8
|
+
Object.defineProperty(exports, "createDxvSso", { enumerable: true, get: function () { return client_1.createDxvSso; } });
|
|
9
|
+
var errors_1 = require("./errors");
|
|
10
|
+
Object.defineProperty(exports, "DxvSsoError", { enumerable: true, get: function () { return errors_1.DxvSsoError; } });
|
|
11
|
+
var transaction_1 = require("./transaction");
|
|
12
|
+
Object.defineProperty(exports, "TRANSACTION_TTL_SECONDS", { enumerable: true, get: function () { return transaction_1.TRANSACTION_TTL_SECONDS; } });
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type JsonWebKey } from "node:crypto";
|
|
2
|
+
import type { DxvSsoPrivateJwk } from "./client";
|
|
3
|
+
export interface FakeDxvAccount {
|
|
4
|
+
sub: string;
|
|
5
|
+
email?: string;
|
|
6
|
+
email_verified?: boolean;
|
|
7
|
+
name?: string;
|
|
8
|
+
platform_role?: string | null;
|
|
9
|
+
mfa_stamp?: string | null;
|
|
10
|
+
amr?: string[];
|
|
11
|
+
acr?: string;
|
|
12
|
+
authTime?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface FakeDxvTamper {
|
|
15
|
+
callbackIss?: string;
|
|
16
|
+
idTokenIssuer?: string;
|
|
17
|
+
idTokenAudience?: string | string[];
|
|
18
|
+
idTokenAzp?: string;
|
|
19
|
+
idTokenNonce?: string;
|
|
20
|
+
}
|
|
21
|
+
export type FakeDxvSigningAlg = "ES256" | "EdDSA" | "Ed25519";
|
|
22
|
+
export interface FakeDxvIdpOptions {
|
|
23
|
+
issuer: string;
|
|
24
|
+
clientId: string;
|
|
25
|
+
clientPublicJwk: JsonWebKey;
|
|
26
|
+
redirectUri: string;
|
|
27
|
+
postLogoutRedirectUri?: string;
|
|
28
|
+
alg?: FakeDxvSigningAlg;
|
|
29
|
+
now?: () => number;
|
|
30
|
+
}
|
|
31
|
+
export interface FakeDxvIdp {
|
|
32
|
+
fetch: typeof fetch;
|
|
33
|
+
signIn(authorizationUrl: string, account: FakeDxvAccount, tamper?: FakeDxvTamper): string;
|
|
34
|
+
update(sub: string, account: Partial<FakeDxvAccount>): void;
|
|
35
|
+
refuse(sub: string, reason: string | null): void;
|
|
36
|
+
readonly endSessionEndpoint: string;
|
|
37
|
+
readonly lastAuthorization: URLSearchParams | null;
|
|
38
|
+
}
|
|
39
|
+
export declare function generateClientKey(): {
|
|
40
|
+
privateJwk: DxvSsoPrivateJwk;
|
|
41
|
+
publicJwk: JsonWebKey;
|
|
42
|
+
};
|
|
43
|
+
export declare function createFakeDxvIdp(options: FakeDxvIdpOptions): FakeDxvIdp;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateClientKey = generateClientKey;
|
|
4
|
+
exports.createFakeDxvIdp = createFakeDxvIdp;
|
|
5
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
|
+
const b64 = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
7
|
+
const token = () => (0, node_crypto_1.randomBytes)(32).toString("base64url");
|
|
8
|
+
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
9
|
+
const oauthError = (error, description, status = 400) => json({ error, error_description: description }, status);
|
|
10
|
+
function generateClientKey() {
|
|
11
|
+
const { privateKey, publicKey } = (0, node_crypto_1.generateKeyPairSync)("ec", { namedCurve: "P-256" });
|
|
12
|
+
const kid = (0, node_crypto_1.randomBytes)(8).toString("hex");
|
|
13
|
+
return {
|
|
14
|
+
privateJwk: { ...privateKey.export({ format: "jwk" }), kid, alg: "ES256" },
|
|
15
|
+
publicJwk: { ...publicKey.export({ format: "jwk" }), kid, alg: "ES256", use: "sig" },
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function signJwt(header, payload, key) {
|
|
19
|
+
const input = `${b64(header)}.${b64(payload)}`;
|
|
20
|
+
const signature = header.alg === "ES256" ? (0, node_crypto_1.sign)("sha256", Buffer.from(input), { key, dsaEncoding: "ieee-p1363" }) : (0, node_crypto_1.sign)(null, Buffer.from(input), key);
|
|
21
|
+
return `${input}.${signature.toString("base64url")}`;
|
|
22
|
+
}
|
|
23
|
+
function verifyJwt(jwt, key) {
|
|
24
|
+
const [h, p, s] = jwt.split(".");
|
|
25
|
+
if (!h || !p || !s)
|
|
26
|
+
return null;
|
|
27
|
+
try {
|
|
28
|
+
const header = JSON.parse(Buffer.from(h, "base64url").toString("utf8"));
|
|
29
|
+
const payload = JSON.parse(Buffer.from(p, "base64url").toString("utf8"));
|
|
30
|
+
const data = Buffer.from(`${h}.${p}`);
|
|
31
|
+
const signature = Buffer.from(s, "base64url");
|
|
32
|
+
const ok = header.alg === "ES256" ? (0, node_crypto_1.verify)("sha256", data, { key, dsaEncoding: "ieee-p1363" }, signature) : header.alg === "EdDSA" || header.alg === "Ed25519" ? (0, node_crypto_1.verify)(null, data, key, signature) : false;
|
|
33
|
+
return ok ? { header, payload } : null;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function createFakeDxvIdp(options) {
|
|
40
|
+
const issuer = options.issuer;
|
|
41
|
+
const base = issuer.replace(/\/+$/, "");
|
|
42
|
+
const endpoints = { authorization: `${base}/auth`, token: `${base}/token`, jwks: `${base}/jwks`, endSession: `${base}/session/end` };
|
|
43
|
+
const alg = options.alg ?? "ES256";
|
|
44
|
+
const pair = alg === "ES256" ? (0, node_crypto_1.generateKeyPairSync)("ec", { namedCurve: "P-256" }) : (0, node_crypto_1.generateKeyPairSync)("ed25519");
|
|
45
|
+
const kid = (0, node_crypto_1.randomBytes)(8).toString("hex");
|
|
46
|
+
const publicJwk = { ...pair.publicKey.export({ format: "jwk" }), kid, alg, use: "sig" };
|
|
47
|
+
const clientKey = (0, node_crypto_1.createPublicKey)({ key: options.clientPublicJwk, format: "jwk" });
|
|
48
|
+
const now = () => Math.floor((options.now ?? Date.now)() / 1000);
|
|
49
|
+
const codes = new Map();
|
|
50
|
+
const refreshTokens = new Map();
|
|
51
|
+
const accounts = new Map();
|
|
52
|
+
const refusals = new Map();
|
|
53
|
+
const seenAssertions = new Set();
|
|
54
|
+
let lastAuthorization = null;
|
|
55
|
+
const idToken = (account, scope, extra) => {
|
|
56
|
+
const scopes = scope.split(" ");
|
|
57
|
+
const issuedAt = now();
|
|
58
|
+
const tamper = extra.tamper ?? {};
|
|
59
|
+
return signJwt({ alg, kid, typ: "JWT" }, {
|
|
60
|
+
iss: tamper.idTokenIssuer ?? issuer,
|
|
61
|
+
aud: tamper.idTokenAudience ?? options.clientId,
|
|
62
|
+
...(tamper.idTokenAzp ? { azp: tamper.idTokenAzp } : {}),
|
|
63
|
+
sub: account.sub,
|
|
64
|
+
iat: issuedAt,
|
|
65
|
+
exp: issuedAt + 3600,
|
|
66
|
+
auth_time: account.authTime ?? issuedAt,
|
|
67
|
+
amr: account.amr ?? ["pwd"],
|
|
68
|
+
acr: account.acr ?? "urn:dxv:acr:pwd",
|
|
69
|
+
...((tamper.idTokenNonce ?? extra.nonce) !== undefined ? { nonce: tamper.idTokenNonce ?? extra.nonce } : {}),
|
|
70
|
+
...(scopes.includes("email") && account.email !== undefined ? { email: account.email, email_verified: account.email_verified ?? true } : {}),
|
|
71
|
+
...(scopes.includes("profile") && account.name !== undefined ? { name: account.name } : {}),
|
|
72
|
+
...(account.platform_role != null ? { platform_role: account.platform_role } : {}),
|
|
73
|
+
...(account.mfa_stamp != null ? { mfa_stamp: account.mfa_stamp } : {}),
|
|
74
|
+
}, pair.privateKey);
|
|
75
|
+
};
|
|
76
|
+
const clientAuthenticated = (form) => {
|
|
77
|
+
if (form.get("client_assertion_type") !== "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
|
|
78
|
+
return false;
|
|
79
|
+
const verified = verifyJwt(form.get("client_assertion") ?? "", clientKey);
|
|
80
|
+
if (!verified)
|
|
81
|
+
return false;
|
|
82
|
+
const { payload } = verified;
|
|
83
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
84
|
+
if (payload.iss !== options.clientId || payload.sub !== options.clientId)
|
|
85
|
+
return false;
|
|
86
|
+
if (aud.length !== 1 || aud[0] !== issuer)
|
|
87
|
+
return false;
|
|
88
|
+
if (typeof payload.exp !== "number" || payload.exp < now())
|
|
89
|
+
return false;
|
|
90
|
+
if (typeof payload.jti !== "string" || seenAssertions.has(payload.jti))
|
|
91
|
+
return false;
|
|
92
|
+
seenAssertions.add(payload.jti);
|
|
93
|
+
return (form.get("client_id") ?? options.clientId) === options.clientId;
|
|
94
|
+
};
|
|
95
|
+
const issue = (account, scope, grant, nonce, tamper) => {
|
|
96
|
+
let refresh;
|
|
97
|
+
if (grant) {
|
|
98
|
+
refresh = token();
|
|
99
|
+
grant.current = refresh;
|
|
100
|
+
refreshTokens.set(refresh, grant);
|
|
101
|
+
}
|
|
102
|
+
return json({ token_type: "Bearer", access_token: token(), expires_in: 3600, scope, id_token: idToken(account, scope, { nonce, tamper }), ...(refresh ? { refresh_token: refresh } : {}) });
|
|
103
|
+
};
|
|
104
|
+
const fakeFetch = async (input, init) => {
|
|
105
|
+
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
|
|
106
|
+
const at = `${url.origin}${url.pathname}`;
|
|
107
|
+
if (url.pathname.endsWith("/.well-known/openid-configuration")) {
|
|
108
|
+
return json({
|
|
109
|
+
issuer,
|
|
110
|
+
authorization_endpoint: endpoints.authorization,
|
|
111
|
+
token_endpoint: endpoints.token,
|
|
112
|
+
jwks_uri: endpoints.jwks,
|
|
113
|
+
end_session_endpoint: endpoints.endSession,
|
|
114
|
+
response_types_supported: ["code"],
|
|
115
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
116
|
+
subject_types_supported: ["public"],
|
|
117
|
+
scopes_supported: ["openid", "email", "profile", "offline_access"],
|
|
118
|
+
code_challenge_methods_supported: ["S256"],
|
|
119
|
+
token_endpoint_auth_methods_supported: ["private_key_jwt"],
|
|
120
|
+
id_token_signing_alg_values_supported: [alg],
|
|
121
|
+
acr_values_supported: ["urn:dxv:acr:pwd", "urn:dxv:acr:mfa"],
|
|
122
|
+
authorization_response_iss_parameter_supported: true,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
if (at === endpoints.jwks)
|
|
126
|
+
return json({ keys: [publicJwk] });
|
|
127
|
+
if (at !== endpoints.token || (init?.method ?? "GET").toUpperCase() !== "POST")
|
|
128
|
+
return json({ error: "not_found" }, 404);
|
|
129
|
+
const form = new URLSearchParams(String(init?.body ?? ""));
|
|
130
|
+
if (!clientAuthenticated(form))
|
|
131
|
+
return oauthError("invalid_client", "client authentication failed", 401);
|
|
132
|
+
const grantType = form.get("grant_type");
|
|
133
|
+
if (grantType === "authorization_code") {
|
|
134
|
+
const code = codes.get(form.get("code") ?? "");
|
|
135
|
+
codes.delete(form.get("code") ?? "");
|
|
136
|
+
if (!code)
|
|
137
|
+
return oauthError("invalid_grant", "authorization code is invalid or was already used");
|
|
138
|
+
if (form.get("redirect_uri") !== code.redirectUri)
|
|
139
|
+
return oauthError("invalid_grant", "redirect_uri mismatch");
|
|
140
|
+
if ((0, node_crypto_1.createHash)("sha256").update(form.get("code_verifier") ?? "").digest("base64url") !== code.challenge)
|
|
141
|
+
return oauthError("invalid_grant", "PKCE verification failed");
|
|
142
|
+
const refusal = refusals.get(code.account.sub);
|
|
143
|
+
if (refusal)
|
|
144
|
+
return oauthError("invalid_grant", refusal);
|
|
145
|
+
const account = accounts.get(code.account.sub) ?? code.account;
|
|
146
|
+
const grant = code.offline ? { sub: account.sub, scope: code.scope, current: "", revoked: false } : null;
|
|
147
|
+
return issue(account, code.scope, grant, code.nonce, code.tamper);
|
|
148
|
+
}
|
|
149
|
+
if (grantType === "refresh_token") {
|
|
150
|
+
const presented = form.get("refresh_token") ?? "";
|
|
151
|
+
const grant = refreshTokens.get(presented);
|
|
152
|
+
if (!grant || grant.revoked)
|
|
153
|
+
return oauthError("invalid_grant", "grant request is invalid");
|
|
154
|
+
if (grant.current !== presented) {
|
|
155
|
+
grant.revoked = true;
|
|
156
|
+
return oauthError("invalid_grant", "refresh token was already used");
|
|
157
|
+
}
|
|
158
|
+
const refusal = refusals.get(grant.sub);
|
|
159
|
+
if (refusal)
|
|
160
|
+
return oauthError("invalid_grant", refusal);
|
|
161
|
+
return issue(accounts.get(grant.sub), grant.scope, grant, undefined, {});
|
|
162
|
+
}
|
|
163
|
+
return oauthError("unsupported_grant_type", "unsupported grant_type");
|
|
164
|
+
};
|
|
165
|
+
return {
|
|
166
|
+
fetch: fakeFetch,
|
|
167
|
+
endSessionEndpoint: endpoints.endSession,
|
|
168
|
+
get lastAuthorization() {
|
|
169
|
+
return lastAuthorization;
|
|
170
|
+
},
|
|
171
|
+
signIn(authorizationUrl, account, tamper = {}) {
|
|
172
|
+
const url = new URL(authorizationUrl);
|
|
173
|
+
const params = url.searchParams;
|
|
174
|
+
lastAuthorization = new URLSearchParams(params);
|
|
175
|
+
const back = new URL(options.redirectUri);
|
|
176
|
+
if (params.has("state"))
|
|
177
|
+
back.searchParams.set("state", params.get("state"));
|
|
178
|
+
back.searchParams.set("iss", tamper.callbackIss ?? issuer);
|
|
179
|
+
const scopes = (params.get("scope") ?? "").split(" ");
|
|
180
|
+
const problem = `${url.origin}${url.pathname}` !== endpoints.authorization ? "wrong authorization endpoint"
|
|
181
|
+
: params.get("client_id") !== options.clientId ? "unknown client_id"
|
|
182
|
+
: params.get("redirect_uri") !== options.redirectUri ? "redirect_uri is not registered"
|
|
183
|
+
: params.get("response_type") !== "code" ? "response_type must be code"
|
|
184
|
+
: params.get("code_challenge_method") !== "S256" || !params.get("code_challenge") ? "PKCE S256 is required"
|
|
185
|
+
: !scopes.includes("openid") ? "openid scope is required"
|
|
186
|
+
: null;
|
|
187
|
+
if (problem) {
|
|
188
|
+
back.searchParams.set("error", "invalid_request");
|
|
189
|
+
back.searchParams.set("error_description", problem);
|
|
190
|
+
return back.href;
|
|
191
|
+
}
|
|
192
|
+
accounts.set(account.sub, { ...account });
|
|
193
|
+
const code = token();
|
|
194
|
+
const prompt = (params.get("prompt") ?? "").split(" ");
|
|
195
|
+
codes.set(code, {
|
|
196
|
+
account: { ...account },
|
|
197
|
+
nonce: params.get("nonce") ?? undefined,
|
|
198
|
+
challenge: params.get("code_challenge"),
|
|
199
|
+
redirectUri: params.get("redirect_uri"),
|
|
200
|
+
scope: scopes.filter((scope) => ["openid", "email", "profile", "offline_access"].includes(scope)).join(" "),
|
|
201
|
+
offline: scopes.includes("offline_access") && prompt.includes("consent"),
|
|
202
|
+
tamper,
|
|
203
|
+
});
|
|
204
|
+
back.searchParams.set("code", code);
|
|
205
|
+
return back.href;
|
|
206
|
+
},
|
|
207
|
+
update(sub, account) {
|
|
208
|
+
const current = accounts.get(sub);
|
|
209
|
+
if (current)
|
|
210
|
+
accounts.set(sub, { ...current, ...account, sub });
|
|
211
|
+
},
|
|
212
|
+
refuse(sub, reason) {
|
|
213
|
+
if (reason === null)
|
|
214
|
+
refusals.delete(sub);
|
|
215
|
+
else
|
|
216
|
+
refusals.set(sub, reason);
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare const TRANSACTION_TTL_SECONDS = 600;
|
|
2
|
+
export interface Transaction {
|
|
3
|
+
state: string;
|
|
4
|
+
nonce: string;
|
|
5
|
+
verifier: string;
|
|
6
|
+
returnTo: string;
|
|
7
|
+
maxAge?: number;
|
|
8
|
+
expiresAt: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function sealTransaction(transaction: Transaction, secrets: readonly string[]): string;
|
|
11
|
+
export declare function openTransaction(sealed: string | undefined, secrets: readonly string[], nowSeconds: number): Transaction;
|
|
12
|
+
export declare function readCookie(header: string | string[] | undefined, name: string): string | undefined;
|
|
13
|
+
export interface CookieAttributes {
|
|
14
|
+
name: string;
|
|
15
|
+
path: string;
|
|
16
|
+
secure: boolean;
|
|
17
|
+
}
|
|
18
|
+
export declare function setCookieHeader(attributes: CookieAttributes, value: string, maxAge: number): string;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TRANSACTION_TTL_SECONDS = void 0;
|
|
4
|
+
exports.sealTransaction = sealTransaction;
|
|
5
|
+
exports.openTransaction = openTransaction;
|
|
6
|
+
exports.readCookie = readCookie;
|
|
7
|
+
exports.setCookieHeader = setCookieHeader;
|
|
8
|
+
const node_crypto_1 = require("node:crypto");
|
|
9
|
+
const errors_1 = require("./errors");
|
|
10
|
+
exports.TRANSACTION_TTL_SECONDS = 600;
|
|
11
|
+
const mac = (payload, secret) => (0, node_crypto_1.createHmac)("sha256", secret).update(payload).digest("base64url");
|
|
12
|
+
function sealTransaction(transaction, secrets) {
|
|
13
|
+
const payload = Buffer.from(JSON.stringify(transaction)).toString("base64url");
|
|
14
|
+
return `${payload}.${mac(payload, secrets[0])}`;
|
|
15
|
+
}
|
|
16
|
+
const isTransaction = (value) => {
|
|
17
|
+
const t = value;
|
|
18
|
+
return (typeof t === "object" &&
|
|
19
|
+
t !== null &&
|
|
20
|
+
typeof t.state === "string" &&
|
|
21
|
+
typeof t.nonce === "string" &&
|
|
22
|
+
typeof t.verifier === "string" &&
|
|
23
|
+
typeof t.returnTo === "string" &&
|
|
24
|
+
typeof t.expiresAt === "number" &&
|
|
25
|
+
(t.maxAge === undefined || typeof t.maxAge === "number"));
|
|
26
|
+
};
|
|
27
|
+
function openTransaction(sealed, secrets, nowSeconds) {
|
|
28
|
+
if (!sealed)
|
|
29
|
+
throw new errors_1.DxvSsoError("transaction_missing", "The sign-in transaction cookie is missing: start the sign-in again.");
|
|
30
|
+
const [payload, signature, extra] = sealed.split(".");
|
|
31
|
+
if (!payload || !signature || extra !== undefined)
|
|
32
|
+
throw new errors_1.DxvSsoError("transaction_invalid", "The sign-in transaction cookie is malformed.");
|
|
33
|
+
const given = Buffer.from(signature);
|
|
34
|
+
const signed = secrets.some((secret) => {
|
|
35
|
+
const expected = Buffer.from(mac(payload, secret));
|
|
36
|
+
return expected.length === given.length && (0, node_crypto_1.timingSafeEqual)(expected, given);
|
|
37
|
+
});
|
|
38
|
+
if (!signed)
|
|
39
|
+
throw new errors_1.DxvSsoError("transaction_invalid", "The sign-in transaction cookie has a bad signature.");
|
|
40
|
+
let transaction;
|
|
41
|
+
try {
|
|
42
|
+
transaction = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
43
|
+
}
|
|
44
|
+
catch (cause) {
|
|
45
|
+
throw new errors_1.DxvSsoError("transaction_invalid", "The sign-in transaction cookie is malformed.", undefined, { cause });
|
|
46
|
+
}
|
|
47
|
+
if (!isTransaction(transaction))
|
|
48
|
+
throw new errors_1.DxvSsoError("transaction_invalid", "The sign-in transaction cookie is malformed.");
|
|
49
|
+
if (transaction.expiresAt <= nowSeconds)
|
|
50
|
+
throw new errors_1.DxvSsoError("transaction_expired", "The sign-in took longer than 10 minutes: start it again.");
|
|
51
|
+
return transaction;
|
|
52
|
+
}
|
|
53
|
+
function readCookie(header, name) {
|
|
54
|
+
const lines = Array.isArray(header) ? header : header ? [header] : [];
|
|
55
|
+
for (const line of lines) {
|
|
56
|
+
for (const part of line.split(";")) {
|
|
57
|
+
const i = part.indexOf("=");
|
|
58
|
+
if (i > 0 && part.slice(0, i).trim() === name)
|
|
59
|
+
return part.slice(i + 1).trim();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
function setCookieHeader(attributes, value, maxAge) {
|
|
65
|
+
return [`${attributes.name}=${value}`, `Path=${attributes.path}`, `Max-Age=${maxAge}`, "HttpOnly", "SameSite=Lax", ...(attributes.secure ? ["Secure"] : [])].join("; ");
|
|
66
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dxv-systems/dxv-sso",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
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
|
+
}
|