@clavis.nexus/setup 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -2,15 +2,16 @@
2
2
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
3
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
4
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
5
+ import { createRequire } from 'module';
5
6
  import { pathToFileURL } from 'url';
6
7
  import { execFile } from 'child_process';
7
8
  import { promisify } from 'util';
8
- import { generateKeyPair, exportJWK } from 'jose';
9
+ import { readFile, mkdir, writeFile, chmod, unlink } from 'fs/promises';
10
+ import { dirname, join } from 'path';
11
+ import { homedir } from 'os';
12
+ import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
9
13
  import { createServer } from 'http';
10
14
  import { randomBytes } from 'crypto';
11
- import { unlink, readFile, mkdir, writeFile, chmod } from 'fs/promises';
12
- import { join, dirname } from 'path';
13
- import { homedir } from 'os';
14
15
 
15
16
  var execFileAsync = promisify(execFile);
16
17
  async function openBrowser(url) {
@@ -25,6 +26,47 @@ async function openBrowser(url) {
25
26
  await execFileAsync("xdg-open", [url]);
26
27
  }
27
28
 
29
+ // src/safe-browser-url.ts
30
+ function parseHttpsUrl(raw) {
31
+ let u;
32
+ try {
33
+ u = new URL(raw.trim());
34
+ } catch {
35
+ throw new Error("invalid URL");
36
+ }
37
+ if (u.protocol !== "https:") {
38
+ throw new Error("only https URLs may be opened in a browser");
39
+ }
40
+ if (u.username || u.password) {
41
+ throw new Error("URL must not contain credentials");
42
+ }
43
+ return u;
44
+ }
45
+ function assertCardCheckoutBrowserUrl(raw) {
46
+ const u = parseHttpsUrl(raw);
47
+ const host = u.hostname.toLowerCase();
48
+ if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
49
+ throw new Error("checkout URL host is not allowed");
50
+ }
51
+ return u.toString();
52
+ }
53
+ function assertOriginBrowserUrl(raw, origin) {
54
+ const u = parseHttpsUrl(raw);
55
+ let expected;
56
+ try {
57
+ expected = new URL(origin.trim());
58
+ } catch {
59
+ throw new Error("invalid expected origin");
60
+ }
61
+ if (expected.protocol !== "https:") {
62
+ throw new Error("expected origin must be https");
63
+ }
64
+ if (u.origin !== expected.origin) {
65
+ throw new Error("URL origin does not match the expected origin");
66
+ }
67
+ return u.toString();
68
+ }
69
+
28
70
  // src/base64url.ts
29
71
  function bytesToBase64Url(bytes) {
30
72
  let bin = "";
@@ -121,14 +163,16 @@ function buildAnchorTxtRecord(args) {
121
163
 
122
164
  // src/ceremony.ts
123
165
  function signProofFromCeremonyPayload(payload) {
124
- if (payload === null || typeof payload !== "object") throw new Error("missing sign_proof");
166
+ if (payload === null || typeof payload !== "object") {
167
+ throw new Error("Passkey confirmation did not return a signature.");
168
+ }
125
169
  const o = payload;
126
170
  const nested = o.sign_proof;
127
171
  if (nested !== null && typeof nested === "object") return nested;
128
172
  if (o.v === 1 && o.intent_type === "generic_sign" && typeof o.intent_id === "string" && o.intent_id.length > 0) {
129
173
  return o;
130
174
  }
131
- throw new Error("missing sign_proof");
175
+ throw new Error("Passkey confirmation did not return a signature.");
132
176
  }
133
177
  async function startCeremony(args) {
134
178
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
@@ -148,7 +192,7 @@ async function startCeremony(args) {
148
192
  });
149
193
  const body = await res.json().catch(() => null);
150
194
  if (!res.ok || typeof body?.payload?.ticket !== "string") {
151
- throw new Error(body?.message ?? body?.error ?? `ceremony/start ${res.status}`);
195
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
152
196
  }
153
197
  return { ticket: body.payload.ticket, expires_in: body.payload.expires_in };
154
198
  }
@@ -156,7 +200,7 @@ async function pollCeremonyResult(args) {
156
200
  const timeoutMs = args.timeoutMs ?? 5 * 6e4;
157
201
  const intervalMs = args.intervalMs ?? 1500;
158
202
  const deadline = Date.now() + timeoutMs;
159
- let lastError = "ceremony result timeout";
203
+ let lastError = "Passkey confirmation timed out. Complete it in the browser, then retry.";
160
204
  while (Date.now() < deadline) {
161
205
  const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
162
206
  method: "POST",
@@ -176,7 +220,7 @@ async function pollCeremonyResult(args) {
176
220
  await sleep(intervalMs);
177
221
  continue;
178
222
  }
179
- throw new Error(body?.message ?? body?.error ?? `ceremony/result ${res.status}`);
223
+ throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
180
224
  }
181
225
  throw new Error(lastError);
182
226
  }
@@ -313,26 +357,99 @@ async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signatur
313
357
  body: { capability }
314
358
  });
315
359
  }
316
- async function getMasterJwkJson(apiOrigin) {
360
+ async function fetchJwksDocument(apiOrigin) {
317
361
  const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
318
362
  headers: { Accept: "application/json" }
319
363
  });
320
364
  if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
321
- const jwks = await res.json();
365
+ return res.json();
366
+ }
367
+ function masterJwkJsonFromDocument(jwks) {
322
368
  const master = jwks.master ?? jwks.keys?.find((k) => k.kid === "master" || k.use === "master" || k.alg === "EdDSA");
323
369
  if (!master) throw new SetupApiError(404, "MASTER_JWK_MISSING", "master JWK not found in JWKS");
324
370
  return JSON.stringify(master);
325
371
  }
372
+ async function getMasterJwkJson(apiOrigin, masterPinJson) {
373
+ const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
374
+ const doc = await fetchJwksDocument(apiOrigin);
375
+ await verifySignedJwksDocument(doc, masterPinJson);
376
+ return masterJwkJsonFromDocument(doc);
377
+ }
378
+ function operatePrivateJwkPath(appId) {
379
+ const app = appId.trim();
380
+ if (!app) throw new Error("appId required");
381
+ const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
382
+ return join(base, app, "operate-private.jwk.json");
383
+ }
384
+ function appEnvFilePath(appId) {
385
+ const app = appId.trim();
386
+ if (!app) throw new Error("appId required");
387
+ const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
388
+ return join(base, app, "app.env");
389
+ }
390
+ async function restrictFileMode(path) {
391
+ try {
392
+ await chmod(path, 384);
393
+ } catch (e) {
394
+ console.warn(
395
+ `clavis: could not set mode 0600 on ${path}: ${e instanceof Error ? e.message : e}`
396
+ );
397
+ }
398
+ }
399
+ async function saveOperatePrivateJwk(appId, jwkJson) {
400
+ const path = operatePrivateJwkPath(appId);
401
+ await mkdir(dirname(path), { recursive: true });
402
+ await writeFile(path, jwkJson.trim(), "utf8");
403
+ await restrictFileMode(path);
404
+ try {
405
+ await chmod(dirname(path), 448);
406
+ } catch {
407
+ }
408
+ return path;
409
+ }
410
+ async function readOperatePrivateJwk(appId) {
411
+ try {
412
+ const raw = await readFile(operatePrivateJwkPath(appId), "utf8");
413
+ return raw.trim() || null;
414
+ } catch {
415
+ return null;
416
+ }
417
+ }
418
+ async function writeAppEnvFile(appId, contents) {
419
+ const path = appEnvFilePath(appId);
420
+ await mkdir(dirname(path), { recursive: true });
421
+ await writeFile(path, contents.endsWith("\n") ? contents : `${contents}
422
+ `, "utf8");
423
+ await restrictFileMode(path);
424
+ return path;
425
+ }
326
426
 
327
427
  // src/emit-env.ts
328
428
  async function emitAppEnv(args) {
329
- const master = await getMasterJwkJson(args.origins.apiOrigin);
330
- return {
429
+ const pin = args.masterPublicJwkJson?.trim() || process.env.CLAVIS_MASTER_PUBLIC_JWK_JSON?.trim() || "";
430
+ if (!pin) {
431
+ throw new Error(
432
+ "CLAVIS_MASTER_PUBLIC_JWK_JSON is required. Set it to the master public JWK from GET {apiOrigin}/.well-known/jwks.json."
433
+ );
434
+ }
435
+ const master = await getMasterJwkJson(args.origins.apiOrigin, pin);
436
+ const operatePath = await saveOperatePrivateJwk(args.appId, args.operatePrivateJwkJson);
437
+ const envRecord = {
331
438
  CLAVIS_API_ORIGIN: args.origins.apiOrigin,
332
439
  CLAVIS_APP_ID: args.appId,
333
440
  OPERATE_PRIVATE_JWK: args.operatePrivateJwkJson,
334
441
  MASTER_PUBLIC_JWK_JSON: master
335
442
  };
443
+ const envFile = await writeAppEnvFile(args.appId, formatEnvExport(envRecord));
444
+ return {
445
+ env_file: envFile,
446
+ operate_private_jwk_path: operatePath,
447
+ public_env: {
448
+ CLAVIS_API_ORIGIN: args.origins.apiOrigin,
449
+ CLAVIS_APP_ID: args.appId
450
+ },
451
+ shell: `set -a && . ${shellQuote(envFile)} && set +a`
452
+ };
336
453
  }
337
454
  function formatEnvExport(env) {
338
455
  return Object.entries(env).map(([k, v]) => `export ${k}=${shellQuote(v)}`).join("\n");
@@ -357,6 +474,11 @@ async function generateOperateKeyPair() {
357
474
  privateJwkJson: JSON.stringify(priv)
358
475
  };
359
476
  }
477
+ async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
478
+ const base = apiOrigin.replace(/\/+$/, "");
479
+ const jwks = createRemoteJWKSet(new URL(`${base}/.well-known/jwks.json`));
480
+ await jwtVerify(accessToken, jwks, { algorithms: ["ES256"] });
481
+ }
360
482
 
361
483
  // src/types.ts
362
484
  var DEFAULT_ORIGINS = {
@@ -395,7 +517,10 @@ async function saveSession(session, origins, path = defaultSessionPath()) {
395
517
  await writeFile(path, JSON.stringify(body, null, 2), "utf8");
396
518
  try {
397
519
  await chmod(path, 384);
398
- } catch {
520
+ } catch (e) {
521
+ console.warn(
522
+ `clavis: could not set session file mode 0600 (${path}): ${e instanceof Error ? e.message : e}`
523
+ );
399
524
  }
400
525
  }
401
526
  async function clearSession(path = defaultSessionPath()) {
@@ -406,10 +531,21 @@ async function clearSession(path = defaultSessionPath()) {
406
531
  }
407
532
 
408
533
  // src/login.ts
534
+ var MAX_CALLBACK_BODY_BYTES = 8192;
409
535
  function readBody(req) {
410
536
  return new Promise((resolve, reject) => {
411
537
  const chunks = [];
412
- req.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
538
+ let total = 0;
539
+ req.on("data", (c) => {
540
+ const buf = Buffer.isBuffer(c) ? c : Buffer.from(c);
541
+ total += buf.length;
542
+ if (total > MAX_CALLBACK_BODY_BYTES) {
543
+ reject(new Error("callback body too large"));
544
+ req.destroy();
545
+ return;
546
+ }
547
+ chunks.push(buf);
548
+ });
413
549
  req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
414
550
  req.on("error", reject);
415
551
  });
@@ -455,6 +591,13 @@ async function loginWithBrowser(args) {
455
591
  res.end(JSON.stringify({ ok: false, error: "invalid_callback" }));
456
592
  return;
457
593
  }
594
+ try {
595
+ await verifyDevelopersAccessToken(body.accessToken, args.origins.apiOrigin);
596
+ } catch {
597
+ res.writeHead(400, { "Content-Type": "application/json" });
598
+ res.end(JSON.stringify({ ok: false, error: "invalid_token" }));
599
+ return;
600
+ }
458
601
  const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
459
602
  const next = {
460
603
  accessToken: body.accessToken,
@@ -484,7 +627,7 @@ async function loginWithBrowser(args) {
484
627
  void (async () => {
485
628
  if (args.open !== false) {
486
629
  try {
487
- await openBrowser(bridge.toString());
630
+ await openBrowser(assertOriginBrowserUrl(bridge.toString(), args.origins.developersOrigin));
488
631
  } catch {
489
632
  }
490
633
  }
@@ -611,7 +754,7 @@ async function runPasskeyCeremony(args) {
611
754
  const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
612
755
  if (args.openBrowserFlag) {
613
756
  try {
614
- await openBrowser(ceremony_url);
757
+ await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
615
758
  } catch {
616
759
  }
617
760
  }
@@ -783,7 +926,7 @@ function createSetupClient(options = {}) {
783
926
  const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
784
927
  if (openBrowserFlag) {
785
928
  try {
786
- await openBrowser(url);
929
+ await openBrowser(assertCardCheckoutBrowserUrl(url));
787
930
  } catch {
788
931
  }
789
932
  }
@@ -832,15 +975,16 @@ function createSetupClient(options = {}) {
832
975
  ...manifest,
833
976
  proposer_sign_proof: proof
834
977
  });
978
+ const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
835
979
  return {
836
980
  ok: true,
837
981
  data: {
838
982
  app_id: registered.app_id,
839
983
  host: registered.host,
840
- operate_private_jwk: keys.privateJwkJson,
984
+ operate_private_jwk_path,
841
985
  human: {
842
986
  needs_human: "passkey",
843
- message: "App registered (pending host). Keep operate_private_jwk secret. Next: app_host_plan."
987
+ message: "App registered (pending host). Operate key saved locally (0600). Next: app_host_plan."
844
988
  }
845
989
  }
846
990
  };
@@ -942,18 +1086,60 @@ function createSetupClient(options = {}) {
942
1086
  return { ok: true, data: { declaration: out.declaration } };
943
1087
  },
944
1088
  async emitEnv(args) {
945
- const env = await emitAppEnv({
1089
+ const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1090
+ if (!jwk) {
1091
+ return {
1092
+ ok: false,
1093
+ error: "operate_jwk_missing",
1094
+ human: {
1095
+ needs_human: "login",
1096
+ message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
1097
+ }
1098
+ };
1099
+ }
1100
+ const out = await emitAppEnv({
946
1101
  origins,
947
1102
  appId: args.appId,
948
- operatePrivateJwkJson: args.operatePrivateJwkJson
1103
+ operatePrivateJwkJson: jwk
949
1104
  });
950
- return { ok: true, data: { env, shell: formatEnvExport(env) } };
1105
+ return { ok: true, data: out };
951
1106
  }
952
1107
  };
953
1108
  return client;
954
1109
  }
955
1110
 
1111
+ // src/redact-transport.ts
1112
+ var SECRET_KEYS = /* @__PURE__ */ new Set([
1113
+ "operate_private_jwk",
1114
+ "OPERATE_PRIVATE_JWK",
1115
+ "accessToken",
1116
+ "refreshToken"
1117
+ ]);
1118
+ function redactForTransport(value) {
1119
+ if (value === null || typeof value !== "object") return value;
1120
+ if (Array.isArray(value)) return value.map((x) => redactForTransport(x));
1121
+ const out = {};
1122
+ for (const [k, v] of Object.entries(value)) {
1123
+ if (SECRET_KEYS.has(k)) {
1124
+ out[k] = "[redacted \u2014 use operate_private_jwk_path or env_file on disk]";
1125
+ continue;
1126
+ }
1127
+ if (k === "shell" && typeof v === "string" && v.includes("OPERATE_PRIVATE_JWK=")) {
1128
+ out[k] = "[redacted \u2014 source env_file instead]";
1129
+ continue;
1130
+ }
1131
+ if (k === "env" && v && typeof v === "object" && !Array.isArray(v)) {
1132
+ out[k] = redactForTransport(v);
1133
+ continue;
1134
+ }
1135
+ out[k] = redactForTransport(v);
1136
+ }
1137
+ return out;
1138
+ }
1139
+
956
1140
  // src/mcp.ts
1141
+ var require2 = createRequire(import.meta.url);
1142
+ var { version: PACKAGE_VERSION } = require2("../package.json");
957
1143
  var TOOLS = [
958
1144
  {
959
1145
  name: "clavis_setup_status",
@@ -1031,7 +1217,7 @@ var TOOLS = [
1031
1217
  },
1032
1218
  {
1033
1219
  name: "clavis_app_register",
1034
- description: "Register an App and generate an operate key (Passkey). Returns the private JWK once.",
1220
+ description: "Register an App and generate an operate key (Passkey). Saves the private key under ~/.config/clavis/apps/<appId>/ (mode 0600) and returns that file path.",
1035
1221
  inputSchema: {
1036
1222
  type: "object",
1037
1223
  properties: {
@@ -1066,7 +1252,7 @@ var TOOLS = [
1066
1252
  },
1067
1253
  {
1068
1254
  name: "clavis_declaration_set",
1069
- description: "Set the App use declaration required before registering signature requests (Passkey).",
1255
+ description: "Replace the App use declaration (Passkey). uses becomes the whole declaration. Include every capability to keep. Signature requests need a signature use.",
1070
1256
  inputSchema: {
1071
1257
  type: "object",
1072
1258
  properties: {
@@ -1096,9 +1282,12 @@ var TOOLS = [
1096
1282
  type: "object",
1097
1283
  properties: {
1098
1284
  app_id: { type: "string" },
1099
- operate_private_jwk: { type: "string" }
1285
+ operate_private_jwk: {
1286
+ type: "string",
1287
+ description: "Optional if app-register already saved the key under ~/.config/clavis/apps/"
1288
+ }
1100
1289
  },
1101
- required: ["app_id", "operate_private_jwk"],
1290
+ required: ["app_id"],
1102
1291
  additionalProperties: false
1103
1292
  }
1104
1293
  }
@@ -1151,7 +1340,7 @@ async function dispatch(client, name, args) {
1151
1340
  case "clavis_emit_app_env":
1152
1341
  return client.emitEnv({
1153
1342
  appId: String(args.app_id),
1154
- operatePrivateJwkJson: String(args.operate_private_jwk)
1343
+ operatePrivateJwkJson: typeof args.operate_private_jwk === "string" ? args.operate_private_jwk : void 0
1155
1344
  });
1156
1345
  default:
1157
1346
  throw new Error(`unknown tool: ${name}`);
@@ -1159,7 +1348,7 @@ async function dispatch(client, name, args) {
1159
1348
  }
1160
1349
  async function runMcpServer() {
1161
1350
  const client = createSetupClient();
1162
- const server = new Server({ name: "clavis-setup", version: "0.1.0" }, { capabilities: { tools: {} } });
1351
+ const server = new Server({ name: "clavis-setup", version: PACKAGE_VERSION }, { capabilities: { tools: {} } });
1163
1352
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
1164
1353
  tools: TOOLS.map((t) => ({
1165
1354
  name: t.name,
@@ -1173,7 +1362,7 @@ async function runMcpServer() {
1173
1362
  try {
1174
1363
  const result = await dispatch(client, name, args);
1175
1364
  return {
1176
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1365
+ content: [{ type: "text", text: JSON.stringify(redactForTransport(result), null, 2) }]
1177
1366
  };
1178
1367
  } catch (e) {
1179
1368
  const message = e instanceof Error ? e.message : String(e);