kinde-testkit 0.6.1 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.1
4
+
5
+ - Management API responses now have every field a real Kinde business returns: `full_name` and `last_organization_sign_ins` on users, `created_on` on organizations in lists, and `is_organization_role_assignable` on permissions. Found by the contract tests.
6
+
7
+ ## 0.7.0
8
+
9
+ Found by running the new contract tests against a real Kinde business.
10
+
11
+ - 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.
12
+ - Add token introspection at `/oauth2/introspect` and dynamic client registration at `/oauth2/register`, with the same errors Kinde returns.
13
+ - A seeded application that lists `audience` may now only request those audiences, and gets Kinde's "has not been whitelisted" error for any other.
14
+ - The discovery document now lists the same endpoints and grant types as a Kinde business.
15
+ - Coverage adds a device sign-in item.
16
+ - The contract tests also compare introspection and registration errors, and explain how to authorize the Management API when Kinde refuses the M2M token.
17
+
3
18
  ## 0.6.1
4
19
 
5
20
  - 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 |
@@ -898,7 +898,8 @@ var Directory = class {
898
898
  isPasswordResetRequested: false,
899
899
  createdOn: (/* @__PURE__ */ new Date()).toISOString(),
900
900
  totalSignIns: 0,
901
- lastSignedIn: null
901
+ lastSignedIn: null,
902
+ lastOrganizationSignIns: {}
902
903
  };
903
904
  this.userMeta.set(user.id, meta);
904
905
  }
@@ -911,7 +912,7 @@ var Directory = class {
911
912
  const meta = this.meta(user);
912
913
  meta.totalSignIns += 1;
913
914
  meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
914
- void organizationCode;
915
+ if (organizationCode) meta.lastOrganizationSignIns[organizationCode] = meta.lastSignedIn;
915
916
  }
916
917
  createUser(input) {
917
918
  const user = createKindeUser({
@@ -1491,7 +1492,8 @@ var COVERAGE_GROUPS = [
1491
1492
  { id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
1492
1493
  { id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
1493
1494
  { 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." }
1495
+ { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." },
1496
+ { id: "session.device-approved", label: "Device sign-in", hint: "Run the device authorization flow and approve it with POST /testkit/device." }
1495
1497
  ]
1496
1498
  },
1497
1499
  {
@@ -1777,10 +1779,25 @@ function renderOrganizationPicker(options) {
1777
1779
  function renderMessage(title, message) {
1778
1780
  return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
1779
1781
  }
1782
+ function renderDeviceCodeEntry(options = {}) {
1783
+ return layout(
1784
+ "Connect a device",
1785
+ `<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>`
1786
+ );
1787
+ }
1788
+ function renderDeviceConfirm(options) {
1789
+ const code = escapeHtml(options.userCode);
1790
+ return layout(
1791
+ "Connect a device",
1792
+ `<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>`
1793
+ );
1794
+ }
1780
1795
 
1781
1796
  // src/oauth.ts
1782
1797
  import { createHash as createHash3, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
1783
1798
  var CODE_LIFETIME_MS = 10 * 60 * 1e3;
1799
+ var DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
1800
+ var USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
1784
1801
  var OAuthError = class extends Error {
1785
1802
  constructor(status, error, description) {
1786
1803
  super(description);
@@ -1791,24 +1808,49 @@ var OAuthError = class extends Error {
1791
1808
  error;
1792
1809
  };
1793
1810
  var AuthorizationServer = class {
1794
- constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
1811
+ constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0, deviceOptions = {}) {
1795
1812
  this.testkit = testkit;
1796
1813
  this.seed = seed;
1797
1814
  this.emit = emit;
1798
1815
  this.directory = directory;
1799
1816
  this.observe = observe;
1817
+ this.deviceOptions = deviceOptions;
1800
1818
  }
1801
1819
  testkit;
1802
1820
  seed;
1803
1821
  emit;
1804
1822
  directory;
1805
1823
  observe;
1824
+ deviceOptions;
1806
1825
  codes = /* @__PURE__ */ new Map();
1807
1826
  refreshTokens = /* @__PURE__ */ new Map();
1808
1827
  signedUpUsers = /* @__PURE__ */ new Map();
1809
- async handle(req, res, url, readBody) {
1828
+ devices = /* @__PURE__ */ new Map();
1829
+ registeredClients = /* @__PURE__ */ new Map();
1830
+ async handle(req, res, url, readBody, readJson2 = async () => ({})) {
1810
1831
  const method = req.method ?? "GET";
1811
1832
  switch (`${method} ${url.pathname}`) {
1833
+ case "POST /oauth2/device/auth":
1834
+ this.deviceAuthorization(res, await readBody());
1835
+ return true;
1836
+ case "GET /device":
1837
+ this.devicePage(res, url.searchParams);
1838
+ return true;
1839
+ case "GET /device/sign-in":
1840
+ this.deviceSignIn(res, url.searchParams);
1841
+ return true;
1842
+ case "GET /device/complete":
1843
+ this.deviceComplete(res, url.searchParams);
1844
+ return true;
1845
+ case "POST /device/deny":
1846
+ this.deviceDeny(res, await readBody());
1847
+ return true;
1848
+ case "POST /oauth2/introspect":
1849
+ await this.introspect(req, res, await readBody());
1850
+ return true;
1851
+ case "POST /oauth2/register":
1852
+ this.register(res, await readJson2());
1853
+ return true;
1812
1854
  case "GET /oauth2/auth":
1813
1855
  this.authorize(res, url.searchParams);
1814
1856
  return true;
@@ -1956,8 +1998,14 @@ var AuthorizationServer = class {
1956
1998
  } else if (grantType === "refresh_token") {
1957
1999
  grant = this.redeemRefreshToken(form2, clientId);
1958
2000
  this.observe("session.refresh");
2001
+ } else if (grantType === DEVICE_CODE_GRANT) {
2002
+ grant = this.pollDevice(form2, clientId);
1959
2003
  } else {
1960
- throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
2004
+ throw new OAuthError(
2005
+ 400,
2006
+ "unsupported_grant_type",
2007
+ `kinde-testkit supports authorization_code, refresh_token, client_credentials and ${DEVICE_CODE_GRANT}, not "${grantType ?? ""}".`
2008
+ );
1961
2009
  }
1962
2010
  sendJson(res, 200, await this.issueTokens(grant));
1963
2011
  } catch (error) {
@@ -1975,6 +2023,7 @@ var AuthorizationServer = class {
1975
2023
  const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
1976
2024
  const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
1977
2025
  const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
2026
+ this.checkAudience(app?.audience ?? null, audience);
1978
2027
  return {
1979
2028
  access_token: await this.testkit.m2mToken({
1980
2029
  clientId,
@@ -1993,6 +2042,201 @@ var AuthorizationServer = class {
1993
2042
  this.codes.clear();
1994
2043
  this.refreshTokens.clear();
1995
2044
  this.signedUpUsers.clear();
2045
+ this.devices.clear();
2046
+ this.registeredClients.clear();
2047
+ }
2048
+ /** A seeded application that lists audiences may only ask for those, as in Kinde, where each API must be authorized for the app. */
2049
+ checkAudience(allowed, requested) {
2050
+ if (!allowed) return;
2051
+ const refused = requested.find((audience) => !allowed.includes(audience));
2052
+ if (refused) {
2053
+ throw new OAuthError(
2054
+ 400,
2055
+ "invalid_request",
2056
+ `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.`
2057
+ );
2058
+ }
2059
+ }
2060
+ deviceAuthorization(res, form2) {
2061
+ try {
2062
+ const clientId = form2.client_id || DEFAULT_CLIENT_ID;
2063
+ const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
2064
+ const app = this.seed.applications.find((a) => a.clientId === clientId);
2065
+ this.checkAudience(app?.audience ?? null, audience);
2066
+ const interval = this.deviceOptions.intervalSeconds ?? 5;
2067
+ const expiresIn = this.deviceOptions.expiresInSeconds ?? 600;
2068
+ const device = {
2069
+ deviceCode: `kinde_dc_${randomToken()}`,
2070
+ userCode: userCode(),
2071
+ clientId,
2072
+ scope: (form2.scope ?? "").split(/\s+/).filter(Boolean),
2073
+ audience,
2074
+ expiresAt: Date.now() + expiresIn * 1e3,
2075
+ interval,
2076
+ lastPollAt: 0,
2077
+ status: "pending",
2078
+ grant: null
2079
+ };
2080
+ this.devices.set(device.deviceCode, device);
2081
+ this.observe("session.device");
2082
+ const verification = `${this.testkit.issuer}/device`;
2083
+ sendJson(res, 200, {
2084
+ device_code: device.deviceCode,
2085
+ user_code: device.userCode,
2086
+ verification_uri: verification,
2087
+ verification_uri_complete: `${verification}?user_code=${device.userCode}`,
2088
+ expires_in: expiresIn,
2089
+ interval
2090
+ });
2091
+ } catch (error) {
2092
+ if (error instanceof OAuthError) return sendJson(res, error.status, { error: error.error, error_description: error.message });
2093
+ throw error;
2094
+ }
2095
+ }
2096
+ findDevice(userCode2) {
2097
+ const wanted = (userCode2 ?? "").toUpperCase().replace(/[^A-Z]/g, "");
2098
+ for (const device of this.devices.values()) {
2099
+ if (device.userCode === wanted && device.status === "pending" && device.expiresAt > Date.now()) return device;
2100
+ }
2101
+ return null;
2102
+ }
2103
+ devicePage(res, params) {
2104
+ const code = params.get("user_code");
2105
+ if (!code) return sendHtml(res, 200, renderDeviceCodeEntry());
2106
+ const device = this.findDevice(code);
2107
+ if (!device) return sendHtml(res, 400, renderDeviceCodeEntry({ userCode: code, error: "That code is unknown, expired or already used." }));
2108
+ sendHtml(res, 200, renderDeviceConfirm({ userCode: device.userCode, clientId: device.clientId }));
2109
+ }
2110
+ deviceSignIn(res, params) {
2111
+ const device = this.findDevice(params.get("user_code"));
2112
+ if (!device) return sendHtml(res, 400, renderDeviceCodeEntry({ error: "That code is unknown, expired or already used." }));
2113
+ const request = {
2114
+ clientId: device.clientId,
2115
+ redirectUri: `${this.testkit.issuer}/device/complete?user_code=${device.userCode}`,
2116
+ state: null,
2117
+ scope: device.scope,
2118
+ nonce: null,
2119
+ audience: device.audience,
2120
+ orgCode: null,
2121
+ loginHint: params.get("login_hint"),
2122
+ codeChallenge: null,
2123
+ codeChallengeMethod: null
2124
+ };
2125
+ sendHtml(res, 200, renderSignIn({ request: encodeRequest(request), users: this.loginPageUsers(), loginHint: request.loginHint ?? void 0 }));
2126
+ }
2127
+ deviceComplete(res, params) {
2128
+ const device = this.findDevice(params.get("user_code"));
2129
+ const pending = this.codes.get(params.get("code") ?? "");
2130
+ this.codes.delete(params.get("code") ?? "");
2131
+ if (!device || !pending || pending.clientId !== device.clientId) {
2132
+ return sendHtml(res, 400, renderMessage("Device not connected", "The code expired or was already used. Start again on the device."));
2133
+ }
2134
+ device.status = "approved";
2135
+ device.grant = { ...pending, scope: device.scope, audience: device.audience };
2136
+ sendHtml(res, 200, renderMessage("Device connected", "You can go back to your device. It signs in the next time it checks."));
2137
+ }
2138
+ deviceDeny(res, form2) {
2139
+ const device = this.findDevice(form2.user_code);
2140
+ if (device) device.status = "denied";
2141
+ sendHtml(res, 200, renderMessage("Device denied", "The device will not be signed in."));
2142
+ }
2143
+ /** Approves or denies a device without a browser. Used by POST /testkit/device. */
2144
+ resolveDevice(input) {
2145
+ const device = this.findDevice(input.userCode);
2146
+ if (!device) throw new OAuthError(400, "invalid_request", `No pending device has the user code "${input.userCode}".`);
2147
+ if (input.deny) {
2148
+ device.status = "denied";
2149
+ return;
2150
+ }
2151
+ if (!input.user) throw new OAuthError(400, "invalid_request", "Pass the user who approves the device.");
2152
+ const scenario = seedScenario(this.seed, { user: input.user, organization: input.organization ?? void 0 });
2153
+ device.status = "approved";
2154
+ device.grant = {
2155
+ clientId: device.clientId,
2156
+ scenario,
2157
+ scope: device.scope,
2158
+ audience: device.audience,
2159
+ nonce: null,
2160
+ authTime: Math.floor(Date.now() / 1e3)
2161
+ };
2162
+ }
2163
+ pollDevice(form2, clientId) {
2164
+ const device = this.devices.get(form2.device_code ?? "");
2165
+ if (!device || device.clientId !== clientId) {
2166
+ throw new OAuthError(400, "invalid_grant", "The device code is unknown or was issued to a different client.");
2167
+ }
2168
+ if (device.expiresAt <= Date.now()) {
2169
+ this.devices.delete(device.deviceCode);
2170
+ throw new OAuthError(400, "expired_token", "The device code has expired. Request a new one.");
2171
+ }
2172
+ if (device.status === "denied") {
2173
+ this.devices.delete(device.deviceCode);
2174
+ throw new OAuthError(400, "access_denied", "The user denied the device.");
2175
+ }
2176
+ if (device.status === "pending") {
2177
+ const now = Date.now();
2178
+ const tooSoon = device.lastPollAt > 0 && now - device.lastPollAt < device.interval * 1e3;
2179
+ device.lastPollAt = now;
2180
+ if (tooSoon) {
2181
+ device.interval += 5;
2182
+ throw new OAuthError(400, "slow_down", `Poll at most every ${device.interval} seconds.`);
2183
+ }
2184
+ throw new OAuthError(400, "authorization_pending", "The user has not finished signing in.");
2185
+ }
2186
+ this.devices.delete(device.deviceCode);
2187
+ this.observe("session.device-approved");
2188
+ return device.grant;
2189
+ }
2190
+ async introspect(req, res, form2) {
2191
+ const header = req.headers.authorization ?? "";
2192
+ if (!header.startsWith("Bearer ")) {
2193
+ return sendJson(res, 401, { error: "request_unauthorized", error_description: "The request could not be authorized. HTTP Authorization header missing." });
2194
+ }
2195
+ const bearer = header.slice(7);
2196
+ const token = form2.token ?? "";
2197
+ if (bearer === token) {
2198
+ return sendJson(res, 401, { error: "request_unauthorized", error_description: "The request could not be authorized. Bearer and introspection token are identical." });
2199
+ }
2200
+ try {
2201
+ await this.testkit.verify(bearer);
2202
+ } catch {
2203
+ return sendJson(res, 401, { error: "request_unauthorized", error_description: "The request could not be authorized. The Bearer token is not valid for this issuer." });
2204
+ }
2205
+ if (!token) return sendJson(res, 400, { error: "invalid_request", error_description: "Send the token to introspect in the token field." });
2206
+ this.observe("token.introspect");
2207
+ const refresh = this.refreshTokens.get(token);
2208
+ if (refresh) return sendJson(res, 200, { active: true, client_id: refresh.clientId });
2209
+ try {
2210
+ const claims = await this.testkit.verify(token);
2211
+ const aud = claims.aud === void 0 ? [] : Array.isArray(claims.aud) ? claims.aud : [claims.aud];
2212
+ sendJson(res, 200, { active: true, aud, client_id: claims.azp ?? null, exp: claims.exp, iat: claims.iat });
2213
+ } catch {
2214
+ sendJson(res, 200, { active: false });
2215
+ }
2216
+ }
2217
+ /** OAuth dynamic client registration (RFC 7591), which Kinde offers for MCP connectors. */
2218
+ register(res, body) {
2219
+ const input = typeof body === "object" && body !== null && !Array.isArray(body) ? body : {};
2220
+ const redirectUris = Array.isArray(input.redirect_uris) ? input.redirect_uris.filter((uri) => typeof uri === "string") : [];
2221
+ if (redirectUris.length === 0 || !redirectUris.every(isHttpUrl2)) {
2222
+ return sendJson(res, 400, { error: "invalid_redirect_uri", error_description: "Redirect URI is not allowed for MCP connector registration" });
2223
+ }
2224
+ const client = {
2225
+ client_id: randomBytes4(16).toString("hex"),
2226
+ client_id_issued_at: Math.floor(Date.now() / 1e3),
2227
+ ...typeof input.client_name === "string" ? { client_name: input.client_name } : {},
2228
+ redirect_uris: redirectUris,
2229
+ grant_types: ["authorization_code", "refresh_token"],
2230
+ response_types: ["code"],
2231
+ token_endpoint_auth_method: "none"
2232
+ };
2233
+ this.registeredClients.set(client.client_id, client);
2234
+ this.observe("session.register");
2235
+ sendJson(res, 201, client);
2236
+ }
2237
+ /** Clients registered through /oauth2/register since the last reset. */
2238
+ registrations() {
2239
+ return [...this.registeredClients.values()];
1996
2240
  }
1997
2241
  redeemCode(form2, clientId) {
1998
2242
  const code = form2.code ?? "";
@@ -2197,6 +2441,9 @@ function isHttpUrl2(value) {
2197
2441
  return false;
2198
2442
  }
2199
2443
  }
2444
+ function userCode() {
2445
+ return Array.from(randomBytes4(8), (byte) => USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length]).join("");
2446
+ }
2200
2447
  function randomToken() {
2201
2448
  return randomBytes4(32).toString("base64url");
2202
2449
  }
@@ -2682,12 +2929,14 @@ var ManagementApi = class {
2682
2929
  username: null,
2683
2930
  last_name: user.familyName,
2684
2931
  first_name: user.givenName,
2932
+ full_name: [user.givenName, user.familyName].filter(Boolean).join(" ") || null,
2685
2933
  is_suspended: meta.isSuspended,
2686
2934
  picture: user.picture,
2687
2935
  total_sign_ins: meta.totalSignIns,
2688
2936
  failed_sign_ins: 0,
2689
2937
  last_signed_in: meta.lastSignedIn,
2690
2938
  created_on: meta.createdOn,
2939
+ last_organization_sign_ins: Object.entries(meta.lastOrganizationSignIns).map(([org_code, last_signed_in]) => ({ org_code, last_signed_in })),
2691
2940
  organizations: this.organizationsOf(user),
2692
2941
  identities: user.email ? [{ type: "email", identity: user.email }] : []
2693
2942
  };
@@ -2707,7 +2956,8 @@ var ManagementApi = class {
2707
2956
  handle: meta.handle,
2708
2957
  is_default: false,
2709
2958
  external_id: meta.externalId,
2710
- is_auto_membership_enabled: false
2959
+ is_auto_membership_enabled: false,
2960
+ created_on: meta.createdOn
2711
2961
  };
2712
2962
  }
2713
2963
  organizationEvent(org) {
@@ -2718,7 +2968,7 @@ var ManagementApi = class {
2718
2968
  return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
2719
2969
  }
2720
2970
  permissionItem(permission) {
2721
- return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
2971
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, is_organization_role_assignable: false };
2722
2972
  }
2723
2973
  };
2724
2974
  function paginate(items, query) {
@@ -2984,7 +3234,7 @@ async function startKindeTestkit(options = {}) {
2984
3234
  const directory = new Directory(seed);
2985
3235
  const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
2986
3236
  webhooks.observe = observe;
2987
- const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
3237
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe, options.device);
2988
3238
  const management = new ManagementApi(testkit, directory, webhooks);
2989
3239
  const account = new AccountApi(testkit, directory);
2990
3240
  const reset = () => {
@@ -3059,7 +3309,7 @@ async function handle(req, res, context) {
3059
3309
  }
3060
3310
  }
3061
3311
  }
3062
- if (await auth.handle(req, res, url, () => readForm(req))) return;
3312
+ if (await auth.handle(req, res, url, () => readForm(req), () => readJson(req))) return;
3063
3313
  if (await context.management.handle(req, res, url, async () => await readJson(req))) {
3064
3314
  if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
3065
3315
  else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
@@ -3119,6 +3369,21 @@ async function handle(req, res, context) {
3119
3369
  const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
3120
3370
  return sendJson4(res, removed ? 200 : 404, { ok: removed });
3121
3371
  }
3372
+ if (method === "POST" && pathname === "/testkit/device") {
3373
+ const input = await readJson(req);
3374
+ try {
3375
+ auth.resolveDevice({
3376
+ userCode: String(input.user_code ?? ""),
3377
+ user: typeof input.user === "string" ? input.user : void 0,
3378
+ organization: typeof input.organization === "string" ? input.organization : null,
3379
+ deny: input.action === "deny"
3380
+ });
3381
+ } catch (error) {
3382
+ if (error instanceof OAuthError) return sendJson4(res, error.status, { error: error.error, error_description: error.message });
3383
+ throw error;
3384
+ }
3385
+ return sendJson4(res, 200, { ok: true });
3386
+ }
3122
3387
  if (method === "POST" && pathname === "/testkit/reset") {
3123
3388
  context.reset();
3124
3389
  return sendJson4(res, 200, { ok: true });
@@ -3242,20 +3507,26 @@ function discovery(testkit) {
3242
3507
  const base = testkit.issuer;
3243
3508
  return {
3244
3509
  issuer: base,
3245
- authorization_endpoint: `${base}/oauth2/auth`,
3510
+ jwks_uri: `${base}/.well-known/jwks`,
3246
3511
  token_endpoint: `${base}/oauth2/token`,
3512
+ claims_supported: ["aud", "exp", "iat", "iss", "sub", "acr", "amr", "auth_time"],
3513
+ scopes_supported: ["address", "email", "offline", "openid", "phone", "profile"],
3247
3514
  userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
3248
- end_session_endpoint: `${base}/logout`,
3249
3515
  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"],
3516
+ end_session_endpoint: `${base}/logout`,
3517
+ grant_types_supported: ["authorization_code", "refresh_token", "client_credentials", "urn:ietf:params:oauth:grant-type:device_code"],
3518
+ registration_endpoint: `${base}/oauth2/register`,
3519
+ authorization_endpoint: `${base}/oauth2/auth`,
3520
+ introspection_endpoint: `${base}/oauth2/introspect`,
3254
3521
  subject_types_supported: ["public"],
3522
+ response_modes_supported: ["query"],
3523
+ response_types_supported: ["code"],
3524
+ device_authorization_endpoint: `${base}/oauth2/device/auth`,
3525
+ request_uri_parameter_supported: false,
3526
+ code_challenge_methods_supported: ["S256"],
3527
+ client_id_metadata_document_supported: false,
3255
3528
  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"]
3529
+ token_endpoint_auth_methods_supported: ["client_secret_post", "none"]
3259
3530
  };
3260
3531
  }
3261
3532
  async function issueToken(testkit, seed, body) {
@@ -3427,4 +3698,4 @@ export {
3427
3698
  loadSeedFile,
3428
3699
  startKindeTestkit
3429
3700
  };
3430
- //# sourceMappingURL=chunk-GCOZVCZY.js.map
3701
+ //# sourceMappingURL=chunk-IOP27RQ5.js.map