kinde-testkit 0.6.1 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ Found by running the new contract tests against a real Kinde business.
6
+
7
+ - Add the device authorization flow: `POST /oauth2/device/auth`, a `/device` page where the user enters the code and signs in, polling with `authorization_pending`, `slow_down`, `access_denied` and `expired_token`, and `POST /testkit/device` to approve or deny without a browser. Change timing with the `device` option.
8
+ - Add token introspection at `/oauth2/introspect` and dynamic client registration at `/oauth2/register`, with the same errors Kinde returns.
9
+ - A seeded application that lists `audience` may now only request those audiences, and gets Kinde's "has not been whitelisted" error for any other.
10
+ - The discovery document now lists the same endpoints and grant types as a Kinde business.
11
+ - Coverage adds a device sign-in item.
12
+ - The contract tests also compare introspection and registration errors, and explain how to authorize the Management API when Kinde refuses the M2M token.
13
+
3
14
  ## 0.6.1
4
15
 
5
16
  - Cut the package from 923 kB to 321 kB. The ESM entry points now share one copy of the issuer instead of each bundling its own.
package/README.md CHANGED
@@ -20,6 +20,7 @@ It also issues machine-to-machine tokens, answers the Management API and Account
20
20
  - [Browser tests with Playwright](#browser-tests-with-playwright)
21
21
  - [Browser tests with Cypress](#browser-tests-with-cypress)
22
22
  - [Machine-to-machine tokens](#machine-to-machine-tokens)
23
+ - [Device sign-in, introspection and client registration](#device-sign-in-introspection-and-client-registration)
23
24
  - [Webhooks](#webhooks)
24
25
  - [Management API and Account API](#management-api-and-account-api)
25
26
  - [Testing outages](#testing-outages)
@@ -267,7 +268,7 @@ Seed the apps your services use:
267
268
  }
268
269
  ```
269
270
 
270
- A seeded app with a `clientSecret` must send that secret. A seeded app with `scopes` is granted only the requested scopes it has, so `scope` holds what was granted and `scp` holds what was asked for, as in Kinde. A client ID that is not seeded gets a token with whatever it asks for.
271
+ A seeded app with a `clientSecret` must send that secret. A seeded app with `scopes` is granted only the requested scopes it has, so `scope` holds what was granted and `scp` holds what was asked for, as in Kinde. A seeded app with `audience` may only ask for those audiences. Any other answers `400 invalid_request` with Kinde's message, "Requested audience ... has not been whitelisted by the OAuth 2.0 Client", the error you get in Kinde when an API is not authorized for the app. A client ID that is not seeded gets a token with whatever it asks for.
271
272
 
272
273
  Your service fetches a token the same way it does from Kinde:
273
274
 
@@ -279,6 +280,33 @@ curl -s -X POST http://localhost:4400/oauth2/token \
279
280
 
280
281
  In tests, mint one directly with `testkit.m2mToken({ clientId, organizationCode, scopes, audience })`, or run `kinde-testkit token --m2m --client-id acme_agent --scope read:users`. M2M tokens take the same `invalid` kinds as user tokens. `principalFromClaims()` reads them as `{ type: "machine", subject: <client ID> }`.
281
282
 
283
+ ## Device sign-in, introspection and client registration
284
+
285
+ CLIs, TV apps and agents that cannot open a browser sign in with the device authorization flow. The device asks the testkit for a code, shows it to the user, and polls `/oauth2/token` until the user approves:
286
+
287
+ ```bash
288
+ curl -s -X POST http://localhost:4400/oauth2/device/auth -d client_id=my_cli -d audience=https://api.example.test
289
+ ```
290
+
291
+ ```json
292
+ { "device_code": "kinde_dc_...", "user_code": "CSLDFDUU", "verification_uri": "http://localhost:4400/device",
293
+ "verification_uri_complete": "http://localhost:4400/device?user_code=CSLDFDUU", "expires_in": 600, "interval": 5 }
294
+ ```
295
+
296
+ The user opens `verification_uri`, enters the code and signs in on the normal sign-in page. Until then, polling answers `authorization_pending`, polling faster than `interval` answers `slow_down`, a denied device gets `access_denied` and an old code gets `expired_token`, as in Kinde. Tests can approve or deny without a browser:
297
+
298
+ ```bash
299
+ curl -X POST http://localhost:4400/testkit/device -H 'content-type: application/json' \
300
+ -d '{"user_code":"CSLDFDUU","user":"admin@example.test","organization":"org_acme"}'
301
+ # or {"user_code":"CSLDFDUU","action":"deny"}
302
+ ```
303
+
304
+ Kinde polls every 5 seconds. Set `device: { intervalSeconds: 0 }` in `useKindeTestkit()` or `startKindeTestkit()` so tests do not wait. `expiresInSeconds` changes the code lifetime. Kinde's response also has a `qr_code` image, which the testkit leaves out.
305
+
306
+ `POST /oauth2/introspect` tells a resource server whether a token is active. Like Kinde, it needs a Bearer token, which must be different from the token being checked, and answers `{ active, aud, client_id, exp, iat }` or `{ active: false }`.
307
+
308
+ `POST /oauth2/register` is OAuth dynamic client registration, which Kinde offers for MCP connectors. Send `redirect_uris` and an optional `client_name` as JSON, and the testkit returns a new public `client_id`. A request with no valid redirect URIs gets Kinde's `invalid_redirect_uri` error. Kinde only accepts the redirect URIs of approved MCP clients, and it does not publish that list, so the testkit accepts any `http` or `https` redirect URI.
309
+
282
310
  ## Webhooks
283
311
 
284
312
  Kinde sends webhooks as a signed JWT with `Content-Type: application/jwt` and a `webhook-id` header that stays the same across retries. Your endpoint checks the signature with `decodeWebhook()` from `@kinde/webhooks`, which fetches keys from your issuer. kinde-testkit sends webhooks the same way, signed with its own key, so the same handler code works in tests when `KINDE_ISSUER_URL` points at the testkit.
@@ -578,13 +606,13 @@ Identity 6/6
578
606
  Organizations 4/5
579
607
  Permissions 5/5
580
608
  Token validation 3/8
581
- Sessions 4/5
609
+ Sessions 4/6
582
610
  Machine-to-machine 0/4
583
611
  Kinde APIs 2/4
584
612
  Webhooks 5/5
585
613
  Outages 2/4
586
614
 
587
- Overall: 31/46
615
+ Overall: 31/47
588
616
 
589
617
  Not covered:
590
618
  Organizations: Organization claim missing. Mint a token with invalid: "missing-organization".
@@ -706,6 +734,10 @@ From `kinde-testkit/playwright`: `test` and `expect` with the `kinde` fixture, t
706
734
  | `POST /oauth2/token` | `authorization_code`, `refresh_token` and `client_credentials` grants. Client credentials in the body or with HTTP Basic. Refresh tokens rotate on every use |
707
735
  | `GET /oauth2/v2/user_profile` | Profile for the Bearer token's user |
708
736
  | `POST /oauth2/revoke` | Revokes a refresh token |
737
+ | `POST /oauth2/device/auth`, `GET /device` | Device authorization flow: the device code request and the page where the user enters the code |
738
+ | `POST /oauth2/introspect` | Token introspection. Needs a Bearer token |
739
+ | `POST /oauth2/register` | Dynamic client registration for MCP connectors |
740
+ | `POST /testkit/device` | Approves or denies a pending device code without a browser |
709
741
  | `GET /logout?redirect=<url>` | Signs out and redirects |
710
742
  | `/api/v1/...` | Management API: users, organizations, members, roles and permissions |
711
743
  | `GET /account_api/v1/...` | Account API: permissions, roles, feature flags, properties and entitlements for the token's user |
@@ -761,6 +793,8 @@ ID tokens carry `amr`, `aud` (the client ID), `auth_time`, `email`, `email_verif
761
793
  | Switching the active organization | Implemented through `org_code` or the organization picker |
762
794
  | Authorization code flow with sign-in page, PKCE and `state` | Implemented |
763
795
  | Refresh tokens with rotation, revocation, logout and user profile | Implemented |
796
+ | Device authorization flow, token introspection and dynamic client registration | Implemented. Error responses checked against a real Kinde business. The device response has no `qr_code` |
797
+ | Audience allow-list for seeded M2M apps | Implemented, with Kinde's error message |
764
798
  | Vitest and Jest helpers, Playwright fixture, Cypress commands | Implemented. Jest runs in the test suite. Cypress's sign-in steps are tested against the Next.js SDK |
765
799
  | Accepted by `@kinde/jwt-validator` and the Next.js SDK's `validateToken` | Tested |
766
800
  | Sign-in, organization switching and sign-out through `@kinde-oss/kinde-auth-nextjs` | Tested in Chrome with Playwright |
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getDefaultTestkit,
3
3
  startKindeTestkit
4
- } from "./chunk-GCOZVCZY.js";
4
+ } from "./chunk-JTAB2S44.js";
5
5
 
6
6
  // src/handle.ts
7
7
  async function kindeTest(options) {
@@ -69,4 +69,4 @@ export {
69
69
  kindeTest,
70
70
  createKindeTestkitHandle
71
71
  };
72
- //# sourceMappingURL=chunk-U2D47SCY.js.map
72
+ //# sourceMappingURL=chunk-2QJ7DTNL.js.map
@@ -1491,7 +1491,8 @@ var COVERAGE_GROUPS = [
1491
1491
  { id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
1492
1492
  { id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
1493
1493
  { id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
1494
- { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
1494
+ { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." },
1495
+ { id: "session.device-approved", label: "Device sign-in", hint: "Run the device authorization flow and approve it with POST /testkit/device." }
1495
1496
  ]
1496
1497
  },
1497
1498
  {
@@ -1777,10 +1778,25 @@ function renderOrganizationPicker(options) {
1777
1778
  function renderMessage(title, message) {
1778
1779
  return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
1779
1780
  }
1781
+ function renderDeviceCodeEntry(options = {}) {
1782
+ return layout(
1783
+ "Connect a device",
1784
+ `<h1>Connect a device</h1><p>Enter the code the device shows.</p>${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="get" action="/device"><label for="user_code">Code</label><input id="user_code" name="user_code" type="text" autocomplete="off" value="${escapeHtml(options.userCode ?? "")}" placeholder="ABCDEFGH" style="width:100%;height:42px;padding:0 12px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit;letter-spacing:.2em"><button class="primary" type="submit">Continue</button></form>`
1785
+ );
1786
+ }
1787
+ function renderDeviceConfirm(options) {
1788
+ const code = escapeHtml(options.userCode);
1789
+ return layout(
1790
+ "Connect a device",
1791
+ `<h1>Connect a device</h1><p>A device using the app <strong>${escapeHtml(options.clientId)}</strong> wants to sign in. Check that it shows this code.</p><p class="note" style="font:600 20px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.2em;text-align:center">${code}</p><form method="get" action="/device/sign-in"><input type="hidden" name="user_code" value="${code}"><button class="primary" type="submit">Continue</button></form><form method="post" action="/device/deny"><input type="hidden" name="user_code" value="${code}"><button class="option" type="submit" style="margin-top:8px;justify-content:center">Deny</button></form>`
1792
+ );
1793
+ }
1780
1794
 
1781
1795
  // src/oauth.ts
1782
1796
  import { createHash as createHash3, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
1783
1797
  var CODE_LIFETIME_MS = 10 * 60 * 1e3;
1798
+ var DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
1799
+ var USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
1784
1800
  var OAuthError = class extends Error {
1785
1801
  constructor(status, error, description) {
1786
1802
  super(description);
@@ -1791,24 +1807,49 @@ var OAuthError = class extends Error {
1791
1807
  error;
1792
1808
  };
1793
1809
  var AuthorizationServer = class {
1794
- constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
1810
+ constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0, deviceOptions = {}) {
1795
1811
  this.testkit = testkit;
1796
1812
  this.seed = seed;
1797
1813
  this.emit = emit;
1798
1814
  this.directory = directory;
1799
1815
  this.observe = observe;
1816
+ this.deviceOptions = deviceOptions;
1800
1817
  }
1801
1818
  testkit;
1802
1819
  seed;
1803
1820
  emit;
1804
1821
  directory;
1805
1822
  observe;
1823
+ deviceOptions;
1806
1824
  codes = /* @__PURE__ */ new Map();
1807
1825
  refreshTokens = /* @__PURE__ */ new Map();
1808
1826
  signedUpUsers = /* @__PURE__ */ new Map();
1809
- async handle(req, res, url, readBody) {
1827
+ devices = /* @__PURE__ */ new Map();
1828
+ registeredClients = /* @__PURE__ */ new Map();
1829
+ async handle(req, res, url, readBody, readJson2 = async () => ({})) {
1810
1830
  const method = req.method ?? "GET";
1811
1831
  switch (`${method} ${url.pathname}`) {
1832
+ case "POST /oauth2/device/auth":
1833
+ this.deviceAuthorization(res, await readBody());
1834
+ return true;
1835
+ case "GET /device":
1836
+ this.devicePage(res, url.searchParams);
1837
+ return true;
1838
+ case "GET /device/sign-in":
1839
+ this.deviceSignIn(res, url.searchParams);
1840
+ return true;
1841
+ case "GET /device/complete":
1842
+ this.deviceComplete(res, url.searchParams);
1843
+ return true;
1844
+ case "POST /device/deny":
1845
+ this.deviceDeny(res, await readBody());
1846
+ return true;
1847
+ case "POST /oauth2/introspect":
1848
+ await this.introspect(req, res, await readBody());
1849
+ return true;
1850
+ case "POST /oauth2/register":
1851
+ this.register(res, await readJson2());
1852
+ return true;
1812
1853
  case "GET /oauth2/auth":
1813
1854
  this.authorize(res, url.searchParams);
1814
1855
  return true;
@@ -1956,8 +1997,14 @@ var AuthorizationServer = class {
1956
1997
  } else if (grantType === "refresh_token") {
1957
1998
  grant = this.redeemRefreshToken(form2, clientId);
1958
1999
  this.observe("session.refresh");
2000
+ } else if (grantType === DEVICE_CODE_GRANT) {
2001
+ grant = this.pollDevice(form2, clientId);
1959
2002
  } else {
1960
- throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
2003
+ throw new OAuthError(
2004
+ 400,
2005
+ "unsupported_grant_type",
2006
+ `kinde-testkit supports authorization_code, refresh_token, client_credentials and ${DEVICE_CODE_GRANT}, not "${grantType ?? ""}".`
2007
+ );
1961
2008
  }
1962
2009
  sendJson(res, 200, await this.issueTokens(grant));
1963
2010
  } catch (error) {
@@ -1975,6 +2022,7 @@ var AuthorizationServer = class {
1975
2022
  const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
1976
2023
  const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
1977
2024
  const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
2025
+ this.checkAudience(app?.audience ?? null, audience);
1978
2026
  return {
1979
2027
  access_token: await this.testkit.m2mToken({
1980
2028
  clientId,
@@ -1993,6 +2041,201 @@ var AuthorizationServer = class {
1993
2041
  this.codes.clear();
1994
2042
  this.refreshTokens.clear();
1995
2043
  this.signedUpUsers.clear();
2044
+ this.devices.clear();
2045
+ this.registeredClients.clear();
2046
+ }
2047
+ /** A seeded application that lists audiences may only ask for those, as in Kinde, where each API must be authorized for the app. */
2048
+ checkAudience(allowed, requested) {
2049
+ if (!allowed) return;
2050
+ const refused = requested.find((audience) => !allowed.includes(audience));
2051
+ if (refused) {
2052
+ throw new OAuthError(
2053
+ 400,
2054
+ "invalid_request",
2055
+ `The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Requested audience '${refused}' has not been whitelisted by the OAuth 2.0 Client.`
2056
+ );
2057
+ }
2058
+ }
2059
+ deviceAuthorization(res, form2) {
2060
+ try {
2061
+ const clientId = form2.client_id || DEFAULT_CLIENT_ID;
2062
+ const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
2063
+ const app = this.seed.applications.find((a) => a.clientId === clientId);
2064
+ this.checkAudience(app?.audience ?? null, audience);
2065
+ const interval = this.deviceOptions.intervalSeconds ?? 5;
2066
+ const expiresIn = this.deviceOptions.expiresInSeconds ?? 600;
2067
+ const device = {
2068
+ deviceCode: `kinde_dc_${randomToken()}`,
2069
+ userCode: userCode(),
2070
+ clientId,
2071
+ scope: (form2.scope ?? "").split(/\s+/).filter(Boolean),
2072
+ audience,
2073
+ expiresAt: Date.now() + expiresIn * 1e3,
2074
+ interval,
2075
+ lastPollAt: 0,
2076
+ status: "pending",
2077
+ grant: null
2078
+ };
2079
+ this.devices.set(device.deviceCode, device);
2080
+ this.observe("session.device");
2081
+ const verification = `${this.testkit.issuer}/device`;
2082
+ sendJson(res, 200, {
2083
+ device_code: device.deviceCode,
2084
+ user_code: device.userCode,
2085
+ verification_uri: verification,
2086
+ verification_uri_complete: `${verification}?user_code=${device.userCode}`,
2087
+ expires_in: expiresIn,
2088
+ interval
2089
+ });
2090
+ } catch (error) {
2091
+ if (error instanceof OAuthError) return sendJson(res, error.status, { error: error.error, error_description: error.message });
2092
+ throw error;
2093
+ }
2094
+ }
2095
+ findDevice(userCode2) {
2096
+ const wanted = (userCode2 ?? "").toUpperCase().replace(/[^A-Z]/g, "");
2097
+ for (const device of this.devices.values()) {
2098
+ if (device.userCode === wanted && device.status === "pending" && device.expiresAt > Date.now()) return device;
2099
+ }
2100
+ return null;
2101
+ }
2102
+ devicePage(res, params) {
2103
+ const code = params.get("user_code");
2104
+ if (!code) return sendHtml(res, 200, renderDeviceCodeEntry());
2105
+ const device = this.findDevice(code);
2106
+ if (!device) return sendHtml(res, 400, renderDeviceCodeEntry({ userCode: code, error: "That code is unknown, expired or already used." }));
2107
+ sendHtml(res, 200, renderDeviceConfirm({ userCode: device.userCode, clientId: device.clientId }));
2108
+ }
2109
+ deviceSignIn(res, params) {
2110
+ const device = this.findDevice(params.get("user_code"));
2111
+ if (!device) return sendHtml(res, 400, renderDeviceCodeEntry({ error: "That code is unknown, expired or already used." }));
2112
+ const request = {
2113
+ clientId: device.clientId,
2114
+ redirectUri: `${this.testkit.issuer}/device/complete?user_code=${device.userCode}`,
2115
+ state: null,
2116
+ scope: device.scope,
2117
+ nonce: null,
2118
+ audience: device.audience,
2119
+ orgCode: null,
2120
+ loginHint: params.get("login_hint"),
2121
+ codeChallenge: null,
2122
+ codeChallengeMethod: null
2123
+ };
2124
+ sendHtml(res, 200, renderSignIn({ request: encodeRequest(request), users: this.loginPageUsers(), loginHint: request.loginHint ?? void 0 }));
2125
+ }
2126
+ deviceComplete(res, params) {
2127
+ const device = this.findDevice(params.get("user_code"));
2128
+ const pending = this.codes.get(params.get("code") ?? "");
2129
+ this.codes.delete(params.get("code") ?? "");
2130
+ if (!device || !pending || pending.clientId !== device.clientId) {
2131
+ return sendHtml(res, 400, renderMessage("Device not connected", "The code expired or was already used. Start again on the device."));
2132
+ }
2133
+ device.status = "approved";
2134
+ device.grant = { ...pending, scope: device.scope, audience: device.audience };
2135
+ sendHtml(res, 200, renderMessage("Device connected", "You can go back to your device. It signs in the next time it checks."));
2136
+ }
2137
+ deviceDeny(res, form2) {
2138
+ const device = this.findDevice(form2.user_code);
2139
+ if (device) device.status = "denied";
2140
+ sendHtml(res, 200, renderMessage("Device denied", "The device will not be signed in."));
2141
+ }
2142
+ /** Approves or denies a device without a browser. Used by POST /testkit/device. */
2143
+ resolveDevice(input) {
2144
+ const device = this.findDevice(input.userCode);
2145
+ if (!device) throw new OAuthError(400, "invalid_request", `No pending device has the user code "${input.userCode}".`);
2146
+ if (input.deny) {
2147
+ device.status = "denied";
2148
+ return;
2149
+ }
2150
+ if (!input.user) throw new OAuthError(400, "invalid_request", "Pass the user who approves the device.");
2151
+ const scenario = seedScenario(this.seed, { user: input.user, organization: input.organization ?? void 0 });
2152
+ device.status = "approved";
2153
+ device.grant = {
2154
+ clientId: device.clientId,
2155
+ scenario,
2156
+ scope: device.scope,
2157
+ audience: device.audience,
2158
+ nonce: null,
2159
+ authTime: Math.floor(Date.now() / 1e3)
2160
+ };
2161
+ }
2162
+ pollDevice(form2, clientId) {
2163
+ const device = this.devices.get(form2.device_code ?? "");
2164
+ if (!device || device.clientId !== clientId) {
2165
+ throw new OAuthError(400, "invalid_grant", "The device code is unknown or was issued to a different client.");
2166
+ }
2167
+ if (device.expiresAt <= Date.now()) {
2168
+ this.devices.delete(device.deviceCode);
2169
+ throw new OAuthError(400, "expired_token", "The device code has expired. Request a new one.");
2170
+ }
2171
+ if (device.status === "denied") {
2172
+ this.devices.delete(device.deviceCode);
2173
+ throw new OAuthError(400, "access_denied", "The user denied the device.");
2174
+ }
2175
+ if (device.status === "pending") {
2176
+ const now = Date.now();
2177
+ const tooSoon = device.lastPollAt > 0 && now - device.lastPollAt < device.interval * 1e3;
2178
+ device.lastPollAt = now;
2179
+ if (tooSoon) {
2180
+ device.interval += 5;
2181
+ throw new OAuthError(400, "slow_down", `Poll at most every ${device.interval} seconds.`);
2182
+ }
2183
+ throw new OAuthError(400, "authorization_pending", "The user has not finished signing in.");
2184
+ }
2185
+ this.devices.delete(device.deviceCode);
2186
+ this.observe("session.device-approved");
2187
+ return device.grant;
2188
+ }
2189
+ async introspect(req, res, form2) {
2190
+ const header = req.headers.authorization ?? "";
2191
+ if (!header.startsWith("Bearer ")) {
2192
+ return sendJson(res, 401, { error: "request_unauthorized", error_description: "The request could not be authorized. HTTP Authorization header missing." });
2193
+ }
2194
+ const bearer = header.slice(7);
2195
+ const token = form2.token ?? "";
2196
+ if (bearer === token) {
2197
+ return sendJson(res, 401, { error: "request_unauthorized", error_description: "The request could not be authorized. Bearer and introspection token are identical." });
2198
+ }
2199
+ try {
2200
+ await this.testkit.verify(bearer);
2201
+ } catch {
2202
+ return sendJson(res, 401, { error: "request_unauthorized", error_description: "The request could not be authorized. The Bearer token is not valid for this issuer." });
2203
+ }
2204
+ if (!token) return sendJson(res, 400, { error: "invalid_request", error_description: "Send the token to introspect in the token field." });
2205
+ this.observe("token.introspect");
2206
+ const refresh = this.refreshTokens.get(token);
2207
+ if (refresh) return sendJson(res, 200, { active: true, client_id: refresh.clientId });
2208
+ try {
2209
+ const claims = await this.testkit.verify(token);
2210
+ const aud = claims.aud === void 0 ? [] : Array.isArray(claims.aud) ? claims.aud : [claims.aud];
2211
+ sendJson(res, 200, { active: true, aud, client_id: claims.azp ?? null, exp: claims.exp, iat: claims.iat });
2212
+ } catch {
2213
+ sendJson(res, 200, { active: false });
2214
+ }
2215
+ }
2216
+ /** OAuth dynamic client registration (RFC 7591), which Kinde offers for MCP connectors. */
2217
+ register(res, body) {
2218
+ const input = typeof body === "object" && body !== null && !Array.isArray(body) ? body : {};
2219
+ const redirectUris = Array.isArray(input.redirect_uris) ? input.redirect_uris.filter((uri) => typeof uri === "string") : [];
2220
+ if (redirectUris.length === 0 || !redirectUris.every(isHttpUrl2)) {
2221
+ return sendJson(res, 400, { error: "invalid_redirect_uri", error_description: "Redirect URI is not allowed for MCP connector registration" });
2222
+ }
2223
+ const client = {
2224
+ client_id: randomBytes4(16).toString("hex"),
2225
+ client_id_issued_at: Math.floor(Date.now() / 1e3),
2226
+ ...typeof input.client_name === "string" ? { client_name: input.client_name } : {},
2227
+ redirect_uris: redirectUris,
2228
+ grant_types: ["authorization_code", "refresh_token"],
2229
+ response_types: ["code"],
2230
+ token_endpoint_auth_method: "none"
2231
+ };
2232
+ this.registeredClients.set(client.client_id, client);
2233
+ this.observe("session.register");
2234
+ sendJson(res, 201, client);
2235
+ }
2236
+ /** Clients registered through /oauth2/register since the last reset. */
2237
+ registrations() {
2238
+ return [...this.registeredClients.values()];
1996
2239
  }
1997
2240
  redeemCode(form2, clientId) {
1998
2241
  const code = form2.code ?? "";
@@ -2197,6 +2440,9 @@ function isHttpUrl2(value) {
2197
2440
  return false;
2198
2441
  }
2199
2442
  }
2443
+ function userCode() {
2444
+ return Array.from(randomBytes4(8), (byte) => USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length]).join("");
2445
+ }
2200
2446
  function randomToken() {
2201
2447
  return randomBytes4(32).toString("base64url");
2202
2448
  }
@@ -2984,7 +3230,7 @@ async function startKindeTestkit(options = {}) {
2984
3230
  const directory = new Directory(seed);
2985
3231
  const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
2986
3232
  webhooks.observe = observe;
2987
- const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
3233
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe, options.device);
2988
3234
  const management = new ManagementApi(testkit, directory, webhooks);
2989
3235
  const account = new AccountApi(testkit, directory);
2990
3236
  const reset = () => {
@@ -3059,7 +3305,7 @@ async function handle(req, res, context) {
3059
3305
  }
3060
3306
  }
3061
3307
  }
3062
- if (await auth.handle(req, res, url, () => readForm(req))) return;
3308
+ if (await auth.handle(req, res, url, () => readForm(req), () => readJson(req))) return;
3063
3309
  if (await context.management.handle(req, res, url, async () => await readJson(req))) {
3064
3310
  if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
3065
3311
  else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
@@ -3119,6 +3365,21 @@ async function handle(req, res, context) {
3119
3365
  const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
3120
3366
  return sendJson4(res, removed ? 200 : 404, { ok: removed });
3121
3367
  }
3368
+ if (method === "POST" && pathname === "/testkit/device") {
3369
+ const input = await readJson(req);
3370
+ try {
3371
+ auth.resolveDevice({
3372
+ userCode: String(input.user_code ?? ""),
3373
+ user: typeof input.user === "string" ? input.user : void 0,
3374
+ organization: typeof input.organization === "string" ? input.organization : null,
3375
+ deny: input.action === "deny"
3376
+ });
3377
+ } catch (error) {
3378
+ if (error instanceof OAuthError) return sendJson4(res, error.status, { error: error.error, error_description: error.message });
3379
+ throw error;
3380
+ }
3381
+ return sendJson4(res, 200, { ok: true });
3382
+ }
3122
3383
  if (method === "POST" && pathname === "/testkit/reset") {
3123
3384
  context.reset();
3124
3385
  return sendJson4(res, 200, { ok: true });
@@ -3242,20 +3503,26 @@ function discovery(testkit) {
3242
3503
  const base = testkit.issuer;
3243
3504
  return {
3244
3505
  issuer: base,
3245
- authorization_endpoint: `${base}/oauth2/auth`,
3506
+ jwks_uri: `${base}/.well-known/jwks`,
3246
3507
  token_endpoint: `${base}/oauth2/token`,
3508
+ claims_supported: ["aud", "exp", "iat", "iss", "sub", "acr", "amr", "auth_time"],
3509
+ scopes_supported: ["address", "email", "offline", "openid", "phone", "profile"],
3247
3510
  userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
3248
- end_session_endpoint: `${base}/logout`,
3249
3511
  revocation_endpoint: `${base}/oauth2/revoke`,
3250
- jwks_uri: `${base}/.well-known/jwks`,
3251
- response_types_supported: ["code"],
3252
- grant_types_supported: ["authorization_code", "refresh_token"],
3253
- code_challenge_methods_supported: ["S256", "plain"],
3512
+ end_session_endpoint: `${base}/logout`,
3513
+ grant_types_supported: ["authorization_code", "refresh_token", "client_credentials", "urn:ietf:params:oauth:grant-type:device_code"],
3514
+ registration_endpoint: `${base}/oauth2/register`,
3515
+ authorization_endpoint: `${base}/oauth2/auth`,
3516
+ introspection_endpoint: `${base}/oauth2/introspect`,
3254
3517
  subject_types_supported: ["public"],
3518
+ response_modes_supported: ["query"],
3519
+ response_types_supported: ["code"],
3520
+ device_authorization_endpoint: `${base}/oauth2/device/auth`,
3521
+ request_uri_parameter_supported: false,
3522
+ code_challenge_methods_supported: ["S256"],
3523
+ client_id_metadata_document_supported: false,
3255
3524
  id_token_signing_alg_values_supported: ["RS256"],
3256
- scopes_supported: ["openid", "profile", "email", "offline"],
3257
- token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic", "none"],
3258
- claims_supported: ["aud", "exp", "iat", "iss", "sub", "org_code", "permissions", "roles", "scp"]
3525
+ token_endpoint_auth_methods_supported: ["client_secret_post", "none"]
3259
3526
  };
3260
3527
  }
3261
3528
  async function issueToken(testkit, seed, body) {
@@ -3427,4 +3694,4 @@ export {
3427
3694
  loadSeedFile,
3428
3695
  startKindeTestkit
3429
3696
  };
3430
- //# sourceMappingURL=chunk-GCOZVCZY.js.map
3697
+ //# sourceMappingURL=chunk-JTAB2S44.js.map