@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/cli.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFile } from 'child_process';
3
3
  import { promisify } from 'util';
4
- import { readFile, mkdir, writeFile, chmod, unlink } from 'fs/promises';
5
- import path, { dirname, join } from 'path';
4
+ import { readFile, chmod, unlink, mkdir, writeFile, lstat } from 'fs/promises';
5
+ import path, { dirname, join, resolve, relative, isAbsolute } from 'path';
6
6
  import { homedir } from 'os';
7
- import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
7
+ import { generateKeyPair, exportJWK, jwtVerify, importJWK } from 'jose';
8
8
  import { createInterface } from 'readline/promises';
9
9
  import { stdin, stdout } from 'process';
10
10
  import { randomBytes } from 'crypto';
@@ -12,27 +12,292 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
12
12
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
13
13
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
14
14
  import { createRequire } from 'module';
15
- import { pathToFileURL } from 'url';
16
15
 
17
16
  var __defProp = Object.defineProperty;
18
17
  var __getOwnPropNames = Object.getOwnPropertyNames;
19
- var __esm = (fn, res) => function __init() {
20
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
18
+ var __esm = (fn, res, err) => function __init() {
19
+ if (err) throw err[0];
20
+ try {
21
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
22
+ } catch (e) {
23
+ throw err = [e], e;
24
+ }
21
25
  };
22
26
  var __export = (target, all) => {
23
27
  for (var name in all)
24
28
  __defProp(target, name, { get: all[name], enumerable: true });
25
29
  };
30
+
31
+ // src/org-api.ts
32
+ async function apiJson(apiOrigin, path2, opts) {
33
+ const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path2}`, {
34
+ method: opts.method ?? "GET",
35
+ redirect: "error",
36
+ headers: {
37
+ Accept: "application/json",
38
+ ...opts.bearer !== void 0 ? { Authorization: `Bearer ${opts.bearer}` } : {},
39
+ ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
40
+ },
41
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
42
+ });
43
+ const body = await res.json().catch(() => null);
44
+ if (!res.ok) {
45
+ const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
46
+ const message = typeof body?.message === "string" ? body.message : code;
47
+ throw new SetupApiError(res.status, code, message);
48
+ }
49
+ return body ?? {};
50
+ }
51
+ async function listOrgs(apiOrigin, bearer) {
52
+ const r = await apiJson(apiOrigin, "/orgs", { bearer });
53
+ return r.orgs ?? [];
54
+ }
55
+ async function getOrg(apiOrigin, bearer, orgId) {
56
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
57
+ }
58
+ function stringList(value) {
59
+ return Array.isArray(value) ? value.filter((code) => typeof code === "string") : [];
60
+ }
61
+ async function getOrgRegions(apiOrigin) {
62
+ const r = await apiJson(
63
+ apiOrigin,
64
+ "/orgs/regions",
65
+ {}
66
+ );
67
+ return r.payload ?? {};
68
+ }
69
+ async function getClosedIncorporations(apiOrigin) {
70
+ return stringList((await getOrgRegions(apiOrigin)).closed_incorporations);
71
+ }
72
+ async function getSelectableAppRegions(apiOrigin) {
73
+ return stringList((await getOrgRegions(apiOrigin)).app_regions);
74
+ }
75
+ async function postDnsChallenge(apiOrigin, bearer, args) {
76
+ return apiJson(apiOrigin, "/orgs/dns/challenge", {
77
+ method: "POST",
78
+ bearer,
79
+ body: {
80
+ domain: args.domain.trim(),
81
+ kind: args.kind ?? "anchor",
82
+ ...args.incorporation !== void 0 ? { incorporation: args.incorporation } : {}
83
+ }
84
+ });
85
+ }
86
+ async function postVerifyAnchor(apiOrigin, bearer, args) {
87
+ return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
88
+ method: "POST",
89
+ bearer,
90
+ body: {
91
+ domain: args.domain.trim(),
92
+ nonce: args.nonce,
93
+ ...args.name ? { name: args.name.trim() } : {},
94
+ accept_customer_terms: args.acceptCustomerTerms === true,
95
+ ...args.incorporation !== void 0 ? { incorporation: args.incorporation } : {}
96
+ }
97
+ });
98
+ }
99
+ async function postPolicyBootstrap(apiOrigin, bearer, orgId, receipt) {
100
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
101
+ method: "POST",
102
+ bearer,
103
+ body: receipt ? { receipt } : {}
104
+ });
105
+ }
106
+ async function listApps(apiOrigin, bearer, orgId) {
107
+ const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
108
+ bearer
109
+ });
110
+ return r.apps ?? [];
111
+ }
112
+ async function getApp(apiOrigin, bearer, orgId, appId) {
113
+ const r = await apiJson(
114
+ apiOrigin,
115
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
116
+ { bearer }
117
+ );
118
+ return r.app;
119
+ }
120
+ async function postAppRegister(apiOrigin, bearer, orgId, payload) {
121
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
122
+ method: "POST",
123
+ bearer,
124
+ body: payload
125
+ });
126
+ }
127
+ async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
128
+ return apiJson(
129
+ apiOrigin,
130
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
131
+ { bearer }
132
+ );
133
+ }
134
+ async function postVerifyHost(apiOrigin, bearer, orgId, appId, receipt) {
135
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
136
+ method: "POST",
137
+ bearer,
138
+ body: { receipt }
139
+ });
140
+ }
141
+ async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
142
+ return apiJson(
143
+ apiOrigin,
144
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
145
+ {
146
+ method: "PUT",
147
+ bearer,
148
+ body: {
149
+ endUsers: args.endUsers,
150
+ uses: args.uses,
151
+ receipt: args.receipt
152
+ }
153
+ }
154
+ );
155
+ }
156
+ async function putAppRegions(apiOrigin, bearer, orgId, appId, args) {
157
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/regions`, {
158
+ method: "PUT",
159
+ bearer,
160
+ body: { accepted_regions: args.regions, receipt: args.receipt }
161
+ });
162
+ }
163
+ async function getCard(apiOrigin, bearer, orgId) {
164
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
165
+ }
166
+ async function postCardIncorporation(apiOrigin, bearer, orgId, args) {
167
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/incorporation`, {
168
+ method: "POST",
169
+ bearer,
170
+ body: { code: args.code, receipt: args.receipt }
171
+ });
172
+ }
173
+ async function postCardCheckout(apiOrigin, bearer, orgId, args) {
174
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
175
+ method: "POST",
176
+ bearer,
177
+ body: {
178
+ capability: args.capability,
179
+ offer: args.offer,
180
+ consent: { polar_provision: args.consentBillingData },
181
+ ui_locale: args.uiLocale,
182
+ receipt: args.receipt
183
+ }
184
+ });
185
+ }
186
+ async function checkTrustRoot(apiOrigin, trustRootJson) {
187
+ const { createVerifier } = await import('@clavis.nexus/app');
188
+ await createVerifier({ trustRoot: trustRootJson, apiOrigin }).trust();
189
+ return JSON.stringify(JSON.parse(trustRootJson));
190
+ }
191
+ var SetupApiError;
192
+ var init_org_api = __esm({
193
+ "src/org-api.ts"() {
194
+ SetupApiError = class extends Error {
195
+ status;
196
+ code;
197
+ constructor(status, code, message) {
198
+ super(message);
199
+ this.name = "SetupApiError";
200
+ this.status = status;
201
+ this.code = code;
202
+ }
203
+ };
204
+ }
205
+ });
206
+
207
+ // src/app-regions.ts
208
+ function isAppRegion(value) {
209
+ return APP_REGIONS.includes(value);
210
+ }
211
+ function chooseAppRegions(input2) {
212
+ const listed = input2.regions !== void 0;
213
+ if (input2.all === true && listed) {
214
+ return { ok: false, error: `regions_conflict \u2014 pass either regions or all, not both. ${CHOICE_HINT}` };
215
+ }
216
+ if (input2.all === true) return { ok: true, regions: null };
217
+ if (!listed) return { ok: false, error: `regions_required \u2014 ${CHOICE_HINT}` };
218
+ return { ok: true, regions: input2.regions };
219
+ }
220
+ function readAppRegionsInput(raw) {
221
+ if (raw === null) return { ok: true, regions: null };
222
+ const codes = raw.map((code) => code.trim().toUpperCase());
223
+ if (codes.length === 0 || new Set(codes).size !== codes.length || !codes.every(isAppRegion)) {
224
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
225
+ }
226
+ return { ok: true, regions: APP_REGIONS.filter((region) => codes.includes(region)) };
227
+ }
228
+ function sameAppRegions(stored, next) {
229
+ const current = stored ?? null;
230
+ if (current === null || next === null) return current === next;
231
+ return current.length === next.length && current.every((region, i) => region === next[i]);
232
+ }
233
+ function regionNotOpenRefusal(closed, selectable) {
234
+ const open = selectable && selectable.length > 0 ? ` Regions you can choose now: ${selectable.join(", ")}.` : "";
235
+ return {
236
+ ok: false,
237
+ error: `region_not_open \u2014 Clavis is not accepting new connections from ${closed.join(", ")} right now, so an App cannot accept them.${open}`
238
+ };
239
+ }
240
+ function appDisabledRefusal() {
241
+ return { ok: false, error: "app_disabled \u2014 this App is disabled, so its regions cannot be changed." };
242
+ }
243
+ function appRegionsRefusal(e, regions) {
244
+ if (!(e instanceof SetupApiError)) return null;
245
+ switch (e.code) {
246
+ case "REGION_NOT_OPEN":
247
+ return regionNotOpenRefusal(regions, null);
248
+ case "REGIONS_INVALID":
249
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
250
+ case "APP_DISABLED":
251
+ return appDisabledRefusal();
252
+ case "FORBIDDEN":
253
+ return { ok: false, error: "forbidden \u2014 only an owner or admin of the Org can change the App's regions." };
254
+ default:
255
+ return null;
256
+ }
257
+ }
258
+ var APP_REGIONS, CHOICE_HINT;
259
+ var init_app_regions = __esm({
260
+ "src/app-regions.ts"() {
261
+ init_org_api();
262
+ APP_REGIONS = ["JP", "US", "GB", "EEA"];
263
+ CHOICE_HINT = "Pass --regions with one or more of JP, US, GB, EEA (comma-separated), or --all (MCP: regions or all: true).";
264
+ }
265
+ });
266
+ function isLoopbackHost(hostname) {
267
+ const host = hostname.toLowerCase();
268
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
269
+ }
270
+ function assertOpenableBrowserUrl(raw) {
271
+ let url;
272
+ try {
273
+ url = new URL(raw.trim());
274
+ } catch {
275
+ throw new Error("invalid URL");
276
+ }
277
+ if (url.username || url.password) throw new Error("URL must not contain credentials");
278
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost(url.hostname);
279
+ if (url.protocol !== "https:" && !loopbackHttp) {
280
+ throw new Error("only https URLs may be opened in a browser");
281
+ }
282
+ return url.toString();
283
+ }
284
+ function windowsBrowserArgs(raw) {
285
+ const url = assertOpenableBrowserUrl(raw);
286
+ const script = `Start-Process -FilePath '${url.replaceAll("'", "''")}'`;
287
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
288
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
289
+ }
26
290
  async function openBrowser(url) {
291
+ const safe = assertOpenableBrowserUrl(url);
27
292
  if (process.platform === "darwin") {
28
- await execFileAsync("open", [url]);
293
+ await execFileAsync("open", [safe]);
29
294
  return;
30
295
  }
31
296
  if (process.platform === "win32") {
32
- await execFileAsync("cmd", ["/c", "start", "", url]);
297
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
33
298
  return;
34
299
  }
35
- await execFileAsync("xdg-open", [url]);
300
+ await execFileAsync("xdg-open", [safe]);
36
301
  }
37
302
  var execFileAsync;
38
303
  var init_browser = __esm({
@@ -41,24 +306,191 @@ var init_browser = __esm({
41
306
  }
42
307
  });
43
308
 
309
+ // src/types.ts
310
+ var DEFAULT_ORIGINS, LEGAL_ORIGIN;
311
+ var init_types = __esm({
312
+ "src/types.ts"() {
313
+ DEFAULT_ORIGINS = {
314
+ apiOrigin: "https://api.clavis.nexus",
315
+ idOrigin: "https://id.clavis.nexus",
316
+ developersOrigin: "https://developers.clavis.nexus"
317
+ };
318
+ LEGAL_ORIGIN = "https://legal.clavis.nexus";
319
+ }
320
+ });
321
+
322
+ // src/org-creation.ts
323
+ function normalizeIncorporation(raw) {
324
+ return (raw ?? "").trim().toUpperCase();
325
+ }
326
+ function checkOrgCreationTerms(terms, human = TERMS_HUMAN) {
327
+ if (terms.acceptCustomerTerms !== true) {
328
+ return { ok: false, error: "customer_terms_not_accepted", human };
329
+ }
330
+ const incorporation = normalizeIncorporation(terms.incorporation);
331
+ if (!incorporation) {
332
+ return {
333
+ ok: false,
334
+ error: `incorporation_required \u2014 pass --incorporation CODE (MCP: incorporation): ${INCORPORATION_HINT}`
335
+ };
336
+ }
337
+ return { ok: true, incorporation };
338
+ }
339
+ function regionClosedRefusal(incorporation) {
340
+ return {
341
+ ok: false,
342
+ error: `region_closed \u2014 Clavis is not accepting new Orgs incorporated in ${incorporation} right now. GET /orgs/regions lists the closed places.`
343
+ };
344
+ }
345
+ function orgCreationRefusal(e, incorporation) {
346
+ if (!(e instanceof SetupApiError)) return null;
347
+ if (e.status === 403 && e.code === "REGION_CLOSED") return regionClosedRefusal(incorporation);
348
+ if (e.code === "TERMS_REQUIRED") return { ok: false, error: "customer_terms_not_accepted", human: TERMS_HUMAN };
349
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
350
+ return null;
351
+ }
352
+ function incorporationInvalidRefusal(incorporation) {
353
+ return {
354
+ ok: false,
355
+ error: `incorporation_invalid \u2014 ${incorporation || "(empty)"} is not a place of incorporation Clavis accepts. Use ${INCORPORATION_HINT}.`
356
+ };
357
+ }
358
+ var INCORPORATION_HINT, TERMS_LINKS, TERMS_HUMAN, INCORPORATION_TERMS_HUMAN;
359
+ var init_org_creation = __esm({
360
+ "src/org-creation.ts"() {
361
+ init_org_api();
362
+ init_types();
363
+ INCORPORATION_HINT = "JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)";
364
+ TERMS_LINKS = `Customer Terms: ${LEGAL_ORIGIN}/en/customer-terms \u2014 DPA: ${LEGAL_ORIGIN}/en/dpa.`;
365
+ TERMS_HUMAN = {
366
+ needs_human: "terms",
367
+ 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).`
368
+ };
369
+ INCORPORATION_TERMS_HUMAN = {
370
+ needs_human: "terms",
371
+ 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).`
372
+ };
373
+ }
374
+ });
375
+
376
+ // src/card.ts
377
+ function checkoutLang(raw) {
378
+ return raw === "ja" ? "ja" : "en";
379
+ }
380
+ function billingConsentHuman(acceptance, lang) {
381
+ const copy = BILLING_CONSENT[lang];
382
+ return {
383
+ needs_human: "terms",
384
+ message: [
385
+ copy.lead,
386
+ copy.statement,
387
+ copy.info(`${LEGAL_ORIGIN}/${lang}/privacy`),
388
+ copy.versions(acceptance.customer_terms_version, acceptance.dpa_version),
389
+ copy.next
390
+ ].join("\n")
391
+ };
392
+ }
393
+ function incorporationNeededRefusal(orgId, stale) {
394
+ 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.";
395
+ return {
396
+ ok: false,
397
+ error: stale ? "incorporation_stale" : "incorporation_required",
398
+ human: {
399
+ needs_human: "terms",
400
+ message: `${why} Run: clavis incorporation-set ${orgId} --incorporation CODE --accept-customer-terms (MCP: clavis_incorporation_set), after the customer agrees.`
401
+ }
402
+ };
403
+ }
404
+ function purchaseRegionClosedRefusal(incorporation) {
405
+ return {
406
+ ok: false,
407
+ error: `region_closed \u2014 new subscriptions are not accepted right now for Orgs incorporated in ${incorporation}.`
408
+ };
409
+ }
410
+ function declarationRegionClosedRefusal(incorporation) {
411
+ return {
412
+ ok: false,
413
+ error: `region_closed \u2014 ${incorporation} cannot be declared as the place of incorporation right now. GET /orgs/regions lists the closed places.`
414
+ };
415
+ }
416
+ function checkoutRefusal(e, args) {
417
+ if (!(e instanceof SetupApiError)) return null;
418
+ switch (e.code) {
419
+ case "REGION_CLOSED":
420
+ return purchaseRegionClosedRefusal(args.incorporation);
421
+ case "INCORPORATION":
422
+ return incorporationNeededRefusal(args.orgId, e.message === "incorporation_stale");
423
+ case "AGE_INELIGIBLE":
424
+ return { ok: false, error: "age_ineligible \u2014 an organisation contract can be made by someone who is 18 or older." };
425
+ case "AGE_BAND_REQUIRED":
426
+ return {
427
+ ok: false,
428
+ error: "age_band_required \u2014 this account has no age record, so the organisation contract can't continue."
429
+ };
430
+ case "BILLING_SUBJECT":
431
+ return {
432
+ ok: false,
433
+ error: "billing_subject_taken \u2014 this account already pays for another Org. Another owner or admin of this Org can subscribe instead."
434
+ };
435
+ case "CHECKOUT_CLOSED":
436
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
437
+ default:
438
+ return null;
439
+ }
440
+ }
441
+ function incorporationSetRefusal(e, incorporation) {
442
+ if (!(e instanceof SetupApiError)) return null;
443
+ if (e.code === "REGION_CLOSED") return declarationRegionClosedRefusal(incorporation);
444
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
445
+ return null;
446
+ }
447
+ var BILLING_CONSENT;
448
+ var init_card = __esm({
449
+ "src/card.ts"() {
450
+ init_org_api();
451
+ init_org_creation();
452
+ init_types();
453
+ BILLING_CONSENT = {
454
+ en: {
455
+ lead: "Subscribing needs the customer's own consent. Show them the statement below and ask. Do not consent on their behalf.",
456
+ 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.",
457
+ 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.`,
458
+ versions: (terms, dpa) => `This purchase is made under Customer Terms ${terms} and DPA ${dpa}.`,
459
+ next: "If they consent, run again with --consent-billing-data (MCP: consent_billing_data: true)."
460
+ },
461
+ ja: {
462
+ 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",
463
+ 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",
464
+ 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`,
465
+ 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`,
466
+ 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"
467
+ }
468
+ };
469
+ }
470
+ });
471
+
44
472
  // src/safe-browser-url.ts
45
- function parseHttpsUrl(raw) {
473
+ function isLoopbackHost2(hostname) {
474
+ const host = hostname.toLowerCase();
475
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
476
+ }
477
+ function parseBrowserUrl(raw) {
46
478
  let u;
47
479
  try {
48
480
  u = new URL(raw.trim());
49
481
  } catch {
50
482
  throw new Error("invalid URL");
51
483
  }
52
- if (u.protocol !== "https:") {
53
- throw new Error("only https URLs may be opened in a browser");
54
- }
55
484
  if (u.username || u.password) {
56
485
  throw new Error("URL must not contain credentials");
57
486
  }
58
487
  return u;
59
488
  }
60
489
  function assertCardCheckoutBrowserUrl(raw) {
61
- const u = parseHttpsUrl(raw);
490
+ const u = parseBrowserUrl(raw);
491
+ if (u.protocol !== "https:") {
492
+ throw new Error("only https URLs may be opened in a browser");
493
+ }
62
494
  const host = u.hostname.toLowerCase();
63
495
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
64
496
  throw new Error("checkout URL host is not allowed");
@@ -66,15 +498,21 @@ function assertCardCheckoutBrowserUrl(raw) {
66
498
  return u.toString();
67
499
  }
68
500
  function assertOriginBrowserUrl(raw, origin) {
69
- const u = parseHttpsUrl(raw);
501
+ const u = parseBrowserUrl(raw);
70
502
  let expected;
71
503
  try {
72
504
  expected = new URL(origin.trim());
73
505
  } catch {
74
506
  throw new Error("invalid expected origin");
75
507
  }
76
- if (expected.protocol !== "https:") {
77
- throw new Error("expected origin must be https");
508
+ if (expected.username || expected.password) {
509
+ throw new Error("expected origin must not contain credentials");
510
+ }
511
+ const loopback = isLoopbackHost2(expected.hostname);
512
+ const https = expected.protocol === "https:" && u.protocol === "https:";
513
+ const loopbackHttp = loopback && expected.protocol === "http:" && u.protocol === "http:";
514
+ if (!https && !loopbackHttp) {
515
+ throw new Error("only https URLs may be opened in a browser");
78
516
  }
79
517
  if (u.origin !== expected.origin) {
80
518
  throw new Error("URL origin does not match the expected origin");
@@ -93,10 +531,6 @@ function bytesToBase64Url(bytes) {
93
531
  const b64 = Buffer.from(bin, "binary").toString("base64");
94
532
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
95
533
  }
96
- async function sha256Base64Url(text) {
97
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
98
- return bytesToBase64Url(digest);
99
- }
100
534
  async function sha256HexUtf8(s) {
101
535
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
102
536
  let out = "";
@@ -127,59 +561,81 @@ var init_canonical_json = __esm({
127
561
  }
128
562
  });
129
563
 
130
- // src/digests.ts
131
- async function computeOrgPolicyBootstrapDigest(input2) {
132
- return sha256Base64Url(
133
- canonicalStringify({
134
- org_id: input2.org_id.trim(),
135
- primary_domain: input2.primary_domain.trim().toLowerCase(),
136
- owner_sub: input2.owner_sub.trim()
137
- })
138
- );
139
- }
140
- async function computePayloadCommitmentHex(payload) {
141
- const o = payload && typeof payload === "object" ? { ...payload } : payload;
142
- if (o && typeof o === "object" && !Array.isArray(o)) {
143
- delete o.proposer_sign_proof;
564
+ // src/statements.ts
565
+ async function digestOf(value) {
566
+ const bytes = new TextEncoder().encode(canonicalStringify(value));
567
+ return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))}`;
568
+ }
569
+ async function valueDigest(type, value) {
570
+ return digestOf({ type, value });
571
+ }
572
+ async function orgPayloadDigest(payload) {
573
+ let value = payload;
574
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
575
+ const { proposer_receipt: _receipt, ...rest } = payload;
576
+ value = rest;
144
577
  }
145
- return sha256HexUtf8(canonicalStringify(o));
578
+ return valueDigest("org.payload@1", value);
146
579
  }
147
- async function computeOrgAppRegisterDigest(input2) {
148
- return sha256Base64Url(
149
- canonicalStringify({
150
- payload_hash: input2.payload_hash.trim().toLowerCase(),
151
- proposer_sub: input2.proposer_sub.trim()
152
- })
153
- );
580
+ function orgAnchorPublishStatement(input2) {
581
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
154
582
  }
155
- async function computeOrgAppVerifyHostDigest(input2) {
156
- return sha256Base64Url(
157
- canonicalStringify({
158
- app_id: input2.app_id.trim(),
159
- host: input2.host.trim().toLowerCase(),
160
- nonce: input2.nonce.trim(),
161
- org_id: input2.org_id.trim()
162
- })
163
- );
583
+ function orgPolicyBootstrapStatement(input2) {
584
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
164
585
  }
165
- async function computeOrgAppDeclarationHash(declaration) {
166
- if (declaration === null) return "cleared";
167
- return sha256Base64Url(
168
- canonicalStringify({
169
- endUsers: declaration.endUsers,
170
- uses: declaration.uses
171
- })
172
- );
586
+ function orgAppRegisterStatement(input2) {
587
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim() };
173
588
  }
174
- async function computeOrgAppDeclarationDigest(input2) {
175
- return sha256Base64Url(
176
- canonicalStringify({
177
- org_id: input2.org_id.trim(),
178
- app_id: input2.app_id.trim(),
179
- declaration_hash: input2.declaration_hash.trim(),
180
- actor_sub: input2.actor_sub.trim()
181
- })
182
- );
589
+ function orgAppVerifyHostStatement(input2) {
590
+ return {
591
+ type: "org.app.verify_host@1",
592
+ org: input2.org.trim(),
593
+ app: input2.app.trim(),
594
+ host: input2.host.trim().toLowerCase(),
595
+ nonce: input2.nonce.trim()
596
+ };
597
+ }
598
+ async function orgAppDeclarationStatement(input2) {
599
+ return {
600
+ type: "org.app.declaration@1",
601
+ org: input2.org.trim(),
602
+ app: input2.app.trim(),
603
+ declaration: input2.declaration === null ? null : await valueDigest("app.declaration@1", { endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
604
+ };
605
+ }
606
+ function orgAppRegionsStatement(input2) {
607
+ return {
608
+ type: "org.app.regions@1",
609
+ org: input2.org.trim(),
610
+ app: input2.app.trim(),
611
+ regions: input2.regions === null ? null : [...new Set(input2.regions)].sort()
612
+ };
613
+ }
614
+ function orgCardIncorporationStatement(input2) {
615
+ return {
616
+ type: "org.card.incorporation_set@1",
617
+ org: input2.org.trim(),
618
+ code: input2.code.trim(),
619
+ customer_terms: input2.customerTerms.trim(),
620
+ dpa: input2.dpa.trim()
621
+ };
622
+ }
623
+ function orgCardCheckoutStatement(input2) {
624
+ return {
625
+ type: "org.card.checkout@1",
626
+ org: input2.org.trim(),
627
+ capability: input2.capability.trim(),
628
+ offer: input2.offer,
629
+ customer_terms: input2.customerTerms.trim(),
630
+ dpa: input2.dpa.trim()
631
+ };
632
+ }
633
+ function sameStatement(a, b) {
634
+ try {
635
+ return canonicalStringify(a) === canonicalStringify(b);
636
+ } catch {
637
+ return false;
638
+ }
183
639
  }
184
640
  async function hashManifestBody(body) {
185
641
  return sha256HexUtf8(canonicalStringify(body));
@@ -187,41 +643,30 @@ async function hashManifestBody(body) {
187
643
  function buildAnchorTxtRecord(args) {
188
644
  return `v=1;kind=anchor;hash=${args.hash};nonce=${args.nonce};exp=${args.exp}`;
189
645
  }
190
- var init_digests = __esm({
191
- "src/digests.ts"() {
646
+ var init_statements = __esm({
647
+ "src/statements.ts"() {
192
648
  init_base64url();
193
649
  init_canonical_json();
194
650
  }
195
651
  });
196
652
 
197
653
  // src/ceremony.ts
198
- function signProofFromCeremonyPayload(payload) {
199
- if (payload === null || typeof payload !== "object") {
200
- throw new Error("Passkey confirmation did not return a signature.");
201
- }
202
- const o = payload;
203
- const nested = o.sign_proof;
204
- if (nested !== null && typeof nested === "object") return nested;
205
- if (o.v === 1 && o.intent_type === "generic_sign" && typeof o.intent_id === "string" && o.intent_id.length > 0) {
206
- return o;
654
+ function receiptFromCeremonyPayload(payload) {
655
+ if (typeof payload !== "string" || payload.length === 0) {
656
+ throw new Error("Passkey confirmation did not return a receipt.");
207
657
  }
208
- throw new Error("Passkey confirmation did not return a signature.");
658
+ return payload;
209
659
  }
210
660
  async function startCeremony(args) {
211
661
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
212
662
  method: "POST",
663
+ redirect: "error",
213
664
  headers: {
214
665
  Accept: "application/json",
215
666
  "Content-Type": "application/json",
216
667
  Authorization: `Bearer ${args.bearer}`
217
668
  },
218
- body: JSON.stringify({
219
- return_to: args.returnTo,
220
- purpose: args.purpose,
221
- ...args.messageDigest ? { message_digest: args.messageDigest } : {},
222
- ...args.displayHint ? { display_hint: args.displayHint } : {},
223
- ...args.label ? { label: args.label } : {}
224
- })
669
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
225
670
  });
226
671
  const body = await res.json().catch(() => null);
227
672
  if (!res.ok || typeof body?.payload?.ticket !== "string") {
@@ -237,216 +682,97 @@ async function pollCeremonyResult(args) {
237
682
  while (Date.now() < deadline) {
238
683
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
239
684
  method: "POST",
685
+ redirect: "error",
240
686
  headers: {
241
- Accept: "application/json",
242
- "Content-Type": "application/json",
243
- Authorization: `Bearer ${args.bearer}`
244
- },
245
- body: JSON.stringify({ ticket: args.ticket })
246
- });
247
- const body = await res.json().catch(() => null);
248
- if (res.ok && body?.payload !== void 0) {
249
- return body.payload.payload;
250
- }
251
- if (res.status === 404) {
252
- lastError = body?.message ?? "waiting for Passkey";
253
- await sleep(intervalMs);
254
- continue;
255
- }
256
- throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
257
- }
258
- throw new Error(lastError);
259
- }
260
- function sleep(ms) {
261
- return new Promise((resolve) => setTimeout(resolve, ms));
262
- }
263
- function ceremonyPageUrl(idOrigin, ticket) {
264
- const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
265
- u.searchParams.set("ticket", ticket);
266
- return u.toString();
267
- }
268
- function setupCeremonyReturnTo(developersOrigin) {
269
- return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
270
- }
271
- var init_ceremony = __esm({
272
- "src/ceremony.ts"() {
273
- }
274
- });
275
-
276
- // src/org-api.ts
277
- async function apiJson(apiOrigin, path2, opts) {
278
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path2}`, {
279
- method: opts.method ?? "GET",
280
- headers: {
281
- Accept: "application/json",
282
- Authorization: `Bearer ${opts.bearer}`,
283
- ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
284
- },
285
- body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
286
- });
287
- const body = await res.json().catch(() => null);
288
- if (!res.ok) {
289
- const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
290
- const message = typeof body?.message === "string" ? body.message : code;
291
- throw new SetupApiError(res.status, code, message);
292
- }
293
- return body ?? {};
294
- }
295
- async function listOrgs(apiOrigin, bearer) {
296
- const r = await apiJson(apiOrigin, "/orgs", { bearer });
297
- return r.orgs ?? [];
298
- }
299
- async function getOrg(apiOrigin, bearer, orgId) {
300
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
301
- }
302
- async function postDnsChallenge(apiOrigin, bearer, domain, kind = "anchor") {
303
- return apiJson(apiOrigin, "/orgs/dns/challenge", {
304
- method: "POST",
305
- bearer,
306
- body: { domain: domain.trim(), kind }
307
- });
308
- }
309
- async function postVerifyAnchor(apiOrigin, bearer, args) {
310
- return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
311
- method: "POST",
312
- bearer,
313
- body: {
314
- domain: args.domain.trim(),
315
- nonce: args.nonce,
316
- ...args.name ? { name: args.name.trim() } : {}
317
- }
318
- });
319
- }
320
- async function postPolicyBootstrap(apiOrigin, bearer, orgId, signProof) {
321
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
322
- method: "POST",
323
- bearer,
324
- body: signProof ? { sign_proof: signProof } : {}
325
- });
326
- }
327
- async function listApps(apiOrigin, bearer, orgId) {
328
- const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
329
- bearer
330
- });
331
- return r.apps ?? [];
332
- }
333
- async function getApp(apiOrigin, bearer, orgId, appId) {
334
- const r = await apiJson(
335
- apiOrigin,
336
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
337
- { bearer }
338
- );
339
- return r.app;
340
- }
341
- async function postAppRegister(apiOrigin, bearer, orgId, payload) {
342
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
343
- method: "POST",
344
- bearer,
345
- body: payload
346
- });
347
- }
348
- async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
349
- return apiJson(
350
- apiOrigin,
351
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
352
- { bearer }
353
- );
354
- }
355
- async function postVerifyHost(apiOrigin, bearer, orgId, appId, signProof) {
356
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
357
- method: "POST",
358
- bearer,
359
- body: { sign_proof: signProof }
360
- });
361
- }
362
- async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
363
- return apiJson(
364
- apiOrigin,
365
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
366
- {
367
- method: "PUT",
368
- bearer,
369
- body: {
370
- endUsers: args.endUsers,
371
- uses: args.uses,
372
- sign_proof: args.signProof
373
- }
687
+ Accept: "application/json",
688
+ "Content-Type": "application/json",
689
+ Authorization: `Bearer ${args.bearer}`
690
+ },
691
+ body: JSON.stringify({ ticket: args.ticket })
692
+ });
693
+ const body = await res.json().catch(() => null);
694
+ if (res.ok && body?.payload !== void 0) {
695
+ return body.payload.receipt;
374
696
  }
375
- );
376
- }
377
- async function getCard(apiOrigin, bearer, orgId) {
378
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
379
- }
380
- async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signature") {
381
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
382
- method: "POST",
383
- bearer,
384
- body: { capability }
385
- });
697
+ if (res.status === 404) {
698
+ lastError = body?.message ?? "waiting for Passkey";
699
+ await sleep(intervalMs);
700
+ continue;
701
+ }
702
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
703
+ }
704
+ throw new Error(lastError);
386
705
  }
387
- async function fetchJwksDocument(apiOrigin) {
388
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
389
- headers: { Accept: "application/json" }
390
- });
391
- if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
392
- return res.json();
706
+ function sleep(ms) {
707
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
393
708
  }
394
- function masterJwkJsonFromDocument(jwks) {
395
- const master = jwks.master ?? jwks.keys?.find((k) => k.kid === "master" || k.use === "master" || k.alg === "EdDSA");
396
- if (!master) throw new SetupApiError(404, "MASTER_JWK_MISSING", "master JWK not found in JWKS");
397
- return JSON.stringify(master);
709
+ function ceremonyPageUrl(idOrigin, ticket) {
710
+ const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
711
+ u.searchParams.set("ticket", ticket);
712
+ return u.toString();
398
713
  }
399
- async function getMasterJwkJson(apiOrigin, masterPinJson) {
400
- const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
401
- const doc = await fetchJwksDocument(apiOrigin);
402
- await verifySignedJwksDocument(doc, masterPinJson);
403
- return masterJwkJsonFromDocument(doc);
714
+ function setupCeremonyReturnTo(developersOrigin) {
715
+ return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
404
716
  }
405
- var SetupApiError;
406
- var init_org_api = __esm({
407
- "src/org-api.ts"() {
408
- SetupApiError = class extends Error {
409
- status;
410
- code;
411
- constructor(status, code, message) {
412
- super(message);
413
- this.name = "SetupApiError";
414
- this.status = status;
415
- this.code = code;
416
- }
417
- };
717
+ var init_ceremony = __esm({
718
+ "src/ceremony.ts"() {
418
719
  }
419
720
  });
420
- function operatePrivateJwkPath(appId) {
421
- const app = appId.trim();
422
- if (!app) throw new Error("appId required");
423
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
424
- return join(base, app, "operate-private.jwk.json");
425
- }
426
- function appEnvFilePath(appId) {
427
- const app = appId.trim();
428
- if (!app) throw new Error("appId required");
429
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
430
- return join(base, app, "app.env");
721
+ async function refuseSymlink(path2) {
722
+ try {
723
+ const st = await lstat(path2);
724
+ if (st.isSymbolicLink()) throw new Error(`refusing to write through a symlink: ${path2}`);
725
+ } catch (e) {
726
+ if (e.code === "ENOENT") return;
727
+ throw e;
728
+ }
431
729
  }
432
- async function restrictFileMode(path2) {
730
+ async function writeMode600(path2, contents) {
731
+ const dir = dirname(path2);
732
+ await mkdir(dir, { recursive: true, mode: 448 });
733
+ await refuseSymlink(dir);
734
+ await refuseSymlink(path2);
735
+ await writeFile(path2, contents, { encoding: "utf8", mode: 384 });
433
736
  try {
434
737
  await chmod(path2, 384);
435
738
  } catch (e) {
436
- console.warn(
437
- `clavis: could not set mode 0600 on ${path2}: ${e instanceof Error ? e.message : e}`
438
- );
739
+ await unlink(path2).catch(() => void 0);
740
+ const message = e instanceof Error ? e.message : String(e);
741
+ throw new Error(`could not set mode 0600 on ${path2}: ${message}`);
742
+ }
743
+ }
744
+ var init_private_file = __esm({
745
+ "src/private-file.ts"() {
439
746
  }
747
+ });
748
+ function assertOperateAppId(appId) {
749
+ const app = appId.trim().toLowerCase();
750
+ if (!APP_ID_RE.test(app)) throw new Error("invalid_app_id");
751
+ return app;
752
+ }
753
+ function keysBase() {
754
+ const override = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim();
755
+ return resolve(override || join(homedir(), ".config", "clavis", "apps"));
756
+ }
757
+ function pathInsideKeys(appId, file) {
758
+ const app = assertOperateAppId(appId);
759
+ const base = keysBase();
760
+ const path2 = resolve(base, app, file);
761
+ const rel = relative(base, path2);
762
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("invalid_app_id");
763
+ return path2;
764
+ }
765
+ function operatePrivateJwkPath(appId) {
766
+ return pathInsideKeys(appId, "operate-private.jwk.json");
767
+ }
768
+ function appEnvFilePath(appId) {
769
+ return pathInsideKeys(appId, "app.env");
440
770
  }
441
771
  async function saveOperatePrivateJwk(appId, jwkJson) {
442
772
  const path2 = operatePrivateJwkPath(appId);
443
- await mkdir(dirname(path2), { recursive: true });
444
- await writeFile(path2, jwkJson.trim(), "utf8");
445
- await restrictFileMode(path2);
446
- try {
447
- await chmod(dirname(path2), 448);
448
- } catch {
449
- }
773
+ await writeMode600(path2, `${jwkJson.trim()}
774
+ `);
775
+ await chmod(dirname(path2), 448).catch(() => void 0);
450
776
  return path2;
451
777
  }
452
778
  async function readOperatePrivateJwk(appId) {
@@ -459,32 +785,31 @@ async function readOperatePrivateJwk(appId) {
459
785
  }
460
786
  async function writeAppEnvFile(appId, contents) {
461
787
  const path2 = appEnvFilePath(appId);
462
- await mkdir(dirname(path2), { recursive: true });
463
- await writeFile(path2, contents.endsWith("\n") ? contents : `${contents}
464
- `, "utf8");
465
- await restrictFileMode(path2);
788
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
789
+ `);
466
790
  return path2;
467
791
  }
792
+ var APP_ID_RE;
468
793
  var init_operate_key_store = __esm({
469
794
  "src/operate-key-store.ts"() {
795
+ init_private_file();
796
+ 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})$/;
470
797
  }
471
798
  });
472
799
 
473
800
  // src/emit-env.ts
474
801
  async function emitAppEnv(args) {
475
- const pin = args.masterPublicJwkJson?.trim() || process.env.CLAVIS_MASTER_PUBLIC_JWK_JSON?.trim() || "";
802
+ const pin = args.trustRoot?.trim() || process.env.CLAVIS_TRUST_ROOT?.trim() || "";
476
803
  if (!pin) {
477
- throw new Error(
478
- "CLAVIS_MASTER_PUBLIC_JWK_JSON is required. Set it to the master public JWK from GET {apiOrigin}/.well-known/jwks.json."
479
- );
804
+ throw new Error("CLAVIS_TRUST_ROOT is required. Set it to the Clavis Master public JWK (docs.clavis.nexus).");
480
805
  }
481
- const master = await getMasterJwkJson(args.origins.apiOrigin, pin);
806
+ const trustRoot = await checkTrustRoot(args.origins.apiOrigin, pin);
482
807
  const operatePath = await saveOperatePrivateJwk(args.appId, args.operatePrivateJwkJson);
483
808
  const envRecord = {
484
809
  CLAVIS_API_ORIGIN: args.origins.apiOrigin,
485
810
  CLAVIS_APP_ID: args.appId,
486
811
  OPERATE_PRIVATE_JWK: args.operatePrivateJwkJson,
487
- MASTER_PUBLIC_JWK_JSON: master
812
+ CLAVIS_TRUST_ROOT: trustRoot
488
813
  };
489
814
  const envFile = await writeAppEnvFile(args.appId, formatEnvExport(envRecord));
490
815
  return {
@@ -530,25 +855,47 @@ var init_keys = __esm({
530
855
  "src/keys.ts"() {
531
856
  }
532
857
  });
858
+ async function sessionKey(origin, kid) {
859
+ const res = await fetch(`${origin}/.well-known/jwks.json`, { redirect: "error", headers: { Accept: "application/json" } });
860
+ if (!res.ok) throw new Error(`jwks ${res.status}`);
861
+ const doc = await res.json();
862
+ const key = (doc.keys ?? []).find((k) => k && k.kid === kid);
863
+ if (!key) return null;
864
+ const slot = Object.entries(key).find(([name]) => SLOT_FIELD.test(name))?.[1];
865
+ if (slot !== SESSION_SLOT) return null;
866
+ const jwk = {};
867
+ for (const m of JWK_MEMBERS) if (key[m] !== void 0) jwk[m] = key[m];
868
+ return importJWK(jwk, "ES256");
869
+ }
533
870
  async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
534
- const base = apiOrigin.replace(/\/+$/, "");
535
- const jwks = createRemoteJWKSet(new URL(`${base}/.well-known/jwks.json`));
536
- await jwtVerify(accessToken, jwks, { algorithms: ["ES256"] });
871
+ const origin = new URL(apiOrigin).origin;
872
+ let refused = false;
873
+ const { payload } = await jwtVerify(
874
+ accessToken,
875
+ async (header) => {
876
+ const key = typeof header.kid === "string" ? await sessionKey(origin, header.kid) : null;
877
+ if (!key) {
878
+ refused = true;
879
+ throw new Error("invalid_access_token_kid");
880
+ }
881
+ return key;
882
+ },
883
+ { algorithms: ["ES256"], issuer: origin, audience: origin, requiredClaims: ["exp", "iss", "aud", "sub"] }
884
+ ).catch((e) => {
885
+ if (refused) throw new Error("invalid_access_token_kid");
886
+ throw e;
887
+ });
888
+ if (payload.tk !== "access") throw new Error("invalid_access_token_kind");
889
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) throw new Error("invalid_access_token_sub");
890
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) throw new Error("invalid_access_token_exp");
891
+ return { sub: payload.sub, expiresAt: payload.exp };
537
892
  }
893
+ var SESSION_SLOT, SLOT_FIELD, JWK_MEMBERS;
538
894
  var init_access_token_verify = __esm({
539
895
  "src/access-token-verify.ts"() {
540
- }
541
- });
542
-
543
- // src/types.ts
544
- var DEFAULT_ORIGINS;
545
- var init_types = __esm({
546
- "src/types.ts"() {
547
- DEFAULT_ORIGINS = {
548
- apiOrigin: "https://api.clavis.nexus",
549
- idOrigin: "https://id.clavis.nexus",
550
- developersOrigin: "https://developers.clavis.nexus"
551
- };
896
+ SESSION_SLOT = "wauthn-auth-jwt";
897
+ SLOT_FIELD = /^[a-z][a-z0-9]{1,31}-slot$/;
898
+ JWK_MEMBERS = ["kty", "crv", "x", "y", "kid", "alg"];
552
899
  }
553
900
  });
554
901
  function defaultSessionPath() {
@@ -556,11 +903,37 @@ function defaultSessionPath() {
556
903
  if (override) return override;
557
904
  return join(homedir(), ".config", "clavis", "session.json");
558
905
  }
906
+ function isLoopbackHost3(hostname) {
907
+ const host = hostname.toLowerCase();
908
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
909
+ }
910
+ function assertSetupOrigin(raw, name) {
911
+ let url;
912
+ try {
913
+ url = new URL(raw.trim());
914
+ } catch {
915
+ throw new Error(`${name} must be an absolute URL`);
916
+ }
917
+ if (url.username || url.password) throw new Error(`${name} must not contain credentials`);
918
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost3(url.hostname);
919
+ if (url.protocol !== "https:" && !loopbackHttp) throw new Error(`${name} must be https`);
920
+ if (url.pathname !== "/" || url.search || url.hash) throw new Error(`${name} must be an origin`);
921
+ return url.origin;
922
+ }
559
923
  function originsFromEnv(overrides) {
560
924
  return {
561
- apiOrigin: overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
562
- idOrigin: overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
563
- developersOrigin: overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin
925
+ apiOrigin: assertSetupOrigin(
926
+ overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
927
+ "apiOrigin"
928
+ ),
929
+ idOrigin: assertSetupOrigin(
930
+ overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
931
+ "idOrigin"
932
+ ),
933
+ developersOrigin: assertSetupOrigin(
934
+ overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin,
935
+ "developersOrigin"
936
+ )
564
937
  };
565
938
  }
566
939
  async function loadSession(path2 = defaultSessionPath()) {
@@ -575,16 +948,8 @@ async function loadSession(path2 = defaultSessionPath()) {
575
948
  }
576
949
  }
577
950
  async function saveSession(session, origins, path2 = defaultSessionPath()) {
578
- await mkdir(dirname(path2), { recursive: true });
579
951
  const body = { v: 1, origins, session, savedAt: Date.now() };
580
- await writeFile(path2, JSON.stringify(body, null, 2), "utf8");
581
- try {
582
- await chmod(path2, 384);
583
- } catch (e) {
584
- console.warn(
585
- `clavis: could not set session file mode 0600 (${path2}): ${e instanceof Error ? e.message : e}`
586
- );
587
- }
952
+ await writeMode600(path2, JSON.stringify(body, null, 2));
588
953
  }
589
954
  async function clearSession(path2 = defaultSessionPath()) {
590
955
  try {
@@ -594,6 +959,7 @@ async function clearSession(path2 = defaultSessionPath()) {
594
959
  }
595
960
  var init_session_store = __esm({
596
961
  "src/session-store.ts"() {
962
+ init_private_file();
597
963
  init_types();
598
964
  }
599
965
  });
@@ -601,17 +967,6 @@ function pendingLoginPath(sessionPath) {
601
967
  const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
602
968
  return path.join(base, "login-pending.json");
603
969
  }
604
- function subFromJwt(accessToken) {
605
- try {
606
- const part = accessToken.split(".")[1];
607
- if (!part) return void 0;
608
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
609
- const payload = JSON.parse(json);
610
- return typeof payload.sub === "string" ? payload.sub : void 0;
611
- } catch {
612
- return void 0;
613
- }
614
- }
615
970
  function loginBridgeUrl(developersOrigin, state) {
616
971
  const bridge = new URL("/developers/setup/login", developersOrigin);
617
972
  bridge.searchParams.set("state", state);
@@ -653,12 +1008,11 @@ async function sessionFromBridge(args) {
653
1008
  if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
654
1009
  throw new Error("invalid_bridge_json");
655
1010
  }
656
- await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
657
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
1011
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
658
1012
  return {
659
1013
  accessToken: body.accessToken,
660
- ...sub ? { sub } : {},
661
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
1014
+ sub: verified.sub,
1015
+ expiresAt: verified.expiresAt
662
1016
  };
663
1017
  }
664
1018
  async function readBridgeJsonFromStdin() {
@@ -699,6 +1053,14 @@ async function loginWithBrowser(args) {
699
1053
  await clearPending(pendingPath);
700
1054
  throw new Error("pending_login_origin_mismatch \u2014 run login again");
701
1055
  }
1056
+ if (!Number.isFinite(pending.createdAt) || Date.now() - pending.createdAt > PENDING_LOGIN_TTL_MS) {
1057
+ await clearPending(pendingPath);
1058
+ throw new Error("pending_login_expired \u2014 run login again");
1059
+ }
1060
+ const openUrl2 = assertOriginBrowserUrl(
1061
+ loginBridgeUrl(args.origins.developersOrigin, pending.state),
1062
+ args.origins.developersOrigin
1063
+ );
702
1064
  const session2 = await sessionFromBridge({
703
1065
  raw: args.bridgeJson,
704
1066
  expectedState: pending.state,
@@ -711,12 +1073,15 @@ async function loginWithBrowser(args) {
711
1073
  human: {
712
1074
  needs_human: "login",
713
1075
  message: "Session stored.",
714
- open_url: loginBridgeUrl(args.origins.developersOrigin, pending.state)
1076
+ open_url: openUrl2
715
1077
  }
716
1078
  };
717
1079
  }
718
1080
  const state = randomBytes(16).toString("hex");
719
- const openUrl = loginBridgeUrl(args.origins.developersOrigin, state);
1081
+ const openUrl = assertOriginBrowserUrl(
1082
+ loginBridgeUrl(args.origins.developersOrigin, state),
1083
+ args.origins.developersOrigin
1084
+ );
720
1085
  await writePending(pendingPath, {
721
1086
  v: 1,
722
1087
  state,
@@ -726,7 +1091,7 @@ async function loginWithBrowser(args) {
726
1091
  });
727
1092
  if (openFlag) {
728
1093
  try {
729
- await openBrowser(assertOriginBrowserUrl(openUrl, args.origins.developersOrigin));
1094
+ await openBrowser(openUrl);
730
1095
  } catch {
731
1096
  }
732
1097
  }
@@ -757,7 +1122,7 @@ async function loginWithBrowser(args) {
757
1122
  }
758
1123
  };
759
1124
  }
760
- var MAX_BRIDGE_JSON_CHARS;
1125
+ var MAX_BRIDGE_JSON_CHARS, PENDING_LOGIN_TTL_MS;
761
1126
  var init_login = __esm({
762
1127
  "src/login.ts"() {
763
1128
  init_browser();
@@ -765,16 +1130,23 @@ var init_login = __esm({
765
1130
  init_access_token_verify();
766
1131
  init_session_store();
767
1132
  MAX_BRIDGE_JSON_CHARS = 16384;
1133
+ PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
768
1134
  }
769
1135
  });
770
1136
 
771
1137
  // src/status.ts
772
- function cardActive(card) {
773
- if (!card) return "unknown";
1138
+ function signatureCard(card) {
774
1139
  const sig = card.capabilities?.signature;
775
- if (!sig) return "inactive";
776
- if (sig.subscribed === true || sig.active === true) return "active";
777
- return "inactive";
1140
+ if (!sig) return { signature_card: "inactive" };
1141
+ if (sig.open === true) return { signature_card: "active" };
1142
+ return {
1143
+ signature_card: "inactive",
1144
+ ...Array.isArray(sig.blockers) && sig.blockers.length > 0 ? { signature_card_blockers: sig.blockers } : {}
1145
+ };
1146
+ }
1147
+ function incorporationOf(card) {
1148
+ const inc = card.incorporation;
1149
+ return inc ? { code: inc.code, terms_current: inc.terms_current === true } : null;
778
1150
  }
779
1151
  async function buildSetupStatus(args) {
780
1152
  if (!args.session) {
@@ -784,7 +1156,9 @@ async function buildSetupStatus(args) {
784
1156
  const detailed = [];
785
1157
  for (const org of orgs) {
786
1158
  let setup_complete = false;
787
- let signature_card = "unknown";
1159
+ let card = {
1160
+ signature_card: "unknown"
1161
+ };
788
1162
  let apps = [];
789
1163
  try {
790
1164
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -792,10 +1166,10 @@ async function buildSetupStatus(args) {
792
1166
  } catch {
793
1167
  }
794
1168
  try {
795
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
796
- signature_card = cardActive(card);
1169
+ const view = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
1170
+ card = { ...signatureCard(view), incorporation: incorporationOf(view) };
797
1171
  } catch {
798
- signature_card = "unknown";
1172
+ card = { signature_card: "unknown" };
799
1173
  }
800
1174
  try {
801
1175
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -803,6 +1177,7 @@ async function buildSetupStatus(args) {
803
1177
  app_id: a.app_id,
804
1178
  host: a.host,
805
1179
  status: a.status,
1180
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
806
1181
  declaration_ok: Boolean(
807
1182
  a.declaration && typeof a.declaration.endUsers === "string" && a.declaration.endUsers.trim() && Array.isArray(a.declaration.uses) && a.declaration.uses.some((u) => u.capability === "signature")
808
1183
  )
@@ -832,7 +1207,7 @@ async function buildSetupStatus(args) {
832
1207
  primary_domain: org.primary_domain,
833
1208
  org_status: org.org_status,
834
1209
  setup_complete,
835
- signature_card,
1210
+ ...card,
836
1211
  apps
837
1212
  });
838
1213
  }
@@ -869,21 +1244,18 @@ async function runPasskeyCeremony(args) {
869
1244
  apiOrigin: args.origins.apiOrigin,
870
1245
  bearer: args.bearer,
871
1246
  returnTo,
872
- purpose: args.purpose,
873
- messageDigest: args.messageDigest,
874
- displayHint: args.displayHint,
875
- label: args.displayHint
1247
+ statement: args.statement
876
1248
  });
877
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1249
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
878
1250
  if (args.openBrowserFlag) {
879
1251
  try {
880
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1252
+ await openBrowser(ceremony_url);
881
1253
  } catch {
882
1254
  }
883
1255
  }
884
1256
  const human = {
885
1257
  needs_human: "passkey",
886
- message: "Confirm with Passkey in the browser, then return to the terminal/agent.",
1258
+ message: `${args.displayHint ? `${args.displayHint}: c` : "C"}onfirm with Passkey in the browser (${args.statement.type}), then return to the terminal/agent.`,
887
1259
  open_url: ceremony_url
888
1260
  };
889
1261
  return {
@@ -896,7 +1268,7 @@ async function runPasskeyCeremony(args) {
896
1268
  bearer: args.bearer,
897
1269
  ticket
898
1270
  });
899
- return signProofFromCeremonyPayload(payload);
1271
+ return receiptFromCeremonyPayload(payload);
900
1272
  }
901
1273
  };
902
1274
  }
@@ -938,18 +1310,43 @@ function createSetupClient(options = {}) {
938
1310
  const report = await buildSetupStatus({ origins, session });
939
1311
  return { ok: true, data: report };
940
1312
  },
941
- async orgAnchorPlan(domain, name) {
1313
+ async orgAnchorPlan(domain, name, terms = {}) {
1314
+ const checked = checkOrgCreationTerms(terms);
1315
+ if (!checked.ok) return checked;
1316
+ const { incorporation } = checked;
942
1317
  const auth = await requireSession({ origins, sessionPath });
943
1318
  if (!auth.ok) return auth;
944
- const challenge = await postDnsChallenge(auth.data.origins.apiOrigin, auth.data.session.accessToken, domain);
945
- if (!challenge.digest) {
946
- return { ok: false, error: "challenge_missing_digest" };
1319
+ const apiOrigin = auth.data.origins.apiOrigin;
1320
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1321
+ if (closed.includes(incorporation)) return regionClosedRefusal(incorporation);
1322
+ let challenge;
1323
+ try {
1324
+ challenge = await postDnsChallenge(apiOrigin, auth.data.session.accessToken, { domain, incorporation });
1325
+ } catch (e) {
1326
+ const refusal = orgCreationRefusal(e, incorporation);
1327
+ if (refusal) return refusal;
1328
+ throw e;
1329
+ }
1330
+ const domainNorm = domain.trim().toLowerCase();
1331
+ 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)) {
1332
+ return { ok: false, error: "challenge_missing_statement" };
1333
+ }
1334
+ const anchorStatement = orgAnchorPublishStatement({ domain: domainNorm, nonce: challenge.nonce, exp: challenge.exp });
1335
+ if (!sameStatement(anchorStatement, challenge.statement)) return { ok: false, error: "challenge_statement_mismatch" };
1336
+ let wellKnown;
1337
+ try {
1338
+ wellKnown = new URL(challenge.well_known_url);
1339
+ } catch {
1340
+ return { ok: false, error: "challenge_url_rejected" };
1341
+ }
1342
+ const txtHost = typeof challenge.txt_host === "string" ? challenge.txt_host.trim().toLowerCase().replace(/\.$/, "") : "";
1343
+ if (wellKnown.protocol !== "https:" || wellKnown.username || wellKnown.password || wellKnown.hostname.toLowerCase() !== domainNorm || txtHost !== domainNorm && !txtHost.endsWith(`.${domainNorm}`)) {
1344
+ return { ok: false, error: "challenge_url_rejected" };
947
1345
  }
948
1346
  const cer = await runPasskeyCeremony({
949
1347
  origins: auth.data.origins,
950
1348
  bearer: auth.data.session.accessToken,
951
- purpose: "org.anchor.publish",
952
- messageDigest: challenge.digest,
1349
+ statement: anchorStatement,
953
1350
  displayHint: `Publish DNS anchor for ${domain}`,
954
1351
  openBrowserFlag
955
1352
  });
@@ -958,9 +1355,10 @@ function createSetupClient(options = {}) {
958
1355
  data: {
959
1356
  domain: challenge.domain,
960
1357
  ...name ? { name } : {},
1358
+ incorporation,
961
1359
  nonce: challenge.nonce,
962
1360
  exp: challenge.exp,
963
- digest: challenge.digest,
1361
+ statement: anchorStatement,
964
1362
  well_known_url: challenge.well_known_url,
965
1363
  txt_host: challenge.txt_host,
966
1364
  ceremony_url: cer.ceremony_url,
@@ -977,12 +1375,12 @@ function createSetupClient(options = {}) {
977
1375
  bearer: auth.data.session.accessToken,
978
1376
  ticket: args.ticket
979
1377
  });
980
- const signProof = signProofFromCeremonyPayload(payload);
1378
+ const receipt = receiptFromCeremonyPayload(payload);
981
1379
  const body = {
982
1380
  v: 1,
983
1381
  kind: "anchor",
984
1382
  domain: args.domain.trim().toLowerCase(),
985
- sign_proof: signProof,
1383
+ receipt,
986
1384
  nonce: args.nonce,
987
1385
  exp: args.exp,
988
1386
  iat: Math.floor(Date.now() / 1e3)
@@ -999,18 +1397,29 @@ function createSetupClient(options = {}) {
999
1397
  txt_value,
1000
1398
  human: {
1001
1399
  needs_human: "dns",
1002
- message: "Publish the well-known JSON and TXT, then call org_verify_anchor."
1400
+ 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."
1003
1401
  }
1004
1402
  }
1005
1403
  };
1006
1404
  },
1007
1405
  async orgVerifyAnchor(args) {
1406
+ const checked = checkOrgCreationTerms(args);
1407
+ if (!checked.ok) return checked;
1408
+ const { incorporation } = checked;
1008
1409
  const auth = await requireSession({ origins, sessionPath });
1009
1410
  if (!auth.ok) return auth;
1010
1411
  try {
1011
- const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, args);
1412
+ const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, {
1413
+ domain: args.domain,
1414
+ nonce: args.nonce,
1415
+ name: args.name,
1416
+ incorporation,
1417
+ acceptCustomerTerms: args.acceptCustomerTerms
1418
+ });
1012
1419
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
1013
1420
  } catch (e) {
1421
+ const refusal = orgCreationRefusal(e, incorporation);
1422
+ if (refusal) return refusal;
1014
1423
  return {
1015
1424
  ok: false,
1016
1425
  error: e instanceof Error ? e.message : String(e),
@@ -1034,18 +1443,10 @@ function createSetupClient(options = {}) {
1034
1443
  if (noop.already_active) return { ok: true, data: noop };
1035
1444
  } catch {
1036
1445
  }
1037
- const sub = auth.data.session.sub;
1038
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1039
- const digest = await computeOrgPolicyBootstrapDigest({
1040
- org_id: orgId,
1041
- primary_domain: detail.primary_domain,
1042
- owner_sub: sub
1043
- });
1044
1446
  const cer = await runPasskeyCeremony({
1045
1447
  origins: auth.data.origins,
1046
1448
  bearer: auth.data.session.accessToken,
1047
- purpose: "org.policy.bootstrap",
1048
- messageDigest: digest,
1449
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
1049
1450
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
1050
1451
  openBrowserFlag
1051
1452
  });
@@ -1058,24 +1459,126 @@ function createSetupClient(options = {}) {
1058
1459
  );
1059
1460
  return { ok: true, data: out };
1060
1461
  },
1061
- async cardCheckout(orgId) {
1462
+ async incorporationSet(args) {
1463
+ const checked = checkOrgCreationTerms(args, INCORPORATION_TERMS_HUMAN);
1464
+ if (!checked.ok) return checked;
1465
+ const code = checked.incorporation;
1466
+ const auth = await requireSession({ origins, sessionPath });
1467
+ if (!auth.ok) return auth;
1468
+ const sub = auth.data.session.sub;
1469
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1470
+ const apiOrigin = auth.data.origins.apiOrigin;
1471
+ const bearer = auth.data.session.accessToken;
1472
+ const card = await getCard(apiOrigin, bearer, args.orgId);
1473
+ const current = card.incorporation;
1474
+ if (current?.code === code && current.terms_current) {
1475
+ return { ok: true, data: { incorporation: current, unchanged: true } };
1476
+ }
1477
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1478
+ if (closed.includes(code) && current?.code !== code) return declarationRegionClosedRefusal(code);
1479
+ const cer = await runPasskeyCeremony({
1480
+ origins: auth.data.origins,
1481
+ bearer,
1482
+ statement: orgCardIncorporationStatement({
1483
+ org: args.orgId,
1484
+ code,
1485
+ customerTerms: card.acceptance.customer_terms_version,
1486
+ dpa: card.acceptance.dpa_version
1487
+ }),
1488
+ displayHint: `Declare ${code} as the place of incorporation`,
1489
+ openBrowserFlag
1490
+ });
1491
+ const proof = await cer.wait();
1492
+ try {
1493
+ const out = await postCardIncorporation(apiOrigin, bearer, args.orgId, { code, receipt: proof });
1494
+ return { ok: true, data: { incorporation: out.incorporation } };
1495
+ } catch (e) {
1496
+ const refusal = incorporationSetRefusal(e, code);
1497
+ if (refusal) return refusal;
1498
+ throw e;
1499
+ }
1500
+ },
1501
+ async cardCheckout(orgId, opts = {}) {
1502
+ const offer = opts.offer === "bundle" ? "bundle" : "meter";
1503
+ const lang = checkoutLang(opts.lang);
1062
1504
  const auth = await requireSession({ origins, sessionPath });
1063
1505
  if (!auth.ok) return auth;
1064
- const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
1506
+ const sub = auth.data.session.sub;
1507
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1508
+ const apiOrigin = auth.data.origins.apiOrigin;
1509
+ const bearer = auth.data.session.accessToken;
1510
+ const card = await getCard(apiOrigin, bearer, orgId);
1511
+ if (card.suspended) return { ok: false, error: "org_suspended" };
1512
+ const signature = card.capabilities?.signature;
1513
+ const open = offer === "bundle" ? signature?.bundle_checkout_open : signature?.checkout_open;
1514
+ if (!signature || open !== true) {
1515
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
1516
+ }
1517
+ const blockers = signature.blockers ?? [];
1518
+ const subscribed = offer === "bundle" ? signature.tariff === "bundle" : !blockers.includes("subscription");
1519
+ if (subscribed) {
1520
+ const state = blockers.length > 0 ? ` (${blockers.join(", ")})` : "";
1521
+ return {
1522
+ ok: false,
1523
+ error: `already_subscribed \u2014 the signature card already has this subscription${state}. Manage it on developers.`
1524
+ };
1525
+ }
1526
+ const incorporation = card.incorporation;
1527
+ if (!incorporation) return incorporationNeededRefusal(orgId, false);
1528
+ if (!incorporation.terms_current) return incorporationNeededRefusal(orgId, true);
1529
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1530
+ if (closed.includes(incorporation.code)) return purchaseRegionClosedRefusal(incorporation.code);
1531
+ if (opts.consentBillingData !== true) {
1532
+ return { ok: false, error: "billing_data_consent_required", human: billingConsentHuman(card.acceptance, lang) };
1533
+ }
1534
+ const cer = await runPasskeyCeremony({
1535
+ origins: auth.data.origins,
1536
+ bearer,
1537
+ statement: orgCardCheckoutStatement({
1538
+ org: orgId,
1539
+ capability: "signature",
1540
+ offer,
1541
+ customerTerms: card.acceptance.customer_terms_version,
1542
+ dpa: card.acceptance.dpa_version
1543
+ }),
1544
+ displayHint: offer === "bundle" ? "Subscribe to the signature card (monthly bundle)" : "Subscribe to the signature card",
1545
+ openBrowserFlag
1546
+ });
1547
+ const proof = await cer.wait();
1548
+ let url;
1549
+ try {
1550
+ ({ url } = await postCardCheckout(apiOrigin, bearer, orgId, {
1551
+ capability: "signature",
1552
+ offer,
1553
+ consentBillingData: true,
1554
+ uiLocale: lang,
1555
+ receipt: proof
1556
+ }));
1557
+ } catch (e) {
1558
+ const refusal = checkoutRefusal(e, { orgId, incorporation: incorporation.code });
1559
+ if (refusal) return refusal;
1560
+ throw e;
1561
+ }
1562
+ let checkoutUrl;
1563
+ try {
1564
+ checkoutUrl = assertCardCheckoutBrowserUrl(url);
1565
+ } catch (e) {
1566
+ return { ok: false, error: e instanceof Error ? e.message : "checkout_url_rejected" };
1567
+ }
1065
1568
  if (openBrowserFlag) {
1066
1569
  try {
1067
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1570
+ await openBrowser(checkoutUrl);
1068
1571
  } catch {
1069
1572
  }
1070
1573
  }
1071
1574
  return {
1072
1575
  ok: true,
1073
1576
  data: {
1074
- url,
1577
+ url: checkoutUrl,
1075
1578
  human: {
1076
1579
  needs_human: "payment",
1077
1580
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
1078
- open_url: url
1581
+ open_url: checkoutUrl
1079
1582
  }
1080
1583
  }
1081
1584
  };
@@ -1092,26 +1595,24 @@ function createSetupClient(options = {}) {
1092
1595
  v: 1,
1093
1596
  host: args.host.trim().toLowerCase(),
1094
1597
  display_name: args.displayName.trim(),
1095
- intent_types: args.intentTypes ?? ["generic.sign"],
1598
+ intent_types: args.intentTypes ?? ["generic_sign"],
1096
1599
  max_ttl_seconds: 300,
1097
1600
  operate_kid: keys.kid,
1098
1601
  operate_public_jwk: keys.publicJwk,
1099
1602
  redirect_paths: paths
1100
1603
  };
1101
- const payload_hash = await computePayloadCommitmentHex(manifest);
1102
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
1604
+ const payload_hash = await orgPayloadDigest(manifest);
1103
1605
  const cer = await runPasskeyCeremony({
1104
1606
  origins: auth.data.origins,
1105
1607
  bearer: auth.data.session.accessToken,
1106
- purpose: "org.app.register",
1107
- messageDigest: digest,
1608
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
1108
1609
  displayHint: `Register App ${manifest.host}`,
1109
1610
  openBrowserFlag
1110
1611
  });
1111
1612
  const proof = await cer.wait();
1112
1613
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
1113
1614
  ...manifest,
1114
- proposer_sign_proof: proof
1615
+ proposer_receipt: proof
1115
1616
  });
1116
1617
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
1117
1618
  return {
@@ -1156,17 +1657,10 @@ function createSetupClient(options = {}) {
1156
1657
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1157
1658
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1158
1659
  if (!nonce) return { ok: false, error: "host_challenge_missing_nonce" };
1159
- const digest = await computeOrgAppVerifyHostDigest({
1160
- org_id: args.orgId,
1161
- app_id: args.appId,
1162
- host: ch.host,
1163
- nonce
1164
- });
1165
1660
  const cer = await runPasskeyCeremony({
1166
1661
  origins: auth.data.origins,
1167
1662
  bearer: auth.data.session.accessToken,
1168
- purpose: "org.app.verify_host",
1169
- messageDigest: digest,
1663
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1170
1664
  displayHint: `Verify host ${ch.host}`,
1171
1665
  openBrowserFlag
1172
1666
  });
@@ -1195,21 +1689,11 @@ function createSetupClient(options = {}) {
1195
1689
  async declarationSet(args) {
1196
1690
  const auth = await requireSession({ origins, sessionPath });
1197
1691
  if (!auth.ok) return auth;
1198
- const sub = auth.data.session.sub;
1199
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1200
1692
  const declaration = { endUsers: args.endUsers, uses: args.uses };
1201
- const declaration_hash = await computeOrgAppDeclarationHash(declaration);
1202
- const digest = await computeOrgAppDeclarationDigest({
1203
- org_id: args.orgId,
1204
- app_id: args.appId,
1205
- declaration_hash,
1206
- actor_sub: sub
1207
- });
1208
1693
  const cer = await runPasskeyCeremony({
1209
1694
  origins: auth.data.origins,
1210
1695
  bearer: auth.data.session.accessToken,
1211
- purpose: "org.app.declaration",
1212
- messageDigest: digest,
1696
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1213
1697
  displayHint: `Declare uses for App ${args.appId}`,
1214
1698
  openBrowserFlag
1215
1699
  });
@@ -1219,10 +1703,47 @@ function createSetupClient(options = {}) {
1219
1703
  auth.data.session.accessToken,
1220
1704
  args.orgId,
1221
1705
  args.appId,
1222
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1706
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1223
1707
  );
1224
1708
  return { ok: true, data: { declaration: out.declaration } };
1225
1709
  },
1710
+ async appRegionsSet(args) {
1711
+ const read = readAppRegionsInput(args.regions);
1712
+ if (!read.ok) return read;
1713
+ const regions = read.regions;
1714
+ const auth = await requireSession({ origins, sessionPath });
1715
+ if (!auth.ok) return auth;
1716
+ const sub = auth.data.session.sub;
1717
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1718
+ const apiOrigin = auth.data.origins.apiOrigin;
1719
+ const bearer = auth.data.session.accessToken;
1720
+ const app = await getApp(apiOrigin, bearer, args.orgId, args.appId);
1721
+ if (app.status === "disabled") return appDisabledRefusal();
1722
+ if (sameAppRegions(app.accepted_regions, regions)) {
1723
+ return { ok: true, data: { accepted_regions: regions, unchanged: true } };
1724
+ }
1725
+ if (regions) {
1726
+ const selectable = await getSelectableAppRegions(apiOrigin).catch(() => null);
1727
+ const closed = selectable ? regions.filter((region) => !selectable.includes(region)) : [];
1728
+ if (closed.length > 0) return regionNotOpenRefusal(closed, selectable);
1729
+ }
1730
+ const cer = await runPasskeyCeremony({
1731
+ origins: auth.data.origins,
1732
+ bearer,
1733
+ statement: orgAppRegionsStatement({ org: args.orgId, app: args.appId, regions }),
1734
+ displayHint: regions ? `Accept new connections to ${app.host} from ${regions.join(", ")} only` : `Accept new connections to ${app.host} from every region Clavis accepts`,
1735
+ openBrowserFlag
1736
+ });
1737
+ const proof = await cer.wait();
1738
+ try {
1739
+ await putAppRegions(apiOrigin, bearer, args.orgId, args.appId, { regions, receipt: proof });
1740
+ return { ok: true, data: { accepted_regions: regions } };
1741
+ } catch (e) {
1742
+ const refusal = appRegionsRefusal(e, regions ?? []);
1743
+ if (refusal) return refusal;
1744
+ throw e;
1745
+ }
1746
+ },
1226
1747
  async emitEnv(args) {
1227
1748
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1228
1749
  if (!jwk) {
@@ -1231,7 +1752,7 @@ function createSetupClient(options = {}) {
1231
1752
  error: "operate_jwk_missing",
1232
1753
  human: {
1233
1754
  needs_human: "login",
1234
- message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
1755
+ message: "Run app-register first so the operate key exists under ~/.config/clavis/apps/"
1235
1756
  }
1236
1757
  };
1237
1758
  }
@@ -1247,15 +1768,18 @@ function createSetupClient(options = {}) {
1247
1768
  }
1248
1769
  var init_setup_client = __esm({
1249
1770
  "src/setup-client.ts"() {
1771
+ init_app_regions();
1250
1772
  init_browser();
1773
+ init_card();
1251
1774
  init_safe_browser_url();
1252
- init_digests();
1775
+ init_statements();
1253
1776
  init_ceremony();
1254
1777
  init_emit_env();
1255
1778
  init_operate_key_store();
1256
1779
  init_keys();
1257
1780
  init_login();
1258
1781
  init_org_api();
1782
+ init_org_creation();
1259
1783
  init_session_store();
1260
1784
  init_status();
1261
1785
  }
@@ -1295,11 +1819,17 @@ var init_redact_transport = __esm({
1295
1819
  }
1296
1820
  });
1297
1821
 
1298
- // src/mcp.ts
1299
- var mcp_exports = {};
1300
- __export(mcp_exports, {
1822
+ // src/mcp-server.ts
1823
+ var mcp_server_exports = {};
1824
+ __export(mcp_server_exports, {
1301
1825
  runMcpServer: () => runMcpServer
1302
1826
  });
1827
+ function orgCreationTerms(args) {
1828
+ return {
1829
+ incorporation: typeof args.incorporation === "string" ? args.incorporation : void 0,
1830
+ acceptCustomerTerms: args.accept_customer_terms === true
1831
+ };
1832
+ }
1303
1833
  async function dispatch(client, name, args) {
1304
1834
  switch (name) {
1305
1835
  case "clavis_setup_status":
@@ -1309,7 +1839,11 @@ async function dispatch(client, name, args) {
1309
1839
  args.bridge_json ? { bridgeJson: String(args.bridge_json) } : void 0
1310
1840
  );
1311
1841
  case "clavis_org_anchor_plan":
1312
- return client.orgAnchorPlan(String(args.domain), args.name ? String(args.name) : void 0);
1842
+ return client.orgAnchorPlan(
1843
+ String(args.domain),
1844
+ args.name ? String(args.name) : void 0,
1845
+ orgCreationTerms(args)
1846
+ );
1313
1847
  case "clavis_org_anchor_finish":
1314
1848
  return client.orgAnchorFinish({
1315
1849
  domain: String(args.domain),
@@ -1323,12 +1857,19 @@ async function dispatch(client, name, args) {
1323
1857
  return client.orgVerifyAnchor({
1324
1858
  domain: String(args.domain),
1325
1859
  nonce: String(args.nonce),
1326
- name: args.name ? String(args.name) : void 0
1860
+ name: args.name ? String(args.name) : void 0,
1861
+ ...orgCreationTerms(args)
1327
1862
  });
1328
1863
  case "clavis_policy_bootstrap":
1329
1864
  return client.policyBootstrap(String(args.org_id));
1865
+ case "clavis_incorporation_set":
1866
+ return client.incorporationSet({ orgId: String(args.org_id), ...orgCreationTerms(args) });
1330
1867
  case "clavis_card_checkout":
1331
- return client.cardCheckout(String(args.org_id));
1868
+ return client.cardCheckout(String(args.org_id), {
1869
+ offer: args.offer === "bundle" ? "bundle" : "meter",
1870
+ lang: checkoutLang(args.lang),
1871
+ consentBillingData: args.consent_billing_data === true
1872
+ });
1332
1873
  case "clavis_app_register":
1333
1874
  return client.appRegister({
1334
1875
  orgId: String(args.org_id),
@@ -1340,6 +1881,14 @@ async function dispatch(client, name, args) {
1340
1881
  return client.appHostPlan(String(args.org_id), String(args.app_id));
1341
1882
  case "clavis_app_verify_host":
1342
1883
  return client.appVerifyHost({ orgId: String(args.org_id), appId: String(args.app_id) });
1884
+ case "clavis_app_regions_set": {
1885
+ const choice = chooseAppRegions({
1886
+ ...args.regions !== void 0 ? { regions: Array.isArray(args.regions) ? args.regions.map((code) => String(code)) : [] } : {},
1887
+ all: args.all === true
1888
+ });
1889
+ if (!choice.ok) return choice;
1890
+ return client.appRegionsSet({ orgId: String(args.org_id), appId: String(args.app_id), regions: choice.regions });
1891
+ }
1343
1892
  case "clavis_declaration_set":
1344
1893
  return client.declarationSet({
1345
1894
  orgId: String(args.org_id),
@@ -1349,8 +1898,7 @@ async function dispatch(client, name, args) {
1349
1898
  });
1350
1899
  case "clavis_emit_app_env":
1351
1900
  return client.emitEnv({
1352
- appId: String(args.app_id),
1353
- operatePrivateJwkJson: typeof args.operate_private_jwk === "string" ? args.operate_private_jwk : void 0
1901
+ appId: String(args.app_id)
1354
1902
  });
1355
1903
  default:
1356
1904
  throw new Error(`unknown tool: ${name}`);
@@ -1385,17 +1933,29 @@ async function runMcpServer() {
1385
1933
  const transport = new StdioServerTransport();
1386
1934
  await server.connect(transport);
1387
1935
  }
1388
- var require2, PACKAGE_VERSION, TOOLS, isMain;
1389
- var init_mcp = __esm({
1390
- "src/mcp.ts"() {
1936
+ var require2, PACKAGE_VERSION, ORG_CREATION_PROPERTIES, TOOLS;
1937
+ var init_mcp_server = __esm({
1938
+ "src/mcp-server.ts"() {
1391
1939
  init_setup_client();
1940
+ init_app_regions();
1941
+ init_card();
1392
1942
  init_redact_transport();
1393
1943
  require2 = createRequire(import.meta.url);
1394
1944
  ({ version: PACKAGE_VERSION } = require2("../package.json"));
1945
+ ORG_CREATION_PROPERTIES = {
1946
+ incorporation: {
1947
+ type: "string",
1948
+ description: "Place of incorporation the customer declares for the Org: JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)."
1949
+ },
1950
+ accept_customer_terms: {
1951
+ type: "boolean",
1952
+ description: "true only after the customer (a human) has agreed to the Customer Terms and the Data Processing Agreement for this Org. Ask them; never set it on their behalf."
1953
+ }
1954
+ };
1395
1955
  TOOLS = [
1396
1956
  {
1397
1957
  name: "clavis_setup_status",
1398
- description: "List Org, App, signature card, and declaration readiness for the logged-in developers session.",
1958
+ description: "List Org, App, signature card (with what holds it back), place of incorporation, and declaration readiness for the logged-in developers session.",
1399
1959
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
1400
1960
  },
1401
1961
  {
@@ -1414,12 +1974,13 @@ var init_mcp = __esm({
1414
1974
  },
1415
1975
  {
1416
1976
  name: "clavis_org_anchor_plan",
1417
- description: "Start the Org DNS anchor challenge and open Passkey confirmation. Returns a ticket and human action.",
1977
+ description: "Start the Org DNS anchor challenge and open Passkey confirmation. Needs the place of incorporation and the customer's agreement to the Customer Terms; a place closed to new Orgs is refused before Passkey. Returns a ticket and human action.",
1418
1978
  inputSchema: {
1419
1979
  type: "object",
1420
1980
  properties: {
1421
1981
  domain: { type: "string" },
1422
- name: { type: "string" }
1982
+ name: { type: "string" },
1983
+ ...ORG_CREATION_PROPERTIES
1423
1984
  },
1424
1985
  required: ["domain"],
1425
1986
  additionalProperties: false
@@ -1444,13 +2005,14 @@ var init_mcp = __esm({
1444
2005
  },
1445
2006
  {
1446
2007
  name: "clavis_org_verify_anchor",
1447
- description: "Verify the Org DNS anchor after TXT and well-known are published.",
2008
+ description: "Verify the Org DNS anchor after TXT and well-known are published, and create the Org. Pass the same incorporation and the customer's agreement to the Customer Terms as org_anchor_plan.",
1448
2009
  inputSchema: {
1449
2010
  type: "object",
1450
2011
  properties: {
1451
2012
  domain: { type: "string" },
1452
2013
  nonce: { type: "string" },
1453
- name: { type: "string" }
2014
+ name: { type: "string" },
2015
+ ...ORG_CREATION_PROPERTIES
1454
2016
  },
1455
2017
  required: ["domain", "nonce"],
1456
2018
  additionalProperties: false
@@ -1466,12 +2028,41 @@ var init_mcp = __esm({
1466
2028
  additionalProperties: false
1467
2029
  }
1468
2030
  },
2031
+ {
2032
+ name: "clavis_incorporation_set",
2033
+ description: "Declare the Org's place of incorporation again (Passkey). Needed before card checkout when status shows incorporation null or terms_current false. The declaration binds the current Customer Terms and DPA, so it needs the customer's agreement.",
2034
+ inputSchema: {
2035
+ type: "object",
2036
+ properties: {
2037
+ org_id: { type: "string" },
2038
+ ...ORG_CREATION_PROPERTIES
2039
+ },
2040
+ required: ["org_id"],
2041
+ additionalProperties: false
2042
+ }
2043
+ },
1469
2044
  {
1470
2045
  name: "clavis_card_checkout",
1471
- description: "Open the checkout URL for the signature card.",
2046
+ description: "Open the checkout URL for the signature card (Passkey). Needs a current place of incorporation and the customer's consent to provide billing data to the payment provider. Call once without consent_billing_data to get the consent statement, show it to the customer, and call again only if they consent.",
1472
2047
  inputSchema: {
1473
2048
  type: "object",
1474
- properties: { org_id: { type: "string" } },
2049
+ properties: {
2050
+ org_id: { type: "string" },
2051
+ offer: {
2052
+ type: "string",
2053
+ enum: ["meter", "bundle"],
2054
+ description: "meter (pay per use, default) or bundle (monthly bundle)."
2055
+ },
2056
+ lang: {
2057
+ type: "string",
2058
+ enum: ["en", "ja"],
2059
+ description: "Language of the consent statement shown to the customer (default en). The purchase record keeps this language."
2060
+ },
2061
+ consent_billing_data: {
2062
+ type: "boolean",
2063
+ description: "true only after the customer (a human) has read the consent statement and consented. Ask them; never set it on their behalf."
2064
+ }
2065
+ },
1475
2066
  required: ["org_id"],
1476
2067
  additionalProperties: false
1477
2068
  }
@@ -1511,6 +2102,29 @@ var init_mcp = __esm({
1511
2102
  additionalProperties: false
1512
2103
  }
1513
2104
  },
2105
+ {
2106
+ name: "clavis_app_regions_set",
2107
+ description: "Choose the regions the App accepts new connections from (Passkey). Pass regions, or all: true to accept every region Clavis accepts. People already connected keep using the App. A region Clavis does not accept right now is refused before Passkey.",
2108
+ inputSchema: {
2109
+ type: "object",
2110
+ properties: {
2111
+ org_id: { type: "string" },
2112
+ app_id: { type: "string" },
2113
+ regions: {
2114
+ type: "array",
2115
+ items: { type: "string", enum: [...APP_REGIONS] },
2116
+ minItems: 1,
2117
+ description: "JP, US, GB, EEA. New connections from anywhere else are refused."
2118
+ },
2119
+ all: {
2120
+ type: "boolean",
2121
+ description: "true to accept every region Clavis accepts (removes the App's list)."
2122
+ }
2123
+ },
2124
+ required: ["org_id", "app_id"],
2125
+ additionalProperties: false
2126
+ }
2127
+ },
1514
2128
  {
1515
2129
  name: "clavis_declaration_set",
1516
2130
  description: "Replace the App use declaration (Passkey). uses becomes the whole declaration. Include every capability to keep. Signature requests need a signature use.",
@@ -1538,31 +2152,76 @@ var init_mcp = __esm({
1538
2152
  },
1539
2153
  {
1540
2154
  name: "clavis_emit_app_env",
1541
- description: "Emit environment variables for @clavis.nexus/app after setup.",
2155
+ description: "Emit environment variables for @clavis.nexus/app after setup. Needs CLAVIS_TRUST_ROOT (the Clavis Master public JWK) in the environment.",
1542
2156
  inputSchema: {
1543
2157
  type: "object",
1544
2158
  properties: {
1545
- app_id: { type: "string" },
1546
- operate_private_jwk: {
1547
- type: "string",
1548
- description: "Optional if app-register already saved the key under ~/.config/clavis/apps/"
1549
- }
2159
+ app_id: { type: "string" }
1550
2160
  },
1551
2161
  required: ["app_id"],
1552
2162
  additionalProperties: false
1553
2163
  }
1554
2164
  }
1555
2165
  ];
1556
- isMain = typeof process.argv[1] === "string" && import.meta.url === pathToFileURL(process.argv[1]).href;
1557
- if (isMain) {
1558
- runMcpServer().catch((e) => {
1559
- console.error(e);
1560
- process.exit(1);
1561
- });
1562
- }
1563
2166
  }
1564
2167
  });
1565
2168
 
2169
+ // src/cli-args.ts
2170
+ init_app_regions();
2171
+ function flag(args, name) {
2172
+ const i = args.indexOf(name);
2173
+ if (i < 0) return void 0;
2174
+ return args[i + 1];
2175
+ }
2176
+ function hasFlag(args, name) {
2177
+ return args.includes(name);
2178
+ }
2179
+ function positionals(args, valueFlags) {
2180
+ const out = [];
2181
+ for (let i = 0; i < args.length; i++) {
2182
+ const arg = args[i];
2183
+ if (valueFlags.includes(arg)) {
2184
+ i++;
2185
+ continue;
2186
+ }
2187
+ if (arg.startsWith("--")) continue;
2188
+ out.push(arg);
2189
+ }
2190
+ return out;
2191
+ }
2192
+ function orgCreationTermsFromArgs(args) {
2193
+ return {
2194
+ incorporation: flag(args, "--incorporation"),
2195
+ acceptCustomerTerms: hasFlag(args, "--accept-customer-terms")
2196
+ };
2197
+ }
2198
+ function cardCheckoutOptionsFromArgs(args) {
2199
+ const offer = flag(args, "--offer");
2200
+ if (offer !== void 0 && offer !== "meter" && offer !== "bundle") {
2201
+ return { ok: false, error: "--offer must be meter or bundle" };
2202
+ }
2203
+ const lang = flag(args, "--lang");
2204
+ if (lang !== void 0 && lang !== "en" && lang !== "ja") {
2205
+ return { ok: false, error: "--lang must be en or ja" };
2206
+ }
2207
+ return {
2208
+ ok: true,
2209
+ options: {
2210
+ ...offer ? { offer } : {},
2211
+ ...lang ? { lang } : {},
2212
+ consentBillingData: hasFlag(args, "--consent-billing-data")
2213
+ }
2214
+ };
2215
+ }
2216
+ function appRegionsFromArgs(args) {
2217
+ const raw = flag(args, "--regions");
2218
+ const listed = args.includes("--regions");
2219
+ return chooseAppRegions({
2220
+ ...listed ? { regions: (raw ?? "").split(",").filter((code) => code.trim().length > 0) } : {},
2221
+ all: hasFlag(args, "--all")
2222
+ });
2223
+ }
2224
+
1566
2225
  // src/cli.ts
1567
2226
  init_setup_client();
1568
2227
  init_redact_transport();
@@ -1571,34 +2230,38 @@ function printJson(value) {
1571
2230
  }
1572
2231
  function usage() {
1573
2232
  console.error(`Usage:
1574
- clavis login [--bridge-json '<json>' | --bridge-json-file <path>]
2233
+ clavis login [--bridge-json-file <path>]
1575
2234
  clavis logout
1576
2235
  clavis status
1577
2236
  clavis mcp
1578
- clavis org-anchor-plan <domain> [name]
2237
+ clavis org-anchor-plan <domain> [name] --incorporation CODE --accept-customer-terms
1579
2238
  clavis org-anchor-finish --domain D --nonce N --exp E --ticket T --well-known-url U --txt-host H
1580
- clavis org-verify-anchor --domain D --nonce N [--name N]
2239
+ clavis org-verify-anchor --domain D --nonce N --incorporation CODE --accept-customer-terms [--name N]
1581
2240
  clavis policy-bootstrap <orgId>
1582
- clavis card-checkout <orgId>
2241
+ clavis incorporation-set <orgId> --incorporation CODE --accept-customer-terms
2242
+ clavis card-checkout <orgId> --consent-billing-data [--offer meter|bundle] [--lang en|ja]
1583
2243
  clavis app-register --org O --host H --name N [--redirect /done]
1584
2244
  clavis app-host-plan <orgId> <appId>
1585
2245
  clavis app-verify-host <orgId> <appId>
2246
+ clavis app-regions-set <orgId> <appId> (--regions JP,US | --all)
1586
2247
  clavis declaration-set --org O --app A --end-users TEXT --use signature=OP
1587
- clavis emit-env --app A [--operate-jwk '{"kty":"..."}']
2248
+ clavis emit-env --app A
1588
2249
 
1589
- login: opens developers /setup/login, then paste the JSON from the page (or pass --bridge-json).
1590
- Secrets stay in ~/.config/clavis/apps/<appId>/ (mode 0600). Command output includes the file path. emit-env needs CLAVIS_MASTER_PUBLIC_JWK_JSON set to the master public JWK from /.well-known/jwks.json.
1591
- declaration-set replaces the App's current declaration. Pass every use to keep. status reports the signature card. WASM and ledger subscription are on developers.
2250
+ login: opens developers /setup/login, then paste the JSON from the page (or pass --bridge-json-file).
2251
+ Do not pass the access token or operate private key as a command-line argument.
2252
+ org-anchor-plan and org-verify-anchor need both flags. --incorporation is the Org's place of incorporation: JP, GB-EAW, an EEA country code, or US-XX.
2253
+ --accept-customer-terms records that the customer agrees to the Customer Terms and the DPA for this Org. That is the customer's decision: pass it only after they agree. It is never on by default.
2254
+ A place of incorporation that is closed to new Orgs right now is refused before Passkey.
2255
+ incorporation-set declares the place again after the Customer Terms change (status shows terms_current false). It needs the customer's agreement too.
2256
+ card-checkout needs --consent-billing-data: the customer's consent to provide billing data to the payment provider. Run it once without the flag to get the statement to show them.
2257
+ Secrets stay in ~/.config/clavis/apps/<appId>/ (mode 0600). Command output includes the file path. emit-env needs CLAVIS_TRUST_ROOT set to the Clavis Master public JWK (docs.clavis.nexus); it checks that the trust documents chain to it before writing CLAVIS_TRUST_ROOT for @clavis.nexus/app.
2258
+ app-regions-set chooses where the App accepts new connections from: JP, US, GB, EEA (comma-separated). --all accepts every region Clavis accepts. People already connected keep using the App.
2259
+ declaration-set replaces the App's current declaration. Pass every use to keep. status reports the signature card and the place of incorporation. Ledger subscription is on developers.
1592
2260
 
1593
2261
  Env: CLAVIS_API_ORIGIN CLAVIS_ID_ORIGIN CLAVIS_DEVELOPERS_ORIGIN CLAVIS_SESSION_PATH
1594
2262
  `);
1595
2263
  process.exit(2);
1596
2264
  }
1597
- function flag(args, name) {
1598
- const i = args.indexOf(name);
1599
- if (i < 0) return void 0;
1600
- return args[i + 1];
1601
- }
1602
2265
  function requireFlag(args, name) {
1603
2266
  const v = flag(args, name);
1604
2267
  if (!v) {
@@ -1613,14 +2276,19 @@ async function main() {
1613
2276
  const client = createSetupClient();
1614
2277
  switch (cmd) {
1615
2278
  case "mcp": {
1616
- const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
2279
+ const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp_server(), mcp_server_exports));
1617
2280
  await runMcpServer2();
1618
2281
  return;
1619
2282
  }
1620
2283
  case "login": {
1621
- const fromFlag = flag(rest, "--bridge-json");
2284
+ if (flag(rest, "--bridge-json")) {
2285
+ console.error(
2286
+ "refusing --bridge-json: the access token would be visible in the process list. Use --bridge-json-file or paste on stdin."
2287
+ );
2288
+ process.exit(2);
2289
+ }
1622
2290
  const fromFile = flag(rest, "--bridge-json-file");
1623
- let bridgeJson = fromFlag;
2291
+ let bridgeJson;
1624
2292
  if (fromFile) {
1625
2293
  const { readFile: readFile4 } = await import('fs/promises');
1626
2294
  bridgeJson = await readFile4(fromFile, "utf8");
@@ -1635,9 +2303,9 @@ async function main() {
1635
2303
  printJson(await client.status());
1636
2304
  return;
1637
2305
  case "org-anchor-plan": {
1638
- const domain = rest[0];
2306
+ const [domain, name] = positionals(rest, ["--incorporation"]);
1639
2307
  if (!domain) usage();
1640
- printJson(await client.orgAnchorPlan(domain, rest[1]));
2308
+ printJson(await client.orgAnchorPlan(domain, name, orgCreationTermsFromArgs(rest)));
1641
2309
  return;
1642
2310
  }
1643
2311
  case "org-anchor-finish":
@@ -1657,7 +2325,8 @@ async function main() {
1657
2325
  await client.orgVerifyAnchor({
1658
2326
  domain: requireFlag(rest, "--domain"),
1659
2327
  nonce: requireFlag(rest, "--nonce"),
1660
- name: flag(rest, "--name")
2328
+ name: flag(rest, "--name"),
2329
+ ...orgCreationTermsFromArgs(rest)
1661
2330
  })
1662
2331
  );
1663
2332
  return;
@@ -1667,10 +2336,21 @@ async function main() {
1667
2336
  printJson(await client.policyBootstrap(orgId));
1668
2337
  return;
1669
2338
  }
2339
+ case "incorporation-set": {
2340
+ const [orgId] = positionals(rest, ["--incorporation"]);
2341
+ if (!orgId) usage();
2342
+ printJson(await client.incorporationSet({ orgId, ...orgCreationTermsFromArgs(rest) }));
2343
+ return;
2344
+ }
1670
2345
  case "card-checkout": {
1671
- const orgId = rest[0];
2346
+ const [orgId] = positionals(rest, ["--offer", "--lang"]);
1672
2347
  if (!orgId) usage();
1673
- printJson(await client.cardCheckout(orgId));
2348
+ const opts = cardCheckoutOptionsFromArgs(rest);
2349
+ if (!opts.ok) {
2350
+ console.error(opts.error);
2351
+ usage();
2352
+ }
2353
+ printJson(await client.cardCheckout(orgId, opts.options));
1674
2354
  return;
1675
2355
  }
1676
2356
  case "app-register":
@@ -1695,6 +2375,17 @@ async function main() {
1695
2375
  printJson(await client.appVerifyHost({ orgId, appId }));
1696
2376
  return;
1697
2377
  }
2378
+ case "app-regions-set": {
2379
+ const [orgId, appId] = positionals(rest, ["--regions"]);
2380
+ if (!orgId || !appId) usage();
2381
+ const choice = appRegionsFromArgs(rest);
2382
+ if (!choice.ok) {
2383
+ console.error(choice.error);
2384
+ usage();
2385
+ }
2386
+ printJson(await client.appRegionsSet({ orgId, appId, regions: choice.regions }));
2387
+ return;
2388
+ }
1698
2389
  case "declaration-set": {
1699
2390
  const useRaw = requireFlag(rest, "--use");
1700
2391
  const [capability, ...opParts] = useRaw.split("=");
@@ -1711,10 +2402,15 @@ async function main() {
1711
2402
  return;
1712
2403
  }
1713
2404
  case "emit-env":
2405
+ if (flag(rest, "--operate-jwk")) {
2406
+ console.error(
2407
+ "refusing --operate-jwk: the private key would be visible in the process list. app-register saves it under ~/.config/clavis/apps/."
2408
+ );
2409
+ process.exit(2);
2410
+ }
1714
2411
  printJson(
1715
2412
  await client.emitEnv({
1716
- appId: requireFlag(rest, "--app"),
1717
- operatePrivateJwkJson: flag(rest, "--operate-jwk")
2413
+ appId: requireFlag(rest, "--app")
1718
2414
  })
1719
2415
  );
1720
2416
  return;