@clavis.nexus/setup 1.0.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,50 +1,447 @@
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
- import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
13
+ import { generateKeyPair, exportJWK, jwtVerify, importJWK } 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 checkTrustRoot(apiOrigin, trustRootJson) {
184
+ const { createVerifier } = await import('@clavis.nexus/app');
185
+ await createVerifier({ trustRoot: trustRootJson, apiOrigin }).trust();
186
+ return JSON.stringify(JSON.parse(trustRootJson));
187
+ }
188
+
189
+ // src/app-regions.ts
190
+ var APP_REGIONS = ["JP", "US", "GB", "EEA"];
191
+ var CHOICE_HINT = "Pass --regions with one or more of JP, US, GB, EEA (comma-separated), or --all (MCP: regions or all: true).";
192
+ function isAppRegion(value) {
193
+ return APP_REGIONS.includes(value);
194
+ }
195
+ function chooseAppRegions(input2) {
196
+ const listed = input2.regions !== void 0;
197
+ if (input2.all === true && listed) {
198
+ return { ok: false, error: `regions_conflict \u2014 pass either regions or all, not both. ${CHOICE_HINT}` };
199
+ }
200
+ if (input2.all === true) return { ok: true, regions: null };
201
+ if (!listed) return { ok: false, error: `regions_required \u2014 ${CHOICE_HINT}` };
202
+ return { ok: true, regions: input2.regions };
203
+ }
204
+ function readAppRegionsInput(raw) {
205
+ if (raw === null) return { ok: true, regions: null };
206
+ const codes = raw.map((code) => code.trim().toUpperCase());
207
+ if (codes.length === 0 || new Set(codes).size !== codes.length || !codes.every(isAppRegion)) {
208
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
209
+ }
210
+ return { ok: true, regions: APP_REGIONS.filter((region) => codes.includes(region)) };
211
+ }
212
+ function sameAppRegions(stored, next) {
213
+ const current = stored ?? null;
214
+ if (current === null || next === null) return current === next;
215
+ return current.length === next.length && current.every((region, i) => region === next[i]);
216
+ }
217
+ function regionNotOpenRefusal(closed, selectable) {
218
+ const open = selectable && selectable.length > 0 ? ` Regions you can choose now: ${selectable.join(", ")}.` : "";
219
+ return {
220
+ ok: false,
221
+ error: `region_not_open \u2014 Clavis is not accepting new connections from ${closed.join(", ")} right now, so an App cannot accept them.${open}`
222
+ };
223
+ }
224
+ function appDisabledRefusal() {
225
+ return { ok: false, error: "app_disabled \u2014 this App is disabled, so its regions cannot be changed." };
226
+ }
227
+ function appRegionsRefusal(e, regions) {
228
+ if (!(e instanceof SetupApiError)) return null;
229
+ switch (e.code) {
230
+ case "REGION_NOT_OPEN":
231
+ return regionNotOpenRefusal(regions, null);
232
+ case "REGIONS_INVALID":
233
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
234
+ case "APP_DISABLED":
235
+ return appDisabledRefusal();
236
+ case "FORBIDDEN":
237
+ return { ok: false, error: "forbidden \u2014 only an owner or admin of the Org can change the App's regions." };
238
+ default:
239
+ return null;
240
+ }
241
+ }
17
242
  var execFileAsync = promisify(execFile);
243
+ function isLoopbackHost(hostname) {
244
+ const host = hostname.toLowerCase();
245
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
246
+ }
247
+ function assertOpenableBrowserUrl(raw) {
248
+ let url;
249
+ try {
250
+ url = new URL(raw.trim());
251
+ } catch {
252
+ throw new Error("invalid URL");
253
+ }
254
+ if (url.username || url.password) throw new Error("URL must not contain credentials");
255
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost(url.hostname);
256
+ if (url.protocol !== "https:" && !loopbackHttp) {
257
+ throw new Error("only https URLs may be opened in a browser");
258
+ }
259
+ return url.toString();
260
+ }
261
+ function windowsBrowserArgs(raw) {
262
+ const url = assertOpenableBrowserUrl(raw);
263
+ const script = `Start-Process -FilePath '${url.replaceAll("'", "''")}'`;
264
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
265
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
266
+ }
18
267
  async function openBrowser(url) {
268
+ const safe = assertOpenableBrowserUrl(url);
19
269
  if (process.platform === "darwin") {
20
- await execFileAsync("open", [url]);
270
+ await execFileAsync("open", [safe]);
21
271
  return;
22
272
  }
23
273
  if (process.platform === "win32") {
24
- await execFileAsync("cmd", ["/c", "start", "", url]);
274
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
25
275
  return;
26
276
  }
27
- await execFileAsync("xdg-open", [url]);
277
+ await execFileAsync("xdg-open", [safe]);
278
+ }
279
+
280
+ // src/types.ts
281
+ var DEFAULT_ORIGINS = {
282
+ apiOrigin: "https://api.clavis.nexus",
283
+ idOrigin: "https://id.clavis.nexus",
284
+ developersOrigin: "https://developers.clavis.nexus"
285
+ };
286
+ var LEGAL_ORIGIN = "https://legal.clavis.nexus";
287
+
288
+ // src/org-creation.ts
289
+ var INCORPORATION_HINT = "JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)";
290
+ var TERMS_LINKS = `Customer Terms: ${LEGAL_ORIGIN}/en/customer-terms \u2014 DPA: ${LEGAL_ORIGIN}/en/dpa.`;
291
+ var TERMS_HUMAN = {
292
+ needs_human: "terms",
293
+ 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).`
294
+ };
295
+ var INCORPORATION_TERMS_HUMAN = {
296
+ needs_human: "terms",
297
+ 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).`
298
+ };
299
+ function normalizeIncorporation(raw) {
300
+ return (raw ?? "").trim().toUpperCase();
301
+ }
302
+ function checkOrgCreationTerms(terms, human = TERMS_HUMAN) {
303
+ if (terms.acceptCustomerTerms !== true) {
304
+ return { ok: false, error: "customer_terms_not_accepted", human };
305
+ }
306
+ const incorporation = normalizeIncorporation(terms.incorporation);
307
+ if (!incorporation) {
308
+ return {
309
+ ok: false,
310
+ error: `incorporation_required \u2014 pass --incorporation CODE (MCP: incorporation): ${INCORPORATION_HINT}`
311
+ };
312
+ }
313
+ return { ok: true, incorporation };
314
+ }
315
+ function regionClosedRefusal(incorporation) {
316
+ return {
317
+ ok: false,
318
+ error: `region_closed \u2014 Clavis is not accepting new Orgs incorporated in ${incorporation} right now. GET /orgs/regions lists the closed places.`
319
+ };
320
+ }
321
+ function orgCreationRefusal(e, incorporation) {
322
+ if (!(e instanceof SetupApiError)) return null;
323
+ if (e.status === 403 && e.code === "REGION_CLOSED") return regionClosedRefusal(incorporation);
324
+ if (e.code === "TERMS_REQUIRED") return { ok: false, error: "customer_terms_not_accepted", human: TERMS_HUMAN };
325
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
326
+ return null;
327
+ }
328
+ function incorporationInvalidRefusal(incorporation) {
329
+ return {
330
+ ok: false,
331
+ error: `incorporation_invalid \u2014 ${incorporation || "(empty)"} is not a place of incorporation Clavis accepts. Use ${INCORPORATION_HINT}.`
332
+ };
333
+ }
334
+
335
+ // src/card.ts
336
+ function checkoutLang(raw) {
337
+ return raw === "ja" ? "ja" : "en";
338
+ }
339
+ var BILLING_CONSENT = {
340
+ en: {
341
+ lead: "Subscribing needs the customer's own consent. Show them the statement below and ask. Do not consent on their behalf.",
342
+ 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.",
343
+ 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.`,
344
+ versions: (terms, dpa) => `This purchase is made under Customer Terms ${terms} and DPA ${dpa}.`,
345
+ next: "If they consent, run again with --consent-billing-data (MCP: consent_billing_data: true)."
346
+ },
347
+ ja: {
348
+ 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",
349
+ 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",
350
+ 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`,
351
+ 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`,
352
+ 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"
353
+ }
354
+ };
355
+ function billingConsentHuman(acceptance, lang) {
356
+ const copy = BILLING_CONSENT[lang];
357
+ return {
358
+ needs_human: "terms",
359
+ message: [
360
+ copy.lead,
361
+ copy.statement,
362
+ copy.info(`${LEGAL_ORIGIN}/${lang}/privacy`),
363
+ copy.versions(acceptance.customer_terms_version, acceptance.dpa_version),
364
+ copy.next
365
+ ].join("\n")
366
+ };
367
+ }
368
+ function incorporationNeededRefusal(orgId, stale) {
369
+ 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.";
370
+ return {
371
+ ok: false,
372
+ error: stale ? "incorporation_stale" : "incorporation_required",
373
+ human: {
374
+ needs_human: "terms",
375
+ message: `${why} Run: clavis incorporation-set ${orgId} --incorporation CODE --accept-customer-terms (MCP: clavis_incorporation_set), after the customer agrees.`
376
+ }
377
+ };
378
+ }
379
+ function purchaseRegionClosedRefusal(incorporation) {
380
+ return {
381
+ ok: false,
382
+ error: `region_closed \u2014 new subscriptions are not accepted right now for Orgs incorporated in ${incorporation}.`
383
+ };
384
+ }
385
+ function declarationRegionClosedRefusal(incorporation) {
386
+ return {
387
+ ok: false,
388
+ error: `region_closed \u2014 ${incorporation} cannot be declared as the place of incorporation right now. GET /orgs/regions lists the closed places.`
389
+ };
390
+ }
391
+ function checkoutRefusal(e, args) {
392
+ if (!(e instanceof SetupApiError)) return null;
393
+ switch (e.code) {
394
+ case "REGION_CLOSED":
395
+ return purchaseRegionClosedRefusal(args.incorporation);
396
+ case "INCORPORATION":
397
+ return incorporationNeededRefusal(args.orgId, e.message === "incorporation_stale");
398
+ case "AGE_INELIGIBLE":
399
+ return { ok: false, error: "age_ineligible \u2014 an organisation contract can be made by someone who is 18 or older." };
400
+ case "AGE_BAND_REQUIRED":
401
+ return {
402
+ ok: false,
403
+ error: "age_band_required \u2014 this account has no age record, so the organisation contract can't continue."
404
+ };
405
+ case "BILLING_SUBJECT":
406
+ return {
407
+ ok: false,
408
+ error: "billing_subject_taken \u2014 this account already pays for another Org. Another owner or admin of this Org can subscribe instead."
409
+ };
410
+ case "CHECKOUT_CLOSED":
411
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
412
+ default:
413
+ return null;
414
+ }
415
+ }
416
+ function incorporationSetRefusal(e, incorporation) {
417
+ if (!(e instanceof SetupApiError)) return null;
418
+ if (e.code === "REGION_CLOSED") return declarationRegionClosedRefusal(incorporation);
419
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
420
+ return null;
28
421
  }
29
422
 
30
423
  // src/safe-browser-url.ts
31
- function parseHttpsUrl(raw) {
424
+ function isLoopbackHost2(hostname) {
425
+ const host = hostname.toLowerCase();
426
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
427
+ }
428
+ function parseBrowserUrl(raw) {
32
429
  let u;
33
430
  try {
34
431
  u = new URL(raw.trim());
35
432
  } catch {
36
433
  throw new Error("invalid URL");
37
434
  }
38
- if (u.protocol !== "https:") {
39
- throw new Error("only https URLs may be opened in a browser");
40
- }
41
435
  if (u.username || u.password) {
42
436
  throw new Error("URL must not contain credentials");
43
437
  }
44
438
  return u;
45
439
  }
46
440
  function assertCardCheckoutBrowserUrl(raw) {
47
- const u = parseHttpsUrl(raw);
441
+ const u = parseBrowserUrl(raw);
442
+ if (u.protocol !== "https:") {
443
+ throw new Error("only https URLs may be opened in a browser");
444
+ }
48
445
  const host = u.hostname.toLowerCase();
49
446
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
50
447
  throw new Error("checkout URL host is not allowed");
@@ -52,15 +449,21 @@ function assertCardCheckoutBrowserUrl(raw) {
52
449
  return u.toString();
53
450
  }
54
451
  function assertOriginBrowserUrl(raw, origin) {
55
- const u = parseHttpsUrl(raw);
452
+ const u = parseBrowserUrl(raw);
56
453
  let expected;
57
454
  try {
58
455
  expected = new URL(origin.trim());
59
456
  } catch {
60
457
  throw new Error("invalid expected origin");
61
458
  }
62
- if (expected.protocol !== "https:") {
63
- throw new Error("expected origin must be https");
459
+ if (expected.username || expected.password) {
460
+ throw new Error("expected origin must not contain credentials");
461
+ }
462
+ const loopback = isLoopbackHost2(expected.hostname);
463
+ const https = expected.protocol === "https:" && u.protocol === "https:";
464
+ const loopbackHttp = loopback && expected.protocol === "http:" && u.protocol === "http:";
465
+ if (!https && !loopbackHttp) {
466
+ throw new Error("only https URLs may be opened in a browser");
64
467
  }
65
468
  if (u.origin !== expected.origin) {
66
469
  throw new Error("URL origin does not match the expected origin");
@@ -75,10 +478,6 @@ function bytesToBase64Url(bytes) {
75
478
  const b64 = Buffer.from(bin, "binary").toString("base64");
76
479
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
77
480
  }
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
481
  async function sha256HexUtf8(s) {
83
482
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
84
483
  let out = "";
@@ -101,59 +500,81 @@ function stableStringify(v) {
101
500
  return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(o[k])}`).join(",")}}`;
102
501
  }
103
502
 
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;
503
+ // src/statements.ts
504
+ async function digestOf(value) {
505
+ const bytes = new TextEncoder().encode(canonicalStringify(value));
506
+ return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))}`;
507
+ }
508
+ async function valueDigest(type, value) {
509
+ return digestOf({ type, value });
510
+ }
511
+ async function orgPayloadDigest(payload) {
512
+ let value = payload;
513
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
514
+ const { proposer_receipt: _receipt, ...rest } = payload;
515
+ value = rest;
118
516
  }
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
- );
517
+ return valueDigest("org.payload@1", value);
128
518
  }
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
- );
519
+ function orgAnchorPublishStatement(input2) {
520
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
138
521
  }
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
- );
522
+ function orgPolicyBootstrapStatement(input2) {
523
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
147
524
  }
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
- );
525
+ function orgAppRegisterStatement(input2) {
526
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim() };
527
+ }
528
+ function orgAppVerifyHostStatement(input2) {
529
+ return {
530
+ type: "org.app.verify_host@1",
531
+ org: input2.org.trim(),
532
+ app: input2.app.trim(),
533
+ host: input2.host.trim().toLowerCase(),
534
+ nonce: input2.nonce.trim()
535
+ };
536
+ }
537
+ async function orgAppDeclarationStatement(input2) {
538
+ return {
539
+ type: "org.app.declaration@1",
540
+ org: input2.org.trim(),
541
+ app: input2.app.trim(),
542
+ declaration: input2.declaration === null ? null : await valueDigest("app.declaration@1", { endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
543
+ };
544
+ }
545
+ function orgAppRegionsStatement(input2) {
546
+ return {
547
+ type: "org.app.regions@1",
548
+ org: input2.org.trim(),
549
+ app: input2.app.trim(),
550
+ regions: input2.regions === null ? null : [...new Set(input2.regions)].sort()
551
+ };
552
+ }
553
+ function orgCardIncorporationStatement(input2) {
554
+ return {
555
+ type: "org.card.incorporation_set@1",
556
+ org: input2.org.trim(),
557
+ code: input2.code.trim(),
558
+ customer_terms: input2.customerTerms.trim(),
559
+ dpa: input2.dpa.trim()
560
+ };
561
+ }
562
+ function orgCardCheckoutStatement(input2) {
563
+ return {
564
+ type: "org.card.checkout@1",
565
+ org: input2.org.trim(),
566
+ capability: input2.capability.trim(),
567
+ offer: input2.offer,
568
+ customer_terms: input2.customerTerms.trim(),
569
+ dpa: input2.dpa.trim()
570
+ };
571
+ }
572
+ function sameStatement(a, b) {
573
+ try {
574
+ return canonicalStringify(a) === canonicalStringify(b);
575
+ } catch {
576
+ return false;
577
+ }
157
578
  }
158
579
  async function hashManifestBody(body) {
159
580
  return sha256HexUtf8(canonicalStringify(body));
@@ -163,33 +584,22 @@ function buildAnchorTxtRecord(args) {
163
584
  }
164
585
 
165
586
  // 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;
587
+ function receiptFromCeremonyPayload(payload) {
588
+ if (typeof payload !== "string" || payload.length === 0) {
589
+ throw new Error("Passkey confirmation did not return a receipt.");
175
590
  }
176
- throw new Error("Passkey confirmation did not return a signature.");
591
+ return payload;
177
592
  }
178
593
  async function startCeremony(args) {
179
594
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
180
595
  method: "POST",
596
+ redirect: "error",
181
597
  headers: {
182
598
  Accept: "application/json",
183
599
  "Content-Type": "application/json",
184
600
  Authorization: `Bearer ${args.bearer}`
185
601
  },
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
- })
602
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
193
603
  });
194
604
  const body = await res.json().catch(() => null);
195
605
  if (!res.ok || typeof body?.payload?.ticket !== "string") {
@@ -205,6 +615,7 @@ async function pollCeremonyResult(args) {
205
615
  while (Date.now() < deadline) {
206
616
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
207
617
  method: "POST",
618
+ redirect: "error",
208
619
  headers: {
209
620
  Accept: "application/json",
210
621
  "Content-Type": "application/json",
@@ -214,7 +625,7 @@ async function pollCeremonyResult(args) {
214
625
  });
215
626
  const body = await res.json().catch(() => null);
216
627
  if (res.ok && body?.payload !== void 0) {
217
- return body.payload.payload;
628
+ return body.payload.receipt;
218
629
  }
219
630
  if (res.status === 404) {
220
631
  lastError = body?.message ?? "waiting for Passkey";
@@ -226,7 +637,7 @@ async function pollCeremonyResult(args) {
226
637
  throw new Error(lastError);
227
638
  }
228
639
  function sleep(ms) {
229
- return new Promise((resolve) => setTimeout(resolve, ms));
640
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
230
641
  }
231
642
  function ceremonyPageUrl(idOrigin, ticket) {
232
643
  const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
@@ -236,176 +647,60 @@ function ceremonyPageUrl(idOrigin, ticket) {
236
647
  function setupCeremonyReturnTo(developersOrigin) {
237
648
  return `${developersOrigin.replace(/\/+$/, "")}/developers/setup/ceremony`;
238
649
  }
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);
650
+ async function refuseSymlink(path2) {
651
+ try {
652
+ const st = await lstat(path2);
653
+ if (st.isSymbolicLink()) throw new Error(`refusing to write through a symlink: ${path2}`);
654
+ } catch (e) {
655
+ if (e.code === "ENOENT") return;
656
+ throw e;
266
657
  }
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
- }
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
- );
328
658
  }
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
- });
335
- }
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
- );
350
- }
351
- async function getCard(apiOrigin, bearer, orgId) {
352
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
353
- }
354
- async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signature") {
355
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
356
- method: "POST",
357
- bearer,
358
- body: { capability }
359
- });
360
- }
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();
367
- }
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);
659
+ async function writeMode600(path2, contents) {
660
+ const dir = dirname(path2);
661
+ await mkdir(dir, { recursive: true, mode: 448 });
662
+ await refuseSymlink(dir);
663
+ await refuseSymlink(path2);
664
+ await writeFile(path2, contents, { encoding: "utf8", mode: 384 });
665
+ try {
666
+ await chmod(path2, 384);
667
+ } catch (e) {
668
+ await unlink(path2).catch(() => void 0);
669
+ const message = e instanceof Error ? e.message : String(e);
670
+ throw new Error(`could not set mode 0600 on ${path2}: ${message}`);
671
+ }
372
672
  }
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);
673
+
674
+ // src/operate-key-store.ts
675
+ 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})$/;
676
+ function assertOperateAppId(appId) {
677
+ const app = appId.trim().toLowerCase();
678
+ if (!APP_ID_RE.test(app)) throw new Error("invalid_app_id");
679
+ return app;
680
+ }
681
+ function keysBase() {
682
+ const override = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim();
683
+ return resolve(override || join(homedir(), ".config", "clavis", "apps"));
684
+ }
685
+ function pathInsideKeys(appId, file) {
686
+ const app = assertOperateAppId(appId);
687
+ const base = keysBase();
688
+ const path2 = resolve(base, app, file);
689
+ const rel = relative(base, path2);
690
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("invalid_app_id");
691
+ return path2;
378
692
  }
379
693
  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");
694
+ return pathInsideKeys(appId, "operate-private.jwk.json");
384
695
  }
385
696
  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");
390
- }
391
- async function restrictFileMode(path2) {
392
- try {
393
- await chmod(path2, 384);
394
- } catch (e) {
395
- console.warn(
396
- `clavis: could not set mode 0600 on ${path2}: ${e instanceof Error ? e.message : e}`
397
- );
398
- }
697
+ return pathInsideKeys(appId, "app.env");
399
698
  }
400
699
  async function saveOperatePrivateJwk(appId, jwkJson) {
401
700
  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
- }
701
+ await writeMode600(path2, `${jwkJson.trim()}
702
+ `);
703
+ await chmod(dirname(path2), 448).catch(() => void 0);
409
704
  return path2;
410
705
  }
411
706
  async function readOperatePrivateJwk(appId) {
@@ -418,28 +713,24 @@ async function readOperatePrivateJwk(appId) {
418
713
  }
419
714
  async function writeAppEnvFile(appId, contents) {
420
715
  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);
716
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
717
+ `);
425
718
  return path2;
426
719
  }
427
720
 
428
721
  // src/emit-env.ts
429
722
  async function emitAppEnv(args) {
430
- const pin = args.masterPublicJwkJson?.trim() || process.env.CLAVIS_MASTER_PUBLIC_JWK_JSON?.trim() || "";
723
+ const pin = args.trustRoot?.trim() || process.env.CLAVIS_TRUST_ROOT?.trim() || "";
431
724
  if (!pin) {
432
- throw new Error(
433
- "CLAVIS_MASTER_PUBLIC_JWK_JSON is required. Set it to the master public JWK from GET {apiOrigin}/.well-known/jwks.json."
434
- );
725
+ throw new Error("CLAVIS_TRUST_ROOT is required. Set it to the Clavis Master public JWK (docs.clavis.nexus).");
435
726
  }
436
- const master = await getMasterJwkJson(args.origins.apiOrigin, pin);
727
+ const trustRoot = await checkTrustRoot(args.origins.apiOrigin, pin);
437
728
  const operatePath = await saveOperatePrivateJwk(args.appId, args.operatePrivateJwkJson);
438
729
  const envRecord = {
439
730
  CLAVIS_API_ORIGIN: args.origins.apiOrigin,
440
731
  CLAVIS_APP_ID: args.appId,
441
732
  OPERATE_PRIVATE_JWK: args.operatePrivateJwkJson,
442
- MASTER_PUBLIC_JWK_JSON: master
733
+ CLAVIS_TRUST_ROOT: trustRoot
443
734
  };
444
735
  const envFile = await writeAppEnvFile(args.appId, formatEnvExport(envRecord));
445
736
  return {
@@ -475,30 +766,80 @@ async function generateOperateKeyPair() {
475
766
  privateJwkJson: JSON.stringify(priv)
476
767
  };
477
768
  }
769
+ var SESSION_SLOT = "wauthn-auth-jwt";
770
+ var SLOT_FIELD = /^[a-z][a-z0-9]{1,31}-slot$/;
771
+ var JWK_MEMBERS = ["kty", "crv", "x", "y", "kid", "alg"];
772
+ async function sessionKey(origin, kid) {
773
+ const res = await fetch(`${origin}/.well-known/jwks.json`, { redirect: "error", headers: { Accept: "application/json" } });
774
+ if (!res.ok) throw new Error(`jwks ${res.status}`);
775
+ const doc = await res.json();
776
+ const key = (doc.keys ?? []).find((k) => k && k.kid === kid);
777
+ if (!key) return null;
778
+ const slot = Object.entries(key).find(([name]) => SLOT_FIELD.test(name))?.[1];
779
+ if (slot !== SESSION_SLOT) return null;
780
+ const jwk = {};
781
+ for (const m of JWK_MEMBERS) if (key[m] !== void 0) jwk[m] = key[m];
782
+ return importJWK(jwk, "ES256");
783
+ }
478
784
  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"] });
785
+ const origin = new URL(apiOrigin).origin;
786
+ let refused = false;
787
+ const { payload } = await jwtVerify(
788
+ accessToken,
789
+ async (header) => {
790
+ const key = typeof header.kid === "string" ? await sessionKey(origin, header.kid) : null;
791
+ if (!key) {
792
+ refused = true;
793
+ throw new Error("invalid_access_token_kid");
794
+ }
795
+ return key;
796
+ },
797
+ { algorithms: ["ES256"], issuer: origin, audience: origin, requiredClaims: ["exp", "iss", "aud", "sub"] }
798
+ ).catch((e) => {
799
+ if (refused) throw new Error("invalid_access_token_kid");
800
+ throw e;
801
+ });
802
+ if (payload.tk !== "access") throw new Error("invalid_access_token_kind");
803
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) throw new Error("invalid_access_token_sub");
804
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) throw new Error("invalid_access_token_exp");
805
+ return { sub: payload.sub, expiresAt: payload.exp };
482
806
  }
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
807
  function defaultSessionPath() {
493
808
  const override = process.env.CLAVIS_SESSION_PATH?.trim();
494
809
  if (override) return override;
495
810
  return join(homedir(), ".config", "clavis", "session.json");
496
811
  }
812
+ function isLoopbackHost3(hostname) {
813
+ const host = hostname.toLowerCase();
814
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
815
+ }
816
+ function assertSetupOrigin(raw, name) {
817
+ let url;
818
+ try {
819
+ url = new URL(raw.trim());
820
+ } catch {
821
+ throw new Error(`${name} must be an absolute URL`);
822
+ }
823
+ if (url.username || url.password) throw new Error(`${name} must not contain credentials`);
824
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost3(url.hostname);
825
+ if (url.protocol !== "https:" && !loopbackHttp) throw new Error(`${name} must be https`);
826
+ if (url.pathname !== "/" || url.search || url.hash) throw new Error(`${name} must be an origin`);
827
+ return url.origin;
828
+ }
497
829
  function originsFromEnv(overrides) {
498
830
  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
831
+ apiOrigin: assertSetupOrigin(
832
+ overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
833
+ "apiOrigin"
834
+ ),
835
+ idOrigin: assertSetupOrigin(
836
+ overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
837
+ "idOrigin"
838
+ ),
839
+ developersOrigin: assertSetupOrigin(
840
+ overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin,
841
+ "developersOrigin"
842
+ )
502
843
  };
503
844
  }
504
845
  async function loadSession(path2 = defaultSessionPath()) {
@@ -513,16 +854,8 @@ async function loadSession(path2 = defaultSessionPath()) {
513
854
  }
514
855
  }
515
856
  async function saveSession(session, origins, path2 = defaultSessionPath()) {
516
- await mkdir(dirname(path2), { recursive: true });
517
857
  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
- }
858
+ await writeMode600(path2, JSON.stringify(body, null, 2));
526
859
  }
527
860
  async function clearSession(path2 = defaultSessionPath()) {
528
861
  try {
@@ -533,21 +866,11 @@ async function clearSession(path2 = defaultSessionPath()) {
533
866
 
534
867
  // src/login.ts
535
868
  var MAX_BRIDGE_JSON_CHARS = 16384;
869
+ var PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
536
870
  function pendingLoginPath(sessionPath) {
537
871
  const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
538
872
  return path.join(base, "login-pending.json");
539
873
  }
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
874
  function loginBridgeUrl(developersOrigin, state) {
552
875
  const bridge = new URL("/developers/setup/login", developersOrigin);
553
876
  bridge.searchParams.set("state", state);
@@ -589,12 +912,11 @@ async function sessionFromBridge(args) {
589
912
  if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
590
913
  throw new Error("invalid_bridge_json");
591
914
  }
592
- await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
593
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
915
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
594
916
  return {
595
917
  accessToken: body.accessToken,
596
- ...sub ? { sub } : {},
597
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
918
+ sub: verified.sub,
919
+ expiresAt: verified.expiresAt
598
920
  };
599
921
  }
600
922
  async function readBridgeJsonFromStdin() {
@@ -635,6 +957,14 @@ async function loginWithBrowser(args) {
635
957
  await clearPending(pendingPath);
636
958
  throw new Error("pending_login_origin_mismatch \u2014 run login again");
637
959
  }
960
+ if (!Number.isFinite(pending.createdAt) || Date.now() - pending.createdAt > PENDING_LOGIN_TTL_MS) {
961
+ await clearPending(pendingPath);
962
+ throw new Error("pending_login_expired \u2014 run login again");
963
+ }
964
+ const openUrl2 = assertOriginBrowserUrl(
965
+ loginBridgeUrl(args.origins.developersOrigin, pending.state),
966
+ args.origins.developersOrigin
967
+ );
638
968
  const session2 = await sessionFromBridge({
639
969
  raw: args.bridgeJson,
640
970
  expectedState: pending.state,
@@ -647,12 +977,15 @@ async function loginWithBrowser(args) {
647
977
  human: {
648
978
  needs_human: "login",
649
979
  message: "Session stored.",
650
- open_url: loginBridgeUrl(args.origins.developersOrigin, pending.state)
980
+ open_url: openUrl2
651
981
  }
652
982
  };
653
983
  }
654
984
  const state = randomBytes(16).toString("hex");
655
- const openUrl = loginBridgeUrl(args.origins.developersOrigin, state);
985
+ const openUrl = assertOriginBrowserUrl(
986
+ loginBridgeUrl(args.origins.developersOrigin, state),
987
+ args.origins.developersOrigin
988
+ );
656
989
  await writePending(pendingPath, {
657
990
  v: 1,
658
991
  state,
@@ -662,7 +995,7 @@ async function loginWithBrowser(args) {
662
995
  });
663
996
  if (openFlag) {
664
997
  try {
665
- await openBrowser(assertOriginBrowserUrl(openUrl, args.origins.developersOrigin));
998
+ await openBrowser(openUrl);
666
999
  } catch {
667
1000
  }
668
1001
  }
@@ -695,12 +1028,18 @@ async function loginWithBrowser(args) {
695
1028
  }
696
1029
 
697
1030
  // src/status.ts
698
- function cardActive(card) {
699
- if (!card) return "unknown";
1031
+ function signatureCard(card) {
700
1032
  const sig = card.capabilities?.signature;
701
- if (!sig) return "inactive";
702
- if (sig.subscribed === true || sig.active === true) return "active";
703
- return "inactive";
1033
+ if (!sig) return { signature_card: "inactive" };
1034
+ if (sig.open === true) return { signature_card: "active" };
1035
+ return {
1036
+ signature_card: "inactive",
1037
+ ...Array.isArray(sig.blockers) && sig.blockers.length > 0 ? { signature_card_blockers: sig.blockers } : {}
1038
+ };
1039
+ }
1040
+ function incorporationOf(card) {
1041
+ const inc = card.incorporation;
1042
+ return inc ? { code: inc.code, terms_current: inc.terms_current === true } : null;
704
1043
  }
705
1044
  async function buildSetupStatus(args) {
706
1045
  if (!args.session) {
@@ -710,7 +1049,9 @@ async function buildSetupStatus(args) {
710
1049
  const detailed = [];
711
1050
  for (const org of orgs) {
712
1051
  let setup_complete = false;
713
- let signature_card = "unknown";
1052
+ let card = {
1053
+ signature_card: "unknown"
1054
+ };
714
1055
  let apps = [];
715
1056
  try {
716
1057
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -718,10 +1059,10 @@ async function buildSetupStatus(args) {
718
1059
  } catch {
719
1060
  }
720
1061
  try {
721
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
722
- signature_card = cardActive(card);
1062
+ const view = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
1063
+ card = { ...signatureCard(view), incorporation: incorporationOf(view) };
723
1064
  } catch {
724
- signature_card = "unknown";
1065
+ card = { signature_card: "unknown" };
725
1066
  }
726
1067
  try {
727
1068
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -729,6 +1070,7 @@ async function buildSetupStatus(args) {
729
1070
  app_id: a.app_id,
730
1071
  host: a.host,
731
1072
  status: a.status,
1073
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
732
1074
  declaration_ok: Boolean(
733
1075
  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
1076
  )
@@ -758,7 +1100,7 @@ async function buildSetupStatus(args) {
758
1100
  primary_domain: org.primary_domain,
759
1101
  org_status: org.org_status,
760
1102
  setup_complete,
761
- signature_card,
1103
+ ...card,
762
1104
  apps
763
1105
  });
764
1106
  }
@@ -790,21 +1132,18 @@ async function runPasskeyCeremony(args) {
790
1132
  apiOrigin: args.origins.apiOrigin,
791
1133
  bearer: args.bearer,
792
1134
  returnTo,
793
- purpose: args.purpose,
794
- messageDigest: args.messageDigest,
795
- displayHint: args.displayHint,
796
- label: args.displayHint
1135
+ statement: args.statement
797
1136
  });
798
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1137
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
799
1138
  if (args.openBrowserFlag) {
800
1139
  try {
801
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1140
+ await openBrowser(ceremony_url);
802
1141
  } catch {
803
1142
  }
804
1143
  }
805
1144
  const human = {
806
1145
  needs_human: "passkey",
807
- message: "Confirm with Passkey in the browser, then return to the terminal/agent.",
1146
+ message: `${args.displayHint ? `${args.displayHint}: c` : "C"}onfirm with Passkey in the browser (${args.statement.type}), then return to the terminal/agent.`,
808
1147
  open_url: ceremony_url
809
1148
  };
810
1149
  return {
@@ -817,7 +1156,7 @@ async function runPasskeyCeremony(args) {
817
1156
  bearer: args.bearer,
818
1157
  ticket
819
1158
  });
820
- return signProofFromCeremonyPayload(payload);
1159
+ return receiptFromCeremonyPayload(payload);
821
1160
  }
822
1161
  };
823
1162
  }
@@ -859,18 +1198,43 @@ function createSetupClient(options = {}) {
859
1198
  const report = await buildSetupStatus({ origins, session });
860
1199
  return { ok: true, data: report };
861
1200
  },
862
- async orgAnchorPlan(domain, name) {
1201
+ async orgAnchorPlan(domain, name, terms = {}) {
1202
+ const checked = checkOrgCreationTerms(terms);
1203
+ if (!checked.ok) return checked;
1204
+ const { incorporation } = checked;
863
1205
  const auth = await requireSession({ origins, sessionPath });
864
1206
  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" };
1207
+ const apiOrigin = auth.data.origins.apiOrigin;
1208
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1209
+ if (closed.includes(incorporation)) return regionClosedRefusal(incorporation);
1210
+ let challenge;
1211
+ try {
1212
+ challenge = await postDnsChallenge(apiOrigin, auth.data.session.accessToken, { domain, incorporation });
1213
+ } catch (e) {
1214
+ const refusal = orgCreationRefusal(e, incorporation);
1215
+ if (refusal) return refusal;
1216
+ throw e;
1217
+ }
1218
+ const domainNorm = domain.trim().toLowerCase();
1219
+ 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)) {
1220
+ return { ok: false, error: "challenge_missing_statement" };
1221
+ }
1222
+ const anchorStatement = orgAnchorPublishStatement({ domain: domainNorm, nonce: challenge.nonce, exp: challenge.exp });
1223
+ if (!sameStatement(anchorStatement, challenge.statement)) return { ok: false, error: "challenge_statement_mismatch" };
1224
+ let wellKnown;
1225
+ try {
1226
+ wellKnown = new URL(challenge.well_known_url);
1227
+ } catch {
1228
+ return { ok: false, error: "challenge_url_rejected" };
1229
+ }
1230
+ const txtHost = typeof challenge.txt_host === "string" ? challenge.txt_host.trim().toLowerCase().replace(/\.$/, "") : "";
1231
+ if (wellKnown.protocol !== "https:" || wellKnown.username || wellKnown.password || wellKnown.hostname.toLowerCase() !== domainNorm || txtHost !== domainNorm && !txtHost.endsWith(`.${domainNorm}`)) {
1232
+ return { ok: false, error: "challenge_url_rejected" };
868
1233
  }
869
1234
  const cer = await runPasskeyCeremony({
870
1235
  origins: auth.data.origins,
871
1236
  bearer: auth.data.session.accessToken,
872
- purpose: "org.anchor.publish",
873
- messageDigest: challenge.digest,
1237
+ statement: anchorStatement,
874
1238
  displayHint: `Publish DNS anchor for ${domain}`,
875
1239
  openBrowserFlag
876
1240
  });
@@ -879,9 +1243,10 @@ function createSetupClient(options = {}) {
879
1243
  data: {
880
1244
  domain: challenge.domain,
881
1245
  ...name ? { name } : {},
1246
+ incorporation,
882
1247
  nonce: challenge.nonce,
883
1248
  exp: challenge.exp,
884
- digest: challenge.digest,
1249
+ statement: anchorStatement,
885
1250
  well_known_url: challenge.well_known_url,
886
1251
  txt_host: challenge.txt_host,
887
1252
  ceremony_url: cer.ceremony_url,
@@ -898,12 +1263,12 @@ function createSetupClient(options = {}) {
898
1263
  bearer: auth.data.session.accessToken,
899
1264
  ticket: args.ticket
900
1265
  });
901
- const signProof = signProofFromCeremonyPayload(payload);
1266
+ const receipt = receiptFromCeremonyPayload(payload);
902
1267
  const body = {
903
1268
  v: 1,
904
1269
  kind: "anchor",
905
1270
  domain: args.domain.trim().toLowerCase(),
906
- sign_proof: signProof,
1271
+ receipt,
907
1272
  nonce: args.nonce,
908
1273
  exp: args.exp,
909
1274
  iat: Math.floor(Date.now() / 1e3)
@@ -920,18 +1285,29 @@ function createSetupClient(options = {}) {
920
1285
  txt_value,
921
1286
  human: {
922
1287
  needs_human: "dns",
923
- message: "Publish the well-known JSON and TXT, then call org_verify_anchor."
1288
+ 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
1289
  }
925
1290
  }
926
1291
  };
927
1292
  },
928
1293
  async orgVerifyAnchor(args) {
1294
+ const checked = checkOrgCreationTerms(args);
1295
+ if (!checked.ok) return checked;
1296
+ const { incorporation } = checked;
929
1297
  const auth = await requireSession({ origins, sessionPath });
930
1298
  if (!auth.ok) return auth;
931
1299
  try {
932
- const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, args);
1300
+ const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, {
1301
+ domain: args.domain,
1302
+ nonce: args.nonce,
1303
+ name: args.name,
1304
+ incorporation,
1305
+ acceptCustomerTerms: args.acceptCustomerTerms
1306
+ });
933
1307
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
934
1308
  } catch (e) {
1309
+ const refusal = orgCreationRefusal(e, incorporation);
1310
+ if (refusal) return refusal;
935
1311
  return {
936
1312
  ok: false,
937
1313
  error: e instanceof Error ? e.message : String(e),
@@ -955,18 +1331,10 @@ function createSetupClient(options = {}) {
955
1331
  if (noop.already_active) return { ok: true, data: noop };
956
1332
  } catch {
957
1333
  }
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
1334
  const cer = await runPasskeyCeremony({
966
1335
  origins: auth.data.origins,
967
1336
  bearer: auth.data.session.accessToken,
968
- purpose: "org.policy.bootstrap",
969
- messageDigest: digest,
1337
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
970
1338
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
971
1339
  openBrowserFlag
972
1340
  });
@@ -979,24 +1347,126 @@ function createSetupClient(options = {}) {
979
1347
  );
980
1348
  return { ok: true, data: out };
981
1349
  },
982
- async cardCheckout(orgId) {
1350
+ async incorporationSet(args) {
1351
+ const checked = checkOrgCreationTerms(args, INCORPORATION_TERMS_HUMAN);
1352
+ if (!checked.ok) return checked;
1353
+ const code = checked.incorporation;
1354
+ const auth = await requireSession({ origins, sessionPath });
1355
+ if (!auth.ok) return auth;
1356
+ const sub = auth.data.session.sub;
1357
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1358
+ const apiOrigin = auth.data.origins.apiOrigin;
1359
+ const bearer = auth.data.session.accessToken;
1360
+ const card = await getCard(apiOrigin, bearer, args.orgId);
1361
+ const current = card.incorporation;
1362
+ if (current?.code === code && current.terms_current) {
1363
+ return { ok: true, data: { incorporation: current, unchanged: true } };
1364
+ }
1365
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1366
+ if (closed.includes(code) && current?.code !== code) return declarationRegionClosedRefusal(code);
1367
+ const cer = await runPasskeyCeremony({
1368
+ origins: auth.data.origins,
1369
+ bearer,
1370
+ statement: orgCardIncorporationStatement({
1371
+ org: args.orgId,
1372
+ code,
1373
+ customerTerms: card.acceptance.customer_terms_version,
1374
+ dpa: card.acceptance.dpa_version
1375
+ }),
1376
+ displayHint: `Declare ${code} as the place of incorporation`,
1377
+ openBrowserFlag
1378
+ });
1379
+ const proof = await cer.wait();
1380
+ try {
1381
+ const out = await postCardIncorporation(apiOrigin, bearer, args.orgId, { code, receipt: proof });
1382
+ return { ok: true, data: { incorporation: out.incorporation } };
1383
+ } catch (e) {
1384
+ const refusal = incorporationSetRefusal(e, code);
1385
+ if (refusal) return refusal;
1386
+ throw e;
1387
+ }
1388
+ },
1389
+ async cardCheckout(orgId, opts = {}) {
1390
+ const offer = opts.offer === "bundle" ? "bundle" : "meter";
1391
+ const lang = checkoutLang(opts.lang);
983
1392
  const auth = await requireSession({ origins, sessionPath });
984
1393
  if (!auth.ok) return auth;
985
- const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
1394
+ const sub = auth.data.session.sub;
1395
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1396
+ const apiOrigin = auth.data.origins.apiOrigin;
1397
+ const bearer = auth.data.session.accessToken;
1398
+ const card = await getCard(apiOrigin, bearer, orgId);
1399
+ if (card.suspended) return { ok: false, error: "org_suspended" };
1400
+ const signature = card.capabilities?.signature;
1401
+ const open = offer === "bundle" ? signature?.bundle_checkout_open : signature?.checkout_open;
1402
+ if (!signature || open !== true) {
1403
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
1404
+ }
1405
+ const blockers = signature.blockers ?? [];
1406
+ const subscribed = offer === "bundle" ? signature.tariff === "bundle" : !blockers.includes("subscription");
1407
+ if (subscribed) {
1408
+ const state = blockers.length > 0 ? ` (${blockers.join(", ")})` : "";
1409
+ return {
1410
+ ok: false,
1411
+ error: `already_subscribed \u2014 the signature card already has this subscription${state}. Manage it on developers.`
1412
+ };
1413
+ }
1414
+ const incorporation = card.incorporation;
1415
+ if (!incorporation) return incorporationNeededRefusal(orgId, false);
1416
+ if (!incorporation.terms_current) return incorporationNeededRefusal(orgId, true);
1417
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1418
+ if (closed.includes(incorporation.code)) return purchaseRegionClosedRefusal(incorporation.code);
1419
+ if (opts.consentBillingData !== true) {
1420
+ return { ok: false, error: "billing_data_consent_required", human: billingConsentHuman(card.acceptance, lang) };
1421
+ }
1422
+ const cer = await runPasskeyCeremony({
1423
+ origins: auth.data.origins,
1424
+ bearer,
1425
+ statement: orgCardCheckoutStatement({
1426
+ org: orgId,
1427
+ capability: "signature",
1428
+ offer,
1429
+ customerTerms: card.acceptance.customer_terms_version,
1430
+ dpa: card.acceptance.dpa_version
1431
+ }),
1432
+ displayHint: offer === "bundle" ? "Subscribe to the signature card (monthly bundle)" : "Subscribe to the signature card",
1433
+ openBrowserFlag
1434
+ });
1435
+ const proof = await cer.wait();
1436
+ let url;
1437
+ try {
1438
+ ({ url } = await postCardCheckout(apiOrigin, bearer, orgId, {
1439
+ capability: "signature",
1440
+ offer,
1441
+ consentBillingData: true,
1442
+ uiLocale: lang,
1443
+ receipt: proof
1444
+ }));
1445
+ } catch (e) {
1446
+ const refusal = checkoutRefusal(e, { orgId, incorporation: incorporation.code });
1447
+ if (refusal) return refusal;
1448
+ throw e;
1449
+ }
1450
+ let checkoutUrl;
1451
+ try {
1452
+ checkoutUrl = assertCardCheckoutBrowserUrl(url);
1453
+ } catch (e) {
1454
+ return { ok: false, error: e instanceof Error ? e.message : "checkout_url_rejected" };
1455
+ }
986
1456
  if (openBrowserFlag) {
987
1457
  try {
988
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1458
+ await openBrowser(checkoutUrl);
989
1459
  } catch {
990
1460
  }
991
1461
  }
992
1462
  return {
993
1463
  ok: true,
994
1464
  data: {
995
- url,
1465
+ url: checkoutUrl,
996
1466
  human: {
997
1467
  needs_human: "payment",
998
1468
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
999
- open_url: url
1469
+ open_url: checkoutUrl
1000
1470
  }
1001
1471
  }
1002
1472
  };
@@ -1013,26 +1483,24 @@ function createSetupClient(options = {}) {
1013
1483
  v: 1,
1014
1484
  host: args.host.trim().toLowerCase(),
1015
1485
  display_name: args.displayName.trim(),
1016
- intent_types: args.intentTypes ?? ["generic.sign"],
1486
+ intent_types: args.intentTypes ?? ["generic_sign"],
1017
1487
  max_ttl_seconds: 300,
1018
1488
  operate_kid: keys.kid,
1019
1489
  operate_public_jwk: keys.publicJwk,
1020
1490
  redirect_paths: paths
1021
1491
  };
1022
- const payload_hash = await computePayloadCommitmentHex(manifest);
1023
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
1492
+ const payload_hash = await orgPayloadDigest(manifest);
1024
1493
  const cer = await runPasskeyCeremony({
1025
1494
  origins: auth.data.origins,
1026
1495
  bearer: auth.data.session.accessToken,
1027
- purpose: "org.app.register",
1028
- messageDigest: digest,
1496
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
1029
1497
  displayHint: `Register App ${manifest.host}`,
1030
1498
  openBrowserFlag
1031
1499
  });
1032
1500
  const proof = await cer.wait();
1033
1501
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
1034
1502
  ...manifest,
1035
- proposer_sign_proof: proof
1503
+ proposer_receipt: proof
1036
1504
  });
1037
1505
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
1038
1506
  return {
@@ -1077,17 +1545,10 @@ function createSetupClient(options = {}) {
1077
1545
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1078
1546
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1079
1547
  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
1548
  const cer = await runPasskeyCeremony({
1087
1549
  origins: auth.data.origins,
1088
1550
  bearer: auth.data.session.accessToken,
1089
- purpose: "org.app.verify_host",
1090
- messageDigest: digest,
1551
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1091
1552
  displayHint: `Verify host ${ch.host}`,
1092
1553
  openBrowserFlag
1093
1554
  });
@@ -1116,21 +1577,11 @@ function createSetupClient(options = {}) {
1116
1577
  async declarationSet(args) {
1117
1578
  const auth = await requireSession({ origins, sessionPath });
1118
1579
  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
1580
  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
1581
  const cer = await runPasskeyCeremony({
1130
1582
  origins: auth.data.origins,
1131
1583
  bearer: auth.data.session.accessToken,
1132
- purpose: "org.app.declaration",
1133
- messageDigest: digest,
1584
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1134
1585
  displayHint: `Declare uses for App ${args.appId}`,
1135
1586
  openBrowserFlag
1136
1587
  });
@@ -1140,10 +1591,47 @@ function createSetupClient(options = {}) {
1140
1591
  auth.data.session.accessToken,
1141
1592
  args.orgId,
1142
1593
  args.appId,
1143
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1594
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1144
1595
  );
1145
1596
  return { ok: true, data: { declaration: out.declaration } };
1146
1597
  },
1598
+ async appRegionsSet(args) {
1599
+ const read = readAppRegionsInput(args.regions);
1600
+ if (!read.ok) return read;
1601
+ const regions = read.regions;
1602
+ const auth = await requireSession({ origins, sessionPath });
1603
+ if (!auth.ok) return auth;
1604
+ const sub = auth.data.session.sub;
1605
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1606
+ const apiOrigin = auth.data.origins.apiOrigin;
1607
+ const bearer = auth.data.session.accessToken;
1608
+ const app = await getApp(apiOrigin, bearer, args.orgId, args.appId);
1609
+ if (app.status === "disabled") return appDisabledRefusal();
1610
+ if (sameAppRegions(app.accepted_regions, regions)) {
1611
+ return { ok: true, data: { accepted_regions: regions, unchanged: true } };
1612
+ }
1613
+ if (regions) {
1614
+ const selectable = await getSelectableAppRegions(apiOrigin).catch(() => null);
1615
+ const closed = selectable ? regions.filter((region) => !selectable.includes(region)) : [];
1616
+ if (closed.length > 0) return regionNotOpenRefusal(closed, selectable);
1617
+ }
1618
+ const cer = await runPasskeyCeremony({
1619
+ origins: auth.data.origins,
1620
+ bearer,
1621
+ statement: orgAppRegionsStatement({ org: args.orgId, app: args.appId, regions }),
1622
+ displayHint: regions ? `Accept new connections to ${app.host} from ${regions.join(", ")} only` : `Accept new connections to ${app.host} from every region Clavis accepts`,
1623
+ openBrowserFlag
1624
+ });
1625
+ const proof = await cer.wait();
1626
+ try {
1627
+ await putAppRegions(apiOrigin, bearer, args.orgId, args.appId, { regions, receipt: proof });
1628
+ return { ok: true, data: { accepted_regions: regions } };
1629
+ } catch (e) {
1630
+ const refusal = appRegionsRefusal(e, regions ?? []);
1631
+ if (refusal) return refusal;
1632
+ throw e;
1633
+ }
1634
+ },
1147
1635
  async emitEnv(args) {
1148
1636
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1149
1637
  if (!jwk) {
@@ -1152,7 +1640,7 @@ function createSetupClient(options = {}) {
1152
1640
  error: "operate_jwk_missing",
1153
1641
  human: {
1154
1642
  needs_human: "login",
1155
- message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
1643
+ message: "Run app-register first so the operate key exists under ~/.config/clavis/apps/"
1156
1644
  }
1157
1645
  };
1158
1646
  }
@@ -1196,13 +1684,23 @@ function redactForTransport(value) {
1196
1684
  return out;
1197
1685
  }
1198
1686
 
1199
- // src/mcp.ts
1687
+ // src/mcp-server.ts
1200
1688
  var require2 = createRequire(import.meta.url);
1201
1689
  var { version: PACKAGE_VERSION } = require2("../package.json");
1690
+ var ORG_CREATION_PROPERTIES = {
1691
+ incorporation: {
1692
+ type: "string",
1693
+ 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)."
1694
+ },
1695
+ accept_customer_terms: {
1696
+ type: "boolean",
1697
+ 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."
1698
+ }
1699
+ };
1202
1700
  var TOOLS = [
1203
1701
  {
1204
1702
  name: "clavis_setup_status",
1205
- description: "List Org, App, signature card, and declaration readiness for the logged-in developers session.",
1703
+ description: "List Org, App, signature card (with what holds it back), place of incorporation, and declaration readiness for the logged-in developers session.",
1206
1704
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
1207
1705
  },
1208
1706
  {
@@ -1221,12 +1719,13 @@ var TOOLS = [
1221
1719
  },
1222
1720
  {
1223
1721
  name: "clavis_org_anchor_plan",
1224
- description: "Start the Org DNS anchor challenge and open Passkey confirmation. Returns a ticket and human action.",
1722
+ 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
1723
  inputSchema: {
1226
1724
  type: "object",
1227
1725
  properties: {
1228
1726
  domain: { type: "string" },
1229
- name: { type: "string" }
1727
+ name: { type: "string" },
1728
+ ...ORG_CREATION_PROPERTIES
1230
1729
  },
1231
1730
  required: ["domain"],
1232
1731
  additionalProperties: false
@@ -1251,13 +1750,14 @@ var TOOLS = [
1251
1750
  },
1252
1751
  {
1253
1752
  name: "clavis_org_verify_anchor",
1254
- description: "Verify the Org DNS anchor after TXT and well-known are published.",
1753
+ 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
1754
  inputSchema: {
1256
1755
  type: "object",
1257
1756
  properties: {
1258
1757
  domain: { type: "string" },
1259
1758
  nonce: { type: "string" },
1260
- name: { type: "string" }
1759
+ name: { type: "string" },
1760
+ ...ORG_CREATION_PROPERTIES
1261
1761
  },
1262
1762
  required: ["domain", "nonce"],
1263
1763
  additionalProperties: false
@@ -1273,12 +1773,41 @@ var TOOLS = [
1273
1773
  additionalProperties: false
1274
1774
  }
1275
1775
  },
1776
+ {
1777
+ name: "clavis_incorporation_set",
1778
+ 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.",
1779
+ inputSchema: {
1780
+ type: "object",
1781
+ properties: {
1782
+ org_id: { type: "string" },
1783
+ ...ORG_CREATION_PROPERTIES
1784
+ },
1785
+ required: ["org_id"],
1786
+ additionalProperties: false
1787
+ }
1788
+ },
1276
1789
  {
1277
1790
  name: "clavis_card_checkout",
1278
- description: "Open the checkout URL for the signature card.",
1791
+ 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
1792
  inputSchema: {
1280
1793
  type: "object",
1281
- properties: { org_id: { type: "string" } },
1794
+ properties: {
1795
+ org_id: { type: "string" },
1796
+ offer: {
1797
+ type: "string",
1798
+ enum: ["meter", "bundle"],
1799
+ description: "meter (pay per use, default) or bundle (monthly bundle)."
1800
+ },
1801
+ lang: {
1802
+ type: "string",
1803
+ enum: ["en", "ja"],
1804
+ description: "Language of the consent statement shown to the customer (default en). The purchase record keeps this language."
1805
+ },
1806
+ consent_billing_data: {
1807
+ type: "boolean",
1808
+ description: "true only after the customer (a human) has read the consent statement and consented. Ask them; never set it on their behalf."
1809
+ }
1810
+ },
1282
1811
  required: ["org_id"],
1283
1812
  additionalProperties: false
1284
1813
  }
@@ -1318,6 +1847,29 @@ var TOOLS = [
1318
1847
  additionalProperties: false
1319
1848
  }
1320
1849
  },
1850
+ {
1851
+ name: "clavis_app_regions_set",
1852
+ 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.",
1853
+ inputSchema: {
1854
+ type: "object",
1855
+ properties: {
1856
+ org_id: { type: "string" },
1857
+ app_id: { type: "string" },
1858
+ regions: {
1859
+ type: "array",
1860
+ items: { type: "string", enum: [...APP_REGIONS] },
1861
+ minItems: 1,
1862
+ description: "JP, US, GB, EEA. New connections from anywhere else are refused."
1863
+ },
1864
+ all: {
1865
+ type: "boolean",
1866
+ description: "true to accept every region Clavis accepts (removes the App's list)."
1867
+ }
1868
+ },
1869
+ required: ["org_id", "app_id"],
1870
+ additionalProperties: false
1871
+ }
1872
+ },
1321
1873
  {
1322
1874
  name: "clavis_declaration_set",
1323
1875
  description: "Replace the App use declaration (Passkey). uses becomes the whole declaration. Include every capability to keep. Signature requests need a signature use.",
@@ -1345,21 +1897,23 @@ var TOOLS = [
1345
1897
  },
1346
1898
  {
1347
1899
  name: "clavis_emit_app_env",
1348
- description: "Emit environment variables for @clavis.nexus/app after setup.",
1900
+ description: "Emit environment variables for @clavis.nexus/app after setup. Needs CLAVIS_TRUST_ROOT (the Clavis Master public JWK) in the environment.",
1349
1901
  inputSchema: {
1350
1902
  type: "object",
1351
1903
  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
- }
1904
+ app_id: { type: "string" }
1357
1905
  },
1358
1906
  required: ["app_id"],
1359
1907
  additionalProperties: false
1360
1908
  }
1361
1909
  }
1362
1910
  ];
1911
+ function orgCreationTerms(args) {
1912
+ return {
1913
+ incorporation: typeof args.incorporation === "string" ? args.incorporation : void 0,
1914
+ acceptCustomerTerms: args.accept_customer_terms === true
1915
+ };
1916
+ }
1363
1917
  async function dispatch(client, name, args) {
1364
1918
  switch (name) {
1365
1919
  case "clavis_setup_status":
@@ -1369,7 +1923,11 @@ async function dispatch(client, name, args) {
1369
1923
  args.bridge_json ? { bridgeJson: String(args.bridge_json) } : void 0
1370
1924
  );
1371
1925
  case "clavis_org_anchor_plan":
1372
- return client.orgAnchorPlan(String(args.domain), args.name ? String(args.name) : void 0);
1926
+ return client.orgAnchorPlan(
1927
+ String(args.domain),
1928
+ args.name ? String(args.name) : void 0,
1929
+ orgCreationTerms(args)
1930
+ );
1373
1931
  case "clavis_org_anchor_finish":
1374
1932
  return client.orgAnchorFinish({
1375
1933
  domain: String(args.domain),
@@ -1383,12 +1941,19 @@ async function dispatch(client, name, args) {
1383
1941
  return client.orgVerifyAnchor({
1384
1942
  domain: String(args.domain),
1385
1943
  nonce: String(args.nonce),
1386
- name: args.name ? String(args.name) : void 0
1944
+ name: args.name ? String(args.name) : void 0,
1945
+ ...orgCreationTerms(args)
1387
1946
  });
1388
1947
  case "clavis_policy_bootstrap":
1389
1948
  return client.policyBootstrap(String(args.org_id));
1949
+ case "clavis_incorporation_set":
1950
+ return client.incorporationSet({ orgId: String(args.org_id), ...orgCreationTerms(args) });
1390
1951
  case "clavis_card_checkout":
1391
- return client.cardCheckout(String(args.org_id));
1952
+ return client.cardCheckout(String(args.org_id), {
1953
+ offer: args.offer === "bundle" ? "bundle" : "meter",
1954
+ lang: checkoutLang(args.lang),
1955
+ consentBillingData: args.consent_billing_data === true
1956
+ });
1392
1957
  case "clavis_app_register":
1393
1958
  return client.appRegister({
1394
1959
  orgId: String(args.org_id),
@@ -1400,6 +1965,14 @@ async function dispatch(client, name, args) {
1400
1965
  return client.appHostPlan(String(args.org_id), String(args.app_id));
1401
1966
  case "clavis_app_verify_host":
1402
1967
  return client.appVerifyHost({ orgId: String(args.org_id), appId: String(args.app_id) });
1968
+ case "clavis_app_regions_set": {
1969
+ const choice = chooseAppRegions({
1970
+ ...args.regions !== void 0 ? { regions: Array.isArray(args.regions) ? args.regions.map((code) => String(code)) : [] } : {},
1971
+ all: args.all === true
1972
+ });
1973
+ if (!choice.ok) return choice;
1974
+ return client.appRegionsSet({ orgId: String(args.org_id), appId: String(args.app_id), regions: choice.regions });
1975
+ }
1403
1976
  case "clavis_declaration_set":
1404
1977
  return client.declarationSet({
1405
1978
  orgId: String(args.org_id),
@@ -1409,8 +1982,7 @@ async function dispatch(client, name, args) {
1409
1982
  });
1410
1983
  case "clavis_emit_app_env":
1411
1984
  return client.emitEnv({
1412
- appId: String(args.app_id),
1413
- operatePrivateJwkJson: typeof args.operate_private_jwk === "string" ? args.operate_private_jwk : void 0
1985
+ appId: String(args.app_id)
1414
1986
  });
1415
1987
  default:
1416
1988
  throw new Error(`unknown tool: ${name}`);
@@ -1445,8 +2017,18 @@ async function runMcpServer() {
1445
2017
  const transport = new StdioServerTransport();
1446
2018
  await server.connect(transport);
1447
2019
  }
1448
- var isMain = typeof process.argv[1] === "string" && import.meta.url === pathToFileURL(process.argv[1]).href;
1449
- if (isMain) {
2020
+
2021
+ // src/mcp.ts
2022
+ function startedDirectly() {
2023
+ const entry = process.argv[1];
2024
+ if (typeof entry !== "string") return false;
2025
+ try {
2026
+ return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
2027
+ } catch {
2028
+ return false;
2029
+ }
2030
+ }
2031
+ if (startedDirectly()) {
1450
2032
  runMcpServer().catch((e) => {
1451
2033
  console.error(e);
1452
2034
  process.exit(1);