@clavis.nexus/setup 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,37 +1,312 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFile } from 'child_process';
3
3
  import { promisify } from 'util';
4
- import { readFile, mkdir, writeFile, chmod, unlink } from 'fs/promises';
5
- import { dirname, join } from 'path';
4
+ import { readFile, chmod, unlink, mkdir, writeFile, lstat } from 'fs/promises';
5
+ import path, { dirname, join, resolve, relative, isAbsolute } from 'path';
6
6
  import { homedir } from 'os';
7
7
  import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
8
- import { createServer } from 'http';
8
+ import { createInterface } from 'readline/promises';
9
+ import { stdin, stdout } from 'process';
9
10
  import { randomBytes } from 'crypto';
10
11
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
11
12
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
12
13
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
13
14
  import { createRequire } from 'module';
14
- import { pathToFileURL } from 'url';
15
15
 
16
16
  var __defProp = Object.defineProperty;
17
17
  var __getOwnPropNames = Object.getOwnPropertyNames;
18
- var __esm = (fn, res) => function __init() {
19
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
18
+ var __esm = (fn, res, err) => function __init() {
19
+ if (err) throw err[0];
20
+ try {
21
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
22
+ } catch (e) {
23
+ throw err = [e], e;
24
+ }
20
25
  };
21
26
  var __export = (target, all) => {
22
27
  for (var name in all)
23
28
  __defProp(target, name, { get: all[name], enumerable: true });
24
29
  };
30
+
31
+ // src/org-api.ts
32
+ async function apiJson(apiOrigin, path2, opts) {
33
+ const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path2}`, {
34
+ method: opts.method ?? "GET",
35
+ redirect: "error",
36
+ headers: {
37
+ Accept: "application/json",
38
+ ...opts.bearer !== void 0 ? { Authorization: `Bearer ${opts.bearer}` } : {},
39
+ ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
40
+ },
41
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
42
+ });
43
+ const body = await res.json().catch(() => null);
44
+ if (!res.ok) {
45
+ const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
46
+ const message = typeof body?.message === "string" ? body.message : code;
47
+ throw new SetupApiError(res.status, code, message);
48
+ }
49
+ return body ?? {};
50
+ }
51
+ async function listOrgs(apiOrigin, bearer) {
52
+ const r = await apiJson(apiOrigin, "/orgs", { bearer });
53
+ return r.orgs ?? [];
54
+ }
55
+ async function getOrg(apiOrigin, bearer, orgId) {
56
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
57
+ }
58
+ function stringList(value) {
59
+ return Array.isArray(value) ? value.filter((code) => typeof code === "string") : [];
60
+ }
61
+ async function getOrgRegions(apiOrigin) {
62
+ const r = await apiJson(
63
+ apiOrigin,
64
+ "/orgs/regions",
65
+ {}
66
+ );
67
+ return r.payload ?? {};
68
+ }
69
+ async function getClosedIncorporations(apiOrigin) {
70
+ return stringList((await getOrgRegions(apiOrigin)).closed_incorporations);
71
+ }
72
+ async function getSelectableAppRegions(apiOrigin) {
73
+ return stringList((await getOrgRegions(apiOrigin)).app_regions);
74
+ }
75
+ async function postDnsChallenge(apiOrigin, bearer, args) {
76
+ return apiJson(apiOrigin, "/orgs/dns/challenge", {
77
+ method: "POST",
78
+ bearer,
79
+ body: {
80
+ domain: args.domain.trim(),
81
+ kind: args.kind ?? "anchor",
82
+ ...args.incorporation !== void 0 ? { incorporation: args.incorporation } : {}
83
+ }
84
+ });
85
+ }
86
+ async function postVerifyAnchor(apiOrigin, bearer, args) {
87
+ return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
88
+ method: "POST",
89
+ bearer,
90
+ body: {
91
+ domain: args.domain.trim(),
92
+ nonce: args.nonce,
93
+ ...args.name ? { name: args.name.trim() } : {},
94
+ accept_customer_terms: args.acceptCustomerTerms === true,
95
+ ...args.incorporation !== void 0 ? { incorporation: args.incorporation } : {}
96
+ }
97
+ });
98
+ }
99
+ async function postPolicyBootstrap(apiOrigin, bearer, orgId, receipt) {
100
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
101
+ method: "POST",
102
+ bearer,
103
+ body: receipt ? { receipt } : {}
104
+ });
105
+ }
106
+ async function listApps(apiOrigin, bearer, orgId) {
107
+ const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
108
+ bearer
109
+ });
110
+ return r.apps ?? [];
111
+ }
112
+ async function getApp(apiOrigin, bearer, orgId, appId) {
113
+ const r = await apiJson(
114
+ apiOrigin,
115
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
116
+ { bearer }
117
+ );
118
+ return r.app;
119
+ }
120
+ async function postAppRegister(apiOrigin, bearer, orgId, payload) {
121
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
122
+ method: "POST",
123
+ bearer,
124
+ body: payload
125
+ });
126
+ }
127
+ async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
128
+ return apiJson(
129
+ apiOrigin,
130
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
131
+ { bearer }
132
+ );
133
+ }
134
+ async function postVerifyHost(apiOrigin, bearer, orgId, appId, receipt) {
135
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
136
+ method: "POST",
137
+ bearer,
138
+ body: { receipt }
139
+ });
140
+ }
141
+ async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
142
+ return apiJson(
143
+ apiOrigin,
144
+ `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
145
+ {
146
+ method: "PUT",
147
+ bearer,
148
+ body: {
149
+ endUsers: args.endUsers,
150
+ uses: args.uses,
151
+ receipt: args.receipt
152
+ }
153
+ }
154
+ );
155
+ }
156
+ async function putAppRegions(apiOrigin, bearer, orgId, appId, args) {
157
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/regions`, {
158
+ method: "PUT",
159
+ bearer,
160
+ body: { accepted_regions: args.regions, receipt: args.receipt }
161
+ });
162
+ }
163
+ async function getCard(apiOrigin, bearer, orgId) {
164
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
165
+ }
166
+ async function postCardIncorporation(apiOrigin, bearer, orgId, args) {
167
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/incorporation`, {
168
+ method: "POST",
169
+ bearer,
170
+ body: { code: args.code, receipt: args.receipt }
171
+ });
172
+ }
173
+ async function postCardCheckout(apiOrigin, bearer, orgId, args) {
174
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
175
+ method: "POST",
176
+ bearer,
177
+ body: {
178
+ capability: args.capability,
179
+ offer: args.offer,
180
+ consent: { polar_provision: args.consentBillingData },
181
+ ui_locale: args.uiLocale,
182
+ receipt: args.receipt
183
+ }
184
+ });
185
+ }
186
+ async function fetchJwksDocument(apiOrigin) {
187
+ const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
188
+ redirect: "error",
189
+ headers: { Accept: "application/json" }
190
+ });
191
+ if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
192
+ return res.json();
193
+ }
194
+ async function getMasterJwkJson(apiOrigin, masterPinJson) {
195
+ const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
196
+ const doc = await fetchJwksDocument(apiOrigin);
197
+ await verifySignedJwksDocument(doc, masterPinJson);
198
+ return JSON.stringify(doc.master);
199
+ }
200
+ var SetupApiError;
201
+ var init_org_api = __esm({
202
+ "src/org-api.ts"() {
203
+ SetupApiError = class extends Error {
204
+ status;
205
+ code;
206
+ constructor(status, code, message) {
207
+ super(message);
208
+ this.name = "SetupApiError";
209
+ this.status = status;
210
+ this.code = code;
211
+ }
212
+ };
213
+ }
214
+ });
215
+
216
+ // src/app-regions.ts
217
+ function isAppRegion(value) {
218
+ return APP_REGIONS.includes(value);
219
+ }
220
+ function chooseAppRegions(input2) {
221
+ const listed = input2.regions !== void 0;
222
+ if (input2.all === true && listed) {
223
+ return { ok: false, error: `regions_conflict \u2014 pass either regions or all, not both. ${CHOICE_HINT}` };
224
+ }
225
+ if (input2.all === true) return { ok: true, regions: null };
226
+ if (!listed) return { ok: false, error: `regions_required \u2014 ${CHOICE_HINT}` };
227
+ return { ok: true, regions: input2.regions };
228
+ }
229
+ function readAppRegionsInput(raw) {
230
+ if (raw === null) return { ok: true, regions: null };
231
+ const codes = raw.map((code) => code.trim().toUpperCase());
232
+ if (codes.length === 0 || new Set(codes).size !== codes.length || !codes.every(isAppRegion)) {
233
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
234
+ }
235
+ return { ok: true, regions: APP_REGIONS.filter((region) => codes.includes(region)) };
236
+ }
237
+ function sameAppRegions(stored, next) {
238
+ const current = stored ?? null;
239
+ if (current === null || next === null) return current === next;
240
+ return current.length === next.length && current.every((region, i) => region === next[i]);
241
+ }
242
+ function regionNotOpenRefusal(closed, selectable) {
243
+ const open = selectable && selectable.length > 0 ? ` Regions you can choose now: ${selectable.join(", ")}.` : "";
244
+ return {
245
+ ok: false,
246
+ error: `region_not_open \u2014 Clavis is not accepting new connections from ${closed.join(", ")} right now, so an App cannot accept them.${open}`
247
+ };
248
+ }
249
+ function appDisabledRefusal() {
250
+ return { ok: false, error: "app_disabled \u2014 this App is disabled, so its regions cannot be changed." };
251
+ }
252
+ function appRegionsRefusal(e, regions) {
253
+ if (!(e instanceof SetupApiError)) return null;
254
+ switch (e.code) {
255
+ case "REGION_NOT_OPEN":
256
+ return regionNotOpenRefusal(regions, null);
257
+ case "REGIONS_INVALID":
258
+ return { ok: false, error: `regions_invalid \u2014 ${CHOICE_HINT}` };
259
+ case "APP_DISABLED":
260
+ return appDisabledRefusal();
261
+ case "FORBIDDEN":
262
+ return { ok: false, error: "forbidden \u2014 only an owner or admin of the Org can change the App's regions." };
263
+ default:
264
+ return null;
265
+ }
266
+ }
267
+ var APP_REGIONS, CHOICE_HINT;
268
+ var init_app_regions = __esm({
269
+ "src/app-regions.ts"() {
270
+ init_org_api();
271
+ APP_REGIONS = ["JP", "US", "GB", "EEA"];
272
+ CHOICE_HINT = "Pass --regions with one or more of JP, US, GB, EEA (comma-separated), or --all (MCP: regions or all: true).";
273
+ }
274
+ });
275
+ function isLoopbackHost(hostname) {
276
+ const host = hostname.toLowerCase();
277
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
278
+ }
279
+ function assertOpenableBrowserUrl(raw) {
280
+ let url;
281
+ try {
282
+ url = new URL(raw.trim());
283
+ } catch {
284
+ throw new Error("invalid URL");
285
+ }
286
+ if (url.username || url.password) throw new Error("URL must not contain credentials");
287
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost(url.hostname);
288
+ if (url.protocol !== "https:" && !loopbackHttp) {
289
+ throw new Error("only https URLs may be opened in a browser");
290
+ }
291
+ return url.toString();
292
+ }
293
+ function windowsBrowserArgs(raw) {
294
+ const url = assertOpenableBrowserUrl(raw);
295
+ const script = `Start-Process -FilePath '${url.replaceAll("'", "''")}'`;
296
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
297
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
298
+ }
25
299
  async function openBrowser(url) {
300
+ const safe = assertOpenableBrowserUrl(url);
26
301
  if (process.platform === "darwin") {
27
- await execFileAsync("open", [url]);
302
+ await execFileAsync("open", [safe]);
28
303
  return;
29
304
  }
30
305
  if (process.platform === "win32") {
31
- await execFileAsync("cmd", ["/c", "start", "", url]);
306
+ await execFileAsync("powershell.exe", windowsBrowserArgs(safe));
32
307
  return;
33
308
  }
34
- await execFileAsync("xdg-open", [url]);
309
+ await execFileAsync("xdg-open", [safe]);
35
310
  }
36
311
  var execFileAsync;
37
312
  var init_browser = __esm({
@@ -40,24 +315,191 @@ var init_browser = __esm({
40
315
  }
41
316
  });
42
317
 
318
+ // src/types.ts
319
+ var DEFAULT_ORIGINS, LEGAL_ORIGIN;
320
+ var init_types = __esm({
321
+ "src/types.ts"() {
322
+ DEFAULT_ORIGINS = {
323
+ apiOrigin: "https://api.clavis.nexus",
324
+ idOrigin: "https://id.clavis.nexus",
325
+ developersOrigin: "https://developers.clavis.nexus"
326
+ };
327
+ LEGAL_ORIGIN = "https://legal.clavis.nexus";
328
+ }
329
+ });
330
+
331
+ // src/org-creation.ts
332
+ function normalizeIncorporation(raw) {
333
+ return (raw ?? "").trim().toUpperCase();
334
+ }
335
+ function checkOrgCreationTerms(terms, human = TERMS_HUMAN) {
336
+ if (terms.acceptCustomerTerms !== true) {
337
+ return { ok: false, error: "customer_terms_not_accepted", human };
338
+ }
339
+ const incorporation = normalizeIncorporation(terms.incorporation);
340
+ if (!incorporation) {
341
+ return {
342
+ ok: false,
343
+ error: `incorporation_required \u2014 pass --incorporation CODE (MCP: incorporation): ${INCORPORATION_HINT}`
344
+ };
345
+ }
346
+ return { ok: true, incorporation };
347
+ }
348
+ function regionClosedRefusal(incorporation) {
349
+ return {
350
+ ok: false,
351
+ error: `region_closed \u2014 Clavis is not accepting new Orgs incorporated in ${incorporation} right now. GET /orgs/regions lists the closed places.`
352
+ };
353
+ }
354
+ function orgCreationRefusal(e, incorporation) {
355
+ if (!(e instanceof SetupApiError)) return null;
356
+ if (e.status === 403 && e.code === "REGION_CLOSED") return regionClosedRefusal(incorporation);
357
+ if (e.code === "TERMS_REQUIRED") return { ok: false, error: "customer_terms_not_accepted", human: TERMS_HUMAN };
358
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
359
+ return null;
360
+ }
361
+ function incorporationInvalidRefusal(incorporation) {
362
+ return {
363
+ ok: false,
364
+ error: `incorporation_invalid \u2014 ${incorporation || "(empty)"} is not a place of incorporation Clavis accepts. Use ${INCORPORATION_HINT}.`
365
+ };
366
+ }
367
+ var INCORPORATION_HINT, TERMS_LINKS, TERMS_HUMAN, INCORPORATION_TERMS_HUMAN;
368
+ var init_org_creation = __esm({
369
+ "src/org-creation.ts"() {
370
+ init_org_api();
371
+ init_types();
372
+ INCORPORATION_HINT = "JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)";
373
+ TERMS_LINKS = `Customer Terms: ${LEGAL_ORIGIN}/en/customer-terms \u2014 DPA: ${LEGAL_ORIGIN}/en/dpa.`;
374
+ TERMS_HUMAN = {
375
+ needs_human: "terms",
376
+ message: `Creating an Org requires the customer to agree to the Customer Terms and the Data Processing Agreement (DPA). ${TERMS_LINKS} Only the customer can decide this. If they agree, pass --accept-customer-terms (MCP: accept_customer_terms: true).`
377
+ };
378
+ INCORPORATION_TERMS_HUMAN = {
379
+ needs_human: "terms",
380
+ message: `Declaring the place of incorporation binds the Org to the current versions of the Customer Terms and the Data Processing Agreement (DPA). ${TERMS_LINKS} Only the customer can decide this. If they agree, pass --accept-customer-terms (MCP: accept_customer_terms: true).`
381
+ };
382
+ }
383
+ });
384
+
385
+ // src/card.ts
386
+ function checkoutLang(raw) {
387
+ return raw === "ja" ? "ja" : "en";
388
+ }
389
+ function billingConsentHuman(acceptance, lang) {
390
+ const copy = BILLING_CONSENT[lang];
391
+ return {
392
+ needs_human: "terms",
393
+ message: [
394
+ copy.lead,
395
+ copy.statement,
396
+ copy.info(`${LEGAL_ORIGIN}/${lang}/privacy`),
397
+ copy.versions(acceptance.customer_terms_version, acceptance.dpa_version),
398
+ copy.next
399
+ ].join("\n")
400
+ };
401
+ }
402
+ function incorporationNeededRefusal(orgId, stale) {
403
+ const why = stale ? "The Customer Terms have a newer version, so the place of incorporation must be declared again." : "Set the place of incorporation before subscribing.";
404
+ return {
405
+ ok: false,
406
+ error: stale ? "incorporation_stale" : "incorporation_required",
407
+ human: {
408
+ needs_human: "terms",
409
+ message: `${why} Run: clavis incorporation-set ${orgId} --incorporation CODE --accept-customer-terms (MCP: clavis_incorporation_set), after the customer agrees.`
410
+ }
411
+ };
412
+ }
413
+ function purchaseRegionClosedRefusal(incorporation) {
414
+ return {
415
+ ok: false,
416
+ error: `region_closed \u2014 new subscriptions are not accepted right now for Orgs incorporated in ${incorporation}.`
417
+ };
418
+ }
419
+ function declarationRegionClosedRefusal(incorporation) {
420
+ return {
421
+ ok: false,
422
+ error: `region_closed \u2014 ${incorporation} cannot be declared as the place of incorporation right now. GET /orgs/regions lists the closed places.`
423
+ };
424
+ }
425
+ function checkoutRefusal(e, args) {
426
+ if (!(e instanceof SetupApiError)) return null;
427
+ switch (e.code) {
428
+ case "REGION_CLOSED":
429
+ return purchaseRegionClosedRefusal(args.incorporation);
430
+ case "INCORPORATION":
431
+ return incorporationNeededRefusal(args.orgId, e.message === "incorporation_stale");
432
+ case "AGE_INELIGIBLE":
433
+ return { ok: false, error: "age_ineligible \u2014 an organisation contract can be made by someone who is 18 or older." };
434
+ case "AGE_BAND_REQUIRED":
435
+ return {
436
+ ok: false,
437
+ error: "age_band_required \u2014 this account has no age record, so the organisation contract can't continue."
438
+ };
439
+ case "BILLING_SUBJECT":
440
+ return {
441
+ ok: false,
442
+ error: "billing_subject_taken \u2014 this account already pays for another Org. Another owner or admin of this Org can subscribe instead."
443
+ };
444
+ case "CHECKOUT_CLOSED":
445
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
446
+ default:
447
+ return null;
448
+ }
449
+ }
450
+ function incorporationSetRefusal(e, incorporation) {
451
+ if (!(e instanceof SetupApiError)) return null;
452
+ if (e.code === "REGION_CLOSED") return declarationRegionClosedRefusal(incorporation);
453
+ if (e.code === "INCORPORATION") return incorporationInvalidRefusal(incorporation);
454
+ return null;
455
+ }
456
+ var BILLING_CONSENT;
457
+ var init_card = __esm({
458
+ "src/card.ts"() {
459
+ init_org_api();
460
+ init_org_creation();
461
+ init_types();
462
+ BILLING_CONSENT = {
463
+ en: {
464
+ lead: "Subscribing needs the customer's own consent. Show them the statement below and ask. Do not consent on their behalf.",
465
+ statement: "I consent to Clavis providing Polar Software Inc. in the United States with my Clavis account identifier, the organisation ID, the feature being purchased, and, after purchase, the organisation's usage of that feature (counts and times), for payment and billing. Polar handles that data under its own privacy notice.",
466
+ info: (privacyUrl) => `Section 5 of the Privacy Notice (${privacyUrl}) sets out the destination country, an outline of the United States regime, and Polar's measures. Without consent you cannot subscribe, and nothing is sent to Polar.`,
467
+ versions: (terms, dpa) => `This purchase is made under Customer Terms ${terms} and DPA ${dpa}.`,
468
+ next: "If they consent, run again with --consent-billing-data (MCP: consent_billing_data: true)."
469
+ },
470
+ ja: {
471
+ lead: "\u8CFC\u5165\u306B\u306F\u9867\u5BA2\u672C\u4EBA\u306E\u540C\u610F\u304C\u8981\u308A\u307E\u3059\u3002\u6B21\u306E\u6587\u3092\u898B\u305B\u3066\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044\u3002\u4EE3\u308F\u308A\u306B\u540C\u610F\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044\u3002",
472
+ statement: "\u6C7A\u6E08\u3068\u8ACB\u6C42\u306E\u305F\u3081\u3001Clavis \u30A2\u30AB\u30A6\u30F3\u30C8\u8B58\u5225\u5B50\u3001Org ID \u3068\u8CFC\u5165\u3059\u308B\u6A5F\u80FD\u3001\u304A\u3088\u3073\u8CFC\u5165\u5F8C\u306E\u5229\u7528\u91CF\uFF08\u4EF6\u6570\u3068\u65E5\u6642\uFF09\u3092\u3001\u7C73\u56FD\u306E Polar Software Inc. \u306B\u63D0\u4F9B\u3059\u308B\u3053\u3068\u306B\u540C\u610F\u3057\u307E\u3059\u3002Polar \u306F\u81EA\u3089\u306E\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u901A\u77E5\u306B\u5F93\u3063\u3066\u53D6\u308A\u6271\u3044\u307E\u3059\u3002",
473
+ info: (privacyUrl) => `\u79FB\u8EE2\u5148\u306E\u56FD\u3001\u7C73\u56FD\u306E\u5236\u5EA6\u306E\u6982\u8981\u3001Polar \u306E\u63AA\u7F6E\u306F\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u901A\u77E5\u306E\u7B2C 5 \u7BC0\uFF08${privacyUrl}\uFF09\u306B\u3042\u308A\u307E\u3059\u3002\u540C\u610F\u3057\u306A\u3044\u5834\u5408\u306F\u8CFC\u5165\u3067\u304D\u305A\u3001Polar \u3078\u306F\u4F55\u3082\u9001\u308A\u307E\u305B\u3093\u3002`,
474
+ versions: (terms, dpa) => `\u3053\u306E\u8CFC\u5165\u306F\u3001\u7D44\u7E54\u306E\u5951\u7D04 ${terms} \u3068 DPA ${dpa} \u306E\u3082\u3068\u3067\u884C\u3044\u307E\u3059\u3002`,
475
+ next: "\u540C\u610F\u3092\u5F97\u305F\u3089\u3001--consent-billing-data\uFF08MCP: consent_billing_data: true\uFF09\u3092\u4ED8\u3051\u3066\u3082\u3046\u4E00\u5EA6\u5B9F\u884C\u3057\u307E\u3059\u3002"
476
+ }
477
+ };
478
+ }
479
+ });
480
+
43
481
  // src/safe-browser-url.ts
44
- function parseHttpsUrl(raw) {
482
+ function isLoopbackHost2(hostname) {
483
+ const host = hostname.toLowerCase();
484
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
485
+ }
486
+ function parseBrowserUrl(raw) {
45
487
  let u;
46
488
  try {
47
489
  u = new URL(raw.trim());
48
490
  } catch {
49
491
  throw new Error("invalid URL");
50
492
  }
51
- if (u.protocol !== "https:") {
52
- throw new Error("only https URLs may be opened in a browser");
53
- }
54
493
  if (u.username || u.password) {
55
494
  throw new Error("URL must not contain credentials");
56
495
  }
57
496
  return u;
58
497
  }
59
498
  function assertCardCheckoutBrowserUrl(raw) {
60
- const u = parseHttpsUrl(raw);
499
+ const u = parseBrowserUrl(raw);
500
+ if (u.protocol !== "https:") {
501
+ throw new Error("only https URLs may be opened in a browser");
502
+ }
61
503
  const host = u.hostname.toLowerCase();
62
504
  if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
63
505
  throw new Error("checkout URL host is not allowed");
@@ -65,15 +507,21 @@ function assertCardCheckoutBrowserUrl(raw) {
65
507
  return u.toString();
66
508
  }
67
509
  function assertOriginBrowserUrl(raw, origin) {
68
- const u = parseHttpsUrl(raw);
510
+ const u = parseBrowserUrl(raw);
69
511
  let expected;
70
512
  try {
71
513
  expected = new URL(origin.trim());
72
514
  } catch {
73
515
  throw new Error("invalid expected origin");
74
516
  }
75
- if (expected.protocol !== "https:") {
76
- throw new Error("expected origin must be https");
517
+ if (expected.username || expected.password) {
518
+ throw new Error("expected origin must not contain credentials");
519
+ }
520
+ const loopback = isLoopbackHost2(expected.hostname);
521
+ const https = expected.protocol === "https:" && u.protocol === "https:";
522
+ const loopbackHttp = loopback && expected.protocol === "http:" && u.protocol === "http:";
523
+ if (!https && !loopbackHttp) {
524
+ throw new Error("only https URLs may be opened in a browser");
77
525
  }
78
526
  if (u.origin !== expected.origin) {
79
527
  throw new Error("URL origin does not match the expected origin");
@@ -92,10 +540,6 @@ function bytesToBase64Url(bytes) {
92
540
  const b64 = Buffer.from(bin, "binary").toString("base64");
93
541
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
94
542
  }
95
- async function sha256Base64Url(text) {
96
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
97
- return bytesToBase64Url(digest);
98
- }
99
543
  async function sha256HexUtf8(s) {
100
544
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
101
545
  let out = "";
@@ -126,101 +570,112 @@ var init_canonical_json = __esm({
126
570
  }
127
571
  });
128
572
 
129
- // src/digests.ts
130
- async function computeOrgPolicyBootstrapDigest(input) {
131
- return sha256Base64Url(
132
- canonicalStringify({
133
- org_id: input.org_id.trim(),
134
- primary_domain: input.primary_domain.trim().toLowerCase(),
135
- owner_sub: input.owner_sub.trim()
136
- })
137
- );
573
+ // src/statements.ts
574
+ async function digestOf(value) {
575
+ const bytes = new TextEncoder().encode(canonicalStringify(value));
576
+ return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))}`;
577
+ }
578
+ function orgAnchorPublishStatement(input2) {
579
+ return { type: "org.anchor.publish@1", domain: input2.domain.trim().toLowerCase(), nonce: input2.nonce, exp: input2.exp };
580
+ }
581
+ function orgPolicyBootstrapStatement(input2) {
582
+ return { type: "org.policy.bootstrap@1", org: input2.org.trim(), domain: input2.domain.trim().toLowerCase() };
583
+ }
584
+ function orgAppRegisterStatement(input2) {
585
+ return { type: "org.app.register@1", org: input2.org.trim(), payload: input2.payload.trim().toLowerCase() };
586
+ }
587
+ function orgAppVerifyHostStatement(input2) {
588
+ return {
589
+ type: "org.app.verify_host@1",
590
+ org: input2.org.trim(),
591
+ app: input2.app.trim(),
592
+ host: input2.host.trim().toLowerCase(),
593
+ nonce: input2.nonce.trim()
594
+ };
595
+ }
596
+ async function orgAppDeclarationStatement(input2) {
597
+ return {
598
+ type: "org.app.declaration@1",
599
+ org: input2.org.trim(),
600
+ app: input2.app.trim(),
601
+ declaration: input2.declaration === null ? null : await digestOf({ endUsers: input2.declaration.endUsers, uses: input2.declaration.uses })
602
+ };
603
+ }
604
+ function orgAppRegionsStatement(input2) {
605
+ return {
606
+ type: "org.app.regions@1",
607
+ org: input2.org.trim(),
608
+ app: input2.app.trim(),
609
+ regions: input2.regions === null ? null : [...new Set(input2.regions)].sort()
610
+ };
611
+ }
612
+ function orgCardIncorporationStatement(input2) {
613
+ return {
614
+ type: "org.card.incorporation_set@1",
615
+ org: input2.org.trim(),
616
+ code: input2.code.trim(),
617
+ customer_terms: input2.customerTerms.trim(),
618
+ dpa: input2.dpa.trim()
619
+ };
620
+ }
621
+ function orgCardCheckoutStatement(input2) {
622
+ return {
623
+ type: "org.card.checkout@1",
624
+ org: input2.org.trim(),
625
+ capability: input2.capability.trim(),
626
+ offer: input2.offer,
627
+ customer_terms: input2.customerTerms.trim(),
628
+ dpa: input2.dpa.trim()
629
+ };
630
+ }
631
+ function sameStatement(a, b) {
632
+ try {
633
+ return canonicalStringify(a) === canonicalStringify(b);
634
+ } catch {
635
+ return false;
636
+ }
138
637
  }
139
638
  async function computePayloadCommitmentHex(payload) {
140
639
  const o = payload && typeof payload === "object" ? { ...payload } : payload;
141
640
  if (o && typeof o === "object" && !Array.isArray(o)) {
142
- delete o.proposer_sign_proof;
641
+ delete o.proposer_receipt;
143
642
  }
144
643
  return sha256HexUtf8(canonicalStringify(o));
145
644
  }
146
- async function computeOrgAppRegisterDigest(input) {
147
- return sha256Base64Url(
148
- canonicalStringify({
149
- payload_hash: input.payload_hash.trim().toLowerCase(),
150
- proposer_sub: input.proposer_sub.trim()
151
- })
152
- );
153
- }
154
- async function computeOrgAppVerifyHostDigest(input) {
155
- return sha256Base64Url(
156
- canonicalStringify({
157
- app_id: input.app_id.trim(),
158
- host: input.host.trim().toLowerCase(),
159
- nonce: input.nonce.trim(),
160
- org_id: input.org_id.trim()
161
- })
162
- );
163
- }
164
- async function computeOrgAppDeclarationHash(declaration) {
165
- if (declaration === null) return "cleared";
166
- return sha256Base64Url(
167
- canonicalStringify({
168
- endUsers: declaration.endUsers,
169
- uses: declaration.uses
170
- })
171
- );
172
- }
173
- async function computeOrgAppDeclarationDigest(input) {
174
- return sha256Base64Url(
175
- canonicalStringify({
176
- org_id: input.org_id.trim(),
177
- app_id: input.app_id.trim(),
178
- declaration_hash: input.declaration_hash.trim(),
179
- actor_sub: input.actor_sub.trim()
180
- })
181
- );
182
- }
183
645
  async function hashManifestBody(body) {
184
646
  return sha256HexUtf8(canonicalStringify(body));
185
647
  }
186
648
  function buildAnchorTxtRecord(args) {
187
649
  return `v=1;kind=anchor;hash=${args.hash};nonce=${args.nonce};exp=${args.exp}`;
188
650
  }
189
- var init_digests = __esm({
190
- "src/digests.ts"() {
651
+ var init_statements = __esm({
652
+ "src/statements.ts"() {
191
653
  init_base64url();
192
654
  init_canonical_json();
193
655
  }
194
656
  });
195
657
 
196
658
  // src/ceremony.ts
197
- function signProofFromCeremonyPayload(payload) {
198
- if (payload === null || typeof payload !== "object") {
199
- throw new Error("Passkey confirmation did not return a signature.");
659
+ function receiptFromCeremonyPayload(payload) {
660
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
661
+ throw new Error("Passkey confirmation did not return a receipt.");
200
662
  }
201
663
  const o = payload;
202
- const nested = o.sign_proof;
203
- if (nested !== null && typeof nested === "object") return nested;
204
- if (o.v === 1 && o.intent_type === "generic_sign" && typeof o.intent_id === "string" && o.intent_id.length > 0) {
205
- return o;
664
+ if (o.type !== "receipt@1" || o.statement === null || typeof o.statement !== "object") {
665
+ throw new Error("Passkey confirmation did not return a receipt.");
206
666
  }
207
- throw new Error("Passkey confirmation did not return a signature.");
667
+ return o;
208
668
  }
209
669
  async function startCeremony(args) {
210
670
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
211
671
  method: "POST",
672
+ redirect: "error",
212
673
  headers: {
213
674
  Accept: "application/json",
214
675
  "Content-Type": "application/json",
215
676
  Authorization: `Bearer ${args.bearer}`
216
677
  },
217
- body: JSON.stringify({
218
- return_to: args.returnTo,
219
- purpose: args.purpose,
220
- ...args.messageDigest ? { message_digest: args.messageDigest } : {},
221
- ...args.displayHint ? { display_hint: args.displayHint } : {},
222
- ...args.label ? { label: args.label } : {}
223
- })
678
+ body: JSON.stringify({ return_to: args.returnTo, statement: args.statement })
224
679
  });
225
680
  const body = await res.json().catch(() => null);
226
681
  if (!res.ok || typeof body?.payload?.ticket !== "string") {
@@ -236,6 +691,7 @@ async function pollCeremonyResult(args) {
236
691
  while (Date.now() < deadline) {
237
692
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
238
693
  method: "POST",
694
+ redirect: "error",
239
695
  headers: {
240
696
  Accept: "application/json",
241
697
  "Content-Type": "application/json",
@@ -245,7 +701,7 @@ async function pollCeremonyResult(args) {
245
701
  });
246
702
  const body = await res.json().catch(() => null);
247
703
  if (res.ok && body?.payload !== void 0) {
248
- return body.payload.payload;
704
+ return body.payload.receipt;
249
705
  }
250
706
  if (res.status === 404) {
251
707
  lastError = body?.message ?? "waiting for Passkey";
@@ -257,7 +713,7 @@ async function pollCeremonyResult(args) {
257
713
  throw new Error(lastError);
258
714
  }
259
715
  function sleep(ms) {
260
- return new Promise((resolve) => setTimeout(resolve, ms));
716
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
261
717
  }
262
718
  function ceremonyPageUrl(idOrigin, ticket) {
263
719
  const u = new URL("/auth/ceremony", idOrigin.replace(/\/+$/, ""));
@@ -271,182 +727,62 @@ var init_ceremony = __esm({
271
727
  "src/ceremony.ts"() {
272
728
  }
273
729
  });
274
-
275
- // src/org-api.ts
276
- async function apiJson(apiOrigin, path, opts) {
277
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}${path}`, {
278
- method: opts.method ?? "GET",
279
- headers: {
280
- Accept: "application/json",
281
- Authorization: `Bearer ${opts.bearer}`,
282
- ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
283
- },
284
- body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
285
- });
286
- const body = await res.json().catch(() => null);
287
- if (!res.ok) {
288
- const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
289
- const message = typeof body?.message === "string" ? body.message : code;
290
- throw new SetupApiError(res.status, code, message);
730
+ async function refuseSymlink(path2) {
731
+ try {
732
+ const st = await lstat(path2);
733
+ if (st.isSymbolicLink()) throw new Error(`refusing to write through a symlink: ${path2}`);
734
+ } catch (e) {
735
+ if (e.code === "ENOENT") return;
736
+ throw e;
291
737
  }
292
- return body ?? {};
293
- }
294
- async function listOrgs(apiOrigin, bearer) {
295
- const r = await apiJson(apiOrigin, "/orgs", { bearer });
296
- return r.orgs ?? [];
297
- }
298
- async function getOrg(apiOrigin, bearer, orgId) {
299
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}`, { bearer });
300
738
  }
301
- async function postDnsChallenge(apiOrigin, bearer, domain, kind = "anchor") {
302
- return apiJson(apiOrigin, "/orgs/dns/challenge", {
303
- method: "POST",
304
- bearer,
305
- body: { domain: domain.trim(), kind }
306
- });
307
- }
308
- async function postVerifyAnchor(apiOrigin, bearer, args) {
309
- return apiJson(apiOrigin, "/orgs/dns/verify-anchor", {
310
- method: "POST",
311
- bearer,
312
- body: {
313
- domain: args.domain.trim(),
314
- nonce: args.nonce,
315
- ...args.name ? { name: args.name.trim() } : {}
316
- }
317
- });
318
- }
319
- async function postPolicyBootstrap(apiOrigin, bearer, orgId, signProof) {
320
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/policy/bootstrap`, {
321
- method: "POST",
322
- bearer,
323
- body: signProof ? { sign_proof: signProof } : {}
324
- });
325
- }
326
- async function listApps(apiOrigin, bearer, orgId) {
327
- const r = await apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
328
- bearer
329
- });
330
- return r.apps ?? [];
331
- }
332
- async function getApp(apiOrigin, bearer, orgId, appId) {
333
- const r = await apiJson(
334
- apiOrigin,
335
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}`,
336
- { bearer }
337
- );
338
- return r.app;
339
- }
340
- async function postAppRegister(apiOrigin, bearer, orgId, payload) {
341
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps`, {
342
- method: "POST",
343
- bearer,
344
- body: payload
345
- });
346
- }
347
- async function getHostChallenge(apiOrigin, bearer, orgId, appId) {
348
- return apiJson(
349
- apiOrigin,
350
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/host-challenge`,
351
- { bearer }
352
- );
353
- }
354
- async function postVerifyHost(apiOrigin, bearer, orgId, appId, signProof) {
355
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/verify-host`, {
356
- method: "POST",
357
- bearer,
358
- body: { sign_proof: signProof }
359
- });
360
- }
361
- async function putDeclaration(apiOrigin, bearer, orgId, appId, args) {
362
- return apiJson(
363
- apiOrigin,
364
- `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/declaration`,
365
- {
366
- method: "PUT",
367
- bearer,
368
- body: {
369
- endUsers: args.endUsers,
370
- uses: args.uses,
371
- sign_proof: args.signProof
372
- }
373
- }
374
- );
375
- }
376
- async function getCard(apiOrigin, bearer, orgId) {
377
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card`, { bearer });
378
- }
379
- async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signature") {
380
- return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/card/checkout`, {
381
- method: "POST",
382
- bearer,
383
- body: { capability }
384
- });
385
- }
386
- async function fetchJwksDocument(apiOrigin) {
387
- const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
388
- headers: { Accept: "application/json" }
389
- });
390
- if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
391
- return res.json();
392
- }
393
- function masterJwkJsonFromDocument(jwks) {
394
- const master = jwks.master ?? jwks.keys?.find((k) => k.kid === "master" || k.use === "master" || k.alg === "EdDSA");
395
- if (!master) throw new SetupApiError(404, "MASTER_JWK_MISSING", "master JWK not found in JWKS");
396
- return JSON.stringify(master);
397
- }
398
- async function getMasterJwkJson(apiOrigin, masterPinJson) {
399
- const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
400
- const doc = await fetchJwksDocument(apiOrigin);
401
- await verifySignedJwksDocument(doc, masterPinJson);
402
- return masterJwkJsonFromDocument(doc);
739
+ async function writeMode600(path2, contents) {
740
+ const dir = dirname(path2);
741
+ await mkdir(dir, { recursive: true, mode: 448 });
742
+ await refuseSymlink(dir);
743
+ await refuseSymlink(path2);
744
+ await writeFile(path2, contents, { encoding: "utf8", mode: 384 });
745
+ try {
746
+ await chmod(path2, 384);
747
+ } catch (e) {
748
+ await unlink(path2).catch(() => void 0);
749
+ const message = e instanceof Error ? e.message : String(e);
750
+ throw new Error(`could not set mode 0600 on ${path2}: ${message}`);
751
+ }
403
752
  }
404
- var SetupApiError;
405
- var init_org_api = __esm({
406
- "src/org-api.ts"() {
407
- SetupApiError = class extends Error {
408
- status;
409
- code;
410
- constructor(status, code, message) {
411
- super(message);
412
- this.name = "SetupApiError";
413
- this.status = status;
414
- this.code = code;
415
- }
416
- };
753
+ var init_private_file = __esm({
754
+ "src/private-file.ts"() {
417
755
  }
418
756
  });
757
+ function assertOperateAppId(appId) {
758
+ const app = appId.trim().toLowerCase();
759
+ if (!APP_ID_RE.test(app)) throw new Error("invalid_app_id");
760
+ return app;
761
+ }
762
+ function keysBase() {
763
+ const override = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim();
764
+ return resolve(override || join(homedir(), ".config", "clavis", "apps"));
765
+ }
766
+ function pathInsideKeys(appId, file) {
767
+ const app = assertOperateAppId(appId);
768
+ const base = keysBase();
769
+ const path2 = resolve(base, app, file);
770
+ const rel = relative(base, path2);
771
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("invalid_app_id");
772
+ return path2;
773
+ }
419
774
  function operatePrivateJwkPath(appId) {
420
- const app = appId.trim();
421
- if (!app) throw new Error("appId required");
422
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
423
- return join(base, app, "operate-private.jwk.json");
775
+ return pathInsideKeys(appId, "operate-private.jwk.json");
424
776
  }
425
777
  function appEnvFilePath(appId) {
426
- const app = appId.trim();
427
- if (!app) throw new Error("appId required");
428
- const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
429
- return join(base, app, "app.env");
430
- }
431
- async function restrictFileMode(path) {
432
- try {
433
- await chmod(path, 384);
434
- } catch (e) {
435
- console.warn(
436
- `clavis: could not set mode 0600 on ${path}: ${e instanceof Error ? e.message : e}`
437
- );
438
- }
778
+ return pathInsideKeys(appId, "app.env");
439
779
  }
440
780
  async function saveOperatePrivateJwk(appId, jwkJson) {
441
- const path = operatePrivateJwkPath(appId);
442
- await mkdir(dirname(path), { recursive: true });
443
- await writeFile(path, jwkJson.trim(), "utf8");
444
- await restrictFileMode(path);
445
- try {
446
- await chmod(dirname(path), 448);
447
- } catch {
448
- }
449
- return path;
781
+ const path2 = operatePrivateJwkPath(appId);
782
+ await writeMode600(path2, `${jwkJson.trim()}
783
+ `);
784
+ await chmod(dirname(path2), 448).catch(() => void 0);
785
+ return path2;
450
786
  }
451
787
  async function readOperatePrivateJwk(appId) {
452
788
  try {
@@ -457,15 +793,16 @@ async function readOperatePrivateJwk(appId) {
457
793
  }
458
794
  }
459
795
  async function writeAppEnvFile(appId, contents) {
460
- const path = appEnvFilePath(appId);
461
- await mkdir(dirname(path), { recursive: true });
462
- await writeFile(path, contents.endsWith("\n") ? contents : `${contents}
463
- `, "utf8");
464
- await restrictFileMode(path);
465
- return path;
796
+ const path2 = appEnvFilePath(appId);
797
+ await writeMode600(path2, contents.endsWith("\n") ? contents : `${contents}
798
+ `);
799
+ return path2;
466
800
  }
801
+ var APP_ID_RE;
467
802
  var init_operate_key_store = __esm({
468
803
  "src/operate-key-store.ts"() {
804
+ init_private_file();
805
+ APP_ID_RE = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[a-z0-9][a-z0-9._-]{0,126})$/;
469
806
  }
470
807
  });
471
808
 
@@ -530,24 +867,25 @@ var init_keys = __esm({
530
867
  }
531
868
  });
532
869
  async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
533
- const base = apiOrigin.replace(/\/+$/, "");
534
- const jwks = createRemoteJWKSet(new URL(`${base}/.well-known/jwks.json`));
535
- await jwtVerify(accessToken, jwks, { algorithms: ["ES256"] });
536
- }
870
+ const origin = new URL(apiOrigin).origin;
871
+ const jwks = createRemoteJWKSet(new URL(`${origin}/.well-known/jwks.json`));
872
+ const { payload, protectedHeader } = await jwtVerify(accessToken, jwks, {
873
+ algorithms: ["ES256"],
874
+ issuer: origin,
875
+ audience: origin,
876
+ requiredClaims: ["exp", "iss", "aud", "sub"]
877
+ });
878
+ const kid = typeof protectedHeader.kid === "string" ? protectedHeader.kid : "";
879
+ if (!SESSION_SLOT_RE.test(kid)) throw new Error("invalid_access_token_kid");
880
+ if (payload.tk !== "access") throw new Error("invalid_access_token_kind");
881
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) throw new Error("invalid_access_token_sub");
882
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) throw new Error("invalid_access_token_exp");
883
+ return { sub: payload.sub, expiresAt: payload.exp };
884
+ }
885
+ var SESSION_SLOT_RE;
537
886
  var init_access_token_verify = __esm({
538
887
  "src/access-token-verify.ts"() {
539
- }
540
- });
541
-
542
- // src/types.ts
543
- var DEFAULT_ORIGINS;
544
- var init_types = __esm({
545
- "src/types.ts"() {
546
- DEFAULT_ORIGINS = {
547
- apiOrigin: "https://api.clavis.nexus",
548
- idOrigin: "https://id.clavis.nexus",
549
- developersOrigin: "https://developers.clavis.nexus"
550
- };
888
+ SESSION_SLOT_RE = /^[a-z][a-z0-9]{1,31}-wauthn-auth-jwt(?:-\d{6})?$/;
551
889
  }
552
890
  });
553
891
  function defaultSessionPath() {
@@ -555,16 +893,42 @@ function defaultSessionPath() {
555
893
  if (override) return override;
556
894
  return join(homedir(), ".config", "clavis", "session.json");
557
895
  }
896
+ function isLoopbackHost3(hostname) {
897
+ const host = hostname.toLowerCase();
898
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
899
+ }
900
+ function assertSetupOrigin(raw, name) {
901
+ let url;
902
+ try {
903
+ url = new URL(raw.trim());
904
+ } catch {
905
+ throw new Error(`${name} must be an absolute URL`);
906
+ }
907
+ if (url.username || url.password) throw new Error(`${name} must not contain credentials`);
908
+ const loopbackHttp = url.protocol === "http:" && isLoopbackHost3(url.hostname);
909
+ if (url.protocol !== "https:" && !loopbackHttp) throw new Error(`${name} must be https`);
910
+ if (url.pathname !== "/" || url.search || url.hash) throw new Error(`${name} must be an origin`);
911
+ return url.origin;
912
+ }
558
913
  function originsFromEnv(overrides) {
559
914
  return {
560
- apiOrigin: overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
561
- idOrigin: overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
562
- developersOrigin: overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin
915
+ apiOrigin: assertSetupOrigin(
916
+ overrides?.apiOrigin ?? process.env.CLAVIS_API_ORIGIN?.trim() ?? DEFAULT_ORIGINS.apiOrigin,
917
+ "apiOrigin"
918
+ ),
919
+ idOrigin: assertSetupOrigin(
920
+ overrides?.idOrigin ?? process.env.CLAVIS_ID_ORIGIN?.trim() ?? DEFAULT_ORIGINS.idOrigin,
921
+ "idOrigin"
922
+ ),
923
+ developersOrigin: assertSetupOrigin(
924
+ overrides?.developersOrigin ?? process.env.CLAVIS_DEVELOPERS_ORIGIN?.trim() ?? DEFAULT_ORIGINS.developersOrigin,
925
+ "developersOrigin"
926
+ )
563
927
  };
564
928
  }
565
- async function loadSession(path = defaultSessionPath()) {
929
+ async function loadSession(path2 = defaultSessionPath()) {
566
930
  try {
567
- const raw = await readFile(path, "utf8");
931
+ const raw = await readFile(path2, "utf8");
568
932
  const parsed = JSON.parse(raw);
569
933
  if (parsed?.v !== 1 || typeof parsed.session?.accessToken !== "string") return null;
570
934
  if (parsed.session.expiresAt && parsed.session.expiresAt * 1e3 < Date.now()) return null;
@@ -573,164 +937,206 @@ async function loadSession(path = defaultSessionPath()) {
573
937
  return null;
574
938
  }
575
939
  }
576
- async function saveSession(session, origins, path = defaultSessionPath()) {
577
- await mkdir(dirname(path), { recursive: true });
940
+ async function saveSession(session, origins, path2 = defaultSessionPath()) {
578
941
  const body = { v: 1, origins, session, savedAt: Date.now() };
579
- await writeFile(path, JSON.stringify(body, null, 2), "utf8");
580
- try {
581
- await chmod(path, 384);
582
- } catch (e) {
583
- console.warn(
584
- `clavis: could not set session file mode 0600 (${path}): ${e instanceof Error ? e.message : e}`
585
- );
586
- }
942
+ await writeMode600(path2, JSON.stringify(body, null, 2));
587
943
  }
588
- async function clearSession(path = defaultSessionPath()) {
944
+ async function clearSession(path2 = defaultSessionPath()) {
589
945
  try {
590
- await unlink(path);
946
+ await unlink(path2);
591
947
  } catch {
592
948
  }
593
949
  }
594
950
  var init_session_store = __esm({
595
951
  "src/session-store.ts"() {
952
+ init_private_file();
596
953
  init_types();
597
954
  }
598
955
  });
599
- function readBody(req) {
600
- return new Promise((resolve, reject) => {
601
- const chunks = [];
602
- let total = 0;
603
- req.on("data", (c) => {
604
- const buf = Buffer.isBuffer(c) ? c : Buffer.from(c);
605
- total += buf.length;
606
- if (total > MAX_CALLBACK_BODY_BYTES) {
607
- reject(new Error("callback body too large"));
608
- req.destroy();
609
- return;
610
- }
611
- chunks.push(buf);
612
- });
613
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
614
- req.on("error", reject);
615
- });
956
+ function pendingLoginPath(sessionPath) {
957
+ const base = sessionPath ? path.dirname(sessionPath) : path.dirname(defaultSessionPath());
958
+ return path.join(base, "login-pending.json");
959
+ }
960
+ function loginBridgeUrl(developersOrigin, state) {
961
+ const bridge = new URL("/developers/setup/login", developersOrigin);
962
+ bridge.searchParams.set("state", state);
963
+ return bridge.toString();
616
964
  }
617
- function cors(res, developersOrigin) {
618
- res.setHeader("Access-Control-Allow-Origin", developersOrigin);
619
- res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
620
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
621
- res.setHeader("Vary", "Origin");
965
+ async function writePending(pendingPath, pending) {
966
+ await mkdir(path.dirname(pendingPath), { recursive: true, mode: 448 });
967
+ await writeFile(pendingPath, `${JSON.stringify(pending, null, 2)}
968
+ `, { mode: 384 });
969
+ }
970
+ async function readPending(pendingPath) {
971
+ try {
972
+ const raw = await readFile(pendingPath, "utf8");
973
+ const parsed = JSON.parse(raw);
974
+ if (parsed?.v !== 1 || typeof parsed.state !== "string" || !parsed.state) return null;
975
+ return parsed;
976
+ } catch {
977
+ return null;
978
+ }
622
979
  }
623
- function subFromJwt(accessToken) {
980
+ async function clearPending(pendingPath) {
624
981
  try {
625
- const part = accessToken.split(".")[1];
626
- if (!part) return void 0;
627
- const json = Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
628
- const payload = JSON.parse(json);
629
- return typeof payload.sub === "string" ? payload.sub : void 0;
982
+ await unlink(pendingPath);
630
983
  } catch {
631
- return void 0;
984
+ }
985
+ }
986
+ function parseBridgePayload(raw) {
987
+ const trimmed = raw.trim();
988
+ if (!trimmed) throw new Error("empty_bridge_json");
989
+ if (trimmed.length > MAX_BRIDGE_JSON_CHARS) throw new Error("bridge_json_too_large");
990
+ const body = JSON.parse(trimmed);
991
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
992
+ throw new Error("bridge_json_not_object");
993
+ }
994
+ return body;
995
+ }
996
+ async function sessionFromBridge(args) {
997
+ const body = parseBridgePayload(args.raw);
998
+ if (body.state !== args.expectedState || typeof body.accessToken !== "string" || !body.accessToken) {
999
+ throw new Error("invalid_bridge_json");
1000
+ }
1001
+ const verified = await verifyDevelopersAccessToken(body.accessToken, args.apiOrigin);
1002
+ return {
1003
+ accessToken: body.accessToken,
1004
+ sub: verified.sub,
1005
+ expiresAt: verified.expiresAt
1006
+ };
1007
+ }
1008
+ async function readBridgeJsonFromStdin() {
1009
+ if (!stdin.isTTY) {
1010
+ const chunks = [];
1011
+ for await (const chunk of stdin) {
1012
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1013
+ }
1014
+ return Buffer.concat(chunks).toString("utf8");
1015
+ }
1016
+ const rl = createInterface({ input: stdin, output: stdout });
1017
+ try {
1018
+ stdout.write(
1019
+ "Paste the JSON shown on developers /setup/login, then press Enter.\n(End with a blank line if the paste spans multiple lines.)\n"
1020
+ );
1021
+ const lines = [];
1022
+ for (; ; ) {
1023
+ const line = await rl.question("");
1024
+ if (line.trim() === "" && lines.length > 0) break;
1025
+ lines.push(line);
1026
+ const joined = lines.join("\n").trim();
1027
+ if (joined.startsWith("{") && joined.endsWith("}")) break;
1028
+ }
1029
+ return lines.join("\n");
1030
+ } finally {
1031
+ rl.close();
632
1032
  }
633
1033
  }
634
1034
  async function loginWithBrowser(args) {
635
- const state = randomBytes(16).toString("hex");
636
- const timeoutMs = args.timeoutMs ?? 5 * 6e4;
637
- const session = await new Promise((resolve, reject) => {
638
- const server = createServer(async (req, res) => {
639
- cors(res, args.origins.developersOrigin);
640
- if (req.method === "OPTIONS") {
641
- res.writeHead(204);
642
- res.end();
643
- return;
644
- }
645
- if (req.method !== "POST" || req.url?.split("?")[0] !== "/callback") {
646
- res.writeHead(404);
647
- res.end("not found");
648
- return;
649
- }
650
- try {
651
- const raw = await readBody(req);
652
- const body = JSON.parse(raw);
653
- if (body.state !== state || typeof body.accessToken !== "string" || !body.accessToken) {
654
- res.writeHead(400, { "Content-Type": "application/json" });
655
- res.end(JSON.stringify({ ok: false, error: "invalid_callback" }));
656
- return;
657
- }
658
- try {
659
- await verifyDevelopersAccessToken(body.accessToken, args.origins.apiOrigin);
660
- } catch {
661
- res.writeHead(400, { "Content-Type": "application/json" });
662
- res.end(JSON.stringify({ ok: false, error: "invalid_token" }));
663
- return;
664
- }
665
- const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
666
- const next = {
667
- accessToken: body.accessToken,
668
- ...sub ? { sub } : {},
669
- ...typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}
670
- };
671
- res.writeHead(200, { "Content-Type": "application/json" });
672
- res.end(JSON.stringify({ ok: true }));
673
- server.close();
674
- resolve(next);
675
- } catch (e) {
676
- res.writeHead(500, { "Content-Type": "application/json" });
677
- res.end(JSON.stringify({ ok: false }));
678
- server.close();
679
- reject(e);
680
- }
1035
+ const pendingPath = pendingLoginPath(args.sessionPath);
1036
+ const openFlag = args.open !== false;
1037
+ if (args.bridgeJson?.trim()) {
1038
+ const pending = await readPending(pendingPath);
1039
+ if (!pending) {
1040
+ throw new Error("no_pending_login \u2014 run login again to open the browser first");
1041
+ }
1042
+ if (pending.apiOrigin !== args.origins.apiOrigin || pending.developersOrigin !== args.origins.developersOrigin) {
1043
+ await clearPending(pendingPath);
1044
+ throw new Error("pending_login_origin_mismatch \u2014 run login again");
1045
+ }
1046
+ if (!Number.isFinite(pending.createdAt) || Date.now() - pending.createdAt > PENDING_LOGIN_TTL_MS) {
1047
+ await clearPending(pendingPath);
1048
+ throw new Error("pending_login_expired \u2014 run login again");
1049
+ }
1050
+ const openUrl2 = assertOriginBrowserUrl(
1051
+ loginBridgeUrl(args.origins.developersOrigin, pending.state),
1052
+ args.origins.developersOrigin
1053
+ );
1054
+ const session2 = await sessionFromBridge({
1055
+ raw: args.bridgeJson,
1056
+ expectedState: pending.state,
1057
+ apiOrigin: args.origins.apiOrigin
681
1058
  });
682
- server.listen(0, "127.0.0.1", () => {
683
- const addr = server.address();
684
- if (!addr || typeof addr === "string") {
685
- reject(new Error("failed to bind localhost"));
686
- return;
1059
+ await saveSession(session2, args.origins, args.sessionPath);
1060
+ await clearPending(pendingPath);
1061
+ return {
1062
+ session: session2,
1063
+ human: {
1064
+ needs_human: "login",
1065
+ message: "Session stored.",
1066
+ open_url: openUrl2
687
1067
  }
688
- const bridge = new URL("/developers/setup/login", args.origins.developersOrigin);
689
- bridge.searchParams.set("callback_port", String(addr.port));
690
- bridge.searchParams.set("state", state);
691
- void (async () => {
692
- if (args.open !== false) {
693
- try {
694
- await openBrowser(assertOriginBrowserUrl(bridge.toString(), args.origins.developersOrigin));
695
- } catch {
696
- }
697
- }
698
- })();
699
- });
700
- const timer = setTimeout(() => {
701
- server.close();
702
- reject(new Error("login timeout \u2014 complete Passkey in the browser"));
703
- }, timeoutMs);
704
- server.on("close", () => clearTimeout(timer));
1068
+ };
1069
+ }
1070
+ const state = randomBytes(16).toString("hex");
1071
+ const openUrl = assertOriginBrowserUrl(
1072
+ loginBridgeUrl(args.origins.developersOrigin, state),
1073
+ args.origins.developersOrigin
1074
+ );
1075
+ await writePending(pendingPath, {
1076
+ v: 1,
1077
+ state,
1078
+ createdAt: Date.now(),
1079
+ developersOrigin: args.origins.developersOrigin,
1080
+ apiOrigin: args.origins.apiOrigin
1081
+ });
1082
+ if (openFlag) {
1083
+ try {
1084
+ await openBrowser(openUrl);
1085
+ } catch {
1086
+ }
1087
+ }
1088
+ if (args.deferPaste) {
1089
+ return {
1090
+ pending: true,
1091
+ human: {
1092
+ needs_human: "login",
1093
+ message: "Complete Passkey in the browser, copy the JSON on the page, then call login again with bridge_json.",
1094
+ open_url: openUrl
1095
+ }
1096
+ };
1097
+ }
1098
+ const raw = await readBridgeJsonFromStdin();
1099
+ const session = await sessionFromBridge({
1100
+ raw,
1101
+ expectedState: state,
1102
+ apiOrigin: args.origins.apiOrigin
705
1103
  });
706
- await saveSession(session, args.origins);
1104
+ await saveSession(session, args.origins, args.sessionPath);
1105
+ await clearPending(pendingPath);
707
1106
  return {
708
1107
  session,
709
1108
  human: {
710
1109
  needs_human: "login",
711
- message: "Complete Passkey login in the browser if the window is still open.",
712
- open_url: `${args.origins.developersOrigin}/developers/setup/login`
1110
+ message: "Session stored. You can close the browser tab.",
1111
+ open_url: openUrl
713
1112
  }
714
1113
  };
715
1114
  }
716
- var MAX_CALLBACK_BODY_BYTES;
1115
+ var MAX_BRIDGE_JSON_CHARS, PENDING_LOGIN_TTL_MS;
717
1116
  var init_login = __esm({
718
1117
  "src/login.ts"() {
719
1118
  init_browser();
720
1119
  init_safe_browser_url();
721
1120
  init_access_token_verify();
722
1121
  init_session_store();
723
- MAX_CALLBACK_BODY_BYTES = 8192;
1122
+ MAX_BRIDGE_JSON_CHARS = 16384;
1123
+ PENDING_LOGIN_TTL_MS = 15 * 60 * 1e3;
724
1124
  }
725
1125
  });
726
1126
 
727
1127
  // src/status.ts
728
- function cardActive(card) {
729
- if (!card) return "unknown";
1128
+ function signatureCard(card) {
730
1129
  const sig = card.capabilities?.signature;
731
- if (!sig) return "inactive";
732
- if (sig.subscribed === true || sig.active === true) return "active";
733
- return "inactive";
1130
+ if (!sig) return { signature_card: "inactive" };
1131
+ if (sig.open === true) return { signature_card: "active" };
1132
+ return {
1133
+ signature_card: "inactive",
1134
+ ...Array.isArray(sig.blockers) && sig.blockers.length > 0 ? { signature_card_blockers: sig.blockers } : {}
1135
+ };
1136
+ }
1137
+ function incorporationOf(card) {
1138
+ const inc = card.incorporation;
1139
+ return inc ? { code: inc.code, terms_current: inc.terms_current === true } : null;
734
1140
  }
735
1141
  async function buildSetupStatus(args) {
736
1142
  if (!args.session) {
@@ -740,7 +1146,9 @@ async function buildSetupStatus(args) {
740
1146
  const detailed = [];
741
1147
  for (const org of orgs) {
742
1148
  let setup_complete = false;
743
- let signature_card = "unknown";
1149
+ let card = {
1150
+ signature_card: "unknown"
1151
+ };
744
1152
  let apps = [];
745
1153
  try {
746
1154
  const detail = await getOrg(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -748,10 +1156,10 @@ async function buildSetupStatus(args) {
748
1156
  } catch {
749
1157
  }
750
1158
  try {
751
- const card = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
752
- signature_card = cardActive(card);
1159
+ const view = await getCard(args.origins.apiOrigin, args.session.accessToken, org.org_id);
1160
+ card = { ...signatureCard(view), incorporation: incorporationOf(view) };
753
1161
  } catch {
754
- signature_card = "unknown";
1162
+ card = { signature_card: "unknown" };
755
1163
  }
756
1164
  try {
757
1165
  const list = await listApps(args.origins.apiOrigin, args.session.accessToken, org.org_id);
@@ -759,6 +1167,7 @@ async function buildSetupStatus(args) {
759
1167
  app_id: a.app_id,
760
1168
  host: a.host,
761
1169
  status: a.status,
1170
+ ...a.accepted_regions ? { accepted_regions: a.accepted_regions } : {},
762
1171
  declaration_ok: Boolean(
763
1172
  a.declaration && typeof a.declaration.endUsers === "string" && a.declaration.endUsers.trim() && Array.isArray(a.declaration.uses) && a.declaration.uses.some((u) => u.capability === "signature")
764
1173
  )
@@ -788,7 +1197,7 @@ async function buildSetupStatus(args) {
788
1197
  primary_domain: org.primary_domain,
789
1198
  org_status: org.org_status,
790
1199
  setup_complete,
791
- signature_card,
1200
+ ...card,
792
1201
  apps
793
1202
  });
794
1203
  }
@@ -825,21 +1234,18 @@ async function runPasskeyCeremony(args) {
825
1234
  apiOrigin: args.origins.apiOrigin,
826
1235
  bearer: args.bearer,
827
1236
  returnTo,
828
- purpose: args.purpose,
829
- messageDigest: args.messageDigest,
830
- displayHint: args.displayHint,
831
- label: args.displayHint
1237
+ statement: args.statement
832
1238
  });
833
- const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
1239
+ const ceremony_url = assertOriginBrowserUrl(ceremonyPageUrl(args.origins.idOrigin, ticket), args.origins.idOrigin);
834
1240
  if (args.openBrowserFlag) {
835
1241
  try {
836
- await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
1242
+ await openBrowser(ceremony_url);
837
1243
  } catch {
838
1244
  }
839
1245
  }
840
1246
  const human = {
841
1247
  needs_human: "passkey",
842
- message: "Confirm with Passkey in the browser, then return to the terminal/agent.",
1248
+ message: `${args.displayHint ? `${args.displayHint}: c` : "C"}onfirm with Passkey in the browser (${args.statement.type}), then return to the terminal/agent.`,
843
1249
  open_url: ceremony_url
844
1250
  };
845
1251
  return {
@@ -852,7 +1258,7 @@ async function runPasskeyCeremony(args) {
852
1258
  bearer: args.bearer,
853
1259
  ticket
854
1260
  });
855
- return signProofFromCeremonyPayload(payload);
1261
+ return receiptFromCeremonyPayload(payload);
856
1262
  }
857
1263
  };
858
1264
  }
@@ -866,9 +1272,24 @@ function createSetupClient(options = {}) {
866
1272
  const s = await loadSession(sessionPath);
867
1273
  return s?.session ?? null;
868
1274
  },
869
- async login() {
870
- const { session } = await loginWithBrowser({ origins, open: openBrowserFlag });
871
- return { ok: true, data: { sub: session.sub } };
1275
+ async login(opts) {
1276
+ const bridgeJson = opts?.bridgeJson?.trim();
1277
+ const deferPaste = !bridgeJson && !process.stdin.isTTY;
1278
+ const out = await loginWithBrowser({
1279
+ origins,
1280
+ open: openBrowserFlag,
1281
+ ...bridgeJson ? { bridgeJson } : {},
1282
+ ...deferPaste ? { deferPaste: true } : {},
1283
+ sessionPath
1284
+ });
1285
+ if (out.pending || !out.session) {
1286
+ return {
1287
+ ok: false,
1288
+ error: "login_pending_paste",
1289
+ human: out.human
1290
+ };
1291
+ }
1292
+ return { ok: true, data: { sub: out.session.sub } };
872
1293
  },
873
1294
  async logout() {
874
1295
  await clearSession(sessionPath);
@@ -879,18 +1300,43 @@ function createSetupClient(options = {}) {
879
1300
  const report = await buildSetupStatus({ origins, session });
880
1301
  return { ok: true, data: report };
881
1302
  },
882
- async orgAnchorPlan(domain, name) {
1303
+ async orgAnchorPlan(domain, name, terms = {}) {
1304
+ const checked = checkOrgCreationTerms(terms);
1305
+ if (!checked.ok) return checked;
1306
+ const { incorporation } = checked;
883
1307
  const auth = await requireSession({ origins, sessionPath });
884
1308
  if (!auth.ok) return auth;
885
- const challenge = await postDnsChallenge(auth.data.origins.apiOrigin, auth.data.session.accessToken, domain);
886
- if (!challenge.digest) {
887
- return { ok: false, error: "challenge_missing_digest" };
1309
+ const apiOrigin = auth.data.origins.apiOrigin;
1310
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1311
+ if (closed.includes(incorporation)) return regionClosedRefusal(incorporation);
1312
+ let challenge;
1313
+ try {
1314
+ challenge = await postDnsChallenge(apiOrigin, auth.data.session.accessToken, { domain, incorporation });
1315
+ } catch (e) {
1316
+ const refusal = orgCreationRefusal(e, incorporation);
1317
+ if (refusal) return refusal;
1318
+ throw e;
1319
+ }
1320
+ const domainNorm = domain.trim().toLowerCase();
1321
+ if (!challenge.statement || typeof challenge.domain !== "string" || challenge.domain.trim().toLowerCase() !== domainNorm || typeof challenge.nonce !== "string" || challenge.nonce.length === 0 || typeof challenge.exp !== "number" || !Number.isFinite(challenge.exp)) {
1322
+ return { ok: false, error: "challenge_missing_statement" };
1323
+ }
1324
+ const anchorStatement = orgAnchorPublishStatement({ domain: domainNorm, nonce: challenge.nonce, exp: challenge.exp });
1325
+ if (!sameStatement(anchorStatement, challenge.statement)) return { ok: false, error: "challenge_statement_mismatch" };
1326
+ let wellKnown;
1327
+ try {
1328
+ wellKnown = new URL(challenge.well_known_url);
1329
+ } catch {
1330
+ return { ok: false, error: "challenge_url_rejected" };
1331
+ }
1332
+ const txtHost = typeof challenge.txt_host === "string" ? challenge.txt_host.trim().toLowerCase().replace(/\.$/, "") : "";
1333
+ if (wellKnown.protocol !== "https:" || wellKnown.username || wellKnown.password || wellKnown.hostname.toLowerCase() !== domainNorm || txtHost !== domainNorm && !txtHost.endsWith(`.${domainNorm}`)) {
1334
+ return { ok: false, error: "challenge_url_rejected" };
888
1335
  }
889
1336
  const cer = await runPasskeyCeremony({
890
1337
  origins: auth.data.origins,
891
1338
  bearer: auth.data.session.accessToken,
892
- purpose: "org.anchor.publish",
893
- messageDigest: challenge.digest,
1339
+ statement: anchorStatement,
894
1340
  displayHint: `Publish DNS anchor for ${domain}`,
895
1341
  openBrowserFlag
896
1342
  });
@@ -899,9 +1345,10 @@ function createSetupClient(options = {}) {
899
1345
  data: {
900
1346
  domain: challenge.domain,
901
1347
  ...name ? { name } : {},
1348
+ incorporation,
902
1349
  nonce: challenge.nonce,
903
1350
  exp: challenge.exp,
904
- digest: challenge.digest,
1351
+ statement: anchorStatement,
905
1352
  well_known_url: challenge.well_known_url,
906
1353
  txt_host: challenge.txt_host,
907
1354
  ceremony_url: cer.ceremony_url,
@@ -918,12 +1365,12 @@ function createSetupClient(options = {}) {
918
1365
  bearer: auth.data.session.accessToken,
919
1366
  ticket: args.ticket
920
1367
  });
921
- const signProof = signProofFromCeremonyPayload(payload);
1368
+ const receipt = receiptFromCeremonyPayload(payload);
922
1369
  const body = {
923
1370
  v: 1,
924
1371
  kind: "anchor",
925
1372
  domain: args.domain.trim().toLowerCase(),
926
- sign_proof: signProof,
1373
+ receipt,
927
1374
  nonce: args.nonce,
928
1375
  exp: args.exp,
929
1376
  iat: Math.floor(Date.now() / 1e3)
@@ -940,18 +1387,29 @@ function createSetupClient(options = {}) {
940
1387
  txt_value,
941
1388
  human: {
942
1389
  needs_human: "dns",
943
- message: "Publish the well-known JSON and TXT, then call org_verify_anchor."
1390
+ message: "Publish the well-known JSON and TXT, then call org_verify_anchor with the same incorporation and the customer's agreement to the Customer Terms."
944
1391
  }
945
1392
  }
946
1393
  };
947
1394
  },
948
1395
  async orgVerifyAnchor(args) {
1396
+ const checked = checkOrgCreationTerms(args);
1397
+ if (!checked.ok) return checked;
1398
+ const { incorporation } = checked;
949
1399
  const auth = await requireSession({ origins, sessionPath });
950
1400
  if (!auth.ok) return auth;
951
1401
  try {
952
- const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, args);
1402
+ const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, {
1403
+ domain: args.domain,
1404
+ nonce: args.nonce,
1405
+ name: args.name,
1406
+ incorporation,
1407
+ acceptCustomerTerms: args.acceptCustomerTerms
1408
+ });
953
1409
  return { ok: true, data: { org_id: out.org_id, org_status: out.org_status } };
954
1410
  } catch (e) {
1411
+ const refusal = orgCreationRefusal(e, incorporation);
1412
+ if (refusal) return refusal;
955
1413
  return {
956
1414
  ok: false,
957
1415
  error: e instanceof Error ? e.message : String(e),
@@ -975,18 +1433,10 @@ function createSetupClient(options = {}) {
975
1433
  if (noop.already_active) return { ok: true, data: noop };
976
1434
  } catch {
977
1435
  }
978
- const sub = auth.data.session.sub;
979
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
980
- const digest = await computeOrgPolicyBootstrapDigest({
981
- org_id: orgId,
982
- primary_domain: detail.primary_domain,
983
- owner_sub: sub
984
- });
985
1436
  const cer = await runPasskeyCeremony({
986
1437
  origins: auth.data.origins,
987
1438
  bearer: auth.data.session.accessToken,
988
- purpose: "org.policy.bootstrap",
989
- messageDigest: digest,
1439
+ statement: orgPolicyBootstrapStatement({ org: orgId, domain: detail.primary_domain }),
990
1440
  displayHint: `Bootstrap policy for ${detail.primary_domain}`,
991
1441
  openBrowserFlag
992
1442
  });
@@ -999,24 +1449,126 @@ function createSetupClient(options = {}) {
999
1449
  );
1000
1450
  return { ok: true, data: out };
1001
1451
  },
1002
- async cardCheckout(orgId) {
1452
+ async incorporationSet(args) {
1453
+ const checked = checkOrgCreationTerms(args, INCORPORATION_TERMS_HUMAN);
1454
+ if (!checked.ok) return checked;
1455
+ const code = checked.incorporation;
1456
+ const auth = await requireSession({ origins, sessionPath });
1457
+ if (!auth.ok) return auth;
1458
+ const sub = auth.data.session.sub;
1459
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1460
+ const apiOrigin = auth.data.origins.apiOrigin;
1461
+ const bearer = auth.data.session.accessToken;
1462
+ const card = await getCard(apiOrigin, bearer, args.orgId);
1463
+ const current = card.incorporation;
1464
+ if (current?.code === code && current.terms_current) {
1465
+ return { ok: true, data: { incorporation: current, unchanged: true } };
1466
+ }
1467
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1468
+ if (closed.includes(code) && current?.code !== code) return declarationRegionClosedRefusal(code);
1469
+ const cer = await runPasskeyCeremony({
1470
+ origins: auth.data.origins,
1471
+ bearer,
1472
+ statement: orgCardIncorporationStatement({
1473
+ org: args.orgId,
1474
+ code,
1475
+ customerTerms: card.acceptance.customer_terms_version,
1476
+ dpa: card.acceptance.dpa_version
1477
+ }),
1478
+ displayHint: `Declare ${code} as the place of incorporation`,
1479
+ openBrowserFlag
1480
+ });
1481
+ const proof = await cer.wait();
1482
+ try {
1483
+ const out = await postCardIncorporation(apiOrigin, bearer, args.orgId, { code, receipt: proof });
1484
+ return { ok: true, data: { incorporation: out.incorporation } };
1485
+ } catch (e) {
1486
+ const refusal = incorporationSetRefusal(e, code);
1487
+ if (refusal) return refusal;
1488
+ throw e;
1489
+ }
1490
+ },
1491
+ async cardCheckout(orgId, opts = {}) {
1492
+ const offer = opts.offer === "bundle" ? "bundle" : "meter";
1493
+ const lang = checkoutLang(opts.lang);
1003
1494
  const auth = await requireSession({ origins, sessionPath });
1004
1495
  if (!auth.ok) return auth;
1005
- const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
1496
+ const sub = auth.data.session.sub;
1497
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1498
+ const apiOrigin = auth.data.origins.apiOrigin;
1499
+ const bearer = auth.data.session.accessToken;
1500
+ const card = await getCard(apiOrigin, bearer, orgId);
1501
+ if (card.suspended) return { ok: false, error: "org_suspended" };
1502
+ const signature = card.capabilities?.signature;
1503
+ const open = offer === "bundle" ? signature?.bundle_checkout_open : signature?.checkout_open;
1504
+ if (!signature || open !== true) {
1505
+ return { ok: false, error: "checkout_closed \u2014 the card checkout is not open right now." };
1506
+ }
1507
+ const blockers = signature.blockers ?? [];
1508
+ const subscribed = offer === "bundle" ? signature.tariff === "bundle" : !blockers.includes("subscription");
1509
+ if (subscribed) {
1510
+ const state = blockers.length > 0 ? ` (${blockers.join(", ")})` : "";
1511
+ return {
1512
+ ok: false,
1513
+ error: `already_subscribed \u2014 the signature card already has this subscription${state}. Manage it on developers.`
1514
+ };
1515
+ }
1516
+ const incorporation = card.incorporation;
1517
+ if (!incorporation) return incorporationNeededRefusal(orgId, false);
1518
+ if (!incorporation.terms_current) return incorporationNeededRefusal(orgId, true);
1519
+ const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
1520
+ if (closed.includes(incorporation.code)) return purchaseRegionClosedRefusal(incorporation.code);
1521
+ if (opts.consentBillingData !== true) {
1522
+ return { ok: false, error: "billing_data_consent_required", human: billingConsentHuman(card.acceptance, lang) };
1523
+ }
1524
+ const cer = await runPasskeyCeremony({
1525
+ origins: auth.data.origins,
1526
+ bearer,
1527
+ statement: orgCardCheckoutStatement({
1528
+ org: orgId,
1529
+ capability: "signature",
1530
+ offer,
1531
+ customerTerms: card.acceptance.customer_terms_version,
1532
+ dpa: card.acceptance.dpa_version
1533
+ }),
1534
+ displayHint: offer === "bundle" ? "Subscribe to the signature card (monthly bundle)" : "Subscribe to the signature card",
1535
+ openBrowserFlag
1536
+ });
1537
+ const proof = await cer.wait();
1538
+ let url;
1539
+ try {
1540
+ ({ url } = await postCardCheckout(apiOrigin, bearer, orgId, {
1541
+ capability: "signature",
1542
+ offer,
1543
+ consentBillingData: true,
1544
+ uiLocale: lang,
1545
+ receipt: proof
1546
+ }));
1547
+ } catch (e) {
1548
+ const refusal = checkoutRefusal(e, { orgId, incorporation: incorporation.code });
1549
+ if (refusal) return refusal;
1550
+ throw e;
1551
+ }
1552
+ let checkoutUrl;
1553
+ try {
1554
+ checkoutUrl = assertCardCheckoutBrowserUrl(url);
1555
+ } catch (e) {
1556
+ return { ok: false, error: e instanceof Error ? e.message : "checkout_url_rejected" };
1557
+ }
1006
1558
  if (openBrowserFlag) {
1007
1559
  try {
1008
- await openBrowser(assertCardCheckoutBrowserUrl(url));
1560
+ await openBrowser(checkoutUrl);
1009
1561
  } catch {
1010
1562
  }
1011
1563
  }
1012
1564
  return {
1013
1565
  ok: true,
1014
1566
  data: {
1015
- url,
1567
+ url: checkoutUrl,
1016
1568
  human: {
1017
1569
  needs_human: "payment",
1018
1570
  message: "Complete card checkout in the browser. Then poll clavis_setup_status.",
1019
- open_url: url
1571
+ open_url: checkoutUrl
1020
1572
  }
1021
1573
  }
1022
1574
  };
@@ -1033,26 +1585,24 @@ function createSetupClient(options = {}) {
1033
1585
  v: 1,
1034
1586
  host: args.host.trim().toLowerCase(),
1035
1587
  display_name: args.displayName.trim(),
1036
- intent_types: args.intentTypes ?? ["generic.sign"],
1588
+ intent_types: args.intentTypes ?? ["generic_sign"],
1037
1589
  max_ttl_seconds: 300,
1038
1590
  operate_kid: keys.kid,
1039
1591
  operate_public_jwk: keys.publicJwk,
1040
1592
  redirect_paths: paths
1041
1593
  };
1042
1594
  const payload_hash = await computePayloadCommitmentHex(manifest);
1043
- const digest = await computeOrgAppRegisterDigest({ payload_hash, proposer_sub: sub });
1044
1595
  const cer = await runPasskeyCeremony({
1045
1596
  origins: auth.data.origins,
1046
1597
  bearer: auth.data.session.accessToken,
1047
- purpose: "org.app.register",
1048
- messageDigest: digest,
1598
+ statement: orgAppRegisterStatement({ org: args.orgId, payload: payload_hash }),
1049
1599
  displayHint: `Register App ${manifest.host}`,
1050
1600
  openBrowserFlag
1051
1601
  });
1052
1602
  const proof = await cer.wait();
1053
1603
  const registered = await postAppRegister(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, {
1054
1604
  ...manifest,
1055
- proposer_sign_proof: proof
1605
+ proposer_receipt: proof
1056
1606
  });
1057
1607
  const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
1058
1608
  return {
@@ -1097,17 +1647,10 @@ function createSetupClient(options = {}) {
1097
1647
  const nonceMatch = /nonce=([^;]+)/.exec(ch.txt_value);
1098
1648
  const nonce = nonceMatch?.[1]?.trim() ?? "";
1099
1649
  if (!nonce) return { ok: false, error: "host_challenge_missing_nonce" };
1100
- const digest = await computeOrgAppVerifyHostDigest({
1101
- org_id: args.orgId,
1102
- app_id: args.appId,
1103
- host: ch.host,
1104
- nonce
1105
- });
1106
1650
  const cer = await runPasskeyCeremony({
1107
1651
  origins: auth.data.origins,
1108
1652
  bearer: auth.data.session.accessToken,
1109
- purpose: "org.app.verify_host",
1110
- messageDigest: digest,
1653
+ statement: orgAppVerifyHostStatement({ org: args.orgId, app: args.appId, host: ch.host, nonce }),
1111
1654
  displayHint: `Verify host ${ch.host}`,
1112
1655
  openBrowserFlag
1113
1656
  });
@@ -1136,21 +1679,11 @@ function createSetupClient(options = {}) {
1136
1679
  async declarationSet(args) {
1137
1680
  const auth = await requireSession({ origins, sessionPath });
1138
1681
  if (!auth.ok) return auth;
1139
- const sub = auth.data.session.sub;
1140
- if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1141
1682
  const declaration = { endUsers: args.endUsers, uses: args.uses };
1142
- const declaration_hash = await computeOrgAppDeclarationHash(declaration);
1143
- const digest = await computeOrgAppDeclarationDigest({
1144
- org_id: args.orgId,
1145
- app_id: args.appId,
1146
- declaration_hash,
1147
- actor_sub: sub
1148
- });
1149
1683
  const cer = await runPasskeyCeremony({
1150
1684
  origins: auth.data.origins,
1151
1685
  bearer: auth.data.session.accessToken,
1152
- purpose: "org.app.declaration",
1153
- messageDigest: digest,
1686
+ statement: await orgAppDeclarationStatement({ org: args.orgId, app: args.appId, declaration }),
1154
1687
  displayHint: `Declare uses for App ${args.appId}`,
1155
1688
  openBrowserFlag
1156
1689
  });
@@ -1160,10 +1693,47 @@ function createSetupClient(options = {}) {
1160
1693
  auth.data.session.accessToken,
1161
1694
  args.orgId,
1162
1695
  args.appId,
1163
- { endUsers: args.endUsers, uses: args.uses, signProof: proof }
1696
+ { endUsers: args.endUsers, uses: args.uses, receipt: proof }
1164
1697
  );
1165
1698
  return { ok: true, data: { declaration: out.declaration } };
1166
1699
  },
1700
+ async appRegionsSet(args) {
1701
+ const read = readAppRegionsInput(args.regions);
1702
+ if (!read.ok) return read;
1703
+ const regions = read.regions;
1704
+ const auth = await requireSession({ origins, sessionPath });
1705
+ if (!auth.ok) return auth;
1706
+ const sub = auth.data.session.sub;
1707
+ if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
1708
+ const apiOrigin = auth.data.origins.apiOrigin;
1709
+ const bearer = auth.data.session.accessToken;
1710
+ const app = await getApp(apiOrigin, bearer, args.orgId, args.appId);
1711
+ if (app.status === "disabled") return appDisabledRefusal();
1712
+ if (sameAppRegions(app.accepted_regions, regions)) {
1713
+ return { ok: true, data: { accepted_regions: regions, unchanged: true } };
1714
+ }
1715
+ if (regions) {
1716
+ const selectable = await getSelectableAppRegions(apiOrigin).catch(() => null);
1717
+ const closed = selectable ? regions.filter((region) => !selectable.includes(region)) : [];
1718
+ if (closed.length > 0) return regionNotOpenRefusal(closed, selectable);
1719
+ }
1720
+ const cer = await runPasskeyCeremony({
1721
+ origins: auth.data.origins,
1722
+ bearer,
1723
+ statement: orgAppRegionsStatement({ org: args.orgId, app: args.appId, regions }),
1724
+ displayHint: regions ? `Accept new connections to ${app.host} from ${regions.join(", ")} only` : `Accept new connections to ${app.host} from every region Clavis accepts`,
1725
+ openBrowserFlag
1726
+ });
1727
+ const proof = await cer.wait();
1728
+ try {
1729
+ await putAppRegions(apiOrigin, bearer, args.orgId, args.appId, { regions, receipt: proof });
1730
+ return { ok: true, data: { accepted_regions: regions } };
1731
+ } catch (e) {
1732
+ const refusal = appRegionsRefusal(e, regions ?? []);
1733
+ if (refusal) return refusal;
1734
+ throw e;
1735
+ }
1736
+ },
1167
1737
  async emitEnv(args) {
1168
1738
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1169
1739
  if (!jwk) {
@@ -1172,7 +1742,7 @@ function createSetupClient(options = {}) {
1172
1742
  error: "operate_jwk_missing",
1173
1743
  human: {
1174
1744
  needs_human: "login",
1175
- message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
1745
+ message: "Run app-register first so the operate key exists under ~/.config/clavis/apps/"
1176
1746
  }
1177
1747
  };
1178
1748
  }
@@ -1188,15 +1758,18 @@ function createSetupClient(options = {}) {
1188
1758
  }
1189
1759
  var init_setup_client = __esm({
1190
1760
  "src/setup-client.ts"() {
1761
+ init_app_regions();
1191
1762
  init_browser();
1763
+ init_card();
1192
1764
  init_safe_browser_url();
1193
- init_digests();
1765
+ init_statements();
1194
1766
  init_ceremony();
1195
1767
  init_emit_env();
1196
1768
  init_operate_key_store();
1197
1769
  init_keys();
1198
1770
  init_login();
1199
1771
  init_org_api();
1772
+ init_org_creation();
1200
1773
  init_session_store();
1201
1774
  init_status();
1202
1775
  }
@@ -1236,19 +1809,31 @@ var init_redact_transport = __esm({
1236
1809
  }
1237
1810
  });
1238
1811
 
1239
- // src/mcp.ts
1240
- var mcp_exports = {};
1241
- __export(mcp_exports, {
1812
+ // src/mcp-server.ts
1813
+ var mcp_server_exports = {};
1814
+ __export(mcp_server_exports, {
1242
1815
  runMcpServer: () => runMcpServer
1243
1816
  });
1817
+ function orgCreationTerms(args) {
1818
+ return {
1819
+ incorporation: typeof args.incorporation === "string" ? args.incorporation : void 0,
1820
+ acceptCustomerTerms: args.accept_customer_terms === true
1821
+ };
1822
+ }
1244
1823
  async function dispatch(client, name, args) {
1245
1824
  switch (name) {
1246
1825
  case "clavis_setup_status":
1247
1826
  return client.status();
1248
1827
  case "clavis_login":
1249
- return client.login();
1828
+ return client.login(
1829
+ args.bridge_json ? { bridgeJson: String(args.bridge_json) } : void 0
1830
+ );
1250
1831
  case "clavis_org_anchor_plan":
1251
- return client.orgAnchorPlan(String(args.domain), args.name ? String(args.name) : void 0);
1832
+ return client.orgAnchorPlan(
1833
+ String(args.domain),
1834
+ args.name ? String(args.name) : void 0,
1835
+ orgCreationTerms(args)
1836
+ );
1252
1837
  case "clavis_org_anchor_finish":
1253
1838
  return client.orgAnchorFinish({
1254
1839
  domain: String(args.domain),
@@ -1262,12 +1847,19 @@ async function dispatch(client, name, args) {
1262
1847
  return client.orgVerifyAnchor({
1263
1848
  domain: String(args.domain),
1264
1849
  nonce: String(args.nonce),
1265
- name: args.name ? String(args.name) : void 0
1850
+ name: args.name ? String(args.name) : void 0,
1851
+ ...orgCreationTerms(args)
1266
1852
  });
1267
1853
  case "clavis_policy_bootstrap":
1268
1854
  return client.policyBootstrap(String(args.org_id));
1855
+ case "clavis_incorporation_set":
1856
+ return client.incorporationSet({ orgId: String(args.org_id), ...orgCreationTerms(args) });
1269
1857
  case "clavis_card_checkout":
1270
- return client.cardCheckout(String(args.org_id));
1858
+ return client.cardCheckout(String(args.org_id), {
1859
+ offer: args.offer === "bundle" ? "bundle" : "meter",
1860
+ lang: checkoutLang(args.lang),
1861
+ consentBillingData: args.consent_billing_data === true
1862
+ });
1271
1863
  case "clavis_app_register":
1272
1864
  return client.appRegister({
1273
1865
  orgId: String(args.org_id),
@@ -1279,6 +1871,14 @@ async function dispatch(client, name, args) {
1279
1871
  return client.appHostPlan(String(args.org_id), String(args.app_id));
1280
1872
  case "clavis_app_verify_host":
1281
1873
  return client.appVerifyHost({ orgId: String(args.org_id), appId: String(args.app_id) });
1874
+ case "clavis_app_regions_set": {
1875
+ const choice = chooseAppRegions({
1876
+ ...args.regions !== void 0 ? { regions: Array.isArray(args.regions) ? args.regions.map((code) => String(code)) : [] } : {},
1877
+ all: args.all === true
1878
+ });
1879
+ if (!choice.ok) return choice;
1880
+ return client.appRegionsSet({ orgId: String(args.org_id), appId: String(args.app_id), regions: choice.regions });
1881
+ }
1282
1882
  case "clavis_declaration_set":
1283
1883
  return client.declarationSet({
1284
1884
  orgId: String(args.org_id),
@@ -1288,8 +1888,7 @@ async function dispatch(client, name, args) {
1288
1888
  });
1289
1889
  case "clavis_emit_app_env":
1290
1890
  return client.emitEnv({
1291
- appId: String(args.app_id),
1292
- operatePrivateJwkJson: typeof args.operate_private_jwk === "string" ? args.operate_private_jwk : void 0
1891
+ appId: String(args.app_id)
1293
1892
  });
1294
1893
  default:
1295
1894
  throw new Error(`unknown tool: ${name}`);
@@ -1324,32 +1923,54 @@ async function runMcpServer() {
1324
1923
  const transport = new StdioServerTransport();
1325
1924
  await server.connect(transport);
1326
1925
  }
1327
- var require2, PACKAGE_VERSION, TOOLS, isMain;
1328
- var init_mcp = __esm({
1329
- "src/mcp.ts"() {
1926
+ var require2, PACKAGE_VERSION, ORG_CREATION_PROPERTIES, TOOLS;
1927
+ var init_mcp_server = __esm({
1928
+ "src/mcp-server.ts"() {
1330
1929
  init_setup_client();
1930
+ init_app_regions();
1931
+ init_card();
1331
1932
  init_redact_transport();
1332
1933
  require2 = createRequire(import.meta.url);
1333
1934
  ({ version: PACKAGE_VERSION } = require2("../package.json"));
1935
+ ORG_CREATION_PROPERTIES = {
1936
+ incorporation: {
1937
+ type: "string",
1938
+ description: "Place of incorporation the customer declares for the Org: JP, GB-EAW, an EEA country code (e.g. DE), or US-XX (e.g. US-DE)."
1939
+ },
1940
+ accept_customer_terms: {
1941
+ type: "boolean",
1942
+ description: "true only after the customer (a human) has agreed to the Customer Terms and the Data Processing Agreement for this Org. Ask them; never set it on their behalf."
1943
+ }
1944
+ };
1334
1945
  TOOLS = [
1335
1946
  {
1336
1947
  name: "clavis_setup_status",
1337
- description: "List Org, App, signature card, and declaration readiness for the logged-in developers session.",
1948
+ description: "List Org, App, signature card (with what holds it back), place of incorporation, and declaration readiness for the logged-in developers session.",
1338
1949
  inputSchema: { type: "object", properties: {}, additionalProperties: false }
1339
1950
  },
1340
1951
  {
1341
1952
  name: "clavis_login",
1342
- description: "Open the browser for developers Passkey login and store a short-lived session.",
1343
- inputSchema: { type: "object", properties: {}, additionalProperties: false }
1953
+ description: "Start or finish developers Passkey login. First call opens the browser; after the human pastes the page JSON, call again with bridge_json.",
1954
+ inputSchema: {
1955
+ type: "object",
1956
+ properties: {
1957
+ bridge_json: {
1958
+ type: "string",
1959
+ description: "JSON shown on developers /setup/login after Passkey (state + accessToken)."
1960
+ }
1961
+ },
1962
+ additionalProperties: false
1963
+ }
1344
1964
  },
1345
1965
  {
1346
1966
  name: "clavis_org_anchor_plan",
1347
- description: "Start the Org DNS anchor challenge and open Passkey confirmation. Returns a ticket and human action.",
1967
+ description: "Start the Org DNS anchor challenge and open Passkey confirmation. Needs the place of incorporation and the customer's agreement to the Customer Terms; a place closed to new Orgs is refused before Passkey. Returns a ticket and human action.",
1348
1968
  inputSchema: {
1349
1969
  type: "object",
1350
1970
  properties: {
1351
1971
  domain: { type: "string" },
1352
- name: { type: "string" }
1972
+ name: { type: "string" },
1973
+ ...ORG_CREATION_PROPERTIES
1353
1974
  },
1354
1975
  required: ["domain"],
1355
1976
  additionalProperties: false
@@ -1374,13 +1995,14 @@ var init_mcp = __esm({
1374
1995
  },
1375
1996
  {
1376
1997
  name: "clavis_org_verify_anchor",
1377
- description: "Verify the Org DNS anchor after TXT and well-known are published.",
1998
+ description: "Verify the Org DNS anchor after TXT and well-known are published, and create the Org. Pass the same incorporation and the customer's agreement to the Customer Terms as org_anchor_plan.",
1378
1999
  inputSchema: {
1379
2000
  type: "object",
1380
2001
  properties: {
1381
2002
  domain: { type: "string" },
1382
2003
  nonce: { type: "string" },
1383
- name: { type: "string" }
2004
+ name: { type: "string" },
2005
+ ...ORG_CREATION_PROPERTIES
1384
2006
  },
1385
2007
  required: ["domain", "nonce"],
1386
2008
  additionalProperties: false
@@ -1396,12 +2018,41 @@ var init_mcp = __esm({
1396
2018
  additionalProperties: false
1397
2019
  }
1398
2020
  },
2021
+ {
2022
+ name: "clavis_incorporation_set",
2023
+ description: "Declare the Org's place of incorporation again (Passkey). Needed before card checkout when status shows incorporation null or terms_current false. The declaration binds the current Customer Terms and DPA, so it needs the customer's agreement.",
2024
+ inputSchema: {
2025
+ type: "object",
2026
+ properties: {
2027
+ org_id: { type: "string" },
2028
+ ...ORG_CREATION_PROPERTIES
2029
+ },
2030
+ required: ["org_id"],
2031
+ additionalProperties: false
2032
+ }
2033
+ },
1399
2034
  {
1400
2035
  name: "clavis_card_checkout",
1401
- description: "Open the checkout URL for the signature card.",
2036
+ description: "Open the checkout URL for the signature card (Passkey). Needs a current place of incorporation and the customer's consent to provide billing data to the payment provider. Call once without consent_billing_data to get the consent statement, show it to the customer, and call again only if they consent.",
1402
2037
  inputSchema: {
1403
2038
  type: "object",
1404
- properties: { org_id: { type: "string" } },
2039
+ properties: {
2040
+ org_id: { type: "string" },
2041
+ offer: {
2042
+ type: "string",
2043
+ enum: ["meter", "bundle"],
2044
+ description: "meter (pay per use, default) or bundle (monthly bundle)."
2045
+ },
2046
+ lang: {
2047
+ type: "string",
2048
+ enum: ["en", "ja"],
2049
+ description: "Language of the consent statement shown to the customer (default en). The purchase record keeps this language."
2050
+ },
2051
+ consent_billing_data: {
2052
+ type: "boolean",
2053
+ description: "true only after the customer (a human) has read the consent statement and consented. Ask them; never set it on their behalf."
2054
+ }
2055
+ },
1405
2056
  required: ["org_id"],
1406
2057
  additionalProperties: false
1407
2058
  }
@@ -1441,6 +2092,29 @@ var init_mcp = __esm({
1441
2092
  additionalProperties: false
1442
2093
  }
1443
2094
  },
2095
+ {
2096
+ name: "clavis_app_regions_set",
2097
+ description: "Choose the regions the App accepts new connections from (Passkey). Pass regions, or all: true to accept every region Clavis accepts. People already connected keep using the App. A region Clavis does not accept right now is refused before Passkey.",
2098
+ inputSchema: {
2099
+ type: "object",
2100
+ properties: {
2101
+ org_id: { type: "string" },
2102
+ app_id: { type: "string" },
2103
+ regions: {
2104
+ type: "array",
2105
+ items: { type: "string", enum: [...APP_REGIONS] },
2106
+ minItems: 1,
2107
+ description: "JP, US, GB, EEA. New connections from anywhere else are refused."
2108
+ },
2109
+ all: {
2110
+ type: "boolean",
2111
+ description: "true to accept every region Clavis accepts (removes the App's list)."
2112
+ }
2113
+ },
2114
+ required: ["org_id", "app_id"],
2115
+ additionalProperties: false
2116
+ }
2117
+ },
1444
2118
  {
1445
2119
  name: "clavis_declaration_set",
1446
2120
  description: "Replace the App use declaration (Passkey). uses becomes the whole declaration. Include every capability to keep. Signature requests need a signature use.",
@@ -1472,27 +2146,72 @@ var init_mcp = __esm({
1472
2146
  inputSchema: {
1473
2147
  type: "object",
1474
2148
  properties: {
1475
- app_id: { type: "string" },
1476
- operate_private_jwk: {
1477
- type: "string",
1478
- description: "Optional if app-register already saved the key under ~/.config/clavis/apps/"
1479
- }
2149
+ app_id: { type: "string" }
1480
2150
  },
1481
2151
  required: ["app_id"],
1482
2152
  additionalProperties: false
1483
2153
  }
1484
2154
  }
1485
2155
  ];
1486
- isMain = typeof process.argv[1] === "string" && import.meta.url === pathToFileURL(process.argv[1]).href;
1487
- if (isMain) {
1488
- runMcpServer().catch((e) => {
1489
- console.error(e);
1490
- process.exit(1);
1491
- });
1492
- }
1493
2156
  }
1494
2157
  });
1495
2158
 
2159
+ // src/cli-args.ts
2160
+ init_app_regions();
2161
+ function flag(args, name) {
2162
+ const i = args.indexOf(name);
2163
+ if (i < 0) return void 0;
2164
+ return args[i + 1];
2165
+ }
2166
+ function hasFlag(args, name) {
2167
+ return args.includes(name);
2168
+ }
2169
+ function positionals(args, valueFlags) {
2170
+ const out = [];
2171
+ for (let i = 0; i < args.length; i++) {
2172
+ const arg = args[i];
2173
+ if (valueFlags.includes(arg)) {
2174
+ i++;
2175
+ continue;
2176
+ }
2177
+ if (arg.startsWith("--")) continue;
2178
+ out.push(arg);
2179
+ }
2180
+ return out;
2181
+ }
2182
+ function orgCreationTermsFromArgs(args) {
2183
+ return {
2184
+ incorporation: flag(args, "--incorporation"),
2185
+ acceptCustomerTerms: hasFlag(args, "--accept-customer-terms")
2186
+ };
2187
+ }
2188
+ function cardCheckoutOptionsFromArgs(args) {
2189
+ const offer = flag(args, "--offer");
2190
+ if (offer !== void 0 && offer !== "meter" && offer !== "bundle") {
2191
+ return { ok: false, error: "--offer must be meter or bundle" };
2192
+ }
2193
+ const lang = flag(args, "--lang");
2194
+ if (lang !== void 0 && lang !== "en" && lang !== "ja") {
2195
+ return { ok: false, error: "--lang must be en or ja" };
2196
+ }
2197
+ return {
2198
+ ok: true,
2199
+ options: {
2200
+ ...offer ? { offer } : {},
2201
+ ...lang ? { lang } : {},
2202
+ consentBillingData: hasFlag(args, "--consent-billing-data")
2203
+ }
2204
+ };
2205
+ }
2206
+ function appRegionsFromArgs(args) {
2207
+ const raw = flag(args, "--regions");
2208
+ const listed = args.includes("--regions");
2209
+ return chooseAppRegions({
2210
+ ...listed ? { regions: (raw ?? "").split(",").filter((code) => code.trim().length > 0) } : {},
2211
+ all: hasFlag(args, "--all")
2212
+ });
2213
+ }
2214
+
1496
2215
  // src/cli.ts
1497
2216
  init_setup_client();
1498
2217
  init_redact_transport();
@@ -1501,33 +2220,38 @@ function printJson(value) {
1501
2220
  }
1502
2221
  function usage() {
1503
2222
  console.error(`Usage:
1504
- clavis login
2223
+ clavis login [--bridge-json-file <path>]
1505
2224
  clavis logout
1506
2225
  clavis status
1507
2226
  clavis mcp
1508
- clavis org-anchor-plan <domain> [name]
2227
+ clavis org-anchor-plan <domain> [name] --incorporation CODE --accept-customer-terms
1509
2228
  clavis org-anchor-finish --domain D --nonce N --exp E --ticket T --well-known-url U --txt-host H
1510
- clavis org-verify-anchor --domain D --nonce N [--name N]
2229
+ clavis org-verify-anchor --domain D --nonce N --incorporation CODE --accept-customer-terms [--name N]
1511
2230
  clavis policy-bootstrap <orgId>
1512
- clavis card-checkout <orgId>
2231
+ clavis incorporation-set <orgId> --incorporation CODE --accept-customer-terms
2232
+ clavis card-checkout <orgId> --consent-billing-data [--offer meter|bundle] [--lang en|ja]
1513
2233
  clavis app-register --org O --host H --name N [--redirect /done]
1514
2234
  clavis app-host-plan <orgId> <appId>
1515
2235
  clavis app-verify-host <orgId> <appId>
2236
+ clavis app-regions-set <orgId> <appId> (--regions JP,US | --all)
1516
2237
  clavis declaration-set --org O --app A --end-users TEXT --use signature=OP
1517
- clavis emit-env --app A [--operate-jwk '{"kty":"..."}']
2238
+ clavis emit-env --app A
1518
2239
 
2240
+ login: opens developers /setup/login, then paste the JSON from the page (or pass --bridge-json-file).
2241
+ Do not pass the access token or operate private key as a command-line argument.
2242
+ org-anchor-plan and org-verify-anchor need both flags. --incorporation is the Org's place of incorporation: JP, GB-EAW, an EEA country code, or US-XX.
2243
+ --accept-customer-terms records that the customer agrees to the Customer Terms and the DPA for this Org. That is the customer's decision: pass it only after they agree. It is never on by default.
2244
+ A place of incorporation that is closed to new Orgs right now is refused before Passkey.
2245
+ incorporation-set declares the place again after the Customer Terms change (status shows terms_current false). It needs the customer's agreement too.
2246
+ card-checkout needs --consent-billing-data: the customer's consent to provide billing data to the payment provider. Run it once without the flag to get the statement to show them.
1519
2247
  Secrets stay in ~/.config/clavis/apps/<appId>/ (mode 0600). Command output includes the file path. emit-env needs CLAVIS_MASTER_PUBLIC_JWK_JSON set to the master public JWK from /.well-known/jwks.json.
1520
- declaration-set replaces the App's current declaration. Pass every use to keep. status reports the signature card. WASM and ledger subscription are on developers.
2248
+ app-regions-set chooses where the App accepts new connections from: JP, US, GB, EEA (comma-separated). --all accepts every region Clavis accepts. People already connected keep using the App.
2249
+ declaration-set replaces the App's current declaration. Pass every use to keep. status reports the signature card and the place of incorporation. Ledger subscription is on developers.
1521
2250
 
1522
2251
  Env: CLAVIS_API_ORIGIN CLAVIS_ID_ORIGIN CLAVIS_DEVELOPERS_ORIGIN CLAVIS_SESSION_PATH
1523
2252
  `);
1524
2253
  process.exit(2);
1525
2254
  }
1526
- function flag(args, name) {
1527
- const i = args.indexOf(name);
1528
- if (i < 0) return void 0;
1529
- return args[i + 1];
1530
- }
1531
2255
  function requireFlag(args, name) {
1532
2256
  const v = flag(args, name);
1533
2257
  if (!v) {
@@ -1542,13 +2266,26 @@ async function main() {
1542
2266
  const client = createSetupClient();
1543
2267
  switch (cmd) {
1544
2268
  case "mcp": {
1545
- const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
2269
+ const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp_server(), mcp_server_exports));
1546
2270
  await runMcpServer2();
1547
2271
  return;
1548
2272
  }
1549
- case "login":
1550
- printJson(await client.login());
2273
+ case "login": {
2274
+ if (flag(rest, "--bridge-json")) {
2275
+ console.error(
2276
+ "refusing --bridge-json: the access token would be visible in the process list. Use --bridge-json-file or paste on stdin."
2277
+ );
2278
+ process.exit(2);
2279
+ }
2280
+ const fromFile = flag(rest, "--bridge-json-file");
2281
+ let bridgeJson;
2282
+ if (fromFile) {
2283
+ const { readFile: readFile4 } = await import('fs/promises');
2284
+ bridgeJson = await readFile4(fromFile, "utf8");
2285
+ }
2286
+ printJson(await client.login(bridgeJson ? { bridgeJson } : void 0));
1551
2287
  return;
2288
+ }
1552
2289
  case "logout":
1553
2290
  printJson(await client.logout());
1554
2291
  return;
@@ -1556,9 +2293,9 @@ async function main() {
1556
2293
  printJson(await client.status());
1557
2294
  return;
1558
2295
  case "org-anchor-plan": {
1559
- const domain = rest[0];
2296
+ const [domain, name] = positionals(rest, ["--incorporation"]);
1560
2297
  if (!domain) usage();
1561
- printJson(await client.orgAnchorPlan(domain, rest[1]));
2298
+ printJson(await client.orgAnchorPlan(domain, name, orgCreationTermsFromArgs(rest)));
1562
2299
  return;
1563
2300
  }
1564
2301
  case "org-anchor-finish":
@@ -1578,7 +2315,8 @@ async function main() {
1578
2315
  await client.orgVerifyAnchor({
1579
2316
  domain: requireFlag(rest, "--domain"),
1580
2317
  nonce: requireFlag(rest, "--nonce"),
1581
- name: flag(rest, "--name")
2318
+ name: flag(rest, "--name"),
2319
+ ...orgCreationTermsFromArgs(rest)
1582
2320
  })
1583
2321
  );
1584
2322
  return;
@@ -1588,10 +2326,21 @@ async function main() {
1588
2326
  printJson(await client.policyBootstrap(orgId));
1589
2327
  return;
1590
2328
  }
2329
+ case "incorporation-set": {
2330
+ const [orgId] = positionals(rest, ["--incorporation"]);
2331
+ if (!orgId) usage();
2332
+ printJson(await client.incorporationSet({ orgId, ...orgCreationTermsFromArgs(rest) }));
2333
+ return;
2334
+ }
1591
2335
  case "card-checkout": {
1592
- const orgId = rest[0];
2336
+ const [orgId] = positionals(rest, ["--offer", "--lang"]);
1593
2337
  if (!orgId) usage();
1594
- printJson(await client.cardCheckout(orgId));
2338
+ const opts = cardCheckoutOptionsFromArgs(rest);
2339
+ if (!opts.ok) {
2340
+ console.error(opts.error);
2341
+ usage();
2342
+ }
2343
+ printJson(await client.cardCheckout(orgId, opts.options));
1595
2344
  return;
1596
2345
  }
1597
2346
  case "app-register":
@@ -1616,6 +2365,17 @@ async function main() {
1616
2365
  printJson(await client.appVerifyHost({ orgId, appId }));
1617
2366
  return;
1618
2367
  }
2368
+ case "app-regions-set": {
2369
+ const [orgId, appId] = positionals(rest, ["--regions"]);
2370
+ if (!orgId || !appId) usage();
2371
+ const choice = appRegionsFromArgs(rest);
2372
+ if (!choice.ok) {
2373
+ console.error(choice.error);
2374
+ usage();
2375
+ }
2376
+ printJson(await client.appRegionsSet({ orgId, appId, regions: choice.regions }));
2377
+ return;
2378
+ }
1619
2379
  case "declaration-set": {
1620
2380
  const useRaw = requireFlag(rest, "--use");
1621
2381
  const [capability, ...opParts] = useRaw.split("=");
@@ -1632,10 +2392,15 @@ async function main() {
1632
2392
  return;
1633
2393
  }
1634
2394
  case "emit-env":
2395
+ if (flag(rest, "--operate-jwk")) {
2396
+ console.error(
2397
+ "refusing --operate-jwk: the private key would be visible in the process list. app-register saves it under ~/.config/clavis/apps/."
2398
+ );
2399
+ process.exit(2);
2400
+ }
1635
2401
  printJson(
1636
2402
  await client.emitEnv({
1637
- appId: requireFlag(rest, "--app"),
1638
- operatePrivateJwkJson: flag(rest, "--operate-jwk")
2403
+ appId: requireFlag(rest, "--app")
1639
2404
  })
1640
2405
  );
1641
2406
  return;