@zitadel/testing 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.
@@ -1,4451 +0,0 @@
1
- const require_handshake = require("./handshake-D6MXSUcd.cjs");
2
- require("node:fs");
3
- require("node:url");
4
- let node_fs_promises = require("node:fs/promises");
5
- let node_os = require("node:os");
6
- let node_path = require("node:path");
7
- let node_child_process = require("node:child_process");
8
- let node_module = require("node:module");
9
- let node_net = require("node:net");
10
- let node_crypto = require("node:crypto");
11
- //#region ../api/dist/runtime/base-url.mjs
12
- let proxyPath = "";
13
- function getProxyPath() {
14
- return proxyPath;
15
- }
16
- function setProxyPath(path) {
17
- proxyPath = path;
18
- }
19
- //#endregion
20
- //#region ../api/dist/runtime/auth.mjs
21
- /**
22
- * Module-global bearer token used by the orval-generated client's
23
- * custom fetch. Set once at command boot (the same lifecycle pattern
24
- * as `base-url.ts`); every generated request reads from here.
25
- *
26
- * Keeping the token here means the CLI doesn't have to thread an
27
- * `Authorization` header through every generated call site; orval's
28
- * `mutator` wires `runtime/fetch.ts` in, and that file pulls the token
29
- * from this module.
30
- */
31
- let apiAuthToken;
32
- function getApiAuthToken() {
33
- return apiAuthToken;
34
- }
35
- function setApiAuthToken(token) {
36
- apiAuthToken = token;
37
- }
38
- /**
39
- * The CSRF token for the first-party browser surfaces (ADR 053 §5). A
40
- * state-changing request that the `__nextgen_session` cookie authenticates must
41
- * carry the session's token — `csrf_token` from `GET /sessions/me/csrf` — in the
42
- * `X-Zitadel-CSRF` header. The app sets it once it has loaded its session;
43
- * `runtime/fetch.ts` then adds the header to unsafe requests. Unset (every
44
- * other caller), nothing is added.
45
- *
46
- * The token belongs to the server that issued it, so it is stored with that
47
- * server's origin and only sent there: another client on the same page, with
48
- * another base URL, never carries it to a different host. The origin defaults
49
- * to the page's own, which is where a same-origin app's API lives; with no
50
- * origin to go by (no page, or an unparsable request URL), nothing is sent.
51
- *
52
- * Unlike the bearer slot, the app sets this one rather than the client, so it
53
- * lives on `globalThis` under a {@link Symbol.for} key, like the project slot in
54
- * `config.ts`: a second copy of this module (an SDK pinning another version)
55
- * must read the token the app's copy wrote.
56
- */
57
- const CSRF_SLOT = Symbol.for("@zitadel/api/auth:csrf");
58
- function csrfSlot() {
59
- const global = globalThis;
60
- const existing = global[CSRF_SLOT];
61
- if (existing) return existing;
62
- const slot = {};
63
- global[CSRF_SLOT] = slot;
64
- return slot;
65
- }
66
- /** The token to send to `origin`, if it was issued there. */
67
- function apiCsrfTokenFor(origin) {
68
- const slot = csrfSlot();
69
- return origin !== void 0 && slot.tokenOrigin === origin ? slot.token : void 0;
70
- }
71
- /** The rejection handler for a refusal from `origin`, if it was registered for it. */
72
- function apiCsrfRejectionHandlerFor(origin) {
73
- const slot = csrfSlot();
74
- return origin !== void 0 && slot.handlerOrigin === origin ? slot.onRejected : void 0;
75
- }
76
- //#endregion
77
- //#region ../api/dist/runtime/fetch.mjs
78
- /** The header the session-bound CSRF token travels in (ADR 053 §5). */
79
- const CSRF_HEADER = "X-Zitadel-CSRF";
80
- const SAFE_METHODS = /* @__PURE__ */ new Set([
81
- "GET",
82
- "HEAD",
83
- "OPTIONS"
84
- ]);
85
- /** The code the server answers a refused CSRF check with. */
86
- const CSRF_INVALID = "auth.csrf_invalid";
87
- /**
88
- * Framework-neutral failure type the orval-generated client throws on
89
- * any non-2xx response. Carries the HTTP status, the parsed error body
90
- * (the spec's `{code, message, details?}` envelope when the server
91
- * returned one), and the request URL — enough for callers to map to
92
- * their own error taxonomy without re-implementing the fetch layer.
93
- *
94
- * Callers that don't care about the distinction can catch `ApiError`
95
- * generically; callers that do (the CLI's `toZitadelError`) read
96
- * `status` and decide.
97
- */
98
- var ApiError = class extends Error {
99
- status;
100
- url;
101
- body;
102
- /**
103
- * The server's ID for the request, from its `X-Request-Id` header: the
104
- * reference that finds the request in the server's logs, to show beside the
105
- * error. `undefined` when the response carried none, as from a proxy.
106
- */
107
- requestId;
108
- constructor(status, url, body, message, requestId) {
109
- super(message);
110
- this.name = "ApiError";
111
- this.status = status;
112
- this.url = url;
113
- this.body = body;
114
- this.requestId = requestId;
115
- }
116
- };
117
- /**
118
- * Thrown when a request got no response at all: the connection was refused or
119
- * reset, the host did not resolve, or the server accepted the connection but
120
- * did not answer in time. The counterpart to {@link ApiError}, which is a
121
- * response that came back with a failing status.
122
- *
123
- * `fetch` only rejects when no response arrived, so this is decided by the
124
- * fact that it rejected, never by how a runtime words the failure. The
125
- * runtime's own error stays on `cause` for debugging.
126
- */
127
- var NetworkError = class extends Error {
128
- url;
129
- /** `timeout` when a deadline cut the request off, `unreachable` otherwise. */
130
- reason;
131
- constructor(url, reason, message, options) {
132
- super(message, options);
133
- this.name = "NetworkError";
134
- this.url = url;
135
- this.reason = reason;
136
- }
137
- };
138
- let requestPolicy = {};
139
- function setRequestPolicy(policy) {
140
- requestPolicy = policy;
141
- }
142
- /**
143
- * The orval `mutator` for the fetch client. Every generated operation
144
- * routes its request through this function instead of the global
145
- * `fetch`. We pin three concerns here so generated call sites stay
146
- * focused on the shape of one HTTP call:
147
- *
148
- * - bearer auth — read from `runtime/auth.ts` and attached automatically;
149
- * - the CSRF header — the session-bound token from `runtime/auth.ts`, on
150
- * unsafe methods to the origin it was issued for, when a first-party surface
151
- * has set one; an unsafe request to that origin refused with
152
- * `403 auth.csrf_invalid` asks the registered rejection handler for a fresh
153
- * token and is retried once with it, only if the handler returns one (the
154
- * session still belongs to the same person);
155
- * - non-2xx → throw — orval's stock client parses the body regardless
156
- * of status, so callers would have to inspect every response. Throw
157
- * `ApiError` on `!res.ok` so failures interrupt control flow;
158
- * - body parsing — return the parsed JSON typed as `T` (the operation's
159
- * return type, threaded through by orval), or `undefined` for the
160
- * spec's `204`/`205`/`304` no-body responses;
161
- * - no response → throw {@link NetworkError}, or the abort reason when the
162
- * caller cancelled (see {@link request}).
163
- */
164
- async function customFetch(url, options) {
165
- const policy = requestPolicy;
166
- const token = getApiAuthToken();
167
- const headers = new Headers(options.headers);
168
- if (token && !headers.has("authorization")) headers.set("authorization", `Bearer ${token}`);
169
- const method = (options.method ?? "GET").toUpperCase();
170
- const unsafe = !SAFE_METHODS.has(method) && !headers.has("X-Zitadel-CSRF");
171
- const target = originOf(url);
172
- const csrfToken = apiCsrfTokenFor(target);
173
- if (unsafe && csrfToken) headers.set(CSRF_HEADER, csrfToken);
174
- let { res, rawBody: parsed } = await request(url, {
175
- ...options,
176
- headers
177
- }, policy, readBody);
178
- const onRejected = apiCsrfRejectionHandlerFor(target);
179
- if (unsafe && onRejected && res.status === 403 && apiErrorCode(parsed) === CSRF_INVALID && !isStream(options.body)) {
180
- const fresh = await onRejected().catch(() => void 0);
181
- if (fresh && fresh !== csrfToken) {
182
- headers.set(CSRF_HEADER, fresh);
183
- ({res, rawBody: parsed} = await request(url, {
184
- ...options,
185
- headers
186
- }, policy, readBody));
187
- }
188
- }
189
- if (!res.ok) {
190
- const message = `${options.method ?? "GET"} ${url} returned ${res.status}`;
191
- throw new ApiError(res.status, url, parsed, message, res.headers.get("x-request-id") || void 0);
192
- }
193
- return parsed;
194
- }
195
- /** The parsed body, or `undefined` for the spec's no-body responses. */
196
- async function readBody(res) {
197
- if ([
198
- 204,
199
- 205,
200
- 304
201
- ].includes(res.status)) return void 0;
202
- const rawBody = await res.text();
203
- return rawBody ? safeJsonParse(rawBody) : void 0;
204
- }
205
- /** The request's origin, resolved against the page for a relative URL. */
206
- function originOf(url) {
207
- try {
208
- return new URL(url, globalThis.location?.href).origin;
209
- } catch {
210
- return;
211
- }
212
- }
213
- function isStream(body) {
214
- return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
215
- }
216
- /**
217
- * `fetch` bound by a {@link RequestPolicy}, with its failures typed.
218
- *
219
- * The policy's signal, its deadline and any signal on `init` are combined, and
220
- * `read` runs under them too, so a server that sends headers and then stalls
221
- * mid-body is cut off as well. When the request does not complete:
222
- *
223
- * - a deadline fired → {@link NetworkError} with reason `timeout`;
224
- * - any other abort → the signal's own reason, rethrown untouched, because a
225
- * cancellation is the caller's decision and the caller knows what it means;
226
- * - anything else → {@link NetworkError} with reason `unreachable`.
227
- *
228
- * Exported for the few callers that need the raw {@link Response} (a
229
- * `Set-Cookie` header the generated client does not expose).
230
- */
231
- async function request(url, init, policy = {}, read) {
232
- const signals = [init.signal, policy.signal].filter((signal) => signal != null);
233
- if (policy.timeoutMs !== void 0) signals.push(AbortSignal.timeout(policy.timeoutMs));
234
- const signal = signals.length > 0 ? AbortSignal.any(signals) : void 0;
235
- const method = init.method ?? "GET";
236
- try {
237
- const res = await fetch(url, {
238
- ...init,
239
- signal
240
- });
241
- return {
242
- res,
243
- rawBody: read ? await read(res) : void 0
244
- };
245
- } catch (error) {
246
- if (signal?.aborted) {
247
- const reason = signal.reason;
248
- if (reason instanceof DOMException && reason.name === "TimeoutError") throw new NetworkError(url, "timeout", `${method} ${url} timed out`, { cause: reason });
249
- throw reason;
250
- }
251
- const code = errnoOf(error);
252
- throw new NetworkError(url, "unreachable", `${method} ${url} got no response${code ? ` (${code})` : ""}`, { cause: error });
253
- }
254
- }
255
- /**
256
- * The errno a runtime attached to a failed request, if any, for the message.
257
- * Undici nests it on `cause`, inside an `AggregateError` when it tried more
258
- * than one address. Only ever used to describe the failure, never to decide
259
- * that it was one.
260
- */
261
- function errnoOf(error) {
262
- let node = error;
263
- for (let depth = 0; depth < 4 && typeof node === "object" && node !== null; depth += 1) {
264
- const { code, errors } = node;
265
- if (typeof code === "string") return code;
266
- node = Array.isArray(errors) ? errors[0] : node.cause;
267
- }
268
- }
269
- /**
270
- * `JSON.parse` wrapped so a non-JSON body (e.g. an HTML 502 from a
271
- * proxy) becomes `{ raw: "<text>" }` instead of throwing inside
272
- * `customFetch`. The thrown `ApiError` then carries something useful
273
- * for the user to see.
274
- */
275
- function safeJsonParse(text) {
276
- try {
277
- return JSON.parse(text);
278
- } catch {
279
- return { raw: text };
280
- }
281
- }
282
- /**
283
- * The `code` of the server's `{code, message, details}` error envelope: from an
284
- * {@link ApiError}, or from a parsed response body. `undefined` when there is
285
- * none, e.g. an HTML error page from a proxy.
286
- */
287
- function apiErrorCode(errorOrBody) {
288
- const body = errorOrBody instanceof ApiError ? errorOrBody.body : errorOrBody;
289
- return isRecord(body) && typeof body.code === "string" ? body.code : void 0;
290
- }
291
- function isRecord(value) {
292
- return typeof value === "object" && value !== null && !Array.isArray(value);
293
- }
294
- //#endregion
295
- //#region ../api/dist/rolldown-runtime-D7D4PA-g.mjs
296
- var __defProp = Object.defineProperty;
297
- var __exportAll = (all, no_symbols) => {
298
- let target = {};
299
- for (var name in all) __defProp(target, name, {
300
- get: all[name],
301
- enumerable: true
302
- });
303
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
304
- return target;
305
- };
306
- //#endregion
307
- //#region ../api/dist/generated/endpoints/zitadelNextGen.mjs
308
- /**
309
- * Generated by orval 🍺
310
- * Do not edit manually.
311
- * Zitadel NextGen
312
- * This is the next generation of the Zitadel identity platform.
313
- * OpenAPI spec version: 0.0.1
314
- */
315
- var zitadelNextGen_exports = /* @__PURE__ */ __exportAll({
316
- addOrigin: () => addOrigin,
317
- beginUserPasskeyRegistration: () => beginUserPasskeyRegistration,
318
- buildRelease: () => buildRelease,
319
- completeClaim: () => completeClaim,
320
- createAuthAttempt: () => createAuthAttempt,
321
- createBranding: () => createBranding,
322
- createDeployment: () => createDeployment,
323
- createFlow: () => createFlow,
324
- createFlowDefinition: () => createFlowDefinition,
325
- createGrant: () => createGrant,
326
- createHandoff: () => createHandoff,
327
- createIdp: () => createIdp,
328
- createProject: () => createProject,
329
- createRelease: () => createRelease,
330
- createSchema: () => createSchema,
331
- createSession: () => createSession,
332
- createTeam: () => createTeam,
333
- createUser: () => createUser,
334
- deleteGrant: () => deleteGrant,
335
- deleteTeam: () => deleteTeam,
336
- deleteUserByID: () => deleteUserByID,
337
- deleteVariable: () => deleteVariable,
338
- evaluatePolicy: () => evaluatePolicy,
339
- exchangeHandoff: () => exchangeHandoff,
340
- finishUserPasskeyRegistration: () => finishUserPasskeyRegistration,
341
- getAddOriginUrl: () => getAddOriginUrl,
342
- getAuthAttempt: () => getAuthAttempt,
343
- getBeginUserPasskeyRegistrationUrl: () => getBeginUserPasskeyRegistrationUrl,
344
- getBrandingById: () => getBrandingById,
345
- getBuildReleaseUrl: () => getBuildReleaseUrl,
346
- getClaimStatus: () => getClaimStatus,
347
- getClaimWindow: () => getClaimWindow,
348
- getCompleteClaimUrl: () => getCompleteClaimUrl,
349
- getCreateAuthAttemptUrl: () => getCreateAuthAttemptUrl,
350
- getCreateBrandingUrl: () => getCreateBrandingUrl,
351
- getCreateDeploymentUrl: () => getCreateDeploymentUrl,
352
- getCreateFlowDefinitionUrl: () => getCreateFlowDefinitionUrl,
353
- getCreateFlowUrl: () => getCreateFlowUrl,
354
- getCreateGrantUrl: () => getCreateGrantUrl,
355
- getCreateHandoffUrl: () => getCreateHandoffUrl,
356
- getCreateIdpUrl: () => getCreateIdpUrl,
357
- getCreateProjectUrl: () => getCreateProjectUrl,
358
- getCreateReleaseUrl: () => getCreateReleaseUrl,
359
- getCreateSchemaUrl: () => getCreateSchemaUrl,
360
- getCreateSessionUrl: () => getCreateSessionUrl,
361
- getCreateTeamUrl: () => getCreateTeamUrl,
362
- getCreateUserUrl: () => getCreateUserUrl,
363
- getDeleteGrantUrl: () => getDeleteGrantUrl,
364
- getDeleteTeamUrl: () => getDeleteTeamUrl,
365
- getDeleteUserByIDUrl: () => getDeleteUserByIDUrl,
366
- getDeleteVariableUrl: () => getDeleteVariableUrl,
367
- getDeploymentById: () => getDeploymentById,
368
- getDeploymentVariables: () => getDeploymentVariables,
369
- getEvaluatePolicyUrl: () => getEvaluatePolicyUrl,
370
- getEvent: () => getEvent,
371
- getExchangeHandoffUrl: () => getExchangeHandoffUrl,
372
- getFinishUserPasskeyRegistrationUrl: () => getFinishUserPasskeyRegistrationUrl,
373
- getFlowDefinition: () => getFlowDefinition,
374
- getFlowStep: () => getFlowStep,
375
- getGetAuthAttemptUrl: () => getGetAuthAttemptUrl,
376
- getGetBrandingByIdUrl: () => getGetBrandingByIdUrl,
377
- getGetClaimStatusUrl: () => getGetClaimStatusUrl,
378
- getGetClaimWindowUrl: () => getGetClaimWindowUrl,
379
- getGetDeploymentByIdUrl: () => getGetDeploymentByIdUrl,
380
- getGetDeploymentVariablesUrl: () => getGetDeploymentVariablesUrl,
381
- getGetEventUrl: () => getGetEventUrl,
382
- getGetFlowDefinitionUrl: () => getGetFlowDefinitionUrl,
383
- getGetFlowStepUrl: () => getGetFlowStepUrl,
384
- getGetGrantUrl: () => getGetGrantUrl,
385
- getGetIdpByIdUrl: () => getGetIdpByIdUrl,
386
- getGetIdpRevisionByIdUrl: () => getGetIdpRevisionByIdUrl,
387
- getGetLiveUrl: () => getGetLiveUrl,
388
- getGetMyPasswordStateUrl: () => getGetMyPasswordStateUrl,
389
- getGetMySessionCsrfTokenUrl: () => getGetMySessionCsrfTokenUrl,
390
- getGetMySessionUrl: () => getGetMySessionUrl,
391
- getGetMyUserSchemaUrl: () => getGetMyUserSchemaUrl,
392
- getGetMyUserUrl: () => getGetMyUserUrl,
393
- getGetPolicyRevisionUrl: () => getGetPolicyRevisionUrl,
394
- getGetPolicyUrl: () => getGetPolicyUrl,
395
- getGetProjectUrl: () => getGetProjectUrl,
396
- getGetReadyUrl: () => getGetReadyUrl,
397
- getGetReleaseByIdUrl: () => getGetReleaseByIdUrl,
398
- getGetSchemaByIdUrl: () => getGetSchemaByIdUrl,
399
- getGetSessionUrl: () => getGetSessionUrl,
400
- getGetTeamUrl: () => getGetTeamUrl,
401
- getGetUserByIDUrl: () => getGetUserByIDUrl,
402
- getGetUserPasswordStateUrl: () => getGetUserPasswordStateUrl,
403
- getGetVariableUrl: () => getGetVariableUrl,
404
- getGetVariablesUrl: () => getGetVariablesUrl,
405
- getGrant: () => getGrant,
406
- getIdpById: () => getIdpById,
407
- getIdpRevisionById: () => getIdpRevisionById,
408
- getInitClaimUrl: () => getInitClaimUrl,
409
- getIssueChallengeUrl: () => getIssueChallengeUrl,
410
- getListBrandingUrl: () => getListBrandingUrl,
411
- getListDeploymentsUrl: () => getListDeploymentsUrl,
412
- getListEventsUrl: () => getListEventsUrl,
413
- getListFlowDefinitionsUrl: () => getListFlowDefinitionsUrl,
414
- getListIdpRevisionsUrl: () => getListIdpRevisionsUrl,
415
- getListMyIdentityLinksUrl: () => getListMyIdentityLinksUrl,
416
- getListMyPasskeysUrl: () => getListMyPasskeysUrl,
417
- getListMyProjectsUrl: () => getListMyProjectsUrl,
418
- getListMyTeamsUrl: () => getListMyTeamsUrl,
419
- getListPoliciesUrl: () => getListPoliciesUrl,
420
- getListPolicyRevisionsUrl: () => getListPolicyRevisionsUrl,
421
- getListPreviewsUrl: () => getListPreviewsUrl,
422
- getListProjectAdminsUrl: () => getListProjectAdminsUrl,
423
- getListReleasesUrl: () => getListReleasesUrl,
424
- getListSchemasUrl: () => getListSchemasUrl,
425
- getListUserIdentityLinksUrl: () => getListUserIdentityLinksUrl,
426
- getListUserPasskeysUrl: () => getListUserPasskeysUrl,
427
- getListUserTeamsUrl: () => getListUserTeamsUrl,
428
- getLive: () => getLive,
429
- getMyPasswordState: () => getMyPasswordState,
430
- getMySession: () => getMySession,
431
- getMySessionCsrfToken: () => getMySessionCsrfToken,
432
- getMyUser: () => getMyUser,
433
- getMyUserSchema: () => getMyUserSchema,
434
- getPatchMyUserUrl: () => getPatchMyUserUrl,
435
- getPatchProjectUrl: () => getPatchProjectUrl,
436
- getPatchUserByIDUrl: () => getPatchUserByIDUrl,
437
- getPolicy: () => getPolicy,
438
- getPolicyRevision: () => getPolicyRevision,
439
- getProject: () => getProject,
440
- getPublishPolicyUrl: () => getPublishPolicyUrl,
441
- getQueryGrantsUrl: () => getQueryGrantsUrl,
442
- getQueryIdpsUrl: () => getQueryIdpsUrl,
443
- getQueryProjectsUrl: () => getQueryProjectsUrl,
444
- getQuerySessionsUrl: () => getQuerySessionsUrl,
445
- getQueryTeamsUrl: () => getQueryTeamsUrl,
446
- getQueryUsersUrl: () => getQueryUsersUrl,
447
- getReady: () => getReady,
448
- getReleaseById: () => getReleaseById,
449
- getRemoveOriginUrl: () => getRemoveOriginUrl,
450
- getRemovePreviewUrl: () => getRemovePreviewUrl,
451
- getRevokeMySessionUrl: () => getRevokeMySessionUrl,
452
- getRevokeReleaseUrl: () => getRevokeReleaseUrl,
453
- getRevokeSessionUrl: () => getRevokeSessionUrl,
454
- getRollbackDeploymentUrl: () => getRollbackDeploymentUrl,
455
- getSchemaById: () => getSchemaById,
456
- getSession: () => getSession,
457
- getSetUserPasswordUrl: () => getSetUserPasswordUrl,
458
- getSubmitFlowStepUrl: () => getSubmitFlowStepUrl,
459
- getTeam: () => getTeam,
460
- getUpdateTeamUrl: () => getUpdateTeamUrl,
461
- getUpdateVariablesUrl: () => getUpdateVariablesUrl,
462
- getUserByID: () => getUserByID,
463
- getUserPasswordState: () => getUserPasswordState,
464
- getVariable: () => getVariable,
465
- getVariables: () => getVariables,
466
- getVerifyChallengeProofUrl: () => getVerifyChallengeProofUrl,
467
- initClaim: () => initClaim,
468
- issueChallenge: () => issueChallenge,
469
- listBranding: () => listBranding,
470
- listDeployments: () => listDeployments,
471
- listEvents: () => listEvents,
472
- listFlowDefinitions: () => listFlowDefinitions,
473
- listIdpRevisions: () => listIdpRevisions,
474
- listMyIdentityLinks: () => listMyIdentityLinks,
475
- listMyPasskeys: () => listMyPasskeys,
476
- listMyProjects: () => listMyProjects,
477
- listMyTeams: () => listMyTeams,
478
- listPolicies: () => listPolicies,
479
- listPolicyRevisions: () => listPolicyRevisions,
480
- listPreviews: () => listPreviews,
481
- listProjectAdmins: () => listProjectAdmins,
482
- listReleases: () => listReleases,
483
- listSchemas: () => listSchemas,
484
- listUserIdentityLinks: () => listUserIdentityLinks,
485
- listUserPasskeys: () => listUserPasskeys,
486
- listUserTeams: () => listUserTeams,
487
- patchMyUser: () => patchMyUser,
488
- patchProject: () => patchProject,
489
- patchUserByID: () => patchUserByID,
490
- publishPolicy: () => publishPolicy,
491
- queryGrants: () => queryGrants,
492
- queryIdps: () => queryIdps,
493
- queryProjects: () => queryProjects,
494
- querySessions: () => querySessions,
495
- queryTeams: () => queryTeams,
496
- queryUsers: () => queryUsers,
497
- removeOrigin: () => removeOrigin,
498
- removePreview: () => removePreview,
499
- revokeMySession: () => revokeMySession,
500
- revokeRelease: () => revokeRelease,
501
- revokeSession: () => revokeSession,
502
- rollbackDeployment: () => rollbackDeployment,
503
- setUserPassword: () => setUserPassword,
504
- submitFlowStep: () => submitFlowStep,
505
- updateTeam: () => updateTeam,
506
- updateVariables: () => updateVariables,
507
- verifyChallengeProof: () => verifyChallengeProof
508
- });
509
- const getGetLiveUrl = () => {
510
- return `${getProxyPath()}/livez`;
511
- };
512
- /**
513
- * Answers `ok` while the server process serves HTTP, and checks nothing behind it.
514
- *
515
- * Point a liveness probe here. It never checks the database, so an outage
516
- * of the database does not restart every instance; `GET /readyz` takes an
517
- * instance out of rotation instead.
518
- * @summary Check server liveness
519
- */
520
- const getLive = async (options) => {
521
- return customFetch(getGetLiveUrl(), {
522
- ...options,
523
- method: "GET"
524
- });
525
- };
526
- const getGetReadyUrl = () => {
527
- return `${getProxyPath()}/readyz`;
528
- };
529
- /**
530
- * Answers whether the server can serve requests, which takes its database answering within a second.
531
- *
532
- * Point a readiness probe here, so that a server whose database does not
533
- * answer gets no requests until it does. The check is one round trip to the
534
- * database.
535
- * @summary Check server readiness
536
- */
537
- const getReady = async (options) => {
538
- return customFetch(getGetReadyUrl(), {
539
- ...options,
540
- method: "GET"
541
- });
542
- };
543
- const getCreateUserUrl = (params) => {
544
- const normalizedParams = new URLSearchParams();
545
- Object.entries(params || {}).forEach(([key, value]) => {
546
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
547
- });
548
- const stringifiedParams = normalizedParams.toString();
549
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users?${stringifiedParams}` : `${getProxyPath()}/users`;
550
- };
551
- /**
552
- * Creates a user whose attributes satisfy the user schema the request names.
553
- *
554
- * The server assigns the user's id. With `team_id`, the user also becomes an
555
- * active member of that team. A value the schema marks unique that another
556
- * user already holds is refused with `409`.
557
- * @summary Create user
558
- */
559
- const createUser = async (createUserBody, params, options) => {
560
- const getHeaders = (h) => {
561
- if (!h) return {};
562
- if (h instanceof Headers) return Object.fromEntries(h.entries());
563
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
564
- const headers = {};
565
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
566
- return headers;
567
- };
568
- return customFetch(getCreateUserUrl(params), {
569
- ...options,
570
- method: "POST",
571
- headers: {
572
- "Content-Type": "application/json",
573
- ...getHeaders(options?.headers)
574
- },
575
- body: JSON.stringify(createUserBody)
576
- });
577
- };
578
- const getQueryUsersUrl = (params) => {
579
- const normalizedParams = new URLSearchParams();
580
- Object.entries(params || {}).forEach(([key, value]) => {
581
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
582
- });
583
- const stringifiedParams = normalizedParams.toString();
584
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/query?${stringifiedParams}` : `${getProxyPath()}/users/query`;
585
- };
586
- /**
587
- * Returns the users of a project, paginated with a cursor.
588
- *
589
- * `project_id` names the project to list; without it, the credential's own
590
- * project is listed.
591
- *
592
- * Accepts either a project secret (`oauth2`) or a user-bound Console
593
- * session cookie (`nextgenSession`). Cookie-authenticated requests
594
- * follow the scheme's CSRF rules (`nextgenSession`).
595
- * @summary Query users
596
- */
597
- const queryUsers = async (queryUsersBody, params, options) => {
598
- const getHeaders = (h) => {
599
- if (!h) return {};
600
- if (h instanceof Headers) return Object.fromEntries(h.entries());
601
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
602
- const headers = {};
603
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
604
- return headers;
605
- };
606
- return customFetch(getQueryUsersUrl(params), {
607
- ...options,
608
- method: "POST",
609
- headers: {
610
- "Content-Type": "application/json",
611
- ...getHeaders(options?.headers)
612
- },
613
- body: JSON.stringify(queryUsersBody)
614
- });
615
- };
616
- const getGetUserByIDUrl = (userId, params) => {
617
- const normalizedParams = new URLSearchParams();
618
- Object.entries(params || {}).forEach(([key, value]) => {
619
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
620
- });
621
- const stringifiedParams = normalizedParams.toString();
622
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/${encodeURIComponent(String(userId))}?${stringifiedParams}` : `${getProxyPath()}/users/${encodeURIComponent(String(userId))}`;
623
- };
624
- /**
625
- * Returns a user by its id, with the attributes its schema defines.
626
- *
627
- * With `team_id`, the user is returned only while they are an active member of
628
- * that team.
629
- * @summary Get user by ID
630
- */
631
- const getUserByID = async (userId, params, options) => {
632
- return customFetch(getGetUserByIDUrl(userId, params), {
633
- ...options,
634
- method: "GET"
635
- });
636
- };
637
- const getPatchUserByIDUrl = (userId) => {
638
- return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}`;
639
- };
640
- /**
641
- * Partially updates a user's schema-defined attributes, and optionally
642
- * moves the user to another registered schema. The merged result is
643
- * validated against the schema before commit. Concurrent writes are
644
- * last-write-wins.
645
- * @summary Update user by ID
646
- */
647
- const patchUserByID = async (userId, patchUserByIDBody, options) => {
648
- const getHeaders = (h) => {
649
- if (!h) return {};
650
- if (h instanceof Headers) return Object.fromEntries(h.entries());
651
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
652
- const headers = {};
653
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
654
- return headers;
655
- };
656
- return customFetch(getPatchUserByIDUrl(userId), {
657
- ...options,
658
- method: "PATCH",
659
- headers: {
660
- "Content-Type": "application/json",
661
- ...getHeaders(options?.headers)
662
- },
663
- body: JSON.stringify(patchUserByIDBody)
664
- });
665
- };
666
- const getDeleteUserByIDUrl = (userId) => {
667
- return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}`;
668
- };
669
- /**
670
- * Deletes a user, removes them from every team they belong to, and revokes
671
- * every grant they hold, on any project.
672
- *
673
- * The user is removed, not deactivated, and the deletion emits `user.deleted`,
674
- * plus `authz.revoked` for each grant on that grant's project.
675
- * With a project secret the request is idempotent: deleting a user that exists
676
- * in no project succeeds without changing anything.
677
- * @summary Delete user by ID
678
- */
679
- const deleteUserByID = async (userId, options) => {
680
- return customFetch(getDeleteUserByIDUrl(userId), {
681
- ...options,
682
- method: "DELETE"
683
- });
684
- };
685
- const getListUserIdentityLinksUrl = (userId, params) => {
686
- const normalizedParams = new URLSearchParams();
687
- Object.entries(params || {}).forEach(([key, value]) => {
688
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
689
- });
690
- const stringifiedParams = normalizedParams.toString();
691
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/identity_links?${stringifiedParams}` : `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/identity_links`;
692
- };
693
- /**
694
- * The identity provider accounts a sign-in linked to the user, oldest first.
695
- * The provider's subject and claims are never returned.
696
- * @summary List the provider accounts linked to a user
697
- */
698
- const listUserIdentityLinks = async (userId, params, options) => {
699
- return customFetch(getListUserIdentityLinksUrl(userId, params), {
700
- ...options,
701
- method: "GET"
702
- });
703
- };
704
- const getListUserPasskeysUrl = (userId, params) => {
705
- const normalizedParams = new URLSearchParams();
706
- Object.entries(params || {}).forEach(([key, value]) => {
707
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
708
- });
709
- const stringifiedParams = normalizedParams.toString();
710
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/passkeys?${stringifiedParams}` : `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/passkeys`;
711
- };
712
- /**
713
- * Returns the passkeys registered for a user, newest first, paginated with a
714
- * cursor.
715
- *
716
- * Each passkey carries its id, its name and when it was registered, never the
717
- * credential itself.
718
- * @summary List user passkeys
719
- */
720
- const listUserPasskeys = async (userId, params, options) => {
721
- return customFetch(getListUserPasskeysUrl(userId, params), {
722
- ...options,
723
- method: "GET"
724
- });
725
- };
726
- const getBeginUserPasskeyRegistrationUrl = (userId) => {
727
- return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/passkeys/registrations`;
728
- };
729
- /**
730
- * Starts a WebAuthn registration ceremony for the user and returns the
731
- * creation options for `navigator.credentials.create()`. Complete the
732
- * ceremony with `POST /users/{user_id}/passkeys/registrations/{registration_id}` within
733
- * five minutes. Credentials already registered for the user are excluded
734
- * automatically.
735
- * @summary Begin passkey registration
736
- */
737
- const beginUserPasskeyRegistration = async (userId, beginUserPasskeyRegistrationBody, options) => {
738
- const getHeaders = (h) => {
739
- if (!h) return {};
740
- if (h instanceof Headers) return Object.fromEntries(h.entries());
741
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
742
- const headers = {};
743
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
744
- return headers;
745
- };
746
- return customFetch(getBeginUserPasskeyRegistrationUrl(userId), {
747
- ...options,
748
- method: "POST",
749
- headers: {
750
- "Content-Type": "application/json",
751
- ...getHeaders(options?.headers)
752
- },
753
- body: JSON.stringify(beginUserPasskeyRegistrationBody)
754
- });
755
- };
756
- const getFinishUserPasskeyRegistrationUrl = (userId, registrationId) => {
757
- return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/passkeys/registrations/${encodeURIComponent(String(registrationId))}`;
758
- };
759
- /**
760
- * Verifies the attestation against the ceremony started by
761
- * `POST /users/{user_id}/passkeys/registrations` and persists the new credential. A
762
- * rejected attestation counts against the ceremony's failure budget and the
763
- * ceremony stays open for a retry. An expired ceremony surfaces as
764
- * `att.stale_challenge`; an unknown or already-consumed registration id
765
- * surfaces as `att.not_found`.
766
- * @summary Finish passkey registration
767
- */
768
- const finishUserPasskeyRegistration = async (userId, registrationId, finishUserPasskeyRegistrationBody, options) => {
769
- const getHeaders = (h) => {
770
- if (!h) return {};
771
- if (h instanceof Headers) return Object.fromEntries(h.entries());
772
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
773
- const headers = {};
774
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
775
- return headers;
776
- };
777
- return customFetch(getFinishUserPasskeyRegistrationUrl(userId, registrationId), {
778
- ...options,
779
- method: "POST",
780
- headers: {
781
- "Content-Type": "application/json",
782
- ...getHeaders(options?.headers)
783
- },
784
- body: JSON.stringify(finishUserPasskeyRegistrationBody)
785
- });
786
- };
787
- const getGetUserPasswordStateUrl = (userId) => {
788
- return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/password`;
789
- };
790
- /**
791
- * Reports when the user's current password was set, and leaves `set_at` out
792
- * when the user has none. The password and its hash are never returned;
793
- * setting one is `PUT` on the same path.
794
- * @summary Get user password state
795
- */
796
- const getUserPasswordState = async (userId, options) => {
797
- return customFetch(getGetUserPasswordStateUrl(userId), {
798
- ...options,
799
- method: "GET"
800
- });
801
- };
802
- const getSetUserPasswordUrl = (userId) => {
803
- return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/password`;
804
- };
805
- /**
806
- * Sets a user's password, hashed with the project's current password hashing
807
- * policy.
808
- *
809
- * The new password replaces the current one, and setting it emits
810
- * `auth.factor.password.set`.
811
- * @summary Set user password
812
- */
813
- const setUserPassword = async (userId, setUserPasswordBody, options) => {
814
- const getHeaders = (h) => {
815
- if (!h) return {};
816
- if (h instanceof Headers) return Object.fromEntries(h.entries());
817
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
818
- const headers = {};
819
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
820
- return headers;
821
- };
822
- return customFetch(getSetUserPasswordUrl(userId), {
823
- ...options,
824
- method: "PUT",
825
- headers: {
826
- "Content-Type": "application/json",
827
- ...getHeaders(options?.headers)
828
- },
829
- body: JSON.stringify(setUserPasswordBody)
830
- });
831
- };
832
- const getListUserTeamsUrl = (userId, params) => {
833
- const normalizedParams = new URLSearchParams();
834
- Object.entries(params || {}).forEach(([key, value]) => {
835
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
836
- });
837
- const stringifiedParams = normalizedParams.toString();
838
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/teams?${stringifiedParams}` : `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/teams`;
839
- };
840
- /**
841
- * The user's team roster, ordered by team name. Each entry carries the
842
- * team's name, so a client renders a page without resolving ids one by one.
843
- *
844
- * This is the N:N roster and it is not lifecycle ownership: the single team
845
- * that owns the user's lifecycle is reported as `metadata.lifecycle_owner_team_id`
846
- * on the user read endpoints. Memberships the user was removed from are not
847
- * returned.
848
- * @summary List the teams a user belongs to
849
- */
850
- const listUserTeams = async (userId, params, options) => {
851
- return customFetch(getListUserTeamsUrl(userId, params), {
852
- ...options,
853
- method: "GET"
854
- });
855
- };
856
- const getGetMyUserUrl = (params) => {
857
- const normalizedParams = new URLSearchParams();
858
- Object.entries(params || {}).forEach(([key, value]) => {
859
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
860
- });
861
- const stringifiedParams = normalizedParams.toString();
862
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me?${stringifiedParams}` : `${getProxyPath()}/users/me`;
863
- };
864
- /**
865
- * Returns the user signed in to the session that authenticates the request.
866
- *
867
- * The project and the user both come from the session cookie, so a caller only
868
- * ever reads their own user.
869
- *
870
- * With `project_id`, the user is returned only when the session belongs to
871
- * that project.
872
- * @summary Get my user information
873
- */
874
- const getMyUser = async (params, options) => {
875
- return customFetch(getGetMyUserUrl(params), {
876
- ...options,
877
- method: "GET"
878
- });
879
- };
880
- const getPatchMyUserUrl = (params) => {
881
- const normalizedParams = new URLSearchParams();
882
- Object.entries(params || {}).forEach(([key, value]) => {
883
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
884
- });
885
- const stringifiedParams = normalizedParams.toString();
886
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me?${stringifiedParams}` : `${getProxyPath()}/users/me`;
887
- };
888
- /**
889
- * Partially updates the caller's own schema-defined attributes. The merged
890
- * result is validated against the user's schema before commit. Concurrent
891
- * writes are last-write-wins.
892
- *
893
- * With `project_id`, the user is updated only when the session belongs to
894
- * that project.
895
- * @summary Update my user information
896
- */
897
- const patchMyUser = async (patchMyUserBody, params, options) => {
898
- const getHeaders = (h) => {
899
- if (!h) return {};
900
- if (h instanceof Headers) return Object.fromEntries(h.entries());
901
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
902
- const headers = {};
903
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
904
- return headers;
905
- };
906
- return customFetch(getPatchMyUserUrl(params), {
907
- ...options,
908
- method: "PATCH",
909
- headers: {
910
- "Content-Type": "application/json",
911
- ...getHeaders(options?.headers)
912
- },
913
- body: JSON.stringify(patchMyUserBody)
914
- });
915
- };
916
- const getListMyIdentityLinksUrl = (params) => {
917
- const normalizedParams = new URLSearchParams();
918
- Object.entries(params || {}).forEach(([key, value]) => {
919
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
920
- });
921
- const stringifiedParams = normalizedParams.toString();
922
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/identity_links?${stringifiedParams}` : `${getProxyPath()}/users/me/identity_links`;
923
- };
924
- /**
925
- * The identity provider accounts a sign-in linked to the signed-in user,
926
- * oldest first. The provider's subject and claims are never returned.
927
- *
928
- * With `project_id`, the links are listed only when the session belongs to
929
- * that project.
930
- * @summary List the provider accounts linked to me
931
- */
932
- const listMyIdentityLinks = async (params, options) => {
933
- return customFetch(getListMyIdentityLinksUrl(params), {
934
- ...options,
935
- method: "GET"
936
- });
937
- };
938
- const getListMyPasskeysUrl = (params) => {
939
- const normalizedParams = new URLSearchParams();
940
- Object.entries(params || {}).forEach(([key, value]) => {
941
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
942
- });
943
- const stringifiedParams = normalizedParams.toString();
944
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/passkeys?${stringifiedParams}` : `${getProxyPath()}/users/me/passkeys`;
945
- };
946
- /**
947
- * The signed-in user's own passkeys, newest first, paginated with a cursor.
948
- * Each passkey carries its id, its name and when it was registered, never the
949
- * credential itself.
950
- *
951
- * With `project_id`, the passkeys are listed only when the session belongs to
952
- * that project.
953
- * @summary List my passkeys
954
- */
955
- const listMyPasskeys = async (params, options) => {
956
- return customFetch(getListMyPasskeysUrl(params), {
957
- ...options,
958
- method: "GET"
959
- });
960
- };
961
- const getGetMyPasswordStateUrl = (params) => {
962
- const normalizedParams = new URLSearchParams();
963
- Object.entries(params || {}).forEach(([key, value]) => {
964
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
965
- });
966
- const stringifiedParams = normalizedParams.toString();
967
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/password?${stringifiedParams}` : `${getProxyPath()}/users/me/password`;
968
- };
969
- /**
970
- * Reports when the signed-in user's current password was set, and leaves
971
- * `set_at` out when they have none. The password and its hash are never
972
- * returned.
973
- *
974
- * With `project_id`, the state is read only when the session belongs to that
975
- * project.
976
- * @summary Get my password state
977
- */
978
- const getMyPasswordState = async (params, options) => {
979
- return customFetch(getGetMyPasswordStateUrl(params), {
980
- ...options,
981
- method: "GET"
982
- });
983
- };
984
- const getListMyProjectsUrl = (params) => {
985
- const normalizedParams = new URLSearchParams();
986
- Object.entries(params || {}).forEach(([key, value]) => {
987
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
988
- });
989
- const stringifiedParams = normalizedParams.toString();
990
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/projects?${stringifiedParams}` : `${getProxyPath()}/users/me/projects`;
991
- };
992
- /**
993
- * The projects the signed-in user can act on: those they hold an active grant
994
- * on, either directly or through a team they are a member of. For a platform
995
- * operator (ADR 075) that is every project of the deployment. Ordered by
996
- * project id and paged with an opaque cursor.
997
- *
998
- * This is not the same question as `queryProjects`, which answers with the one
999
- * project the calling credential is bound to. Here the session is the caller
1000
- * and the grants are the answer, so the list spans projects.
1001
- *
1002
- * With `name_contains`, only the projects whose name contains that text are
1003
- * listed. The search runs on the server together with the grants, so it
1004
- * reaches every project the user can act on, however many there are, and
1005
- * pages like the full list.
1006
- *
1007
- * With `project_id`, the projects are listed only when the session belongs to
1008
- * that project. It names the project the session was signed in to, not one to
1009
- * list.
1010
- * @summary List the projects I can act on
1011
- */
1012
- const listMyProjects = async (params, options) => {
1013
- return customFetch(getListMyProjectsUrl(params), {
1014
- ...options,
1015
- method: "GET"
1016
- });
1017
- };
1018
- const getGetMyUserSchemaUrl = (params) => {
1019
- const normalizedParams = new URLSearchParams();
1020
- Object.entries(params || {}).forEach(([key, value]) => {
1021
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1022
- });
1023
- const stringifiedParams = normalizedParams.toString();
1024
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/schema?${stringifiedParams}` : `${getProxyPath()}/users/me/schema`;
1025
- };
1026
- /**
1027
- * The schema the signed-in user's own record is validated against.
1028
- *
1029
- * With `project_id`, the schema is returned only when the session belongs to
1030
- * that project.
1031
- * @summary Get my user schema
1032
- */
1033
- const getMyUserSchema = async (params, options) => {
1034
- return customFetch(getGetMyUserSchemaUrl(params), {
1035
- ...options,
1036
- method: "GET"
1037
- });
1038
- };
1039
- const getListMyTeamsUrl = (params) => {
1040
- const normalizedParams = new URLSearchParams();
1041
- Object.entries(params || {}).forEach(([key, value]) => {
1042
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1043
- });
1044
- const stringifiedParams = normalizedParams.toString();
1045
- return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/teams?${stringifiedParams}` : `${getProxyPath()}/users/me/teams`;
1046
- };
1047
- /**
1048
- * The signed-in user's own team roster, ordered by team name.
1049
- *
1050
- * With `project_id`, the teams are listed only when the session belongs to
1051
- * that project.
1052
- * @summary List the teams I belong to
1053
- */
1054
- const listMyTeams = async (params, options) => {
1055
- return customFetch(getListMyTeamsUrl(params), {
1056
- ...options,
1057
- method: "GET"
1058
- });
1059
- };
1060
- const getCreateFlowUrl = () => {
1061
- return `${getProxyPath()}/flow`;
1062
- };
1063
- /**
1064
- * Resolves a flow definition based on purpose + audience context and returns
1065
- * the first capability step. Creates a new session implicitly unless
1066
- * `session_id` is provided, together with that session's `session_token`
1067
- * (for step-up / reauth on an existing session).
1068
- *
1069
- * The browser `Origin` header selects which deployment serves this attempt:
1070
- * the gate admits the origin against the project's origin patterns and live
1071
- * previews, the newest deployment to that exact origin is the target, and
1072
- * that deployment's release supplies flow definitions, user schemas and
1073
- * branding. The resolved deployment is sealed into the `_zflow` cookie so
1074
- * later steps keep the same configuration. An origin that matches no pattern
1075
- * answers `403` with `proj.origin_not_allowed`; one that matches a preview
1076
- * pattern with no live preview answers `403` with `proj.preview_not_live`;
1077
- * nothing deployed to the target answers `409` with `rel.not_deployed`; a
1078
- * revoked release answers `409` with `rel.revoked`. A request with no
1079
- * `Origin` passes the gate and still needs a deployment target. A loopback
1080
- * origin passes it too, and so does the server's own origin, from which its
1081
- * console previews a project's login; a step submitted from the server's
1082
- * own origin is still refused unless the project lists it.
1083
- *
1084
- * The response contains an `id` field — the flow handle. Use it as the path
1085
- * parameter for all subsequent `/flow/{id}/submit` calls.
1086
- *
1087
- * The response also sets an encrypted `HttpOnly` cookie (`_zflow`) containing
1088
- * the flow's orchestration state (current step, collected data, history).
1089
- * The server is stateless between requests — all flow state lives in this
1090
- * cookie. The browser sends it automatically on subsequent requests.
1091
- * @summary Start a new flow
1092
- */
1093
- const createFlow = async (createFlowBody, options) => {
1094
- const getHeaders = (h) => {
1095
- if (!h) return {};
1096
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1097
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1098
- const headers = {};
1099
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1100
- return headers;
1101
- };
1102
- return customFetch(getCreateFlowUrl(), {
1103
- ...options,
1104
- method: "POST",
1105
- headers: {
1106
- "Content-Type": "application/json",
1107
- ...getHeaders(options?.headers)
1108
- },
1109
- body: JSON.stringify(createFlowBody)
1110
- });
1111
- };
1112
- const getGetFlowStepUrl = (id) => {
1113
- return `${getProxyPath()}/flow/${encodeURIComponent(String(id))}`;
1114
- };
1115
- /**
1116
- * Returns the current capability step without advancing the state machine.
1117
- * Useful for page reloads or re-rendering after a network error.
1118
- *
1119
- * Reuses the deployment sealed into `_zflow` at `createFlow`; it does not
1120
- * re-resolve from `Origin`. If that release was revoked since the attempt
1121
- * started, the response is `409` with `rel.revoked`.
1122
- * @summary Get current step (re-render)
1123
- */
1124
- const getFlowStep = async (id, options) => {
1125
- return customFetch(getGetFlowStepUrl(id), {
1126
- ...options,
1127
- method: "GET"
1128
- });
1129
- };
1130
- const getSubmitFlowStepUrl = (id) => {
1131
- return `${getProxyPath()}/flow/${encodeURIComponent(String(id))}/submit`;
1132
- };
1133
- /**
1134
- * Submits user input for the current step. The server validates,
1135
- * processes (e.g., verifies a credential), advances the state machine
1136
- * through any invisible steps, and returns the next visible step.
1137
- *
1138
- * The response sets an updated encrypted `HttpOnly` cookie (`_zflow`)
1139
- * with the new flow state. The server is stateless — all orchestration
1140
- * state is carried in this cookie between requests.
1141
- *
1142
- * **Important:** The `id` in the response may differ from the `id` used in
1143
- * the request. This happens when a flow pivots (pushes a new flow onto the
1144
- * stack) or when a stacked flow completes (auto-pops to the parent flow).
1145
- * Always use the `id` from the latest response for the next request.
1146
- *
1147
- * ## Flow completion
1148
- *
1149
- * When `step.type` is `complete`, the flow is terminal. The `step.behavior`
1150
- * field tells the frontend what to do:
1151
- *
1152
- * | `behavior` | Action |
1153
- * |------------- |------------------------------------------------------------|
1154
- * | `redirect` | Navigate to `redirect_uri` (OIDC/SAML auth request done). |
1155
- * | `show` | Render the step as a success screen (e.g., registration). |
1156
- *
1157
- * A `complete` step is only returned when the **entire flow stack** is done.
1158
- * If a stacked flow (e.g., recovery pivoted from login) finishes, the server
1159
- * auto-pops to the parent flow and returns the parent's next step — the
1160
- * frontend never sees a `complete` for intermediate flows.
1161
- *
1162
- * ## External sign-in
1163
- *
1164
- * `{action: "sso", sso_provider_id, return_target}` on a step that offers
1165
- * `sso_providers` returns the engine-emitted `sso-redirect` step, whose
1166
- * `redirect_url` the frontend navigates to.
1167
- *
1168
- * - The flow state does not change, but `_zflow` is re-sealed like on
1169
- * every response, so its ten-minute window restarts at this submission;
1170
- * the external sign-in and the return must complete within it.
1171
- * - A second `Set-Cookie` line carries the browser-binding cookie the
1172
- * callback checks: `HttpOnly`, `Path=/`, `SameSite=Lax`.
1173
- * - On every host except http loopback it is `__Host-_zsso` with `Secure`.
1174
- * - When the request host is http loopback (local development, where
1175
- * Safari rejects `Secure`), it is `_zsso` with no `Secure`; the
1176
- * `__Host-` prefix is dropped because it requires `Secure`.
1177
- *
1178
- * A connection whose `client_id` is a `${{ NAME }}` reference has it filled
1179
- * from the project's variables. A provider the engine cannot start a
1180
- * sign-in with, including a reference with no variable behind it,
1181
- * re-renders the step with `error.sso_unavailable`.
1182
- *
1183
- * Reuses the deployment sealed into `_zflow` at `createFlow`; it does not
1184
- * re-resolve from `Origin`. If that release was revoked since the attempt
1185
- * started, the response is `409` with `rel.revoked`.
1186
- * @summary Submit step data and advance
1187
- */
1188
- const submitFlowStep = async (id, submitFlowStepBody, options) => {
1189
- const getHeaders = (h) => {
1190
- if (!h) return {};
1191
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1192
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1193
- const headers = {};
1194
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1195
- return headers;
1196
- };
1197
- return customFetch(getSubmitFlowStepUrl(id), {
1198
- ...options,
1199
- method: "POST",
1200
- headers: {
1201
- "Content-Type": "application/json",
1202
- ...getHeaders(options?.headers)
1203
- },
1204
- body: JSON.stringify(submitFlowStepBody)
1205
- });
1206
- };
1207
- const getCreateAuthAttemptUrl = () => {
1208
- return `${getProxyPath()}/auth_attempts`;
1209
- };
1210
- /**
1211
- * Starts a new authentication attempt. This is the entry point for the auth_attempts state machine.
1212
- *
1213
- * An attempt is an ephemeral (15-minute TTL) state machine that drives a single authentication round.
1214
- * It accepts factor challenges, verifies proofs, and completes into a session or handoff token.
1215
- *
1216
- * Accepts a project_id and challenge_nonce (from POST /bootstrap/challenge). For step-up re-auth,
1217
- * also include session_id and that session's session_token to add factors to an existing session.
1218
- *
1219
- * The project comes from the project secret. A body `project_id` that disagrees
1220
- * answers `403` with `proj.mismatch`. Sealed `deployment_id` / `release_id` are
1221
- * filled only when create runs with a runtime resolution already on the
1222
- * context (the flow create path); this HTTP entry point does not resolve
1223
- * Origin or refuse a revoked release itself.
1224
- * @summary Create a new authentication attempt
1225
- */
1226
- const createAuthAttempt = async (createAuthAttemptBody, options) => {
1227
- const getHeaders = (h) => {
1228
- if (!h) return {};
1229
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1230
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1231
- const headers = {};
1232
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1233
- return headers;
1234
- };
1235
- return customFetch(getCreateAuthAttemptUrl(), {
1236
- ...options,
1237
- method: "POST",
1238
- headers: {
1239
- "Content-Type": "application/json",
1240
- ...getHeaders(options?.headers)
1241
- },
1242
- body: JSON.stringify(createAuthAttemptBody)
1243
- });
1244
- };
1245
- const getGetAuthAttemptUrl = (attemptId) => {
1246
- return `${getProxyPath()}/auth_attempts/${encodeURIComponent(String(attemptId))}`;
1247
- };
1248
- /**
1249
- * Polls the current state of an authentication attempt.
1250
- *
1251
- * Returns the attempt's state, available factors for the next challenge,
1252
- * challenges issued so far, and any errors preventing progress.
1253
- *
1254
- * Use this for polling during long-running factor verifications (e.g., waiting for
1255
- * a federated IdP callback or a device flow).
1256
- * @summary Get authentication attempt state
1257
- */
1258
- const getAuthAttempt = async (attemptId, options) => {
1259
- return customFetch(getGetAuthAttemptUrl(attemptId), {
1260
- ...options,
1261
- method: "GET"
1262
- });
1263
- };
1264
- const getIssueChallengeUrl = (attemptId) => {
1265
- return `${getProxyPath()}/auth_attempts/${encodeURIComponent(String(attemptId))}/challenges`;
1266
- };
1267
- /**
1268
- * Issues a single-factor verification challenge within an auth attempt.
1269
- *
1270
- * This advances the authentication state machine by requesting a specific factor method
1271
- * (password, passkey, TOTP, OTP via SMS, etc.). The server responds with challenge details
1272
- * including method, metadata, and any UI hints. The client then verifies the proof
1273
- * by calling POST /auth_attempts/{attempt_id}/challenges/{challenge_id}/verify.
1274
- * @summary Issue a factor challenge
1275
- */
1276
- const issueChallenge = async (attemptId, issueChallengeBody, options) => {
1277
- const getHeaders = (h) => {
1278
- if (!h) return {};
1279
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1280
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1281
- const headers = {};
1282
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1283
- return headers;
1284
- };
1285
- return customFetch(getIssueChallengeUrl(attemptId), {
1286
- ...options,
1287
- method: "POST",
1288
- headers: {
1289
- "Content-Type": "application/json",
1290
- ...getHeaders(options?.headers)
1291
- },
1292
- body: JSON.stringify(issueChallengeBody)
1293
- });
1294
- };
1295
- const getVerifyChallengeProofUrl = (attemptId, challengeId) => {
1296
- return `${getProxyPath()}/auth_attempts/${encodeURIComponent(String(attemptId))}/challenges/${encodeURIComponent(String(challengeId))}/verify`;
1297
- };
1298
- /**
1299
- * Submits a proof (credential, code, assertion) to verify a factor challenge.
1300
- *
1301
- * The proof format depends on the challenge method. For example:
1302
- * - `password` method: { password: "…" }
1303
- * - `totp` method: { totp: { code: "123456" } }
1304
- * - `passkey` method: { passkey: { assertion: "…" } }
1305
- * - `recovery_code` method: { recovery_code: "…" }
1306
- *
1307
- * On successful verification, the factor is written to the auth attempt.
1308
- * The attempt moves to the next pending challenge or completes if all required factors are verified.
1309
- * @summary Verify a factor proof
1310
- */
1311
- const verifyChallengeProof = async (attemptId, challengeId, verifyChallengeProofBody, options) => {
1312
- const getHeaders = (h) => {
1313
- if (!h) return {};
1314
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1315
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1316
- const headers = {};
1317
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1318
- return headers;
1319
- };
1320
- return customFetch(getVerifyChallengeProofUrl(attemptId, challengeId), {
1321
- ...options,
1322
- method: "POST",
1323
- headers: {
1324
- "Content-Type": "application/json",
1325
- ...getHeaders(options?.headers)
1326
- },
1327
- body: JSON.stringify(verifyChallengeProofBody)
1328
- });
1329
- };
1330
- const getCreateHandoffUrl = (attemptId) => {
1331
- return `${getProxyPath()}/auth_attempts/${encodeURIComponent(String(attemptId))}/handoff`;
1332
- };
1333
- /**
1334
- * Completes the authentication attempt and mints a `handoff_token`.
1335
- *
1336
- * Call this after all required factors have been verified and the attempt is in `completed` state.
1337
- * The handoff token is short-lived (≤60 seconds) and must be exchanged at
1338
- * POST /sessions/exchange to receive the final session and session_token.
1339
- *
1340
- * The handoff token is:
1341
- * - Single-use (atomic exchange, no retry)
1342
- * - Audience-bound (requires matching project key for exchange)
1343
- * - Idempotency-safe within a 5-minute window (see conventions)
1344
- *
1345
- * Revoke refusal for a sealed release happens at handoff exchange, not here.
1346
- * @summary Complete authentication and create handoff token
1347
- */
1348
- const createHandoff = async (attemptId, options) => {
1349
- return customFetch(getCreateHandoffUrl(attemptId), {
1350
- ...options,
1351
- method: "POST"
1352
- });
1353
- };
1354
- const getCreateProjectUrl = () => {
1355
- return `${getProxyPath()}/projects`;
1356
- };
1357
- /**
1358
- * Creates a project and returns its project secret and preview secret, which no
1359
- * other endpoint returns.
1360
- *
1361
- * The request needs no credential and is rate-limited. Unless `seed_defaults` is
1362
- * `false`, the project starts with a default user schema and flow; the CLI turns
1363
- * that off and uploads its own from `.zitadel/`.
1364
- * @summary Create project
1365
- */
1366
- const createProject = async (createProjectBody, options) => {
1367
- const getHeaders = (h) => {
1368
- if (!h) return {};
1369
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1370
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1371
- const headers = {};
1372
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1373
- return headers;
1374
- };
1375
- return customFetch(getCreateProjectUrl(), {
1376
- ...options,
1377
- method: "POST",
1378
- headers: {
1379
- "Content-Type": "application/json",
1380
- ...getHeaders(options?.headers)
1381
- },
1382
- body: JSON.stringify(createProjectBody)
1383
- });
1384
- };
1385
- const getQueryProjectsUrl = () => {
1386
- return `${getProxyPath()}/projects/query`;
1387
- };
1388
- /**
1389
- * Returns the project the project secret belongs to, as a page of at most one
1390
- * project.
1391
- *
1392
- * A credential is scoped to one project until ADR 036 widens it, so the filters
1393
- * and sorting apply to that project alone. The projects a signed-in person can
1394
- * act on are listed by `GET /users/me/projects`.
1395
- * @summary Query projects
1396
- */
1397
- const queryProjects = async (queryProjectsBody, options) => {
1398
- const getHeaders = (h) => {
1399
- if (!h) return {};
1400
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1401
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1402
- const headers = {};
1403
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1404
- return headers;
1405
- };
1406
- return customFetch(getQueryProjectsUrl(), {
1407
- ...options,
1408
- method: "POST",
1409
- headers: {
1410
- "Content-Type": "application/json",
1411
- ...getHeaders(options?.headers)
1412
- },
1413
- body: JSON.stringify(queryProjectsBody)
1414
- });
1415
- };
1416
- const getGetProjectUrl = (projectId) => {
1417
- return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}`;
1418
- };
1419
- /**
1420
- * Returns the current state of a project.
1421
- * @summary Get project
1422
- */
1423
- const getProject = async (projectId, options) => {
1424
- return customFetch(getGetProjectUrl(projectId), {
1425
- ...options,
1426
- method: "GET"
1427
- });
1428
- };
1429
- const getPatchProjectUrl = (projectId) => {
1430
- return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}`;
1431
- };
1432
- /**
1433
- * Updates the state of a project.
1434
- * @summary Update project
1435
- */
1436
- const patchProject = async (projectId, patchProjectBody, options) => {
1437
- const getHeaders = (h) => {
1438
- if (!h) return {};
1439
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1440
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1441
- const headers = {};
1442
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1443
- return headers;
1444
- };
1445
- return customFetch(getPatchProjectUrl(projectId), {
1446
- ...options,
1447
- method: "PATCH",
1448
- headers: {
1449
- "Content-Type": "application/json",
1450
- ...getHeaders(options?.headers)
1451
- },
1452
- body: JSON.stringify(patchProjectBody)
1453
- });
1454
- };
1455
- const getListProjectAdminsUrl = (projectId, params) => {
1456
- const normalizedParams = new URLSearchParams();
1457
- Object.entries(params || {}).forEach(([key, value]) => {
1458
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1459
- });
1460
- const stringifiedParams = normalizedParams.toString();
1461
- return stringifiedParams.length > 0 ? `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/admins?${stringifiedParams}` : `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/admins`;
1462
- };
1463
- /**
1464
- * Lists the people who can administer the project, and how each of them
1465
- * gets that access. A person appears once, with one entry in `sources` per
1466
- * way they hold it:
1467
- *
1468
- * - `owning_team`: an active member of the team that owns the project
1469
- * (ADR 054 §2). Removing a grant does not remove this access; it ends
1470
- * only when the person leaves the team or the project changes owner.
1471
- * - `grant`: an unexpired `admin` grant on the project, either to the
1472
- * person (`grant_id` only) or to a team they are an active member of
1473
- * (`grant_id` and `team`). Revoking that grant removes this source.
1474
- *
1475
- * The list follows the authorization check: team membership is read from
1476
- * the same membership projection the check expands, so a person who left a
1477
- * team, or whose team or user was deactivated, is not listed through it.
1478
- * Grants that expired or carry a lower role are left out. A person whose
1479
- * only access is a `viewer` or `editor` grant is not an admin and is not
1480
- * listed. Like the check, the list does not look at a person's user status
1481
- * beyond that, so a direct grant to a suspended person is listed.
1482
- *
1483
- * A person whose access comes only through teams the caller is not a
1484
- * member of is left out, and a team the caller is not in is named by
1485
- * `team_id` only. The grant to such a team still shows in the project's
1486
- * grants.
1487
- *
1488
- * Ordered by `user_id` and paginated with `page_token`.
1489
- *
1490
- * Accepts either a project secret (`oauth2`) or a user-bound Console
1491
- * session cookie (`nextgenSession`) that can read the project.
1492
- * @summary List project admins
1493
- */
1494
- const listProjectAdmins = async (projectId, params, options) => {
1495
- return customFetch(getListProjectAdminsUrl(projectId, params), {
1496
- ...options,
1497
- method: "GET"
1498
- });
1499
- };
1500
- const getInitClaimUrl = (projectId) => {
1501
- return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/init`;
1502
- };
1503
- /**
1504
- * Starts a claim challenge for an unclaimed project. Authenticated by the
1505
- * project secret, this mints a single-use, short-lived challenge and returns
1506
- * the `claim_url` the developer opens in a browser to complete the claim,
1507
- * together with the `challenge_id` the CLI polls with. The exact expiry is
1508
- * carried by `expires_at` on the response.
1509
- * @summary Initialize a project claim
1510
- */
1511
- const initClaim = async (projectId, options) => {
1512
- return customFetch(getInitClaimUrl(projectId), {
1513
- ...options,
1514
- method: "POST"
1515
- });
1516
- };
1517
- const getGetClaimStatusUrl = (projectId, params) => {
1518
- const normalizedParams = new URLSearchParams();
1519
- Object.entries(params || {}).forEach(([key, value]) => {
1520
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1521
- });
1522
- const stringifiedParams = normalizedParams.toString();
1523
- return stringifiedParams.length > 0 ? `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/status?${stringifiedParams}` : `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/status`;
1524
- };
1525
- /**
1526
- * Polled by the CLI while a browser completes the claim. Authorized by the
1527
- * project secret that initiated the challenge. Returns `pending`, or
1528
- * `completed` with the owning team, the claim timestamp, and the dashboard
1529
- * URL once the project is claimed. The claim grant, not the polled
1530
- * challenge, is the source of truth: a project claimed through another
1531
- * concurrent challenge also reports `completed`, and a completed claim
1532
- * keeps reporting `completed` past this challenge's expiry and past the
1533
- * project's claim window.
1534
- * @summary Get claim status
1535
- */
1536
- const getClaimStatus = async (projectId, params, options) => {
1537
- return customFetch(getGetClaimStatusUrl(projectId, params), {
1538
- ...options,
1539
- method: "GET"
1540
- });
1541
- };
1542
- const getCompleteClaimUrl = (projectId) => {
1543
- return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/complete`;
1544
- };
1545
- /**
1546
- * Called by the browser after the developer authenticates on the claim page.
1547
- * Authenticated by the `__nextgen_session` cookie, it attaches the project to
1548
- * the developer's personal team using the `challenge_id` from the claim URL as
1549
- * its single-use, browser-safe authorization.
1550
- * @summary Complete a project claim
1551
- */
1552
- const completeClaim = async (projectId, completeClaimBody, options) => {
1553
- const getHeaders = (h) => {
1554
- if (!h) return {};
1555
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1556
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1557
- const headers = {};
1558
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1559
- return headers;
1560
- };
1561
- return customFetch(getCompleteClaimUrl(projectId), {
1562
- ...options,
1563
- method: "POST",
1564
- headers: {
1565
- "Content-Type": "application/json",
1566
- ...getHeaders(options?.headers)
1567
- },
1568
- body: JSON.stringify(completeClaimBody)
1569
- });
1570
- };
1571
- const getGetClaimWindowUrl = (projectId, params) => {
1572
- const normalizedParams = new URLSearchParams();
1573
- Object.entries(params || {}).forEach(([key, value]) => {
1574
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1575
- });
1576
- const stringifiedParams = normalizedParams.toString();
1577
- return stringifiedParams.length > 0 ? `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/window?${stringifiedParams}` : `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/window`;
1578
- };
1579
- /**
1580
- * Read by the claim page in the browser to show how long is left to claim the
1581
- * project. Unauthenticated by design: the claim page runs this before the
1582
- * developer has signed in, and holding the `challenge_id` from the claim URL
1583
- * is the authorization — the same capability `claim/complete` accepts. It
1584
- * reveals only the window, never the project itself, and unlike
1585
- * `claim/complete` it spends nothing, so a reload is free.
1586
- * @summary Get the claim window for a project
1587
- */
1588
- const getClaimWindow = async (projectId, params, options) => {
1589
- return customFetch(getGetClaimWindowUrl(projectId, params), {
1590
- ...options,
1591
- method: "GET"
1592
- });
1593
- };
1594
- const getAddOriginUrl = (projectId) => {
1595
- return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/origins`;
1596
- };
1597
- /**
1598
- * Adds one `{pattern, kind}` to the project's origins. A primary pattern
1599
- * must be an exact URL (no wildcard). Preview patterns may include a single
1600
- * DNS-label wildcard. Adding a pattern that already exists with the same
1601
- * kind is idempotent and answers 201 with the stored origin.
1602
- * @summary Add an origin pattern
1603
- */
1604
- const addOrigin = async (projectId, addOriginBody, options) => {
1605
- const getHeaders = (h) => {
1606
- if (!h) return {};
1607
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1608
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1609
- const headers = {};
1610
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1611
- return headers;
1612
- };
1613
- return customFetch(getAddOriginUrl(projectId), {
1614
- ...options,
1615
- method: "POST",
1616
- headers: {
1617
- "Content-Type": "application/json",
1618
- ...getHeaders(options?.headers)
1619
- },
1620
- body: JSON.stringify(addOriginBody)
1621
- });
1622
- };
1623
- const getRemoveOriginUrl = (projectId) => {
1624
- return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/origins/remove`;
1625
- };
1626
- /**
1627
- * Removes one pattern from the project's origins. Requests from URLs only
1628
- * that pattern admitted are refused from then on; live previews and
1629
- * deployment history are untouched. Removing a pattern that is already
1630
- * absent is idempotent and answers 204.
1631
- * @summary Remove an origin pattern
1632
- */
1633
- const removeOrigin = async (projectId, removeOriginBody, options) => {
1634
- const getHeaders = (h) => {
1635
- if (!h) return {};
1636
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1637
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1638
- const headers = {};
1639
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1640
- return headers;
1641
- };
1642
- return customFetch(getRemoveOriginUrl(projectId), {
1643
- ...options,
1644
- method: "POST",
1645
- headers: {
1646
- "Content-Type": "application/json",
1647
- ...getHeaders(options?.headers)
1648
- },
1649
- body: JSON.stringify(removeOriginBody)
1650
- });
1651
- };
1652
- const getListPreviewsUrl = (projectId, params) => {
1653
- const normalizedParams = new URLSearchParams();
1654
- Object.entries(params || {}).forEach(([key, value]) => {
1655
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1656
- });
1657
- const stringifiedParams = normalizedParams.toString();
1658
- return stringifiedParams.length > 0 ? `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/previews?${stringifiedParams}` : `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/previews`;
1659
- };
1660
- /**
1661
- * Lists the project's live previews, newest first by `created_at`. An
1662
- * expired or removed preview is not listed; what was deployed to it stays
1663
- * in `GET /deployments`.
1664
- * @summary List previews
1665
- */
1666
- const listPreviews = async (projectId, params, options) => {
1667
- return customFetch(getListPreviewsUrl(projectId, params), {
1668
- ...options,
1669
- method: "GET"
1670
- });
1671
- };
1672
- const getRemovePreviewUrl = (projectId) => {
1673
- return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/previews/remove`;
1674
- };
1675
- /**
1676
- * Ends a preview before it expires: the URL stops being served at once.
1677
- * The deployments to it stay in the history.
1678
- *
1679
- * Idempotent: a URL with no live preview, including one that has already
1680
- * expired or was removed before, answers `204` too, so a cleanup that
1681
- * races the expiry still succeeds.
1682
- *
1683
- * The URL travels in the body rather than the path because an origin
1684
- * contains `/`.
1685
- * @summary Remove a preview
1686
- */
1687
- const removePreview = async (projectId, removePreviewBody, options) => {
1688
- const getHeaders = (h) => {
1689
- if (!h) return {};
1690
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1691
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1692
- const headers = {};
1693
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1694
- return headers;
1695
- };
1696
- return customFetch(getRemovePreviewUrl(projectId), {
1697
- ...options,
1698
- method: "POST",
1699
- headers: {
1700
- "Content-Type": "application/json",
1701
- ...getHeaders(options?.headers)
1702
- },
1703
- body: JSON.stringify(removePreviewBody)
1704
- });
1705
- };
1706
- const getCreateSessionUrl = () => {
1707
- return `${getProxyPath()}/sessions`;
1708
- };
1709
- /**
1710
- * Creates an anonymous session shell with no user and no factors (`state: building`).
1711
- *
1712
- * This is optional — an `auth_attempt` will create a session implicitly if none is provided.
1713
- * Use this explicitly when you want to:
1714
- * - Pre-allocate a `session_id` before the user is known, so device/telemetry signals
1715
- * can be correlated with the eventual authenticated session from the start.
1716
- * - Track anonymous state (bot detection, device fingerprint) that survives until authentication.
1717
- *
1718
- * Creating a session is an app-plane operation on the project credential
1719
- * (`session.write`). The returned `session_token` is a session credential for the
1720
- * end-user client, not a management scope: it is delivered as the
1721
- * `__nextgen_session` cookie and authorises the self-service operations
1722
- * `GET /sessions/me` and `DELETE /sessions/me` (`nextgenSession` scheme). The
1723
- * by-id operations `GET /sessions/{session_id}` and `DELETE /sessions/{session_id}`
1724
- * are operator endpoints and require `session.read` / `session.delete` instead.
1725
- *
1726
- * The `session_token` is superseded when a handoff exchange completes — clients must
1727
- * replace it at that point.
1728
- *
1729
- * Anonymous sessions expire aggressively (10-minute TTL). The TTL resets to the configured
1730
- * full session TTL when the first authentication factor is written via a completing `auth_attempt`.
1731
- * @summary Create an anonymous session shell
1732
- */
1733
- const createSession = async (createSessionBody, options) => {
1734
- const getHeaders = (h) => {
1735
- if (!h) return {};
1736
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1737
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1738
- const headers = {};
1739
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1740
- return headers;
1741
- };
1742
- return customFetch(getCreateSessionUrl(), {
1743
- ...options,
1744
- method: "POST",
1745
- headers: {
1746
- "Content-Type": "application/json",
1747
- ...getHeaders(options?.headers)
1748
- },
1749
- body: JSON.stringify(createSessionBody)
1750
- });
1751
- };
1752
- const getQuerySessionsUrl = (params) => {
1753
- const normalizedParams = new URLSearchParams();
1754
- Object.entries(params || {}).forEach(([key, value]) => {
1755
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1756
- });
1757
- const stringifiedParams = normalizedParams.toString();
1758
- return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/query?${stringifiedParams}` : `${getProxyPath()}/sessions/query`;
1759
- };
1760
- /**
1761
- * Returns the sessions of a project, paginated with a cursor.
1762
- * Sessions of every lifecycle state are returned; each carries its `state`.
1763
- * Requires `session.read` permission.
1764
- * @summary Query sessions
1765
- */
1766
- const querySessions = async (querySessionsBody, params, options) => {
1767
- const getHeaders = (h) => {
1768
- if (!h) return {};
1769
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1770
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1771
- const headers = {};
1772
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1773
- return headers;
1774
- };
1775
- return customFetch(getQuerySessionsUrl(params), {
1776
- ...options,
1777
- method: "POST",
1778
- headers: {
1779
- "Content-Type": "application/json",
1780
- ...getHeaders(options?.headers)
1781
- },
1782
- body: JSON.stringify(querySessionsBody)
1783
- });
1784
- };
1785
- const getExchangeHandoffUrl = (params) => {
1786
- const normalizedParams = new URLSearchParams();
1787
- Object.entries(params || {}).forEach(([key, value]) => {
1788
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1789
- });
1790
- const stringifiedParams = normalizedParams.toString();
1791
- return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/exchange?${stringifiedParams}` : `${getProxyPath()}/sessions/exchange`;
1792
- };
1793
- /**
1794
- * Consumes a one-time `handoff_token` minted by `POST /auth_attempts/{id}/handoff`
1795
- * and returns the resulting session and a `session_token`.
1796
- *
1797
- * The server resolves the originating `auth_attempt` from the token and then:
1798
- *
1799
- * | Originating auth_attempt | Outcome |
1800
- * |---|---|
1801
- * | No `session_id` | A new authenticated session is **created**. |
1802
- * | `session_id` points to an anonymous shell | Existing session is **upgraded** — user and factors written in, TTL reset to full session TTL. |
1803
- * | `session_id` points to an active session (step-up) | Existing session is **upgraded** — new factors merged, `assurance_levels[]` expanded. |
1804
- *
1805
- * The response shape is identical in all three cases.
1806
- *
1807
- * The `session_token` supersedes any previously issued `session_token` for the same session.
1808
- * Clients must replace their stored token at this point.
1809
- *
1810
- * Requires a project service key (OAuth2 client credentials).
1811
- *
1812
- * The project comes from the project secret. A query `project_id` that
1813
- * disagrees answers `403` with `proj.mismatch`. The exchange resolves a
1814
- * deployment the same way as other runtime operations; with no browser
1815
- * `Origin` and nothing deployed to the resolved target the response is
1816
- * `409` with `rel.not_deployed`. A revoked release answers `409` with
1817
- * `rel.revoked`.
1818
- * @summary Exchange handoff token for a session
1819
- */
1820
- const exchangeHandoff = async (exchangeHandoffBody, params, options) => {
1821
- const getHeaders = (h) => {
1822
- if (!h) return {};
1823
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1824
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1825
- const headers = {};
1826
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1827
- return headers;
1828
- };
1829
- return customFetch(getExchangeHandoffUrl(params), {
1830
- ...options,
1831
- method: "POST",
1832
- headers: {
1833
- "Content-Type": "application/json",
1834
- ...getHeaders(options?.headers)
1835
- },
1836
- body: JSON.stringify(exchangeHandoffBody)
1837
- });
1838
- };
1839
- const getGetSessionUrl = (sessionId) => {
1840
- return `${getProxyPath()}/sessions/${encodeURIComponent(String(sessionId))}`;
1841
- };
1842
- /**
1843
- * Returns the current state of a session including its factors and all currently
1844
- * satisfied assurance levels.
1845
- *
1846
- * `assurance_levels[]` may shrink over time as factor freshness windows expire,
1847
- * without the session itself expiring. Use step-up authentication (a new `auth_attempt`
1848
- * against the same `session_id`) to restore a dropped assurance level.
1849
- * @summary Get session state
1850
- */
1851
- const getSession = async (sessionId, options) => {
1852
- return customFetch(getGetSessionUrl(sessionId), {
1853
- ...options,
1854
- method: "GET"
1855
- });
1856
- };
1857
- const getRevokeSessionUrl = (sessionId) => {
1858
- return `${getProxyPath()}/sessions/${encodeURIComponent(String(sessionId))}`;
1859
- };
1860
- /**
1861
- * Permanently deletes the session, terminating it immediately.
1862
- *
1863
- * This is the operator revoke path and requires the `session.delete` scope on a
1864
- * project-bound credential. End-user logout with the `__nextgen_session` cookie is
1865
- * `DELETE /sessions/me` (`nextgenSession` scheme).
1866
- *
1867
- * Idempotent: deleting a session that does not exist (or was already deleted)
1868
- * still returns 204. After deletion, any tokens derived from the session are
1869
- * invalidated.
1870
- * @summary Revoke session
1871
- */
1872
- const revokeSession = async (sessionId, options) => {
1873
- return customFetch(getRevokeSessionUrl(sessionId), {
1874
- ...options,
1875
- method: "DELETE"
1876
- });
1877
- };
1878
- const getGetMySessionUrl = (params) => {
1879
- const normalizedParams = new URLSearchParams();
1880
- Object.entries(params || {}).forEach(([key, value]) => {
1881
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1882
- });
1883
- const stringifiedParams = normalizedParams.toString();
1884
- return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/me?${stringifiedParams}` : `${getProxyPath()}/sessions/me`;
1885
- };
1886
- /**
1887
- * Returns the current state of the current session including its factors and all currently
1888
- * satisfied assurance levels.
1889
- *
1890
- * With `project_id`, the session is returned only when it belongs to that project.
1891
- *
1892
- * `assurance_levels[]` may shrink over time as factor freshness windows expire,
1893
- * without the session itself expiring. Use step-up authentication (a new `auth_attempt`
1894
- * against the same `session_id`) to restore a dropped assurance level.
1895
- * @summary Get my session state
1896
- */
1897
- const getMySession = async (params, options) => {
1898
- return customFetch(getGetMySessionUrl(params), {
1899
- ...options,
1900
- method: "GET"
1901
- });
1902
- };
1903
- const getRevokeMySessionUrl = (params) => {
1904
- const normalizedParams = new URLSearchParams();
1905
- Object.entries(params || {}).forEach(([key, value]) => {
1906
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1907
- });
1908
- const stringifiedParams = normalizedParams.toString();
1909
- return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/me?${stringifiedParams}` : `${getProxyPath()}/sessions/me`;
1910
- };
1911
- /**
1912
- * Logs out by permanently deleting the session.
1913
- *
1914
- * The `__nextgen_session` cookie issued at creation (or superseded by a handoff
1915
- * exchange) is required, with the session's token from `GET /sessions/me/csrf`
1916
- * in the `X-Zitadel-CSRF` header. Idempotent: if the session is already gone
1917
- * this still returns 204. Any tokens derived from the session are invalidated,
1918
- * and the cookie itself is cleared in the response.
1919
- *
1920
- * With `project_id`, only a session of that project is deleted. A session of
1921
- * another project is left alone, and so is its cookie.
1922
- * @summary Revoke my session
1923
- */
1924
- const revokeMySession = async (params, options) => {
1925
- return customFetch(getRevokeMySessionUrl(params), {
1926
- ...options,
1927
- method: "DELETE"
1928
- });
1929
- };
1930
- const getGetMySessionCsrfTokenUrl = (params) => {
1931
- const normalizedParams = new URLSearchParams();
1932
- Object.entries(params || {}).forEach(([key, value]) => {
1933
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1934
- });
1935
- const stringifiedParams = normalizedParams.toString();
1936
- return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/me/csrf?${stringifiedParams}` : `${getProxyPath()}/sessions/me/csrf`;
1937
- };
1938
- /**
1939
- * Returns the session-bound token for cross-site request forgery protection
1940
- * (ADR 053 §5). Browser code sends it in the `X-Zitadel-CSRF` header on the
1941
- * state-changing requests the session cookie authenticates that require it
1942
- * — see the `nextgenSession` scheme. It authorizes nothing on its own: the
1943
- * HttpOnly cookie is still the credential, and a cross-site page cannot
1944
- * read this response. It stays the same for the life of the session, so a
1945
- * client fetches it once per session.
1946
- *
1947
- * With `project_id`, the token is returned only when the session belongs to
1948
- * that project.
1949
- * @summary Get my session's CSRF token
1950
- */
1951
- const getMySessionCsrfToken = async (params, options) => {
1952
- return customFetch(getGetMySessionCsrfTokenUrl(params), {
1953
- ...options,
1954
- method: "GET"
1955
- });
1956
- };
1957
- const getCreateSchemaUrl = (params) => {
1958
- const normalizedParams = new URLSearchParams();
1959
- Object.entries(params || {}).forEach(([key, value]) => {
1960
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1961
- });
1962
- const stringifiedParams = normalizedParams.toString();
1963
- return stringifiedParams.length > 0 ? `${getProxyPath()}/schemas?${stringifiedParams}` : `${getProxyPath()}/schemas`;
1964
- };
1965
- /**
1966
- * Create a new schema. The optional `$id` field is the JSON Schema document
1967
- * URI used to identify the schema in future requests (GitOps-stable identity,
1968
- * not a free-form resource primary key). When `$id` is omitted, the server
1969
- * generates a `sch_*` URL. When provided, `$id` must be unique within the
1970
- * project and should ideally be a valid URI pointing at where the schema can
1971
- * be accessed.
1972
- *
1973
- * The schema can either be a concrete schema, e.g. a user schema, or a
1974
- * schema-url which will be resolved by the server.
1975
- * @summary Create new schema
1976
- */
1977
- const createSchema = async (createSchemaBody, params, options) => {
1978
- const getHeaders = (h) => {
1979
- if (!h) return {};
1980
- if (h instanceof Headers) return Object.fromEntries(h.entries());
1981
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1982
- const headers = {};
1983
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1984
- return headers;
1985
- };
1986
- return customFetch(getCreateSchemaUrl(params), {
1987
- ...options,
1988
- method: "POST",
1989
- headers: {
1990
- "Content-Type": "application/json",
1991
- ...getHeaders(options?.headers)
1992
- },
1993
- body: JSON.stringify(createSchemaBody)
1994
- });
1995
- };
1996
- const getListSchemasUrl = (params) => {
1997
- const normalizedParams = new URLSearchParams();
1998
- Object.entries(params || {}).forEach(([key, value]) => {
1999
- if (Array.isArray(value) && ["expand"].includes(key)) {
2000
- value.forEach((v) => {
2001
- normalizedParams.append(key, v === null ? "null" : String(v));
2002
- });
2003
- return;
2004
- }
2005
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2006
- });
2007
- const stringifiedParams = normalizedParams.toString();
2008
- return stringifiedParams.length > 0 ? `${getProxyPath()}/schemas?${stringifiedParams}` : `${getProxyPath()}/schemas`;
2009
- };
2010
- /**
2011
- * Retrieve a list of all schemas available in the system. This endpoint
2012
- * supports pagination and filtering based on schema attributes.
2013
- * @summary List all schemas
2014
- */
2015
- const listSchemas = async (params, options) => {
2016
- return customFetch(getListSchemasUrl(params), {
2017
- ...options,
2018
- method: "GET"
2019
- });
2020
- };
2021
- const getGetSchemaByIdUrl = (id, params) => {
2022
- const normalizedParams = new URLSearchParams();
2023
- Object.entries(params || {}).forEach(([key, value]) => {
2024
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2025
- });
2026
- const stringifiedParams = normalizedParams.toString();
2027
- return stringifiedParams.length > 0 ? `${getProxyPath()}/schemas/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/schemas/${encodeURIComponent(String(id))}`;
2028
- };
2029
- /**
2030
- * Get a schema by its ID. A schema ID identifies one immutable revision, so
2031
- * this returns exactly that revision. To find the current revision of an
2032
- * object type, list with `revisions=latest`.
2033
- *
2034
- * Schema IDs are unique within a project, not across projects (the seeded
2035
- * default schema carries the same `$id` in every project). A Console
2036
- * session that manages more than one project names the project with
2037
- * `project_id`; without it, the ID is resolved in the credential's own
2038
- * project when it is ambiguous. A project secret always resolves in its
2039
- * own project and ignores `project_id`.
2040
- * @summary Get schema by ID
2041
- */
2042
- const getSchemaById = async (id, params, options) => {
2043
- return customFetch(getGetSchemaByIdUrl(id, params), {
2044
- ...options,
2045
- method: "GET"
2046
- });
2047
- };
2048
- const getCreateFlowDefinitionUrl = () => {
2049
- return `${getProxyPath()}/flow_definitions`;
2050
- };
2051
- /**
2052
- * Publishes a new flow definition revision.
2053
- * Flow definitions are templates that define the sequence of steps (capabilities)
2054
- * for a particular user journey (e.g., registration, login, password reset).
2055
- *
2056
- * Flow definitions are created based on the flow definition schema, which includes the flow's purpose, audience, and the steps involved.
2057
- *
2058
- * Every call allocates a new opaque id. Revisions of one flow share its
2059
- * `name`; posting a definition under an existing `name` publishes a new
2060
- * revision of that flow, it is not a conflict. List with `name` to see a
2061
- * flow's revisions, newest by creation time first.
2062
- * @summary Create a new flow definition
2063
- */
2064
- const createFlowDefinition = async (createFlowDefinitionBody, options) => {
2065
- const getHeaders = (h) => {
2066
- if (!h) return {};
2067
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2068
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2069
- const headers = {};
2070
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2071
- return headers;
2072
- };
2073
- return customFetch(getCreateFlowDefinitionUrl(), {
2074
- ...options,
2075
- method: "POST",
2076
- headers: {
2077
- "Content-Type": "application/json",
2078
- ...getHeaders(options?.headers)
2079
- },
2080
- body: JSON.stringify(createFlowDefinitionBody)
2081
- });
2082
- };
2083
- const getListFlowDefinitionsUrl = (params) => {
2084
- const normalizedParams = new URLSearchParams();
2085
- Object.entries(params || {}).forEach(([key, value]) => {
2086
- if (Array.isArray(value) && ["expand"].includes(key)) {
2087
- value.forEach((v) => {
2088
- normalizedParams.append(key, v === null ? "null" : String(v));
2089
- });
2090
- return;
2091
- }
2092
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2093
- });
2094
- const stringifiedParams = normalizedParams.toString();
2095
- return stringifiedParams.length > 0 ? `${getProxyPath()}/flow_definitions?${stringifiedParams}` : `${getProxyPath()}/flow_definitions`;
2096
- };
2097
- /**
2098
- * Retrieves a list of all flow definitions, newest by creation time first.
2099
- * This endpoint can be used to view existing flow definitions and their configurations.
2100
- * Filter by `name` to list the revisions of one flow.
2101
- * @summary List flow definitions
2102
- */
2103
- const listFlowDefinitions = async (params, options) => {
2104
- return customFetch(getListFlowDefinitionsUrl(params), {
2105
- ...options,
2106
- method: "GET"
2107
- });
2108
- };
2109
- const getGetFlowDefinitionUrl = (id) => {
2110
- return `${getProxyPath()}/flow_definitions/${encodeURIComponent(String(id))}`;
2111
- };
2112
- /**
2113
- * Get a flow definition by id
2114
- * @summary Get a flow definition by id
2115
- */
2116
- const getFlowDefinition = async (id, options) => {
2117
- return customFetch(getGetFlowDefinitionUrl(id), {
2118
- ...options,
2119
- method: "GET"
2120
- });
2121
- };
2122
- const getCreateTeamUrl = (params) => {
2123
- const normalizedParams = new URLSearchParams();
2124
- Object.entries(params || {}).forEach(([key, value]) => {
2125
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2126
- });
2127
- const stringifiedParams = normalizedParams.toString();
2128
- return stringifiedParams.length > 0 ? `${getProxyPath()}/teams?${stringifiedParams}` : `${getProxyPath()}/teams`;
2129
- };
2130
- /**
2131
- * Creates a team in the project, with a name no other team in the project has.
2132
- *
2133
- * A taken name is refused with `409 team.already_exists`. The new team has no
2134
- * members yet.
2135
- * @summary Create team
2136
- */
2137
- const createTeam = async (createTeamBody, params, options) => {
2138
- const getHeaders = (h) => {
2139
- if (!h) return {};
2140
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2141
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2142
- const headers = {};
2143
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2144
- return headers;
2145
- };
2146
- return customFetch(getCreateTeamUrl(params), {
2147
- ...options,
2148
- method: "POST",
2149
- headers: {
2150
- "Content-Type": "application/json",
2151
- ...getHeaders(options?.headers)
2152
- },
2153
- body: JSON.stringify(createTeamBody)
2154
- });
2155
- };
2156
- const getQueryTeamsUrl = (params) => {
2157
- const normalizedParams = new URLSearchParams();
2158
- Object.entries(params || {}).forEach(([key, value]) => {
2159
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2160
- });
2161
- const stringifiedParams = normalizedParams.toString();
2162
- return stringifiedParams.length > 0 ? `${getProxyPath()}/teams/query?${stringifiedParams}` : `${getProxyPath()}/teams/query`;
2163
- };
2164
- /**
2165
- * Returns the teams of a project, paginated with a cursor.
2166
- * @summary Query teams
2167
- */
2168
- const queryTeams = async (queryTeamsBody, params, options) => {
2169
- const getHeaders = (h) => {
2170
- if (!h) return {};
2171
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2172
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2173
- const headers = {};
2174
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2175
- return headers;
2176
- };
2177
- return customFetch(getQueryTeamsUrl(params), {
2178
- ...options,
2179
- method: "POST",
2180
- headers: {
2181
- "Content-Type": "application/json",
2182
- ...getHeaders(options?.headers)
2183
- },
2184
- body: JSON.stringify(queryTeamsBody)
2185
- });
2186
- };
2187
- const getGetTeamUrl = (teamId) => {
2188
- return `${getProxyPath()}/teams/${encodeURIComponent(String(teamId))}`;
2189
- };
2190
- /**
2191
- * Returns a Team by its id.
2192
- * @summary Get team
2193
- */
2194
- const getTeam = async (teamId, options) => {
2195
- return customFetch(getGetTeamUrl(teamId), {
2196
- ...options,
2197
- method: "GET"
2198
- });
2199
- };
2200
- const getDeleteTeamUrl = (teamId) => {
2201
- return `${getProxyPath()}/teams/${encodeURIComponent(String(teamId))}`;
2202
- };
2203
- /**
2204
- * Deactivates the team.
2205
- *
2206
- * The team is tombstoned rather than erased: it stays readable through
2207
- * getTeam with status `deactivated`. Its memberships are removed and the
2208
- * users whose lifecycle it owns are deactivated with it.
2209
- *
2210
- * The request is idempotent. Deleting a team that is already deactivated
2211
- * or doesn't exist succeeds without changing anything.
2212
- *
2213
- * A team that still owns a project is refused with `409
2214
- * team.owns_project`: deactivating it would leave the project owned by a
2215
- * dead team and so unmanageable. No endpoint releases that ownership yet,
2216
- * so such a team cannot currently be deactivated through the API.
2217
- * @summary Delete team
2218
- */
2219
- const deleteTeam = async (teamId, options) => {
2220
- return customFetch(getDeleteTeamUrl(teamId), {
2221
- ...options,
2222
- method: "DELETE"
2223
- });
2224
- };
2225
- const getUpdateTeamUrl = (teamId) => {
2226
- return `${getProxyPath()}/teams/${encodeURIComponent(String(teamId))}`;
2227
- };
2228
- /**
2229
- * Update team. Only active teams can be updated.
2230
- * @summary Update team
2231
- */
2232
- const updateTeam = async (teamId, updateTeamBody, options) => {
2233
- const getHeaders = (h) => {
2234
- if (!h) return {};
2235
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2236
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2237
- const headers = {};
2238
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2239
- return headers;
2240
- };
2241
- return customFetch(getUpdateTeamUrl(teamId), {
2242
- ...options,
2243
- method: "PATCH",
2244
- headers: {
2245
- "Content-Type": "application/json",
2246
- ...getHeaders(options?.headers)
2247
- },
2248
- body: JSON.stringify(updateTeamBody)
2249
- });
2250
- };
2251
- const getCreateBrandingUrl = (params) => {
2252
- const normalizedParams = new URLSearchParams();
2253
- Object.entries(params || {}).forEach(([key, value]) => {
2254
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2255
- });
2256
- const stringifiedParams = normalizedParams.toString();
2257
- return stringifiedParams.length > 0 ? `${getProxyPath()}/branding?${stringifiedParams}` : `${getProxyPath()}/branding`;
2258
- };
2259
- /**
2260
- * Publishes a new immutable branding revision for the project. Branding
2261
- * revisions cannot be updated or deleted; every edit publishes a new
2262
- * revision, and flow responses resolve the latest revision per project.
2263
- *
2264
- * The `liquid_template` is validated lexically on save (size, encoding,
2265
- * banned patterns such as `<script>` tags, inline event handlers, and the
2266
- * `| raw` filter). Authoritative LiquidJS validation runs at authoring
2267
- * time via `zitadel plan` / `zitadel apply`.
2268
- * @summary Publish a new branding revision
2269
- */
2270
- const createBranding = async (createBrandingBody, params, options) => {
2271
- const getHeaders = (h) => {
2272
- if (!h) return {};
2273
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2274
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2275
- const headers = {};
2276
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2277
- return headers;
2278
- };
2279
- return customFetch(getCreateBrandingUrl(params), {
2280
- ...options,
2281
- method: "POST",
2282
- headers: {
2283
- "Content-Type": "application/json",
2284
- ...getHeaders(options?.headers)
2285
- },
2286
- body: JSON.stringify(createBrandingBody)
2287
- });
2288
- };
2289
- const getListBrandingUrl = (params) => {
2290
- const normalizedParams = new URLSearchParams();
2291
- Object.entries(params || {}).forEach(([key, value]) => {
2292
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2293
- });
2294
- const stringifiedParams = normalizedParams.toString();
2295
- return stringifiedParams.length > 0 ? `${getProxyPath()}/branding?${stringifiedParams}` : `${getProxyPath()}/branding`;
2296
- };
2297
- /**
2298
- * Lists branding revisions for the project, newest first, capped at the
2299
- * 100 most recent. The first entry is the revision flow responses
2300
- * currently resolve. Deliberately unpaginated in v1 — list endpoints gain a
2301
- * real query mechanism together; advertising pagination parameters the
2302
- * server ignores would be worse than none.
2303
- * @summary List branding revisions
2304
- */
2305
- const listBranding = async (params, options) => {
2306
- return customFetch(getListBrandingUrl(params), {
2307
- ...options,
2308
- method: "GET"
2309
- });
2310
- };
2311
- const getGetBrandingByIdUrl = (id) => {
2312
- return `${getProxyPath()}/branding/${encodeURIComponent(String(id))}`;
2313
- };
2314
- /**
2315
- * Retrieves a single branding revision, including its stored configuration.
2316
- * @summary Get a branding revision by ID
2317
- */
2318
- const getBrandingById = async (id, options) => {
2319
- return customFetch(getGetBrandingByIdUrl(id), {
2320
- ...options,
2321
- method: "GET"
2322
- });
2323
- };
2324
- const getCreateIdpUrl = (params) => {
2325
- const normalizedParams = new URLSearchParams();
2326
- Object.entries(params || {}).forEach(([key, value]) => {
2327
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2328
- });
2329
- const stringifiedParams = normalizedParams.toString();
2330
- return stringifiedParams.length > 0 ? `${getProxyPath()}/idps?${stringifiedParams}` : `${getProxyPath()}/idps`;
2331
- };
2332
- /**
2333
- * Creates or revises a connection document. If the slug does not already
2334
- * exist, a new connection is created. If a connection with that slug already
2335
- * exists, a revision is created.
2336
- *
2337
- * A revision gets a new `revision_id` and does not modify the connection
2338
- * `id`, so identity links that reference the connection keep resolving while
2339
- * releases and auth attempts stay pinned to the revision they captured.
2340
- *
2341
- * Identity fields are fixed for the life of the connection and a revision
2342
- * that changes one is rejected: `protocol`, `subject_claim`, and `issuer`,
2343
- * the field that names the authority. Their values decide which provider
2344
- * account a stored subject belongs to, so changing one would silently
2345
- * repoint existing identities at a different provider.
2346
- *
2347
- * `subject_claim` is optional, and `sub` is used as the default value. If a
2348
- * revision updates `subject_claim` to a different value than the one set
2349
- * during creation, the request is rejected.
2350
- *
2351
- * OIDC is the only protocol.
2352
- *
2353
- * The document is validated against the `idp-connection.json` schema before
2354
- * anything is stored. The rules the engine applies when it starts a sign-in
2355
- * then run on the document, so a connection that could never start one is
2356
- * refused here instead with `idp.endpoints_partial`: the OIDC block sets an
2357
- * endpoint without the others. It either sets no endpoint, and discovery
2358
- * fills them, or sets `authorization_endpoint`, `token_endpoint`, `jwks_uri`,
2359
- * and `userinfo_endpoint`. `userinfo_endpoint` may be left out when
2360
- * `id_token_mapping` is on, but setting it alone still counts as setting an
2361
- * endpoint. The details list the missing endpoints.
2362
- *
2363
- * A refused document stores nothing, and on a revise the current revision
2364
- * stays unchanged.
2365
- * @summary Create or revise an identity provider connection
2366
- */
2367
- const createIdp = async (createIdpBody, params, options) => {
2368
- const getHeaders = (h) => {
2369
- if (!h) return {};
2370
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2371
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2372
- const headers = {};
2373
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2374
- return headers;
2375
- };
2376
- return customFetch(getCreateIdpUrl(params), {
2377
- ...options,
2378
- method: "POST",
2379
- headers: {
2380
- "Content-Type": "application/json",
2381
- ...getHeaders(options?.headers)
2382
- },
2383
- body: JSON.stringify(createIdpBody)
2384
- });
2385
- };
2386
- const getQueryIdpsUrl = (params) => {
2387
- const normalizedParams = new URLSearchParams();
2388
- Object.entries(params || {}).forEach(([key, value]) => {
2389
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2390
- });
2391
- const stringifiedParams = normalizedParams.toString();
2392
- return stringifiedParams.length > 0 ? `${getProxyPath()}/idps/query?${stringifiedParams}` : `${getProxyPath()}/idps/query`;
2393
- };
2394
- /**
2395
- * Returns the identity provider connections of a project, paginated with a
2396
- * cursor. One row per connection, carrying its newest revision.
2397
- * @summary Query identity provider connections
2398
- */
2399
- const queryIdps = async (queryIdpsBody, params, options) => {
2400
- const getHeaders = (h) => {
2401
- if (!h) return {};
2402
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2403
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2404
- const headers = {};
2405
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2406
- return headers;
2407
- };
2408
- return customFetch(getQueryIdpsUrl(params), {
2409
- ...options,
2410
- method: "POST",
2411
- headers: {
2412
- "Content-Type": "application/json",
2413
- ...getHeaders(options?.headers)
2414
- },
2415
- body: JSON.stringify(queryIdpsBody)
2416
- });
2417
- };
2418
- const getGetIdpByIdUrl = (id, params) => {
2419
- const normalizedParams = new URLSearchParams();
2420
- Object.entries(params || {}).forEach(([key, value]) => {
2421
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2422
- });
2423
- const stringifiedParams = normalizedParams.toString();
2424
- return stringifiedParams.length > 0 ? `${getProxyPath()}/idps/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/idps/${encodeURIComponent(String(id))}`;
2425
- };
2426
- /**
2427
- * Reads a connection by its id, at its newest revision.
2428
- * `GET /idps/{id}/revisions` lists every revision of the connection.
2429
- *
2430
- * The lookup is scoped to the project in `project_id`.
2431
- * @summary Get an identity provider connection by id
2432
- */
2433
- const getIdpById = async (id, params, options) => {
2434
- return customFetch(getGetIdpByIdUrl(id, params), {
2435
- ...options,
2436
- method: "GET"
2437
- });
2438
- };
2439
- const getListIdpRevisionsUrl = (id, params) => {
2440
- const normalizedParams = new URLSearchParams();
2441
- Object.entries(params || {}).forEach(([key, value]) => {
2442
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2443
- });
2444
- const stringifiedParams = normalizedParams.toString();
2445
- return stringifiedParams.length > 0 ? `${getProxyPath()}/idps/${encodeURIComponent(String(id))}/revisions?${stringifiedParams}` : `${getProxyPath()}/idps/${encodeURIComponent(String(id))}/revisions`;
2446
- };
2447
- /**
2448
- * Returns every revision of one connection, newest first, paginated with a
2449
- * cursor. The order is fixed, so there is no `sorting`.
2450
- *
2451
- * The lookup is scoped to the project in `project_id`.
2452
- * @summary List the revisions of an identity provider connection
2453
- */
2454
- const listIdpRevisions = async (id, params, options) => {
2455
- return customFetch(getListIdpRevisionsUrl(id, params), {
2456
- ...options,
2457
- method: "GET"
2458
- });
2459
- };
2460
- const getGetIdpRevisionByIdUrl = (revisionId, params) => {
2461
- const normalizedParams = new URLSearchParams();
2462
- Object.entries(params || {}).forEach(([key, value]) => {
2463
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2464
- });
2465
- const stringifiedParams = normalizedParams.toString();
2466
- return stringifiedParams.length > 0 ? `${getProxyPath()}/idps/revisions/${encodeURIComponent(String(revisionId))}?${stringifiedParams}` : `${getProxyPath()}/idps/revisions/${encodeURIComponent(String(revisionId))}`;
2467
- };
2468
- /**
2469
- * Reads one revision of a connection by its `revision_id`, the value an auth
2470
- * attempt or a release pins.
2471
- *
2472
- * The lookup is scoped to the project in `project_id`.
2473
- * @summary Get one revision of an identity provider connection
2474
- */
2475
- const getIdpRevisionById = async (revisionId, params, options) => {
2476
- return customFetch(getGetIdpRevisionByIdUrl(revisionId, params), {
2477
- ...options,
2478
- method: "GET"
2479
- });
2480
- };
2481
- const getListPoliciesUrl = (params) => {
2482
- const normalizedParams = new URLSearchParams();
2483
- Object.entries(params || {}).forEach(([key, value]) => {
2484
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2485
- });
2486
- const stringifiedParams = normalizedParams.toString();
2487
- return stringifiedParams.length > 0 ? `${getProxyPath()}/policies?${stringifiedParams}` : `${getProxyPath()}/policies`;
2488
- };
2489
- /**
2490
- * Lists the project's policies, one per operation, each as its newest
2491
- * revision, ordered by `created_at` (first publish) and then `id`. Filter
2492
- * by `operation` to read the policy of one operation; a project that never
2493
- * published one gets an empty list.
2494
- *
2495
- * The lookup is scoped to the project in `project_id`.
2496
- * @summary List policies
2497
- */
2498
- const listPolicies = async (params, options) => {
2499
- return customFetch(getListPoliciesUrl(params), {
2500
- ...options,
2501
- method: "GET"
2502
- });
2503
- };
2504
- const getPublishPolicyUrl = (params) => {
2505
- const normalizedParams = new URLSearchParams();
2506
- Object.entries(params || {}).forEach(([key, value]) => {
2507
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2508
- });
2509
- const stringifiedParams = normalizedParams.toString();
2510
- return stringifiedParams.length > 0 ? `${getProxyPath()}/policies?${stringifiedParams}` : `${getProxyPath()}/policies`;
2511
- };
2512
- /**
2513
- * Publishes the project's policy for an operation as a new immutable
2514
- * revision, creating the policy on its first publish. The newest revision
2515
- * applies to the next time the operation runs; nothing already stored is
2516
- * re-evaluated, so a stricter password policy applies the next time a
2517
- * password is set.
2518
- *
2519
- * The request is typed by `operation`: an unknown operation or setting, or
2520
- * a value of the wrong type or outside its bounds, answers `req.invalid`
2521
- * like any malformed request. The operation's template then checks the
2522
- * config again, together with the rules that relate settings to each other
2523
- * (a `min_length` above `max_length`), and answers `pol.invalid`. Its
2524
- * `details.details.violations` lists everything that failed, settings
2525
- * first, then rules: `{"setting": "min_length"}` for one setting, or
2526
- * `{"config_rule": "min_length_not_above_max_length", "settings":
2527
- * ["min_length", "max_length"]}` for a rule across settings, with the
2528
- * settings it reads. A setting left out is off, and `{}` switches every
2529
- * rule off; there are no defaults.
2530
- * @summary Publish a policy
2531
- */
2532
- const publishPolicy = async (publishPolicyBody, params, options) => {
2533
- const getHeaders = (h) => {
2534
- if (!h) return {};
2535
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2536
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2537
- const headers = {};
2538
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2539
- return headers;
2540
- };
2541
- return customFetch(getPublishPolicyUrl(params), {
2542
- ...options,
2543
- method: "POST",
2544
- headers: {
2545
- "Content-Type": "application/json",
2546
- ...getHeaders(options?.headers)
2547
- },
2548
- body: JSON.stringify(publishPolicyBody)
2549
- });
2550
- };
2551
- const getEvaluatePolicyUrl = (params) => {
2552
- const normalizedParams = new URLSearchParams();
2553
- Object.entries(params || {}).forEach(([key, value]) => {
2554
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2555
- });
2556
- const stringifiedParams = normalizedParams.toString();
2557
- return stringifiedParams.length > 0 ? `${getProxyPath()}/policies/evaluate?${stringifiedParams}` : `${getProxyPath()}/policies/evaluate`;
2558
- };
2559
- /**
2560
- * Evaluates a policy config against one request, without side effects, and
2561
- * answers the decision the operation would reach. Nothing is read from or
2562
- * written to the project: the config is the one in the body, checked
2563
- * exactly as a publish checks it, so an invalid config answers `pol.invalid`
2564
- * with the same violations.
2565
- *
2566
- * `input` is what the operation's request carries, in the operation's own
2567
- * terms (a password, not its length): the server derives what the policy
2568
- * checks with the code the live operation runs, guards included. `facts`
2569
- * states what the operation would look up at runtime, such as whether the
2570
- * candidate matches one of the user's kept passwords.
2571
- *
2572
- * The decision and the names of the failed rules hold wherever the
2573
- * operation runs. `code` and `violations` are what an API call answers; a
2574
- * login flow shows the same rules as field errors on the password field
2575
- * (`error.x-auth-methods#password_<rule>` in `step.error`).
2576
- *
2577
- * Which policy a project or release applies is not decided here: read it
2578
- * and pass its config.
2579
- *
2580
- * The caller needs read access to the project in `project_id`.
2581
- * @summary Evaluate a policy
2582
- */
2583
- const evaluatePolicy = async (evaluatePolicyBody, params, options) => {
2584
- const getHeaders = (h) => {
2585
- if (!h) return {};
2586
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2587
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2588
- const headers = {};
2589
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2590
- return headers;
2591
- };
2592
- return customFetch(getEvaluatePolicyUrl(params), {
2593
- ...options,
2594
- method: "POST",
2595
- headers: {
2596
- "Content-Type": "application/json",
2597
- ...getHeaders(options?.headers)
2598
- },
2599
- body: JSON.stringify(evaluatePolicyBody)
2600
- });
2601
- };
2602
- const getGetPolicyUrl = (policyId, params) => {
2603
- const normalizedParams = new URLSearchParams();
2604
- Object.entries(params || {}).forEach(([key, value]) => {
2605
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2606
- });
2607
- const stringifiedParams = normalizedParams.toString();
2608
- return stringifiedParams.length > 0 ? `${getProxyPath()}/policies/${encodeURIComponent(String(policyId))}?${stringifiedParams}` : `${getProxyPath()}/policies/${encodeURIComponent(String(policyId))}`;
2609
- };
2610
- /**
2611
- * Reads a policy as its newest revision, the one that applies the next time
2612
- * its operation runs.
2613
- *
2614
- * The lookup is scoped to the project in `project_id`: a policy of another
2615
- * project answers not found exactly as an unknown id does.
2616
- * @summary Get a policy
2617
- */
2618
- const getPolicy = async (policyId, params, options) => {
2619
- return customFetch(getGetPolicyUrl(policyId, params), {
2620
- ...options,
2621
- method: "GET"
2622
- });
2623
- };
2624
- const getListPolicyRevisionsUrl = (policyId, params) => {
2625
- const normalizedParams = new URLSearchParams();
2626
- Object.entries(params || {}).forEach(([key, value]) => {
2627
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2628
- });
2629
- const stringifiedParams = normalizedParams.toString();
2630
- return stringifiedParams.length > 0 ? `${getProxyPath()}/policies/${encodeURIComponent(String(policyId))}/revisions?${stringifiedParams}` : `${getProxyPath()}/policies/${encodeURIComponent(String(policyId))}/revisions`;
2631
- };
2632
- /**
2633
- * Returns every revision of one policy, newest first, paginated with a
2634
- * cursor. The order is fixed, so there is no `sorting`.
2635
- *
2636
- * The lookup is scoped to the project in `project_id`: a policy of another
2637
- * project answers not found exactly as an unknown id does.
2638
- * @summary List the revisions of a policy
2639
- */
2640
- const listPolicyRevisions = async (policyId, params, options) => {
2641
- return customFetch(getListPolicyRevisionsUrl(policyId, params), {
2642
- ...options,
2643
- method: "GET"
2644
- });
2645
- };
2646
- const getGetPolicyRevisionUrl = (revisionId, params) => {
2647
- const normalizedParams = new URLSearchParams();
2648
- Object.entries(params || {}).forEach(([key, value]) => {
2649
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2650
- });
2651
- const stringifiedParams = normalizedParams.toString();
2652
- return stringifiedParams.length > 0 ? `${getProxyPath()}/policies/revisions/${encodeURIComponent(String(revisionId))}?${stringifiedParams}` : `${getProxyPath()}/policies/revisions/${encodeURIComponent(String(revisionId))}`;
2653
- };
2654
- /**
2655
- * Reads one revision of a policy, newest or not.
2656
- *
2657
- * The lookup is scoped to the project in `project_id`: a revision of another
2658
- * project answers not found exactly as an unknown id does.
2659
- * @summary Get a policy revision
2660
- */
2661
- const getPolicyRevision = async (revisionId, params, options) => {
2662
- return customFetch(getGetPolicyRevisionUrl(revisionId, params), {
2663
- ...options,
2664
- method: "GET"
2665
- });
2666
- };
2667
- const getCreateReleaseUrl = (params) => {
2668
- const normalizedParams = new URLSearchParams();
2669
- Object.entries(params || {}).forEach(([key, value]) => {
2670
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2671
- });
2672
- const stringifiedParams = normalizedParams.toString();
2673
- return stringifiedParams.length > 0 ? `${getProxyPath()}/releases?${stringifiedParams}` : `${getProxyPath()}/releases`;
2674
- };
2675
- /**
2676
- * Assembles a release from existing revisions, given as
2677
- * `(kind, revision_id)` pairs. To build one from files on disk, use
2678
- * `POST /releases/build`.
2679
- *
2680
- * Each revision must exist in the project and is recorded under the handle
2681
- * it declares. The release must be complete and consistent:
2682
- *
2683
- * - Every handle its revisions name must be in the release: a flow's
2684
- * `user_schema`, and the IDP connections named by a flow step's
2685
- * `sso_providers` or a schema's `x-auth-methods.sso.providers`. A missing
2686
- * one answers `rel.unresolved_reference`, naming the resource and the
2687
- * handle, e.g. `flow_definition default-login: user_schema human-user not found`.
2688
- * - Every flow is validated as on save, against the user schema revision
2689
- * in the release. A flow that fails answers `rel.invalid`, with the
2690
- * reason in `details`.
2691
- *
2692
- * Idempotent on the set of revisions: the same revisions with a different
2693
- * `message` answer `200` with the existing release. A new release answers
2694
- * `201`. Creating a release does not deploy it.
2695
- * @summary Create a release
2696
- */
2697
- const createRelease = async (createReleaseBody, params, options) => {
2698
- const getHeaders = (h) => {
2699
- if (!h) return {};
2700
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2701
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2702
- const headers = {};
2703
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2704
- return headers;
2705
- };
2706
- return customFetch(getCreateReleaseUrl(params), {
2707
- ...options,
2708
- method: "POST",
2709
- headers: {
2710
- "Content-Type": "application/json",
2711
- ...getHeaders(options?.headers)
2712
- },
2713
- body: JSON.stringify(createReleaseBody)
2714
- });
2715
- };
2716
- const getListReleasesUrl = (params) => {
2717
- const normalizedParams = new URLSearchParams();
2718
- Object.entries(params || {}).forEach(([key, value]) => {
2719
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2720
- });
2721
- const stringifiedParams = normalizedParams.toString();
2722
- return stringifiedParams.length > 0 ? `${getProxyPath()}/releases?${stringifiedParams}` : `${getProxyPath()}/releases`;
2723
- };
2724
- /**
2725
- * Lists the project's releases, newest first.
2726
- *
2727
- * Entries carry the digest, the metadata and `revoked_at` — the pinned set
2728
- * is omitted.
2729
- * Read one release with `GET /releases/{release_id}` to get its pointers.
2730
- *
2731
- * `content_hash` looks a release up by its content, as the CLI does when a
2732
- * person types the digest a transcript printed. The project holds at most
2733
- * one release per digest, so the filtered list has one entry or none, and
2734
- * an unknown digest is an empty list rather than an error. Paths take the
2735
- * `rel_` id only; the matched entry's `id` is what to use there.
2736
- * @summary List releases
2737
- */
2738
- const listReleases = async (params, options) => {
2739
- return customFetch(getListReleasesUrl(params), {
2740
- ...options,
2741
- method: "GET"
2742
- });
2743
- };
2744
- const getBuildReleaseUrl = (params) => {
2745
- const normalizedParams = new URLSearchParams();
2746
- Object.entries(params || {}).forEach(([key, value]) => {
2747
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2748
- });
2749
- const stringifiedParams = normalizedParams.toString();
2750
- return stringifiedParams.length > 0 ? `${getProxyPath()}/releases/build?${stringifiedParams}` : `${getProxyPath()}/releases/build`;
2751
- };
2752
- /**
2753
- * Builds a release from the resources of `.zitadel/` as authored on disk,
2754
- * grouped by kind, in one transaction: a failure anywhere leaves no
2755
- * revision and no release. The caller records nothing.
2756
- *
2757
- * If the project already holds a release with the same content, the same
2758
- * `content_hash`, the request answers `200` with that release and
2759
- * allocates nothing, however long ago it was built. Otherwise every resource is compared against the
2760
- * project's newest revision of the same handle: unchanged content reuses
2761
- * that revision, changed content allocates a new one, and the request
2762
- * answers `201` with the new release. A policy whose config matches only an
2763
- * older revision allocates a new one too, so a request that resolves no
2764
- * release, which reads the newest revision, applies it as well. Metadata is excluded from the
2765
- * comparison, so the same content under a different `message` is the same
2766
- * release.
2767
- *
2768
- * A structurally malformed request is refused while decoding with
2769
- * `req.invalid`, naming the offending fields. A well-formed bundle is then
2770
- * checked resource by resource, as each kind's create endpoint checks it,
2771
- * and every failure is reported at once: the request answers `400` with
2772
- * `rel.invalid`, and `details.resources` lists each resource that failed.
2773
- * A handle that resolves neither in the bundle nor in the project answers
2774
- * `rel.unresolved_reference`, naming the pointer and the handle.
2775
- *
2776
- * Building writes revisions, so besides `release.write` it needs the write
2777
- * scope of every kind the bundle carries a resource of: `schema.write`,
2778
- * `flow_definition.write`, `branding.write`, `idp.write` and
2779
- * `policy.write`, as the per-kind create endpoints do. A missing scope answers `403` with `rel.permission_denied`,
2780
- * naming the kind. An empty kind needs no scope.
2781
- *
2782
- * Building a release does not deploy it. A release is not tied to an
2783
- * origin, and the same release can later be deployed to any number of
2784
- * origins unchanged.
2785
- * @summary Build a release from files
2786
- */
2787
- const buildRelease = async (buildReleaseBody, params, options) => {
2788
- const getHeaders = (h) => {
2789
- if (!h) return {};
2790
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2791
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2792
- const headers = {};
2793
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2794
- return headers;
2795
- };
2796
- return customFetch(getBuildReleaseUrl(params), {
2797
- ...options,
2798
- method: "POST",
2799
- headers: {
2800
- "Content-Type": "application/json",
2801
- ...getHeaders(options?.headers)
2802
- },
2803
- body: JSON.stringify(buildReleaseBody)
2804
- });
2805
- };
2806
- const getGetReleaseByIdUrl = (releaseId, params) => {
2807
- const normalizedParams = new URLSearchParams();
2808
- Object.entries(params || {}).forEach(([key, value]) => {
2809
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2810
- });
2811
- const stringifiedParams = normalizedParams.toString();
2812
- return stringifiedParams.length > 0 ? `${getProxyPath()}/releases/${encodeURIComponent(String(releaseId))}?${stringifiedParams}` : `${getProxyPath()}/releases/${encodeURIComponent(String(releaseId))}`;
2813
- };
2814
- /**
2815
- * Reads one release: its digest, its metadata, whether it was revoked, and
2816
- * the `(kind, handle, revision_id)` tuples it pins.
2817
- *
2818
- * The path takes the `rel_` id only. To find a release from its digest,
2819
- * list with the `content_hash` filter and read the matched entry's `id`.
2820
- *
2821
- * Does not embed resource content. Resolve each `revision_id` through the
2822
- * per-kind read endpoints when the bytes are needed.
2823
- *
2824
- * The lookup is scoped to the project in `project_id`: a release id belonging
2825
- * to another project answers not found exactly as an unknown id does, so the
2826
- * endpoint cannot be used to probe for releases in projects the caller cannot
2827
- * read.
2828
- * @summary Get a release by id
2829
- */
2830
- const getReleaseById = async (releaseId, params, options) => {
2831
- return customFetch(getGetReleaseByIdUrl(releaseId, params), {
2832
- ...options,
2833
- method: "GET"
2834
- });
2835
- };
2836
- const getRevokeReleaseUrl = (releaseId, params) => {
2837
- const normalizedParams = new URLSearchParams();
2838
- Object.entries(params || {}).forEach(([key, value]) => {
2839
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2840
- });
2841
- const stringifiedParams = normalizedParams.toString();
2842
- return stringifiedParams.length > 0 ? `${getProxyPath()}/releases/${encodeURIComponent(String(releaseId))}/revoke?${stringifiedParams}` : `${getProxyPath()}/releases/${encodeURIComponent(String(releaseId))}/revoke`;
2843
- };
2844
- /**
2845
- * Marks the release revoked, so that its content is never served again.
2846
- * From then on the release cannot be deployed and is refused on every path
2847
- * that would serve it, including to a build that pins its digest, with
2848
- * `rel.revoked`.
2849
- *
2850
- * A release that any origin still serves cannot be revoked. An origin
2851
- * serves the release of the newest deployment to it, so the call answers
2852
- * `409` with `rel.in_use`, naming each such origin and that deployment.
2853
- * Deploy another release there or roll back first, then revoke. Revoking
2854
- * therefore never takes an origin down. Deployments that named the release
2855
- * earlier stay in the history.
2856
- *
2857
- * Idempotent: revoking a release that is already revoked answers `200`
2858
- * with the release unchanged, `revoked_at` still naming the first
2859
- * revocation. There is no un-revoke; build a new release instead.
2860
- *
2861
- * Takes no body. The lookup is scoped to the project in `project_id`, so a
2862
- * release id of another project answers not found exactly as an unknown id
2863
- * does.
2864
- * @summary Revoke a release
2865
- */
2866
- const revokeRelease = async (releaseId, params, options) => {
2867
- return customFetch(getRevokeReleaseUrl(releaseId, params), {
2868
- ...options,
2869
- method: "POST"
2870
- });
2871
- };
2872
- const getCreateGrantUrl = (params) => {
2873
- const normalizedParams = new URLSearchParams();
2874
- Object.entries(params || {}).forEach(([key, value]) => {
2875
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2876
- });
2877
- const stringifiedParams = normalizedParams.toString();
2878
- return stringifiedParams.length > 0 ? `${getProxyPath()}/grants?${stringifiedParams}` : `${getProxyPath()}/grants`;
2879
- };
2880
- /**
2881
- * Bind a user or team to `project.viewer`, `project.editor`, or
2882
- * `project.admin` on the project identified by the `project-id` header.
2883
- * Name the principal with `user` (`user_id` or `identifier`) or `team`
2884
- * (`team_id` or `name`). IDs are `asgn_<opaque>`. Owning-team
2885
- * (`project.team`) grants are not created here — claim owns that path. An
2886
- * unrevoked grant with the same principal and relation occupies the unique
2887
- * key even after `expires_at`; DELETE it before re-creating.
2888
- * Create does not accept `expand`. The `user_id` and team locators
2889
- * return 201, whose `user` / `team` carry only `user_id` / `team_id`,
2890
- * and still 404 / 409 when the principal is missing or the tuple
2891
- * already exists. Creating by `user.identifier` answers 202 with no
2892
- * body on every outcome. Granting the session caller's own user is
2893
- * `grant.invalid` on either user locator. Read the grant back for
2894
- * identifier and display.
2895
- *
2896
- * Accepts either a project secret (`oauth2`) or a user-bound Console
2897
- * session cookie (`nextgenSession`). Session callers are authorized as
2898
- * the human against the target project (home may differ). Cookie-authenticated
2899
- * requests follow the scheme's CSRF rules (`nextgenSession`).
2900
- * @summary Create grant
2901
- */
2902
- const createGrant = async (createGrantBody, params, options) => {
2903
- const getHeaders = (h) => {
2904
- if (!h) return {};
2905
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2906
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2907
- const headers = {};
2908
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2909
- return headers;
2910
- };
2911
- return customFetch(getCreateGrantUrl(params), {
2912
- ...options,
2913
- method: "POST",
2914
- headers: {
2915
- "Content-Type": "application/json",
2916
- ...getHeaders(options?.headers)
2917
- },
2918
- body: JSON.stringify(createGrantBody)
2919
- });
2920
- };
2921
- const getQueryGrantsUrl = (params) => {
2922
- const normalizedParams = new URLSearchParams();
2923
- Object.entries(params || {}).forEach(([key, value]) => {
2924
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2925
- });
2926
- const stringifiedParams = normalizedParams.toString();
2927
- return stringifiedParams.length > 0 ? `${getProxyPath()}/grants/query?${stringifiedParams}` : `${getProxyPath()}/grants/query`;
2928
- };
2929
- /**
2930
- * Returns the collaboration grants of a project, paginated with a cursor.
2931
- * Only unrevoked grants this API manages are listed (user or team bound to
2932
- * viewer, editor, or admin), including expired grants so a client can
2933
- * DELETE before re-granting. Project-secret setup (`sk_proj`) and
2934
- * owning-team (`relation=team`) rows are not returned. Grants are not in
2935
- * `resource_scope_index`; project scope is required on the query (same as
2936
- * get). Requires `project.read`. `expand: ["principal"]` adds envelope
2937
- * fields on `user` / `team` and additionally requires `user.read` and
2938
- * `team.read` for project secrets (documented on the expand enum; those
2939
- * scopes cannot be ANDed onto this security block because they are
2940
- * body-conditional). A user-bound Console session that already passed
2941
- * the project Check may expand without those scopes.
2942
- *
2943
- * Accepts either a project secret (`oauth2`) or a user-bound Console
2944
- * session cookie (`nextgenSession`). Cookie-authenticated requests
2945
- * follow the scheme's CSRF rules (`nextgenSession`).
2946
- * @summary Query grants
2947
- */
2948
- const queryGrants = async (queryGrantsBody, params, options) => {
2949
- const getHeaders = (h) => {
2950
- if (!h) return {};
2951
- if (h instanceof Headers) return Object.fromEntries(h.entries());
2952
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2953
- const headers = {};
2954
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2955
- return headers;
2956
- };
2957
- return customFetch(getQueryGrantsUrl(params), {
2958
- ...options,
2959
- method: "POST",
2960
- headers: {
2961
- "Content-Type": "application/json",
2962
- ...getHeaders(options?.headers)
2963
- },
2964
- body: JSON.stringify(queryGrantsBody)
2965
- });
2966
- };
2967
- const getGetGrantUrl = (id, params) => {
2968
- const normalizedParams = new URLSearchParams();
2969
- Object.entries(params || {}).forEach(([key, value]) => {
2970
- if (Array.isArray(value) && ["expand"].includes(key)) {
2971
- value.forEach((v) => {
2972
- normalizedParams.append(key, v === null ? "null" : String(v));
2973
- });
2974
- return;
2975
- }
2976
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2977
- });
2978
- const stringifiedParams = normalizedParams.toString();
2979
- return stringifiedParams.length > 0 ? `${getProxyPath()}/grants/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/grants/${encodeURIComponent(String(id))}`;
2980
- };
2981
- /**
2982
- * Loads a grant by `(project_id, id)` that this API manages (user or team
2983
- * bound to viewer, editor, or admin) and that has not been revoked.
2984
- * "Active" here means not revoked: expired grants stay visible so the
2985
- * client can DELETE before re-granting the same binding. Authorization
2986
- * still ignores expired grants. Grants are not registered in
2987
- * `resource_scope_index`; project scope is required on the query (same as
2988
- * events). Misses, revoked rows, project-secret setup (`sk_proj`),
2989
- * owning-team (`relation=team`) rows, and cross-project ids return 404.
2990
- * `expand=principal` adds envelope fields on `user` or `team` and requires
2991
- * `user.read` and `team.read` in addition to `project.read` for project
2992
- * secrets. A user-bound Console session that already passed the project
2993
- * Check may expand without those scopes.
2994
- *
2995
- * Accepts either a project secret (`oauth2`) or a user-bound Console
2996
- * session cookie (`nextgenSession`). Cookie-authenticated requests
2997
- * follow the scheme's CSRF rules (`nextgenSession`).
2998
- * @summary Get grant
2999
- */
3000
- const getGrant = async (id, params, options) => {
3001
- return customFetch(getGetGrantUrl(id, params), {
3002
- ...options,
3003
- method: "GET"
3004
- });
3005
- };
3006
- const getDeleteGrantUrl = (id, params) => {
3007
- const normalizedParams = new URLSearchParams();
3008
- Object.entries(params || {}).forEach(([key, value]) => {
3009
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3010
- });
3011
- const stringifiedParams = normalizedParams.toString();
3012
- return stringifiedParams.length > 0 ? `${getProxyPath()}/grants/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/grants/${encodeURIComponent(String(id))}`;
3013
- };
3014
- /**
3015
- * Soft-revokes a grant this API manages and emits `authz.revoked`.
3016
- * Already-revoked, missing, project-secret setup, and owning-team grants
3017
- * return 404. The row is not un-revoked. Expired grants can still be
3018
- * revoked so the unique binding can be reused.
3019
- *
3020
- * Accepts either a project secret (`oauth2`) or a user-bound Console
3021
- * session cookie (`nextgenSession`). Cookie-authenticated requests
3022
- * follow the scheme's CSRF rules (`nextgenSession`).
3023
- * @summary Revoke grant
3024
- */
3025
- const deleteGrant = async (id, params, options) => {
3026
- return customFetch(getDeleteGrantUrl(id, params), {
3027
- ...options,
3028
- method: "DELETE"
3029
- });
3030
- };
3031
- const getListEventsUrl = (params) => {
3032
- const normalizedParams = new URLSearchParams();
3033
- Object.entries(params || {}).forEach(([key, value]) => {
3034
- if (Array.isArray(value) && ["category", "event_type"].includes(key)) {
3035
- value.forEach((v) => {
3036
- normalizedParams.append(key, v === null ? "null" : String(v));
3037
- });
3038
- return;
3039
- }
3040
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3041
- });
3042
- const stringifiedParams = normalizedParams.toString();
3043
- return stringifiedParams.length > 0 ? `${getProxyPath()}/events?${stringifiedParams}` : `${getProxyPath()}/events`;
3044
- };
3045
- /**
3046
- * Returns project-scoped audit events, newest-first by keyset on
3047
- * `(created_at, id)` (ADR 027 / ADR 049). Pass `order=asc` for oldest-first.
3048
- * Requires `events.read`.
3049
- *
3050
- * Pre-claim projects return an empty list (events are stored but not
3051
- * visible until claim succeeds). Team-scoped credentials see only events
3052
- * whose emit-time `team_id` matches the credential team (enforced when
3053
- * team-scoped tokens exist).
3054
- *
3055
- * Clients discriminate each item via `event_type` (OpenAPI Event oneOf) —
3056
- * see docs/design/api/events-catalog.md.
3057
- * @summary List events
3058
- */
3059
- const listEvents = async (params, options) => {
3060
- return customFetch(getListEventsUrl(params), {
3061
- ...options,
3062
- method: "GET"
3063
- });
3064
- };
3065
- const getGetEventUrl = (id, params) => {
3066
- const normalizedParams = new URLSearchParams();
3067
- Object.entries(params || {}).forEach(([key, value]) => {
3068
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3069
- });
3070
- const stringifiedParams = normalizedParams.toString();
3071
- return stringifiedParams.length > 0 ? `${getProxyPath()}/events/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/events/${encodeURIComponent(String(id))}`;
3072
- };
3073
- /**
3074
- * Loads a single event by `(project_id, id)`. Requires `events.read`.
3075
- * Events are not registered in `resource_scope_index`; project scope is
3076
- * required on the query (ADR 049). Misses and cross-project ids return 404.
3077
- *
3078
- * Pre-claim projects return 404 (stored events stay invisible until claim).
3079
- * @summary Get event by ID
3080
- */
3081
- const getEvent = async (id, params, options) => {
3082
- return customFetch(getGetEventUrl(id, params), {
3083
- ...options,
3084
- method: "GET"
3085
- });
3086
- };
3087
- const getGetVariablesUrl = (params) => {
3088
- const normalizedParams = new URLSearchParams();
3089
- Object.entries(params || {}).forEach(([key, value]) => {
3090
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3091
- });
3092
- const stringifiedParams = normalizedParams.toString();
3093
- return stringifiedParams.length > 0 ? `${getProxyPath()}/variables?${stringifiedParams}` : `${getProxyPath()}/variables`;
3094
- };
3095
- /**
3096
- * Returns the project's variables, keyed by name, each with its value per
3097
- * kind. With `kind`, only that kind's values are returned.
3098
- *
3099
- * Secret values are not returned. A secret appears as `{"secret": true}`,
3100
- * which says a value is held without disclosing it.
3101
- * @summary Get variables
3102
- */
3103
- const getVariables = async (params, options) => {
3104
- return customFetch(getGetVariablesUrl(params), {
3105
- ...options,
3106
- method: "GET"
3107
- });
3108
- };
3109
- const getUpdateVariablesUrl = (params) => {
3110
- const normalizedParams = new URLSearchParams();
3111
- Object.entries(params || {}).forEach(([key, value]) => {
3112
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3113
- });
3114
- const stringifiedParams = normalizedParams.toString();
3115
- return stringifiedParams.length > 0 ? `${getProxyPath()}/variables?${stringifiedParams}` : `${getProxyPath()}/variables`;
3116
- };
3117
- /**
3118
- * Enters, replaces and removes the project's variables for the requested
3119
- * kind. Names not in the body are untouched. Existing deployments keep the
3120
- * values they froze.
3121
- *
3122
- * Without `kind`, a plain value is written for both kinds. A secret is
3123
- * written for `primary` only and removes the name's `preview` value, so a
3124
- * preview never keeps a plaintext copy; set a preview secret with
3125
- * `kind=preview`. `null` removes the name from both.
3126
- *
3127
- * A bare scalar enters a non-secret value. `{"value": …, "secret": true}`
3128
- * stores the value encrypted under the project's active `secret` key, after
3129
- * which it can be referenced but not read back. `null` removes the name
3130
- * (RFC 7386), which is how several variables are removed in one request;
3131
- * removing a name the project does not hold is a no-op rather than an error.
3132
- *
3133
- * The body is applied whole or not at all, so a rejected request leaves the
3134
- * project's variables exactly as they were. Writing the same name twice
3135
- * replaces the value rather than duplicating it, which makes a retry safe.
3136
- * @summary Update variables
3137
- */
3138
- const updateVariables = async (updateVariablesBody, params, options) => {
3139
- const getHeaders = (h) => {
3140
- if (!h) return {};
3141
- if (h instanceof Headers) return Object.fromEntries(h.entries());
3142
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
3143
- const headers = {};
3144
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
3145
- return headers;
3146
- };
3147
- return customFetch(getUpdateVariablesUrl(params), {
3148
- ...options,
3149
- method: "PATCH",
3150
- headers: {
3151
- "Content-Type": "application/json",
3152
- ...getHeaders(options?.headers)
3153
- },
3154
- body: JSON.stringify(updateVariablesBody)
3155
- });
3156
- };
3157
- const getGetVariableUrl = (variableName, params) => {
3158
- const normalizedParams = new URLSearchParams();
3159
- Object.entries(params || {}).forEach(([key, value]) => {
3160
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3161
- });
3162
- const stringifiedParams = normalizedParams.toString();
3163
- return stringifiedParams.length > 0 ? `${getProxyPath()}/variables/${encodeURIComponent(String(variableName))}?${stringifiedParams}` : `${getProxyPath()}/variables/${encodeURIComponent(String(variableName))}`;
3164
- };
3165
- /**
3166
- * Reads one variable by name, with its value per kind. A name with no
3167
- * value for the requested kind answers `var.not_found`. A secret reads
3168
- * back as `{"secret": true}`.
3169
- * @summary Get a variable
3170
- */
3171
- const getVariable = async (variableName, params, options) => {
3172
- return customFetch(getGetVariableUrl(variableName, params), {
3173
- ...options,
3174
- method: "GET"
3175
- });
3176
- };
3177
- const getDeleteVariableUrl = (variableName, params) => {
3178
- const normalizedParams = new URLSearchParams();
3179
- Object.entries(params || {}).forEach(([key, value]) => {
3180
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3181
- });
3182
- const stringifiedParams = normalizedParams.toString();
3183
- return stringifiedParams.length > 0 ? `${getProxyPath()}/variables/${encodeURIComponent(String(variableName))}?${stringifiedParams}` : `${getProxyPath()}/variables/${encodeURIComponent(String(variableName))}`;
3184
- };
3185
- /**
3186
- * Removes a variable for the requested kind, or for both kinds without
3187
- * `kind`. A name with no value for that kind answers `var.not_found`.
3188
- * Existing deployments keep the values they froze.
3189
- * @summary Delete a variable
3190
- */
3191
- const deleteVariable = async (variableName, params, options) => {
3192
- return customFetch(getDeleteVariableUrl(variableName, params), {
3193
- ...options,
3194
- method: "DELETE"
3195
- });
3196
- };
3197
- const getCreateDeploymentUrl = (params) => {
3198
- const normalizedParams = new URLSearchParams();
3199
- Object.entries(params || {}).forEach(([key, value]) => {
3200
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3201
- });
3202
- const stringifiedParams = normalizedParams.toString();
3203
- return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments?${stringifiedParams}` : `${getProxyPath()}/deployments`;
3204
- };
3205
- /**
3206
- * Makes a release live on its targets by recording a deployment,
3207
- * atomically: on success every target serves the release and the record
3208
- * exists; on failure nothing changes and no record is written.
3209
- *
3210
- * Name the release by exactly one of `release_id` or `content_hash`; it
3211
- * must already exist in the project. `targets` is `primary` or preview
3212
- * URLs. The deployment freezes the project's variable values for its kind,
3213
- * with no fallback between primary and preview values.
3214
- *
3215
- * A deployment to `primary` changes nothing when the project's newest
3216
- * primary deployment has the same release and frozen values and covers
3217
- * exactly the current primary origins: the call answers `200` with that
3218
- * deployment. Any other request writes a new deployment and answers `201`;
3219
- * for preview URLs that record renews their previews.
3220
- *
3221
- * Failures:
3222
- * - `400 dep.invalid`: both or neither of `release_id` and `content_hash`;
3223
- * a primary origin named exactly; `primary` mixed with preview URLs;
3224
- * `primary` on a project with no primary origin; `ttl` with `primary`;
3225
- * `ttl` above 365 days (`P365D`).
3226
- * - `400 dep.variables_missing`: a referenced variable has no value for
3227
- * the kind; `details` names the kind and every missing variable.
3228
- * - `403 proj.origin_not_allowed`: a preview URL matches no preview
3229
- * pattern, or is a loopback URL.
3230
- * - `404 rel.not_found`: the release id or digest names no release here.
3231
- * - `409 dep.conflict`: `expected_deployment_id` is not the deployment
3232
- * this write replaces; `details.deployment` is that deployment.
3233
- * - `409 rel.revoked`: the release is revoked.
3234
- * @summary Create a deployment
3235
- */
3236
- const createDeployment = async (createDeploymentBody, params, options) => {
3237
- const getHeaders = (h) => {
3238
- if (!h) return {};
3239
- if (h instanceof Headers) return Object.fromEntries(h.entries());
3240
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
3241
- const headers = {};
3242
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
3243
- return headers;
3244
- };
3245
- return customFetch(getCreateDeploymentUrl(params), {
3246
- ...options,
3247
- method: "POST",
3248
- headers: {
3249
- "Content-Type": "application/json",
3250
- ...getHeaders(options?.headers)
3251
- },
3252
- body: JSON.stringify(createDeploymentBody)
3253
- });
3254
- };
3255
- const getListDeploymentsUrl = (params) => {
3256
- const normalizedParams = new URLSearchParams();
3257
- Object.entries(params || {}).forEach(([key, value]) => {
3258
- if (Array.isArray(value) && ["expand"].includes(key)) {
3259
- value.forEach((v) => {
3260
- normalizedParams.append(key, v === null ? "null" : String(v));
3261
- });
3262
- return;
3263
- }
3264
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3265
- });
3266
- const stringifiedParams = normalizedParams.toString();
3267
- return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments?${stringifiedParams}` : `${getProxyPath()}/deployments`;
3268
- };
3269
- /**
3270
- * Lists what ran where, and when.
3271
- *
3272
- * By default the list is the history, newest first: every deployment of
3273
- * the project with every target it made the release live on. With
3274
- * `origin`, the history of that origin alone.
3275
- *
3276
- * With `live=true`, the list is what is served now, newest first: the
3277
- * project's newest primary deployment, narrowed to origins that are still
3278
- * primary, and the newest deployment to each live preview URL, narrowed to
3279
- * the URLs it still serves. Combined with `origin`, it is the one
3280
- * deployment that origin serves, or empty.
3281
- *
3282
- * `expand: ["release"]` embeds the release each deployment made live; it
3283
- * requires `release.read` and does not change the ordering or the page
3284
- * tokens.
3285
- * @summary List deployments
3286
- */
3287
- const listDeployments = async (params, options) => {
3288
- return customFetch(getListDeploymentsUrl(params), {
3289
- ...options,
3290
- method: "GET"
3291
- });
3292
- };
3293
- const getGetDeploymentByIdUrl = (deploymentId, params) => {
3294
- const normalizedParams = new URLSearchParams();
3295
- Object.entries(params || {}).forEach(([key, value]) => {
3296
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3297
- });
3298
- const stringifiedParams = normalizedParams.toString();
3299
- return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}?${stringifiedParams}` : `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}`;
3300
- };
3301
- /**
3302
- * Reads one deployment record.
3303
- *
3304
- * The lookup is scoped to the project in `project_id`: a deployment id
3305
- * belonging to another project answers not found exactly as an unknown id
3306
- * does, so the endpoint cannot be used to probe for deployments in projects
3307
- * the caller cannot read.
3308
- * @summary Get a deployment by id
3309
- */
3310
- const getDeploymentById = async (deploymentId, params, options) => {
3311
- return customFetch(getGetDeploymentByIdUrl(deploymentId, params), {
3312
- ...options,
3313
- method: "GET"
3314
- });
3315
- };
3316
- const getRollbackDeploymentUrl = (deploymentId, params) => {
3317
- const normalizedParams = new URLSearchParams();
3318
- Object.entries(params || {}).forEach(([key, value]) => {
3319
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3320
- });
3321
- const stringifiedParams = normalizedParams.toString();
3322
- return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}/rollback?${stringifiedParams}` : `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}/rollback`;
3323
- };
3324
- /**
3325
- * Re-deploys the release of the deployment named in the path to `primary`,
3326
- * with the variable values it froze: a new deployment with `reason:
3327
- * rollback` and `rollback_to` naming it. Like any deployment to `primary`,
3328
- * it covers every current primary origin. Idempotent like a deployment to
3329
- * `primary`: when nothing would change it answers `200` with the newest
3330
- * primary deployment.
3331
- *
3332
- * Failures:
3333
- * - `400 dep.invalid`: the deployment went to preview URLs (deploy to the
3334
- * preview again instead), or the project has no primary origin.
3335
- * - `404 dep.not_found`: no deployment of the project has that id.
3336
- * - `409 dep.conflict`: `expected_deployment_id` is not the project's
3337
- * newest primary deployment; `details.deployment` is that deployment.
3338
- * - `409 rel.revoked`: the release is revoked.
3339
- * @summary Roll back to a deployment
3340
- */
3341
- const rollbackDeployment = async (deploymentId, params, rollbackDeploymentBody, options) => {
3342
- const getHeaders = (h) => {
3343
- if (!h) return {};
3344
- if (h instanceof Headers) return Object.fromEntries(h.entries());
3345
- if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
3346
- const headers = {};
3347
- for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
3348
- return headers;
3349
- };
3350
- return customFetch(getRollbackDeploymentUrl(deploymentId, params), {
3351
- ...options,
3352
- method: "POST",
3353
- headers: {
3354
- "Content-Type": "application/json",
3355
- ...getHeaders(options?.headers)
3356
- },
3357
- body: JSON.stringify(rollbackDeploymentBody)
3358
- });
3359
- };
3360
- const getGetDeploymentVariablesUrl = (deploymentId, params) => {
3361
- const normalizedParams = new URLSearchParams();
3362
- Object.entries(params || {}).forEach(([key, value]) => {
3363
- if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3364
- });
3365
- const stringifiedParams = normalizedParams.toString();
3366
- return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}/variables?${stringifiedParams}` : `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}/variables`;
3367
- };
3368
- /**
3369
- * Returns the variable values the deployment froze when it was made. Later
3370
- * changes to the project's variables do not affect them. A secret reads
3371
- * back as `{"secret": true}`.
3372
- * @summary Get a deployment's variables
3373
- */
3374
- const getDeploymentVariables = async (deploymentId, params, options) => {
3375
- return customFetch(getGetDeploymentVariablesUrl(deploymentId, params), {
3376
- ...options,
3377
- method: "GET"
3378
- });
3379
- };
3380
- //#endregion
3381
- //#region ../api/dist/runtime/api-factory.mjs
3382
- /**
3383
- * Factory for the typed Zitadel client every consumer reaches for.
3384
- *
3385
- * Wraps the orval-generated endpoints in a {@link Proxy} so each
3386
- * generated function sees the right base URL and (optionally) the
3387
- * right bearer token at call time — without the caller having to
3388
- * thread either through every operation, and without exposing the
3389
- * module-globals (`setProxyPath` / `setApiAuthToken`) as part of the
3390
- * public API.
3391
- *
3392
- * Per-instance isolation: multiple clients can coexist in one process
3393
- * (different servers, different tokens). Their Proxy `get` traps set
3394
- * the globals synchronously before invoking the underlying generated
3395
- * function, which reads them at the top of `customFetch` before any
3396
- * `await`. Two clients running interleaved within a single JS turn
3397
- * are safe; two clients running in parallel across awaits could
3398
- * clobber each other — not a pattern any current consumer uses.
3399
- */
3400
- /**
3401
- * Build a typed Zitadel client pre-bound to a base URL and (optionally)
3402
- * a bearer token. Every method on the returned object mirrors a
3403
- * generated orval function:
3404
- *
3405
- * const client = createZitadelClient({ baseUrl, token });
3406
- * await client.createProject({ origins: [] });
3407
- * await client.createSchema(body, { project_id });
3408
- */
3409
- function createZitadelClient(opts) {
3410
- let baseUrl = opts.baseUrl;
3411
- while (baseUrl.endsWith("/")) baseUrl = baseUrl.slice(0, -1);
3412
- return new Proxy(zitadelNextGen_exports, { get(target, prop, receiver) {
3413
- const value = Reflect.get(target, prop, receiver);
3414
- if (typeof value !== "function") return value;
3415
- return (...args) => {
3416
- setProxyPath(baseUrl);
3417
- setApiAuthToken(opts.token);
3418
- setRequestPolicy({
3419
- signal: opts.signal,
3420
- timeoutMs: opts.timeoutMs
3421
- });
3422
- return value(...args);
3423
- };
3424
- } });
3425
- }
3426
- //#endregion
3427
- //#region ../config/dist/defaults-Cuaveyma.mjs
3428
- var default_human_user_default = {
3429
- title: "DefaultHumanUserSchema",
3430
- $schema: "https://json-schema.org/draft/2020-12/schema",
3431
- metaSchema: "${SERVER_URL}/user-schema.json",
3432
- $id: "${USER_SCHEMA_URL}",
3433
- objectType: "human-user",
3434
- kind: "user-schema",
3435
- type: "object",
3436
- "x-identifier": "email",
3437
- description: "The default editable schema for human users.",
3438
- "x-auth-methods": {
3439
- "password": { "enabled": true },
3440
- "passkey": { "enabled": true }
3441
- },
3442
- required: ["email"],
3443
- properties: { "email": {
3444
- "type": "string",
3445
- "format": "email",
3446
- "x-unique": "project",
3447
- "description": "The user's email address."
3448
- } }
3449
- };
3450
- var default_login_default = {
3451
- $schema: "../meta/flow-definition.json",
3452
- name: "default-login",
3453
- status: "active",
3454
- user_schema: "human-user",
3455
- purposes: {
3456
- "login": "identifier",
3457
- "register": "register"
3458
- },
3459
- steps: [
3460
- {
3461
- "name": "identifier",
3462
- "fields": ["email"],
3463
- "actions": [{
3464
- "name": "submit",
3465
- "kind": "submit",
3466
- "primary": true,
3467
- "text_key": "identifier.action.continue"
3468
- }, {
3469
- "name": "register",
3470
- "kind": "navigate",
3471
- "primary": false,
3472
- "text_key": "identifier.action.register.link"
3473
- }],
3474
- "transitions": {
3475
- "submit": { "target": "password" },
3476
- "user_not_found": { "target": "register" },
3477
- "register": {
3478
- "target": "register",
3479
- "purpose": "register"
3480
- }
3481
- }
3482
- },
3483
- {
3484
- "name": "password",
3485
- "fields": ["x-auth-methods#password"],
3486
- "actions": [{
3487
- "name": "submit",
3488
- "kind": "submit",
3489
- "primary": true,
3490
- "text_key": "password.action.signin"
3491
- }],
3492
- "transitions": { "submit": { "target": "done" } }
3493
- },
3494
- {
3495
- "name": "register",
3496
- "fields": ["email"],
3497
- "actions": [{
3498
- "name": "submit",
3499
- "kind": "submit",
3500
- "primary": true,
3501
- "text_key": "register.action.password"
3502
- }, {
3503
- "name": "sign_in",
3504
- "kind": "navigate",
3505
- "primary": false,
3506
- "text_key": "register.action.sign_in.link"
3507
- }],
3508
- "transitions": {
3509
- "submit": { "target": "register-password" },
3510
- "user_already_exists": { "target": "password" },
3511
- "sign_in": {
3512
- "target": "identifier",
3513
- "purpose": "login"
3514
- }
3515
- }
3516
- },
3517
- {
3518
- "name": "register-password",
3519
- "fields": ["x-auth-methods#password"],
3520
- "actions": [{
3521
- "name": "submit",
3522
- "kind": "submit",
3523
- "primary": true,
3524
- "text_key": "register-password.action.submit"
3525
- }],
3526
- "on_success": "create_user",
3527
- "transitions": {
3528
- "submit": { "target": "done" },
3529
- "user_already_exists": { "target": "password" }
3530
- }
3531
- },
3532
- {
3533
- "name": "done",
3534
- "complete": "show"
3535
- }
3536
- ]
3537
- };
3538
- var human_user_default = {
3539
- title: "DefaultHumanUserSchema",
3540
- $schema: "https://json-schema.org/draft/2020-12/schema",
3541
- metaSchema: "${SERVER_URL}/user-schema.json",
3542
- $id: "${USER_SCHEMA_URL}",
3543
- objectType: "human-user",
3544
- kind: "user-schema",
3545
- type: "object",
3546
- "x-identifier": "email",
3547
- description: "The default editable schema for human users (passkey-first sign-in).",
3548
- "x-auth-methods": {
3549
- "passkey": { "enabled": true },
3550
- "password": { "enabled": true }
3551
- },
3552
- required: ["email"],
3553
- properties: { "email": {
3554
- "type": "string",
3555
- "format": "email",
3556
- "x-unique": "project",
3557
- "description": "The user's email address."
3558
- } }
3559
- };
3560
- var login_default = {
3561
- $schema: "../meta/flow-definition.json",
3562
- name: "default-login",
3563
- status: "active",
3564
- user_schema: "human-user",
3565
- purposes: {
3566
- "login": "passkey-first",
3567
- "register": "register"
3568
- },
3569
- steps: [
3570
- {
3571
- "name": "passkey-first",
3572
- "fields": [],
3573
- "actions": [
3574
- {
3575
- "name": "passkey",
3576
- "kind": "passkey",
3577
- "primary": true,
3578
- "text_key": "passkey-first.action.passkey"
3579
- },
3580
- {
3581
- "name": "email_fallback",
3582
- "kind": "navigate",
3583
- "primary": false,
3584
- "text_key": "passkey-first.action.email_fallback"
3585
- },
3586
- {
3587
- "name": "register",
3588
- "kind": "navigate",
3589
- "primary": false,
3590
- "text_key": "identifier.action.register.link"
3591
- }
3592
- ],
3593
- "transitions": {
3594
- "passkey": { "target": "done" },
3595
- "email_fallback": { "target": "identifier" },
3596
- "user_not_found": { "target": "register" },
3597
- "register": {
3598
- "target": "register",
3599
- "purpose": "register"
3600
- }
3601
- }
3602
- },
3603
- {
3604
- "name": "identifier",
3605
- "fields": ["email"],
3606
- "actions": [
3607
- {
3608
- "name": "submit",
3609
- "kind": "submit",
3610
- "primary": true,
3611
- "text_key": "identifier.action.continue"
3612
- },
3613
- {
3614
- "name": "passkey",
3615
- "kind": "passkey",
3616
- "primary": false,
3617
- "text_key": "identifier.action.passkey"
3618
- },
3619
- {
3620
- "name": "register",
3621
- "kind": "navigate",
3622
- "primary": false,
3623
- "text_key": "identifier.action.register.link"
3624
- }
3625
- ],
3626
- "transitions": {
3627
- "submit": { "target": "password" },
3628
- "passkey": { "target": "done" },
3629
- "user_not_found": { "target": "register" },
3630
- "register": {
3631
- "target": "register",
3632
- "purpose": "register"
3633
- }
3634
- }
3635
- },
3636
- {
3637
- "name": "password",
3638
- "fields": ["x-auth-methods#password"],
3639
- "actions": [{
3640
- "name": "submit",
3641
- "kind": "submit",
3642
- "primary": true,
3643
- "text_key": "password.action.signin"
3644
- }, {
3645
- "name": "passkey",
3646
- "kind": "passkey",
3647
- "primary": false,
3648
- "text_key": "password.action.passkey"
3649
- }],
3650
- "transitions": {
3651
- "submit": { "target": "done" },
3652
- "passkey": { "target": "done" }
3653
- }
3654
- },
3655
- {
3656
- "name": "register",
3657
- "fields": ["email"],
3658
- "actions": [
3659
- {
3660
- "name": "passkey_register",
3661
- "kind": "passkey_register",
3662
- "primary": true,
3663
- "text_key": "register.action.passkey"
3664
- },
3665
- {
3666
- "name": "submit",
3667
- "kind": "submit",
3668
- "primary": false,
3669
- "text_key": "register.action.password"
3670
- },
3671
- {
3672
- "name": "sign_in",
3673
- "kind": "navigate",
3674
- "primary": false,
3675
- "text_key": "register.action.sign_in.link"
3676
- }
3677
- ],
3678
- "transitions": {
3679
- "passkey_register": { "target": "done" },
3680
- "submit": { "target": "register-password" },
3681
- "user_already_exists": { "target": "password" },
3682
- "sign_in": {
3683
- "target": "passkey-first",
3684
- "purpose": "login"
3685
- }
3686
- }
3687
- },
3688
- {
3689
- "name": "register-password",
3690
- "fields": ["x-auth-methods#password"],
3691
- "actions": [{
3692
- "name": "submit",
3693
- "kind": "submit",
3694
- "primary": true,
3695
- "text_key": "register-password.action.submit"
3696
- }],
3697
- "on_success": "create_user",
3698
- "transitions": {
3699
- "submit": { "target": "done" },
3700
- "user_already_exists": { "target": "password" }
3701
- }
3702
- },
3703
- {
3704
- "name": "done",
3705
- "complete": "show"
3706
- }
3707
- ]
3708
- };
3709
- const DEFAULT_BUILTIN_SCHEMA_BASE = "https://zitadel.com/schemas/v1";
3710
- const DEFAULT_FLOW_SCHEMA_URI = `${DEFAULT_BUILTIN_SCHEMA_BASE}/flow-definition.json`;
3711
- /**
3712
- * Named schema+flow bundles `zitadel setup` can scaffold (#448: the prompt
3713
- * fires before any `.zitadel/` file is written; each preset maps to a
3714
- * pre-defined bundle the CLI copies on first setup). `password-first` is
3715
- * today's default; `passkey-first` puts a passkey ceremony on the login
3716
- * entry step with an email→password fallback path.
3717
- */
3718
- const SETUP_PRESETS = ["password-first", "passkey-first"];
3719
- const PRESET_TEMPLATES = {
3720
- "password-first": {
3721
- schema: default_human_user_default,
3722
- flow: default_login_default
3723
- },
3724
- "passkey-first": {
3725
- schema: human_user_default,
3726
- flow: login_default
3727
- }
3728
- };
3729
- function presetTemplates(preset) {
3730
- if (!Object.hasOwn(PRESET_TEMPLATES, preset)) throw new Error(`unknown setup preset ${JSON.stringify(preset)} (known presets: ${SETUP_PRESETS.join(", ")})`);
3731
- return PRESET_TEMPLATES[preset];
3732
- }
3733
- /**
3734
- * The second setup axis (#448): *who* signs in, orthogonal to the sign-in
3735
- * preset (*how* they sign in). The sign-in preset owns the flow shape and
3736
- * auth methods; the use case owns which profile fields the schema collects.
3737
- * Composing the two keeps us at one field catalog + one flow-per-preset
3738
- * instead of a bundle per (use case × preset) pair. `minimal` is the
3739
- * default and never blocks non-interactive runs.
3740
- */
3741
- const SETUP_USE_CASES = [
3742
- "minimal",
3743
- "consumer",
3744
- "business"
3745
- ];
3746
- /**
3747
- * Fields each use case collects, in register/display order. `email` is
3748
- * always first and stays the only required property; the rest are optional
3749
- * profile attributes gathered on the flow's register step. `givenName`/
3750
- * `familyName` are the attributes the backend reads for a user's identity
3751
- * (`internal/domain/user.go`); `companyName` is stored as a plain user
3752
- * attribute today — there is no org/team model behind it yet.
3753
- */
3754
- const USE_CASE_FIELDS = {
3755
- minimal: ["email"],
3756
- consumer: [
3757
- "email",
3758
- "givenName",
3759
- "familyName"
3760
- ],
3761
- business: [
3762
- "email",
3763
- "givenName",
3764
- "familyName",
3765
- "companyName"
3766
- ]
3767
- };
3768
- /**
3769
- * JSON-Schema bodies for the optional profile fields the CLI composes in per
3770
- * use case. The shipped templates are an email-only baseline (shared verbatim
3771
- * with the Go server fallback), so this catalog owns every field beyond
3772
- * `email`. Authored in the templates' style — no `x-claim`, since the backend
3773
- * maps identity by attribute name and the user-property meta-schema defines no
3774
- * claim keyword. `givenName`/`familyName` are the attributes the backend reads
3775
- * for a user's identity (`internal/domain/user.go`).
3776
- */
3777
- const EXTRA_FIELD_BODIES = {
3778
- givenName: {
3779
- type: "string",
3780
- maxLength: 50,
3781
- description: "The user's given (first) name."
3782
- },
3783
- familyName: {
3784
- type: "string",
3785
- maxLength: 50,
3786
- description: "The user's family (last) name."
3787
- },
3788
- companyName: {
3789
- type: "string",
3790
- maxLength: 200,
3791
- description: "The user's company name."
3792
- }
3793
- };
3794
- function useCaseFields(useCase) {
3795
- if (!Object.hasOwn(USE_CASE_FIELDS, useCase)) throw new Error(`unknown setup use case ${JSON.stringify(useCase)} (known use cases: ${SETUP_USE_CASES.join(", ")})`);
3796
- return USE_CASE_FIELDS[useCase];
3797
- }
3798
- /**
3799
- * The body for one use-case field: reuse the template's authored body when it
3800
- * has one (so composed schemas match the shipped defaults for shared fields),
3801
- * else the extra catalog, else a generic editable string so composition stays
3802
- * total for any field a future use case introduces.
3803
- */
3804
- function fieldBody(field, templateProps) {
3805
- if (Object.hasOwn(templateProps, field)) return { ...templateProps[field] };
3806
- if (Object.hasOwn(EXTRA_FIELD_BODIES, field)) return { ...EXTRA_FIELD_BODIES[field] };
3807
- return {
3808
- type: "string",
3809
- description: `The user's ${field}.`
3810
- };
3811
- }
3812
- /**
3813
- * The fields a user's display name is made of, in order. A schema designates
3814
- * those its use case collects as `x-display`, so a session names the user
3815
- * ("Ada Lovelace") rather than leaving the app only their email.
3816
- */
3817
- const DISPLAY_FIELDS = ["givenName", "familyName"];
3818
- /**
3819
- * Narrow a rendered schema to the chosen use case: keep the preset-owned
3820
- * header and `x-auth-methods`, but replace `properties`/`required` with the
3821
- * use case's field set, and designate its name fields as `x-display`. `email`
3822
- * is the sole required property.
3823
- */
3824
- function applyUseCaseToSchema(schema, useCase) {
3825
- const templateProps = schema.properties ?? {};
3826
- const fields = useCaseFields(useCase);
3827
- const properties = {};
3828
- for (const field of fields) properties[field] = fieldBody(field, templateProps);
3829
- const display = DISPLAY_FIELDS.filter((field) => fields.includes(field));
3830
- return {
3831
- ...schema,
3832
- required: ["email"],
3833
- properties,
3834
- ...display.length > 0 ? { "x-display": display } : {}
3835
- };
3836
- }
3837
- /**
3838
- * Derive the flow's register-step fields from the use case rather than
3839
- * copying a hard-coded list into every bundle (#448): the register step
3840
- * collects exactly what the schema defines. Other steps are untouched.
3841
- */
3842
- function applyUseCaseToFlow(flow, useCase) {
3843
- const fields = [...useCaseFields(useCase)];
3844
- const steps = flow.steps.map((step) => step.name === "register" ? {
3845
- ...step,
3846
- fields
3847
- } : step);
3848
- return {
3849
- ...flow,
3850
- steps
3851
- };
3852
- }
3853
- function defaultHumanUserSchemaUrl(builtinSchemaBase = DEFAULT_BUILTIN_SCHEMA_BASE) {
3854
- return `${trimTrailingSlash(builtinSchemaBase)}/default-human-user.json`;
3855
- }
3856
- function getDefaultHumanUserSchema(options = {}) {
3857
- const builtinSchemaBase = trimTrailingSlash(options.builtinSchemaBase ?? "https://zitadel.com/schemas/v1");
3858
- return applyUseCaseToSchema(renderTemplate(presetTemplates(options.preset ?? "password-first").schema, {
3859
- SERVER_URL: builtinSchemaBase,
3860
- USER_SCHEMA_URL: options.userSchemaUrl ?? defaultHumanUserSchemaUrl(builtinSchemaBase)
3861
- }), options.useCase ?? "minimal");
3862
- }
3863
- function getDefaultLoginFlow(options = {}) {
3864
- const builtinSchemaBase = trimTrailingSlash(options.builtinSchemaBase ?? "https://zitadel.com/schemas/v1");
3865
- return applyUseCaseToFlow(renderTemplate(presetTemplates(options.preset ?? "password-first").flow, { SERVER_URL: builtinSchemaBase }), options.useCase ?? "minimal");
3866
- }
3867
- function renderTemplate(value, replacements) {
3868
- if (Array.isArray(value)) return value.map((item) => renderTemplate(item, replacements));
3869
- if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, renderTemplate(item, replacements)]));
3870
- if (typeof value === "string") return value.replaceAll(/\$\{([A-Z_]+)\}/g, (match, name) => {
3871
- return replacements[name] ?? match;
3872
- });
3873
- return value;
3874
- }
3875
- function trimTrailingSlash(value) {
3876
- let trimmed = value;
3877
- while (trimmed.endsWith("/")) trimmed = trimmed.slice(0, -1);
3878
- return trimmed;
3879
- }
3880
- //#endregion
3881
- //#region src/bootstrap.ts
3882
- const DEFAULT_PROJECT_NAME = "zitadel-testing";
3883
- /**
3884
- * Server-side half of `zitadel setup`, without any file scaffolding:
3885
- * `POST /projects` is unauthenticated and mints the projectSecret used as the
3886
- * bearer for everything else; the schema is uploaded without `$id` so the
3887
- * server assigns an opaque id, which the flow must then reference.
3888
- */
3889
- async function bootstrapProject(options) {
3890
- const { baseUrl } = options;
3891
- const project = await createZitadelClient({ baseUrl }).createProject({
3892
- name: options.projectName ?? DEFAULT_PROJECT_NAME,
3893
- origins: (options.appOrigins ?? []).map((pattern) => ({
3894
- pattern,
3895
- kind: "preview"
3896
- })),
3897
- seed_defaults: false
3898
- });
3899
- const projectId = requireString(project.id, "project id");
3900
- const projectSecret = requireString(project.project_secret, "project secret");
3901
- const previewSecret = typeof project.preview_secret === "string" ? project.preview_secret : void 0;
3902
- const client = createZitadelClient({
3903
- baseUrl,
3904
- token: projectSecret
3905
- });
3906
- const { $id: _templateId, ...schemaBody } = getDefaultHumanUserSchema({
3907
- preset: options.preset,
3908
- useCase: options.useCase
3909
- });
3910
- const schemaId = requireString((await client.createSchema(schemaBody, { project_id: projectId })).id, "schema id");
3911
- const flowBody = getDefaultLoginFlow({
3912
- preset: options.preset,
3913
- useCase: options.useCase
3914
- });
3915
- return {
3916
- projectId,
3917
- projectSecret,
3918
- previewSecret,
3919
- schemaId,
3920
- flowId: requireString((await client.createFlowDefinition({
3921
- project_id: projectId,
3922
- schema_uri: DEFAULT_FLOW_SCHEMA_URI,
3923
- flow_definition: flowBody
3924
- })).id, "flow definition id")
3925
- };
3926
- }
3927
- function requireString(value, label) {
3928
- if (typeof value === "string" && value.length > 0) return value;
3929
- throw new Error(`Missing ${label} in server response.`);
3930
- }
3931
- //#endregion
3932
- //#region src/cli.ts
3933
- const DEFAULT_TIMEOUT_MS = 12e4;
3934
- function resolveCliBin() {
3935
- const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
3936
- const pkgPath = require$1.resolve("@zitadel/cli/package.json");
3937
- const rel = require$1(pkgPath).bin?.zitadel;
3938
- if (!rel) throw new Error("@zitadel/cli does not declare a `zitadel` bin entry");
3939
- return (0, node_path.join)((0, node_path.dirname)(pkgPath), rel);
3940
- }
3941
- function runCli(options) {
3942
- const bin = options.bin ?? resolveCliBin();
3943
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
3944
- return new Promise((resolve, reject) => {
3945
- const child = (0, node_child_process.spawn)(process.execPath, [bin, ...options.args], {
3946
- env: {
3947
- ...process.env,
3948
- ...options.env
3949
- },
3950
- stdio: [
3951
- "ignore",
3952
- "pipe",
3953
- "pipe"
3954
- ]
3955
- });
3956
- let stdout = "";
3957
- let stderr = "";
3958
- child.stdout.setEncoding("utf8");
3959
- child.stdout.on("data", (chunk) => {
3960
- stdout += chunk;
3961
- });
3962
- child.stderr.setEncoding("utf8");
3963
- child.stderr.on("data", (chunk) => {
3964
- stderr += chunk;
3965
- });
3966
- const timer = setTimeout(() => {
3967
- child.kill("SIGKILL");
3968
- reject(/* @__PURE__ */ new Error(`zitadel ${options.args[0] ?? ""} timed out after ${timeoutMs}ms\n${tail(stderr)}`));
3969
- }, timeoutMs);
3970
- timer.unref();
3971
- child.on("error", (error) => {
3972
- clearTimeout(timer);
3973
- reject(error);
3974
- });
3975
- child.on("close", (code) => {
3976
- clearTimeout(timer);
3977
- resolve({
3978
- exitCode: code ?? -1,
3979
- stdout,
3980
- stderr
3981
- });
3982
- });
3983
- });
3984
- }
3985
- function tail(text, lines = 20) {
3986
- return text.split("\n").slice(-lines).join("\n").trim();
3987
- }
3988
- //#endregion
3989
- //#region src/envelope.ts
3990
- /**
3991
- * Render an error envelope's remediation fields for humans — the CLI's
3992
- * `hint`/`next_commands` are the actionable part of a failure (e.g. "Reinstall
3993
- * @zitadel/cli so npm can install @zitadel/server"), so surface them instead
3994
- * of a raw stdout dump. Returns undefined when the envelope has no message.
3995
- */
3996
- function describeEnvelopeError(envelope) {
3997
- if (typeof envelope.message !== "string" || envelope.message.length === 0) return;
3998
- const lines = [envelope.code ? `${envelope.code}: ${envelope.message}` : envelope.message];
3999
- if (envelope.hint) lines.push(`hint: ${envelope.hint}`);
4000
- if (envelope.next_commands && envelope.next_commands.length > 0) lines.push(`next: ${envelope.next_commands.join(" | ")}`);
4001
- return lines.join("\n");
4002
- }
4003
- function parseCliEnvelope(stdout, context) {
4004
- const start = stdout.indexOf("{");
4005
- const end = stdout.lastIndexOf("}");
4006
- if (start === -1 || end <= start) throw new Error(`${context}: expected a JSON envelope on stdout, got:\n${stdout.trim() || "(empty)"}`);
4007
- let parsed;
4008
- try {
4009
- parsed = JSON.parse(stdout.slice(start, end + 1));
4010
- } catch (error) {
4011
- throw new Error(`${context}: failed to parse JSON envelope: ${error.message}\n${stdout.trim()}`, { cause: error });
4012
- }
4013
- if (typeof parsed !== "object" || parsed === null || typeof parsed.status !== "string") throw new Error(`${context}: stdout JSON is not a CLI envelope:\n${stdout.trim()}`);
4014
- return parsed;
4015
- }
4016
- //#endregion
4017
- //#region src/ports.ts
4018
- /**
4019
- * Ask the OS for a free TCP port. The port is released before returning, so a
4020
- * racing process could grab it; the CLI's own preflight surfaces that as
4021
- * E_PORT_IN_USE, which is loud rather than corrupting.
4022
- */
4023
- function getFreePort() {
4024
- return new Promise((resolve, reject) => {
4025
- const server = (0, node_net.createServer)();
4026
- server.unref();
4027
- server.on("error", reject);
4028
- server.listen(0, "127.0.0.1", () => {
4029
- const address = server.address();
4030
- if (address === null || typeof address === "string") {
4031
- server.close();
4032
- reject(/* @__PURE__ */ new Error("could not determine a free port"));
4033
- return;
4034
- }
4035
- const { port } = address;
4036
- server.close((err) => {
4037
- if (err) {
4038
- reject(err);
4039
- return;
4040
- }
4041
- resolve(port);
4042
- });
4043
- });
4044
- });
4045
- }
4046
- //#endregion
4047
- //#region src/lifecycle.ts
4048
- /**
4049
- * Boot an ephemeral local server by shelling out to `zitadel start` and parse
4050
- * its JSON envelope. The CLI owns the subtle parts (port preflight, health
4051
- * wait, process-group stop), so this module stays a thin adapter; swapping it
4052
- * for direct library calls later must not change the shape returned here.
4053
- */
4054
- async function bootLocalServer(options = {}) {
4055
- const ownsDir = options.dir === void 0;
4056
- const dir = options.dir ?? await (0, node_fs_promises.mkdtemp)((0, node_path.join)((0, node_os.tmpdir)(), "zitadel-testing-"));
4057
- const port = options.port ?? await getFreePort();
4058
- const env = {};
4059
- if (options.serverBinary) env.ZITADEL_SERVER_BINARY = options.serverBinary;
4060
- const result = await runCli({
4061
- args: [
4062
- "start",
4063
- "--port",
4064
- String(port),
4065
- "--non-interactive",
4066
- "--json",
4067
- "-c",
4068
- dir
4069
- ],
4070
- bin: options.cliBin,
4071
- env,
4072
- timeoutMs: options.timeoutMs
4073
- });
4074
- if (result.exitCode !== 0) throw new Error(`zitadel start exited with code ${result.exitCode}.\n${failureDetail(result)}\nstate dir kept for inspection: ${dir}`);
4075
- const stopViaCli = async () => {
4076
- const stopResult = await runCli({
4077
- args: [
4078
- "stop",
4079
- "--non-interactive",
4080
- "--json",
4081
- "-c",
4082
- dir
4083
- ],
4084
- bin: options.cliBin,
4085
- env,
4086
- timeoutMs: options.timeoutMs
4087
- });
4088
- if (stopResult.exitCode !== 0) throw new Error(`zitadel stop exited with code ${stopResult.exitCode}.\n${failureDetail(stopResult)}\nstate dir kept for inspection: ${dir}`);
4089
- };
4090
- let envelope;
4091
- try {
4092
- envelope = parseCliEnvelope(result.stdout, "zitadel start");
4093
- if (envelope.status !== "ok") throw new Error(`zitadel start reported status "${envelope.status}":\n${describeEnvelopeError(envelope) ?? tail(result.stdout)}`);
4094
- } catch (error) {
4095
- const startError = new Error(`zitadel start produced unusable output.\nreason: ${error instanceof Error ? error.message : String(error)}\nstdout: ${tail(result.stdout) || "(empty)"}\nstderr: ${tail(result.stderr) || "(empty)"}\nstate dir kept for inspection: ${dir}`, { cause: error });
4096
- try {
4097
- await stopViaCli();
4098
- } catch (stopError) {
4099
- throw new AggregateError([startError, stopError], `${startError.message}\nStopping the possibly-running instance also failed: ${stopError instanceof Error ? stopError.message : String(stopError)}`);
4100
- }
4101
- throw startError;
4102
- }
4103
- const { runtime, urls } = envelope.data;
4104
- const runStop = async () => {
4105
- await stopViaCli();
4106
- if (ownsDir && !options.keep) await (0, node_fs_promises.rm)(dir, {
4107
- recursive: true,
4108
- force: true
4109
- });
4110
- };
4111
- let stopPromise;
4112
- const stop = () => {
4113
- stopPromise ??= runStop().catch((error) => {
4114
- stopPromise = void 0;
4115
- throw error;
4116
- });
4117
- return stopPromise;
4118
- };
4119
- return {
4120
- baseUrl: urls.api,
4121
- runtime: {
4122
- port: runtime.port,
4123
- pid: runtime.pid,
4124
- dir,
4125
- logPath: runtime.log_path
4126
- },
4127
- stop
4128
- };
4129
- }
4130
- /**
4131
- * A failed CLI run usually still prints an error envelope; its
4132
- * message/hint/next_commands beat raw output tails (e.g. a fresh install
4133
- * missing @zitadel/server gets "Reinstall @zitadel/cli" instead of a stack).
4134
- */
4135
- function failureDetail(result) {
4136
- try {
4137
- const described = describeEnvelopeError(parseCliEnvelope(result.stdout, "zitadel"));
4138
- if (described) return described;
4139
- } catch {}
4140
- return `stdout: ${tail(result.stdout) || "(empty)"}\nstderr: ${tail(result.stderr) || "(empty)"}`;
4141
- }
4142
- //#endregion
4143
- //#region src/seed.ts
4144
- /**
4145
- * A unique unused email + password. Nothing is created on the instance —
4146
- * this is the input for registration-flow specs, which must prove the flow
4147
- * creates the user. It needs no instance either, so both entry points export
4148
- * it for specs that run without `withZitadel()`; `seed.identity()` and
4149
- * `zitadel.identity()` call this function.
4150
- */
4151
- function identity() {
4152
- return {
4153
- email: `e2e-${(0, node_crypto.randomUUID)().slice(0, 8)}@example.com`,
4154
- password: `Pw!${(0, node_crypto.randomUUID)()}`
4155
- };
4156
- }
4157
- /**
4158
- * Create a user that can immediately complete the password login flow:
4159
- * `POST /users` (the body carries `schema: <schema id>` and the schema-defined
4160
- * content under `attributes`) followed by `PUT /users/{id}/password`.
4161
- *
4162
- * Defaults mint a unique email per call (email is x-unique per project), which
4163
- * is what makes per-test seeding parallel-safe on a shared instance.
4164
- */
4165
- async function seedUser(client, context, input = {}) {
4166
- const fresh = identity();
4167
- const email = input.email ?? fresh.email;
4168
- const password = input.password ?? fresh.password;
4169
- const id = requireString((await client.createUser({
4170
- schema: context.schemaId,
4171
- attributes: {
4172
- ...input.attributes,
4173
- email
4174
- }
4175
- }, { project_id: context.projectId })).id, "user id");
4176
- await client.setUserPassword(id, { password });
4177
- return {
4178
- id,
4179
- email,
4180
- password
4181
- };
4182
- }
4183
- /**
4184
- * Seed `count` users sequentially. The template makes fixture data
4185
- * deterministic per index (stable emails/names keep screenshot diffs about
4186
- * code, not reshuffled data — the `console:dev-real` pattern); untemplated
4187
- * fields fall back to the unique defaults. Name-like attributes need a
4188
- * schema that declares them (`useCase: "consumer"` or wider).
4189
- */
4190
- async function seedUsers(client, context, count, template = {}) {
4191
- const users = [];
4192
- for (let index = 0; index < count; index += 1) users.push(await seedUser(client, context, {
4193
- email: template.email?.(index),
4194
- password: template.password?.(index),
4195
- attributes: template.attributes?.(index)
4196
- }));
4197
- return users;
4198
- }
4199
- //#endregion
4200
- //#region src/session.ts
4201
- /**
4202
- * Mirrors the server's session cookie (internal/api/session.go): the name a
4203
- * direct call to the server sends, and the one an app keeps behind a proxy that
4204
- * passes the server's cookie through, such as an SPA's in production.
4205
- */
4206
- const SESSION_COOKIE_NAME = "__nextgen_session";
4207
- /**
4208
- * The cookie an app keeps its session in on its own origin behind a server SDK
4209
- * (Next.js, Nuxt, SvelteKit, SolidStart, TanStack Start, Qwik Router) or the dev
4210
- * proxy `zitadel setup` writes for an SPA: `__nextgen_session_<projectId>`. The
4211
- * proxy renames the server's cookie, so the apps and the Console on one host
4212
- * keep a session each (ADR 073).
4213
- *
4214
- * Mirrors `sessionCookieName` in `@zitadel/sdk-core`, including the
4215
- * percent-encoding of every byte outside `[A-Za-z0-9_-]`.
4216
- */
4217
- function sessionCookieName(projectId) {
4218
- let name = `${SESSION_COOKIE_NAME}_`;
4219
- for (const byte of new TextEncoder().encode(projectId)) {
4220
- const char = String.fromCharCode(byte);
4221
- name += /[A-Za-z0-9_-]/.test(char) ? char : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
4222
- }
4223
- return name;
4224
- }
4225
- const MAX_FLOW_STEPS = 6;
4226
- /**
4227
- * Drive the real login flow headlessly for a seeded password user and
4228
- * exchange the terminal handoff for a session: exactly what `<zitadel-login>`
4229
- * does, minus the rendering. Supports flows whose steps only ask for the
4230
- * user's email and password (the shipped `password-first` presets); any step
4231
- * demanding more — a challenge, an unknown field — fails loudly by design.
4232
- *
4233
- * Flow calls use raw fetch instead of the typed client because the flow is
4234
- * stateless through the sealed `_zflow` cookie (internal/api/flow.go): every
4235
- * response re-seals the flow state into Set-Cookie, and submits are rejected
4236
- * without it. Browsers round-trip it implicitly; here a one-cookie jar does.
4237
- */
4238
- async function mintSession(client, handle, context, user, options = {}) {
4239
- const values = {
4240
- email: user.email,
4241
- password: user.password
4242
- };
4243
- const jar = new FlowCookieJar();
4244
- const origin = options.origin;
4245
- let response = await flowFetch(handle, jar, origin, "/flow", {
4246
- project_id: context.projectId,
4247
- purpose: "login",
4248
- ...options.flowDefinitionName ? { flow_definition_name: options.flowDefinitionName } : {}
4249
- });
4250
- for (let hop = 0; hop < MAX_FLOW_STEPS; hop += 1) {
4251
- if (response.handoff_token) {
4252
- const exchanged = await client.exchangeHandoff({ handoff_token: response.handoff_token }, { project_id: context.projectId });
4253
- return {
4254
- user,
4255
- sessionToken: exchanged.session_token,
4256
- expiresAt: exchanged.session.expires_at,
4257
- cookie: {
4258
- name: SESSION_COOKIE_NAME,
4259
- value: exchanged.session_token,
4260
- httpOnly: true,
4261
- secure: true,
4262
- sameSite: "Lax",
4263
- path: "/"
4264
- }
4265
- };
4266
- }
4267
- response = await flowFetch(handle, jar, origin, `/flow/${encodeURIComponent(response.id)}/submit`, {
4268
- session_token: response.session_token,
4269
- action: "submit",
4270
- fields: collectFields(response, values)
4271
- });
4272
- }
4273
- throw new Error(`seed.session: flow did not complete within ${MAX_FLOW_STEPS} steps (last step: ${describeStep(response)}).`);
4274
- }
4275
- /** One-cookie jar for the sealed `_zflow` flow-state cookie. */
4276
- var FlowCookieJar = class {
4277
- cookie;
4278
- absorb(response) {
4279
- for (const raw of response.headers.getSetCookie()) {
4280
- const [pair] = raw.split(";", 1);
4281
- if (pair?.startsWith("_zflow=")) this.cookie = pair;
4282
- }
4283
- }
4284
- header() {
4285
- return this.cookie ? { cookie: this.cookie } : {};
4286
- }
4287
- };
4288
- async function flowFetch(handle, jar, origin, path, body) {
4289
- const response = await fetch(`${handle.baseUrl}${path}`, {
4290
- method: "POST",
4291
- headers: {
4292
- "content-type": "application/json",
4293
- authorization: `Bearer ${handle.projectSecret}`,
4294
- ...origin ? { origin } : {},
4295
- ...jar.header()
4296
- },
4297
- body: JSON.stringify(body)
4298
- });
4299
- jar.absorb(response);
4300
- const parsed = await response.json().catch(() => void 0);
4301
- if (!response.ok || !parsed) {
4302
- const detail = parsed && typeof parsed === "object" ? ` — ${JSON.stringify(parsed)}` : "";
4303
- const hint = !origin && /origin/i.test(detail) ? "\nNo Origin header was sent: pass `origin` to seedSession() (the Playwright fixtures pass the suite's baseURL) or `appOrigins` to startLocalZitadel()." : "";
4304
- throw new Error(`seed.session: POST ${path} returned ${response.status}${detail}${hint}`);
4305
- }
4306
- return parsed;
4307
- }
4308
- /**
4309
- * Fill exactly the fields the current step declares — the orchestrator's
4310
- * convention — from the known email/password values. An unknown required
4311
- * field means this flow needs more than a password login can provide.
4312
- */
4313
- function collectFields(response, values) {
4314
- const fields = {};
4315
- for (const field of response.step.fields ?? []) {
4316
- const value = values[fieldKey(field)];
4317
- if (value === void 0) throw new Error(`seed.session supports password flows only; step ${describeStep(response)} declares field "${field.name}", which the kit cannot fill. Log in through the UI for flows with additional factors.`);
4318
- fields[field.name] = value;
4319
- }
4320
- return fields;
4321
- }
4322
- /**
4323
- * Steps name credential fields with schema pointers (e.g.
4324
- * `x-auth-methods#password`); match on the trailing segment so the value map
4325
- * stays the plain `{ email, password }` a caller thinks in.
4326
- */
4327
- function fieldKey(field) {
4328
- const name = field.name;
4329
- return (name.split(/[#/.]/).at(-1) ?? name).toLowerCase();
4330
- }
4331
- function describeStep(response) {
4332
- const name = response.step.name ?? "(unnamed)";
4333
- const declared = (response.step.fields ?? []).map((field) => field.name).join(", ");
4334
- return `"${name}"${declared ? ` [fields: ${declared}]` : ""}`;
4335
- }
4336
- //#endregion
4337
- //#region src/index.ts
4338
- /**
4339
- * Attach to an already-bootstrapped instance/project. Lifecycle-free on
4340
- * purpose: this is the entry point for Playwright workers (via the handshake
4341
- * file) and, later, for seeding remote instances.
4342
- */
4343
- function connectZitadel(handle) {
4344
- const api = createZitadelClient({
4345
- baseUrl: handle.baseUrl,
4346
- token: handle.projectSecret
4347
- });
4348
- const context = {
4349
- projectId: handle.projectId,
4350
- schemaId: handle.schemaId
4351
- };
4352
- return {
4353
- handle,
4354
- api,
4355
- appEnv: require_handshake.applyAppEnvTemplate(require_handshake.nextAppEnv, handle),
4356
- seedUser: (input) => seedUser(api, context, input),
4357
- seedUsers: (count, template) => seedUsers(api, context, count, template),
4358
- identity,
4359
- seedSession: async (input = {}) => {
4360
- const { user: existing, flowDefinitionName, origin, ...userInput } = input;
4361
- const user = existing ?? await seedUser(api, context, userInput);
4362
- return mintSession(api, handle, context, user, {
4363
- flowDefinitionName,
4364
- origin: origin ?? handle.appOrigin
4365
- });
4366
- }
4367
- };
4368
- }
4369
- /**
4370
- * Boot an ephemeral local instance (binary runtime + SQLite by default, no
4371
- * Docker) and bootstrap a project + default schema + login flow on it. The
4372
- * result can seed loginable password users immediately.
4373
- */
4374
- async function startLocalZitadel(options = {}) {
4375
- const server = await bootLocalServer(options);
4376
- let bootstrapped;
4377
- try {
4378
- bootstrapped = await bootstrapProject({
4379
- baseUrl: server.baseUrl,
4380
- projectName: options.projectName,
4381
- appOrigins: options.appOrigins,
4382
- preset: options.preset,
4383
- useCase: options.useCase
4384
- });
4385
- } catch (error) {
4386
- try {
4387
- await server.stop();
4388
- } catch (stopError) {
4389
- throw new AggregateError([error, stopError], "bootstrap failed, and stopping the booted instance also failed");
4390
- }
4391
- throw error;
4392
- }
4393
- return {
4394
- ...connectZitadel({
4395
- baseUrl: server.baseUrl,
4396
- projectId: bootstrapped.projectId,
4397
- projectSecret: bootstrapped.projectSecret,
4398
- schemaId: bootstrapped.schemaId,
4399
- previewSecret: bootstrapped.previewSecret,
4400
- appOrigin: options.appOrigins?.[0]
4401
- }),
4402
- runtime: server.runtime,
4403
- stop: server.stop,
4404
- [Symbol.asyncDispose]: server.stop
4405
- };
4406
- }
4407
- //#endregion
4408
- Object.defineProperty(exports, "SESSION_COOKIE_NAME", {
4409
- enumerable: true,
4410
- get: function() {
4411
- return SESSION_COOKIE_NAME;
4412
- }
4413
- });
4414
- Object.defineProperty(exports, "bootLocalServer", {
4415
- enumerable: true,
4416
- get: function() {
4417
- return bootLocalServer;
4418
- }
4419
- });
4420
- Object.defineProperty(exports, "bootstrapProject", {
4421
- enumerable: true,
4422
- get: function() {
4423
- return bootstrapProject;
4424
- }
4425
- });
4426
- Object.defineProperty(exports, "connectZitadel", {
4427
- enumerable: true,
4428
- get: function() {
4429
- return connectZitadel;
4430
- }
4431
- });
4432
- Object.defineProperty(exports, "identity", {
4433
- enumerable: true,
4434
- get: function() {
4435
- return identity;
4436
- }
4437
- });
4438
- Object.defineProperty(exports, "sessionCookieName", {
4439
- enumerable: true,
4440
- get: function() {
4441
- return sessionCookieName;
4442
- }
4443
- });
4444
- Object.defineProperty(exports, "startLocalZitadel", {
4445
- enumerable: true,
4446
- get: function() {
4447
- return startLocalZitadel;
4448
- }
4449
- });
4450
-
4451
- //# sourceMappingURL=src-BxDa7FSy.cjs.map