@clavis.nexus/setup 1.0.1 → 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,44 +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 { 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
- import { createServer } from 'http';
7
+ import { createInterface } from 'readline/promises';
8
+ import { stdin, stdout } from 'process';
8
9
  import { randomBytes } from 'crypto';
9
10
 
10
- // 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
+ }
11
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
+ }
12
260
  async function openBrowser(url) {
261
+ const safe = assertOpenableBrowserUrl(url);
13
262
  if (process.platform === "darwin") {
14
- await execFileAsync("open", [url]);
263
+ await execFileAsync("open", [safe]);
15
264
  return;
16
265
  }
17
266
  if (process.platform === "win32") {
18
- await execFileAsync("cmd", ["/c", "start", "", url]);
267
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
19
268
  return;
20
269
  }
21
- 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;
22
414
  }
23
415
 
24
416
  // src/safe-browser-url.ts
25
- 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) {
26
422
  let u;
27
423
  try {
28
424
  u = new URL(raw.trim());
29
425
  } catch {
30
426
  throw new Error("invalid URL");
31
427
  }
32
- if (u.protocol !== "https:") {
33
- throw new Error("only https URLs may be opened in a browser");
34
- }
35
428
  if (u.username || u.password) {
36
429
  throw new Error("URL must not contain credentials");
37
430
  }
38
431
  return u;
39
432
  }
40
433
  function assertCardCheckoutBrowserUrl(raw) {
41
- 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
+ }
42
438
  const host = u.hostname.toLowerCase();
43
439
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
44
440
  throw new Error("checkout URL host is not allowed");
@@ -46,15 +442,21 @@ function assertCardCheckoutBrowserUrl(raw) {
46
442
  return u.toString();
47
443
  }
48
444
  function assertOriginBrowserUrl(raw, origin) {
49
- const u = parseHttpsUrl(raw);
445
+ const u = parseBrowserUrl(raw);
50
446
  let expected;
51
447
  try {
52
448
  expected = new URL(origin.trim());
53
449
  } catch {
54
450
  throw new Error("invalid expected origin");
55
451
  }
56
- if (expected.protocol !== "https:") {
57
- 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");
58
460
  }
59
461
  if (u.origin !== expected.origin) {
60
462
  throw new Error("URL origin does not match the expected origin");
@@ -69,10 +471,6 @@ function bytesToBase64Url(bytes) {
69
471
  const b64 = Buffer.from(bin, "binary").toString("base64");
70
472
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
71
473
  }
72
- async function sha256Base64Url(text) {
73
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
74
- return bytesToBase64Url(digest);
75
- }
76
474
  async function sha256HexUtf8(s) {
77
475
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
78
476
  let out = "";
@@ -95,312 +493,208 @@ function stableStringify(v) {
95
493
  return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`).join(",")}}`;
96
494
  }
97
495
 
98
- // src/digests.ts
99
- async function computeOrgPolicyBootstrapDigest(input) {
100
- return sha256Base64Url(
101
- canonicalStringify({
102
- org_id: input.org_id.trim(),
103
- primary_domain: input.primary_domain.trim().toLowerCase(),
104
- owner_sub: input.owner_sub.trim()
105
- })
106
- );
107
- }
108
- async function computePayloadCommitmentHex(payload) {
109
- const o = payload && typeof payload === "object" ? { ...payload } : payload;
110
- if (o && typeof o === "object" && !Array.isArray(o)) {
111
- delete o.proposer_sign_proof;
112
- }
113
- return sha256HexUtf8(canonicalStringify(o));
114
- }
115
- async function computeOrgAppRegisterDigest(input) {
116
- return sha256Base64Url(
117
- canonicalStringify({
118
- payload_hash: input.payload_hash.trim().toLowerCase(),
119
- proposer_sub: input.proposer_sub.trim()
120
- })
121
- );
122
- }
123
- async function computeOrgAppVerifyHostDigest(input) {
124
- return sha256Base64Url(
125
- canonicalStringify({
126
- app_id: input.app_id.trim(),
127
- host: input.host.trim().toLowerCase(),
128
- nonce: input.nonce.trim(),
129
- org_id: input.org_id.trim()
130
- })
131
- );
132
- }
133
- async function computeOrgAppDeclarationHash(declaration) {
134
- if (declaration === null) return "cleared";
135
- return sha256Base64Url(
136
- canonicalStringify({
137
- endUsers: declaration.endUsers,
138
- uses: declaration.uses
139
- })
140
- );
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)))}`;
141
500
  }
142
- async function computeOrgAppDeclarationDigest(input) {
143
- return sha256Base64Url(
144
- canonicalStringify({
145
- org_id: input.org_id.trim(),
146
- app_id: input.app_id.trim(),
147
- declaration_hash: input.declaration_hash.trim(),
148
- actor_sub: input.actor_sub.trim()
149
- })
150
- );
501
+ function orgAnchorPublishStatement(input2) {
502
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
151
503
  }
152
- async function hashManifestBody(body) {
153
- return sha256HexUtf8(canonicalStringify(body));
504
+ function orgPolicyBootstrapStatement(input2) {
505
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
154
506
  }
155
- function buildAnchorTxtRecord(args) {
156
- return `v=1;kind=anchor;hash=${args.hash};nonce=${args.nonce};exp=${args.exp}`;
507
+ function orgAppRegisterStatement(input2) {
508
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim().toLowerCase() };
157
509
  }
158
-
159
- // src/ceremony.ts
160
- function signProofFromCeremonyPayload(payload) {
161
- if (payload === null || typeof payload !== "object") {
162
- throw new Error("Passkey confirmation did not return a signature.");
163
- }
164
- const o = payload;
165
- const nested = o.sign_proof;
166
- if (nested !== null && typeof nested === "object") return nested;
167
- if (o.v === 1 && o.intent_type === "generic_sign" && typeof o.intent_id === "string" && o.intent_id.length > 0) {
168
- return o;
169
- }
170
- throw new Error("Passkey confirmation did not return a signature.");
171
- }
172
- async function startCeremony(args) {
173
- const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
174
- method: "POST",
175
- headers: {
176
- Accept: "application/json",
177
- "Content-Type": "application/json",
178
- Authorization: `Bearer ${args.bearer}`
179
- },
180
- body: JSON.stringify({
181
- return_to: args.returnTo,
182
- purpose: args.purpose,
183
- ...args.messageDigest ? { message_digest: args.messageDigest } : {},
184
- ...args.displayHint ? { display_hint: args.displayHint } : {},
185
- ...args.label ? { label: args.label } : {}
186
- })
187
- });
188
- const body = await res.json().catch(() => null);
189
- if (!res.ok || typeof body?.payload?.ticket !== "string") {
190
- throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
191
- }
192
- return { ticket: body.payload.ticket, expires_in: body.payload.expires_in };
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
+ };
193
518
  }
194
- async function pollCeremonyResult(args) {
195
- const timeoutMs = args.timeoutMs ?? 5 * 6e4;
196
- const intervalMs = args.intervalMs ?? 1500;
197
- const deadline = Date.now() + timeoutMs;
198
- let lastError = "Passkey confirmation timed out. Complete it in the browser, then retry.";
199
- while (Date.now() < deadline) {
200
- const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
201
- method: "POST",
202
- headers: {
203
- Accept: "application/json",
204
- "Content-Type": "application/json",
205
- Authorization: `Bearer ${args.bearer}`
206
- },
207
- body: JSON.stringify({ ticket: args.ticket })
208
- });
209
- const body = await res.json().catch(() => null);
210
- if (res.ok && body?.payload !== void 0) {
211
- return body.payload.payload;
212
- }
213
- if (res.status === 404) {
214
- lastError = body?.message ?? "waiting for Passkey";
215
- await sleep(intervalMs);
216
- continue;
217
- }
218
- throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
219
- }
220
- throw new Error(lastError);
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
+ };
221
526
  }
222
- function sleep(ms) {
223
- return new Promise((resolve) => setTimeout(resolve, ms));
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
+ };
224
534
  }
225
- function ceremonyPageUrl(idOrigin, ticket) {
226
- const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
227
- u.searchParams.set("ticket", ticket);
228
- return u.toString();
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
+ };
229
543
  }
230
- function setupCeremonyReturnTo(developersOrigin) {
231
- return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
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
+ };
232
553
  }
233
-
234
- // src/org-api.ts
235
- var SetupApiError = class extends Error {
236
- status;
237
- code;
238
- constructor(status, code, message) {
239
- super(message);
240
- this.name = "SetupApiError";
241
- this.status = status;
242
- this.code = code;
243
- }
244
- };
245
- async function apiJson(apiOrigin, path, opts) {
246
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path}`, {
247
- method: opts.method ?? "GET",
248
- headers: {
249
- Accept: "application/json",
250
- Authorization: `Bearer ${opts.bearer}`,
251
- ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
252
- },
253
- body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
254
- });
255
- const body = await res.json().catch(() => null);
256
- if (!res.ok) {
257
- const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
258
- const message = typeof body?.message === "string" ? body.message : code;
259
- throw new SetupApiError(res.status, code, message);
554
+ function sameStatement(a, b) {
555
+ try {
556
+ return canonicalStringify(a) === canonicalStringify(b);
557
+ } catch {
558
+ return false;
260
559
  }
261
- return body ?? {};
262
- }
263
- async function listOrgs(apiOrigin, bearer) {
264
- const r = await apiJson(apiOrigin, "/orgs", { bearer });
265
- return r.orgs ?? [];
266
- }
267
- async function getOrg(apiOrigin, bearer, orgId) {
268
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
269
- }
270
- async function postDnsChallenge(apiOrigin, bearer, domain, kind = "anchor") {
271
- return apiJson(apiOrigin, "/orgs/dns/challenge", {
272
- method: "POST",
273
- bearer,
274
- body: { domain: domain.trim(), kind }
275
- });
276
- }
277
- async function postVerifyAnchor(apiOrigin, bearer, args) {
278
- return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
279
- method: "POST",
280
- bearer,
281
- body: {
282
- domain: args.domain.trim(),
283
- nonce: args.nonce,
284
- ...args.name ? { name: args.name.trim() } : {}
285
- }
286
- });
287
- }
288
- async function postPolicyBootstrap(apiOrigin, bearer, orgId, signProof) {
289
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
290
- method: "POST",
291
- bearer,
292
- body: signProof ? { sign_proof: signProof } : {}
293
- });
294
560
  }
295
- async function listApps(apiOrigin, bearer, orgId) {
296
- const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
297
- bearer
298
- });
299
- return r.apps ?? [];
300
- }
301
- async function getApp(apiOrigin, bearer, orgId, appId) {
302
- const r = await apiJson(
303
- apiOrigin,
304
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
305
- { bearer }
306
- );
307
- return r.app;
308
- }
309
- async function postAppRegister(apiOrigin, bearer, orgId, payload) {
310
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
311
- method: "POST",
312
- bearer,
313
- body: payload
314
- });
315
- }
316
- async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
317
- return apiJson(
318
- apiOrigin,
319
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
320
- { bearer }
321
- );
561
+ async function computePayloadCommitmentHex(payload) {
562
+ const o = payload && typeof payload === "object" ? { ...payload } : payload;
563
+ if (o && typeof o === "object" && !Array.isArray(o)) {
564
+ delete o.proposer_receipt;
565
+ }
566
+ return sha256HexUtf8(canonicalStringify(o));
322
567
  }
323
- async function postVerifyHost(apiOrigin, bearer, orgId, appId, signProof) {
324
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
325
- method: "POST",
326
- bearer,
327
- body: { sign_proof: signProof }
328
- });
568
+ async function hashManifestBody(body) {
569
+ return sha256HexUtf8(canonicalStringify(body));
329
570
  }
330
- async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
331
- return apiJson(
332
- apiOrigin,
333
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
334
- {
335
- method: "PUT",
336
- bearer,
337
- body: {
338
- endUsers: args.endUsers,
339
- uses: args.uses,
340
- sign_proof: args.signProof
341
- }
342
- }
343
- );
571
+ function buildAnchorTxtRecord(args) {
572
+ return `v=1;kind=anchor;hash=${args.hash};nonce=${args.nonce};exp=${args.exp}`;
344
573
  }
345
- async function getCard(apiOrigin, bearer, orgId) {
346
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
574
+
575
+ // src/ceremony.ts
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.");
579
+ }
580
+ const o = payload;
581
+ if (o.type !== "receipt@1" || o.statement === null || typeof o.statement !== "object") {
582
+ throw new Error("Passkey confirmation did not return a receipt.");
583
+ }
584
+ return o;
347
585
  }
348
- async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signature") {
349
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
586
+ async function startCeremony(args) {
587
+ const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
350
588
  method: "POST",
351
- bearer,
352
- body: { capability }
353
- });
354
- }
355
- async function fetchJwksDocument(apiOrigin) {
356
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
357
- headers: { Accept: "application/json" }
589
+ redirect: "error",
590
+ headers: {
591
+ Accept: "application/json",
592
+ "Content-Type": "application/json",
593
+ Authorization: `Bearer ${args.bearer}`
594
+ },
595
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
358
596
  });
359
- if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
360
- return res.json();
597
+ const body = await res.json().catch(() => null);
598
+ if (!res.ok || typeof body?.payload?.ticket !== "string") {
599
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
600
+ }
601
+ return { ticket: body.payload.ticket, expires_in: body.payload.expires_in };
361
602
  }
362
- function masterJwkJsonFromDocument(jwks) {
363
- const master = jwks.master ?? jwks.keys?.find((k) => k.kid === "master" || k.use === "master" || k.alg === "EdDSA");
364
- if (!master) throw new SetupApiError(404, "MASTER_JWK_MISSING", "master JWK not found in JWKS");
365
- return JSON.stringify(master);
603
+ async function pollCeremonyResult(args) {
604
+ const timeoutMs = args.timeoutMs ?? 5 * 6e4;
605
+ const intervalMs = args.intervalMs ?? 1500;
606
+ const deadline = Date.now() + timeoutMs;
607
+ let lastError = "Passkey confirmation timed out. Complete it in the browser, then retry.";
608
+ while (Date.now() < deadline) {
609
+ const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
610
+ method: "POST",
611
+ redirect: "error",
612
+ headers: {
613
+ Accept: "application/json",
614
+ "Content-Type": "application/json",
615
+ Authorization: `Bearer ${args.bearer}`
616
+ },
617
+ body: JSON.stringify({ ticket: args.ticket })
618
+ });
619
+ const body = await res.json().catch(() => null);
620
+ if (res.ok && body?.payload !== void 0) {
621
+ return body.payload.receipt;
622
+ }
623
+ if (res.status === 404) {
624
+ lastError = body?.message ?? "waiting for Passkey";
625
+ await sleep(intervalMs);
626
+ continue;
627
+ }
628
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
629
+ }
630
+ throw new Error(lastError);
366
631
  }
367
- async function getMasterJwkJson(apiOrigin, masterPinJson) {
368
- const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
369
- const doc = await fetchJwksDocument(apiOrigin);
370
- await verifySignedJwksDocument(doc, masterPinJson);
371
- return masterJwkJsonFromDocument(doc);
632
+ function sleep(ms) {
633
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
372
634
  }
373
- function operatePrivateJwkPath(appId) {
374
- const app = appId.trim();
375
- if (!app) throw new Error("appId required");
376
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
377
- return join(base, app, "operate-private.jwk.json");
635
+ function ceremonyPageUrl(idOrigin, ticket) {
636
+ const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
637
+ u.searchParams.set("ticket", ticket);
638
+ return u.toString();
378
639
  }
379
- function appEnvFilePath(appId) {
380
- const app = appId.trim();
381
- if (!app) throw new Error("appId required");
382
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
383
- return join(base, app, "app.env");
640
+ function setupCeremonyReturnTo(developersOrigin) {
641
+ return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
384
642
  }
385
- async function restrictFileMode(path) {
643
+ async function refuseSymlink(path2) {
386
644
  try {
387
- await chmod(path, 384);
645
+ const st = await lstat(path2);
646
+ if (st.isSymbolicLink()) throw new Error(`refusing to write through a symlink: ${path2}`);
388
647
  } catch (e) {
389
- console.warn(
390
- `clavis: could not set mode 0600 on ${path}: ${e instanceof Error ? e.message : e}`
391
- );
648
+ if (e.code === "ENOENT") return;
649
+ throw e;
392
650
  }
393
651
  }
394
- async function saveOperatePrivateJwk(appId, jwkJson) {
395
- const path = operatePrivateJwkPath(appId);
396
- await mkdir(dirname(path), { recursive: true });
397
- await writeFile(path, jwkJson.trim(), "utf8");
398
- await restrictFileMode(path);
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 });
399
658
  try {
400
- await chmod(dirname(path), 448);
401
- } catch {
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}`);
402
664
  }
403
- return path;
665
+ }
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;
685
+ }
686
+ function operatePrivateJwkPath(appId) {
687
+ return pathInsideKeys(appId, "operate-private.jwk.json");
688
+ }
689
+ function appEnvFilePath(appId) {
690
+ return pathInsideKeys(appId, "app.env");
691
+ }
692
+ async function saveOperatePrivateJwk(appId, jwkJson) {
693
+ const path2 = operatePrivateJwkPath(appId);
694
+ await writeMode600(path2, `${jwkJson.trim()}
695
+ `);
696
+ await chmod(dirname(path2), 448).catch(() => void 0);
697
+ return path2;
404
698
  }
405
699
  async function readOperatePrivateJwk(appId) {
406
700
  try {
@@ -411,12 +705,10 @@ async function readOperatePrivateJwk(appId) {
411
705
  }
412
706
  }
413
707
  async function writeAppEnvFile(appId, contents) {
414
- const path = appEnvFilePath(appId);
415
- await mkdir(dirname(path), { recursive: true });
416
- await writeFile(path, contents.endsWith("\n") ? contents : `${contents}
417
- `, "utf8");
418
- await restrictFileMode(path);
419
- return path;
708
+ const path2 = appEnvFilePath(appId);
709
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
710
+ `);
711
+ return path2;
420
712
  }
421
713
 
422
714
  // src/emit-env.ts
@@ -469,35 +761,64 @@ async function generateOperateKeyPair() {
469
761
  privateJwkJson: JSON.stringify(priv)
470
762
  };
471
763
  }
764
+ var SESSION_SLOT_RE = /^[a-z][a-z0-9]{1,31}-wauthn-auth-jwt(?:-\d{6})?$/;
472
765
  async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
473
- const base = apiOrigin.replace(/\/+$/, "");
474
- const jwks = createRemoteJWKSet(new URL(`${base}/.well-known/jwks.json`));
475
- 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 };
476
780
  }
477
-
478
- // src/types.ts
479
- var DEFAULT_ORIGINS = {
480
- apiOrigin: "https://api.clavis.nexus",
481
- idOrigin: "https://id.clavis.nexus",
482
- developersOrigin: "https://developers.clavis.nexus"
483
- };
484
-
485
- // src/session-store.ts
486
781
  function defaultSessionPath() {
487
782
  const override = process.env.CLAVIS_SESSION_PATH?.trim();
488
783
  if (override) return override;
489
784
  return join(homedir(), ".config", "clavis", "session.json");
490
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
+ }
491
803
  function originsFromEnv(overrides) {
492
804
  return {
493
- apiOrigin: overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
494
- idOrigin: overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
495
- 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
+ )
496
817
  };
497
818
  }
498
- async function loadSession(path = defaultSessionPath()) {
819
+ async function loadSession(path2 = defaultSessionPath()) {
499
820
  try {
500
- const raw = await readFile(path, "utf8");
821
+ const raw = await readFile(path2, "utf8");
501
822
  const parsed = JSON.parse(raw);
502
823
  if (parsed?.v !== 1 || typeof parsed.session?.accessToken !== "string") return null;
503
824
  if (parsed.session.expiresAt && parsed.session.expiresAt * 1e3 < Date.now()) return null;
@@ -506,152 +827,193 @@ async function loadSession(path = defaultSessionPath()) {
506
827
  return null;
507
828
  }
508
829
  }
509
- async function saveSession(session, origins, path = defaultSessionPath()) {
510
- await mkdir(dirname(path), { recursive: true });
830
+ async function saveSession(session, origins, path2 = defaultSessionPath()) {
511
831
  const body = { v: 1, origins, session, savedAt: Date.now() };
512
- await writeFile(path, JSON.stringify(body, null, 2), "utf8");
513
- try {
514
- await chmod(path, 384);
515
- } catch (e) {
516
- console.warn(
517
- `clavis: could not set session file mode 0600 (${path}): ${e instanceof Error ? e.message : e}`
518
- );
519
- }
832
+ await writeMode600(path2, JSON.stringify(body, null, 2));
520
833
  }
521
- async function clearSession(path = defaultSessionPath()) {
834
+ async function clearSession(path2 = defaultSessionPath()) {
522
835
  try {
523
- await unlink(path);
836
+ await unlink(path2);
524
837
  } catch {
525
838
  }
526
839
  }
527
840
 
528
841
  // src/login.ts
529
- var MAX_CALLBACK_BODY_BYTES = 8192;
530
- function readBody(req) {
531
- return new Promise((resolve, reject) => {
532
- const chunks = [];
533
- let total = 0;
534
- req.on("data", (c) => {
535
- const buf = Buffer.isBuffer(c) ? c : Buffer.from(c);
536
- total += buf.length;
537
- if (total > MAX_CALLBACK_BODY_BYTES) {
538
- reject(new Error("callback body too large"));
539
- req.destroy();
540
- return;
541
- }
542
- chunks.push(buf);
543
- });
544
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
545
- req.on("error", reject);
546
- });
547
- }
548
- function cors(res, developersOrigin) {
549
- res.setHeader("Access-Control-Allow-Origin", developersOrigin);
550
- res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
551
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
552
- res.setHeader("Vary", "Origin");
842
+ var MAX_BRIDGE_JSON_CHARS = 16384;
843
+ var PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
844
+ function pendingLoginPath(sessionPath) {
845
+ const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
846
+ return path.join(base, "login-pending.json");
847
+ }
848
+ function loginBridgeUrl(developersOrigin, state) {
849
+ const bridge = new URL("/developers/setup/login", developersOrigin);
850
+ bridge.searchParams.set("state", state);
851
+ return bridge.toString();
852
+ }
853
+ async function writePending(pendingPath, pending) {
854
+ await mkdir(path.dirname(pendingPath), { recursive: true, mode: 448 });
855
+ await writeFile(pendingPath, `${JSON.stringify(pending, null, 2)}
856
+ `, { mode: 384 });
857
+ }
858
+ async function readPending(pendingPath) {
859
+ try {
860
+ const raw = await readFile(pendingPath, "utf8");
861
+ const parsed = JSON.parse(raw);
862
+ if (parsed?.v !== 1 || typeof parsed.state !== "string" || !parsed.state) return null;
863
+ return parsed;
864
+ } catch {
865
+ return null;
866
+ }
553
867
  }
554
- function subFromJwt(accessToken) {
868
+ async function clearPending(pendingPath) {
555
869
  try {
556
- const part = accessToken.split(".")[1];
557
- if (!part) return void 0;
558
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
559
- const payload = JSON.parse(json);
560
- return typeof payload.sub === "string" ? payload.sub : void 0;
870
+ await unlink(pendingPath);
561
871
  } catch {
562
- return void 0;
872
+ }
873
+ }
874
+ function parseBridgePayload(raw) {
875
+ const trimmed = raw.trim();
876
+ if (!trimmed) throw new Error("empty_bridge_json");
877
+ if (trimmed.length > MAX_BRIDGE_JSON_CHARS) throw new Error("bridge_json_too_large");
878
+ const body = JSON.parse(trimmed);
879
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
880
+ throw new Error("bridge_json_not_object");
881
+ }
882
+ return body;
883
+ }
884
+ async function sessionFromBridge(args) {
885
+ const body = parseBridgePayload(args.raw);
886
+ if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
887
+ throw new Error("invalid_bridge_json");
888
+ }
889
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
890
+ return {
891
+ accessToken: body.accessToken,
892
+ sub: verified.sub,
893
+ expiresAt: verified.expiresAt
894
+ };
895
+ }
896
+ async function readBridgeJsonFromStdin() {
897
+ if (!stdin.isTTY) {
898
+ const chunks = [];
899
+ for await (const chunk of stdin) {
900
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
901
+ }
902
+ return Buffer.concat(chunks).toString("utf8");
903
+ }
904
+ const rl = createInterface({ input: stdin, output: stdout });
905
+ try {
906
+ stdout.write(
907
+ "Paste the JSON shown on developers /setup/login, then press Enter.\n(End with a blank line if the paste spans multiple lines.)\n"
908
+ );
909
+ const lines = [];
910
+ for (; ; ) {
911
+ const line = await rl.question("");
912
+ if (line.trim() === "" && lines.length > 0) break;
913
+ lines.push(line);
914
+ const joined = lines.join("\n").trim();
915
+ if (joined.startsWith("{") && joined.endsWith("}")) break;
916
+ }
917
+ return lines.join("\n");
918
+ } finally {
919
+ rl.close();
563
920
  }
564
921
  }
565
922
  async function loginWithBrowser(args) {
566
- const state = randomBytes(16).toString("hex");
567
- const timeoutMs = args.timeoutMs ?? 5 * 6e4;
568
- const session = await new Promise((resolve, reject) => {
569
- const server = createServer(async (req, res) => {
570
- cors(res, args.origins.developersOrigin);
571
- if (req.method === "OPTIONS") {
572
- res.writeHead(204);
573
- res.end();
574
- return;
575
- }
576
- if (req.method !== "POST" || req.url?.split("?")[0] !== "/callback") {
577
- res.writeHead(404);
578
- res.end("not found");
579
- return;
580
- }
581
- try {
582
- const raw = await readBody(req);
583
- const body = JSON.parse(raw);
584
- if (body.state !== state || typeof body.accessToken !== "string" || !body.accessToken) {
585
- res.writeHead(400, { "Content-Type": "application/json" });
586
- res.end(JSON.stringify({ ok: false, error: "invalid_callback" }));
587
- return;
588
- }
589
- try {
590
- await verifyDevelopersAccessToken(body.accessToken, args.origins.apiOrigin);
591
- } catch {
592
- res.writeHead(400, { "Content-Type": "application/json" });
593
- res.end(JSON.stringify({ ok: false, error: "invalid_token" }));
594
- return;
595
- }
596
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
597
- const next = {
598
- accessToken: body.accessToken,
599
- ...sub ? { sub } : {},
600
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
601
- };
602
- res.writeHead(200, { "Content-Type": "application/json" });
603
- res.end(JSON.stringify({ ok: true }));
604
- server.close();
605
- resolve(next);
606
- } catch (e) {
607
- res.writeHead(500, { "Content-Type": "application/json" });
608
- res.end(JSON.stringify({ ok: false }));
609
- server.close();
610
- reject(e);
611
- }
923
+ const pendingPath = pendingLoginPath(args.sessionPath);
924
+ const openFlag = args.open !== false;
925
+ if (args.bridgeJson?.trim()) {
926
+ const pending = await readPending(pendingPath);
927
+ if (!pending) {
928
+ throw new Error("no_pending_login \u2014 run login again to open the browser first");
929
+ }
930
+ if (pending.apiOrigin !== args.origins.apiOrigin || pending.developersOrigin !== args.origins.developersOrigin) {
931
+ await clearPending(pendingPath);
932
+ throw new Error("pending_login_origin_mismatch \u2014 run login again");
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
+ );
942
+ const session2 = await sessionFromBridge({
943
+ raw: args.bridgeJson,
944
+ expectedState: pending.state,
945
+ apiOrigin: args.origins.apiOrigin
612
946
  });
613
- server.listen(0, "127.0.0.1", () => {
614
- const addr = server.address();
615
- if (!addr || typeof addr === "string") {
616
- reject(new Error("failed to bind localhost"));
617
- return;
947
+ await saveSession(session2, args.origins, args.sessionPath);
948
+ await clearPending(pendingPath);
949
+ return {
950
+ session: session2,
951
+ human: {
952
+ needs_human: "login",
953
+ message: "Session stored.",
954
+ open_url: openUrl2
618
955
  }
619
- const bridge = new URL("/developers/setup/login", args.origins.developersOrigin);
620
- bridge.searchParams.set("callback_port", String(addr.port));
621
- bridge.searchParams.set("state", state);
622
- void (async () => {
623
- if (args.open !== false) {
624
- try {
625
- await openBrowser(assertOriginBrowserUrl(bridge.toString(), args.origins.developersOrigin));
626
- } catch {
627
- }
628
- }
629
- })();
630
- });
631
- const timer = setTimeout(() => {
632
- server.close();
633
- reject(new Error("login timeout \u2014 complete Passkey in the browser"));
634
- }, timeoutMs);
635
- server.on("close", () => clearTimeout(timer));
956
+ };
957
+ }
958
+ const state = randomBytes(16).toString("hex");
959
+ const openUrl = assertOriginBrowserUrl(
960
+ loginBridgeUrl(args.origins.developersOrigin, state),
961
+ args.origins.developersOrigin
962
+ );
963
+ await writePending(pendingPath, {
964
+ v: 1,
965
+ state,
966
+ createdAt: Date.now(),
967
+ developersOrigin: args.origins.developersOrigin,
968
+ apiOrigin: args.origins.apiOrigin
969
+ });
970
+ if (openFlag) {
971
+ try {
972
+ await openBrowser(openUrl);
973
+ } catch {
974
+ }
975
+ }
976
+ if (args.deferPaste) {
977
+ return {
978
+ pending: true,
979
+ human: {
980
+ needs_human: "login",
981
+ message: "Complete Passkey in the browser, copy the JSON on the page, then call login again with bridge_json.",
982
+ open_url: openUrl
983
+ }
984
+ };
985
+ }
986
+ const raw = await readBridgeJsonFromStdin();
987
+ const session = await sessionFromBridge({
988
+ raw,
989
+ expectedState: state,
990
+ apiOrigin: args.origins.apiOrigin
636
991
  });
637
- await saveSession(session, args.origins);
992
+ await saveSession(session, args.origins, args.sessionPath);
993
+ await clearPending(pendingPath);
638
994
  return {
639
995
  session,
640
996
  human: {
641
997
  needs_human: "login",
642
- message: "Complete Passkey login in the browser if the window is still open.",
643
- open_url: `${args.origins.developersOrigin}/developers/setup/login`
998
+ message: "Session stored. You can close the browser tab.",
999
+ open_url: openUrl
644
1000
  }
645
1001
  };
646
1002
  }
647
1003
 
648
1004
  // src/status.ts
649
- function cardActive(card) {
650
- if (!card) return "unknown";
1005
+ function signatureCard(card) {
651
1006
  const sig = card.capabilities?.signature;
652
- if (!sig) return "inactive";
653
- if (sig.subscribed === true || sig.active === true) return "active";
654
- 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;
655
1017
  }
656
1018
  async function buildSetupStatus(args) {
657
1019
  if (!args.session) {
@@ -661,7 +1023,9 @@ async function buildSetupStatus(args) {
661
1023
  const detailed = [];
662
1024
  for (const org of orgs) {
663
1025
  let setup_complete = false;
664
- let signature_card = "unknown";
1026
+ let card = {
1027
+ signature_card: "unknown"
1028
+ };
665
1029
  let apps = [];
666
1030
  try {
667
1031
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -669,10 +1033,10 @@ async function buildSetupStatus(args) {
669
1033
  } catch {
670
1034
  }
671
1035
  try {
672
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
673
- 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) };
674
1038
  } catch {
675
- signature_card = "unknown";
1039
+ card = { signature_card: "unknown" };
676
1040
  }
677
1041
  try {
678
1042
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -680,6 +1044,7 @@ async function buildSetupStatus(args) {
680
1044
  app_id: a.app_id,
681
1045
  host: a.host,
682
1046
  status: a.status,
1047
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
683
1048
  declaration_ok: Boolean(
684
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")
685
1050
  )
@@ -709,7 +1074,7 @@ async function buildSetupStatus(args) {
709
1074
  primary_domain: org.primary_domain,
710
1075
  org_status: org.org_status,
711
1076
  setup_complete,
712
- signature_card,
1077
+ ...card,
713
1078
  apps
714
1079
  });
715
1080
  }
@@ -741,21 +1106,18 @@ async function runPasskeyCeremony(args) {
741
1106
  apiOrigin: args.origins.apiOrigin,
742
1107
  bearer: args.bearer,
743
1108
  returnTo,
744
- purpose: args.purpose,
745
- messageDigest: args.messageDigest,
746
- displayHint: args.displayHint,
747
- label: args.displayHint
1109
+ statement: args.statement
748
1110
  });
749
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1111
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
750
1112
  if (args.openBrowserFlag) {
751
1113
  try {
752
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1114
+ await openBrowser(ceremony_url);
753
1115
  } catch {
754
1116
  }
755
1117
  }
756
1118
  const human = {
757
1119
  needs_human: "passkey",
758
- 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.`,
759
1121
  open_url: ceremony_url
760
1122
  };
761
1123
  return {
@@ -768,7 +1130,7 @@ async function runPasskeyCeremony(args) {
768
1130
  bearer: args.bearer,
769
1131
  ticket
770
1132
  });
771
- return signProofFromCeremonyPayload(payload);
1133
+ return receiptFromCeremonyPayload(payload);
772
1134
  }
773
1135
  };
774
1136
  }
@@ -782,9 +1144,24 @@ function createSetupClient(options = {}) {
782
1144
  const s = await loadSession(sessionPath);
783
1145
  return s?.session ?? null;
784
1146
  },
785
- async login() {
786
- const { session } = await loginWithBrowser({ origins, open: openBrowserFlag });
787
- return { ok: true, data: { sub: session.sub } };
1147
+ async login(opts) {
1148
+ const bridgeJson = opts?.bridgeJson?.trim();
1149
+ const deferPaste = !bridgeJson && !process.stdin.isTTY;
1150
+ const out = await loginWithBrowser({
1151
+ origins,
1152
+ open: openBrowserFlag,
1153
+ ...bridgeJson ? { bridgeJson } : {},
1154
+ ...deferPaste ? { deferPaste: true } : {},
1155
+ sessionPath
1156
+ });
1157
+ if (out.pending || !out.session) {
1158
+ return {
1159
+ ok: false,
1160
+ error: "login_pending_paste",
1161
+ human: out.human
1162
+ };
1163
+ }
1164
+ return { ok: true, data: { sub: out.session.sub } };
788
1165
  },
789
1166
  async logout() {
790
1167
  await clearSession(sessionPath);
@@ -795,18 +1172,43 @@ function createSetupClient(options = {}) {
795
1172
  const report = await buildSetupStatus({ origins, session });
796
1173
  return { ok: true, data: report };
797
1174
  },
798
- 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;
799
1179
  const auth = await requireSession({ origins, sessionPath });
800
1180
  if (!auth.ok) return auth;
801
- const challenge = await postDnsChallenge(auth.data.origins.apiOrigin, auth.data.session.accessToken, domain);
802
- if (!challenge.digest) {
803
- 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" };
804
1207
  }
805
1208
  const cer = await runPasskeyCeremony({
806
1209
  origins: auth.data.origins,
807
1210
  bearer: auth.data.session.accessToken,
808
- purpose: "org.anchor.publish",
809
- messageDigest: challenge.digest,
1211
+ statement: anchorStatement,
810
1212
  displayHint: `Publish DNS anchor for ${domain}`,
811
1213
  openBrowserFlag
812
1214
  });
@@ -815,9 +1217,10 @@ function createSetupClient(options = {}) {
815
1217
  data: {
816
1218
  domain: challenge.domain,
817
1219
  ...name ? { name } : {},
1220
+ incorporation,
818
1221
  nonce: challenge.nonce,
819
1222
  exp: challenge.exp,
820
- digest: challenge.digest,
1223
+ statement: anchorStatement,
821
1224
  well_known_url: challenge.well_known_url,
822
1225
  txt_host: challenge.txt_host,
823
1226
  ceremony_url: cer.ceremony_url,
@@ -834,12 +1237,12 @@ function createSetupClient(options = {}) {
834
1237
  bearer: auth.data.session.accessToken,
835
1238
  ticket: args.ticket
836
1239
  });
837
- const signProof = signProofFromCeremonyPayload(payload);
1240
+ const receipt = receiptFromCeremonyPayload(payload);
838
1241
  const body = {
839
1242
  v: 1,
840
1243
  kind: "anchor",
841
1244
  domain: args.domain.trim().toLowerCase(),
842
- sign_proof: signProof,
1245
+ receipt,
843
1246
  nonce: args.nonce,
844
1247
  exp: args.exp,
845
1248
  iat: Math.floor(Date.now() / 1e3)
@@ -856,18 +1259,29 @@ function createSetupClient(options = {}) {
856
1259
  txt_value,
857
1260
  human: {
858
1261
  needs_human: "dns",
859
- 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."
860
1263
  }
861
1264
  }
862
1265
  };
863
1266
  },
864
1267
  async orgVerifyAnchor(args) {
1268
+ const checked = checkOrgCreationTerms(args);
1269
+ if (!checked.ok) return checked;
1270
+ const { incorporation } = checked;
865
1271
  const auth = await requireSession({ origins, sessionPath });
866
1272
  if (!auth.ok) return auth;
867
1273
  try {
868
- 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
+ });
869
1281
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
870
1282
  } catch (e) {
1283
+ const refusal = orgCreationRefusal(e, incorporation);
1284
+ if (refusal) return refusal;
871
1285
  return {
872
1286
  ok: false,
873
1287
  error: e instanceof Error ? e.message : String(e),
@@ -891,18 +1305,10 @@ function createSetupClient(options = {}) {
891
1305
  if (noop.already_active) return { ok: true, data: noop };
892
1306
  } catch {
893
1307
  }
894
- const sub = auth.data.session.sub;
895
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
896
- const digest = await computeOrgPolicyBootstrapDigest({
897
- org_id: orgId,
898
- primary_domain: detail.primary_domain,
899
- owner_sub: sub
900
- });
901
1308
  const cer = await runPasskeyCeremony({
902
1309
  origins: auth.data.origins,
903
1310
  bearer: auth.data.session.accessToken,
904
- purpose: "org.policy.bootstrap",
905
- messageDigest: digest,
1311
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
906
1312
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
907
1313
  openBrowserFlag
908
1314
  });
@@ -915,24 +1321,126 @@ function createSetupClient(options = {}) {
915
1321
  );
916
1322
  return { ok: true, data: out };
917
1323
  },
918
- 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);
919
1366
  const auth = await requireSession({ origins, sessionPath });
920
1367
  if (!auth.ok) return auth;
921
- 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
+ }
922
1430
  if (openBrowserFlag) {
923
1431
  try {
924
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1432
+ await openBrowser(checkoutUrl);
925
1433
  } catch {
926
1434
  }
927
1435
  }
928
1436
  return {
929
1437
  ok: true,
930
1438
  data: {
931
- url,
1439
+ url: checkoutUrl,
932
1440
  human: {
933
1441
  needs_human: "payment",
934
1442
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
935
- open_url: url
1443
+ open_url: checkoutUrl
936
1444
  }
937
1445
  }
938
1446
  };
@@ -949,26 +1457,24 @@ function createSetupClient(options = {}) {
949
1457
  v: 1,
950
1458
  host: args.host.trim().toLowerCase(),
951
1459
  display_name: args.displayName.trim(),
952
- intent_types: args.intentTypes ?? ["generic.sign"],
1460
+ intent_types: args.intentTypes ?? ["generic_sign"],
953
1461
  max_ttl_seconds: 300,
954
1462
  operate_kid: keys.kid,
955
1463
  operate_public_jwk: keys.publicJwk,
956
1464
  redirect_paths: paths
957
1465
  };
958
1466
  const payload_hash = await computePayloadCommitmentHex(manifest);
959
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
960
1467
  const cer = await runPasskeyCeremony({
961
1468
  origins: auth.data.origins,
962
1469
  bearer: auth.data.session.accessToken,
963
- purpose: "org.app.register",
964
- messageDigest: digest,
1470
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
965
1471
  displayHint: `Register App ${manifest.host}`,
966
1472
  openBrowserFlag
967
1473
  });
968
1474
  const proof = await cer.wait();
969
1475
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
970
1476
  ...manifest,
971
- proposer_sign_proof: proof
1477
+ proposer_receipt: proof
972
1478
  });
973
1479
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
974
1480
  return {
@@ -1013,17 +1519,10 @@ function createSetupClient(options = {}) {
1013
1519
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1014
1520
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1015
1521
  if (!nonce) return { ok: false, error: "host_challenge_missing_nonce" };
1016
- const digest = await computeOrgAppVerifyHostDigest({
1017
- org_id: args.orgId,
1018
- app_id: args.appId,
1019
- host: ch.host,
1020
- nonce
1021
- });
1022
1522
  const cer = await runPasskeyCeremony({
1023
1523
  origins: auth.data.origins,
1024
1524
  bearer: auth.data.session.accessToken,
1025
- purpose: "org.app.verify_host",
1026
- messageDigest: digest,
1525
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1027
1526
  displayHint: `Verify host ${ch.host}`,
1028
1527
  openBrowserFlag
1029
1528
  });
@@ -1052,21 +1551,11 @@ function createSetupClient(options = {}) {
1052
1551
  async declarationSet(args) {
1053
1552
  const auth = await requireSession({ origins, sessionPath });
1054
1553
  if (!auth.ok) return auth;
1055
- const sub = auth.data.session.sub;
1056
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1057
1554
  const declaration = { endUsers: args.endUsers, uses: args.uses };
1058
- const declaration_hash = await computeOrgAppDeclarationHash(declaration);
1059
- const digest = await computeOrgAppDeclarationDigest({
1060
- org_id: args.orgId,
1061
- app_id: args.appId,
1062
- declaration_hash,
1063
- actor_sub: sub
1064
- });
1065
1555
  const cer = await runPasskeyCeremony({
1066
1556
  origins: auth.data.origins,
1067
1557
  bearer: auth.data.session.accessToken,
1068
- purpose: "org.app.declaration",
1069
- messageDigest: digest,
1558
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1070
1559
  displayHint: `Declare uses for App ${args.appId}`,
1071
1560
  openBrowserFlag
1072
1561
  });
@@ -1076,10 +1565,47 @@ function createSetupClient(options = {}) {
1076
1565
  auth.data.session.accessToken,
1077
1566
  args.orgId,
1078
1567
  args.appId,
1079
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1568
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1080
1569
  );
1081
1570
  return { ok: true, data: { declaration: out.declaration } };
1082
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
+ },
1083
1609
  async emitEnv(args) {
1084
1610
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1085
1611
  if (!jwk) {
@@ -1088,7 +1614,7 @@ function createSetupClient(options = {}) {
1088
1614
  error: "operate_jwk_missing",
1089
1615
  human: {
1090
1616
  needs_human: "login",
1091
- 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/"
1092
1618
  }
1093
1619
  };
1094
1620
  }
@@ -1103,6 +1629,6 @@ function createSetupClient(options = {}) {
1103
1629
  return client;
1104
1630
  }
1105
1631
 
1106
- 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 };
1107
1633
  //# sourceMappingURL=index.js.map
1108
1634
  //# sourceMappingURL=index.js.map