@clavis.nexus/setup 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
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
7
  import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
8
8
  import { createInterface } from 'readline/promises';
@@ -12,27 +12,301 @@ 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 fetchJwksDocument(apiOrigin) {
187
+ const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
188
+ redirect: "error",
189
+ headers: { Accept: "application/json" }
190
+ });
191
+ if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
192
+ return res.json();
193
+ }
194
+ async function getMasterJwkJson(apiOrigin, masterPinJson) {
195
+ const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
196
+ const doc = await fetchJwksDocument(apiOrigin);
197
+ await verifySignedJwksDocument(doc, masterPinJson);
198
+ return JSON.stringify(doc.master);
199
+ }
200
+ var SetupApiError;
201
+ var init_org_api = __esm({
202
+ "src/org-api.ts"() {
203
+ SetupApiError = class extends Error {
204
+ status;
205
+ code;
206
+ constructor(status, code, message) {
207
+ super(message);
208
+ this.name = "SetupApiError";
209
+ this.status = status;
210
+ this.code = code;
211
+ }
212
+ };
213
+ }
214
+ });
215
+
216
+ // src/app-regions.ts
217
+ function isAppRegion(value) {
218
+ return APP_REGIONS.includes(value);
219
+ }
220
+ function chooseAppRegions(input2) {
221
+ const listed = input2.regions !== void 0;
222
+ if (input2.all === true && listed) {
223
+ return { ok: false, error: `regions_conflict \u2014 pass either regions or all, not both. ${CHOICE_HINT}` };
224
+ }
225
+ if (input2.all === true) return { ok: true, regions: null };
226
+ if (!listed) return { ok: false, error: `regions_required \u2014 ${CHOICE_HINT}` };
227
+ return { ok: true, regions: input2.regions };
228
+ }
229
+ function readAppRegionsInput(raw) {
230
+ if (raw === null) return { ok: true, regions: null };
231
+ const codes = raw.map((code) => code.trim().toUpperCase());
232
+ if (codes.length === 0 || new Set(codes).size !== codes.length || !codes.every(isAppRegion)) {
233
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
234
+ }
235
+ return { ok: true, regions: APP_REGIONS.filter((region) => codes.includes(region)) };
236
+ }
237
+ function sameAppRegions(stored, next) {
238
+ const current = stored ?? null;
239
+ if (current === null || next === null) return current === next;
240
+ return current.length === next.length && current.every((region, i) => region === next[i]);
241
+ }
242
+ function regionNotOpenRefusal(closed, selectable) {
243
+ const open = selectable && selectable.length > 0 ? ` Regions you can choose now: ${selectable.join(", ")}.` : "";
244
+ return {
245
+ ok: false,
246
+ error: `region_not_open \u2014 Clavis is not accepting new connections from ${closed.join(", ")} right now, so an App cannot accept them.${open}`
247
+ };
248
+ }
249
+ function appDisabledRefusal() {
250
+ return { ok: false, error: "app_disabled \u2014 this App is disabled, so its regions cannot be changed." };
251
+ }
252
+ function appRegionsRefusal(e, regions) {
253
+ if (!(e instanceof SetupApiError)) return null;
254
+ switch (e.code) {
255
+ case "REGION_NOT_OPEN":
256
+ return regionNotOpenRefusal(regions, null);
257
+ case "REGIONS_INVALID":
258
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
259
+ case "APP_DISABLED":
260
+ return appDisabledRefusal();
261
+ case "FORBIDDEN":
262
+ return { ok: false, error: "forbidden \u2014 only an owner or admin of the Org can change the App's regions." };
263
+ default:
264
+ return null;
265
+ }
266
+ }
267
+ var APP_REGIONS, CHOICE_HINT;
268
+ var init_app_regions = __esm({
269
+ "src/app-regions.ts"() {
270
+ init_org_api();
271
+ APP_REGIONS = ["JP", "US", "GB", "EEA"];
272
+ CHOICE_HINT = "Pass --regions with one or more of JP, US, GB, EEA (comma-separated), or --all (MCP: regions or all: true).";
273
+ }
274
+ });
275
+ function isLoopbackHost(hostname) {
276
+ const host = hostname.toLowerCase();
277
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
278
+ }
279
+ function assertOpenableBrowserUrl(raw) {
280
+ let url;
281
+ try {
282
+ url = new URL(raw.trim());
283
+ } catch {
284
+ throw new Error("invalid URL");
285
+ }
286
+ if (url.username || url.password) throw new Error("URL must not contain credentials");
287
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost(url.hostname);
288
+ if (url.protocol !== "https:" && !loopbackHttp) {
289
+ throw new Error("only https URLs may be opened in a browser");
290
+ }
291
+ return url.toString();
292
+ }
293
+ function windowsBrowserArgs(raw) {
294
+ const url = assertOpenableBrowserUrl(raw);
295
+ const script = `Start-Process -FilePath '${url.replaceAll("'", "''")}'`;
296
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
297
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
298
+ }
26
299
  async function openBrowser(url) {
300
+ const safe = assertOpenableBrowserUrl(url);
27
301
  if (process.platform === "darwin") {
28
- await execFileAsync("open", [url]);
302
+ await execFileAsync("open", [safe]);
29
303
  return;
30
304
  }
31
305
  if (process.platform === "win32") {
32
- await execFileAsync("cmd", ["/c", "start", "", url]);
306
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
33
307
  return;
34
308
  }
35
- await execFileAsync("xdg-open", [url]);
309
+ await execFileAsync("xdg-open", [safe]);
36
310
  }
37
311
  var execFileAsync;
38
312
  var init_browser = __esm({
@@ -41,24 +315,191 @@ var init_browser = __esm({
41
315
  }
42
316
  });
43
317
 
318
+ // src/types.ts
319
+ var DEFAULT_ORIGINS, LEGAL_ORIGIN;
320
+ var init_types = __esm({
321
+ "src/types.ts"() {
322
+ DEFAULT_ORIGINS = {
323
+ apiOrigin: "https://api.clavis.nexus",
324
+ idOrigin: "https://id.clavis.nexus",
325
+ developersOrigin: "https://developers.clavis.nexus"
326
+ };
327
+ LEGAL_ORIGIN = "https://legal.clavis.nexus";
328
+ }
329
+ });
330
+
331
+ // src/org-creation.ts
332
+ function normalizeIncorporation(raw) {
333
+ return (raw ?? "").trim().toUpperCase();
334
+ }
335
+ function checkOrgCreationTerms(terms, human = TERMS_HUMAN) {
336
+ if (terms.acceptCustomerTerms !== true) {
337
+ return { ok: false, error: "customer_terms_not_accepted", human };
338
+ }
339
+ const incorporation = normalizeIncorporation(terms.incorporation);
340
+ if (!incorporation) {
341
+ return {
342
+ ok: false,
343
+ error: `incorporation_required \u2014 pass --incorporation CODE (MCP: incorporation): ${INCORPORATION_HINT}`
344
+ };
345
+ }
346
+ return { ok: true, incorporation };
347
+ }
348
+ function regionClosedRefusal(incorporation) {
349
+ return {
350
+ ok: false,
351
+ error: `region_closed \u2014 Clavis is not accepting new Orgs incorporated in ${incorporation} right now. GET /orgs/regions lists the closed places.`
352
+ };
353
+ }
354
+ function orgCreationRefusal(e, incorporation) {
355
+ if (!(e instanceof SetupApiError)) return null;
356
+ if (e.status === 403 && e.code === "REGION_CLOSED") return regionClosedRefusal(incorporation);
357
+ if (e.code === "TERMS_REQUIRED") return { ok: false, error: "customer_terms_not_accepted", human: TERMS_HUMAN };
358
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
359
+ return null;
360
+ }
361
+ function incorporationInvalidRefusal(incorporation) {
362
+ return {
363
+ ok: false,
364
+ error: `incorporation_invalid \u2014 ${incorporation || "(empty)"} is not a place of incorporation Clavis accepts. Use ${INCORPORATION_HINT}.`
365
+ };
366
+ }
367
+ var INCORPORATION_HINT, TERMS_LINKS, TERMS_HUMAN, INCORPORATION_TERMS_HUMAN;
368
+ var init_org_creation = __esm({
369
+ "src/org-creation.ts"() {
370
+ init_org_api();
371
+ init_types();
372
+ INCORPORATION_HINT = "JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)";
373
+ TERMS_LINKS = `Customer Terms: ${LEGAL_ORIGIN}/en/customer-terms \u2014 DPA: ${LEGAL_ORIGIN}/en/dpa.`;
374
+ TERMS_HUMAN = {
375
+ needs_human: "terms",
376
+ 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).`
377
+ };
378
+ INCORPORATION_TERMS_HUMAN = {
379
+ needs_human: "terms",
380
+ 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).`
381
+ };
382
+ }
383
+ });
384
+
385
+ // src/card.ts
386
+ function checkoutLang(raw) {
387
+ return raw === "ja" ? "ja" : "en";
388
+ }
389
+ function billingConsentHuman(acceptance, lang) {
390
+ const copy = BILLING_CONSENT[lang];
391
+ return {
392
+ needs_human: "terms",
393
+ message: [
394
+ copy.lead,
395
+ copy.statement,
396
+ copy.info(`${LEGAL_ORIGIN}/${lang}/privacy`),
397
+ copy.versions(acceptance.customer_terms_version, acceptance.dpa_version),
398
+ copy.next
399
+ ].join("\n")
400
+ };
401
+ }
402
+ function incorporationNeededRefusal(orgId, stale) {
403
+ 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.";
404
+ return {
405
+ ok: false,
406
+ error: stale ? "incorporation_stale" : "incorporation_required",
407
+ human: {
408
+ needs_human: "terms",
409
+ message: `${why} Run: clavis incorporation-set ${orgId} --incorporation CODE --accept-customer-terms (MCP: clavis_incorporation_set), after the customer agrees.`
410
+ }
411
+ };
412
+ }
413
+ function purchaseRegionClosedRefusal(incorporation) {
414
+ return {
415
+ ok: false,
416
+ error: `region_closed \u2014 new subscriptions are not accepted right now for Orgs incorporated in ${incorporation}.`
417
+ };
418
+ }
419
+ function declarationRegionClosedRefusal(incorporation) {
420
+ return {
421
+ ok: false,
422
+ error: `region_closed \u2014 ${incorporation} cannot be declared as the place of incorporation right now. GET /orgs/regions lists the closed places.`
423
+ };
424
+ }
425
+ function checkoutRefusal(e, args) {
426
+ if (!(e instanceof SetupApiError)) return null;
427
+ switch (e.code) {
428
+ case "REGION_CLOSED":
429
+ return purchaseRegionClosedRefusal(args.incorporation);
430
+ case "INCORPORATION":
431
+ return incorporationNeededRefusal(args.orgId, e.message === "incorporation_stale");
432
+ case "AGE_INELIGIBLE":
433
+ return { ok: false, error: "age_ineligible \u2014 an organisation contract can be made by someone who is 18 or older." };
434
+ case "AGE_BAND_REQUIRED":
435
+ return {
436
+ ok: false,
437
+ error: "age_band_required \u2014 this account has no age record, so the organisation contract can't continue."
438
+ };
439
+ case "BILLING_SUBJECT":
440
+ return {
441
+ ok: false,
442
+ error: "billing_subject_taken \u2014 this account already pays for another Org. Another owner or admin of this Org can subscribe instead."
443
+ };
444
+ case "CHECKOUT_CLOSED":
445
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
446
+ default:
447
+ return null;
448
+ }
449
+ }
450
+ function incorporationSetRefusal(e, incorporation) {
451
+ if (!(e instanceof SetupApiError)) return null;
452
+ if (e.code === "REGION_CLOSED") return declarationRegionClosedRefusal(incorporation);
453
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
454
+ return null;
455
+ }
456
+ var BILLING_CONSENT;
457
+ var init_card = __esm({
458
+ "src/card.ts"() {
459
+ init_org_api();
460
+ init_org_creation();
461
+ init_types();
462
+ BILLING_CONSENT = {
463
+ en: {
464
+ lead: "Subscribing needs the customer's own consent. Show them the statement below and ask. Do not consent on their behalf.",
465
+ 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.",
466
+ 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.`,
467
+ versions: (terms, dpa) => `This purchase is made under Customer Terms ${terms} and DPA ${dpa}.`,
468
+ next: "If they consent, run again with --consent-billing-data (MCP: consent_billing_data: true)."
469
+ },
470
+ ja: {
471
+ 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",
472
+ 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",
473
+ 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`,
474
+ 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`,
475
+ 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"
476
+ }
477
+ };
478
+ }
479
+ });
480
+
44
481
  // src/safe-browser-url.ts
45
- function parseHttpsUrl(raw) {
482
+ function isLoopbackHost2(hostname) {
483
+ const host = hostname.toLowerCase();
484
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
485
+ }
486
+ function parseBrowserUrl(raw) {
46
487
  let u;
47
488
  try {
48
489
  u = new URL(raw.trim());
49
490
  } catch {
50
491
  throw new Error("invalid URL");
51
492
  }
52
- if (u.protocol !== "https:") {
53
- throw new Error("only https URLs may be opened in a browser");
54
- }
55
493
  if (u.username || u.password) {
56
494
  throw new Error("URL must not contain credentials");
57
495
  }
58
496
  return u;
59
497
  }
60
498
  function assertCardCheckoutBrowserUrl(raw) {
61
- const u = parseHttpsUrl(raw);
499
+ const u = parseBrowserUrl(raw);
500
+ if (u.protocol !== "https:") {
501
+ throw new Error("only https URLs may be opened in a browser");
502
+ }
62
503
  const host = u.hostname.toLowerCase();
63
504
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
64
505
  throw new Error("checkout URL host is not allowed");
@@ -66,15 +507,21 @@ function assertCardCheckoutBrowserUrl(raw) {
66
507
  return u.toString();
67
508
  }
68
509
  function assertOriginBrowserUrl(raw, origin) {
69
- const u = parseHttpsUrl(raw);
510
+ const u = parseBrowserUrl(raw);
70
511
  let expected;
71
512
  try {
72
513
  expected = new URL(origin.trim());
73
514
  } catch {
74
515
  throw new Error("invalid expected origin");
75
516
  }
76
- if (expected.protocol !== "https:") {
77
- throw new Error("expected origin must be https");
517
+ if (expected.username || expected.password) {
518
+ throw new Error("expected origin must not contain credentials");
519
+ }
520
+ const loopback = isLoopbackHost2(expected.hostname);
521
+ const https = expected.protocol === "https:" && u.protocol === "https:";
522
+ const loopbackHttp = loopback && expected.protocol === "http:" && u.protocol === "http:";
523
+ if (!https && !loopbackHttp) {
524
+ throw new Error("only https URLs may be opened in a browser");
78
525
  }
79
526
  if (u.origin !== expected.origin) {
80
527
  throw new Error("URL origin does not match the expected origin");
@@ -93,10 +540,6 @@ function bytesToBase64Url(bytes) {
93
540
  const b64 = Buffer.from(bin, "binary").toString("base64");
94
541
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
95
542
  }
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
543
  async function sha256HexUtf8(s) {
101
544
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
102
545
  let out = "";
@@ -127,101 +570,112 @@ var init_canonical_json = __esm({
127
570
  }
128
571
  });
129
572
 
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
- );
573
+ // src/statements.ts
574
+ async function digestOf(value) {
575
+ const bytes = new TextEncoder().encode(canonicalStringify(value));
576
+ return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))}`;
577
+ }
578
+ function orgAnchorPublishStatement(input2) {
579
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
580
+ }
581
+ function orgPolicyBootstrapStatement(input2) {
582
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
583
+ }
584
+ function orgAppRegisterStatement(input2) {
585
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim().toLowerCase() };
586
+ }
587
+ function orgAppVerifyHostStatement(input2) {
588
+ return {
589
+ type: "org.app.verify_host@1",
590
+ org: input2.org.trim(),
591
+ app: input2.app.trim(),
592
+ host: input2.host.trim().toLowerCase(),
593
+ nonce: input2.nonce.trim()
594
+ };
595
+ }
596
+ async function orgAppDeclarationStatement(input2) {
597
+ return {
598
+ type: "org.app.declaration@1",
599
+ org: input2.org.trim(),
600
+ app: input2.app.trim(),
601
+ declaration: input2.declaration === null ? null : await digestOf({ endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
602
+ };
603
+ }
604
+ function orgAppRegionsStatement(input2) {
605
+ return {
606
+ type: "org.app.regions@1",
607
+ org: input2.org.trim(),
608
+ app: input2.app.trim(),
609
+ regions: input2.regions === null ? null : [...new Set(input2.regions)].sort()
610
+ };
611
+ }
612
+ function orgCardIncorporationStatement(input2) {
613
+ return {
614
+ type: "org.card.incorporation_set@1",
615
+ org: input2.org.trim(),
616
+ code: input2.code.trim(),
617
+ customer_terms: input2.customerTerms.trim(),
618
+ dpa: input2.dpa.trim()
619
+ };
620
+ }
621
+ function orgCardCheckoutStatement(input2) {
622
+ return {
623
+ type: "org.card.checkout@1",
624
+ org: input2.org.trim(),
625
+ capability: input2.capability.trim(),
626
+ offer: input2.offer,
627
+ customer_terms: input2.customerTerms.trim(),
628
+ dpa: input2.dpa.trim()
629
+ };
630
+ }
631
+ function sameStatement(a, b) {
632
+ try {
633
+ return canonicalStringify(a) === canonicalStringify(b);
634
+ } catch {
635
+ return false;
636
+ }
139
637
  }
140
638
  async function computePayloadCommitmentHex(payload) {
141
639
  const o = payload && typeof payload === "object" ? { ...payload } : payload;
142
640
  if (o && typeof o === "object" && !Array.isArray(o)) {
143
- delete o.proposer_sign_proof;
641
+ delete o.proposer_receipt;
144
642
  }
145
643
  return sha256HexUtf8(canonicalStringify(o));
146
644
  }
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
- );
154
- }
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
- );
164
- }
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
- );
173
- }
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
- );
183
- }
184
645
  async function hashManifestBody(body) {
185
646
  return sha256HexUtf8(canonicalStringify(body));
186
647
  }
187
648
  function buildAnchorTxtRecord(args) {
188
649
  return `v=1;kind=anchor;hash=${args.hash};nonce=${args.nonce};exp=${args.exp}`;
189
650
  }
190
- var init_digests = __esm({
191
- "src/digests.ts"() {
651
+ var init_statements = __esm({
652
+ "src/statements.ts"() {
192
653
  init_base64url();
193
654
  init_canonical_json();
194
655
  }
195
656
  });
196
657
 
197
658
  // 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.");
659
+ function receiptFromCeremonyPayload(payload) {
660
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
661
+ throw new Error("Passkey confirmation did not return a receipt.");
201
662
  }
202
663
  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;
664
+ if (o.type !== "receipt@1" || o.statement === null || typeof o.statement !== "object") {
665
+ throw new Error("Passkey confirmation did not return a receipt.");
207
666
  }
208
- throw new Error("Passkey confirmation did not return a signature.");
667
+ return o;
209
668
  }
210
669
  async function startCeremony(args) {
211
670
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
212
671
  method: "POST",
672
+ redirect: "error",
213
673
  headers: {
214
674
  Accept: "application/json",
215
675
  "Content-Type": "application/json",
216
676
  Authorization: `Bearer ${args.bearer}`
217
677
  },
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
- })
678
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
225
679
  });
226
680
  const body = await res.json().catch(() => null);
227
681
  if (!res.ok || typeof body?.payload?.ticket !== "string") {
@@ -237,6 +691,7 @@ async function pollCeremonyResult(args) {
237
691
  while (Date.now() < deadline) {
238
692
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
239
693
  method: "POST",
694
+ redirect: "error",
240
695
  headers: {
241
696
  Accept: "application/json",
242
697
  "Content-Type": "application/json",
@@ -244,209 +699,89 @@ async function pollCeremonyResult(args) {
244
699
  },
245
700
  body: JSON.stringify({ ticket: args.ticket })
246
701
  });
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
- }
702
+ const body = await res.json().catch(() => null);
703
+ if (res.ok && body?.payload !== void 0) {
704
+ return body.payload.receipt;
374
705
  }
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
- });
706
+ if (res.status === 404) {
707
+ lastError = body?.message ?? "waiting for Passkey";
708
+ await sleep(intervalMs);
709
+ continue;
710
+ }
711
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
712
+ }
713
+ throw new Error(lastError);
386
714
  }
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();
715
+ function sleep(ms) {
716
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
393
717
  }
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);
718
+ function ceremonyPageUrl(idOrigin, ticket) {
719
+ const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
720
+ u.searchParams.set("ticket", ticket);
721
+ return u.toString();
398
722
  }
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);
723
+ function setupCeremonyReturnTo(developersOrigin) {
724
+ return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
404
725
  }
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
- };
726
+ var init_ceremony = __esm({
727
+ "src/ceremony.ts"() {
418
728
  }
419
729
  });
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");
730
+ async function refuseSymlink(path2) {
731
+ try {
732
+ const st = await lstat(path2);
733
+ if (st.isSymbolicLink()) throw new Error(`refusing to write through a symlink: ${path2}`);
734
+ } catch (e) {
735
+ if (e.code === "ENOENT") return;
736
+ throw e;
737
+ }
431
738
  }
432
- async function restrictFileMode(path2) {
739
+ async function writeMode600(path2, contents) {
740
+ const dir = dirname(path2);
741
+ await mkdir(dir, { recursive: true, mode: 448 });
742
+ await refuseSymlink(dir);
743
+ await refuseSymlink(path2);
744
+ await writeFile(path2, contents, { encoding: "utf8", mode: 384 });
433
745
  try {
434
746
  await chmod(path2, 384);
435
747
  } catch (e) {
436
- console.warn(
437
- `clavis: could not set mode 0600 on ${path2}: ${e instanceof Error ? e.message : e}`
438
- );
748
+ await unlink(path2).catch(() => void 0);
749
+ const message = e instanceof Error ? e.message : String(e);
750
+ throw new Error(`could not set mode 0600 on ${path2}: ${message}`);
751
+ }
752
+ }
753
+ var init_private_file = __esm({
754
+ "src/private-file.ts"() {
439
755
  }
756
+ });
757
+ function assertOperateAppId(appId) {
758
+ const app = appId.trim().toLowerCase();
759
+ if (!APP_ID_RE.test(app)) throw new Error("invalid_app_id");
760
+ return app;
761
+ }
762
+ function keysBase() {
763
+ const override = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim();
764
+ return resolve(override || join(homedir(), ".config", "clavis", "apps"));
765
+ }
766
+ function pathInsideKeys(appId, file) {
767
+ const app = assertOperateAppId(appId);
768
+ const base = keysBase();
769
+ const path2 = resolve(base, app, file);
770
+ const rel = relative(base, path2);
771
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("invalid_app_id");
772
+ return path2;
773
+ }
774
+ function operatePrivateJwkPath(appId) {
775
+ return pathInsideKeys(appId, "operate-private.jwk.json");
776
+ }
777
+ function appEnvFilePath(appId) {
778
+ return pathInsideKeys(appId, "app.env");
440
779
  }
441
780
  async function saveOperatePrivateJwk(appId, jwkJson) {
442
781
  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
- }
782
+ await writeMode600(path2, `${jwkJson.trim()}
783
+ `);
784
+ await chmod(dirname(path2), 448).catch(() => void 0);
450
785
  return path2;
451
786
  }
452
787
  async function readOperatePrivateJwk(appId) {
@@ -459,14 +794,15 @@ async function readOperatePrivateJwk(appId) {
459
794
  }
460
795
  async function writeAppEnvFile(appId, contents) {
461
796
  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);
797
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
798
+ `);
466
799
  return path2;
467
800
  }
801
+ var APP_ID_RE;
468
802
  var init_operate_key_store = __esm({
469
803
  "src/operate-key-store.ts"() {
804
+ init_private_file();
805
+ 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
806
  }
471
807
  });
472
808
 
@@ -531,24 +867,25 @@ var init_keys = __esm({
531
867
  }
532
868
  });
533
869
  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"] });
537
- }
870
+ const origin = new URL(apiOrigin).origin;
871
+ const jwks = createRemoteJWKSet(new URL(`${origin}/.well-known/jwks.json`));
872
+ const { payload, protectedHeader } = await jwtVerify(accessToken, jwks, {
873
+ algorithms: ["ES256"],
874
+ issuer: origin,
875
+ audience: origin,
876
+ requiredClaims: ["exp", "iss", "aud", "sub"]
877
+ });
878
+ const kid = typeof protectedHeader.kid === "string" ? protectedHeader.kid : "";
879
+ if (!SESSION_SLOT_RE.test(kid)) throw new Error("invalid_access_token_kid");
880
+ if (payload.tk !== "access") throw new Error("invalid_access_token_kind");
881
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) throw new Error("invalid_access_token_sub");
882
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) throw new Error("invalid_access_token_exp");
883
+ return { sub: payload.sub, expiresAt: payload.exp };
884
+ }
885
+ var SESSION_SLOT_RE;
538
886
  var init_access_token_verify = __esm({
539
887
  "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
- };
888
+ SESSION_SLOT_RE = /^[a-z][a-z0-9]{1,31}-wauthn-auth-jwt(?:-\d{6})?$/;
552
889
  }
553
890
  });
554
891
  function defaultSessionPath() {
@@ -556,11 +893,37 @@ function defaultSessionPath() {
556
893
  if (override) return override;
557
894
  return join(homedir(), ".config", "clavis", "session.json");
558
895
  }
896
+ function isLoopbackHost3(hostname) {
897
+ const host = hostname.toLowerCase();
898
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
899
+ }
900
+ function assertSetupOrigin(raw, name) {
901
+ let url;
902
+ try {
903
+ url = new URL(raw.trim());
904
+ } catch {
905
+ throw new Error(`${name} must be an absolute URL`);
906
+ }
907
+ if (url.username || url.password) throw new Error(`${name} must not contain credentials`);
908
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost3(url.hostname);
909
+ if (url.protocol !== "https:" && !loopbackHttp) throw new Error(`${name} must be https`);
910
+ if (url.pathname !== "/" || url.search || url.hash) throw new Error(`${name} must be an origin`);
911
+ return url.origin;
912
+ }
559
913
  function originsFromEnv(overrides) {
560
914
  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
915
+ apiOrigin: assertSetupOrigin(
916
+ overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
917
+ "apiOrigin"
918
+ ),
919
+ idOrigin: assertSetupOrigin(
920
+ overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
921
+ "idOrigin"
922
+ ),
923
+ developersOrigin: assertSetupOrigin(
924
+ overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin,
925
+ "developersOrigin"
926
+ )
564
927
  };
565
928
  }
566
929
  async function loadSession(path2 = defaultSessionPath()) {
@@ -575,16 +938,8 @@ async function loadSession(path2 = defaultSessionPath()) {
575
938
  }
576
939
  }
577
940
  async function saveSession(session, origins, path2 = defaultSessionPath()) {
578
- await mkdir(dirname(path2), { recursive: true });
579
941
  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
- }
942
+ await writeMode600(path2, JSON.stringify(body, null, 2));
588
943
  }
589
944
  async function clearSession(path2 = defaultSessionPath()) {
590
945
  try {
@@ -594,6 +949,7 @@ async function clearSession(path2 = defaultSessionPath()) {
594
949
  }
595
950
  var init_session_store = __esm({
596
951
  "src/session-store.ts"() {
952
+ init_private_file();
597
953
  init_types();
598
954
  }
599
955
  });
@@ -601,17 +957,6 @@ function pendingLoginPath(sessionPath) {
601
957
  const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
602
958
  return path.join(base, "login-pending.json");
603
959
  }
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
960
  function loginBridgeUrl(developersOrigin, state) {
616
961
  const bridge = new URL("/developers/setup/login", developersOrigin);
617
962
  bridge.searchParams.set("state", state);
@@ -653,12 +998,11 @@ async function sessionFromBridge(args) {
653
998
  if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
654
999
  throw new Error("invalid_bridge_json");
655
1000
  }
656
- await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
657
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
1001
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
658
1002
  return {
659
1003
  accessToken: body.accessToken,
660
- ...sub ? { sub } : {},
661
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
1004
+ sub: verified.sub,
1005
+ expiresAt: verified.expiresAt
662
1006
  };
663
1007
  }
664
1008
  async function readBridgeJsonFromStdin() {
@@ -699,6 +1043,14 @@ async function loginWithBrowser(args) {
699
1043
  await clearPending(pendingPath);
700
1044
  throw new Error("pending_login_origin_mismatch \u2014 run login again");
701
1045
  }
1046
+ if (!Number.isFinite(pending.createdAt) || Date.now() - pending.createdAt > PENDING_LOGIN_TTL_MS) {
1047
+ await clearPending(pendingPath);
1048
+ throw new Error("pending_login_expired \u2014 run login again");
1049
+ }
1050
+ const openUrl2 = assertOriginBrowserUrl(
1051
+ loginBridgeUrl(args.origins.developersOrigin, pending.state),
1052
+ args.origins.developersOrigin
1053
+ );
702
1054
  const session2 = await sessionFromBridge({
703
1055
  raw: args.bridgeJson,
704
1056
  expectedState: pending.state,
@@ -711,12 +1063,15 @@ async function loginWithBrowser(args) {
711
1063
  human: {
712
1064
  needs_human: "login",
713
1065
  message: "Session stored.",
714
- open_url: loginBridgeUrl(args.origins.developersOrigin, pending.state)
1066
+ open_url: openUrl2
715
1067
  }
716
1068
  };
717
1069
  }
718
1070
  const state = randomBytes(16).toString("hex");
719
- const openUrl = loginBridgeUrl(args.origins.developersOrigin, state);
1071
+ const openUrl = assertOriginBrowserUrl(
1072
+ loginBridgeUrl(args.origins.developersOrigin, state),
1073
+ args.origins.developersOrigin
1074
+ );
720
1075
  await writePending(pendingPath, {
721
1076
  v: 1,
722
1077
  state,
@@ -726,7 +1081,7 @@ async function loginWithBrowser(args) {
726
1081
  });
727
1082
  if (openFlag) {
728
1083
  try {
729
- await openBrowser(assertOriginBrowserUrl(openUrl, args.origins.developersOrigin));
1084
+ await openBrowser(openUrl);
730
1085
  } catch {
731
1086
  }
732
1087
  }
@@ -757,7 +1112,7 @@ async function loginWithBrowser(args) {
757
1112
  }
758
1113
  };
759
1114
  }
760
- var MAX_BRIDGE_JSON_CHARS;
1115
+ var MAX_BRIDGE_JSON_CHARS, PENDING_LOGIN_TTL_MS;
761
1116
  var init_login = __esm({
762
1117
  "src/login.ts"() {
763
1118
  init_browser();
@@ -765,16 +1120,23 @@ var init_login = __esm({
765
1120
  init_access_token_verify();
766
1121
  init_session_store();
767
1122
  MAX_BRIDGE_JSON_CHARS = 16384;
1123
+ PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
768
1124
  }
769
1125
  });
770
1126
 
771
1127
  // src/status.ts
772
- function cardActive(card) {
773
- if (!card) return "unknown";
1128
+ function signatureCard(card) {
774
1129
  const sig = card.capabilities?.signature;
775
- if (!sig) return "inactive";
776
- if (sig.subscribed === true || sig.active === true) return "active";
777
- return "inactive";
1130
+ if (!sig) return { signature_card: "inactive" };
1131
+ if (sig.open === true) return { signature_card: "active" };
1132
+ return {
1133
+ signature_card: "inactive",
1134
+ ...Array.isArray(sig.blockers) && sig.blockers.length > 0 ? { signature_card_blockers: sig.blockers } : {}
1135
+ };
1136
+ }
1137
+ function incorporationOf(card) {
1138
+ const inc = card.incorporation;
1139
+ return inc ? { code: inc.code, terms_current: inc.terms_current === true } : null;
778
1140
  }
779
1141
  async function buildSetupStatus(args) {
780
1142
  if (!args.session) {
@@ -784,7 +1146,9 @@ async function buildSetupStatus(args) {
784
1146
  const detailed = [];
785
1147
  for (const org of orgs) {
786
1148
  let setup_complete = false;
787
- let signature_card = "unknown";
1149
+ let card = {
1150
+ signature_card: "unknown"
1151
+ };
788
1152
  let apps = [];
789
1153
  try {
790
1154
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -792,10 +1156,10 @@ async function buildSetupStatus(args) {
792
1156
  } catch {
793
1157
  }
794
1158
  try {
795
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
796
- signature_card = cardActive(card);
1159
+ const view = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
1160
+ card = { ...signatureCard(view), incorporation: incorporationOf(view) };
797
1161
  } catch {
798
- signature_card = "unknown";
1162
+ card = { signature_card: "unknown" };
799
1163
  }
800
1164
  try {
801
1165
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -803,6 +1167,7 @@ async function buildSetupStatus(args) {
803
1167
  app_id: a.app_id,
804
1168
  host: a.host,
805
1169
  status: a.status,
1170
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
806
1171
  declaration_ok: Boolean(
807
1172
  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
1173
  )
@@ -832,7 +1197,7 @@ async function buildSetupStatus(args) {
832
1197
  primary_domain: org.primary_domain,
833
1198
  org_status: org.org_status,
834
1199
  setup_complete,
835
- signature_card,
1200
+ ...card,
836
1201
  apps
837
1202
  });
838
1203
  }
@@ -869,21 +1234,18 @@ async function runPasskeyCeremony(args) {
869
1234
  apiOrigin: args.origins.apiOrigin,
870
1235
  bearer: args.bearer,
871
1236
  returnTo,
872
- purpose: args.purpose,
873
- messageDigest: args.messageDigest,
874
- displayHint: args.displayHint,
875
- label: args.displayHint
1237
+ statement: args.statement
876
1238
  });
877
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1239
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
878
1240
  if (args.openBrowserFlag) {
879
1241
  try {
880
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1242
+ await openBrowser(ceremony_url);
881
1243
  } catch {
882
1244
  }
883
1245
  }
884
1246
  const human = {
885
1247
  needs_human: "passkey",
886
- message: "Confirm with Passkey in the browser, then return to the terminal/agent.",
1248
+ message: `${args.displayHint ? `${args.displayHint}: c` : "C"}onfirm with Passkey in the browser (${args.statement.type}), then return to the terminal/agent.`,
887
1249
  open_url: ceremony_url
888
1250
  };
889
1251
  return {
@@ -896,7 +1258,7 @@ async function runPasskeyCeremony(args) {
896
1258
  bearer: args.bearer,
897
1259
  ticket
898
1260
  });
899
- return signProofFromCeremonyPayload(payload);
1261
+ return receiptFromCeremonyPayload(payload);
900
1262
  }
901
1263
  };
902
1264
  }
@@ -938,18 +1300,43 @@ function createSetupClient(options = {}) {
938
1300
  const report = await buildSetupStatus({ origins, session });
939
1301
  return { ok: true, data: report };
940
1302
  },
941
- async orgAnchorPlan(domain, name) {
1303
+ async orgAnchorPlan(domain, name, terms = {}) {
1304
+ const checked = checkOrgCreationTerms(terms);
1305
+ if (!checked.ok) return checked;
1306
+ const { incorporation } = checked;
942
1307
  const auth = await requireSession({ origins, sessionPath });
943
1308
  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" };
1309
+ const apiOrigin = auth.data.origins.apiOrigin;
1310
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1311
+ if (closed.includes(incorporation)) return regionClosedRefusal(incorporation);
1312
+ let challenge;
1313
+ try {
1314
+ challenge = await postDnsChallenge(apiOrigin, auth.data.session.accessToken, { domain, incorporation });
1315
+ } catch (e) {
1316
+ const refusal = orgCreationRefusal(e, incorporation);
1317
+ if (refusal) return refusal;
1318
+ throw e;
1319
+ }
1320
+ const domainNorm = domain.trim().toLowerCase();
1321
+ 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)) {
1322
+ return { ok: false, error: "challenge_missing_statement" };
1323
+ }
1324
+ const anchorStatement = orgAnchorPublishStatement({ domain: domainNorm, nonce: challenge.nonce, exp: challenge.exp });
1325
+ if (!sameStatement(anchorStatement, challenge.statement)) return { ok: false, error: "challenge_statement_mismatch" };
1326
+ let wellKnown;
1327
+ try {
1328
+ wellKnown = new URL(challenge.well_known_url);
1329
+ } catch {
1330
+ return { ok: false, error: "challenge_url_rejected" };
1331
+ }
1332
+ const txtHost = typeof challenge.txt_host === "string" ? challenge.txt_host.trim().toLowerCase().replace(/\.$/, "") : "";
1333
+ if (wellKnown.protocol !== "https:" || wellKnown.username || wellKnown.password || wellKnown.hostname.toLowerCase() !== domainNorm || txtHost !== domainNorm && !txtHost.endsWith(`.${domainNorm}`)) {
1334
+ return { ok: false, error: "challenge_url_rejected" };
947
1335
  }
948
1336
  const cer = await runPasskeyCeremony({
949
1337
  origins: auth.data.origins,
950
1338
  bearer: auth.data.session.accessToken,
951
- purpose: "org.anchor.publish",
952
- messageDigest: challenge.digest,
1339
+ statement: anchorStatement,
953
1340
  displayHint: `Publish DNS anchor for ${domain}`,
954
1341
  openBrowserFlag
955
1342
  });
@@ -958,9 +1345,10 @@ function createSetupClient(options = {}) {
958
1345
  data: {
959
1346
  domain: challenge.domain,
960
1347
  ...name ? { name } : {},
1348
+ incorporation,
961
1349
  nonce: challenge.nonce,
962
1350
  exp: challenge.exp,
963
- digest: challenge.digest,
1351
+ statement: anchorStatement,
964
1352
  well_known_url: challenge.well_known_url,
965
1353
  txt_host: challenge.txt_host,
966
1354
  ceremony_url: cer.ceremony_url,
@@ -977,12 +1365,12 @@ function createSetupClient(options = {}) {
977
1365
  bearer: auth.data.session.accessToken,
978
1366
  ticket: args.ticket
979
1367
  });
980
- const signProof = signProofFromCeremonyPayload(payload);
1368
+ const receipt = receiptFromCeremonyPayload(payload);
981
1369
  const body = {
982
1370
  v: 1,
983
1371
  kind: "anchor",
984
1372
  domain: args.domain.trim().toLowerCase(),
985
- sign_proof: signProof,
1373
+ receipt,
986
1374
  nonce: args.nonce,
987
1375
  exp: args.exp,
988
1376
  iat: Math.floor(Date.now() / 1e3)
@@ -999,18 +1387,29 @@ function createSetupClient(options = {}) {
999
1387
  txt_value,
1000
1388
  human: {
1001
1389
  needs_human: "dns",
1002
- message: "Publish the well-known JSON and TXT, then call org_verify_anchor."
1390
+ 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
1391
  }
1004
1392
  }
1005
1393
  };
1006
1394
  },
1007
1395
  async orgVerifyAnchor(args) {
1396
+ const checked = checkOrgCreationTerms(args);
1397
+ if (!checked.ok) return checked;
1398
+ const { incorporation } = checked;
1008
1399
  const auth = await requireSession({ origins, sessionPath });
1009
1400
  if (!auth.ok) return auth;
1010
1401
  try {
1011
- const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, args);
1402
+ const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, {
1403
+ domain: args.domain,
1404
+ nonce: args.nonce,
1405
+ name: args.name,
1406
+ incorporation,
1407
+ acceptCustomerTerms: args.acceptCustomerTerms
1408
+ });
1012
1409
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
1013
1410
  } catch (e) {
1411
+ const refusal = orgCreationRefusal(e, incorporation);
1412
+ if (refusal) return refusal;
1014
1413
  return {
1015
1414
  ok: false,
1016
1415
  error: e instanceof Error ? e.message : String(e),
@@ -1034,18 +1433,10 @@ function createSetupClient(options = {}) {
1034
1433
  if (noop.already_active) return { ok: true, data: noop };
1035
1434
  } catch {
1036
1435
  }
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
1436
  const cer = await runPasskeyCeremony({
1045
1437
  origins: auth.data.origins,
1046
1438
  bearer: auth.data.session.accessToken,
1047
- purpose: "org.policy.bootstrap",
1048
- messageDigest: digest,
1439
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
1049
1440
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
1050
1441
  openBrowserFlag
1051
1442
  });
@@ -1058,24 +1449,126 @@ function createSetupClient(options = {}) {
1058
1449
  );
1059
1450
  return { ok: true, data: out };
1060
1451
  },
1061
- async cardCheckout(orgId) {
1452
+ async incorporationSet(args) {
1453
+ const checked = checkOrgCreationTerms(args, INCORPORATION_TERMS_HUMAN);
1454
+ if (!checked.ok) return checked;
1455
+ const code = checked.incorporation;
1456
+ const auth = await requireSession({ origins, sessionPath });
1457
+ if (!auth.ok) return auth;
1458
+ const sub = auth.data.session.sub;
1459
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1460
+ const apiOrigin = auth.data.origins.apiOrigin;
1461
+ const bearer = auth.data.session.accessToken;
1462
+ const card = await getCard(apiOrigin, bearer, args.orgId);
1463
+ const current = card.incorporation;
1464
+ if (current?.code === code && current.terms_current) {
1465
+ return { ok: true, data: { incorporation: current, unchanged: true } };
1466
+ }
1467
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1468
+ if (closed.includes(code) && current?.code !== code) return declarationRegionClosedRefusal(code);
1469
+ const cer = await runPasskeyCeremony({
1470
+ origins: auth.data.origins,
1471
+ bearer,
1472
+ statement: orgCardIncorporationStatement({
1473
+ org: args.orgId,
1474
+ code,
1475
+ customerTerms: card.acceptance.customer_terms_version,
1476
+ dpa: card.acceptance.dpa_version
1477
+ }),
1478
+ displayHint: `Declare ${code} as the place of incorporation`,
1479
+ openBrowserFlag
1480
+ });
1481
+ const proof = await cer.wait();
1482
+ try {
1483
+ const out = await postCardIncorporation(apiOrigin, bearer, args.orgId, { code, receipt: proof });
1484
+ return { ok: true, data: { incorporation: out.incorporation } };
1485
+ } catch (e) {
1486
+ const refusal = incorporationSetRefusal(e, code);
1487
+ if (refusal) return refusal;
1488
+ throw e;
1489
+ }
1490
+ },
1491
+ async cardCheckout(orgId, opts = {}) {
1492
+ const offer = opts.offer === "bundle" ? "bundle" : "meter";
1493
+ const lang = checkoutLang(opts.lang);
1062
1494
  const auth = await requireSession({ origins, sessionPath });
1063
1495
  if (!auth.ok) return auth;
1064
- const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
1496
+ const sub = auth.data.session.sub;
1497
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1498
+ const apiOrigin = auth.data.origins.apiOrigin;
1499
+ const bearer = auth.data.session.accessToken;
1500
+ const card = await getCard(apiOrigin, bearer, orgId);
1501
+ if (card.suspended) return { ok: false, error: "org_suspended" };
1502
+ const signature = card.capabilities?.signature;
1503
+ const open = offer === "bundle" ? signature?.bundle_checkout_open : signature?.checkout_open;
1504
+ if (!signature || open !== true) {
1505
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
1506
+ }
1507
+ const blockers = signature.blockers ?? [];
1508
+ const subscribed = offer === "bundle" ? signature.tariff === "bundle" : !blockers.includes("subscription");
1509
+ if (subscribed) {
1510
+ const state = blockers.length > 0 ? ` (${blockers.join(", ")})` : "";
1511
+ return {
1512
+ ok: false,
1513
+ error: `already_subscribed \u2014 the signature card already has this subscription${state}. Manage it on developers.`
1514
+ };
1515
+ }
1516
+ const incorporation = card.incorporation;
1517
+ if (!incorporation) return incorporationNeededRefusal(orgId, false);
1518
+ if (!incorporation.terms_current) return incorporationNeededRefusal(orgId, true);
1519
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1520
+ if (closed.includes(incorporation.code)) return purchaseRegionClosedRefusal(incorporation.code);
1521
+ if (opts.consentBillingData !== true) {
1522
+ return { ok: false, error: "billing_data_consent_required", human: billingConsentHuman(card.acceptance, lang) };
1523
+ }
1524
+ const cer = await runPasskeyCeremony({
1525
+ origins: auth.data.origins,
1526
+ bearer,
1527
+ statement: orgCardCheckoutStatement({
1528
+ org: orgId,
1529
+ capability: "signature",
1530
+ offer,
1531
+ customerTerms: card.acceptance.customer_terms_version,
1532
+ dpa: card.acceptance.dpa_version
1533
+ }),
1534
+ displayHint: offer === "bundle" ? "Subscribe to the signature card (monthly bundle)" : "Subscribe to the signature card",
1535
+ openBrowserFlag
1536
+ });
1537
+ const proof = await cer.wait();
1538
+ let url;
1539
+ try {
1540
+ ({ url } = await postCardCheckout(apiOrigin, bearer, orgId, {
1541
+ capability: "signature",
1542
+ offer,
1543
+ consentBillingData: true,
1544
+ uiLocale: lang,
1545
+ receipt: proof
1546
+ }));
1547
+ } catch (e) {
1548
+ const refusal = checkoutRefusal(e, { orgId, incorporation: incorporation.code });
1549
+ if (refusal) return refusal;
1550
+ throw e;
1551
+ }
1552
+ let checkoutUrl;
1553
+ try {
1554
+ checkoutUrl = assertCardCheckoutBrowserUrl(url);
1555
+ } catch (e) {
1556
+ return { ok: false, error: e instanceof Error ? e.message : "checkout_url_rejected" };
1557
+ }
1065
1558
  if (openBrowserFlag) {
1066
1559
  try {
1067
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1560
+ await openBrowser(checkoutUrl);
1068
1561
  } catch {
1069
1562
  }
1070
1563
  }
1071
1564
  return {
1072
1565
  ok: true,
1073
1566
  data: {
1074
- url,
1567
+ url: checkoutUrl,
1075
1568
  human: {
1076
1569
  needs_human: "payment",
1077
1570
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
1078
- open_url: url
1571
+ open_url: checkoutUrl
1079
1572
  }
1080
1573
  }
1081
1574
  };
@@ -1092,26 +1585,24 @@ function createSetupClient(options = {}) {
1092
1585
  v: 1,
1093
1586
  host: args.host.trim().toLowerCase(),
1094
1587
  display_name: args.displayName.trim(),
1095
- intent_types: args.intentTypes ?? ["generic.sign"],
1588
+ intent_types: args.intentTypes ?? ["generic_sign"],
1096
1589
  max_ttl_seconds: 300,
1097
1590
  operate_kid: keys.kid,
1098
1591
  operate_public_jwk: keys.publicJwk,
1099
1592
  redirect_paths: paths
1100
1593
  };
1101
1594
  const payload_hash = await computePayloadCommitmentHex(manifest);
1102
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
1103
1595
  const cer = await runPasskeyCeremony({
1104
1596
  origins: auth.data.origins,
1105
1597
  bearer: auth.data.session.accessToken,
1106
- purpose: "org.app.register",
1107
- messageDigest: digest,
1598
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
1108
1599
  displayHint: `Register App ${manifest.host}`,
1109
1600
  openBrowserFlag
1110
1601
  });
1111
1602
  const proof = await cer.wait();
1112
1603
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
1113
1604
  ...manifest,
1114
- proposer_sign_proof: proof
1605
+ proposer_receipt: proof
1115
1606
  });
1116
1607
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
1117
1608
  return {
@@ -1156,17 +1647,10 @@ function createSetupClient(options = {}) {
1156
1647
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1157
1648
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1158
1649
  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
1650
  const cer = await runPasskeyCeremony({
1166
1651
  origins: auth.data.origins,
1167
1652
  bearer: auth.data.session.accessToken,
1168
- purpose: "org.app.verify_host",
1169
- messageDigest: digest,
1653
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1170
1654
  displayHint: `Verify host ${ch.host}`,
1171
1655
  openBrowserFlag
1172
1656
  });
@@ -1195,21 +1679,11 @@ function createSetupClient(options = {}) {
1195
1679
  async declarationSet(args) {
1196
1680
  const auth = await requireSession({ origins, sessionPath });
1197
1681
  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
1682
  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
1683
  const cer = await runPasskeyCeremony({
1209
1684
  origins: auth.data.origins,
1210
1685
  bearer: auth.data.session.accessToken,
1211
- purpose: "org.app.declaration",
1212
- messageDigest: digest,
1686
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1213
1687
  displayHint: `Declare uses for App ${args.appId}`,
1214
1688
  openBrowserFlag
1215
1689
  });
@@ -1219,10 +1693,47 @@ function createSetupClient(options = {}) {
1219
1693
  auth.data.session.accessToken,
1220
1694
  args.orgId,
1221
1695
  args.appId,
1222
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1696
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1223
1697
  );
1224
1698
  return { ok: true, data: { declaration: out.declaration } };
1225
1699
  },
1700
+ async appRegionsSet(args) {
1701
+ const read = readAppRegionsInput(args.regions);
1702
+ if (!read.ok) return read;
1703
+ const regions = read.regions;
1704
+ const auth = await requireSession({ origins, sessionPath });
1705
+ if (!auth.ok) return auth;
1706
+ const sub = auth.data.session.sub;
1707
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1708
+ const apiOrigin = auth.data.origins.apiOrigin;
1709
+ const bearer = auth.data.session.accessToken;
1710
+ const app = await getApp(apiOrigin, bearer, args.orgId, args.appId);
1711
+ if (app.status === "disabled") return appDisabledRefusal();
1712
+ if (sameAppRegions(app.accepted_regions, regions)) {
1713
+ return { ok: true, data: { accepted_regions: regions, unchanged: true } };
1714
+ }
1715
+ if (regions) {
1716
+ const selectable = await getSelectableAppRegions(apiOrigin).catch(() => null);
1717
+ const closed = selectable ? regions.filter((region) => !selectable.includes(region)) : [];
1718
+ if (closed.length > 0) return regionNotOpenRefusal(closed, selectable);
1719
+ }
1720
+ const cer = await runPasskeyCeremony({
1721
+ origins: auth.data.origins,
1722
+ bearer,
1723
+ statement: orgAppRegionsStatement({ org: args.orgId, app: args.appId, regions }),
1724
+ displayHint: regions ? `Accept new connections to ${app.host} from ${regions.join(", ")} only` : `Accept new connections to ${app.host} from every region Clavis accepts`,
1725
+ openBrowserFlag
1726
+ });
1727
+ const proof = await cer.wait();
1728
+ try {
1729
+ await putAppRegions(apiOrigin, bearer, args.orgId, args.appId, { regions, receipt: proof });
1730
+ return { ok: true, data: { accepted_regions: regions } };
1731
+ } catch (e) {
1732
+ const refusal = appRegionsRefusal(e, regions ?? []);
1733
+ if (refusal) return refusal;
1734
+ throw e;
1735
+ }
1736
+ },
1226
1737
  async emitEnv(args) {
1227
1738
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1228
1739
  if (!jwk) {
@@ -1231,7 +1742,7 @@ function createSetupClient(options = {}) {
1231
1742
  error: "operate_jwk_missing",
1232
1743
  human: {
1233
1744
  needs_human: "login",
1234
- message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
1745
+ message: "Run app-register first so the operate key exists under ~/.config/clavis/apps/"
1235
1746
  }
1236
1747
  };
1237
1748
  }
@@ -1247,15 +1758,18 @@ function createSetupClient(options = {}) {
1247
1758
  }
1248
1759
  var init_setup_client = __esm({
1249
1760
  "src/setup-client.ts"() {
1761
+ init_app_regions();
1250
1762
  init_browser();
1763
+ init_card();
1251
1764
  init_safe_browser_url();
1252
- init_digests();
1765
+ init_statements();
1253
1766
  init_ceremony();
1254
1767
  init_emit_env();
1255
1768
  init_operate_key_store();
1256
1769
  init_keys();
1257
1770
  init_login();
1258
1771
  init_org_api();
1772
+ init_org_creation();
1259
1773
  init_session_store();
1260
1774
  init_status();
1261
1775
  }
@@ -1295,11 +1809,17 @@ var init_redact_transport = __esm({
1295
1809
  }
1296
1810
  });
1297
1811
 
1298
- // src/mcp.ts
1299
- var mcp_exports = {};
1300
- __export(mcp_exports, {
1812
+ // src/mcp-server.ts
1813
+ var mcp_server_exports = {};
1814
+ __export(mcp_server_exports, {
1301
1815
  runMcpServer: () => runMcpServer
1302
1816
  });
1817
+ function orgCreationTerms(args) {
1818
+ return {
1819
+ incorporation: typeof args.incorporation === "string" ? args.incorporation : void 0,
1820
+ acceptCustomerTerms: args.accept_customer_terms === true
1821
+ };
1822
+ }
1303
1823
  async function dispatch(client, name, args) {
1304
1824
  switch (name) {
1305
1825
  case "clavis_setup_status":
@@ -1309,7 +1829,11 @@ async function dispatch(client, name, args) {
1309
1829
  args.bridge_json ? { bridgeJson: String(args.bridge_json) } : void 0
1310
1830
  );
1311
1831
  case "clavis_org_anchor_plan":
1312
- return client.orgAnchorPlan(String(args.domain), args.name ? String(args.name) : void 0);
1832
+ return client.orgAnchorPlan(
1833
+ String(args.domain),
1834
+ args.name ? String(args.name) : void 0,
1835
+ orgCreationTerms(args)
1836
+ );
1313
1837
  case "clavis_org_anchor_finish":
1314
1838
  return client.orgAnchorFinish({
1315
1839
  domain: String(args.domain),
@@ -1323,12 +1847,19 @@ async function dispatch(client, name, args) {
1323
1847
  return client.orgVerifyAnchor({
1324
1848
  domain: String(args.domain),
1325
1849
  nonce: String(args.nonce),
1326
- name: args.name ? String(args.name) : void 0
1850
+ name: args.name ? String(args.name) : void 0,
1851
+ ...orgCreationTerms(args)
1327
1852
  });
1328
1853
  case "clavis_policy_bootstrap":
1329
1854
  return client.policyBootstrap(String(args.org_id));
1855
+ case "clavis_incorporation_set":
1856
+ return client.incorporationSet({ orgId: String(args.org_id), ...orgCreationTerms(args) });
1330
1857
  case "clavis_card_checkout":
1331
- return client.cardCheckout(String(args.org_id));
1858
+ return client.cardCheckout(String(args.org_id), {
1859
+ offer: args.offer === "bundle" ? "bundle" : "meter",
1860
+ lang: checkoutLang(args.lang),
1861
+ consentBillingData: args.consent_billing_data === true
1862
+ });
1332
1863
  case "clavis_app_register":
1333
1864
  return client.appRegister({
1334
1865
  orgId: String(args.org_id),
@@ -1340,6 +1871,14 @@ async function dispatch(client, name, args) {
1340
1871
  return client.appHostPlan(String(args.org_id), String(args.app_id));
1341
1872
  case "clavis_app_verify_host":
1342
1873
  return client.appVerifyHost({ orgId: String(args.org_id), appId: String(args.app_id) });
1874
+ case "clavis_app_regions_set": {
1875
+ const choice = chooseAppRegions({
1876
+ ...args.regions !== void 0 ? { regions: Array.isArray(args.regions) ? args.regions.map((code) => String(code)) : [] } : {},
1877
+ all: args.all === true
1878
+ });
1879
+ if (!choice.ok) return choice;
1880
+ return client.appRegionsSet({ orgId: String(args.org_id), appId: String(args.app_id), regions: choice.regions });
1881
+ }
1343
1882
  case "clavis_declaration_set":
1344
1883
  return client.declarationSet({
1345
1884
  orgId: String(args.org_id),
@@ -1349,8 +1888,7 @@ async function dispatch(client, name, args) {
1349
1888
  });
1350
1889
  case "clavis_emit_app_env":
1351
1890
  return client.emitEnv({
1352
- appId: String(args.app_id),
1353
- operatePrivateJwkJson: typeof args.operate_private_jwk === "string" ? args.operate_private_jwk : void 0
1891
+ appId: String(args.app_id)
1354
1892
  });
1355
1893
  default:
1356
1894
  throw new Error(`unknown tool: ${name}`);
@@ -1385,17 +1923,29 @@ async function runMcpServer() {
1385
1923
  const transport = new StdioServerTransport();
1386
1924
  await server.connect(transport);
1387
1925
  }
1388
- var require2, PACKAGE_VERSION, TOOLS, isMain;
1389
- var init_mcp = __esm({
1390
- "src/mcp.ts"() {
1926
+ var require2, PACKAGE_VERSION, ORG_CREATION_PROPERTIES, TOOLS;
1927
+ var init_mcp_server = __esm({
1928
+ "src/mcp-server.ts"() {
1391
1929
  init_setup_client();
1930
+ init_app_regions();
1931
+ init_card();
1392
1932
  init_redact_transport();
1393
1933
  require2 = createRequire(import.meta.url);
1394
1934
  ({ version: PACKAGE_VERSION } = require2("../package.json"));
1935
+ ORG_CREATION_PROPERTIES = {
1936
+ incorporation: {
1937
+ type: "string",
1938
+ 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)."
1939
+ },
1940
+ accept_customer_terms: {
1941
+ type: "boolean",
1942
+ 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."
1943
+ }
1944
+ };
1395
1945
  TOOLS = [
1396
1946
  {
1397
1947
  name: "clavis_setup_status",
1398
- description: "List Org, App, signature card, and declaration readiness for the logged-in developers session.",
1948
+ description: "List Org, App, signature card (with what holds it back), place of incorporation, and declaration readiness for the logged-in developers session.",
1399
1949
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
1400
1950
  },
1401
1951
  {
@@ -1414,12 +1964,13 @@ var init_mcp = __esm({
1414
1964
  },
1415
1965
  {
1416
1966
  name: "clavis_org_anchor_plan",
1417
- description: "Start the Org DNS anchor challenge and open Passkey confirmation. Returns a ticket and human action.",
1967
+ 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
1968
  inputSchema: {
1419
1969
  type: "object",
1420
1970
  properties: {
1421
1971
  domain: { type: "string" },
1422
- name: { type: "string" }
1972
+ name: { type: "string" },
1973
+ ...ORG_CREATION_PROPERTIES
1423
1974
  },
1424
1975
  required: ["domain"],
1425
1976
  additionalProperties: false
@@ -1444,13 +1995,14 @@ var init_mcp = __esm({
1444
1995
  },
1445
1996
  {
1446
1997
  name: "clavis_org_verify_anchor",
1447
- description: "Verify the Org DNS anchor after TXT and well-known are published.",
1998
+ 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
1999
  inputSchema: {
1449
2000
  type: "object",
1450
2001
  properties: {
1451
2002
  domain: { type: "string" },
1452
2003
  nonce: { type: "string" },
1453
- name: { type: "string" }
2004
+ name: { type: "string" },
2005
+ ...ORG_CREATION_PROPERTIES
1454
2006
  },
1455
2007
  required: ["domain", "nonce"],
1456
2008
  additionalProperties: false
@@ -1466,12 +2018,41 @@ var init_mcp = __esm({
1466
2018
  additionalProperties: false
1467
2019
  }
1468
2020
  },
2021
+ {
2022
+ name: "clavis_incorporation_set",
2023
+ 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.",
2024
+ inputSchema: {
2025
+ type: "object",
2026
+ properties: {
2027
+ org_id: { type: "string" },
2028
+ ...ORG_CREATION_PROPERTIES
2029
+ },
2030
+ required: ["org_id"],
2031
+ additionalProperties: false
2032
+ }
2033
+ },
1469
2034
  {
1470
2035
  name: "clavis_card_checkout",
1471
- description: "Open the checkout URL for the signature card.",
2036
+ 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
2037
  inputSchema: {
1473
2038
  type: "object",
1474
- properties: { org_id: { type: "string" } },
2039
+ properties: {
2040
+ org_id: { type: "string" },
2041
+ offer: {
2042
+ type: "string",
2043
+ enum: ["meter", "bundle"],
2044
+ description: "meter (pay per use, default) or bundle (monthly bundle)."
2045
+ },
2046
+ lang: {
2047
+ type: "string",
2048
+ enum: ["en", "ja"],
2049
+ description: "Language of the consent statement shown to the customer (default en). The purchase record keeps this language."
2050
+ },
2051
+ consent_billing_data: {
2052
+ type: "boolean",
2053
+ description: "true only after the customer (a human) has read the consent statement and consented. Ask them; never set it on their behalf."
2054
+ }
2055
+ },
1475
2056
  required: ["org_id"],
1476
2057
  additionalProperties: false
1477
2058
  }
@@ -1511,6 +2092,29 @@ var init_mcp = __esm({
1511
2092
  additionalProperties: false
1512
2093
  }
1513
2094
  },
2095
+ {
2096
+ name: "clavis_app_regions_set",
2097
+ 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.",
2098
+ inputSchema: {
2099
+ type: "object",
2100
+ properties: {
2101
+ org_id: { type: "string" },
2102
+ app_id: { type: "string" },
2103
+ regions: {
2104
+ type: "array",
2105
+ items: { type: "string", enum: [...APP_REGIONS] },
2106
+ minItems: 1,
2107
+ description: "JP, US, GB, EEA. New connections from anywhere else are refused."
2108
+ },
2109
+ all: {
2110
+ type: "boolean",
2111
+ description: "true to accept every region Clavis accepts (removes the App's list)."
2112
+ }
2113
+ },
2114
+ required: ["org_id", "app_id"],
2115
+ additionalProperties: false
2116
+ }
2117
+ },
1514
2118
  {
1515
2119
  name: "clavis_declaration_set",
1516
2120
  description: "Replace the App use declaration (Passkey). uses becomes the whole declaration. Include every capability to keep. Signature requests need a signature use.",
@@ -1542,27 +2146,72 @@ var init_mcp = __esm({
1542
2146
  inputSchema: {
1543
2147
  type: "object",
1544
2148
  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
- }
2149
+ app_id: { type: "string" }
1550
2150
  },
1551
2151
  required: ["app_id"],
1552
2152
  additionalProperties: false
1553
2153
  }
1554
2154
  }
1555
2155
  ];
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
2156
  }
1564
2157
  });
1565
2158
 
2159
+ // src/cli-args.ts
2160
+ init_app_regions();
2161
+ function flag(args, name) {
2162
+ const i = args.indexOf(name);
2163
+ if (i < 0) return void 0;
2164
+ return args[i + 1];
2165
+ }
2166
+ function hasFlag(args, name) {
2167
+ return args.includes(name);
2168
+ }
2169
+ function positionals(args, valueFlags) {
2170
+ const out = [];
2171
+ for (let i = 0; i < args.length; i++) {
2172
+ const arg = args[i];
2173
+ if (valueFlags.includes(arg)) {
2174
+ i++;
2175
+ continue;
2176
+ }
2177
+ if (arg.startsWith("--")) continue;
2178
+ out.push(arg);
2179
+ }
2180
+ return out;
2181
+ }
2182
+ function orgCreationTermsFromArgs(args) {
2183
+ return {
2184
+ incorporation: flag(args, "--incorporation"),
2185
+ acceptCustomerTerms: hasFlag(args, "--accept-customer-terms")
2186
+ };
2187
+ }
2188
+ function cardCheckoutOptionsFromArgs(args) {
2189
+ const offer = flag(args, "--offer");
2190
+ if (offer !== void 0 && offer !== "meter" && offer !== "bundle") {
2191
+ return { ok: false, error: "--offer must be meter or bundle" };
2192
+ }
2193
+ const lang = flag(args, "--lang");
2194
+ if (lang !== void 0 && lang !== "en" && lang !== "ja") {
2195
+ return { ok: false, error: "--lang must be en or ja" };
2196
+ }
2197
+ return {
2198
+ ok: true,
2199
+ options: {
2200
+ ...offer ? { offer } : {},
2201
+ ...lang ? { lang } : {},
2202
+ consentBillingData: hasFlag(args, "--consent-billing-data")
2203
+ }
2204
+ };
2205
+ }
2206
+ function appRegionsFromArgs(args) {
2207
+ const raw = flag(args, "--regions");
2208
+ const listed = args.includes("--regions");
2209
+ return chooseAppRegions({
2210
+ ...listed ? { regions: (raw ?? "").split(",").filter((code) => code.trim().length > 0) } : {},
2211
+ all: hasFlag(args, "--all")
2212
+ });
2213
+ }
2214
+
1566
2215
  // src/cli.ts
1567
2216
  init_setup_client();
1568
2217
  init_redact_transport();
@@ -1571,34 +2220,38 @@ function printJson(value) {
1571
2220
  }
1572
2221
  function usage() {
1573
2222
  console.error(`Usage:
1574
- clavis login [--bridge-json '<json>' | --bridge-json-file <path>]
2223
+ clavis login [--bridge-json-file <path>]
1575
2224
  clavis logout
1576
2225
  clavis status
1577
2226
  clavis mcp
1578
- clavis org-anchor-plan <domain> [name]
2227
+ clavis org-anchor-plan <domain> [name] --incorporation CODE --accept-customer-terms
1579
2228
  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]
2229
+ clavis org-verify-anchor --domain D --nonce N --incorporation CODE --accept-customer-terms [--name N]
1581
2230
  clavis policy-bootstrap <orgId>
1582
- clavis card-checkout <orgId>
2231
+ clavis incorporation-set <orgId> --incorporation CODE --accept-customer-terms
2232
+ clavis card-checkout <orgId> --consent-billing-data [--offer meter|bundle] [--lang en|ja]
1583
2233
  clavis app-register --org O --host H --name N [--redirect /done]
1584
2234
  clavis app-host-plan <orgId> <appId>
1585
2235
  clavis app-verify-host <orgId> <appId>
2236
+ clavis app-regions-set <orgId> <appId> (--regions JP,US | --all)
1586
2237
  clavis declaration-set --org O --app A --end-users TEXT --use signature=OP
1587
- clavis emit-env --app A [--operate-jwk '{"kty":"..."}']
2238
+ clavis emit-env --app A
1588
2239
 
1589
- login: opens developers /setup/login, then paste the JSON from the page (or pass --bridge-json).
2240
+ login: opens developers /setup/login, then paste the JSON from the page (or pass --bridge-json-file).
2241
+ Do not pass the access token or operate private key as a command-line argument.
2242
+ 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.
2243
+ --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.
2244
+ A place of incorporation that is closed to new Orgs right now is refused before Passkey.
2245
+ incorporation-set declares the place again after the Customer Terms change (status shows terms_current false). It needs the customer's agreement too.
2246
+ 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.
1590
2247
  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.
2248
+ 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.
2249
+ 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
2250
 
1593
2251
  Env: CLAVIS_API_ORIGIN CLAVIS_ID_ORIGIN CLAVIS_DEVELOPERS_ORIGIN CLAVIS_SESSION_PATH
1594
2252
  `);
1595
2253
  process.exit(2);
1596
2254
  }
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
2255
  function requireFlag(args, name) {
1603
2256
  const v = flag(args, name);
1604
2257
  if (!v) {
@@ -1613,14 +2266,19 @@ async function main() {
1613
2266
  const client = createSetupClient();
1614
2267
  switch (cmd) {
1615
2268
  case "mcp": {
1616
- const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
2269
+ const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp_server(), mcp_server_exports));
1617
2270
  await runMcpServer2();
1618
2271
  return;
1619
2272
  }
1620
2273
  case "login": {
1621
- const fromFlag = flag(rest, "--bridge-json");
2274
+ if (flag(rest, "--bridge-json")) {
2275
+ console.error(
2276
+ "refusing --bridge-json: the access token would be visible in the process list. Use --bridge-json-file or paste on stdin."
2277
+ );
2278
+ process.exit(2);
2279
+ }
1622
2280
  const fromFile = flag(rest, "--bridge-json-file");
1623
- let bridgeJson = fromFlag;
2281
+ let bridgeJson;
1624
2282
  if (fromFile) {
1625
2283
  const { readFile: readFile4 } = await import('fs/promises');
1626
2284
  bridgeJson = await readFile4(fromFile, "utf8");
@@ -1635,9 +2293,9 @@ async function main() {
1635
2293
  printJson(await client.status());
1636
2294
  return;
1637
2295
  case "org-anchor-plan": {
1638
- const domain = rest[0];
2296
+ const [domain, name] = positionals(rest, ["--incorporation"]);
1639
2297
  if (!domain) usage();
1640
- printJson(await client.orgAnchorPlan(domain, rest[1]));
2298
+ printJson(await client.orgAnchorPlan(domain, name, orgCreationTermsFromArgs(rest)));
1641
2299
  return;
1642
2300
  }
1643
2301
  case "org-anchor-finish":
@@ -1657,7 +2315,8 @@ async function main() {
1657
2315
  await client.orgVerifyAnchor({
1658
2316
  domain: requireFlag(rest, "--domain"),
1659
2317
  nonce: requireFlag(rest, "--nonce"),
1660
- name: flag(rest, "--name")
2318
+ name: flag(rest, "--name"),
2319
+ ...orgCreationTermsFromArgs(rest)
1661
2320
  })
1662
2321
  );
1663
2322
  return;
@@ -1667,10 +2326,21 @@ async function main() {
1667
2326
  printJson(await client.policyBootstrap(orgId));
1668
2327
  return;
1669
2328
  }
2329
+ case "incorporation-set": {
2330
+ const [orgId] = positionals(rest, ["--incorporation"]);
2331
+ if (!orgId) usage();
2332
+ printJson(await client.incorporationSet({ orgId, ...orgCreationTermsFromArgs(rest) }));
2333
+ return;
2334
+ }
1670
2335
  case "card-checkout": {
1671
- const orgId = rest[0];
2336
+ const [orgId] = positionals(rest, ["--offer", "--lang"]);
1672
2337
  if (!orgId) usage();
1673
- printJson(await client.cardCheckout(orgId));
2338
+ const opts = cardCheckoutOptionsFromArgs(rest);
2339
+ if (!opts.ok) {
2340
+ console.error(opts.error);
2341
+ usage();
2342
+ }
2343
+ printJson(await client.cardCheckout(orgId, opts.options));
1674
2344
  return;
1675
2345
  }
1676
2346
  case "app-register":
@@ -1695,6 +2365,17 @@ async function main() {
1695
2365
  printJson(await client.appVerifyHost({ orgId, appId }));
1696
2366
  return;
1697
2367
  }
2368
+ case "app-regions-set": {
2369
+ const [orgId, appId] = positionals(rest, ["--regions"]);
2370
+ if (!orgId || !appId) usage();
2371
+ const choice = appRegionsFromArgs(rest);
2372
+ if (!choice.ok) {
2373
+ console.error(choice.error);
2374
+ usage();
2375
+ }
2376
+ printJson(await client.appRegionsSet({ orgId, appId, regions: choice.regions }));
2377
+ return;
2378
+ }
1698
2379
  case "declaration-set": {
1699
2380
  const useRaw = requireFlag(rest, "--use");
1700
2381
  const [capability, ...opParts] = useRaw.split("=");
@@ -1711,10 +2392,15 @@ async function main() {
1711
2392
  return;
1712
2393
  }
1713
2394
  case "emit-env":
2395
+ if (flag(rest, "--operate-jwk")) {
2396
+ console.error(
2397
+ "refusing --operate-jwk: the private key would be visible in the process list. app-register saves it under ~/.config/clavis/apps/."
2398
+ );
2399
+ process.exit(2);
2400
+ }
1714
2401
  printJson(
1715
2402
  await client.emitEnv({
1716
- appId: requireFlag(rest, "--app"),
1717
- operatePrivateJwkJson: flag(rest, "--operate-jwk")
2403
+ appId: requireFlag(rest, "--app")
1718
2404
  })
1719
2405
  );
1720
2406
  return;