@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.129
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 +76 -5
- package/dist/{chunk-HZI5PBN4.js → chunk-BVGASV3B.js} +2047 -138
- package/dist/{chunk-72NIZMZN.js → chunk-DYXCJ6WZ.js} +15 -10
- package/dist/{chunk-TNWI3JWK.js → chunk-FHDTJP2C.js} +4 -2
- package/dist/{chunk-C4QNBSWB.js → chunk-HDL3UXYJ.js} +8 -8
- package/dist/{chunk-RV3JFSMX.js → chunk-IJ3W2YBM.js} +4 -4
- package/dist/{chunk-O65UVJZH.js → chunk-IZAEAALI.js} +2 -2
- package/dist/{chunk-H74RDXKP.js → chunk-KZNOT2YH.js} +2 -2
- package/dist/{chunk-R4EYLEIK.js → chunk-L7U3G4XR.js} +2 -2
- package/dist/{chunk-MGKSZSTV.js → chunk-LBZJD2I4.js} +3 -5
- package/dist/{chunk-UUQT5GMO.js → chunk-MMMY57UA.js} +22 -837
- package/dist/{chunk-H6X52UVF.js → chunk-NWWTFQP2.js} +1 -1
- package/dist/{chunk-WGTUNUIS.js → chunk-QSDWWEHF.js} +5 -5
- package/dist/{chunk-NVDPKW7Z.js → chunk-RAEOSDQ6.js} +3 -51
- package/dist/{chunk-KFRGVHGB.js → chunk-RS5ADTDF.js} +6 -6
- package/dist/{chunk-A5VTE43F.js → chunk-RWJ7WHTJ.js} +2 -2
- package/dist/{chunk-VVFVENU4.js → chunk-SJE7OWVS.js} +6 -6
- package/dist/{chunk-L6IL4N6Y.js → chunk-USJ4JGDC.js} +34 -34
- package/dist/{chunk-JCKOW45X.js → chunk-YPHDV5AS.js} +2 -2
- package/dist/{chunk-F3FDVHR7.js → chunk-YSV43WLK.js} +1 -1
- package/dist/{chunk-URYZDQFH.js → chunk-ZKIBD5MO.js} +3 -5
- package/dist/daemon/server.js +1769 -487
- package/dist/hook-runtime/daemon/server.js +1769 -487
- package/dist/hook-runtime/hooks/post-commit.js +611 -337
- package/dist/hook-runtime/hooks/post-rewrite.js +606 -332
- package/dist/hook-runtime/hooks/post-tool-use.js +1841 -683
- package/dist/hook-runtime/hooks/pre-commit.js +1713 -434
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1308 -150
- package/dist/hook-runtime/hooks/prim-hook.js +1863 -705
- package/dist/hook-runtime/hooks/session-end.js +538 -385
- package/dist/hook-runtime/hooks/session-start.js +1379 -233
- package/dist/hook-runtime/index.js +5438 -4052
- package/dist/hook-runtime/statusline-main.js +547 -273
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +18 -18
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +64 -22
- package/dist/index.js +396 -52
- package/dist/statusline-main.js +547 -273
- package/package.json +1 -1
|
@@ -87,15 +87,17 @@ function isClaudeCloudSession(env = process.env) {
|
|
|
87
87
|
}
|
|
88
88
|
var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
|
|
89
89
|
var CLOUD_REJECTED_CREDENTIALS_REMEDY = 'correct the credentials in the cloud environment\'s settings, or if the installation was revoked mint a replacement on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`; then start a new cloud session';
|
|
90
|
+
var CLOUD_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
|
|
91
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
90
92
|
function cloudSetupPointer(message, env = process.env) {
|
|
91
93
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
92
94
|
}
|
|
93
95
|
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
94
96
|
|
|
95
97
|
// src/client.ts
|
|
96
|
-
import { createHash as
|
|
97
|
-
import { chmodSync as
|
|
98
|
-
import { dirname as
|
|
98
|
+
import { createHash as createHash8 } from "crypto";
|
|
99
|
+
import { chmodSync as chmodSync4, existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync8 } from "fs";
|
|
100
|
+
import { dirname as dirname8 } from "path";
|
|
99
101
|
|
|
100
102
|
// src/lib/atomic-file.ts
|
|
101
103
|
import { randomUUID } from "crypto";
|
|
@@ -177,26 +179,26 @@ function atomicWriteFile(target, content, options = {}) {
|
|
|
177
179
|
}
|
|
178
180
|
|
|
179
181
|
// src/lib/credentials.ts
|
|
180
|
-
import { createHash as
|
|
181
|
-
import { readFileSync as
|
|
182
|
-
import { join as
|
|
182
|
+
import { createHash as createHash7 } from "crypto";
|
|
183
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
184
|
+
import { join as join11 } from "path";
|
|
183
185
|
|
|
184
186
|
// src/lib/machine-credentials.ts
|
|
185
|
-
import { execFileSync } from "child_process";
|
|
186
|
-
import { createHash as
|
|
187
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
188
|
+
import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
|
|
187
189
|
import {
|
|
188
|
-
chmodSync,
|
|
189
|
-
existsSync as
|
|
190
|
+
chmodSync as chmodSync2,
|
|
191
|
+
existsSync as existsSync5,
|
|
190
192
|
linkSync,
|
|
191
|
-
lstatSync as
|
|
192
|
-
mkdirSync as
|
|
193
|
-
readFileSync as
|
|
194
|
-
rmSync as
|
|
195
|
-
writeFileSync as
|
|
193
|
+
lstatSync as lstatSync5,
|
|
194
|
+
mkdirSync as mkdirSync4,
|
|
195
|
+
readFileSync as readFileSync7,
|
|
196
|
+
rmSync as rmSync7,
|
|
197
|
+
writeFileSync as writeFileSync4
|
|
196
198
|
} from "fs";
|
|
197
|
-
import { createRequire } from "module";
|
|
198
|
-
import { dirname as
|
|
199
|
-
import { fileURLToPath as
|
|
199
|
+
import { createRequire as createRequire2 } from "module";
|
|
200
|
+
import { dirname as dirname7, join as join10 } from "path";
|
|
201
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
200
202
|
|
|
201
203
|
// src/lib/file-lock.ts
|
|
202
204
|
import { randomBytes } from "crypto";
|
|
@@ -292,14 +294,14 @@ function throwIfAborted(signal) {
|
|
|
292
294
|
}
|
|
293
295
|
async function defaultSleep(ms, signal) {
|
|
294
296
|
if (!signal) {
|
|
295
|
-
await new Promise((
|
|
297
|
+
await new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
296
298
|
return;
|
|
297
299
|
}
|
|
298
300
|
throwIfAborted(signal);
|
|
299
|
-
await new Promise((
|
|
301
|
+
await new Promise((resolve4, reject) => {
|
|
300
302
|
const timer = setTimeout(() => {
|
|
301
303
|
signal.removeEventListener("abort", onAbort);
|
|
302
|
-
|
|
304
|
+
resolve4();
|
|
303
305
|
}, ms);
|
|
304
306
|
const onAbort = () => {
|
|
305
307
|
clearTimeout(timer);
|
|
@@ -341,20 +343,74 @@ async function withFileLock(lockDir, operation, options = {}) {
|
|
|
341
343
|
}
|
|
342
344
|
}
|
|
343
345
|
|
|
344
|
-
// src/lib/
|
|
345
|
-
import {
|
|
346
|
-
import {
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
346
|
+
// src/lib/hook-runtime.ts
|
|
347
|
+
import { createHash, randomBytes as randomBytes2 } from "crypto";
|
|
348
|
+
import {
|
|
349
|
+
constants as constants2,
|
|
350
|
+
accessSync,
|
|
351
|
+
chmodSync,
|
|
352
|
+
copyFileSync,
|
|
353
|
+
existsSync as existsSync4,
|
|
354
|
+
lstatSync,
|
|
355
|
+
mkdirSync as mkdirSync3,
|
|
356
|
+
mkdtempSync,
|
|
357
|
+
readFileSync as readFileSync3,
|
|
358
|
+
readdirSync,
|
|
359
|
+
realpathSync,
|
|
360
|
+
renameSync as renameSync2,
|
|
361
|
+
rmSync as rmSync3,
|
|
362
|
+
statSync as statSync2,
|
|
363
|
+
utimesSync,
|
|
364
|
+
writeFileSync as writeFileSync3
|
|
365
|
+
} from "fs";
|
|
366
|
+
import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
|
|
351
367
|
|
|
352
368
|
// src/lib/bin-path.ts
|
|
353
369
|
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
354
370
|
import { dirname as dirname3, isAbsolute, join as join2 } from "path";
|
|
355
371
|
import { fileURLToPath } from "url";
|
|
372
|
+
|
|
373
|
+
// src/lib/semver.ts
|
|
374
|
+
function parseSemver(value) {
|
|
375
|
+
if (typeof value !== "string" || value.length > 256) return;
|
|
376
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(
|
|
377
|
+
value
|
|
378
|
+
);
|
|
379
|
+
if (!match) return;
|
|
380
|
+
const prerelease = match[4]?.split(".") ?? [];
|
|
381
|
+
if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
|
|
385
|
+
}
|
|
386
|
+
function compareSemver(left, right) {
|
|
387
|
+
const a = parseSemver(left);
|
|
388
|
+
const b = parseSemver(right);
|
|
389
|
+
if (!a || !b) return;
|
|
390
|
+
for (let i = 0; i < a.core.length; i += 1) {
|
|
391
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
392
|
+
}
|
|
393
|
+
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
394
|
+
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
|
|
395
|
+
}
|
|
396
|
+
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
|
|
397
|
+
const x = a.prerelease[i];
|
|
398
|
+
const y = b.prerelease[i];
|
|
399
|
+
if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
|
|
400
|
+
if (x === y) continue;
|
|
401
|
+
const xNumeric = /^\d+$/u.test(x);
|
|
402
|
+
const yNumeric = /^\d+$/u.test(y);
|
|
403
|
+
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
404
|
+
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
|
|
405
|
+
return x < y ? -1 : 1;
|
|
406
|
+
}
|
|
407
|
+
return 0;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// src/lib/bin-path.ts
|
|
356
411
|
var PKG_NAME = "@primitive.ai/prim";
|
|
357
412
|
var ROOT_WALK_LIMIT = 6;
|
|
413
|
+
var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
|
|
358
414
|
var resolvedRoot;
|
|
359
415
|
function locateRoot() {
|
|
360
416
|
if (resolvedRoot !== void 0) {
|
|
@@ -401,6 +457,309 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
|
401
457
|
"fi; fi; "
|
|
402
458
|
].join("");
|
|
403
459
|
|
|
460
|
+
// src/lib/git-hook-contract.ts
|
|
461
|
+
var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
|
|
462
|
+
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
463
|
+
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
464
|
+
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
465
|
+
# where prim is active (git config prim.active true) and never fails the hook.
|
|
466
|
+
case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
|
|
467
|
+
prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
|
|
468
|
+
[ -x "$prim_launcher" ] || exit 0
|
|
469
|
+
[ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
|
|
470
|
+
prim_hook=\${1-}
|
|
471
|
+
if [ "$#" -gt 0 ]; then shift; fi
|
|
472
|
+
case "$prim_hook" in
|
|
473
|
+
pre-commit)
|
|
474
|
+
"$prim_launcher" prim-pre-commit "$@" || :
|
|
475
|
+
;;
|
|
476
|
+
post-commit)
|
|
477
|
+
prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
|
|
478
|
+
case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
|
|
479
|
+
case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
|
|
480
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
481
|
+
prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
|
|
482
|
+
(
|
|
483
|
+
trap '' HUP
|
|
484
|
+
trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
|
|
485
|
+
PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
|
|
486
|
+
) </dev/null >/dev/null 2>&1 &
|
|
487
|
+
;;
|
|
488
|
+
post-rewrite)
|
|
489
|
+
case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
|
|
490
|
+
prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
|
|
491
|
+
if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
|
|
492
|
+
rm -f "$prim_pairs"
|
|
493
|
+
exit 0
|
|
494
|
+
fi
|
|
495
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
496
|
+
(
|
|
497
|
+
trap '' HUP
|
|
498
|
+
trap 'rm -f "$prim_pairs"' 0
|
|
499
|
+
PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
|
|
500
|
+
) </dev/null >/dev/null 2>&1 &
|
|
501
|
+
;;
|
|
502
|
+
esac
|
|
503
|
+
exit 0
|
|
504
|
+
`;
|
|
505
|
+
|
|
506
|
+
// src/lib/native-keyring.ts
|
|
507
|
+
import { existsSync as existsSync3 } from "fs";
|
|
508
|
+
import { createRequire } from "module";
|
|
509
|
+
import { dirname as dirname4, join as join3 } from "path";
|
|
510
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
511
|
+
var require2 = createRequire(import.meta.url);
|
|
512
|
+
var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
|
|
513
|
+
|
|
514
|
+
// src/lib/paths.ts
|
|
515
|
+
import { homedir } from "os";
|
|
516
|
+
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
517
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
518
|
+
function absolutePath(value, variable) {
|
|
519
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
520
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
521
|
+
}
|
|
522
|
+
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
523
|
+
const normalized = normalize(value);
|
|
524
|
+
return normalized === value ? value : void 0;
|
|
525
|
+
}
|
|
526
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
527
|
+
const env = options.env ?? process.env;
|
|
528
|
+
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
529
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
530
|
+
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
531
|
+
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
532
|
+
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
533
|
+
if (!home) {
|
|
534
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
535
|
+
}
|
|
536
|
+
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
537
|
+
}
|
|
538
|
+
function primConfigDirectory(options = {}) {
|
|
539
|
+
return resolvePrimConfigDirectory(options).path;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// src/lib/hook-runtime.ts
|
|
543
|
+
var HOOK_RUNTIME_SCHEMA_VERSION = 1;
|
|
544
|
+
var RELEASE_PREFIX = "release-";
|
|
545
|
+
var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
|
|
546
|
+
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
547
|
+
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
548
|
+
var HOOK_RUNTIME_ENTRIES = {
|
|
549
|
+
// SessionStart self-healing resolves this exact CLI entry to run
|
|
550
|
+
// `daemon ensure`; it must travel with the immutable hook release.
|
|
551
|
+
prim: "dist/index.js",
|
|
552
|
+
"prim-hook": "dist/hooks/prim-hook.js",
|
|
553
|
+
"prim-pre-commit": "dist/hooks/pre-commit.js",
|
|
554
|
+
"prim-post-commit": "dist/hooks/post-commit.js",
|
|
555
|
+
"prim-post-rewrite": "dist/hooks/post-rewrite.js",
|
|
556
|
+
"prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
|
|
557
|
+
"prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
|
|
558
|
+
"prim-post-tool-use": "dist/hooks/post-tool-use.js",
|
|
559
|
+
"prim-session-start": "dist/hooks/session-start.js",
|
|
560
|
+
"prim-session-end": "dist/hooks/session-end.js",
|
|
561
|
+
"prim-daemon-server": "dist/daemon/server.js",
|
|
562
|
+
"prim-statusline": "dist/statusline-main.js"
|
|
563
|
+
};
|
|
564
|
+
var SOURCE_ENTRIES = Object.fromEntries(
|
|
565
|
+
Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
|
|
566
|
+
bin,
|
|
567
|
+
target.replace(/^dist\//u, "")
|
|
568
|
+
])
|
|
569
|
+
);
|
|
570
|
+
function hookRuntimePaths(options = {}) {
|
|
571
|
+
const env = options.env ?? process.env;
|
|
572
|
+
const configDir = primConfigDirectory({
|
|
573
|
+
...options,
|
|
574
|
+
env,
|
|
575
|
+
homeDir: options.homeDir ?? env.HOME ?? ""
|
|
576
|
+
});
|
|
577
|
+
const runtimeDir = join5(configDir, "hook-runtime");
|
|
578
|
+
return {
|
|
579
|
+
configDir,
|
|
580
|
+
launcher: join5(configDir, STABLE_HOOK_LAUNCHER_NAME),
|
|
581
|
+
gitHookEntrypoint: join5(configDir, GIT_HOOK_ENTRYPOINT_NAME),
|
|
582
|
+
runtimeDir,
|
|
583
|
+
releasesDir: join5(runtimeDir, "releases"),
|
|
584
|
+
current: join5(runtimeDir, "current"),
|
|
585
|
+
selectionLock: join5(runtimeDir, "selection.lock")
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
function sha256(path) {
|
|
589
|
+
return createHash("sha256").update(readFileSync3(path)).digest("hex");
|
|
590
|
+
}
|
|
591
|
+
function exactManifest(manifest) {
|
|
592
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
593
|
+
`;
|
|
594
|
+
}
|
|
595
|
+
function exactKeys(value, expected) {
|
|
596
|
+
const actual = Object.keys(value).sort();
|
|
597
|
+
const wanted = [...expected].sort();
|
|
598
|
+
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
599
|
+
}
|
|
600
|
+
function releaseId(manifest) {
|
|
601
|
+
return createHash("sha256").update(exactManifest(manifest)).digest("hex");
|
|
602
|
+
}
|
|
603
|
+
function runtimePackageJson(manifest) {
|
|
604
|
+
return `${JSON.stringify(
|
|
605
|
+
{
|
|
606
|
+
name: "@primitive.ai/prim",
|
|
607
|
+
version: manifest.version,
|
|
608
|
+
type: "module",
|
|
609
|
+
bin: HOOK_RUNTIME_ENTRIES
|
|
610
|
+
},
|
|
611
|
+
null,
|
|
612
|
+
2
|
|
613
|
+
)}
|
|
614
|
+
`;
|
|
615
|
+
}
|
|
616
|
+
function validateRelease(releaseDir, manifest) {
|
|
617
|
+
try {
|
|
618
|
+
if (!directReleaseLayout(releaseDir, manifest)) return false;
|
|
619
|
+
if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
|
|
620
|
+
return false;
|
|
621
|
+
}
|
|
622
|
+
if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
|
|
626
|
+
`) {
|
|
627
|
+
return false;
|
|
628
|
+
}
|
|
629
|
+
for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
630
|
+
const target = join5(releaseDir, relativePath);
|
|
631
|
+
if (sha256(target) !== manifest.files[bin]) return false;
|
|
632
|
+
}
|
|
633
|
+
for (const [path, digest] of Object.entries(manifest.native ?? {})) {
|
|
634
|
+
if (sha256(join5(releaseDir, path)) !== digest) return false;
|
|
635
|
+
}
|
|
636
|
+
return true;
|
|
637
|
+
} catch {
|
|
638
|
+
return false;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
function directReleaseLayout(releaseDir, manifest) {
|
|
642
|
+
try {
|
|
643
|
+
const directories = /* @__PURE__ */ new Set([releaseDir]);
|
|
644
|
+
for (const relativePath of [
|
|
645
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
646
|
+
...Object.keys(manifest.native ?? {})
|
|
647
|
+
]) {
|
|
648
|
+
for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
|
|
649
|
+
directories.add(join5(releaseDir, directory));
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
|
|
653
|
+
const files = [
|
|
654
|
+
"manifest.json",
|
|
655
|
+
"package.json",
|
|
656
|
+
"node",
|
|
657
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
658
|
+
...Object.keys(manifest.native ?? {})
|
|
659
|
+
];
|
|
660
|
+
const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join5(releaseDir, path))]);
|
|
661
|
+
if (![...directories].every(
|
|
662
|
+
(directory) => readdirSync(directory).every((name) => owned.has(join5(directory, name)))
|
|
663
|
+
))
|
|
664
|
+
return false;
|
|
665
|
+
return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
|
|
666
|
+
} catch {
|
|
667
|
+
return false;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
function readReleaseManifest(releaseDir, releaseName) {
|
|
671
|
+
try {
|
|
672
|
+
const manifestPath = join5(releaseDir, "manifest.json");
|
|
673
|
+
const manifestStat = statSync2(manifestPath);
|
|
674
|
+
if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
|
|
675
|
+
const raw = readFileSync3(manifestPath, "utf8");
|
|
676
|
+
const parsed = JSON.parse(raw);
|
|
677
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
678
|
+
if (!exactKeys(parsed, [
|
|
679
|
+
"schemaVersion",
|
|
680
|
+
"version",
|
|
681
|
+
"nodePath",
|
|
682
|
+
"files",
|
|
683
|
+
..."native" in parsed ? ["native"] : []
|
|
684
|
+
]))
|
|
685
|
+
return null;
|
|
686
|
+
const candidate = parsed;
|
|
687
|
+
if (candidate.schemaVersion !== HOOK_RUNTIME_SCHEMA_VERSION || typeof candidate.version !== "string" || compareSemver(candidate.version, candidate.version) !== 0 || typeof candidate.nodePath !== "string" || !isAbsolute3(candidate.nodePath) || /[\r\n]/u.test(candidate.nodePath) || !candidate.files || typeof candidate.files !== "object" || Array.isArray(candidate.files) || !exactKeys(candidate.files, Object.keys(HOOK_RUNTIME_ENTRIES)) || Object.values(candidate.files).some(
|
|
688
|
+
(digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
|
|
689
|
+
)) {
|
|
690
|
+
return null;
|
|
691
|
+
}
|
|
692
|
+
if (candidate.native !== void 0 && (!candidate.native || typeof candidate.native !== "object" || Array.isArray(candidate.native) || !exactKeys(candidate.native, KEYRING_NATIVE_FILES) || Object.values(candidate.native).some(
|
|
693
|
+
(digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
|
|
694
|
+
)))
|
|
695
|
+
return null;
|
|
696
|
+
const manifest = candidate;
|
|
697
|
+
if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
return manifest;
|
|
701
|
+
} catch {
|
|
702
|
+
return null;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
function readSelectedRelease(paths) {
|
|
706
|
+
let raw;
|
|
707
|
+
try {
|
|
708
|
+
raw = readFileSync3(paths.current, "utf8");
|
|
709
|
+
} catch (error) {
|
|
710
|
+
if (error.code === "ENOENT") return null;
|
|
711
|
+
throw error;
|
|
712
|
+
}
|
|
713
|
+
const name = raw.endsWith("\n") ? raw.slice(0, -1) : "";
|
|
714
|
+
if (`${name}
|
|
715
|
+
` !== raw || !RELEASE_NAME_RE.test(name)) {
|
|
716
|
+
throw new Error("cannot stage hook runtime: selected release is malformed");
|
|
717
|
+
}
|
|
718
|
+
const dir = join5(paths.releasesDir, name);
|
|
719
|
+
const manifest = readReleaseManifest(dir, name);
|
|
720
|
+
if (!manifest) {
|
|
721
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
722
|
+
}
|
|
723
|
+
return { name, dir, manifest };
|
|
724
|
+
}
|
|
725
|
+
function selectedHookRuntimeKeyringLoader(options = {}) {
|
|
726
|
+
try {
|
|
727
|
+
const selected = readSelectedRelease(hookRuntimePaths(options));
|
|
728
|
+
if (!selected?.manifest.native) return void 0;
|
|
729
|
+
const loader = join5(selected.dir, "native", "keyring.cjs");
|
|
730
|
+
return existsSync4(loader) ? loader : void 0;
|
|
731
|
+
} catch {
|
|
732
|
+
return void 0;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
736
|
+
set -eu
|
|
737
|
+
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
738
|
+
IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
|
|
739
|
+
case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
|
|
740
|
+
prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
|
|
741
|
+
case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
|
|
742
|
+
[ "\${#prim_release_id}" -eq 64 ] || exit 69
|
|
743
|
+
prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
|
|
744
|
+
case "\${1-}" in
|
|
745
|
+
${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
|
|
746
|
+
*) exit 64 ;;
|
|
747
|
+
esac
|
|
748
|
+
shift
|
|
749
|
+
IFS= read -r prim_node < "$prim_release/node" || exit 69
|
|
750
|
+
case "$prim_node" in /*) ;; *) exit 69 ;; esac
|
|
751
|
+
[ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
|
|
752
|
+
exec "$prim_node" "$prim_entry" "$@"
|
|
753
|
+
`;
|
|
754
|
+
|
|
755
|
+
// src/lib/machine-broker.ts
|
|
756
|
+
import { spawn } from "child_process";
|
|
757
|
+
import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
758
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
|
|
759
|
+
import { createServer } from "http";
|
|
760
|
+
import { basename, join as join6 } from "path";
|
|
761
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
762
|
+
|
|
404
763
|
// src/lib/loopback-fetch.ts
|
|
405
764
|
import { request } from "http";
|
|
406
765
|
import { Readable } from "stream";
|
|
@@ -408,7 +767,7 @@ function loopbackFetch(url, init = {}) {
|
|
|
408
767
|
const target = new URL(url);
|
|
409
768
|
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
410
769
|
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
411
|
-
return new Promise((
|
|
770
|
+
return new Promise((resolve4, reject) => {
|
|
412
771
|
const outgoing = request(
|
|
413
772
|
target,
|
|
414
773
|
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
@@ -419,7 +778,7 @@ function loopbackFetch(url, init = {}) {
|
|
|
419
778
|
if (typeof value === "string") headers.set(name, value);
|
|
420
779
|
const status = incoming.statusCode ?? 502;
|
|
421
780
|
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
422
|
-
|
|
781
|
+
resolve4(new Response(body, { status, headers }));
|
|
423
782
|
} catch (error) {
|
|
424
783
|
incoming.destroy();
|
|
425
784
|
reject(error);
|
|
@@ -567,10 +926,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
567
926
|
"access_token",
|
|
568
927
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
569
928
|
);
|
|
570
|
-
const
|
|
929
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
571
930
|
return {
|
|
572
931
|
accessToken,
|
|
573
|
-
refreshToken:
|
|
932
|
+
refreshToken: refreshToken3,
|
|
574
933
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
575
934
|
};
|
|
576
935
|
}
|
|
@@ -821,34 +1180,6 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
|
|
|
821
1180
|
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
822
1181
|
}
|
|
823
1182
|
|
|
824
|
-
// src/lib/paths.ts
|
|
825
|
-
import { homedir } from "os";
|
|
826
|
-
import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
|
|
827
|
-
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
828
|
-
function absolutePath(value, variable) {
|
|
829
|
-
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
830
|
-
throw new Error(`${variable} contains unsafe characters`);
|
|
831
|
-
}
|
|
832
|
-
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
833
|
-
const normalized = normalize(value);
|
|
834
|
-
return normalized === value ? value : void 0;
|
|
835
|
-
}
|
|
836
|
-
function resolvePrimConfigDirectory(options = {}) {
|
|
837
|
-
const env = options.env ?? process.env;
|
|
838
|
-
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
839
|
-
if (explicit) return { path: explicit, source: "explicit" };
|
|
840
|
-
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
841
|
-
if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
|
|
842
|
-
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
843
|
-
if (!home) {
|
|
844
|
-
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
845
|
-
}
|
|
846
|
-
return { path: join3(home, ".config", "prim"), source: "default" };
|
|
847
|
-
}
|
|
848
|
-
function primConfigDirectory(options = {}) {
|
|
849
|
-
return resolvePrimConfigDirectory(options).path;
|
|
850
|
-
}
|
|
851
|
-
|
|
852
1183
|
// src/lib/machine-broker.ts
|
|
853
1184
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
854
1185
|
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
@@ -858,14 +1189,14 @@ var FORWARD_REQUEST_PROOF = "forward-request";
|
|
|
858
1189
|
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
859
1190
|
var IDLE_MS = 5 * 6e4;
|
|
860
1191
|
function descriptorPath(directory, generation) {
|
|
861
|
-
return
|
|
1192
|
+
return join6(directory, `machine_broker_${generation}.json`);
|
|
862
1193
|
}
|
|
863
1194
|
function readDescriptor(path) {
|
|
864
1195
|
try {
|
|
865
|
-
const stat =
|
|
1196
|
+
const stat = lstatSync2(path);
|
|
866
1197
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
867
1198
|
return void 0;
|
|
868
|
-
const data = JSON.parse(
|
|
1199
|
+
const data = JSON.parse(readFileSync4(path, "utf8"));
|
|
869
1200
|
return Number.isInteger(data.port) && data.port > 0 && data.port <= 65535 && /^[a-f0-9]{64}$/u.test(data.nonce) && Number.isInteger(data.pid) ? data : void 0;
|
|
870
1201
|
} catch {
|
|
871
1202
|
return void 0;
|
|
@@ -878,7 +1209,7 @@ function matches(left, right) {
|
|
|
878
1209
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
879
1210
|
}
|
|
880
1211
|
function tokenHash(token) {
|
|
881
|
-
return token ?
|
|
1212
|
+
return token ? createHash2("sha256").update(token).digest("hex") : void 0;
|
|
882
1213
|
}
|
|
883
1214
|
async function brokerRequest(descriptor, environment, options) {
|
|
884
1215
|
const body = JSON.stringify({
|
|
@@ -955,7 +1286,7 @@ async function acquireBrokerCredential(options) {
|
|
|
955
1286
|
async function ensureBroker(options) {
|
|
956
1287
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
957
1288
|
return withFileLock(
|
|
958
|
-
|
|
1289
|
+
join6(options.directory, "machine-broker.lock"),
|
|
959
1290
|
async () => {
|
|
960
1291
|
const current = readDescriptor(path);
|
|
961
1292
|
if (current) {
|
|
@@ -968,14 +1299,14 @@ async function ensureBroker(options) {
|
|
|
968
1299
|
options.signal.throwIfAborted();
|
|
969
1300
|
}
|
|
970
1301
|
}
|
|
971
|
-
const bundled =
|
|
1302
|
+
const bundled = fileURLToPath3(import.meta.url);
|
|
972
1303
|
const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
973
1304
|
if (!entry)
|
|
974
1305
|
throw new MachineAuthError(
|
|
975
1306
|
"broker_unavailable",
|
|
976
1307
|
"Reinstall Prim to restore its machine credential broker."
|
|
977
1308
|
);
|
|
978
|
-
await new Promise((
|
|
1309
|
+
await new Promise((resolve4, reject) => {
|
|
979
1310
|
const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
|
|
980
1311
|
detached: true,
|
|
981
1312
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
@@ -990,7 +1321,7 @@ async function ensureBroker(options) {
|
|
|
990
1321
|
if (error) child.kill();
|
|
991
1322
|
if (child.connected) child.disconnect();
|
|
992
1323
|
child.unref();
|
|
993
|
-
error ? reject(error) :
|
|
1324
|
+
error ? reject(error) : resolve4();
|
|
994
1325
|
};
|
|
995
1326
|
const abort = () => finish(
|
|
996
1327
|
new MachineAuthError(
|
|
@@ -1106,23 +1437,23 @@ async function forwardBrokerRequest(options) {
|
|
|
1106
1437
|
}
|
|
1107
1438
|
|
|
1108
1439
|
// src/lib/machine-retry.ts
|
|
1109
|
-
import { createHash as
|
|
1110
|
-
import { lstatSync as
|
|
1111
|
-
import { join as
|
|
1440
|
+
import { createHash as createHash3 } from "crypto";
|
|
1441
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync5 } from "fs";
|
|
1442
|
+
import { join as join7 } from "path";
|
|
1112
1443
|
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
1113
1444
|
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
1114
1445
|
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
1115
1446
|
signal?.throwIfAborted();
|
|
1116
|
-
const key =
|
|
1117
|
-
const path =
|
|
1447
|
+
const key = createHash3("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
1448
|
+
const path = join7(directory, `machine_retry_${key}.json`);
|
|
1118
1449
|
let state = {
|
|
1119
1450
|
failures: 0,
|
|
1120
1451
|
retryAt: 0
|
|
1121
1452
|
};
|
|
1122
1453
|
try {
|
|
1123
|
-
const stat =
|
|
1454
|
+
const stat = lstatSync3(path);
|
|
1124
1455
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
1125
|
-
const data = JSON.parse(
|
|
1456
|
+
const data = JSON.parse(readFileSync5(path, "utf8"));
|
|
1126
1457
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
1127
1458
|
throw new Error("Invalid retry state");
|
|
1128
1459
|
state = data;
|
|
@@ -1146,7 +1477,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
1146
1477
|
);
|
|
1147
1478
|
try {
|
|
1148
1479
|
const result = await request3();
|
|
1149
|
-
|
|
1480
|
+
rmSync5(path, { force: true });
|
|
1150
1481
|
return result;
|
|
1151
1482
|
} catch (error) {
|
|
1152
1483
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -1173,32 +1504,1196 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
1173
1504
|
}
|
|
1174
1505
|
}
|
|
1175
1506
|
|
|
1507
|
+
// src/lib/session-identity.ts
|
|
1508
|
+
import { execFile } from "child_process";
|
|
1509
|
+
import { createHash as createHash5 } from "crypto";
|
|
1510
|
+
import { rmSync as rmSync6 } from "fs";
|
|
1511
|
+
import { join as join9 } from "path";
|
|
1512
|
+
import { promisify } from "util";
|
|
1513
|
+
|
|
1514
|
+
// src/lib/git.ts
|
|
1515
|
+
import { execFileSync } from "child_process";
|
|
1516
|
+
import { createHash as createHash4 } from "crypto";
|
|
1517
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
|
|
1518
|
+
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve2, sep } from "path";
|
|
1519
|
+
var GIT_TIMEOUT_MS = 1e3;
|
|
1520
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
1521
|
+
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
1522
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
1523
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
1524
|
+
function gitChildEnvironment(env = process.env) {
|
|
1525
|
+
return Object.fromEntries(
|
|
1526
|
+
Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
|
|
1527
|
+
);
|
|
1528
|
+
}
|
|
1529
|
+
function gitToplevel(cwd) {
|
|
1530
|
+
try {
|
|
1531
|
+
return execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1532
|
+
cwd,
|
|
1533
|
+
encoding: "utf-8",
|
|
1534
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1535
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1536
|
+
env: gitChildEnvironment()
|
|
1537
|
+
}).trim();
|
|
1538
|
+
} catch {
|
|
1539
|
+
return null;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
function gitValue(cwd, args) {
|
|
1543
|
+
try {
|
|
1544
|
+
const value = execFileSync("git", args, {
|
|
1545
|
+
cwd,
|
|
1546
|
+
encoding: "utf-8",
|
|
1547
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1548
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1549
|
+
env: gitChildEnvironment()
|
|
1550
|
+
}).trim();
|
|
1551
|
+
return value || void 0;
|
|
1552
|
+
} catch {
|
|
1553
|
+
return void 0;
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
function currentBranch(cwd) {
|
|
1557
|
+
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
1558
|
+
}
|
|
1559
|
+
function parseGithubRepositoryName(path) {
|
|
1560
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
1561
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
1562
|
+
return null;
|
|
1563
|
+
}
|
|
1564
|
+
return `${parts[0]}/${parts[1]}`;
|
|
1565
|
+
}
|
|
1566
|
+
function githubRepositoryFromRemote(remote) {
|
|
1567
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
1568
|
+
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
1569
|
+
remote
|
|
1570
|
+
);
|
|
1571
|
+
const path = match?.[1] ?? match?.[2];
|
|
1572
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
1573
|
+
}
|
|
1574
|
+
function checkoutSettingsText(repoRoot) {
|
|
1575
|
+
const path = join8(repoRoot, ".claude", "settings.json");
|
|
1576
|
+
try {
|
|
1577
|
+
if (!lstatSync4(join8(repoRoot, ".claude")).isDirectory()) return null;
|
|
1578
|
+
const stat = lstatSync4(path);
|
|
1579
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
1580
|
+
return readFileSync6(path, "utf8");
|
|
1581
|
+
} catch {
|
|
1582
|
+
return null;
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
function checkoutDeclaration(repoRoot, name) {
|
|
1586
|
+
const text = checkoutSettingsText(repoRoot);
|
|
1587
|
+
if (text === null) return null;
|
|
1588
|
+
let parsed;
|
|
1589
|
+
try {
|
|
1590
|
+
parsed = JSON.parse(text);
|
|
1591
|
+
} catch {
|
|
1592
|
+
return null;
|
|
1593
|
+
}
|
|
1594
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
1595
|
+
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
1596
|
+
return typeof value === "string" ? value : null;
|
|
1597
|
+
}
|
|
1598
|
+
function declaredGithubRepository(repoRoot) {
|
|
1599
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
1600
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
1601
|
+
}
|
|
1602
|
+
function githubRepositoryFullName(cwd) {
|
|
1603
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
1604
|
+
if (remote) {
|
|
1605
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
1606
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
1607
|
+
}
|
|
1608
|
+
const root = gitToplevel(cwd);
|
|
1609
|
+
return root ? declaredGithubRepository(root) : null;
|
|
1610
|
+
}
|
|
1611
|
+
function canonicalGitRoot(cwd) {
|
|
1612
|
+
try {
|
|
1613
|
+
const top = gitToplevel(cwd);
|
|
1614
|
+
return top ? realpathSync2.native(top) : null;
|
|
1615
|
+
} catch {
|
|
1616
|
+
return null;
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
function normalizeOriginRemote(remote) {
|
|
1620
|
+
const value = remote.trim();
|
|
1621
|
+
if (!value) return void 0;
|
|
1622
|
+
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
1623
|
+
if (scp?.host && scp.path) {
|
|
1624
|
+
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1625
|
+
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
1626
|
+
}
|
|
1627
|
+
try {
|
|
1628
|
+
const url = new URL(value);
|
|
1629
|
+
url.username = "";
|
|
1630
|
+
url.password = "";
|
|
1631
|
+
url.search = "";
|
|
1632
|
+
url.hash = "";
|
|
1633
|
+
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1634
|
+
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
1635
|
+
return void 0;
|
|
1636
|
+
} catch {
|
|
1637
|
+
return void 0;
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
function nearestExistingAncestor(path) {
|
|
1641
|
+
const suffix = [];
|
|
1642
|
+
let cursor = path;
|
|
1643
|
+
while (true) {
|
|
1644
|
+
try {
|
|
1645
|
+
lstatSync4(cursor);
|
|
1646
|
+
break;
|
|
1647
|
+
} catch (error) {
|
|
1648
|
+
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
1649
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
1650
|
+
const parent = dirname6(cursor);
|
|
1651
|
+
if (parent === cursor) return null;
|
|
1652
|
+
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
1653
|
+
cursor = parent;
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
try {
|
|
1657
|
+
return { real: realpathSync2.native(cursor), suffix };
|
|
1658
|
+
} catch {
|
|
1659
|
+
return null;
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
1663
|
+
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
1664
|
+
return { ok: false, reason: "invalid_path" };
|
|
1665
|
+
}
|
|
1666
|
+
const absolute = resolve2(baseDir, filePath);
|
|
1667
|
+
const resolved = nearestExistingAncestor(absolute);
|
|
1668
|
+
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
1669
|
+
const target = resolve2(resolved.real, ...resolved.suffix);
|
|
1670
|
+
const rel = relative(context.repoRoot, target);
|
|
1671
|
+
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
1672
|
+
if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
1673
|
+
return { ok: false, reason: "outside_repository" };
|
|
1674
|
+
}
|
|
1675
|
+
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
1676
|
+
}
|
|
1677
|
+
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
|
|
1678
|
+
if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
1679
|
+
return null;
|
|
1680
|
+
const absolute = resolve2(cwd, filePath);
|
|
1681
|
+
let target;
|
|
1682
|
+
try {
|
|
1683
|
+
const stat = lstatSync4(absolute);
|
|
1684
|
+
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
1685
|
+
target = realpathSync2.native(absolute);
|
|
1686
|
+
} catch (error) {
|
|
1687
|
+
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
1688
|
+
return null;
|
|
1689
|
+
}
|
|
1690
|
+
try {
|
|
1691
|
+
const parent = realpathSync2.native(dirname6(absolute));
|
|
1692
|
+
if (!lstatSync4(parent).isDirectory()) return null;
|
|
1693
|
+
target = resolve2(parent, basename2(absolute));
|
|
1694
|
+
} catch {
|
|
1695
|
+
return null;
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
const rel = relative(repositoryRoot, target);
|
|
1699
|
+
if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
1700
|
+
return null;
|
|
1701
|
+
}
|
|
1702
|
+
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
1703
|
+
}
|
|
1704
|
+
function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
1705
|
+
if (typeof contextOrCwd === "string") {
|
|
1706
|
+
return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
|
|
1707
|
+
}
|
|
1708
|
+
return canonicalRepositoryPathScoped(
|
|
1709
|
+
filePath,
|
|
1710
|
+
contextOrCwd,
|
|
1711
|
+
baseDirOrRoot ?? contextOrCwd.repoRoot
|
|
1712
|
+
);
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
// src/lib/terminal-safe.ts
|
|
1716
|
+
function replaceIsolatedSurrogates(value) {
|
|
1717
|
+
let out = "";
|
|
1718
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1719
|
+
const unit = value.charCodeAt(index);
|
|
1720
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
1721
|
+
const next = value.charCodeAt(index + 1);
|
|
1722
|
+
if (next >= 56320 && next <= 57343) {
|
|
1723
|
+
out += value[index] + value[index + 1];
|
|
1724
|
+
index += 1;
|
|
1725
|
+
} else {
|
|
1726
|
+
out += "\uFFFD";
|
|
1727
|
+
}
|
|
1728
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
1729
|
+
out += "\uFFFD";
|
|
1730
|
+
} else {
|
|
1731
|
+
out += value[index];
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
return out;
|
|
1735
|
+
}
|
|
1736
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
1737
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
1738
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
1739
|
+
point === 1564 || // Arabic letter mark
|
|
1740
|
+
point === 6158 || // Mongolian vowel separator
|
|
1741
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
1742
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
1743
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
1744
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
1745
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
1746
|
+
point >= 917504 && point <= 917631;
|
|
1747
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
1748
|
+
}
|
|
1749
|
+
function terminalSafeText(value) {
|
|
1750
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
1751
|
+
}
|
|
1752
|
+
function terminalSafeLine(value) {
|
|
1753
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
// src/lib/session-identity.ts
|
|
1757
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
1758
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
1759
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
1760
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
1761
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
1762
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
1763
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
1764
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
1765
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
1766
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
1767
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
1768
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
1769
|
+
token: "/api/cli/session-identity/token",
|
|
1770
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
1771
|
+
link: "/api/cli/session-identity/link"
|
|
1772
|
+
};
|
|
1773
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
1774
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
1775
|
+
var GIT_TIMEOUT_MS2 = 1e4;
|
|
1776
|
+
var POLL_BUDGET_MS = 15e3;
|
|
1777
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
1778
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
1779
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
1780
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
1781
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
1782
|
+
function sessionIdentityRequested(env = process.env) {
|
|
1783
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
1784
|
+
}
|
|
1785
|
+
function sessionIdentityMode(deps = {}) {
|
|
1786
|
+
const env = deps.env ?? process.env;
|
|
1787
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
1788
|
+
}
|
|
1789
|
+
function failure(code, cause, remedy) {
|
|
1790
|
+
return { status: "failed", code, cause, remedy };
|
|
1791
|
+
}
|
|
1792
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
1793
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
1794
|
+
var ENVIRONMENT_CREDENTIAL_REMEDY = 'ask the organization admin who set up the environment to check its credential, or to mint a replacement with `prim auth enroll --new-environment "<name>" --print-env`; then start a new cloud session';
|
|
1795
|
+
var SESSION_REVOKED = failure(
|
|
1796
|
+
"session_revoked",
|
|
1797
|
+
"Primitive no longer accepts this session's member token: an organization admin revoked the session or the member's GitHub link, the member left the organization, or the token was renewed elsewhere",
|
|
1798
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
1799
|
+
);
|
|
1800
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
1801
|
+
"challenge_expired",
|
|
1802
|
+
"this session's identity check expired before it was exchanged for a token (a verified check stays usable, including for linking a GitHub account, for 30 minutes)",
|
|
1803
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
1804
|
+
);
|
|
1805
|
+
var CHALLENGE_GONE = failure(
|
|
1806
|
+
"challenge_not_found",
|
|
1807
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
1808
|
+
NEW_SESSION_REMEDY
|
|
1809
|
+
);
|
|
1810
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
1811
|
+
function rejectionFailure(reason, repository) {
|
|
1812
|
+
switch (reason) {
|
|
1813
|
+
case "identity_mismatch":
|
|
1814
|
+
return failure(
|
|
1815
|
+
"identity_mismatch",
|
|
1816
|
+
"the session branch was created by a GitHub account linked to a different Primitive member than the one signed in to Claude, so Primitive attributes this session to no one",
|
|
1817
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
1818
|
+
);
|
|
1819
|
+
case "push_after_expiry":
|
|
1820
|
+
return failure(
|
|
1821
|
+
"push_after_expiry",
|
|
1822
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
1823
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
1824
|
+
);
|
|
1825
|
+
case "repository_mismatch":
|
|
1826
|
+
return failure(
|
|
1827
|
+
"repository_mismatch",
|
|
1828
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
1829
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
1830
|
+
);
|
|
1831
|
+
case "conflicting_push":
|
|
1832
|
+
return failure(
|
|
1833
|
+
"conflicting_push",
|
|
1834
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
1835
|
+
NEW_SESSION_REMEDY
|
|
1836
|
+
);
|
|
1837
|
+
case "unsupported_sender":
|
|
1838
|
+
return failure(
|
|
1839
|
+
"unsupported_sender",
|
|
1840
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
1841
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
1842
|
+
);
|
|
1843
|
+
default:
|
|
1844
|
+
return failure(
|
|
1845
|
+
"challenge_rejected",
|
|
1846
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
1847
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
1848
|
+
);
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
function sessionIdentityMessage(outcome) {
|
|
1852
|
+
if (outcome.status === "link_required")
|
|
1853
|
+
return `GitHub account @${outcome.githubLogin} started this Claude Code cloud session but is not linked to a Primitive account yet. To link it once, run \`prim auth link\` and sign in at the URL it prints with the code it shows; later sessions then identify you automatically.`;
|
|
1854
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
1855
|
+
}
|
|
1856
|
+
function hash(value) {
|
|
1857
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
1858
|
+
}
|
|
1859
|
+
function sessionContext(deps) {
|
|
1860
|
+
const env = deps.env ?? process.env;
|
|
1861
|
+
const environment = environmentCredentials(deps);
|
|
1862
|
+
if (!environment)
|
|
1863
|
+
return failure(
|
|
1864
|
+
"environment_credential_missing",
|
|
1865
|
+
"the cloud environment has no environment credential",
|
|
1866
|
+
'ask an organization admin to create one with `prim auth enroll --new-environment "<name>" --print-env` and add it to the environment, then start a new cloud session'
|
|
1867
|
+
);
|
|
1868
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
1869
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
1870
|
+
return failure(
|
|
1871
|
+
"session_id_missing",
|
|
1872
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
1873
|
+
NEW_SESSION_REMEDY
|
|
1874
|
+
);
|
|
1875
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
1876
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
1877
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
1878
|
+
return {
|
|
1879
|
+
directory,
|
|
1880
|
+
apiUrl,
|
|
1881
|
+
clientId: environment.clientId,
|
|
1882
|
+
generation: environment.generation,
|
|
1883
|
+
sessionId,
|
|
1884
|
+
tokenPath: join9(directory, `session_identity_${key}.json`),
|
|
1885
|
+
statePath: join9(directory, `session_identity_${key}.state.json`),
|
|
1886
|
+
lockPath: join9(directory, "session-identity.lock")
|
|
1887
|
+
};
|
|
1888
|
+
}
|
|
1889
|
+
function readRecord(path) {
|
|
1890
|
+
try {
|
|
1891
|
+
const value = readMachineMetadata(path);
|
|
1892
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
1893
|
+
} catch {
|
|
1894
|
+
return void 0;
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
function finiteNumber(value) {
|
|
1898
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1899
|
+
}
|
|
1900
|
+
function readToken(context) {
|
|
1901
|
+
const data = readRecord(context.tokenPath);
|
|
1902
|
+
if (!data || data.version !== 1 || data.apiUrl !== context.apiUrl || data.clientId !== context.clientId || data.generation !== context.generation || data.sessionId !== context.sessionId || !machineString(data.accessToken, 8192) || !data.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !finiteNumber(data.expiresAt) || !finiteNumber(data.refreshAfter) || !machineString(data.userId, 256) || !machineString(data.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.issuer, 2048) || !machineString(data.audience, 256))
|
|
1903
|
+
return void 0;
|
|
1904
|
+
const identity = data.identity;
|
|
1905
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
1906
|
+
return void 0;
|
|
1907
|
+
return data;
|
|
1908
|
+
}
|
|
1909
|
+
function readState(context) {
|
|
1910
|
+
const data = readRecord(context.statePath);
|
|
1911
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
1912
|
+
return void 0;
|
|
1913
|
+
return data;
|
|
1914
|
+
}
|
|
1915
|
+
function writeToken(context, record) {
|
|
1916
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1917
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
1918
|
+
rmSync6(context.statePath, { force: true });
|
|
1919
|
+
}
|
|
1920
|
+
function writeState(context, state) {
|
|
1921
|
+
try {
|
|
1922
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1923
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
1924
|
+
} catch {
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
function tokenValid(record, now = Date.now()) {
|
|
1928
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
1929
|
+
}
|
|
1930
|
+
function tokenFresh(record, now = Date.now()) {
|
|
1931
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
1932
|
+
}
|
|
1933
|
+
function toCredential(record) {
|
|
1934
|
+
return {
|
|
1935
|
+
issuer: record.issuer,
|
|
1936
|
+
audience: record.audience,
|
|
1937
|
+
...record.identity,
|
|
1938
|
+
accessToken: record.accessToken,
|
|
1939
|
+
expiresAt: record.expiresAt,
|
|
1940
|
+
apiUrl: record.apiUrl,
|
|
1941
|
+
generation: record.generation,
|
|
1942
|
+
storage: "environment",
|
|
1943
|
+
session: {
|
|
1944
|
+
userId: record.userId,
|
|
1945
|
+
displayName: record.displayName,
|
|
1946
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1947
|
+
refreshAfter: record.refreshAfter
|
|
1948
|
+
}
|
|
1949
|
+
};
|
|
1950
|
+
}
|
|
1951
|
+
function identified(record, reused) {
|
|
1952
|
+
return {
|
|
1953
|
+
status: "ok",
|
|
1954
|
+
credential: toCredential(record),
|
|
1955
|
+
displayName: record.displayName,
|
|
1956
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1957
|
+
reused
|
|
1958
|
+
};
|
|
1959
|
+
}
|
|
1960
|
+
function cachedSessionCredential(deps = {}) {
|
|
1961
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
1962
|
+
let context;
|
|
1963
|
+
try {
|
|
1964
|
+
context = sessionContext(deps);
|
|
1965
|
+
} catch {
|
|
1966
|
+
return void 0;
|
|
1967
|
+
}
|
|
1968
|
+
if ("status" in context) return void 0;
|
|
1969
|
+
const record = readToken(context);
|
|
1970
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
1971
|
+
}
|
|
1972
|
+
function outcomeFromState(state) {
|
|
1973
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
1974
|
+
return {
|
|
1975
|
+
status: "link_required",
|
|
1976
|
+
githubLogin: state.githubLogin,
|
|
1977
|
+
challengeId: state.challengeId,
|
|
1978
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
1979
|
+
};
|
|
1980
|
+
return failure(
|
|
1981
|
+
state.code,
|
|
1982
|
+
state.cause ?? "the last identity check failed",
|
|
1983
|
+
state.remedy ?? RETRY_REMEDY
|
|
1984
|
+
);
|
|
1985
|
+
}
|
|
1986
|
+
function parseInstant(value) {
|
|
1987
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
1988
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
1989
|
+
const parsed = Date.parse(value);
|
|
1990
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1991
|
+
}
|
|
1992
|
+
return void 0;
|
|
1993
|
+
}
|
|
1994
|
+
async function sendJson(url, init, fetchImpl) {
|
|
1995
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
1996
|
+
let value;
|
|
1997
|
+
try {
|
|
1998
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
1999
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
2000
|
+
} catch {
|
|
2001
|
+
value = void 0;
|
|
2002
|
+
}
|
|
2003
|
+
return { status: response.status, value };
|
|
2004
|
+
}
|
|
2005
|
+
function environmentOnly(deps) {
|
|
2006
|
+
return { ...deps, environmentOnly: true };
|
|
2007
|
+
}
|
|
2008
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
2009
|
+
const send = async (credential2) => {
|
|
2010
|
+
const headers = { "Content-Type": "application/json" };
|
|
2011
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
2012
|
+
if (credential2.tokenInjection) {
|
|
2013
|
+
const response = await forwardMachineRequest(
|
|
2014
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
2015
|
+
signal,
|
|
2016
|
+
environmentOnly(deps)
|
|
2017
|
+
);
|
|
2018
|
+
const parsed = await response.json().catch(() => void 0);
|
|
2019
|
+
return {
|
|
2020
|
+
status: response.status,
|
|
2021
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
2022
|
+
};
|
|
2023
|
+
}
|
|
2024
|
+
return sendJson(
|
|
2025
|
+
`${credential2.apiUrl}${path}`,
|
|
2026
|
+
{
|
|
2027
|
+
method,
|
|
2028
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
2029
|
+
...text === void 0 ? {} : { body: text },
|
|
2030
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
|
|
2031
|
+
},
|
|
2032
|
+
deps.fetch ?? fetch
|
|
2033
|
+
);
|
|
2034
|
+
};
|
|
2035
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
2036
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
2037
|
+
let answer = await send(credential);
|
|
2038
|
+
if (answer.status === 401) {
|
|
2039
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
2040
|
+
if (!credential)
|
|
2041
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
2042
|
+
answer = await send(credential);
|
|
2043
|
+
}
|
|
2044
|
+
return answer;
|
|
2045
|
+
}
|
|
2046
|
+
function environmentFailure(error, apiUrl) {
|
|
2047
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
2048
|
+
return failure(
|
|
2049
|
+
"environment_credential_rejected",
|
|
2050
|
+
"Primitive rejected the cloud environment's credential",
|
|
2051
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
2052
|
+
);
|
|
2053
|
+
const host = (() => {
|
|
2054
|
+
try {
|
|
2055
|
+
return new URL(apiUrl).hostname;
|
|
2056
|
+
} catch {
|
|
2057
|
+
return "Primitive";
|
|
2058
|
+
}
|
|
2059
|
+
})();
|
|
2060
|
+
return failure(
|
|
2061
|
+
"identity_unavailable",
|
|
2062
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
2063
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
2064
|
+
);
|
|
2065
|
+
}
|
|
2066
|
+
function answerError(answer) {
|
|
2067
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
2068
|
+
}
|
|
2069
|
+
async function git(root, args, signal) {
|
|
2070
|
+
try {
|
|
2071
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
2072
|
+
cwd: root,
|
|
2073
|
+
encoding: "utf8",
|
|
2074
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
2075
|
+
signal,
|
|
2076
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
2077
|
+
maxBuffer: 1024 * 1024
|
|
2078
|
+
});
|
|
2079
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
2080
|
+
} catch (error) {
|
|
2081
|
+
const failed = error;
|
|
2082
|
+
return {
|
|
2083
|
+
ok: false,
|
|
2084
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
2085
|
+
stdout: failed.stdout ?? "",
|
|
2086
|
+
stderr: failed.stderr ?? "",
|
|
2087
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
2088
|
+
};
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
function gitDetail(stderr) {
|
|
2092
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
2093
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
2094
|
+
}
|
|
2095
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
2096
|
+
await new Promise((resolve4, reject) => {
|
|
2097
|
+
const timer = setTimeout(resolve4, milliseconds);
|
|
2098
|
+
signal?.addEventListener(
|
|
2099
|
+
"abort",
|
|
2100
|
+
() => {
|
|
2101
|
+
clearTimeout(timer);
|
|
2102
|
+
reject(signal.reason);
|
|
2103
|
+
},
|
|
2104
|
+
{ once: true }
|
|
2105
|
+
);
|
|
2106
|
+
});
|
|
2107
|
+
}
|
|
2108
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
2109
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
2110
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
2111
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
2112
|
+
let unreachable;
|
|
2113
|
+
for (; ; ) {
|
|
2114
|
+
const remaining = deadline - Date.now();
|
|
2115
|
+
if (remaining <= 0) break;
|
|
2116
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
2117
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
2118
|
+
let answer;
|
|
2119
|
+
try {
|
|
2120
|
+
answer = await environmentRequest(
|
|
2121
|
+
"GET",
|
|
2122
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
2123
|
+
void 0,
|
|
2124
|
+
deps,
|
|
2125
|
+
signal
|
|
2126
|
+
);
|
|
2127
|
+
} catch (error) {
|
|
2128
|
+
signal?.throwIfAborted();
|
|
2129
|
+
unreachable = error;
|
|
2130
|
+
continue;
|
|
2131
|
+
}
|
|
2132
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2133
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2134
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
2135
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
2136
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
2137
|
+
continue;
|
|
2138
|
+
}
|
|
2139
|
+
unreachable = void 0;
|
|
2140
|
+
const status = answer.value;
|
|
2141
|
+
if (status?.status === "verified")
|
|
2142
|
+
return {
|
|
2143
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
2144
|
+
};
|
|
2145
|
+
if (status?.status === "expired")
|
|
2146
|
+
return failure(
|
|
2147
|
+
"challenge_expired",
|
|
2148
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
2149
|
+
NEW_SESSION_REMEDY
|
|
2150
|
+
);
|
|
2151
|
+
if (status?.status === "rejected")
|
|
2152
|
+
return rejectionFailure(status.reason, repository);
|
|
2153
|
+
}
|
|
2154
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
2155
|
+
return failure(
|
|
2156
|
+
"webhook_timeout",
|
|
2157
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
2158
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2159
|
+
);
|
|
2160
|
+
}
|
|
2161
|
+
function parseTokenAnswer(value) {
|
|
2162
|
+
if (!value) return void 0;
|
|
2163
|
+
const user = value.user;
|
|
2164
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
2165
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
2166
|
+
if (!machineString(value.accessToken, 8192) || !value.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !expiresAt || !refreshAfter || !user || !machineString(user.id, 256) || !machineString(user.displayName, 256) || !machineString(value.organizationId, 256))
|
|
2167
|
+
return void 0;
|
|
2168
|
+
return {
|
|
2169
|
+
accessToken: value.accessToken,
|
|
2170
|
+
expiresAt,
|
|
2171
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
2172
|
+
userId: user.id,
|
|
2173
|
+
displayName: user.displayName,
|
|
2174
|
+
organizationId: value.organizationId
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
2178
|
+
"server_contract",
|
|
2179
|
+
"Primitive's answer did not identify the linked member",
|
|
2180
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
2181
|
+
);
|
|
2182
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
2183
|
+
let identity;
|
|
2184
|
+
let environment;
|
|
2185
|
+
try {
|
|
2186
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
2187
|
+
identity = await verifyMachineIdentity(
|
|
2188
|
+
context.apiUrl,
|
|
2189
|
+
answer.accessToken,
|
|
2190
|
+
context.clientId,
|
|
2191
|
+
signal,
|
|
2192
|
+
deps.fetch
|
|
2193
|
+
);
|
|
2194
|
+
} catch (error) {
|
|
2195
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
2196
|
+
return SERVER_CONTRACT_FAILURE;
|
|
2197
|
+
return environmentFailure(error, context.apiUrl);
|
|
2198
|
+
}
|
|
2199
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
2200
|
+
return SERVER_CONTRACT_FAILURE;
|
|
2201
|
+
return {
|
|
2202
|
+
version: 1,
|
|
2203
|
+
apiUrl: context.apiUrl,
|
|
2204
|
+
clientId: context.clientId,
|
|
2205
|
+
generation: context.generation,
|
|
2206
|
+
sessionId: context.sessionId,
|
|
2207
|
+
issuer: environment.issuer,
|
|
2208
|
+
audience: environment.audience,
|
|
2209
|
+
accessToken: answer.accessToken,
|
|
2210
|
+
expiresAt: answer.expiresAt,
|
|
2211
|
+
refreshAfter: answer.refreshAfter,
|
|
2212
|
+
userId: answer.userId,
|
|
2213
|
+
displayName: answer.displayName,
|
|
2214
|
+
organizationId: answer.organizationId,
|
|
2215
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
2216
|
+
identity,
|
|
2217
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
2218
|
+
};
|
|
2219
|
+
}
|
|
2220
|
+
async function refreshToken(context, record, deps, signal) {
|
|
2221
|
+
let answer;
|
|
2222
|
+
try {
|
|
2223
|
+
answer = await environmentRequest(
|
|
2224
|
+
"POST",
|
|
2225
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
2226
|
+
{ accessToken: record.accessToken },
|
|
2227
|
+
deps,
|
|
2228
|
+
signal
|
|
2229
|
+
);
|
|
2230
|
+
} catch (error) {
|
|
2231
|
+
signal?.throwIfAborted();
|
|
2232
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
2233
|
+
}
|
|
2234
|
+
const code = answerError(answer);
|
|
2235
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
2236
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
2237
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2238
|
+
return {
|
|
2239
|
+
status: "refused",
|
|
2240
|
+
failure: environmentFailure(
|
|
2241
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
2242
|
+
context.apiUrl
|
|
2243
|
+
)
|
|
2244
|
+
};
|
|
2245
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2246
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
2247
|
+
return { status: "unavailable" };
|
|
2248
|
+
return {
|
|
2249
|
+
status: "ok",
|
|
2250
|
+
record: {
|
|
2251
|
+
...record,
|
|
2252
|
+
accessToken: token.accessToken,
|
|
2253
|
+
expiresAt: token.expiresAt,
|
|
2254
|
+
refreshAfter: token.refreshAfter,
|
|
2255
|
+
displayName: token.displayName
|
|
2256
|
+
}
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2259
|
+
function exchangeRefusal(answer, repository) {
|
|
2260
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2261
|
+
if (answer.status !== 409) return void 0;
|
|
2262
|
+
switch (answerError(answer)) {
|
|
2263
|
+
case "identity_mismatch":
|
|
2264
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
2265
|
+
case "challenge_rejected":
|
|
2266
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
2267
|
+
case "challenge_expired":
|
|
2268
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
2269
|
+
case "challenge_already_exchanged":
|
|
2270
|
+
return failure(
|
|
2271
|
+
"challenge_already_exchanged",
|
|
2272
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
2273
|
+
NEW_SESSION_REMEDY
|
|
2274
|
+
);
|
|
2275
|
+
case "challenge_pending":
|
|
2276
|
+
return failure(
|
|
2277
|
+
"webhook_timeout",
|
|
2278
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
2279
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2280
|
+
);
|
|
2281
|
+
default:
|
|
2282
|
+
return void 0;
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
2286
|
+
let answer;
|
|
2287
|
+
try {
|
|
2288
|
+
answer = await environmentRequest(
|
|
2289
|
+
"POST",
|
|
2290
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
2291
|
+
{ challengeId: challenge.challengeId },
|
|
2292
|
+
deps,
|
|
2293
|
+
signal
|
|
2294
|
+
);
|
|
2295
|
+
} catch (error) {
|
|
2296
|
+
signal?.throwIfAborted();
|
|
2297
|
+
return environmentFailure(error, context.apiUrl);
|
|
2298
|
+
}
|
|
2299
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
2300
|
+
const login = answer.value?.githubLogin;
|
|
2301
|
+
return {
|
|
2302
|
+
status: "link_required",
|
|
2303
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
2304
|
+
challengeId: challenge.challengeId,
|
|
2305
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
const refused = exchangeRefusal(
|
|
2309
|
+
answer,
|
|
2310
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
2311
|
+
);
|
|
2312
|
+
if (refused) return refused;
|
|
2313
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2314
|
+
if (!token) {
|
|
2315
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2316
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2317
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2318
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2319
|
+
context.apiUrl
|
|
2320
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2321
|
+
}
|
|
2322
|
+
return recordFor(
|
|
2323
|
+
context,
|
|
2324
|
+
token,
|
|
2325
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
2326
|
+
deps,
|
|
2327
|
+
signal
|
|
2328
|
+
);
|
|
2329
|
+
}
|
|
2330
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
2331
|
+
const env = deps.env ?? process.env;
|
|
2332
|
+
const repository = githubRepositoryFullName(root);
|
|
2333
|
+
if (!repository)
|
|
2334
|
+
return failure(
|
|
2335
|
+
"repository_unidentified",
|
|
2336
|
+
"this checkout does not name its GitHub repository",
|
|
2337
|
+
"run it in the repository the session cloned; for a checkout with no GitHub origin, commit its repository declaration with `prim claude install --scope project` from a clone whose origin is on GitHub"
|
|
2338
|
+
);
|
|
2339
|
+
const branch = currentBranch(root);
|
|
2340
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
2341
|
+
return failure(
|
|
2342
|
+
"not_session_branch",
|
|
2343
|
+
`this checkout is on ${branch ? `branch ${terminalSafeLine(branch).slice(0, 120)}` : "a detached HEAD"}, not the session's own claude/\u2026 branch, so prim cannot prove who started the session and pushed nothing`,
|
|
2344
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
2345
|
+
);
|
|
2346
|
+
attempt.branch = branch;
|
|
2347
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
2348
|
+
if (!baseSha) {
|
|
2349
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
2350
|
+
baseSha = head.stdout.trim();
|
|
2351
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
2352
|
+
return failure(
|
|
2353
|
+
"no_commit",
|
|
2354
|
+
"this checkout has no commit to create the session branch at",
|
|
2355
|
+
NEW_SESSION_REMEDY
|
|
2356
|
+
);
|
|
2357
|
+
}
|
|
2358
|
+
const published = await git(
|
|
2359
|
+
root,
|
|
2360
|
+
[
|
|
2361
|
+
"for-each-ref",
|
|
2362
|
+
"--count=1",
|
|
2363
|
+
"--format=%(refname)",
|
|
2364
|
+
"--contains",
|
|
2365
|
+
baseSha,
|
|
2366
|
+
"refs/remotes/origin/"
|
|
2367
|
+
],
|
|
2368
|
+
signal
|
|
2369
|
+
);
|
|
2370
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
2371
|
+
return failure(
|
|
2372
|
+
"unpublished_commits",
|
|
2373
|
+
`this checkout's commit ${baseSha.slice(0, 12)} is not on GitHub yet, and creating the session branch at it would publish it, so prim pushed nothing`,
|
|
2374
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
2375
|
+
);
|
|
2376
|
+
attempt.baseSha = baseSha;
|
|
2377
|
+
const remote = await git(
|
|
2378
|
+
root,
|
|
2379
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
2380
|
+
signal
|
|
2381
|
+
);
|
|
2382
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
2383
|
+
if (remote.ok && recorded) {
|
|
2384
|
+
Object.assign(attempt, recorded);
|
|
2385
|
+
return { ...recorded, repository };
|
|
2386
|
+
}
|
|
2387
|
+
if (remote.ok)
|
|
2388
|
+
return failure(
|
|
2389
|
+
"branch_exists",
|
|
2390
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
2391
|
+
NEW_SESSION_REMEDY
|
|
2392
|
+
);
|
|
2393
|
+
if (remote.code !== 2)
|
|
2394
|
+
return failure(
|
|
2395
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
2396
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
2397
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
2398
|
+
);
|
|
2399
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
2400
|
+
Object.assign(attempt, recorded);
|
|
2401
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
2402
|
+
}
|
|
2403
|
+
let answer;
|
|
2404
|
+
try {
|
|
2405
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
2406
|
+
answer = await environmentRequest(
|
|
2407
|
+
"POST",
|
|
2408
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
2409
|
+
{
|
|
2410
|
+
repositoryFullName: repository,
|
|
2411
|
+
claudeSessionId: context.sessionId,
|
|
2412
|
+
branch,
|
|
2413
|
+
baseSha,
|
|
2414
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
2415
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
2416
|
+
},
|
|
2417
|
+
deps,
|
|
2418
|
+
signal
|
|
2419
|
+
);
|
|
2420
|
+
} catch (error) {
|
|
2421
|
+
signal?.throwIfAborted();
|
|
2422
|
+
return environmentFailure(error, context.apiUrl);
|
|
2423
|
+
}
|
|
2424
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
2425
|
+
return failure(
|
|
2426
|
+
"repository_not_connected",
|
|
2427
|
+
`${repository} is not connected to Primitive`,
|
|
2428
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
2429
|
+
);
|
|
2430
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2431
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2432
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
2433
|
+
return failure(
|
|
2434
|
+
"challenge_open",
|
|
2435
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
2436
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
2437
|
+
);
|
|
2438
|
+
if (answer.status === 429)
|
|
2439
|
+
return failure(
|
|
2440
|
+
"too_many_challenges",
|
|
2441
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
2442
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
2443
|
+
);
|
|
2444
|
+
const challengeId = answer.value?.challengeId;
|
|
2445
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
2446
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
2447
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2448
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2449
|
+
context.apiUrl
|
|
2450
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2451
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
2452
|
+
attempt.challengeId = challengeId;
|
|
2453
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
2454
|
+
return pushSessionBranch(
|
|
2455
|
+
root,
|
|
2456
|
+
repository,
|
|
2457
|
+
branch,
|
|
2458
|
+
baseSha,
|
|
2459
|
+
{ challengeId, challengeExpiresAt },
|
|
2460
|
+
signal
|
|
2461
|
+
);
|
|
2462
|
+
}
|
|
2463
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
2464
|
+
const push = await git(
|
|
2465
|
+
root,
|
|
2466
|
+
[
|
|
2467
|
+
"-c",
|
|
2468
|
+
"core.hooksPath=/dev/null",
|
|
2469
|
+
"-c",
|
|
2470
|
+
"push.followTags=false",
|
|
2471
|
+
"-c",
|
|
2472
|
+
"push.recurseSubmodules=no",
|
|
2473
|
+
"-c",
|
|
2474
|
+
"push.gpgSign=false",
|
|
2475
|
+
"-c",
|
|
2476
|
+
"push.pushOption=",
|
|
2477
|
+
"push",
|
|
2478
|
+
"--no-verify",
|
|
2479
|
+
"--no-follow-tags",
|
|
2480
|
+
"--no-recurse-submodules",
|
|
2481
|
+
"--no-signed",
|
|
2482
|
+
"--quiet",
|
|
2483
|
+
"origin",
|
|
2484
|
+
`${baseSha}:refs/heads/${branch}`
|
|
2485
|
+
],
|
|
2486
|
+
signal
|
|
2487
|
+
);
|
|
2488
|
+
if (!push.ok)
|
|
2489
|
+
return push.timedOut ? failure(
|
|
2490
|
+
"push_timeout",
|
|
2491
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
|
|
2492
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
2493
|
+
) : failure(
|
|
2494
|
+
"push_refused",
|
|
2495
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
2496
|
+
`check that the GitHub account that started this session can push to ${repository} and that the cloud environment lets the session push, then ${NEW_SESSION_REMEDY}`
|
|
2497
|
+
);
|
|
2498
|
+
return { ...challenge, repository };
|
|
2499
|
+
}
|
|
2500
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
2501
|
+
let context;
|
|
2502
|
+
try {
|
|
2503
|
+
context = sessionContext(deps);
|
|
2504
|
+
} catch (error) {
|
|
2505
|
+
return failure(
|
|
2506
|
+
"environment_credential_invalid",
|
|
2507
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
2508
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
2509
|
+
);
|
|
2510
|
+
}
|
|
2511
|
+
if ("status" in context) return context;
|
|
2512
|
+
const ctx = context;
|
|
2513
|
+
const startedAt = Date.now();
|
|
2514
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
2515
|
+
return withFileLock(
|
|
2516
|
+
ctx.lockPath,
|
|
2517
|
+
async () => {
|
|
2518
|
+
const record = readToken(ctx);
|
|
2519
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
2520
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
2521
|
+
if (record) {
|
|
2522
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
2523
|
+
if (refreshed.status === "ok") {
|
|
2524
|
+
writeToken(ctx, refreshed.record);
|
|
2525
|
+
return identified(refreshed.record, true);
|
|
2526
|
+
}
|
|
2527
|
+
if (refreshed.status === "refused") {
|
|
2528
|
+
rmSync6(ctx.tokenPath, { force: true });
|
|
2529
|
+
writeState(ctx, {
|
|
2530
|
+
sessionId: ctx.sessionId,
|
|
2531
|
+
status: "failed",
|
|
2532
|
+
code: refreshed.failure.code,
|
|
2533
|
+
cause: refreshed.failure.cause,
|
|
2534
|
+
remedy: refreshed.failure.remedy,
|
|
2535
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
2536
|
+
at: Date.now()
|
|
2537
|
+
});
|
|
2538
|
+
return refreshed.failure;
|
|
2539
|
+
}
|
|
2540
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
2541
|
+
}
|
|
2542
|
+
const state = readState(ctx);
|
|
2543
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
2544
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
2545
|
+
if (!options.explicit) {
|
|
2546
|
+
if (!root || !(record || state))
|
|
2547
|
+
return failure(
|
|
2548
|
+
"not_identified",
|
|
2549
|
+
"this session has not identified who started it yet",
|
|
2550
|
+
RETRY_REMEDY
|
|
2551
|
+
);
|
|
2552
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
2553
|
+
} else if (state && state.at >= startedAt) {
|
|
2554
|
+
return outcomeFromState(state);
|
|
2555
|
+
}
|
|
2556
|
+
if (!root)
|
|
2557
|
+
return failure(
|
|
2558
|
+
"repository_missing",
|
|
2559
|
+
"this is not a git repository",
|
|
2560
|
+
"run it in the repository the session cloned"
|
|
2561
|
+
);
|
|
2562
|
+
const attempt = { root };
|
|
2563
|
+
const remember = (outcome) => {
|
|
2564
|
+
writeState(ctx, {
|
|
2565
|
+
sessionId: ctx.sessionId,
|
|
2566
|
+
status: outcome.status,
|
|
2567
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
2568
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
2569
|
+
githubLogin: outcome.githubLogin
|
|
2570
|
+
},
|
|
2571
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
2572
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
2573
|
+
repositoryRoot: root,
|
|
2574
|
+
branch: attempt.branch ?? state?.branch,
|
|
2575
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
2576
|
+
at: Date.now()
|
|
2577
|
+
});
|
|
2578
|
+
return outcome;
|
|
2579
|
+
};
|
|
2580
|
+
let challenge;
|
|
2581
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
2582
|
+
attempt.challengeId = state.challengeId;
|
|
2583
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2584
|
+
attempt.branch = state.branch;
|
|
2585
|
+
attempt.baseSha = state.baseSha;
|
|
2586
|
+
challenge = {
|
|
2587
|
+
challengeId: state.challengeId,
|
|
2588
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2589
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
2590
|
+
};
|
|
2591
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
2592
|
+
attempt.challengeId = state.challengeId;
|
|
2593
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2594
|
+
const exchanged2 = await exchangeChallenge(
|
|
2595
|
+
ctx,
|
|
2596
|
+
{
|
|
2597
|
+
challengeId: state.challengeId,
|
|
2598
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2599
|
+
githubLogin: state.githubLogin
|
|
2600
|
+
},
|
|
2601
|
+
root,
|
|
2602
|
+
deps,
|
|
2603
|
+
options.signal
|
|
2604
|
+
);
|
|
2605
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
2606
|
+
writeToken(ctx, exchanged2);
|
|
2607
|
+
return identified(exchanged2, false);
|
|
2608
|
+
} else if (!options.explicit) {
|
|
2609
|
+
return state ? outcomeFromState(state) : failure(
|
|
2610
|
+
"not_identified",
|
|
2611
|
+
"this session has not identified who started it yet",
|
|
2612
|
+
RETRY_REMEDY
|
|
2613
|
+
);
|
|
2614
|
+
} else {
|
|
2615
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
2616
|
+
if ("status" in pushed) return remember(pushed);
|
|
2617
|
+
challenge = pushed;
|
|
2618
|
+
}
|
|
2619
|
+
const verified = await pollChallenge(
|
|
2620
|
+
ctx.apiUrl,
|
|
2621
|
+
challenge.challengeId,
|
|
2622
|
+
challenge.repository,
|
|
2623
|
+
// A hook process waits only briefly for a late notice.
|
|
2624
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
2625
|
+
options.signal
|
|
2626
|
+
);
|
|
2627
|
+
if ("status" in verified) return remember(verified);
|
|
2628
|
+
const exchanged = await exchangeChallenge(
|
|
2629
|
+
ctx,
|
|
2630
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
2631
|
+
root,
|
|
2632
|
+
deps,
|
|
2633
|
+
options.signal
|
|
2634
|
+
);
|
|
2635
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
2636
|
+
writeToken(ctx, exchanged);
|
|
2637
|
+
return identified(exchanged, false);
|
|
2638
|
+
},
|
|
2639
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
2640
|
+
);
|
|
2641
|
+
}
|
|
2642
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
2643
|
+
const cached2 = cachedSessionCredential(deps);
|
|
2644
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
2645
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
2646
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2647
|
+
let outcome;
|
|
2648
|
+
try {
|
|
2649
|
+
outcome = await ensureSessionIdentity(
|
|
2650
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
2651
|
+
deps
|
|
2652
|
+
);
|
|
2653
|
+
} catch (error) {
|
|
2654
|
+
options.signal?.throwIfAborted();
|
|
2655
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2656
|
+
throw new MachineAuthError(
|
|
2657
|
+
"identity_unavailable",
|
|
2658
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
2659
|
+
);
|
|
2660
|
+
}
|
|
2661
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
2662
|
+
throw new MachineAuthError(
|
|
2663
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
2664
|
+
sessionIdentityMessage(outcome)
|
|
2665
|
+
);
|
|
2666
|
+
}
|
|
2667
|
+
|
|
1176
2668
|
// src/lib/machine-credentials.ts
|
|
1177
|
-
|
|
2669
|
+
function sessionScoped(deps) {
|
|
2670
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
2671
|
+
}
|
|
2672
|
+
var require3 = createRequire2(import.meta.url);
|
|
1178
2673
|
var SERVICE = "ai.primitive.prim.machine";
|
|
1179
|
-
var
|
|
2674
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
1180
2675
|
var PROFILE_FILE = "machine_profile.json";
|
|
1181
|
-
var
|
|
2676
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
1182
2677
|
var cached;
|
|
1183
2678
|
function configurationDirectory(deps) {
|
|
1184
2679
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
1185
2680
|
}
|
|
1186
2681
|
function apiUrlFor(deps) {
|
|
1187
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
2682
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
1188
2683
|
}
|
|
1189
|
-
function
|
|
1190
|
-
return
|
|
2684
|
+
function hash2(value) {
|
|
2685
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
1191
2686
|
}
|
|
1192
2687
|
function recordPath(directory, generation) {
|
|
1193
|
-
return
|
|
2688
|
+
return join10(directory, `machine_${generation}.json`);
|
|
1194
2689
|
}
|
|
1195
2690
|
function storageKey(directory, generation) {
|
|
1196
|
-
return `${
|
|
2691
|
+
return `${hash2(directory)}:${generation}`;
|
|
1197
2692
|
}
|
|
1198
2693
|
function environmentContextPath(deps, clientId) {
|
|
1199
|
-
return
|
|
2694
|
+
return join10(
|
|
1200
2695
|
configurationDirectory(deps),
|
|
1201
|
-
`machine_context_${
|
|
2696
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1202
2697
|
);
|
|
1203
2698
|
}
|
|
1204
2699
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -1256,27 +2751,33 @@ function readEnvironmentContext(environment, deps) {
|
|
|
1256
2751
|
return void 0;
|
|
1257
2752
|
}
|
|
1258
2753
|
}
|
|
1259
|
-
function
|
|
1260
|
-
let directory =
|
|
2754
|
+
function keyringLoaderPath(start, options = {}) {
|
|
2755
|
+
let directory = start;
|
|
1261
2756
|
for (let depth = 0; depth < 5; depth++) {
|
|
1262
|
-
const loader =
|
|
1263
|
-
if (
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
2757
|
+
const loader = join10(directory, "native", "keyring.cjs");
|
|
2758
|
+
if (existsSync5(loader)) return loader;
|
|
2759
|
+
directory = dirname7(directory);
|
|
2760
|
+
}
|
|
2761
|
+
try {
|
|
2762
|
+
createRequire2(join10(start, "noop.js")).resolve("@napi-rs/keyring");
|
|
2763
|
+
return void 0;
|
|
2764
|
+
} catch {
|
|
2765
|
+
return selectedHookRuntimeKeyringLoader(options);
|
|
1268
2766
|
}
|
|
1269
|
-
|
|
2767
|
+
}
|
|
2768
|
+
function keyringEntry(key) {
|
|
2769
|
+
const loader = keyringLoaderPath(dirname7(fileURLToPath4(import.meta.url)));
|
|
2770
|
+
const module = require3(loader ?? "@napi-rs/keyring");
|
|
1270
2771
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1271
2772
|
}
|
|
1272
2773
|
function protectPath(path, directory) {
|
|
1273
2774
|
if (process.platform !== "win32") {
|
|
1274
|
-
|
|
2775
|
+
chmodSync2(path, directory ? 448 : 384);
|
|
1275
2776
|
return;
|
|
1276
2777
|
}
|
|
1277
2778
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
1278
2779
|
const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
|
|
1279
|
-
|
|
2780
|
+
execFileSync2(
|
|
1280
2781
|
"powershell.exe",
|
|
1281
2782
|
[
|
|
1282
2783
|
"-NoProfile",
|
|
@@ -1288,8 +2789,8 @@ function protectPath(path, directory) {
|
|
|
1288
2789
|
);
|
|
1289
2790
|
}
|
|
1290
2791
|
function ensureDirectory(directory) {
|
|
1291
|
-
|
|
1292
|
-
if (
|
|
2792
|
+
mkdirSync4(directory, { recursive: true, mode: 448 });
|
|
2793
|
+
if (lstatSync5(directory).isSymbolicLink())
|
|
1293
2794
|
throw new MachineAuthError(
|
|
1294
2795
|
"unsafe_storage",
|
|
1295
2796
|
"Credential directory must not be a symbolic link."
|
|
@@ -1301,17 +2802,20 @@ function writePrivate(path, value) {
|
|
|
1301
2802
|
`, { mode: 384 });
|
|
1302
2803
|
protectPath(path, false);
|
|
1303
2804
|
}
|
|
2805
|
+
function readMachineMetadata(path) {
|
|
2806
|
+
return readPrivate(path);
|
|
2807
|
+
}
|
|
1304
2808
|
function readPrivate(path) {
|
|
1305
2809
|
let raw;
|
|
1306
2810
|
try {
|
|
1307
|
-
const stat =
|
|
2811
|
+
const stat = lstatSync5(path);
|
|
1308
2812
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1309
2813
|
throw new MachineAuthError(
|
|
1310
2814
|
"unsafe_storage",
|
|
1311
2815
|
"Machine credential files must be owner-only regular files."
|
|
1312
2816
|
);
|
|
1313
2817
|
}
|
|
1314
|
-
raw =
|
|
2818
|
+
raw = readFileSync7(path, "utf8");
|
|
1315
2819
|
} catch (error) {
|
|
1316
2820
|
if (error.code === "ENOENT") return void 0;
|
|
1317
2821
|
throw error;
|
|
@@ -1356,7 +2860,7 @@ function parseProfile(value) {
|
|
|
1356
2860
|
};
|
|
1357
2861
|
}
|
|
1358
2862
|
function readMachineProfile(deps = {}) {
|
|
1359
|
-
const value = readPrivate(
|
|
2863
|
+
const value = readPrivate(join10(configurationDirectory(deps), PROFILE_FILE));
|
|
1360
2864
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1361
2865
|
}
|
|
1362
2866
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -1365,20 +2869,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
1365
2869
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
1366
2870
|
function networkSecretBrokerKey(deps, clientId) {
|
|
1367
2871
|
const directory = configurationDirectory(deps);
|
|
1368
|
-
const path =
|
|
2872
|
+
const path = join10(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
1369
2873
|
const known = brokerKeys.get(path);
|
|
1370
2874
|
if (known) return known;
|
|
1371
2875
|
ensureDirectory(directory);
|
|
1372
2876
|
const read = () => {
|
|
1373
2877
|
try {
|
|
1374
|
-
const stat =
|
|
2878
|
+
const stat = lstatSync5(path);
|
|
1375
2879
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
1376
2880
|
throw new MachineAuthError(
|
|
1377
2881
|
"unsafe_storage",
|
|
1378
2882
|
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
1379
2883
|
true
|
|
1380
2884
|
);
|
|
1381
|
-
const value =
|
|
2885
|
+
const value = readFileSync7(path, "utf8").trim();
|
|
1382
2886
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
1383
2887
|
} catch (error) {
|
|
1384
2888
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -1397,16 +2901,16 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
1397
2901
|
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
1398
2902
|
true
|
|
1399
2903
|
);
|
|
1400
|
-
const staged = `${path}.${process.pid}.${
|
|
2904
|
+
const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
|
|
1401
2905
|
try {
|
|
1402
|
-
|
|
2906
|
+
writeFileSync4(staged, `${randomBytes4(32).toString("hex")}
|
|
1403
2907
|
`, { mode: 384, flag: "wx" });
|
|
1404
2908
|
protectPath(staged, false);
|
|
1405
2909
|
linkSync(staged, path);
|
|
1406
2910
|
} catch (error) {
|
|
1407
2911
|
if (error.code !== "EEXIST") throw error;
|
|
1408
2912
|
} finally {
|
|
1409
|
-
|
|
2913
|
+
rmSync7(staged, { force: true });
|
|
1410
2914
|
}
|
|
1411
2915
|
}
|
|
1412
2916
|
const key = read()?.key;
|
|
@@ -1439,7 +2943,7 @@ function environmentCredentials(deps) {
|
|
|
1439
2943
|
"conflicting_credentials",
|
|
1440
2944
|
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
1441
2945
|
);
|
|
1442
|
-
const generation =
|
|
2946
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
1443
2947
|
const credentials = {
|
|
1444
2948
|
clientId,
|
|
1445
2949
|
generation,
|
|
@@ -1460,12 +2964,12 @@ function environmentCredentials(deps) {
|
|
|
1460
2964
|
return {
|
|
1461
2965
|
clientId,
|
|
1462
2966
|
clientSecret,
|
|
1463
|
-
generation:
|
|
2967
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1464
2968
|
};
|
|
1465
2969
|
}
|
|
1466
2970
|
function hasMachineConfiguration(deps = {}) {
|
|
1467
2971
|
const env = deps.env ?? process.env;
|
|
1468
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 ||
|
|
2972
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join10(configurationDirectory(deps), PROFILE_FILE));
|
|
1469
2973
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1470
2974
|
throw new MachineAuthError(
|
|
1471
2975
|
"conflicting_credentials",
|
|
@@ -1477,6 +2981,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
1477
2981
|
}
|
|
1478
2982
|
function machineContext(deps = {}) {
|
|
1479
2983
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2984
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1480
2985
|
const environment = environmentCredentials(deps);
|
|
1481
2986
|
if (environment) {
|
|
1482
2987
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -1491,6 +2996,7 @@ function machineContext(deps = {}) {
|
|
|
1491
2996
|
return profile;
|
|
1492
2997
|
}
|
|
1493
2998
|
function cachedMachineCredential(deps = {}) {
|
|
2999
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1494
3000
|
const context = machineContext(deps);
|
|
1495
3001
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1496
3002
|
}
|
|
@@ -1499,7 +3005,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
1499
3005
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1500
3006
|
if (!generation) return false;
|
|
1501
3007
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1502
|
-
return readPrivate(
|
|
3008
|
+
return readPrivate(join10(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1503
3009
|
}
|
|
1504
3010
|
var environmentTerminal;
|
|
1505
3011
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -1563,6 +3069,7 @@ async function persistRecord(record, deps, signal) {
|
|
|
1563
3069
|
}
|
|
1564
3070
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1565
3071
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3072
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
1566
3073
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1567
3074
|
const apiUrl = apiUrlFor(deps);
|
|
1568
3075
|
const environment = environmentCredentials(deps);
|
|
@@ -1591,7 +3098,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1591
3098
|
}
|
|
1592
3099
|
}
|
|
1593
3100
|
return withFileLock(
|
|
1594
|
-
|
|
3101
|
+
join10(directory2, "credentials.lock"),
|
|
1595
3102
|
async () => {
|
|
1596
3103
|
if (machineSessionEnded(deps))
|
|
1597
3104
|
throw new MachineAuthError(
|
|
@@ -1599,7 +3106,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1599
3106
|
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1600
3107
|
true
|
|
1601
3108
|
);
|
|
1602
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
3109
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
1603
3110
|
return cached;
|
|
1604
3111
|
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
1605
3112
|
throw networkRejection.error;
|
|
@@ -1673,7 +3180,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1673
3180
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1674
3181
|
try {
|
|
1675
3182
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1676
|
-
|
|
3183
|
+
rmSync7(contextPath, { force: true });
|
|
1677
3184
|
} catch {
|
|
1678
3185
|
}
|
|
1679
3186
|
throw error;
|
|
@@ -1683,7 +3190,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1683
3190
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1684
3191
|
try {
|
|
1685
3192
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1686
|
-
|
|
3193
|
+
rmSync7(contextPath, { force: true });
|
|
1687
3194
|
} catch {
|
|
1688
3195
|
}
|
|
1689
3196
|
}
|
|
@@ -1697,7 +3204,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1697
3204
|
const expected = machineContext(deps);
|
|
1698
3205
|
const directory = configurationDirectory(deps);
|
|
1699
3206
|
return withFileLock(
|
|
1700
|
-
|
|
3207
|
+
join10(directory, "credentials.lock"),
|
|
1701
3208
|
async () => {
|
|
1702
3209
|
const profile = readMachineProfile(deps);
|
|
1703
3210
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -1712,7 +3219,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1712
3219
|
true
|
|
1713
3220
|
);
|
|
1714
3221
|
let record = await loadRecord(profile, deps, signal);
|
|
1715
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
3222
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
1716
3223
|
try {
|
|
1717
3224
|
const { tokens, identity } = await withMachineCooldown(
|
|
1718
3225
|
directory,
|
|
@@ -1747,7 +3254,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1747
3254
|
await persistRecord(record, deps, signal);
|
|
1748
3255
|
} catch (error) {
|
|
1749
3256
|
if (error instanceof MachineAuthError && error.terminal)
|
|
1750
|
-
writePrivate(
|
|
3257
|
+
writePrivate(join10(directory, "machine_terminal.json"), profile.generation);
|
|
1751
3258
|
throw error;
|
|
1752
3259
|
}
|
|
1753
3260
|
}
|
|
@@ -1776,23 +3283,29 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
|
1776
3283
|
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
1777
3284
|
});
|
|
1778
3285
|
}
|
|
3286
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
3287
|
+
ensureDirectory(directory);
|
|
3288
|
+
}
|
|
3289
|
+
function writeMachineMetadata(path, value) {
|
|
3290
|
+
writePrivate(path, value);
|
|
3291
|
+
}
|
|
1779
3292
|
|
|
1780
3293
|
// src/lib/credentials.ts
|
|
1781
3294
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
1782
|
-
var TOKEN_FILE_PATH =
|
|
1783
|
-
var REFRESH_TOKEN_PATH =
|
|
1784
|
-
var TOKEN_EXPIRES_PATH =
|
|
1785
|
-
var TERMINAL_REFRESH_PATH =
|
|
1786
|
-
var CREDENTIAL_METADATA_PATH =
|
|
1787
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
1788
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
1789
|
-
var CREDENTIAL_LOCK_PATH =
|
|
3295
|
+
var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
|
|
3296
|
+
var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
|
|
3297
|
+
var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
|
|
3298
|
+
var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
|
|
3299
|
+
var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
3300
|
+
var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
|
|
3301
|
+
var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
|
|
3302
|
+
var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
|
|
1790
3303
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
1791
3304
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
1792
3305
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
1793
3306
|
function readTrimmed(path) {
|
|
1794
3307
|
try {
|
|
1795
|
-
const value =
|
|
3308
|
+
const value = readFileSync8(path, "utf8").trim();
|
|
1796
3309
|
return value || void 0;
|
|
1797
3310
|
} catch {
|
|
1798
3311
|
return void 0;
|
|
@@ -1814,22 +3327,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
1814
3327
|
);
|
|
1815
3328
|
if (metadata.state === "legacy_broker") {
|
|
1816
3329
|
if (metadata.metadata) {
|
|
1817
|
-
const
|
|
1818
|
-
if (!
|
|
3330
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3331
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
1819
3332
|
return void 0;
|
|
1820
3333
|
}
|
|
1821
3334
|
}
|
|
1822
3335
|
return { token: stored, source: "token_file" };
|
|
1823
3336
|
}
|
|
1824
3337
|
if (metadata.state === "invalid") return void 0;
|
|
1825
|
-
const
|
|
1826
|
-
if (!
|
|
3338
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3339
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
1827
3340
|
return void 0;
|
|
1828
3341
|
}
|
|
1829
3342
|
return { token: stored, source: "token_file" };
|
|
1830
3343
|
}
|
|
1831
3344
|
function credentialFingerprint(value) {
|
|
1832
|
-
return
|
|
3345
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
1833
3346
|
}
|
|
1834
3347
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
1835
3348
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -1849,7 +3362,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
1849
3362
|
function readBoundedCredentialJson(path) {
|
|
1850
3363
|
let raw;
|
|
1851
3364
|
try {
|
|
1852
|
-
raw =
|
|
3365
|
+
raw = readFileSync8(path, "utf8");
|
|
1853
3366
|
} catch (error) {
|
|
1854
3367
|
return error.code === "ENOENT" ? void 0 : null;
|
|
1855
3368
|
}
|
|
@@ -1921,9 +3434,9 @@ function jwtExpiresAt(token) {
|
|
|
1921
3434
|
}
|
|
1922
3435
|
|
|
1923
3436
|
// src/daemon/client-instance-id.ts
|
|
1924
|
-
import { randomBytes as
|
|
1925
|
-
import { chmodSync as
|
|
1926
|
-
import { join as
|
|
3437
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
3438
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync6, readFileSync as readFileSync9 } from "fs";
|
|
3439
|
+
import { join as join12 } from "path";
|
|
1927
3440
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
1928
3441
|
var INSTANCE_FILE_MODE = 384;
|
|
1929
3442
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -1936,17 +3449,17 @@ function isClientInstanceId(value) {
|
|
|
1936
3449
|
}
|
|
1937
3450
|
function ensurePrivateConfigDirectory(configDir) {
|
|
1938
3451
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
1939
|
-
const metadata =
|
|
3452
|
+
const metadata = lstatSync6(configDir);
|
|
1940
3453
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
1941
3454
|
throw new Error("prim config path must be a private directory");
|
|
1942
3455
|
}
|
|
1943
|
-
|
|
3456
|
+
chmodSync3(configDir, CONFIG_DIRECTORY_MODE);
|
|
1944
3457
|
syncDirectory(configDir);
|
|
1945
3458
|
}
|
|
1946
3459
|
function readExisting(path) {
|
|
1947
3460
|
let metadata;
|
|
1948
3461
|
try {
|
|
1949
|
-
metadata =
|
|
3462
|
+
metadata = lstatSync6(path);
|
|
1950
3463
|
} catch (error) {
|
|
1951
3464
|
if (error.code === "ENOENT") {
|
|
1952
3465
|
return;
|
|
@@ -1956,11 +3469,11 @@ function readExisting(path) {
|
|
|
1956
3469
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
1957
3470
|
throw new Error("stored client instance identity is invalid");
|
|
1958
3471
|
}
|
|
1959
|
-
|
|
3472
|
+
chmodSync3(path, INSTANCE_FILE_MODE);
|
|
1960
3473
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
1961
3474
|
throw new Error("stored client instance identity is invalid");
|
|
1962
3475
|
}
|
|
1963
|
-
const raw =
|
|
3476
|
+
const raw = readFileSync9(path, "utf8");
|
|
1964
3477
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
1965
3478
|
if (raw !== value && raw !== `${value}
|
|
1966
3479
|
` || !isClientInstanceId(value)) {
|
|
@@ -1974,8 +3487,8 @@ function atomicWrite(path, value) {
|
|
|
1974
3487
|
}
|
|
1975
3488
|
async function getOrCreateClientInstanceId(options) {
|
|
1976
3489
|
const configDir = options.configDir;
|
|
1977
|
-
const path =
|
|
1978
|
-
const lockPath =
|
|
3490
|
+
const path = join12(configDir, "client_instance_id");
|
|
3491
|
+
const lockPath = join12(configDir, "client-instance.lock");
|
|
1979
3492
|
ensurePrivateConfigDirectory(configDir);
|
|
1980
3493
|
return withFileLock(
|
|
1981
3494
|
lockPath,
|
|
@@ -1984,7 +3497,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
1984
3497
|
if (existing !== void 0) {
|
|
1985
3498
|
return existing;
|
|
1986
3499
|
}
|
|
1987
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
3500
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
1988
3501
|
"base64url"
|
|
1989
3502
|
)}`;
|
|
1990
3503
|
if (!isClientInstanceId(generated)) {
|
|
@@ -2019,59 +3532,18 @@ async function ingestUploaderHeaders() {
|
|
|
2019
3532
|
return headers;
|
|
2020
3533
|
}
|
|
2021
3534
|
|
|
2022
|
-
// src/lib/terminal-safe.ts
|
|
2023
|
-
function replaceIsolatedSurrogates(value) {
|
|
2024
|
-
let out = "";
|
|
2025
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
2026
|
-
const unit = value.charCodeAt(index);
|
|
2027
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
2028
|
-
const next = value.charCodeAt(index + 1);
|
|
2029
|
-
if (next >= 56320 && next <= 57343) {
|
|
2030
|
-
out += value[index] + value[index + 1];
|
|
2031
|
-
index += 1;
|
|
2032
|
-
} else {
|
|
2033
|
-
out += "\uFFFD";
|
|
2034
|
-
}
|
|
2035
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
2036
|
-
out += "\uFFFD";
|
|
2037
|
-
} else {
|
|
2038
|
-
out += value[index];
|
|
2039
|
-
}
|
|
2040
|
-
}
|
|
2041
|
-
return out;
|
|
2042
|
-
}
|
|
2043
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
2044
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
2045
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
2046
|
-
point === 1564 || // Arabic letter mark
|
|
2047
|
-
point === 6158 || // Mongolian vowel separator
|
|
2048
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
2049
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
2050
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
2051
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
2052
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
2053
|
-
point >= 917504 && point <= 917631;
|
|
2054
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
2055
|
-
}
|
|
2056
|
-
function terminalSafeText(value) {
|
|
2057
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
2058
|
-
}
|
|
2059
|
-
function terminalSafeLine(value) {
|
|
2060
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2061
|
-
}
|
|
2062
|
-
|
|
2063
3535
|
// src/client.ts
|
|
2064
3536
|
var CONFIG_DIR_MODE = 448;
|
|
2065
3537
|
var CREDENTIAL_FILE_MODE = 384;
|
|
2066
3538
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
2067
|
-
var
|
|
3539
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
2068
3540
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
2069
3541
|
function authExpiredMessage() {
|
|
2070
3542
|
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
2071
3543
|
}
|
|
2072
3544
|
function readTrimmed2(path) {
|
|
2073
3545
|
try {
|
|
2074
|
-
const value =
|
|
3546
|
+
const value = readFileSync10(path, "utf8").trim();
|
|
2075
3547
|
return value || void 0;
|
|
2076
3548
|
} catch {
|
|
2077
3549
|
return void 0;
|
|
@@ -2081,23 +3553,23 @@ function getSiteUrl() {
|
|
|
2081
3553
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
2082
3554
|
}
|
|
2083
3555
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
2084
|
-
return primApiUrl?.trim() ||
|
|
3556
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
2085
3557
|
}
|
|
2086
3558
|
function expiresAtFor(token, expiresIn) {
|
|
2087
3559
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
2088
3560
|
}
|
|
2089
3561
|
function ensureConfigDirectory() {
|
|
2090
|
-
const directory =
|
|
2091
|
-
|
|
2092
|
-
|
|
3562
|
+
const directory = dirname8(TOKEN_FILE_PATH);
|
|
3563
|
+
mkdirSync5(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
3564
|
+
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
2093
3565
|
}
|
|
2094
3566
|
function atomicWrite2(path, content) {
|
|
2095
3567
|
ensureConfigDirectory();
|
|
2096
3568
|
atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
|
|
2097
3569
|
}
|
|
2098
3570
|
function removeCredentialFile(path) {
|
|
2099
|
-
if (!
|
|
2100
|
-
|
|
3571
|
+
if (!existsSync6(path)) return false;
|
|
3572
|
+
rmSync8(path, { force: true });
|
|
2101
3573
|
return true;
|
|
2102
3574
|
}
|
|
2103
3575
|
function getTokenExpiresAt() {
|
|
@@ -2112,23 +3584,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
2112
3584
|
const expiresAt = getTokenExpiresAt();
|
|
2113
3585
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
2114
3586
|
}
|
|
2115
|
-
function refreshFingerprint(
|
|
2116
|
-
return
|
|
3587
|
+
function refreshFingerprint(refreshToken3) {
|
|
3588
|
+
return createHash8("sha256").update(refreshToken3).digest("hex");
|
|
2117
3589
|
}
|
|
2118
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
3590
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
2119
3591
|
return {
|
|
2120
3592
|
version: 1,
|
|
2121
3593
|
family: "legacy_broker",
|
|
2122
3594
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2123
|
-
refreshTokenHash: refreshFingerprint(
|
|
3595
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2124
3596
|
};
|
|
2125
3597
|
}
|
|
2126
|
-
function credentialFamilyMetadata(accessToken,
|
|
3598
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
2127
3599
|
const hashes = {
|
|
2128
3600
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2129
|
-
refreshTokenHash: refreshFingerprint(
|
|
3601
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2130
3602
|
};
|
|
2131
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
3603
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
2132
3604
|
}
|
|
2133
3605
|
function writeCredentialMigrationSentinel() {
|
|
2134
3606
|
atomicWrite2(
|
|
@@ -2140,11 +3612,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
2140
3612
|
`
|
|
2141
3613
|
);
|
|
2142
3614
|
}
|
|
2143
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
2144
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
3615
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
3616
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
2145
3617
|
return { state: "invalid" };
|
|
2146
3618
|
}
|
|
2147
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
3619
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2148
3620
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
2149
3621
|
return { state: "invalid" };
|
|
2150
3622
|
}
|
|
@@ -2161,17 +3633,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
2161
3633
|
const metadata = readStoredCredentialMetadata();
|
|
2162
3634
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
2163
3635
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
2164
|
-
const
|
|
2165
|
-
if (!(accessToken &&
|
|
2166
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
3636
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
3637
|
+
if (!(accessToken && refreshToken3)) return;
|
|
3638
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2167
3639
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2168
3640
|
`);
|
|
2169
3641
|
}
|
|
2170
3642
|
function terminalFingerprint() {
|
|
2171
3643
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
2172
3644
|
}
|
|
2173
|
-
function writeTerminalFingerprint(
|
|
2174
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
3645
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
3646
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
2175
3647
|
`);
|
|
2176
3648
|
}
|
|
2177
3649
|
function clearTerminalFingerprint() {
|
|
@@ -2180,20 +3652,20 @@ function clearTerminalFingerprint() {
|
|
|
2180
3652
|
function isSessionEnded() {
|
|
2181
3653
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
2182
3654
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
2183
|
-
const
|
|
3655
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
2184
3656
|
const ended = terminalFingerprint();
|
|
2185
|
-
return Boolean(
|
|
3657
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
2186
3658
|
}
|
|
2187
3659
|
function withCredentialLock(operation, options = {}) {
|
|
2188
3660
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
2189
3661
|
}
|
|
2190
3662
|
function commitCredentialsUnlocked(credentials) {
|
|
2191
3663
|
const accessToken = credentials.accessToken.trim();
|
|
2192
|
-
const
|
|
2193
|
-
if (!accessToken || !
|
|
3664
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
3665
|
+
if (!accessToken || !refreshToken3) {
|
|
2194
3666
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
2195
3667
|
}
|
|
2196
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
3668
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
2197
3669
|
if (credentials.metadata !== void 0) {
|
|
2198
3670
|
preserveMarkerlessLegacyGeneration();
|
|
2199
3671
|
writeCredentialMigrationSentinel();
|
|
@@ -2201,10 +3673,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
2201
3673
|
`);
|
|
2202
3674
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
2203
3675
|
`);
|
|
2204
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
3676
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2205
3677
|
`);
|
|
2206
3678
|
} else {
|
|
2207
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
3679
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2208
3680
|
`);
|
|
2209
3681
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2210
3682
|
`);
|
|
@@ -2241,15 +3713,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
2241
3713
|
`
|
|
2242
3714
|
);
|
|
2243
3715
|
}
|
|
2244
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
3716
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
2245
3717
|
const current = readStoredCredentialMetadata();
|
|
2246
3718
|
if (expected.state === "legacy_broker") {
|
|
2247
3719
|
if (current.state !== "legacy_broker") return false;
|
|
2248
3720
|
if (!expected.metadata) return current.metadata === void 0;
|
|
2249
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
3721
|
+
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
2250
3722
|
}
|
|
2251
3723
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
2252
|
-
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
3724
|
+
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
2253
3725
|
}
|
|
2254
3726
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
2255
3727
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -2418,7 +3890,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
2418
3890
|
);
|
|
2419
3891
|
}
|
|
2420
3892
|
var _refreshInFlight;
|
|
2421
|
-
function
|
|
3893
|
+
function refreshToken2(options = {}) {
|
|
2422
3894
|
if (hasMachineConfiguration())
|
|
2423
3895
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
2424
3896
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -2556,7 +4028,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2556
4028
|
if (response.status === 401)
|
|
2557
4029
|
throw new HttpError(
|
|
2558
4030
|
401,
|
|
2559
|
-
selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
4031
|
+
selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
2560
4032
|
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
2561
4033
|
)
|
|
2562
4034
|
);
|
|
@@ -2577,7 +4049,7 @@ async function request2(method, path, body, options) {
|
|
|
2577
4049
|
let refreshAttempted = false;
|
|
2578
4050
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
2579
4051
|
refreshAttempted = true;
|
|
2580
|
-
const token = await
|
|
4052
|
+
const token = await refreshToken2({
|
|
2581
4053
|
signal: options?.signal,
|
|
2582
4054
|
quiet: options?.quietRefresh
|
|
2583
4055
|
});
|
|
@@ -2596,7 +4068,7 @@ async function request2(method, path, body, options) {
|
|
|
2596
4068
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
2597
4069
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
2598
4070
|
refreshAttempted = true;
|
|
2599
|
-
retryToken = await
|
|
4071
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
2600
4072
|
}
|
|
2601
4073
|
if (retryToken) {
|
|
2602
4074
|
_cachedCredential = {
|
|
@@ -2616,23 +4088,23 @@ function getClient() {
|
|
|
2616
4088
|
}
|
|
2617
4089
|
|
|
2618
4090
|
// src/daemon/principal.ts
|
|
2619
|
-
import { createHash as
|
|
4091
|
+
import { createHash as createHash9 } from "crypto";
|
|
2620
4092
|
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
2621
4093
|
function boundedClaim(value) {
|
|
2622
4094
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
2623
4095
|
}
|
|
2624
|
-
function
|
|
2625
|
-
return
|
|
4096
|
+
function sha2562(value) {
|
|
4097
|
+
return createHash9("sha256").update(value).digest("hex");
|
|
2626
4098
|
}
|
|
2627
4099
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
2628
4100
|
if (hasMachineConfiguration()) {
|
|
2629
4101
|
const machine = machineContext();
|
|
2630
4102
|
return machine ? {
|
|
2631
|
-
principalId:
|
|
4103
|
+
principalId: sha2562(
|
|
2632
4104
|
`${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
|
|
2633
4105
|
),
|
|
2634
4106
|
organizationId: machine.workosOrganizationId,
|
|
2635
|
-
credentialFingerprint:
|
|
4107
|
+
credentialFingerprint: sha2562(machine.generation)
|
|
2636
4108
|
} : void 0;
|
|
2637
4109
|
}
|
|
2638
4110
|
if (!token) return void 0;
|
|
@@ -2642,9 +4114,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
|
2642
4114
|
if (!(subject && organizationId)) return void 0;
|
|
2643
4115
|
const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
|
|
2644
4116
|
return {
|
|
2645
|
-
principalId:
|
|
4117
|
+
principalId: sha2562(`${issuer}\0${subject}`),
|
|
2646
4118
|
organizationId,
|
|
2647
|
-
credentialFingerprint:
|
|
4119
|
+
credentialFingerprint: sha2562(token)
|
|
2648
4120
|
};
|
|
2649
4121
|
}
|
|
2650
4122
|
|
|
@@ -2673,8 +4145,8 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
2673
4145
|
|
|
2674
4146
|
// src/daemon/client.ts
|
|
2675
4147
|
import { createConnection } from "net";
|
|
2676
|
-
import { join as
|
|
2677
|
-
var SOCK_PATH =
|
|
4148
|
+
import { join as join14 } from "path";
|
|
4149
|
+
var SOCK_PATH = join14(primConfigDirectory(), "sock");
|
|
2678
4150
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
2679
4151
|
var nextRequestId = 1;
|
|
2680
4152
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -2687,7 +4159,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
2687
4159
|
...caller ? { caller } : {}
|
|
2688
4160
|
};
|
|
2689
4161
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
2690
|
-
return new Promise((
|
|
4162
|
+
return new Promise((resolve4) => {
|
|
2691
4163
|
let settled = false;
|
|
2692
4164
|
let socket;
|
|
2693
4165
|
let buffer = Buffer.alloc(0);
|
|
@@ -2702,7 +4174,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
2702
4174
|
} catch {
|
|
2703
4175
|
}
|
|
2704
4176
|
}
|
|
2705
|
-
|
|
4177
|
+
resolve4(value);
|
|
2706
4178
|
};
|
|
2707
4179
|
const timer = setTimeout(() => settle(null), timeoutMs);
|
|
2708
4180
|
timer.unref();
|
|
@@ -2789,215 +4261,22 @@ async function daemonOrDirectGet(method, path, client, timeoutMs = DAEMON_HTTP_T
|
|
|
2789
4261
|
|
|
2790
4262
|
// src/lib/activation.ts
|
|
2791
4263
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
2792
|
-
import { existsSync as
|
|
4264
|
+
import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
|
|
2793
4265
|
import { homedir as homedir2 } from "os";
|
|
2794
|
-
import { join as
|
|
4266
|
+
import { join as join16 } from "path";
|
|
2795
4267
|
|
|
2796
4268
|
// src/lib/cloud-prepared.ts
|
|
2797
|
-
import { existsSync as
|
|
2798
|
-
import { join as
|
|
4269
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync11, rmSync as rmSync9, writeFileSync as writeFileSync5 } from "fs";
|
|
4270
|
+
import { join as join15 } from "path";
|
|
2799
4271
|
|
|
2800
4272
|
// src/lib/demo-pause.ts
|
|
2801
|
-
import { execFileSync as execFileSync2 } from "child_process";
|
|
2802
|
-
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
2803
|
-
|
|
2804
|
-
// src/lib/git.ts
|
|
2805
4273
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
2806
|
-
|
|
2807
|
-
import { lstatSync as lstatSync5, readFileSync as readFileSync10, realpathSync } from "fs";
|
|
2808
|
-
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, join as join12, relative, resolve as resolve2, sep } from "path";
|
|
2809
|
-
var GIT_TIMEOUT_MS = 1e3;
|
|
2810
|
-
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
2811
|
-
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
2812
|
-
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
2813
|
-
function gitToplevel(cwd) {
|
|
2814
|
-
try {
|
|
2815
|
-
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
2816
|
-
cwd,
|
|
2817
|
-
encoding: "utf-8",
|
|
2818
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
2819
|
-
timeout: GIT_TIMEOUT_MS
|
|
2820
|
-
}).trim();
|
|
2821
|
-
} catch {
|
|
2822
|
-
return null;
|
|
2823
|
-
}
|
|
2824
|
-
}
|
|
2825
|
-
function gitValue(cwd, args) {
|
|
2826
|
-
try {
|
|
2827
|
-
const value = execFileSync3("git", args, {
|
|
2828
|
-
cwd,
|
|
2829
|
-
encoding: "utf-8",
|
|
2830
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
2831
|
-
timeout: GIT_TIMEOUT_MS
|
|
2832
|
-
}).trim();
|
|
2833
|
-
return value || void 0;
|
|
2834
|
-
} catch {
|
|
2835
|
-
return void 0;
|
|
2836
|
-
}
|
|
2837
|
-
}
|
|
2838
|
-
function currentBranch(cwd) {
|
|
2839
|
-
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
2840
|
-
}
|
|
2841
|
-
function parseGithubRepositoryName(path) {
|
|
2842
|
-
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
2843
|
-
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
2844
|
-
return null;
|
|
2845
|
-
}
|
|
2846
|
-
return `${parts[0]}/${parts[1]}`;
|
|
2847
|
-
}
|
|
2848
|
-
function githubRepositoryFromRemote(remote) {
|
|
2849
|
-
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
2850
|
-
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
2851
|
-
remote
|
|
2852
|
-
);
|
|
2853
|
-
const path = match?.[1] ?? match?.[2];
|
|
2854
|
-
return path ? parseGithubRepositoryName(path) : null;
|
|
2855
|
-
}
|
|
2856
|
-
function checkoutSettingsText(repoRoot) {
|
|
2857
|
-
const path = join12(repoRoot, ".claude", "settings.json");
|
|
2858
|
-
try {
|
|
2859
|
-
if (!lstatSync5(join12(repoRoot, ".claude")).isDirectory()) return null;
|
|
2860
|
-
const stat = lstatSync5(path);
|
|
2861
|
-
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
2862
|
-
return readFileSync10(path, "utf8");
|
|
2863
|
-
} catch {
|
|
2864
|
-
return null;
|
|
2865
|
-
}
|
|
2866
|
-
}
|
|
2867
|
-
function checkoutDeclaration(repoRoot, name) {
|
|
2868
|
-
const text = checkoutSettingsText(repoRoot);
|
|
2869
|
-
if (text === null) return null;
|
|
2870
|
-
let parsed;
|
|
2871
|
-
try {
|
|
2872
|
-
parsed = JSON.parse(text);
|
|
2873
|
-
} catch {
|
|
2874
|
-
return null;
|
|
2875
|
-
}
|
|
2876
|
-
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
2877
|
-
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
2878
|
-
return typeof value === "string" ? value : null;
|
|
2879
|
-
}
|
|
2880
|
-
function declaredGithubRepository(repoRoot) {
|
|
2881
|
-
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
2882
|
-
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
2883
|
-
}
|
|
2884
|
-
function githubRepositoryFullName(cwd) {
|
|
2885
|
-
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
2886
|
-
if (remote) {
|
|
2887
|
-
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
2888
|
-
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
2889
|
-
}
|
|
2890
|
-
const root = gitToplevel(cwd);
|
|
2891
|
-
return root ? declaredGithubRepository(root) : null;
|
|
2892
|
-
}
|
|
2893
|
-
function canonicalGitRoot(cwd) {
|
|
2894
|
-
try {
|
|
2895
|
-
const top = gitToplevel(cwd);
|
|
2896
|
-
return top ? realpathSync.native(top) : null;
|
|
2897
|
-
} catch {
|
|
2898
|
-
return null;
|
|
2899
|
-
}
|
|
2900
|
-
}
|
|
2901
|
-
function normalizeOriginRemote(remote) {
|
|
2902
|
-
const value = remote.trim();
|
|
2903
|
-
if (!value) return void 0;
|
|
2904
|
-
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
2905
|
-
if (scp?.host && scp.path) {
|
|
2906
|
-
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
2907
|
-
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
2908
|
-
}
|
|
2909
|
-
try {
|
|
2910
|
-
const url = new URL(value);
|
|
2911
|
-
url.username = "";
|
|
2912
|
-
url.password = "";
|
|
2913
|
-
url.search = "";
|
|
2914
|
-
url.hash = "";
|
|
2915
|
-
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
2916
|
-
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
2917
|
-
return void 0;
|
|
2918
|
-
} catch {
|
|
2919
|
-
return void 0;
|
|
2920
|
-
}
|
|
2921
|
-
}
|
|
2922
|
-
function nearestExistingAncestor(path) {
|
|
2923
|
-
const suffix = [];
|
|
2924
|
-
let cursor = path;
|
|
2925
|
-
while (true) {
|
|
2926
|
-
try {
|
|
2927
|
-
lstatSync5(cursor);
|
|
2928
|
-
break;
|
|
2929
|
-
} catch (error) {
|
|
2930
|
-
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
2931
|
-
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
2932
|
-
const parent = dirname6(cursor);
|
|
2933
|
-
if (parent === cursor) return null;
|
|
2934
|
-
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
2935
|
-
cursor = parent;
|
|
2936
|
-
}
|
|
2937
|
-
}
|
|
2938
|
-
try {
|
|
2939
|
-
return { real: realpathSync.native(cursor), suffix };
|
|
2940
|
-
} catch {
|
|
2941
|
-
return null;
|
|
2942
|
-
}
|
|
2943
|
-
}
|
|
2944
|
-
function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
2945
|
-
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
2946
|
-
return { ok: false, reason: "invalid_path" };
|
|
2947
|
-
}
|
|
2948
|
-
const absolute = resolve2(baseDir, filePath);
|
|
2949
|
-
const resolved = nearestExistingAncestor(absolute);
|
|
2950
|
-
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
2951
|
-
const target = resolve2(resolved.real, ...resolved.suffix);
|
|
2952
|
-
const rel = relative(context.repoRoot, target);
|
|
2953
|
-
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
2954
|
-
if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
2955
|
-
return { ok: false, reason: "outside_repository" };
|
|
2956
|
-
}
|
|
2957
|
-
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
2958
|
-
}
|
|
2959
|
-
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
|
|
2960
|
-
if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
2961
|
-
return null;
|
|
2962
|
-
const absolute = resolve2(cwd, filePath);
|
|
2963
|
-
let target;
|
|
2964
|
-
try {
|
|
2965
|
-
const stat = lstatSync5(absolute);
|
|
2966
|
-
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
2967
|
-
target = realpathSync.native(absolute);
|
|
2968
|
-
} catch (error) {
|
|
2969
|
-
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
2970
|
-
return null;
|
|
2971
|
-
}
|
|
2972
|
-
try {
|
|
2973
|
-
const parent = realpathSync.native(dirname6(absolute));
|
|
2974
|
-
if (!lstatSync5(parent).isDirectory()) return null;
|
|
2975
|
-
target = resolve2(parent, basename2(absolute));
|
|
2976
|
-
} catch {
|
|
2977
|
-
return null;
|
|
2978
|
-
}
|
|
2979
|
-
}
|
|
2980
|
-
const rel = relative(repositoryRoot, target);
|
|
2981
|
-
if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
2982
|
-
return null;
|
|
2983
|
-
}
|
|
2984
|
-
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
2985
|
-
}
|
|
2986
|
-
function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
2987
|
-
if (typeof contextOrCwd === "string") {
|
|
2988
|
-
return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
|
|
2989
|
-
}
|
|
2990
|
-
return canonicalRepositoryPathScoped(
|
|
2991
|
-
filePath,
|
|
2992
|
-
contextOrCwd,
|
|
2993
|
-
baseDirOrRoot ?? contextOrCwd.repoRoot
|
|
2994
|
-
);
|
|
2995
|
-
}
|
|
4274
|
+
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
2996
4275
|
|
|
2997
4276
|
// src/lib/activation.ts
|
|
2998
4277
|
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
2999
4278
|
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
3000
|
-
var
|
|
4279
|
+
var GIT_TIMEOUT_MS3 = 1e3;
|
|
3001
4280
|
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
3002
4281
|
function isValidRepoSyncId(value) {
|
|
3003
4282
|
return typeof value === "string" && REPO_SYNC_ID_RE.test(value);
|
|
@@ -3008,7 +4287,7 @@ function localGitConfigValue(cwd, key) {
|
|
|
3008
4287
|
cwd,
|
|
3009
4288
|
encoding: "utf-8",
|
|
3010
4289
|
stdio: ["ignore", "pipe", "ignore"],
|
|
3011
|
-
timeout:
|
|
4290
|
+
timeout: GIT_TIMEOUT_MS3
|
|
3012
4291
|
}).trim();
|
|
3013
4292
|
return value || void 0;
|
|
3014
4293
|
} catch {
|