@clavis.nexus/setup 1.0.2 → 3.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,431 @@
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
- import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
6
+ import { generateKeyPair, exportJWK, jwtVerify, importJWK } 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 checkTrustRoot(apiOrigin, trustRootJson) {
177
+ const { createVerifier } = await import('@clavis.nexus/app');
178
+ await createVerifier({ trustRoot: trustRootJson, apiOrigin }).trust();
179
+ return JSON.stringify(JSON.parse(trustRootJson));
180
+ }
181
+
182
+ // src/app-regions.ts
183
+ var APP_REGIONS = ["JP", "US", "GB", "EEA"];
184
+ var CHOICE_HINT = "Pass --regions with one or more of JP, US, GB, EEA (comma-separated), or --all (MCP: regions or all: true).";
185
+ function isAppRegion(value) {
186
+ return APP_REGIONS.includes(value);
187
+ }
188
+ function readAppRegionsInput(raw) {
189
+ if (raw === null) return { ok: true, regions: null };
190
+ const codes = raw.map((code) => code.trim().toUpperCase());
191
+ if (codes.length === 0 || new Set(codes).size !== codes.length || !codes.every(isAppRegion)) {
192
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
193
+ }
194
+ return { ok: true, regions: APP_REGIONS.filter((region) => codes.includes(region)) };
195
+ }
196
+ function sameAppRegions(stored, next) {
197
+ const current = stored ?? null;
198
+ if (current === null || next === null) return current === next;
199
+ return current.length === next.length && current.every((region, i) => region === next[i]);
200
+ }
201
+ function regionNotOpenRefusal(closed, selectable) {
202
+ const open = selectable && selectable.length > 0 ? ` Regions you can choose now: ${selectable.join(", ")}.` : "";
203
+ return {
204
+ ok: false,
205
+ error: `region_not_open \u2014 Clavis is not accepting new connections from ${closed.join(", ")} right now, so an App cannot accept them.${open}`
206
+ };
207
+ }
208
+ function appDisabledRefusal() {
209
+ return { ok: false, error: "app_disabled \u2014 this App is disabled, so its regions cannot be changed." };
210
+ }
211
+ function appRegionsRefusal(e, regions) {
212
+ if (!(e instanceof SetupApiError)) return null;
213
+ switch (e.code) {
214
+ case "REGION_NOT_OPEN":
215
+ return regionNotOpenRefusal(regions, null);
216
+ case "REGIONS_INVALID":
217
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
218
+ case "APP_DISABLED":
219
+ return appDisabledRefusal();
220
+ case "FORBIDDEN":
221
+ return { ok: false, error: "forbidden \u2014 only an owner or admin of the Org can change the App's regions." };
222
+ default:
223
+ return null;
224
+ }
225
+ }
12
226
  var execFileAsync = promisify(execFile);
227
+ function isLoopbackHost(hostname) {
228
+ const host = hostname.toLowerCase();
229
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
230
+ }
231
+ function assertOpenableBrowserUrl(raw) {
232
+ let url;
233
+ try {
234
+ url = new URL(raw.trim());
235
+ } catch {
236
+ throw new Error("invalid URL");
237
+ }
238
+ if (url.username || url.password) throw new Error("URL must not contain credentials");
239
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost(url.hostname);
240
+ if (url.protocol !== "https:" && !loopbackHttp) {
241
+ throw new Error("only https URLs may be opened in a browser");
242
+ }
243
+ return url.toString();
244
+ }
245
+ function windowsBrowserArgs(raw) {
246
+ const url = assertOpenableBrowserUrl(raw);
247
+ const script = `Start-Process -FilePath '${url.replaceAll("'", "''")}'`;
248
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
249
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
250
+ }
13
251
  async function openBrowser(url) {
252
+ const safe = assertOpenableBrowserUrl(url);
14
253
  if (process.platform === "darwin") {
15
- await execFileAsync("open", [url]);
254
+ await execFileAsync("open", [safe]);
16
255
  return;
17
256
  }
18
257
  if (process.platform === "win32") {
19
- await execFileAsync("cmd", ["/c", "start", "", url]);
258
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
20
259
  return;
21
260
  }
22
- await execFileAsync("xdg-open", [url]);
261
+ await execFileAsync("xdg-open", [safe]);
262
+ }
263
+
264
+ // src/types.ts
265
+ var DEFAULT_ORIGINS = {
266
+ apiOrigin: "https://api.clavis.nexus",
267
+ idOrigin: "https://id.clavis.nexus",
268
+ developersOrigin: "https://developers.clavis.nexus"
269
+ };
270
+ var LEGAL_ORIGIN = "https://legal.clavis.nexus";
271
+
272
+ // src/org-creation.ts
273
+ var INCORPORATION_HINT = "JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)";
274
+ var TERMS_LINKS = `Customer Terms: ${LEGAL_ORIGIN}/en/customer-terms \u2014 DPA: ${LEGAL_ORIGIN}/en/dpa.`;
275
+ var TERMS_HUMAN = {
276
+ needs_human: "terms",
277
+ 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).`
278
+ };
279
+ var INCORPORATION_TERMS_HUMAN = {
280
+ needs_human: "terms",
281
+ 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).`
282
+ };
283
+ function normalizeIncorporation(raw) {
284
+ return (raw ?? "").trim().toUpperCase();
285
+ }
286
+ function checkOrgCreationTerms(terms, human = TERMS_HUMAN) {
287
+ if (terms.acceptCustomerTerms !== true) {
288
+ return { ok: false, error: "customer_terms_not_accepted", human };
289
+ }
290
+ const incorporation = normalizeIncorporation(terms.incorporation);
291
+ if (!incorporation) {
292
+ return {
293
+ ok: false,
294
+ error: `incorporation_required \u2014 pass --incorporation CODE (MCP: incorporation): ${INCORPORATION_HINT}`
295
+ };
296
+ }
297
+ return { ok: true, incorporation };
298
+ }
299
+ function regionClosedRefusal(incorporation) {
300
+ return {
301
+ ok: false,
302
+ error: `region_closed \u2014 Clavis is not accepting new Orgs incorporated in ${incorporation} right now. GET /orgs/regions lists the closed places.`
303
+ };
304
+ }
305
+ function orgCreationRefusal(e, incorporation) {
306
+ if (!(e instanceof SetupApiError)) return null;
307
+ if (e.status === 403 && e.code === "REGION_CLOSED") return regionClosedRefusal(incorporation);
308
+ if (e.code === "TERMS_REQUIRED") return { ok: false, error: "customer_terms_not_accepted", human: TERMS_HUMAN };
309
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
310
+ return null;
311
+ }
312
+ function incorporationInvalidRefusal(incorporation) {
313
+ return {
314
+ ok: false,
315
+ error: `incorporation_invalid \u2014 ${incorporation || "(empty)"} is not a place of incorporation Clavis accepts. Use ${INCORPORATION_HINT}.`
316
+ };
317
+ }
318
+
319
+ // src/card.ts
320
+ function checkoutLang(raw) {
321
+ return raw === "ja" ? "ja" : "en";
322
+ }
323
+ var BILLING_CONSENT = {
324
+ en: {
325
+ lead: "Subscribing needs the customer's own consent. Show them the statement below and ask. Do not consent on their behalf.",
326
+ 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.",
327
+ 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.`,
328
+ versions: (terms, dpa) => `This purchase is made under Customer Terms ${terms} and DPA ${dpa}.`,
329
+ next: "If they consent, run again with --consent-billing-data (MCP: consent_billing_data: true)."
330
+ },
331
+ ja: {
332
+ 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",
333
+ 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",
334
+ 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`,
335
+ 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`,
336
+ 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"
337
+ }
338
+ };
339
+ function billingConsentHuman(acceptance, lang) {
340
+ const copy = BILLING_CONSENT[lang];
341
+ return {
342
+ needs_human: "terms",
343
+ message: [
344
+ copy.lead,
345
+ copy.statement,
346
+ copy.info(`${LEGAL_ORIGIN}/${lang}/privacy`),
347
+ copy.versions(acceptance.customer_terms_version, acceptance.dpa_version),
348
+ copy.next
349
+ ].join("\n")
350
+ };
351
+ }
352
+ function incorporationNeededRefusal(orgId, stale) {
353
+ 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.";
354
+ return {
355
+ ok: false,
356
+ error: stale ? "incorporation_stale" : "incorporation_required",
357
+ human: {
358
+ needs_human: "terms",
359
+ message: `${why} Run: clavis incorporation-set ${orgId} --incorporation CODE --accept-customer-terms (MCP: clavis_incorporation_set), after the customer agrees.`
360
+ }
361
+ };
362
+ }
363
+ function purchaseRegionClosedRefusal(incorporation) {
364
+ return {
365
+ ok: false,
366
+ error: `region_closed \u2014 new subscriptions are not accepted right now for Orgs incorporated in ${incorporation}.`
367
+ };
368
+ }
369
+ function declarationRegionClosedRefusal(incorporation) {
370
+ return {
371
+ ok: false,
372
+ error: `region_closed \u2014 ${incorporation} cannot be declared as the place of incorporation right now. GET /orgs/regions lists the closed places.`
373
+ };
374
+ }
375
+ function checkoutRefusal(e, args) {
376
+ if (!(e instanceof SetupApiError)) return null;
377
+ switch (e.code) {
378
+ case "REGION_CLOSED":
379
+ return purchaseRegionClosedRefusal(args.incorporation);
380
+ case "INCORPORATION":
381
+ return incorporationNeededRefusal(args.orgId, e.message === "incorporation_stale");
382
+ case "AGE_INELIGIBLE":
383
+ return { ok: false, error: "age_ineligible \u2014 an organisation contract can be made by someone who is 18 or older." };
384
+ case "AGE_BAND_REQUIRED":
385
+ return {
386
+ ok: false,
387
+ error: "age_band_required \u2014 this account has no age record, so the organisation contract can't continue."
388
+ };
389
+ case "BILLING_SUBJECT":
390
+ return {
391
+ ok: false,
392
+ error: "billing_subject_taken \u2014 this account already pays for another Org. Another owner or admin of this Org can subscribe instead."
393
+ };
394
+ case "CHECKOUT_CLOSED":
395
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
396
+ default:
397
+ return null;
398
+ }
399
+ }
400
+ function incorporationSetRefusal(e, incorporation) {
401
+ if (!(e instanceof SetupApiError)) return null;
402
+ if (e.code === "REGION_CLOSED") return declarationRegionClosedRefusal(incorporation);
403
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
404
+ return null;
23
405
  }
24
406
 
25
407
  // src/safe-browser-url.ts
26
- function parseHttpsUrl(raw) {
408
+ function isLoopbackHost2(hostname) {
409
+ const host = hostname.toLowerCase();
410
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
411
+ }
412
+ function parseBrowserUrl(raw) {
27
413
  let u;
28
414
  try {
29
415
  u = new URL(raw.trim());
30
416
  } catch {
31
417
  throw new Error("invalid URL");
32
418
  }
33
- if (u.protocol !== "https:") {
34
- throw new Error("only https URLs may be opened in a browser");
35
- }
36
419
  if (u.username || u.password) {
37
420
  throw new Error("URL must not contain credentials");
38
421
  }
39
422
  return u;
40
423
  }
41
424
  function assertCardCheckoutBrowserUrl(raw) {
42
- const u = parseHttpsUrl(raw);
425
+ const u = parseBrowserUrl(raw);
426
+ if (u.protocol !== "https:") {
427
+ throw new Error("only https URLs may be opened in a browser");
428
+ }
43
429
  const host = u.hostname.toLowerCase();
44
430
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
45
431
  throw new Error("checkout URL host is not allowed");
@@ -47,15 +433,21 @@ function assertCardCheckoutBrowserUrl(raw) {
47
433
  return u.toString();
48
434
  }
49
435
  function assertOriginBrowserUrl(raw, origin) {
50
- const u = parseHttpsUrl(raw);
436
+ const u = parseBrowserUrl(raw);
51
437
  let expected;
52
438
  try {
53
439
  expected = new URL(origin.trim());
54
440
  } catch {
55
441
  throw new Error("invalid expected origin");
56
442
  }
57
- if (expected.protocol !== "https:") {
58
- throw new Error("expected origin must be https");
443
+ if (expected.username || expected.password) {
444
+ throw new Error("expected origin must not contain credentials");
445
+ }
446
+ const loopback = isLoopbackHost2(expected.hostname);
447
+ const https = expected.protocol === "https:" && u.protocol === "https:";
448
+ const loopbackHttp = loopback && expected.protocol === "http:" && u.protocol === "http:";
449
+ if (!https && !loopbackHttp) {
450
+ throw new Error("only https URLs may be opened in a browser");
59
451
  }
60
452
  if (u.origin !== expected.origin) {
61
453
  throw new Error("URL origin does not match the expected origin");
@@ -70,10 +462,6 @@ function bytesToBase64Url(bytes) {
70
462
  const b64 = Buffer.from(bin, "binary").toString("base64");
71
463
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
72
464
  }
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
465
  async function sha256HexUtf8(s) {
78
466
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
79
467
  let out = "";
@@ -96,59 +484,81 @@ function stableStringify(v) {
96
484
  return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`).join(",")}}`;
97
485
  }
98
486
 
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
- );
108
- }
109
- async function computePayloadCommitmentHex(payload) {
110
- const o = payload && typeof payload === "object" ? { ...payload } : payload;
111
- if (o && typeof o === "object" && !Array.isArray(o)) {
112
- delete o.proposer_sign_proof;
487
+ // src/statements.ts
488
+ async function digestOf(value) {
489
+ const bytes = new TextEncoder().encode(canonicalStringify(value));
490
+ return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))}`;
491
+ }
492
+ async function valueDigest(type, value) {
493
+ return digestOf({ type, value });
494
+ }
495
+ async function orgPayloadDigest(payload) {
496
+ let value = payload;
497
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
498
+ const { proposer_receipt: _receipt, ...rest } = payload;
499
+ value = rest;
113
500
  }
114
- return sha256HexUtf8(canonicalStringify(o));
115
- }
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
- );
501
+ return valueDigest("org.payload@1", value);
123
502
  }
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
- );
503
+ function orgAnchorPublishStatement(input2) {
504
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
133
505
  }
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
- );
506
+ function orgPolicyBootstrapStatement(input2) {
507
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
142
508
  }
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
- );
509
+ function orgAppRegisterStatement(input2) {
510
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim() };
511
+ }
512
+ function orgAppVerifyHostStatement(input2) {
513
+ return {
514
+ type: "org.app.verify_host@1",
515
+ org: input2.org.trim(),
516
+ app: input2.app.trim(),
517
+ host: input2.host.trim().toLowerCase(),
518
+ nonce: input2.nonce.trim()
519
+ };
520
+ }
521
+ async function orgAppDeclarationStatement(input2) {
522
+ return {
523
+ type: "org.app.declaration@1",
524
+ org: input2.org.trim(),
525
+ app: input2.app.trim(),
526
+ declaration: input2.declaration === null ? null : await valueDigest("app.declaration@1", { endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
527
+ };
528
+ }
529
+ function orgAppRegionsStatement(input2) {
530
+ return {
531
+ type: "org.app.regions@1",
532
+ org: input2.org.trim(),
533
+ app: input2.app.trim(),
534
+ regions: input2.regions === null ? null : [...new Set(input2.regions)].sort()
535
+ };
536
+ }
537
+ function orgCardIncorporationStatement(input2) {
538
+ return {
539
+ type: "org.card.incorporation_set@1",
540
+ org: input2.org.trim(),
541
+ code: input2.code.trim(),
542
+ customer_terms: input2.customerTerms.trim(),
543
+ dpa: input2.dpa.trim()
544
+ };
545
+ }
546
+ function orgCardCheckoutStatement(input2) {
547
+ return {
548
+ type: "org.card.checkout@1",
549
+ org: input2.org.trim(),
550
+ capability: input2.capability.trim(),
551
+ offer: input2.offer,
552
+ customer_terms: input2.customerTerms.trim(),
553
+ dpa: input2.dpa.trim()
554
+ };
555
+ }
556
+ function sameStatement(a, b) {
557
+ try {
558
+ return canonicalStringify(a) === canonicalStringify(b);
559
+ } catch {
560
+ return false;
561
+ }
152
562
  }
153
563
  async function hashManifestBody(body) {
154
564
  return sha256HexUtf8(canonicalStringify(body));
@@ -158,33 +568,22 @@ function buildAnchorTxtRecord(args) {
158
568
  }
159
569
 
160
570
  // 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.");
571
+ function receiptFromCeremonyPayload(payload) {
572
+ if (typeof payload !== "string" || payload.length === 0) {
573
+ throw new Error("Passkey confirmation did not return a receipt.");
164
574
  }
165
- 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;
170
- }
171
- throw new Error("Passkey confirmation did not return a signature.");
575
+ return payload;
172
576
  }
173
577
  async function startCeremony(args) {
174
578
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
175
579
  method: "POST",
580
+ redirect: "error",
176
581
  headers: {
177
582
  Accept: "application/json",
178
583
  "Content-Type": "application/json",
179
584
  Authorization: `Bearer ${args.bearer}`
180
585
  },
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
- })
586
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
188
587
  });
189
588
  const body = await res.json().catch(() => null);
190
589
  if (!res.ok || typeof body?.payload?.ticket !== "string") {
@@ -200,6 +599,7 @@ async function pollCeremonyResult(args) {
200
599
  while (Date.now() < deadline) {
201
600
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
202
601
  method: "POST",
602
+ redirect: "error",
203
603
  headers: {
204
604
  Accept: "application/json",
205
605
  "Content-Type": "application/json",
@@ -209,7 +609,7 @@ async function pollCeremonyResult(args) {
209
609
  });
210
610
  const body = await res.json().catch(() => null);
211
611
  if (res.ok && body?.payload !== void 0) {
212
- return body.payload.payload;
612
+ return body.payload.receipt;
213
613
  }
214
614
  if (res.status === 404) {
215
615
  lastError = body?.message ?? "waiting for Passkey";
@@ -221,7 +621,7 @@ async function pollCeremonyResult(args) {
221
621
  throw new Error(lastError);
222
622
  }
223
623
  function sleep(ms) {
224
- return new Promise((resolve) => setTimeout(resolve, ms));
624
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
225
625
  }
226
626
  function ceremonyPageUrl(idOrigin, ticket) {
227
627
  const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
@@ -231,176 +631,60 @@ function ceremonyPageUrl(idOrigin, ticket) {
231
631
  function setupCeremonyReturnTo(developersOrigin) {
232
632
  return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
233
633
  }
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);
634
+ async function refuseSymlink(path2) {
635
+ try {
636
+ const st = await lstat(path2);
637
+ if (st.isSymbolicLink()) throw new Error(`refusing to write through a symlink: ${path2}`);
638
+ } catch (e) {
639
+ if (e.code === "ENOENT") return;
640
+ throw e;
261
641
  }
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
642
  }
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);
643
+ async function writeMode600(path2, contents) {
644
+ const dir = dirname(path2);
645
+ await mkdir(dir, { recursive: true, mode: 448 });
646
+ await refuseSymlink(dir);
647
+ await refuseSymlink(path2);
648
+ await writeFile(path2, contents, { encoding: "utf8", mode: 384 });
649
+ try {
650
+ await chmod(path2, 384);
651
+ } catch (e) {
652
+ await unlink(path2).catch(() => void 0);
653
+ const message = e instanceof Error ? e.message : String(e);
654
+ throw new Error(`could not set mode 0600 on ${path2}: ${message}`);
655
+ }
367
656
  }
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);
657
+
658
+ // src/operate-key-store.ts
659
+ 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})$/;
660
+ function assertOperateAppId(appId) {
661
+ const app = appId.trim().toLowerCase();
662
+ if (!APP_ID_RE.test(app)) throw new Error("invalid_app_id");
663
+ return app;
664
+ }
665
+ function keysBase() {
666
+ const override = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim();
667
+ return resolve(override || join(homedir(), ".config", "clavis", "apps"));
668
+ }
669
+ function pathInsideKeys(appId, file) {
670
+ const app = assertOperateAppId(appId);
671
+ const base = keysBase();
672
+ const path2 = resolve(base, app, file);
673
+ const rel = relative(base, path2);
674
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("invalid_app_id");
675
+ return path2;
373
676
  }
374
677
  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");
678
+ return pathInsideKeys(appId, "operate-private.jwk.json");
379
679
  }
380
680
  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
- }
681
+ return pathInsideKeys(appId, "app.env");
394
682
  }
395
683
  async function saveOperatePrivateJwk(appId, jwkJson) {
396
684
  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
- }
685
+ await writeMode600(path2, `${jwkJson.trim()}
686
+ `);
687
+ await chmod(dirname(path2), 448).catch(() => void 0);
404
688
  return path2;
405
689
  }
406
690
  async function readOperatePrivateJwk(appId) {
@@ -413,28 +697,24 @@ async function readOperatePrivateJwk(appId) {
413
697
  }
414
698
  async function writeAppEnvFile(appId, contents) {
415
699
  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);
700
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
701
+ `);
420
702
  return path2;
421
703
  }
422
704
 
423
705
  // src/emit-env.ts
424
706
  async function emitAppEnv(args) {
425
- const pin = args.masterPublicJwkJson?.trim() || process.env.CLAVIS_MASTER_PUBLIC_JWK_JSON?.trim() || "";
707
+ const pin = args.trustRoot?.trim() || process.env.CLAVIS_TRUST_ROOT?.trim() || "";
426
708
  if (!pin) {
427
- throw new Error(
428
- "CLAVIS_MASTER_PUBLIC_JWK_JSON is required. Set it to the master public JWK from GET {apiOrigin}/.well-known/jwks.json."
429
- );
709
+ throw new Error("CLAVIS_TRUST_ROOT is required. Set it to the Clavis Master public JWK (docs.clavis.nexus).");
430
710
  }
431
- const master = await getMasterJwkJson(args.origins.apiOrigin, pin);
711
+ const trustRoot = await checkTrustRoot(args.origins.apiOrigin, pin);
432
712
  const operatePath = await saveOperatePrivateJwk(args.appId, args.operatePrivateJwkJson);
433
713
  const envRecord = {
434
714
  CLAVIS_API_ORIGIN: args.origins.apiOrigin,
435
715
  CLAVIS_APP_ID: args.appId,
436
716
  OPERATE_PRIVATE_JWK: args.operatePrivateJwkJson,
437
- MASTER_PUBLIC_JWK_JSON: master
717
+ CLAVIS_TRUST_ROOT: trustRoot
438
718
  };
439
719
  const envFile = await writeAppEnvFile(args.appId, formatEnvExport(envRecord));
440
720
  return {
@@ -470,30 +750,80 @@ async function generateOperateKeyPair() {
470
750
  privateJwkJson: JSON.stringify(priv)
471
751
  };
472
752
  }
753
+ var SESSION_SLOT = "wauthn-auth-jwt";
754
+ var SLOT_FIELD = /^[a-z][a-z0-9]{1,31}-slot$/;
755
+ var JWK_MEMBERS = ["kty", "crv", "x", "y", "kid", "alg"];
756
+ async function sessionKey(origin, kid) {
757
+ const res = await fetch(`${origin}/.well-known/jwks.json`, { redirect: "error", headers: { Accept: "application/json" } });
758
+ if (!res.ok) throw new Error(`jwks ${res.status}`);
759
+ const doc = await res.json();
760
+ const key = (doc.keys ?? []).find((k) => k && k.kid === kid);
761
+ if (!key) return null;
762
+ const slot = Object.entries(key).find(([name]) => SLOT_FIELD.test(name))?.[1];
763
+ if (slot !== SESSION_SLOT) return null;
764
+ const jwk = {};
765
+ for (const m of JWK_MEMBERS) if (key[m] !== void 0) jwk[m] = key[m];
766
+ return importJWK(jwk, "ES256");
767
+ }
473
768
  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"] });
769
+ const origin = new URL(apiOrigin).origin;
770
+ let refused = false;
771
+ const { payload } = await jwtVerify(
772
+ accessToken,
773
+ async (header) => {
774
+ const key = typeof header.kid === "string" ? await sessionKey(origin, header.kid) : null;
775
+ if (!key) {
776
+ refused = true;
777
+ throw new Error("invalid_access_token_kid");
778
+ }
779
+ return key;
780
+ },
781
+ { algorithms: ["ES256"], issuer: origin, audience: origin, requiredClaims: ["exp", "iss", "aud", "sub"] }
782
+ ).catch((e) => {
783
+ if (refused) throw new Error("invalid_access_token_kid");
784
+ throw e;
785
+ });
786
+ if (payload.tk !== "access") throw new Error("invalid_access_token_kind");
787
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) throw new Error("invalid_access_token_sub");
788
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) throw new Error("invalid_access_token_exp");
789
+ return { sub: payload.sub, expiresAt: payload.exp };
477
790
  }
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
791
  function defaultSessionPath() {
488
792
  const override = process.env.CLAVIS_SESSION_PATH?.trim();
489
793
  if (override) return override;
490
794
  return join(homedir(), ".config", "clavis", "session.json");
491
795
  }
796
+ function isLoopbackHost3(hostname) {
797
+ const host = hostname.toLowerCase();
798
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
799
+ }
800
+ function assertSetupOrigin(raw, name) {
801
+ let url;
802
+ try {
803
+ url = new URL(raw.trim());
804
+ } catch {
805
+ throw new Error(`${name} must be an absolute URL`);
806
+ }
807
+ if (url.username || url.password) throw new Error(`${name} must not contain credentials`);
808
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost3(url.hostname);
809
+ if (url.protocol !== "https:" && !loopbackHttp) throw new Error(`${name} must be https`);
810
+ if (url.pathname !== "/" || url.search || url.hash) throw new Error(`${name} must be an origin`);
811
+ return url.origin;
812
+ }
492
813
  function originsFromEnv(overrides) {
493
814
  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
815
+ apiOrigin: assertSetupOrigin(
816
+ overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
817
+ "apiOrigin"
818
+ ),
819
+ idOrigin: assertSetupOrigin(
820
+ overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
821
+ "idOrigin"
822
+ ),
823
+ developersOrigin: assertSetupOrigin(
824
+ overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin,
825
+ "developersOrigin"
826
+ )
497
827
  };
498
828
  }
499
829
  async function loadSession(path2 = defaultSessionPath()) {
@@ -508,16 +838,8 @@ async function loadSession(path2 = defaultSessionPath()) {
508
838
  }
509
839
  }
510
840
  async function saveSession(session, origins, path2 = defaultSessionPath()) {
511
- await mkdir(dirname(path2), { recursive: true });
512
841
  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
- }
842
+ await writeMode600(path2, JSON.stringify(body, null, 2));
521
843
  }
522
844
  async function clearSession(path2 = defaultSessionPath()) {
523
845
  try {
@@ -528,21 +850,11 @@ async function clearSession(path2 = defaultSessionPath()) {
528
850
 
529
851
  // src/login.ts
530
852
  var MAX_BRIDGE_JSON_CHARS = 16384;
853
+ var PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
531
854
  function pendingLoginPath(sessionPath) {
532
855
  const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
533
856
  return path.join(base, "login-pending.json");
534
857
  }
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
858
  function loginBridgeUrl(developersOrigin, state) {
547
859
  const bridge = new URL("/developers/setup/login", developersOrigin);
548
860
  bridge.searchParams.set("state", state);
@@ -584,12 +896,11 @@ async function sessionFromBridge(args) {
584
896
  if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
585
897
  throw new Error("invalid_bridge_json");
586
898
  }
587
- await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
588
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
899
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
589
900
  return {
590
901
  accessToken: body.accessToken,
591
- ...sub ? { sub } : {},
592
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
902
+ sub: verified.sub,
903
+ expiresAt: verified.expiresAt
593
904
  };
594
905
  }
595
906
  async function readBridgeJsonFromStdin() {
@@ -630,6 +941,14 @@ async function loginWithBrowser(args) {
630
941
  await clearPending(pendingPath);
631
942
  throw new Error("pending_login_origin_mismatch \u2014 run login again");
632
943
  }
944
+ if (!Number.isFinite(pending.createdAt) || Date.now() - pending.createdAt > PENDING_LOGIN_TTL_MS) {
945
+ await clearPending(pendingPath);
946
+ throw new Error("pending_login_expired \u2014 run login again");
947
+ }
948
+ const openUrl2 = assertOriginBrowserUrl(
949
+ loginBridgeUrl(args.origins.developersOrigin, pending.state),
950
+ args.origins.developersOrigin
951
+ );
633
952
  const session2 = await sessionFromBridge({
634
953
  raw: args.bridgeJson,
635
954
  expectedState: pending.state,
@@ -642,12 +961,15 @@ async function loginWithBrowser(args) {
642
961
  human: {
643
962
  needs_human: "login",
644
963
  message: "Session stored.",
645
- open_url: loginBridgeUrl(args.origins.developersOrigin, pending.state)
964
+ open_url: openUrl2
646
965
  }
647
966
  };
648
967
  }
649
968
  const state = randomBytes(16).toString("hex");
650
- const openUrl = loginBridgeUrl(args.origins.developersOrigin, state);
969
+ const openUrl = assertOriginBrowserUrl(
970
+ loginBridgeUrl(args.origins.developersOrigin, state),
971
+ args.origins.developersOrigin
972
+ );
651
973
  await writePending(pendingPath, {
652
974
  v: 1,
653
975
  state,
@@ -657,7 +979,7 @@ async function loginWithBrowser(args) {
657
979
  });
658
980
  if (openFlag) {
659
981
  try {
660
- await openBrowser(assertOriginBrowserUrl(openUrl, args.origins.developersOrigin));
982
+ await openBrowser(openUrl);
661
983
  } catch {
662
984
  }
663
985
  }
@@ -690,12 +1012,18 @@ async function loginWithBrowser(args) {
690
1012
  }
691
1013
 
692
1014
  // src/status.ts
693
- function cardActive(card) {
694
- if (!card) return "unknown";
1015
+ function signatureCard(card) {
695
1016
  const sig = card.capabilities?.signature;
696
- if (!sig) return "inactive";
697
- if (sig.subscribed === true || sig.active === true) return "active";
698
- return "inactive";
1017
+ if (!sig) return { signature_card: "inactive" };
1018
+ if (sig.open === true) return { signature_card: "active" };
1019
+ return {
1020
+ signature_card: "inactive",
1021
+ ...Array.isArray(sig.blockers) && sig.blockers.length > 0 ? { signature_card_blockers: sig.blockers } : {}
1022
+ };
1023
+ }
1024
+ function incorporationOf(card) {
1025
+ const inc = card.incorporation;
1026
+ return inc ? { code: inc.code, terms_current: inc.terms_current === true } : null;
699
1027
  }
700
1028
  async function buildSetupStatus(args) {
701
1029
  if (!args.session) {
@@ -705,7 +1033,9 @@ async function buildSetupStatus(args) {
705
1033
  const detailed = [];
706
1034
  for (const org of orgs) {
707
1035
  let setup_complete = false;
708
- let signature_card = "unknown";
1036
+ let card = {
1037
+ signature_card: "unknown"
1038
+ };
709
1039
  let apps = [];
710
1040
  try {
711
1041
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -713,10 +1043,10 @@ async function buildSetupStatus(args) {
713
1043
  } catch {
714
1044
  }
715
1045
  try {
716
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
717
- signature_card = cardActive(card);
1046
+ const view = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
1047
+ card = { ...signatureCard(view), incorporation: incorporationOf(view) };
718
1048
  } catch {
719
- signature_card = "unknown";
1049
+ card = { signature_card: "unknown" };
720
1050
  }
721
1051
  try {
722
1052
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -724,6 +1054,7 @@ async function buildSetupStatus(args) {
724
1054
  app_id: a.app_id,
725
1055
  host: a.host,
726
1056
  status: a.status,
1057
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
727
1058
  declaration_ok: Boolean(
728
1059
  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
1060
  )
@@ -753,7 +1084,7 @@ async function buildSetupStatus(args) {
753
1084
  primary_domain: org.primary_domain,
754
1085
  org_status: org.org_status,
755
1086
  setup_complete,
756
- signature_card,
1087
+ ...card,
757
1088
  apps
758
1089
  });
759
1090
  }
@@ -785,21 +1116,18 @@ async function runPasskeyCeremony(args) {
785
1116
  apiOrigin: args.origins.apiOrigin,
786
1117
  bearer: args.bearer,
787
1118
  returnTo,
788
- purpose: args.purpose,
789
- messageDigest: args.messageDigest,
790
- displayHint: args.displayHint,
791
- label: args.displayHint
1119
+ statement: args.statement
792
1120
  });
793
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1121
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
794
1122
  if (args.openBrowserFlag) {
795
1123
  try {
796
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1124
+ await openBrowser(ceremony_url);
797
1125
  } catch {
798
1126
  }
799
1127
  }
800
1128
  const human = {
801
1129
  needs_human: "passkey",
802
- message: "Confirm with Passkey in the browser, then return to the terminal/agent.",
1130
+ message: `${args.displayHint ? `${args.displayHint}: c` : "C"}onfirm with Passkey in the browser (${args.statement.type}), then return to the terminal/agent.`,
803
1131
  open_url: ceremony_url
804
1132
  };
805
1133
  return {
@@ -812,7 +1140,7 @@ async function runPasskeyCeremony(args) {
812
1140
  bearer: args.bearer,
813
1141
  ticket
814
1142
  });
815
- return signProofFromCeremonyPayload(payload);
1143
+ return receiptFromCeremonyPayload(payload);
816
1144
  }
817
1145
  };
818
1146
  }
@@ -854,18 +1182,43 @@ function createSetupClient(options = {}) {
854
1182
  const report = await buildSetupStatus({ origins, session });
855
1183
  return { ok: true, data: report };
856
1184
  },
857
- async orgAnchorPlan(domain, name) {
1185
+ async orgAnchorPlan(domain, name, terms = {}) {
1186
+ const checked = checkOrgCreationTerms(terms);
1187
+ if (!checked.ok) return checked;
1188
+ const { incorporation } = checked;
858
1189
  const auth = await requireSession({ origins, sessionPath });
859
1190
  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" };
1191
+ const apiOrigin = auth.data.origins.apiOrigin;
1192
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1193
+ if (closed.includes(incorporation)) return regionClosedRefusal(incorporation);
1194
+ let challenge;
1195
+ try {
1196
+ challenge = await postDnsChallenge(apiOrigin, auth.data.session.accessToken, { domain, incorporation });
1197
+ } catch (e) {
1198
+ const refusal = orgCreationRefusal(e, incorporation);
1199
+ if (refusal) return refusal;
1200
+ throw e;
1201
+ }
1202
+ const domainNorm = domain.trim().toLowerCase();
1203
+ 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)) {
1204
+ return { ok: false, error: "challenge_missing_statement" };
1205
+ }
1206
+ const anchorStatement = orgAnchorPublishStatement({ domain: domainNorm, nonce: challenge.nonce, exp: challenge.exp });
1207
+ if (!sameStatement(anchorStatement, challenge.statement)) return { ok: false, error: "challenge_statement_mismatch" };
1208
+ let wellKnown;
1209
+ try {
1210
+ wellKnown = new URL(challenge.well_known_url);
1211
+ } catch {
1212
+ return { ok: false, error: "challenge_url_rejected" };
1213
+ }
1214
+ const txtHost = typeof challenge.txt_host === "string" ? challenge.txt_host.trim().toLowerCase().replace(/\.$/, "") : "";
1215
+ if (wellKnown.protocol !== "https:" || wellKnown.username || wellKnown.password || wellKnown.hostname.toLowerCase() !== domainNorm || txtHost !== domainNorm && !txtHost.endsWith(`.${domainNorm}`)) {
1216
+ return { ok: false, error: "challenge_url_rejected" };
863
1217
  }
864
1218
  const cer = await runPasskeyCeremony({
865
1219
  origins: auth.data.origins,
866
1220
  bearer: auth.data.session.accessToken,
867
- purpose: "org.anchor.publish",
868
- messageDigest: challenge.digest,
1221
+ statement: anchorStatement,
869
1222
  displayHint: `Publish DNS anchor for ${domain}`,
870
1223
  openBrowserFlag
871
1224
  });
@@ -874,9 +1227,10 @@ function createSetupClient(options = {}) {
874
1227
  data: {
875
1228
  domain: challenge.domain,
876
1229
  ...name ? { name } : {},
1230
+ incorporation,
877
1231
  nonce: challenge.nonce,
878
1232
  exp: challenge.exp,
879
- digest: challenge.digest,
1233
+ statement: anchorStatement,
880
1234
  well_known_url: challenge.well_known_url,
881
1235
  txt_host: challenge.txt_host,
882
1236
  ceremony_url: cer.ceremony_url,
@@ -893,12 +1247,12 @@ function createSetupClient(options = {}) {
893
1247
  bearer: auth.data.session.accessToken,
894
1248
  ticket: args.ticket
895
1249
  });
896
- const signProof = signProofFromCeremonyPayload(payload);
1250
+ const receipt = receiptFromCeremonyPayload(payload);
897
1251
  const body = {
898
1252
  v: 1,
899
1253
  kind: "anchor",
900
1254
  domain: args.domain.trim().toLowerCase(),
901
- sign_proof: signProof,
1255
+ receipt,
902
1256
  nonce: args.nonce,
903
1257
  exp: args.exp,
904
1258
  iat: Math.floor(Date.now() / 1e3)
@@ -915,18 +1269,29 @@ function createSetupClient(options = {}) {
915
1269
  txt_value,
916
1270
  human: {
917
1271
  needs_human: "dns",
918
- message: "Publish the well-known JSON and TXT, then call org_verify_anchor."
1272
+ 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
1273
  }
920
1274
  }
921
1275
  };
922
1276
  },
923
1277
  async orgVerifyAnchor(args) {
1278
+ const checked = checkOrgCreationTerms(args);
1279
+ if (!checked.ok) return checked;
1280
+ const { incorporation } = checked;
924
1281
  const auth = await requireSession({ origins, sessionPath });
925
1282
  if (!auth.ok) return auth;
926
1283
  try {
927
- const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, args);
1284
+ const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, {
1285
+ domain: args.domain,
1286
+ nonce: args.nonce,
1287
+ name: args.name,
1288
+ incorporation,
1289
+ acceptCustomerTerms: args.acceptCustomerTerms
1290
+ });
928
1291
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
929
1292
  } catch (e) {
1293
+ const refusal = orgCreationRefusal(e, incorporation);
1294
+ if (refusal) return refusal;
930
1295
  return {
931
1296
  ok: false,
932
1297
  error: e instanceof Error ? e.message : String(e),
@@ -950,18 +1315,10 @@ function createSetupClient(options = {}) {
950
1315
  if (noop.already_active) return { ok: true, data: noop };
951
1316
  } catch {
952
1317
  }
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
1318
  const cer = await runPasskeyCeremony({
961
1319
  origins: auth.data.origins,
962
1320
  bearer: auth.data.session.accessToken,
963
- purpose: "org.policy.bootstrap",
964
- messageDigest: digest,
1321
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
965
1322
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
966
1323
  openBrowserFlag
967
1324
  });
@@ -974,24 +1331,126 @@ function createSetupClient(options = {}) {
974
1331
  );
975
1332
  return { ok: true, data: out };
976
1333
  },
977
- async cardCheckout(orgId) {
1334
+ async incorporationSet(args) {
1335
+ const checked = checkOrgCreationTerms(args, INCORPORATION_TERMS_HUMAN);
1336
+ if (!checked.ok) return checked;
1337
+ const code = checked.incorporation;
978
1338
  const auth = await requireSession({ origins, sessionPath });
979
1339
  if (!auth.ok) return auth;
980
- const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
1340
+ const sub = auth.data.session.sub;
1341
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1342
+ const apiOrigin = auth.data.origins.apiOrigin;
1343
+ const bearer = auth.data.session.accessToken;
1344
+ const card = await getCard(apiOrigin, bearer, args.orgId);
1345
+ const current = card.incorporation;
1346
+ if (current?.code === code && current.terms_current) {
1347
+ return { ok: true, data: { incorporation: current, unchanged: true } };
1348
+ }
1349
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1350
+ if (closed.includes(code) && current?.code !== code) return declarationRegionClosedRefusal(code);
1351
+ const cer = await runPasskeyCeremony({
1352
+ origins: auth.data.origins,
1353
+ bearer,
1354
+ statement: orgCardIncorporationStatement({
1355
+ org: args.orgId,
1356
+ code,
1357
+ customerTerms: card.acceptance.customer_terms_version,
1358
+ dpa: card.acceptance.dpa_version
1359
+ }),
1360
+ displayHint: `Declare ${code} as the place of incorporation`,
1361
+ openBrowserFlag
1362
+ });
1363
+ const proof = await cer.wait();
1364
+ try {
1365
+ const out = await postCardIncorporation(apiOrigin, bearer, args.orgId, { code, receipt: proof });
1366
+ return { ok: true, data: { incorporation: out.incorporation } };
1367
+ } catch (e) {
1368
+ const refusal = incorporationSetRefusal(e, code);
1369
+ if (refusal) return refusal;
1370
+ throw e;
1371
+ }
1372
+ },
1373
+ async cardCheckout(orgId, opts = {}) {
1374
+ const offer = opts.offer === "bundle" ? "bundle" : "meter";
1375
+ const lang = checkoutLang(opts.lang);
1376
+ const auth = await requireSession({ origins, sessionPath });
1377
+ if (!auth.ok) return auth;
1378
+ const sub = auth.data.session.sub;
1379
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1380
+ const apiOrigin = auth.data.origins.apiOrigin;
1381
+ const bearer = auth.data.session.accessToken;
1382
+ const card = await getCard(apiOrigin, bearer, orgId);
1383
+ if (card.suspended) return { ok: false, error: "org_suspended" };
1384
+ const signature = card.capabilities?.signature;
1385
+ const open = offer === "bundle" ? signature?.bundle_checkout_open : signature?.checkout_open;
1386
+ if (!signature || open !== true) {
1387
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
1388
+ }
1389
+ const blockers = signature.blockers ?? [];
1390
+ const subscribed = offer === "bundle" ? signature.tariff === "bundle" : !blockers.includes("subscription");
1391
+ if (subscribed) {
1392
+ const state = blockers.length > 0 ? ` (${blockers.join(", ")})` : "";
1393
+ return {
1394
+ ok: false,
1395
+ error: `already_subscribed \u2014 the signature card already has this subscription${state}. Manage it on developers.`
1396
+ };
1397
+ }
1398
+ const incorporation = card.incorporation;
1399
+ if (!incorporation) return incorporationNeededRefusal(orgId, false);
1400
+ if (!incorporation.terms_current) return incorporationNeededRefusal(orgId, true);
1401
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1402
+ if (closed.includes(incorporation.code)) return purchaseRegionClosedRefusal(incorporation.code);
1403
+ if (opts.consentBillingData !== true) {
1404
+ return { ok: false, error: "billing_data_consent_required", human: billingConsentHuman(card.acceptance, lang) };
1405
+ }
1406
+ const cer = await runPasskeyCeremony({
1407
+ origins: auth.data.origins,
1408
+ bearer,
1409
+ statement: orgCardCheckoutStatement({
1410
+ org: orgId,
1411
+ capability: "signature",
1412
+ offer,
1413
+ customerTerms: card.acceptance.customer_terms_version,
1414
+ dpa: card.acceptance.dpa_version
1415
+ }),
1416
+ displayHint: offer === "bundle" ? "Subscribe to the signature card (monthly bundle)" : "Subscribe to the signature card",
1417
+ openBrowserFlag
1418
+ });
1419
+ const proof = await cer.wait();
1420
+ let url;
1421
+ try {
1422
+ ({ url } = await postCardCheckout(apiOrigin, bearer, orgId, {
1423
+ capability: "signature",
1424
+ offer,
1425
+ consentBillingData: true,
1426
+ uiLocale: lang,
1427
+ receipt: proof
1428
+ }));
1429
+ } catch (e) {
1430
+ const refusal = checkoutRefusal(e, { orgId, incorporation: incorporation.code });
1431
+ if (refusal) return refusal;
1432
+ throw e;
1433
+ }
1434
+ let checkoutUrl;
1435
+ try {
1436
+ checkoutUrl = assertCardCheckoutBrowserUrl(url);
1437
+ } catch (e) {
1438
+ return { ok: false, error: e instanceof Error ? e.message : "checkout_url_rejected" };
1439
+ }
981
1440
  if (openBrowserFlag) {
982
1441
  try {
983
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1442
+ await openBrowser(checkoutUrl);
984
1443
  } catch {
985
1444
  }
986
1445
  }
987
1446
  return {
988
1447
  ok: true,
989
1448
  data: {
990
- url,
1449
+ url: checkoutUrl,
991
1450
  human: {
992
1451
  needs_human: "payment",
993
1452
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
994
- open_url: url
1453
+ open_url: checkoutUrl
995
1454
  }
996
1455
  }
997
1456
  };
@@ -1008,26 +1467,24 @@ function createSetupClient(options = {}) {
1008
1467
  v: 1,
1009
1468
  host: args.host.trim().toLowerCase(),
1010
1469
  display_name: args.displayName.trim(),
1011
- intent_types: args.intentTypes ?? ["generic.sign"],
1470
+ intent_types: args.intentTypes ?? ["generic_sign"],
1012
1471
  max_ttl_seconds: 300,
1013
1472
  operate_kid: keys.kid,
1014
1473
  operate_public_jwk: keys.publicJwk,
1015
1474
  redirect_paths: paths
1016
1475
  };
1017
- const payload_hash = await computePayloadCommitmentHex(manifest);
1018
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
1476
+ const payload_hash = await orgPayloadDigest(manifest);
1019
1477
  const cer = await runPasskeyCeremony({
1020
1478
  origins: auth.data.origins,
1021
1479
  bearer: auth.data.session.accessToken,
1022
- purpose: "org.app.register",
1023
- messageDigest: digest,
1480
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
1024
1481
  displayHint: `Register App ${manifest.host}`,
1025
1482
  openBrowserFlag
1026
1483
  });
1027
1484
  const proof = await cer.wait();
1028
1485
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
1029
1486
  ...manifest,
1030
- proposer_sign_proof: proof
1487
+ proposer_receipt: proof
1031
1488
  });
1032
1489
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
1033
1490
  return {
@@ -1072,17 +1529,10 @@ function createSetupClient(options = {}) {
1072
1529
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1073
1530
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1074
1531
  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
1532
  const cer = await runPasskeyCeremony({
1082
1533
  origins: auth.data.origins,
1083
1534
  bearer: auth.data.session.accessToken,
1084
- purpose: "org.app.verify_host",
1085
- messageDigest: digest,
1535
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1086
1536
  displayHint: `Verify host ${ch.host}`,
1087
1537
  openBrowserFlag
1088
1538
  });
@@ -1111,21 +1561,11 @@ function createSetupClient(options = {}) {
1111
1561
  async declarationSet(args) {
1112
1562
  const auth = await requireSession({ origins, sessionPath });
1113
1563
  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
1564
  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
1565
  const cer = await runPasskeyCeremony({
1125
1566
  origins: auth.data.origins,
1126
1567
  bearer: auth.data.session.accessToken,
1127
- purpose: "org.app.declaration",
1128
- messageDigest: digest,
1568
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1129
1569
  displayHint: `Declare uses for App ${args.appId}`,
1130
1570
  openBrowserFlag
1131
1571
  });
@@ -1135,10 +1575,47 @@ function createSetupClient(options = {}) {
1135
1575
  auth.data.session.accessToken,
1136
1576
  args.orgId,
1137
1577
  args.appId,
1138
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1578
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1139
1579
  );
1140
1580
  return { ok: true, data: { declaration: out.declaration } };
1141
1581
  },
1582
+ async appRegionsSet(args) {
1583
+ const read = readAppRegionsInput(args.regions);
1584
+ if (!read.ok) return read;
1585
+ const regions = read.regions;
1586
+ const auth = await requireSession({ origins, sessionPath });
1587
+ if (!auth.ok) return auth;
1588
+ const sub = auth.data.session.sub;
1589
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1590
+ const apiOrigin = auth.data.origins.apiOrigin;
1591
+ const bearer = auth.data.session.accessToken;
1592
+ const app = await getApp(apiOrigin, bearer, args.orgId, args.appId);
1593
+ if (app.status === "disabled") return appDisabledRefusal();
1594
+ if (sameAppRegions(app.accepted_regions, regions)) {
1595
+ return { ok: true, data: { accepted_regions: regions, unchanged: true } };
1596
+ }
1597
+ if (regions) {
1598
+ const selectable = await getSelectableAppRegions(apiOrigin).catch(() => null);
1599
+ const closed = selectable ? regions.filter((region) => !selectable.includes(region)) : [];
1600
+ if (closed.length > 0) return regionNotOpenRefusal(closed, selectable);
1601
+ }
1602
+ const cer = await runPasskeyCeremony({
1603
+ origins: auth.data.origins,
1604
+ bearer,
1605
+ statement: orgAppRegionsStatement({ org: args.orgId, app: args.appId, regions }),
1606
+ displayHint: regions ? `Accept new connections to ${app.host} from ${regions.join(", ")} only` : `Accept new connections to ${app.host} from every region Clavis accepts`,
1607
+ openBrowserFlag
1608
+ });
1609
+ const proof = await cer.wait();
1610
+ try {
1611
+ await putAppRegions(apiOrigin, bearer, args.orgId, args.appId, { regions, receipt: proof });
1612
+ return { ok: true, data: { accepted_regions: regions } };
1613
+ } catch (e) {
1614
+ const refusal = appRegionsRefusal(e, regions ?? []);
1615
+ if (refusal) return refusal;
1616
+ throw e;
1617
+ }
1618
+ },
1142
1619
  async emitEnv(args) {
1143
1620
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1144
1621
  if (!jwk) {
@@ -1147,7 +1624,7 @@ function createSetupClient(options = {}) {
1147
1624
  error: "operate_jwk_missing",
1148
1625
  human: {
1149
1626
  needs_human: "login",
1150
- message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
1627
+ message: "Run app-register first so the operate key exists under ~/.config/clavis/apps/"
1151
1628
  }
1152
1629
  };
1153
1630
  }
@@ -1162,6 +1639,6 @@ function createSetupClient(options = {}) {
1162
1639
  return client;
1163
1640
  }
1164
1641
 
1165
- export { DEFAULT_ORIGINS, SetupApiError, clearSession, createSetupClient, defaultSessionPath, formatEnvExport, generateOperateKeyPair, loadSession, originsFromEnv, saveSession };
1642
+ export { APP_REGIONS, DEFAULT_ORIGINS, SetupApiError, clearSession, createSetupClient, defaultSessionPath, formatEnvExport, generateOperateKeyPair, loadSession, originsFromEnv, saveSession };
1166
1643
  //# sourceMappingURL=index.js.map
1167
1644
  //# sourceMappingURL=index.js.map