kinde-testkit 0.2.1 → 0.3.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.
@@ -4,6 +4,18 @@ function createKindeFixture(page, options) {
4
4
  const issuer = new URL(options.issuer);
5
5
  const onIssuer = (url) => url.origin === issuer.origin;
6
6
  let currentUser = null;
7
+ const injected = /* @__PURE__ */ new Set();
8
+ async function control(path, init = {}) {
9
+ const response = await fetch(`${issuer.origin}${path}`, {
10
+ ...init,
11
+ headers: { "content-type": "application/json", ...init.headers ?? {} }
12
+ });
13
+ if (!response.ok && response.status !== 404) {
14
+ const body = await response.json().catch(() => ({}));
15
+ throw new Error(body.error_description ?? `kinde-testkit answered ${response.status} for ${path}.`);
16
+ }
17
+ return response;
18
+ }
7
19
  async function signInAs(user, signIn = {}) {
8
20
  const params = new URLSearchParams({ login_hint: user });
9
21
  if (signIn.org) params.set("org_code", signIn.org);
@@ -43,6 +55,19 @@ function createKindeFixture(page, options) {
43
55
  async signOut() {
44
56
  await page.goto(options.logoutPath);
45
57
  currentUser = null;
58
+ },
59
+ async injectFailure(rule) {
60
+ const response = await control("/testkit/failures", { method: "POST", body: JSON.stringify(rule) });
61
+ const failure = await response.json();
62
+ injected.add(failure.id);
63
+ return failure;
64
+ },
65
+ async clearFailures() {
66
+ await Promise.all([...injected].map((id) => control(`/testkit/failures/${id}`, { method: "DELETE" })));
67
+ injected.clear();
68
+ },
69
+ async dispose() {
70
+ if (injected.size > 0) await this.clearFailures();
46
71
  }
47
72
  };
48
73
  }
@@ -51,13 +76,13 @@ var test = base.extend({
51
76
  kindeLoginPath: ["/api/auth/login", { option: true }],
52
77
  kindeLogoutPath: ["/api/auth/logout", { option: true }],
53
78
  kinde: async ({ page, kindeIssuer, kindeLoginPath, kindeLogoutPath }, use) => {
54
- await use(
55
- createKindeFixture(page, {
56
- issuer: kindeIssuer,
57
- loginPath: kindeLoginPath,
58
- logoutPath: kindeLogoutPath
59
- })
60
- );
79
+ const fixture = createKindeFixture(page, {
80
+ issuer: kindeIssuer,
81
+ loginPath: kindeLoginPath,
82
+ logoutPath: kindeLogoutPath
83
+ });
84
+ await use(fixture);
85
+ await fixture.dispose();
61
86
  }
62
87
  });
63
88
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/playwright.ts"],"sourcesContent":["import { test as base, expect, type Page } from \"@playwright/test\";\n\nexport interface KindeFixtureOptions {\n issuer: string;\n loginPath: string;\n logoutPath: string;\n}\n\nexport interface SignInOptions {\n org?: string;\n}\n\nexport interface KindeFixture {\n readonly issuer: string;\n readonly currentUser: string | null;\n signInAs(user: string, options?: SignInOptions): Promise<void>;\n switchOrganization(org: string): Promise<void>;\n signOut(): Promise<void>;\n}\n\nexport interface KindeTestOptions {\n kindeIssuer: string;\n kindeLoginPath: string;\n kindeLogoutPath: string;\n}\n\nexport function createKindeFixture(page: Page, options: KindeFixtureOptions): KindeFixture {\n const issuer = new URL(options.issuer);\n const onIssuer = (url: URL) => url.origin === issuer.origin;\n let currentUser: string | null = null;\n\n async function signInAs(user: string, signIn: SignInOptions = {}): Promise<void> {\n const params = new URLSearchParams({ login_hint: user });\n if (signIn.org) params.set(\"org_code\", signIn.org);\n await page.goto(`${options.loginPath}?${params}`);\n\n if (!(onIssuer(new URL(page.url())) && new URL(page.url()).pathname === \"/oauth2/auth\")) {\n throw new Error(\n `Expected ${options.loginPath} to redirect to the kinde-testkit sign-in page at ${issuer.origin}, but the browser is at ${page.url()}. Check that the app's KINDE_ISSUER_URL is ${issuer.origin}.`,\n );\n }\n\n await page.getByLabel(\"Email\").fill(user);\n await page.getByRole(\"button\", { name: \"Continue\", exact: true }).click();\n await page.waitForURL((url) => !(onIssuer(url) && url.pathname === \"/oauth2/auth\"));\n\n const landed = new URL(page.url());\n if (onIssuer(landed)) {\n const alert = page.getByRole(\"alert\");\n if (await alert.count()) {\n throw new Error(`kinde-testkit refused the sign-in: ${(await alert.innerText()).trim()}`);\n }\n if (await page.getByRole(\"heading\", { name: \"Choose an organization\" }).count()) {\n throw new Error(`${user} belongs to more than one organization. Pass one with signInAs(\"${user}\", { org: \"org_...\" }).`);\n }\n throw new Error(`Sign-in stopped on ${page.url()}.`);\n }\n\n await page.waitForURL((url) => !onIssuer(url) && !url.pathname.endsWith(\"/kinde_callback\"));\n currentUser = user;\n }\n\n return {\n issuer: issuer.origin,\n get currentUser() {\n return currentUser;\n },\n signInAs,\n async switchOrganization(org: string) {\n if (!currentUser) throw new Error(\"Call signInAs() before switchOrganization().\");\n await signInAs(currentUser, { org });\n },\n async signOut() {\n await page.goto(options.logoutPath);\n currentUser = null;\n },\n };\n}\n\nexport const test = base.extend<KindeTestOptions & { kinde: KindeFixture }>({\n kindeIssuer: [process.env.KINDE_ISSUER_URL ?? \"http://localhost:4400\", { option: true }],\n kindeLoginPath: [\"/api/auth/login\", { option: true }],\n kindeLogoutPath: [\"/api/auth/logout\", { option: true }],\n kinde: async ({ page, kindeIssuer, kindeLoginPath, kindeLogoutPath }, use) => {\n await use(\n createKindeFixture(page, {\n issuer: kindeIssuer,\n loginPath: kindeLoginPath,\n logoutPath: kindeLogoutPath,\n }),\n );\n },\n});\n\nexport { expect };\n"],"mappings":";AAAA,SAAS,QAAQ,MAAM,cAAyB;AA0BzC,SAAS,mBAAmB,MAAY,SAA4C;AACzF,QAAM,SAAS,IAAI,IAAI,QAAQ,MAAM;AACrC,QAAM,WAAW,CAAC,QAAa,IAAI,WAAW,OAAO;AACrD,MAAI,cAA6B;AAEjC,iBAAe,SAAS,MAAc,SAAwB,CAAC,GAAkB;AAC/E,UAAM,SAAS,IAAI,gBAAgB,EAAE,YAAY,KAAK,CAAC;AACvD,QAAI,OAAO,IAAK,QAAO,IAAI,YAAY,OAAO,GAAG;AACjD,UAAM,KAAK,KAAK,GAAG,QAAQ,SAAS,IAAI,MAAM,EAAE;AAEhD,QAAI,EAAE,SAAS,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,IAAI,KAAK,IAAI,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AQ,UAAU;AAClC,oBAAc;AAAA,IAChB;AAAA,EACF;AACF;AAEO,IAAM,OAAO,KAAK,OAAmD;AAAA,EAC1E,aAAa,CAAC,QAAQ,IAAI,oBAAoB,yBAAyB,EAAE,QAAQ,KAAK,CAAC;AAAA,EACvF,gBAAgB,CAAC,mBAAmB,EAAE,QAAQ,KAAK,CAAC;AAAA,EACpD,iBAAiB,CAAC,oBAAoB,EAAE,QAAQ,KAAK,CAAC;AAAA,EACtD,OAAO,OAAO,EAAE,MAAM,aAAa,gBAAgB,gBAAgB,GAAG,QAAQ;AAC5E,UAAM;AAAA,MACJ,mBAAmB,MAAM;AAAA,QACvB,QAAQ;AAAA,QACR,WAAW;AAAA,QACX,YAAY;AAAA,MACd,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/playwright.ts"],"sourcesContent":["import { test as base, expect, type Page } from \"@playwright/test\";\nimport type { ActiveFailure, FailureRule } from \"./failures.js\";\n\nexport interface KindeFixtureOptions {\n issuer: string;\n loginPath: string;\n logoutPath: string;\n}\n\nexport interface SignInOptions {\n org?: string;\n}\n\nexport interface KindeFixture {\n readonly issuer: string;\n readonly currentUser: string | null;\n signInAs(user: string, options?: SignInOptions): Promise<void>;\n switchOrganization(org: string): Promise<void>;\n signOut(): Promise<void>;\n injectFailure(rule: FailureRule): Promise<ActiveFailure>;\n clearFailures(): Promise<void>;\n}\n\ninterface ManagedKindeFixture extends KindeFixture {\n dispose(): Promise<void>;\n}\n\nexport interface KindeTestOptions {\n kindeIssuer: string;\n kindeLoginPath: string;\n kindeLogoutPath: string;\n}\n\nexport function createKindeFixture(page: Page, options: KindeFixtureOptions): ManagedKindeFixture {\n const issuer = new URL(options.issuer);\n const onIssuer = (url: URL) => url.origin === issuer.origin;\n let currentUser: string | null = null;\n const injected = new Set<string>();\n\n async function control(path: string, init: RequestInit = {}): Promise<Response> {\n const response = await fetch(`${issuer.origin}${path}`, {\n ...init,\n headers: { \"content-type\": \"application/json\", ...(init.headers ?? {}) },\n });\n if (!response.ok && response.status !== 404) {\n const body = (await response.json().catch(() => ({}))) as { error_description?: string };\n throw new Error(body.error_description ?? `kinde-testkit answered ${response.status} for ${path}.`);\n }\n return response;\n }\n\n async function signInAs(user: string, signIn: SignInOptions = {}): Promise<void> {\n const params = new URLSearchParams({ login_hint: user });\n if (signIn.org) params.set(\"org_code\", signIn.org);\n await page.goto(`${options.loginPath}?${params}`);\n\n if (!(onIssuer(new URL(page.url())) && new URL(page.url()).pathname === \"/oauth2/auth\")) {\n throw new Error(\n `Expected ${options.loginPath} to redirect to the kinde-testkit sign-in page at ${issuer.origin}, but the browser is at ${page.url()}. Check that the app's KINDE_ISSUER_URL is ${issuer.origin}.`,\n );\n }\n\n await page.getByLabel(\"Email\").fill(user);\n await page.getByRole(\"button\", { name: \"Continue\", exact: true }).click();\n await page.waitForURL((url) => !(onIssuer(url) && url.pathname === \"/oauth2/auth\"));\n\n const landed = new URL(page.url());\n if (onIssuer(landed)) {\n const alert = page.getByRole(\"alert\");\n if (await alert.count()) {\n throw new Error(`kinde-testkit refused the sign-in: ${(await alert.innerText()).trim()}`);\n }\n if (await page.getByRole(\"heading\", { name: \"Choose an organization\" }).count()) {\n throw new Error(`${user} belongs to more than one organization. Pass one with signInAs(\"${user}\", { org: \"org_...\" }).`);\n }\n throw new Error(`Sign-in stopped on ${page.url()}.`);\n }\n\n await page.waitForURL((url) => !onIssuer(url) && !url.pathname.endsWith(\"/kinde_callback\"));\n currentUser = user;\n }\n\n return {\n issuer: issuer.origin,\n get currentUser() {\n return currentUser;\n },\n signInAs,\n async switchOrganization(org: string) {\n if (!currentUser) throw new Error(\"Call signInAs() before switchOrganization().\");\n await signInAs(currentUser, { org });\n },\n async signOut() {\n await page.goto(options.logoutPath);\n currentUser = null;\n },\n async injectFailure(rule: FailureRule) {\n const response = await control(\"/testkit/failures\", { method: \"POST\", body: JSON.stringify(rule) });\n const failure = (await response.json()) as ActiveFailure;\n injected.add(failure.id);\n return failure;\n },\n async clearFailures() {\n await Promise.all([...injected].map((id) => control(`/testkit/failures/${id}`, { method: \"DELETE\" })));\n injected.clear();\n },\n async dispose() {\n if (injected.size > 0) await this.clearFailures();\n },\n };\n}\n\nexport const test = base.extend<KindeTestOptions & { kinde: KindeFixture }>({\n kindeIssuer: [process.env.KINDE_ISSUER_URL ?? \"http://localhost:4400\", { option: true }],\n kindeLoginPath: [\"/api/auth/login\", { option: true }],\n kindeLogoutPath: [\"/api/auth/logout\", { option: true }],\n kinde: async ({ page, kindeIssuer, kindeLoginPath, kindeLogoutPath }, use) => {\n const fixture = createKindeFixture(page, {\n issuer: kindeIssuer,\n loginPath: kindeLoginPath,\n logoutPath: kindeLogoutPath,\n });\n await use(fixture);\n await fixture.dispose();\n },\n});\n\nexport { expect };\n"],"mappings":";AAAA,SAAS,QAAQ,MAAM,cAAyB;AAiCzC,SAAS,mBAAmB,MAAY,SAAmD;AAChG,QAAM,SAAS,IAAI,IAAI,QAAQ,MAAM;AACrC,QAAM,WAAW,CAAC,QAAa,IAAI,WAAW,OAAO;AACrD,MAAI,cAA6B;AACjC,QAAM,WAAW,oBAAI,IAAY;AAEjC,iBAAe,QAAQ,MAAc,OAAoB,CAAC,GAAsB;AAC9E,UAAM,WAAW,MAAM,MAAM,GAAG,OAAO,MAAM,GAAG,IAAI,IAAI;AAAA,MACtD,GAAG;AAAA,MACH,SAAS,EAAE,gBAAgB,oBAAoB,GAAI,KAAK,WAAW,CAAC,EAAG;AAAA,IACzE,CAAC;AACD,QAAI,CAAC,SAAS,MAAM,SAAS,WAAW,KAAK;AAC3C,YAAM,OAAQ,MAAM,SAAS,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AACpD,YAAM,IAAI,MAAM,KAAK,qBAAqB,0BAA0B,SAAS,MAAM,QAAQ,IAAI,GAAG;AAAA,IACpG;AACA,WAAO;AAAA,EACT;AAEA,iBAAe,SAAS,MAAc,SAAwB,CAAC,GAAkB;AAC/E,UAAM,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,QAAQ,QAAQ;AAAA,EACxB;AACF,CAAC;","names":[]}
package/dist/vitest.d.ts CHANGED
@@ -32,6 +32,7 @@ interface UnauthenticatedScenario {
32
32
  }
33
33
  type Scenario = AuthenticatedScenario | UnauthenticatedScenario;
34
34
  interface KindePrincipal {
35
+ type: "user" | "machine";
35
36
  subject: string;
36
37
  issuer: string;
37
38
  organization: {
@@ -71,6 +72,17 @@ interface KindeTestkitOptions {
71
72
  now?: () => number;
72
73
  }
73
74
  type ScenarioTokenOverrides = Pick<KindeTokenOptions, "expiresIn" | "invalid" | "scopes" | "featureFlags" | "claims" | "authMethods" | "authTime" | "clientId" | "audience">;
75
+ interface M2MTokenOptions {
76
+ clientId?: string;
77
+ organizationCode?: string | null;
78
+ scopes?: string[];
79
+ grantedScopes?: string[];
80
+ audience?: string[];
81
+ permissions?: string[];
82
+ claims?: Record<string, unknown>;
83
+ expiresIn?: Duration;
84
+ invalid?: InvalidTokenKind;
85
+ }
74
86
  interface IdTokenOptions {
75
87
  expiresIn?: Duration;
76
88
  authMethods?: string[];
@@ -97,6 +109,7 @@ declare class KindeTestkit {
97
109
  keys: JWK[];
98
110
  };
99
111
  token(options?: KindeTokenOptions): Promise<string>;
112
+ m2mToken(options?: M2MTokenOptions): Promise<string>;
100
113
  tokenFor(scenario: Scenario, overrides?: ScenarioTokenOverrides): Promise<string | null>;
101
114
  idTokenFor(scenario: Scenario, options?: IdTokenOptions): Promise<string | null>;
102
115
  headersFor(scenario: Scenario, overrides?: ScenarioTokenOverrides): Promise<Record<string, string>>;
@@ -129,6 +142,45 @@ interface TestkitSeed {
129
142
  roles?: string[];
130
143
  permissions?: string[];
131
144
  }>;
145
+ applications?: Array<{
146
+ clientId: string;
147
+ clientSecret?: string;
148
+ name?: string;
149
+ organization?: string;
150
+ scopes?: string[];
151
+ permissions?: string[];
152
+ audience?: string | string[];
153
+ }>;
154
+ }
155
+
156
+ interface FailureRule {
157
+ path: string;
158
+ method?: string;
159
+ status?: number;
160
+ delayMs?: number;
161
+ hang?: boolean;
162
+ times?: number;
163
+ retryAfter?: number;
164
+ }
165
+ interface ActiveFailure {
166
+ id: string;
167
+ path: string;
168
+ method: string | null;
169
+ status: number | null;
170
+ delayMs: number;
171
+ hang: boolean;
172
+ remaining: number | null;
173
+ retryAfter: number;
174
+ hits: number;
175
+ }
176
+ declare class FailureInjector {
177
+ private rules;
178
+ private nextId;
179
+ add(rule: FailureRule): ActiveFailure;
180
+ remove(id: string): boolean;
181
+ clear(): void;
182
+ list(): ActiveFailure[];
183
+ take(method: string, path: string): ActiveFailure | null;
132
184
  }
133
185
 
134
186
  interface StartKindeTestkitOptions {
@@ -159,7 +211,9 @@ interface KindeTestkitHandle {
159
211
  readonly issuer: string;
160
212
  readonly jwksUri: string;
161
213
  readonly testkit: KindeTestkit;
214
+ readonly failures: FailureInjector;
162
215
  auth(scenario: Scenario, token?: ScenarioTokenOverrides): Promise<KindeTestAuth>;
216
+ reset(): void;
163
217
  }
164
218
  declare function useKindeTestkit(options?: StartKindeTestkitOptions): KindeTestkitHandle;
165
219
 
package/dist/vitest.js CHANGED
@@ -111,6 +111,7 @@ function invalid(value) {
111
111
  // src/testkit.ts
112
112
  var DEFAULT_ISSUER = "http://localhost:4400";
113
113
  var DEFAULT_CLIENT_ID = "kinde_testkit_client";
114
+ var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
114
115
  var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
115
116
  var DEFAULT_AUTH_METHODS = ["email"];
116
117
  var INVALID_TOKEN_KINDS = [
@@ -189,6 +190,27 @@ var KindeTestkit = class _KindeTestkit {
189
190
  Object.assign(payload, options.claims ?? {});
190
191
  return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
191
192
  }
193
+ async m2mToken(options = {}) {
194
+ const now = this.clock();
195
+ const requested = [...options.scopes ?? []];
196
+ const granted = [...options.grantedScopes ?? requested];
197
+ const payload = {
198
+ aud: [...options.audience ?? this.audience],
199
+ azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
200
+ exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
201
+ gty: ["client_credentials"],
202
+ iat: now,
203
+ iss: this.issuer,
204
+ jti: randomUUID(),
205
+ scope: granted.join(" "),
206
+ scp: requested,
207
+ v: "2"
208
+ };
209
+ if (options.organizationCode) payload.org_code = options.organizationCode;
210
+ if (options.permissions !== void 0) payload.permissions = [...options.permissions];
211
+ Object.assign(payload, options.claims ?? {});
212
+ return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
213
+ }
192
214
  async tokenFor(scenario, overrides = {}) {
193
215
  if (scenario.kind === "unauthenticated") return null;
194
216
  return this.token({
@@ -258,6 +280,7 @@ var KindeTestkit = class _KindeTestkit {
258
280
  };
259
281
  function scenarioPrincipal(scenario, issuer) {
260
282
  return {
283
+ type: "user",
261
284
  subject: scenario.user.id,
262
285
  issuer,
263
286
  organization: scenario.organization ? { code: scenario.organization.code } : null,
@@ -345,6 +368,7 @@ function resolveSeed(input) {
345
368
  const rawUsers = listOf(input.users, "users", problems);
346
369
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
347
370
  const rawMemberships = listOf(input.memberships, "memberships", problems);
371
+ const rawApplications = listOf(input.applications, "applications", problems);
348
372
  const users = [];
349
373
  rawUsers.forEach((raw, index) => {
350
374
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -400,10 +424,43 @@ function resolveSeed(input) {
400
424
  })
401
425
  );
402
426
  });
427
+ const applications = [];
428
+ rawApplications.forEach((raw, index) => {
429
+ if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
430
+ problems.push(`applications[${index}] needs a string "clientId".`);
431
+ return;
432
+ }
433
+ if (applications.some((app) => app.clientId === raw.clientId)) {
434
+ problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
435
+ return;
436
+ }
437
+ if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
438
+ problems.push(`applications[${index}].clientSecret must be a string.`);
439
+ }
440
+ if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
441
+ problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
442
+ }
443
+ for (const field of ["scopes", "permissions"]) {
444
+ const value = raw[field];
445
+ if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
446
+ problems.push(`applications[${index}].${field} must be a list of strings.`);
447
+ }
448
+ }
449
+ const audience = raw.audience;
450
+ applications.push({
451
+ clientId: raw.clientId,
452
+ clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
453
+ name: typeof raw.name === "string" ? raw.name : raw.clientId,
454
+ organizationCode: typeof raw.organization === "string" ? raw.organization : null,
455
+ scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
456
+ permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
457
+ audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
458
+ });
459
+ });
403
460
  if (problems.length > 0) {
404
461
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
405
462
  }
406
- return { users, organizations, memberships };
463
+ return { users, organizations, memberships, applications };
407
464
  }
408
465
  function findUser(users, ref) {
409
466
  const needle = ref.toLowerCase();
@@ -672,13 +729,16 @@ var AuthorizationServer = class {
672
729
  try {
673
730
  const clientId = clientIdFrom(req, form);
674
731
  const grantType = form.grant_type;
732
+ if (grantType === "client_credentials") {
733
+ return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
734
+ }
675
735
  let grant;
676
736
  if (grantType === "authorization_code") {
677
737
  grant = this.redeemCode(form, clientId);
678
738
  } else if (grantType === "refresh_token") {
679
739
  grant = this.redeemRefreshToken(form, clientId);
680
740
  } else {
681
- throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and refresh_token, not "${grantType ?? ""}".`);
741
+ throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
682
742
  }
683
743
  sendJson(res, 200, await this.issueTokens(grant));
684
744
  } catch (error) {
@@ -688,6 +748,33 @@ var AuthorizationServer = class {
688
748
  throw error;
689
749
  }
690
750
  }
751
+ async clientCredentials(clientId, clientSecret, form) {
752
+ const app = this.seed.applications.find((a) => a.clientId === clientId);
753
+ if (app?.clientSecret && app.clientSecret !== clientSecret) {
754
+ throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
755
+ }
756
+ const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
757
+ const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
758
+ const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
759
+ return {
760
+ access_token: await this.testkit.m2mToken({
761
+ clientId,
762
+ organizationCode: app?.organizationCode ?? null,
763
+ scopes: requested,
764
+ grantedScopes: granted,
765
+ audience: audience.length > 0 ? audience : app?.audience ?? void 0,
766
+ permissions: app?.permissions ?? void 0
767
+ }),
768
+ expires_in: this.testkit.accessTokenLifetime,
769
+ scope: granted.join(" "),
770
+ token_type: "bearer"
771
+ };
772
+ }
773
+ reset() {
774
+ this.codes.clear();
775
+ this.refreshTokens.clear();
776
+ this.signedUpUsers.clear();
777
+ }
691
778
  redeemCode(form, clientId) {
692
779
  const code = form.code ?? "";
693
780
  const pending = this.codes.get(code);
@@ -859,6 +946,15 @@ function clientIdFrom(req, form) {
859
946
  if (form.client_id) return form.client_id;
860
947
  throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
861
948
  }
949
+ function clientSecretFrom(req, form) {
950
+ const header = req.headers.authorization ?? "";
951
+ if (header.startsWith("Basic ")) {
952
+ const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
953
+ const index = decoded.indexOf(":");
954
+ if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
955
+ }
956
+ return form.client_secret ?? null;
957
+ }
862
958
  function redirectWithError(res, request, error, description) {
863
959
  const target = new URL(request.redirectUri);
864
960
  target.searchParams.set("error", error);
@@ -899,6 +995,86 @@ function sendJson(res, status, body) {
899
995
  res.end(JSON.stringify(body));
900
996
  }
901
997
 
998
+ // src/failures.ts
999
+ var MAX_DELAY_MS = 6e4;
1000
+ var FailureInjector = class {
1001
+ rules = [];
1002
+ nextId = 1;
1003
+ add(rule) {
1004
+ const problems = validate(rule);
1005
+ if (problems.length > 0) {
1006
+ throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
1007
+ }
1008
+ const active = {
1009
+ id: `failure_${this.nextId++}`,
1010
+ path: rule.path,
1011
+ method: rule.method ? rule.method.toUpperCase() : null,
1012
+ status: rule.status ?? null,
1013
+ delayMs: rule.delayMs ?? 0,
1014
+ hang: rule.hang ?? false,
1015
+ remaining: rule.times ?? null,
1016
+ retryAfter: rule.retryAfter ?? 1,
1017
+ hits: 0
1018
+ };
1019
+ this.rules.push(active);
1020
+ return { ...active };
1021
+ }
1022
+ remove(id) {
1023
+ const before = this.rules.length;
1024
+ this.rules = this.rules.filter((rule) => rule.id !== id);
1025
+ return this.rules.length < before;
1026
+ }
1027
+ clear() {
1028
+ this.rules = [];
1029
+ }
1030
+ list() {
1031
+ return this.rules.map((rule) => ({ ...rule }));
1032
+ }
1033
+ take(method, path) {
1034
+ const rule = this.rules.find((r) => matches(r, method, path));
1035
+ if (!rule) return null;
1036
+ rule.hits += 1;
1037
+ if (rule.remaining !== null) {
1038
+ rule.remaining -= 1;
1039
+ if (rule.remaining <= 0) this.remove(rule.id);
1040
+ }
1041
+ return { ...rule };
1042
+ }
1043
+ };
1044
+ function failureBody(status) {
1045
+ const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
1046
+ return { error, error_description: `kinde-testkit injected a ${status} response.` };
1047
+ }
1048
+ function matches(rule, method, path) {
1049
+ if (rule.method && rule.method !== method.toUpperCase()) return false;
1050
+ if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
1051
+ return rule.path === path;
1052
+ }
1053
+ function validate(rule) {
1054
+ const problems = [];
1055
+ if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
1056
+ problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
1057
+ } else if (rule.path.startsWith("/testkit/")) {
1058
+ problems.push("Failures cannot target /testkit/ control endpoints.");
1059
+ }
1060
+ if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
1061
+ problems.push('"status" must be an HTTP error status between 400 and 599.');
1062
+ }
1063
+ if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
1064
+ problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
1065
+ }
1066
+ if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
1067
+ problems.push('"times" must be a whole number of 1 or more.');
1068
+ }
1069
+ if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
1070
+ problems.push('"retryAfter" must be a whole number of seconds.');
1071
+ }
1072
+ if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
1073
+ problems.push('Set at least one of "status", "delayMs" or "hang".');
1074
+ }
1075
+ return problems;
1076
+ }
1077
+
902
1078
  // src/server.ts
903
1079
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
904
1080
  var MAX_BODY_BYTES = 64 * 1024;
@@ -912,12 +1088,11 @@ async function startKindeTestkit(options = {}) {
912
1088
  );
913
1089
  }
914
1090
  const seed = resolveSeed(options.seed ?? {});
1091
+ const failures = new FailureInjector();
915
1092
  let ready;
916
- const testkitReady = new Promise(
917
- (resolve) => ready = resolve
918
- );
1093
+ const testkitReady = new Promise((resolve) => ready = resolve);
919
1094
  const server = createServer((req, res) => {
920
- testkitReady.then(({ testkit: testkit2, auth }) => handle(req, res, testkit2, auth, seed)).catch((error) => sendError(res, error));
1095
+ testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
921
1096
  });
922
1097
  await new Promise((resolve, reject) => {
923
1098
  server.once("error", reject);
@@ -931,7 +1106,12 @@ async function startKindeTestkit(options = {}) {
931
1106
  audience: options.audience ?? options.seed?.audience,
932
1107
  clientId: options.clientId ?? options.seed?.clientId
933
1108
  });
934
- ready({ testkit, auth: new AuthorizationServer(testkit, seed) });
1109
+ const auth = new AuthorizationServer(testkit, seed);
1110
+ const reset = () => {
1111
+ auth.reset();
1112
+ failures.clear();
1113
+ };
1114
+ ready({ testkit, auth, seed, failures, reset });
935
1115
  return {
936
1116
  url,
937
1117
  issuer: testkit.issuer,
@@ -939,16 +1119,31 @@ async function startKindeTestkit(options = {}) {
939
1119
  jwksUri: `${url}/.well-known/jwks`,
940
1120
  testkit,
941
1121
  seed,
1122
+ failures,
1123
+ reset,
942
1124
  close: () => new Promise((resolve, reject) => {
943
1125
  server.closeAllConnections();
944
1126
  server.close((error) => error ? reject(error) : resolve());
945
1127
  })
946
1128
  };
947
1129
  }
948
- async function handle(req, res, testkit, auth, seed) {
1130
+ async function handle(req, res, context) {
1131
+ const { testkit, auth, seed, failures } = context;
949
1132
  const url = new URL(req.url ?? "/", "http://localhost");
950
1133
  const { pathname } = url;
951
1134
  const method = req.method ?? "GET";
1135
+ if (!pathname.startsWith("/testkit/")) {
1136
+ const failure = failures.take(method, pathname);
1137
+ if (failure) {
1138
+ if (failure.hang) return;
1139
+ if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
1140
+ if (failure.status !== null) {
1141
+ const headers = {};
1142
+ if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
1143
+ return sendJson2(res, failure.status, failureBody(failure.status), headers);
1144
+ }
1145
+ }
1146
+ }
952
1147
  if (await auth.handle(req, res, url, () => readForm(req))) return;
953
1148
  if (method === "GET" && pathname === "/.well-known/openid-configuration") {
954
1149
  return sendJson2(res, 200, discovery(testkit));
@@ -966,6 +1161,22 @@ async function handle(req, res, testkit, auth, seed) {
966
1161
  if (method === "GET" && pathname === "/testkit/memberships") {
967
1162
  return sendJson2(res, 200, seed.memberships);
968
1163
  }
1164
+ if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
1165
+ if (method === "POST" && pathname === "/testkit/failures") {
1166
+ return sendJson2(res, 201, failures.add(await readJson(req)));
1167
+ }
1168
+ if (method === "DELETE" && pathname === "/testkit/failures") {
1169
+ failures.clear();
1170
+ return sendJson2(res, 200, { ok: true });
1171
+ }
1172
+ if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
1173
+ const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1174
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1175
+ }
1176
+ if (method === "POST" && pathname === "/testkit/reset") {
1177
+ context.reset();
1178
+ return sendJson2(res, 200, { ok: true });
1179
+ }
969
1180
  if (method === "POST" && pathname === "/testkit/token") {
970
1181
  const body = await readJson(req);
971
1182
  const accessToken = await issueToken(testkit, seed, body);
@@ -1005,6 +1216,21 @@ async function issueToken(testkit, seed, body) {
1005
1216
  ]);
1006
1217
  }
1007
1218
  const expiresIn = input.expiresIn;
1219
+ if (input.m2m === true) {
1220
+ const clientId = optionalString(input, "clientId");
1221
+ const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
1222
+ const scopes = optionalStrings(input, "scopes") ?? [];
1223
+ return testkit.m2mToken({
1224
+ clientId,
1225
+ organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
1226
+ scopes,
1227
+ grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
1228
+ audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
1229
+ permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
1230
+ expiresIn,
1231
+ invalid: invalid2
1232
+ });
1233
+ }
1008
1234
  const permissions = optionalStrings(input, "permissions");
1009
1235
  const roles = optionalStrings(input, "roles");
1010
1236
  const userRef = optionalString(input, "user");
@@ -1080,10 +1306,11 @@ async function readText(req) {
1080
1306
  }
1081
1307
  return Buffer.concat(chunks).toString("utf8").trim();
1082
1308
  }
1083
- function sendJson2(res, status, body) {
1309
+ function sendJson2(res, status, body, headers = {}) {
1084
1310
  res.writeHead(status, {
1085
1311
  "content-type": "application/json; charset=utf-8",
1086
- "cache-control": "no-store"
1312
+ "cache-control": "no-store",
1313
+ ...headers
1087
1314
  });
1088
1315
  res.end(JSON.stringify(body));
1089
1316
  }
@@ -1140,7 +1367,11 @@ function useKindeTestkit(options = {}) {
1140
1367
  get testkit() {
1141
1368
  return current().testkit;
1142
1369
  },
1143
- auth: (scenario, token) => kindeTest({ scenario, testkit: current().testkit, token })
1370
+ get failures() {
1371
+ return current().failures;
1372
+ },
1373
+ auth: (scenario, token) => kindeTest({ scenario, testkit: current().testkit, token }),
1374
+ reset: () => current().reset()
1144
1375
  };
1145
1376
  }
1146
1377
  export {