kinde-testkit 0.7.0 → 0.8.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +97 -9
  3. package/dist/chunk-BPPG4G52.js +427 -0
  4. package/dist/chunk-BPPG4G52.js.map +1 -0
  5. package/dist/{chunk-JTAB2S44.js → chunk-CY75AADD.js} +175 -454
  6. package/dist/chunk-CY75AADD.js.map +1 -0
  7. package/dist/chunk-EZUKOKNO.js +48 -0
  8. package/dist/chunk-EZUKOKNO.js.map +1 -0
  9. package/dist/{chunk-2QJ7DTNL.js → chunk-YJPE5HAM.js} +5 -3
  10. package/dist/{chunk-2QJ7DTNL.js.map → chunk-YJPE5HAM.js.map} +1 -1
  11. package/dist/cli.js +8 -2
  12. package/dist/cli.js.map +1 -1
  13. package/dist/cypress-support.d.ts +142 -0
  14. package/dist/cypress-support.js +21 -6
  15. package/dist/cypress-support.js.map +1 -1
  16. package/dist/cypress.cjs +142 -14
  17. package/dist/cypress.d.cts +1 -1
  18. package/dist/cypress.d.ts +3 -2
  19. package/dist/cypress.js +2 -1
  20. package/dist/cypress.js.map +1 -1
  21. package/dist/{handle-estfqypp.d.cts → handle-DRPxm36j.d.cts} +1 -1
  22. package/dist/{handle-E_BhdHx8.d.ts → handle-Pjt9fSUq.d.ts} +3 -2
  23. package/dist/index.cjs +145 -14
  24. package/dist/index.d.cts +17 -4
  25. package/dist/index.d.ts +8 -26
  26. package/dist/index.js +27 -51
  27. package/dist/index.js.map +1 -1
  28. package/dist/jest.cjs +142 -14
  29. package/dist/jest.d.cts +3 -3
  30. package/dist/jest.d.ts +5 -4
  31. package/dist/jest.js +3 -2
  32. package/dist/jest.js.map +1 -1
  33. package/dist/playwright.d.ts +12 -3
  34. package/dist/playwright.js +30 -0
  35. package/dist/playwright.js.map +1 -1
  36. package/dist/react.d.ts +43 -0
  37. package/dist/react.js +110 -0
  38. package/dist/react.js.map +1 -0
  39. package/dist/{server-CTBJXMac.d.cts → server-CLRn67qI.d.cts} +26 -0
  40. package/dist/{server-B9fBcnyQ.d.ts → server-CuHAHsaN.d.ts} +3 -56
  41. package/dist/sign-in-flow-DNrDXSLI.d.ts +35 -0
  42. package/dist/testkit-BvCAFsSj.d.ts +156 -0
  43. package/dist/vitest.d.ts +5 -4
  44. package/dist/vitest.js +3 -2
  45. package/dist/vitest.js.map +1 -1
  46. package/dist/{webhooks-DJyCsbdF.d.ts → webhooks-CiK9_pVw.d.ts} +82 -155
  47. package/package.json +30 -3
  48. package/dist/chunk-JTAB2S44.js.map +0 -1
package/dist/jest.cjs CHANGED
@@ -1478,6 +1478,25 @@ function layout(title, body) {
1478
1478
  function displayName(user) {
1479
1479
  return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
1480
1480
  }
1481
+ var SOCIAL_CONNECTIONS = ["google", "github", "microsoft", "apple", "facebook", "gitlab", "linkedin", "slack", "x"];
1482
+ function select(id, label, options) {
1483
+ return `<label for="${id}">${label}</label><select id="${id}" name="${id}" style="width:100%;height:38px;padding:0 10px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit">${options.map(([value, text]) => `<option value="${value}">${escapeHtml(text)}</option>`).join("")}</select>`;
1484
+ }
1485
+ function testOptions() {
1486
+ return `<h2>Test options</h2>${select("connection", "Sign in with", [
1487
+ ["email", "Email"],
1488
+ ...SOCIAL_CONNECTIONS.map((c) => [c, c === "x" ? "X" : c[0].toUpperCase() + c.slice(1)])
1489
+ ])}${select("provider_result", "Provider result", [
1490
+ ["success", "Signed in"],
1491
+ ["cancelled", "User cancelled"],
1492
+ ["error", "Provider error"]
1493
+ ])}${select("mfa", "Multi-factor authentication", [
1494
+ ["none", "Not required"],
1495
+ ["passed", "Passed"],
1496
+ ["failed", "Wrong code"],
1497
+ ["cancelled", "Cancelled"]
1498
+ ])}`;
1499
+ }
1481
1500
  function renderSignIn(options) {
1482
1501
  const users = options.users.map(({ user, organizations }) => {
1483
1502
  const value = escapeHtml(user.email ?? user.id);
@@ -1489,16 +1508,17 @@ function renderSignIn(options) {
1489
1508
  const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
1490
1509
  return layout(
1491
1510
  "Sign in",
1492
- `<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}</form>`
1511
+ `<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}${testOptions()}</form>`
1493
1512
  );
1494
1513
  }
1495
1514
  function renderOrganizationPicker(options) {
1515
+ const carried = Object.entries(options.carry ?? {}).map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`).join("");
1496
1516
  const choices = options.organizations.map(
1497
1517
  (org) => `<button class="option" type="submit" name="org" value="${escapeHtml(org.code)}"><span><strong>${escapeHtml(org.name)}</strong><small>${escapeHtml(org.code)}</small></span></button>`
1498
1518
  ).join("");
1499
1519
  return layout(
1500
1520
  "Choose an organization",
1501
- `<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}"><div class="list" style="margin-top:20px">${choices}</div></form>`
1521
+ `<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}">${carried}<div class="list" style="margin-top:20px">${choices}</div></form>`
1502
1522
  );
1503
1523
  }
1504
1524
  function renderMessage(title, message2) {
@@ -1939,6 +1959,17 @@ var AuthorizationServer = class {
1939
1959
  return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
1940
1960
  }
1941
1961
  const encoded = encodeRequest(request);
1962
+ const connection = (form2.connection || "email").trim().toLowerCase();
1963
+ const providerResult = form2.provider_result || "success";
1964
+ const mfa = form2.mfa || "none";
1965
+ if (!/^[a-z0-9_-]{1,40}$/.test(connection) || !["success", "cancelled", "error"].includes(providerResult) || !["none", "passed", "failed", "cancelled"].includes(mfa)) {
1966
+ return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "The test options on the sign-in form are not valid." }));
1967
+ }
1968
+ if (connection !== "email" && providerResult !== "success") {
1969
+ this.observe("session.sign-in-refused");
1970
+ return providerResult === "cancelled" ? redirectWithError(res, request, "access_denied", `The user cancelled sign-in with ${connection}.`) : redirectWithError(res, request, "server_error", `${connection} returned an error during sign-in.`);
1971
+ }
1972
+ const carry = { connection, provider_result: providerResult, mfa };
1942
1973
  const ref = (form2.user || form2.email || "").trim();
1943
1974
  if (!ref) {
1944
1975
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
@@ -1960,6 +1991,21 @@ var AuthorizationServer = class {
1960
1991
  })
1961
1992
  );
1962
1993
  }
1994
+ if (mfa === "failed") {
1995
+ this.observe("session.sign-in-refused");
1996
+ return sendHtml(
1997
+ res,
1998
+ 401,
1999
+ renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "The verification code is not correct." })
2000
+ );
2001
+ }
2002
+ if (mfa === "cancelled") {
2003
+ this.observe("session.sign-in-refused");
2004
+ return redirectWithError(res, request, "access_denied", "The user cancelled multi-factor authentication.");
2005
+ }
2006
+ if (connection !== "email") this.observe("identity.social");
2007
+ if (mfa === "passed") this.observe("identity.mfa");
2008
+ const authMethods = [connection, ...mfa === "passed" ? ["mfa"] : []];
1963
2009
  const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
1964
2010
  const wanted = request.orgCode ?? form2.org ?? null;
1965
2011
  let organizationCode = null;
@@ -1987,7 +2033,8 @@ var AuthorizationServer = class {
1987
2033
  renderOrganizationPicker({
1988
2034
  request: encoded,
1989
2035
  user,
1990
- organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
2036
+ organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null),
2037
+ carry
1991
2038
  })
1992
2039
  );
1993
2040
  }
@@ -2009,6 +2056,7 @@ var AuthorizationServer = class {
2009
2056
  audience: request.audience,
2010
2057
  nonce: request.nonce,
2011
2058
  authTime: Math.floor(Date.now() / 1e3),
2059
+ authMethods,
2012
2060
  codeChallenge: request.codeChallenge,
2013
2061
  codeChallengeMethod: request.codeChallengeMethod,
2014
2062
  expiresAt: Date.now() + CODE_LIFETIME_MS
@@ -2320,6 +2368,7 @@ var AuthorizationServer = class {
2320
2368
  clientId: grant.clientId,
2321
2369
  audience: grant.audience.length > 0 ? grant.audience : void 0,
2322
2370
  authTime: grant.authTime,
2371
+ authMethods: grant.authMethods,
2323
2372
  featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
2324
2373
  }),
2325
2374
  expires_in: this.testkit.accessTokenLifetime,
@@ -2330,7 +2379,8 @@ var AuthorizationServer = class {
2330
2379
  body.id_token = await this.testkit.idTokenFor(scenario, {
2331
2380
  clientId: grant.clientId,
2332
2381
  nonce: grant.nonce ?? void 0,
2333
- authTime: grant.authTime
2382
+ authTime: grant.authTime,
2383
+ authMethods: grant.authMethods
2334
2384
  });
2335
2385
  }
2336
2386
  if (grant.scope.includes("offline")) {
@@ -2678,7 +2728,8 @@ var Directory = class {
2678
2728
  isPasswordResetRequested: false,
2679
2729
  createdOn: (/* @__PURE__ */ new Date()).toISOString(),
2680
2730
  totalSignIns: 0,
2681
- lastSignedIn: null
2731
+ lastSignedIn: null,
2732
+ lastOrganizationSignIns: {}
2682
2733
  };
2683
2734
  this.userMeta.set(user.id, meta);
2684
2735
  }
@@ -2691,7 +2742,7 @@ var Directory = class {
2691
2742
  const meta = this.meta(user);
2692
2743
  meta.totalSignIns += 1;
2693
2744
  meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
2694
- void organizationCode;
2745
+ if (organizationCode) meta.lastOrganizationSignIns[organizationCode] = meta.lastSignedIn;
2695
2746
  }
2696
2747
  createUser(input) {
2697
2748
  const user = createKindeUser({
@@ -2761,6 +2812,34 @@ var Directory = class {
2761
2812
  for (const key of permissions) this.ensurePermission(key);
2762
2813
  return membership;
2763
2814
  }
2815
+ /**
2816
+ * Makes sure a user exists with exactly these roles and permissions in the organization, creating
2817
+ * the user, organization and membership when they are missing. Used by authenticateAs() in browser
2818
+ * tests, so a test can sign in as any identity without adding it to the seed. reset() removes it.
2819
+ */
2820
+ ensureIdentity(input) {
2821
+ const email = input.email.trim().toLowerCase();
2822
+ let user = findUser(this.seed.users, email);
2823
+ if (!user) {
2824
+ user = createKindeUser({ email, givenName: input.givenName ?? null, familyName: input.familyName ?? null });
2825
+ this.seed.users.push(user);
2826
+ }
2827
+ if (!input.organization) return { user, organization: null };
2828
+ let organization = this.organization(input.organization);
2829
+ if (!organization) {
2830
+ organization = createKindeOrganization({ code: input.organization, name: input.organizationName ?? input.organization });
2831
+ this.seed.organizations.push(organization);
2832
+ }
2833
+ const roles = input.roles ?? [];
2834
+ const permissions = input.permissions ?? [];
2835
+ const index = this.seed.memberships.findIndex((m) => m.userId === user.id && m.organizationCode === organization.code);
2836
+ const membership = createMembership({ userId: user.id, organizationCode: organization.code, roles, permissions });
2837
+ if (index >= 0) this.seed.memberships[index] = membership;
2838
+ else this.seed.memberships.push(membership);
2839
+ for (const key of roles) this.ensureRole(key);
2840
+ for (const key of permissions) this.ensurePermission(key);
2841
+ return { user, organization };
2842
+ }
2764
2843
  removeMembership(userId, organizationCode) {
2765
2844
  const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
2766
2845
  if (index < 0) return false;
@@ -3138,12 +3217,14 @@ var ManagementApi = class {
3138
3217
  username: null,
3139
3218
  last_name: user.familyName,
3140
3219
  first_name: user.givenName,
3220
+ full_name: [user.givenName, user.familyName].filter(Boolean).join(" ") || null,
3141
3221
  is_suspended: meta.isSuspended,
3142
3222
  picture: user.picture,
3143
3223
  total_sign_ins: meta.totalSignIns,
3144
3224
  failed_sign_ins: 0,
3145
3225
  last_signed_in: meta.lastSignedIn,
3146
3226
  created_on: meta.createdOn,
3227
+ last_organization_sign_ins: Object.entries(meta.lastOrganizationSignIns).map(([org_code, last_signed_in]) => ({ org_code, last_signed_in })),
3147
3228
  organizations: this.organizationsOf(user),
3148
3229
  identities: user.email ? [{ type: "email", identity: user.email }] : []
3149
3230
  };
@@ -3163,7 +3244,8 @@ var ManagementApi = class {
3163
3244
  handle: meta.handle,
3164
3245
  is_default: false,
3165
3246
  external_id: meta.externalId,
3166
- is_auto_membership_enabled: false
3247
+ is_auto_membership_enabled: false,
3248
+ created_on: meta.createdOn
3167
3249
  };
3168
3250
  }
3169
3251
  organizationEvent(org) {
@@ -3174,7 +3256,7 @@ var ManagementApi = class {
3174
3256
  return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
3175
3257
  }
3176
3258
  permissionItem(permission) {
3177
- return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
3259
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, is_organization_role_assignable: false };
3178
3260
  }
3179
3261
  };
3180
3262
  function paginate(items, query) {
@@ -3203,6 +3285,7 @@ function sendJson3(res, status, body) {
3203
3285
  }
3204
3286
 
3205
3287
  // src/failures.ts
3288
+ var MALFORMED_KINDS = ["invalid-json", "empty", "html", "unexpected-json"];
3206
3289
  var MAX_DELAY_MS = 6e4;
3207
3290
  var FailureInjector = class {
3208
3291
  rules = [];
@@ -3221,6 +3304,7 @@ var FailureInjector = class {
3221
3304
  hang: rule.hang ?? false,
3222
3305
  remaining: rule.times ?? null,
3223
3306
  retryAfter: rule.retryAfter ?? 1,
3307
+ malformed: rule.malformed ?? null,
3224
3308
  hits: 0
3225
3309
  };
3226
3310
  this.rules.push(active);
@@ -3252,6 +3336,18 @@ function failureBody(status) {
3252
3336
  const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
3253
3337
  return { error, error_description: `kinde-testkit injected a ${status} response.` };
3254
3338
  }
3339
+ function malformedBody(kind) {
3340
+ switch (kind) {
3341
+ case "invalid-json":
3342
+ return { contentType: "application/json", body: '{"access_token":"eyJhbGciOiJSUzI1NiJ9.' };
3343
+ case "empty":
3344
+ return { contentType: "application/json", body: "" };
3345
+ case "html":
3346
+ return { contentType: "text/html; charset=utf-8", body: "<!doctype html><html><body><h1>Bad gateway</h1></body></html>" };
3347
+ case "unexpected-json":
3348
+ return { contentType: "application/json", body: JSON.stringify({ message: "kinde-testkit sent a JSON body in a shape your client does not expect." }) };
3349
+ }
3350
+ }
3255
3351
  function matches(rule, method, path) {
3256
3352
  if (rule.method && rule.method !== method.toUpperCase()) return false;
3257
3353
  if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
@@ -3264,8 +3360,12 @@ function validate(rule) {
3264
3360
  } else if (rule.path.startsWith("/testkit/")) {
3265
3361
  problems.push("Failures cannot target /testkit/ control endpoints.");
3266
3362
  }
3267
- if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
3268
- problems.push('"status" must be an HTTP error status between 400 and 599.');
3363
+ if (rule.malformed !== void 0 && !MALFORMED_KINDS.includes(rule.malformed)) {
3364
+ problems.push(`"malformed" must be one of ${MALFORMED_KINDS.join(", ")}.`);
3365
+ }
3366
+ const lowest = rule.malformed ? 200 : 400;
3367
+ if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < lowest || rule.status > 599)) {
3368
+ problems.push(rule.malformed ? '"status" must be between 200 and 599.' : '"status" must be an HTTP error status between 400 and 599.');
3269
3369
  }
3270
3370
  if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
3271
3371
  problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
@@ -3276,8 +3376,8 @@ function validate(rule) {
3276
3376
  if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
3277
3377
  problems.push('"retryAfter" must be a whole number of seconds.');
3278
3378
  }
3279
- if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
3280
- problems.push('Set at least one of "status", "delayMs" or "hang".');
3379
+ if (rule.status === void 0 && !rule.delayMs && !rule.hang && !rule.malformed) {
3380
+ problems.push('Set at least one of "status", "delayMs", "hang" or "malformed".');
3281
3381
  }
3282
3382
  return problems;
3283
3383
  }
@@ -3633,7 +3733,9 @@ var COVERAGE_GROUPS = [
3633
3733
  { id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
3634
3734
  { id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
3635
3735
  { id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
3636
- { id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
3736
+ { id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." },
3737
+ { id: "identity.social", label: "Social sign-in", hint: 'Sign in with a social connection, such as signInAs(email, { connection: "google" }).' },
3738
+ { id: "identity.mfa", label: "Multi-factor sign-in", hint: 'Sign in with { mfa: "passed" }.' }
3637
3739
  ]
3638
3740
  },
3639
3741
  {
@@ -3670,6 +3772,7 @@ var COVERAGE_GROUPS = [
3670
3772
  { id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
3671
3773
  { id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
3672
3774
  { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." },
3775
+ { id: "session.sign-in-refused", label: "Sign-in cancelled or failed", hint: `Sign in with { providerResult: "cancelled" } or { mfa: "failed" } and check the app's error handling.` },
3673
3776
  { id: "session.device-approved", label: "Device sign-in", hint: "Run the device authorization flow and approve it with POST /testkit/device." }
3674
3777
  ]
3675
3778
  },
@@ -3707,7 +3810,8 @@ var COVERAGE_GROUPS = [
3707
3810
  { id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
3708
3811
  { id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
3709
3812
  { id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
3710
- { id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
3813
+ { id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." },
3814
+ { id: "outage.malformed", label: "Malformed answer", hint: "Inject a malformed response, such as invalid JSON from the token endpoint." }
3711
3815
  ]
3712
3816
  }
3713
3817
  ];
@@ -4150,6 +4254,13 @@ async function handle(req, res, context) {
4150
4254
  if (failure.delayMs > 0) coverage.hit("outage.slow");
4151
4255
  if (failure.hang) return;
4152
4256
  if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
4257
+ if (failure.malformed) {
4258
+ coverage.hit("outage.malformed");
4259
+ const { contentType, body } = malformedBody(failure.malformed);
4260
+ res.writeHead(failure.status ?? 200, { "content-type": contentType, "cache-control": "no-store" });
4261
+ res.end(body);
4262
+ return;
4263
+ }
4153
4264
  if (failure.status !== null) {
4154
4265
  const headers = {};
4155
4266
  if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
@@ -4217,6 +4328,23 @@ async function handle(req, res, context) {
4217
4328
  const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
4218
4329
  return sendJson4(res, removed ? 200 : 404, { ok: removed });
4219
4330
  }
4331
+ if (method === "POST" && pathname === "/testkit/identities") {
4332
+ const input = await readJson(req);
4333
+ if (typeof input.email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.email)) {
4334
+ throw new TestkitError("INVALID_REQUEST", "An identity needs an email address.");
4335
+ }
4336
+ const strings2 = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : void 0;
4337
+ const { user, organization } = context.directory.ensureIdentity({
4338
+ email: input.email,
4339
+ givenName: typeof input.givenName === "string" ? input.givenName : null,
4340
+ familyName: typeof input.familyName === "string" ? input.familyName : null,
4341
+ organization: typeof input.organization === "string" ? input.organization : null,
4342
+ organizationName: typeof input.organizationName === "string" ? input.organizationName : void 0,
4343
+ roles: strings2(input.roles),
4344
+ permissions: strings2(input.permissions)
4345
+ });
4346
+ return sendJson4(res, 200, { user: { id: user.id, email: user.email }, organization: organization?.code ?? null });
4347
+ }
4220
4348
  if (method === "POST" && pathname === "/testkit/device") {
4221
4349
  const input = await readJson(req);
4222
4350
  try {
package/dist/jest.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { a as KindeTestkitHandle } from './handle-estfqypp.cjs';
2
- export { K as KindeTestAuth, k as kindeTest } from './handle-estfqypp.cjs';
3
- import { S as StartKindeTestkitOptions } from './server-CTBJXMac.cjs';
1
+ import { a as KindeTestkitHandle } from './handle-DRPxm36j.cjs';
2
+ export { K as KindeTestAuth, k as kindeTest } from './handle-DRPxm36j.cjs';
3
+ import { S as StartKindeTestkitOptions } from './server-CLRn67qI.cjs';
4
4
  import 'jose';
5
5
 
6
6
  type Hook = (fn: () => Promise<void>, timeout?: number) => void;
package/dist/jest.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { a as KindeTestkitHandle } from './handle-E_BhdHx8.js';
2
- export { K as KindeTestAuth, k as kindeTest } from './handle-E_BhdHx8.js';
3
- import { S as StartKindeTestkitOptions } from './server-B9fBcnyQ.js';
4
- import './webhooks-DJyCsbdF.js';
1
+ import { a as KindeTestkitHandle } from './handle-Pjt9fSUq.js';
2
+ export { K as KindeTestAuth, k as kindeTest } from './handle-Pjt9fSUq.js';
3
+ import { S as StartKindeTestkitOptions } from './server-CuHAHsaN.js';
4
+ import './testkit-BvCAFsSj.js';
5
5
  import 'jose';
6
+ import './webhooks-CiK9_pVw.js';
6
7
 
7
8
  type Hook = (fn: () => Promise<void>, timeout?: number) => void;
8
9
  /**
package/dist/jest.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import {
2
2
  createKindeTestkitHandle,
3
3
  kindeTest
4
- } from "./chunk-2QJ7DTNL.js";
5
- import "./chunk-JTAB2S44.js";
4
+ } from "./chunk-YJPE5HAM.js";
5
+ import "./chunk-CY75AADD.js";
6
+ import "./chunk-BPPG4G52.js";
6
7
 
7
8
  // src/jest.ts
8
9
  function useKindeTestkit(options = {}, hooks) {
package/dist/jest.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/jest.ts"],"sourcesContent":["import { createKindeTestkitHandle, type KindeTestkitHandle } from \"./handle.js\";\nimport type { StartKindeTestkitOptions } from \"./server.js\";\n\nexport { kindeTest, type KindeTestAuth, type KindeTestkitHandle } from \"./handle.js\";\n\ntype Hook = (fn: () => Promise<void>, timeout?: number) => void;\n\n/**\n * Starts a testkit for the test file. Use the handle inside tests and hooks.\n * Uses Jest's global beforeAll and afterAll. With injectGlobals: false, pass them in:\n * useKindeTestkit(options, { beforeAll, afterAll }) with the functions from @jest/globals.\n */\nexport function useKindeTestkit(\n options: StartKindeTestkitOptions = {},\n hooks?: { beforeAll: Hook; afterAll: Hook },\n): KindeTestkitHandle {\n const globals = globalThis as unknown as { beforeAll?: Hook; afterAll?: Hook };\n const beforeAll = hooks?.beforeAll ?? globals.beforeAll;\n const afterAll = hooks?.afterAll ?? globals.afterAll;\n if (typeof beforeAll !== \"function\" || typeof afterAll !== \"function\") {\n throw new Error(\n \"useKindeTestkit() from kinde-testkit/jest needs Jest's beforeAll and afterAll. Call it at the top of a test file, or pass them from @jest/globals.\",\n );\n }\n return createKindeTestkitHandle({ beforeAll, afterAll }, options, \"useKindeTestkit\");\n}\n"],"mappings":";;;;;;;AAYO,SAAS,gBACd,UAAoC,CAAC,GACrC,OACoB;AACpB,QAAM,UAAU;AAChB,QAAM,YAAY,OAAO,aAAa,QAAQ;AAC9C,QAAM,WAAW,OAAO,YAAY,QAAQ;AAC5C,MAAI,OAAO,cAAc,cAAc,OAAO,aAAa,YAAY;AACrE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,yBAAyB,EAAE,WAAW,SAAS,GAAG,SAAS,iBAAiB;AACrF;","names":[]}
1
+ {"version":3,"sources":["../src/jest.ts"],"sourcesContent":["import { createKindeTestkitHandle, type KindeTestkitHandle } from \"./handle.js\";\nimport type { StartKindeTestkitOptions } from \"./server.js\";\n\nexport { kindeTest, type KindeTestAuth, type KindeTestkitHandle } from \"./handle.js\";\n\ntype Hook = (fn: () => Promise<void>, timeout?: number) => void;\n\n/**\n * Starts a testkit for the test file. Use the handle inside tests and hooks.\n * Uses Jest's global beforeAll and afterAll. With injectGlobals: false, pass them in:\n * useKindeTestkit(options, { beforeAll, afterAll }) with the functions from @jest/globals.\n */\nexport function useKindeTestkit(\n options: StartKindeTestkitOptions = {},\n hooks?: { beforeAll: Hook; afterAll: Hook },\n): KindeTestkitHandle {\n const globals = globalThis as unknown as { beforeAll?: Hook; afterAll?: Hook };\n const beforeAll = hooks?.beforeAll ?? globals.beforeAll;\n const afterAll = hooks?.afterAll ?? globals.afterAll;\n if (typeof beforeAll !== \"function\" || typeof afterAll !== \"function\") {\n throw new Error(\n \"useKindeTestkit() from kinde-testkit/jest needs Jest's beforeAll and afterAll. Call it at the top of a test file, or pass them from @jest/globals.\",\n );\n }\n return createKindeTestkitHandle({ beforeAll, afterAll }, options, \"useKindeTestkit\");\n}\n"],"mappings":";;;;;;;;AAYO,SAAS,gBACd,UAAoC,CAAC,GACrC,OACoB;AACpB,QAAM,UAAU;AAChB,QAAM,YAAY,OAAO,aAAa,QAAQ;AAC9C,QAAM,WAAW,OAAO,YAAY,QAAQ;AAC5C,MAAI,OAAO,cAAc,cAAc,OAAO,aAAa,YAAY;AACrE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,yBAAyB,EAAE,WAAW,SAAS,GAAG,SAAS,iBAAiB;AACrF;","names":[]}
@@ -1,7 +1,9 @@
1
1
  import * as playwright_test from 'playwright/test';
2
2
  import { Page } from '@playwright/test';
3
3
  export { expect } from '@playwright/test';
4
- import { j as FailureRule, d as ActiveFailure, s as SendWebhookOptions, v as WebhookDelivery } from './webhooks-DJyCsbdF.js';
4
+ import { I as Identity, a as FailureRule, A as ActiveFailure, S as SendWebhookOptions, c as WebhookDelivery } from './webhooks-CiK9_pVw.js';
5
+ import { S as SignInMethodOptions } from './sign-in-flow-DNrDXSLI.js';
6
+ import './testkit-BvCAFsSj.js';
5
7
  import 'jose';
6
8
 
7
9
  interface KindeFixtureOptions {
@@ -9,13 +11,20 @@ interface KindeFixtureOptions {
9
11
  loginPath: string;
10
12
  logoutPath: string;
11
13
  }
12
- interface SignInOptions {
14
+ interface SignInOptions extends SignInMethodOptions {
13
15
  org?: string;
14
16
  }
15
17
  interface KindeFixture {
16
18
  readonly issuer: string;
17
19
  readonly currentUser: string | null;
18
20
  signInAs(user: string, options?: SignInOptions): Promise<void>;
21
+ /**
22
+ * Signs in as a seeded user by email, or as an identity described inline. An inline identity is
23
+ * created in the testkit with exactly these roles and permissions, so it needs no seed entry.
24
+ */
25
+ authenticateAs(identity: string | Identity): Promise<void>;
26
+ /** Saves the browser's cookies and storage, so other tests can start signed in with test.use({ storageState }). */
27
+ saveState(path: string): Promise<void>;
19
28
  switchOrganization(org: string): Promise<void>;
20
29
  signOut(): Promise<void>;
21
30
  injectFailure(rule: FailureRule): Promise<ActiveFailure>;
@@ -35,4 +44,4 @@ declare const test: playwright_test.TestType<playwright_test.PlaywrightTestArgs
35
44
  kinde: KindeFixture;
36
45
  }, playwright_test.PlaywrightWorkerArgs & playwright_test.PlaywrightWorkerOptions>;
37
46
 
38
- export { type KindeFixture, type KindeFixtureOptions, type KindeTestOptions, type SignInOptions, createKindeFixture, test };
47
+ export { Identity, type KindeFixture, type KindeFixtureOptions, type KindeTestOptions, type SignInOptions, createKindeFixture, test };
@@ -1,3 +1,7 @@
1
+ import {
2
+ signInFails
3
+ } from "./chunk-EZUKOKNO.js";
4
+
1
5
  // src/playwright.ts
2
6
  import { test as base, expect } from "@playwright/test";
3
7
  function createKindeFixture(page, options) {
@@ -26,6 +30,24 @@ function createKindeFixture(page, options) {
26
30
  );
27
31
  }
28
32
  await page.getByLabel("Email").fill(user);
33
+ if (signIn.connection) await page.getByLabel("Sign in with").selectOption(signIn.connection);
34
+ if (signIn.providerResult) await page.getByLabel("Provider result").selectOption(signIn.providerResult);
35
+ if (signIn.mfa) await page.getByLabel("Multi-factor authentication").selectOption(signIn.mfa);
36
+ if (signInFails(signIn)) {
37
+ if (signIn.mfa === "failed") {
38
+ await page.getByRole("button", { name: "Continue", exact: true }).click();
39
+ await page.getByText("The verification code is not correct.").waitFor();
40
+ return;
41
+ }
42
+ const errorReachedApp = page.waitForRequest((request) => {
43
+ const url = new URL(request.url());
44
+ return !onIssuer(url) && url.searchParams.has("error");
45
+ });
46
+ await page.getByRole("button", { name: "Continue", exact: true }).click();
47
+ await errorReachedApp;
48
+ await page.waitForLoadState();
49
+ return;
50
+ }
29
51
  await page.getByRole("button", { name: "Continue", exact: true }).click();
30
52
  await page.waitForURL((url) => !(onIssuer(url) && url.pathname === "/oauth2/auth"));
31
53
  const landed = new URL(page.url());
@@ -48,6 +70,14 @@ function createKindeFixture(page, options) {
48
70
  return currentUser;
49
71
  },
50
72
  signInAs,
73
+ async authenticateAs(identity) {
74
+ if (typeof identity === "string") return signInAs(identity);
75
+ await control("/testkit/identities", { method: "POST", body: JSON.stringify(identity) });
76
+ await signInAs(identity.email, identity.organization ? { org: identity.organization } : {});
77
+ },
78
+ async saveState(path) {
79
+ await page.context().storageState({ path });
80
+ },
51
81
  async switchOrganization(org) {
52
82
  if (!currentUser) throw new Error("Call signInAs() before switchOrganization().");
53
83
  await signInAs(currentUser, { org });
@@ -1 +1 @@
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\";\nimport type { SendWebhookOptions, WebhookDelivery } from \"./webhooks.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 sendWebhook(options: SendWebhookOptions): Promise<WebhookDelivery[]>;\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 sendWebhook(webhook: SendWebhookOptions) {\n const response = await control(\"/testkit/webhooks\", { method: \"POST\", body: JSON.stringify(webhook) });\n return (await response.json()) as WebhookDelivery[];\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;AAmCzC,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,EAA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AK,cAAc;AAAA,IAClD;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,UAAU,mBAAmB,MAAM;AAAA,MACvC,QAAQ;AAAA,MACR,WAAW;AAAA,MACX,YAAY;AAAA,IACd,CAAC;AACD,UAAM,IAAI,OAAO;AACjB,UAAM,QAAQ,QAAQ;AAAA,EACxB;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\";\nimport type { SendWebhookOptions, WebhookDelivery } from \"./webhooks.js\";\nimport type { Identity } from \"./directory.js\";\nimport { signInFails, type SignInMethodOptions } from \"./sign-in-flow.js\";\n\nexport type { Identity };\n\nexport interface KindeFixtureOptions {\n issuer: string;\n loginPath: string;\n logoutPath: string;\n}\n\nexport interface SignInOptions extends SignInMethodOptions {\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 /**\n * Signs in as a seeded user by email, or as an identity described inline. An inline identity is\n * created in the testkit with exactly these roles and permissions, so it needs no seed entry.\n */\n authenticateAs(identity: string | Identity): Promise<void>;\n /** Saves the browser's cookies and storage, so other tests can start signed in with test.use({ storageState }). */\n saveState(path: string): Promise<void>;\n switchOrganization(org: string): Promise<void>;\n signOut(): Promise<void>;\n injectFailure(rule: FailureRule): Promise<ActiveFailure>;\n clearFailures(): Promise<void>;\n sendWebhook(options: SendWebhookOptions): Promise<WebhookDelivery[]>;\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 if (signIn.connection) await page.getByLabel(\"Sign in with\").selectOption(signIn.connection);\n if (signIn.providerResult) await page.getByLabel(\"Provider result\").selectOption(signIn.providerResult);\n if (signIn.mfa) await page.getByLabel(\"Multi-factor authentication\").selectOption(signIn.mfa);\n\n if (signInFails(signIn)) {\n // The sign-in is meant to fail. A wrong MFA code stays on the sign-in page with an error. A cancelled\n // or failed provider sends the app an OAuth error. What the app does next is up to the app (Kinde's\n // Next.js SDK starts sign-in again), so this waits until the app has received the error.\n if (signIn.mfa === \"failed\") {\n await page.getByRole(\"button\", { name: \"Continue\", exact: true }).click();\n await page.getByText(\"The verification code is not correct.\").waitFor();\n return;\n }\n const errorReachedApp = page.waitForRequest((request) => {\n const url = new URL(request.url());\n return !onIssuer(url) && url.searchParams.has(\"error\");\n });\n await page.getByRole(\"button\", { name: \"Continue\", exact: true }).click();\n await errorReachedApp;\n await page.waitForLoadState();\n return;\n }\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 authenticateAs(identity: string | Identity) {\n if (typeof identity === \"string\") return signInAs(identity);\n await control(\"/testkit/identities\", { method: \"POST\", body: JSON.stringify(identity) });\n await signInAs(identity.email, identity.organization ? { org: identity.organization } : {});\n },\n async saveState(path: string) {\n await page.context().storageState({ path });\n },\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 sendWebhook(webhook: SendWebhookOptions) {\n const response = await control(\"/testkit/webhooks\", { method: \"POST\", body: JSON.stringify(webhook) });\n return (await response.json()) as WebhookDelivery[];\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;AA8CzC,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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AA,IACd,CAAC;AACD,UAAM,IAAI,OAAO;AACjB,UAAM,QAAQ,QAAQ;AAAA,EACxB;AACF,CAAC;","names":[]}
@@ -0,0 +1,43 @@
1
+ import { KindeContextProps } from '@kinde-oss/kinde-auth-react';
2
+ import { ReactNode } from 'react';
3
+ import { m as KindeTestkit, p as ScenarioTokenOverrides, S as Scenario } from './testkit-BvCAFsSj.js';
4
+ import 'jose';
5
+
6
+ interface KindeTestAuthOptions {
7
+ /** Signs the tokens. Defaults to the shared testkit whose issuer is http://localhost:4400. */
8
+ testkit?: KindeTestkit;
9
+ /** Feature flags in the access token, such as { new_editor: true }. */
10
+ featureFlags?: Record<string, boolean | string | number>;
11
+ /** Other token settings, the same as kindeTest() and tokenFor(). */
12
+ token?: ScenarioTokenOverrides;
13
+ }
14
+ /** A call your component made to a Kinde action, such as login() or logout(). */
15
+ interface KindeTestAuthCall {
16
+ method: "login" | "register" | "logout" | "switchOrg" | "refreshToken" | "generatePortalUrl";
17
+ args: unknown[];
18
+ }
19
+ interface KindeTestAuth {
20
+ /** Pass to React Testing Library: render(<App />, { wrapper: auth.wrapper }). */
21
+ wrapper: (props: {
22
+ children?: ReactNode;
23
+ }) => ReactNode;
24
+ /** The value the wrapper gives KindeContext. */
25
+ value: KindeContextProps;
26
+ /** Every login(), logout(), register() and switchOrg() call, in order. */
27
+ calls: KindeTestAuthCall[];
28
+ accessToken: string | null;
29
+ idToken: string | null;
30
+ }
31
+ /**
32
+ * Builds Kinde auth state for components under test. Components that call useKindeAuth() from
33
+ * @kinde-oss/kinde-auth-react or useKindeBrowserClient() from @kinde-oss/kinde-auth-nextjs read
34
+ * real tokens signed for the scenario, through the same @kinde/js-utils functions the SDKs use.
35
+ */
36
+ declare function kindeAuth(scenario: Scenario, options?: KindeTestAuthOptions): Promise<KindeTestAuth>;
37
+ /** Wraps children in Kinde auth state built by kindeAuth(). */
38
+ declare function KindeTestProvider({ auth, children }: {
39
+ auth: KindeTestAuth;
40
+ children?: ReactNode;
41
+ }): ReactNode;
42
+
43
+ export { type KindeTestAuth, type KindeTestAuthCall, type KindeTestAuthOptions, KindeTestProvider, kindeAuth };