@smartcrab/management-client 0.1.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.
@@ -0,0 +1,1114 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import type { ManagementClient } from "./client.js";
3
+ import { createManagementClient } from "./client.js";
4
+ import type { ManagementClientError } from "./errors.js";
5
+ import { isFailure, isSuccess } from "./result.js";
6
+ import type { Result } from "./result.js";
7
+
8
+ // ---------------------------------------------------------------------------
9
+ // Fixtures (valid per @smartcrab/contracts-management schemas)
10
+ // ---------------------------------------------------------------------------
11
+
12
+ const ID = (prefix: string) => `${prefix}_${"a".repeat(32)}`;
13
+ const TS = "2026-08-02T08:10:00Z";
14
+ const BASE_URL = "https://api.example-auth.com/v1";
15
+ const API_KEY = "sk_test_fixturekey0000000000";
16
+ const REQUEST_ID = ID("req");
17
+
18
+ const workspace = {
19
+ id: ID("wsp"),
20
+ name: "Acme Inc",
21
+ slug: "acme-inc",
22
+ status: "active",
23
+ stripe_customer_id: null,
24
+ created_at: TS,
25
+ updated_at: TS,
26
+ deleted_at: null,
27
+ };
28
+ const project = {
29
+ id: ID("prj"),
30
+ workspace_id: ID("wsp"),
31
+ name: "App",
32
+ slug: "app",
33
+ created_at: TS,
34
+ updated_at: TS,
35
+ deleted_at: null,
36
+ };
37
+ const environment = {
38
+ id: ID("env"),
39
+ project_id: ID("prj"),
40
+ type: "test",
41
+ name: "Test",
42
+ status: "active",
43
+ issuer: `https://id.example-auth.com/e/${ID("env")}`,
44
+ interaction_domain: `${ID("env")}.login.example-auth.com`,
45
+ rp_id: `${ID("env")}.login.example-auth.com`,
46
+ config_version: 0,
47
+ created_at: TS,
48
+ updated_at: TS,
49
+ };
50
+ const rpMigration = {
51
+ environment_id: ID("env"),
52
+ active_rp_id: "auth.example.com",
53
+ legacy_rp_id: `${ID("env")}.login.example-auth.com`,
54
+ legacy_disabled_at: null,
55
+ total_users: 4,
56
+ migrated_users: 3,
57
+ legacy_only_users: 1,
58
+ migrated_share: 0.75,
59
+ };
60
+ const clientResource = {
61
+ id: ID("cli"),
62
+ environment_id: ID("env"),
63
+ client_type: "web_spa",
64
+ name: "SPA",
65
+ public_key_prefix: null,
66
+ redirect_uris: [],
67
+ post_logout_redirect_uris: [],
68
+ allowed_origins: [],
69
+ allowed_scopes: [],
70
+ allowed_resources: [],
71
+ token_endpoint_auth_method: "none",
72
+ require_pkce: true,
73
+ status: "active",
74
+ mobile_app: null,
75
+ created_at: TS,
76
+ updated_at: TS,
77
+ };
78
+ const connection = {
79
+ id: ID("con"),
80
+ environment_id: ID("env"),
81
+ provider: "google",
82
+ mode: "managed",
83
+ provider_key: "google",
84
+ issuer: null,
85
+ provider_client_id: "provider-client-id",
86
+ scopes: [],
87
+ profile_mapping: {},
88
+ owner_confirmed: true,
89
+ status: "active",
90
+ created_at: TS,
91
+ updated_at: TS,
92
+ };
93
+ const domain = {
94
+ id: ID("dom"),
95
+ environment_id: ID("env"),
96
+ hostname: "auth.customer.example",
97
+ status: "pending",
98
+ rp_enabled: false,
99
+ validation_errors: [],
100
+ created_at: TS,
101
+ updated_at: TS,
102
+ activated_at: null,
103
+ };
104
+ const user = {
105
+ id: ID("usr"),
106
+ environment_id: ID("env"),
107
+ email: null,
108
+ email_verified: false,
109
+ name: null,
110
+ avatar_url: null,
111
+ locale: null,
112
+ timezone: null,
113
+ status: "active",
114
+ metadata: {},
115
+ created_at: TS,
116
+ updated_at: TS,
117
+ last_login_at: null,
118
+ };
119
+ const workspaceMember = {
120
+ platform_user_id: ID("usr"),
121
+ role: "owner",
122
+ created_at: TS,
123
+ updated_at: TS,
124
+ };
125
+ const webhookDelivery = {
126
+ id: ID("dlv"),
127
+ webhook_id: ID("whk"),
128
+ event_id: ID("evt"),
129
+ event_type: "user.created",
130
+ attempt: 1,
131
+ status: "delivered",
132
+ response_status_code: 200,
133
+ duration_ms: 25,
134
+ occurred_at: TS,
135
+ };
136
+ const identity = {
137
+ identity_id: ID("idn"),
138
+ user_id: ID("usr"),
139
+ provider: "google",
140
+ linked_at: TS,
141
+ last_used_at: null,
142
+ };
143
+ const passkey = {
144
+ passkey_id: ID("psk"),
145
+ user_id: ID("usr"),
146
+ name: null,
147
+ created_at: TS,
148
+ last_used_at: null,
149
+ device_type: null,
150
+ backed_up: false,
151
+ };
152
+ const session = {
153
+ session_id: ID("ses"),
154
+ user_id: ID("usr"),
155
+ client_id: ID("cli"),
156
+ device_name: null,
157
+ created_at: TS,
158
+ last_active_at: TS,
159
+ idle_expires_at: TS,
160
+ absolute_expires_at: TS,
161
+ revoked_at: null,
162
+ };
163
+ const importJob = {
164
+ id: ID("job"),
165
+ environment_id: ID("env"),
166
+ status: "pending",
167
+ format: "json",
168
+ source_url: "https://exports.customer.example/users.json",
169
+ total_records: null,
170
+ processed_records: 0,
171
+ succeeded_records: 0,
172
+ failed_records: 0,
173
+ error_report_url: null,
174
+ created_by: { actor_type: "api_key", actor_id: ID("mky") },
175
+ created_at: TS,
176
+ updated_at: TS,
177
+ completed_at: null,
178
+ };
179
+ const exportJob = {
180
+ id: ID("job"),
181
+ environment_id: ID("env"),
182
+ target_user_id: ID("usr"),
183
+ status: "pending",
184
+ contents: ["profile"],
185
+ download_url: null,
186
+ download_url_expires_at: null,
187
+ created_by: { actor_type: "api_key", actor_id: ID("mky") },
188
+ created_at: TS,
189
+ updated_at: TS,
190
+ completed_at: null,
191
+ };
192
+ const webhook = {
193
+ id: ID("whk"),
194
+ environment_id: ID("env"),
195
+ url: "https://customer.example/hooks/auth",
196
+ event_types: ["user.created"],
197
+ status: "active",
198
+ created_at: TS,
199
+ updated_at: TS,
200
+ };
201
+ const auditEvent = {
202
+ id: ID("evt"),
203
+ environment_id: ID("env"),
204
+ workspace_id: ID("wsp"),
205
+ actor_type: "api_key",
206
+ actor_id: null,
207
+ action: "user.block",
208
+ subject_type: "user",
209
+ subject_id: ID("usr"),
210
+ result: "success",
211
+ request_id: REQUEST_ID,
212
+ metadata: {},
213
+ created_at: TS,
214
+ };
215
+ const mauUsage = {
216
+ workspace_id: ID("wsp"),
217
+ billing_month: "2026-08",
218
+ total_count: 0,
219
+ free_tier_limit: 30000,
220
+ percent_used: 0,
221
+ threshold_reached: null,
222
+ billing_activated: false,
223
+ grace_period: {
224
+ status: "none",
225
+ started_at: null,
226
+ expires_at: null,
227
+ new_user_creation_blocked: false,
228
+ },
229
+ environments: [],
230
+ };
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Recording stub fetch
234
+ // ---------------------------------------------------------------------------
235
+
236
+ interface RecordedRequest {
237
+ readonly url: string;
238
+ readonly method: string;
239
+ readonly headers: Readonly<Record<string, string>>;
240
+ readonly body: string | undefined;
241
+ }
242
+
243
+ const jsonResponse = (
244
+ body: unknown,
245
+ status = 200,
246
+ extraHeaders: Readonly<Record<string, string>> = {},
247
+ ): Response =>
248
+ new Response(JSON.stringify(body), {
249
+ status,
250
+ headers: {
251
+ "content-type": "application/json",
252
+ "x-request-id": REQUEST_ID,
253
+ ...extraHeaders,
254
+ },
255
+ });
256
+
257
+ const createStubFetch = (handler: (request: RecordedRequest) => Response) => {
258
+ const requests: RecordedRequest[] = [];
259
+ const fetchFn: typeof fetch = (input, init) => {
260
+ const headers = new Headers(init?.headers);
261
+ const recorded: RecordedRequest = {
262
+ url: String(input),
263
+ method: init?.method ?? "GET",
264
+ headers: Object.fromEntries(headers.entries()),
265
+ body: typeof init?.body === "string" ? init.body : undefined,
266
+ };
267
+ requests.push(recorded);
268
+ return Promise.resolve(handler(recorded));
269
+ };
270
+ return { fetchFn, requests };
271
+ };
272
+
273
+ const createClient = (handler: (request: RecordedRequest) => Response) => {
274
+ const stub = createStubFetch(handler);
275
+ const client = createManagementClient({
276
+ baseUrl: BASE_URL,
277
+ apiKey: API_KEY,
278
+ fetch: stub.fetchFn,
279
+ });
280
+ return { client, requests: stub.requests };
281
+ };
282
+
283
+ /** Every response is a fixed 200 JSON payload; returns the single recorded request. */
284
+ const recordSingle = async (
285
+ body: unknown,
286
+ invoke: (client: ManagementClient) => Promise<Result<unknown, ManagementClientError>>,
287
+ headers: Readonly<Record<string, string>> = {},
288
+ ): Promise<RecordedRequest> => {
289
+ const { client, requests } = createClient(() => jsonResponse(body, 200, headers));
290
+ const result = await invoke(client);
291
+ expect(isSuccess(result)).toBe(true);
292
+ expect(requests).toHaveLength(1);
293
+ const [request] = requests;
294
+ if (request === undefined) throw new Error("expected a recorded request");
295
+ return request;
296
+ };
297
+
298
+ // ---------------------------------------------------------------------------
299
+ // Route table: every §26.2 method's HTTP method + path
300
+ // ---------------------------------------------------------------------------
301
+
302
+ interface RouteCase {
303
+ readonly name: string;
304
+ readonly invoke: (client: ManagementClient) => Promise<Result<unknown, ManagementClientError>>;
305
+ readonly method: "GET" | "POST" | "PATCH" | "DELETE";
306
+ readonly path: string;
307
+ readonly responseBody: unknown;
308
+ readonly write: boolean;
309
+ }
310
+
311
+ const page = (item: unknown) => ({ items: [item], next_cursor: null });
312
+
313
+ const ROUTES: readonly RouteCase[] = [
314
+ // Workspaces
315
+ {
316
+ name: "listWorkspaces",
317
+ invoke: (c) => c.listWorkspaces(),
318
+ method: "GET",
319
+ path: "/workspaces",
320
+ responseBody: page(workspace),
321
+ write: false,
322
+ },
323
+ {
324
+ name: "listWorkspaceMembers",
325
+ invoke: (c) => c.listWorkspaceMembers(ID("wsp")),
326
+ method: "GET",
327
+ path: `/workspaces/${ID("wsp")}/members`,
328
+ responseBody: page(workspaceMember),
329
+ write: false,
330
+ },
331
+ {
332
+ name: "createWorkspace",
333
+ invoke: (c) => c.createWorkspace({ name: "Acme Inc" }),
334
+ method: "POST",
335
+ path: "/workspaces",
336
+ responseBody: workspace,
337
+ write: true,
338
+ },
339
+ {
340
+ name: "getWorkspace",
341
+ invoke: (c) => c.getWorkspace(ID("wsp")),
342
+ method: "GET",
343
+ path: `/workspaces/${ID("wsp")}`,
344
+ responseBody: workspace,
345
+ write: false,
346
+ },
347
+ {
348
+ name: "updateWorkspace",
349
+ invoke: (c) => c.updateWorkspace(ID("wsp"), { name: "Acme 2" }),
350
+ method: "PATCH",
351
+ path: `/workspaces/${ID("wsp")}`,
352
+ responseBody: workspace,
353
+ write: true,
354
+ },
355
+ // Projects
356
+ {
357
+ name: "listProjects",
358
+ invoke: (c) => c.listProjects({ workspace_id: ID("wsp") }),
359
+ method: "GET",
360
+ path: "/projects",
361
+ responseBody: page(project),
362
+ write: false,
363
+ },
364
+ {
365
+ name: "createProject",
366
+ invoke: (c) => c.createProject({ workspace_id: ID("wsp"), name: "App" }),
367
+ method: "POST",
368
+ path: "/projects",
369
+ responseBody: project,
370
+ write: true,
371
+ },
372
+ {
373
+ name: "getProject",
374
+ invoke: (c) => c.getProject(ID("prj")),
375
+ method: "GET",
376
+ path: `/projects/${ID("prj")}`,
377
+ responseBody: project,
378
+ write: false,
379
+ },
380
+ {
381
+ name: "updateProject",
382
+ invoke: (c) => c.updateProject(ID("prj"), { name: "App 2" }),
383
+ method: "PATCH",
384
+ path: `/projects/${ID("prj")}`,
385
+ responseBody: project,
386
+ write: true,
387
+ },
388
+ {
389
+ name: "deleteProject",
390
+ invoke: (c) => c.deleteProject(ID("prj")),
391
+ method: "DELETE",
392
+ path: `/projects/${ID("prj")}`,
393
+ responseBody: { id: ID("prj"), deleted: true },
394
+ write: true,
395
+ },
396
+ // Environments
397
+ {
398
+ name: "listEnvironments",
399
+ invoke: (c) => c.listEnvironments({ project_id: ID("prj") }),
400
+ method: "GET",
401
+ path: "/environments",
402
+ responseBody: page(environment),
403
+ write: false,
404
+ },
405
+ {
406
+ name: "createEnvironment",
407
+ invoke: (c) => c.createEnvironment({ project_id: ID("prj"), type: "test", name: "Test" }),
408
+ method: "POST",
409
+ path: "/environments",
410
+ responseBody: environment,
411
+ write: true,
412
+ },
413
+ {
414
+ name: "getEnvironment",
415
+ invoke: (c) => c.getEnvironment(ID("env")),
416
+ method: "GET",
417
+ path: `/environments/${ID("env")}`,
418
+ responseBody: environment,
419
+ write: false,
420
+ },
421
+ {
422
+ name: "updateEnvironment",
423
+ invoke: (c) => c.updateEnvironment(ID("env"), { name: "Test 2" }),
424
+ method: "PATCH",
425
+ path: `/environments/${ID("env")}`,
426
+ responseBody: environment,
427
+ write: true,
428
+ },
429
+ {
430
+ name: "deleteEnvironment",
431
+ invoke: (c) => c.deleteEnvironment(ID("env")),
432
+ method: "DELETE",
433
+ path: `/environments/${ID("env")}`,
434
+ responseBody: { id: ID("env"), status: "deleted" },
435
+ write: true,
436
+ },
437
+ {
438
+ name: "getRpMigration",
439
+ invoke: (c) => c.getRpMigration(ID("env")),
440
+ method: "GET",
441
+ path: `/environments/${ID("env")}/rp-migration`,
442
+ responseBody: rpMigration,
443
+ write: false,
444
+ },
445
+ {
446
+ name: "disableLegacyRp",
447
+ invoke: (c) => c.disableLegacyRp(ID("env"), { confirm_rp_id: "auth.example.com" }),
448
+ method: "POST",
449
+ path: `/environments/${ID("env")}/rp-migration/disable-legacy`,
450
+ responseBody: rpMigration,
451
+ write: true,
452
+ },
453
+ // Clients
454
+ {
455
+ name: "listClients",
456
+ invoke: (c) => c.listClients({ environment_id: ID("env") }),
457
+ method: "GET",
458
+ path: "/clients",
459
+ responseBody: page(clientResource),
460
+ write: false,
461
+ },
462
+ {
463
+ name: "createClient",
464
+ invoke: (c) =>
465
+ c.createClient({
466
+ environment_id: ID("env"),
467
+ client_type: "web_spa",
468
+ name: "SPA",
469
+ token_endpoint_auth_method: "none",
470
+ }),
471
+ method: "POST",
472
+ path: "/clients",
473
+ responseBody: clientResource,
474
+ write: true,
475
+ },
476
+ {
477
+ name: "getClient",
478
+ invoke: (c) => c.getClient(ID("cli")),
479
+ method: "GET",
480
+ path: `/clients/${ID("cli")}`,
481
+ responseBody: clientResource,
482
+ write: false,
483
+ },
484
+ {
485
+ name: "updateClient",
486
+ invoke: (c) => c.updateClient(ID("cli"), { name: "SPA 2" }),
487
+ method: "PATCH",
488
+ path: `/clients/${ID("cli")}`,
489
+ responseBody: clientResource,
490
+ write: true,
491
+ },
492
+ {
493
+ name: "deleteClient",
494
+ invoke: (c) => c.deleteClient(ID("cli")),
495
+ method: "DELETE",
496
+ path: `/clients/${ID("cli")}`,
497
+ responseBody: { id: ID("cli"), deleted: true },
498
+ write: true,
499
+ },
500
+ {
501
+ name: "rotateClientSecret",
502
+ invoke: (c) => c.rotateClientSecret(ID("cli")),
503
+ method: "POST",
504
+ path: `/clients/${ID("cli")}/rotate-secret`,
505
+ responseBody: { id: ID("cli"), client_secret: "secret", rotated_at: TS },
506
+ write: true,
507
+ },
508
+ // Connections
509
+ {
510
+ name: "listConnections",
511
+ invoke: (c) => c.listConnections({ environment_id: ID("env") }),
512
+ method: "GET",
513
+ path: "/connections",
514
+ responseBody: page(connection),
515
+ write: false,
516
+ },
517
+ {
518
+ name: "createConnection",
519
+ invoke: (c) =>
520
+ c.createConnection({
521
+ environment_id: ID("env"),
522
+ provider: "google",
523
+ mode: "managed",
524
+ provider_key: "google",
525
+ provider_client_id: "pid",
526
+ provider_client_secret: "ps",
527
+ }),
528
+ method: "POST",
529
+ path: "/connections",
530
+ responseBody: connection,
531
+ write: true,
532
+ },
533
+ {
534
+ name: "updateConnection",
535
+ invoke: (c) => c.updateConnection(ID("con"), { status: "disabled" }),
536
+ method: "PATCH",
537
+ path: `/connections/${ID("con")}`,
538
+ responseBody: connection,
539
+ write: true,
540
+ },
541
+ {
542
+ name: "deleteConnection",
543
+ invoke: (c) => c.deleteConnection(ID("con")),
544
+ method: "DELETE",
545
+ path: `/connections/${ID("con")}`,
546
+ responseBody: { id: ID("con"), deleted: true },
547
+ write: true,
548
+ },
549
+ // Domains
550
+ {
551
+ name: "listDomains",
552
+ invoke: (c) => c.listDomains({ environment_id: ID("env") }),
553
+ method: "GET",
554
+ path: "/domains",
555
+ responseBody: page(domain),
556
+ write: false,
557
+ },
558
+ {
559
+ name: "createDomain",
560
+ invoke: (c) => c.createDomain({ environment_id: ID("env"), hostname: "auth.customer.example" }),
561
+ method: "POST",
562
+ path: "/domains",
563
+ responseBody: domain,
564
+ write: true,
565
+ },
566
+ {
567
+ name: "getDomain",
568
+ invoke: (c) => c.getDomain(ID("dom")),
569
+ method: "GET",
570
+ path: `/domains/${ID("dom")}`,
571
+ responseBody: domain,
572
+ write: false,
573
+ },
574
+ {
575
+ name: "updateDomain",
576
+ invoke: (c) => c.updateDomain(ID("dom"), { rp_enabled: true }),
577
+ method: "PATCH",
578
+ path: `/domains/${ID("dom")}`,
579
+ responseBody: domain,
580
+ write: true,
581
+ },
582
+ {
583
+ name: "deleteDomain",
584
+ invoke: (c) => c.deleteDomain(ID("dom")),
585
+ method: "DELETE",
586
+ path: `/domains/${ID("dom")}`,
587
+ responseBody: { id: ID("dom"), deleted: true },
588
+ write: true,
589
+ },
590
+ {
591
+ name: "retryDomainValidation",
592
+ invoke: (c) => c.retryDomainValidation(ID("dom")),
593
+ method: "POST",
594
+ path: `/domains/${ID("dom")}/retry-validation`,
595
+ responseBody: domain,
596
+ write: true,
597
+ },
598
+ // Users
599
+ {
600
+ name: "listUsers",
601
+ invoke: (c) => c.listUsers({ environment_id: ID("env") }),
602
+ method: "GET",
603
+ path: "/users",
604
+ responseBody: page(user),
605
+ write: false,
606
+ },
607
+ {
608
+ name: "createUser",
609
+ invoke: (c) => c.createUser({ environment_id: ID("env"), email: "a@b.example" }),
610
+ method: "POST",
611
+ path: "/users",
612
+ responseBody: user,
613
+ write: true,
614
+ },
615
+ {
616
+ name: "getUser",
617
+ invoke: (c) => c.getUser(ID("env"), ID("usr")),
618
+ method: "GET",
619
+ path: `/users/${ID("usr")}`,
620
+ responseBody: user,
621
+ write: false,
622
+ },
623
+ {
624
+ name: "updateUser",
625
+ invoke: (c) => c.updateUser(ID("env"), ID("usr"), { name: "N" }),
626
+ method: "PATCH",
627
+ path: `/users/${ID("usr")}`,
628
+ responseBody: user,
629
+ write: true,
630
+ },
631
+ {
632
+ name: "deleteUser",
633
+ invoke: (c) => c.deleteUser(ID("env"), ID("usr")),
634
+ method: "DELETE",
635
+ path: `/users/${ID("usr")}`,
636
+ responseBody: { id: ID("usr"), status: "pending_deletion" },
637
+ write: true,
638
+ },
639
+ {
640
+ name: "blockUser",
641
+ invoke: (c) => c.blockUser(ID("env"), ID("usr"), { reason: "abuse" }),
642
+ method: "POST",
643
+ path: `/users/${ID("usr")}/block`,
644
+ responseBody: { id: ID("usr"), status: "blocked" },
645
+ write: true,
646
+ },
647
+ {
648
+ name: "unblockUser",
649
+ invoke: (c) => c.unblockUser(ID("env"), ID("usr")),
650
+ method: "POST",
651
+ path: `/users/${ID("usr")}/unblock`,
652
+ responseBody: { id: ID("usr"), status: "active" },
653
+ write: true,
654
+ },
655
+ // User sub-resources
656
+ {
657
+ name: "listUserIdentities",
658
+ invoke: (c) => c.listUserIdentities(ID("env"), ID("usr")),
659
+ method: "GET",
660
+ path: `/users/${ID("usr")}/identities`,
661
+ responseBody: page(identity),
662
+ write: false,
663
+ },
664
+ {
665
+ name: "deleteUserIdentity",
666
+ invoke: (c) => c.deleteUserIdentity(ID("env"), ID("usr"), ID("idn")),
667
+ method: "DELETE",
668
+ path: `/users/${ID("usr")}/identities/${ID("idn")}`,
669
+ responseBody: { identity_id: ID("idn"), deleted: true },
670
+ write: true,
671
+ },
672
+ {
673
+ name: "listUserPasskeys",
674
+ invoke: (c) => c.listUserPasskeys(ID("env"), ID("usr")),
675
+ method: "GET",
676
+ path: `/users/${ID("usr")}/passkeys`,
677
+ responseBody: page(passkey),
678
+ write: false,
679
+ },
680
+ {
681
+ name: "deleteUserPasskey",
682
+ invoke: (c) => c.deleteUserPasskey(ID("env"), ID("usr"), ID("psk")),
683
+ method: "DELETE",
684
+ path: `/users/${ID("usr")}/passkeys/${ID("psk")}`,
685
+ responseBody: { passkey_id: ID("psk"), deleted: true },
686
+ write: true,
687
+ },
688
+ {
689
+ name: "listUserSessions",
690
+ invoke: (c) => c.listUserSessions(ID("env"), ID("usr")),
691
+ method: "GET",
692
+ path: `/users/${ID("usr")}/sessions`,
693
+ responseBody: page(session),
694
+ write: false,
695
+ },
696
+ {
697
+ name: "revokeUserSession",
698
+ invoke: (c) => c.revokeUserSession(ID("env"), ID("usr"), ID("ses")),
699
+ method: "DELETE",
700
+ path: `/users/${ID("usr")}/sessions/${ID("ses")}`,
701
+ responseBody: { session_id: ID("ses"), revoked: true },
702
+ write: true,
703
+ },
704
+ {
705
+ name: "revokeAllUserSessions",
706
+ invoke: (c) => c.revokeAllUserSessions(ID("env"), ID("usr")),
707
+ method: "DELETE",
708
+ path: `/users/${ID("usr")}/sessions`,
709
+ responseBody: { revoked: true },
710
+ write: true,
711
+ },
712
+ // User import/export jobs
713
+ {
714
+ name: "createUserImportJob",
715
+ invoke: (c) =>
716
+ c.createUserImportJob({
717
+ environment_id: ID("env"),
718
+ format: "json",
719
+ source_url: "https://exports.customer.example/users.json",
720
+ }),
721
+ method: "POST",
722
+ path: "/user-import-jobs",
723
+ responseBody: importJob,
724
+ write: true,
725
+ },
726
+ {
727
+ name: "getUserImportJob",
728
+ invoke: (c) => c.getUserImportJob(ID("job")),
729
+ method: "GET",
730
+ path: `/user-import-jobs/${ID("job")}`,
731
+ responseBody: importJob,
732
+ write: false,
733
+ },
734
+ {
735
+ name: "createUserExportJob",
736
+ invoke: (c) => c.createUserExportJob({ environment_id: ID("env"), target_user_id: ID("usr") }),
737
+ method: "POST",
738
+ path: "/user-export-jobs",
739
+ responseBody: exportJob,
740
+ write: true,
741
+ },
742
+ {
743
+ name: "getUserExportJob",
744
+ invoke: (c) => c.getUserExportJob(ID("job")),
745
+ method: "GET",
746
+ path: `/user-export-jobs/${ID("job")}`,
747
+ responseBody: exportJob,
748
+ write: false,
749
+ },
750
+ // Webhooks
751
+ {
752
+ name: "listWebhooks",
753
+ invoke: (c) => c.listWebhooks({ environment_id: ID("env") }),
754
+ method: "GET",
755
+ path: "/webhooks",
756
+ responseBody: page(webhook),
757
+ write: false,
758
+ },
759
+ {
760
+ name: "listWebhookDeliveries",
761
+ invoke: (c) => c.listWebhookDeliveries(ID("whk")),
762
+ method: "GET",
763
+ path: `/webhooks/${ID("whk")}/deliveries`,
764
+ responseBody: page(webhookDelivery),
765
+ write: false,
766
+ },
767
+ {
768
+ name: "createWebhook",
769
+ invoke: (c) =>
770
+ c.createWebhook({
771
+ environment_id: ID("env"),
772
+ url: "https://customer.example/hooks/auth",
773
+ event_types: ["user.created"],
774
+ }),
775
+ method: "POST",
776
+ path: "/webhooks",
777
+ responseBody: { ...webhook, secret: "whsec" },
778
+ write: true,
779
+ },
780
+ {
781
+ name: "updateWebhook",
782
+ invoke: (c) => c.updateWebhook(ID("whk"), { status: "disabled" }),
783
+ method: "PATCH",
784
+ path: `/webhooks/${ID("whk")}`,
785
+ responseBody: webhook,
786
+ write: true,
787
+ },
788
+ {
789
+ name: "deleteWebhook",
790
+ invoke: (c) => c.deleteWebhook(ID("whk")),
791
+ method: "DELETE",
792
+ path: `/webhooks/${ID("whk")}`,
793
+ responseBody: { id: ID("whk"), deleted: true },
794
+ write: true,
795
+ },
796
+ {
797
+ name: "rotateWebhookSecret",
798
+ invoke: (c) => c.rotateWebhookSecret(ID("whk")),
799
+ method: "POST",
800
+ path: `/webhooks/${ID("whk")}/rotate-secret`,
801
+ responseBody: { id: ID("whk"), secret: "whsec2", rotated_at: TS },
802
+ write: true,
803
+ },
804
+ {
805
+ name: "testWebhook",
806
+ invoke: (c) => c.testWebhook(ID("whk"), { event_type: "user.created" }),
807
+ method: "POST",
808
+ path: `/webhooks/${ID("whk")}/test`,
809
+ responseBody: { delivered: true, response_status: 200, response_time_ms: 12, requested_at: TS },
810
+ write: true,
811
+ },
812
+ // Audit / usage / billing
813
+ {
814
+ name: "listAuditEvents",
815
+ invoke: (c) => c.listAuditEvents({ environment_id: ID("env") }),
816
+ method: "GET",
817
+ path: "/audit-events",
818
+ responseBody: page(auditEvent),
819
+ write: false,
820
+ },
821
+ {
822
+ name: "getMauUsage",
823
+ invoke: (c) => c.getMauUsage(),
824
+ method: "GET",
825
+ path: "/usage/mau",
826
+ responseBody: mauUsage,
827
+ write: false,
828
+ },
829
+ {
830
+ name: "createBillingCheckoutSession",
831
+ invoke: (c) =>
832
+ c.createBillingCheckoutSession({
833
+ success_url: "https://customer.example/ok",
834
+ cancel_url: "https://customer.example/cancel",
835
+ }),
836
+ method: "POST",
837
+ path: "/billing/checkout-session",
838
+ responseBody: { checkout_url: "https://checkout.stripe.com/c/s", expires_at: TS },
839
+ write: true,
840
+ },
841
+ {
842
+ name: "createBillingPortalSession",
843
+ invoke: (c) => c.createBillingPortalSession({ return_url: "https://customer.example/back" }),
844
+ method: "POST",
845
+ path: "/billing/portal-session",
846
+ responseBody: { portal_url: "https://billing.stripe.com/p/s" },
847
+ write: true,
848
+ },
849
+ ];
850
+
851
+ describe("createManagementClient — one method per design.md §26.2 route", () => {
852
+ test(`covers ${ROUTES.length} routes`, () => {
853
+ expect(ROUTES.length).toBe(62);
854
+ expect(new Set(ROUTES.map((r) => r.name)).size).toBe(ROUTES.length);
855
+ });
856
+
857
+ for (const route of ROUTES) {
858
+ test(`${route.name}: ${route.method} ${route.path}`, async () => {
859
+ const request = await recordSingle(route.responseBody, route.invoke);
860
+ const url = new URL(request.url);
861
+ expect(url.origin + url.pathname.replace(/^\/v1/, "")).toBe(
862
+ `https://api.example-auth.com${route.path}`,
863
+ );
864
+ expect(request.method).toBe(route.method);
865
+ // Authorization header on every request (design.md §26.1)
866
+ expect(request.headers.authorization).toBe(`Bearer ${API_KEY}`);
867
+ expect(request.headers.accept).toBe("application/json");
868
+ // Idempotency-Key on writes, absent on reads (design.md §26.3)
869
+ if (route.write) {
870
+ expect(request.headers["idempotency-key"]).toMatch(
871
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
872
+ );
873
+ } else {
874
+ expect(request.headers["idempotency-key"]).toBeUndefined();
875
+ }
876
+ });
877
+ }
878
+
879
+ test("honors a caller-provided Idempotency-Key override", async () => {
880
+ const { client, requests } = createClient(() => jsonResponse(workspace));
881
+ await client.createWorkspace({ name: "Acme Inc" }, { idempotencyKey: "idem-fixed-1" });
882
+ expect(requests[0]?.headers["idempotency-key"]).toBe("idem-fixed-1");
883
+ });
884
+
885
+ test("sends If-Match on conditional PATCH when an etag is provided", async () => {
886
+ const { client, requests } = createClient(() => jsonResponse(workspace));
887
+ await client.updateWorkspace(ID("wsp"), { name: "Acme 2" }, { ifMatch: '"v3"' });
888
+ expect(requests[0]?.headers["if-match"]).toBe('"v3"');
889
+ });
890
+
891
+ test("sends If-Match on conditional DELETE when an etag is provided", async () => {
892
+ const { client, requests } = createClient(() => jsonResponse({ id: ID("prj"), deleted: true }));
893
+ await client.deleteProject(ID("prj"), { ifMatch: 'W/"v9"' });
894
+ expect(requests[0]?.headers["if-match"]).toBe('W/"v9"');
895
+ });
896
+
897
+ test("omits If-Match when no etag is provided", async () => {
898
+ const request = await recordSingle(workspace, (c) =>
899
+ c.updateWorkspace(ID("wsp"), { name: "Acme 2" }),
900
+ );
901
+ expect(request.headers["if-match"]).toBeUndefined();
902
+ });
903
+
904
+ test("serializes list query params (cursor/limit/filters) with encoding", async () => {
905
+ const { client, requests } = createClient(() => jsonResponse(page(user)));
906
+ await client.listUsers({
907
+ environment_id: ID("env"),
908
+ status: "blocked",
909
+ search: "a b",
910
+ cursor: "cur/1",
911
+ limit: 50,
912
+ });
913
+ const url = new URL(requests[0]?.url ?? "");
914
+ expect(url.searchParams.get("environment_id")).toBe(ID("env"));
915
+ expect(url.searchParams.get("status")).toBe("blocked");
916
+ expect(url.searchParams.get("search")).toBe("a b");
917
+ expect(url.searchParams.get("cursor")).toBe("cur/1");
918
+ expect(url.searchParams.get("limit")).toBe("50");
919
+ });
920
+ test("serializes environment context on individual user reads and writes", async () => {
921
+ const getRequest = await recordSingle(user, (c) => c.getUser(ID("env"), ID("usr")));
922
+ expect(new URL(getRequest.url).searchParams.get("environment_id")).toBe(ID("env"));
923
+
924
+ const updateRequest = await recordSingle(user, (c) =>
925
+ c.updateUser(ID("env"), ID("usr"), { name: "Updated" }),
926
+ );
927
+ expect(new URL(updateRequest.url).searchParams.get("environment_id")).toBe(ID("env"));
928
+
929
+ const listRequest = await recordSingle(page(identity), (c) =>
930
+ c.listUserIdentities(ID("env"), ID("usr"), { limit: 10 }),
931
+ );
932
+ expect(new URL(listRequest.url).searchParams.get("environment_id")).toBe(ID("env"));
933
+ });
934
+
935
+ test("sends the validated JSON body and applies schema defaults", async () => {
936
+ const { client, requests } = createClient(() => jsonResponse(clientResource));
937
+ await client.createClient({
938
+ environment_id: ID("env"),
939
+ client_type: "web_spa",
940
+ name: "SPA",
941
+ token_endpoint_auth_method: "none",
942
+ });
943
+ const sent = JSON.parse(requests[0]?.body ?? "{}") as Record<string, unknown>;
944
+ expect(sent.name).toBe("SPA");
945
+ // schema defaults materialized client-side
946
+ expect(sent.redirect_uris).toEqual([]);
947
+ expect(sent.require_pkce).toBe(true);
948
+ expect(requests[0]?.headers["content-type"]).toBe("application/json");
949
+ });
950
+
951
+ test("client-side validation failure → invalid_request, nothing sent", async () => {
952
+ const { client, requests } = createClient(() => jsonResponse(workspace));
953
+ const result = await client.createWorkspace({ name: "" });
954
+ expect(isFailure(result)).toBe(true);
955
+ if (isFailure(result)) {
956
+ expect(result.error.type).toBe("invalid_request");
957
+ if (result.error.type === "invalid_request") {
958
+ expect(result.error.issues.length).toBeGreaterThan(0);
959
+ }
960
+ }
961
+ expect(requests).toHaveLength(0);
962
+ });
963
+
964
+ test("surfaces x-request-id and etag response headers on success", async () => {
965
+ const { client } = createClient(() => jsonResponse(workspace, 200, { etag: '"v7"' }));
966
+ const result = await client.getWorkspace(ID("wsp"));
967
+ expect(isSuccess(result)).toBe(true);
968
+ if (isSuccess(result)) {
969
+ expect(result.value.requestId).toBe(REQUEST_ID);
970
+ expect(result.value.etag).toBe('"v7"');
971
+ expect(result.value.data.id).toBe(workspace.id);
972
+ }
973
+ });
974
+ });
975
+
976
+ // ---------------------------------------------------------------------------
977
+ // Error mapping
978
+ // ---------------------------------------------------------------------------
979
+
980
+ const problem = (status: number, code: string) => ({
981
+ type: `https://docs.example-auth.com/errors/${code.replaceAll("_", "-")}`,
982
+ title: "Request failed",
983
+ status,
984
+ detail: `detail for ${code}`,
985
+ code,
986
+ request_id: REQUEST_ID,
987
+ });
988
+
989
+ describe("error mapping (design.md §26.3 Problem Details)", () => {
990
+ const MATRIX: ReadonlyArray<{
991
+ readonly status: number;
992
+ readonly code: string;
993
+ readonly retryable: boolean;
994
+ }> = [
995
+ { status: 401, code: "unauthorized", retryable: false },
996
+ { status: 403, code: "forbidden", retryable: false },
997
+ { status: 404, code: "not_found", retryable: false },
998
+ { status: 409, code: "conflict", retryable: false },
999
+ { status: 429, code: "rate_limited", retryable: true },
1000
+ { status: 500, code: "unexpected_error", retryable: true },
1001
+ ];
1002
+
1003
+ for (const { status, code, retryable } of MATRIX) {
1004
+ test(`${status} ${code} → api_error with status+code+request_id`, async () => {
1005
+ const { client } = createClient(() => jsonResponse(problem(status, code), status));
1006
+ const result = await client.getWorkspace(ID("wsp"));
1007
+ expect(isFailure(result)).toBe(true);
1008
+ if (!isFailure(result)) return;
1009
+ expect(result.error.type).toBe("api_error");
1010
+ if (result.error.type === "api_error") {
1011
+ expect(result.error.status).toBe(status);
1012
+ expect(result.error.code).toBe(code);
1013
+ expect(result.error.requestId).toBe(REQUEST_ID);
1014
+ expect(result.error.detail).toBe(`detail for ${code}`);
1015
+ expect(result.error.retryable).toBe(retryable ? true : undefined);
1016
+ }
1017
+ });
1018
+ }
1019
+
1020
+ test("non-Problem-Details error body → api_error with http_<status> fallback code", async () => {
1021
+ const { client } = createClient(
1022
+ () => new Response("Bad Gateway", { status: 502, headers: { "x-request-id": REQUEST_ID } }),
1023
+ );
1024
+ const result = await client.getWorkspace(ID("wsp"));
1025
+ expect(isFailure(result)).toBe(true);
1026
+ if (!isFailure(result)) return;
1027
+ expect(result.error.type).toBe("api_error");
1028
+ if (result.error.type === "api_error") {
1029
+ expect(result.error.status).toBe(502);
1030
+ expect(result.error.code).toBe("http_502");
1031
+ expect(result.error.title).toBe("Bad Gateway");
1032
+ expect(result.error.requestId).toBe(REQUEST_ID);
1033
+ expect(result.error.retryable).toBe(true);
1034
+ }
1035
+ });
1036
+
1037
+ test("fetch rejection → typed network_error (retryable)", async () => {
1038
+ const fetchFn: typeof fetch = () => Promise.reject(new Error("connect ECONNREFUSED"));
1039
+ const client = createManagementClient({ baseUrl: BASE_URL, apiKey: API_KEY, fetch: fetchFn });
1040
+ const result = await client.listWorkspaces();
1041
+ expect(isFailure(result)).toBe(true);
1042
+ if (!isFailure(result)) return;
1043
+ expect(result.error.type).toBe("network_error");
1044
+ if (result.error.type === "network_error") {
1045
+ expect(result.error.message).toContain("ECONNREFUSED");
1046
+ expect(result.error.retryable).toBe(true);
1047
+ }
1048
+ });
1049
+
1050
+ test("malformed 2xx payload → invalid_response (never trust the wire)", async () => {
1051
+ const { client } = createClient(() => jsonResponse({ unexpected: true }));
1052
+ const result = await client.getWorkspace(ID("wsp"));
1053
+ expect(isFailure(result)).toBe(true);
1054
+ if (!isFailure(result)) return;
1055
+ expect(result.error.type).toBe("invalid_response");
1056
+ if (result.error.type === "invalid_response") {
1057
+ expect(result.error.status).toBe(200);
1058
+ expect(result.error.requestId).toBe(REQUEST_ID);
1059
+ expect(result.error.issues.length).toBeGreaterThan(0);
1060
+ }
1061
+ });
1062
+
1063
+ test("non-JSON 2xx body → invalid_response", async () => {
1064
+ const { client } = createClient(() => new Response("<html>ok</html>", { status: 200 }));
1065
+ const result = await client.listWorkspaces();
1066
+ expect(isFailure(result)).toBe(true);
1067
+ if (!isFailure(result)) return;
1068
+ expect(result.error.type).toBe("invalid_response");
1069
+ if (result.error.type === "invalid_response") {
1070
+ expect(result.error.issues).toEqual(["response body is not valid JSON"]);
1071
+ }
1072
+ });
1073
+ });
1074
+
1075
+ describe("createManagementClient option validation", () => {
1076
+ test("rejects an unparseable baseUrl", () => {
1077
+ expect(() => createManagementClient({ baseUrl: "not a url", apiKey: API_KEY })).toThrow(
1078
+ TypeError,
1079
+ );
1080
+ });
1081
+
1082
+ test("rejects a non-http(s) baseUrl", () => {
1083
+ expect(() =>
1084
+ createManagementClient({ baseUrl: "ftp://example.com/v1", apiKey: API_KEY }),
1085
+ ).toThrow(TypeError);
1086
+ });
1087
+
1088
+ test("rejects an empty apiKey", () => {
1089
+ expect(() => createManagementClient({ baseUrl: BASE_URL, apiKey: "" })).toThrow(TypeError);
1090
+ });
1091
+
1092
+ test("strips a trailing slash from baseUrl", async () => {
1093
+ const stub = createStubFetch(() => jsonResponse(page(workspace)));
1094
+ const client = createManagementClient({
1095
+ baseUrl: `${BASE_URL}/`,
1096
+ apiKey: API_KEY,
1097
+ fetch: stub.fetchFn,
1098
+ });
1099
+ await client.listWorkspaces();
1100
+ expect(stub.requests[0]?.url.startsWith(`${BASE_URL}/workspaces`)).toBe(true);
1101
+ });
1102
+ });
1103
+
1104
+ describe("error union ergonomics", () => {
1105
+ test("ManagementClientError variants are discriminated by `type`", () => {
1106
+ const kinds: readonly ManagementClientError["type"][] = [
1107
+ "api_error",
1108
+ "network_error",
1109
+ "invalid_response",
1110
+ "invalid_request",
1111
+ ];
1112
+ expect(new Set(kinds).size).toBe(4);
1113
+ });
1114
+ });