@clavis.nexus/setup 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,49 +1,456 @@
1
1
  #!/usr/bin/env node
2
+ import { realpathSync } from 'fs';
3
+ import { fileURLToPath } from 'url';
2
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
5
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
6
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
5
7
  import { createRequire } from 'module';
6
- import { pathToFileURL } from 'url';
7
8
  import { execFile } from 'child_process';
8
9
  import { promisify } from 'util';
9
- import { readFile, mkdir, writeFile, chmod, unlink } from 'fs/promises';
10
- import { dirname, join } from 'path';
10
+ import { readFile, chmod, unlink, mkdir, writeFile, lstat } from 'fs/promises';
11
+ import path, { dirname, join, resolve, relative, isAbsolute } from 'path';
11
12
  import { homedir } from 'os';
12
13
  import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
13
- import { createServer } from 'http';
14
+ import { createInterface } from 'readline/promises';
15
+ import { stdin, stdout } from 'process';
14
16
  import { randomBytes } from 'crypto';
15
17
 
18
+ // src/org-api.ts
19
+ var SetupApiError = class extends Error {
20
+ status;
21
+ code;
22
+ constructor(status, code, message) {
23
+ super(message);
24
+ this.name = "SetupApiError";
25
+ this.status = status;
26
+ this.code = code;
27
+ }
28
+ };
29
+ async function apiJson(apiOrigin, path2, opts) {
30
+ const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path2}`, {
31
+ method: opts.method ?? "GET",
32
+ redirect: "error",
33
+ headers: {
34
+ Accept: "application/json",
35
+ ...opts.bearer !== void 0 ? { Authorization: `Bearer ${opts.bearer}` } : {},
36
+ ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
37
+ },
38
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
39
+ });
40
+ const body = await res.json().catch(() => null);
41
+ if (!res.ok) {
42
+ const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
43
+ const message = typeof body?.message === "string" ? body.message : code;
44
+ throw new SetupApiError(res.status, code, message);
45
+ }
46
+ return body ?? {};
47
+ }
48
+ async function listOrgs(apiOrigin, bearer) {
49
+ const r = await apiJson(apiOrigin, "/orgs", { bearer });
50
+ return r.orgs ?? [];
51
+ }
52
+ async function getOrg(apiOrigin, bearer, orgId) {
53
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
54
+ }
55
+ function stringList(value) {
56
+ return Array.isArray(value) ? value.filter((code) => typeof code === "string") : [];
57
+ }
58
+ async function getOrgRegions(apiOrigin) {
59
+ const r = await apiJson(
60
+ apiOrigin,
61
+ "/orgs/regions",
62
+ {}
63
+ );
64
+ return r.payload ?? {};
65
+ }
66
+ async function getClosedIncorporations(apiOrigin) {
67
+ return stringList((await getOrgRegions(apiOrigin)).closed_incorporations);
68
+ }
69
+ async function getSelectableAppRegions(apiOrigin) {
70
+ return stringList((await getOrgRegions(apiOrigin)).app_regions);
71
+ }
72
+ async function postDnsChallenge(apiOrigin, bearer, args) {
73
+ return apiJson(apiOrigin, "/orgs/dns/challenge", {
74
+ method: "POST",
75
+ bearer,
76
+ body: {
77
+ domain: args.domain.trim(),
78
+ kind: args.kind ?? "anchor",
79
+ ...args.incorporation !== void 0 ? { incorporation: args.incorporation } : {}
80
+ }
81
+ });
82
+ }
83
+ async function postVerifyAnchor(apiOrigin, bearer, args) {
84
+ return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
85
+ method: "POST",
86
+ bearer,
87
+ body: {
88
+ domain: args.domain.trim(),
89
+ nonce: args.nonce,
90
+ ...args.name ? { name: args.name.trim() } : {},
91
+ accept_customer_terms: args.acceptCustomerTerms === true,
92
+ ...args.incorporation !== void 0 ? { incorporation: args.incorporation } : {}
93
+ }
94
+ });
95
+ }
96
+ async function postPolicyBootstrap(apiOrigin, bearer, orgId, receipt) {
97
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
98
+ method: "POST",
99
+ bearer,
100
+ body: receipt ? { receipt } : {}
101
+ });
102
+ }
103
+ async function listApps(apiOrigin, bearer, orgId) {
104
+ const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
105
+ bearer
106
+ });
107
+ return r.apps ?? [];
108
+ }
109
+ async function getApp(apiOrigin, bearer, orgId, appId) {
110
+ const r = await apiJson(
111
+ apiOrigin,
112
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
113
+ { bearer }
114
+ );
115
+ return r.app;
116
+ }
117
+ async function postAppRegister(apiOrigin, bearer, orgId, payload) {
118
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
119
+ method: "POST",
120
+ bearer,
121
+ body: payload
122
+ });
123
+ }
124
+ async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
125
+ return apiJson(
126
+ apiOrigin,
127
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
128
+ { bearer }
129
+ );
130
+ }
131
+ async function postVerifyHost(apiOrigin, bearer, orgId, appId, receipt) {
132
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
133
+ method: "POST",
134
+ bearer,
135
+ body: { receipt }
136
+ });
137
+ }
138
+ async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
139
+ return apiJson(
140
+ apiOrigin,
141
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
142
+ {
143
+ method: "PUT",
144
+ bearer,
145
+ body: {
146
+ endUsers: args.endUsers,
147
+ uses: args.uses,
148
+ receipt: args.receipt
149
+ }
150
+ }
151
+ );
152
+ }
153
+ async function putAppRegions(apiOrigin, bearer, orgId, appId, args) {
154
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/regions`, {
155
+ method: "PUT",
156
+ bearer,
157
+ body: { accepted_regions: args.regions, receipt: args.receipt }
158
+ });
159
+ }
160
+ async function getCard(apiOrigin, bearer, orgId) {
161
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
162
+ }
163
+ async function postCardIncorporation(apiOrigin, bearer, orgId, args) {
164
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/incorporation`, {
165
+ method: "POST",
166
+ bearer,
167
+ body: { code: args.code, receipt: args.receipt }
168
+ });
169
+ }
170
+ async function postCardCheckout(apiOrigin, bearer, orgId, args) {
171
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
172
+ method: "POST",
173
+ bearer,
174
+ body: {
175
+ capability: args.capability,
176
+ offer: args.offer,
177
+ consent: { polar_provision: args.consentBillingData },
178
+ ui_locale: args.uiLocale,
179
+ receipt: args.receipt
180
+ }
181
+ });
182
+ }
183
+ async function fetchJwksDocument(apiOrigin) {
184
+ const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
185
+ redirect: "error",
186
+ headers: { Accept: "application/json" }
187
+ });
188
+ if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
189
+ return res.json();
190
+ }
191
+ async function getMasterJwkJson(apiOrigin, masterPinJson) {
192
+ const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
193
+ const doc = await fetchJwksDocument(apiOrigin);
194
+ await verifySignedJwksDocument(doc, masterPinJson);
195
+ return JSON.stringify(doc.master);
196
+ }
197
+
198
+ // src/app-regions.ts
199
+ var APP_REGIONS = ["JP", "US", "GB", "EEA"];
200
+ var CHOICE_HINT = "Pass --regions with one or more of JP, US, GB, EEA (comma-separated), or --all (MCP: regions or all: true).";
201
+ function isAppRegion(value) {
202
+ return APP_REGIONS.includes(value);
203
+ }
204
+ function chooseAppRegions(input2) {
205
+ const listed = input2.regions !== void 0;
206
+ if (input2.all === true && listed) {
207
+ return { ok: false, error: `regions_conflict \u2014 pass either regions or all, not both. ${CHOICE_HINT}` };
208
+ }
209
+ if (input2.all === true) return { ok: true, regions: null };
210
+ if (!listed) return { ok: false, error: `regions_required \u2014 ${CHOICE_HINT}` };
211
+ return { ok: true, regions: input2.regions };
212
+ }
213
+ function readAppRegionsInput(raw) {
214
+ if (raw === null) return { ok: true, regions: null };
215
+ const codes = raw.map((code) => code.trim().toUpperCase());
216
+ if (codes.length === 0 || new Set(codes).size !== codes.length || !codes.every(isAppRegion)) {
217
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
218
+ }
219
+ return { ok: true, regions: APP_REGIONS.filter((region) => codes.includes(region)) };
220
+ }
221
+ function sameAppRegions(stored, next) {
222
+ const current = stored ?? null;
223
+ if (current === null || next === null) return current === next;
224
+ return current.length === next.length && current.every((region, i) => region === next[i]);
225
+ }
226
+ function regionNotOpenRefusal(closed, selectable) {
227
+ const open = selectable && selectable.length > 0 ? ` Regions you can choose now: ${selectable.join(", ")}.` : "";
228
+ return {
229
+ ok: false,
230
+ error: `region_not_open \u2014 Clavis is not accepting new connections from ${closed.join(", ")} right now, so an App cannot accept them.${open}`
231
+ };
232
+ }
233
+ function appDisabledRefusal() {
234
+ return { ok: false, error: "app_disabled \u2014 this App is disabled, so its regions cannot be changed." };
235
+ }
236
+ function appRegionsRefusal(e, regions) {
237
+ if (!(e instanceof SetupApiError)) return null;
238
+ switch (e.code) {
239
+ case "REGION_NOT_OPEN":
240
+ return regionNotOpenRefusal(regions, null);
241
+ case "REGIONS_INVALID":
242
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
243
+ case "APP_DISABLED":
244
+ return appDisabledRefusal();
245
+ case "FORBIDDEN":
246
+ return { ok: false, error: "forbidden \u2014 only an owner or admin of the Org can change the App's regions." };
247
+ default:
248
+ return null;
249
+ }
250
+ }
16
251
  var execFileAsync = promisify(execFile);
252
+ function isLoopbackHost(hostname) {
253
+ const host = hostname.toLowerCase();
254
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
255
+ }
256
+ function assertOpenableBrowserUrl(raw) {
257
+ let url;
258
+ try {
259
+ url = new URL(raw.trim());
260
+ } catch {
261
+ throw new Error("invalid URL");
262
+ }
263
+ if (url.username || url.password) throw new Error("URL must not contain credentials");
264
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost(url.hostname);
265
+ if (url.protocol !== "https:" && !loopbackHttp) {
266
+ throw new Error("only https URLs may be opened in a browser");
267
+ }
268
+ return url.toString();
269
+ }
270
+ function windowsBrowserArgs(raw) {
271
+ const url = assertOpenableBrowserUrl(raw);
272
+ const script = `Start-Process -FilePath '${url.replaceAll("'", "''")}'`;
273
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
274
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
275
+ }
17
276
  async function openBrowser(url) {
277
+ const safe = assertOpenableBrowserUrl(url);
18
278
  if (process.platform === "darwin") {
19
- await execFileAsync("open", [url]);
279
+ await execFileAsync("open", [safe]);
20
280
  return;
21
281
  }
22
282
  if (process.platform === "win32") {
23
- await execFileAsync("cmd", ["/c", "start", "", url]);
283
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
24
284
  return;
25
285
  }
26
- await execFileAsync("xdg-open", [url]);
286
+ await execFileAsync("xdg-open", [safe]);
287
+ }
288
+
289
+ // src/types.ts
290
+ var DEFAULT_ORIGINS = {
291
+ apiOrigin: "https://api.clavis.nexus",
292
+ idOrigin: "https://id.clavis.nexus",
293
+ developersOrigin: "https://developers.clavis.nexus"
294
+ };
295
+ var LEGAL_ORIGIN = "https://legal.clavis.nexus";
296
+
297
+ // src/org-creation.ts
298
+ var INCORPORATION_HINT = "JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)";
299
+ var TERMS_LINKS = `Customer Terms: ${LEGAL_ORIGIN}/en/customer-terms \u2014 DPA: ${LEGAL_ORIGIN}/en/dpa.`;
300
+ var TERMS_HUMAN = {
301
+ needs_human: "terms",
302
+ 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).`
303
+ };
304
+ var INCORPORATION_TERMS_HUMAN = {
305
+ needs_human: "terms",
306
+ 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).`
307
+ };
308
+ function normalizeIncorporation(raw) {
309
+ return (raw ?? "").trim().toUpperCase();
310
+ }
311
+ function checkOrgCreationTerms(terms, human = TERMS_HUMAN) {
312
+ if (terms.acceptCustomerTerms !== true) {
313
+ return { ok: false, error: "customer_terms_not_accepted", human };
314
+ }
315
+ const incorporation = normalizeIncorporation(terms.incorporation);
316
+ if (!incorporation) {
317
+ return {
318
+ ok: false,
319
+ error: `incorporation_required \u2014 pass --incorporation CODE (MCP: incorporation): ${INCORPORATION_HINT}`
320
+ };
321
+ }
322
+ return { ok: true, incorporation };
323
+ }
324
+ function regionClosedRefusal(incorporation) {
325
+ return {
326
+ ok: false,
327
+ error: `region_closed \u2014 Clavis is not accepting new Orgs incorporated in ${incorporation} right now. GET /orgs/regions lists the closed places.`
328
+ };
329
+ }
330
+ function orgCreationRefusal(e, incorporation) {
331
+ if (!(e instanceof SetupApiError)) return null;
332
+ if (e.status === 403 && e.code === "REGION_CLOSED") return regionClosedRefusal(incorporation);
333
+ if (e.code === "TERMS_REQUIRED") return { ok: false, error: "customer_terms_not_accepted", human: TERMS_HUMAN };
334
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
335
+ return null;
336
+ }
337
+ function incorporationInvalidRefusal(incorporation) {
338
+ return {
339
+ ok: false,
340
+ error: `incorporation_invalid \u2014 ${incorporation || "(empty)"} is not a place of incorporation Clavis accepts. Use ${INCORPORATION_HINT}.`
341
+ };
342
+ }
343
+
344
+ // src/card.ts
345
+ function checkoutLang(raw) {
346
+ return raw === "ja" ? "ja" : "en";
347
+ }
348
+ var BILLING_CONSENT = {
349
+ en: {
350
+ lead: "Subscribing needs the customer's own consent. Show them the statement below and ask. Do not consent on their behalf.",
351
+ 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.",
352
+ 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.`,
353
+ versions: (terms, dpa) => `This purchase is made under Customer Terms ${terms} and DPA ${dpa}.`,
354
+ next: "If they consent, run again with --consent-billing-data (MCP: consent_billing_data: true)."
355
+ },
356
+ ja: {
357
+ 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",
358
+ 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",
359
+ 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`,
360
+ 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`,
361
+ 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"
362
+ }
363
+ };
364
+ function billingConsentHuman(acceptance, lang) {
365
+ const copy = BILLING_CONSENT[lang];
366
+ return {
367
+ needs_human: "terms",
368
+ message: [
369
+ copy.lead,
370
+ copy.statement,
371
+ copy.info(`${LEGAL_ORIGIN}/${lang}/privacy`),
372
+ copy.versions(acceptance.customer_terms_version, acceptance.dpa_version),
373
+ copy.next
374
+ ].join("\n")
375
+ };
376
+ }
377
+ function incorporationNeededRefusal(orgId, stale) {
378
+ 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.";
379
+ return {
380
+ ok: false,
381
+ error: stale ? "incorporation_stale" : "incorporation_required",
382
+ human: {
383
+ needs_human: "terms",
384
+ message: `${why} Run: clavis incorporation-set ${orgId} --incorporation CODE --accept-customer-terms (MCP: clavis_incorporation_set), after the customer agrees.`
385
+ }
386
+ };
387
+ }
388
+ function purchaseRegionClosedRefusal(incorporation) {
389
+ return {
390
+ ok: false,
391
+ error: `region_closed \u2014 new subscriptions are not accepted right now for Orgs incorporated in ${incorporation}.`
392
+ };
393
+ }
394
+ function declarationRegionClosedRefusal(incorporation) {
395
+ return {
396
+ ok: false,
397
+ error: `region_closed \u2014 ${incorporation} cannot be declared as the place of incorporation right now. GET /orgs/regions lists the closed places.`
398
+ };
399
+ }
400
+ function checkoutRefusal(e, args) {
401
+ if (!(e instanceof SetupApiError)) return null;
402
+ switch (e.code) {
403
+ case "REGION_CLOSED":
404
+ return purchaseRegionClosedRefusal(args.incorporation);
405
+ case "INCORPORATION":
406
+ return incorporationNeededRefusal(args.orgId, e.message === "incorporation_stale");
407
+ case "AGE_INELIGIBLE":
408
+ return { ok: false, error: "age_ineligible \u2014 an organisation contract can be made by someone who is 18 or older." };
409
+ case "AGE_BAND_REQUIRED":
410
+ return {
411
+ ok: false,
412
+ error: "age_band_required \u2014 this account has no age record, so the organisation contract can't continue."
413
+ };
414
+ case "BILLING_SUBJECT":
415
+ return {
416
+ ok: false,
417
+ error: "billing_subject_taken \u2014 this account already pays for another Org. Another owner or admin of this Org can subscribe instead."
418
+ };
419
+ case "CHECKOUT_CLOSED":
420
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
421
+ default:
422
+ return null;
423
+ }
424
+ }
425
+ function incorporationSetRefusal(e, incorporation) {
426
+ if (!(e instanceof SetupApiError)) return null;
427
+ if (e.code === "REGION_CLOSED") return declarationRegionClosedRefusal(incorporation);
428
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
429
+ return null;
27
430
  }
28
431
 
29
432
  // src/safe-browser-url.ts
30
- function parseHttpsUrl(raw) {
433
+ function isLoopbackHost2(hostname) {
434
+ const host = hostname.toLowerCase();
435
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
436
+ }
437
+ function parseBrowserUrl(raw) {
31
438
  let u;
32
439
  try {
33
440
  u = new URL(raw.trim());
34
441
  } catch {
35
442
  throw new Error("invalid URL");
36
443
  }
37
- if (u.protocol !== "https:") {
38
- throw new Error("only https URLs may be opened in a browser");
39
- }
40
444
  if (u.username || u.password) {
41
445
  throw new Error("URL must not contain credentials");
42
446
  }
43
447
  return u;
44
448
  }
45
449
  function assertCardCheckoutBrowserUrl(raw) {
46
- const u = parseHttpsUrl(raw);
450
+ const u = parseBrowserUrl(raw);
451
+ if (u.protocol !== "https:") {
452
+ throw new Error("only https URLs may be opened in a browser");
453
+ }
47
454
  const host = u.hostname.toLowerCase();
48
455
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
49
456
  throw new Error("checkout URL host is not allowed");
@@ -51,15 +458,21 @@ function assertCardCheckoutBrowserUrl(raw) {
51
458
  return u.toString();
52
459
  }
53
460
  function assertOriginBrowserUrl(raw, origin) {
54
- const u = parseHttpsUrl(raw);
461
+ const u = parseBrowserUrl(raw);
55
462
  let expected;
56
463
  try {
57
464
  expected = new URL(origin.trim());
58
465
  } catch {
59
466
  throw new Error("invalid expected origin");
60
467
  }
61
- if (expected.protocol !== "https:") {
62
- throw new Error("expected origin must be https");
468
+ if (expected.username || expected.password) {
469
+ throw new Error("expected origin must not contain credentials");
470
+ }
471
+ const loopback = isLoopbackHost2(expected.hostname);
472
+ const https = expected.protocol === "https:" && u.protocol === "https:";
473
+ const loopbackHttp = loopback && expected.protocol === "http:" && u.protocol === "http:";
474
+ if (!https && !loopbackHttp) {
475
+ throw new Error("only https URLs may be opened in a browser");
63
476
  }
64
477
  if (u.origin !== expected.origin) {
65
478
  throw new Error("URL origin does not match the expected origin");
@@ -74,10 +487,6 @@ function bytesToBase64Url(bytes) {
74
487
  const b64 = Buffer.from(bin, "binary").toString("base64");
75
488
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
76
489
  }
77
- async function sha256Base64Url(text) {
78
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
79
- return bytesToBase64Url(digest);
80
- }
81
490
  async function sha256HexUtf8(s) {
82
491
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
83
492
  let out = "";
@@ -100,60 +509,78 @@ function stableStringify(v) {
100
509
  return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`).join(",")}}`;
101
510
  }
102
511
 
103
- // src/digests.ts
104
- async function computeOrgPolicyBootstrapDigest(input) {
105
- return sha256Base64Url(
106
- canonicalStringify({
107
- org_id: input.org_id.trim(),
108
- primary_domain: input.primary_domain.trim().toLowerCase(),
109
- owner_sub: input.owner_sub.trim()
110
- })
111
- );
512
+ // src/statements.ts
513
+ async function digestOf(value) {
514
+ const bytes = new TextEncoder().encode(canonicalStringify(value));
515
+ return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))}`;
516
+ }
517
+ function orgAnchorPublishStatement(input2) {
518
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
519
+ }
520
+ function orgPolicyBootstrapStatement(input2) {
521
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
522
+ }
523
+ function orgAppRegisterStatement(input2) {
524
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim().toLowerCase() };
525
+ }
526
+ function orgAppVerifyHostStatement(input2) {
527
+ return {
528
+ type: "org.app.verify_host@1",
529
+ org: input2.org.trim(),
530
+ app: input2.app.trim(),
531
+ host: input2.host.trim().toLowerCase(),
532
+ nonce: input2.nonce.trim()
533
+ };
534
+ }
535
+ async function orgAppDeclarationStatement(input2) {
536
+ return {
537
+ type: "org.app.declaration@1",
538
+ org: input2.org.trim(),
539
+ app: input2.app.trim(),
540
+ declaration: input2.declaration === null ? null : await digestOf({ endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
541
+ };
542
+ }
543
+ function orgAppRegionsStatement(input2) {
544
+ return {
545
+ type: "org.app.regions@1",
546
+ org: input2.org.trim(),
547
+ app: input2.app.trim(),
548
+ regions: input2.regions === null ? null : [...new Set(input2.regions)].sort()
549
+ };
550
+ }
551
+ function orgCardIncorporationStatement(input2) {
552
+ return {
553
+ type: "org.card.incorporation_set@1",
554
+ org: input2.org.trim(),
555
+ code: input2.code.trim(),
556
+ customer_terms: input2.customerTerms.trim(),
557
+ dpa: input2.dpa.trim()
558
+ };
559
+ }
560
+ function orgCardCheckoutStatement(input2) {
561
+ return {
562
+ type: "org.card.checkout@1",
563
+ org: input2.org.trim(),
564
+ capability: input2.capability.trim(),
565
+ offer: input2.offer,
566
+ customer_terms: input2.customerTerms.trim(),
567
+ dpa: input2.dpa.trim()
568
+ };
569
+ }
570
+ function sameStatement(a, b) {
571
+ try {
572
+ return canonicalStringify(a) === canonicalStringify(b);
573
+ } catch {
574
+ return false;
575
+ }
112
576
  }
113
577
  async function computePayloadCommitmentHex(payload) {
114
578
  const o = payload && typeof payload === "object" ? { ...payload } : payload;
115
579
  if (o && typeof o === "object" && !Array.isArray(o)) {
116
- delete o.proposer_sign_proof;
580
+ delete o.proposer_receipt;
117
581
  }
118
582
  return sha256HexUtf8(canonicalStringify(o));
119
583
  }
120
- async function computeOrgAppRegisterDigest(input) {
121
- return sha256Base64Url(
122
- canonicalStringify({
123
- payload_hash: input.payload_hash.trim().toLowerCase(),
124
- proposer_sub: input.proposer_sub.trim()
125
- })
126
- );
127
- }
128
- async function computeOrgAppVerifyHostDigest(input) {
129
- return sha256Base64Url(
130
- canonicalStringify({
131
- app_id: input.app_id.trim(),
132
- host: input.host.trim().toLowerCase(),
133
- nonce: input.nonce.trim(),
134
- org_id: input.org_id.trim()
135
- })
136
- );
137
- }
138
- async function computeOrgAppDeclarationHash(declaration) {
139
- if (declaration === null) return "cleared";
140
- return sha256Base64Url(
141
- canonicalStringify({
142
- endUsers: declaration.endUsers,
143
- uses: declaration.uses
144
- })
145
- );
146
- }
147
- async function computeOrgAppDeclarationDigest(input) {
148
- return sha256Base64Url(
149
- canonicalStringify({
150
- org_id: input.org_id.trim(),
151
- app_id: input.app_id.trim(),
152
- declaration_hash: input.declaration_hash.trim(),
153
- actor_sub: input.actor_sub.trim()
154
- })
155
- );
156
- }
157
584
  async function hashManifestBody(body) {
158
585
  return sha256HexUtf8(canonicalStringify(body));
159
586
  }
@@ -162,33 +589,26 @@ function buildAnchorTxtRecord(args) {
162
589
  }
163
590
 
164
591
  // src/ceremony.ts
165
- function signProofFromCeremonyPayload(payload) {
166
- if (payload === null || typeof payload !== "object") {
167
- throw new Error("Passkey confirmation did not return a signature.");
592
+ function receiptFromCeremonyPayload(payload) {
593
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
594
+ throw new Error("Passkey confirmation did not return a receipt.");
168
595
  }
169
596
  const o = payload;
170
- const nested = o.sign_proof;
171
- if (nested !== null && typeof nested === "object") return nested;
172
- if (o.v === 1 && o.intent_type === "generic_sign" && typeof o.intent_id === "string" && o.intent_id.length > 0) {
173
- return o;
597
+ if (o.type !== "receipt@1" || o.statement === null || typeof o.statement !== "object") {
598
+ throw new Error("Passkey confirmation did not return a receipt.");
174
599
  }
175
- throw new Error("Passkey confirmation did not return a signature.");
600
+ return o;
176
601
  }
177
602
  async function startCeremony(args) {
178
603
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
179
604
  method: "POST",
605
+ redirect: "error",
180
606
  headers: {
181
607
  Accept: "application/json",
182
608
  "Content-Type": "application/json",
183
609
  Authorization: `Bearer ${args.bearer}`
184
610
  },
185
- body: JSON.stringify({
186
- return_to: args.returnTo,
187
- purpose: args.purpose,
188
- ...args.messageDigest ? { message_digest: args.messageDigest } : {},
189
- ...args.displayHint ? { display_hint: args.displayHint } : {},
190
- ...args.label ? { label: args.label } : {}
191
- })
611
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
192
612
  });
193
613
  const body = await res.json().catch(() => null);
194
614
  if (!res.ok || typeof body?.payload?.ticket !== "string") {
@@ -204,6 +624,7 @@ async function pollCeremonyResult(args) {
204
624
  while (Date.now() < deadline) {
205
625
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
206
626
  method: "POST",
627
+ redirect: "error",
207
628
  headers: {
208
629
  Accept: "application/json",
209
630
  "Content-Type": "application/json",
@@ -213,199 +634,83 @@ async function pollCeremonyResult(args) {
213
634
  });
214
635
  const body = await res.json().catch(() => null);
215
636
  if (res.ok && body?.payload !== void 0) {
216
- return body.payload.payload;
637
+ return body.payload.receipt;
217
638
  }
218
639
  if (res.status === 404) {
219
640
  lastError = body?.message ?? "waiting for Passkey";
220
641
  await sleep(intervalMs);
221
642
  continue;
222
643
  }
223
- throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
224
- }
225
- throw new Error(lastError);
226
- }
227
- function sleep(ms) {
228
- return new Promise((resolve) => setTimeout(resolve, ms));
229
- }
230
- function ceremonyPageUrl(idOrigin, ticket) {
231
- const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
232
- u.searchParams.set("ticket", ticket);
233
- return u.toString();
234
- }
235
- function setupCeremonyReturnTo(developersOrigin) {
236
- return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
237
- }
238
-
239
- // src/org-api.ts
240
- var SetupApiError = class extends Error {
241
- status;
242
- code;
243
- constructor(status, code, message) {
244
- super(message);
245
- this.name = "SetupApiError";
246
- this.status = status;
247
- this.code = code;
248
- }
249
- };
250
- async function apiJson(apiOrigin, path, opts) {
251
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path}`, {
252
- method: opts.method ?? "GET",
253
- headers: {
254
- Accept: "application/json",
255
- Authorization: `Bearer ${opts.bearer}`,
256
- ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
257
- },
258
- body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
259
- });
260
- const body = await res.json().catch(() => null);
261
- if (!res.ok) {
262
- const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
263
- const message = typeof body?.message === "string" ? body.message : code;
264
- throw new SetupApiError(res.status, code, message);
265
- }
266
- return body ?? {};
267
- }
268
- async function listOrgs(apiOrigin, bearer) {
269
- const r = await apiJson(apiOrigin, "/orgs", { bearer });
270
- return r.orgs ?? [];
271
- }
272
- async function getOrg(apiOrigin, bearer, orgId) {
273
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
274
- }
275
- async function postDnsChallenge(apiOrigin, bearer, domain, kind = "anchor") {
276
- return apiJson(apiOrigin, "/orgs/dns/challenge", {
277
- method: "POST",
278
- bearer,
279
- body: { domain: domain.trim(), kind }
280
- });
281
- }
282
- async function postVerifyAnchor(apiOrigin, bearer, args) {
283
- return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
284
- method: "POST",
285
- bearer,
286
- body: {
287
- domain: args.domain.trim(),
288
- nonce: args.nonce,
289
- ...args.name ? { name: args.name.trim() } : {}
290
- }
291
- });
292
- }
293
- async function postPolicyBootstrap(apiOrigin, bearer, orgId, signProof) {
294
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
295
- method: "POST",
296
- bearer,
297
- body: signProof ? { sign_proof: signProof } : {}
298
- });
299
- }
300
- async function listApps(apiOrigin, bearer, orgId) {
301
- const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
302
- bearer
303
- });
304
- return r.apps ?? [];
305
- }
306
- async function getApp(apiOrigin, bearer, orgId, appId) {
307
- const r = await apiJson(
308
- apiOrigin,
309
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
310
- { bearer }
311
- );
312
- return r.app;
313
- }
314
- async function postAppRegister(apiOrigin, bearer, orgId, payload) {
315
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
316
- method: "POST",
317
- bearer,
318
- body: payload
319
- });
320
- }
321
- async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
322
- return apiJson(
323
- apiOrigin,
324
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
325
- { bearer }
326
- );
327
- }
328
- async function postVerifyHost(apiOrigin, bearer, orgId, appId, signProof) {
329
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
330
- method: "POST",
331
- bearer,
332
- body: { sign_proof: signProof }
333
- });
334
- }
335
- async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
336
- return apiJson(
337
- apiOrigin,
338
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
339
- {
340
- method: "PUT",
341
- bearer,
342
- body: {
343
- endUsers: args.endUsers,
344
- uses: args.uses,
345
- sign_proof: args.signProof
346
- }
347
- }
348
- );
644
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
645
+ }
646
+ throw new Error(lastError);
349
647
  }
350
- async function getCard(apiOrigin, bearer, orgId) {
351
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
648
+ function sleep(ms) {
649
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
352
650
  }
353
- async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signature") {
354
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
355
- method: "POST",
356
- bearer,
357
- body: { capability }
358
- });
651
+ function ceremonyPageUrl(idOrigin, ticket) {
652
+ const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
653
+ u.searchParams.set("ticket", ticket);
654
+ return u.toString();
359
655
  }
360
- async function fetchJwksDocument(apiOrigin) {
361
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
362
- headers: { Accept: "application/json" }
363
- });
364
- if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
365
- return res.json();
656
+ function setupCeremonyReturnTo(developersOrigin) {
657
+ return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
366
658
  }
367
- function masterJwkJsonFromDocument(jwks) {
368
- const master = jwks.master ?? jwks.keys?.find((k) => k.kid === "master" || k.use === "master" || k.alg === "EdDSA");
369
- if (!master) throw new SetupApiError(404, "MASTER_JWK_MISSING", "master JWK not found in JWKS");
370
- return JSON.stringify(master);
659
+ async function refuseSymlink(path2) {
660
+ try {
661
+ const st = await lstat(path2);
662
+ if (st.isSymbolicLink()) throw new Error(`refusing to write through a symlink: ${path2}`);
663
+ } catch (e) {
664
+ if (e.code === "ENOENT") return;
665
+ throw e;
666
+ }
371
667
  }
372
- async function getMasterJwkJson(apiOrigin, masterPinJson) {
373
- const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
374
- const doc = await fetchJwksDocument(apiOrigin);
375
- await verifySignedJwksDocument(doc, masterPinJson);
376
- return masterJwkJsonFromDocument(doc);
668
+ async function writeMode600(path2, contents) {
669
+ const dir = dirname(path2);
670
+ await mkdir(dir, { recursive: true, mode: 448 });
671
+ await refuseSymlink(dir);
672
+ await refuseSymlink(path2);
673
+ await writeFile(path2, contents, { encoding: "utf8", mode: 384 });
674
+ try {
675
+ await chmod(path2, 384);
676
+ } catch (e) {
677
+ await unlink(path2).catch(() => void 0);
678
+ const message = e instanceof Error ? e.message : String(e);
679
+ throw new Error(`could not set mode 0600 on ${path2}: ${message}`);
680
+ }
681
+ }
682
+
683
+ // src/operate-key-store.ts
684
+ var APP_ID_RE = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[a-z0-9][a-z0-9._-]{0,126})$/;
685
+ function assertOperateAppId(appId) {
686
+ const app = appId.trim().toLowerCase();
687
+ if (!APP_ID_RE.test(app)) throw new Error("invalid_app_id");
688
+ return app;
689
+ }
690
+ function keysBase() {
691
+ const override = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim();
692
+ return resolve(override || join(homedir(), ".config", "clavis", "apps"));
693
+ }
694
+ function pathInsideKeys(appId, file) {
695
+ const app = assertOperateAppId(appId);
696
+ const base = keysBase();
697
+ const path2 = resolve(base, app, file);
698
+ const rel = relative(base, path2);
699
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("invalid_app_id");
700
+ return path2;
377
701
  }
378
702
  function operatePrivateJwkPath(appId) {
379
- const app = appId.trim();
380
- if (!app) throw new Error("appId required");
381
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
382
- return join(base, app, "operate-private.jwk.json");
703
+ return pathInsideKeys(appId, "operate-private.jwk.json");
383
704
  }
384
705
  function appEnvFilePath(appId) {
385
- const app = appId.trim();
386
- if (!app) throw new Error("appId required");
387
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
388
- return join(base, app, "app.env");
389
- }
390
- async function restrictFileMode(path) {
391
- try {
392
- await chmod(path, 384);
393
- } catch (e) {
394
- console.warn(
395
- `clavis: could not set mode 0600 on ${path}: ${e instanceof Error ? e.message : e}`
396
- );
397
- }
706
+ return pathInsideKeys(appId, "app.env");
398
707
  }
399
708
  async function saveOperatePrivateJwk(appId, jwkJson) {
400
- const path = operatePrivateJwkPath(appId);
401
- await mkdir(dirname(path), { recursive: true });
402
- await writeFile(path, jwkJson.trim(), "utf8");
403
- await restrictFileMode(path);
404
- try {
405
- await chmod(dirname(path), 448);
406
- } catch {
407
- }
408
- return path;
709
+ const path2 = operatePrivateJwkPath(appId);
710
+ await writeMode600(path2, `${jwkJson.trim()}
711
+ `);
712
+ await chmod(dirname(path2), 448).catch(() => void 0);
713
+ return path2;
409
714
  }
410
715
  async function readOperatePrivateJwk(appId) {
411
716
  try {
@@ -416,12 +721,10 @@ async function readOperatePrivateJwk(appId) {
416
721
  }
417
722
  }
418
723
  async function writeAppEnvFile(appId, contents) {
419
- const path = appEnvFilePath(appId);
420
- await mkdir(dirname(path), { recursive: true });
421
- await writeFile(path, contents.endsWith("\n") ? contents : `${contents}
422
- `, "utf8");
423
- await restrictFileMode(path);
424
- return path;
724
+ const path2 = appEnvFilePath(appId);
725
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
726
+ `);
727
+ return path2;
425
728
  }
426
729
 
427
730
  // src/emit-env.ts
@@ -474,35 +777,64 @@ async function generateOperateKeyPair() {
474
777
  privateJwkJson: JSON.stringify(priv)
475
778
  };
476
779
  }
780
+ var SESSION_SLOT_RE = /^[a-z][a-z0-9]{1,31}-wauthn-auth-jwt(?:-\d{6})?$/;
477
781
  async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
478
- const base = apiOrigin.replace(/\/+$/, "");
479
- const jwks = createRemoteJWKSet(new URL(`${base}/.well-known/jwks.json`));
480
- await jwtVerify(accessToken, jwks, { algorithms: ["ES256"] });
782
+ const origin = new URL(apiOrigin).origin;
783
+ const jwks = createRemoteJWKSet(new URL(`${origin}/.well-known/jwks.json`));
784
+ const { payload, protectedHeader } = await jwtVerify(accessToken, jwks, {
785
+ algorithms: ["ES256"],
786
+ issuer: origin,
787
+ audience: origin,
788
+ requiredClaims: ["exp", "iss", "aud", "sub"]
789
+ });
790
+ const kid = typeof protectedHeader.kid === "string" ? protectedHeader.kid : "";
791
+ if (!SESSION_SLOT_RE.test(kid)) throw new Error("invalid_access_token_kid");
792
+ if (payload.tk !== "access") throw new Error("invalid_access_token_kind");
793
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) throw new Error("invalid_access_token_sub");
794
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) throw new Error("invalid_access_token_exp");
795
+ return { sub: payload.sub, expiresAt: payload.exp };
481
796
  }
482
-
483
- // src/types.ts
484
- var DEFAULT_ORIGINS = {
485
- apiOrigin: "https://api.clavis.nexus",
486
- idOrigin: "https://id.clavis.nexus",
487
- developersOrigin: "https://developers.clavis.nexus"
488
- };
489
-
490
- // src/session-store.ts
491
797
  function defaultSessionPath() {
492
798
  const override = process.env.CLAVIS_SESSION_PATH?.trim();
493
799
  if (override) return override;
494
800
  return join(homedir(), ".config", "clavis", "session.json");
495
801
  }
802
+ function isLoopbackHost3(hostname) {
803
+ const host = hostname.toLowerCase();
804
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
805
+ }
806
+ function assertSetupOrigin(raw, name) {
807
+ let url;
808
+ try {
809
+ url = new URL(raw.trim());
810
+ } catch {
811
+ throw new Error(`${name} must be an absolute URL`);
812
+ }
813
+ if (url.username || url.password) throw new Error(`${name} must not contain credentials`);
814
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost3(url.hostname);
815
+ if (url.protocol !== "https:" && !loopbackHttp) throw new Error(`${name} must be https`);
816
+ if (url.pathname !== "/" || url.search || url.hash) throw new Error(`${name} must be an origin`);
817
+ return url.origin;
818
+ }
496
819
  function originsFromEnv(overrides) {
497
820
  return {
498
- apiOrigin: overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
499
- idOrigin: overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
500
- developersOrigin: overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin
821
+ apiOrigin: assertSetupOrigin(
822
+ overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
823
+ "apiOrigin"
824
+ ),
825
+ idOrigin: assertSetupOrigin(
826
+ overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
827
+ "idOrigin"
828
+ ),
829
+ developersOrigin: assertSetupOrigin(
830
+ overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin,
831
+ "developersOrigin"
832
+ )
501
833
  };
502
834
  }
503
- async function loadSession(path = defaultSessionPath()) {
835
+ async function loadSession(path2 = defaultSessionPath()) {
504
836
  try {
505
- const raw = await readFile(path, "utf8");
837
+ const raw = await readFile(path2, "utf8");
506
838
  const parsed = JSON.parse(raw);
507
839
  if (parsed?.v !== 1 || typeof parsed.session?.accessToken !== "string") return null;
508
840
  if (parsed.session.expiresAt && parsed.session.expiresAt * 1e3 < Date.now()) return null;
@@ -511,152 +843,193 @@ async function loadSession(path = defaultSessionPath()) {
511
843
  return null;
512
844
  }
513
845
  }
514
- async function saveSession(session, origins, path = defaultSessionPath()) {
515
- await mkdir(dirname(path), { recursive: true });
846
+ async function saveSession(session, origins, path2 = defaultSessionPath()) {
516
847
  const body = { v: 1, origins, session, savedAt: Date.now() };
517
- await writeFile(path, JSON.stringify(body, null, 2), "utf8");
518
- try {
519
- await chmod(path, 384);
520
- } catch (e) {
521
- console.warn(
522
- `clavis: could not set session file mode 0600 (${path}): ${e instanceof Error ? e.message : e}`
523
- );
524
- }
848
+ await writeMode600(path2, JSON.stringify(body, null, 2));
525
849
  }
526
- async function clearSession(path = defaultSessionPath()) {
850
+ async function clearSession(path2 = defaultSessionPath()) {
527
851
  try {
528
- await unlink(path);
852
+ await unlink(path2);
529
853
  } catch {
530
854
  }
531
855
  }
532
856
 
533
857
  // src/login.ts
534
- var MAX_CALLBACK_BODY_BYTES = 8192;
535
- function readBody(req) {
536
- return new Promise((resolve, reject) => {
537
- const chunks = [];
538
- let total = 0;
539
- req.on("data", (c) => {
540
- const buf = Buffer.isBuffer(c) ? c : Buffer.from(c);
541
- total += buf.length;
542
- if (total > MAX_CALLBACK_BODY_BYTES) {
543
- reject(new Error("callback body too large"));
544
- req.destroy();
545
- return;
546
- }
547
- chunks.push(buf);
548
- });
549
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
550
- req.on("error", reject);
551
- });
552
- }
553
- function cors(res, developersOrigin) {
554
- res.setHeader("Access-Control-Allow-Origin", developersOrigin);
555
- res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
556
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
557
- res.setHeader("Vary", "Origin");
858
+ var MAX_BRIDGE_JSON_CHARS = 16384;
859
+ var PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
860
+ function pendingLoginPath(sessionPath) {
861
+ const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
862
+ return path.join(base, "login-pending.json");
863
+ }
864
+ function loginBridgeUrl(developersOrigin, state) {
865
+ const bridge = new URL("/developers/setup/login", developersOrigin);
866
+ bridge.searchParams.set("state", state);
867
+ return bridge.toString();
868
+ }
869
+ async function writePending(pendingPath, pending) {
870
+ await mkdir(path.dirname(pendingPath), { recursive: true, mode: 448 });
871
+ await writeFile(pendingPath, `${JSON.stringify(pending, null, 2)}
872
+ `, { mode: 384 });
873
+ }
874
+ async function readPending(pendingPath) {
875
+ try {
876
+ const raw = await readFile(pendingPath, "utf8");
877
+ const parsed = JSON.parse(raw);
878
+ if (parsed?.v !== 1 || typeof parsed.state !== "string" || !parsed.state) return null;
879
+ return parsed;
880
+ } catch {
881
+ return null;
882
+ }
558
883
  }
559
- function subFromJwt(accessToken) {
884
+ async function clearPending(pendingPath) {
560
885
  try {
561
- const part = accessToken.split(".")[1];
562
- if (!part) return void 0;
563
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
564
- const payload = JSON.parse(json);
565
- return typeof payload.sub === "string" ? payload.sub : void 0;
886
+ await unlink(pendingPath);
566
887
  } catch {
567
- return void 0;
888
+ }
889
+ }
890
+ function parseBridgePayload(raw) {
891
+ const trimmed = raw.trim();
892
+ if (!trimmed) throw new Error("empty_bridge_json");
893
+ if (trimmed.length > MAX_BRIDGE_JSON_CHARS) throw new Error("bridge_json_too_large");
894
+ const body = JSON.parse(trimmed);
895
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
896
+ throw new Error("bridge_json_not_object");
897
+ }
898
+ return body;
899
+ }
900
+ async function sessionFromBridge(args) {
901
+ const body = parseBridgePayload(args.raw);
902
+ if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
903
+ throw new Error("invalid_bridge_json");
904
+ }
905
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
906
+ return {
907
+ accessToken: body.accessToken,
908
+ sub: verified.sub,
909
+ expiresAt: verified.expiresAt
910
+ };
911
+ }
912
+ async function readBridgeJsonFromStdin() {
913
+ if (!stdin.isTTY) {
914
+ const chunks = [];
915
+ for await (const chunk of stdin) {
916
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
917
+ }
918
+ return Buffer.concat(chunks).toString("utf8");
919
+ }
920
+ const rl = createInterface({ input: stdin, output: stdout });
921
+ try {
922
+ stdout.write(
923
+ "Paste the JSON shown on developers /setup/login, then press Enter.\n(End with a blank line if the paste spans multiple lines.)\n"
924
+ );
925
+ const lines = [];
926
+ for (; ; ) {
927
+ const line = await rl.question("");
928
+ if (line.trim() === "" && lines.length > 0) break;
929
+ lines.push(line);
930
+ const joined = lines.join("\n").trim();
931
+ if (joined.startsWith("{") && joined.endsWith("}")) break;
932
+ }
933
+ return lines.join("\n");
934
+ } finally {
935
+ rl.close();
568
936
  }
569
937
  }
570
938
  async function loginWithBrowser(args) {
571
- const state = randomBytes(16).toString("hex");
572
- const timeoutMs = args.timeoutMs ?? 5 * 6e4;
573
- const session = await new Promise((resolve, reject) => {
574
- const server = createServer(async (req, res) => {
575
- cors(res, args.origins.developersOrigin);
576
- if (req.method === "OPTIONS") {
577
- res.writeHead(204);
578
- res.end();
579
- return;
580
- }
581
- if (req.method !== "POST" || req.url?.split("?")[0] !== "/callback") {
582
- res.writeHead(404);
583
- res.end("not found");
584
- return;
585
- }
586
- try {
587
- const raw = await readBody(req);
588
- const body = JSON.parse(raw);
589
- if (body.state !== state || typeof body.accessToken !== "string" || !body.accessToken) {
590
- res.writeHead(400, { "Content-Type": "application/json" });
591
- res.end(JSON.stringify({ ok: false, error: "invalid_callback" }));
592
- return;
593
- }
594
- try {
595
- await verifyDevelopersAccessToken(body.accessToken, args.origins.apiOrigin);
596
- } catch {
597
- res.writeHead(400, { "Content-Type": "application/json" });
598
- res.end(JSON.stringify({ ok: false, error: "invalid_token" }));
599
- return;
600
- }
601
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
602
- const next = {
603
- accessToken: body.accessToken,
604
- ...sub ? { sub } : {},
605
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
606
- };
607
- res.writeHead(200, { "Content-Type": "application/json" });
608
- res.end(JSON.stringify({ ok: true }));
609
- server.close();
610
- resolve(next);
611
- } catch (e) {
612
- res.writeHead(500, { "Content-Type": "application/json" });
613
- res.end(JSON.stringify({ ok: false }));
614
- server.close();
615
- reject(e);
616
- }
939
+ const pendingPath = pendingLoginPath(args.sessionPath);
940
+ const openFlag = args.open !== false;
941
+ if (args.bridgeJson?.trim()) {
942
+ const pending = await readPending(pendingPath);
943
+ if (!pending) {
944
+ throw new Error("no_pending_login \u2014 run login again to open the browser first");
945
+ }
946
+ if (pending.apiOrigin !== args.origins.apiOrigin || pending.developersOrigin !== args.origins.developersOrigin) {
947
+ await clearPending(pendingPath);
948
+ throw new Error("pending_login_origin_mismatch \u2014 run login again");
949
+ }
950
+ if (!Number.isFinite(pending.createdAt) || Date.now() - pending.createdAt > PENDING_LOGIN_TTL_MS) {
951
+ await clearPending(pendingPath);
952
+ throw new Error("pending_login_expired \u2014 run login again");
953
+ }
954
+ const openUrl2 = assertOriginBrowserUrl(
955
+ loginBridgeUrl(args.origins.developersOrigin, pending.state),
956
+ args.origins.developersOrigin
957
+ );
958
+ const session2 = await sessionFromBridge({
959
+ raw: args.bridgeJson,
960
+ expectedState: pending.state,
961
+ apiOrigin: args.origins.apiOrigin
617
962
  });
618
- server.listen(0, "127.0.0.1", () => {
619
- const addr = server.address();
620
- if (!addr || typeof addr === "string") {
621
- reject(new Error("failed to bind localhost"));
622
- return;
963
+ await saveSession(session2, args.origins, args.sessionPath);
964
+ await clearPending(pendingPath);
965
+ return {
966
+ session: session2,
967
+ human: {
968
+ needs_human: "login",
969
+ message: "Session stored.",
970
+ open_url: openUrl2
623
971
  }
624
- const bridge = new URL("/developers/setup/login", args.origins.developersOrigin);
625
- bridge.searchParams.set("callback_port", String(addr.port));
626
- bridge.searchParams.set("state", state);
627
- void (async () => {
628
- if (args.open !== false) {
629
- try {
630
- await openBrowser(assertOriginBrowserUrl(bridge.toString(), args.origins.developersOrigin));
631
- } catch {
632
- }
633
- }
634
- })();
635
- });
636
- const timer = setTimeout(() => {
637
- server.close();
638
- reject(new Error("login timeout \u2014 complete Passkey in the browser"));
639
- }, timeoutMs);
640
- server.on("close", () => clearTimeout(timer));
972
+ };
973
+ }
974
+ const state = randomBytes(16).toString("hex");
975
+ const openUrl = assertOriginBrowserUrl(
976
+ loginBridgeUrl(args.origins.developersOrigin, state),
977
+ args.origins.developersOrigin
978
+ );
979
+ await writePending(pendingPath, {
980
+ v: 1,
981
+ state,
982
+ createdAt: Date.now(),
983
+ developersOrigin: args.origins.developersOrigin,
984
+ apiOrigin: args.origins.apiOrigin
641
985
  });
642
- await saveSession(session, args.origins);
986
+ if (openFlag) {
987
+ try {
988
+ await openBrowser(openUrl);
989
+ } catch {
990
+ }
991
+ }
992
+ if (args.deferPaste) {
993
+ return {
994
+ pending: true,
995
+ human: {
996
+ needs_human: "login",
997
+ message: "Complete Passkey in the browser, copy the JSON on the page, then call login again with bridge_json.",
998
+ open_url: openUrl
999
+ }
1000
+ };
1001
+ }
1002
+ const raw = await readBridgeJsonFromStdin();
1003
+ const session = await sessionFromBridge({
1004
+ raw,
1005
+ expectedState: state,
1006
+ apiOrigin: args.origins.apiOrigin
1007
+ });
1008
+ await saveSession(session, args.origins, args.sessionPath);
1009
+ await clearPending(pendingPath);
643
1010
  return {
644
1011
  session,
645
1012
  human: {
646
1013
  needs_human: "login",
647
- message: "Complete Passkey login in the browser if the window is still open.",
648
- open_url: `${args.origins.developersOrigin}/developers/setup/login`
1014
+ message: "Session stored. You can close the browser tab.",
1015
+ open_url: openUrl
649
1016
  }
650
1017
  };
651
1018
  }
652
1019
 
653
1020
  // src/status.ts
654
- function cardActive(card) {
655
- if (!card) return "unknown";
1021
+ function signatureCard(card) {
656
1022
  const sig = card.capabilities?.signature;
657
- if (!sig) return "inactive";
658
- if (sig.subscribed === true || sig.active === true) return "active";
659
- return "inactive";
1023
+ if (!sig) return { signature_card: "inactive" };
1024
+ if (sig.open === true) return { signature_card: "active" };
1025
+ return {
1026
+ signature_card: "inactive",
1027
+ ...Array.isArray(sig.blockers) && sig.blockers.length > 0 ? { signature_card_blockers: sig.blockers } : {}
1028
+ };
1029
+ }
1030
+ function incorporationOf(card) {
1031
+ const inc = card.incorporation;
1032
+ return inc ? { code: inc.code, terms_current: inc.terms_current === true } : null;
660
1033
  }
661
1034
  async function buildSetupStatus(args) {
662
1035
  if (!args.session) {
@@ -666,7 +1039,9 @@ async function buildSetupStatus(args) {
666
1039
  const detailed = [];
667
1040
  for (const org of orgs) {
668
1041
  let setup_complete = false;
669
- let signature_card = "unknown";
1042
+ let card = {
1043
+ signature_card: "unknown"
1044
+ };
670
1045
  let apps = [];
671
1046
  try {
672
1047
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -674,10 +1049,10 @@ async function buildSetupStatus(args) {
674
1049
  } catch {
675
1050
  }
676
1051
  try {
677
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
678
- signature_card = cardActive(card);
1052
+ const view = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
1053
+ card = { ...signatureCard(view), incorporation: incorporationOf(view) };
679
1054
  } catch {
680
- signature_card = "unknown";
1055
+ card = { signature_card: "unknown" };
681
1056
  }
682
1057
  try {
683
1058
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -685,6 +1060,7 @@ async function buildSetupStatus(args) {
685
1060
  app_id: a.app_id,
686
1061
  host: a.host,
687
1062
  status: a.status,
1063
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
688
1064
  declaration_ok: Boolean(
689
1065
  a.declaration && typeof a.declaration.endUsers === "string" && a.declaration.endUsers.trim() && Array.isArray(a.declaration.uses) && a.declaration.uses.some((u) => u.capability === "signature")
690
1066
  )
@@ -714,7 +1090,7 @@ async function buildSetupStatus(args) {
714
1090
  primary_domain: org.primary_domain,
715
1091
  org_status: org.org_status,
716
1092
  setup_complete,
717
- signature_card,
1093
+ ...card,
718
1094
  apps
719
1095
  });
720
1096
  }
@@ -746,21 +1122,18 @@ async function runPasskeyCeremony(args) {
746
1122
  apiOrigin: args.origins.apiOrigin,
747
1123
  bearer: args.bearer,
748
1124
  returnTo,
749
- purpose: args.purpose,
750
- messageDigest: args.messageDigest,
751
- displayHint: args.displayHint,
752
- label: args.displayHint
1125
+ statement: args.statement
753
1126
  });
754
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1127
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
755
1128
  if (args.openBrowserFlag) {
756
1129
  try {
757
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1130
+ await openBrowser(ceremony_url);
758
1131
  } catch {
759
1132
  }
760
1133
  }
761
1134
  const human = {
762
1135
  needs_human: "passkey",
763
- message: "Confirm with Passkey in the browser, then return to the terminal/agent.",
1136
+ message: `${args.displayHint ? `${args.displayHint}: c` : "C"}onfirm with Passkey in the browser (${args.statement.type}), then return to the terminal/agent.`,
764
1137
  open_url: ceremony_url
765
1138
  };
766
1139
  return {
@@ -773,7 +1146,7 @@ async function runPasskeyCeremony(args) {
773
1146
  bearer: args.bearer,
774
1147
  ticket
775
1148
  });
776
- return signProofFromCeremonyPayload(payload);
1149
+ return receiptFromCeremonyPayload(payload);
777
1150
  }
778
1151
  };
779
1152
  }
@@ -787,9 +1160,24 @@ function createSetupClient(options = {}) {
787
1160
  const s = await loadSession(sessionPath);
788
1161
  return s?.session ?? null;
789
1162
  },
790
- async login() {
791
- const { session } = await loginWithBrowser({ origins, open: openBrowserFlag });
792
- return { ok: true, data: { sub: session.sub } };
1163
+ async login(opts) {
1164
+ const bridgeJson = opts?.bridgeJson?.trim();
1165
+ const deferPaste = !bridgeJson && !process.stdin.isTTY;
1166
+ const out = await loginWithBrowser({
1167
+ origins,
1168
+ open: openBrowserFlag,
1169
+ ...bridgeJson ? { bridgeJson } : {},
1170
+ ...deferPaste ? { deferPaste: true } : {},
1171
+ sessionPath
1172
+ });
1173
+ if (out.pending || !out.session) {
1174
+ return {
1175
+ ok: false,
1176
+ error: "login_pending_paste",
1177
+ human: out.human
1178
+ };
1179
+ }
1180
+ return { ok: true, data: { sub: out.session.sub } };
793
1181
  },
794
1182
  async logout() {
795
1183
  await clearSession(sessionPath);
@@ -800,18 +1188,43 @@ function createSetupClient(options = {}) {
800
1188
  const report = await buildSetupStatus({ origins, session });
801
1189
  return { ok: true, data: report };
802
1190
  },
803
- async orgAnchorPlan(domain, name) {
1191
+ async orgAnchorPlan(domain, name, terms = {}) {
1192
+ const checked = checkOrgCreationTerms(terms);
1193
+ if (!checked.ok) return checked;
1194
+ const { incorporation } = checked;
804
1195
  const auth = await requireSession({ origins, sessionPath });
805
1196
  if (!auth.ok) return auth;
806
- const challenge = await postDnsChallenge(auth.data.origins.apiOrigin, auth.data.session.accessToken, domain);
807
- if (!challenge.digest) {
808
- return { ok: false, error: "challenge_missing_digest" };
1197
+ const apiOrigin = auth.data.origins.apiOrigin;
1198
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1199
+ if (closed.includes(incorporation)) return regionClosedRefusal(incorporation);
1200
+ let challenge;
1201
+ try {
1202
+ challenge = await postDnsChallenge(apiOrigin, auth.data.session.accessToken, { domain, incorporation });
1203
+ } catch (e) {
1204
+ const refusal = orgCreationRefusal(e, incorporation);
1205
+ if (refusal) return refusal;
1206
+ throw e;
1207
+ }
1208
+ const domainNorm = domain.trim().toLowerCase();
1209
+ 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)) {
1210
+ return { ok: false, error: "challenge_missing_statement" };
1211
+ }
1212
+ const anchorStatement = orgAnchorPublishStatement({ domain: domainNorm, nonce: challenge.nonce, exp: challenge.exp });
1213
+ if (!sameStatement(anchorStatement, challenge.statement)) return { ok: false, error: "challenge_statement_mismatch" };
1214
+ let wellKnown;
1215
+ try {
1216
+ wellKnown = new URL(challenge.well_known_url);
1217
+ } catch {
1218
+ return { ok: false, error: "challenge_url_rejected" };
1219
+ }
1220
+ const txtHost = typeof challenge.txt_host === "string" ? challenge.txt_host.trim().toLowerCase().replace(/\.$/, "") : "";
1221
+ if (wellKnown.protocol !== "https:" || wellKnown.username || wellKnown.password || wellKnown.hostname.toLowerCase() !== domainNorm || txtHost !== domainNorm && !txtHost.endsWith(`.${domainNorm}`)) {
1222
+ return { ok: false, error: "challenge_url_rejected" };
809
1223
  }
810
1224
  const cer = await runPasskeyCeremony({
811
1225
  origins: auth.data.origins,
812
1226
  bearer: auth.data.session.accessToken,
813
- purpose: "org.anchor.publish",
814
- messageDigest: challenge.digest,
1227
+ statement: anchorStatement,
815
1228
  displayHint: `Publish DNS anchor for ${domain}`,
816
1229
  openBrowserFlag
817
1230
  });
@@ -820,9 +1233,10 @@ function createSetupClient(options = {}) {
820
1233
  data: {
821
1234
  domain: challenge.domain,
822
1235
  ...name ? { name } : {},
1236
+ incorporation,
823
1237
  nonce: challenge.nonce,
824
1238
  exp: challenge.exp,
825
- digest: challenge.digest,
1239
+ statement: anchorStatement,
826
1240
  well_known_url: challenge.well_known_url,
827
1241
  txt_host: challenge.txt_host,
828
1242
  ceremony_url: cer.ceremony_url,
@@ -839,12 +1253,12 @@ function createSetupClient(options = {}) {
839
1253
  bearer: auth.data.session.accessToken,
840
1254
  ticket: args.ticket
841
1255
  });
842
- const signProof = signProofFromCeremonyPayload(payload);
1256
+ const receipt = receiptFromCeremonyPayload(payload);
843
1257
  const body = {
844
1258
  v: 1,
845
1259
  kind: "anchor",
846
1260
  domain: args.domain.trim().toLowerCase(),
847
- sign_proof: signProof,
1261
+ receipt,
848
1262
  nonce: args.nonce,
849
1263
  exp: args.exp,
850
1264
  iat: Math.floor(Date.now() / 1e3)
@@ -861,18 +1275,29 @@ function createSetupClient(options = {}) {
861
1275
  txt_value,
862
1276
  human: {
863
1277
  needs_human: "dns",
864
- message: "Publish the well-known JSON and TXT, then call org_verify_anchor."
1278
+ 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."
865
1279
  }
866
1280
  }
867
1281
  };
868
1282
  },
869
1283
  async orgVerifyAnchor(args) {
1284
+ const checked = checkOrgCreationTerms(args);
1285
+ if (!checked.ok) return checked;
1286
+ const { incorporation } = checked;
870
1287
  const auth = await requireSession({ origins, sessionPath });
871
1288
  if (!auth.ok) return auth;
872
1289
  try {
873
- const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, args);
1290
+ const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, {
1291
+ domain: args.domain,
1292
+ nonce: args.nonce,
1293
+ name: args.name,
1294
+ incorporation,
1295
+ acceptCustomerTerms: args.acceptCustomerTerms
1296
+ });
874
1297
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
875
1298
  } catch (e) {
1299
+ const refusal = orgCreationRefusal(e, incorporation);
1300
+ if (refusal) return refusal;
876
1301
  return {
877
1302
  ok: false,
878
1303
  error: e instanceof Error ? e.message : String(e),
@@ -896,18 +1321,10 @@ function createSetupClient(options = {}) {
896
1321
  if (noop.already_active) return { ok: true, data: noop };
897
1322
  } catch {
898
1323
  }
899
- const sub = auth.data.session.sub;
900
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
901
- const digest = await computeOrgPolicyBootstrapDigest({
902
- org_id: orgId,
903
- primary_domain: detail.primary_domain,
904
- owner_sub: sub
905
- });
906
1324
  const cer = await runPasskeyCeremony({
907
1325
  origins: auth.data.origins,
908
1326
  bearer: auth.data.session.accessToken,
909
- purpose: "org.policy.bootstrap",
910
- messageDigest: digest,
1327
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
911
1328
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
912
1329
  openBrowserFlag
913
1330
  });
@@ -920,24 +1337,126 @@ function createSetupClient(options = {}) {
920
1337
  );
921
1338
  return { ok: true, data: out };
922
1339
  },
923
- async cardCheckout(orgId) {
1340
+ async incorporationSet(args) {
1341
+ const checked = checkOrgCreationTerms(args, INCORPORATION_TERMS_HUMAN);
1342
+ if (!checked.ok) return checked;
1343
+ const code = checked.incorporation;
1344
+ const auth = await requireSession({ origins, sessionPath });
1345
+ if (!auth.ok) return auth;
1346
+ const sub = auth.data.session.sub;
1347
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1348
+ const apiOrigin = auth.data.origins.apiOrigin;
1349
+ const bearer = auth.data.session.accessToken;
1350
+ const card = await getCard(apiOrigin, bearer, args.orgId);
1351
+ const current = card.incorporation;
1352
+ if (current?.code === code && current.terms_current) {
1353
+ return { ok: true, data: { incorporation: current, unchanged: true } };
1354
+ }
1355
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1356
+ if (closed.includes(code) && current?.code !== code) return declarationRegionClosedRefusal(code);
1357
+ const cer = await runPasskeyCeremony({
1358
+ origins: auth.data.origins,
1359
+ bearer,
1360
+ statement: orgCardIncorporationStatement({
1361
+ org: args.orgId,
1362
+ code,
1363
+ customerTerms: card.acceptance.customer_terms_version,
1364
+ dpa: card.acceptance.dpa_version
1365
+ }),
1366
+ displayHint: `Declare ${code} as the place of incorporation`,
1367
+ openBrowserFlag
1368
+ });
1369
+ const proof = await cer.wait();
1370
+ try {
1371
+ const out = await postCardIncorporation(apiOrigin, bearer, args.orgId, { code, receipt: proof });
1372
+ return { ok: true, data: { incorporation: out.incorporation } };
1373
+ } catch (e) {
1374
+ const refusal = incorporationSetRefusal(e, code);
1375
+ if (refusal) return refusal;
1376
+ throw e;
1377
+ }
1378
+ },
1379
+ async cardCheckout(orgId, opts = {}) {
1380
+ const offer = opts.offer === "bundle" ? "bundle" : "meter";
1381
+ const lang = checkoutLang(opts.lang);
924
1382
  const auth = await requireSession({ origins, sessionPath });
925
1383
  if (!auth.ok) return auth;
926
- const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
1384
+ const sub = auth.data.session.sub;
1385
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1386
+ const apiOrigin = auth.data.origins.apiOrigin;
1387
+ const bearer = auth.data.session.accessToken;
1388
+ const card = await getCard(apiOrigin, bearer, orgId);
1389
+ if (card.suspended) return { ok: false, error: "org_suspended" };
1390
+ const signature = card.capabilities?.signature;
1391
+ const open = offer === "bundle" ? signature?.bundle_checkout_open : signature?.checkout_open;
1392
+ if (!signature || open !== true) {
1393
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
1394
+ }
1395
+ const blockers = signature.blockers ?? [];
1396
+ const subscribed = offer === "bundle" ? signature.tariff === "bundle" : !blockers.includes("subscription");
1397
+ if (subscribed) {
1398
+ const state = blockers.length > 0 ? ` (${blockers.join(", ")})` : "";
1399
+ return {
1400
+ ok: false,
1401
+ error: `already_subscribed \u2014 the signature card already has this subscription${state}. Manage it on developers.`
1402
+ };
1403
+ }
1404
+ const incorporation = card.incorporation;
1405
+ if (!incorporation) return incorporationNeededRefusal(orgId, false);
1406
+ if (!incorporation.terms_current) return incorporationNeededRefusal(orgId, true);
1407
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1408
+ if (closed.includes(incorporation.code)) return purchaseRegionClosedRefusal(incorporation.code);
1409
+ if (opts.consentBillingData !== true) {
1410
+ return { ok: false, error: "billing_data_consent_required", human: billingConsentHuman(card.acceptance, lang) };
1411
+ }
1412
+ const cer = await runPasskeyCeremony({
1413
+ origins: auth.data.origins,
1414
+ bearer,
1415
+ statement: orgCardCheckoutStatement({
1416
+ org: orgId,
1417
+ capability: "signature",
1418
+ offer,
1419
+ customerTerms: card.acceptance.customer_terms_version,
1420
+ dpa: card.acceptance.dpa_version
1421
+ }),
1422
+ displayHint: offer === "bundle" ? "Subscribe to the signature card (monthly bundle)" : "Subscribe to the signature card",
1423
+ openBrowserFlag
1424
+ });
1425
+ const proof = await cer.wait();
1426
+ let url;
1427
+ try {
1428
+ ({ url } = await postCardCheckout(apiOrigin, bearer, orgId, {
1429
+ capability: "signature",
1430
+ offer,
1431
+ consentBillingData: true,
1432
+ uiLocale: lang,
1433
+ receipt: proof
1434
+ }));
1435
+ } catch (e) {
1436
+ const refusal = checkoutRefusal(e, { orgId, incorporation: incorporation.code });
1437
+ if (refusal) return refusal;
1438
+ throw e;
1439
+ }
1440
+ let checkoutUrl;
1441
+ try {
1442
+ checkoutUrl = assertCardCheckoutBrowserUrl(url);
1443
+ } catch (e) {
1444
+ return { ok: false, error: e instanceof Error ? e.message : "checkout_url_rejected" };
1445
+ }
927
1446
  if (openBrowserFlag) {
928
1447
  try {
929
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1448
+ await openBrowser(checkoutUrl);
930
1449
  } catch {
931
1450
  }
932
1451
  }
933
1452
  return {
934
1453
  ok: true,
935
1454
  data: {
936
- url,
1455
+ url: checkoutUrl,
937
1456
  human: {
938
1457
  needs_human: "payment",
939
1458
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
940
- open_url: url
1459
+ open_url: checkoutUrl
941
1460
  }
942
1461
  }
943
1462
  };
@@ -954,26 +1473,24 @@ function createSetupClient(options = {}) {
954
1473
  v: 1,
955
1474
  host: args.host.trim().toLowerCase(),
956
1475
  display_name: args.displayName.trim(),
957
- intent_types: args.intentTypes ?? ["generic.sign"],
1476
+ intent_types: args.intentTypes ?? ["generic_sign"],
958
1477
  max_ttl_seconds: 300,
959
1478
  operate_kid: keys.kid,
960
1479
  operate_public_jwk: keys.publicJwk,
961
1480
  redirect_paths: paths
962
1481
  };
963
1482
  const payload_hash = await computePayloadCommitmentHex(manifest);
964
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
965
1483
  const cer = await runPasskeyCeremony({
966
1484
  origins: auth.data.origins,
967
1485
  bearer: auth.data.session.accessToken,
968
- purpose: "org.app.register",
969
- messageDigest: digest,
1486
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
970
1487
  displayHint: `Register App ${manifest.host}`,
971
1488
  openBrowserFlag
972
1489
  });
973
1490
  const proof = await cer.wait();
974
1491
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
975
1492
  ...manifest,
976
- proposer_sign_proof: proof
1493
+ proposer_receipt: proof
977
1494
  });
978
1495
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
979
1496
  return {
@@ -1018,17 +1535,10 @@ function createSetupClient(options = {}) {
1018
1535
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1019
1536
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1020
1537
  if (!nonce) return { ok: false, error: "host_challenge_missing_nonce" };
1021
- const digest = await computeOrgAppVerifyHostDigest({
1022
- org_id: args.orgId,
1023
- app_id: args.appId,
1024
- host: ch.host,
1025
- nonce
1026
- });
1027
1538
  const cer = await runPasskeyCeremony({
1028
1539
  origins: auth.data.origins,
1029
1540
  bearer: auth.data.session.accessToken,
1030
- purpose: "org.app.verify_host",
1031
- messageDigest: digest,
1541
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1032
1542
  displayHint: `Verify host ${ch.host}`,
1033
1543
  openBrowserFlag
1034
1544
  });
@@ -1057,21 +1567,11 @@ function createSetupClient(options = {}) {
1057
1567
  async declarationSet(args) {
1058
1568
  const auth = await requireSession({ origins, sessionPath });
1059
1569
  if (!auth.ok) return auth;
1060
- const sub = auth.data.session.sub;
1061
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1062
1570
  const declaration = { endUsers: args.endUsers, uses: args.uses };
1063
- const declaration_hash = await computeOrgAppDeclarationHash(declaration);
1064
- const digest = await computeOrgAppDeclarationDigest({
1065
- org_id: args.orgId,
1066
- app_id: args.appId,
1067
- declaration_hash,
1068
- actor_sub: sub
1069
- });
1070
1571
  const cer = await runPasskeyCeremony({
1071
1572
  origins: auth.data.origins,
1072
1573
  bearer: auth.data.session.accessToken,
1073
- purpose: "org.app.declaration",
1074
- messageDigest: digest,
1574
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1075
1575
  displayHint: `Declare uses for App ${args.appId}`,
1076
1576
  openBrowserFlag
1077
1577
  });
@@ -1081,10 +1581,47 @@ function createSetupClient(options = {}) {
1081
1581
  auth.data.session.accessToken,
1082
1582
  args.orgId,
1083
1583
  args.appId,
1084
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1584
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1085
1585
  );
1086
1586
  return { ok: true, data: { declaration: out.declaration } };
1087
1587
  },
1588
+ async appRegionsSet(args) {
1589
+ const read = readAppRegionsInput(args.regions);
1590
+ if (!read.ok) return read;
1591
+ const regions = read.regions;
1592
+ const auth = await requireSession({ origins, sessionPath });
1593
+ if (!auth.ok) return auth;
1594
+ const sub = auth.data.session.sub;
1595
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1596
+ const apiOrigin = auth.data.origins.apiOrigin;
1597
+ const bearer = auth.data.session.accessToken;
1598
+ const app = await getApp(apiOrigin, bearer, args.orgId, args.appId);
1599
+ if (app.status === "disabled") return appDisabledRefusal();
1600
+ if (sameAppRegions(app.accepted_regions, regions)) {
1601
+ return { ok: true, data: { accepted_regions: regions, unchanged: true } };
1602
+ }
1603
+ if (regions) {
1604
+ const selectable = await getSelectableAppRegions(apiOrigin).catch(() => null);
1605
+ const closed = selectable ? regions.filter((region) => !selectable.includes(region)) : [];
1606
+ if (closed.length > 0) return regionNotOpenRefusal(closed, selectable);
1607
+ }
1608
+ const cer = await runPasskeyCeremony({
1609
+ origins: auth.data.origins,
1610
+ bearer,
1611
+ statement: orgAppRegionsStatement({ org: args.orgId, app: args.appId, regions }),
1612
+ displayHint: regions ? `Accept new connections to ${app.host} from ${regions.join(", ")} only` : `Accept new connections to ${app.host} from every region Clavis accepts`,
1613
+ openBrowserFlag
1614
+ });
1615
+ const proof = await cer.wait();
1616
+ try {
1617
+ await putAppRegions(apiOrigin, bearer, args.orgId, args.appId, { regions, receipt: proof });
1618
+ return { ok: true, data: { accepted_regions: regions } };
1619
+ } catch (e) {
1620
+ const refusal = appRegionsRefusal(e, regions ?? []);
1621
+ if (refusal) return refusal;
1622
+ throw e;
1623
+ }
1624
+ },
1088
1625
  async emitEnv(args) {
1089
1626
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1090
1627
  if (!jwk) {
@@ -1093,7 +1630,7 @@ function createSetupClient(options = {}) {
1093
1630
  error: "operate_jwk_missing",
1094
1631
  human: {
1095
1632
  needs_human: "login",
1096
- message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
1633
+ message: "Run app-register first so the operate key exists under ~/.config/clavis/apps/"
1097
1634
  }
1098
1635
  };
1099
1636
  }
@@ -1137,28 +1674,48 @@ function redactForTransport(value) {
1137
1674
  return out;
1138
1675
  }
1139
1676
 
1140
- // src/mcp.ts
1677
+ // src/mcp-server.ts
1141
1678
  var require2 = createRequire(import.meta.url);
1142
1679
  var { version: PACKAGE_VERSION } = require2("../package.json");
1680
+ var ORG_CREATION_PROPERTIES = {
1681
+ incorporation: {
1682
+ type: "string",
1683
+ 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)."
1684
+ },
1685
+ accept_customer_terms: {
1686
+ type: "boolean",
1687
+ 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."
1688
+ }
1689
+ };
1143
1690
  var TOOLS = [
1144
1691
  {
1145
1692
  name: "clavis_setup_status",
1146
- description: "List Org, App, signature card, and declaration readiness for the logged-in developers session.",
1693
+ description: "List Org, App, signature card (with what holds it back), place of incorporation, and declaration readiness for the logged-in developers session.",
1147
1694
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
1148
1695
  },
1149
1696
  {
1150
1697
  name: "clavis_login",
1151
- description: "Open the browser for developers Passkey login and store a short-lived session.",
1152
- inputSchema: { type: "object", properties: {}, additionalProperties: false }
1698
+ description: "Start or finish developers Passkey login. First call opens the browser; after the human pastes the page JSON, call again with bridge_json.",
1699
+ inputSchema: {
1700
+ type: "object",
1701
+ properties: {
1702
+ bridge_json: {
1703
+ type: "string",
1704
+ description: "JSON shown on developers /setup/login after Passkey (state + accessToken)."
1705
+ }
1706
+ },
1707
+ additionalProperties: false
1708
+ }
1153
1709
  },
1154
1710
  {
1155
1711
  name: "clavis_org_anchor_plan",
1156
- description: "Start the Org DNS anchor challenge and open Passkey confirmation. Returns a ticket and human action.",
1712
+ 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.",
1157
1713
  inputSchema: {
1158
1714
  type: "object",
1159
1715
  properties: {
1160
1716
  domain: { type: "string" },
1161
- name: { type: "string" }
1717
+ name: { type: "string" },
1718
+ ...ORG_CREATION_PROPERTIES
1162
1719
  },
1163
1720
  required: ["domain"],
1164
1721
  additionalProperties: false
@@ -1183,13 +1740,14 @@ var TOOLS = [
1183
1740
  },
1184
1741
  {
1185
1742
  name: "clavis_org_verify_anchor",
1186
- description: "Verify the Org DNS anchor after TXT and well-known are published.",
1743
+ 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.",
1187
1744
  inputSchema: {
1188
1745
  type: "object",
1189
1746
  properties: {
1190
1747
  domain: { type: "string" },
1191
1748
  nonce: { type: "string" },
1192
- name: { type: "string" }
1749
+ name: { type: "string" },
1750
+ ...ORG_CREATION_PROPERTIES
1193
1751
  },
1194
1752
  required: ["domain", "nonce"],
1195
1753
  additionalProperties: false
@@ -1205,12 +1763,41 @@ var TOOLS = [
1205
1763
  additionalProperties: false
1206
1764
  }
1207
1765
  },
1766
+ {
1767
+ name: "clavis_incorporation_set",
1768
+ 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.",
1769
+ inputSchema: {
1770
+ type: "object",
1771
+ properties: {
1772
+ org_id: { type: "string" },
1773
+ ...ORG_CREATION_PROPERTIES
1774
+ },
1775
+ required: ["org_id"],
1776
+ additionalProperties: false
1777
+ }
1778
+ },
1208
1779
  {
1209
1780
  name: "clavis_card_checkout",
1210
- description: "Open the checkout URL for the signature card.",
1781
+ 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.",
1211
1782
  inputSchema: {
1212
1783
  type: "object",
1213
- properties: { org_id: { type: "string" } },
1784
+ properties: {
1785
+ org_id: { type: "string" },
1786
+ offer: {
1787
+ type: "string",
1788
+ enum: ["meter", "bundle"],
1789
+ description: "meter (pay per use, default) or bundle (monthly bundle)."
1790
+ },
1791
+ lang: {
1792
+ type: "string",
1793
+ enum: ["en", "ja"],
1794
+ description: "Language of the consent statement shown to the customer (default en). The purchase record keeps this language."
1795
+ },
1796
+ consent_billing_data: {
1797
+ type: "boolean",
1798
+ description: "true only after the customer (a human) has read the consent statement and consented. Ask them; never set it on their behalf."
1799
+ }
1800
+ },
1214
1801
  required: ["org_id"],
1215
1802
  additionalProperties: false
1216
1803
  }
@@ -1250,6 +1837,29 @@ var TOOLS = [
1250
1837
  additionalProperties: false
1251
1838
  }
1252
1839
  },
1840
+ {
1841
+ name: "clavis_app_regions_set",
1842
+ 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.",
1843
+ inputSchema: {
1844
+ type: "object",
1845
+ properties: {
1846
+ org_id: { type: "string" },
1847
+ app_id: { type: "string" },
1848
+ regions: {
1849
+ type: "array",
1850
+ items: { type: "string", enum: [...APP_REGIONS] },
1851
+ minItems: 1,
1852
+ description: "JP, US, GB, EEA. New connections from anywhere else are refused."
1853
+ },
1854
+ all: {
1855
+ type: "boolean",
1856
+ description: "true to accept every region Clavis accepts (removes the App's list)."
1857
+ }
1858
+ },
1859
+ required: ["org_id", "app_id"],
1860
+ additionalProperties: false
1861
+ }
1862
+ },
1253
1863
  {
1254
1864
  name: "clavis_declaration_set",
1255
1865
  description: "Replace the App use declaration (Passkey). uses becomes the whole declaration. Include every capability to keep. Signature requests need a signature use.",
@@ -1281,25 +1891,33 @@ var TOOLS = [
1281
1891
  inputSchema: {
1282
1892
  type: "object",
1283
1893
  properties: {
1284
- app_id: { type: "string" },
1285
- operate_private_jwk: {
1286
- type: "string",
1287
- description: "Optional if app-register already saved the key under ~/.config/clavis/apps/"
1288
- }
1894
+ app_id: { type: "string" }
1289
1895
  },
1290
1896
  required: ["app_id"],
1291
1897
  additionalProperties: false
1292
1898
  }
1293
1899
  }
1294
1900
  ];
1901
+ function orgCreationTerms(args) {
1902
+ return {
1903
+ incorporation: typeof args.incorporation === "string" ? args.incorporation : void 0,
1904
+ acceptCustomerTerms: args.accept_customer_terms === true
1905
+ };
1906
+ }
1295
1907
  async function dispatch(client, name, args) {
1296
1908
  switch (name) {
1297
1909
  case "clavis_setup_status":
1298
1910
  return client.status();
1299
1911
  case "clavis_login":
1300
- return client.login();
1912
+ return client.login(
1913
+ args.bridge_json ? { bridgeJson: String(args.bridge_json) } : void 0
1914
+ );
1301
1915
  case "clavis_org_anchor_plan":
1302
- return client.orgAnchorPlan(String(args.domain), args.name ? String(args.name) : void 0);
1916
+ return client.orgAnchorPlan(
1917
+ String(args.domain),
1918
+ args.name ? String(args.name) : void 0,
1919
+ orgCreationTerms(args)
1920
+ );
1303
1921
  case "clavis_org_anchor_finish":
1304
1922
  return client.orgAnchorFinish({
1305
1923
  domain: String(args.domain),
@@ -1313,12 +1931,19 @@ async function dispatch(client, name, args) {
1313
1931
  return client.orgVerifyAnchor({
1314
1932
  domain: String(args.domain),
1315
1933
  nonce: String(args.nonce),
1316
- name: args.name ? String(args.name) : void 0
1934
+ name: args.name ? String(args.name) : void 0,
1935
+ ...orgCreationTerms(args)
1317
1936
  });
1318
1937
  case "clavis_policy_bootstrap":
1319
1938
  return client.policyBootstrap(String(args.org_id));
1939
+ case "clavis_incorporation_set":
1940
+ return client.incorporationSet({ orgId: String(args.org_id), ...orgCreationTerms(args) });
1320
1941
  case "clavis_card_checkout":
1321
- return client.cardCheckout(String(args.org_id));
1942
+ return client.cardCheckout(String(args.org_id), {
1943
+ offer: args.offer === "bundle" ? "bundle" : "meter",
1944
+ lang: checkoutLang(args.lang),
1945
+ consentBillingData: args.consent_billing_data === true
1946
+ });
1322
1947
  case "clavis_app_register":
1323
1948
  return client.appRegister({
1324
1949
  orgId: String(args.org_id),
@@ -1330,6 +1955,14 @@ async function dispatch(client, name, args) {
1330
1955
  return client.appHostPlan(String(args.org_id), String(args.app_id));
1331
1956
  case "clavis_app_verify_host":
1332
1957
  return client.appVerifyHost({ orgId: String(args.org_id), appId: String(args.app_id) });
1958
+ case "clavis_app_regions_set": {
1959
+ const choice = chooseAppRegions({
1960
+ ...args.regions !== void 0 ? { regions: Array.isArray(args.regions) ? args.regions.map((code) => String(code)) : [] } : {},
1961
+ all: args.all === true
1962
+ });
1963
+ if (!choice.ok) return choice;
1964
+ return client.appRegionsSet({ orgId: String(args.org_id), appId: String(args.app_id), regions: choice.regions });
1965
+ }
1333
1966
  case "clavis_declaration_set":
1334
1967
  return client.declarationSet({
1335
1968
  orgId: String(args.org_id),
@@ -1339,8 +1972,7 @@ async function dispatch(client, name, args) {
1339
1972
  });
1340
1973
  case "clavis_emit_app_env":
1341
1974
  return client.emitEnv({
1342
- appId: String(args.app_id),
1343
- operatePrivateJwkJson: typeof args.operate_private_jwk === "string" ? args.operate_private_jwk : void 0
1975
+ appId: String(args.app_id)
1344
1976
  });
1345
1977
  default:
1346
1978
  throw new Error(`unknown tool: ${name}`);
@@ -1375,8 +2007,18 @@ async function runMcpServer() {
1375
2007
  const transport = new StdioServerTransport();
1376
2008
  await server.connect(transport);
1377
2009
  }
1378
- var isMain = typeof process.argv[1] === "string" && import.meta.url === pathToFileURL(process.argv[1]).href;
1379
- if (isMain) {
2010
+
2011
+ // src/mcp.ts
2012
+ function startedDirectly() {
2013
+ const entry = process.argv[1];
2014
+ if (typeof entry !== "string") return false;
2015
+ try {
2016
+ return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
2017
+ } catch {
2018
+ return false;
2019
+ }
2020
+ }
2021
+ if (startedDirectly()) {
1380
2022
  runMcpServer().catch((e) => {
1381
2023
  console.error(e);
1382
2024
  process.exit(1);