kinde-testkit 0.3.0 → 0.5.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.5.0
4
+
5
+ - Add the Management API at `/api/v1`: users, organizations, organization members, member roles and permissions, roles and permissions. It needs an M2M token for `<issuer>/api`, checks the scopes of seeded applications, and writes every change into the testkit's data. Changes send the matching webhooks. Unimplemented routes answer 404 `ROUTE_NOT_FOUND`.
6
+ - Add the Account API at `/account_api/v1`: permissions, roles, feature flags, properties, entitlements and the portal link, for the active organization of the user's token. Kinde's `@kinde/js-utils` helpers work against it.
7
+ - Add HTTPS mode (`https: true`, `start --https`, `kinde-testkit cert`) with a local certificate, so Kinde's official `@kinde/management-api-js` client runs unchanged. CLI commands given an `https://` URL trust the certificate on their own.
8
+ - The seed takes `roles` with permissions, `permissions`, `featureFlags` with organization values, `plans` with entitlements, and user `properties`. A role's permissions are added to the member's token. Feature flags go into access tokens.
9
+ - Suspended users cannot sign in, and `reset()` restores the seed after API changes.
10
+
11
+ ## 0.4.0
12
+
13
+ - Add signed webhooks in Kinde's format: a JWT body with `Content-Type: application/jwt` and a `webhook-id` header, decodable with `@kinde/webhooks`.
14
+ - 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`.
15
+ - 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.
16
+ - Test the hard cases with `duplicate`, and with `invalid` set to `bad-signature`, `unknown-key`, `unsigned` or `stale`.
17
+ - Signing in on the testkit page sends `user.authenticated`, and a first sign-in with an unseeded email sends `user.created`.
18
+ - Add `kinde-testkit webhook`, `kinde.webhooks` in Vitest, `kinde.sendWebhook()` in Playwright, and `/testkit/webhooks` endpoints.
19
+ - The Next.js example adds a webhook route with tests for valid, duplicated, forged and stale events.
20
+
3
21
  ## 0.3.0
4
22
 
5
23
  - 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`.
package/README.md CHANGED
@@ -9,7 +9,7 @@ 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, 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.
12
+ It also issues machine-to-machine tokens, answers the Management API and Account API calls your app makes, 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
13
 
14
14
  ## Why it exists
15
15
 
@@ -147,6 +147,7 @@ test("a consultant switches organization", async ({ page, kinde }) => {
147
147
  | `kinde.signOut()` | Opens your app's logout route |
148
148
  | `kinde.injectFailure(rule)` | Makes a testkit endpoint fail, slow down or hang. Removed when the test ends |
149
149
  | `kinde.clearFailures()` | Removes the failures this test added |
150
+ | `kinde.sendWebhook(event)` | Sends a signed webhook and returns the delivery results |
150
151
 
151
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.
152
153
 
@@ -186,6 +187,100 @@ curl -s -X POST http://localhost:4400/oauth2/token \
186
187
 
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> }`.
188
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
+ ## Management API and Account API
242
+
243
+ Many apps call Kinde's APIs as well as signing users in. An admin page creates organizations and adds members, a signup flow creates users, and the front end asks the Account API for the current user's permissions and feature flags. kinde-testkit answers these calls from the seed, so the test checks what your code does with the result.
244
+
245
+ The Management API is at `/api/v1`. Like Kinde, it needs a machine-to-machine token for the audience `<issuer>/api`. When a seeded application has scopes, the token gets those scopes and each route checks for its own, such as `read:users` or `create:organizations`. These routes work:
246
+
247
+ | Area | Routes |
248
+ | --- | --- |
249
+ | Users | List, filter by ID or email, get, create, update (including `is_suspended`), delete |
250
+ | Organizations | List, get, create, update, delete |
251
+ | Members | List, add with roles, remove |
252
+ | Member roles and permissions | List, grant, remove |
253
+ | Roles and permissions | List, get, create, delete, and list a role's permissions |
254
+
255
+ Every change goes into the testkit's data. A user you create can sign in, a member you add gets the role's permissions in their next token, and a suspended user sees an error on the sign-in page. Each change also sends the matching webhook, such as `organization.created` or `user.deleted`, to your configured endpoints. `reset()` puts the seed back. A route the testkit does not implement answers 404 with the code `ROUTE_NOT_FOUND`, so a test never passes against an empty answer.
256
+
257
+ Kinde's official client, `@kinde/management-api-js`, forces `https://`. Start the testkit with HTTPS and run your code with the certificate it prints:
258
+
259
+ ```ts
260
+ const kinde = useKindeTestkit({ seed, https: true });
261
+ ```
262
+
263
+ ```bash
264
+ npx kinde-testkit start --https
265
+ NODE_EXTRA_CA_CERTS=.kinde-testkit/localhost-cert.pem npm test
266
+ ```
267
+
268
+ The first start writes a self-signed certificate for `localhost` and `127.0.0.1` to `.kinde-testkit/` and reuses it after that. The test suite runs the official client against the testkit without changes.
269
+
270
+ The Account API is at `/account_api/v1`. It reads the user's access token and answers for the token's active organization: `permissions`, `permission/<key>`, `roles`, `feature_flags`, `properties`, `entitlements`, `entitlement/<key>` and `portal_link`. Kinde's `@kinde/js-utils` helpers, such as `getPermissions({ forceApi: true })`, `getFlag()` and `getEntitlements()`, work against it. Add the data it returns to the seed:
271
+
272
+ ```json
273
+ {
274
+ "users": [{ "id": "kp_admin", "email": "admin@example.test", "properties": { "team": "platform" } }],
275
+ "roles": [{ "key": "admin", "name": "Admin", "permissions": ["projects:read", "projects:delete"] }],
276
+ "memberships": [{ "user": "kp_admin", "organization": "org_acme", "roles": ["admin"] }],
277
+ "featureFlags": [{ "key": "new_editor", "value": false, "organizations": { "org_acme": true } }],
278
+ "plans": [{ "key": "pro", "subscribers": ["org_acme"], "entitlements": [{ "featureKey": "seats", "limitMax": 10 }] }]
279
+ }
280
+ ```
281
+
282
+ A role's permissions are added to the member's own permissions, in tokens and in both APIs. Feature flags also go into access tokens as `feature_flags`, with the organization's value when it has one.
283
+
189
284
  ## Testing outages
190
285
 
191
286
  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:
@@ -310,6 +405,9 @@ When `kinde-testkit.json` exists in the current folder, `start` loads it. Pass `
310
405
  ],
311
406
  "applications": [
312
407
  { "clientId": "acme_agent", "organization": "org_acme", "scopes": ["read:users"] }
408
+ ],
409
+ "webhooks": [
410
+ { "url": "http://localhost:3000/api/webhooks/kinde" }
313
411
  ]
314
412
  }
315
413
  ```
@@ -320,7 +418,8 @@ A token for a seeded user takes its roles and permissions from the membership in
320
418
 
321
419
  | Command | What it does |
322
420
  | --- | --- |
323
- | `kinde-testkit start` | Start the issuer. Options: `--port`, `--host`, `--issuer`, `--audience`, `--client-id`, `--seed`, `--allow-public`, `--json` |
421
+ | `kinde-testkit start` | Start the issuer. Options: `--port`, `--host`, `--issuer`, `--audience`, `--client-id`, `--seed`, `--webhook`, `--https`, `--cert-dir`, `--allow-public`, `--json` |
422
+ | `kinde-testkit cert` | Write the local HTTPS certificate and print the `NODE_EXTRA_CA_CERTS` line. Options: `--dir` |
324
423
  | `kinde-testkit token` | Print a signed access token. Options: `--user`, `--org`, `--sub`, `--permissions`, `--roles`, `--expires-in`, `--invalid`, `--url`, `--json` |
325
424
  | `kinde-testkit users` | List seeded users |
326
425
  | `kinde-testkit organizations` | List seeded organizations |
@@ -328,7 +427,8 @@ A token for a seeded user takes its roles and permissions from the membership in
328
427
  | `kinde-testkit inspect [token]` | Decode a token and check it. Reads stdin when no token is given. Options: `--url`, `--json` |
329
428
  | `kinde-testkit doctor` | Check your app's Kinde settings against the issuer. Options: `--url`, `--env-file`, `--json` |
330
429
  | `kinde-testkit fail <path>` | Add a failure rule. Options: `--status`, `--delay`, `--hang`, `--times`, `--method`, `--list`, `--clear` |
331
- | `kinde-testkit reset` | Clear sign-in sessions and failure rules |
430
+ | `kinde-testkit reset` | Clear sign-in sessions, failure rules, webhook deliveries and endpoints added at runtime |
431
+ | `kinde-testkit webhook <type>` | Send a signed webhook. Options: `--user`, `--org`, `--role`, `--permission`, `--data`, `--to`, `--duplicate`, `--invalid`, `--types`, `--deliveries` |
332
432
 
333
433
  Every command takes `--json` for CI scripts and coding agents.
334
434
 
@@ -368,13 +468,13 @@ import {
368
468
 
369
469
  - `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.
370
470
  - `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.
371
- - `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)` and `jwks()`.
372
- - `startKindeTestkit({ port, seed, audience })` runs the issuer in-process and returns `{ url, issuer, jwksUri, testkit, failures, reset(), close() }`.
471
+ - `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()`.
472
+ - `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.
373
473
  - `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`.
374
474
  - `createKindeToken(options)` signs with a shared default testkit whose issuer is `http://localhost:4400`, or `KINDE_TESTKIT_ISSUER` when set.
375
475
  - `principalFromClaims(claims)` turns verified claims into `{ type, subject, issuer, organization, roles, permissions }`. `type` is `"user"`, or `"machine"` for M2M tokens.
376
476
 
377
- From `kinde-testkit/vitest`: `useKindeTestkit()`, which also exposes `failures` and `reset()`, and `kindeTest()`.
477
+ From `kinde-testkit/vitest`: `useKindeTestkit()`, which also exposes `failures`, `webhooks` and `reset()`, and `kindeTest()`.
378
478
 
379
479
  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()`.
380
480
 
@@ -389,10 +489,15 @@ From `kinde-testkit/playwright`: `test` and `expect` with the `kinde` fixture, t
389
489
  | `GET /oauth2/v2/user_profile` | Profile for the Bearer token's user |
390
490
  | `POST /oauth2/revoke` | Revokes a refresh token |
391
491
  | `GET /logout?redirect=<url>` | Signs out and redirects |
492
+ | `/api/v1/...` | Management API: users, organizations, members, roles and permissions |
493
+ | `GET /account_api/v1/...` | Account API: permissions, roles, feature flags, properties and entitlements for the token's user |
392
494
  | `POST /testkit/token` | Mints a token directly, used by `kinde-testkit token` |
393
495
  | `GET /testkit/users`, `/testkit/organizations`, `/testkit/memberships`, `/testkit/health` | Seed data and a health check |
394
496
  | `GET`, `POST`, `DELETE /testkit/failures`, `DELETE /testkit/failures/<id>` | List, add and remove failure rules |
395
- | `POST /testkit/reset` | Clear sign-in state and failure rules |
497
+ | `POST /testkit/webhooks` | Send a webhook and return the deliveries |
498
+ | `GET /testkit/webhooks/deliveries`, `/testkit/webhooks/types` | Delivery log and the event types with built-in payloads |
499
+ | `GET`, `POST /testkit/webhooks/endpoints`, `DELETE /testkit/webhooks/endpoints/<id>` | List, add and remove webhook endpoints |
500
+ | `POST /testkit/reset` | Clear sign-in state, failure rules and webhook deliveries |
396
501
 
397
502
  ## Token shape
398
503
 
@@ -440,7 +545,7 @@ ID tokens carry `amr`, `aud` (the client ID), `auth_time`, `email`, `email_verif
440
545
  | Failure injection: error status, delay, hang, by path, method and count | Implemented, tested through the Next.js SDK |
441
546
  | `doctor`, `inspect` and `reset` commands | Implemented |
442
547
  | Management API and Account API | Not implemented |
443
- | Webhooks | Not implemented |
548
+ | 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 |
444
549
 
445
550
  ## Safety
446
551