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
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sign-in-flow.ts","../src/cypress-support.ts"],"sourcesContent":["/**\n * Steps for signing in through the testkit with plain HTTP requests instead of a browser page.\n * The Cypress commands use these. No Node APIs here, because Cypress bundles this file for the browser.\n */\n\nexport interface RequestSignInOptions {\n /** Email address or ID of the user. */\n user: string;\n /** Active organization, for users in more than one. */\n org?: string;\n}\n\n/** The app's login route, with the hints the testkit sign-in page reads. */\nexport function appLoginUrl(loginPath: string, options: RequestSignInOptions): string {\n const params = new URLSearchParams({ login_hint: options.user });\n if (options.org) params.set(\"org_code\", options.org);\n return `${loginPath}${loginPath.includes(\"?\") ? \"&\" : \"?\"}${params}`;\n}\n\n/** Reads the hidden request field from the testkit sign-in page. */\nexport function readSignInRequest(html: string): string {\n const match = /name=\"request\" value=\"([^\"]+)\"/.exec(html);\n if (!match) {\n throw new Error(\"The page is not the kinde-testkit sign-in page. Check that the app's KINDE_ISSUER_URL points at the testkit.\");\n }\n return decodeEntities(match[1]!);\n}\n\n/** The form the sign-in page posts to /oauth2/auth/login. */\nexport function signInForm(request: string, options: RequestSignInOptions): Record<string, string> {\n const form: Record<string, string> = { request, email: options.user };\n if (options.org) form.org = options.org;\n return form;\n}\n\n/** Explains why the testkit did not redirect back to the app after the form was posted. */\nexport function signInFailure(status: number, html: string, options: RequestSignInOptions): Error {\n if (status === 200 && html.includes(\"Choose an organization\")) {\n return new Error(`${options.user} belongs to more than one organization. Pass one with { org: \"org_...\" }.`);\n }\n const alert = /role=\"alert\"[^>]*>([\\s\\S]*?)<\\//.exec(html)?.[1];\n const text = alert ? decodeEntities(alert.replace(/<[^>]+>/g, \"\")).trim() : `the sign-in page answered ${status}`;\n return new Error(`kinde-testkit refused the sign-in: ${text}`);\n}\n\n/** Resolves a Location header, which can be relative, against the URL that sent it. */\nexport function resolveLocation(location: string, from: string): string {\n return new URL(location, from).toString();\n}\n\nfunction decodeEntities(value: string): string {\n return value\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&amp;/g, \"&\");\n}\n","/**\n * Cypress commands for kinde-testkit. Import this file from cypress/support/e2e.ts:\n *\n * import \"kinde-testkit/cypress/support\";\n *\n * Runs in the browser, so it calls the testkit with cy.request and never imports Node code.\n */\nimport { appLoginUrl, readSignInRequest, resolveLocation, signInFailure, signInForm, type RequestSignInOptions } from \"./sign-in-flow.js\";\nimport type { ActiveFailure, FailureRule } from \"./failures.js\";\nimport type { SendWebhookOptions, WebhookDelivery } from \"./webhooks.js\";\n\nexport interface KindeSignInOptions {\n /** Active organization, for users in more than one. */\n org?: string;\n /** Your app's login route. Default /api/auth/login, as in Kinde's Next.js SDK. */\n loginPath?: string;\n}\n\nexport interface KindeSignOutOptions {\n /** Your app's logout route. Default /api/auth/logout. */\n logoutPath?: string;\n}\n\nexport interface KindeTokenRequest {\n user?: string;\n organization?: string;\n subject?: string;\n permissions?: string[];\n roles?: string[];\n expiresIn?: string | number;\n invalid?: string;\n m2m?: boolean;\n clientId?: string;\n scopes?: string[];\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Cypress {\n // Matches Cypress's own declaration so the two merge.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n interface Chainable<Subject = any> {\n /** Signs a seeded user in through your app's login route, with requests instead of the sign-in page. */\n kindeSignIn(user: string, options?: KindeSignInOptions): Chainable<void>;\n /** Opens your app's logout route. */\n kindeSignOut(options?: KindeSignOutOptions): Chainable<void>;\n /** Mints an access token from the testkit. */\n kindeToken(options: KindeTokenRequest): Chainable<string>;\n /** Makes a testkit endpoint fail, slow down or hang until the test ends. */\n kindeInjectFailure(rule: FailureRule): Chainable<ActiveFailure>;\n /** Removes the failures this test added. */\n kindeClearFailures(): Chainable<void>;\n /** Sends a signed webhook and yields the deliveries. */\n kindeSendWebhook(options: SendWebhookOptions): Chainable<WebhookDelivery[]>;\n /** Clears sessions, failures, webhook deliveries and Management API changes. */\n kindeReset(): Chainable<void>;\n }\n }\n}\n\ninterface CyResponse<T = unknown> {\n status: number;\n body: T;\n headers: Record<string, string | string[]>;\n}\n\ninterface CyRequestOptions {\n method?: string;\n url: string;\n body?: unknown;\n form?: boolean;\n followRedirect?: boolean;\n failOnStatusCode?: boolean;\n log?: boolean;\n}\n\ninterface CyChain<T = unknown> {\n then<R>(fn: (value: T) => R): CyChain<R extends CyChain<infer U> ? U : R>;\n}\n\ninterface Cy {\n request<T = unknown>(options: CyRequestOptions): CyChain<CyResponse<T>>;\n visit(url: string): CyChain;\n wrap<T>(value: T, options?: { log?: boolean }): CyChain<T>;\n url(): CyChain<string>;\n}\n\ninterface CypressStatic {\n env(name: string): unknown;\n config(name: string): unknown;\n Commands: { add(name: string, fn: (...args: never[]) => unknown): void };\n log(options: { name: string; message: string }): void;\n}\n\ndeclare const cy: Cy;\ndeclare const Cypress: CypressStatic;\ndeclare const afterEach: (fn: () => unknown) => void;\n\nconst injected: string[] = [];\n\nfunction issuer(): string {\n const url = (Cypress.env(\"KINDE_TESTKIT_URL\") as string | undefined) ?? (Cypress.env(\"KINDE_ISSUER_URL\") as string | undefined);\n if (!url) {\n throw new Error(\n 'kinde-testkit does not know where the issuer is. Call setupKindeTestkit(on, config) from setupNodeEvents in cypress.config, or set env KINDE_TESTKIT_URL.',\n );\n }\n return url.replace(/\\/+$/, \"\");\n}\n\nfunction appBase(): string {\n const base = Cypress.config(\"baseUrl\") as string | null;\n if (!base) throw new Error(\"Set baseUrl in cypress.config so kinde-testkit can find your app's login route.\");\n return base.replace(/\\/+$/, \"\");\n}\n\nfunction location(response: CyResponse, from: string): string {\n const header = response.headers.location;\n const value = Array.isArray(header) ? header[0] : header;\n if (!value) throw new Error(`Expected a redirect from ${from}, got ${response.status}.`);\n return resolveLocation(value, from);\n}\n\nfunction control<T>(method: string, path: string, body?: unknown): CyChain<T> {\n return cy\n .request<T & { error_description?: string }>({ method, url: `${issuer()}${path}`, body, failOnStatusCode: false, log: false })\n .then((response) => {\n if (response.status >= 400 && response.status !== 404) {\n throw new Error(response.body?.error_description ?? `kinde-testkit answered ${response.status} for ${path}.`);\n }\n return response.body as T;\n }) as CyChain<T>;\n}\n\nCypress.Commands.add(\"kindeSignIn\", (user: string, options: KindeSignInOptions = {}) => {\n const signIn: RequestSignInOptions = { user, org: options.org };\n const start = `${appBase()}${appLoginUrl(options.loginPath ?? \"/api/auth/login\", signIn)}`;\n Cypress.log({ name: \"kindeSignIn\", message: options.org ? `${user} in ${options.org}` : user });\n return cy\n .request({ url: start, followRedirect: false, log: false })\n .then((response) => {\n const signInPage = location(response, start);\n if (!signInPage.startsWith(issuer())) {\n throw new Error(`Expected the login route to redirect to kinde-testkit at ${issuer()}, but it went to ${signInPage}. Check the app's KINDE_ISSUER_URL.`);\n }\n return cy.request<string>({ url: signInPage, log: false });\n })\n .then((page) =>\n cy.request<string>({\n method: \"POST\",\n url: `${issuer()}/oauth2/auth/login`,\n form: true,\n body: signInForm(readSignInRequest(page.body), signIn),\n followRedirect: false,\n failOnStatusCode: false,\n log: false,\n }),\n )\n .then((response) => {\n if (response.status !== 302 && response.status !== 303) throw signInFailure(response.status, String(response.body), signIn);\n return cy.visit(location(response, `${issuer()}/oauth2/auth/login`));\n });\n});\n\nCypress.Commands.add(\"kindeSignOut\", (options: KindeSignOutOptions = {}) => {\n return cy.visit(`${appBase()}${options.logoutPath ?? \"/api/auth/logout\"}`);\n});\n\nCypress.Commands.add(\"kindeToken\", (options: KindeTokenRequest) => {\n return control<{ access_token: string }>(\"POST\", \"/testkit/token\", options).then((body) => body.access_token);\n});\n\nCypress.Commands.add(\"kindeInjectFailure\", (rule: FailureRule) => {\n return control<ActiveFailure>(\"POST\", \"/testkit/failures\", rule).then((failure) => {\n injected.push(failure.id);\n return failure;\n });\n});\n\nfunction clearInjected(): CyChain<void> {\n const ids = injected.splice(0, injected.length);\n let chain: CyChain<unknown> = cy.wrap(null, { log: false });\n for (const id of ids) chain = chain.then(() => control(\"DELETE\", `/testkit/failures/${encodeURIComponent(id)}`));\n return chain.then(() => undefined);\n}\n\nCypress.Commands.add(\"kindeClearFailures\", () => clearInjected());\n\nCypress.Commands.add(\"kindeSendWebhook\", (options: SendWebhookOptions) => {\n return control<WebhookDelivery[]>(\"POST\", \"/testkit/webhooks\", options);\n});\n\nCypress.Commands.add(\"kindeReset\", () => {\n injected.length = 0;\n return control(\"POST\", \"/testkit/reset\").then(() => undefined);\n});\n\nafterEach(() => {\n if (injected.length > 0) return clearInjected();\n return undefined;\n});\n"],"mappings":";AAaO,SAAS,YAAY,WAAmB,SAAuC;AACpF,QAAM,SAAS,IAAI,gBAAgB,EAAE,YAAY,QAAQ,KAAK,CAAC;AAC/D,MAAI,QAAQ,IAAK,QAAO,IAAI,YAAY,QAAQ,GAAG;AACnD,SAAO,GAAG,SAAS,GAAG,UAAU,SAAS,GAAG,IAAI,MAAM,GAAG,GAAG,MAAM;AACpE;AAGO,SAAS,kBAAkB,MAAsB;AACtD,QAAM,QAAQ,iCAAiC,KAAK,IAAI;AACxD,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,8GAA8G;AAAA,EAChI;AACA,SAAO,eAAe,MAAM,CAAC,CAAE;AACjC;AAGO,SAAS,WAAW,SAAiB,SAAuD;AACjG,QAAM,OAA+B,EAAE,SAAS,OAAO,QAAQ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AAqB,OAAO;AACxE,CAAC;AAED,QAAQ,SAAS,IAAI,cAAc,MAAM;AACvC,WAAS,SAAS;AAClB,SAAO,QAAQ,QAAQ,gBAAgB,EAAE,KAAK,MAAM,MAAS;AAC/D,CAAC;AAED,UAAU,MAAM;AACd,MAAI,SAAS,SAAS,EAAG,QAAO,cAAc;AAC9C,SAAO;AACT,CAAC;","names":["location"]}
1
+ {"version":3,"sources":["../src/sign-in-flow.ts","../src/cypress-support.ts"],"sourcesContent":["/**\n * Steps for signing in through the testkit with plain HTTP requests instead of a browser page.\n * The Cypress commands use these. No Node APIs here, because Cypress bundles this file for the browser.\n */\n\n/** What the social provider does when the user picks it on the sign-in page. */\nexport type ProviderResult = \"success\" | \"cancelled\" | \"error\";\n/** What happens at the multi-factor authentication step. */\nexport type MfaOutcome = \"none\" | \"passed\" | \"failed\" | \"cancelled\";\n\n/** How the user signs in on the testkit page. */\nexport interface SignInMethodOptions {\n /** \"email\" (the default), or a social provider such as \"google\", \"github\" or \"microsoft\". */\n connection?: string;\n /** For a social provider: \"success\" (the default), \"cancelled\" by the user, or a provider \"error\". */\n providerResult?: ProviderResult;\n /** Multi-factor authentication: \"none\" (the default), \"passed\", \"failed\" with a wrong code, or \"cancelled\". */\n mfa?: MfaOutcome;\n}\n\nexport interface RequestSignInOptions extends SignInMethodOptions {\n /** Email address or ID of the user. */\n user: string;\n /** Active organization, for users in more than one. */\n org?: string;\n}\n\n/** True when the options ask for a sign-in that does not reach the app with a session. */\nexport function signInFails(options: SignInMethodOptions): boolean {\n return options.mfa === \"failed\" || options.mfa === \"cancelled\" || options.providerResult === \"cancelled\" || options.providerResult === \"error\";\n}\n\n/** The app's login route, with the hints the testkit sign-in page reads. */\nexport function appLoginUrl(loginPath: string, options: RequestSignInOptions): string {\n const params = new URLSearchParams({ login_hint: options.user });\n if (options.org) params.set(\"org_code\", options.org);\n return `${loginPath}${loginPath.includes(\"?\") ? \"&\" : \"?\"}${params}`;\n}\n\n/** Reads the hidden request field from the testkit sign-in page. */\nexport function readSignInRequest(html: string): string {\n const match = /name=\"request\" value=\"([^\"]+)\"/.exec(html);\n if (!match) {\n throw new Error(\"The page is not the kinde-testkit sign-in page. Check that the app's KINDE_ISSUER_URL points at the testkit.\");\n }\n return decodeEntities(match[1]!);\n}\n\n/** The form the sign-in page posts to /oauth2/auth/login. */\nexport function signInForm(request: string, options: RequestSignInOptions): Record<string, string> {\n const form: Record<string, string> = { request, email: options.user };\n if (options.org) form.org = options.org;\n if (options.connection) form.connection = options.connection;\n if (options.providerResult) form.provider_result = options.providerResult;\n if (options.mfa) form.mfa = options.mfa;\n return form;\n}\n\n/** Explains why the testkit did not redirect back to the app after the form was posted. */\nexport function signInFailure(status: number, html: string, options: RequestSignInOptions): Error {\n if (status === 200 && html.includes(\"Choose an organization\")) {\n return new Error(`${options.user} belongs to more than one organization. Pass one with { org: \"org_...\" }.`);\n }\n const alert = /role=\"alert\"[^>]*>([\\s\\S]*?)<\\//.exec(html)?.[1];\n const text = alert ? decodeEntities(alert.replace(/<[^>]+>/g, \"\")).trim() : `the sign-in page answered ${status}`;\n return new Error(`kinde-testkit refused the sign-in: ${text}`);\n}\n\n/** Resolves a Location header, which can be relative, against the URL that sent it. */\nexport function resolveLocation(location: string, from: string): string {\n return new URL(location, from).toString();\n}\n\nfunction decodeEntities(value: string): string {\n return value\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&amp;/g, \"&\");\n}\n","/**\n * Cypress commands for kinde-testkit. Import this file from cypress/support/e2e.ts:\n *\n * import \"kinde-testkit/cypress/support\";\n *\n * Runs in the browser, so it calls the testkit with cy.request and never imports Node code.\n */\nimport {\n appLoginUrl,\n readSignInRequest,\n resolveLocation,\n signInFailure,\n signInFails,\n signInForm,\n type RequestSignInOptions,\n type SignInMethodOptions,\n} from \"./sign-in-flow.js\";\nimport type { ActiveFailure, FailureRule } from \"./failures.js\";\nimport type { SendWebhookOptions, WebhookDelivery } from \"./webhooks.js\";\nimport type { Identity } from \"./directory.js\";\n\nexport interface KindeSignInOptions extends SignInMethodOptions {\n /** Active organization, for users in more than one. */\n org?: string;\n /** Your app's login route. Default /api/auth/login, as in Kinde's Next.js SDK. */\n loginPath?: string;\n}\n\nexport interface KindeSignOutOptions {\n /** Your app's logout route. Default /api/auth/logout. */\n logoutPath?: string;\n}\n\nexport interface KindeTokenRequest {\n user?: string;\n organization?: string;\n subject?: string;\n permissions?: string[];\n roles?: string[];\n expiresIn?: string | number;\n invalid?: string;\n m2m?: boolean;\n clientId?: string;\n scopes?: string[];\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Cypress {\n // Matches Cypress's own declaration so the two merge.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n interface Chainable<Subject = any> {\n /** Signs a seeded user in through your app's login route, with requests instead of the sign-in page. */\n kindeSignIn(user: string, options?: KindeSignInOptions): Chainable<void>;\n /** Signs in as a seeded user by email, or as an identity described inline with its organization, roles and permissions. */\n kindeAuthenticateAs(identity: string | Identity, options?: Omit<KindeSignInOptions, \"org\">): Chainable<void>;\n /** Opens your app's logout route. */\n kindeSignOut(options?: KindeSignOutOptions): Chainable<void>;\n /** Mints an access token from the testkit. */\n kindeToken(options: KindeTokenRequest): Chainable<string>;\n /** Makes a testkit endpoint fail, slow down or hang until the test ends. */\n kindeInjectFailure(rule: FailureRule): Chainable<ActiveFailure>;\n /** Removes the failures this test added. */\n kindeClearFailures(): Chainable<void>;\n /** Sends a signed webhook and yields the deliveries. */\n kindeSendWebhook(options: SendWebhookOptions): Chainable<WebhookDelivery[]>;\n /** Clears sessions, failures, webhook deliveries and Management API changes. */\n kindeReset(): Chainable<void>;\n }\n }\n}\n\ninterface CyResponse<T = unknown> {\n status: number;\n body: T;\n headers: Record<string, string | string[]>;\n}\n\ninterface CyRequestOptions {\n method?: string;\n url: string;\n body?: unknown;\n form?: boolean;\n followRedirect?: boolean;\n failOnStatusCode?: boolean;\n log?: boolean;\n}\n\ninterface CyChain<T = unknown> {\n then<R>(fn: (value: T) => R): CyChain<R extends CyChain<infer U> ? U : R>;\n}\n\ninterface Cy {\n request<T = unknown>(options: CyRequestOptions): CyChain<CyResponse<T>>;\n visit(url: string, options?: { failOnStatusCode?: boolean }): CyChain;\n wrap<T>(value: T, options?: { log?: boolean }): CyChain<T>;\n url(): CyChain<string>;\n}\n\ninterface CypressStatic {\n env(name: string): unknown;\n config(name: string): unknown;\n Commands: { add(name: string, fn: (...args: never[]) => unknown): void };\n log(options: { name: string; message: string }): void;\n}\n\ndeclare const cy: Cy;\ndeclare const Cypress: CypressStatic;\ndeclare const afterEach: (fn: () => unknown) => void;\n\nconst injected: string[] = [];\n\nfunction issuer(): string {\n const url = (Cypress.env(\"KINDE_TESTKIT_URL\") as string | undefined) ?? (Cypress.env(\"KINDE_ISSUER_URL\") as string | undefined);\n if (!url) {\n throw new Error(\n 'kinde-testkit does not know where the issuer is. Call setupKindeTestkit(on, config) from setupNodeEvents in cypress.config, or set env KINDE_TESTKIT_URL.',\n );\n }\n return url.replace(/\\/+$/, \"\");\n}\n\nfunction appBase(): string {\n const base = Cypress.config(\"baseUrl\") as string | null;\n if (!base) throw new Error(\"Set baseUrl in cypress.config so kinde-testkit can find your app's login route.\");\n return base.replace(/\\/+$/, \"\");\n}\n\nfunction location(response: CyResponse, from: string): string {\n const header = response.headers.location;\n const value = Array.isArray(header) ? header[0] : header;\n if (!value) throw new Error(`Expected a redirect from ${from}, got ${response.status}.`);\n return resolveLocation(value, from);\n}\n\nfunction control<T>(method: string, path: string, body?: unknown): CyChain<T> {\n return cy\n .request<T & { error_description?: string }>({ method, url: `${issuer()}${path}`, body, failOnStatusCode: false, log: false })\n .then((response) => {\n if (response.status >= 400 && response.status !== 404) {\n throw new Error(response.body?.error_description ?? `kinde-testkit answered ${response.status} for ${path}.`);\n }\n return response.body as T;\n }) as CyChain<T>;\n}\n\nfunction signIn(user: string, options: KindeSignInOptions = {}) {\n const signIn: RequestSignInOptions = { user, org: options.org, connection: options.connection, providerResult: options.providerResult, mfa: options.mfa };\n const failing = signInFails(signIn);\n const start = `${appBase()}${appLoginUrl(options.loginPath ?? \"/api/auth/login\", signIn)}`;\n Cypress.log({ name: \"kindeSignIn\", message: options.org ? `${user} in ${options.org}` : user });\n return cy\n .request({ url: start, followRedirect: false, log: false })\n .then((response) => {\n const signInPage = location(response, start);\n if (!signInPage.startsWith(issuer())) {\n throw new Error(`Expected the login route to redirect to kinde-testkit at ${issuer()}, but it went to ${signInPage}. Check the app's KINDE_ISSUER_URL.`);\n }\n return cy.request<string>({ url: signInPage, log: false });\n })\n .then((page) =>\n cy.request<string>({\n method: \"POST\",\n url: `${issuer()}/oauth2/auth/login`,\n form: true,\n body: signInForm(readSignInRequest(page.body), signIn),\n followRedirect: false,\n failOnStatusCode: false,\n log: false,\n }),\n )\n .then((response) => {\n // A wrong MFA code keeps the user on the sign-in page, so there is nothing for the app to receive.\n if (failing && signIn.mfa === \"failed\" && response.status === 401) return undefined;\n if (response.status !== 302 && response.status !== 303) throw signInFailure(response.status, String(response.body), signIn);\n // A cancelled or failed sign-in returns to the app with an OAuth error, which the app may answer with an error status.\n return cy.visit(location(response, `${issuer()}/oauth2/auth/login`), failing ? { failOnStatusCode: false } : undefined);\n });\n}\n\nCypress.Commands.add(\"kindeSignIn\", signIn);\n\nCypress.Commands.add(\"kindeAuthenticateAs\", (identity: string | Identity, options: Omit<KindeSignInOptions, \"org\"> = {}) => {\n if (typeof identity === \"string\") return signIn(identity, options);\n return control(\"POST\", \"/testkit/identities\", identity).then(() =>\n signIn(identity.email, { ...options, ...(identity.organization ? { org: identity.organization } : {}) }),\n );\n});\n\nCypress.Commands.add(\"kindeSignOut\", (options: KindeSignOutOptions = {}) => {\n return cy.visit(`${appBase()}${options.logoutPath ?? \"/api/auth/logout\"}`);\n});\n\nCypress.Commands.add(\"kindeToken\", (options: KindeTokenRequest) => {\n return control<{ access_token: string }>(\"POST\", \"/testkit/token\", options).then((body) => body.access_token);\n});\n\nCypress.Commands.add(\"kindeInjectFailure\", (rule: FailureRule) => {\n return control<ActiveFailure>(\"POST\", \"/testkit/failures\", rule).then((failure) => {\n injected.push(failure.id);\n return failure;\n });\n});\n\nfunction clearInjected(): CyChain<void> {\n const ids = injected.splice(0, injected.length);\n let chain: CyChain<unknown> = cy.wrap(null, { log: false });\n for (const id of ids) chain = chain.then(() => control(\"DELETE\", `/testkit/failures/${encodeURIComponent(id)}`));\n return chain.then(() => undefined);\n}\n\nCypress.Commands.add(\"kindeClearFailures\", () => clearInjected());\n\nCypress.Commands.add(\"kindeSendWebhook\", (options: SendWebhookOptions) => {\n return control<WebhookDelivery[]>(\"POST\", \"/testkit/webhooks\", options);\n});\n\nCypress.Commands.add(\"kindeReset\", () => {\n injected.length = 0;\n return control(\"POST\", \"/testkit/reset\").then(() => undefined);\n});\n\nafterEach(() => {\n if (injected.length > 0) return clearInjected();\n return undefined;\n});\n"],"mappings":";AA4BO,SAAS,YAAY,SAAuC;AACjE,SAAO,QAAQ,QAAQ,YAAY,QAAQ,QAAQ,eAAe,QAAQ,mBAAmB,eAAe,QAAQ,mBAAmB;AACzI;AAGO,SAAS,YAAY,WAAmB,SAAuC;AACpF,QAAM,SAAS,IAAI,gBAAgB,EAAE,YAAY,QAAQ,KAAK,CAAC;AAC/D,MAAI,QAAQ,IAAK,QAAO,IAAI,YAAY,QAAQ,GAAG;AACnD,SAAO,GAAG,SAAS,GAAG,UAAU,SAAS,GAAG,IAAI,MAAM,GAAG,GAAG,MAAM;AACpE;AAGO,SAAS,kBAAkB,MAAsB;AACtD,QAAM,QAAQ,iCAAiC,KAAK,IAAI;AACxD,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,8GAA8G;AAAA,EAChI;AACA,SAAO,eAAe,MAAM,CAAC,CAAE;AACjC;AAGO,SAAS,WAAW,SAAiB,SAAuD;AACjG,QAAM,OAA+B,EAAE,SAAS,OAAO,QAA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O,QAAkC,QAAQ,kBAAkB,OAAO,EAAE,KAAK,CAAC,SAAS,KAAK,YAAY;AAC9G,CAAC;AAED,QAAQ,SAAS,IAAI,sBAAsB,CAAC,SAAsB;AAChE,SAAO,QAAuB,QAAQ,qBAAqB,IAAI,EAAE,KAAK,CAAC,YAAY;AACjF,aAAS,KAAK,QAAQ,EAAE;AACxB,WAAO;AAAA,EACT,CAAC;AACH,CAAC;AAED,SAAS,gBAA+B;AACtC,QAAM,MAAM,SAAS,OAAO,GAAG,SAAS,MAAM;AAC9C,MAAI,QAA0B,GAAG,KAAK,MAAM,EAAE,KAAK,MAAM,CAAC;AAC1D,aAAW,MAAM,IAAK,SAAQ,MAAM,KAAK,MAAM,QAAQ,UAAU,qBAAqB,mBAAmB,EAAE,CAAC,EAAE,CAAC;AAC/G,SAAO,MAAM,KAAK,MAAM,MAAS;AACnC;AAEA,QAAQ,SAAS,IAAI,sBAAsB,MAAM,cAAc,CAAC;AAEhE,QAAQ,SAAS,IAAI,oBAAoB,CAAC,YAAgC;AACxE,SAAO,QAA2B,QAAQ,qBAAqB,OAAO;AACxE,CAAC;AAED,QAAQ,SAAS,IAAI,cAAc,MAAM;AACvC,WAAS,SAAS;AAClB,SAAO,QAAQ,QAAQ,gBAAgB,EAAE,KAAK,MAAM,MAAS;AAC/D,CAAC;AAED,UAAU,MAAM;AACd,MAAI,SAAS,SAAS,EAAG,QAAO,cAAc;AAC9C,SAAO;AACT,CAAC;","names":["location","signIn"]}
package/dist/cypress.cjs CHANGED
@@ -1469,6 +1469,25 @@ function layout(title, body) {
1469
1469
  function displayName(user) {
1470
1470
  return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
1471
1471
  }
1472
+ var SOCIAL_CONNECTIONS = ["google", "github", "microsoft", "apple", "facebook", "gitlab", "linkedin", "slack", "x"];
1473
+ function select(id, label, options) {
1474
+ 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>`;
1475
+ }
1476
+ function testOptions() {
1477
+ return `<h2>Test options</h2>${select("connection", "Sign in with", [
1478
+ ["email", "Email"],
1479
+ ...SOCIAL_CONNECTIONS.map((c) => [c, c === "x" ? "X" : c[0].toUpperCase() + c.slice(1)])
1480
+ ])}${select("provider_result", "Provider result", [
1481
+ ["success", "Signed in"],
1482
+ ["cancelled", "User cancelled"],
1483
+ ["error", "Provider error"]
1484
+ ])}${select("mfa", "Multi-factor authentication", [
1485
+ ["none", "Not required"],
1486
+ ["passed", "Passed"],
1487
+ ["failed", "Wrong code"],
1488
+ ["cancelled", "Cancelled"]
1489
+ ])}`;
1490
+ }
1472
1491
  function renderSignIn(options) {
1473
1492
  const users = options.users.map(({ user, organizations }) => {
1474
1493
  const value = escapeHtml(user.email ?? user.id);
@@ -1480,16 +1499,17 @@ function renderSignIn(options) {
1480
1499
  const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
1481
1500
  return layout(
1482
1501
  "Sign in",
1483
- `<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>`
1502
+ `<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>`
1484
1503
  );
1485
1504
  }
1486
1505
  function renderOrganizationPicker(options) {
1506
+ const carried = Object.entries(options.carry ?? {}).map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`).join("");
1487
1507
  const choices = options.organizations.map(
1488
1508
  (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>`
1489
1509
  ).join("");
1490
1510
  return layout(
1491
1511
  "Choose an organization",
1492
- `<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>`
1512
+ `<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>`
1493
1513
  );
1494
1514
  }
1495
1515
  function renderMessage(title, message2) {
@@ -1930,6 +1950,17 @@ var AuthorizationServer = class {
1930
1950
  return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
1931
1951
  }
1932
1952
  const encoded = encodeRequest(request);
1953
+ const connection = (form2.connection || "email").trim().toLowerCase();
1954
+ const providerResult = form2.provider_result || "success";
1955
+ const mfa = form2.mfa || "none";
1956
+ if (!/^[a-z0-9_-]{1,40}$/.test(connection) || !["success", "cancelled", "error"].includes(providerResult) || !["none", "passed", "failed", "cancelled"].includes(mfa)) {
1957
+ 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." }));
1958
+ }
1959
+ if (connection !== "email" && providerResult !== "success") {
1960
+ this.observe("session.sign-in-refused");
1961
+ 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.`);
1962
+ }
1963
+ const carry = { connection, provider_result: providerResult, mfa };
1933
1964
  const ref = (form2.user || form2.email || "").trim();
1934
1965
  if (!ref) {
1935
1966
  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." }));
@@ -1951,6 +1982,21 @@ var AuthorizationServer = class {
1951
1982
  })
1952
1983
  );
1953
1984
  }
1985
+ if (mfa === "failed") {
1986
+ this.observe("session.sign-in-refused");
1987
+ return sendHtml(
1988
+ res,
1989
+ 401,
1990
+ renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "The verification code is not correct." })
1991
+ );
1992
+ }
1993
+ if (mfa === "cancelled") {
1994
+ this.observe("session.sign-in-refused");
1995
+ return redirectWithError(res, request, "access_denied", "The user cancelled multi-factor authentication.");
1996
+ }
1997
+ if (connection !== "email") this.observe("identity.social");
1998
+ if (mfa === "passed") this.observe("identity.mfa");
1999
+ const authMethods = [connection, ...mfa === "passed" ? ["mfa"] : []];
1954
2000
  const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
1955
2001
  const wanted = request.orgCode ?? form2.org ?? null;
1956
2002
  let organizationCode = null;
@@ -1978,7 +2024,8 @@ var AuthorizationServer = class {
1978
2024
  renderOrganizationPicker({
1979
2025
  request: encoded,
1980
2026
  user,
1981
- organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
2027
+ organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null),
2028
+ carry
1982
2029
  })
1983
2030
  );
1984
2031
  }
@@ -2000,6 +2047,7 @@ var AuthorizationServer = class {
2000
2047
  audience: request.audience,
2001
2048
  nonce: request.nonce,
2002
2049
  authTime: Math.floor(Date.now() / 1e3),
2050
+ authMethods,
2003
2051
  codeChallenge: request.codeChallenge,
2004
2052
  codeChallengeMethod: request.codeChallengeMethod,
2005
2053
  expiresAt: Date.now() + CODE_LIFETIME_MS
@@ -2311,6 +2359,7 @@ var AuthorizationServer = class {
2311
2359
  clientId: grant.clientId,
2312
2360
  audience: grant.audience.length > 0 ? grant.audience : void 0,
2313
2361
  authTime: grant.authTime,
2362
+ authMethods: grant.authMethods,
2314
2363
  featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
2315
2364
  }),
2316
2365
  expires_in: this.testkit.accessTokenLifetime,
@@ -2321,7 +2370,8 @@ var AuthorizationServer = class {
2321
2370
  body.id_token = await this.testkit.idTokenFor(scenario, {
2322
2371
  clientId: grant.clientId,
2323
2372
  nonce: grant.nonce ?? void 0,
2324
- authTime: grant.authTime
2373
+ authTime: grant.authTime,
2374
+ authMethods: grant.authMethods
2325
2375
  });
2326
2376
  }
2327
2377
  if (grant.scope.includes("offline")) {
@@ -2669,7 +2719,8 @@ var Directory = class {
2669
2719
  isPasswordResetRequested: false,
2670
2720
  createdOn: (/* @__PURE__ */ new Date()).toISOString(),
2671
2721
  totalSignIns: 0,
2672
- lastSignedIn: null
2722
+ lastSignedIn: null,
2723
+ lastOrganizationSignIns: {}
2673
2724
  };
2674
2725
  this.userMeta.set(user.id, meta);
2675
2726
  }
@@ -2682,7 +2733,7 @@ var Directory = class {
2682
2733
  const meta = this.meta(user);
2683
2734
  meta.totalSignIns += 1;
2684
2735
  meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
2685
- void organizationCode;
2736
+ if (organizationCode) meta.lastOrganizationSignIns[organizationCode] = meta.lastSignedIn;
2686
2737
  }
2687
2738
  createUser(input) {
2688
2739
  const user = createKindeUser({
@@ -2752,6 +2803,34 @@ var Directory = class {
2752
2803
  for (const key of permissions) this.ensurePermission(key);
2753
2804
  return membership;
2754
2805
  }
2806
+ /**
2807
+ * Makes sure a user exists with exactly these roles and permissions in the organization, creating
2808
+ * the user, organization and membership when they are missing. Used by authenticateAs() in browser
2809
+ * tests, so a test can sign in as any identity without adding it to the seed. reset() removes it.
2810
+ */
2811
+ ensureIdentity(input) {
2812
+ const email = input.email.trim().toLowerCase();
2813
+ let user = findUser(this.seed.users, email);
2814
+ if (!user) {
2815
+ user = createKindeUser({ email, givenName: input.givenName ?? null, familyName: input.familyName ?? null });
2816
+ this.seed.users.push(user);
2817
+ }
2818
+ if (!input.organization) return { user, organization: null };
2819
+ let organization = this.organization(input.organization);
2820
+ if (!organization) {
2821
+ organization = createKindeOrganization({ code: input.organization, name: input.organizationName ?? input.organization });
2822
+ this.seed.organizations.push(organization);
2823
+ }
2824
+ const roles = input.roles ?? [];
2825
+ const permissions = input.permissions ?? [];
2826
+ const index = this.seed.memberships.findIndex((m) => m.userId === user.id && m.organizationCode === organization.code);
2827
+ const membership = createMembership({ userId: user.id, organizationCode: organization.code, roles, permissions });
2828
+ if (index >= 0) this.seed.memberships[index] = membership;
2829
+ else this.seed.memberships.push(membership);
2830
+ for (const key of roles) this.ensureRole(key);
2831
+ for (const key of permissions) this.ensurePermission(key);
2832
+ return { user, organization };
2833
+ }
2755
2834
  removeMembership(userId, organizationCode) {
2756
2835
  const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
2757
2836
  if (index < 0) return false;
@@ -3129,12 +3208,14 @@ var ManagementApi = class {
3129
3208
  username: null,
3130
3209
  last_name: user.familyName,
3131
3210
  first_name: user.givenName,
3211
+ full_name: [user.givenName, user.familyName].filter(Boolean).join(" ") || null,
3132
3212
  is_suspended: meta.isSuspended,
3133
3213
  picture: user.picture,
3134
3214
  total_sign_ins: meta.totalSignIns,
3135
3215
  failed_sign_ins: 0,
3136
3216
  last_signed_in: meta.lastSignedIn,
3137
3217
  created_on: meta.createdOn,
3218
+ last_organization_sign_ins: Object.entries(meta.lastOrganizationSignIns).map(([org_code, last_signed_in]) => ({ org_code, last_signed_in })),
3138
3219
  organizations: this.organizationsOf(user),
3139
3220
  identities: user.email ? [{ type: "email", identity: user.email }] : []
3140
3221
  };
@@ -3154,7 +3235,8 @@ var ManagementApi = class {
3154
3235
  handle: meta.handle,
3155
3236
  is_default: false,
3156
3237
  external_id: meta.externalId,
3157
- is_auto_membership_enabled: false
3238
+ is_auto_membership_enabled: false,
3239
+ created_on: meta.createdOn
3158
3240
  };
3159
3241
  }
3160
3242
  organizationEvent(org) {
@@ -3165,7 +3247,7 @@ var ManagementApi = class {
3165
3247
  return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
3166
3248
  }
3167
3249
  permissionItem(permission) {
3168
- return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
3250
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, is_organization_role_assignable: false };
3169
3251
  }
3170
3252
  };
3171
3253
  function paginate(items, query) {
@@ -3194,6 +3276,7 @@ function sendJson3(res, status, body) {
3194
3276
  }
3195
3277
 
3196
3278
  // src/failures.ts
3279
+ var MALFORMED_KINDS = ["invalid-json", "empty", "html", "unexpected-json"];
3197
3280
  var MAX_DELAY_MS = 6e4;
3198
3281
  var FailureInjector = class {
3199
3282
  rules = [];
@@ -3212,6 +3295,7 @@ var FailureInjector = class {
3212
3295
  hang: rule.hang ?? false,
3213
3296
  remaining: rule.times ?? null,
3214
3297
  retryAfter: rule.retryAfter ?? 1,
3298
+ malformed: rule.malformed ?? null,
3215
3299
  hits: 0
3216
3300
  };
3217
3301
  this.rules.push(active);
@@ -3243,6 +3327,18 @@ function failureBody(status) {
3243
3327
  const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
3244
3328
  return { error, error_description: `kinde-testkit injected a ${status} response.` };
3245
3329
  }
3330
+ function malformedBody(kind) {
3331
+ switch (kind) {
3332
+ case "invalid-json":
3333
+ return { contentType: "application/json", body: '{"access_token":"eyJhbGciOiJSUzI1NiJ9.' };
3334
+ case "empty":
3335
+ return { contentType: "application/json", body: "" };
3336
+ case "html":
3337
+ return { contentType: "text/html; charset=utf-8", body: "<!doctype html><html><body><h1>Bad gateway</h1></body></html>" };
3338
+ case "unexpected-json":
3339
+ return { contentType: "application/json", body: JSON.stringify({ message: "kinde-testkit sent a JSON body in a shape your client does not expect." }) };
3340
+ }
3341
+ }
3246
3342
  function matches(rule, method, path) {
3247
3343
  if (rule.method && rule.method !== method.toUpperCase()) return false;
3248
3344
  if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
@@ -3255,8 +3351,12 @@ function validate(rule) {
3255
3351
  } else if (rule.path.startsWith("/testkit/")) {
3256
3352
  problems.push("Failures cannot target /testkit/ control endpoints.");
3257
3353
  }
3258
- if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
3259
- problems.push('"status" must be an HTTP error status between 400 and 599.');
3354
+ if (rule.malformed !== void 0 && !MALFORMED_KINDS.includes(rule.malformed)) {
3355
+ problems.push(`"malformed" must be one of ${MALFORMED_KINDS.join(", ")}.`);
3356
+ }
3357
+ const lowest = rule.malformed ? 200 : 400;
3358
+ if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < lowest || rule.status > 599)) {
3359
+ problems.push(rule.malformed ? '"status" must be between 200 and 599.' : '"status" must be an HTTP error status between 400 and 599.');
3260
3360
  }
3261
3361
  if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
3262
3362
  problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
@@ -3267,8 +3367,8 @@ function validate(rule) {
3267
3367
  if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
3268
3368
  problems.push('"retryAfter" must be a whole number of seconds.');
3269
3369
  }
3270
- if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
3271
- problems.push('Set at least one of "status", "delayMs" or "hang".');
3370
+ if (rule.status === void 0 && !rule.delayMs && !rule.hang && !rule.malformed) {
3371
+ problems.push('Set at least one of "status", "delayMs", "hang" or "malformed".');
3272
3372
  }
3273
3373
  return problems;
3274
3374
  }
@@ -3624,7 +3724,9 @@ var COVERAGE_GROUPS = [
3624
3724
  { id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
3625
3725
  { id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
3626
3726
  { id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
3627
- { id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
3727
+ { id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." },
3728
+ { id: "identity.social", label: "Social sign-in", hint: 'Sign in with a social connection, such as signInAs(email, { connection: "google" }).' },
3729
+ { id: "identity.mfa", label: "Multi-factor sign-in", hint: 'Sign in with { mfa: "passed" }.' }
3628
3730
  ]
3629
3731
  },
3630
3732
  {
@@ -3661,6 +3763,7 @@ var COVERAGE_GROUPS = [
3661
3763
  { id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
3662
3764
  { id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
3663
3765
  { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." },
3766
+ { 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.` },
3664
3767
  { id: "session.device-approved", label: "Device sign-in", hint: "Run the device authorization flow and approve it with POST /testkit/device." }
3665
3768
  ]
3666
3769
  },
@@ -3698,7 +3801,8 @@ var COVERAGE_GROUPS = [
3698
3801
  { id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
3699
3802
  { id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
3700
3803
  { id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
3701
- { id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
3804
+ { id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." },
3805
+ { id: "outage.malformed", label: "Malformed answer", hint: "Inject a malformed response, such as invalid JSON from the token endpoint." }
3702
3806
  ]
3703
3807
  }
3704
3808
  ];
@@ -4141,6 +4245,13 @@ async function handle(req, res, context) {
4141
4245
  if (failure.delayMs > 0) coverage.hit("outage.slow");
4142
4246
  if (failure.hang) return;
4143
4247
  if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
4248
+ if (failure.malformed) {
4249
+ coverage.hit("outage.malformed");
4250
+ const { contentType, body } = malformedBody(failure.malformed);
4251
+ res.writeHead(failure.status ?? 200, { "content-type": contentType, "cache-control": "no-store" });
4252
+ res.end(body);
4253
+ return;
4254
+ }
4144
4255
  if (failure.status !== null) {
4145
4256
  const headers = {};
4146
4257
  if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
@@ -4208,6 +4319,23 @@ async function handle(req, res, context) {
4208
4319
  const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
4209
4320
  return sendJson4(res, removed ? 200 : 404, { ok: removed });
4210
4321
  }
4322
+ if (method === "POST" && pathname === "/testkit/identities") {
4323
+ const input = await readJson(req);
4324
+ if (typeof input.email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.email)) {
4325
+ throw new TestkitError("INVALID_REQUEST", "An identity needs an email address.");
4326
+ }
4327
+ const strings2 = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : void 0;
4328
+ const { user, organization } = context.directory.ensureIdentity({
4329
+ email: input.email,
4330
+ givenName: typeof input.givenName === "string" ? input.givenName : null,
4331
+ familyName: typeof input.familyName === "string" ? input.familyName : null,
4332
+ organization: typeof input.organization === "string" ? input.organization : null,
4333
+ organizationName: typeof input.organizationName === "string" ? input.organizationName : void 0,
4334
+ roles: strings2(input.roles),
4335
+ permissions: strings2(input.permissions)
4336
+ });
4337
+ return sendJson4(res, 200, { user: { id: user.id, email: user.email }, organization: organization?.code ?? null });
4338
+ }
4211
4339
  if (method === "POST" && pathname === "/testkit/device") {
4212
4340
  const input = await readJson(req);
4213
4341
  try {
@@ -1,4 +1,4 @@
1
- import { S as StartKindeTestkitOptions } from './server-CTBJXMac.cjs';
1
+ import { S as StartKindeTestkitOptions } from './server-CLRn67qI.cjs';
2
2
  import 'jose';
3
3
 
4
4
  interface SetupKindeTestkitOptions {
package/dist/cypress.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { S as StartKindeTestkitOptions } from './server-B9fBcnyQ.js';
2
- import './webhooks-DJyCsbdF.js';
1
+ import { S as StartKindeTestkitOptions } from './server-CuHAHsaN.js';
2
+ import './testkit-BvCAFsSj.js';
3
3
  import 'jose';
4
+ import './webhooks-CiK9_pVw.js';
4
5
 
5
6
  interface SetupKindeTestkitOptions {
6
7
  /**
package/dist/cypress.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  startKindeTestkit
3
- } from "./chunk-JTAB2S44.js";
3
+ } from "./chunk-CY75AADD.js";
4
+ import "./chunk-BPPG4G52.js";
4
5
 
5
6
  // src/cypress.ts
6
7
  async function setupKindeTestkit(on, config, options = {}) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cypress.ts"],"sourcesContent":["import { startKindeTestkit, type RunningKindeTestkit, type StartKindeTestkitOptions } from \"./server.js\";\n\nexport interface SetupKindeTestkitOptions {\n /**\n * Start a testkit inside the Cypress process. Your app must use the same issuer,\n * so keep the default port 4400 or set KINDE_ISSUER_URL to match.\n * Leave this out to use an issuer you started yourself with `kinde-testkit start`.\n */\n start?: StartKindeTestkitOptions;\n /** The issuer to use when you started it yourself. Default: KINDE_ISSUER_URL, then http://localhost:4400. */\n url?: string;\n}\n\ninterface CypressConfig {\n env: Record<string, unknown>;\n}\n\n// Matches the \"after:run\" overload of Cypress's on(), so Cypress's own on() can be passed in.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype On = (event: \"after:run\", handler: (results: any) => void | Promise<void>) => void;\n\n/**\n * Call from setupNodeEvents in cypress.config.ts. Starts the testkit when asked and tells the\n * kinde-testkit Cypress commands where it is, through Cypress.env(\"KINDE_TESTKIT_URL\").\n */\nexport async function setupKindeTestkit<C extends CypressConfig>(\n on: On,\n config: C,\n options: SetupKindeTestkitOptions = {},\n): Promise<C> {\n let url = options.url ?? (config.env.KINDE_TESTKIT_URL as string | undefined) ?? process.env.KINDE_ISSUER_URL ?? \"http://localhost:4400\";\n let running: RunningKindeTestkit | null = null;\n if (options.start) {\n running = await startKindeTestkit({ port: 4400, ...options.start });\n url = running.url;\n on(\"after:run\", async () => {\n await running?.close();\n running = null;\n });\n }\n config.env.KINDE_TESTKIT_URL = url.replace(/\\/+$/, \"\");\n return config;\n}\n"],"mappings":";;;;;AAyBA,eAAsB,kBACpB,IACA,QACA,UAAoC,CAAC,GACzB;AACZ,MAAI,MAAM,QAAQ,OAAQ,OAAO,IAAI,qBAA4C,QAAQ,IAAI,oBAAoB;AACjH,MAAI,UAAsC;AAC1C,MAAI,QAAQ,OAAO;AACjB,cAAU,MAAM,kBAAkB,EAAE,MAAM,MAAM,GAAG,QAAQ,MAAM,CAAC;AAClE,UAAM,QAAQ;AACd,OAAG,aAAa,YAAY;AAC1B,YAAM,SAAS,MAAM;AACrB,gBAAU;AAAA,IACZ,CAAC;AAAA,EACH;AACA,SAAO,IAAI,oBAAoB,IAAI,QAAQ,QAAQ,EAAE;AACrD,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/cypress.ts"],"sourcesContent":["import { startKindeTestkit, type RunningKindeTestkit, type StartKindeTestkitOptions } from \"./server.js\";\n\nexport interface SetupKindeTestkitOptions {\n /**\n * Start a testkit inside the Cypress process. Your app must use the same issuer,\n * so keep the default port 4400 or set KINDE_ISSUER_URL to match.\n * Leave this out to use an issuer you started yourself with `kinde-testkit start`.\n */\n start?: StartKindeTestkitOptions;\n /** The issuer to use when you started it yourself. Default: KINDE_ISSUER_URL, then http://localhost:4400. */\n url?: string;\n}\n\ninterface CypressConfig {\n env: Record<string, unknown>;\n}\n\n// Matches the \"after:run\" overload of Cypress's on(), so Cypress's own on() can be passed in.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype On = (event: \"after:run\", handler: (results: any) => void | Promise<void>) => void;\n\n/**\n * Call from setupNodeEvents in cypress.config.ts. Starts the testkit when asked and tells the\n * kinde-testkit Cypress commands where it is, through Cypress.env(\"KINDE_TESTKIT_URL\").\n */\nexport async function setupKindeTestkit<C extends CypressConfig>(\n on: On,\n config: C,\n options: SetupKindeTestkitOptions = {},\n): Promise<C> {\n let url = options.url ?? (config.env.KINDE_TESTKIT_URL as string | undefined) ?? process.env.KINDE_ISSUER_URL ?? \"http://localhost:4400\";\n let running: RunningKindeTestkit | null = null;\n if (options.start) {\n running = await startKindeTestkit({ port: 4400, ...options.start });\n url = running.url;\n on(\"after:run\", async () => {\n await running?.close();\n running = null;\n });\n }\n config.env.KINDE_TESTKIT_URL = url.replace(/\\/+$/, \"\");\n return config;\n}\n"],"mappings":";;;;;;AAyBA,eAAsB,kBACpB,IACA,QACA,UAAoC,CAAC,GACzB;AACZ,MAAI,MAAM,QAAQ,OAAQ,OAAO,IAAI,qBAA4C,QAAQ,IAAI,oBAAoB;AACjH,MAAI,UAAsC;AAC1C,MAAI,QAAQ,OAAO;AACjB,cAAU,MAAM,kBAAkB,EAAE,MAAM,MAAM,GAAG,QAAQ,MAAM,CAAC;AAClE,UAAM,QAAQ;AACd,OAAG,aAAa,YAAY;AAC1B,YAAM,SAAS,MAAM;AACrB,gBAAU;AAAA,IACZ,CAAC;AAAA,EACH;AACA,SAAO,IAAI,oBAAoB,IAAI,QAAQ,QAAQ,EAAE;AACrD,SAAO;AACT;","names":[]}
@@ -1,4 +1,4 @@
1
- import { y as KindePrincipal, z as KindeTestkit, F as FailureInjector, X as WebhookDispatcher, s as Directory, j as CoverageRecorder, f as ActivityLog, d as Scenario, L as ScenarioTokenOverrides, T as TestkitSeed } from './server-CTBJXMac.cjs';
1
+ import { y as KindePrincipal, z as KindeTestkit, F as FailureInjector, X as WebhookDispatcher, s as Directory, j as CoverageRecorder, f as ActivityLog, d as Scenario, L as ScenarioTokenOverrides, T as TestkitSeed } from './server-CLRn67qI.cjs';
2
2
 
3
3
  interface KindeTestAuth {
4
4
  token: string | null;
@@ -1,5 +1,6 @@
1
- import { n as KindePrincipal, o as KindeTestkit, F as FailureInjector, w as WebhookDispatcher, S as Scenario, r as ScenarioTokenOverrides, T as TestkitSeed } from './webhooks-DJyCsbdF.js';
2
- import { h as Directory, d as CoverageRecorder, A as ActivityLog } from './server-B9fBcnyQ.js';
1
+ import { l as KindePrincipal, m as KindeTestkit, S as Scenario, p as ScenarioTokenOverrides } from './testkit-BvCAFsSj.js';
2
+ import { F as FailureInjector, d as WebhookDispatcher, D as Directory, T as TestkitSeed } from './webhooks-CiK9_pVw.js';
3
+ import { d as CoverageRecorder, A as ActivityLog } from './server-CuHAHsaN.js';
3
4
 
4
5
  interface KindeTestAuth {
5
6
  token: string | null;