@primitive.ai/prim 0.1.0-alpha.128 → 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/dist/{chunk-6QAXVFRJ.js → chunk-BVGASV3B.js} +942 -123
- package/dist/{chunk-M6KIDB5R.js → chunk-DYXCJ6WZ.js} +10 -10
- package/dist/{chunk-B3ICJZXV.js → chunk-FHDTJP2C.js} +2 -2
- package/dist/{chunk-XINFTNA2.js → chunk-HDL3UXYJ.js} +5 -5
- package/dist/{chunk-C357P37M.js → chunk-IJ3W2YBM.js} +4 -4
- package/dist/{chunk-N6PZE7HX.js → chunk-IZAEAALI.js} +2 -2
- package/dist/{chunk-PTZ6BWSU.js → chunk-KZNOT2YH.js} +2 -2
- package/dist/{chunk-P4O7L7JZ.js → chunk-L7U3G4XR.js} +2 -2
- package/dist/{chunk-EQWUCFXK.js → chunk-LBZJD2I4.js} +3 -5
- package/dist/{chunk-PRJ7P6J5.js → chunk-MMMY57UA.js} +22 -837
- package/dist/{chunk-WEGZGF3K.js → chunk-NWWTFQP2.js} +1 -1
- package/dist/{chunk-NYDM4HSS.js → chunk-QSDWWEHF.js} +2 -2
- package/dist/{chunk-3KPTVK4N.js → chunk-RAEOSDQ6.js} +1 -1
- package/dist/{chunk-E57UVUJL.js → chunk-RS5ADTDF.js} +4 -4
- package/dist/{chunk-ANMNGGTN.js → chunk-RWJ7WHTJ.js} +2 -2
- package/dist/{chunk-RDT2IV2Z.js → chunk-SJE7OWVS.js} +3 -3
- package/dist/{chunk-VLT2KGPE.js → chunk-USJ4JGDC.js} +3 -3
- package/dist/{chunk-ZCT23NBS.js → chunk-YPHDV5AS.js} +2 -2
- package/dist/{chunk-QQ3G5SXX.js → chunk-YSV43WLK.js} +1 -1
- package/dist/{chunk-4DYEBYKM.js → chunk-ZKIBD5MO.js} +2 -2
- package/dist/daemon/server.js +624 -289
- package/dist/hook-runtime/daemon/server.js +624 -289
- package/dist/hook-runtime/hooks/post-commit.js +307 -186
- package/dist/hook-runtime/hooks/post-rewrite.js +302 -181
- package/dist/hook-runtime/hooks/post-tool-use.js +490 -276
- package/dist/hook-runtime/hooks/pre-commit.js +516 -181
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +221 -7
- package/dist/hook-runtime/hooks/prim-hook.js +511 -297
- package/dist/hook-runtime/hooks/session-end.js +229 -229
- package/dist/hook-runtime/hooks/session-start.js +170 -14
- package/dist/hook-runtime/index.js +1623 -1607
- package/dist/hook-runtime/statusline-main.js +245 -124
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +15 -15
- 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 +12 -13
- package/dist/index.js +24 -24
- package/dist/statusline-main.js +245 -124
- package/package.json +1 -1
|
@@ -15965,29 +15965,29 @@ function updateNotifier(options) {
|
|
|
15965
15965
|
}
|
|
15966
15966
|
|
|
15967
15967
|
// src/daemon/principal.ts
|
|
15968
|
-
import { createHash as
|
|
15968
|
+
import { createHash as createHash8 } from "crypto";
|
|
15969
15969
|
|
|
15970
15970
|
// src/lib/credentials.ts
|
|
15971
|
-
import { createHash as
|
|
15972
|
-
import { readFileSync as
|
|
15973
|
-
import { join as
|
|
15971
|
+
import { createHash as createHash7 } from "crypto";
|
|
15972
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
15973
|
+
import { join as join11 } from "path";
|
|
15974
15974
|
|
|
15975
15975
|
// src/lib/machine-credentials.ts
|
|
15976
15976
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
15977
|
-
import { createHash as
|
|
15977
|
+
import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
|
|
15978
15978
|
import {
|
|
15979
|
-
chmodSync,
|
|
15980
|
-
existsSync as
|
|
15979
|
+
chmodSync as chmodSync2,
|
|
15980
|
+
existsSync as existsSync5,
|
|
15981
15981
|
linkSync,
|
|
15982
|
-
lstatSync as
|
|
15983
|
-
mkdirSync as
|
|
15984
|
-
readFileSync as
|
|
15985
|
-
rmSync as
|
|
15986
|
-
writeFileSync as
|
|
15982
|
+
lstatSync as lstatSync5,
|
|
15983
|
+
mkdirSync as mkdirSync4,
|
|
15984
|
+
readFileSync as readFileSync7,
|
|
15985
|
+
rmSync as rmSync7,
|
|
15986
|
+
writeFileSync as writeFileSync5
|
|
15987
15987
|
} from "fs";
|
|
15988
|
-
import { createRequire } from "module";
|
|
15989
|
-
import { dirname as
|
|
15990
|
-
import { fileURLToPath as
|
|
15988
|
+
import { createRequire as createRequire2 } from "module";
|
|
15989
|
+
import { dirname as dirname7, join as join10 } from "path";
|
|
15990
|
+
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
15991
15991
|
|
|
15992
15992
|
// src/lib/atomic-file.ts
|
|
15993
15993
|
import { randomUUID } from "crypto";
|
|
@@ -16246,13 +16246,27 @@ async function withFileLock(lockDir, operation, options = {}) {
|
|
|
16246
16246
|
}
|
|
16247
16247
|
}
|
|
16248
16248
|
|
|
16249
|
-
// src/lib/
|
|
16250
|
-
import {
|
|
16251
|
-
import {
|
|
16252
|
-
|
|
16253
|
-
|
|
16254
|
-
|
|
16255
|
-
|
|
16249
|
+
// src/lib/hook-runtime.ts
|
|
16250
|
+
import { createHash, randomBytes as randomBytes2 } from "crypto";
|
|
16251
|
+
import {
|
|
16252
|
+
constants as constants2,
|
|
16253
|
+
accessSync,
|
|
16254
|
+
chmodSync,
|
|
16255
|
+
copyFileSync,
|
|
16256
|
+
existsSync as existsSync4,
|
|
16257
|
+
lstatSync,
|
|
16258
|
+
mkdirSync as mkdirSync3,
|
|
16259
|
+
mkdtempSync,
|
|
16260
|
+
readFileSync as readFileSync3,
|
|
16261
|
+
readdirSync,
|
|
16262
|
+
realpathSync,
|
|
16263
|
+
renameSync as renameSync2,
|
|
16264
|
+
rmSync as rmSync3,
|
|
16265
|
+
statSync as statSync2,
|
|
16266
|
+
utimesSync,
|
|
16267
|
+
writeFileSync as writeFileSync4
|
|
16268
|
+
} from "fs";
|
|
16269
|
+
import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
|
|
16256
16270
|
|
|
16257
16271
|
// src/lib/bin-path.ts
|
|
16258
16272
|
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
@@ -16450,746 +16464,1536 @@ function hookCommandResolutions(commands, bins) {
|
|
|
16450
16464
|
return resolutions;
|
|
16451
16465
|
}
|
|
16452
16466
|
|
|
16453
|
-
// src/lib/
|
|
16454
|
-
|
|
16455
|
-
|
|
16456
|
-
|
|
16457
|
-
|
|
16458
|
-
|
|
16459
|
-
|
|
16460
|
-
return
|
|
16461
|
-
|
|
16462
|
-
|
|
16463
|
-
|
|
16464
|
-
|
|
16465
|
-
|
|
16466
|
-
|
|
16467
|
-
|
|
16468
|
-
|
|
16469
|
-
|
|
16470
|
-
|
|
16471
|
-
|
|
16472
|
-
|
|
16473
|
-
|
|
16474
|
-
|
|
16475
|
-
|
|
16467
|
+
// src/lib/git-hook-contract.ts
|
|
16468
|
+
var MANAGED_GIT_HOOK_NAMES = ["pre-commit", "post-commit", "post-rewrite"];
|
|
16469
|
+
var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
|
|
16470
|
+
var GIT_HOOK_CONTRACT_VERSION = 1;
|
|
16471
|
+
var CONTRACT_LINE_PREFIX = "# prim git hook v";
|
|
16472
|
+
var CONTRACT_LINE_RE = /^# prim git hook v([0-9]+)\b/mu;
|
|
16473
|
+
function blockMarkers(hook) {
|
|
16474
|
+
return { start: `# >>> prim ${hook} hook >>>`, end: `# <<< prim ${hook} hook <<<` };
|
|
16475
|
+
}
|
|
16476
|
+
function entrypointCommand(hook) {
|
|
16477
|
+
const script = [
|
|
16478
|
+
PRIM_CONFIG_SHELL_RESOLVER,
|
|
16479
|
+
`case "$prim_config" in /) prim_entry=/${GIT_HOOK_ENTRYPOINT_NAME} ;; `,
|
|
16480
|
+
`*) prim_entry="$prim_config/${GIT_HOOK_ENTRYPOINT_NAME}" ;; esac; `,
|
|
16481
|
+
'[ -x "$prim_entry" ] || exit 0; exec "$prim_entry" "$@"'
|
|
16482
|
+
].join("");
|
|
16483
|
+
return `/bin/sh -c ${shellQuote(script)} ${GIT_HOOK_ENTRYPOINT_NAME} ${hook} "$@"`;
|
|
16484
|
+
}
|
|
16485
|
+
function managedHookBlock(hook) {
|
|
16486
|
+
const { start, end } = blockMarkers(hook);
|
|
16487
|
+
const header = `${CONTRACT_LINE_PREFIX}${GIT_HOOK_CONTRACT_VERSION}: a no-op unless prim is installed and enabled here (see \`prim hooks snippet ${hook}\`).`;
|
|
16488
|
+
if (hook !== "post-rewrite") {
|
|
16489
|
+
return `${start}
|
|
16490
|
+
${header}
|
|
16491
|
+
# shellcheck disable=SC2016
|
|
16492
|
+
${entrypointCommand(hook)} || :
|
|
16493
|
+
${end}`;
|
|
16494
|
+
}
|
|
16495
|
+
return `${start}
|
|
16496
|
+
${header}
|
|
16497
|
+
prim_rewrite_stdin=$(mktemp 2>/dev/null) || prim_rewrite_stdin=
|
|
16498
|
+
if test -n "\${prim_rewrite_stdin}" && cat >"\${prim_rewrite_stdin}"; then
|
|
16499
|
+
# shellcheck disable=SC2016
|
|
16500
|
+
${entrypointCommand(hook)} <"\${prim_rewrite_stdin}" || :
|
|
16501
|
+
exec <"\${prim_rewrite_stdin}"
|
|
16502
|
+
fi
|
|
16503
|
+
if test -n "\${prim_rewrite_stdin}"; then rm -f "\${prim_rewrite_stdin}"; fi
|
|
16504
|
+
unset prim_rewrite_stdin
|
|
16505
|
+
${end}`;
|
|
16506
|
+
}
|
|
16507
|
+
var OPEN_WORDS = /* @__PURE__ */ new Set(["then", "do", "else", "{", "(", "&&", "||", "|"]);
|
|
16508
|
+
function canonicalHookBlock(text) {
|
|
16509
|
+
const tokens = [];
|
|
16510
|
+
let word = "";
|
|
16511
|
+
let quote2;
|
|
16512
|
+
const separate = () => {
|
|
16513
|
+
const last = tokens.at(-1);
|
|
16514
|
+
if (last !== void 0 && last !== ";" && !OPEN_WORDS.has(last)) tokens.push(";");
|
|
16515
|
+
};
|
|
16516
|
+
const flush2 = () => {
|
|
16517
|
+
if (word === "") return;
|
|
16518
|
+
const last = tokens.at(-1);
|
|
16519
|
+
if (last !== void 0 && /^[0-9]*(?:<|>|>>|<&|>&)$/u.test(last))
|
|
16520
|
+
tokens[tokens.length - 1] += word;
|
|
16521
|
+
else tokens.push(word);
|
|
16522
|
+
word = "";
|
|
16523
|
+
};
|
|
16524
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
16525
|
+
const char = text[index];
|
|
16526
|
+
if (quote2) {
|
|
16527
|
+
word += char;
|
|
16528
|
+
if (char === quote2) quote2 = void 0;
|
|
16529
|
+
continue;
|
|
16530
|
+
}
|
|
16531
|
+
if (char === "'" || char === '"') {
|
|
16532
|
+
quote2 = char;
|
|
16533
|
+
word += char;
|
|
16534
|
+
} else if (char === "#" && word === "") {
|
|
16535
|
+
const end = text.indexOf("\n", index);
|
|
16536
|
+
const comment2 = text.slice(index, end === -1 ? text.length : end);
|
|
16537
|
+
tokens.push(comment2.replace(/\s+/gu, " ").trim());
|
|
16538
|
+
index = (end === -1 ? text.length : end) - 1;
|
|
16539
|
+
} else if (char === "\n" || char === ";") {
|
|
16540
|
+
flush2();
|
|
16541
|
+
if (char === ";" && text[index + 1] === ";") {
|
|
16542
|
+
tokens.push(";;");
|
|
16543
|
+
index += 1;
|
|
16544
|
+
} else {
|
|
16545
|
+
separate();
|
|
16476
16546
|
}
|
|
16547
|
+
} else if (/\s/u.test(char)) {
|
|
16548
|
+
flush2();
|
|
16549
|
+
} else {
|
|
16550
|
+
word += char;
|
|
16551
|
+
}
|
|
16552
|
+
}
|
|
16553
|
+
flush2();
|
|
16554
|
+
while (tokens.at(-1) === ";") tokens.pop();
|
|
16555
|
+
return tokens.join("\0");
|
|
16556
|
+
}
|
|
16557
|
+
function hookBlockContractVersion(block) {
|
|
16558
|
+
const match = CONTRACT_LINE_RE.exec(block);
|
|
16559
|
+
return match?.[1] ? Number(match[1]) : void 0;
|
|
16560
|
+
}
|
|
16561
|
+
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
16562
|
+
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
16563
|
+
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
16564
|
+
# where prim is active (git config prim.active true) and never fails the hook.
|
|
16565
|
+
case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
|
|
16566
|
+
prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
|
|
16567
|
+
[ -x "$prim_launcher" ] || exit 0
|
|
16568
|
+
[ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
|
|
16569
|
+
prim_hook=\${1-}
|
|
16570
|
+
if [ "$#" -gt 0 ]; then shift; fi
|
|
16571
|
+
case "$prim_hook" in
|
|
16572
|
+
pre-commit)
|
|
16573
|
+
"$prim_launcher" prim-pre-commit "$@" || :
|
|
16574
|
+
;;
|
|
16575
|
+
post-commit)
|
|
16576
|
+
prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
|
|
16577
|
+
case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
|
|
16578
|
+
case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
|
|
16579
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
16580
|
+
prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
|
|
16581
|
+
(
|
|
16582
|
+
trap '' HUP
|
|
16583
|
+
trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
|
|
16584
|
+
PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
|
|
16585
|
+
) </dev/null >/dev/null 2>&1 &
|
|
16586
|
+
;;
|
|
16587
|
+
post-rewrite)
|
|
16588
|
+
case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
|
|
16589
|
+
prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
|
|
16590
|
+
if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
|
|
16591
|
+
rm -f "$prim_pairs"
|
|
16592
|
+
exit 0
|
|
16593
|
+
fi
|
|
16594
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
16595
|
+
(
|
|
16596
|
+
trap '' HUP
|
|
16597
|
+
trap 'rm -f "$prim_pairs"' 0
|
|
16598
|
+
PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
|
|
16599
|
+
) </dev/null >/dev/null 2>&1 &
|
|
16600
|
+
;;
|
|
16601
|
+
esac
|
|
16602
|
+
exit 0
|
|
16603
|
+
`;
|
|
16604
|
+
|
|
16605
|
+
// src/lib/native-keyring.ts
|
|
16606
|
+
import { existsSync as existsSync3 } from "fs";
|
|
16607
|
+
import { createRequire } from "module";
|
|
16608
|
+
import { dirname as dirname4, join as join3 } from "path";
|
|
16609
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
16610
|
+
var require2 = createRequire(import.meta.url);
|
|
16611
|
+
var KEYRING_LOADER = 'module.exports = require("./keyring.node");\n';
|
|
16612
|
+
var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
|
|
16613
|
+
function keyringNativeBinary() {
|
|
16614
|
+
let directory = dirname4(fileURLToPath4(import.meta.url));
|
|
16615
|
+
for (let depth = 0; depth < 5; depth++) {
|
|
16616
|
+
const binary3 = join3(directory, "native", "keyring.node");
|
|
16617
|
+
if (existsSync3(binary3)) return binary3;
|
|
16618
|
+
directory = dirname4(directory);
|
|
16619
|
+
}
|
|
16620
|
+
const packagePath = require2.resolve("@napi-rs/keyring");
|
|
16621
|
+
require2(packagePath);
|
|
16622
|
+
const entry = require2.cache[packagePath];
|
|
16623
|
+
const binary2 = entry?.children.find(
|
|
16624
|
+
(child) => child.filename.endsWith(".node") && child.filename.includes("keyring")
|
|
16625
|
+
);
|
|
16626
|
+
if (!binary2 || !existsSync3(binary2.filename))
|
|
16627
|
+
throw new Error(
|
|
16628
|
+
"Cannot stage the native credential store; reinstall Prim with optional dependencies enabled."
|
|
16477
16629
|
);
|
|
16478
|
-
|
|
16479
|
-
outgoing.end(init.body);
|
|
16480
|
-
});
|
|
16630
|
+
return binary2.filename;
|
|
16481
16631
|
}
|
|
16482
16632
|
|
|
16483
|
-
// src/lib/
|
|
16484
|
-
|
|
16485
|
-
|
|
16633
|
+
// src/lib/paths.ts
|
|
16634
|
+
import { homedir } from "os";
|
|
16635
|
+
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
16636
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
16637
|
+
function absolutePath(value, variable) {
|
|
16638
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
16639
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
16640
|
+
}
|
|
16641
|
+
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
16642
|
+
const normalized = normalize(value);
|
|
16643
|
+
return normalized === value ? value : void 0;
|
|
16486
16644
|
}
|
|
16487
|
-
function
|
|
16488
|
-
|
|
16645
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
16646
|
+
const env4 = options.env ?? process.env;
|
|
16647
|
+
const explicit = absolutePath(env4.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
16648
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
16649
|
+
const xdgConfigHome = absolutePath(env4.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
16650
|
+
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
16651
|
+
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
16652
|
+
if (!home) {
|
|
16653
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
16654
|
+
}
|
|
16655
|
+
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
16489
16656
|
}
|
|
16490
|
-
|
|
16491
|
-
|
|
16492
|
-
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}.`;
|
|
16493
|
-
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
16494
|
-
function cloudSetupPointer(message, env4 = process.env) {
|
|
16495
|
-
return isClaudeCloudSession(env4) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
16657
|
+
function primConfigDirectory(options = {}) {
|
|
16658
|
+
return resolvePrimConfigDirectory(options).path;
|
|
16496
16659
|
}
|
|
16497
|
-
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
16498
16660
|
|
|
16499
|
-
// src/lib/
|
|
16500
|
-
var
|
|
16501
|
-
var
|
|
16502
|
-
var
|
|
16503
|
-
var
|
|
16504
|
-
var
|
|
16505
|
-
var
|
|
16506
|
-
var
|
|
16507
|
-
var
|
|
16508
|
-
var
|
|
16509
|
-
var
|
|
16510
|
-
var
|
|
16511
|
-
var
|
|
16512
|
-
|
|
16513
|
-
|
|
16514
|
-
|
|
16515
|
-
|
|
16516
|
-
|
|
16517
|
-
|
|
16518
|
-
|
|
16519
|
-
|
|
16520
|
-
|
|
16521
|
-
|
|
16522
|
-
|
|
16661
|
+
// src/lib/hook-runtime.ts
|
|
16662
|
+
var HOOK_RUNTIME_SCHEMA_VERSION = 1;
|
|
16663
|
+
var DIRECTORY_MODE2 = 448;
|
|
16664
|
+
var DATA_FILE_MODE = 384;
|
|
16665
|
+
var LAUNCHER_MODE = 448;
|
|
16666
|
+
var RELEASE_PREFIX = "release-";
|
|
16667
|
+
var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
|
|
16668
|
+
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
16669
|
+
var MAX_RELEASES = 8;
|
|
16670
|
+
var MAX_RELEASE_DELETIONS_PER_STAGE = 8;
|
|
16671
|
+
var RETAIN_PREDECESSORS = 2;
|
|
16672
|
+
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
16673
|
+
var HOOK_RUNTIME_ENTRIES = {
|
|
16674
|
+
// SessionStart self-healing resolves this exact CLI entry to run
|
|
16675
|
+
// `daemon ensure`; it must travel with the immutable hook release.
|
|
16676
|
+
prim: "dist/index.js",
|
|
16677
|
+
"prim-hook": "dist/hooks/prim-hook.js",
|
|
16678
|
+
"prim-pre-commit": "dist/hooks/pre-commit.js",
|
|
16679
|
+
"prim-post-commit": "dist/hooks/post-commit.js",
|
|
16680
|
+
"prim-post-rewrite": "dist/hooks/post-rewrite.js",
|
|
16681
|
+
"prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
|
|
16682
|
+
"prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
|
|
16683
|
+
"prim-post-tool-use": "dist/hooks/post-tool-use.js",
|
|
16684
|
+
"prim-session-start": "dist/hooks/session-start.js",
|
|
16685
|
+
"prim-session-end": "dist/hooks/session-end.js",
|
|
16686
|
+
"prim-daemon-server": "dist/daemon/server.js",
|
|
16687
|
+
"prim-statusline": "dist/statusline-main.js"
|
|
16523
16688
|
};
|
|
16524
|
-
|
|
16525
|
-
|
|
16526
|
-
|
|
16527
|
-
|
|
16528
|
-
|
|
16529
|
-
|
|
16530
|
-
function
|
|
16531
|
-
const
|
|
16532
|
-
|
|
16533
|
-
|
|
16689
|
+
var SOURCE_ENTRIES = Object.fromEntries(
|
|
16690
|
+
Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
|
|
16691
|
+
bin,
|
|
16692
|
+
target.replace(/^dist\//u, "")
|
|
16693
|
+
])
|
|
16694
|
+
);
|
|
16695
|
+
function hookRuntimePaths(options = {}) {
|
|
16696
|
+
const env4 = options.env ?? process.env;
|
|
16697
|
+
const configDir = primConfigDirectory({
|
|
16698
|
+
...options,
|
|
16699
|
+
env: env4,
|
|
16700
|
+
homeDir: options.homeDir ?? env4.HOME ?? ""
|
|
16534
16701
|
});
|
|
16535
|
-
|
|
16536
|
-
|
|
16537
|
-
|
|
16538
|
-
|
|
16702
|
+
const runtimeDir = join5(configDir, "hook-runtime");
|
|
16703
|
+
return {
|
|
16704
|
+
configDir,
|
|
16705
|
+
launcher: join5(configDir, STABLE_HOOK_LAUNCHER_NAME),
|
|
16706
|
+
gitHookEntrypoint: join5(configDir, GIT_HOOK_ENTRYPOINT_NAME),
|
|
16707
|
+
runtimeDir,
|
|
16708
|
+
releasesDir: join5(runtimeDir, "releases"),
|
|
16709
|
+
current: join5(runtimeDir, "current"),
|
|
16710
|
+
selectionLock: join5(runtimeDir, "selection.lock")
|
|
16711
|
+
};
|
|
16539
16712
|
}
|
|
16540
|
-
function
|
|
16541
|
-
|
|
16542
|
-
throw new WorkosConnectProtocolError("invalid_response", `${field} is invalid`);
|
|
16543
|
-
}
|
|
16544
|
-
return value;
|
|
16713
|
+
function sha256(path9) {
|
|
16714
|
+
return createHash("sha256").update(readFileSync3(path9)).digest("hex");
|
|
16545
16715
|
}
|
|
16546
|
-
function
|
|
16547
|
-
|
|
16548
|
-
|
|
16716
|
+
function exactManifest(manifest) {
|
|
16717
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
16718
|
+
`;
|
|
16719
|
+
}
|
|
16720
|
+
function exactKeys(value, expected) {
|
|
16721
|
+
const actual = Object.keys(value).sort();
|
|
16722
|
+
const wanted = [...expected].sort();
|
|
16723
|
+
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
16724
|
+
}
|
|
16725
|
+
function releaseId(manifest) {
|
|
16726
|
+
return createHash("sha256").update(exactManifest(manifest)).digest("hex");
|
|
16727
|
+
}
|
|
16728
|
+
function runtimePackageJson(manifest) {
|
|
16729
|
+
return `${JSON.stringify(
|
|
16730
|
+
{
|
|
16731
|
+
name: "@primitive.ai/prim",
|
|
16732
|
+
version: manifest.version,
|
|
16733
|
+
type: "module",
|
|
16734
|
+
bin: HOOK_RUNTIME_ENTRIES
|
|
16735
|
+
},
|
|
16736
|
+
null,
|
|
16737
|
+
2
|
|
16738
|
+
)}
|
|
16739
|
+
`;
|
|
16740
|
+
}
|
|
16741
|
+
function validateRelease(releaseDir, manifest) {
|
|
16549
16742
|
try {
|
|
16550
|
-
|
|
16743
|
+
if (!directReleaseLayout(releaseDir, manifest)) return false;
|
|
16744
|
+
if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
|
|
16745
|
+
return false;
|
|
16746
|
+
}
|
|
16747
|
+
if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
|
|
16748
|
+
return false;
|
|
16749
|
+
}
|
|
16750
|
+
if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
|
|
16751
|
+
`) {
|
|
16752
|
+
return false;
|
|
16753
|
+
}
|
|
16754
|
+
for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
16755
|
+
const target = join5(releaseDir, relativePath);
|
|
16756
|
+
if (sha256(target) !== manifest.files[bin]) return false;
|
|
16757
|
+
}
|
|
16758
|
+
for (const [path9, digest3] of Object.entries(manifest.native ?? {})) {
|
|
16759
|
+
if (sha256(join5(releaseDir, path9)) !== digest3) return false;
|
|
16760
|
+
}
|
|
16761
|
+
return true;
|
|
16551
16762
|
} catch {
|
|
16552
|
-
|
|
16553
|
-
}
|
|
16554
|
-
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash || parsed.origin !== issuer) {
|
|
16555
|
-
throw new WorkosConnectProtocolError("invalid_response", "issuer must be an HTTPS origin");
|
|
16763
|
+
return false;
|
|
16556
16764
|
}
|
|
16557
|
-
return issuer;
|
|
16558
16765
|
}
|
|
16559
|
-
function
|
|
16560
|
-
const raw = exactString(value, field, MAX_URL_LENGTH);
|
|
16561
|
-
let parsed;
|
|
16766
|
+
function directReleaseLayout(releaseDir, manifest) {
|
|
16562
16767
|
try {
|
|
16563
|
-
|
|
16768
|
+
const directories = /* @__PURE__ */ new Set([releaseDir]);
|
|
16769
|
+
for (const relativePath of [
|
|
16770
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
16771
|
+
...Object.keys(manifest.native ?? {})
|
|
16772
|
+
]) {
|
|
16773
|
+
for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
|
|
16774
|
+
directories.add(join5(releaseDir, directory));
|
|
16775
|
+
}
|
|
16776
|
+
}
|
|
16777
|
+
if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
|
|
16778
|
+
const files = [
|
|
16779
|
+
"manifest.json",
|
|
16780
|
+
"package.json",
|
|
16781
|
+
"node",
|
|
16782
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
16783
|
+
...Object.keys(manifest.native ?? {})
|
|
16784
|
+
];
|
|
16785
|
+
const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path9) => join5(releaseDir, path9))]);
|
|
16786
|
+
if (![...directories].every(
|
|
16787
|
+
(directory) => readdirSync(directory).every((name2) => owned.has(join5(directory, name2)))
|
|
16788
|
+
))
|
|
16789
|
+
return false;
|
|
16790
|
+
return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
|
|
16564
16791
|
} catch {
|
|
16565
|
-
|
|
16566
|
-
}
|
|
16567
|
-
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.origin !== issuer) {
|
|
16568
|
-
throw new WorkosConnectProtocolError("invalid_response", `${field} is not trusted`);
|
|
16792
|
+
return false;
|
|
16569
16793
|
}
|
|
16570
|
-
return parsed.toString();
|
|
16571
16794
|
}
|
|
16572
|
-
function
|
|
16573
|
-
|
|
16574
|
-
|
|
16575
|
-
|
|
16576
|
-
|
|
16577
|
-
|
|
16578
|
-
|
|
16579
|
-
|
|
16580
|
-
|
|
16581
|
-
|
|
16795
|
+
function readReleaseManifest(releaseDir, releaseName) {
|
|
16796
|
+
try {
|
|
16797
|
+
const manifestPath2 = join5(releaseDir, "manifest.json");
|
|
16798
|
+
const manifestStat = statSync2(manifestPath2);
|
|
16799
|
+
if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
|
|
16800
|
+
const raw = readFileSync3(manifestPath2, "utf8");
|
|
16801
|
+
const parsed = JSON.parse(raw);
|
|
16802
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
16803
|
+
if (!exactKeys(parsed, [
|
|
16804
|
+
"schemaVersion",
|
|
16805
|
+
"version",
|
|
16806
|
+
"nodePath",
|
|
16807
|
+
"files",
|
|
16808
|
+
..."native" in parsed ? ["native"] : []
|
|
16809
|
+
]))
|
|
16810
|
+
return null;
|
|
16811
|
+
const candidate = parsed;
|
|
16812
|
+
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(
|
|
16813
|
+
(digest3) => typeof digest3 !== "string" || !/^[0-9a-f]{64}$/u.test(digest3)
|
|
16814
|
+
)) {
|
|
16815
|
+
return null;
|
|
16816
|
+
}
|
|
16817
|
+
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(
|
|
16818
|
+
(digest3) => typeof digest3 !== "string" || !/^[a-f0-9]{64}$/u.test(digest3)
|
|
16819
|
+
)))
|
|
16820
|
+
return null;
|
|
16821
|
+
const manifest = candidate;
|
|
16822
|
+
if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
|
|
16823
|
+
return null;
|
|
16824
|
+
}
|
|
16825
|
+
return manifest;
|
|
16826
|
+
} catch {
|
|
16827
|
+
return null;
|
|
16582
16828
|
}
|
|
16583
|
-
return {
|
|
16584
|
-
issuer,
|
|
16585
|
-
clientId,
|
|
16586
|
-
scopes: [...WORKOS_CONNECT_DEFAULT_SCOPES]
|
|
16587
|
-
};
|
|
16588
16829
|
}
|
|
16589
|
-
function
|
|
16590
|
-
|
|
16591
|
-
|
|
16592
|
-
|
|
16830
|
+
function readSelectedRelease(paths) {
|
|
16831
|
+
let raw;
|
|
16832
|
+
try {
|
|
16833
|
+
raw = readFileSync3(paths.current, "utf8");
|
|
16834
|
+
} catch (error) {
|
|
16835
|
+
if (error.code === "ENOENT") return null;
|
|
16836
|
+
throw error;
|
|
16593
16837
|
}
|
|
16594
|
-
const
|
|
16595
|
-
|
|
16596
|
-
|
|
16597
|
-
|
|
16598
|
-
if (!CONNECT_CLIENT_ID_PATTERN.test(clientId)) {
|
|
16599
|
-
throw new WorkosConnectProtocolError("invalid_metadata", "credential clientId is invalid");
|
|
16838
|
+
const name2 = raw.endsWith("\n") ? raw.slice(0, -1) : "";
|
|
16839
|
+
if (`${name2}
|
|
16840
|
+
` !== raw || !RELEASE_NAME_RE.test(name2)) {
|
|
16841
|
+
throw new Error("cannot stage hook runtime: selected release is malformed");
|
|
16600
16842
|
}
|
|
16601
|
-
|
|
16602
|
-
|
|
16603
|
-
|
|
16604
|
-
|
|
16605
|
-
);
|
|
16843
|
+
const dir = join5(paths.releasesDir, name2);
|
|
16844
|
+
const manifest = readReleaseManifest(dir, name2);
|
|
16845
|
+
if (!manifest) {
|
|
16846
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
16606
16847
|
}
|
|
16607
|
-
|
|
16608
|
-
|
|
16609
|
-
|
|
16610
|
-
|
|
16611
|
-
);
|
|
16848
|
+
return { name: name2, dir, manifest };
|
|
16849
|
+
}
|
|
16850
|
+
function selectedHookRuntimeKeyringLoader(options = {}) {
|
|
16851
|
+
try {
|
|
16852
|
+
const selected = readSelectedRelease(hookRuntimePaths(options));
|
|
16853
|
+
if (!selected?.manifest.native) return void 0;
|
|
16854
|
+
const loader = join5(selected.dir, "native", "keyring.cjs");
|
|
16855
|
+
return existsSync4(loader) ? loader : void 0;
|
|
16856
|
+
} catch {
|
|
16857
|
+
return void 0;
|
|
16612
16858
|
}
|
|
16613
|
-
return {
|
|
16614
|
-
version: 1,
|
|
16615
|
-
family: "workos_connect",
|
|
16616
|
-
issuer,
|
|
16617
|
-
clientId,
|
|
16618
|
-
accessTokenHash,
|
|
16619
|
-
refreshTokenHash
|
|
16620
|
-
};
|
|
16621
16859
|
}
|
|
16622
|
-
|
|
16623
|
-
|
|
16624
|
-
|
|
16625
|
-
|
|
16626
|
-
|
|
16860
|
+
function releaseEntries(paths) {
|
|
16861
|
+
return readdirSync(paths.releasesDir, { withFileTypes: true }).flatMap((entry) => {
|
|
16862
|
+
if (!entry.isDirectory() || !RELEASE_NAME_RE.test(entry.name)) return [];
|
|
16863
|
+
const dir = join5(paths.releasesDir, entry.name);
|
|
16864
|
+
try {
|
|
16865
|
+
return [{ name: entry.name, dir, mtimeMs: statSync2(dir).mtimeMs }];
|
|
16866
|
+
} catch {
|
|
16867
|
+
return [];
|
|
16627
16868
|
}
|
|
16869
|
+
});
|
|
16870
|
+
}
|
|
16871
|
+
function pruneReleases(paths, protectedNames, reserveSlots, now) {
|
|
16872
|
+
const entries = releaseEntries(paths).sort(
|
|
16873
|
+
(left, right) => right.mtimeMs - left.mtimeMs || left.name.localeCompare(right.name)
|
|
16874
|
+
);
|
|
16875
|
+
const protectedWithPredecessors = new Set(protectedNames);
|
|
16876
|
+
for (const entry of entries) {
|
|
16877
|
+
if (protectedWithPredecessors.size >= protectedNames.size + RETAIN_PREDECESSORS) break;
|
|
16878
|
+
if (!protectedWithPredecessors.has(entry.name)) protectedWithPredecessors.add(entry.name);
|
|
16628
16879
|
}
|
|
16629
|
-
|
|
16630
|
-
|
|
16631
|
-
|
|
16632
|
-
|
|
16633
|
-
|
|
16634
|
-
|
|
16635
|
-
|
|
16636
|
-
|
|
16637
|
-
|
|
16638
|
-
|
|
16639
|
-
|
|
16640
|
-
|
|
16641
|
-
await reader.cancel();
|
|
16642
|
-
throw new WorkosConnectProtocolError("invalid_response", "response body is too large");
|
|
16643
|
-
}
|
|
16644
|
-
chunks.push(result.value);
|
|
16645
|
-
}
|
|
16646
|
-
} finally {
|
|
16647
|
-
reader.releaseLock();
|
|
16648
|
-
}
|
|
16649
|
-
const bytes = new Uint8Array(total);
|
|
16650
|
-
let offset = 0;
|
|
16651
|
-
for (const chunk2 of chunks) {
|
|
16652
|
-
bytes.set(chunk2, offset);
|
|
16653
|
-
offset += chunk2.byteLength;
|
|
16880
|
+
const candidates = entries.filter(
|
|
16881
|
+
(entry) => !protectedWithPredecessors.has(entry.name) && now - entry.mtimeMs >= RELEASE_GRACE_MS
|
|
16882
|
+
).sort((left, right) => left.mtimeMs - right.mtimeMs || left.name.localeCompare(right.name));
|
|
16883
|
+
let remaining = entries.length;
|
|
16884
|
+
let deleted = 0;
|
|
16885
|
+
for (const entry of candidates) {
|
|
16886
|
+
if (remaining + reserveSlots <= MAX_RELEASES || deleted >= MAX_RELEASE_DELETIONS_PER_STAGE) {
|
|
16887
|
+
break;
|
|
16888
|
+
}
|
|
16889
|
+
rmSync3(entry.dir, { recursive: true, force: true });
|
|
16890
|
+
remaining -= 1;
|
|
16891
|
+
deleted += 1;
|
|
16654
16892
|
}
|
|
16655
|
-
|
|
16656
|
-
|
|
16657
|
-
|
|
16658
|
-
|
|
16659
|
-
} catch {
|
|
16660
|
-
throw new WorkosConnectProtocolError("invalid_response", "response body is not valid JSON");
|
|
16893
|
+
if (remaining + reserveSlots > MAX_RELEASES) {
|
|
16894
|
+
throw new Error(
|
|
16895
|
+
"cannot stage hook runtime: release retention is full while recent runtimes are protected"
|
|
16896
|
+
);
|
|
16661
16897
|
}
|
|
16662
16898
|
}
|
|
16663
|
-
|
|
16664
|
-
const
|
|
16665
|
-
|
|
16666
|
-
|
|
16667
|
-
|
|
16668
|
-
|
|
16669
|
-
|
|
16670
|
-
);
|
|
16899
|
+
function sourceManifest(sourceDir, version, nodePath) {
|
|
16900
|
+
const files = {};
|
|
16901
|
+
for (const [bin, relativePath] of Object.entries(SOURCE_ENTRIES)) {
|
|
16902
|
+
const source = join5(sourceDir, relativePath);
|
|
16903
|
+
if (!existsSync4(source) || !statSync2(source).isFile()) {
|
|
16904
|
+
throw new Error(`cannot stage hook runtime: missing self-contained ${bin} bundle`);
|
|
16905
|
+
}
|
|
16906
|
+
files[bin] = sha256(source);
|
|
16671
16907
|
}
|
|
16672
16908
|
return {
|
|
16673
|
-
|
|
16674
|
-
|
|
16675
|
-
|
|
16676
|
-
|
|
16909
|
+
schemaVersion: HOOK_RUNTIME_SCHEMA_VERSION,
|
|
16910
|
+
version,
|
|
16911
|
+
nodePath,
|
|
16912
|
+
files,
|
|
16913
|
+
native: {
|
|
16914
|
+
"native/keyring.cjs": createHash("sha256").update(KEYRING_LOADER).digest("hex"),
|
|
16915
|
+
"native/keyring.node": sha256(keyringNativeBinary())
|
|
16916
|
+
}
|
|
16677
16917
|
};
|
|
16678
16918
|
}
|
|
16679
|
-
|
|
16680
|
-
|
|
16919
|
+
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
16920
|
+
set -eu
|
|
16921
|
+
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
16922
|
+
IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
|
|
16923
|
+
case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
|
|
16924
|
+
prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
|
|
16925
|
+
case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
|
|
16926
|
+
[ "\${#prim_release_id}" -eq 64 ] || exit 69
|
|
16927
|
+
prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
|
|
16928
|
+
case "\${1-}" in
|
|
16929
|
+
${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
|
|
16930
|
+
*) exit 64 ;;
|
|
16931
|
+
esac
|
|
16932
|
+
shift
|
|
16933
|
+
IFS= read -r prim_node < "$prim_release/node" || exit 69
|
|
16934
|
+
case "$prim_node" in /*) ;; *) exit 69 ;; esac
|
|
16935
|
+
[ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
|
|
16936
|
+
exec "$prim_node" "$prim_entry" "$@"
|
|
16937
|
+
`;
|
|
16938
|
+
function privateDirectory(path9) {
|
|
16939
|
+
const stat = lstatIfPresent(path9);
|
|
16940
|
+
if (!stat?.isDirectory()) return false;
|
|
16941
|
+
if (process.platform === "win32") return true;
|
|
16942
|
+
const uid = process.getuid?.();
|
|
16943
|
+
return (Number(stat.mode) & 511) === DIRECTORY_MODE2 && (uid === void 0 || stat.uid === uid);
|
|
16681
16944
|
}
|
|
16682
|
-
|
|
16683
|
-
const
|
|
16684
|
-
|
|
16685
|
-
|
|
16686
|
-
|
|
16687
|
-
|
|
16688
|
-
|
|
16689
|
-
|
|
16690
|
-
|
|
16691
|
-
|
|
16692
|
-
|
|
16693
|
-
|
|
16694
|
-
|
|
16695
|
-
|
|
16696
|
-
|
|
16697
|
-
|
|
16698
|
-
`Device authorization returned HTTP ${response.status}`
|
|
16699
|
-
);
|
|
16945
|
+
function privateFile(path9, mode) {
|
|
16946
|
+
const stat = lstatIfPresent(path9);
|
|
16947
|
+
if (!stat?.isFile()) return false;
|
|
16948
|
+
if (process.platform === "win32") return true;
|
|
16949
|
+
const uid = process.getuid?.();
|
|
16950
|
+
return (Number(stat.mode) & 511) === mode && (uid === void 0 || stat.uid === uid);
|
|
16951
|
+
}
|
|
16952
|
+
function hasSafeRuntimeLayout(paths, selected) {
|
|
16953
|
+
const releaseDirectories = /* @__PURE__ */ new Set([selected.dir]);
|
|
16954
|
+
for (const relativePath of [
|
|
16955
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
16956
|
+
...Object.keys(selected.manifest.native ?? {})
|
|
16957
|
+
]) {
|
|
16958
|
+
for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
|
|
16959
|
+
releaseDirectories.add(join5(selected.dir, directory));
|
|
16960
|
+
}
|
|
16700
16961
|
}
|
|
16701
|
-
|
|
16702
|
-
|
|
16703
|
-
|
|
16704
|
-
|
|
16705
|
-
|
|
16706
|
-
|
|
16707
|
-
|
|
16708
|
-
deviceCode: exactString(record3.device_code, "device_code", MAX_DEVICE_CODE_LENGTH),
|
|
16709
|
-
userCode: exactString(record3.user_code, "user_code", MAX_USER_CODE_LENGTH),
|
|
16710
|
-
verificationUri,
|
|
16711
|
-
verificationUriComplete: record3.verification_uri_complete === void 0 ? void 0 : sameIssuerUrl(
|
|
16712
|
-
record3.verification_uri_complete,
|
|
16713
|
-
"verification_uri_complete",
|
|
16714
|
-
configuration.issuer
|
|
16715
|
-
),
|
|
16716
|
-
expiresIn: safeInteger(record3.expires_in, "expires_in", 1, MAX_DEVICE_LIFETIME_SECONDS),
|
|
16717
|
-
interval: safeInteger(record3.interval ?? 5, "interval", 1, MAX_INTERVAL_SECONDS)
|
|
16718
|
-
};
|
|
16962
|
+
if (!privateDirectory(paths.configDir) || !privateDirectory(paths.runtimeDir) || !privateDirectory(paths.releasesDir) || ![...releaseDirectories].every(privateDirectory) || !privateFile(paths.launcher, LAUNCHER_MODE) || !privateFile(paths.current, DATA_FILE_MODE) || !privateFile(join5(selected.dir, "manifest.json"), DATA_FILE_MODE) || !privateFile(join5(selected.dir, "package.json"), DATA_FILE_MODE) || !privateFile(join5(selected.dir, "node"), DATA_FILE_MODE)) {
|
|
16963
|
+
return false;
|
|
16964
|
+
}
|
|
16965
|
+
return [
|
|
16966
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
16967
|
+
...Object.keys(selected.manifest.native ?? {})
|
|
16968
|
+
].every((relativePath) => privateFile(join5(selected.dir, relativePath), DATA_FILE_MODE));
|
|
16719
16969
|
}
|
|
16720
|
-
function
|
|
16721
|
-
|
|
16722
|
-
|
|
16723
|
-
|
|
16724
|
-
|
|
16725
|
-
|
|
16726
|
-
|
|
16727
|
-
|
|
16728
|
-
return {
|
|
16729
|
-
accessToken,
|
|
16730
|
-
refreshToken: refreshToken3,
|
|
16731
|
-
expiresIn: record3.expires_in === void 0 ? void 0 : safeInteger(record3.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
16732
|
-
};
|
|
16970
|
+
function sameNodeExecutable(recorded, desired) {
|
|
16971
|
+
try {
|
|
16972
|
+
if (!statSync2(recorded).isFile()) return false;
|
|
16973
|
+
accessSync(recorded, constants2.X_OK);
|
|
16974
|
+
return realpathSync(recorded) === realpathSync(desired);
|
|
16975
|
+
} catch {
|
|
16976
|
+
return false;
|
|
16977
|
+
}
|
|
16733
16978
|
}
|
|
16734
|
-
function
|
|
16735
|
-
|
|
16736
|
-
return exactString(error, "error", MAX_USER_CODE_LENGTH);
|
|
16979
|
+
function recordedNodeMatchesCurrentProcess(nodePath) {
|
|
16980
|
+
return sameNodeExecutable(nodePath, process.execPath);
|
|
16737
16981
|
}
|
|
16738
|
-
|
|
16739
|
-
|
|
16740
|
-
|
|
16741
|
-
|
|
16742
|
-
|
|
16982
|
+
function inspectHookRuntime(options = {}) {
|
|
16983
|
+
let paths;
|
|
16984
|
+
try {
|
|
16985
|
+
paths = hookRuntimePaths(options);
|
|
16986
|
+
} catch {
|
|
16987
|
+
return { state: "invalid" };
|
|
16988
|
+
}
|
|
16989
|
+
const launcher = lstatIfPresent(paths.launcher);
|
|
16990
|
+
const selector = lstatIfPresent(paths.current);
|
|
16991
|
+
if (!(launcher || selector)) return { state: "missing" };
|
|
16992
|
+
if (!(launcher && selector)) return { state: "invalid" };
|
|
16993
|
+
try {
|
|
16994
|
+
if (readFileSync3(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT) {
|
|
16995
|
+
return { state: "invalid" };
|
|
16743
16996
|
}
|
|
16744
|
-
const
|
|
16745
|
-
|
|
16746
|
-
|
|
16747
|
-
};
|
|
16748
|
-
|
|
16749
|
-
|
|
16750
|
-
|
|
16751
|
-
|
|
16752
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
16753
|
-
});
|
|
16997
|
+
const selected = readSelectedRelease(paths);
|
|
16998
|
+
if (!selected) return { state: "invalid" };
|
|
16999
|
+
assertOwnedHookRuntime(paths);
|
|
17000
|
+
if (!hasSafeRuntimeLayout(paths, selected)) return { state: "invalid" };
|
|
17001
|
+
return recordedNodeMatchesCurrentProcess(selected.manifest.nodePath) ? { state: "ready", version: selected.manifest.version } : { state: "invalid" };
|
|
17002
|
+
} catch {
|
|
17003
|
+
return { state: "invalid" };
|
|
17004
|
+
}
|
|
16754
17005
|
}
|
|
16755
|
-
|
|
16756
|
-
const
|
|
16757
|
-
|
|
16758
|
-
|
|
16759
|
-
|
|
16760
|
-
|
|
16761
|
-
|
|
16762
|
-
|
|
16763
|
-
|
|
16764
|
-
|
|
16765
|
-
let response;
|
|
16766
|
-
try {
|
|
16767
|
-
response = await fetchImpl(workosConnectTokenEndpoint(configuration.issuer), {
|
|
16768
|
-
method: "POST",
|
|
16769
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
16770
|
-
body: new URLSearchParams({
|
|
16771
|
-
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
16772
|
-
device_code: authorization.deviceCode,
|
|
16773
|
-
client_id: configuration.clientId
|
|
16774
|
-
}),
|
|
16775
|
-
signal: AbortSignal.any([signal, AbortSignal.timeout(POLL_REQUEST_TIMEOUT_MS)])
|
|
16776
|
-
});
|
|
16777
|
-
} catch (error2) {
|
|
16778
|
-
if (signal.aborted) {
|
|
16779
|
-
throw new WorkosConnectProtocolError("expired_token", "Device authorization expired");
|
|
17006
|
+
function writeRelease(sourceDir, releaseDir, manifest, releasesDir) {
|
|
17007
|
+
const stagingDir = mkdtempSync(join5(releasesDir, ".stage-"));
|
|
17008
|
+
chmodSync(stagingDir, DIRECTORY_MODE2);
|
|
17009
|
+
try {
|
|
17010
|
+
const directories = /* @__PURE__ */ new Set([stagingDir]);
|
|
17011
|
+
const syncStagedFile = (path9) => {
|
|
17012
|
+
syncFile(path9);
|
|
17013
|
+
for (let directory = dirname5(path9); ; directory = dirname5(directory)) {
|
|
17014
|
+
directories.add(directory);
|
|
17015
|
+
if (directory === stagingDir) break;
|
|
16780
17016
|
}
|
|
16781
|
-
|
|
17017
|
+
};
|
|
17018
|
+
for (const [bin, targetRelative] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
17019
|
+
const source = join5(sourceDir, SOURCE_ENTRIES[bin]);
|
|
17020
|
+
const target = join5(stagingDir, targetRelative);
|
|
17021
|
+
mkdirSync3(dirname5(target), { recursive: true, mode: DIRECTORY_MODE2 });
|
|
17022
|
+
chmodSync(dirname5(target), DIRECTORY_MODE2);
|
|
17023
|
+
copyFileSync(source, target);
|
|
17024
|
+
chmodSync(target, DATA_FILE_MODE);
|
|
17025
|
+
if (sha256(target) !== manifest.files[bin]) {
|
|
17026
|
+
throw new Error(`cannot stage hook runtime: ${bin} changed while it was copied`);
|
|
17027
|
+
}
|
|
17028
|
+
syncStagedFile(target);
|
|
16782
17029
|
}
|
|
16783
|
-
|
|
16784
|
-
|
|
16785
|
-
|
|
16786
|
-
|
|
16787
|
-
|
|
16788
|
-
|
|
16789
|
-
|
|
17030
|
+
if (manifest.native) {
|
|
17031
|
+
const nativeDir = join5(stagingDir, "native");
|
|
17032
|
+
mkdirSync3(nativeDir, { mode: DIRECTORY_MODE2 });
|
|
17033
|
+
writeFileSync4(join5(nativeDir, "keyring.cjs"), KEYRING_LOADER, { mode: DATA_FILE_MODE });
|
|
17034
|
+
copyFileSync(keyringNativeBinary(), join5(nativeDir, "keyring.node"));
|
|
17035
|
+
chmodSync(join5(nativeDir, "keyring.node"), DATA_FILE_MODE);
|
|
17036
|
+
for (const [path9, digest3] of Object.entries(manifest.native)) {
|
|
17037
|
+
const target = join5(stagingDir, path9);
|
|
17038
|
+
if (sha256(target) !== digest3)
|
|
17039
|
+
throw new Error("Native credential store changed while copying");
|
|
17040
|
+
syncStagedFile(target);
|
|
17041
|
+
}
|
|
16790
17042
|
}
|
|
16791
|
-
|
|
16792
|
-
|
|
17043
|
+
const nodePath = join5(stagingDir, "node");
|
|
17044
|
+
writeFileSync4(nodePath, `${manifest.nodePath}
|
|
17045
|
+
`, {
|
|
17046
|
+
encoding: "utf8",
|
|
17047
|
+
flag: "wx",
|
|
17048
|
+
mode: DATA_FILE_MODE
|
|
17049
|
+
});
|
|
17050
|
+
syncStagedFile(nodePath);
|
|
17051
|
+
const packageJsonPath = join5(stagingDir, "package.json");
|
|
17052
|
+
writeFileSync4(packageJsonPath, runtimePackageJson(manifest), {
|
|
17053
|
+
encoding: "utf8",
|
|
17054
|
+
flag: "wx",
|
|
17055
|
+
mode: DATA_FILE_MODE
|
|
17056
|
+
});
|
|
17057
|
+
syncStagedFile(packageJsonPath);
|
|
17058
|
+
const manifestPath2 = join5(stagingDir, "manifest.json");
|
|
17059
|
+
writeFileSync4(manifestPath2, exactManifest(manifest), {
|
|
17060
|
+
encoding: "utf8",
|
|
17061
|
+
flag: "wx",
|
|
17062
|
+
mode: DATA_FILE_MODE
|
|
17063
|
+
});
|
|
17064
|
+
syncStagedFile(manifestPath2);
|
|
17065
|
+
for (const directory of [...directories].sort((left, right) => right.length - left.length)) {
|
|
17066
|
+
syncDirectory(directory);
|
|
16793
17067
|
}
|
|
16794
|
-
|
|
16795
|
-
|
|
16796
|
-
|
|
16797
|
-
|
|
16798
|
-
|
|
16799
|
-
|
|
16800
|
-
|
|
16801
|
-
|
|
16802
|
-
|
|
16803
|
-
|
|
16804
|
-
this.terminal = terminal;
|
|
16805
|
-
this.retryAt = retryAt;
|
|
16806
|
-
this.name = "MachineAuthError";
|
|
17068
|
+
try {
|
|
17069
|
+
renameSync2(stagingDir, releaseDir);
|
|
17070
|
+
} catch (error) {
|
|
17071
|
+
const code = error.code;
|
|
17072
|
+
if (code !== "EEXIST" && code !== "ENOTEMPTY" || !validateRelease(releaseDir, manifest)) {
|
|
17073
|
+
throw error;
|
|
17074
|
+
}
|
|
17075
|
+
}
|
|
17076
|
+
} finally {
|
|
17077
|
+
rmSync3(stagingDir, { recursive: true, force: true });
|
|
16807
17078
|
}
|
|
16808
|
-
};
|
|
16809
|
-
function machineRetryAt(response, now = Date.now()) {
|
|
16810
|
-
const value = response.headers.get("Retry-After")?.trim();
|
|
16811
|
-
if (!value || value.length > 128) return void 0;
|
|
16812
|
-
const timestamp2 = /^\d+$/u.test(value) ? now + Number(value) * 1e3 : Date.parse(value);
|
|
16813
|
-
return Number.isSafeInteger(timestamp2) && timestamp2 > now ? timestamp2 : void 0;
|
|
16814
|
-
}
|
|
16815
|
-
function machineString(value, maximum = 4096) {
|
|
16816
|
-
return typeof value === "string" && value.length > 0 && value.length <= maximum && value.trim() === value && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
16817
17079
|
}
|
|
16818
|
-
function
|
|
16819
|
-
|
|
16820
|
-
|
|
17080
|
+
function stableNodePath(execPath = process.execPath, searchPath = process.env.PATH ?? "") {
|
|
17081
|
+
let target;
|
|
17082
|
+
try {
|
|
17083
|
+
target = realpathSync(execPath);
|
|
17084
|
+
} catch {
|
|
17085
|
+
return execPath;
|
|
16821
17086
|
}
|
|
16822
|
-
|
|
16823
|
-
|
|
16824
|
-
|
|
16825
|
-
|
|
16826
|
-
|
|
16827
|
-
|
|
16828
|
-
|
|
17087
|
+
for (const directory of searchPath.split(delimiter)) {
|
|
17088
|
+
if (!isAbsolute3(directory)) continue;
|
|
17089
|
+
const candidate = join5(directory, "node");
|
|
17090
|
+
try {
|
|
17091
|
+
if (realpathSync(candidate) === target) return candidate;
|
|
17092
|
+
} catch {
|
|
17093
|
+
}
|
|
16829
17094
|
}
|
|
16830
|
-
return
|
|
17095
|
+
return execPath;
|
|
16831
17096
|
}
|
|
16832
|
-
function
|
|
16833
|
-
const
|
|
16834
|
-
|
|
16835
|
-
|
|
17097
|
+
function stageHookRuntime(options = {}) {
|
|
17098
|
+
const root = packageRoot();
|
|
17099
|
+
const sourceDir = options.sourceDir ?? (root ? join5(root, "dist", "hook-runtime") : null);
|
|
17100
|
+
const version = options.version ?? packageVersion();
|
|
17101
|
+
const nodePath = resolve(options.nodePath ?? stableNodePath());
|
|
17102
|
+
if (!sourceDir || !version || compareSemver(version, version) !== 0 || !isAbsolute3(nodePath) || /[\r\n]/u.test(nodePath)) {
|
|
17103
|
+
throw new Error("cannot stage hook runtime: package identity is unavailable");
|
|
16836
17104
|
}
|
|
16837
|
-
const
|
|
16838
|
-
|
|
16839
|
-
|
|
16840
|
-
|
|
16841
|
-
|
|
17105
|
+
const manifest = sourceManifest(sourceDir, version, nodePath);
|
|
17106
|
+
const paths = hookRuntimePaths(options);
|
|
17107
|
+
const releaseName = `${RELEASE_PREFIX}${releaseId(manifest)}`;
|
|
17108
|
+
const releaseDir = join5(paths.releasesDir, releaseName);
|
|
17109
|
+
mkdirSync3(paths.releasesDir, { recursive: true, mode: DIRECTORY_MODE2 });
|
|
17110
|
+
chmodSync(paths.configDir, DIRECTORY_MODE2);
|
|
17111
|
+
chmodSync(paths.runtimeDir, DIRECTORY_MODE2);
|
|
17112
|
+
chmodSync(paths.releasesDir, DIRECTORY_MODE2);
|
|
17113
|
+
return withFileLockSync(paths.selectionLock, () => {
|
|
17114
|
+
const now = Date.now();
|
|
17115
|
+
const selected = readSelectedRelease(paths);
|
|
17116
|
+
if (selected) utimesSync(selected.dir, now / 1e3, now / 1e3);
|
|
17117
|
+
const precedence = selected ? compareSemver(selected.manifest.version, manifest.version) : -1;
|
|
17118
|
+
if (precedence === void 0) {
|
|
17119
|
+
throw new Error("cannot stage hook runtime: selected release version is malformed");
|
|
17120
|
+
}
|
|
17121
|
+
const selectRequested = !selected || precedence < 0 || precedence === 0 && !sameNodeExecutable(selected.manifest.nodePath, nodePath);
|
|
17122
|
+
const requestedExists = existsSync4(releaseDir);
|
|
17123
|
+
const protectedBefore = new Set(selected ? [selected.name] : []);
|
|
17124
|
+
if (selectRequested && requestedExists) protectedBefore.add(releaseName);
|
|
17125
|
+
pruneReleases(paths, protectedBefore, selectRequested && !requestedExists ? 1 : 0, now);
|
|
17126
|
+
if (selectRequested && !validateRelease(releaseDir, manifest)) {
|
|
17127
|
+
if (requestedExists) {
|
|
17128
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
17129
|
+
}
|
|
17130
|
+
writeRelease(sourceDir, releaseDir, manifest, paths.releasesDir);
|
|
17131
|
+
}
|
|
17132
|
+
const finalRelease = selectRequested ? { name: releaseName, dir: releaseDir, manifest } : selected;
|
|
17133
|
+
const launcherCurrent = (() => {
|
|
17134
|
+
try {
|
|
17135
|
+
return readFileSync3(paths.launcher, "utf8") === STABLE_HOOK_LAUNCHER_CONTENT;
|
|
17136
|
+
} catch {
|
|
17137
|
+
return false;
|
|
17138
|
+
}
|
|
17139
|
+
})();
|
|
17140
|
+
const selectorCurrent = selected?.name === finalRelease.name;
|
|
17141
|
+
if (!launcherCurrent) {
|
|
17142
|
+
atomicWriteFile(paths.launcher, STABLE_HOOK_LAUNCHER_CONTENT, {
|
|
17143
|
+
ensureParent: true,
|
|
17144
|
+
mode: LAUNCHER_MODE
|
|
17145
|
+
});
|
|
17146
|
+
}
|
|
17147
|
+
const entrypointCurrent = gitHookEntrypointCurrent(paths);
|
|
17148
|
+
if (!entrypointCurrent) {
|
|
17149
|
+
atomicWriteFile(paths.gitHookEntrypoint, GIT_HOOK_ENTRYPOINT_CONTENT, {
|
|
17150
|
+
ensureParent: true,
|
|
17151
|
+
mode: LAUNCHER_MODE
|
|
17152
|
+
});
|
|
17153
|
+
}
|
|
17154
|
+
if (!selectorCurrent) {
|
|
17155
|
+
syncDirectory(paths.releasesDir);
|
|
17156
|
+
atomicWriteFile(paths.current, `${finalRelease.name}
|
|
17157
|
+
`, {
|
|
17158
|
+
ensureParent: true,
|
|
17159
|
+
mode: DATA_FILE_MODE
|
|
17160
|
+
});
|
|
17161
|
+
}
|
|
17162
|
+
utimesSync(finalRelease.dir, now / 1e3, now / 1e3);
|
|
17163
|
+
pruneReleases(
|
|
17164
|
+
paths,
|
|
17165
|
+
/* @__PURE__ */ new Set([finalRelease.name, ...selected ? [selected.name] : []]),
|
|
17166
|
+
0,
|
|
17167
|
+
now
|
|
16842
17168
|
);
|
|
16843
|
-
|
|
16844
|
-
|
|
16845
|
-
|
|
16846
|
-
|
|
16847
|
-
|
|
16848
|
-
|
|
16849
|
-
}
|
|
16850
|
-
function rejectedCredentialsMessage(message, env4 = process.env) {
|
|
16851
|
-
return isClaudeCloudSession(env4) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
16852
|
-
}
|
|
16853
|
-
function machineSignal(signal) {
|
|
16854
|
-
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
17169
|
+
return {
|
|
17170
|
+
changed: !launcherCurrent || !entrypointCurrent || !selectorCurrent,
|
|
17171
|
+
releaseDir: finalRelease.dir,
|
|
17172
|
+
manifest: finalRelease.manifest,
|
|
17173
|
+
paths
|
|
17174
|
+
};
|
|
17175
|
+
});
|
|
16855
17176
|
}
|
|
16856
|
-
function
|
|
17177
|
+
function gitHookEntrypointCurrent(paths) {
|
|
16857
17178
|
try {
|
|
16858
|
-
return
|
|
17179
|
+
return readFileSync3(paths.gitHookEntrypoint, "utf8") === GIT_HOOK_ENTRYPOINT_CONTENT;
|
|
16859
17180
|
} catch {
|
|
16860
|
-
return
|
|
17181
|
+
return false;
|
|
16861
17182
|
}
|
|
16862
17183
|
}
|
|
16863
|
-
|
|
17184
|
+
function inspectGitHookEntrypoint(options = {}) {
|
|
17185
|
+
let paths;
|
|
16864
17186
|
try {
|
|
16865
|
-
|
|
17187
|
+
paths = hookRuntimePaths(options);
|
|
16866
17188
|
} catch {
|
|
16867
|
-
|
|
16868
|
-
throw new MachineAuthError(
|
|
16869
|
-
"authentication_unavailable",
|
|
16870
|
-
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
16871
|
-
// Primitive's are blocked by default: name the one that failed.
|
|
16872
|
-
isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
16873
|
-
);
|
|
17189
|
+
return "invalid";
|
|
16874
17190
|
}
|
|
16875
|
-
}
|
|
16876
|
-
async function readMachineJson(response, maximumBytes) {
|
|
16877
17191
|
try {
|
|
16878
|
-
|
|
17192
|
+
const entrypoint = lstatIfPresent(paths.gitHookEntrypoint);
|
|
17193
|
+
if (!entrypoint) return "missing";
|
|
17194
|
+
if (!entrypoint.isFile() || (Number(entrypoint.mode) & 64) === 0 || !gitHookEntrypointCurrent(paths) || readFileSync3(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT || !lstatIfPresent(paths.current)?.isFile()) {
|
|
17195
|
+
return "invalid";
|
|
17196
|
+
}
|
|
17197
|
+
return "ready";
|
|
16879
17198
|
} catch {
|
|
16880
|
-
|
|
17199
|
+
return "invalid";
|
|
16881
17200
|
}
|
|
16882
17201
|
}
|
|
16883
|
-
|
|
16884
|
-
|
|
16885
|
-
|
|
16886
|
-
|
|
16887
|
-
|
|
16888
|
-
|
|
16889
|
-
|
|
16890
|
-
|
|
16891
|
-
);
|
|
16892
|
-
if (!response.ok)
|
|
16893
|
-
throw new MachineAuthError(
|
|
16894
|
-
response.status === 404 ? "server_upgrade_required" : "discovery_unavailable",
|
|
16895
|
-
response.status === 404 ? "This server does not support machine authentication yet." : "Machine authentication discovery is unavailable."
|
|
16896
|
-
);
|
|
16897
|
-
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
17202
|
+
function lstatIfPresent(path9) {
|
|
17203
|
+
try {
|
|
17204
|
+
return lstatSync(path9);
|
|
17205
|
+
} catch (error) {
|
|
17206
|
+
const code = error.code;
|
|
17207
|
+
if (code === "ENOENT" || code === "ENOTDIR") return void 0;
|
|
17208
|
+
throw error;
|
|
17209
|
+
}
|
|
16898
17210
|
}
|
|
16899
|
-
|
|
16900
|
-
const
|
|
16901
|
-
if (
|
|
16902
|
-
throw new
|
|
16903
|
-
|
|
16904
|
-
"A machine client ID and secret are required.",
|
|
16905
|
-
true
|
|
17211
|
+
function assertOwnedHookRuntime(paths) {
|
|
17212
|
+
const entrypoint = lstatIfPresent(paths.gitHookEntrypoint);
|
|
17213
|
+
if (entrypoint && (!entrypoint.isFile() || !gitHookEntrypointCurrent(paths))) {
|
|
17214
|
+
throw new Error(
|
|
17215
|
+
`refusing to remove unrecognized Git hook entrypoint at ${paths.gitHookEntrypoint}`
|
|
16906
17216
|
);
|
|
16907
17217
|
}
|
|
16908
|
-
const
|
|
16909
|
-
|
|
16910
|
-
{
|
|
16911
|
-
|
|
16912
|
-
|
|
16913
|
-
signal: machineSignal(signal),
|
|
16914
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
16915
|
-
// With a network secret the agent proxy authenticates the client with
|
|
16916
|
-
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
16917
|
-
body: new URLSearchParams(
|
|
16918
|
-
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
16919
|
-
)
|
|
16920
|
-
},
|
|
16921
|
-
fetchImpl
|
|
16922
|
-
);
|
|
16923
|
-
if (!response.ok) {
|
|
16924
|
-
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
16925
|
-
throw new MachineAuthError(
|
|
16926
|
-
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
16927
|
-
terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
|
|
16928
|
-
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
16929
|
-
) : "The machine token service is temporarily unavailable.",
|
|
16930
|
-
terminal,
|
|
16931
|
-
terminal ? void 0 : machineRetryAt(response)
|
|
16932
|
-
);
|
|
17218
|
+
const launcher = lstatIfPresent(paths.launcher);
|
|
17219
|
+
if (launcher) {
|
|
17220
|
+
if (!launcher.isFile() || readFileSync3(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT) {
|
|
17221
|
+
throw new Error(`refusing to remove unrecognized hook launcher at ${paths.launcher}`);
|
|
17222
|
+
}
|
|
16933
17223
|
}
|
|
16934
|
-
const
|
|
16935
|
-
if (!
|
|
16936
|
-
|
|
16937
|
-
|
|
16938
|
-
"The token service returned an invalid access token."
|
|
16939
|
-
);
|
|
17224
|
+
const runtime = lstatIfPresent(paths.runtimeDir);
|
|
17225
|
+
if (!runtime) return;
|
|
17226
|
+
if (!runtime.isDirectory()) {
|
|
17227
|
+
throw new Error(`refusing to remove non-directory hook runtime at ${paths.runtimeDir}`);
|
|
16940
17228
|
}
|
|
16941
|
-
|
|
16942
|
-
|
|
16943
|
-
|
|
16944
|
-
|
|
17229
|
+
const allowed = /* @__PURE__ */ new Set(["current", "releases", "selection.lock"]);
|
|
17230
|
+
const unexpected = readdirSync(paths.runtimeDir).filter((entry) => !allowed.has(entry));
|
|
17231
|
+
if (unexpected.length > 0) {
|
|
17232
|
+
throw new Error(
|
|
17233
|
+
`refusing to remove hook runtime with unrecognized entries: ${unexpected.sort().join(", ")}`
|
|
16945
17234
|
);
|
|
16946
|
-
} catch {
|
|
16947
|
-
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
16948
17235
|
}
|
|
16949
|
-
|
|
16950
|
-
|
|
16951
|
-
|
|
16952
|
-
|
|
16953
|
-
|
|
16954
|
-
|
|
16955
|
-
throw new MachineAuthError(
|
|
16956
|
-
"token_identity_mismatch",
|
|
16957
|
-
"The token does not match the configured machine and deployment."
|
|
16958
|
-
);
|
|
17236
|
+
const current = lstatIfPresent(paths.current);
|
|
17237
|
+
const releases = lstatIfPresent(paths.releasesDir);
|
|
17238
|
+
if (current) {
|
|
17239
|
+
if (!current.isFile() || !releases || !readSelectedRelease(paths)) {
|
|
17240
|
+
throw new Error(`refusing to remove malformed hook runtime selection at ${paths.current}`);
|
|
17241
|
+
}
|
|
16959
17242
|
}
|
|
16960
|
-
return
|
|
16961
|
-
|
|
16962
|
-
|
|
16963
|
-
};
|
|
16964
|
-
}
|
|
16965
|
-
function parseMachineIdentity(value, clientId) {
|
|
16966
|
-
const data = machineRecord(value);
|
|
16967
|
-
const principal = machineRecord(data.principal);
|
|
16968
|
-
if (data.authenticated !== true || data.captureAuthorityKind !== "workos_m2m" || ![2, 3].includes(data.organizationBindingVersion) || (data.organizationBindingVersion === 3 ? !machineString(principal.authorizedUserId, 256) : principal.authorizedUserId !== void 0) || principal.kind !== "machine" || principal.clientId !== clientId || !machineString(principal.machineId, 256) || !machineString(principal.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.workosOrganizationId, 256) || !Array.isArray(principal.scopes) || !principal.scopes.every((scope) => machineString(scope, 128))) {
|
|
16969
|
-
throw new MachineAuthError(
|
|
16970
|
-
"machine_identity_rejected",
|
|
16971
|
-
"The API did not verify a machine identity.",
|
|
16972
|
-
true
|
|
16973
|
-
);
|
|
17243
|
+
if (!releases) return;
|
|
17244
|
+
if (!releases.isDirectory()) {
|
|
17245
|
+
throw new Error(`refusing to remove non-directory hook releases at ${paths.releasesDir}`);
|
|
16974
17246
|
}
|
|
16975
|
-
|
|
16976
|
-
|
|
16977
|
-
|
|
16978
|
-
|
|
16979
|
-
|
|
16980
|
-
organizationId: data.organizationId,
|
|
16981
|
-
workosOrganizationId: data.workosOrganizationId,
|
|
16982
|
-
scopes: principal.scopes
|
|
16983
|
-
};
|
|
16984
|
-
}
|
|
16985
|
-
async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetchImpl = fetch) {
|
|
16986
|
-
const response = await fetchMachine(
|
|
16987
|
-
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
16988
|
-
{
|
|
16989
|
-
headers: { Authorization: `Bearer ${accessToken}` },
|
|
16990
|
-
redirect: "error",
|
|
16991
|
-
signal: machineSignal(signal)
|
|
16992
|
-
},
|
|
16993
|
-
fetchImpl
|
|
16994
|
-
);
|
|
16995
|
-
if (!response.ok) {
|
|
16996
|
-
const terminal = response.status === 401 || response.status === 403;
|
|
16997
|
-
throw new MachineAuthError(
|
|
16998
|
-
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
16999
|
-
terminal ? rejectedCredentialsMessage(
|
|
17000
|
-
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
17001
|
-
) : "Machine verification is temporarily unavailable.",
|
|
17002
|
-
terminal
|
|
17003
|
-
);
|
|
17247
|
+
for (const entry of readdirSync(paths.releasesDir, { withFileTypes: true })) {
|
|
17248
|
+
const releaseDir = join5(paths.releasesDir, entry.name);
|
|
17249
|
+
if (!entry.isDirectory() || !RELEASE_NAME_RE.test(entry.name) || !readReleaseManifest(releaseDir, entry.name)) {
|
|
17250
|
+
throw new Error(`refusing to remove unrecognized hook release ${releaseDir}`);
|
|
17251
|
+
}
|
|
17004
17252
|
}
|
|
17005
|
-
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
17006
17253
|
}
|
|
17007
|
-
function
|
|
17008
|
-
const
|
|
17009
|
-
|
|
17010
|
-
|
|
17011
|
-
|
|
17012
|
-
);
|
|
17013
|
-
|
|
17014
|
-
if (
|
|
17015
|
-
|
|
17016
|
-
|
|
17017
|
-
|
|
17018
|
-
);
|
|
17019
|
-
let data;
|
|
17020
|
-
try {
|
|
17021
|
-
data = machineRecord(value);
|
|
17022
|
-
} catch {
|
|
17023
|
-
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
17254
|
+
function removeHookRuntime(options = {}) {
|
|
17255
|
+
const paths = hookRuntimePaths(options);
|
|
17256
|
+
const hadLauncher = lstatIfPresent(paths.launcher) !== void 0;
|
|
17257
|
+
const hadEntrypoint = lstatIfPresent(paths.gitHookEntrypoint) !== void 0;
|
|
17258
|
+
const hadRuntime = lstatIfPresent(paths.runtimeDir) !== void 0;
|
|
17259
|
+
if (!hadLauncher && !hadEntrypoint && !hadRuntime) return { changed: false, paths };
|
|
17260
|
+
assertOwnedHookRuntime(paths);
|
|
17261
|
+
if (!hadRuntime) {
|
|
17262
|
+
rmSync3(paths.gitHookEntrypoint, { force: true });
|
|
17263
|
+
rmSync3(paths.launcher, { force: true });
|
|
17264
|
+
return { changed: true, paths };
|
|
17024
17265
|
}
|
|
17025
|
-
|
|
17026
|
-
|
|
17027
|
-
|
|
17028
|
-
|
|
17029
|
-
|
|
17030
|
-
|
|
17031
|
-
|
|
17266
|
+
withFileLockSync(paths.selectionLock, () => {
|
|
17267
|
+
assertOwnedHookRuntime(paths);
|
|
17268
|
+
if (lstatIfPresent(paths.gitHookEntrypoint)) rmSync3(paths.gitHookEntrypoint, { force: true });
|
|
17269
|
+
if (lstatIfPresent(paths.launcher)) rmSync3(paths.launcher, { force: true });
|
|
17270
|
+
const quarantined = `${paths.runtimeDir}.uninstall-${String(process.pid)}-${randomBytes2(8).toString("hex")}`;
|
|
17271
|
+
renameSync2(paths.runtimeDir, quarantined);
|
|
17272
|
+
rmSync3(quarantined, { recursive: true, force: true });
|
|
17273
|
+
});
|
|
17274
|
+
return { changed: true, paths };
|
|
17275
|
+
}
|
|
17276
|
+
|
|
17277
|
+
// src/lib/machine-broker.ts
|
|
17278
|
+
import { spawn as spawn2 } from "child_process";
|
|
17279
|
+
import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
17280
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
|
|
17281
|
+
import { createServer } from "http";
|
|
17282
|
+
import { basename, join as join6 } from "path";
|
|
17283
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
17284
|
+
|
|
17285
|
+
// src/lib/loopback-fetch.ts
|
|
17286
|
+
import { request } from "http";
|
|
17287
|
+
import { Readable as Readable2 } from "stream";
|
|
17288
|
+
function loopbackFetch(url, init = {}) {
|
|
17289
|
+
const target = new URL(url);
|
|
17290
|
+
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
17291
|
+
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
17292
|
+
return new Promise((resolve17, reject) => {
|
|
17293
|
+
const outgoing = request(
|
|
17294
|
+
target,
|
|
17295
|
+
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
17296
|
+
(incoming) => {
|
|
17297
|
+
try {
|
|
17298
|
+
const headers = new Headers();
|
|
17299
|
+
for (const [name2, value] of Object.entries(incoming.headers))
|
|
17300
|
+
if (typeof value === "string") headers.set(name2, value);
|
|
17301
|
+
const status2 = incoming.statusCode ?? 502;
|
|
17302
|
+
const body = [101, 204, 205, 304].includes(status2) ? null : Readable2.toWeb(incoming);
|
|
17303
|
+
resolve17(new Response(body, { status: status2, headers }));
|
|
17304
|
+
} catch (error) {
|
|
17305
|
+
incoming.destroy();
|
|
17306
|
+
reject(error);
|
|
17307
|
+
}
|
|
17308
|
+
}
|
|
17032
17309
|
);
|
|
17033
|
-
|
|
17310
|
+
outgoing.once("error", reject);
|
|
17311
|
+
outgoing.end(init.body);
|
|
17312
|
+
});
|
|
17034
17313
|
}
|
|
17035
|
-
|
|
17036
|
-
|
|
17037
|
-
|
|
17038
|
-
|
|
17039
|
-
|
|
17040
|
-
|
|
17041
|
-
|
|
17042
|
-
|
|
17314
|
+
|
|
17315
|
+
// src/lib/cloud-env.ts
|
|
17316
|
+
function isClaudeCloudSession(env4 = process.env) {
|
|
17317
|
+
return env4.CLAUDE_CODE_REMOTE === "true";
|
|
17318
|
+
}
|
|
17319
|
+
function insideClaudeCode(env4 = process.env) {
|
|
17320
|
+
return env4.CLAUDECODE === "1";
|
|
17321
|
+
}
|
|
17322
|
+
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';
|
|
17323
|
+
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';
|
|
17324
|
+
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}.`;
|
|
17325
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
17326
|
+
function cloudSetupPointer(message, env4 = process.env) {
|
|
17327
|
+
return isClaudeCloudSession(env4) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
17043
17328
|
}
|
|
17329
|
+
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
17044
17330
|
|
|
17045
|
-
// src/lib/
|
|
17046
|
-
|
|
17047
|
-
|
|
17048
|
-
var
|
|
17049
|
-
|
|
17050
|
-
|
|
17051
|
-
|
|
17331
|
+
// src/lib/workos-connect.ts
|
|
17332
|
+
var DISCOVERY_PATH = "/api/cli/auth/connect/config";
|
|
17333
|
+
var DEVICE_AUTHORIZATION_PATH = "/oauth2/device_authorization";
|
|
17334
|
+
var TOKEN_PATH = "/oauth2/token";
|
|
17335
|
+
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
17336
|
+
var WORKOS_CONNECT_RESPONSE_MAX_BYTES = 64 * 1024;
|
|
17337
|
+
var MAX_DEVICE_LIFETIME_SECONDS = 60 * 60;
|
|
17338
|
+
var MAX_TOKEN_LIFETIME_SECONDS = 24 * 60 * 60;
|
|
17339
|
+
var MAX_INTERVAL_SECONDS = 60;
|
|
17340
|
+
var POLL_REQUEST_TIMEOUT_MS = 3e4;
|
|
17341
|
+
var SLOW_DOWN_SECONDS = 5;
|
|
17342
|
+
var MAX_URL_LENGTH = 2048;
|
|
17343
|
+
var MAX_DEVICE_CODE_LENGTH = 4096;
|
|
17344
|
+
var MAX_USER_CODE_LENGTH = 128;
|
|
17345
|
+
var MAX_CLIENT_ID_LENGTH = 256;
|
|
17346
|
+
var CONNECT_CLIENT_ID_PATTERN = /^client_[A-Za-z0-9_-]+$/u;
|
|
17347
|
+
var WORKOS_CONNECT_DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"];
|
|
17348
|
+
var WorkosConnectProtocolError = class extends Error {
|
|
17349
|
+
code;
|
|
17350
|
+
constructor(code, message) {
|
|
17351
|
+
super(message);
|
|
17352
|
+
this.name = "WorkosConnectProtocolError";
|
|
17353
|
+
this.code = code;
|
|
17052
17354
|
}
|
|
17053
|
-
|
|
17054
|
-
|
|
17055
|
-
|
|
17355
|
+
};
|
|
17356
|
+
function recordFrom(value, label2) {
|
|
17357
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
17358
|
+
throw new WorkosConnectProtocolError("invalid_response", `${label2} must be an object`);
|
|
17359
|
+
}
|
|
17360
|
+
return value;
|
|
17056
17361
|
}
|
|
17057
|
-
function
|
|
17058
|
-
const
|
|
17059
|
-
|
|
17060
|
-
|
|
17061
|
-
|
|
17062
|
-
if (
|
|
17063
|
-
|
|
17064
|
-
if (!home) {
|
|
17065
|
-
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
17362
|
+
function exactString(value, field, maxLength) {
|
|
17363
|
+
const containsControl = typeof value === "string" && [...value].some((character) => {
|
|
17364
|
+
const code = character.charCodeAt(0);
|
|
17365
|
+
return code <= 31 || code === 127;
|
|
17366
|
+
});
|
|
17367
|
+
if (typeof value !== "string" || value.length === 0 || value.length > maxLength || value.trim() !== value || containsControl) {
|
|
17368
|
+
throw new WorkosConnectProtocolError("invalid_response", `${field} is invalid`);
|
|
17066
17369
|
}
|
|
17067
|
-
return
|
|
17370
|
+
return value;
|
|
17068
17371
|
}
|
|
17069
|
-
function
|
|
17070
|
-
|
|
17372
|
+
function safeInteger(value, field, minimum, maximum) {
|
|
17373
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
|
|
17374
|
+
throw new WorkosConnectProtocolError("invalid_response", `${field} is invalid`);
|
|
17375
|
+
}
|
|
17376
|
+
return value;
|
|
17071
17377
|
}
|
|
17072
|
-
|
|
17073
|
-
|
|
17074
|
-
|
|
17075
|
-
|
|
17076
|
-
|
|
17077
|
-
|
|
17078
|
-
|
|
17079
|
-
|
|
17080
|
-
|
|
17081
|
-
|
|
17082
|
-
|
|
17378
|
+
function canonicalIssuer(value) {
|
|
17379
|
+
const issuer = exactString(value, "issuer", MAX_URL_LENGTH);
|
|
17380
|
+
let parsed;
|
|
17381
|
+
try {
|
|
17382
|
+
parsed = new URL(issuer);
|
|
17383
|
+
} catch {
|
|
17384
|
+
throw new WorkosConnectProtocolError("invalid_response", "issuer must be an HTTPS origin");
|
|
17385
|
+
}
|
|
17386
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash || parsed.origin !== issuer) {
|
|
17387
|
+
throw new WorkosConnectProtocolError("invalid_response", "issuer must be an HTTPS origin");
|
|
17388
|
+
}
|
|
17389
|
+
return issuer;
|
|
17083
17390
|
}
|
|
17084
|
-
function
|
|
17391
|
+
function sameIssuerUrl(value, field, issuer) {
|
|
17392
|
+
const raw = exactString(value, field, MAX_URL_LENGTH);
|
|
17393
|
+
let parsed;
|
|
17085
17394
|
try {
|
|
17086
|
-
|
|
17087
|
-
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
17088
|
-
return void 0;
|
|
17089
|
-
const data = JSON.parse(readFileSync3(path9, "utf8"));
|
|
17090
|
-
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;
|
|
17395
|
+
parsed = new URL(raw);
|
|
17091
17396
|
} catch {
|
|
17092
|
-
|
|
17397
|
+
throw new WorkosConnectProtocolError("invalid_response", `${field} must be an HTTPS URL`);
|
|
17398
|
+
}
|
|
17399
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.origin !== issuer) {
|
|
17400
|
+
throw new WorkosConnectProtocolError("invalid_response", `${field} is not trusted`);
|
|
17093
17401
|
}
|
|
17402
|
+
return parsed.toString();
|
|
17094
17403
|
}
|
|
17095
|
-
function
|
|
17096
|
-
|
|
17404
|
+
function parseWorkosConnectConfiguration(value) {
|
|
17405
|
+
const record3 = recordFrom(value, "Connect discovery");
|
|
17406
|
+
const expectedKeys = ["protocol_version", "issuer", "client_id", "default_scopes"];
|
|
17407
|
+
if (record3.protocol_version !== 1 || Object.keys(record3).length !== expectedKeys.length || expectedKeys.some((key) => !Object.hasOwn(record3, key)) || !Array.isArray(record3.default_scopes) || record3.default_scopes.length !== WORKOS_CONNECT_DEFAULT_SCOPES.length || record3.default_scopes.some((scope, index) => scope !== WORKOS_CONNECT_DEFAULT_SCOPES[index])) {
|
|
17408
|
+
throw new WorkosConnectProtocolError("invalid_response", "Connect discovery is invalid");
|
|
17409
|
+
}
|
|
17410
|
+
const issuer = canonicalIssuer(record3.issuer);
|
|
17411
|
+
const clientId = exactString(record3.client_id, "client_id", MAX_CLIENT_ID_LENGTH);
|
|
17412
|
+
if (!CONNECT_CLIENT_ID_PATTERN.test(clientId)) {
|
|
17413
|
+
throw new WorkosConnectProtocolError("invalid_response", "Connect discovery is invalid");
|
|
17414
|
+
}
|
|
17415
|
+
return {
|
|
17416
|
+
issuer,
|
|
17417
|
+
clientId,
|
|
17418
|
+
scopes: [...WORKOS_CONNECT_DEFAULT_SCOPES]
|
|
17419
|
+
};
|
|
17097
17420
|
}
|
|
17098
|
-
function
|
|
17099
|
-
|
|
17421
|
+
function parseWorkosConnectCredentialMetadata(value) {
|
|
17422
|
+
const record3 = recordFrom(value, "credential metadata");
|
|
17423
|
+
if (record3.version !== 1 || record3.family !== "workos_connect") {
|
|
17424
|
+
throw new WorkosConnectProtocolError("invalid_metadata", "credential metadata is invalid");
|
|
17425
|
+
}
|
|
17426
|
+
const issuer = canonicalIssuer(record3.issuer);
|
|
17427
|
+
const clientId = exactString(record3.clientId, "clientId", MAX_CLIENT_ID_LENGTH);
|
|
17428
|
+
const accessTokenHash = exactString(record3.accessTokenHash, "accessTokenHash", 64);
|
|
17429
|
+
const refreshTokenHash = exactString(record3.refreshTokenHash, "refreshTokenHash", 64);
|
|
17430
|
+
if (!CONNECT_CLIENT_ID_PATTERN.test(clientId)) {
|
|
17431
|
+
throw new WorkosConnectProtocolError("invalid_metadata", "credential clientId is invalid");
|
|
17432
|
+
}
|
|
17433
|
+
if (!/^[a-f0-9]{64}$/u.test(accessTokenHash)) {
|
|
17434
|
+
throw new WorkosConnectProtocolError(
|
|
17435
|
+
"invalid_metadata",
|
|
17436
|
+
"credential accessTokenHash is invalid"
|
|
17437
|
+
);
|
|
17438
|
+
}
|
|
17439
|
+
if (!/^[a-f0-9]{64}$/u.test(refreshTokenHash)) {
|
|
17440
|
+
throw new WorkosConnectProtocolError(
|
|
17441
|
+
"invalid_metadata",
|
|
17442
|
+
"credential refreshTokenHash is invalid"
|
|
17443
|
+
);
|
|
17444
|
+
}
|
|
17445
|
+
return {
|
|
17446
|
+
version: 1,
|
|
17447
|
+
family: "workos_connect",
|
|
17448
|
+
issuer,
|
|
17449
|
+
clientId,
|
|
17450
|
+
accessTokenHash,
|
|
17451
|
+
refreshTokenHash
|
|
17452
|
+
};
|
|
17100
17453
|
}
|
|
17101
|
-
function
|
|
17102
|
-
|
|
17454
|
+
async function readBoundedJson(response, maxBytes) {
|
|
17455
|
+
const contentLength = response.headers.get("content-length");
|
|
17456
|
+
if (contentLength !== null) {
|
|
17457
|
+
if (!/^\d+$/u.test(contentLength) || Number(contentLength) > maxBytes) {
|
|
17458
|
+
throw new WorkosConnectProtocolError("invalid_response", "response body is too large");
|
|
17459
|
+
}
|
|
17460
|
+
}
|
|
17461
|
+
if (!response.body) {
|
|
17462
|
+
throw new WorkosConnectProtocolError("invalid_response", "response body is missing");
|
|
17463
|
+
}
|
|
17464
|
+
const reader = response.body.getReader();
|
|
17465
|
+
const chunks = [];
|
|
17466
|
+
let total = 0;
|
|
17467
|
+
try {
|
|
17468
|
+
while (true) {
|
|
17469
|
+
const result = await reader.read();
|
|
17470
|
+
if (result.done) break;
|
|
17471
|
+
total += result.value.byteLength;
|
|
17472
|
+
if (total > maxBytes) {
|
|
17473
|
+
await reader.cancel();
|
|
17474
|
+
throw new WorkosConnectProtocolError("invalid_response", "response body is too large");
|
|
17475
|
+
}
|
|
17476
|
+
chunks.push(result.value);
|
|
17477
|
+
}
|
|
17478
|
+
} finally {
|
|
17479
|
+
reader.releaseLock();
|
|
17480
|
+
}
|
|
17481
|
+
const bytes = new Uint8Array(total);
|
|
17482
|
+
let offset = 0;
|
|
17483
|
+
for (const chunk2 of chunks) {
|
|
17484
|
+
bytes.set(chunk2, offset);
|
|
17485
|
+
offset += chunk2.byteLength;
|
|
17486
|
+
}
|
|
17487
|
+
let text;
|
|
17488
|
+
try {
|
|
17489
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
17490
|
+
return JSON.parse(text);
|
|
17491
|
+
} catch {
|
|
17492
|
+
throw new WorkosConnectProtocolError("invalid_response", "response body is not valid JSON");
|
|
17493
|
+
}
|
|
17103
17494
|
}
|
|
17104
|
-
async function
|
|
17105
|
-
const
|
|
17106
|
-
|
|
17107
|
-
|
|
17108
|
-
|
|
17109
|
-
|
|
17495
|
+
async function discoverWorkosConnect(siteUrl, fetchImpl = fetch, signal = AbortSignal.timeout(1e4)) {
|
|
17496
|
+
const response = await fetchImpl(`${siteUrl}${DISCOVERY_PATH}`, { signal });
|
|
17497
|
+
if (response.status === 404) return { state: "legacy_server" };
|
|
17498
|
+
if (!response.ok) {
|
|
17499
|
+
throw new WorkosConnectProtocolError(
|
|
17500
|
+
"discovery_unavailable",
|
|
17501
|
+
`Connect discovery returned HTTP ${response.status}`
|
|
17502
|
+
);
|
|
17503
|
+
}
|
|
17504
|
+
return {
|
|
17505
|
+
state: "available",
|
|
17506
|
+
configuration: parseWorkosConnectConfiguration(
|
|
17507
|
+
await readBoundedJson(response, DISCOVERY_MAX_BYTES)
|
|
17508
|
+
)
|
|
17509
|
+
};
|
|
17510
|
+
}
|
|
17511
|
+
function workosConnectTokenEndpoint(issuer) {
|
|
17512
|
+
return `${issuer}${TOKEN_PATH}`;
|
|
17513
|
+
}
|
|
17514
|
+
async function requestWorkosDeviceAuthorization(configuration, fetchImpl = fetch, signal = AbortSignal.timeout(1e4)) {
|
|
17515
|
+
const body = new URLSearchParams({
|
|
17516
|
+
client_id: configuration.clientId,
|
|
17517
|
+
scope: configuration.scopes.join(" ")
|
|
17110
17518
|
});
|
|
17111
|
-
const response = await
|
|
17519
|
+
const response = await fetchImpl(`${configuration.issuer}${DEVICE_AUTHORIZATION_PATH}`, {
|
|
17112
17520
|
method: "POST",
|
|
17521
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
17113
17522
|
body,
|
|
17114
|
-
signal
|
|
17115
|
-
headers: {
|
|
17116
|
-
"Content-Type": "application/json",
|
|
17117
|
-
"X-Prim-Proof": signature(environment.clientSecret, descriptor.nonce, body)
|
|
17118
|
-
}
|
|
17523
|
+
signal
|
|
17119
17524
|
});
|
|
17120
|
-
const
|
|
17121
|
-
if (
|
|
17122
|
-
|
|
17123
|
-
|
|
17124
|
-
|
|
17125
|
-
|
|
17126
|
-
const data = machineRecord(JSON.parse(envelope.body));
|
|
17127
|
-
if (data.error) {
|
|
17128
|
-
const error = machineRecord(data.error);
|
|
17129
|
-
throw new MachineAuthError(
|
|
17130
|
-
String(error.code),
|
|
17131
|
-
String(error.message),
|
|
17132
|
-
error.terminal === true,
|
|
17133
|
-
typeof error.retryAt === "number" ? error.retryAt : void 0
|
|
17525
|
+
const value = await readBoundedJson(response, WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
17526
|
+
if (!response.ok) {
|
|
17527
|
+
const error = recordFrom(value, "device authorization error").error;
|
|
17528
|
+
throw new WorkosConnectProtocolError(
|
|
17529
|
+
typeof error === "string" ? error : "device_authorization_failed",
|
|
17530
|
+
`Device authorization returned HTTP ${response.status}`
|
|
17134
17531
|
);
|
|
17135
17532
|
}
|
|
17136
|
-
const
|
|
17137
|
-
|
|
17138
|
-
|
|
17139
|
-
|
|
17140
|
-
|
|
17141
|
-
|
|
17142
|
-
return
|
|
17533
|
+
const record3 = recordFrom(value, "device authorization");
|
|
17534
|
+
const verificationUri = sameIssuerUrl(
|
|
17535
|
+
record3.verification_uri,
|
|
17536
|
+
"verification_uri",
|
|
17537
|
+
configuration.issuer
|
|
17538
|
+
);
|
|
17539
|
+
return {
|
|
17540
|
+
deviceCode: exactString(record3.device_code, "device_code", MAX_DEVICE_CODE_LENGTH),
|
|
17541
|
+
userCode: exactString(record3.user_code, "user_code", MAX_USER_CODE_LENGTH),
|
|
17542
|
+
verificationUri,
|
|
17543
|
+
verificationUriComplete: record3.verification_uri_complete === void 0 ? void 0 : sameIssuerUrl(
|
|
17544
|
+
record3.verification_uri_complete,
|
|
17545
|
+
"verification_uri_complete",
|
|
17546
|
+
configuration.issuer
|
|
17547
|
+
),
|
|
17548
|
+
expiresIn: safeInteger(record3.expires_in, "expires_in", 1, MAX_DEVICE_LIFETIME_SECONDS),
|
|
17549
|
+
interval: safeInteger(record3.interval ?? 5, "interval", 1, MAX_INTERVAL_SECONDS)
|
|
17550
|
+
};
|
|
17143
17551
|
}
|
|
17144
|
-
function
|
|
17145
|
-
const
|
|
17552
|
+
function parseWorkosConnectTokens(value, options = {}) {
|
|
17553
|
+
const record3 = recordFrom(value, "token response");
|
|
17554
|
+
const accessToken = exactString(
|
|
17555
|
+
record3.access_token,
|
|
17556
|
+
"access_token",
|
|
17557
|
+
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
17558
|
+
);
|
|
17559
|
+
const refreshToken3 = record3.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record3.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
17146
17560
|
return {
|
|
17147
|
-
|
|
17148
|
-
|
|
17149
|
-
|
|
17150
|
-
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
17561
|
+
accessToken,
|
|
17562
|
+
refreshToken: refreshToken3,
|
|
17563
|
+
expiresIn: record3.expires_in === void 0 ? void 0 : safeInteger(record3.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
17151
17564
|
};
|
|
17152
17565
|
}
|
|
17153
|
-
|
|
17154
|
-
const
|
|
17155
|
-
|
|
17156
|
-
if (existing) {
|
|
17157
|
-
try {
|
|
17158
|
-
return await brokerRequest(existing, options.environment, options);
|
|
17159
|
-
} catch (error) {
|
|
17160
|
-
options.signal.throwIfAborted();
|
|
17161
|
-
if (error instanceof MachineAuthError) throw error;
|
|
17162
|
-
}
|
|
17163
|
-
}
|
|
17164
|
-
const descriptor = await ensureBroker(options);
|
|
17165
|
-
try {
|
|
17166
|
-
return await brokerRequest(descriptor, options.environment, options);
|
|
17167
|
-
} catch (error) {
|
|
17168
|
-
options.signal.throwIfAborted();
|
|
17169
|
-
if (error instanceof MachineAuthError) throw error;
|
|
17170
|
-
throw new MachineAuthError(
|
|
17171
|
-
"broker_unavailable",
|
|
17172
|
-
"Machine credential broker is unavailable. Retry the command."
|
|
17173
|
-
);
|
|
17174
|
-
}
|
|
17566
|
+
function providerError(value) {
|
|
17567
|
+
const error = recordFrom(value, "token error").error;
|
|
17568
|
+
return exactString(error, "error", MAX_USER_CODE_LENGTH);
|
|
17175
17569
|
}
|
|
17176
|
-
async function
|
|
17177
|
-
|
|
17178
|
-
|
|
17179
|
-
|
|
17180
|
-
|
|
17181
|
-
|
|
17182
|
-
|
|
17183
|
-
|
|
17184
|
-
|
|
17185
|
-
|
|
17186
|
-
|
|
17187
|
-
|
|
17570
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
17571
|
+
await new Promise((resolve17, reject) => {
|
|
17572
|
+
if (signal.aborted) {
|
|
17573
|
+
reject(signal.reason);
|
|
17574
|
+
return;
|
|
17575
|
+
}
|
|
17576
|
+
const abort = () => {
|
|
17577
|
+
clearTimeout(timer);
|
|
17578
|
+
reject(signal.reason);
|
|
17579
|
+
};
|
|
17580
|
+
const timer = setTimeout(() => {
|
|
17581
|
+
signal.removeEventListener("abort", abort);
|
|
17582
|
+
resolve17();
|
|
17583
|
+
}, milliseconds);
|
|
17584
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
17585
|
+
});
|
|
17586
|
+
}
|
|
17587
|
+
async function pollWorkosDeviceAuthorization(configuration, authorization, options = {}) {
|
|
17588
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
17589
|
+
const now = options.now ?? Date.now;
|
|
17590
|
+
const sleep2 = options.sleep ?? defaultSleep2;
|
|
17591
|
+
const signal = options.signal ?? AbortSignal.timeout(authorization.expiresIn * 1e3);
|
|
17592
|
+
const deadline = now() + authorization.expiresIn * 1e3;
|
|
17593
|
+
let intervalSeconds = authorization.interval;
|
|
17594
|
+
while (now() < deadline) {
|
|
17595
|
+
await sleep2(Math.min(intervalSeconds * 1e3, Math.max(0, deadline - now())), signal);
|
|
17596
|
+
if (now() >= deadline) break;
|
|
17597
|
+
let response;
|
|
17598
|
+
try {
|
|
17599
|
+
response = await fetchImpl(workosConnectTokenEndpoint(configuration.issuer), {
|
|
17600
|
+
method: "POST",
|
|
17601
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
17602
|
+
body: new URLSearchParams({
|
|
17603
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
17604
|
+
device_code: authorization.deviceCode,
|
|
17605
|
+
client_id: configuration.clientId
|
|
17606
|
+
}),
|
|
17607
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(POLL_REQUEST_TIMEOUT_MS)])
|
|
17608
|
+
});
|
|
17609
|
+
} catch (error2) {
|
|
17610
|
+
if (signal.aborted) {
|
|
17611
|
+
throw new WorkosConnectProtocolError("expired_token", "Device authorization expired");
|
|
17612
|
+
}
|
|
17613
|
+
continue;
|
|
17614
|
+
}
|
|
17615
|
+
const value = await readBoundedJson(response, WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
17616
|
+
if (response.ok) return parseWorkosConnectTokens(value);
|
|
17617
|
+
const error = providerError(value);
|
|
17618
|
+
if (error === "authorization_pending") continue;
|
|
17619
|
+
if (error === "slow_down") {
|
|
17620
|
+
intervalSeconds = Math.min(MAX_INTERVAL_SECONDS, intervalSeconds + SLOW_DOWN_SECONDS);
|
|
17621
|
+
continue;
|
|
17622
|
+
}
|
|
17623
|
+
if (error === "access_denied" || error === "expired_token") {
|
|
17624
|
+
throw new WorkosConnectProtocolError(error, `Device authorization failed: ${error}`);
|
|
17625
|
+
}
|
|
17626
|
+
throw new WorkosConnectProtocolError(error, "Token endpoint rejected device authorization");
|
|
17627
|
+
}
|
|
17628
|
+
throw new WorkosConnectProtocolError("expired_token", "Device authorization expired");
|
|
17629
|
+
}
|
|
17630
|
+
|
|
17631
|
+
// src/lib/machine-protocol.ts
|
|
17632
|
+
var MachineAuthError = class extends Error {
|
|
17633
|
+
constructor(code, message, terminal = false, retryAt) {
|
|
17634
|
+
super(message);
|
|
17635
|
+
this.code = code;
|
|
17636
|
+
this.terminal = terminal;
|
|
17637
|
+
this.retryAt = retryAt;
|
|
17638
|
+
this.name = "MachineAuthError";
|
|
17639
|
+
}
|
|
17640
|
+
};
|
|
17641
|
+
function machineRetryAt(response, now = Date.now()) {
|
|
17642
|
+
const value = response.headers.get("Retry-After")?.trim();
|
|
17643
|
+
if (!value || value.length > 128) return void 0;
|
|
17644
|
+
const timestamp2 = /^\d+$/u.test(value) ? now + Number(value) * 1e3 : Date.parse(value);
|
|
17645
|
+
return Number.isSafeInteger(timestamp2) && timestamp2 > now ? timestamp2 : void 0;
|
|
17646
|
+
}
|
|
17647
|
+
function machineString(value, maximum = 4096) {
|
|
17648
|
+
return typeof value === "string" && value.length > 0 && value.length <= maximum && value.trim() === value && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
17649
|
+
}
|
|
17650
|
+
function machineRecord(value) {
|
|
17651
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
17652
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
17653
|
+
}
|
|
17654
|
+
return value;
|
|
17655
|
+
}
|
|
17656
|
+
function machineApiUrl(value) {
|
|
17657
|
+
const url = new URL(value);
|
|
17658
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
17659
|
+
if (url.protocol !== "https:" && !(local && url.protocol === "http:") || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
17660
|
+
throw new MachineAuthError("invalid_configuration", "The API URL must be an HTTPS origin.");
|
|
17661
|
+
}
|
|
17662
|
+
return url.origin;
|
|
17663
|
+
}
|
|
17664
|
+
function parseMachineConfiguration(value) {
|
|
17665
|
+
const record3 = machineRecord(value);
|
|
17666
|
+
if (record3.protocol_version !== 1 || !machineString(record3.issuer, 2048) || !machineString(record3.audience, 256) || !/^client_[\w-]+$/u.test(record3.audience)) {
|
|
17667
|
+
throw new MachineAuthError("invalid_configuration", "Invalid M2M discovery configuration.");
|
|
17668
|
+
}
|
|
17669
|
+
const issuer = new URL(record3.issuer);
|
|
17670
|
+
if (issuer.protocol !== "https:" || issuer.origin !== record3.issuer) {
|
|
17671
|
+
throw new MachineAuthError(
|
|
17672
|
+
"invalid_configuration",
|
|
17673
|
+
"The WorkOS issuer must be an HTTPS origin."
|
|
17674
|
+
);
|
|
17675
|
+
}
|
|
17676
|
+
return {
|
|
17677
|
+
issuer: record3.issuer,
|
|
17678
|
+
audience: record3.audience,
|
|
17679
|
+
...record3.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
17680
|
+
};
|
|
17681
|
+
}
|
|
17682
|
+
function rejectedCredentialsMessage(message, env4 = process.env) {
|
|
17683
|
+
return isClaudeCloudSession(env4) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
17684
|
+
}
|
|
17685
|
+
function machineSignal(signal) {
|
|
17686
|
+
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
17687
|
+
}
|
|
17688
|
+
function hostOf(url) {
|
|
17689
|
+
try {
|
|
17690
|
+
return new URL(url).hostname;
|
|
17691
|
+
} catch {
|
|
17692
|
+
return "Primitive";
|
|
17693
|
+
}
|
|
17694
|
+
}
|
|
17695
|
+
async function fetchMachine(url, options, fetchImpl) {
|
|
17696
|
+
try {
|
|
17697
|
+
return await fetchImpl(url, options);
|
|
17698
|
+
} catch {
|
|
17699
|
+
options.signal?.throwIfAborted();
|
|
17700
|
+
throw new MachineAuthError(
|
|
17701
|
+
"authentication_unavailable",
|
|
17702
|
+
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
17703
|
+
// Primitive's are blocked by default: name the one that failed.
|
|
17704
|
+
isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
17705
|
+
);
|
|
17706
|
+
}
|
|
17707
|
+
}
|
|
17708
|
+
async function readMachineJson(response, maximumBytes) {
|
|
17709
|
+
try {
|
|
17710
|
+
return await readBoundedJson(response, maximumBytes);
|
|
17711
|
+
} catch {
|
|
17712
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
17713
|
+
}
|
|
17714
|
+
}
|
|
17715
|
+
async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
17716
|
+
const response = await fetchMachine(
|
|
17717
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/m2m/config`,
|
|
17718
|
+
{
|
|
17719
|
+
signal: machineSignal(signal),
|
|
17720
|
+
redirect: "error"
|
|
17721
|
+
},
|
|
17722
|
+
fetchImpl
|
|
17723
|
+
);
|
|
17724
|
+
if (!response.ok)
|
|
17725
|
+
throw new MachineAuthError(
|
|
17726
|
+
response.status === 404 ? "server_upgrade_required" : "discovery_unavailable",
|
|
17727
|
+
response.status === 404 ? "This server does not support machine authentication yet." : "Machine authentication discovery is unavailable."
|
|
17728
|
+
);
|
|
17729
|
+
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
17730
|
+
}
|
|
17731
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
|
|
17732
|
+
const network = options.secretInjection === "network";
|
|
17733
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
|
|
17734
|
+
throw new MachineAuthError(
|
|
17735
|
+
"invalid_credentials",
|
|
17736
|
+
"A machine client ID and secret are required.",
|
|
17737
|
+
true
|
|
17738
|
+
);
|
|
17739
|
+
}
|
|
17740
|
+
const response = await fetchMachine(
|
|
17741
|
+
`${configuration.issuer}/oauth2/token`,
|
|
17742
|
+
{
|
|
17743
|
+
method: "POST",
|
|
17744
|
+
redirect: "error",
|
|
17745
|
+
signal: machineSignal(signal),
|
|
17746
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
17747
|
+
// With a network secret the agent proxy authenticates the client with
|
|
17748
|
+
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
17749
|
+
body: new URLSearchParams(
|
|
17750
|
+
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
17751
|
+
)
|
|
17752
|
+
},
|
|
17753
|
+
fetchImpl
|
|
17754
|
+
);
|
|
17755
|
+
if (!response.ok) {
|
|
17756
|
+
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
17757
|
+
throw new MachineAuthError(
|
|
17758
|
+
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
17759
|
+
terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
|
|
17760
|
+
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
17761
|
+
) : "The machine token service is temporarily unavailable.",
|
|
17762
|
+
terminal,
|
|
17763
|
+
terminal ? void 0 : machineRetryAt(response)
|
|
17764
|
+
);
|
|
17765
|
+
}
|
|
17766
|
+
const data = machineRecord(await readMachineJson(response, 64 * 1024));
|
|
17767
|
+
if (!machineString(data.access_token, 60 * 1024) || typeof data.token_type !== "string" || data.token_type.toLowerCase() !== "bearer" || !Number.isSafeInteger(data.expires_in) || data.expires_in <= 0 || data.expires_in > 86400) {
|
|
17768
|
+
throw new MachineAuthError(
|
|
17769
|
+
"invalid_response",
|
|
17770
|
+
"The token service returned an invalid access token."
|
|
17771
|
+
);
|
|
17772
|
+
}
|
|
17773
|
+
let claims;
|
|
17774
|
+
try {
|
|
17775
|
+
claims = machineRecord(
|
|
17776
|
+
JSON.parse(Buffer.from(data.access_token.split(".")[1] ?? "", "base64url").toString("utf8"))
|
|
17777
|
+
);
|
|
17778
|
+
} catch {
|
|
17779
|
+
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
17780
|
+
}
|
|
17781
|
+
if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
|
|
17782
|
+
throw new MachineAuthError(
|
|
17783
|
+
"token_client_mismatch",
|
|
17784
|
+
"The token service issued a token for another machine client."
|
|
17785
|
+
);
|
|
17786
|
+
if (claims.iss !== configuration.issuer || claims.aud !== configuration.audience || claims.sub !== clientId || claims.client_id !== clientId || !machineString(claims.org_id, 256) || typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1e3 <= Date.now()) {
|
|
17787
|
+
throw new MachineAuthError(
|
|
17788
|
+
"token_identity_mismatch",
|
|
17789
|
+
"The token does not match the configured machine and deployment."
|
|
17790
|
+
);
|
|
17791
|
+
}
|
|
17792
|
+
return {
|
|
17793
|
+
accessToken: data.access_token,
|
|
17794
|
+
expiresAt: Math.min(Date.now() + data.expires_in * 1e3, claims.exp * 1e3)
|
|
17795
|
+
};
|
|
17796
|
+
}
|
|
17797
|
+
function parseMachineIdentity(value, clientId) {
|
|
17798
|
+
const data = machineRecord(value);
|
|
17799
|
+
const principal = machineRecord(data.principal);
|
|
17800
|
+
if (data.authenticated !== true || data.captureAuthorityKind !== "workos_m2m" || ![2, 3].includes(data.organizationBindingVersion) || (data.organizationBindingVersion === 3 ? !machineString(principal.authorizedUserId, 256) : principal.authorizedUserId !== void 0) || principal.kind !== "machine" || principal.clientId !== clientId || !machineString(principal.machineId, 256) || !machineString(principal.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.workosOrganizationId, 256) || !Array.isArray(principal.scopes) || !principal.scopes.every((scope) => machineString(scope, 128))) {
|
|
17801
|
+
throw new MachineAuthError(
|
|
17802
|
+
"machine_identity_rejected",
|
|
17803
|
+
"The API did not verify a machine identity.",
|
|
17804
|
+
true
|
|
17805
|
+
);
|
|
17806
|
+
}
|
|
17807
|
+
return {
|
|
17808
|
+
machineId: principal.machineId,
|
|
17809
|
+
...data.organizationBindingVersion === 3 ? { authorizedUserId: principal.authorizedUserId } : {},
|
|
17810
|
+
clientId,
|
|
17811
|
+
displayName: principal.displayName,
|
|
17812
|
+
organizationId: data.organizationId,
|
|
17813
|
+
workosOrganizationId: data.workosOrganizationId,
|
|
17814
|
+
scopes: principal.scopes
|
|
17815
|
+
};
|
|
17816
|
+
}
|
|
17817
|
+
async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetchImpl = fetch) {
|
|
17818
|
+
const response = await fetchMachine(
|
|
17819
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
17820
|
+
{
|
|
17821
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
17822
|
+
redirect: "error",
|
|
17823
|
+
signal: machineSignal(signal)
|
|
17824
|
+
},
|
|
17825
|
+
fetchImpl
|
|
17826
|
+
);
|
|
17827
|
+
if (!response.ok) {
|
|
17828
|
+
const terminal = response.status === 401 || response.status === 403;
|
|
17829
|
+
throw new MachineAuthError(
|
|
17830
|
+
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
17831
|
+
terminal ? rejectedCredentialsMessage(
|
|
17832
|
+
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
17833
|
+
) : "Machine verification is temporarily unavailable.",
|
|
17834
|
+
terminal
|
|
17835
|
+
);
|
|
17836
|
+
}
|
|
17837
|
+
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
17838
|
+
}
|
|
17839
|
+
function parseInjectedMachineIdentity(status2, value, apiUrl, clientId) {
|
|
17840
|
+
const rejected = () => new MachineAuthError(
|
|
17841
|
+
"network_token_rejected",
|
|
17842
|
+
`Primitive did not accept this machine: the cloud environment's proxy attached no token it accepts, or the installation was revoked. Check the environment's OAuth 2.0 client credentials network secret: allowed website ${new URL(apiUrl).hostname}, the client ID (${clientId}), the client secret, and the token URL.`,
|
|
17843
|
+
true
|
|
17844
|
+
);
|
|
17845
|
+
if (status2 === 401 || status2 === 403) throw rejected();
|
|
17846
|
+
if (status2 < 200 || status2 > 299)
|
|
17847
|
+
throw new MachineAuthError(
|
|
17848
|
+
"verification_unavailable",
|
|
17849
|
+
"Machine verification is temporarily unavailable."
|
|
17850
|
+
);
|
|
17851
|
+
let data;
|
|
17852
|
+
try {
|
|
17853
|
+
data = machineRecord(value);
|
|
17854
|
+
} catch {
|
|
17855
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
17856
|
+
}
|
|
17857
|
+
if (data.authenticated !== true) throw rejected();
|
|
17858
|
+
const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
|
|
17859
|
+
if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
|
|
17860
|
+
throw new MachineAuthError(
|
|
17861
|
+
"network_secret_mismatch",
|
|
17862
|
+
`The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
|
|
17863
|
+
true
|
|
17864
|
+
);
|
|
17865
|
+
return parseMachineIdentity(data, clientId);
|
|
17866
|
+
}
|
|
17867
|
+
async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
|
|
17868
|
+
const response = await fetchMachine(
|
|
17869
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
17870
|
+
{ redirect: "error", signal: machineSignal(signal) },
|
|
17871
|
+
fetchImpl
|
|
17872
|
+
);
|
|
17873
|
+
const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
|
|
17874
|
+
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
17875
|
+
}
|
|
17876
|
+
|
|
17877
|
+
// src/lib/machine-broker.ts
|
|
17878
|
+
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
17879
|
+
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
17880
|
+
var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
17881
|
+
var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
|
|
17882
|
+
var FORWARD_REQUEST_PROOF = "forward-request";
|
|
17883
|
+
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
17884
|
+
var IDLE_MS = 5 * 6e4;
|
|
17885
|
+
function descriptorPath(directory, generation) {
|
|
17886
|
+
return join6(directory, `machine_broker_${generation}.json`);
|
|
17887
|
+
}
|
|
17888
|
+
function readDescriptor(path9) {
|
|
17889
|
+
try {
|
|
17890
|
+
const stat = lstatSync2(path9);
|
|
17891
|
+
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
17892
|
+
return void 0;
|
|
17893
|
+
const data = JSON.parse(readFileSync4(path9, "utf8"));
|
|
17894
|
+
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;
|
|
17895
|
+
} catch {
|
|
17896
|
+
return void 0;
|
|
17897
|
+
}
|
|
17898
|
+
}
|
|
17899
|
+
function signature(secret, nonce, body, purpose) {
|
|
17900
|
+
return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
|
|
17901
|
+
}
|
|
17902
|
+
function matches(left, right) {
|
|
17903
|
+
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
17904
|
+
}
|
|
17905
|
+
function tokenHash(token) {
|
|
17906
|
+
return token ? createHash2("sha256").update(token).digest("hex") : void 0;
|
|
17907
|
+
}
|
|
17908
|
+
async function brokerRequest(descriptor, environment, options) {
|
|
17909
|
+
const body = JSON.stringify({
|
|
17910
|
+
generation: environment.generation,
|
|
17911
|
+
force: options.force === true,
|
|
17912
|
+
observedTokenHash: tokenHash(options.observedToken),
|
|
17913
|
+
timestamp: Date.now()
|
|
17914
|
+
});
|
|
17915
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
17916
|
+
method: "POST",
|
|
17917
|
+
body,
|
|
17918
|
+
signal: options.signal,
|
|
17919
|
+
headers: {
|
|
17920
|
+
"Content-Type": "application/json",
|
|
17921
|
+
"X-Prim-Proof": signature(environment.clientSecret, descriptor.nonce, body)
|
|
17922
|
+
}
|
|
17923
|
+
});
|
|
17924
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_RESPONSE_BYTES));
|
|
17925
|
+
if (typeof envelope.body !== "string" || !matches(signature(environment.clientSecret, descriptor.nonce, envelope.body), envelope.proof))
|
|
17926
|
+
throw new MachineAuthError(
|
|
17927
|
+
"broker_unavailable",
|
|
17928
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
17929
|
+
);
|
|
17930
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
17931
|
+
if (data.error) {
|
|
17932
|
+
const error = machineRecord(data.error);
|
|
17933
|
+
throw new MachineAuthError(
|
|
17934
|
+
String(error.code),
|
|
17935
|
+
String(error.message),
|
|
17936
|
+
error.terminal === true,
|
|
17937
|
+
typeof error.retryAt === "number" ? error.retryAt : void 0
|
|
17938
|
+
);
|
|
17939
|
+
}
|
|
17940
|
+
const credential = data.credential;
|
|
17941
|
+
if (credential?.generation !== environment.generation || credential.clientId !== environment.clientId || credential.storage !== "environment")
|
|
17942
|
+
throw new MachineAuthError(
|
|
17943
|
+
"identity_changed",
|
|
17944
|
+
"Machine identity changed; restart the operation."
|
|
17945
|
+
);
|
|
17946
|
+
return credential;
|
|
17947
|
+
}
|
|
17948
|
+
function brokerEnvironment(options) {
|
|
17949
|
+
const routed = options.environment.secretInjection || options.environment.tokenInjection;
|
|
17950
|
+
return {
|
|
17951
|
+
...options.env,
|
|
17952
|
+
PRIM_API_URL: options.apiUrl,
|
|
17953
|
+
PRIM_CONFIG_DIR: options.directory,
|
|
17954
|
+
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
17955
|
+
};
|
|
17956
|
+
}
|
|
17957
|
+
async function acquireBrokerCredential(options) {
|
|
17958
|
+
const path9 = descriptorPath(options.directory, options.environment.generation);
|
|
17959
|
+
const existing = readDescriptor(path9);
|
|
17960
|
+
if (existing) {
|
|
17961
|
+
try {
|
|
17962
|
+
return await brokerRequest(existing, options.environment, options);
|
|
17963
|
+
} catch (error) {
|
|
17964
|
+
options.signal.throwIfAborted();
|
|
17965
|
+
if (error instanceof MachineAuthError) throw error;
|
|
17966
|
+
}
|
|
17967
|
+
}
|
|
17968
|
+
const descriptor = await ensureBroker(options);
|
|
17969
|
+
try {
|
|
17970
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
17971
|
+
} catch (error) {
|
|
17972
|
+
options.signal.throwIfAborted();
|
|
17973
|
+
if (error instanceof MachineAuthError) throw error;
|
|
17974
|
+
throw new MachineAuthError(
|
|
17975
|
+
"broker_unavailable",
|
|
17976
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
17977
|
+
);
|
|
17978
|
+
}
|
|
17979
|
+
}
|
|
17980
|
+
async function ensureBroker(options) {
|
|
17981
|
+
const path9 = descriptorPath(options.directory, options.environment.generation);
|
|
17982
|
+
return withFileLock(
|
|
17983
|
+
join6(options.directory, "machine-broker.lock"),
|
|
17984
|
+
async () => {
|
|
17985
|
+
const current = readDescriptor(path9);
|
|
17986
|
+
if (current) {
|
|
17987
|
+
try {
|
|
17988
|
+
const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
|
|
17989
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
17990
|
+
});
|
|
17991
|
+
if (response.ok && await response.text() === current.nonce) return current;
|
|
17188
17992
|
} catch {
|
|
17189
17993
|
options.signal.throwIfAborted();
|
|
17190
17994
|
}
|
|
17191
17995
|
}
|
|
17192
|
-
const bundled =
|
|
17996
|
+
const bundled = fileURLToPath5(import.meta.url);
|
|
17193
17997
|
const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
17194
17998
|
if (!entry)
|
|
17195
17999
|
throw new MachineAuthError(
|
|
@@ -17327,26 +18131,26 @@ async function forwardBrokerRequest(options) {
|
|
|
17327
18131
|
}
|
|
17328
18132
|
|
|
17329
18133
|
// src/lib/machine-retry.ts
|
|
17330
|
-
import { createHash as
|
|
17331
|
-
import { lstatSync as
|
|
17332
|
-
import { join as
|
|
18134
|
+
import { createHash as createHash3 } from "crypto";
|
|
18135
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync5 } from "fs";
|
|
18136
|
+
import { join as join7 } from "path";
|
|
17333
18137
|
function clearMachineCooldowns(directory) {
|
|
17334
18138
|
let names;
|
|
17335
18139
|
try {
|
|
17336
|
-
names =
|
|
18140
|
+
names = readdirSync2(directory);
|
|
17337
18141
|
} catch {
|
|
17338
18142
|
return;
|
|
17339
18143
|
}
|
|
17340
18144
|
for (const name2 of names) {
|
|
17341
18145
|
if (!/^machine_retry_[0-9a-f]{64}\.json$/u.test(name2)) continue;
|
|
17342
|
-
const path9 =
|
|
18146
|
+
const path9 = join7(directory, name2);
|
|
17343
18147
|
try {
|
|
17344
|
-
const state = JSON.parse(
|
|
18148
|
+
const state = JSON.parse(readFileSync5(path9, "utf8"));
|
|
17345
18149
|
if (state.serverRetryAfter === true) continue;
|
|
17346
18150
|
} catch {
|
|
17347
18151
|
}
|
|
17348
18152
|
try {
|
|
17349
|
-
|
|
18153
|
+
rmSync5(path9, { force: true });
|
|
17350
18154
|
} catch {
|
|
17351
18155
|
}
|
|
17352
18156
|
}
|
|
@@ -17355,16 +18159,16 @@ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
|
17355
18159
|
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
17356
18160
|
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
17357
18161
|
signal?.throwIfAborted();
|
|
17358
|
-
const key =
|
|
17359
|
-
const path9 =
|
|
18162
|
+
const key = createHash3("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
18163
|
+
const path9 = join7(directory, `machine_retry_${key}.json`);
|
|
17360
18164
|
let state = {
|
|
17361
18165
|
failures: 0,
|
|
17362
18166
|
retryAt: 0
|
|
17363
18167
|
};
|
|
17364
18168
|
try {
|
|
17365
|
-
const stat =
|
|
18169
|
+
const stat = lstatSync3(path9);
|
|
17366
18170
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
17367
|
-
const data = JSON.parse(
|
|
18171
|
+
const data = JSON.parse(readFileSync5(path9, "utf8"));
|
|
17368
18172
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
17369
18173
|
throw new Error("Invalid retry state");
|
|
17370
18174
|
state = data;
|
|
@@ -17388,7 +18192,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
17388
18192
|
);
|
|
17389
18193
|
try {
|
|
17390
18194
|
const result = await request3();
|
|
17391
|
-
|
|
18195
|
+
rmSync5(path9, { force: true });
|
|
17392
18196
|
return result;
|
|
17393
18197
|
} catch (error) {
|
|
17394
18198
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -17417,16 +18221,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
17417
18221
|
|
|
17418
18222
|
// src/lib/session-identity.ts
|
|
17419
18223
|
import { execFile } from "child_process";
|
|
17420
|
-
import { createHash as
|
|
17421
|
-
import { rmSync as
|
|
17422
|
-
import { join as
|
|
18224
|
+
import { createHash as createHash5 } from "crypto";
|
|
18225
|
+
import { rmSync as rmSync6 } from "fs";
|
|
18226
|
+
import { join as join9 } from "path";
|
|
17423
18227
|
import { promisify as promisify2 } from "util";
|
|
17424
18228
|
|
|
17425
18229
|
// src/lib/git.ts
|
|
17426
18230
|
import { execFileSync } from "child_process";
|
|
17427
|
-
import { createHash as
|
|
17428
|
-
import { lstatSync as
|
|
17429
|
-
import { basename as basename2, dirname as
|
|
18231
|
+
import { createHash as createHash4 } from "crypto";
|
|
18232
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
|
|
18233
|
+
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve2, sep } from "path";
|
|
17430
18234
|
var GIT_TIMEOUT_MS = 1e3;
|
|
17431
18235
|
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
17432
18236
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
@@ -17462,9 +18266,9 @@ function mainWorktreeRoot(cwd) {
|
|
|
17462
18266
|
timeout: GIT_TIMEOUT_MS,
|
|
17463
18267
|
env: gitChildEnvironment()
|
|
17464
18268
|
}
|
|
17465
|
-
).trim().split("\n").map((value) =>
|
|
18269
|
+
).trim().split("\n").map((value) => resolve2(cwd ?? process.cwd(), value));
|
|
17466
18270
|
if (gitDir === void 0 || commonDir === void 0 || gitDir === commonDir) return null;
|
|
17467
|
-
return basename2(commonDir) === ".git" ?
|
|
18271
|
+
return basename2(commonDir) === ".git" ? dirname6(commonDir) : null;
|
|
17468
18272
|
} catch {
|
|
17469
18273
|
return null;
|
|
17470
18274
|
}
|
|
@@ -17523,12 +18327,12 @@ function isGitIgnored(cwd, path9) {
|
|
|
17523
18327
|
}
|
|
17524
18328
|
}
|
|
17525
18329
|
function checkoutSettingsText(repoRoot) {
|
|
17526
|
-
const path9 =
|
|
18330
|
+
const path9 = join8(repoRoot, ".claude", "settings.json");
|
|
17527
18331
|
try {
|
|
17528
|
-
if (!
|
|
17529
|
-
const stat =
|
|
18332
|
+
if (!lstatSync4(join8(repoRoot, ".claude")).isDirectory()) return null;
|
|
18333
|
+
const stat = lstatSync4(path9);
|
|
17530
18334
|
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
17531
|
-
return
|
|
18335
|
+
return readFileSync6(path9, "utf8");
|
|
17532
18336
|
} catch {
|
|
17533
18337
|
return null;
|
|
17534
18338
|
}
|
|
@@ -17562,7 +18366,7 @@ function githubRepositoryFullName(cwd) {
|
|
|
17562
18366
|
function canonicalGitRoot(cwd) {
|
|
17563
18367
|
try {
|
|
17564
18368
|
const top = gitToplevel(cwd);
|
|
17565
|
-
return top ?
|
|
18369
|
+
return top ? realpathSync2.native(top) : null;
|
|
17566
18370
|
} catch {
|
|
17567
18371
|
return null;
|
|
17568
18372
|
}
|
|
@@ -17593,19 +18397,19 @@ function nearestExistingAncestor(path9) {
|
|
|
17593
18397
|
let cursor = path9;
|
|
17594
18398
|
while (true) {
|
|
17595
18399
|
try {
|
|
17596
|
-
|
|
18400
|
+
lstatSync4(cursor);
|
|
17597
18401
|
break;
|
|
17598
18402
|
} catch (error) {
|
|
17599
18403
|
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
17600
18404
|
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
17601
|
-
const parent =
|
|
18405
|
+
const parent = dirname6(cursor);
|
|
17602
18406
|
if (parent === cursor) return null;
|
|
17603
18407
|
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
17604
18408
|
cursor = parent;
|
|
17605
18409
|
}
|
|
17606
18410
|
}
|
|
17607
18411
|
try {
|
|
17608
|
-
return { real:
|
|
18412
|
+
return { real: realpathSync2.native(cursor), suffix };
|
|
17609
18413
|
} catch {
|
|
17610
18414
|
return null;
|
|
17611
18415
|
}
|
|
@@ -17614,13 +18418,13 @@ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
|
17614
18418
|
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
17615
18419
|
return { ok: false, reason: "invalid_path" };
|
|
17616
18420
|
}
|
|
17617
|
-
const absolute =
|
|
18421
|
+
const absolute = resolve2(baseDir, filePath);
|
|
17618
18422
|
const resolved = nearestExistingAncestor(absolute);
|
|
17619
18423
|
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
17620
|
-
const target =
|
|
18424
|
+
const target = resolve2(resolved.real, ...resolved.suffix);
|
|
17621
18425
|
const rel = relative(context.repoRoot, target);
|
|
17622
18426
|
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
17623
|
-
if (
|
|
18427
|
+
if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
17624
18428
|
return { ok: false, reason: "outside_repository" };
|
|
17625
18429
|
}
|
|
17626
18430
|
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
@@ -17628,26 +18432,26 @@ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
|
17628
18432
|
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot2 = canonicalGitRoot(cwd)) {
|
|
17629
18433
|
if (!repositoryRoot2 || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
17630
18434
|
return null;
|
|
17631
|
-
const absolute =
|
|
18435
|
+
const absolute = resolve2(cwd, filePath);
|
|
17632
18436
|
let target;
|
|
17633
18437
|
try {
|
|
17634
|
-
const stat =
|
|
18438
|
+
const stat = lstatSync4(absolute);
|
|
17635
18439
|
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
17636
|
-
target =
|
|
18440
|
+
target = realpathSync2.native(absolute);
|
|
17637
18441
|
} catch (error) {
|
|
17638
18442
|
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
17639
18443
|
return null;
|
|
17640
18444
|
}
|
|
17641
18445
|
try {
|
|
17642
|
-
const parent =
|
|
17643
|
-
if (!
|
|
17644
|
-
target =
|
|
18446
|
+
const parent = realpathSync2.native(dirname6(absolute));
|
|
18447
|
+
if (!lstatSync4(parent).isDirectory()) return null;
|
|
18448
|
+
target = resolve2(parent, basename2(absolute));
|
|
17645
18449
|
} catch {
|
|
17646
18450
|
return null;
|
|
17647
18451
|
}
|
|
17648
18452
|
}
|
|
17649
18453
|
const rel = relative(repositoryRoot2, target);
|
|
17650
|
-
if (!rel ||
|
|
18454
|
+
if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
17651
18455
|
return null;
|
|
17652
18456
|
}
|
|
17653
18457
|
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
@@ -17806,7 +18610,7 @@ function sessionIdentityMessage(outcome) {
|
|
|
17806
18610
|
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
17807
18611
|
}
|
|
17808
18612
|
function hash(value) {
|
|
17809
|
-
return
|
|
18613
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
17810
18614
|
}
|
|
17811
18615
|
function sessionContext(deps) {
|
|
17812
18616
|
const env4 = deps.env ?? process.env;
|
|
@@ -17833,9 +18637,9 @@ function sessionContext(deps) {
|
|
|
17833
18637
|
clientId: environment.clientId,
|
|
17834
18638
|
generation: environment.generation,
|
|
17835
18639
|
sessionId,
|
|
17836
|
-
tokenPath:
|
|
17837
|
-
statePath:
|
|
17838
|
-
lockPath:
|
|
18640
|
+
tokenPath: join9(directory, `session_identity_${key}.json`),
|
|
18641
|
+
statePath: join9(directory, `session_identity_${key}.state.json`),
|
|
18642
|
+
lockPath: join9(directory, "session-identity.lock")
|
|
17839
18643
|
};
|
|
17840
18644
|
}
|
|
17841
18645
|
function readRecord(path9) {
|
|
@@ -17867,7 +18671,7 @@ function readState(context) {
|
|
|
17867
18671
|
function writeToken(context, record3) {
|
|
17868
18672
|
prepareMachineMetadataDirectory(context.directory);
|
|
17869
18673
|
writeMachineMetadata(context.tokenPath, record3);
|
|
17870
|
-
|
|
18674
|
+
rmSync6(context.statePath, { force: true });
|
|
17871
18675
|
}
|
|
17872
18676
|
function writeState(context, state) {
|
|
17873
18677
|
try {
|
|
@@ -18477,7 +19281,7 @@ async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
|
18477
19281
|
return identified(refreshed.record, true);
|
|
18478
19282
|
}
|
|
18479
19283
|
if (refreshed.status === "refused") {
|
|
18480
|
-
|
|
19284
|
+
rmSync6(ctx.tokenPath, { force: true });
|
|
18481
19285
|
writeState(ctx, {
|
|
18482
19286
|
sessionId: ctx.sessionId,
|
|
18483
19287
|
status: "failed",
|
|
@@ -18716,7 +19520,7 @@ async function linkSessionIdentity(challenge, humanAccessToken, options = {}, de
|
|
|
18716
19520
|
function sessionScoped(deps) {
|
|
18717
19521
|
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
18718
19522
|
}
|
|
18719
|
-
var
|
|
19523
|
+
var require3 = createRequire2(import.meta.url);
|
|
18720
19524
|
var SERVICE = "ai.primitive.prim.machine";
|
|
18721
19525
|
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
18722
19526
|
var PROFILE_FILE = "machine_profile.json";
|
|
@@ -18729,16 +19533,16 @@ function apiUrlFor(deps) {
|
|
|
18729
19533
|
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
18730
19534
|
}
|
|
18731
19535
|
function hash2(value) {
|
|
18732
|
-
return
|
|
19536
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
18733
19537
|
}
|
|
18734
19538
|
function recordPath(directory, generation) {
|
|
18735
|
-
return
|
|
19539
|
+
return join10(directory, `machine_${generation}.json`);
|
|
18736
19540
|
}
|
|
18737
19541
|
function storageKey(directory, generation) {
|
|
18738
19542
|
return `${hash2(directory)}:${generation}`;
|
|
18739
19543
|
}
|
|
18740
19544
|
function environmentContextPath(deps, clientId) {
|
|
18741
|
-
return
|
|
19545
|
+
return join10(
|
|
18742
19546
|
configurationDirectory(deps),
|
|
18743
19547
|
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
18744
19548
|
);
|
|
@@ -18798,22 +19602,28 @@ function readEnvironmentContext(environment, deps) {
|
|
|
18798
19602
|
return void 0;
|
|
18799
19603
|
}
|
|
18800
19604
|
}
|
|
18801
|
-
function
|
|
18802
|
-
let directory =
|
|
19605
|
+
function keyringLoaderPath(start, options = {}) {
|
|
19606
|
+
let directory = start;
|
|
18803
19607
|
for (let depth = 0; depth < 5; depth++) {
|
|
18804
|
-
const loader =
|
|
18805
|
-
if (
|
|
18806
|
-
|
|
18807
|
-
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
18808
|
-
}
|
|
18809
|
-
directory = dirname5(directory);
|
|
19608
|
+
const loader = join10(directory, "native", "keyring.cjs");
|
|
19609
|
+
if (existsSync5(loader)) return loader;
|
|
19610
|
+
directory = dirname7(directory);
|
|
18810
19611
|
}
|
|
18811
|
-
|
|
19612
|
+
try {
|
|
19613
|
+
createRequire2(join10(start, "noop.js")).resolve("@napi-rs/keyring");
|
|
19614
|
+
return void 0;
|
|
19615
|
+
} catch {
|
|
19616
|
+
return selectedHookRuntimeKeyringLoader(options);
|
|
19617
|
+
}
|
|
19618
|
+
}
|
|
19619
|
+
function keyringEntry(key) {
|
|
19620
|
+
const loader = keyringLoaderPath(dirname7(fileURLToPath6(import.meta.url)));
|
|
19621
|
+
const module = require3(loader ?? "@napi-rs/keyring");
|
|
18812
19622
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
18813
19623
|
}
|
|
18814
19624
|
function protectPath(path9, directory) {
|
|
18815
19625
|
if (process.platform !== "win32") {
|
|
18816
|
-
|
|
19626
|
+
chmodSync2(path9, directory ? 448 : 384);
|
|
18817
19627
|
return;
|
|
18818
19628
|
}
|
|
18819
19629
|
const encodedPath = Buffer.from(path9).toString("base64");
|
|
@@ -18830,8 +19640,8 @@ function protectPath(path9, directory) {
|
|
|
18830
19640
|
);
|
|
18831
19641
|
}
|
|
18832
19642
|
function ensureDirectory(directory) {
|
|
18833
|
-
|
|
18834
|
-
if (
|
|
19643
|
+
mkdirSync4(directory, { recursive: true, mode: 448 });
|
|
19644
|
+
if (lstatSync5(directory).isSymbolicLink())
|
|
18835
19645
|
throw new MachineAuthError(
|
|
18836
19646
|
"unsafe_storage",
|
|
18837
19647
|
"Credential directory must not be a symbolic link."
|
|
@@ -18849,14 +19659,14 @@ function readMachineMetadata(path9) {
|
|
|
18849
19659
|
function readPrivate(path9) {
|
|
18850
19660
|
let raw;
|
|
18851
19661
|
try {
|
|
18852
|
-
const stat =
|
|
19662
|
+
const stat = lstatSync5(path9);
|
|
18853
19663
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
18854
19664
|
throw new MachineAuthError(
|
|
18855
19665
|
"unsafe_storage",
|
|
18856
19666
|
"Machine credential files must be owner-only regular files."
|
|
18857
19667
|
);
|
|
18858
19668
|
}
|
|
18859
|
-
raw =
|
|
19669
|
+
raw = readFileSync7(path9, "utf8");
|
|
18860
19670
|
} catch (error) {
|
|
18861
19671
|
if (error.code === "ENOENT") return void 0;
|
|
18862
19672
|
throw error;
|
|
@@ -18901,7 +19711,7 @@ function parseProfile(value) {
|
|
|
18901
19711
|
};
|
|
18902
19712
|
}
|
|
18903
19713
|
function readMachineProfile(deps = {}) {
|
|
18904
|
-
const value = readPrivate(
|
|
19714
|
+
const value = readPrivate(join10(configurationDirectory(deps), PROFILE_FILE));
|
|
18905
19715
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
18906
19716
|
}
|
|
18907
19717
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -18910,20 +19720,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
18910
19720
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
18911
19721
|
function networkSecretBrokerKey(deps, clientId) {
|
|
18912
19722
|
const directory = configurationDirectory(deps);
|
|
18913
|
-
const path9 =
|
|
19723
|
+
const path9 = join10(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
18914
19724
|
const known = brokerKeys.get(path9);
|
|
18915
19725
|
if (known) return known;
|
|
18916
19726
|
ensureDirectory(directory);
|
|
18917
19727
|
const read = () => {
|
|
18918
19728
|
try {
|
|
18919
|
-
const stat =
|
|
19729
|
+
const stat = lstatSync5(path9);
|
|
18920
19730
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
18921
19731
|
throw new MachineAuthError(
|
|
18922
19732
|
"unsafe_storage",
|
|
18923
19733
|
`The machine broker key at ${path9} is not an owner-only file. Delete it and retry.`,
|
|
18924
19734
|
true
|
|
18925
19735
|
);
|
|
18926
|
-
const value =
|
|
19736
|
+
const value = readFileSync7(path9, "utf8").trim();
|
|
18927
19737
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
18928
19738
|
} catch (error) {
|
|
18929
19739
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -18942,16 +19752,16 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
18942
19752
|
`The machine broker key at ${path9} is damaged. Delete it and retry.`,
|
|
18943
19753
|
true
|
|
18944
19754
|
);
|
|
18945
|
-
const staged = `${path9}.${process.pid}.${
|
|
19755
|
+
const staged = `${path9}.${process.pid}.${randomBytes4(6).toString("hex")}`;
|
|
18946
19756
|
try {
|
|
18947
|
-
|
|
19757
|
+
writeFileSync5(staged, `${randomBytes4(32).toString("hex")}
|
|
18948
19758
|
`, { mode: 384, flag: "wx" });
|
|
18949
19759
|
protectPath(staged, false);
|
|
18950
19760
|
linkSync(staged, path9);
|
|
18951
19761
|
} catch (error) {
|
|
18952
19762
|
if (error.code !== "EEXIST") throw error;
|
|
18953
19763
|
} finally {
|
|
18954
|
-
|
|
19764
|
+
rmSync7(staged, { force: true });
|
|
18955
19765
|
}
|
|
18956
19766
|
}
|
|
18957
19767
|
const key = read()?.key;
|
|
@@ -19010,7 +19820,7 @@ function environmentCredentials(deps) {
|
|
|
19010
19820
|
}
|
|
19011
19821
|
function hasMachineConfiguration(deps = {}) {
|
|
19012
19822
|
const env4 = deps.env ?? process.env;
|
|
19013
|
-
const configured = env4.PRIM_M2M_CLIENT_ID !== void 0 || env4.PRIM_M2M_CLIENT_SECRET !== void 0 || env4.PRIM_M2M_CLIENT_AUTH !== void 0 ||
|
|
19823
|
+
const configured = env4.PRIM_M2M_CLIENT_ID !== void 0 || env4.PRIM_M2M_CLIENT_SECRET !== void 0 || env4.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join10(configurationDirectory(deps), PROFILE_FILE));
|
|
19014
19824
|
if (configured && env4.PRIM_TOKEN?.trim()) {
|
|
19015
19825
|
throw new MachineAuthError(
|
|
19016
19826
|
"conflicting_credentials",
|
|
@@ -19046,7 +19856,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
19046
19856
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
19047
19857
|
if (!generation) return false;
|
|
19048
19858
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
19049
|
-
return readPrivate(
|
|
19859
|
+
return readPrivate(join10(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
19050
19860
|
}
|
|
19051
19861
|
var environmentTerminal;
|
|
19052
19862
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -19119,7 +19929,7 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
|
|
|
19119
19929
|
const directory = configurationDirectory(deps);
|
|
19120
19930
|
ensureDirectory(directory);
|
|
19121
19931
|
return withFileLock(
|
|
19122
|
-
|
|
19932
|
+
join10(directory, "credentials.lock"),
|
|
19123
19933
|
async () => {
|
|
19124
19934
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
19125
19935
|
directory,
|
|
@@ -19175,11 +19985,11 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
|
|
|
19175
19985
|
profile = { ...profile, storage: "file" };
|
|
19176
19986
|
await persistRecord({ ...profile, ...tokens, clientSecret }, deps, signal);
|
|
19177
19987
|
}
|
|
19178
|
-
writePrivate(
|
|
19179
|
-
|
|
19988
|
+
writePrivate(join10(directory, PROFILE_FILE), profile);
|
|
19989
|
+
rmSync7(join10(directory, "machine_terminal.json"), { force: true });
|
|
19180
19990
|
cached = { ...profile, ...tokens };
|
|
19181
19991
|
if (previous) {
|
|
19182
|
-
writePrivate(
|
|
19992
|
+
writePrivate(join10(directory, "machine_retired.json"), [...retired, previous]);
|
|
19183
19993
|
}
|
|
19184
19994
|
await cleanupRetired(deps, signal);
|
|
19185
19995
|
return profile;
|
|
@@ -19218,7 +20028,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
19218
20028
|
}
|
|
19219
20029
|
}
|
|
19220
20030
|
return withFileLock(
|
|
19221
|
-
|
|
20031
|
+
join10(directory2, "credentials.lock"),
|
|
19222
20032
|
async () => {
|
|
19223
20033
|
if (machineSessionEnded(deps))
|
|
19224
20034
|
throw new MachineAuthError(
|
|
@@ -19300,7 +20110,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
19300
20110
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
19301
20111
|
try {
|
|
19302
20112
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
19303
|
-
|
|
20113
|
+
rmSync7(contextPath, { force: true });
|
|
19304
20114
|
} catch {
|
|
19305
20115
|
}
|
|
19306
20116
|
throw error;
|
|
@@ -19310,7 +20120,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
19310
20120
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
19311
20121
|
try {
|
|
19312
20122
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
19313
|
-
|
|
20123
|
+
rmSync7(contextPath, { force: true });
|
|
19314
20124
|
} catch {
|
|
19315
20125
|
}
|
|
19316
20126
|
}
|
|
@@ -19324,7 +20134,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
19324
20134
|
const expected = machineContext(deps);
|
|
19325
20135
|
const directory = configurationDirectory(deps);
|
|
19326
20136
|
return withFileLock(
|
|
19327
|
-
|
|
20137
|
+
join10(directory, "credentials.lock"),
|
|
19328
20138
|
async () => {
|
|
19329
20139
|
const profile = readMachineProfile(deps);
|
|
19330
20140
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -19374,7 +20184,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
19374
20184
|
await persistRecord(record3, deps, signal);
|
|
19375
20185
|
} catch (error) {
|
|
19376
20186
|
if (error instanceof MachineAuthError && error.terminal)
|
|
19377
|
-
writePrivate(
|
|
20187
|
+
writePrivate(join10(directory, "machine_terminal.json"), profile.generation);
|
|
19378
20188
|
throw error;
|
|
19379
20189
|
}
|
|
19380
20190
|
}
|
|
@@ -19416,12 +20226,12 @@ async function verifyAcquiredMachineIdentity(machine, deps = {}) {
|
|
|
19416
20226
|
}
|
|
19417
20227
|
async function clearMachineCredentials(deps = {}) {
|
|
19418
20228
|
const directory = configurationDirectory(deps);
|
|
19419
|
-
if (!
|
|
19420
|
-
return withFileLock(
|
|
20229
|
+
if (!existsSync5(join10(directory, PROFILE_FILE))) return false;
|
|
20230
|
+
return withFileLock(join10(directory, "credentials.lock"), async () => {
|
|
19421
20231
|
const profile = readMachineProfile(deps);
|
|
19422
20232
|
if (!profile) return false;
|
|
19423
20233
|
await cleanupRetired(deps, AbortSignal.timeout(1e4));
|
|
19424
|
-
if (
|
|
20234
|
+
if (existsSync5(join10(directory, "machine_retired.json")))
|
|
19425
20235
|
throw new MachineAuthError(
|
|
19426
20236
|
"storage_unavailable",
|
|
19427
20237
|
"Unlock the credential store to remove retired machine credentials."
|
|
@@ -19437,9 +20247,9 @@ async function clearMachineCredentials(deps = {}) {
|
|
|
19437
20247
|
"Unlock the keychain to remove the saved machine credential."
|
|
19438
20248
|
);
|
|
19439
20249
|
}
|
|
19440
|
-
} else
|
|
19441
|
-
|
|
19442
|
-
|
|
20250
|
+
} else rmSync7(recordPath(directory, profile.generation), { force: true });
|
|
20251
|
+
rmSync7(join10(directory, PROFILE_FILE), { force: true });
|
|
20252
|
+
rmSync7(join10(directory, "machine_terminal.json"), { force: true });
|
|
19443
20253
|
cached = void 0;
|
|
19444
20254
|
return true;
|
|
19445
20255
|
});
|
|
@@ -19454,7 +20264,7 @@ function machinePendingBucket(identity) {
|
|
|
19454
20264
|
return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
19455
20265
|
}
|
|
19456
20266
|
function readRetiredProfiles(directory) {
|
|
19457
|
-
const value = readPrivate(
|
|
20267
|
+
const value = readPrivate(join10(directory, "machine_retired.json"));
|
|
19458
20268
|
if (value === void 0) return [];
|
|
19459
20269
|
if (!Array.isArray(value))
|
|
19460
20270
|
throw new MachineAuthError(
|
|
@@ -19465,20 +20275,20 @@ function readRetiredProfiles(directory) {
|
|
|
19465
20275
|
}
|
|
19466
20276
|
async function cleanupRetired(deps, signal) {
|
|
19467
20277
|
const directory = configurationDirectory(deps);
|
|
19468
|
-
const path9 =
|
|
20278
|
+
const path9 = join10(directory, "machine_retired.json");
|
|
19469
20279
|
const pending = [];
|
|
19470
20280
|
for (const profile of readRetiredProfiles(directory)) {
|
|
19471
20281
|
try {
|
|
19472
20282
|
if (profile.storage === "keychain") {
|
|
19473
20283
|
const entry = (deps.entry ?? keyringEntry)(storageKey(directory, profile.generation));
|
|
19474
20284
|
if (await entry.getPassword(signal) !== null) await entry.deletePassword(signal);
|
|
19475
|
-
} else
|
|
20285
|
+
} else rmSync7(recordPath(directory, profile.generation), { force: true });
|
|
19476
20286
|
} catch {
|
|
19477
20287
|
pending.push(profile);
|
|
19478
20288
|
}
|
|
19479
20289
|
}
|
|
19480
20290
|
if (pending.length) writePrivate(path9, pending);
|
|
19481
|
-
else
|
|
20291
|
+
else rmSync7(path9, { force: true });
|
|
19482
20292
|
}
|
|
19483
20293
|
function prepareMachineMetadataDirectory(directory) {
|
|
19484
20294
|
ensureDirectory(directory);
|
|
@@ -19489,20 +20299,20 @@ function writeMachineMetadata(path9, value) {
|
|
|
19489
20299
|
|
|
19490
20300
|
// src/lib/credentials.ts
|
|
19491
20301
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
19492
|
-
var TOKEN_FILE_PATH =
|
|
19493
|
-
var REFRESH_TOKEN_PATH =
|
|
19494
|
-
var TOKEN_EXPIRES_PATH =
|
|
19495
|
-
var TERMINAL_REFRESH_PATH =
|
|
19496
|
-
var CREDENTIAL_METADATA_PATH =
|
|
19497
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
19498
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
19499
|
-
var CREDENTIAL_LOCK_PATH =
|
|
20302
|
+
var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
|
|
20303
|
+
var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
|
|
20304
|
+
var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
|
|
20305
|
+
var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
|
|
20306
|
+
var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
20307
|
+
var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
|
|
20308
|
+
var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
|
|
20309
|
+
var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
|
|
19500
20310
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
19501
20311
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
19502
20312
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
19503
20313
|
function readTrimmed(path9) {
|
|
19504
20314
|
try {
|
|
19505
|
-
const value =
|
|
20315
|
+
const value = readFileSync8(path9, "utf8").trim();
|
|
19506
20316
|
return value || void 0;
|
|
19507
20317
|
} catch {
|
|
19508
20318
|
return void 0;
|
|
@@ -19542,15 +20352,15 @@ function resolveStoredCredential(env4 = process.env) {
|
|
|
19542
20352
|
const directory = primConfigDirectory({ env: env4 });
|
|
19543
20353
|
return resolveAuthCredential({
|
|
19544
20354
|
env: env4,
|
|
19545
|
-
tokenFilePath:
|
|
19546
|
-
refreshTokenPath:
|
|
19547
|
-
metadataPath:
|
|
19548
|
-
familyPath:
|
|
19549
|
-
migrationPath:
|
|
20355
|
+
tokenFilePath: join11(directory, "token"),
|
|
20356
|
+
refreshTokenPath: join11(directory, "refresh_token"),
|
|
20357
|
+
metadataPath: join11(directory, "credential_metadata.json"),
|
|
20358
|
+
familyPath: join11(directory, "credential_family.json"),
|
|
20359
|
+
migrationPath: join11(directory, "credential_migration.json")
|
|
19550
20360
|
});
|
|
19551
20361
|
}
|
|
19552
20362
|
function credentialFingerprint(value) {
|
|
19553
|
-
return
|
|
20363
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
19554
20364
|
}
|
|
19555
20365
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
19556
20366
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -19570,7 +20380,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
19570
20380
|
function readBoundedCredentialJson(path9) {
|
|
19571
20381
|
let raw;
|
|
19572
20382
|
try {
|
|
19573
|
-
raw =
|
|
20383
|
+
raw = readFileSync8(path9, "utf8");
|
|
19574
20384
|
} catch (error) {
|
|
19575
20385
|
return error.code === "ENOENT" ? void 0 : null;
|
|
19576
20386
|
}
|
|
@@ -19646,18 +20456,18 @@ var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
|
19646
20456
|
function boundedClaim(value) {
|
|
19647
20457
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
19648
20458
|
}
|
|
19649
|
-
function
|
|
19650
|
-
return
|
|
20459
|
+
function sha2562(value) {
|
|
20460
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
19651
20461
|
}
|
|
19652
20462
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
19653
20463
|
if (hasMachineConfiguration()) {
|
|
19654
20464
|
const machine = machineContext();
|
|
19655
20465
|
return machine ? {
|
|
19656
|
-
principalId:
|
|
20466
|
+
principalId: sha2562(
|
|
19657
20467
|
`${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
|
|
19658
20468
|
),
|
|
19659
20469
|
organizationId: machine.workosOrganizationId,
|
|
19660
|
-
credentialFingerprint:
|
|
20470
|
+
credentialFingerprint: sha2562(machine.generation)
|
|
19661
20471
|
} : void 0;
|
|
19662
20472
|
}
|
|
19663
20473
|
if (!token) return void 0;
|
|
@@ -19667,9 +20477,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
|
19667
20477
|
if (!(subject && organizationId)) return void 0;
|
|
19668
20478
|
const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
|
|
19669
20479
|
return {
|
|
19670
|
-
principalId:
|
|
20480
|
+
principalId: sha2562(`${issuer}\0${subject}`),
|
|
19671
20481
|
organizationId,
|
|
19672
|
-
credentialFingerprint:
|
|
20482
|
+
credentialFingerprint: sha2562(token)
|
|
19673
20483
|
};
|
|
19674
20484
|
}
|
|
19675
20485
|
|
|
@@ -19698,8 +20508,8 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
19698
20508
|
|
|
19699
20509
|
// src/daemon/client.ts
|
|
19700
20510
|
import { createConnection } from "net";
|
|
19701
|
-
import { join as
|
|
19702
|
-
var SOCK_PATH =
|
|
20511
|
+
import { join as join12 } from "path";
|
|
20512
|
+
var SOCK_PATH = join12(primConfigDirectory(), "sock");
|
|
19703
20513
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
19704
20514
|
var nextRequestId = 1;
|
|
19705
20515
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -19794,23 +20604,23 @@ async function daemonIsLive(timeoutMs2 = DEFAULT_TIMEOUT_MS2) {
|
|
|
19794
20604
|
|
|
19795
20605
|
// src/lib/activation.ts
|
|
19796
20606
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
19797
|
-
import { existsSync as
|
|
20607
|
+
import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
|
|
19798
20608
|
import { homedir as homedir2 } from "os";
|
|
19799
|
-
import { join as
|
|
20609
|
+
import { join as join14 } from "path";
|
|
19800
20610
|
|
|
19801
20611
|
// src/lib/cloud-prepared.ts
|
|
19802
|
-
import { existsSync as
|
|
19803
|
-
import { join as
|
|
20612
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync9, rmSync as rmSync8, writeFileSync as writeFileSync6 } from "fs";
|
|
20613
|
+
import { join as join13 } from "path";
|
|
19804
20614
|
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
19805
20615
|
var CLOUD_PREPARED_VERSION = "1";
|
|
19806
20616
|
var SESSION_ORIGIN = "session";
|
|
19807
20617
|
function cloudPreparedPath(env4 = process.env) {
|
|
19808
|
-
return
|
|
20618
|
+
return join13(primConfigDirectory({ env: env4 }), CLOUD_PREPARED_MARKER);
|
|
19809
20619
|
}
|
|
19810
20620
|
function markCloudPrepared(env4 = process.env, origin = "image") {
|
|
19811
20621
|
const directory = primConfigDirectory({ env: env4 });
|
|
19812
|
-
|
|
19813
|
-
|
|
20622
|
+
mkdirSync5(directory, { recursive: true, mode: 448 });
|
|
20623
|
+
writeFileSync6(
|
|
19814
20624
|
cloudPreparedPath(env4),
|
|
19815
20625
|
`${CLOUD_PREPARED_VERSION}${origin === "session" ? ` ${SESSION_ORIGIN}` : ""}
|
|
19816
20626
|
`,
|
|
@@ -19819,18 +20629,18 @@ function markCloudPrepared(env4 = process.env, origin = "image") {
|
|
|
19819
20629
|
}
|
|
19820
20630
|
function preparedInSession(env4 = process.env) {
|
|
19821
20631
|
try {
|
|
19822
|
-
return
|
|
20632
|
+
return readFileSync9(cloudPreparedPath(env4), "utf8").trim().split(/\s+/u)[1] === SESSION_ORIGIN;
|
|
19823
20633
|
} catch {
|
|
19824
20634
|
return false;
|
|
19825
20635
|
}
|
|
19826
20636
|
}
|
|
19827
20637
|
function clearCloudPrepared(env4 = process.env) {
|
|
19828
|
-
|
|
20638
|
+
rmSync8(cloudPreparedPath(env4), { force: true });
|
|
19829
20639
|
}
|
|
19830
20640
|
function isPreparedCloudSession(env4 = process.env) {
|
|
19831
20641
|
if (!isClaudeCloudSession(env4)) return false;
|
|
19832
20642
|
try {
|
|
19833
|
-
return
|
|
20643
|
+
return existsSync6(cloudPreparedPath(env4));
|
|
19834
20644
|
} catch {
|
|
19835
20645
|
return false;
|
|
19836
20646
|
}
|
|
@@ -20045,10 +20855,10 @@ function hasProjectPrimInstall(cwd) {
|
|
|
20045
20855
|
function projectPrimInstallAt(root) {
|
|
20046
20856
|
if (root === null || root === homedir2()) return false;
|
|
20047
20857
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
20048
|
-
const path9 =
|
|
20049
|
-
if (
|
|
20858
|
+
const path9 = join14(root, rel);
|
|
20859
|
+
if (existsSync7(path9)) {
|
|
20050
20860
|
try {
|
|
20051
|
-
const content2 =
|
|
20861
|
+
const content2 = readFileSync10(path9, "utf-8");
|
|
20052
20862
|
if (PRIM_HOOK_BINS.some((bin) => content2.includes(bin))) return true;
|
|
20053
20863
|
} catch {
|
|
20054
20864
|
}
|
|
@@ -20169,14 +20979,14 @@ function publicDecisionResponse(value) {
|
|
|
20169
20979
|
}
|
|
20170
20980
|
|
|
20171
20981
|
// src/client.ts
|
|
20172
|
-
import { createHash as
|
|
20173
|
-
import { chmodSync as
|
|
20174
|
-
import { dirname as
|
|
20982
|
+
import { createHash as createHash9 } from "crypto";
|
|
20983
|
+
import { chmodSync as chmodSync4, existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, rmSync as rmSync9 } from "fs";
|
|
20984
|
+
import { dirname as dirname8 } from "path";
|
|
20175
20985
|
|
|
20176
20986
|
// src/daemon/client-instance-id.ts
|
|
20177
|
-
import { randomBytes as
|
|
20178
|
-
import { chmodSync as
|
|
20179
|
-
import { join as
|
|
20987
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
20988
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync6, readFileSync as readFileSync11 } from "fs";
|
|
20989
|
+
import { join as join15 } from "path";
|
|
20180
20990
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
20181
20991
|
var INSTANCE_FILE_MODE = 384;
|
|
20182
20992
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -20189,17 +20999,17 @@ function isClientInstanceId(value) {
|
|
|
20189
20999
|
}
|
|
20190
21000
|
function ensurePrivateConfigDirectory(configDir) {
|
|
20191
21001
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
20192
|
-
const metadata =
|
|
21002
|
+
const metadata = lstatSync6(configDir);
|
|
20193
21003
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
20194
21004
|
throw new Error("prim config path must be a private directory");
|
|
20195
21005
|
}
|
|
20196
|
-
|
|
21006
|
+
chmodSync3(configDir, CONFIG_DIRECTORY_MODE);
|
|
20197
21007
|
syncDirectory(configDir);
|
|
20198
21008
|
}
|
|
20199
21009
|
function readExisting(path9) {
|
|
20200
21010
|
let metadata;
|
|
20201
21011
|
try {
|
|
20202
|
-
metadata =
|
|
21012
|
+
metadata = lstatSync6(path9);
|
|
20203
21013
|
} catch (error) {
|
|
20204
21014
|
if (error.code === "ENOENT") {
|
|
20205
21015
|
return;
|
|
@@ -20209,11 +21019,11 @@ function readExisting(path9) {
|
|
|
20209
21019
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
20210
21020
|
throw new Error("stored client instance identity is invalid");
|
|
20211
21021
|
}
|
|
20212
|
-
|
|
21022
|
+
chmodSync3(path9, INSTANCE_FILE_MODE);
|
|
20213
21023
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
20214
21024
|
throw new Error("stored client instance identity is invalid");
|
|
20215
21025
|
}
|
|
20216
|
-
const raw =
|
|
21026
|
+
const raw = readFileSync11(path9, "utf8");
|
|
20217
21027
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
20218
21028
|
if (raw !== value && raw !== `${value}
|
|
20219
21029
|
` || !isClientInstanceId(value)) {
|
|
@@ -20227,8 +21037,8 @@ function atomicWrite(path9, value) {
|
|
|
20227
21037
|
}
|
|
20228
21038
|
async function getOrCreateClientInstanceId(options) {
|
|
20229
21039
|
const configDir = options.configDir;
|
|
20230
|
-
const path9 =
|
|
20231
|
-
const lockPath =
|
|
21040
|
+
const path9 = join15(configDir, "client_instance_id");
|
|
21041
|
+
const lockPath = join15(configDir, "client-instance.lock");
|
|
20232
21042
|
ensurePrivateConfigDirectory(configDir);
|
|
20233
21043
|
return withFileLock(
|
|
20234
21044
|
lockPath,
|
|
@@ -20237,7 +21047,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
20237
21047
|
if (existing !== void 0) {
|
|
20238
21048
|
return existing;
|
|
20239
21049
|
}
|
|
20240
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
21050
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
20241
21051
|
"base64url"
|
|
20242
21052
|
)}`;
|
|
20243
21053
|
if (!isClientInstanceId(generated)) {
|
|
@@ -20283,7 +21093,7 @@ function authExpiredMessage() {
|
|
|
20283
21093
|
}
|
|
20284
21094
|
function readTrimmed2(path9) {
|
|
20285
21095
|
try {
|
|
20286
|
-
const value =
|
|
21096
|
+
const value = readFileSync12(path9, "utf8").trim();
|
|
20287
21097
|
return value || void 0;
|
|
20288
21098
|
} catch {
|
|
20289
21099
|
return void 0;
|
|
@@ -20299,17 +21109,17 @@ function expiresAtFor(token, expiresIn) {
|
|
|
20299
21109
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
20300
21110
|
}
|
|
20301
21111
|
function ensureConfigDirectory() {
|
|
20302
|
-
const directory =
|
|
20303
|
-
|
|
20304
|
-
|
|
21112
|
+
const directory = dirname8(TOKEN_FILE_PATH);
|
|
21113
|
+
mkdirSync6(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
21114
|
+
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
20305
21115
|
}
|
|
20306
21116
|
function atomicWrite2(path9, content2) {
|
|
20307
21117
|
ensureConfigDirectory();
|
|
20308
21118
|
atomicWriteFile(path9, content2, { mode: CREDENTIAL_FILE_MODE });
|
|
20309
21119
|
}
|
|
20310
21120
|
function removeCredentialFile(path9) {
|
|
20311
|
-
if (!
|
|
20312
|
-
|
|
21121
|
+
if (!existsSync8(path9)) return false;
|
|
21122
|
+
rmSync9(path9, { force: true });
|
|
20313
21123
|
return true;
|
|
20314
21124
|
}
|
|
20315
21125
|
function getTokenExpiresAt() {
|
|
@@ -20325,7 +21135,7 @@ function isTokenExpiringSoon(credential) {
|
|
|
20325
21135
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
20326
21136
|
}
|
|
20327
21137
|
function refreshFingerprint(refreshToken3) {
|
|
20328
|
-
return
|
|
21138
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
20329
21139
|
}
|
|
20330
21140
|
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
20331
21141
|
return {
|
|
@@ -47913,8 +48723,8 @@ function scheduleCollectScopeRefresh(cwd, collectScopeVersion, dependencies = de
|
|
|
47913
48723
|
|
|
47914
48724
|
// src/lib/commit-heartbeat.ts
|
|
47915
48725
|
import { execFileSync as execFileSync5 } from "child_process";
|
|
47916
|
-
import { mkdirSync as
|
|
47917
|
-
import { dirname as
|
|
48726
|
+
import { mkdirSync as mkdirSync7, readFileSync as readFileSync13, readdirSync as readdirSync3, unlinkSync } from "fs";
|
|
48727
|
+
import { dirname as dirname9, join as join17, resolve as resolve4 } from "path";
|
|
47918
48728
|
var FIRED_DIR = "prim/post-commit-fired";
|
|
47919
48729
|
var WIRED_PATH = "prim/git-hooks-wired";
|
|
47920
48730
|
var GIT_TIMEOUT_MS5 = 1e3;
|
|
@@ -47933,7 +48743,7 @@ function commonPath(cwd, relative5) {
|
|
|
47933
48743
|
timeout: GIT_TIMEOUT_MS5
|
|
47934
48744
|
}).replace(/\r?\n$/u, "");
|
|
47935
48745
|
if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
|
|
47936
|
-
return
|
|
48746
|
+
return join17(resolve4(cwd, value), relative5);
|
|
47937
48747
|
}
|
|
47938
48748
|
function gitPath(cwd, relative5) {
|
|
47939
48749
|
const value = execFileSync5("git", ["rev-parse", "--git-path", relative5], {
|
|
@@ -47943,11 +48753,11 @@ function gitPath(cwd, relative5) {
|
|
|
47943
48753
|
timeout: GIT_TIMEOUT_MS5
|
|
47944
48754
|
}).replace(/\r?\n$/u, "");
|
|
47945
48755
|
if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
|
|
47946
|
-
return
|
|
48756
|
+
return resolve4(cwd, value);
|
|
47947
48757
|
}
|
|
47948
48758
|
function ensurePrivateParent(path9) {
|
|
47949
|
-
|
|
47950
|
-
|
|
48759
|
+
mkdirSync7(dirname9(dirname9(path9)), { recursive: true, mode: 448 });
|
|
48760
|
+
mkdirSync7(dirname9(path9), { recursive: true, mode: 448 });
|
|
47951
48761
|
}
|
|
47952
48762
|
function writeStamp(path9, at) {
|
|
47953
48763
|
ensurePrivateParent(path9);
|
|
@@ -47956,7 +48766,7 @@ function writeStamp(path9, at) {
|
|
|
47956
48766
|
}
|
|
47957
48767
|
function readStampAt(path9) {
|
|
47958
48768
|
try {
|
|
47959
|
-
const raw =
|
|
48769
|
+
const raw = readFileSync13(path9, "utf8");
|
|
47960
48770
|
if (raw.length > MAX_STAMP_BYTES) return void 0;
|
|
47961
48771
|
const parsed = JSON.parse(raw);
|
|
47962
48772
|
return typeof parsed.at === "number" && Number.isSafeInteger(parsed.at) && parsed.at > 0 ? parsed.at : void 0;
|
|
@@ -47974,9 +48784,9 @@ function lastConversationCaptured(cwd, agent) {
|
|
|
47974
48784
|
function readFiredStamps(cwd) {
|
|
47975
48785
|
try {
|
|
47976
48786
|
const dir = gitPath(cwd, FIRED_DIR);
|
|
47977
|
-
return
|
|
48787
|
+
return readdirSync3(dir).flatMap((sha) => {
|
|
47978
48788
|
if (!FULL_SHA_RE.test(sha)) return [];
|
|
47979
|
-
const at = readStampAt(
|
|
48789
|
+
const at = readStampAt(join17(dir, sha));
|
|
47980
48790
|
return at === void 0 ? [] : [{ sha, at }];
|
|
47981
48791
|
});
|
|
47982
48792
|
} catch {
|
|
@@ -48089,151 +48899,13 @@ import {
|
|
|
48089
48899
|
} from "fs";
|
|
48090
48900
|
import { basename as basename3, dirname as dirname10, isAbsolute as isAbsolute6, join as join19, relative as relative2, resolve as resolve5, sep as sep2 } from "path";
|
|
48091
48901
|
|
|
48092
|
-
// src/lib/git-hook-contract.ts
|
|
48093
|
-
var MANAGED_GIT_HOOK_NAMES = ["pre-commit", "post-commit", "post-rewrite"];
|
|
48094
|
-
var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
|
|
48095
|
-
var GIT_HOOK_CONTRACT_VERSION = 1;
|
|
48096
|
-
var CONTRACT_LINE_PREFIX = "# prim git hook v";
|
|
48097
|
-
var CONTRACT_LINE_RE = /^# prim git hook v([0-9]+)\b/mu;
|
|
48098
|
-
function blockMarkers(hook) {
|
|
48099
|
-
return { start: `# >>> prim ${hook} hook >>>`, end: `# <<< prim ${hook} hook <<<` };
|
|
48100
|
-
}
|
|
48101
|
-
function entrypointCommand(hook) {
|
|
48102
|
-
const script = [
|
|
48103
|
-
PRIM_CONFIG_SHELL_RESOLVER,
|
|
48104
|
-
`case "$prim_config" in /) prim_entry=/${GIT_HOOK_ENTRYPOINT_NAME} ;; `,
|
|
48105
|
-
`*) prim_entry="$prim_config/${GIT_HOOK_ENTRYPOINT_NAME}" ;; esac; `,
|
|
48106
|
-
'[ -x "$prim_entry" ] || exit 0; exec "$prim_entry" "$@"'
|
|
48107
|
-
].join("");
|
|
48108
|
-
return `/bin/sh -c ${shellQuote(script)} ${GIT_HOOK_ENTRYPOINT_NAME} ${hook} "$@"`;
|
|
48109
|
-
}
|
|
48110
|
-
function managedHookBlock(hook) {
|
|
48111
|
-
const { start, end } = blockMarkers(hook);
|
|
48112
|
-
const header = `${CONTRACT_LINE_PREFIX}${GIT_HOOK_CONTRACT_VERSION}: a no-op unless prim is installed and enabled here (see \`prim hooks snippet ${hook}\`).`;
|
|
48113
|
-
if (hook !== "post-rewrite") {
|
|
48114
|
-
return `${start}
|
|
48115
|
-
${header}
|
|
48116
|
-
# shellcheck disable=SC2016
|
|
48117
|
-
${entrypointCommand(hook)} || :
|
|
48118
|
-
${end}`;
|
|
48119
|
-
}
|
|
48120
|
-
return `${start}
|
|
48121
|
-
${header}
|
|
48122
|
-
prim_rewrite_stdin=$(mktemp 2>/dev/null) || prim_rewrite_stdin=
|
|
48123
|
-
if test -n "\${prim_rewrite_stdin}" && cat >"\${prim_rewrite_stdin}"; then
|
|
48124
|
-
# shellcheck disable=SC2016
|
|
48125
|
-
${entrypointCommand(hook)} <"\${prim_rewrite_stdin}" || :
|
|
48126
|
-
exec <"\${prim_rewrite_stdin}"
|
|
48127
|
-
fi
|
|
48128
|
-
if test -n "\${prim_rewrite_stdin}"; then rm -f "\${prim_rewrite_stdin}"; fi
|
|
48129
|
-
unset prim_rewrite_stdin
|
|
48130
|
-
${end}`;
|
|
48131
|
-
}
|
|
48132
|
-
var OPEN_WORDS = /* @__PURE__ */ new Set(["then", "do", "else", "{", "(", "&&", "||", "|"]);
|
|
48133
|
-
function canonicalHookBlock(text) {
|
|
48134
|
-
const tokens = [];
|
|
48135
|
-
let word = "";
|
|
48136
|
-
let quote2;
|
|
48137
|
-
const separate = () => {
|
|
48138
|
-
const last = tokens.at(-1);
|
|
48139
|
-
if (last !== void 0 && last !== ";" && !OPEN_WORDS.has(last)) tokens.push(";");
|
|
48140
|
-
};
|
|
48141
|
-
const flush2 = () => {
|
|
48142
|
-
if (word === "") return;
|
|
48143
|
-
const last = tokens.at(-1);
|
|
48144
|
-
if (last !== void 0 && /^[0-9]*(?:<|>|>>|<&|>&)$/u.test(last))
|
|
48145
|
-
tokens[tokens.length - 1] += word;
|
|
48146
|
-
else tokens.push(word);
|
|
48147
|
-
word = "";
|
|
48148
|
-
};
|
|
48149
|
-
for (let index = 0; index < text.length; index += 1) {
|
|
48150
|
-
const char = text[index];
|
|
48151
|
-
if (quote2) {
|
|
48152
|
-
word += char;
|
|
48153
|
-
if (char === quote2) quote2 = void 0;
|
|
48154
|
-
continue;
|
|
48155
|
-
}
|
|
48156
|
-
if (char === "'" || char === '"') {
|
|
48157
|
-
quote2 = char;
|
|
48158
|
-
word += char;
|
|
48159
|
-
} else if (char === "#" && word === "") {
|
|
48160
|
-
const end = text.indexOf("\n", index);
|
|
48161
|
-
const comment2 = text.slice(index, end === -1 ? text.length : end);
|
|
48162
|
-
tokens.push(comment2.replace(/\s+/gu, " ").trim());
|
|
48163
|
-
index = (end === -1 ? text.length : end) - 1;
|
|
48164
|
-
} else if (char === "\n" || char === ";") {
|
|
48165
|
-
flush2();
|
|
48166
|
-
if (char === ";" && text[index + 1] === ";") {
|
|
48167
|
-
tokens.push(";;");
|
|
48168
|
-
index += 1;
|
|
48169
|
-
} else {
|
|
48170
|
-
separate();
|
|
48171
|
-
}
|
|
48172
|
-
} else if (/\s/u.test(char)) {
|
|
48173
|
-
flush2();
|
|
48174
|
-
} else {
|
|
48175
|
-
word += char;
|
|
48176
|
-
}
|
|
48177
|
-
}
|
|
48178
|
-
flush2();
|
|
48179
|
-
while (tokens.at(-1) === ";") tokens.pop();
|
|
48180
|
-
return tokens.join("\0");
|
|
48181
|
-
}
|
|
48182
|
-
function hookBlockContractVersion(block) {
|
|
48183
|
-
const match = CONTRACT_LINE_RE.exec(block);
|
|
48184
|
-
return match?.[1] ? Number(match[1]) : void 0;
|
|
48185
|
-
}
|
|
48186
|
-
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
48187
|
-
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
48188
|
-
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
48189
|
-
# where prim is active (git config prim.active true) and never fails the hook.
|
|
48190
|
-
case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
|
|
48191
|
-
prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
|
|
48192
|
-
[ -x "$prim_launcher" ] || exit 0
|
|
48193
|
-
[ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
|
|
48194
|
-
prim_hook=\${1-}
|
|
48195
|
-
if [ "$#" -gt 0 ]; then shift; fi
|
|
48196
|
-
case "$prim_hook" in
|
|
48197
|
-
pre-commit)
|
|
48198
|
-
"$prim_launcher" prim-pre-commit "$@" || :
|
|
48199
|
-
;;
|
|
48200
|
-
post-commit)
|
|
48201
|
-
prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
|
|
48202
|
-
case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
|
|
48203
|
-
case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
|
|
48204
|
-
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
48205
|
-
prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
|
|
48206
|
-
(
|
|
48207
|
-
trap '' HUP
|
|
48208
|
-
trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
|
|
48209
|
-
PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
|
|
48210
|
-
) </dev/null >/dev/null 2>&1 &
|
|
48211
|
-
;;
|
|
48212
|
-
post-rewrite)
|
|
48213
|
-
case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
|
|
48214
|
-
prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
|
|
48215
|
-
if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
|
|
48216
|
-
rm -f "$prim_pairs"
|
|
48217
|
-
exit 0
|
|
48218
|
-
fi
|
|
48219
|
-
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
48220
|
-
(
|
|
48221
|
-
trap '' HUP
|
|
48222
|
-
trap 'rm -f "$prim_pairs"' 0
|
|
48223
|
-
PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
|
|
48224
|
-
) </dev/null >/dev/null 2>&1 &
|
|
48225
|
-
;;
|
|
48226
|
-
esac
|
|
48227
|
-
exit 0
|
|
48228
|
-
`;
|
|
48229
|
-
|
|
48230
48902
|
// src/lib/git-hook-legacy.ts
|
|
48231
|
-
import { isAbsolute as
|
|
48903
|
+
import { isAbsolute as isAbsolute5 } from "path";
|
|
48232
48904
|
|
|
48233
48905
|
// src/lib/bin-cache.ts
|
|
48234
|
-
import { chmodSync as
|
|
48906
|
+
import { chmodSync as chmodSync5, mkdirSync as mkdirSync8 } from "fs";
|
|
48235
48907
|
import { homedir as homedir3 } from "os";
|
|
48236
|
-
import { join as
|
|
48908
|
+
import { join as join18 } from "path";
|
|
48237
48909
|
var GIT_HOOK_CACHE_SHELL_DIR = "${XDG_CACHE_HOME:-$HOME/.cache}/prim/bin";
|
|
48238
48910
|
var GIT_HOOK_CACHE_TTL_MINUTES = 1440;
|
|
48239
48911
|
|
|
@@ -48376,7 +49048,7 @@ var SHELL_QUOTED_RE = /^'(?:[^']|'"'"')*'$/u;
|
|
|
48376
49048
|
function decodePinnedPath(token) {
|
|
48377
49049
|
if (!token || !SHELL_QUOTED_RE.test(token)) return void 0;
|
|
48378
49050
|
const value = token.slice(1, -1).replaceAll(`'"'"'`, "'");
|
|
48379
|
-
if (!
|
|
49051
|
+
if (!isAbsolute5(value) || value.includes("\0") || value.includes("\n") || value.includes("\r")) {
|
|
48380
49052
|
return void 0;
|
|
48381
49053
|
}
|
|
48382
49054
|
return value;
|
|
@@ -48468,662 +49140,6 @@ ${end}`;
|
|
|
48468
49140
|
return normalize2(block) === normalize2(expected);
|
|
48469
49141
|
}
|
|
48470
49142
|
|
|
48471
|
-
// src/lib/hook-runtime.ts
|
|
48472
|
-
import { createHash as createHash9, randomBytes as randomBytes5 } from "crypto";
|
|
48473
|
-
import {
|
|
48474
|
-
constants as constants2,
|
|
48475
|
-
accessSync,
|
|
48476
|
-
chmodSync as chmodSync5,
|
|
48477
|
-
copyFileSync,
|
|
48478
|
-
existsSync as existsSync8,
|
|
48479
|
-
lstatSync as lstatSync6,
|
|
48480
|
-
mkdirSync as mkdirSync8,
|
|
48481
|
-
mkdtempSync,
|
|
48482
|
-
readFileSync as readFileSync13,
|
|
48483
|
-
readdirSync as readdirSync3,
|
|
48484
|
-
realpathSync as realpathSync2,
|
|
48485
|
-
renameSync as renameSync2,
|
|
48486
|
-
rmSync as rmSync9,
|
|
48487
|
-
statSync as statSync2,
|
|
48488
|
-
utimesSync,
|
|
48489
|
-
writeFileSync as writeFileSync6
|
|
48490
|
-
} from "fs";
|
|
48491
|
-
import { delimiter, dirname as dirname9, isAbsolute as isAbsolute5, join as join18, resolve as resolve4 } from "path";
|
|
48492
|
-
|
|
48493
|
-
// src/lib/native-keyring.ts
|
|
48494
|
-
import { existsSync as existsSync7 } from "fs";
|
|
48495
|
-
import { createRequire as createRequire2 } from "module";
|
|
48496
|
-
import { dirname as dirname8, join as join17 } from "path";
|
|
48497
|
-
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
48498
|
-
var require3 = createRequire2(import.meta.url);
|
|
48499
|
-
var KEYRING_LOADER = 'module.exports = require("./keyring.node");\n';
|
|
48500
|
-
var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
|
|
48501
|
-
function keyringNativeBinary() {
|
|
48502
|
-
let directory = dirname8(fileURLToPath6(import.meta.url));
|
|
48503
|
-
for (let depth = 0; depth < 5; depth++) {
|
|
48504
|
-
const binary3 = join17(directory, "native", "keyring.node");
|
|
48505
|
-
if (existsSync7(binary3)) return binary3;
|
|
48506
|
-
directory = dirname8(directory);
|
|
48507
|
-
}
|
|
48508
|
-
const packagePath = require3.resolve("@napi-rs/keyring");
|
|
48509
|
-
require3(packagePath);
|
|
48510
|
-
const entry = require3.cache[packagePath];
|
|
48511
|
-
const binary2 = entry?.children.find(
|
|
48512
|
-
(child) => child.filename.endsWith(".node") && child.filename.includes("keyring")
|
|
48513
|
-
);
|
|
48514
|
-
if (!binary2 || !existsSync7(binary2.filename))
|
|
48515
|
-
throw new Error(
|
|
48516
|
-
"Cannot stage the native credential store; reinstall Prim with optional dependencies enabled."
|
|
48517
|
-
);
|
|
48518
|
-
return binary2.filename;
|
|
48519
|
-
}
|
|
48520
|
-
|
|
48521
|
-
// src/lib/hook-runtime.ts
|
|
48522
|
-
var HOOK_RUNTIME_SCHEMA_VERSION = 1;
|
|
48523
|
-
var DIRECTORY_MODE2 = 448;
|
|
48524
|
-
var DATA_FILE_MODE = 384;
|
|
48525
|
-
var LAUNCHER_MODE = 448;
|
|
48526
|
-
var RELEASE_PREFIX = "release-";
|
|
48527
|
-
var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
|
|
48528
|
-
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
48529
|
-
var MAX_RELEASES = 8;
|
|
48530
|
-
var MAX_RELEASE_DELETIONS_PER_STAGE = 8;
|
|
48531
|
-
var RETAIN_PREDECESSORS = 2;
|
|
48532
|
-
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
48533
|
-
var HOOK_RUNTIME_ENTRIES = {
|
|
48534
|
-
// SessionStart self-healing resolves this exact CLI entry to run
|
|
48535
|
-
// `daemon ensure`; it must travel with the immutable hook release.
|
|
48536
|
-
prim: "dist/index.js",
|
|
48537
|
-
"prim-hook": "dist/hooks/prim-hook.js",
|
|
48538
|
-
"prim-pre-commit": "dist/hooks/pre-commit.js",
|
|
48539
|
-
"prim-post-commit": "dist/hooks/post-commit.js",
|
|
48540
|
-
"prim-post-rewrite": "dist/hooks/post-rewrite.js",
|
|
48541
|
-
"prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
|
|
48542
|
-
"prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
|
|
48543
|
-
"prim-post-tool-use": "dist/hooks/post-tool-use.js",
|
|
48544
|
-
"prim-session-start": "dist/hooks/session-start.js",
|
|
48545
|
-
"prim-session-end": "dist/hooks/session-end.js",
|
|
48546
|
-
"prim-daemon-server": "dist/daemon/server.js",
|
|
48547
|
-
"prim-statusline": "dist/statusline-main.js"
|
|
48548
|
-
};
|
|
48549
|
-
var SOURCE_ENTRIES = Object.fromEntries(
|
|
48550
|
-
Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
|
|
48551
|
-
bin,
|
|
48552
|
-
target.replace(/^dist\//u, "")
|
|
48553
|
-
])
|
|
48554
|
-
);
|
|
48555
|
-
function hookRuntimePaths(options = {}) {
|
|
48556
|
-
const env4 = options.env ?? process.env;
|
|
48557
|
-
const configDir = primConfigDirectory({
|
|
48558
|
-
...options,
|
|
48559
|
-
env: env4,
|
|
48560
|
-
homeDir: options.homeDir ?? env4.HOME ?? ""
|
|
48561
|
-
});
|
|
48562
|
-
const runtimeDir = join18(configDir, "hook-runtime");
|
|
48563
|
-
return {
|
|
48564
|
-
configDir,
|
|
48565
|
-
launcher: join18(configDir, STABLE_HOOK_LAUNCHER_NAME),
|
|
48566
|
-
gitHookEntrypoint: join18(configDir, GIT_HOOK_ENTRYPOINT_NAME),
|
|
48567
|
-
runtimeDir,
|
|
48568
|
-
releasesDir: join18(runtimeDir, "releases"),
|
|
48569
|
-
current: join18(runtimeDir, "current"),
|
|
48570
|
-
selectionLock: join18(runtimeDir, "selection.lock")
|
|
48571
|
-
};
|
|
48572
|
-
}
|
|
48573
|
-
function sha2562(path9) {
|
|
48574
|
-
return createHash9("sha256").update(readFileSync13(path9)).digest("hex");
|
|
48575
|
-
}
|
|
48576
|
-
function exactManifest(manifest) {
|
|
48577
|
-
return `${JSON.stringify(manifest, null, 2)}
|
|
48578
|
-
`;
|
|
48579
|
-
}
|
|
48580
|
-
function exactKeys(value, expected) {
|
|
48581
|
-
const actual = Object.keys(value).sort();
|
|
48582
|
-
const wanted = [...expected].sort();
|
|
48583
|
-
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
48584
|
-
}
|
|
48585
|
-
function releaseId(manifest) {
|
|
48586
|
-
return createHash9("sha256").update(exactManifest(manifest)).digest("hex");
|
|
48587
|
-
}
|
|
48588
|
-
function runtimePackageJson(manifest) {
|
|
48589
|
-
return `${JSON.stringify(
|
|
48590
|
-
{
|
|
48591
|
-
name: "@primitive.ai/prim",
|
|
48592
|
-
version: manifest.version,
|
|
48593
|
-
type: "module",
|
|
48594
|
-
bin: HOOK_RUNTIME_ENTRIES
|
|
48595
|
-
},
|
|
48596
|
-
null,
|
|
48597
|
-
2
|
|
48598
|
-
)}
|
|
48599
|
-
`;
|
|
48600
|
-
}
|
|
48601
|
-
function validateRelease(releaseDir, manifest) {
|
|
48602
|
-
try {
|
|
48603
|
-
if (!directReleaseLayout(releaseDir, manifest)) return false;
|
|
48604
|
-
if (readFileSync13(join18(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
|
|
48605
|
-
return false;
|
|
48606
|
-
}
|
|
48607
|
-
if (readFileSync13(join18(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
|
|
48608
|
-
return false;
|
|
48609
|
-
}
|
|
48610
|
-
if (readFileSync13(join18(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
|
|
48611
|
-
`) {
|
|
48612
|
-
return false;
|
|
48613
|
-
}
|
|
48614
|
-
for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
48615
|
-
const target = join18(releaseDir, relativePath);
|
|
48616
|
-
if (sha2562(target) !== manifest.files[bin]) return false;
|
|
48617
|
-
}
|
|
48618
|
-
for (const [path9, digest3] of Object.entries(manifest.native ?? {})) {
|
|
48619
|
-
if (sha2562(join18(releaseDir, path9)) !== digest3) return false;
|
|
48620
|
-
}
|
|
48621
|
-
return true;
|
|
48622
|
-
} catch {
|
|
48623
|
-
return false;
|
|
48624
|
-
}
|
|
48625
|
-
}
|
|
48626
|
-
function directReleaseLayout(releaseDir, manifest) {
|
|
48627
|
-
try {
|
|
48628
|
-
const directories = /* @__PURE__ */ new Set([releaseDir]);
|
|
48629
|
-
for (const relativePath of [
|
|
48630
|
-
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
48631
|
-
...Object.keys(manifest.native ?? {})
|
|
48632
|
-
]) {
|
|
48633
|
-
for (let directory = dirname9(relativePath); directory !== "."; directory = dirname9(directory)) {
|
|
48634
|
-
directories.add(join18(releaseDir, directory));
|
|
48635
|
-
}
|
|
48636
|
-
}
|
|
48637
|
-
if (![...directories].every((directory) => lstatSync6(directory).isDirectory())) return false;
|
|
48638
|
-
const files = [
|
|
48639
|
-
"manifest.json",
|
|
48640
|
-
"package.json",
|
|
48641
|
-
"node",
|
|
48642
|
-
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
48643
|
-
...Object.keys(manifest.native ?? {})
|
|
48644
|
-
];
|
|
48645
|
-
const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path9) => join18(releaseDir, path9))]);
|
|
48646
|
-
if (![...directories].every(
|
|
48647
|
-
(directory) => readdirSync3(directory).every((name2) => owned.has(join18(directory, name2)))
|
|
48648
|
-
))
|
|
48649
|
-
return false;
|
|
48650
|
-
return files.every((relativePath) => lstatSync6(join18(releaseDir, relativePath)).isFile());
|
|
48651
|
-
} catch {
|
|
48652
|
-
return false;
|
|
48653
|
-
}
|
|
48654
|
-
}
|
|
48655
|
-
function readReleaseManifest(releaseDir, releaseName) {
|
|
48656
|
-
try {
|
|
48657
|
-
const manifestPath2 = join18(releaseDir, "manifest.json");
|
|
48658
|
-
const manifestStat = statSync2(manifestPath2);
|
|
48659
|
-
if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
|
|
48660
|
-
const raw = readFileSync13(manifestPath2, "utf8");
|
|
48661
|
-
const parsed = JSON.parse(raw);
|
|
48662
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
48663
|
-
if (!exactKeys(parsed, [
|
|
48664
|
-
"schemaVersion",
|
|
48665
|
-
"version",
|
|
48666
|
-
"nodePath",
|
|
48667
|
-
"files",
|
|
48668
|
-
..."native" in parsed ? ["native"] : []
|
|
48669
|
-
]))
|
|
48670
|
-
return null;
|
|
48671
|
-
const candidate = parsed;
|
|
48672
|
-
if (candidate.schemaVersion !== HOOK_RUNTIME_SCHEMA_VERSION || typeof candidate.version !== "string" || compareSemver(candidate.version, candidate.version) !== 0 || typeof candidate.nodePath !== "string" || !isAbsolute5(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(
|
|
48673
|
-
(digest3) => typeof digest3 !== "string" || !/^[0-9a-f]{64}$/u.test(digest3)
|
|
48674
|
-
)) {
|
|
48675
|
-
return null;
|
|
48676
|
-
}
|
|
48677
|
-
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(
|
|
48678
|
-
(digest3) => typeof digest3 !== "string" || !/^[a-f0-9]{64}$/u.test(digest3)
|
|
48679
|
-
)))
|
|
48680
|
-
return null;
|
|
48681
|
-
const manifest = candidate;
|
|
48682
|
-
if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
|
|
48683
|
-
return null;
|
|
48684
|
-
}
|
|
48685
|
-
return manifest;
|
|
48686
|
-
} catch {
|
|
48687
|
-
return null;
|
|
48688
|
-
}
|
|
48689
|
-
}
|
|
48690
|
-
function readSelectedRelease(paths) {
|
|
48691
|
-
let raw;
|
|
48692
|
-
try {
|
|
48693
|
-
raw = readFileSync13(paths.current, "utf8");
|
|
48694
|
-
} catch (error) {
|
|
48695
|
-
if (error.code === "ENOENT") return null;
|
|
48696
|
-
throw error;
|
|
48697
|
-
}
|
|
48698
|
-
const name2 = raw.endsWith("\n") ? raw.slice(0, -1) : "";
|
|
48699
|
-
if (`${name2}
|
|
48700
|
-
` !== raw || !RELEASE_NAME_RE.test(name2)) {
|
|
48701
|
-
throw new Error("cannot stage hook runtime: selected release is malformed");
|
|
48702
|
-
}
|
|
48703
|
-
const dir = join18(paths.releasesDir, name2);
|
|
48704
|
-
const manifest = readReleaseManifest(dir, name2);
|
|
48705
|
-
if (!manifest) {
|
|
48706
|
-
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
48707
|
-
}
|
|
48708
|
-
return { name: name2, dir, manifest };
|
|
48709
|
-
}
|
|
48710
|
-
function releaseEntries(paths) {
|
|
48711
|
-
return readdirSync3(paths.releasesDir, { withFileTypes: true }).flatMap((entry) => {
|
|
48712
|
-
if (!entry.isDirectory() || !RELEASE_NAME_RE.test(entry.name)) return [];
|
|
48713
|
-
const dir = join18(paths.releasesDir, entry.name);
|
|
48714
|
-
try {
|
|
48715
|
-
return [{ name: entry.name, dir, mtimeMs: statSync2(dir).mtimeMs }];
|
|
48716
|
-
} catch {
|
|
48717
|
-
return [];
|
|
48718
|
-
}
|
|
48719
|
-
});
|
|
48720
|
-
}
|
|
48721
|
-
function pruneReleases(paths, protectedNames, reserveSlots, now) {
|
|
48722
|
-
const entries = releaseEntries(paths).sort(
|
|
48723
|
-
(left, right) => right.mtimeMs - left.mtimeMs || left.name.localeCompare(right.name)
|
|
48724
|
-
);
|
|
48725
|
-
const protectedWithPredecessors = new Set(protectedNames);
|
|
48726
|
-
for (const entry of entries) {
|
|
48727
|
-
if (protectedWithPredecessors.size >= protectedNames.size + RETAIN_PREDECESSORS) break;
|
|
48728
|
-
if (!protectedWithPredecessors.has(entry.name)) protectedWithPredecessors.add(entry.name);
|
|
48729
|
-
}
|
|
48730
|
-
const candidates = entries.filter(
|
|
48731
|
-
(entry) => !protectedWithPredecessors.has(entry.name) && now - entry.mtimeMs >= RELEASE_GRACE_MS
|
|
48732
|
-
).sort((left, right) => left.mtimeMs - right.mtimeMs || left.name.localeCompare(right.name));
|
|
48733
|
-
let remaining = entries.length;
|
|
48734
|
-
let deleted = 0;
|
|
48735
|
-
for (const entry of candidates) {
|
|
48736
|
-
if (remaining + reserveSlots <= MAX_RELEASES || deleted >= MAX_RELEASE_DELETIONS_PER_STAGE) {
|
|
48737
|
-
break;
|
|
48738
|
-
}
|
|
48739
|
-
rmSync9(entry.dir, { recursive: true, force: true });
|
|
48740
|
-
remaining -= 1;
|
|
48741
|
-
deleted += 1;
|
|
48742
|
-
}
|
|
48743
|
-
if (remaining + reserveSlots > MAX_RELEASES) {
|
|
48744
|
-
throw new Error(
|
|
48745
|
-
"cannot stage hook runtime: release retention is full while recent runtimes are protected"
|
|
48746
|
-
);
|
|
48747
|
-
}
|
|
48748
|
-
}
|
|
48749
|
-
function sourceManifest(sourceDir, version, nodePath) {
|
|
48750
|
-
const files = {};
|
|
48751
|
-
for (const [bin, relativePath] of Object.entries(SOURCE_ENTRIES)) {
|
|
48752
|
-
const source = join18(sourceDir, relativePath);
|
|
48753
|
-
if (!existsSync8(source) || !statSync2(source).isFile()) {
|
|
48754
|
-
throw new Error(`cannot stage hook runtime: missing self-contained ${bin} bundle`);
|
|
48755
|
-
}
|
|
48756
|
-
files[bin] = sha2562(source);
|
|
48757
|
-
}
|
|
48758
|
-
return {
|
|
48759
|
-
schemaVersion: HOOK_RUNTIME_SCHEMA_VERSION,
|
|
48760
|
-
version,
|
|
48761
|
-
nodePath,
|
|
48762
|
-
files,
|
|
48763
|
-
native: {
|
|
48764
|
-
"native/keyring.cjs": createHash9("sha256").update(KEYRING_LOADER).digest("hex"),
|
|
48765
|
-
"native/keyring.node": sha2562(keyringNativeBinary())
|
|
48766
|
-
}
|
|
48767
|
-
};
|
|
48768
|
-
}
|
|
48769
|
-
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
48770
|
-
set -eu
|
|
48771
|
-
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
48772
|
-
IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
|
|
48773
|
-
case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
|
|
48774
|
-
prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
|
|
48775
|
-
case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
|
|
48776
|
-
[ "\${#prim_release_id}" -eq 64 ] || exit 69
|
|
48777
|
-
prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
|
|
48778
|
-
case "\${1-}" in
|
|
48779
|
-
${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
|
|
48780
|
-
*) exit 64 ;;
|
|
48781
|
-
esac
|
|
48782
|
-
shift
|
|
48783
|
-
IFS= read -r prim_node < "$prim_release/node" || exit 69
|
|
48784
|
-
case "$prim_node" in /*) ;; *) exit 69 ;; esac
|
|
48785
|
-
[ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
|
|
48786
|
-
exec "$prim_node" "$prim_entry" "$@"
|
|
48787
|
-
`;
|
|
48788
|
-
function privateDirectory(path9) {
|
|
48789
|
-
const stat = lstatIfPresent(path9);
|
|
48790
|
-
if (!stat?.isDirectory()) return false;
|
|
48791
|
-
if (process.platform === "win32") return true;
|
|
48792
|
-
const uid = process.getuid?.();
|
|
48793
|
-
return (Number(stat.mode) & 511) === DIRECTORY_MODE2 && (uid === void 0 || stat.uid === uid);
|
|
48794
|
-
}
|
|
48795
|
-
function privateFile(path9, mode) {
|
|
48796
|
-
const stat = lstatIfPresent(path9);
|
|
48797
|
-
if (!stat?.isFile()) return false;
|
|
48798
|
-
if (process.platform === "win32") return true;
|
|
48799
|
-
const uid = process.getuid?.();
|
|
48800
|
-
return (Number(stat.mode) & 511) === mode && (uid === void 0 || stat.uid === uid);
|
|
48801
|
-
}
|
|
48802
|
-
function hasSafeRuntimeLayout(paths, selected) {
|
|
48803
|
-
const releaseDirectories = /* @__PURE__ */ new Set([selected.dir]);
|
|
48804
|
-
for (const relativePath of [
|
|
48805
|
-
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
48806
|
-
...Object.keys(selected.manifest.native ?? {})
|
|
48807
|
-
]) {
|
|
48808
|
-
for (let directory = dirname9(relativePath); directory !== "."; directory = dirname9(directory)) {
|
|
48809
|
-
releaseDirectories.add(join18(selected.dir, directory));
|
|
48810
|
-
}
|
|
48811
|
-
}
|
|
48812
|
-
if (!privateDirectory(paths.configDir) || !privateDirectory(paths.runtimeDir) || !privateDirectory(paths.releasesDir) || ![...releaseDirectories].every(privateDirectory) || !privateFile(paths.launcher, LAUNCHER_MODE) || !privateFile(paths.current, DATA_FILE_MODE) || !privateFile(join18(selected.dir, "manifest.json"), DATA_FILE_MODE) || !privateFile(join18(selected.dir, "package.json"), DATA_FILE_MODE) || !privateFile(join18(selected.dir, "node"), DATA_FILE_MODE)) {
|
|
48813
|
-
return false;
|
|
48814
|
-
}
|
|
48815
|
-
return [
|
|
48816
|
-
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
48817
|
-
...Object.keys(selected.manifest.native ?? {})
|
|
48818
|
-
].every((relativePath) => privateFile(join18(selected.dir, relativePath), DATA_FILE_MODE));
|
|
48819
|
-
}
|
|
48820
|
-
function sameNodeExecutable(recorded, desired) {
|
|
48821
|
-
try {
|
|
48822
|
-
if (!statSync2(recorded).isFile()) return false;
|
|
48823
|
-
accessSync(recorded, constants2.X_OK);
|
|
48824
|
-
return realpathSync2(recorded) === realpathSync2(desired);
|
|
48825
|
-
} catch {
|
|
48826
|
-
return false;
|
|
48827
|
-
}
|
|
48828
|
-
}
|
|
48829
|
-
function recordedNodeMatchesCurrentProcess(nodePath) {
|
|
48830
|
-
return sameNodeExecutable(nodePath, process.execPath);
|
|
48831
|
-
}
|
|
48832
|
-
function inspectHookRuntime(options = {}) {
|
|
48833
|
-
let paths;
|
|
48834
|
-
try {
|
|
48835
|
-
paths = hookRuntimePaths(options);
|
|
48836
|
-
} catch {
|
|
48837
|
-
return { state: "invalid" };
|
|
48838
|
-
}
|
|
48839
|
-
const launcher = lstatIfPresent(paths.launcher);
|
|
48840
|
-
const selector = lstatIfPresent(paths.current);
|
|
48841
|
-
if (!(launcher || selector)) return { state: "missing" };
|
|
48842
|
-
if (!(launcher && selector)) return { state: "invalid" };
|
|
48843
|
-
try {
|
|
48844
|
-
if (readFileSync13(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT) {
|
|
48845
|
-
return { state: "invalid" };
|
|
48846
|
-
}
|
|
48847
|
-
const selected = readSelectedRelease(paths);
|
|
48848
|
-
if (!selected) return { state: "invalid" };
|
|
48849
|
-
assertOwnedHookRuntime(paths);
|
|
48850
|
-
if (!hasSafeRuntimeLayout(paths, selected)) return { state: "invalid" };
|
|
48851
|
-
return recordedNodeMatchesCurrentProcess(selected.manifest.nodePath) ? { state: "ready", version: selected.manifest.version } : { state: "invalid" };
|
|
48852
|
-
} catch {
|
|
48853
|
-
return { state: "invalid" };
|
|
48854
|
-
}
|
|
48855
|
-
}
|
|
48856
|
-
function writeRelease(sourceDir, releaseDir, manifest, releasesDir) {
|
|
48857
|
-
const stagingDir = mkdtempSync(join18(releasesDir, ".stage-"));
|
|
48858
|
-
chmodSync5(stagingDir, DIRECTORY_MODE2);
|
|
48859
|
-
try {
|
|
48860
|
-
const directories = /* @__PURE__ */ new Set([stagingDir]);
|
|
48861
|
-
const syncStagedFile = (path9) => {
|
|
48862
|
-
syncFile(path9);
|
|
48863
|
-
for (let directory = dirname9(path9); ; directory = dirname9(directory)) {
|
|
48864
|
-
directories.add(directory);
|
|
48865
|
-
if (directory === stagingDir) break;
|
|
48866
|
-
}
|
|
48867
|
-
};
|
|
48868
|
-
for (const [bin, targetRelative] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
48869
|
-
const source = join18(sourceDir, SOURCE_ENTRIES[bin]);
|
|
48870
|
-
const target = join18(stagingDir, targetRelative);
|
|
48871
|
-
mkdirSync8(dirname9(target), { recursive: true, mode: DIRECTORY_MODE2 });
|
|
48872
|
-
chmodSync5(dirname9(target), DIRECTORY_MODE2);
|
|
48873
|
-
copyFileSync(source, target);
|
|
48874
|
-
chmodSync5(target, DATA_FILE_MODE);
|
|
48875
|
-
if (sha2562(target) !== manifest.files[bin]) {
|
|
48876
|
-
throw new Error(`cannot stage hook runtime: ${bin} changed while it was copied`);
|
|
48877
|
-
}
|
|
48878
|
-
syncStagedFile(target);
|
|
48879
|
-
}
|
|
48880
|
-
if (manifest.native) {
|
|
48881
|
-
const nativeDir = join18(stagingDir, "native");
|
|
48882
|
-
mkdirSync8(nativeDir, { mode: DIRECTORY_MODE2 });
|
|
48883
|
-
writeFileSync6(join18(nativeDir, "keyring.cjs"), KEYRING_LOADER, { mode: DATA_FILE_MODE });
|
|
48884
|
-
copyFileSync(keyringNativeBinary(), join18(nativeDir, "keyring.node"));
|
|
48885
|
-
chmodSync5(join18(nativeDir, "keyring.node"), DATA_FILE_MODE);
|
|
48886
|
-
for (const [path9, digest3] of Object.entries(manifest.native)) {
|
|
48887
|
-
const target = join18(stagingDir, path9);
|
|
48888
|
-
if (sha2562(target) !== digest3)
|
|
48889
|
-
throw new Error("Native credential store changed while copying");
|
|
48890
|
-
syncStagedFile(target);
|
|
48891
|
-
}
|
|
48892
|
-
}
|
|
48893
|
-
const nodePath = join18(stagingDir, "node");
|
|
48894
|
-
writeFileSync6(nodePath, `${manifest.nodePath}
|
|
48895
|
-
`, {
|
|
48896
|
-
encoding: "utf8",
|
|
48897
|
-
flag: "wx",
|
|
48898
|
-
mode: DATA_FILE_MODE
|
|
48899
|
-
});
|
|
48900
|
-
syncStagedFile(nodePath);
|
|
48901
|
-
const packageJsonPath = join18(stagingDir, "package.json");
|
|
48902
|
-
writeFileSync6(packageJsonPath, runtimePackageJson(manifest), {
|
|
48903
|
-
encoding: "utf8",
|
|
48904
|
-
flag: "wx",
|
|
48905
|
-
mode: DATA_FILE_MODE
|
|
48906
|
-
});
|
|
48907
|
-
syncStagedFile(packageJsonPath);
|
|
48908
|
-
const manifestPath2 = join18(stagingDir, "manifest.json");
|
|
48909
|
-
writeFileSync6(manifestPath2, exactManifest(manifest), {
|
|
48910
|
-
encoding: "utf8",
|
|
48911
|
-
flag: "wx",
|
|
48912
|
-
mode: DATA_FILE_MODE
|
|
48913
|
-
});
|
|
48914
|
-
syncStagedFile(manifestPath2);
|
|
48915
|
-
for (const directory of [...directories].sort((left, right) => right.length - left.length)) {
|
|
48916
|
-
syncDirectory(directory);
|
|
48917
|
-
}
|
|
48918
|
-
try {
|
|
48919
|
-
renameSync2(stagingDir, releaseDir);
|
|
48920
|
-
} catch (error) {
|
|
48921
|
-
const code = error.code;
|
|
48922
|
-
if (code !== "EEXIST" && code !== "ENOTEMPTY" || !validateRelease(releaseDir, manifest)) {
|
|
48923
|
-
throw error;
|
|
48924
|
-
}
|
|
48925
|
-
}
|
|
48926
|
-
} finally {
|
|
48927
|
-
rmSync9(stagingDir, { recursive: true, force: true });
|
|
48928
|
-
}
|
|
48929
|
-
}
|
|
48930
|
-
function stableNodePath(execPath = process.execPath, searchPath = process.env.PATH ?? "") {
|
|
48931
|
-
let target;
|
|
48932
|
-
try {
|
|
48933
|
-
target = realpathSync2(execPath);
|
|
48934
|
-
} catch {
|
|
48935
|
-
return execPath;
|
|
48936
|
-
}
|
|
48937
|
-
for (const directory of searchPath.split(delimiter)) {
|
|
48938
|
-
if (!isAbsolute5(directory)) continue;
|
|
48939
|
-
const candidate = join18(directory, "node");
|
|
48940
|
-
try {
|
|
48941
|
-
if (realpathSync2(candidate) === target) return candidate;
|
|
48942
|
-
} catch {
|
|
48943
|
-
}
|
|
48944
|
-
}
|
|
48945
|
-
return execPath;
|
|
48946
|
-
}
|
|
48947
|
-
function stageHookRuntime(options = {}) {
|
|
48948
|
-
const root = packageRoot();
|
|
48949
|
-
const sourceDir = options.sourceDir ?? (root ? join18(root, "dist", "hook-runtime") : null);
|
|
48950
|
-
const version = options.version ?? packageVersion();
|
|
48951
|
-
const nodePath = resolve4(options.nodePath ?? stableNodePath());
|
|
48952
|
-
if (!sourceDir || !version || compareSemver(version, version) !== 0 || !isAbsolute5(nodePath) || /[\r\n]/u.test(nodePath)) {
|
|
48953
|
-
throw new Error("cannot stage hook runtime: package identity is unavailable");
|
|
48954
|
-
}
|
|
48955
|
-
const manifest = sourceManifest(sourceDir, version, nodePath);
|
|
48956
|
-
const paths = hookRuntimePaths(options);
|
|
48957
|
-
const releaseName = `${RELEASE_PREFIX}${releaseId(manifest)}`;
|
|
48958
|
-
const releaseDir = join18(paths.releasesDir, releaseName);
|
|
48959
|
-
mkdirSync8(paths.releasesDir, { recursive: true, mode: DIRECTORY_MODE2 });
|
|
48960
|
-
chmodSync5(paths.configDir, DIRECTORY_MODE2);
|
|
48961
|
-
chmodSync5(paths.runtimeDir, DIRECTORY_MODE2);
|
|
48962
|
-
chmodSync5(paths.releasesDir, DIRECTORY_MODE2);
|
|
48963
|
-
return withFileLockSync(paths.selectionLock, () => {
|
|
48964
|
-
const now = Date.now();
|
|
48965
|
-
const selected = readSelectedRelease(paths);
|
|
48966
|
-
if (selected) utimesSync(selected.dir, now / 1e3, now / 1e3);
|
|
48967
|
-
const precedence = selected ? compareSemver(selected.manifest.version, manifest.version) : -1;
|
|
48968
|
-
if (precedence === void 0) {
|
|
48969
|
-
throw new Error("cannot stage hook runtime: selected release version is malformed");
|
|
48970
|
-
}
|
|
48971
|
-
const selectRequested = !selected || precedence < 0 || precedence === 0 && !sameNodeExecutable(selected.manifest.nodePath, nodePath);
|
|
48972
|
-
const requestedExists = existsSync8(releaseDir);
|
|
48973
|
-
const protectedBefore = new Set(selected ? [selected.name] : []);
|
|
48974
|
-
if (selectRequested && requestedExists) protectedBefore.add(releaseName);
|
|
48975
|
-
pruneReleases(paths, protectedBefore, selectRequested && !requestedExists ? 1 : 0, now);
|
|
48976
|
-
if (selectRequested && !validateRelease(releaseDir, manifest)) {
|
|
48977
|
-
if (requestedExists) {
|
|
48978
|
-
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
48979
|
-
}
|
|
48980
|
-
writeRelease(sourceDir, releaseDir, manifest, paths.releasesDir);
|
|
48981
|
-
}
|
|
48982
|
-
const finalRelease = selectRequested ? { name: releaseName, dir: releaseDir, manifest } : selected;
|
|
48983
|
-
const launcherCurrent = (() => {
|
|
48984
|
-
try {
|
|
48985
|
-
return readFileSync13(paths.launcher, "utf8") === STABLE_HOOK_LAUNCHER_CONTENT;
|
|
48986
|
-
} catch {
|
|
48987
|
-
return false;
|
|
48988
|
-
}
|
|
48989
|
-
})();
|
|
48990
|
-
const selectorCurrent = selected?.name === finalRelease.name;
|
|
48991
|
-
if (!launcherCurrent) {
|
|
48992
|
-
atomicWriteFile(paths.launcher, STABLE_HOOK_LAUNCHER_CONTENT, {
|
|
48993
|
-
ensureParent: true,
|
|
48994
|
-
mode: LAUNCHER_MODE
|
|
48995
|
-
});
|
|
48996
|
-
}
|
|
48997
|
-
const entrypointCurrent = gitHookEntrypointCurrent(paths);
|
|
48998
|
-
if (!entrypointCurrent) {
|
|
48999
|
-
atomicWriteFile(paths.gitHookEntrypoint, GIT_HOOK_ENTRYPOINT_CONTENT, {
|
|
49000
|
-
ensureParent: true,
|
|
49001
|
-
mode: LAUNCHER_MODE
|
|
49002
|
-
});
|
|
49003
|
-
}
|
|
49004
|
-
if (!selectorCurrent) {
|
|
49005
|
-
syncDirectory(paths.releasesDir);
|
|
49006
|
-
atomicWriteFile(paths.current, `${finalRelease.name}
|
|
49007
|
-
`, {
|
|
49008
|
-
ensureParent: true,
|
|
49009
|
-
mode: DATA_FILE_MODE
|
|
49010
|
-
});
|
|
49011
|
-
}
|
|
49012
|
-
utimesSync(finalRelease.dir, now / 1e3, now / 1e3);
|
|
49013
|
-
pruneReleases(
|
|
49014
|
-
paths,
|
|
49015
|
-
/* @__PURE__ */ new Set([finalRelease.name, ...selected ? [selected.name] : []]),
|
|
49016
|
-
0,
|
|
49017
|
-
now
|
|
49018
|
-
);
|
|
49019
|
-
return {
|
|
49020
|
-
changed: !launcherCurrent || !entrypointCurrent || !selectorCurrent,
|
|
49021
|
-
releaseDir: finalRelease.dir,
|
|
49022
|
-
manifest: finalRelease.manifest,
|
|
49023
|
-
paths
|
|
49024
|
-
};
|
|
49025
|
-
});
|
|
49026
|
-
}
|
|
49027
|
-
function gitHookEntrypointCurrent(paths) {
|
|
49028
|
-
try {
|
|
49029
|
-
return readFileSync13(paths.gitHookEntrypoint, "utf8") === GIT_HOOK_ENTRYPOINT_CONTENT;
|
|
49030
|
-
} catch {
|
|
49031
|
-
return false;
|
|
49032
|
-
}
|
|
49033
|
-
}
|
|
49034
|
-
function inspectGitHookEntrypoint(options = {}) {
|
|
49035
|
-
let paths;
|
|
49036
|
-
try {
|
|
49037
|
-
paths = hookRuntimePaths(options);
|
|
49038
|
-
} catch {
|
|
49039
|
-
return "invalid";
|
|
49040
|
-
}
|
|
49041
|
-
try {
|
|
49042
|
-
const entrypoint = lstatIfPresent(paths.gitHookEntrypoint);
|
|
49043
|
-
if (!entrypoint) return "missing";
|
|
49044
|
-
if (!entrypoint.isFile() || (Number(entrypoint.mode) & 64) === 0 || !gitHookEntrypointCurrent(paths) || readFileSync13(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT || !lstatIfPresent(paths.current)?.isFile()) {
|
|
49045
|
-
return "invalid";
|
|
49046
|
-
}
|
|
49047
|
-
return "ready";
|
|
49048
|
-
} catch {
|
|
49049
|
-
return "invalid";
|
|
49050
|
-
}
|
|
49051
|
-
}
|
|
49052
|
-
function lstatIfPresent(path9) {
|
|
49053
|
-
try {
|
|
49054
|
-
return lstatSync6(path9);
|
|
49055
|
-
} catch (error) {
|
|
49056
|
-
const code = error.code;
|
|
49057
|
-
if (code === "ENOENT" || code === "ENOTDIR") return void 0;
|
|
49058
|
-
throw error;
|
|
49059
|
-
}
|
|
49060
|
-
}
|
|
49061
|
-
function assertOwnedHookRuntime(paths) {
|
|
49062
|
-
const entrypoint = lstatIfPresent(paths.gitHookEntrypoint);
|
|
49063
|
-
if (entrypoint && (!entrypoint.isFile() || !gitHookEntrypointCurrent(paths))) {
|
|
49064
|
-
throw new Error(
|
|
49065
|
-
`refusing to remove unrecognized Git hook entrypoint at ${paths.gitHookEntrypoint}`
|
|
49066
|
-
);
|
|
49067
|
-
}
|
|
49068
|
-
const launcher = lstatIfPresent(paths.launcher);
|
|
49069
|
-
if (launcher) {
|
|
49070
|
-
if (!launcher.isFile() || readFileSync13(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT) {
|
|
49071
|
-
throw new Error(`refusing to remove unrecognized hook launcher at ${paths.launcher}`);
|
|
49072
|
-
}
|
|
49073
|
-
}
|
|
49074
|
-
const runtime = lstatIfPresent(paths.runtimeDir);
|
|
49075
|
-
if (!runtime) return;
|
|
49076
|
-
if (!runtime.isDirectory()) {
|
|
49077
|
-
throw new Error(`refusing to remove non-directory hook runtime at ${paths.runtimeDir}`);
|
|
49078
|
-
}
|
|
49079
|
-
const allowed = /* @__PURE__ */ new Set(["current", "releases", "selection.lock"]);
|
|
49080
|
-
const unexpected = readdirSync3(paths.runtimeDir).filter((entry) => !allowed.has(entry));
|
|
49081
|
-
if (unexpected.length > 0) {
|
|
49082
|
-
throw new Error(
|
|
49083
|
-
`refusing to remove hook runtime with unrecognized entries: ${unexpected.sort().join(", ")}`
|
|
49084
|
-
);
|
|
49085
|
-
}
|
|
49086
|
-
const current = lstatIfPresent(paths.current);
|
|
49087
|
-
const releases = lstatIfPresent(paths.releasesDir);
|
|
49088
|
-
if (current) {
|
|
49089
|
-
if (!current.isFile() || !releases || !readSelectedRelease(paths)) {
|
|
49090
|
-
throw new Error(`refusing to remove malformed hook runtime selection at ${paths.current}`);
|
|
49091
|
-
}
|
|
49092
|
-
}
|
|
49093
|
-
if (!releases) return;
|
|
49094
|
-
if (!releases.isDirectory()) {
|
|
49095
|
-
throw new Error(`refusing to remove non-directory hook releases at ${paths.releasesDir}`);
|
|
49096
|
-
}
|
|
49097
|
-
for (const entry of readdirSync3(paths.releasesDir, { withFileTypes: true })) {
|
|
49098
|
-
const releaseDir = join18(paths.releasesDir, entry.name);
|
|
49099
|
-
if (!entry.isDirectory() || !RELEASE_NAME_RE.test(entry.name) || !readReleaseManifest(releaseDir, entry.name)) {
|
|
49100
|
-
throw new Error(`refusing to remove unrecognized hook release ${releaseDir}`);
|
|
49101
|
-
}
|
|
49102
|
-
}
|
|
49103
|
-
}
|
|
49104
|
-
function removeHookRuntime(options = {}) {
|
|
49105
|
-
const paths = hookRuntimePaths(options);
|
|
49106
|
-
const hadLauncher = lstatIfPresent(paths.launcher) !== void 0;
|
|
49107
|
-
const hadEntrypoint = lstatIfPresent(paths.gitHookEntrypoint) !== void 0;
|
|
49108
|
-
const hadRuntime = lstatIfPresent(paths.runtimeDir) !== void 0;
|
|
49109
|
-
if (!hadLauncher && !hadEntrypoint && !hadRuntime) return { changed: false, paths };
|
|
49110
|
-
assertOwnedHookRuntime(paths);
|
|
49111
|
-
if (!hadRuntime) {
|
|
49112
|
-
rmSync9(paths.gitHookEntrypoint, { force: true });
|
|
49113
|
-
rmSync9(paths.launcher, { force: true });
|
|
49114
|
-
return { changed: true, paths };
|
|
49115
|
-
}
|
|
49116
|
-
withFileLockSync(paths.selectionLock, () => {
|
|
49117
|
-
assertOwnedHookRuntime(paths);
|
|
49118
|
-
if (lstatIfPresent(paths.gitHookEntrypoint)) rmSync9(paths.gitHookEntrypoint, { force: true });
|
|
49119
|
-
if (lstatIfPresent(paths.launcher)) rmSync9(paths.launcher, { force: true });
|
|
49120
|
-
const quarantined = `${paths.runtimeDir}.uninstall-${String(process.pid)}-${randomBytes5(8).toString("hex")}`;
|
|
49121
|
-
renameSync2(paths.runtimeDir, quarantined);
|
|
49122
|
-
rmSync9(quarantined, { recursive: true, force: true });
|
|
49123
|
-
});
|
|
49124
|
-
return { changed: true, paths };
|
|
49125
|
-
}
|
|
49126
|
-
|
|
49127
49143
|
// src/lib/git-hooks.ts
|
|
49128
49144
|
var LEGACY_PRIM_CREATED_MARK = "prim-created-hook";
|
|
49129
49145
|
var LEGACY_PRIM_OWNED_HEADER = "# prim post-commit hook \u2014 installed by: prim hooks install (prim-managed-hook)";
|