@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/mcp.js CHANGED
@@ -1,50 +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 path, { 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
14
  import { createInterface } from 'readline/promises';
14
15
  import { stdin, stdout } from 'process';
15
16
  import { randomBytes } from 'crypto';
16
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
+ }
17
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
+ }
18
276
  async function openBrowser(url) {
277
+ const safe = assertOpenableBrowserUrl(url);
19
278
  if (process.platform === "darwin") {
20
- await execFileAsync("open", [url]);
279
+ await execFileAsync("open", [safe]);
21
280
  return;
22
281
  }
23
282
  if (process.platform === "win32") {
24
- await execFileAsync("cmd", ["/c", "start", "", url]);
283
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
25
284
  return;
26
285
  }
27
- 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;
28
430
  }
29
431
 
30
432
  // src/safe-browser-url.ts
31
- 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) {
32
438
  let u;
33
439
  try {
34
440
  u = new URL(raw.trim());
35
441
  } catch {
36
442
  throw new Error("invalid URL");
37
443
  }
38
- if (u.protocol !== "https:") {
39
- throw new Error("only https URLs may be opened in a browser");
40
- }
41
444
  if (u.username || u.password) {
42
445
  throw new Error("URL must not contain credentials");
43
446
  }
44
447
  return u;
45
448
  }
46
449
  function assertCardCheckoutBrowserUrl(raw) {
47
- 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
+ }
48
454
  const host = u.hostname.toLowerCase();
49
455
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
50
456
  throw new Error("checkout URL host is not allowed");
@@ -52,15 +458,21 @@ function assertCardCheckoutBrowserUrl(raw) {
52
458
  return u.toString();
53
459
  }
54
460
  function assertOriginBrowserUrl(raw, origin) {
55
- const u = parseHttpsUrl(raw);
461
+ const u = parseBrowserUrl(raw);
56
462
  let expected;
57
463
  try {
58
464
  expected = new URL(origin.trim());
59
465
  } catch {
60
466
  throw new Error("invalid expected origin");
61
467
  }
62
- if (expected.protocol !== "https:") {
63
- 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");
64
476
  }
65
477
  if (u.origin !== expected.origin) {
66
478
  throw new Error("URL origin does not match the expected origin");
@@ -75,10 +487,6 @@ function bytesToBase64Url(bytes) {
75
487
  const b64 = Buffer.from(bin, "binary").toString("base64");
76
488
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
77
489
  }
78
- async function sha256Base64Url(text) {
79
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
80
- return bytesToBase64Url(digest);
81
- }
82
490
  async function sha256HexUtf8(s) {
83
491
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
84
492
  let out = "";
@@ -101,311 +509,207 @@ function stableStringify(v) {
101
509
  return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`).join(",")}}`;
102
510
  }
103
511
 
104
- // src/digests.ts
105
- async function computeOrgPolicyBootstrapDigest(input2) {
106
- return sha256Base64Url(
107
- canonicalStringify({
108
- org_id: input2.org_id.trim(),
109
- primary_domain: input2.primary_domain.trim().toLowerCase(),
110
- owner_sub: input2.owner_sub.trim()
111
- })
112
- );
113
- }
114
- async function computePayloadCommitmentHex(payload) {
115
- const o = payload && typeof payload === "object" ? { ...payload } : payload;
116
- if (o && typeof o === "object" && !Array.isArray(o)) {
117
- delete o.proposer_sign_proof;
118
- }
119
- return sha256HexUtf8(canonicalStringify(o));
120
- }
121
- async function computeOrgAppRegisterDigest(input2) {
122
- return sha256Base64Url(
123
- canonicalStringify({
124
- payload_hash: input2.payload_hash.trim().toLowerCase(),
125
- proposer_sub: input2.proposer_sub.trim()
126
- })
127
- );
128
- }
129
- async function computeOrgAppVerifyHostDigest(input2) {
130
- return sha256Base64Url(
131
- canonicalStringify({
132
- app_id: input2.app_id.trim(),
133
- host: input2.host.trim().toLowerCase(),
134
- nonce: input2.nonce.trim(),
135
- org_id: input2.org_id.trim()
136
- })
137
- );
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)))}`;
138
516
  }
139
- async function computeOrgAppDeclarationHash(declaration) {
140
- if (declaration === null) return "cleared";
141
- return sha256Base64Url(
142
- canonicalStringify({
143
- endUsers: declaration.endUsers,
144
- uses: declaration.uses
145
- })
146
- );
517
+ function orgAnchorPublishStatement(input2) {
518
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
147
519
  }
148
- async function computeOrgAppDeclarationDigest(input2) {
149
- return sha256Base64Url(
150
- canonicalStringify({
151
- org_id: input2.org_id.trim(),
152
- app_id: input2.app_id.trim(),
153
- declaration_hash: input2.declaration_hash.trim(),
154
- actor_sub: input2.actor_sub.trim()
155
- })
156
- );
520
+ function orgPolicyBootstrapStatement(input2) {
521
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
157
522
  }
158
- async function hashManifestBody(body) {
159
- return sha256HexUtf8(canonicalStringify(body));
523
+ function orgAppRegisterStatement(input2) {
524
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim().toLowerCase() };
160
525
  }
161
- function buildAnchorTxtRecord(args) {
162
- return `v=1;kind=anchor;hash=${args.hash};nonce=${args.nonce};exp=${args.exp}`;
163
- }
164
-
165
- // src/ceremony.ts
166
- function signProofFromCeremonyPayload(payload) {
167
- if (payload === null || typeof payload !== "object") {
168
- throw new Error("Passkey confirmation did not return a signature.");
169
- }
170
- const o = payload;
171
- const nested = o.sign_proof;
172
- if (nested !== null && typeof nested === "object") return nested;
173
- if (o.v === 1 && o.intent_type === "generic_sign" && typeof o.intent_id === "string" && o.intent_id.length > 0) {
174
- return o;
175
- }
176
- throw new Error("Passkey confirmation did not return a signature.");
177
- }
178
- async function startCeremony(args) {
179
- const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
180
- method: "POST",
181
- headers: {
182
- Accept: "application/json",
183
- "Content-Type": "application/json",
184
- Authorization: `Bearer ${args.bearer}`
185
- },
186
- body: JSON.stringify({
187
- return_to: args.returnTo,
188
- purpose: args.purpose,
189
- ...args.messageDigest ? { message_digest: args.messageDigest } : {},
190
- ...args.displayHint ? { display_hint: args.displayHint } : {},
191
- ...args.label ? { label: args.label } : {}
192
- })
193
- });
194
- const body = await res.json().catch(() => null);
195
- if (!res.ok || typeof body?.payload?.ticket !== "string") {
196
- throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
197
- }
198
- return { ticket: body.payload.ticket, expires_in: body.payload.expires_in };
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
+ };
199
534
  }
200
- async function pollCeremonyResult(args) {
201
- const timeoutMs = args.timeoutMs ?? 5 * 6e4;
202
- const intervalMs = args.intervalMs ?? 1500;
203
- const deadline = Date.now() + timeoutMs;
204
- let lastError = "Passkey confirmation timed out. Complete it in the browser, then retry.";
205
- while (Date.now() < deadline) {
206
- const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
207
- method: "POST",
208
- headers: {
209
- Accept: "application/json",
210
- "Content-Type": "application/json",
211
- Authorization: `Bearer ${args.bearer}`
212
- },
213
- body: JSON.stringify({ ticket: args.ticket })
214
- });
215
- const body = await res.json().catch(() => null);
216
- if (res.ok && body?.payload !== void 0) {
217
- return body.payload.payload;
218
- }
219
- if (res.status === 404) {
220
- lastError = body?.message ?? "waiting for Passkey";
221
- await sleep(intervalMs);
222
- continue;
223
- }
224
- throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
225
- }
226
- throw new Error(lastError);
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
+ };
227
542
  }
228
- function sleep(ms) {
229
- return new Promise((resolve) => setTimeout(resolve, ms));
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
+ };
230
550
  }
231
- function ceremonyPageUrl(idOrigin, ticket) {
232
- const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
233
- u.searchParams.set("ticket", ticket);
234
- return u.toString();
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
+ };
235
559
  }
236
- function setupCeremonyReturnTo(developersOrigin) {
237
- return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
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
+ };
238
569
  }
239
-
240
- // src/org-api.ts
241
- var SetupApiError = class extends Error {
242
- status;
243
- code;
244
- constructor(status, code, message) {
245
- super(message);
246
- this.name = "SetupApiError";
247
- this.status = status;
248
- this.code = code;
249
- }
250
- };
251
- async function apiJson(apiOrigin, path2, opts) {
252
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path2}`, {
253
- method: opts.method ?? "GET",
254
- headers: {
255
- Accept: "application/json",
256
- Authorization: `Bearer ${opts.bearer}`,
257
- ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
258
- },
259
- body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
260
- });
261
- const body = await res.json().catch(() => null);
262
- if (!res.ok) {
263
- const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
264
- const message = typeof body?.message === "string" ? body.message : code;
265
- throw new SetupApiError(res.status, code, message);
570
+ function sameStatement(a, b) {
571
+ try {
572
+ return canonicalStringify(a) === canonicalStringify(b);
573
+ } catch {
574
+ return false;
266
575
  }
267
- return body ?? {};
268
- }
269
- async function listOrgs(apiOrigin, bearer) {
270
- const r = await apiJson(apiOrigin, "/orgs", { bearer });
271
- return r.orgs ?? [];
272
- }
273
- async function getOrg(apiOrigin, bearer, orgId) {
274
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
275
- }
276
- async function postDnsChallenge(apiOrigin, bearer, domain, kind = "anchor") {
277
- return apiJson(apiOrigin, "/orgs/dns/challenge", {
278
- method: "POST",
279
- bearer,
280
- body: { domain: domain.trim(), kind }
281
- });
282
- }
283
- async function postVerifyAnchor(apiOrigin, bearer, args) {
284
- return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
285
- method: "POST",
286
- bearer,
287
- body: {
288
- domain: args.domain.trim(),
289
- nonce: args.nonce,
290
- ...args.name ? { name: args.name.trim() } : {}
291
- }
292
- });
293
- }
294
- async function postPolicyBootstrap(apiOrigin, bearer, orgId, signProof) {
295
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
296
- method: "POST",
297
- bearer,
298
- body: signProof ? { sign_proof: signProof } : {}
299
- });
300
- }
301
- async function listApps(apiOrigin, bearer, orgId) {
302
- const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
303
- bearer
304
- });
305
- return r.apps ?? [];
306
- }
307
- async function getApp(apiOrigin, bearer, orgId, appId) {
308
- const r = await apiJson(
309
- apiOrigin,
310
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
311
- { bearer }
312
- );
313
- return r.app;
314
- }
315
- async function postAppRegister(apiOrigin, bearer, orgId, payload) {
316
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
317
- method: "POST",
318
- bearer,
319
- body: payload
320
- });
321
576
  }
322
- async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
323
- return apiJson(
324
- apiOrigin,
325
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
326
- { bearer }
327
- );
577
+ async function computePayloadCommitmentHex(payload) {
578
+ const o = payload && typeof payload === "object" ? { ...payload } : payload;
579
+ if (o && typeof o === "object" && !Array.isArray(o)) {
580
+ delete o.proposer_receipt;
581
+ }
582
+ return sha256HexUtf8(canonicalStringify(o));
328
583
  }
329
- async function postVerifyHost(apiOrigin, bearer, orgId, appId, signProof) {
330
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
331
- method: "POST",
332
- bearer,
333
- body: { sign_proof: signProof }
334
- });
584
+ async function hashManifestBody(body) {
585
+ return sha256HexUtf8(canonicalStringify(body));
335
586
  }
336
- async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
337
- return apiJson(
338
- apiOrigin,
339
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
340
- {
341
- method: "PUT",
342
- bearer,
343
- body: {
344
- endUsers: args.endUsers,
345
- uses: args.uses,
346
- sign_proof: args.signProof
347
- }
348
- }
349
- );
587
+ function buildAnchorTxtRecord(args) {
588
+ return `v=1;kind=anchor;hash=${args.hash};nonce=${args.nonce};exp=${args.exp}`;
350
589
  }
351
- async function getCard(apiOrigin, bearer, orgId) {
352
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
590
+
591
+ // src/ceremony.ts
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.");
595
+ }
596
+ const o = payload;
597
+ if (o.type !== "receipt@1" || o.statement === null || typeof o.statement !== "object") {
598
+ throw new Error("Passkey confirmation did not return a receipt.");
599
+ }
600
+ return o;
353
601
  }
354
- async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signature") {
355
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
602
+ async function startCeremony(args) {
603
+ const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
356
604
  method: "POST",
357
- bearer,
358
- body: { capability }
605
+ redirect: "error",
606
+ headers: {
607
+ Accept: "application/json",
608
+ "Content-Type": "application/json",
609
+ Authorization: `Bearer ${args.bearer}`
610
+ },
611
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
359
612
  });
613
+ const body = await res.json().catch(() => null);
614
+ if (!res.ok || typeof body?.payload?.ticket !== "string") {
615
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
616
+ }
617
+ return { ticket: body.payload.ticket, expires_in: body.payload.expires_in };
360
618
  }
361
- async function fetchJwksDocument(apiOrigin) {
362
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
363
- headers: { Accept: "application/json" }
364
- });
365
- if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
366
- return res.json();
619
+ async function pollCeremonyResult(args) {
620
+ const timeoutMs = args.timeoutMs ?? 5 * 6e4;
621
+ const intervalMs = args.intervalMs ?? 1500;
622
+ const deadline = Date.now() + timeoutMs;
623
+ let lastError = "Passkey confirmation timed out. Complete it in the browser, then retry.";
624
+ while (Date.now() < deadline) {
625
+ const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
626
+ method: "POST",
627
+ redirect: "error",
628
+ headers: {
629
+ Accept: "application/json",
630
+ "Content-Type": "application/json",
631
+ Authorization: `Bearer ${args.bearer}`
632
+ },
633
+ body: JSON.stringify({ ticket: args.ticket })
634
+ });
635
+ const body = await res.json().catch(() => null);
636
+ if (res.ok && body?.payload !== void 0) {
637
+ return body.payload.receipt;
638
+ }
639
+ if (res.status === 404) {
640
+ lastError = body?.message ?? "waiting for Passkey";
641
+ await sleep(intervalMs);
642
+ continue;
643
+ }
644
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
645
+ }
646
+ throw new Error(lastError);
367
647
  }
368
- function masterJwkJsonFromDocument(jwks) {
369
- const master = jwks.master ?? jwks.keys?.find((k) => k.kid === "master" || k.use === "master" || k.alg === "EdDSA");
370
- if (!master) throw new SetupApiError(404, "MASTER_JWK_MISSING", "master JWK not found in JWKS");
371
- return JSON.stringify(master);
648
+ function sleep(ms) {
649
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
372
650
  }
373
- async function getMasterJwkJson(apiOrigin, masterPinJson) {
374
- const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
375
- const doc = await fetchJwksDocument(apiOrigin);
376
- await verifySignedJwksDocument(doc, masterPinJson);
377
- return masterJwkJsonFromDocument(doc);
651
+ function ceremonyPageUrl(idOrigin, ticket) {
652
+ const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
653
+ u.searchParams.set("ticket", ticket);
654
+ return u.toString();
378
655
  }
379
- function operatePrivateJwkPath(appId) {
380
- const app = appId.trim();
381
- if (!app) throw new Error("appId required");
382
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
383
- return join(base, app, "operate-private.jwk.json");
656
+ function setupCeremonyReturnTo(developersOrigin) {
657
+ return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
384
658
  }
385
- function appEnvFilePath(appId) {
386
- const app = appId.trim();
387
- if (!app) throw new Error("appId required");
388
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
389
- return join(base, app, "app.env");
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
+ }
390
667
  }
391
- async function restrictFileMode(path2) {
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 });
392
674
  try {
393
675
  await chmod(path2, 384);
394
676
  } catch (e) {
395
- console.warn(
396
- `clavis: could not set mode 0600 on ${path2}: ${e instanceof Error ? e.message : e}`
397
- );
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}`);
398
680
  }
399
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;
701
+ }
702
+ function operatePrivateJwkPath(appId) {
703
+ return pathInsideKeys(appId, "operate-private.jwk.json");
704
+ }
705
+ function appEnvFilePath(appId) {
706
+ return pathInsideKeys(appId, "app.env");
707
+ }
400
708
  async function saveOperatePrivateJwk(appId, jwkJson) {
401
709
  const path2 = operatePrivateJwkPath(appId);
402
- await mkdir(dirname(path2), { recursive: true });
403
- await writeFile(path2, jwkJson.trim(), "utf8");
404
- await restrictFileMode(path2);
405
- try {
406
- await chmod(dirname(path2), 448);
407
- } catch {
408
- }
710
+ await writeMode600(path2, `${jwkJson.trim()}
711
+ `);
712
+ await chmod(dirname(path2), 448).catch(() => void 0);
409
713
  return path2;
410
714
  }
411
715
  async function readOperatePrivateJwk(appId) {
@@ -418,10 +722,8 @@ async function readOperatePrivateJwk(appId) {
418
722
  }
419
723
  async function writeAppEnvFile(appId, contents) {
420
724
  const path2 = appEnvFilePath(appId);
421
- await mkdir(dirname(path2), { recursive: true });
422
- await writeFile(path2, contents.endsWith("\n") ? contents : `${contents}
423
- `, "utf8");
424
- await restrictFileMode(path2);
725
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
726
+ `);
425
727
  return path2;
426
728
  }
427
729
 
@@ -475,30 +777,59 @@ async function generateOperateKeyPair() {
475
777
  privateJwkJson: JSON.stringify(priv)
476
778
  };
477
779
  }
780
+ var SESSION_SLOT_RE = /^[a-z][a-z0-9]{1,31}-wauthn-auth-jwt(?:-\d{6})?$/;
478
781
  async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
479
- const base = apiOrigin.replace(/\/+$/, "");
480
- const jwks = createRemoteJWKSet(new URL(`${base}/.well-known/jwks.json`));
481
- 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 };
482
796
  }
483
-
484
- // src/types.ts
485
- var DEFAULT_ORIGINS = {
486
- apiOrigin: "https://api.clavis.nexus",
487
- idOrigin: "https://id.clavis.nexus",
488
- developersOrigin: "https://developers.clavis.nexus"
489
- };
490
-
491
- // src/session-store.ts
492
797
  function defaultSessionPath() {
493
798
  const override = process.env.CLAVIS_SESSION_PATH?.trim();
494
799
  if (override) return override;
495
800
  return join(homedir(), ".config", "clavis", "session.json");
496
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
+ }
497
819
  function originsFromEnv(overrides) {
498
820
  return {
499
- apiOrigin: overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
500
- idOrigin: overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
501
- 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
+ )
502
833
  };
503
834
  }
504
835
  async function loadSession(path2 = defaultSessionPath()) {
@@ -513,16 +844,8 @@ async function loadSession(path2 = defaultSessionPath()) {
513
844
  }
514
845
  }
515
846
  async function saveSession(session, origins, path2 = defaultSessionPath()) {
516
- await mkdir(dirname(path2), { recursive: true });
517
847
  const body = { v: 1, origins, session, savedAt: Date.now() };
518
- await writeFile(path2, JSON.stringify(body, null, 2), "utf8");
519
- try {
520
- await chmod(path2, 384);
521
- } catch (e) {
522
- console.warn(
523
- `clavis: could not set session file mode 0600 (${path2}): ${e instanceof Error ? e.message : e}`
524
- );
525
- }
848
+ await writeMode600(path2, JSON.stringify(body, null, 2));
526
849
  }
527
850
  async function clearSession(path2 = defaultSessionPath()) {
528
851
  try {
@@ -533,21 +856,11 @@ async function clearSession(path2 = defaultSessionPath()) {
533
856
 
534
857
  // src/login.ts
535
858
  var MAX_BRIDGE_JSON_CHARS = 16384;
859
+ var PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
536
860
  function pendingLoginPath(sessionPath) {
537
861
  const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
538
862
  return path.join(base, "login-pending.json");
539
863
  }
540
- function subFromJwt(accessToken) {
541
- try {
542
- const part = accessToken.split(".")[1];
543
- if (!part) return void 0;
544
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
545
- const payload = JSON.parse(json);
546
- return typeof payload.sub === "string" ? payload.sub : void 0;
547
- } catch {
548
- return void 0;
549
- }
550
- }
551
864
  function loginBridgeUrl(developersOrigin, state) {
552
865
  const bridge = new URL("/developers/setup/login", developersOrigin);
553
866
  bridge.searchParams.set("state", state);
@@ -589,12 +902,11 @@ async function sessionFromBridge(args) {
589
902
  if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
590
903
  throw new Error("invalid_bridge_json");
591
904
  }
592
- await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
593
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
905
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
594
906
  return {
595
907
  accessToken: body.accessToken,
596
- ...sub ? { sub } : {},
597
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
908
+ sub: verified.sub,
909
+ expiresAt: verified.expiresAt
598
910
  };
599
911
  }
600
912
  async function readBridgeJsonFromStdin() {
@@ -635,6 +947,14 @@ async function loginWithBrowser(args) {
635
947
  await clearPending(pendingPath);
636
948
  throw new Error("pending_login_origin_mismatch \u2014 run login again");
637
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
+ );
638
958
  const session2 = await sessionFromBridge({
639
959
  raw: args.bridgeJson,
640
960
  expectedState: pending.state,
@@ -647,12 +967,15 @@ async function loginWithBrowser(args) {
647
967
  human: {
648
968
  needs_human: "login",
649
969
  message: "Session stored.",
650
- open_url: loginBridgeUrl(args.origins.developersOrigin, pending.state)
970
+ open_url: openUrl2
651
971
  }
652
972
  };
653
973
  }
654
974
  const state = randomBytes(16).toString("hex");
655
- const openUrl = loginBridgeUrl(args.origins.developersOrigin, state);
975
+ const openUrl = assertOriginBrowserUrl(
976
+ loginBridgeUrl(args.origins.developersOrigin, state),
977
+ args.origins.developersOrigin
978
+ );
656
979
  await writePending(pendingPath, {
657
980
  v: 1,
658
981
  state,
@@ -662,7 +985,7 @@ async function loginWithBrowser(args) {
662
985
  });
663
986
  if (openFlag) {
664
987
  try {
665
- await openBrowser(assertOriginBrowserUrl(openUrl, args.origins.developersOrigin));
988
+ await openBrowser(openUrl);
666
989
  } catch {
667
990
  }
668
991
  }
@@ -695,12 +1018,18 @@ async function loginWithBrowser(args) {
695
1018
  }
696
1019
 
697
1020
  // src/status.ts
698
- function cardActive(card) {
699
- if (!card) return "unknown";
1021
+ function signatureCard(card) {
700
1022
  const sig = card.capabilities?.signature;
701
- if (!sig) return "inactive";
702
- if (sig.subscribed === true || sig.active === true) return "active";
703
- 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;
704
1033
  }
705
1034
  async function buildSetupStatus(args) {
706
1035
  if (!args.session) {
@@ -710,7 +1039,9 @@ async function buildSetupStatus(args) {
710
1039
  const detailed = [];
711
1040
  for (const org of orgs) {
712
1041
  let setup_complete = false;
713
- let signature_card = "unknown";
1042
+ let card = {
1043
+ signature_card: "unknown"
1044
+ };
714
1045
  let apps = [];
715
1046
  try {
716
1047
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -718,10 +1049,10 @@ async function buildSetupStatus(args) {
718
1049
  } catch {
719
1050
  }
720
1051
  try {
721
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
722
- 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) };
723
1054
  } catch {
724
- signature_card = "unknown";
1055
+ card = { signature_card: "unknown" };
725
1056
  }
726
1057
  try {
727
1058
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -729,6 +1060,7 @@ async function buildSetupStatus(args) {
729
1060
  app_id: a.app_id,
730
1061
  host: a.host,
731
1062
  status: a.status,
1063
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
732
1064
  declaration_ok: Boolean(
733
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")
734
1066
  )
@@ -758,7 +1090,7 @@ async function buildSetupStatus(args) {
758
1090
  primary_domain: org.primary_domain,
759
1091
  org_status: org.org_status,
760
1092
  setup_complete,
761
- signature_card,
1093
+ ...card,
762
1094
  apps
763
1095
  });
764
1096
  }
@@ -790,21 +1122,18 @@ async function runPasskeyCeremony(args) {
790
1122
  apiOrigin: args.origins.apiOrigin,
791
1123
  bearer: args.bearer,
792
1124
  returnTo,
793
- purpose: args.purpose,
794
- messageDigest: args.messageDigest,
795
- displayHint: args.displayHint,
796
- label: args.displayHint
1125
+ statement: args.statement
797
1126
  });
798
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1127
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
799
1128
  if (args.openBrowserFlag) {
800
1129
  try {
801
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1130
+ await openBrowser(ceremony_url);
802
1131
  } catch {
803
1132
  }
804
1133
  }
805
1134
  const human = {
806
1135
  needs_human: "passkey",
807
- 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.`,
808
1137
  open_url: ceremony_url
809
1138
  };
810
1139
  return {
@@ -817,7 +1146,7 @@ async function runPasskeyCeremony(args) {
817
1146
  bearer: args.bearer,
818
1147
  ticket
819
1148
  });
820
- return signProofFromCeremonyPayload(payload);
1149
+ return receiptFromCeremonyPayload(payload);
821
1150
  }
822
1151
  };
823
1152
  }
@@ -859,18 +1188,43 @@ function createSetupClient(options = {}) {
859
1188
  const report = await buildSetupStatus({ origins, session });
860
1189
  return { ok: true, data: report };
861
1190
  },
862
- 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;
863
1195
  const auth = await requireSession({ origins, sessionPath });
864
1196
  if (!auth.ok) return auth;
865
- const challenge = await postDnsChallenge(auth.data.origins.apiOrigin, auth.data.session.accessToken, domain);
866
- if (!challenge.digest) {
867
- 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" };
868
1223
  }
869
1224
  const cer = await runPasskeyCeremony({
870
1225
  origins: auth.data.origins,
871
1226
  bearer: auth.data.session.accessToken,
872
- purpose: "org.anchor.publish",
873
- messageDigest: challenge.digest,
1227
+ statement: anchorStatement,
874
1228
  displayHint: `Publish DNS anchor for ${domain}`,
875
1229
  openBrowserFlag
876
1230
  });
@@ -879,9 +1233,10 @@ function createSetupClient(options = {}) {
879
1233
  data: {
880
1234
  domain: challenge.domain,
881
1235
  ...name ? { name } : {},
1236
+ incorporation,
882
1237
  nonce: challenge.nonce,
883
1238
  exp: challenge.exp,
884
- digest: challenge.digest,
1239
+ statement: anchorStatement,
885
1240
  well_known_url: challenge.well_known_url,
886
1241
  txt_host: challenge.txt_host,
887
1242
  ceremony_url: cer.ceremony_url,
@@ -898,12 +1253,12 @@ function createSetupClient(options = {}) {
898
1253
  bearer: auth.data.session.accessToken,
899
1254
  ticket: args.ticket
900
1255
  });
901
- const signProof = signProofFromCeremonyPayload(payload);
1256
+ const receipt = receiptFromCeremonyPayload(payload);
902
1257
  const body = {
903
1258
  v: 1,
904
1259
  kind: "anchor",
905
1260
  domain: args.domain.trim().toLowerCase(),
906
- sign_proof: signProof,
1261
+ receipt,
907
1262
  nonce: args.nonce,
908
1263
  exp: args.exp,
909
1264
  iat: Math.floor(Date.now() / 1e3)
@@ -920,18 +1275,29 @@ function createSetupClient(options = {}) {
920
1275
  txt_value,
921
1276
  human: {
922
1277
  needs_human: "dns",
923
- 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."
924
1279
  }
925
1280
  }
926
1281
  };
927
1282
  },
928
1283
  async orgVerifyAnchor(args) {
1284
+ const checked = checkOrgCreationTerms(args);
1285
+ if (!checked.ok) return checked;
1286
+ const { incorporation } = checked;
929
1287
  const auth = await requireSession({ origins, sessionPath });
930
1288
  if (!auth.ok) return auth;
931
1289
  try {
932
- 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
+ });
933
1297
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
934
1298
  } catch (e) {
1299
+ const refusal = orgCreationRefusal(e, incorporation);
1300
+ if (refusal) return refusal;
935
1301
  return {
936
1302
  ok: false,
937
1303
  error: e instanceof Error ? e.message : String(e),
@@ -955,18 +1321,10 @@ function createSetupClient(options = {}) {
955
1321
  if (noop.already_active) return { ok: true, data: noop };
956
1322
  } catch {
957
1323
  }
958
- const sub = auth.data.session.sub;
959
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
960
- const digest = await computeOrgPolicyBootstrapDigest({
961
- org_id: orgId,
962
- primary_domain: detail.primary_domain,
963
- owner_sub: sub
964
- });
965
1324
  const cer = await runPasskeyCeremony({
966
1325
  origins: auth.data.origins,
967
1326
  bearer: auth.data.session.accessToken,
968
- purpose: "org.policy.bootstrap",
969
- messageDigest: digest,
1327
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
970
1328
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
971
1329
  openBrowserFlag
972
1330
  });
@@ -979,24 +1337,126 @@ function createSetupClient(options = {}) {
979
1337
  );
980
1338
  return { ok: true, data: out };
981
1339
  },
982
- 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);
983
1382
  const auth = await requireSession({ origins, sessionPath });
984
1383
  if (!auth.ok) return auth;
985
- 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
+ }
986
1446
  if (openBrowserFlag) {
987
1447
  try {
988
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1448
+ await openBrowser(checkoutUrl);
989
1449
  } catch {
990
1450
  }
991
1451
  }
992
1452
  return {
993
1453
  ok: true,
994
1454
  data: {
995
- url,
1455
+ url: checkoutUrl,
996
1456
  human: {
997
1457
  needs_human: "payment",
998
1458
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
999
- open_url: url
1459
+ open_url: checkoutUrl
1000
1460
  }
1001
1461
  }
1002
1462
  };
@@ -1013,26 +1473,24 @@ function createSetupClient(options = {}) {
1013
1473
  v: 1,
1014
1474
  host: args.host.trim().toLowerCase(),
1015
1475
  display_name: args.displayName.trim(),
1016
- intent_types: args.intentTypes ?? ["generic.sign"],
1476
+ intent_types: args.intentTypes ?? ["generic_sign"],
1017
1477
  max_ttl_seconds: 300,
1018
1478
  operate_kid: keys.kid,
1019
1479
  operate_public_jwk: keys.publicJwk,
1020
1480
  redirect_paths: paths
1021
1481
  };
1022
1482
  const payload_hash = await computePayloadCommitmentHex(manifest);
1023
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
1024
1483
  const cer = await runPasskeyCeremony({
1025
1484
  origins: auth.data.origins,
1026
1485
  bearer: auth.data.session.accessToken,
1027
- purpose: "org.app.register",
1028
- messageDigest: digest,
1486
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
1029
1487
  displayHint: `Register App ${manifest.host}`,
1030
1488
  openBrowserFlag
1031
1489
  });
1032
1490
  const proof = await cer.wait();
1033
1491
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
1034
1492
  ...manifest,
1035
- proposer_sign_proof: proof
1493
+ proposer_receipt: proof
1036
1494
  });
1037
1495
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
1038
1496
  return {
@@ -1077,17 +1535,10 @@ function createSetupClient(options = {}) {
1077
1535
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1078
1536
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1079
1537
  if (!nonce) return { ok: false, error: "host_challenge_missing_nonce" };
1080
- const digest = await computeOrgAppVerifyHostDigest({
1081
- org_id: args.orgId,
1082
- app_id: args.appId,
1083
- host: ch.host,
1084
- nonce
1085
- });
1086
1538
  const cer = await runPasskeyCeremony({
1087
1539
  origins: auth.data.origins,
1088
1540
  bearer: auth.data.session.accessToken,
1089
- purpose: "org.app.verify_host",
1090
- messageDigest: digest,
1541
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1091
1542
  displayHint: `Verify host ${ch.host}`,
1092
1543
  openBrowserFlag
1093
1544
  });
@@ -1116,21 +1567,11 @@ function createSetupClient(options = {}) {
1116
1567
  async declarationSet(args) {
1117
1568
  const auth = await requireSession({ origins, sessionPath });
1118
1569
  if (!auth.ok) return auth;
1119
- const sub = auth.data.session.sub;
1120
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1121
1570
  const declaration = { endUsers: args.endUsers, uses: args.uses };
1122
- const declaration_hash = await computeOrgAppDeclarationHash(declaration);
1123
- const digest = await computeOrgAppDeclarationDigest({
1124
- org_id: args.orgId,
1125
- app_id: args.appId,
1126
- declaration_hash,
1127
- actor_sub: sub
1128
- });
1129
1571
  const cer = await runPasskeyCeremony({
1130
1572
  origins: auth.data.origins,
1131
1573
  bearer: auth.data.session.accessToken,
1132
- purpose: "org.app.declaration",
1133
- messageDigest: digest,
1574
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1134
1575
  displayHint: `Declare uses for App ${args.appId}`,
1135
1576
  openBrowserFlag
1136
1577
  });
@@ -1140,10 +1581,47 @@ function createSetupClient(options = {}) {
1140
1581
  auth.data.session.accessToken,
1141
1582
  args.orgId,
1142
1583
  args.appId,
1143
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1584
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1144
1585
  );
1145
1586
  return { ok: true, data: { declaration: out.declaration } };
1146
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
+ },
1147
1625
  async emitEnv(args) {
1148
1626
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1149
1627
  if (!jwk) {
@@ -1152,7 +1630,7 @@ function createSetupClient(options = {}) {
1152
1630
  error: "operate_jwk_missing",
1153
1631
  human: {
1154
1632
  needs_human: "login",
1155
- 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/"
1156
1634
  }
1157
1635
  };
1158
1636
  }
@@ -1196,13 +1674,23 @@ function redactForTransport(value) {
1196
1674
  return out;
1197
1675
  }
1198
1676
 
1199
- // src/mcp.ts
1677
+ // src/mcp-server.ts
1200
1678
  var require2 = createRequire(import.meta.url);
1201
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
+ };
1202
1690
  var TOOLS = [
1203
1691
  {
1204
1692
  name: "clavis_setup_status",
1205
- 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.",
1206
1694
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
1207
1695
  },
1208
1696
  {
@@ -1221,12 +1709,13 @@ var TOOLS = [
1221
1709
  },
1222
1710
  {
1223
1711
  name: "clavis_org_anchor_plan",
1224
- 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.",
1225
1713
  inputSchema: {
1226
1714
  type: "object",
1227
1715
  properties: {
1228
1716
  domain: { type: "string" },
1229
- name: { type: "string" }
1717
+ name: { type: "string" },
1718
+ ...ORG_CREATION_PROPERTIES
1230
1719
  },
1231
1720
  required: ["domain"],
1232
1721
  additionalProperties: false
@@ -1251,13 +1740,14 @@ var TOOLS = [
1251
1740
  },
1252
1741
  {
1253
1742
  name: "clavis_org_verify_anchor",
1254
- 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.",
1255
1744
  inputSchema: {
1256
1745
  type: "object",
1257
1746
  properties: {
1258
1747
  domain: { type: "string" },
1259
1748
  nonce: { type: "string" },
1260
- name: { type: "string" }
1749
+ name: { type: "string" },
1750
+ ...ORG_CREATION_PROPERTIES
1261
1751
  },
1262
1752
  required: ["domain", "nonce"],
1263
1753
  additionalProperties: false
@@ -1273,12 +1763,41 @@ var TOOLS = [
1273
1763
  additionalProperties: false
1274
1764
  }
1275
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
+ },
1276
1779
  {
1277
1780
  name: "clavis_card_checkout",
1278
- 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.",
1279
1782
  inputSchema: {
1280
1783
  type: "object",
1281
- 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
+ },
1282
1801
  required: ["org_id"],
1283
1802
  additionalProperties: false
1284
1803
  }
@@ -1318,6 +1837,29 @@ var TOOLS = [
1318
1837
  additionalProperties: false
1319
1838
  }
1320
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
+ },
1321
1863
  {
1322
1864
  name: "clavis_declaration_set",
1323
1865
  description: "Replace the App use declaration (Passkey). uses becomes the whole declaration. Include every capability to keep. Signature requests need a signature use.",
@@ -1349,17 +1891,19 @@ var TOOLS = [
1349
1891
  inputSchema: {
1350
1892
  type: "object",
1351
1893
  properties: {
1352
- app_id: { type: "string" },
1353
- operate_private_jwk: {
1354
- type: "string",
1355
- description: "Optional if app-register already saved the key under ~/.config/clavis/apps/"
1356
- }
1894
+ app_id: { type: "string" }
1357
1895
  },
1358
1896
  required: ["app_id"],
1359
1897
  additionalProperties: false
1360
1898
  }
1361
1899
  }
1362
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
+ }
1363
1907
  async function dispatch(client, name, args) {
1364
1908
  switch (name) {
1365
1909
  case "clavis_setup_status":
@@ -1369,7 +1913,11 @@ async function dispatch(client, name, args) {
1369
1913
  args.bridge_json ? { bridgeJson: String(args.bridge_json) } : void 0
1370
1914
  );
1371
1915
  case "clavis_org_anchor_plan":
1372
- 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
+ );
1373
1921
  case "clavis_org_anchor_finish":
1374
1922
  return client.orgAnchorFinish({
1375
1923
  domain: String(args.domain),
@@ -1383,12 +1931,19 @@ async function dispatch(client, name, args) {
1383
1931
  return client.orgVerifyAnchor({
1384
1932
  domain: String(args.domain),
1385
1933
  nonce: String(args.nonce),
1386
- name: args.name ? String(args.name) : void 0
1934
+ name: args.name ? String(args.name) : void 0,
1935
+ ...orgCreationTerms(args)
1387
1936
  });
1388
1937
  case "clavis_policy_bootstrap":
1389
1938
  return client.policyBootstrap(String(args.org_id));
1939
+ case "clavis_incorporation_set":
1940
+ return client.incorporationSet({ orgId: String(args.org_id), ...orgCreationTerms(args) });
1390
1941
  case "clavis_card_checkout":
1391
- 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
+ });
1392
1947
  case "clavis_app_register":
1393
1948
  return client.appRegister({
1394
1949
  orgId: String(args.org_id),
@@ -1400,6 +1955,14 @@ async function dispatch(client, name, args) {
1400
1955
  return client.appHostPlan(String(args.org_id), String(args.app_id));
1401
1956
  case "clavis_app_verify_host":
1402
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
+ }
1403
1966
  case "clavis_declaration_set":
1404
1967
  return client.declarationSet({
1405
1968
  orgId: String(args.org_id),
@@ -1409,8 +1972,7 @@ async function dispatch(client, name, args) {
1409
1972
  });
1410
1973
  case "clavis_emit_app_env":
1411
1974
  return client.emitEnv({
1412
- appId: String(args.app_id),
1413
- operatePrivateJwkJson: typeof args.operate_private_jwk === "string" ? args.operate_private_jwk : void 0
1975
+ appId: String(args.app_id)
1414
1976
  });
1415
1977
  default:
1416
1978
  throw new Error(`unknown tool: ${name}`);
@@ -1445,8 +2007,18 @@ async function runMcpServer() {
1445
2007
  const transport = new StdioServerTransport();
1446
2008
  await server.connect(transport);
1447
2009
  }
1448
- var isMain = typeof process.argv[1] === "string" && import.meta.url === pathToFileURL(process.argv[1]).href;
1449
- 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()) {
1450
2022
  runMcpServer().catch((e) => {
1451
2023
  console.error(e);
1452
2024
  process.exit(1);