kinde-testkit 0.7.1 → 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.
- package/CHANGELOG.md +11 -0
- package/README.md +97 -9
- package/dist/chunk-BPPG4G52.js +427 -0
- package/dist/chunk-BPPG4G52.js.map +1 -0
- package/dist/{chunk-IOP27RQ5.js → chunk-CY75AADD.js} +167 -450
- package/dist/chunk-CY75AADD.js.map +1 -0
- package/dist/chunk-EZUKOKNO.js +48 -0
- package/dist/chunk-EZUKOKNO.js.map +1 -0
- package/dist/{chunk-K5YNZAOM.js → chunk-YJPE5HAM.js} +5 -3
- package/dist/{chunk-K5YNZAOM.js.map → chunk-YJPE5HAM.js.map} +1 -1
- package/dist/cli.js +8 -2
- package/dist/cli.js.map +1 -1
- package/dist/cypress-support.d.ts +45 -1
- package/dist/cypress-support.js +21 -6
- package/dist/cypress-support.js.map +1 -1
- package/dist/cypress.cjs +134 -10
- package/dist/cypress.d.cts +1 -1
- package/dist/cypress.d.ts +3 -2
- package/dist/cypress.js +2 -1
- package/dist/cypress.js.map +1 -1
- package/dist/{handle-QF340J2E.d.cts → handle-DRPxm36j.d.cts} +1 -1
- package/dist/{handle-DxF0uwza.d.ts → handle-Pjt9fSUq.d.ts} +3 -2
- package/dist/index.cjs +137 -10
- package/dist/index.d.cts +17 -4
- package/dist/index.d.ts +8 -26
- package/dist/index.js +27 -51
- package/dist/index.js.map +1 -1
- package/dist/jest.cjs +134 -10
- package/dist/jest.d.cts +3 -3
- package/dist/jest.d.ts +5 -4
- package/dist/jest.js +3 -2
- package/dist/jest.js.map +1 -1
- package/dist/playwright.d.ts +12 -3
- package/dist/playwright.js +30 -0
- package/dist/playwright.js.map +1 -1
- package/dist/react.d.ts +43 -0
- package/dist/react.js +110 -0
- package/dist/react.js.map +1 -0
- package/dist/{server-CcXI3vJ-.d.cts → server-CLRn67qI.d.cts} +24 -0
- package/dist/{server-Dghq0aLx.d.ts → server-CuHAHsaN.d.ts} +3 -58
- package/dist/sign-in-flow-DNrDXSLI.d.ts +35 -0
- package/dist/testkit-BvCAFsSj.d.ts +156 -0
- package/dist/vitest.d.ts +5 -4
- package/dist/vitest.js +3 -2
- package/dist/vitest.js.map +1 -1
- package/dist/{webhooks-DJyCsbdF.d.ts → webhooks-CiK9_pVw.d.ts} +82 -155
- package/package.json +30 -3
- package/dist/chunk-IOP27RQ5.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.8.0
|
|
4
|
+
|
|
5
|
+
- Add `kinde-testkit/react` for React Testing Library. `kindeAuth(scenario)` gives components that call `useKindeAuth()` from the React SDK or `useKindeBrowserClient()` from the Next.js SDK real tokens for the scenario, and records `login()`, `logout()` and `switchOrg()` calls.
|
|
6
|
+
- Add `authenticateAs(identity)` to the Playwright fixture and `cy.kindeAuthenticateAs()` to Cypress. A test can sign in as a user described inline, with an organization, roles and permissions, without a seed entry. `POST /testkit/identities` does the same over HTTP.
|
|
7
|
+
- Add `kinde.saveState(path)` to reuse a signed-in browser across tests and workers.
|
|
8
|
+
- Add social sign-in and MFA to the sign-in page and the sign-in helpers: a social connection, a passed, failed or cancelled MFA step, and a cancelled or failed provider. Tokens record the method in `amr`.
|
|
9
|
+
- Add `malformed` failure rules: invalid JSON, an empty body, an HTML error page or JSON in an unexpected shape. The CLI takes `kinde-testkit fail <path> --malformed <kind>`.
|
|
10
|
+
- Coverage adds social sign-in, MFA sign-in, refused sign-ins and malformed answers.
|
|
11
|
+
- The Next.js example adds tests for inline identities, saved sign-in state, social sign-in and MFA.
|
|
12
|
+
- Fix: 0.6.1 and 0.7.0 were published without `dist/cypress-support.d.ts`, so TypeScript did not know the `cy.kinde*` commands. Parallel builds could delete it. The build now cleans once first, and fails if any file `package.json` exports is missing.
|
|
13
|
+
|
|
3
14
|
## 0.7.1
|
|
4
15
|
|
|
5
16
|
- Management API responses now have every field a real Kinde business returns: `full_name` and `last_organization_sign_ins` on users, `created_on` on organizations in lists, and `is_organization_role_assignable` on permissions. Found by the contract tests.
|
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ It also issues machine-to-machine tokens, answers the Management API and Account
|
|
|
19
19
|
- [Quick start with Vitest](#quick-start-with-vitest)
|
|
20
20
|
- [Browser tests with Playwright](#browser-tests-with-playwright)
|
|
21
21
|
- [Browser tests with Cypress](#browser-tests-with-cypress)
|
|
22
|
+
- [Component tests with React Testing Library](#component-tests-with-react-testing-library)
|
|
22
23
|
- [Machine-to-machine tokens](#machine-to-machine-tokens)
|
|
23
24
|
- [Device sign-in, introspection and client registration](#device-sign-in-introspection-and-client-registration)
|
|
24
25
|
- [Webhooks](#webhooks)
|
|
@@ -189,7 +190,9 @@ test("a consultant switches organization", async ({ page, kinde }) => {
|
|
|
189
190
|
|
|
190
191
|
| Fixture method | What it does |
|
|
191
192
|
| --- | --- |
|
|
192
|
-
| `kinde.signInAs(email, { org })` | Opens your app's login route, signs in on the testkit page and waits until the app has the session |
|
|
193
|
+
| `kinde.signInAs(email, { org, connection, providerResult, mfa })` | Opens your app's login route, signs in on the testkit page and waits until the app has the session. The other options are under [Social sign-in and MFA](#social-sign-in-and-mfa) |
|
|
194
|
+
| `kinde.authenticateAs(identity)` | Signs in as a seeded user by email, or as an identity described inline, with no seed entry |
|
|
195
|
+
| `kinde.saveState(path)` | Saves the signed-in browser state for `test.use({ storageState })` |
|
|
193
196
|
| `kinde.switchOrganization(code)` | Signs the same user in again with another active organization |
|
|
194
197
|
| `kinde.signOut()` | Opens your app's logout route |
|
|
195
198
|
| `kinde.injectFailure(rule)` | Makes a testkit endpoint fail, slow down or hang. Removed when the test ends |
|
|
@@ -200,6 +203,36 @@ The fixture uses `/api/auth/login` and `/api/auth/logout`, the Next.js SDK's rou
|
|
|
200
203
|
|
|
201
204
|
A user with more than one organization needs `{ org }`, otherwise the fixture stops with an error that names the user. Signing in to an organization the user does not belong to also fails, the same way Kinde refuses it.
|
|
202
205
|
|
|
206
|
+
To test a user who is not in the seed file, describe the identity in the test. The testkit creates the user, the organization if it is new, and a membership with exactly these roles and permissions. Calling it again with other permissions changes them, so you can check what the app does when a user's access changes:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
test("an auditor can delete projects", async ({ page, kinde }) => {
|
|
210
|
+
await kinde.authenticateAs({
|
|
211
|
+
email: `auditor+w${test.info().parallelIndex}@example.test`,
|
|
212
|
+
organization: "org_acme",
|
|
213
|
+
roles: ["auditor"],
|
|
214
|
+
permissions: ["projects:read", "projects:delete"],
|
|
215
|
+
});
|
|
216
|
+
await page.goto("/projects");
|
|
217
|
+
await expect(page.getByRole("button", { name: "Delete Customer portal" })).toBeVisible();
|
|
218
|
+
});
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Putting `parallelIndex` in the email gives each Playwright worker its own identity, so parallel workers never change each other's users. `reset()` removes these identities.
|
|
222
|
+
|
|
223
|
+
To sign in once and reuse the session, save the browser state and start other tests with it. Tokens stay valid while the same testkit runs, because it keeps one signing key until it stops:
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
// auth.setup.ts, in a setup project the other projects depend on
|
|
227
|
+
setup("sign in as admin", async ({ kinde }) => {
|
|
228
|
+
await kinde.authenticateAs("admin@example.test");
|
|
229
|
+
await kinde.saveState("playwright/.auth/admin.json");
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
// in a test file
|
|
233
|
+
test.use({ storageState: "playwright/.auth/admin.json" });
|
|
234
|
+
```
|
|
235
|
+
|
|
203
236
|
[`examples/nextjs`](examples/nextjs) is a working Next.js app on `@kinde-oss/kinde-auth-nextjs` with these tests.
|
|
204
237
|
|
|
205
238
|
## Browser tests with Cypress
|
|
@@ -238,7 +271,8 @@ it("a viewer cannot delete projects", () => {
|
|
|
238
271
|
|
|
239
272
|
| Command | What it does |
|
|
240
273
|
| --- | --- |
|
|
241
|
-
| `cy.kindeSignIn(email, { org, loginPath })` | Signs in through your app's login route with requests, then opens the app's callback. Fast, and needs no `cy.origin()` |
|
|
274
|
+
| `cy.kindeSignIn(email, { org, loginPath, connection, providerResult, mfa })` | Signs in through your app's login route with requests, then opens the app's callback. Fast, and needs no `cy.origin()` |
|
|
275
|
+
| `cy.kindeAuthenticateAs(identity)` | Signs in as a seeded user by email, or as an identity described inline with its organization, roles and permissions |
|
|
242
276
|
| `cy.kindeSignOut({ logoutPath })` | Opens your app's logout route |
|
|
243
277
|
| `cy.kindeToken(options)` | Yields an access token, with the same options as `POST /testkit/token` |
|
|
244
278
|
| `cy.kindeInjectFailure(rule)` | Makes a testkit endpoint fail, slow down or hang. Removed when the test ends |
|
|
@@ -252,6 +286,51 @@ it("a viewer cannot delete projects", () => {
|
|
|
252
286
|
|
|
253
287
|
The page at `/oauth2/auth` lists the seeded users. You can also type any email address: a user that is not in the seed file signs in without an organization. A user with more than one organization picks one on the next screen, unless the app sent `org_code`.
|
|
254
288
|
|
|
289
|
+
### Social sign-in and MFA
|
|
290
|
+
|
|
291
|
+
Under **Test options**, the sign-in page can sign in with a social connection, such as Google or GitHub, and add a multi-factor step. Each one can also fail, so you can test what your app does when sign-in does not finish:
|
|
292
|
+
|
|
293
|
+
| Option | Values | What the app gets |
|
|
294
|
+
| --- | --- | --- |
|
|
295
|
+
| `connection` | `email` (default), `google`, `github`, `microsoft`, `apple` and other providers | A session whose tokens have `amr: ["google"]`, for example |
|
|
296
|
+
| `providerResult` | `success` (default), `cancelled`, `error` | `cancelled` sends the app `error=access_denied`, and `error` sends `error=server_error` |
|
|
297
|
+
| `mfa` | `none` (default), `passed`, `failed`, `cancelled` | `passed` adds `"mfa"` to `amr`. `failed` keeps the user on the sign-in page with a wrong-code error. `cancelled` sends the app `error=access_denied` |
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
await kinde.signInAs("admin@example.test", { connection: "google", mfa: "passed" });
|
|
301
|
+
await kinde.signInAs("admin@example.test", { connection: "github", providerResult: "cancelled" });
|
|
302
|
+
cy.kindeSignIn("admin@example.test", { mfa: "failed" });
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
For an outcome that fails, `signInAs()` returns once the app has the error, or once the sign-in page shows it, and the test checks what happens next. Kinde's Next.js SDK, for example, answers an OAuth error by starting sign-in again.
|
|
306
|
+
|
|
307
|
+
Kinde does not publish the `amr` values it uses for social and MFA sign-ins. The testkit uses the connection name and `"mfa"`, the value RFC 8176 defines. If your app checks other values, mint tokens with `authMethods` instead.
|
|
308
|
+
|
|
309
|
+
## Component tests with React Testing Library
|
|
310
|
+
|
|
311
|
+
`kinde-testkit/react` renders components that call `useKindeAuth()` from `@kinde-oss/kinde-auth-react` or `useKindeBrowserClient()` from `@kinde-oss/kinde-auth-nextjs`. It gives the SDK's own context real tokens signed for a scenario, read through the same `@kinde/js-utils` functions the SDKs use, so `getPermission()`, `getFlag()` and `getOrganization()` answer from the token as they do in the browser:
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
import { fireEvent, render, screen } from "@testing-library/react";
|
|
315
|
+
import { scenario } from "kinde-testkit";
|
|
316
|
+
import { kindeAuth } from "kinde-testkit/react";
|
|
317
|
+
|
|
318
|
+
it("hides the delete button from a viewer", async () => {
|
|
319
|
+
const auth = await kindeAuth(scenario().user({ email: "viewer@example.test" }).organization("org_acme").permissions(["projects:read"]).authenticated());
|
|
320
|
+
render(<Projects />, { wrapper: auth.wrapper });
|
|
321
|
+
expect(await screen.findByText("Read only")).toBeTruthy();
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
it("starts sign-in from the button", async () => {
|
|
325
|
+
const auth = await kindeAuth(scenario().unauthenticated());
|
|
326
|
+
render(<Projects />, { wrapper: auth.wrapper });
|
|
327
|
+
fireEvent.click(screen.getByText("Sign in"));
|
|
328
|
+
expect(auth.calls).toEqual([{ method: "login", args: [] }]);
|
|
329
|
+
});
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
`login()`, `logout()`, `register()` and `switchOrg()` do not leave the page. They are recorded in `auth.calls` so the test can check them. Pass `featureFlags` to put flags in the token. The component tests run in jsdom, so they need no testkit server. `kinde-testkit/react` is ESM only and needs `react`, `@kinde-oss/kinde-auth-react` and `@kinde/js-utils`, which the React and Next.js SDKs install.
|
|
333
|
+
|
|
255
334
|
## Machine-to-machine tokens
|
|
256
335
|
|
|
257
336
|
Backend services and AI agents authenticate with Kinde through the client credentials grant. kinde-testkit answers it at `/oauth2/token` with tokens in Kinde's M2M shape: `gty: ["client_credentials"]`, `azp` set to the client ID, `scope`, `scp` and `v: "2"`, and no `sub`. Org-scoped apps also get `org_code`.
|
|
@@ -403,7 +482,7 @@ A role's permissions are added to the member's own permissions, in tokens and in
|
|
|
403
482
|
|
|
404
483
|
## Testing outages
|
|
405
484
|
|
|
406
|
-
Your app should handle Kinde being slow or
|
|
485
|
+
Your app should handle Kinde being slow, down or broken. kinde-testkit can make any endpoint answer with an error, wait before answering, never answer, or answer with a body your client cannot use:
|
|
407
486
|
|
|
408
487
|
```ts
|
|
409
488
|
// Vitest, in the same process
|
|
@@ -415,6 +494,7 @@ await kinde.injectFailure({ path: "/.well-known/jwks.json", delayMs: 3000 });
|
|
|
415
494
|
|
|
416
495
|
```bash
|
|
417
496
|
kinde-testkit fail /oauth2/token --status 429 --times 3
|
|
497
|
+
kinde-testkit fail /.well-known/jwks.json --malformed invalid-json
|
|
418
498
|
kinde-testkit fail --list
|
|
419
499
|
kinde-testkit fail --clear
|
|
420
500
|
```
|
|
@@ -426,6 +506,7 @@ kinde-testkit fail --clear
|
|
|
426
506
|
| `status` | Answer with this status. 429 and 503 also send `Retry-After` |
|
|
427
507
|
| `delayMs` | Wait this long first, up to 60 seconds |
|
|
428
508
|
| `hang` | Never answer, so the client hits its own timeout |
|
|
509
|
+
| `malformed` | Answer with `invalid-json`, an `empty` body, an `html` error page or `unexpected-json`. The status is 200 unless you set one |
|
|
429
510
|
| `times` | Apply to the next n matching requests, then remove the rule |
|
|
430
511
|
|
|
431
512
|
Failure rules apply to the whole issuer, so every test using it sees them. In Playwright, put outage tests in their own project that runs after the others. [`examples/nextjs`](examples/nextjs) has an `outage` project that takes the token endpoint down during sign-in, then slows it down. `/testkit/` control endpoints never fail.
|
|
@@ -602,17 +683,17 @@ npx kinde-testkit coverage
|
|
|
602
683
|
```
|
|
603
684
|
Kinde authentication coverage
|
|
604
685
|
|
|
605
|
-
Identity 6/
|
|
686
|
+
Identity 6/8
|
|
606
687
|
Organizations 4/5
|
|
607
688
|
Permissions 5/5
|
|
608
689
|
Token validation 3/8
|
|
609
|
-
Sessions 4/
|
|
690
|
+
Sessions 4/7
|
|
610
691
|
Machine-to-machine 0/4
|
|
611
692
|
Kinde APIs 2/4
|
|
612
693
|
Webhooks 5/5
|
|
613
|
-
Outages 2/
|
|
694
|
+
Outages 2/5
|
|
614
695
|
|
|
615
|
-
Overall: 31/
|
|
696
|
+
Overall: 31/51
|
|
616
697
|
|
|
617
698
|
Not covered:
|
|
618
699
|
Organizations: Organization claim missing. Mint a token with invalid: "missing-organization".
|
|
@@ -720,6 +801,8 @@ import {
|
|
|
720
801
|
|
|
721
802
|
From `kinde-testkit/vitest` and `kinde-testkit/jest`: `useKindeTestkit()`, which also exposes `failures`, `webhooks`, `directory`, `coverage`, `activity`, `loadSeed()` and `reset()`, and `kindeTest()`.
|
|
722
803
|
|
|
804
|
+
From `kinde-testkit/react`: `kindeAuth(scenario, { featureFlags, testkit, token })` and `KindeTestProvider`.
|
|
805
|
+
|
|
723
806
|
From `kinde-testkit/cypress`: `setupKindeTestkit(on, config, { start, url })`. From `kinde-testkit/cypress/support`: the `cy.kinde*` commands and their types.
|
|
724
807
|
|
|
725
808
|
From `kinde-testkit/playwright`: `test` and `expect` with the `kinde` fixture, the `KindeTestOptions` type for your config, and `createKindeFixture(page, options)` for building the fixture into your own `test.extend()`.
|
|
@@ -738,6 +821,7 @@ From `kinde-testkit/playwright`: `test` and `expect` with the `kinde` fixture, t
|
|
|
738
821
|
| `POST /oauth2/introspect` | Token introspection. Needs a Bearer token |
|
|
739
822
|
| `POST /oauth2/register` | Dynamic client registration for MCP connectors |
|
|
740
823
|
| `POST /testkit/device` | Approves or denies a pending device code without a browser |
|
|
824
|
+
| `POST /testkit/identities` | Creates or updates a user, organization and membership with the given roles and permissions, as `authenticateAs()` does |
|
|
741
825
|
| `GET /logout?redirect=<url>` | Signs out and redirects |
|
|
742
826
|
| `/api/v1/...` | Management API: users, organizations, members, roles and permissions |
|
|
743
827
|
| `GET /account_api/v1/...` | Account API: permissions, roles, feature flags, properties and entitlements for the token's user |
|
|
@@ -795,7 +879,9 @@ ID tokens carry `amr`, `aud` (the client ID), `auth_time`, `email`, `email_verif
|
|
|
795
879
|
| Refresh tokens with rotation, revocation, logout and user profile | Implemented |
|
|
796
880
|
| Device authorization flow, token introspection and dynamic client registration | Implemented. Error responses checked against a real Kinde business. The device response has no `qr_code` |
|
|
797
881
|
| Audience allow-list for seeded M2M apps | Implemented, with Kinde's error message |
|
|
798
|
-
| Vitest and Jest helpers, Playwright fixture, Cypress commands | Implemented. Jest runs in the test suite. Cypress
|
|
882
|
+
| Vitest and Jest helpers, Playwright fixture, Cypress commands | Implemented. Jest runs in the test suite. Cypress runs against the Next.js example |
|
|
883
|
+
| React Testing Library helper for `useKindeAuth()` and `useKindeBrowserClient()` | Implemented, tested with both SDKs |
|
|
884
|
+
| Inline identities with `authenticateAs()` and saved sign-in state | Implemented, tested in Chrome with Playwright |
|
|
799
885
|
| Accepted by `@kinde/jwt-validator` and the Next.js SDK's `validateToken` | Tested |
|
|
800
886
|
| Sign-in, organization switching and sign-out through `@kinde-oss/kinde-auth-nextjs` | Tested in Chrome with Playwright |
|
|
801
887
|
| Client credentials grant with Kinde's M2M token shape, seeded and org-scoped apps | Implemented |
|
|
@@ -807,7 +893,9 @@ ID tokens carry `amr`, `aud` (the client ID), `auth_time`, `email`, `email_verif
|
|
|
807
893
|
| Dashboard, request and token log | Implemented |
|
|
808
894
|
| Authentication coverage report | Implemented |
|
|
809
895
|
| Docker image | Dockerfile in the repository |
|
|
810
|
-
|
|
|
896
|
+
| Social sign-in and MFA | Simulated: the method, a passed or failed MFA step, and cancelled or failed providers. Kinde's `amr` values for them are not published |
|
|
897
|
+
| Passwords and SAML | Not emulated. The sign-in page signs in any seeded user or email directly |
|
|
898
|
+
| Malformed responses | Implemented: invalid JSON, empty bodies, HTML error pages and unexpected JSON |
|
|
811
899
|
| Kinde's hosted pages, such as the self-serve portal | Not emulated. `portal_link` returns a placeholder page |
|
|
812
900
|
| Signed webhooks for the 16 event types in `@kinde/webhooks`, billing events with your data, retries, duplicates, forged and stale events | Implemented, tested with `@kinde/webhooks` and a Next.js route |
|
|
813
901
|
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
// src/ids.ts
|
|
2
|
+
import { createHash } from "crypto";
|
|
3
|
+
var counters = /* @__PURE__ */ new Map();
|
|
4
|
+
function stableId(prefix, seed) {
|
|
5
|
+
return `${prefix}_${createHash("sha256").update(seed).digest("hex").slice(0, 16)}`;
|
|
6
|
+
}
|
|
7
|
+
function nextSequence(prefix) {
|
|
8
|
+
const next = (counters.get(prefix) ?? 0) + 1;
|
|
9
|
+
counters.set(prefix, next);
|
|
10
|
+
return next;
|
|
11
|
+
}
|
|
12
|
+
function resetSequences() {
|
|
13
|
+
counters.clear();
|
|
14
|
+
}
|
|
15
|
+
function slug(value) {
|
|
16
|
+
return value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
17
|
+
}
|
|
18
|
+
function titleCase(value) {
|
|
19
|
+
return value.replace(/^org_/, "").split(/[_\-\s]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/factories.ts
|
|
23
|
+
function createKindeUser(options = {}) {
|
|
24
|
+
const email = options.email === void 0 ? `user-${nextSequence("user")}@example.test` : options.email;
|
|
25
|
+
const id = options.id ?? (email ? stableId("kp", email) : `kp_test_${nextSequence("kp")}`);
|
|
26
|
+
return {
|
|
27
|
+
id,
|
|
28
|
+
email,
|
|
29
|
+
emailVerified: options.emailVerified ?? email !== null,
|
|
30
|
+
givenName: options.givenName === void 0 ? null : options.givenName,
|
|
31
|
+
familyName: options.familyName === void 0 ? null : options.familyName,
|
|
32
|
+
picture: options.picture === void 0 ? null : options.picture,
|
|
33
|
+
claims: { ...options.claims ?? {} }
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function createKindeOrganization(options = {}) {
|
|
37
|
+
const code = options.code ?? (options.name ? `org_${slug(options.name)}` : `org_test_${nextSequence("org")}`);
|
|
38
|
+
return {
|
|
39
|
+
code,
|
|
40
|
+
name: options.name ?? titleCase(code),
|
|
41
|
+
metadata: { ...options.metadata ?? {} }
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function createMembership(options) {
|
|
45
|
+
return {
|
|
46
|
+
userId: options.userId,
|
|
47
|
+
organizationCode: options.organizationCode,
|
|
48
|
+
roles: unique(options.roles ?? []),
|
|
49
|
+
permissions: unique(options.permissions ?? [])
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function toKindeRole(role) {
|
|
53
|
+
if (typeof role !== "string") return role;
|
|
54
|
+
return { id: stableId("role", role), key: role, name: titleCase(role) };
|
|
55
|
+
}
|
|
56
|
+
function resetFactories() {
|
|
57
|
+
resetSequences();
|
|
58
|
+
}
|
|
59
|
+
function unique(values) {
|
|
60
|
+
return [...new Set(values)];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/errors.ts
|
|
64
|
+
var TestkitError = class extends Error {
|
|
65
|
+
code;
|
|
66
|
+
details;
|
|
67
|
+
/** The message without the details list. */
|
|
68
|
+
summary;
|
|
69
|
+
constructor(code, message, details = []) {
|
|
70
|
+
super(details.length > 0 ? `${message}
|
|
71
|
+
|
|
72
|
+
${details.map((d) => ` - ${d}`).join("\n")}` : message);
|
|
73
|
+
this.name = "TestkitError";
|
|
74
|
+
this.code = code;
|
|
75
|
+
this.details = details;
|
|
76
|
+
this.summary = message;
|
|
77
|
+
}
|
|
78
|
+
toString() {
|
|
79
|
+
return `${this.code}
|
|
80
|
+
|
|
81
|
+
${this.message}`;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// src/testkit.ts
|
|
86
|
+
import { randomUUID } from "crypto";
|
|
87
|
+
import {
|
|
88
|
+
SignJWT,
|
|
89
|
+
base64url,
|
|
90
|
+
calculateJwkThumbprint,
|
|
91
|
+
exportJWK,
|
|
92
|
+
generateKeyPair,
|
|
93
|
+
jwtVerify
|
|
94
|
+
} from "jose";
|
|
95
|
+
|
|
96
|
+
// src/duration.ts
|
|
97
|
+
var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
|
|
98
|
+
function toSeconds(value) {
|
|
99
|
+
if (typeof value === "number") {
|
|
100
|
+
if (!Number.isFinite(value) || value < 0) throw invalid(String(value));
|
|
101
|
+
return Math.floor(value);
|
|
102
|
+
}
|
|
103
|
+
const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
|
|
104
|
+
if (!match) {
|
|
105
|
+
if (/^\d+$/.test(value.trim())) return Number(value.trim());
|
|
106
|
+
throw invalid(value);
|
|
107
|
+
}
|
|
108
|
+
return Number(match[1]) * UNITS[match[2]];
|
|
109
|
+
}
|
|
110
|
+
function invalid(value) {
|
|
111
|
+
return new TestkitError(
|
|
112
|
+
"INVALID_DURATION",
|
|
113
|
+
`"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// src/testkit.ts
|
|
118
|
+
var DEFAULT_ISSUER = "http://localhost:4400";
|
|
119
|
+
var DEFAULT_CLIENT_ID = "kinde_testkit_client";
|
|
120
|
+
var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
|
|
121
|
+
var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
|
|
122
|
+
var DEFAULT_AUTH_METHODS = ["email"];
|
|
123
|
+
var INVALID_TOKEN_KINDS = [
|
|
124
|
+
"expired",
|
|
125
|
+
"wrong-issuer",
|
|
126
|
+
"wrong-audience",
|
|
127
|
+
"missing-subject",
|
|
128
|
+
"missing-organization",
|
|
129
|
+
"missing-permissions",
|
|
130
|
+
"future-iat",
|
|
131
|
+
"bad-signature",
|
|
132
|
+
"unknown-key",
|
|
133
|
+
"unsigned"
|
|
134
|
+
];
|
|
135
|
+
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
136
|
+
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
137
|
+
var KindeTestkit = class _KindeTestkit {
|
|
138
|
+
observers = [];
|
|
139
|
+
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
140
|
+
observe(observer) {
|
|
141
|
+
this.observers.push(observer);
|
|
142
|
+
return () => {
|
|
143
|
+
this.observers = this.observers.filter((o) => o !== observer);
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
async signAccess(payload, invalid2, now) {
|
|
147
|
+
const final = applyInvalidClaims(payload, invalid2, now);
|
|
148
|
+
const token = await this.sign(final, invalid2);
|
|
149
|
+
for (const observer of this.observers) observer.accessToken?.(final, invalid2, token);
|
|
150
|
+
return token;
|
|
151
|
+
}
|
|
152
|
+
issuer;
|
|
153
|
+
audience;
|
|
154
|
+
clientId;
|
|
155
|
+
accessTokenExpiresIn;
|
|
156
|
+
idTokenExpiresIn;
|
|
157
|
+
clock;
|
|
158
|
+
signingKey;
|
|
159
|
+
strangerKey = null;
|
|
160
|
+
static async create(options = {}) {
|
|
161
|
+
return new _KindeTestkit(options, await createSigningKey("kinde-testkit"));
|
|
162
|
+
}
|
|
163
|
+
constructor(options, signingKey) {
|
|
164
|
+
this.issuer = trimSlash(options.issuer ?? DEFAULT_ISSUER);
|
|
165
|
+
this.audience = toArray(options.audience);
|
|
166
|
+
this.clientId = options.clientId ?? DEFAULT_CLIENT_ID;
|
|
167
|
+
this.accessTokenExpiresIn = options.accessTokenExpiresIn ?? "24h";
|
|
168
|
+
this.idTokenExpiresIn = options.idTokenExpiresIn ?? "1h";
|
|
169
|
+
this.clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
170
|
+
this.signingKey = signingKey;
|
|
171
|
+
warnIfRealKindeDomain(this.issuer);
|
|
172
|
+
}
|
|
173
|
+
get jwksUri() {
|
|
174
|
+
return `${this.issuer}/.well-known/jwks`;
|
|
175
|
+
}
|
|
176
|
+
get keyId() {
|
|
177
|
+
return this.signingKey.kid;
|
|
178
|
+
}
|
|
179
|
+
get accessTokenLifetime() {
|
|
180
|
+
return toSeconds(this.accessTokenExpiresIn);
|
|
181
|
+
}
|
|
182
|
+
async verify(token) {
|
|
183
|
+
const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
|
|
184
|
+
issuer: this.issuer,
|
|
185
|
+
algorithms: ["RS256"]
|
|
186
|
+
});
|
|
187
|
+
return payload;
|
|
188
|
+
}
|
|
189
|
+
jwks() {
|
|
190
|
+
return { keys: [{ ...this.signingKey.publicJwk }] };
|
|
191
|
+
}
|
|
192
|
+
async token(options = {}) {
|
|
193
|
+
const now = this.clock();
|
|
194
|
+
const payload = {
|
|
195
|
+
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
196
|
+
aud: [...options.audience ?? this.audience],
|
|
197
|
+
auth_time: options.authTime ?? now,
|
|
198
|
+
azp: options.clientId ?? this.clientId,
|
|
199
|
+
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
200
|
+
iat: now,
|
|
201
|
+
iss: this.issuer,
|
|
202
|
+
jti: randomUUID(),
|
|
203
|
+
scp: [...options.scopes ?? DEFAULT_SCOPES],
|
|
204
|
+
sub: options.subject ?? stableId("kp", "default-test-user")
|
|
205
|
+
};
|
|
206
|
+
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
207
|
+
if (options.roles !== void 0) payload.roles = options.roles.map(toKindeRole);
|
|
208
|
+
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
209
|
+
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
210
|
+
Object.assign(payload, options.claims ?? {});
|
|
211
|
+
return this.signAccess(payload, options.invalid, now);
|
|
212
|
+
}
|
|
213
|
+
async m2mToken(options = {}) {
|
|
214
|
+
const now = this.clock();
|
|
215
|
+
const requested = [...options.scopes ?? []];
|
|
216
|
+
const granted = [...options.grantedScopes ?? requested];
|
|
217
|
+
const payload = {
|
|
218
|
+
aud: [...options.audience ?? this.audience],
|
|
219
|
+
azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
|
|
220
|
+
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
221
|
+
gty: ["client_credentials"],
|
|
222
|
+
iat: now,
|
|
223
|
+
iss: this.issuer,
|
|
224
|
+
jti: randomUUID(),
|
|
225
|
+
scope: granted.join(" "),
|
|
226
|
+
scp: requested,
|
|
227
|
+
v: "2"
|
|
228
|
+
};
|
|
229
|
+
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
230
|
+
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
231
|
+
Object.assign(payload, options.claims ?? {});
|
|
232
|
+
return this.signAccess(payload, options.invalid, now);
|
|
233
|
+
}
|
|
234
|
+
async tokenFor(scenario, overrides = {}) {
|
|
235
|
+
if (scenario.kind === "unauthenticated") {
|
|
236
|
+
for (const observer of this.observers) observer.anonymous?.();
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
return this.token({
|
|
240
|
+
subject: scenario.user.id,
|
|
241
|
+
organizationCode: scenario.organization?.code ?? null,
|
|
242
|
+
roles: scenario.roles.length > 0 ? scenario.roles : void 0,
|
|
243
|
+
permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
|
|
244
|
+
...overrides,
|
|
245
|
+
claims: { ...scenario.claims, ...overrides.claims ?? {} }
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
async idTokenFor(scenario, options = {}) {
|
|
249
|
+
if (scenario.kind === "unauthenticated") return null;
|
|
250
|
+
const { user, organization } = scenario;
|
|
251
|
+
const now = this.clock();
|
|
252
|
+
const authTime = options.authTime ?? now;
|
|
253
|
+
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
254
|
+
const clientId = options.clientId ?? this.clientId;
|
|
255
|
+
const payload = {
|
|
256
|
+
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
257
|
+
aud: [clientId],
|
|
258
|
+
auth_time: authTime,
|
|
259
|
+
azp: clientId,
|
|
260
|
+
email: user.email,
|
|
261
|
+
email_verified: user.emailVerified,
|
|
262
|
+
exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
|
|
263
|
+
family_name: user.familyName,
|
|
264
|
+
given_name: user.givenName,
|
|
265
|
+
iat: now,
|
|
266
|
+
iss: this.issuer,
|
|
267
|
+
jti: randomUUID(),
|
|
268
|
+
name: name || null,
|
|
269
|
+
nonce: options.nonce,
|
|
270
|
+
org_codes: organization ? [organization.code] : void 0,
|
|
271
|
+
picture: user.picture,
|
|
272
|
+
rat: authTime,
|
|
273
|
+
sub: user.id,
|
|
274
|
+
updated_at: now,
|
|
275
|
+
...user.claims
|
|
276
|
+
};
|
|
277
|
+
for (const key of Object.keys(payload)) {
|
|
278
|
+
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
279
|
+
}
|
|
280
|
+
const token = await this.sign(payload);
|
|
281
|
+
for (const observer of this.observers) observer.idToken?.(payload, token);
|
|
282
|
+
return token;
|
|
283
|
+
}
|
|
284
|
+
async headersFor(scenario, overrides = {}) {
|
|
285
|
+
const token = await this.tokenFor(scenario, overrides);
|
|
286
|
+
return token ? { authorization: `Bearer ${token}` } : {};
|
|
287
|
+
}
|
|
288
|
+
principalFor(scenario) {
|
|
289
|
+
if (scenario.kind === "unauthenticated") return null;
|
|
290
|
+
return scenarioPrincipal(scenario, this.issuer);
|
|
291
|
+
}
|
|
292
|
+
async signPayload(payload, invalid2) {
|
|
293
|
+
return this.sign(payload, invalid2);
|
|
294
|
+
}
|
|
295
|
+
async sign(payload, invalid2) {
|
|
296
|
+
if (invalid2 === "unsigned") {
|
|
297
|
+
const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
298
|
+
return `${header}.${base64url.encode(JSON.stringify(payload))}.`;
|
|
299
|
+
}
|
|
300
|
+
const key = invalid2 === "unknown-key" ? await this.stranger() : this.signingKey;
|
|
301
|
+
const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
|
|
302
|
+
return invalid2 === "bad-signature" ? tamperSignature(jwt) : jwt;
|
|
303
|
+
}
|
|
304
|
+
stranger() {
|
|
305
|
+
this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
|
|
306
|
+
return this.strangerKey;
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
function principalFromClaims(claims) {
|
|
310
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map(
|
|
311
|
+
(role) => typeof role === "string" ? role : String(role.key ?? "")
|
|
312
|
+
) : [];
|
|
313
|
+
const permissions = Array.isArray(claims.permissions) ? claims.permissions.map(String) : [];
|
|
314
|
+
const machine = Array.isArray(claims.gty) && claims.gty.includes("client_credentials");
|
|
315
|
+
return {
|
|
316
|
+
type: machine ? "machine" : "user",
|
|
317
|
+
subject: String((machine ? claims.azp : claims.sub) ?? ""),
|
|
318
|
+
issuer: String(claims.iss ?? ""),
|
|
319
|
+
organization: typeof claims.org_code === "string" ? { code: claims.org_code } : null,
|
|
320
|
+
roles: roles.filter(Boolean),
|
|
321
|
+
permissions,
|
|
322
|
+
claims: { ...claims }
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
function scenarioPrincipal(scenario, issuer) {
|
|
326
|
+
return {
|
|
327
|
+
type: "user",
|
|
328
|
+
subject: scenario.user.id,
|
|
329
|
+
issuer,
|
|
330
|
+
organization: scenario.organization ? { code: scenario.organization.code } : null,
|
|
331
|
+
roles: [...scenario.roles],
|
|
332
|
+
permissions: [...scenario.permissions],
|
|
333
|
+
claims: { ...scenario.claims }
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
function applyInvalidClaims(payload, invalid2, now) {
|
|
337
|
+
const next = { ...payload };
|
|
338
|
+
switch (invalid2) {
|
|
339
|
+
case "expired":
|
|
340
|
+
next.iat = now - 7200;
|
|
341
|
+
next.exp = now - 3600;
|
|
342
|
+
break;
|
|
343
|
+
case "future-iat":
|
|
344
|
+
next.iat = now + 3600;
|
|
345
|
+
next.exp = now + 7200;
|
|
346
|
+
break;
|
|
347
|
+
case "wrong-issuer":
|
|
348
|
+
next.iss = WRONG_ISSUER;
|
|
349
|
+
break;
|
|
350
|
+
case "wrong-audience":
|
|
351
|
+
next.aud = [WRONG_AUDIENCE];
|
|
352
|
+
break;
|
|
353
|
+
case "missing-subject":
|
|
354
|
+
delete next.sub;
|
|
355
|
+
break;
|
|
356
|
+
case "missing-organization":
|
|
357
|
+
delete next.org_code;
|
|
358
|
+
break;
|
|
359
|
+
case "missing-permissions":
|
|
360
|
+
next.permissions = [];
|
|
361
|
+
break;
|
|
362
|
+
default:
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
return next;
|
|
366
|
+
}
|
|
367
|
+
async function createSigningKey(prefix) {
|
|
368
|
+
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
|
369
|
+
const jwk = await exportJWK(publicKey);
|
|
370
|
+
const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
|
|
371
|
+
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
372
|
+
}
|
|
373
|
+
function tamperSignature(jwt) {
|
|
374
|
+
const [header, payload, signature] = jwt.split(".");
|
|
375
|
+
const bytes = base64url.decode(signature);
|
|
376
|
+
bytes[0] = (bytes[0] ?? 0) ^ 255;
|
|
377
|
+
return `${header}.${payload}.${base64url.encode(bytes)}`;
|
|
378
|
+
}
|
|
379
|
+
function toArray(value) {
|
|
380
|
+
if (value === void 0) return [];
|
|
381
|
+
return Array.isArray(value) ? [...value] : [value];
|
|
382
|
+
}
|
|
383
|
+
function trimSlash(value) {
|
|
384
|
+
return value.replace(/\/+$/, "");
|
|
385
|
+
}
|
|
386
|
+
function warnIfRealKindeDomain(issuer) {
|
|
387
|
+
if (/^https:\/\/[^/]+\.kinde\.com$/i.test(issuer)) {
|
|
388
|
+
process.emitWarning(
|
|
389
|
+
`kinde-testkit issuer is set to ${issuer}, which looks like a real Kinde domain. Test tokens are signed with a local key and will never verify against Kinde's JWKS.`,
|
|
390
|
+
{ code: "KINDE_TESTKIT_REAL_ISSUER" }
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
var defaultTestkit = null;
|
|
395
|
+
function getDefaultTestkit() {
|
|
396
|
+
defaultTestkit ??= KindeTestkit.create({
|
|
397
|
+
issuer: process.env.KINDE_TESTKIT_ISSUER ?? DEFAULT_ISSUER,
|
|
398
|
+
audience: process.env.KINDE_TESTKIT_AUDIENCE?.split(",").filter(Boolean)
|
|
399
|
+
});
|
|
400
|
+
return defaultTestkit;
|
|
401
|
+
}
|
|
402
|
+
async function createKindeToken(options = {}) {
|
|
403
|
+
return (await getDefaultTestkit()).token(options);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export {
|
|
407
|
+
stableId,
|
|
408
|
+
slug,
|
|
409
|
+
titleCase,
|
|
410
|
+
createKindeUser,
|
|
411
|
+
createKindeOrganization,
|
|
412
|
+
createMembership,
|
|
413
|
+
toKindeRole,
|
|
414
|
+
resetFactories,
|
|
415
|
+
TestkitError,
|
|
416
|
+
DEFAULT_ISSUER,
|
|
417
|
+
DEFAULT_CLIENT_ID,
|
|
418
|
+
DEFAULT_M2M_CLIENT_ID,
|
|
419
|
+
DEFAULT_SCOPES,
|
|
420
|
+
DEFAULT_AUTH_METHODS,
|
|
421
|
+
INVALID_TOKEN_KINDS,
|
|
422
|
+
KindeTestkit,
|
|
423
|
+
principalFromClaims,
|
|
424
|
+
getDefaultTestkit,
|
|
425
|
+
createKindeToken
|
|
426
|
+
};
|
|
427
|
+
//# sourceMappingURL=chunk-BPPG4G52.js.map
|