@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/README.md +36 -23
- package/dist/cli.js +250 -33
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +8 -3
- package/dist/index.js +176 -22
- package/dist/index.js.map +1 -1
- package/dist/mcp.js +219 -30
- package/dist/mcp.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { execFile } from 'child_process';
|
|
2
2
|
import { promisify } from 'util';
|
|
3
|
-
import { generateKeyPair, exportJWK } from 'jose';
|
|
4
|
-
import { createServer } from 'http';
|
|
5
|
-
import { randomBytes } from 'crypto';
|
|
6
3
|
import { readFile, mkdir, writeFile, chmod, unlink } from 'fs/promises';
|
|
7
4
|
import { join, dirname } from 'path';
|
|
8
5
|
import { homedir } from 'os';
|
|
6
|
+
import { generateKeyPair, exportJWK, createRemoteJWKSet, jwtVerify } from 'jose';
|
|
7
|
+
import { createServer } from 'http';
|
|
8
|
+
import { randomBytes } from 'crypto';
|
|
9
9
|
|
|
10
10
|
// src/browser.ts
|
|
11
11
|
var execFileAsync = promisify(execFile);
|
|
@@ -21,6 +21,47 @@ async function openBrowser(url) {
|
|
|
21
21
|
await execFileAsync("xdg-open", [url]);
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
// src/safe-browser-url.ts
|
|
25
|
+
function parseHttpsUrl(raw) {
|
|
26
|
+
let u;
|
|
27
|
+
try {
|
|
28
|
+
u = new URL(raw.trim());
|
|
29
|
+
} catch {
|
|
30
|
+
throw new Error("invalid URL");
|
|
31
|
+
}
|
|
32
|
+
if (u.protocol !== "https:") {
|
|
33
|
+
throw new Error("only https URLs may be opened in a browser");
|
|
34
|
+
}
|
|
35
|
+
if (u.username || u.password) {
|
|
36
|
+
throw new Error("URL must not contain credentials");
|
|
37
|
+
}
|
|
38
|
+
return u;
|
|
39
|
+
}
|
|
40
|
+
function assertCardCheckoutBrowserUrl(raw) {
|
|
41
|
+
const u = parseHttpsUrl(raw);
|
|
42
|
+
const host = u.hostname.toLowerCase();
|
|
43
|
+
if (host !== "polar.sh" && !host.endsWith(".polar.sh")) {
|
|
44
|
+
throw new Error("checkout URL host is not allowed");
|
|
45
|
+
}
|
|
46
|
+
return u.toString();
|
|
47
|
+
}
|
|
48
|
+
function assertOriginBrowserUrl(raw, origin) {
|
|
49
|
+
const u = parseHttpsUrl(raw);
|
|
50
|
+
let expected;
|
|
51
|
+
try {
|
|
52
|
+
expected = new URL(origin.trim());
|
|
53
|
+
} catch {
|
|
54
|
+
throw new Error("invalid expected origin");
|
|
55
|
+
}
|
|
56
|
+
if (expected.protocol !== "https:") {
|
|
57
|
+
throw new Error("expected origin must be https");
|
|
58
|
+
}
|
|
59
|
+
if (u.origin !== expected.origin) {
|
|
60
|
+
throw new Error("URL origin does not match the expected origin");
|
|
61
|
+
}
|
|
62
|
+
return u.toString();
|
|
63
|
+
}
|
|
64
|
+
|
|
24
65
|
// src/base64url.ts
|
|
25
66
|
function bytesToBase64Url(bytes) {
|
|
26
67
|
let bin = "";
|
|
@@ -117,14 +158,16 @@ function buildAnchorTxtRecord(args) {
|
|
|
117
158
|
|
|
118
159
|
// src/ceremony.ts
|
|
119
160
|
function signProofFromCeremonyPayload(payload) {
|
|
120
|
-
if (payload === null || typeof payload !== "object")
|
|
161
|
+
if (payload === null || typeof payload !== "object") {
|
|
162
|
+
throw new Error("Passkey confirmation did not return a signature.");
|
|
163
|
+
}
|
|
121
164
|
const o = payload;
|
|
122
165
|
const nested = o.sign_proof;
|
|
123
166
|
if (nested !== null && typeof nested === "object") return nested;
|
|
124
167
|
if (o.v === 1 && o.intent_type === "generic_sign" && typeof o.intent_id === "string" && o.intent_id.length > 0) {
|
|
125
168
|
return o;
|
|
126
169
|
}
|
|
127
|
-
throw new Error("
|
|
170
|
+
throw new Error("Passkey confirmation did not return a signature.");
|
|
128
171
|
}
|
|
129
172
|
async function startCeremony(args) {
|
|
130
173
|
const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/start`, {
|
|
@@ -144,7 +187,7 @@ async function startCeremony(args) {
|
|
|
144
187
|
});
|
|
145
188
|
const body = await res.json().catch(() => null);
|
|
146
189
|
if (!res.ok || typeof body?.payload?.ticket !== "string") {
|
|
147
|
-
throw new Error(body?.message ?? body?.error ?? `
|
|
190
|
+
throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
|
|
148
191
|
}
|
|
149
192
|
return { ticket: body.payload.ticket, expires_in: body.payload.expires_in };
|
|
150
193
|
}
|
|
@@ -152,7 +195,7 @@ async function pollCeremonyResult(args) {
|
|
|
152
195
|
const timeoutMs = args.timeoutMs ?? 5 * 6e4;
|
|
153
196
|
const intervalMs = args.intervalMs ?? 1500;
|
|
154
197
|
const deadline = Date.now() + timeoutMs;
|
|
155
|
-
let lastError = "
|
|
198
|
+
let lastError = "Passkey confirmation timed out. Complete it in the browser, then retry.";
|
|
156
199
|
while (Date.now() < deadline) {
|
|
157
200
|
const res = await fetch(`${args.apiOrigin.replace(/\/+$/, "")}/webauthn/authentication/ceremony/result`, {
|
|
158
201
|
method: "POST",
|
|
@@ -172,7 +215,7 @@ async function pollCeremonyResult(args) {
|
|
|
172
215
|
await sleep(intervalMs);
|
|
173
216
|
continue;
|
|
174
217
|
}
|
|
175
|
-
throw new Error(body?.message ?? body?.error ?? `
|
|
218
|
+
throw new Error(body?.message ?? body?.error ?? `Passkey confirmation failed (HTTP ${res.status})`);
|
|
176
219
|
}
|
|
177
220
|
throw new Error(lastError);
|
|
178
221
|
}
|
|
@@ -309,26 +352,99 @@ async function postCardCheckout(apiOrigin, bearer, orgId, capability = "signatur
|
|
|
309
352
|
body: { capability }
|
|
310
353
|
});
|
|
311
354
|
}
|
|
312
|
-
async function
|
|
355
|
+
async function fetchJwksDocument(apiOrigin) {
|
|
313
356
|
const res = await fetch(`${apiOrigin.replace(/\/+$/, "")}/.well-known/jwks.json`, {
|
|
314
357
|
headers: { Accept: "application/json" }
|
|
315
358
|
});
|
|
316
359
|
if (!res.ok) throw new SetupApiError(res.status, "JWKS_FETCH", `jwks ${res.status}`);
|
|
317
|
-
|
|
360
|
+
return res.json();
|
|
361
|
+
}
|
|
362
|
+
function masterJwkJsonFromDocument(jwks) {
|
|
318
363
|
const master = jwks.master ?? jwks.keys?.find((k) => k.kid === "master" || k.use === "master" || k.alg === "EdDSA");
|
|
319
364
|
if (!master) throw new SetupApiError(404, "MASTER_JWK_MISSING", "master JWK not found in JWKS");
|
|
320
365
|
return JSON.stringify(master);
|
|
321
366
|
}
|
|
367
|
+
async function getMasterJwkJson(apiOrigin, masterPinJson) {
|
|
368
|
+
const { verifySignedJwksDocument } = await import('@clavis.nexus/app');
|
|
369
|
+
const doc = await fetchJwksDocument(apiOrigin);
|
|
370
|
+
await verifySignedJwksDocument(doc, masterPinJson);
|
|
371
|
+
return masterJwkJsonFromDocument(doc);
|
|
372
|
+
}
|
|
373
|
+
function operatePrivateJwkPath(appId) {
|
|
374
|
+
const app = appId.trim();
|
|
375
|
+
if (!app) throw new Error("appId required");
|
|
376
|
+
const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
|
|
377
|
+
return join(base, app, "operate-private.jwk.json");
|
|
378
|
+
}
|
|
379
|
+
function appEnvFilePath(appId) {
|
|
380
|
+
const app = appId.trim();
|
|
381
|
+
if (!app) throw new Error("appId required");
|
|
382
|
+
const base = process.env.CLAVIS_OPERATE_KEYS_DIR?.trim() || join(homedir(), ".config", "clavis", "apps");
|
|
383
|
+
return join(base, app, "app.env");
|
|
384
|
+
}
|
|
385
|
+
async function restrictFileMode(path) {
|
|
386
|
+
try {
|
|
387
|
+
await chmod(path, 384);
|
|
388
|
+
} catch (e) {
|
|
389
|
+
console.warn(
|
|
390
|
+
`clavis: could not set mode 0600 on ${path}: ${e instanceof Error ? e.message : e}`
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
async function saveOperatePrivateJwk(appId, jwkJson) {
|
|
395
|
+
const path = operatePrivateJwkPath(appId);
|
|
396
|
+
await mkdir(dirname(path), { recursive: true });
|
|
397
|
+
await writeFile(path, jwkJson.trim(), "utf8");
|
|
398
|
+
await restrictFileMode(path);
|
|
399
|
+
try {
|
|
400
|
+
await chmod(dirname(path), 448);
|
|
401
|
+
} catch {
|
|
402
|
+
}
|
|
403
|
+
return path;
|
|
404
|
+
}
|
|
405
|
+
async function readOperatePrivateJwk(appId) {
|
|
406
|
+
try {
|
|
407
|
+
const raw = await readFile(operatePrivateJwkPath(appId), "utf8");
|
|
408
|
+
return raw.trim() || null;
|
|
409
|
+
} catch {
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
async function writeAppEnvFile(appId, contents) {
|
|
414
|
+
const path = appEnvFilePath(appId);
|
|
415
|
+
await mkdir(dirname(path), { recursive: true });
|
|
416
|
+
await writeFile(path, contents.endsWith("\n") ? contents : `${contents}
|
|
417
|
+
`, "utf8");
|
|
418
|
+
await restrictFileMode(path);
|
|
419
|
+
return path;
|
|
420
|
+
}
|
|
322
421
|
|
|
323
422
|
// src/emit-env.ts
|
|
324
423
|
async function emitAppEnv(args) {
|
|
325
|
-
const
|
|
326
|
-
|
|
424
|
+
const pin = args.masterPublicJwkJson?.trim() || process.env.CLAVIS_MASTER_PUBLIC_JWK_JSON?.trim() || "";
|
|
425
|
+
if (!pin) {
|
|
426
|
+
throw new Error(
|
|
427
|
+
"CLAVIS_MASTER_PUBLIC_JWK_JSON is required. Set it to the master public JWK from GET {apiOrigin}/.well-known/jwks.json."
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
const master = await getMasterJwkJson(args.origins.apiOrigin, pin);
|
|
431
|
+
const operatePath = await saveOperatePrivateJwk(args.appId, args.operatePrivateJwkJson);
|
|
432
|
+
const envRecord = {
|
|
327
433
|
CLAVIS_API_ORIGIN: args.origins.apiOrigin,
|
|
328
434
|
CLAVIS_APP_ID: args.appId,
|
|
329
435
|
OPERATE_PRIVATE_JWK: args.operatePrivateJwkJson,
|
|
330
436
|
MASTER_PUBLIC_JWK_JSON: master
|
|
331
437
|
};
|
|
438
|
+
const envFile = await writeAppEnvFile(args.appId, formatEnvExport(envRecord));
|
|
439
|
+
return {
|
|
440
|
+
env_file: envFile,
|
|
441
|
+
operate_private_jwk_path: operatePath,
|
|
442
|
+
public_env: {
|
|
443
|
+
CLAVIS_API_ORIGIN: args.origins.apiOrigin,
|
|
444
|
+
CLAVIS_APP_ID: args.appId
|
|
445
|
+
},
|
|
446
|
+
shell: `set -a && . ${shellQuote(envFile)} && set +a`
|
|
447
|
+
};
|
|
332
448
|
}
|
|
333
449
|
function formatEnvExport(env) {
|
|
334
450
|
return Object.entries(env).map(([k, v]) => `export ${k}=${shellQuote(v)}`).join("\n");
|
|
@@ -353,6 +469,11 @@ async function generateOperateKeyPair() {
|
|
|
353
469
|
privateJwkJson: JSON.stringify(priv)
|
|
354
470
|
};
|
|
355
471
|
}
|
|
472
|
+
async function verifyDevelopersAccessToken(accessToken, apiOrigin) {
|
|
473
|
+
const base = apiOrigin.replace(/\/+$/, "");
|
|
474
|
+
const jwks = createRemoteJWKSet(new URL(`${base}/.well-known/jwks.json`));
|
|
475
|
+
await jwtVerify(accessToken, jwks, { algorithms: ["ES256"] });
|
|
476
|
+
}
|
|
356
477
|
|
|
357
478
|
// src/types.ts
|
|
358
479
|
var DEFAULT_ORIGINS = {
|
|
@@ -391,7 +512,10 @@ async function saveSession(session, origins, path = defaultSessionPath()) {
|
|
|
391
512
|
await writeFile(path, JSON.stringify(body, null, 2), "utf8");
|
|
392
513
|
try {
|
|
393
514
|
await chmod(path, 384);
|
|
394
|
-
} catch {
|
|
515
|
+
} catch (e) {
|
|
516
|
+
console.warn(
|
|
517
|
+
`clavis: could not set session file mode 0600 (${path}): ${e instanceof Error ? e.message : e}`
|
|
518
|
+
);
|
|
395
519
|
}
|
|
396
520
|
}
|
|
397
521
|
async function clearSession(path = defaultSessionPath()) {
|
|
@@ -402,10 +526,21 @@ async function clearSession(path = defaultSessionPath()) {
|
|
|
402
526
|
}
|
|
403
527
|
|
|
404
528
|
// src/login.ts
|
|
529
|
+
var MAX_CALLBACK_BODY_BYTES = 8192;
|
|
405
530
|
function readBody(req) {
|
|
406
531
|
return new Promise((resolve, reject) => {
|
|
407
532
|
const chunks = [];
|
|
408
|
-
|
|
533
|
+
let total = 0;
|
|
534
|
+
req.on("data", (c) => {
|
|
535
|
+
const buf = Buffer.isBuffer(c) ? c : Buffer.from(c);
|
|
536
|
+
total += buf.length;
|
|
537
|
+
if (total > MAX_CALLBACK_BODY_BYTES) {
|
|
538
|
+
reject(new Error("callback body too large"));
|
|
539
|
+
req.destroy();
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
chunks.push(buf);
|
|
543
|
+
});
|
|
409
544
|
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
410
545
|
req.on("error", reject);
|
|
411
546
|
});
|
|
@@ -451,6 +586,13 @@ async function loginWithBrowser(args) {
|
|
|
451
586
|
res.end(JSON.stringify({ ok: false, error: "invalid_callback" }));
|
|
452
587
|
return;
|
|
453
588
|
}
|
|
589
|
+
try {
|
|
590
|
+
await verifyDevelopersAccessToken(body.accessToken, args.origins.apiOrigin);
|
|
591
|
+
} catch {
|
|
592
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
593
|
+
res.end(JSON.stringify({ ok: false, error: "invalid_token" }));
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
454
596
|
const sub = typeof body.sub === "string" ? body.sub : subFromJwt(body.accessToken);
|
|
455
597
|
const next = {
|
|
456
598
|
accessToken: body.accessToken,
|
|
@@ -480,7 +622,7 @@ async function loginWithBrowser(args) {
|
|
|
480
622
|
void (async () => {
|
|
481
623
|
if (args.open !== false) {
|
|
482
624
|
try {
|
|
483
|
-
await openBrowser(bridge.toString());
|
|
625
|
+
await openBrowser(assertOriginBrowserUrl(bridge.toString(), args.origins.developersOrigin));
|
|
484
626
|
} catch {
|
|
485
627
|
}
|
|
486
628
|
}
|
|
@@ -607,7 +749,7 @@ async function runPasskeyCeremony(args) {
|
|
|
607
749
|
const ceremony_url = ceremonyPageUrl(args.origins.idOrigin, ticket);
|
|
608
750
|
if (args.openBrowserFlag) {
|
|
609
751
|
try {
|
|
610
|
-
await openBrowser(ceremony_url);
|
|
752
|
+
await openBrowser(assertOriginBrowserUrl(ceremony_url, args.origins.idOrigin));
|
|
611
753
|
} catch {
|
|
612
754
|
}
|
|
613
755
|
}
|
|
@@ -779,7 +921,7 @@ function createSetupClient(options = {}) {
|
|
|
779
921
|
const { url } = await postCardCheckout(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
|
|
780
922
|
if (openBrowserFlag) {
|
|
781
923
|
try {
|
|
782
|
-
await openBrowser(url);
|
|
924
|
+
await openBrowser(assertCardCheckoutBrowserUrl(url));
|
|
783
925
|
} catch {
|
|
784
926
|
}
|
|
785
927
|
}
|
|
@@ -828,15 +970,16 @@ function createSetupClient(options = {}) {
|
|
|
828
970
|
...manifest,
|
|
829
971
|
proposer_sign_proof: proof
|
|
830
972
|
});
|
|
973
|
+
const operate_private_jwk_path = await saveOperatePrivateJwk(registered.app_id, keys.privateJwkJson);
|
|
831
974
|
return {
|
|
832
975
|
ok: true,
|
|
833
976
|
data: {
|
|
834
977
|
app_id: registered.app_id,
|
|
835
978
|
host: registered.host,
|
|
836
|
-
|
|
979
|
+
operate_private_jwk_path,
|
|
837
980
|
human: {
|
|
838
981
|
needs_human: "passkey",
|
|
839
|
-
message: "App registered (pending host).
|
|
982
|
+
message: "App registered (pending host). Operate key saved locally (0600). Next: app_host_plan."
|
|
840
983
|
}
|
|
841
984
|
}
|
|
842
985
|
};
|
|
@@ -938,12 +1081,23 @@ function createSetupClient(options = {}) {
|
|
|
938
1081
|
return { ok: true, data: { declaration: out.declaration } };
|
|
939
1082
|
},
|
|
940
1083
|
async emitEnv(args) {
|
|
941
|
-
const
|
|
1084
|
+
const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
|
|
1085
|
+
if (!jwk) {
|
|
1086
|
+
return {
|
|
1087
|
+
ok: false,
|
|
1088
|
+
error: "operate_jwk_missing",
|
|
1089
|
+
human: {
|
|
1090
|
+
needs_human: "login",
|
|
1091
|
+
message: "Pass --operate-jwk or run app-register first so the operate key exists under ~/.config/clavis/apps/"
|
|
1092
|
+
}
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
const out = await emitAppEnv({
|
|
942
1096
|
origins,
|
|
943
1097
|
appId: args.appId,
|
|
944
|
-
operatePrivateJwkJson:
|
|
1098
|
+
operatePrivateJwkJson: jwk
|
|
945
1099
|
});
|
|
946
|
-
return { ok: true, data:
|
|
1100
|
+
return { ok: true, data: out };
|
|
947
1101
|
}
|
|
948
1102
|
};
|
|
949
1103
|
return client;
|