kinde-testkit 0.2.2 → 0.4.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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - Add signed webhooks in Kinde's format: a JWT body with `Content-Type: application/jwt` and a `webhook-id` header, decodable with `@kinde/webhooks`.
6
+ - Build payloads for the 16 event types `@kinde/webhooks` defines from seeded users, organizations, roles and permissions. Send billing events, and any other type, with your own `data`.
7
+ - Deliver to endpoints from the seed's `webhooks`, `start --webhook`, `addEndpoint()` or a `to` URL, with event filters, Kinde's rule that only a 200 counts as delivered, fast retries with the same `webhook-id`, timeouts, and a delivery log.
8
+ - Test the hard cases with `duplicate`, and with `invalid` set to `bad-signature`, `unknown-key`, `unsigned` or `stale`.
9
+ - Signing in on the testkit page sends `user.authenticated`, and a first sign-in with an unseeded email sends `user.created`.
10
+ - Add `kinde-testkit webhook`, `kinde.webhooks` in Vitest, `kinde.sendWebhook()` in Playwright, and `/testkit/webhooks` endpoints.
11
+ - The Next.js example adds a webhook route with tests for valid, duplicated, forged and stale events.
12
+
13
+ ## 0.3.0
14
+
15
+ - Add the `client_credentials` grant with Kinde's machine-to-machine token shape (`gty`, `scope`, `scp`, `v`, no `sub`), seeded `applications` with secrets, scopes, permissions, audiences and organizations, `testkit.m2mToken()`, and `kinde-testkit token --m2m`.
16
+ - Add failure injection: make any endpoint answer with an error status, wait, or hang, matched by path, prefix, method and count. Use it from Vitest (`kinde.failures`), Playwright (`kinde.injectFailure()`), the CLI (`kinde-testkit fail`) or HTTP (`/testkit/failures`).
17
+ - Add `kinde-testkit doctor`, which checks an app's Kinde settings against the running issuer, `kinde-testkit inspect`, which decodes a token and explains what is wrong with it, and `kinde-testkit reset`.
18
+ - `principalFromClaims()` now returns `type`, which is `"machine"` for M2M tokens, with the client ID as `subject`.
19
+ - The Next.js example adds outage tests that run through the real SDK.
20
+
3
21
  ## 0.2.2
4
22
 
5
23
  - Show the README diagrams as images, so they display on npm as well as GitHub.
package/README.md CHANGED
@@ -9,6 +9,8 @@ There are two ways to use it:
9
9
  - **API and unit tests:** mint a token for any user, organization and permission set, including expired, tampered and unsigned tokens, and send it to your API.
10
10
  - **Browser tests:** point your app at the testkit, and Playwright signs in as any seeded user through your app's own login route.
11
11
 
12
+ It also issues machine-to-machine tokens, sends signed webhooks, makes Kinde's endpoints fail or slow down on demand, and has a `doctor` command that checks your app's Kinde settings before a test run.
13
+
12
14
  ## Why it exists
13
15
 
14
16
  Kinde's testing guides start with a test environment, a test user with a password, and a client ID and secret in `.env`. Every test then goes through a real sign-in. That works for a few smoke tests. It gets slow and hard to run in CI once you want to test what your app does with each kind of user, such as:
@@ -143,6 +145,9 @@ test("a consultant switches organization", async ({ page, kinde }) => {
143
145
  | `kinde.signInAs(email, { org })` | Opens your app's login route, signs in on the testkit page and waits until the app has the session |
144
146
  | `kinde.switchOrganization(code)` | Signs the same user in again with another active organization |
145
147
  | `kinde.signOut()` | Opens your app's logout route |
148
+ | `kinde.injectFailure(rule)` | Makes a testkit endpoint fail, slow down or hang. Removed when the test ends |
149
+ | `kinde.clearFailures()` | Removes the failures this test added |
150
+ | `kinde.sendWebhook(event)` | Sends a signed webhook and returns the delivery results |
146
151
 
147
152
  The fixture uses `/api/auth/login` and `/api/auth/logout`, the Next.js SDK's routes. Set `kindeLoginPath` and `kindeLogoutPath` in `use` when your app's routes are different. Each test gets its own browser context, so tests run in parallel without sharing sessions.
148
153
 
@@ -154,6 +159,151 @@ A user with more than one organization needs `{ org }`, otherwise the fixture st
154
159
 
155
160
  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`.
156
161
 
162
+ ## Machine-to-machine tokens
163
+
164
+ 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`.
165
+
166
+ Seed the apps your services use:
167
+
168
+ ```json
169
+ {
170
+ "organizations": [{ "code": "org_acme" }],
171
+ "applications": [
172
+ { "clientId": "billing_worker", "clientSecret": "billing_secret", "scopes": ["read:invoices", "write:invoices"] },
173
+ { "clientId": "acme_agent", "organization": "org_acme", "permissions": ["read:users"], "audience": "https://api.example.test" }
174
+ ]
175
+ }
176
+ ```
177
+
178
+ A seeded app with a `clientSecret` must send that secret. A seeded app with `scopes` is granted only the requested scopes it has, so `scope` holds what was granted and `scp` holds what was asked for, as in Kinde. A client ID that is not seeded gets a token with whatever it asks for.
179
+
180
+ Your service fetches a token the same way it does from Kinde:
181
+
182
+ ```bash
183
+ curl -s -X POST http://localhost:4400/oauth2/token \
184
+ -d grant_type=client_credentials -d client_id=acme_agent -d client_secret=x \
185
+ -d audience=https://api.example.test -d scope=read:users
186
+ ```
187
+
188
+ In tests, mint one directly with `testkit.m2mToken({ clientId, organizationCode, scopes, audience })`, or run `kinde-testkit token --m2m --client-id acme_agent --scope read:users`. M2M tokens take the same `invalid` kinds as user tokens. `principalFromClaims()` reads them as `{ type: "machine", subject: <client ID> }`.
189
+
190
+ ## Webhooks
191
+
192
+ Kinde sends webhooks as a signed JWT with `Content-Type: application/jwt` and a `webhook-id` header that stays the same across retries. Your endpoint checks the signature with `decodeWebhook()` from `@kinde/webhooks`, which fetches keys from your issuer. kinde-testkit sends webhooks the same way, signed with its own key, so the same handler code works in tests when `KINDE_ISSUER_URL` points at the testkit.
193
+
194
+ Add the endpoints that should receive events to the seed file, or pass `--webhook <url>` to `start`:
195
+
196
+ ```json
197
+ {
198
+ "webhooks": [
199
+ { "url": "http://localhost:3000/api/webhooks/kinde" },
200
+ { "url": "http://localhost:3000/api/webhooks/billing", "events": ["customer.payment_succeeded"] }
201
+ ]
202
+ }
203
+ ```
204
+
205
+ Then send events from a test or the command line:
206
+
207
+ ```ts
208
+ // Vitest
209
+ const [delivery] = await kinde.webhooks.send({ type: "user.created", user: "admin@example.test" });
210
+ expect(delivery.delivered).toBe(true);
211
+
212
+ // Playwright
213
+ await kinde.sendWebhook({ type: "organization.created", organization: "org_acme", duplicate: 3 });
214
+ ```
215
+
216
+ ```bash
217
+ kinde-testkit webhook user.created --user admin@example.test
218
+ kinde-testkit webhook customer.payment_succeeded --data '{"customer_id":"customer_123"}'
219
+ kinde-testkit webhook --deliveries
220
+ ```
221
+
222
+ kinde-testkit builds the payload for the 16 event types that `@kinde/webhooks` defines, such as `user.created`, `organization.updated`, `role.deleted` and `access_request.created`, from your seeded users, organizations, roles and permissions. Kinde does not publish payload shapes for its billing events, such as `customer.plan_assigned`, so for those you pass the `data` object yourself. `kinde-testkit webhook --types` lists both groups.
223
+
224
+ With an endpoint configured, signing in on the testkit page sends `user.authenticated`, and the first sign-in with an email that is not seeded also sends `user.created`, as Kinde does.
225
+
226
+ Delivery follows Kinde's rules. Only a `200` counts as delivered. Anything else, or no answer, is retried with the same `webhook-id`. Kinde retries over 36 hours; the testkit retries after 0, 100 and 500 milliseconds by default, so tests stay fast. Change that with `startKindeTestkit({ webhooks: { retryDelaysMs, timeoutMs } })`.
227
+
228
+ These options test the hard parts of a webhook handler:
229
+
230
+ | Option | What it tests |
231
+ | --- | --- |
232
+ | `duplicate: n` | n copies with the same `webhook-id` and `event_id`. Your handler should process the event once |
233
+ | `invalid: "bad-signature"` | A tampered signature. `decodeWebhook()` returns `null` |
234
+ | `invalid: "unknown-key"` | Signed by a key your issuer never published |
235
+ | `invalid: "unsigned"` | `alg: none` |
236
+ | `invalid: "stale"` | A valid signature on an hour-old `timestamp`, for replay checks |
237
+ | `to: url` | Send to one URL instead of the configured endpoints |
238
+
239
+ `kinde.webhooks.deliveries()`, `kinde-testkit webhook --deliveries` and `GET /testkit/webhooks/deliveries` show every attempt with its status code or error. [`examples/nextjs`](examples/nextjs) has a webhook route and Playwright tests for valid, duplicated, forged and stale events.
240
+
241
+ ## Testing outages
242
+
243
+ Your app should handle Kinde being slow or down. kinde-testkit can make any endpoint answer with an error, wait before answering, or never answer:
244
+
245
+ ```ts
246
+ // Vitest, in the same process
247
+ kinde.failures.add({ path: "/oauth2/token", status: 503, times: 1 });
248
+
249
+ // Playwright, removed again when the test ends
250
+ await kinde.injectFailure({ path: "/.well-known/jwks.json", delayMs: 3000 });
251
+ ```
252
+
253
+ ```bash
254
+ kinde-testkit fail /oauth2/token --status 429 --times 3
255
+ kinde-testkit fail --list
256
+ kinde-testkit fail --clear
257
+ ```
258
+
259
+ | Rule field | What it does |
260
+ | --- | --- |
261
+ | `path` | An exact path such as `/oauth2/token`, or a prefix such as `/oauth2/*` |
262
+ | `method` | Only match this HTTP method |
263
+ | `status` | Answer with this status. 429 and 503 also send `Retry-After` |
264
+ | `delayMs` | Wait this long first, up to 60 seconds |
265
+ | `hang` | Never answer, so the client hits its own timeout |
266
+ | `times` | Apply to the next n matching requests, then remove the rule |
267
+
268
+ 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.
269
+
270
+ `kinde-testkit reset` (or `POST /testkit/reset`, or `kinde.reset()` in Vitest) clears sign-in codes, refresh tokens, users who signed in with an unseeded email, and failure rules.
271
+
272
+ ## Check your setup
273
+
274
+ `kinde-testkit doctor` reads `.env`, `.env.local`, `.env.test` and `.env.test.local`, plus any `KINDE_` variables in your shell, and checks them against the running issuer:
275
+
276
+ ```
277
+ ✓ Issuer running http://localhost:4400 answers, issuer http://localhost:4400.
278
+ ✓ Discovery The discovery document names the same issuer.
279
+ ✓ JWKS 1 RS256 signing key at /.well-known/jwks.json.
280
+ ✓ Seed 3 seeded users.
281
+ ✗ KINDE_ISSUER_URL https://acme.kinde.com is a real Kinde domain. Tests would sign in against Kinde, not the testkit.
282
+ ✓ KINDE_CLIENT_ID Set. The testkit accepts any client ID.
283
+ ✗ KINDE_CLIENT_SECRET The Next.js SDK only accepts 40 to 60 letters and digits.
284
+ ✓ KINDE_SITE_URL http://localhost:3000.
285
+ ```
286
+
287
+ It exits with code 1 when a check fails, so it can run before your test suite in CI.
288
+
289
+ `kinde-testkit inspect <token>` decodes any Kinde or testkit token and says what is wrong with it. Pipe a token in, or paste one. With `--url`, it also checks the issuer and verifies the signature:
290
+
291
+ ```bash
292
+ kinde-testkit token --user admin@example.test --invalid expired | kinde-testkit inspect --url http://localhost:4400
293
+ ```
294
+
295
+ ```
296
+ Access token
297
+
298
+ Subject kp_admin
299
+ Organization org_acme
300
+ Permissions ["projects:read"]
301
+
302
+ ✓ Algorithm RS256, the algorithm Kinde signs with.
303
+ ✗ Expiry Expired 1h 0m ago.
304
+ ✓ Signature Verified against http://localhost:4400/.well-known/jwks.json.
305
+ ```
306
+
157
307
  ## With Kinde's SDKs
158
308
 
159
309
  Kinde's JavaScript SDKs check tokens with `@kinde/jwt-validator`, which fetches keys from `<issuer>/.well-known/jwks.json` and then compares `iss` with the issuer you configured. kinde-testkit serves the same path, and its test suite runs that validator against every token kind.
@@ -209,6 +359,12 @@ When `kinde-testkit.json` exists in the current folder, `start` loads it. Pass `
209
359
  { "user": "kp_admin", "organization": "org_acme", "roles": ["admin"], "permissions": ["projects:read", "projects:delete"] },
210
360
  { "user": "kp_consultant", "organization": "org_acme", "roles": ["viewer"], "permissions": ["projects:read"] },
211
361
  { "user": "kp_consultant", "organization": "org_globex", "roles": ["admin"], "permissions": ["projects:delete"] }
362
+ ],
363
+ "applications": [
364
+ { "clientId": "acme_agent", "organization": "org_acme", "scopes": ["read:users"] }
365
+ ],
366
+ "webhooks": [
367
+ { "url": "http://localhost:3000/api/webhooks/kinde" }
212
368
  ]
213
369
  }
214
370
  ```
@@ -219,10 +375,16 @@ A token for a seeded user takes its roles and permissions from the membership in
219
375
 
220
376
  | Command | What it does |
221
377
  | --- | --- |
222
- | `kinde-testkit start` | Start the issuer. Options: `--port`, `--host`, `--issuer`, `--audience`, `--client-id`, `--seed`, `--allow-public`, `--json` |
378
+ | `kinde-testkit start` | Start the issuer. Options: `--port`, `--host`, `--issuer`, `--audience`, `--client-id`, `--seed`, `--webhook`, `--allow-public`, `--json` |
223
379
  | `kinde-testkit token` | Print a signed access token. Options: `--user`, `--org`, `--sub`, `--permissions`, `--roles`, `--expires-in`, `--invalid`, `--url`, `--json` |
224
380
  | `kinde-testkit users` | List seeded users |
225
381
  | `kinde-testkit organizations` | List seeded organizations |
382
+ | `kinde-testkit token --m2m` | Print a machine-to-machine token. Options: `--client-id`, `--scope`, `--org`, `--permissions`, `--expires-in`, `--invalid` |
383
+ | `kinde-testkit inspect [token]` | Decode a token and check it. Reads stdin when no token is given. Options: `--url`, `--json` |
384
+ | `kinde-testkit doctor` | Check your app's Kinde settings against the issuer. Options: `--url`, `--env-file`, `--json` |
385
+ | `kinde-testkit fail <path>` | Add a failure rule. Options: `--status`, `--delay`, `--hang`, `--times`, `--method`, `--list`, `--clear` |
386
+ | `kinde-testkit reset` | Clear sign-in sessions, failure rules, webhook deliveries and endpoints added at runtime |
387
+ | `kinde-testkit webhook <type>` | Send a signed webhook. Options: `--user`, `--org`, `--role`, `--permission`, `--data`, `--to`, `--duplicate`, `--invalid`, `--types`, `--deliveries` |
226
388
 
227
389
  Every command takes `--json` for CI scripts and coding agents.
228
390
 
@@ -262,10 +424,13 @@ import {
262
424
 
263
425
  - `scenario()` builds a caller: `.user()`, `.organization()`, `.withoutOrganization()`, `.role()`, `.permissions()`, `.claims()`, then `.authenticated()` or `.unauthenticated()`. The result is plain JSON, so you can keep scenarios in a shared file and import them anywhere.
264
426
  - `createKindeUser()` gives a user a stable id derived from the email, so the same email always maps to the same `kp_` id. `createKindeOrganization()` and `createMembership()` cover organizations and per-organization roles.
265
- - `KindeTestkit.create({ issuer, audience, clientId, accessTokenExpiresIn, idTokenExpiresIn })` holds a signing key. Access tokens last 24 hours and ID tokens 1 hour by default, the same as Kinde's defaults. Use `token()`, `tokenFor(scenario)`, `idTokenFor(scenario)`, `headersFor(scenario)`, `principalFor(scenario)` and `jwks()`.
266
- - `startKindeTestkit({ port, seed, audience })` runs the issuer in-process and returns `{ url, issuer, jwksUri, testkit, close() }`.
427
+ - `KindeTestkit.create({ issuer, audience, clientId, accessTokenExpiresIn, idTokenExpiresIn })` holds a signing key. Access tokens last 24 hours and ID tokens 1 hour by default, the same as Kinde's defaults. Use `token()`, `tokenFor(scenario)`, `idTokenFor(scenario)`, `m2mToken()`, `headersFor(scenario)`, `principalFor(scenario)`, `signPayload()` and `jwks()`.
428
+ - `startKindeTestkit({ port, seed, audience })` runs the issuer in-process and returns `{ url, issuer, jwksUri, testkit, failures, webhooks, reset(), close() }`. Pass `webhooks: { retryDelaysMs, timeoutMs }` to change webhook retries.
429
+ - `inspectToken(token, { issuerUrl })` and `runDoctor({ url, env })` are the functions behind `inspect` and `doctor`. Both return a list of checks with `pass`, `warn` or `fail`.
267
430
  - `createKindeToken(options)` signs with a shared default testkit whose issuer is `http://localhost:4400`, or `KINDE_TESTKIT_ISSUER` when set.
268
- - `principalFromClaims(claims)` turns verified claims into `{ subject, issuer, organization, roles, permissions }`.
431
+ - `principalFromClaims(claims)` turns verified claims into `{ type, subject, issuer, organization, roles, permissions }`. `type` is `"user"`, or `"machine"` for M2M tokens.
432
+
433
+ From `kinde-testkit/vitest`: `useKindeTestkit()`, which also exposes `failures`, `webhooks` and `reset()`, and `kindeTest()`.
269
434
 
270
435
  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()`.
271
436
 
@@ -276,12 +441,17 @@ From `kinde-testkit/playwright`: `test` and `expect` with the `kinde` fixture, t
276
441
  | `GET /.well-known/openid-configuration` | OIDC discovery |
277
442
  | `GET /.well-known/jwks`, `/.well-known/jwks.json` | Public signing key |
278
443
  | `GET /oauth2/auth` | Sign-in page. Takes `client_id`, `redirect_uri`, `response_type=code`, `state`, `scope`, `nonce`, `audience`, `org_code`, `login_hint`, `prompt=none` and PKCE |
279
- | `POST /oauth2/token` | `authorization_code` and `refresh_token` grants. Client credentials in the body or with HTTP Basic. Refresh tokens rotate on every use |
444
+ | `POST /oauth2/token` | `authorization_code`, `refresh_token` and `client_credentials` grants. Client credentials in the body or with HTTP Basic. Refresh tokens rotate on every use |
280
445
  | `GET /oauth2/v2/user_profile` | Profile for the Bearer token's user |
281
446
  | `POST /oauth2/revoke` | Revokes a refresh token |
282
447
  | `GET /logout?redirect=<url>` | Signs out and redirects |
283
448
  | `POST /testkit/token` | Mints a token directly, used by `kinde-testkit token` |
284
449
  | `GET /testkit/users`, `/testkit/organizations`, `/testkit/memberships`, `/testkit/health` | Seed data and a health check |
450
+ | `GET`, `POST`, `DELETE /testkit/failures`, `DELETE /testkit/failures/<id>` | List, add and remove failure rules |
451
+ | `POST /testkit/webhooks` | Send a webhook and return the deliveries |
452
+ | `GET /testkit/webhooks/deliveries`, `/testkit/webhooks/types` | Delivery log and the event types with built-in payloads |
453
+ | `GET`, `POST /testkit/webhooks/endpoints`, `DELETE /testkit/webhooks/endpoints/<id>` | List, add and remove webhook endpoints |
454
+ | `POST /testkit/reset` | Clear sign-in state, failure rules and webhook deliveries |
285
455
 
286
456
  ## Token shape
287
457
 
@@ -325,9 +495,11 @@ ID tokens carry `amr`, `aud` (the client ID), `auth_time`, `email`, `email_verif
325
495
  | Vitest helper and Playwright fixture | Implemented |
326
496
  | Accepted by `@kinde/jwt-validator` and the Next.js SDK's `validateToken` | Tested |
327
497
  | Sign-in, organization switching and sign-out through `@kinde-oss/kinde-auth-nextjs` | Tested in Chrome with Playwright |
328
- | Client credentials (machine-to-machine) grant | Not implemented |
498
+ | Client credentials grant with Kinde's M2M token shape, seeded and org-scoped apps | Implemented |
499
+ | Failure injection: error status, delay, hang, by path, method and count | Implemented, tested through the Next.js SDK |
500
+ | `doctor`, `inspect` and `reset` commands | Implemented |
329
501
  | Management API and Account API | Not implemented |
330
- | Webhooks | Not implemented |
502
+ | 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 |
331
503
 
332
504
  ## Safety
333
505