@clavis.nexus/setup 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,45 +1,440 @@
1
1
  import { execFile } from 'child_process';
2
2
  import { promisify } from 'util';
3
- import { readFile, mkdir, writeFile, chmod, unlink } from 'fs/promises';
4
- import path, { join, dirname } from 'path';
3
+ import { readFile, unlink, mkdir, writeFile, chmod, lstat } from 'fs/promises';
4
+ import path, { join, dirname, resolve, relative, isAbsolute } from 'path';
5
5
  import { homedir } from 'os';
6
6
  import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
7
7
  import { createInterface } from 'readline/promises';
8
8
  import { stdin, stdout } from 'process';
9
9
  import { randomBytes } from 'crypto';
10
10
 
11
- // src/browser.ts
11
+ // src/org-api.ts
12
+ var SetupApiError = class extends Error {
13
+ status;
14
+ code;
15
+ constructor(status, code, message) {
16
+ super(message);
17
+ this.name = "SetupApiError";
18
+ this.status = status;
19
+ this.code = code;
20
+ }
21
+ };
22
+ async function apiJson(apiOrigin, path2, opts) {
23
+ const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path2}`, {
24
+ method: opts.method ?? "GET",
25
+ redirect: "error",
26
+ headers: {
27
+ Accept: "application/json",
28
+ ...opts.bearer !== void 0 ? { Authorization: `Bearer ${opts.bearer}` } : {},
29
+ ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
30
+ },
31
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
32
+ });
33
+ const body = await res.json().catch(() => null);
34
+ if (!res.ok) {
35
+ const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
36
+ const message = typeof body?.message === "string" ? body.message : code;
37
+ throw new SetupApiError(res.status, code, message);
38
+ }
39
+ return body ?? {};
40
+ }
41
+ async function listOrgs(apiOrigin, bearer) {
42
+ const r = await apiJson(apiOrigin, "/orgs", { bearer });
43
+ return r.orgs ?? [];
44
+ }
45
+ async function getOrg(apiOrigin, bearer, orgId) {
46
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
47
+ }
48
+ function stringList(value) {
49
+ return Array.isArray(value) ? value.filter((code) => typeof code === "string") : [];
50
+ }
51
+ async function getOrgRegions(apiOrigin) {
52
+ const r = await apiJson(
53
+ apiOrigin,
54
+ "/orgs/regions",
55
+ {}
56
+ );
57
+ return r.payload ?? {};
58
+ }
59
+ async function getClosedIncorporations(apiOrigin) {
60
+ return stringList((await getOrgRegions(apiOrigin)).closed_incorporations);
61
+ }
62
+ async function getSelectableAppRegions(apiOrigin) {
63
+ return stringList((await getOrgRegions(apiOrigin)).app_regions);
64
+ }
65
+ async function postDnsChallenge(apiOrigin, bearer, args) {
66
+ return apiJson(apiOrigin, "/orgs/dns/challenge", {
67
+ method: "POST",
68
+ bearer,
69
+ body: {
70
+ domain: args.domain.trim(),
71
+ kind: args.kind ?? "anchor",
72
+ ...args.incorporation !== void 0 ? { incorporation: args.incorporation } : {}
73
+ }
74
+ });
75
+ }
76
+ async function postVerifyAnchor(apiOrigin, bearer, args) {
77
+ return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
78
+ method: "POST",
79
+ bearer,
80
+ body: {
81
+ domain: args.domain.trim(),
82
+ nonce: args.nonce,
83
+ ...args.name ? { name: args.name.trim() } : {},
84
+ accept_customer_terms: args.acceptCustomerTerms === true,
85
+ ...args.incorporation !== void 0 ? { incorporation: args.incorporation } : {}
86
+ }
87
+ });
88
+ }
89
+ async function postPolicyBootstrap(apiOrigin, bearer, orgId, receipt) {
90
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
91
+ method: "POST",
92
+ bearer,
93
+ body: receipt ? { receipt } : {}
94
+ });
95
+ }
96
+ async function listApps(apiOrigin, bearer, orgId) {
97
+ const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
98
+ bearer
99
+ });
100
+ return r.apps ?? [];
101
+ }
102
+ async function getApp(apiOrigin, bearer, orgId, appId) {
103
+ const r = await apiJson(
104
+ apiOrigin,
105
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
106
+ { bearer }
107
+ );
108
+ return r.app;
109
+ }
110
+ async function postAppRegister(apiOrigin, bearer, orgId, payload) {
111
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
112
+ method: "POST",
113
+ bearer,
114
+ body: payload
115
+ });
116
+ }
117
+ async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
118
+ return apiJson(
119
+ apiOrigin,
120
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
121
+ { bearer }
122
+ );
123
+ }
124
+ async function postVerifyHost(apiOrigin, bearer, orgId, appId, receipt) {
125
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
126
+ method: "POST",
127
+ bearer,
128
+ body: { receipt }
129
+ });
130
+ }
131
+ async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
132
+ return apiJson(
133
+ apiOrigin,
134
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
135
+ {
136
+ method: "PUT",
137
+ bearer,
138
+ body: {
139
+ endUsers: args.endUsers,
140
+ uses: args.uses,
141
+ receipt: args.receipt
142
+ }
143
+ }
144
+ );
145
+ }
146
+ async function putAppRegions(apiOrigin, bearer, orgId, appId, args) {
147
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/regions`, {
148
+ method: "PUT",
149
+ bearer,
150
+ body: { accepted_regions: args.regions, receipt: args.receipt }
151
+ });
152
+ }
153
+ async function getCard(apiOrigin, bearer, orgId) {
154
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
155
+ }
156
+ async function postCardIncorporation(apiOrigin, bearer, orgId, args) {
157
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/incorporation`, {
158
+ method: "POST",
159
+ bearer,
160
+ body: { code: args.code, receipt: args.receipt }
161
+ });
162
+ }
163
+ async function postCardCheckout(apiOrigin, bearer, orgId, args) {
164
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
165
+ method: "POST",
166
+ bearer,
167
+ body: {
168
+ capability: args.capability,
169
+ offer: args.offer,
170
+ consent: { polar_provision: args.consentBillingData },
171
+ ui_locale: args.uiLocale,
172
+ receipt: args.receipt
173
+ }
174
+ });
175
+ }
176
+ async function fetchJwksDocument(apiOrigin) {
177
+ const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
178
+ redirect: "error",
179
+ headers: { Accept: "application/json" }
180
+ });
181
+ if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
182
+ return res.json();
183
+ }
184
+ async function getMasterJwkJson(apiOrigin, masterPinJson) {
185
+ const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
186
+ const doc = await fetchJwksDocument(apiOrigin);
187
+ await verifySignedJwksDocument(doc, masterPinJson);
188
+ return JSON.stringify(doc.master);
189
+ }
190
+
191
+ // src/app-regions.ts
192
+ var APP_REGIONS = ["JP", "US", "GB", "EEA"];
193
+ var CHOICE_HINT = "Pass --regions with one or more of JP, US, GB, EEA (comma-separated), or --all (MCP: regions or all: true).";
194
+ function isAppRegion(value) {
195
+ return APP_REGIONS.includes(value);
196
+ }
197
+ function readAppRegionsInput(raw) {
198
+ if (raw === null) return { ok: true, regions: null };
199
+ const codes = raw.map((code) => code.trim().toUpperCase());
200
+ if (codes.length === 0 || new Set(codes).size !== codes.length || !codes.every(isAppRegion)) {
201
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
202
+ }
203
+ return { ok: true, regions: APP_REGIONS.filter((region) => codes.includes(region)) };
204
+ }
205
+ function sameAppRegions(stored, next) {
206
+ const current = stored ?? null;
207
+ if (current === null || next === null) return current === next;
208
+ return current.length === next.length && current.every((region, i) => region === next[i]);
209
+ }
210
+ function regionNotOpenRefusal(closed, selectable) {
211
+ const open = selectable && selectable.length > 0 ? ` Regions you can choose now: ${selectable.join(", ")}.` : "";
212
+ return {
213
+ ok: false,
214
+ error: `region_not_open \u2014 Clavis is not accepting new connections from ${closed.join(", ")} right now, so an App cannot accept them.${open}`
215
+ };
216
+ }
217
+ function appDisabledRefusal() {
218
+ return { ok: false, error: "app_disabled \u2014 this App is disabled, so its regions cannot be changed." };
219
+ }
220
+ function appRegionsRefusal(e, regions) {
221
+ if (!(e instanceof SetupApiError)) return null;
222
+ switch (e.code) {
223
+ case "REGION_NOT_OPEN":
224
+ return regionNotOpenRefusal(regions, null);
225
+ case "REGIONS_INVALID":
226
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
227
+ case "APP_DISABLED":
228
+ return appDisabledRefusal();
229
+ case "FORBIDDEN":
230
+ return { ok: false, error: "forbidden \u2014 only an owner or admin of the Org can change the App's regions." };
231
+ default:
232
+ return null;
233
+ }
234
+ }
12
235
  var execFileAsync = promisify(execFile);
236
+ function isLoopbackHost(hostname) {
237
+ const host = hostname.toLowerCase();
238
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
239
+ }
240
+ function assertOpenableBrowserUrl(raw) {
241
+ let url;
242
+ try {
243
+ url = new URL(raw.trim());
244
+ } catch {
245
+ throw new Error("invalid URL");
246
+ }
247
+ if (url.username || url.password) throw new Error("URL must not contain credentials");
248
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost(url.hostname);
249
+ if (url.protocol !== "https:" && !loopbackHttp) {
250
+ throw new Error("only https URLs may be opened in a browser");
251
+ }
252
+ return url.toString();
253
+ }
254
+ function windowsBrowserArgs(raw) {
255
+ const url = assertOpenableBrowserUrl(raw);
256
+ const script = `Start-Process -FilePath '${url.replaceAll("'", "''")}'`;
257
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
258
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
259
+ }
13
260
  async function openBrowser(url) {
261
+ const safe = assertOpenableBrowserUrl(url);
14
262
  if (process.platform === "darwin") {
15
- await execFileAsync("open", [url]);
263
+ await execFileAsync("open", [safe]);
16
264
  return;
17
265
  }
18
266
  if (process.platform === "win32") {
19
- await execFileAsync("cmd", ["/c", "start", "", url]);
267
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
20
268
  return;
21
269
  }
22
- await execFileAsync("xdg-open", [url]);
270
+ await execFileAsync("xdg-open", [safe]);
271
+ }
272
+
273
+ // src/types.ts
274
+ var DEFAULT_ORIGINS = {
275
+ apiOrigin: "https://api.clavis.nexus",
276
+ idOrigin: "https://id.clavis.nexus",
277
+ developersOrigin: "https://developers.clavis.nexus"
278
+ };
279
+ var LEGAL_ORIGIN = "https://legal.clavis.nexus";
280
+
281
+ // src/org-creation.ts
282
+ var INCORPORATION_HINT = "JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)";
283
+ var TERMS_LINKS = `Customer Terms: ${LEGAL_ORIGIN}/en/customer-terms \u2014 DPA: ${LEGAL_ORIGIN}/en/dpa.`;
284
+ var TERMS_HUMAN = {
285
+ needs_human: "terms",
286
+ message: `Creating an Org requires the customer to agree to the Customer Terms and the Data Processing Agreement (DPA). ${TERMS_LINKS} Only the customer can decide this. If they agree, pass --accept-customer-terms (MCP: accept_customer_terms: true).`
287
+ };
288
+ var INCORPORATION_TERMS_HUMAN = {
289
+ needs_human: "terms",
290
+ message: `Declaring the place of incorporation binds the Org to the current versions of the Customer Terms and the Data Processing Agreement (DPA). ${TERMS_LINKS} Only the customer can decide this. If they agree, pass --accept-customer-terms (MCP: accept_customer_terms: true).`
291
+ };
292
+ function normalizeIncorporation(raw) {
293
+ return (raw ?? "").trim().toUpperCase();
294
+ }
295
+ function checkOrgCreationTerms(terms, human = TERMS_HUMAN) {
296
+ if (terms.acceptCustomerTerms !== true) {
297
+ return { ok: false, error: "customer_terms_not_accepted", human };
298
+ }
299
+ const incorporation = normalizeIncorporation(terms.incorporation);
300
+ if (!incorporation) {
301
+ return {
302
+ ok: false,
303
+ error: `incorporation_required \u2014 pass --incorporation CODE (MCP: incorporation): ${INCORPORATION_HINT}`
304
+ };
305
+ }
306
+ return { ok: true, incorporation };
307
+ }
308
+ function regionClosedRefusal(incorporation) {
309
+ return {
310
+ ok: false,
311
+ error: `region_closed \u2014 Clavis is not accepting new Orgs incorporated in ${incorporation} right now. GET /orgs/regions lists the closed places.`
312
+ };
313
+ }
314
+ function orgCreationRefusal(e, incorporation) {
315
+ if (!(e instanceof SetupApiError)) return null;
316
+ if (e.status === 403 && e.code === "REGION_CLOSED") return regionClosedRefusal(incorporation);
317
+ if (e.code === "TERMS_REQUIRED") return { ok: false, error: "customer_terms_not_accepted", human: TERMS_HUMAN };
318
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
319
+ return null;
320
+ }
321
+ function incorporationInvalidRefusal(incorporation) {
322
+ return {
323
+ ok: false,
324
+ error: `incorporation_invalid \u2014 ${incorporation || "(empty)"} is not a place of incorporation Clavis accepts. Use ${INCORPORATION_HINT}.`
325
+ };
326
+ }
327
+
328
+ // src/card.ts
329
+ function checkoutLang(raw) {
330
+ return raw === "ja" ? "ja" : "en";
331
+ }
332
+ var BILLING_CONSENT = {
333
+ en: {
334
+ lead: "Subscribing needs the customer's own consent. Show them the statement below and ask. Do not consent on their behalf.",
335
+ statement: "I consent to Clavis providing Polar Software Inc. in the United States with my Clavis account identifier, the organisation ID, the feature being purchased, and, after purchase, the organisation's usage of that feature (counts and times), for payment and billing. Polar handles that data under its own privacy notice.",
336
+ info: (privacyUrl) => `Section 5 of the Privacy Notice (${privacyUrl}) sets out the destination country, an outline of the United States regime, and Polar's measures. Without consent you cannot subscribe, and nothing is sent to Polar.`,
337
+ versions: (terms, dpa) => `This purchase is made under Customer Terms ${terms} and DPA ${dpa}.`,
338
+ next: "If they consent, run again with --consent-billing-data (MCP: consent_billing_data: true)."
339
+ },
340
+ ja: {
341
+ lead: "\u8CFC\u5165\u306B\u306F\u9867\u5BA2\u672C\u4EBA\u306E\u540C\u610F\u304C\u8981\u308A\u307E\u3059\u3002\u6B21\u306E\u6587\u3092\u898B\u305B\u3066\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044\u3002\u4EE3\u308F\u308A\u306B\u540C\u610F\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044\u3002",
342
+ statement: "\u6C7A\u6E08\u3068\u8ACB\u6C42\u306E\u305F\u3081\u3001Clavis \u30A2\u30AB\u30A6\u30F3\u30C8\u8B58\u5225\u5B50\u3001Org ID \u3068\u8CFC\u5165\u3059\u308B\u6A5F\u80FD\u3001\u304A\u3088\u3073\u8CFC\u5165\u5F8C\u306E\u5229\u7528\u91CF\uFF08\u4EF6\u6570\u3068\u65E5\u6642\uFF09\u3092\u3001\u7C73\u56FD\u306E Polar Software Inc. \u306B\u63D0\u4F9B\u3059\u308B\u3053\u3068\u306B\u540C\u610F\u3057\u307E\u3059\u3002Polar \u306F\u81EA\u3089\u306E\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u901A\u77E5\u306B\u5F93\u3063\u3066\u53D6\u308A\u6271\u3044\u307E\u3059\u3002",
343
+ info: (privacyUrl) => `\u79FB\u8EE2\u5148\u306E\u56FD\u3001\u7C73\u56FD\u306E\u5236\u5EA6\u306E\u6982\u8981\u3001Polar \u306E\u63AA\u7F6E\u306F\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u901A\u77E5\u306E\u7B2C 5 \u7BC0\uFF08${privacyUrl}\uFF09\u306B\u3042\u308A\u307E\u3059\u3002\u540C\u610F\u3057\u306A\u3044\u5834\u5408\u306F\u8CFC\u5165\u3067\u304D\u305A\u3001Polar \u3078\u306F\u4F55\u3082\u9001\u308A\u307E\u305B\u3093\u3002`,
344
+ versions: (terms, dpa) => `\u3053\u306E\u8CFC\u5165\u306F\u3001\u7D44\u7E54\u306E\u5951\u7D04 ${terms} \u3068 DPA ${dpa} \u306E\u3082\u3068\u3067\u884C\u3044\u307E\u3059\u3002`,
345
+ next: "\u540C\u610F\u3092\u5F97\u305F\u3089\u3001--consent-billing-data\uFF08MCP: consent_billing_data: true\uFF09\u3092\u4ED8\u3051\u3066\u3082\u3046\u4E00\u5EA6\u5B9F\u884C\u3057\u307E\u3059\u3002"
346
+ }
347
+ };
348
+ function billingConsentHuman(acceptance, lang) {
349
+ const copy = BILLING_CONSENT[lang];
350
+ return {
351
+ needs_human: "terms",
352
+ message: [
353
+ copy.lead,
354
+ copy.statement,
355
+ copy.info(`${LEGAL_ORIGIN}/${lang}/privacy`),
356
+ copy.versions(acceptance.customer_terms_version, acceptance.dpa_version),
357
+ copy.next
358
+ ].join("\n")
359
+ };
360
+ }
361
+ function incorporationNeededRefusal(orgId, stale) {
362
+ const why = stale ? "The Customer Terms have a newer version, so the place of incorporation must be declared again." : "Set the place of incorporation before subscribing.";
363
+ return {
364
+ ok: false,
365
+ error: stale ? "incorporation_stale" : "incorporation_required",
366
+ human: {
367
+ needs_human: "terms",
368
+ message: `${why} Run: clavis incorporation-set ${orgId} --incorporation CODE --accept-customer-terms (MCP: clavis_incorporation_set), after the customer agrees.`
369
+ }
370
+ };
371
+ }
372
+ function purchaseRegionClosedRefusal(incorporation) {
373
+ return {
374
+ ok: false,
375
+ error: `region_closed \u2014 new subscriptions are not accepted right now for Orgs incorporated in ${incorporation}.`
376
+ };
377
+ }
378
+ function declarationRegionClosedRefusal(incorporation) {
379
+ return {
380
+ ok: false,
381
+ error: `region_closed \u2014 ${incorporation} cannot be declared as the place of incorporation right now. GET /orgs/regions lists the closed places.`
382
+ };
383
+ }
384
+ function checkoutRefusal(e, args) {
385
+ if (!(e instanceof SetupApiError)) return null;
386
+ switch (e.code) {
387
+ case "REGION_CLOSED":
388
+ return purchaseRegionClosedRefusal(args.incorporation);
389
+ case "INCORPORATION":
390
+ return incorporationNeededRefusal(args.orgId, e.message === "incorporation_stale");
391
+ case "AGE_INELIGIBLE":
392
+ return { ok: false, error: "age_ineligible \u2014 an organisation contract can be made by someone who is 18 or older." };
393
+ case "AGE_BAND_REQUIRED":
394
+ return {
395
+ ok: false,
396
+ error: "age_band_required \u2014 this account has no age record, so the organisation contract can't continue."
397
+ };
398
+ case "BILLING_SUBJECT":
399
+ return {
400
+ ok: false,
401
+ error: "billing_subject_taken \u2014 this account already pays for another Org. Another owner or admin of this Org can subscribe instead."
402
+ };
403
+ case "CHECKOUT_CLOSED":
404
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
405
+ default:
406
+ return null;
407
+ }
408
+ }
409
+ function incorporationSetRefusal(e, incorporation) {
410
+ if (!(e instanceof SetupApiError)) return null;
411
+ if (e.code === "REGION_CLOSED") return declarationRegionClosedRefusal(incorporation);
412
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
413
+ return null;
23
414
  }
24
415
 
25
416
  // src/safe-browser-url.ts
26
- function parseHttpsUrl(raw) {
417
+ function isLoopbackHost2(hostname) {
418
+ const host = hostname.toLowerCase();
419
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
420
+ }
421
+ function parseBrowserUrl(raw) {
27
422
  let u;
28
423
  try {
29
424
  u = new URL(raw.trim());
30
425
  } catch {
31
426
  throw new Error("invalid URL");
32
427
  }
33
- if (u.protocol !== "https:") {
34
- throw new Error("only https URLs may be opened in a browser");
35
- }
36
428
  if (u.username || u.password) {
37
429
  throw new Error("URL must not contain credentials");
38
430
  }
39
431
  return u;
40
432
  }
41
433
  function assertCardCheckoutBrowserUrl(raw) {
42
- const u = parseHttpsUrl(raw);
434
+ const u = parseBrowserUrl(raw);
435
+ if (u.protocol !== "https:") {
436
+ throw new Error("only https URLs may be opened in a browser");
437
+ }
43
438
  const host = u.hostname.toLowerCase();
44
439
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
45
440
  throw new Error("checkout URL host is not allowed");
@@ -47,15 +442,21 @@ function assertCardCheckoutBrowserUrl(raw) {
47
442
  return u.toString();
48
443
  }
49
444
  function assertOriginBrowserUrl(raw, origin) {
50
- const u = parseHttpsUrl(raw);
445
+ const u = parseBrowserUrl(raw);
51
446
  let expected;
52
447
  try {
53
448
  expected = new URL(origin.trim());
54
449
  } catch {
55
450
  throw new Error("invalid expected origin");
56
451
  }
57
- if (expected.protocol !== "https:") {
58
- throw new Error("expected origin must be https");
452
+ if (expected.username || expected.password) {
453
+ throw new Error("expected origin must not contain credentials");
454
+ }
455
+ const loopback = isLoopbackHost2(expected.hostname);
456
+ const https = expected.protocol === "https:" && u.protocol === "https:";
457
+ const loopbackHttp = loopback && expected.protocol === "http:" && u.protocol === "http:";
458
+ if (!https && !loopbackHttp) {
459
+ throw new Error("only https URLs may be opened in a browser");
59
460
  }
60
461
  if (u.origin !== expected.origin) {
61
462
  throw new Error("URL origin does not match the expected origin");
@@ -70,10 +471,6 @@ function bytesToBase64Url(bytes) {
70
471
  const b64 = Buffer.from(bin, "binary").toString("base64");
71
472
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
72
473
  }
73
- async function sha256Base64Url(text) {
74
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
75
- return bytesToBase64Url(digest);
76
- }
77
474
  async function sha256HexUtf8(s) {
78
475
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
79
476
  let out = "";
@@ -96,60 +493,78 @@ function stableStringify(v) {
96
493
  return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`).join(",")}}`;
97
494
  }
98
495
 
99
- // src/digests.ts
100
- async function computeOrgPolicyBootstrapDigest(input2) {
101
- return sha256Base64Url(
102
- canonicalStringify({
103
- org_id: input2.org_id.trim(),
104
- primary_domain: input2.primary_domain.trim().toLowerCase(),
105
- owner_sub: input2.owner_sub.trim()
106
- })
107
- );
496
+ // src/statements.ts
497
+ async function digestOf(value) {
498
+ const bytes = new TextEncoder().encode(canonicalStringify(value));
499
+ return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))}`;
500
+ }
501
+ function orgAnchorPublishStatement(input2) {
502
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
503
+ }
504
+ function orgPolicyBootstrapStatement(input2) {
505
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
506
+ }
507
+ function orgAppRegisterStatement(input2) {
508
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim().toLowerCase() };
509
+ }
510
+ function orgAppVerifyHostStatement(input2) {
511
+ return {
512
+ type: "org.app.verify_host@1",
513
+ org: input2.org.trim(),
514
+ app: input2.app.trim(),
515
+ host: input2.host.trim().toLowerCase(),
516
+ nonce: input2.nonce.trim()
517
+ };
518
+ }
519
+ async function orgAppDeclarationStatement(input2) {
520
+ return {
521
+ type: "org.app.declaration@1",
522
+ org: input2.org.trim(),
523
+ app: input2.app.trim(),
524
+ declaration: input2.declaration === null ? null : await digestOf({ endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
525
+ };
526
+ }
527
+ function orgAppRegionsStatement(input2) {
528
+ return {
529
+ type: "org.app.regions@1",
530
+ org: input2.org.trim(),
531
+ app: input2.app.trim(),
532
+ regions: input2.regions === null ? null : [...new Set(input2.regions)].sort()
533
+ };
534
+ }
535
+ function orgCardIncorporationStatement(input2) {
536
+ return {
537
+ type: "org.card.incorporation_set@1",
538
+ org: input2.org.trim(),
539
+ code: input2.code.trim(),
540
+ customer_terms: input2.customerTerms.trim(),
541
+ dpa: input2.dpa.trim()
542
+ };
543
+ }
544
+ function orgCardCheckoutStatement(input2) {
545
+ return {
546
+ type: "org.card.checkout@1",
547
+ org: input2.org.trim(),
548
+ capability: input2.capability.trim(),
549
+ offer: input2.offer,
550
+ customer_terms: input2.customerTerms.trim(),
551
+ dpa: input2.dpa.trim()
552
+ };
553
+ }
554
+ function sameStatement(a, b) {
555
+ try {
556
+ return canonicalStringify(a) === canonicalStringify(b);
557
+ } catch {
558
+ return false;
559
+ }
108
560
  }
109
561
  async function computePayloadCommitmentHex(payload) {
110
562
  const o = payload && typeof payload === "object" ? { ...payload } : payload;
111
563
  if (o && typeof o === "object" && !Array.isArray(o)) {
112
- delete o.proposer_sign_proof;
564
+ delete o.proposer_receipt;
113
565
  }
114
566
  return sha256HexUtf8(canonicalStringify(o));
115
567
  }
116
- async function computeOrgAppRegisterDigest(input2) {
117
- return sha256Base64Url(
118
- canonicalStringify({
119
- payload_hash: input2.payload_hash.trim().toLowerCase(),
120
- proposer_sub: input2.proposer_sub.trim()
121
- })
122
- );
123
- }
124
- async function computeOrgAppVerifyHostDigest(input2) {
125
- return sha256Base64Url(
126
- canonicalStringify({
127
- app_id: input2.app_id.trim(),
128
- host: input2.host.trim().toLowerCase(),
129
- nonce: input2.nonce.trim(),
130
- org_id: input2.org_id.trim()
131
- })
132
- );
133
- }
134
- async function computeOrgAppDeclarationHash(declaration) {
135
- if (declaration === null) return "cleared";
136
- return sha256Base64Url(
137
- canonicalStringify({
138
- endUsers: declaration.endUsers,
139
- uses: declaration.uses
140
- })
141
- );
142
- }
143
- async function computeOrgAppDeclarationDigest(input2) {
144
- return sha256Base64Url(
145
- canonicalStringify({
146
- org_id: input2.org_id.trim(),
147
- app_id: input2.app_id.trim(),
148
- declaration_hash: input2.declaration_hash.trim(),
149
- actor_sub: input2.actor_sub.trim()
150
- })
151
- );
152
- }
153
568
  async function hashManifestBody(body) {
154
569
  return sha256HexUtf8(canonicalStringify(body));
155
570
  }
@@ -158,33 +573,26 @@ function buildAnchorTxtRecord(args) {
158
573
  }
159
574
 
160
575
  // src/ceremony.ts
161
- function signProofFromCeremonyPayload(payload) {
162
- if (payload === null || typeof payload !== "object") {
163
- throw new Error("Passkey confirmation did not return a signature.");
576
+ function receiptFromCeremonyPayload(payload) {
577
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
578
+ throw new Error("Passkey confirmation did not return a receipt.");
164
579
  }
165
580
  const o = payload;
166
- const nested = o.sign_proof;
167
- if (nested !== null && typeof nested === "object") return nested;
168
- if (o.v === 1 && o.intent_type === "generic_sign" && typeof o.intent_id === "string" && o.intent_id.length > 0) {
169
- return o;
581
+ if (o.type !== "receipt@1" || o.statement === null || typeof o.statement !== "object") {
582
+ throw new Error("Passkey confirmation did not return a receipt.");
170
583
  }
171
- throw new Error("Passkey confirmation did not return a signature.");
584
+ return o;
172
585
  }
173
586
  async function startCeremony(args) {
174
587
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
175
588
  method: "POST",
589
+ redirect: "error",
176
590
  headers: {
177
591
  Accept: "application/json",
178
592
  "Content-Type": "application/json",
179
593
  Authorization: `Bearer ${args.bearer}`
180
594
  },
181
- body: JSON.stringify({
182
- return_to: args.returnTo,
183
- purpose: args.purpose,
184
- ...args.messageDigest ? { message_digest: args.messageDigest } : {},
185
- ...args.displayHint ? { display_hint: args.displayHint } : {},
186
- ...args.label ? { label: args.label } : {}
187
- })
595
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
188
596
  });
189
597
  const body = await res.json().catch(() => null);
190
598
  if (!res.ok || typeof body?.payload?.ticket !== "string") {
@@ -200,6 +608,7 @@ async function pollCeremonyResult(args) {
200
608
  while (Date.now() < deadline) {
201
609
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
202
610
  method: "POST",
611
+ redirect: "error",
203
612
  headers: {
204
613
  Accept: "application/json",
205
614
  "Content-Type": "application/json",
@@ -209,7 +618,7 @@ async function pollCeremonyResult(args) {
209
618
  });
210
619
  const body = await res.json().catch(() => null);
211
620
  if (res.ok && body?.payload !== void 0) {
212
- return body.payload.payload;
621
+ return body.payload.receipt;
213
622
  }
214
623
  if (res.status === 404) {
215
624
  lastError = body?.message ?? "waiting for Passkey";
@@ -221,7 +630,7 @@ async function pollCeremonyResult(args) {
221
630
  throw new Error(lastError);
222
631
  }
223
632
  function sleep(ms) {
224
- return new Promise((resolve) => setTimeout(resolve, ms));
633
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
225
634
  }
226
635
  function ceremonyPageUrl(idOrigin, ticket) {
227
636
  const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
@@ -231,176 +640,60 @@ function ceremonyPageUrl(idOrigin, ticket) {
231
640
  function setupCeremonyReturnTo(developersOrigin) {
232
641
  return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
233
642
  }
234
-
235
- // src/org-api.ts
236
- var SetupApiError = class extends Error {
237
- status;
238
- code;
239
- constructor(status, code, message) {
240
- super(message);
241
- this.name = "SetupApiError";
242
- this.status = status;
243
- this.code = code;
244
- }
245
- };
246
- async function apiJson(apiOrigin, path2, opts) {
247
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path2}`, {
248
- method: opts.method ?? "GET",
249
- headers: {
250
- Accept: "application/json",
251
- Authorization: `Bearer ${opts.bearer}`,
252
- ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
253
- },
254
- body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
255
- });
256
- const body = await res.json().catch(() => null);
257
- if (!res.ok) {
258
- const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
259
- const message = typeof body?.message === "string" ? body.message : code;
260
- throw new SetupApiError(res.status, code, message);
643
+ async function refuseSymlink(path2) {
644
+ try {
645
+ const st = await lstat(path2);
646
+ if (st.isSymbolicLink()) throw new Error(`refusing to write through a symlink: ${path2}`);
647
+ } catch (e) {
648
+ if (e.code === "ENOENT") return;
649
+ throw e;
261
650
  }
262
- return body ?? {};
263
- }
264
- async function listOrgs(apiOrigin, bearer) {
265
- const r = await apiJson(apiOrigin, "/orgs", { bearer });
266
- return r.orgs ?? [];
267
- }
268
- async function getOrg(apiOrigin, bearer, orgId) {
269
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
270
- }
271
- async function postDnsChallenge(apiOrigin, bearer, domain, kind = "anchor") {
272
- return apiJson(apiOrigin, "/orgs/dns/challenge", {
273
- method: "POST",
274
- bearer,
275
- body: { domain: domain.trim(), kind }
276
- });
277
- }
278
- async function postVerifyAnchor(apiOrigin, bearer, args) {
279
- return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
280
- method: "POST",
281
- bearer,
282
- body: {
283
- domain: args.domain.trim(),
284
- nonce: args.nonce,
285
- ...args.name ? { name: args.name.trim() } : {}
286
- }
287
- });
288
- }
289
- async function postPolicyBootstrap(apiOrigin, bearer, orgId, signProof) {
290
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
291
- method: "POST",
292
- bearer,
293
- body: signProof ? { sign_proof: signProof } : {}
294
- });
295
- }
296
- async function listApps(apiOrigin, bearer, orgId) {
297
- const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
298
- bearer
299
- });
300
- return r.apps ?? [];
301
- }
302
- async function getApp(apiOrigin, bearer, orgId, appId) {
303
- const r = await apiJson(
304
- apiOrigin,
305
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
306
- { bearer }
307
- );
308
- return r.app;
309
- }
310
- async function postAppRegister(apiOrigin, bearer, orgId, payload) {
311
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
312
- method: "POST",
313
- bearer,
314
- body: payload
315
- });
316
- }
317
- async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
318
- return apiJson(
319
- apiOrigin,
320
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
321
- { bearer }
322
- );
323
- }
324
- async function postVerifyHost(apiOrigin, bearer, orgId, appId, signProof) {
325
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
326
- method: "POST",
327
- bearer,
328
- body: { sign_proof: signProof }
329
- });
330
- }
331
- async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
332
- return apiJson(
333
- apiOrigin,
334
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
335
- {
336
- method: "PUT",
337
- bearer,
338
- body: {
339
- endUsers: args.endUsers,
340
- uses: args.uses,
341
- sign_proof: args.signProof
342
- }
343
- }
344
- );
345
- }
346
- async function getCard(apiOrigin, bearer, orgId) {
347
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
348
- }
349
- async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signature") {
350
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
351
- method: "POST",
352
- bearer,
353
- body: { capability }
354
- });
355
651
  }
356
- async function fetchJwksDocument(apiOrigin) {
357
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
358
- headers: { Accept: "application/json" }
359
- });
360
- if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
361
- return res.json();
362
- }
363
- function masterJwkJsonFromDocument(jwks) {
364
- const master = jwks.master ?? jwks.keys?.find((k) => k.kid === "master" || k.use === "master" || k.alg === "EdDSA");
365
- if (!master) throw new SetupApiError(404, "MASTER_JWK_MISSING", "master JWK not found in JWKS");
366
- return JSON.stringify(master);
652
+ async function writeMode600(path2, contents) {
653
+ const dir = dirname(path2);
654
+ await mkdir(dir, { recursive: true, mode: 448 });
655
+ await refuseSymlink(dir);
656
+ await refuseSymlink(path2);
657
+ await writeFile(path2, contents, { encoding: "utf8", mode: 384 });
658
+ try {
659
+ await chmod(path2, 384);
660
+ } catch (e) {
661
+ await unlink(path2).catch(() => void 0);
662
+ const message = e instanceof Error ? e.message : String(e);
663
+ throw new Error(`could not set mode 0600 on ${path2}: ${message}`);
664
+ }
367
665
  }
368
- async function getMasterJwkJson(apiOrigin, masterPinJson) {
369
- const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
370
- const doc = await fetchJwksDocument(apiOrigin);
371
- await verifySignedJwksDocument(doc, masterPinJson);
372
- return masterJwkJsonFromDocument(doc);
666
+
667
+ // src/operate-key-store.ts
668
+ var APP_ID_RE = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[a-z0-9][a-z0-9._-]{0,126})$/;
669
+ function assertOperateAppId(appId) {
670
+ const app = appId.trim().toLowerCase();
671
+ if (!APP_ID_RE.test(app)) throw new Error("invalid_app_id");
672
+ return app;
673
+ }
674
+ function keysBase() {
675
+ const override = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim();
676
+ return resolve(override || join(homedir(), ".config", "clavis", "apps"));
677
+ }
678
+ function pathInsideKeys(appId, file) {
679
+ const app = assertOperateAppId(appId);
680
+ const base = keysBase();
681
+ const path2 = resolve(base, app, file);
682
+ const rel = relative(base, path2);
683
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("invalid_app_id");
684
+ return path2;
373
685
  }
374
686
  function operatePrivateJwkPath(appId) {
375
- const app = appId.trim();
376
- if (!app) throw new Error("appId required");
377
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
378
- return join(base, app, "operate-private.jwk.json");
687
+ return pathInsideKeys(appId, "operate-private.jwk.json");
379
688
  }
380
689
  function appEnvFilePath(appId) {
381
- const app = appId.trim();
382
- if (!app) throw new Error("appId required");
383
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
384
- return join(base, app, "app.env");
385
- }
386
- async function restrictFileMode(path2) {
387
- try {
388
- await chmod(path2, 384);
389
- } catch (e) {
390
- console.warn(
391
- `clavis: could not set mode 0600 on ${path2}: ${e instanceof Error ? e.message : e}`
392
- );
393
- }
690
+ return pathInsideKeys(appId, "app.env");
394
691
  }
395
692
  async function saveOperatePrivateJwk(appId, jwkJson) {
396
693
  const path2 = operatePrivateJwkPath(appId);
397
- await mkdir(dirname(path2), { recursive: true });
398
- await writeFile(path2, jwkJson.trim(), "utf8");
399
- await restrictFileMode(path2);
400
- try {
401
- await chmod(dirname(path2), 448);
402
- } catch {
403
- }
694
+ await writeMode600(path2, `${jwkJson.trim()}
695
+ `);
696
+ await chmod(dirname(path2), 448).catch(() => void 0);
404
697
  return path2;
405
698
  }
406
699
  async function readOperatePrivateJwk(appId) {
@@ -413,10 +706,8 @@ async function readOperatePrivateJwk(appId) {
413
706
  }
414
707
  async function writeAppEnvFile(appId, contents) {
415
708
  const path2 = appEnvFilePath(appId);
416
- await mkdir(dirname(path2), { recursive: true });
417
- await writeFile(path2, contents.endsWith("\n") ? contents : `${contents}
418
- `, "utf8");
419
- await restrictFileMode(path2);
709
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
710
+ `);
420
711
  return path2;
421
712
  }
422
713
 
@@ -470,30 +761,59 @@ async function generateOperateKeyPair() {
470
761
  privateJwkJson: JSON.stringify(priv)
471
762
  };
472
763
  }
764
+ var SESSION_SLOT_RE = /^[a-z][a-z0-9]{1,31}-wauthn-auth-jwt(?:-\d{6})?$/;
473
765
  async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
474
- const base = apiOrigin.replace(/\/+$/, "");
475
- const jwks = createRemoteJWKSet(new URL(`${base}/.well-known/jwks.json`));
476
- await jwtVerify(accessToken, jwks, { algorithms: ["ES256"] });
766
+ const origin = new URL(apiOrigin).origin;
767
+ const jwks = createRemoteJWKSet(new URL(`${origin}/.well-known/jwks.json`));
768
+ const { payload, protectedHeader } = await jwtVerify(accessToken, jwks, {
769
+ algorithms: ["ES256"],
770
+ issuer: origin,
771
+ audience: origin,
772
+ requiredClaims: ["exp", "iss", "aud", "sub"]
773
+ });
774
+ const kid = typeof protectedHeader.kid === "string" ? protectedHeader.kid : "";
775
+ if (!SESSION_SLOT_RE.test(kid)) throw new Error("invalid_access_token_kid");
776
+ if (payload.tk !== "access") throw new Error("invalid_access_token_kind");
777
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) throw new Error("invalid_access_token_sub");
778
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) throw new Error("invalid_access_token_exp");
779
+ return { sub: payload.sub, expiresAt: payload.exp };
477
780
  }
478
-
479
- // src/types.ts
480
- var DEFAULT_ORIGINS = {
481
- apiOrigin: "https://api.clavis.nexus",
482
- idOrigin: "https://id.clavis.nexus",
483
- developersOrigin: "https://developers.clavis.nexus"
484
- };
485
-
486
- // src/session-store.ts
487
781
  function defaultSessionPath() {
488
782
  const override = process.env.CLAVIS_SESSION_PATH?.trim();
489
783
  if (override) return override;
490
784
  return join(homedir(), ".config", "clavis", "session.json");
491
785
  }
786
+ function isLoopbackHost3(hostname) {
787
+ const host = hostname.toLowerCase();
788
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
789
+ }
790
+ function assertSetupOrigin(raw, name) {
791
+ let url;
792
+ try {
793
+ url = new URL(raw.trim());
794
+ } catch {
795
+ throw new Error(`${name} must be an absolute URL`);
796
+ }
797
+ if (url.username || url.password) throw new Error(`${name} must not contain credentials`);
798
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost3(url.hostname);
799
+ if (url.protocol !== "https:" && !loopbackHttp) throw new Error(`${name} must be https`);
800
+ if (url.pathname !== "/" || url.search || url.hash) throw new Error(`${name} must be an origin`);
801
+ return url.origin;
802
+ }
492
803
  function originsFromEnv(overrides) {
493
804
  return {
494
- apiOrigin: overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
495
- idOrigin: overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
496
- developersOrigin: overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin
805
+ apiOrigin: assertSetupOrigin(
806
+ overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
807
+ "apiOrigin"
808
+ ),
809
+ idOrigin: assertSetupOrigin(
810
+ overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
811
+ "idOrigin"
812
+ ),
813
+ developersOrigin: assertSetupOrigin(
814
+ overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin,
815
+ "developersOrigin"
816
+ )
497
817
  };
498
818
  }
499
819
  async function loadSession(path2 = defaultSessionPath()) {
@@ -508,16 +828,8 @@ async function loadSession(path2 = defaultSessionPath()) {
508
828
  }
509
829
  }
510
830
  async function saveSession(session, origins, path2 = defaultSessionPath()) {
511
- await mkdir(dirname(path2), { recursive: true });
512
831
  const body = { v: 1, origins, session, savedAt: Date.now() };
513
- await writeFile(path2, JSON.stringify(body, null, 2), "utf8");
514
- try {
515
- await chmod(path2, 384);
516
- } catch (e) {
517
- console.warn(
518
- `clavis: could not set session file mode 0600 (${path2}): ${e instanceof Error ? e.message : e}`
519
- );
520
- }
832
+ await writeMode600(path2, JSON.stringify(body, null, 2));
521
833
  }
522
834
  async function clearSession(path2 = defaultSessionPath()) {
523
835
  try {
@@ -528,21 +840,11 @@ async function clearSession(path2 = defaultSessionPath()) {
528
840
 
529
841
  // src/login.ts
530
842
  var MAX_BRIDGE_JSON_CHARS = 16384;
843
+ var PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
531
844
  function pendingLoginPath(sessionPath) {
532
845
  const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
533
846
  return path.join(base, "login-pending.json");
534
847
  }
535
- function subFromJwt(accessToken) {
536
- try {
537
- const part = accessToken.split(".")[1];
538
- if (!part) return void 0;
539
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
540
- const payload = JSON.parse(json);
541
- return typeof payload.sub === "string" ? payload.sub : void 0;
542
- } catch {
543
- return void 0;
544
- }
545
- }
546
848
  function loginBridgeUrl(developersOrigin, state) {
547
849
  const bridge = new URL("/developers/setup/login", developersOrigin);
548
850
  bridge.searchParams.set("state", state);
@@ -584,12 +886,11 @@ async function sessionFromBridge(args) {
584
886
  if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
585
887
  throw new Error("invalid_bridge_json");
586
888
  }
587
- await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
588
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
889
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
589
890
  return {
590
891
  accessToken: body.accessToken,
591
- ...sub ? { sub } : {},
592
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
892
+ sub: verified.sub,
893
+ expiresAt: verified.expiresAt
593
894
  };
594
895
  }
595
896
  async function readBridgeJsonFromStdin() {
@@ -630,6 +931,14 @@ async function loginWithBrowser(args) {
630
931
  await clearPending(pendingPath);
631
932
  throw new Error("pending_login_origin_mismatch \u2014 run login again");
632
933
  }
934
+ if (!Number.isFinite(pending.createdAt) || Date.now() - pending.createdAt > PENDING_LOGIN_TTL_MS) {
935
+ await clearPending(pendingPath);
936
+ throw new Error("pending_login_expired \u2014 run login again");
937
+ }
938
+ const openUrl2 = assertOriginBrowserUrl(
939
+ loginBridgeUrl(args.origins.developersOrigin, pending.state),
940
+ args.origins.developersOrigin
941
+ );
633
942
  const session2 = await sessionFromBridge({
634
943
  raw: args.bridgeJson,
635
944
  expectedState: pending.state,
@@ -642,12 +951,15 @@ async function loginWithBrowser(args) {
642
951
  human: {
643
952
  needs_human: "login",
644
953
  message: "Session stored.",
645
- open_url: loginBridgeUrl(args.origins.developersOrigin, pending.state)
954
+ open_url: openUrl2
646
955
  }
647
956
  };
648
957
  }
649
958
  const state = randomBytes(16).toString("hex");
650
- const openUrl = loginBridgeUrl(args.origins.developersOrigin, state);
959
+ const openUrl = assertOriginBrowserUrl(
960
+ loginBridgeUrl(args.origins.developersOrigin, state),
961
+ args.origins.developersOrigin
962
+ );
651
963
  await writePending(pendingPath, {
652
964
  v: 1,
653
965
  state,
@@ -657,7 +969,7 @@ async function loginWithBrowser(args) {
657
969
  });
658
970
  if (openFlag) {
659
971
  try {
660
- await openBrowser(assertOriginBrowserUrl(openUrl, args.origins.developersOrigin));
972
+ await openBrowser(openUrl);
661
973
  } catch {
662
974
  }
663
975
  }
@@ -690,12 +1002,18 @@ async function loginWithBrowser(args) {
690
1002
  }
691
1003
 
692
1004
  // src/status.ts
693
- function cardActive(card) {
694
- if (!card) return "unknown";
1005
+ function signatureCard(card) {
695
1006
  const sig = card.capabilities?.signature;
696
- if (!sig) return "inactive";
697
- if (sig.subscribed === true || sig.active === true) return "active";
698
- return "inactive";
1007
+ if (!sig) return { signature_card: "inactive" };
1008
+ if (sig.open === true) return { signature_card: "active" };
1009
+ return {
1010
+ signature_card: "inactive",
1011
+ ...Array.isArray(sig.blockers) && sig.blockers.length > 0 ? { signature_card_blockers: sig.blockers } : {}
1012
+ };
1013
+ }
1014
+ function incorporationOf(card) {
1015
+ const inc = card.incorporation;
1016
+ return inc ? { code: inc.code, terms_current: inc.terms_current === true } : null;
699
1017
  }
700
1018
  async function buildSetupStatus(args) {
701
1019
  if (!args.session) {
@@ -705,7 +1023,9 @@ async function buildSetupStatus(args) {
705
1023
  const detailed = [];
706
1024
  for (const org of orgs) {
707
1025
  let setup_complete = false;
708
- let signature_card = "unknown";
1026
+ let card = {
1027
+ signature_card: "unknown"
1028
+ };
709
1029
  let apps = [];
710
1030
  try {
711
1031
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -713,10 +1033,10 @@ async function buildSetupStatus(args) {
713
1033
  } catch {
714
1034
  }
715
1035
  try {
716
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
717
- signature_card = cardActive(card);
1036
+ const view = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
1037
+ card = { ...signatureCard(view), incorporation: incorporationOf(view) };
718
1038
  } catch {
719
- signature_card = "unknown";
1039
+ card = { signature_card: "unknown" };
720
1040
  }
721
1041
  try {
722
1042
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -724,6 +1044,7 @@ async function buildSetupStatus(args) {
724
1044
  app_id: a.app_id,
725
1045
  host: a.host,
726
1046
  status: a.status,
1047
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
727
1048
  declaration_ok: Boolean(
728
1049
  a.declaration && typeof a.declaration.endUsers === "string" && a.declaration.endUsers.trim() && Array.isArray(a.declaration.uses) && a.declaration.uses.some((u) => u.capability === "signature")
729
1050
  )
@@ -753,7 +1074,7 @@ async function buildSetupStatus(args) {
753
1074
  primary_domain: org.primary_domain,
754
1075
  org_status: org.org_status,
755
1076
  setup_complete,
756
- signature_card,
1077
+ ...card,
757
1078
  apps
758
1079
  });
759
1080
  }
@@ -785,21 +1106,18 @@ async function runPasskeyCeremony(args) {
785
1106
  apiOrigin: args.origins.apiOrigin,
786
1107
  bearer: args.bearer,
787
1108
  returnTo,
788
- purpose: args.purpose,
789
- messageDigest: args.messageDigest,
790
- displayHint: args.displayHint,
791
- label: args.displayHint
1109
+ statement: args.statement
792
1110
  });
793
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1111
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
794
1112
  if (args.openBrowserFlag) {
795
1113
  try {
796
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1114
+ await openBrowser(ceremony_url);
797
1115
  } catch {
798
1116
  }
799
1117
  }
800
1118
  const human = {
801
1119
  needs_human: "passkey",
802
- message: "Confirm with Passkey in the browser, then return to the terminal/agent.",
1120
+ message: `${args.displayHint ? `${args.displayHint}: c` : "C"}onfirm with Passkey in the browser (${args.statement.type}), then return to the terminal/agent.`,
803
1121
  open_url: ceremony_url
804
1122
  };
805
1123
  return {
@@ -812,7 +1130,7 @@ async function runPasskeyCeremony(args) {
812
1130
  bearer: args.bearer,
813
1131
  ticket
814
1132
  });
815
- return signProofFromCeremonyPayload(payload);
1133
+ return receiptFromCeremonyPayload(payload);
816
1134
  }
817
1135
  };
818
1136
  }
@@ -854,18 +1172,43 @@ function createSetupClient(options = {}) {
854
1172
  const report = await buildSetupStatus({ origins, session });
855
1173
  return { ok: true, data: report };
856
1174
  },
857
- async orgAnchorPlan(domain, name) {
1175
+ async orgAnchorPlan(domain, name, terms = {}) {
1176
+ const checked = checkOrgCreationTerms(terms);
1177
+ if (!checked.ok) return checked;
1178
+ const { incorporation } = checked;
858
1179
  const auth = await requireSession({ origins, sessionPath });
859
1180
  if (!auth.ok) return auth;
860
- const challenge = await postDnsChallenge(auth.data.origins.apiOrigin, auth.data.session.accessToken, domain);
861
- if (!challenge.digest) {
862
- return { ok: false, error: "challenge_missing_digest" };
1181
+ const apiOrigin = auth.data.origins.apiOrigin;
1182
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1183
+ if (closed.includes(incorporation)) return regionClosedRefusal(incorporation);
1184
+ let challenge;
1185
+ try {
1186
+ challenge = await postDnsChallenge(apiOrigin, auth.data.session.accessToken, { domain, incorporation });
1187
+ } catch (e) {
1188
+ const refusal = orgCreationRefusal(e, incorporation);
1189
+ if (refusal) return refusal;
1190
+ throw e;
1191
+ }
1192
+ const domainNorm = domain.trim().toLowerCase();
1193
+ if (!challenge.statement || typeof challenge.domain !== "string" || challenge.domain.trim().toLowerCase() !== domainNorm || typeof challenge.nonce !== "string" || challenge.nonce.length === 0 || typeof challenge.exp !== "number" || !Number.isFinite(challenge.exp)) {
1194
+ return { ok: false, error: "challenge_missing_statement" };
1195
+ }
1196
+ const anchorStatement = orgAnchorPublishStatement({ domain: domainNorm, nonce: challenge.nonce, exp: challenge.exp });
1197
+ if (!sameStatement(anchorStatement, challenge.statement)) return { ok: false, error: "challenge_statement_mismatch" };
1198
+ let wellKnown;
1199
+ try {
1200
+ wellKnown = new URL(challenge.well_known_url);
1201
+ } catch {
1202
+ return { ok: false, error: "challenge_url_rejected" };
1203
+ }
1204
+ const txtHost = typeof challenge.txt_host === "string" ? challenge.txt_host.trim().toLowerCase().replace(/\.$/, "") : "";
1205
+ if (wellKnown.protocol !== "https:" || wellKnown.username || wellKnown.password || wellKnown.hostname.toLowerCase() !== domainNorm || txtHost !== domainNorm && !txtHost.endsWith(`.${domainNorm}`)) {
1206
+ return { ok: false, error: "challenge_url_rejected" };
863
1207
  }
864
1208
  const cer = await runPasskeyCeremony({
865
1209
  origins: auth.data.origins,
866
1210
  bearer: auth.data.session.accessToken,
867
- purpose: "org.anchor.publish",
868
- messageDigest: challenge.digest,
1211
+ statement: anchorStatement,
869
1212
  displayHint: `Publish DNS anchor for ${domain}`,
870
1213
  openBrowserFlag
871
1214
  });
@@ -874,9 +1217,10 @@ function createSetupClient(options = {}) {
874
1217
  data: {
875
1218
  domain: challenge.domain,
876
1219
  ...name ? { name } : {},
1220
+ incorporation,
877
1221
  nonce: challenge.nonce,
878
1222
  exp: challenge.exp,
879
- digest: challenge.digest,
1223
+ statement: anchorStatement,
880
1224
  well_known_url: challenge.well_known_url,
881
1225
  txt_host: challenge.txt_host,
882
1226
  ceremony_url: cer.ceremony_url,
@@ -893,12 +1237,12 @@ function createSetupClient(options = {}) {
893
1237
  bearer: auth.data.session.accessToken,
894
1238
  ticket: args.ticket
895
1239
  });
896
- const signProof = signProofFromCeremonyPayload(payload);
1240
+ const receipt = receiptFromCeremonyPayload(payload);
897
1241
  const body = {
898
1242
  v: 1,
899
1243
  kind: "anchor",
900
1244
  domain: args.domain.trim().toLowerCase(),
901
- sign_proof: signProof,
1245
+ receipt,
902
1246
  nonce: args.nonce,
903
1247
  exp: args.exp,
904
1248
  iat: Math.floor(Date.now() / 1e3)
@@ -915,18 +1259,29 @@ function createSetupClient(options = {}) {
915
1259
  txt_value,
916
1260
  human: {
917
1261
  needs_human: "dns",
918
- message: "Publish the well-known JSON and TXT, then call org_verify_anchor."
1262
+ message: "Publish the well-known JSON and TXT, then call org_verify_anchor with the same incorporation and the customer's agreement to the Customer Terms."
919
1263
  }
920
1264
  }
921
1265
  };
922
1266
  },
923
1267
  async orgVerifyAnchor(args) {
1268
+ const checked = checkOrgCreationTerms(args);
1269
+ if (!checked.ok) return checked;
1270
+ const { incorporation } = checked;
924
1271
  const auth = await requireSession({ origins, sessionPath });
925
1272
  if (!auth.ok) return auth;
926
1273
  try {
927
- const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, args);
1274
+ const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, {
1275
+ domain: args.domain,
1276
+ nonce: args.nonce,
1277
+ name: args.name,
1278
+ incorporation,
1279
+ acceptCustomerTerms: args.acceptCustomerTerms
1280
+ });
928
1281
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
929
1282
  } catch (e) {
1283
+ const refusal = orgCreationRefusal(e, incorporation);
1284
+ if (refusal) return refusal;
930
1285
  return {
931
1286
  ok: false,
932
1287
  error: e instanceof Error ? e.message : String(e),
@@ -950,18 +1305,10 @@ function createSetupClient(options = {}) {
950
1305
  if (noop.already_active) return { ok: true, data: noop };
951
1306
  } catch {
952
1307
  }
953
- const sub = auth.data.session.sub;
954
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
955
- const digest = await computeOrgPolicyBootstrapDigest({
956
- org_id: orgId,
957
- primary_domain: detail.primary_domain,
958
- owner_sub: sub
959
- });
960
1308
  const cer = await runPasskeyCeremony({
961
1309
  origins: auth.data.origins,
962
1310
  bearer: auth.data.session.accessToken,
963
- purpose: "org.policy.bootstrap",
964
- messageDigest: digest,
1311
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
965
1312
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
966
1313
  openBrowserFlag
967
1314
  });
@@ -974,24 +1321,126 @@ function createSetupClient(options = {}) {
974
1321
  );
975
1322
  return { ok: true, data: out };
976
1323
  },
977
- async cardCheckout(orgId) {
1324
+ async incorporationSet(args) {
1325
+ const checked = checkOrgCreationTerms(args, INCORPORATION_TERMS_HUMAN);
1326
+ if (!checked.ok) return checked;
1327
+ const code = checked.incorporation;
1328
+ const auth = await requireSession({ origins, sessionPath });
1329
+ if (!auth.ok) return auth;
1330
+ const sub = auth.data.session.sub;
1331
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1332
+ const apiOrigin = auth.data.origins.apiOrigin;
1333
+ const bearer = auth.data.session.accessToken;
1334
+ const card = await getCard(apiOrigin, bearer, args.orgId);
1335
+ const current = card.incorporation;
1336
+ if (current?.code === code && current.terms_current) {
1337
+ return { ok: true, data: { incorporation: current, unchanged: true } };
1338
+ }
1339
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1340
+ if (closed.includes(code) && current?.code !== code) return declarationRegionClosedRefusal(code);
1341
+ const cer = await runPasskeyCeremony({
1342
+ origins: auth.data.origins,
1343
+ bearer,
1344
+ statement: orgCardIncorporationStatement({
1345
+ org: args.orgId,
1346
+ code,
1347
+ customerTerms: card.acceptance.customer_terms_version,
1348
+ dpa: card.acceptance.dpa_version
1349
+ }),
1350
+ displayHint: `Declare ${code} as the place of incorporation`,
1351
+ openBrowserFlag
1352
+ });
1353
+ const proof = await cer.wait();
1354
+ try {
1355
+ const out = await postCardIncorporation(apiOrigin, bearer, args.orgId, { code, receipt: proof });
1356
+ return { ok: true, data: { incorporation: out.incorporation } };
1357
+ } catch (e) {
1358
+ const refusal = incorporationSetRefusal(e, code);
1359
+ if (refusal) return refusal;
1360
+ throw e;
1361
+ }
1362
+ },
1363
+ async cardCheckout(orgId, opts = {}) {
1364
+ const offer = opts.offer === "bundle" ? "bundle" : "meter";
1365
+ const lang = checkoutLang(opts.lang);
978
1366
  const auth = await requireSession({ origins, sessionPath });
979
1367
  if (!auth.ok) return auth;
980
- const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
1368
+ const sub = auth.data.session.sub;
1369
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1370
+ const apiOrigin = auth.data.origins.apiOrigin;
1371
+ const bearer = auth.data.session.accessToken;
1372
+ const card = await getCard(apiOrigin, bearer, orgId);
1373
+ if (card.suspended) return { ok: false, error: "org_suspended" };
1374
+ const signature = card.capabilities?.signature;
1375
+ const open = offer === "bundle" ? signature?.bundle_checkout_open : signature?.checkout_open;
1376
+ if (!signature || open !== true) {
1377
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
1378
+ }
1379
+ const blockers = signature.blockers ?? [];
1380
+ const subscribed = offer === "bundle" ? signature.tariff === "bundle" : !blockers.includes("subscription");
1381
+ if (subscribed) {
1382
+ const state = blockers.length > 0 ? ` (${blockers.join(", ")})` : "";
1383
+ return {
1384
+ ok: false,
1385
+ error: `already_subscribed \u2014 the signature card already has this subscription${state}. Manage it on developers.`
1386
+ };
1387
+ }
1388
+ const incorporation = card.incorporation;
1389
+ if (!incorporation) return incorporationNeededRefusal(orgId, false);
1390
+ if (!incorporation.terms_current) return incorporationNeededRefusal(orgId, true);
1391
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1392
+ if (closed.includes(incorporation.code)) return purchaseRegionClosedRefusal(incorporation.code);
1393
+ if (opts.consentBillingData !== true) {
1394
+ return { ok: false, error: "billing_data_consent_required", human: billingConsentHuman(card.acceptance, lang) };
1395
+ }
1396
+ const cer = await runPasskeyCeremony({
1397
+ origins: auth.data.origins,
1398
+ bearer,
1399
+ statement: orgCardCheckoutStatement({
1400
+ org: orgId,
1401
+ capability: "signature",
1402
+ offer,
1403
+ customerTerms: card.acceptance.customer_terms_version,
1404
+ dpa: card.acceptance.dpa_version
1405
+ }),
1406
+ displayHint: offer === "bundle" ? "Subscribe to the signature card (monthly bundle)" : "Subscribe to the signature card",
1407
+ openBrowserFlag
1408
+ });
1409
+ const proof = await cer.wait();
1410
+ let url;
1411
+ try {
1412
+ ({ url } = await postCardCheckout(apiOrigin, bearer, orgId, {
1413
+ capability: "signature",
1414
+ offer,
1415
+ consentBillingData: true,
1416
+ uiLocale: lang,
1417
+ receipt: proof
1418
+ }));
1419
+ } catch (e) {
1420
+ const refusal = checkoutRefusal(e, { orgId, incorporation: incorporation.code });
1421
+ if (refusal) return refusal;
1422
+ throw e;
1423
+ }
1424
+ let checkoutUrl;
1425
+ try {
1426
+ checkoutUrl = assertCardCheckoutBrowserUrl(url);
1427
+ } catch (e) {
1428
+ return { ok: false, error: e instanceof Error ? e.message : "checkout_url_rejected" };
1429
+ }
981
1430
  if (openBrowserFlag) {
982
1431
  try {
983
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1432
+ await openBrowser(checkoutUrl);
984
1433
  } catch {
985
1434
  }
986
1435
  }
987
1436
  return {
988
1437
  ok: true,
989
1438
  data: {
990
- url,
1439
+ url: checkoutUrl,
991
1440
  human: {
992
1441
  needs_human: "payment",
993
1442
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
994
- open_url: url
1443
+ open_url: checkoutUrl
995
1444
  }
996
1445
  }
997
1446
  };
@@ -1008,26 +1457,24 @@ function createSetupClient(options = {}) {
1008
1457
  v: 1,
1009
1458
  host: args.host.trim().toLowerCase(),
1010
1459
  display_name: args.displayName.trim(),
1011
- intent_types: args.intentTypes ?? ["generic.sign"],
1460
+ intent_types: args.intentTypes ?? ["generic_sign"],
1012
1461
  max_ttl_seconds: 300,
1013
1462
  operate_kid: keys.kid,
1014
1463
  operate_public_jwk: keys.publicJwk,
1015
1464
  redirect_paths: paths
1016
1465
  };
1017
1466
  const payload_hash = await computePayloadCommitmentHex(manifest);
1018
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
1019
1467
  const cer = await runPasskeyCeremony({
1020
1468
  origins: auth.data.origins,
1021
1469
  bearer: auth.data.session.accessToken,
1022
- purpose: "org.app.register",
1023
- messageDigest: digest,
1470
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
1024
1471
  displayHint: `Register App ${manifest.host}`,
1025
1472
  openBrowserFlag
1026
1473
  });
1027
1474
  const proof = await cer.wait();
1028
1475
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
1029
1476
  ...manifest,
1030
- proposer_sign_proof: proof
1477
+ proposer_receipt: proof
1031
1478
  });
1032
1479
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
1033
1480
  return {
@@ -1072,17 +1519,10 @@ function createSetupClient(options = {}) {
1072
1519
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1073
1520
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1074
1521
  if (!nonce) return { ok: false, error: "host_challenge_missing_nonce" };
1075
- const digest = await computeOrgAppVerifyHostDigest({
1076
- org_id: args.orgId,
1077
- app_id: args.appId,
1078
- host: ch.host,
1079
- nonce
1080
- });
1081
1522
  const cer = await runPasskeyCeremony({
1082
1523
  origins: auth.data.origins,
1083
1524
  bearer: auth.data.session.accessToken,
1084
- purpose: "org.app.verify_host",
1085
- messageDigest: digest,
1525
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1086
1526
  displayHint: `Verify host ${ch.host}`,
1087
1527
  openBrowserFlag
1088
1528
  });
@@ -1111,21 +1551,11 @@ function createSetupClient(options = {}) {
1111
1551
  async declarationSet(args) {
1112
1552
  const auth = await requireSession({ origins, sessionPath });
1113
1553
  if (!auth.ok) return auth;
1114
- const sub = auth.data.session.sub;
1115
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1116
1554
  const declaration = { endUsers: args.endUsers, uses: args.uses };
1117
- const declaration_hash = await computeOrgAppDeclarationHash(declaration);
1118
- const digest = await computeOrgAppDeclarationDigest({
1119
- org_id: args.orgId,
1120
- app_id: args.appId,
1121
- declaration_hash,
1122
- actor_sub: sub
1123
- });
1124
1555
  const cer = await runPasskeyCeremony({
1125
1556
  origins: auth.data.origins,
1126
1557
  bearer: auth.data.session.accessToken,
1127
- purpose: "org.app.declaration",
1128
- messageDigest: digest,
1558
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1129
1559
  displayHint: `Declare uses for App ${args.appId}`,
1130
1560
  openBrowserFlag
1131
1561
  });
@@ -1135,10 +1565,47 @@ function createSetupClient(options = {}) {
1135
1565
  auth.data.session.accessToken,
1136
1566
  args.orgId,
1137
1567
  args.appId,
1138
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1568
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1139
1569
  );
1140
1570
  return { ok: true, data: { declaration: out.declaration } };
1141
1571
  },
1572
+ async appRegionsSet(args) {
1573
+ const read = readAppRegionsInput(args.regions);
1574
+ if (!read.ok) return read;
1575
+ const regions = read.regions;
1576
+ const auth = await requireSession({ origins, sessionPath });
1577
+ if (!auth.ok) return auth;
1578
+ const sub = auth.data.session.sub;
1579
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1580
+ const apiOrigin = auth.data.origins.apiOrigin;
1581
+ const bearer = auth.data.session.accessToken;
1582
+ const app = await getApp(apiOrigin, bearer, args.orgId, args.appId);
1583
+ if (app.status === "disabled") return appDisabledRefusal();
1584
+ if (sameAppRegions(app.accepted_regions, regions)) {
1585
+ return { ok: true, data: { accepted_regions: regions, unchanged: true } };
1586
+ }
1587
+ if (regions) {
1588
+ const selectable = await getSelectableAppRegions(apiOrigin).catch(() => null);
1589
+ const closed = selectable ? regions.filter((region) => !selectable.includes(region)) : [];
1590
+ if (closed.length > 0) return regionNotOpenRefusal(closed, selectable);
1591
+ }
1592
+ const cer = await runPasskeyCeremony({
1593
+ origins: auth.data.origins,
1594
+ bearer,
1595
+ statement: orgAppRegionsStatement({ org: args.orgId, app: args.appId, regions }),
1596
+ displayHint: regions ? `Accept new connections to ${app.host} from ${regions.join(", ")} only` : `Accept new connections to ${app.host} from every region Clavis accepts`,
1597
+ openBrowserFlag
1598
+ });
1599
+ const proof = await cer.wait();
1600
+ try {
1601
+ await putAppRegions(apiOrigin, bearer, args.orgId, args.appId, { regions, receipt: proof });
1602
+ return { ok: true, data: { accepted_regions: regions } };
1603
+ } catch (e) {
1604
+ const refusal = appRegionsRefusal(e, regions ?? []);
1605
+ if (refusal) return refusal;
1606
+ throw e;
1607
+ }
1608
+ },
1142
1609
  async emitEnv(args) {
1143
1610
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1144
1611
  if (!jwk) {
@@ -1147,7 +1614,7 @@ function createSetupClient(options = {}) {
1147
1614
  error: "operate_jwk_missing",
1148
1615
  human: {
1149
1616
  needs_human: "login",
1150
- message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
1617
+ message: "Run app-register first so the operate key exists under ~/.config/clavis/apps/"
1151
1618
  }
1152
1619
  };
1153
1620
  }
@@ -1162,6 +1629,6 @@ function createSetupClient(options = {}) {
1162
1629
  return client;
1163
1630
  }
1164
1631
 
1165
- export { DEFAULT_ORIGINS, SetupApiError, clearSession, createSetupClient, defaultSessionPath, formatEnvExport, generateOperateKeyPair, loadSession, originsFromEnv, saveSession };
1632
+ export { APP_REGIONS, DEFAULT_ORIGINS, SetupApiError, clearSession, createSetupClient, defaultSessionPath, formatEnvExport, generateOperateKeyPair, loadSession, originsFromEnv, saveSession };
1166
1633
  //# sourceMappingURL=index.js.map
1167
1634
  //# sourceMappingURL=index.js.map