@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.129
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -5
- package/dist/{chunk-HZI5PBN4.js → chunk-BVGASV3B.js} +2047 -138
- package/dist/{chunk-72NIZMZN.js → chunk-DYXCJ6WZ.js} +15 -10
- package/dist/{chunk-TNWI3JWK.js → chunk-FHDTJP2C.js} +4 -2
- package/dist/{chunk-C4QNBSWB.js → chunk-HDL3UXYJ.js} +8 -8
- package/dist/{chunk-RV3JFSMX.js → chunk-IJ3W2YBM.js} +4 -4
- package/dist/{chunk-O65UVJZH.js → chunk-IZAEAALI.js} +2 -2
- package/dist/{chunk-H74RDXKP.js → chunk-KZNOT2YH.js} +2 -2
- package/dist/{chunk-R4EYLEIK.js → chunk-L7U3G4XR.js} +2 -2
- package/dist/{chunk-MGKSZSTV.js → chunk-LBZJD2I4.js} +3 -5
- package/dist/{chunk-UUQT5GMO.js → chunk-MMMY57UA.js} +22 -837
- package/dist/{chunk-H6X52UVF.js → chunk-NWWTFQP2.js} +1 -1
- package/dist/{chunk-WGTUNUIS.js → chunk-QSDWWEHF.js} +5 -5
- package/dist/{chunk-NVDPKW7Z.js → chunk-RAEOSDQ6.js} +3 -51
- package/dist/{chunk-KFRGVHGB.js → chunk-RS5ADTDF.js} +6 -6
- package/dist/{chunk-A5VTE43F.js → chunk-RWJ7WHTJ.js} +2 -2
- package/dist/{chunk-VVFVENU4.js → chunk-SJE7OWVS.js} +6 -6
- package/dist/{chunk-L6IL4N6Y.js → chunk-USJ4JGDC.js} +34 -34
- package/dist/{chunk-JCKOW45X.js → chunk-YPHDV5AS.js} +2 -2
- package/dist/{chunk-F3FDVHR7.js → chunk-YSV43WLK.js} +1 -1
- package/dist/{chunk-URYZDQFH.js → chunk-ZKIBD5MO.js} +3 -5
- package/dist/daemon/server.js +1769 -487
- package/dist/hook-runtime/daemon/server.js +1769 -487
- package/dist/hook-runtime/hooks/post-commit.js +611 -337
- package/dist/hook-runtime/hooks/post-rewrite.js +606 -332
- package/dist/hook-runtime/hooks/post-tool-use.js +1841 -683
- package/dist/hook-runtime/hooks/pre-commit.js +1713 -434
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1308 -150
- package/dist/hook-runtime/hooks/prim-hook.js +1863 -705
- package/dist/hook-runtime/hooks/session-end.js +538 -385
- package/dist/hook-runtime/hooks/session-start.js +1379 -233
- package/dist/hook-runtime/index.js +5438 -4052
- package/dist/hook-runtime/statusline-main.js +547 -273
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +18 -18
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +64 -22
- package/dist/index.js +396 -52
- package/dist/statusline-main.js +547 -273
- package/package.json +1 -1
|
@@ -203,6 +203,7 @@ function insideClaudeCode(env = process.env) {
|
|
|
203
203
|
}
|
|
204
204
|
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';
|
|
205
205
|
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';
|
|
206
|
+
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}.`;
|
|
206
207
|
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
207
208
|
function cloudSetupPointer(message, env = process.env) {
|
|
208
209
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
@@ -218,13 +219,20 @@ var GIT_TIMEOUT_MS = 1e3;
|
|
|
218
219
|
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
219
220
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
220
221
|
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
222
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
223
|
+
function gitChildEnvironment(env = process.env) {
|
|
224
|
+
return Object.fromEntries(
|
|
225
|
+
Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
|
|
226
|
+
);
|
|
227
|
+
}
|
|
221
228
|
function gitToplevel(cwd) {
|
|
222
229
|
try {
|
|
223
230
|
return execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
224
231
|
cwd,
|
|
225
232
|
encoding: "utf-8",
|
|
226
233
|
stdio: ["ignore", "pipe", "ignore"],
|
|
227
|
-
timeout: GIT_TIMEOUT_MS
|
|
234
|
+
timeout: GIT_TIMEOUT_MS,
|
|
235
|
+
env: gitChildEnvironment()
|
|
228
236
|
}).trim();
|
|
229
237
|
} catch {
|
|
230
238
|
return null;
|
|
@@ -239,7 +247,8 @@ function mainWorktreeRoot(cwd) {
|
|
|
239
247
|
cwd,
|
|
240
248
|
encoding: "utf-8",
|
|
241
249
|
stdio: ["ignore", "pipe", "ignore"],
|
|
242
|
-
timeout: GIT_TIMEOUT_MS
|
|
250
|
+
timeout: GIT_TIMEOUT_MS,
|
|
251
|
+
env: gitChildEnvironment()
|
|
243
252
|
}
|
|
244
253
|
).trim().split("\n").map((value) => resolve(cwd ?? process.cwd(), value));
|
|
245
254
|
if (gitDir === void 0 || commonDir === void 0 || gitDir === commonDir) return null;
|
|
@@ -254,7 +263,8 @@ function gitValue(cwd, args) {
|
|
|
254
263
|
cwd,
|
|
255
264
|
encoding: "utf-8",
|
|
256
265
|
stdio: ["ignore", "pipe", "ignore"],
|
|
257
|
-
timeout: GIT_TIMEOUT_MS
|
|
266
|
+
timeout: GIT_TIMEOUT_MS,
|
|
267
|
+
env: gitChildEnvironment()
|
|
258
268
|
}).trim();
|
|
259
269
|
return value || void 0;
|
|
260
270
|
} catch {
|
|
@@ -292,7 +302,8 @@ function isGitIgnored(cwd, path) {
|
|
|
292
302
|
execFileSync("git", ["check-ignore", "--quiet", "--", path], {
|
|
293
303
|
cwd,
|
|
294
304
|
stdio: ["ignore", "ignore", "ignore"],
|
|
295
|
-
timeout: GIT_TIMEOUT_MS
|
|
305
|
+
timeout: GIT_TIMEOUT_MS,
|
|
306
|
+
env: gitChildEnvironment()
|
|
296
307
|
});
|
|
297
308
|
return true;
|
|
298
309
|
} catch {
|
|
@@ -1035,14 +1046,14 @@ function throwIfAborted(signal) {
|
|
|
1035
1046
|
}
|
|
1036
1047
|
async function defaultSleep(ms, signal) {
|
|
1037
1048
|
if (!signal) {
|
|
1038
|
-
await new Promise((
|
|
1049
|
+
await new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
1039
1050
|
return;
|
|
1040
1051
|
}
|
|
1041
1052
|
throwIfAborted(signal);
|
|
1042
|
-
await new Promise((
|
|
1053
|
+
await new Promise((resolve3, reject) => {
|
|
1043
1054
|
const timer = setTimeout(() => {
|
|
1044
1055
|
signal.removeEventListener("abort", onAbort);
|
|
1045
|
-
|
|
1056
|
+
resolve3();
|
|
1046
1057
|
}, ms);
|
|
1047
1058
|
const onAbort = () => {
|
|
1048
1059
|
clearTimeout(timer);
|
|
@@ -1111,6 +1122,810 @@ async function withFileLock(lockDir, operation, options = {}) {
|
|
|
1111
1122
|
}
|
|
1112
1123
|
}
|
|
1113
1124
|
|
|
1125
|
+
// src/lib/git-hook-contract.ts
|
|
1126
|
+
var MANAGED_GIT_HOOK_NAMES = ["pre-commit", "post-commit", "post-rewrite"];
|
|
1127
|
+
var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
|
|
1128
|
+
var GIT_HOOK_CONTRACT_VERSION = 1;
|
|
1129
|
+
var CONTRACT_LINE_PREFIX = "# prim git hook v";
|
|
1130
|
+
var CONTRACT_LINE_RE = /^# prim git hook v([0-9]+)\b/mu;
|
|
1131
|
+
function blockMarkers(hook) {
|
|
1132
|
+
return { start: `# >>> prim ${hook} hook >>>`, end: `# <<< prim ${hook} hook <<<` };
|
|
1133
|
+
}
|
|
1134
|
+
function entrypointCommand(hook) {
|
|
1135
|
+
const script = [
|
|
1136
|
+
PRIM_CONFIG_SHELL_RESOLVER,
|
|
1137
|
+
`case "$prim_config" in /) prim_entry=/${GIT_HOOK_ENTRYPOINT_NAME} ;; `,
|
|
1138
|
+
`*) prim_entry="$prim_config/${GIT_HOOK_ENTRYPOINT_NAME}" ;; esac; `,
|
|
1139
|
+
'[ -x "$prim_entry" ] || exit 0; exec "$prim_entry" "$@"'
|
|
1140
|
+
].join("");
|
|
1141
|
+
return `/bin/sh -c ${shellQuote(script)} ${GIT_HOOK_ENTRYPOINT_NAME} ${hook} "$@"`;
|
|
1142
|
+
}
|
|
1143
|
+
function managedHookBlock(hook) {
|
|
1144
|
+
const { start, end } = blockMarkers(hook);
|
|
1145
|
+
const header = `${CONTRACT_LINE_PREFIX}${GIT_HOOK_CONTRACT_VERSION}: a no-op unless prim is installed and enabled here (see \`prim hooks snippet ${hook}\`).`;
|
|
1146
|
+
if (hook !== "post-rewrite") {
|
|
1147
|
+
return `${start}
|
|
1148
|
+
${header}
|
|
1149
|
+
# shellcheck disable=SC2016
|
|
1150
|
+
${entrypointCommand(hook)} || :
|
|
1151
|
+
${end}`;
|
|
1152
|
+
}
|
|
1153
|
+
return `${start}
|
|
1154
|
+
${header}
|
|
1155
|
+
prim_rewrite_stdin=$(mktemp 2>/dev/null) || prim_rewrite_stdin=
|
|
1156
|
+
if test -n "\${prim_rewrite_stdin}" && cat >"\${prim_rewrite_stdin}"; then
|
|
1157
|
+
# shellcheck disable=SC2016
|
|
1158
|
+
${entrypointCommand(hook)} <"\${prim_rewrite_stdin}" || :
|
|
1159
|
+
exec <"\${prim_rewrite_stdin}"
|
|
1160
|
+
fi
|
|
1161
|
+
if test -n "\${prim_rewrite_stdin}"; then rm -f "\${prim_rewrite_stdin}"; fi
|
|
1162
|
+
unset prim_rewrite_stdin
|
|
1163
|
+
${end}`;
|
|
1164
|
+
}
|
|
1165
|
+
var OPEN_WORDS = /* @__PURE__ */ new Set(["then", "do", "else", "{", "(", "&&", "||", "|"]);
|
|
1166
|
+
function canonicalHookBlock(text) {
|
|
1167
|
+
const tokens = [];
|
|
1168
|
+
let word = "";
|
|
1169
|
+
let quote;
|
|
1170
|
+
const separate = () => {
|
|
1171
|
+
const last = tokens.at(-1);
|
|
1172
|
+
if (last !== void 0 && last !== ";" && !OPEN_WORDS.has(last)) tokens.push(";");
|
|
1173
|
+
};
|
|
1174
|
+
const flush = () => {
|
|
1175
|
+
if (word === "") return;
|
|
1176
|
+
const last = tokens.at(-1);
|
|
1177
|
+
if (last !== void 0 && /^[0-9]*(?:<|>|>>|<&|>&)$/u.test(last))
|
|
1178
|
+
tokens[tokens.length - 1] += word;
|
|
1179
|
+
else tokens.push(word);
|
|
1180
|
+
word = "";
|
|
1181
|
+
};
|
|
1182
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
1183
|
+
const char = text[index];
|
|
1184
|
+
if (quote) {
|
|
1185
|
+
word += char;
|
|
1186
|
+
if (char === quote) quote = void 0;
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
if (char === "'" || char === '"') {
|
|
1190
|
+
quote = char;
|
|
1191
|
+
word += char;
|
|
1192
|
+
} else if (char === "#" && word === "") {
|
|
1193
|
+
const end = text.indexOf("\n", index);
|
|
1194
|
+
const comment = text.slice(index, end === -1 ? text.length : end);
|
|
1195
|
+
tokens.push(comment.replace(/\s+/gu, " ").trim());
|
|
1196
|
+
index = (end === -1 ? text.length : end) - 1;
|
|
1197
|
+
} else if (char === "\n" || char === ";") {
|
|
1198
|
+
flush();
|
|
1199
|
+
if (char === ";" && text[index + 1] === ";") {
|
|
1200
|
+
tokens.push(";;");
|
|
1201
|
+
index += 1;
|
|
1202
|
+
} else {
|
|
1203
|
+
separate();
|
|
1204
|
+
}
|
|
1205
|
+
} else if (/\s/u.test(char)) {
|
|
1206
|
+
flush();
|
|
1207
|
+
} else {
|
|
1208
|
+
word += char;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
flush();
|
|
1212
|
+
while (tokens.at(-1) === ";") tokens.pop();
|
|
1213
|
+
return tokens.join("\0");
|
|
1214
|
+
}
|
|
1215
|
+
function hookBlockContractVersion(block) {
|
|
1216
|
+
const match = CONTRACT_LINE_RE.exec(block);
|
|
1217
|
+
return match?.[1] ? Number(match[1]) : void 0;
|
|
1218
|
+
}
|
|
1219
|
+
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
1220
|
+
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
1221
|
+
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
1222
|
+
# where prim is active (git config prim.active true) and never fails the hook.
|
|
1223
|
+
case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
|
|
1224
|
+
prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
|
|
1225
|
+
[ -x "$prim_launcher" ] || exit 0
|
|
1226
|
+
[ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
|
|
1227
|
+
prim_hook=\${1-}
|
|
1228
|
+
if [ "$#" -gt 0 ]; then shift; fi
|
|
1229
|
+
case "$prim_hook" in
|
|
1230
|
+
pre-commit)
|
|
1231
|
+
"$prim_launcher" prim-pre-commit "$@" || :
|
|
1232
|
+
;;
|
|
1233
|
+
post-commit)
|
|
1234
|
+
prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
|
|
1235
|
+
case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
|
|
1236
|
+
case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
|
|
1237
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
1238
|
+
prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
|
|
1239
|
+
(
|
|
1240
|
+
trap '' HUP
|
|
1241
|
+
trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
|
|
1242
|
+
PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
|
|
1243
|
+
) </dev/null >/dev/null 2>&1 &
|
|
1244
|
+
;;
|
|
1245
|
+
post-rewrite)
|
|
1246
|
+
case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
|
|
1247
|
+
prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
|
|
1248
|
+
if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
|
|
1249
|
+
rm -f "$prim_pairs"
|
|
1250
|
+
exit 0
|
|
1251
|
+
fi
|
|
1252
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
1253
|
+
(
|
|
1254
|
+
trap '' HUP
|
|
1255
|
+
trap 'rm -f "$prim_pairs"' 0
|
|
1256
|
+
PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
|
|
1257
|
+
) </dev/null >/dev/null 2>&1 &
|
|
1258
|
+
;;
|
|
1259
|
+
esac
|
|
1260
|
+
exit 0
|
|
1261
|
+
`;
|
|
1262
|
+
|
|
1263
|
+
// src/lib/hook-runtime.ts
|
|
1264
|
+
import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
|
|
1265
|
+
import {
|
|
1266
|
+
constants as constants2,
|
|
1267
|
+
accessSync,
|
|
1268
|
+
chmodSync,
|
|
1269
|
+
copyFileSync,
|
|
1270
|
+
existsSync as existsSync6,
|
|
1271
|
+
lstatSync as lstatSync2,
|
|
1272
|
+
mkdirSync as mkdirSync4,
|
|
1273
|
+
mkdtempSync,
|
|
1274
|
+
readFileSync as readFileSync6,
|
|
1275
|
+
readdirSync,
|
|
1276
|
+
realpathSync as realpathSync2,
|
|
1277
|
+
renameSync as renameSync2,
|
|
1278
|
+
rmSync as rmSync4,
|
|
1279
|
+
statSync as statSync2,
|
|
1280
|
+
utimesSync,
|
|
1281
|
+
writeFileSync as writeFileSync4
|
|
1282
|
+
} from "fs";
|
|
1283
|
+
import { delimiter, dirname as dirname6, isAbsolute as isAbsolute4, join as join8, resolve as resolve2 } from "path";
|
|
1284
|
+
|
|
1285
|
+
// src/lib/native-keyring.ts
|
|
1286
|
+
import { existsSync as existsSync5 } from "fs";
|
|
1287
|
+
import { createRequire } from "module";
|
|
1288
|
+
import { dirname as dirname5, join as join7 } from "path";
|
|
1289
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1290
|
+
var require2 = createRequire(import.meta.url);
|
|
1291
|
+
var KEYRING_LOADER = 'module.exports = require("./keyring.node");\n';
|
|
1292
|
+
var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
|
|
1293
|
+
function keyringNativeBinary() {
|
|
1294
|
+
let directory = dirname5(fileURLToPath2(import.meta.url));
|
|
1295
|
+
for (let depth = 0; depth < 5; depth++) {
|
|
1296
|
+
const binary2 = join7(directory, "native", "keyring.node");
|
|
1297
|
+
if (existsSync5(binary2)) return binary2;
|
|
1298
|
+
directory = dirname5(directory);
|
|
1299
|
+
}
|
|
1300
|
+
const packagePath = require2.resolve("@napi-rs/keyring");
|
|
1301
|
+
require2(packagePath);
|
|
1302
|
+
const entry = require2.cache[packagePath];
|
|
1303
|
+
const binary = entry?.children.find(
|
|
1304
|
+
(child) => child.filename.endsWith(".node") && child.filename.includes("keyring")
|
|
1305
|
+
);
|
|
1306
|
+
if (!binary || !existsSync5(binary.filename))
|
|
1307
|
+
throw new Error(
|
|
1308
|
+
"Cannot stage the native credential store; reinstall Prim with optional dependencies enabled."
|
|
1309
|
+
);
|
|
1310
|
+
return binary.filename;
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
// src/lib/hook-runtime.ts
|
|
1314
|
+
var HOOK_RUNTIME_SCHEMA_VERSION = 1;
|
|
1315
|
+
var DIRECTORY_MODE2 = 448;
|
|
1316
|
+
var DATA_FILE_MODE = 384;
|
|
1317
|
+
var LAUNCHER_MODE = 448;
|
|
1318
|
+
var RELEASE_PREFIX = "release-";
|
|
1319
|
+
var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
|
|
1320
|
+
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
1321
|
+
var MAX_RELEASES = 8;
|
|
1322
|
+
var MAX_RELEASE_DELETIONS_PER_STAGE = 8;
|
|
1323
|
+
var RETAIN_PREDECESSORS = 2;
|
|
1324
|
+
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
1325
|
+
var HOOK_RUNTIME_ENTRIES = {
|
|
1326
|
+
// SessionStart self-healing resolves this exact CLI entry to run
|
|
1327
|
+
// `daemon ensure`; it must travel with the immutable hook release.
|
|
1328
|
+
prim: "dist/index.js",
|
|
1329
|
+
"prim-hook": "dist/hooks/prim-hook.js",
|
|
1330
|
+
"prim-pre-commit": "dist/hooks/pre-commit.js",
|
|
1331
|
+
"prim-post-commit": "dist/hooks/post-commit.js",
|
|
1332
|
+
"prim-post-rewrite": "dist/hooks/post-rewrite.js",
|
|
1333
|
+
"prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
|
|
1334
|
+
"prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
|
|
1335
|
+
"prim-post-tool-use": "dist/hooks/post-tool-use.js",
|
|
1336
|
+
"prim-session-start": "dist/hooks/session-start.js",
|
|
1337
|
+
"prim-session-end": "dist/hooks/session-end.js",
|
|
1338
|
+
"prim-daemon-server": "dist/daemon/server.js",
|
|
1339
|
+
"prim-statusline": "dist/statusline-main.js"
|
|
1340
|
+
};
|
|
1341
|
+
var SOURCE_ENTRIES = Object.fromEntries(
|
|
1342
|
+
Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
|
|
1343
|
+
bin,
|
|
1344
|
+
target.replace(/^dist\//u, "")
|
|
1345
|
+
])
|
|
1346
|
+
);
|
|
1347
|
+
function hookRuntimePaths(options = {}) {
|
|
1348
|
+
const env = options.env ?? process.env;
|
|
1349
|
+
const configDir = primConfigDirectory({
|
|
1350
|
+
...options,
|
|
1351
|
+
env,
|
|
1352
|
+
homeDir: options.homeDir ?? env.HOME ?? ""
|
|
1353
|
+
});
|
|
1354
|
+
const runtimeDir = join8(configDir, "hook-runtime");
|
|
1355
|
+
return {
|
|
1356
|
+
configDir,
|
|
1357
|
+
launcher: join8(configDir, STABLE_HOOK_LAUNCHER_NAME),
|
|
1358
|
+
gitHookEntrypoint: join8(configDir, GIT_HOOK_ENTRYPOINT_NAME),
|
|
1359
|
+
runtimeDir,
|
|
1360
|
+
releasesDir: join8(runtimeDir, "releases"),
|
|
1361
|
+
current: join8(runtimeDir, "current"),
|
|
1362
|
+
selectionLock: join8(runtimeDir, "selection.lock")
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
function sha256(path) {
|
|
1366
|
+
return createHash2("sha256").update(readFileSync6(path)).digest("hex");
|
|
1367
|
+
}
|
|
1368
|
+
function exactManifest(manifest) {
|
|
1369
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
1370
|
+
`;
|
|
1371
|
+
}
|
|
1372
|
+
function exactKeys(value, expected) {
|
|
1373
|
+
const actual = Object.keys(value).sort();
|
|
1374
|
+
const wanted = [...expected].sort();
|
|
1375
|
+
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
1376
|
+
}
|
|
1377
|
+
function releaseId(manifest) {
|
|
1378
|
+
return createHash2("sha256").update(exactManifest(manifest)).digest("hex");
|
|
1379
|
+
}
|
|
1380
|
+
function runtimePackageJson(manifest) {
|
|
1381
|
+
return `${JSON.stringify(
|
|
1382
|
+
{
|
|
1383
|
+
name: "@primitive.ai/prim",
|
|
1384
|
+
version: manifest.version,
|
|
1385
|
+
type: "module",
|
|
1386
|
+
bin: HOOK_RUNTIME_ENTRIES
|
|
1387
|
+
},
|
|
1388
|
+
null,
|
|
1389
|
+
2
|
|
1390
|
+
)}
|
|
1391
|
+
`;
|
|
1392
|
+
}
|
|
1393
|
+
function validateRelease(releaseDir, manifest) {
|
|
1394
|
+
try {
|
|
1395
|
+
if (!directReleaseLayout(releaseDir, manifest)) return false;
|
|
1396
|
+
if (readFileSync6(join8(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
|
|
1397
|
+
return false;
|
|
1398
|
+
}
|
|
1399
|
+
if (readFileSync6(join8(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
|
|
1400
|
+
return false;
|
|
1401
|
+
}
|
|
1402
|
+
if (readFileSync6(join8(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
|
|
1403
|
+
`) {
|
|
1404
|
+
return false;
|
|
1405
|
+
}
|
|
1406
|
+
for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
1407
|
+
const target = join8(releaseDir, relativePath);
|
|
1408
|
+
if (sha256(target) !== manifest.files[bin]) return false;
|
|
1409
|
+
}
|
|
1410
|
+
for (const [path, digest] of Object.entries(manifest.native ?? {})) {
|
|
1411
|
+
if (sha256(join8(releaseDir, path)) !== digest) return false;
|
|
1412
|
+
}
|
|
1413
|
+
return true;
|
|
1414
|
+
} catch {
|
|
1415
|
+
return false;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
function directReleaseLayout(releaseDir, manifest) {
|
|
1419
|
+
try {
|
|
1420
|
+
const directories = /* @__PURE__ */ new Set([releaseDir]);
|
|
1421
|
+
for (const relativePath of [
|
|
1422
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
1423
|
+
...Object.keys(manifest.native ?? {})
|
|
1424
|
+
]) {
|
|
1425
|
+
for (let directory = dirname6(relativePath); directory !== "."; directory = dirname6(directory)) {
|
|
1426
|
+
directories.add(join8(releaseDir, directory));
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
if (![...directories].every((directory) => lstatSync2(directory).isDirectory())) return false;
|
|
1430
|
+
const files = [
|
|
1431
|
+
"manifest.json",
|
|
1432
|
+
"package.json",
|
|
1433
|
+
"node",
|
|
1434
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
1435
|
+
...Object.keys(manifest.native ?? {})
|
|
1436
|
+
];
|
|
1437
|
+
const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join8(releaseDir, path))]);
|
|
1438
|
+
if (![...directories].every(
|
|
1439
|
+
(directory) => readdirSync(directory).every((name) => owned.has(join8(directory, name)))
|
|
1440
|
+
))
|
|
1441
|
+
return false;
|
|
1442
|
+
return files.every((relativePath) => lstatSync2(join8(releaseDir, relativePath)).isFile());
|
|
1443
|
+
} catch {
|
|
1444
|
+
return false;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
function readReleaseManifest(releaseDir, releaseName) {
|
|
1448
|
+
try {
|
|
1449
|
+
const manifestPath = join8(releaseDir, "manifest.json");
|
|
1450
|
+
const manifestStat = statSync2(manifestPath);
|
|
1451
|
+
if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
|
|
1452
|
+
const raw = readFileSync6(manifestPath, "utf8");
|
|
1453
|
+
const parsed = JSON.parse(raw);
|
|
1454
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
1455
|
+
if (!exactKeys(parsed, [
|
|
1456
|
+
"schemaVersion",
|
|
1457
|
+
"version",
|
|
1458
|
+
"nodePath",
|
|
1459
|
+
"files",
|
|
1460
|
+
..."native" in parsed ? ["native"] : []
|
|
1461
|
+
]))
|
|
1462
|
+
return null;
|
|
1463
|
+
const candidate = parsed;
|
|
1464
|
+
if (candidate.schemaVersion !== HOOK_RUNTIME_SCHEMA_VERSION || typeof candidate.version !== "string" || compareSemver(candidate.version, candidate.version) !== 0 || typeof candidate.nodePath !== "string" || !isAbsolute4(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(
|
|
1465
|
+
(digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
|
|
1466
|
+
)) {
|
|
1467
|
+
return null;
|
|
1468
|
+
}
|
|
1469
|
+
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(
|
|
1470
|
+
(digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
|
|
1471
|
+
)))
|
|
1472
|
+
return null;
|
|
1473
|
+
const manifest = candidate;
|
|
1474
|
+
if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
|
|
1475
|
+
return null;
|
|
1476
|
+
}
|
|
1477
|
+
return manifest;
|
|
1478
|
+
} catch {
|
|
1479
|
+
return null;
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
function readSelectedRelease(paths) {
|
|
1483
|
+
let raw;
|
|
1484
|
+
try {
|
|
1485
|
+
raw = readFileSync6(paths.current, "utf8");
|
|
1486
|
+
} catch (error) {
|
|
1487
|
+
if (error.code === "ENOENT") return null;
|
|
1488
|
+
throw error;
|
|
1489
|
+
}
|
|
1490
|
+
const name = raw.endsWith("\n") ? raw.slice(0, -1) : "";
|
|
1491
|
+
if (`${name}
|
|
1492
|
+
` !== raw || !RELEASE_NAME_RE.test(name)) {
|
|
1493
|
+
throw new Error("cannot stage hook runtime: selected release is malformed");
|
|
1494
|
+
}
|
|
1495
|
+
const dir = join8(paths.releasesDir, name);
|
|
1496
|
+
const manifest = readReleaseManifest(dir, name);
|
|
1497
|
+
if (!manifest) {
|
|
1498
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
1499
|
+
}
|
|
1500
|
+
return { name, dir, manifest };
|
|
1501
|
+
}
|
|
1502
|
+
function selectedHookRuntimeKeyringLoader(options = {}) {
|
|
1503
|
+
try {
|
|
1504
|
+
const selected = readSelectedRelease(hookRuntimePaths(options));
|
|
1505
|
+
if (!selected?.manifest.native) return void 0;
|
|
1506
|
+
const loader = join8(selected.dir, "native", "keyring.cjs");
|
|
1507
|
+
return existsSync6(loader) ? loader : void 0;
|
|
1508
|
+
} catch {
|
|
1509
|
+
return void 0;
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
function releaseEntries(paths) {
|
|
1513
|
+
return readdirSync(paths.releasesDir, { withFileTypes: true }).flatMap((entry) => {
|
|
1514
|
+
if (!entry.isDirectory() || !RELEASE_NAME_RE.test(entry.name)) return [];
|
|
1515
|
+
const dir = join8(paths.releasesDir, entry.name);
|
|
1516
|
+
try {
|
|
1517
|
+
return [{ name: entry.name, dir, mtimeMs: statSync2(dir).mtimeMs }];
|
|
1518
|
+
} catch {
|
|
1519
|
+
return [];
|
|
1520
|
+
}
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
function pruneReleases(paths, protectedNames, reserveSlots, now) {
|
|
1524
|
+
const entries = releaseEntries(paths).sort(
|
|
1525
|
+
(left, right) => right.mtimeMs - left.mtimeMs || left.name.localeCompare(right.name)
|
|
1526
|
+
);
|
|
1527
|
+
const protectedWithPredecessors = new Set(protectedNames);
|
|
1528
|
+
for (const entry of entries) {
|
|
1529
|
+
if (protectedWithPredecessors.size >= protectedNames.size + RETAIN_PREDECESSORS) break;
|
|
1530
|
+
if (!protectedWithPredecessors.has(entry.name)) protectedWithPredecessors.add(entry.name);
|
|
1531
|
+
}
|
|
1532
|
+
const candidates = entries.filter(
|
|
1533
|
+
(entry) => !protectedWithPredecessors.has(entry.name) && now - entry.mtimeMs >= RELEASE_GRACE_MS
|
|
1534
|
+
).sort((left, right) => left.mtimeMs - right.mtimeMs || left.name.localeCompare(right.name));
|
|
1535
|
+
let remaining = entries.length;
|
|
1536
|
+
let deleted = 0;
|
|
1537
|
+
for (const entry of candidates) {
|
|
1538
|
+
if (remaining + reserveSlots <= MAX_RELEASES || deleted >= MAX_RELEASE_DELETIONS_PER_STAGE) {
|
|
1539
|
+
break;
|
|
1540
|
+
}
|
|
1541
|
+
rmSync4(entry.dir, { recursive: true, force: true });
|
|
1542
|
+
remaining -= 1;
|
|
1543
|
+
deleted += 1;
|
|
1544
|
+
}
|
|
1545
|
+
if (remaining + reserveSlots > MAX_RELEASES) {
|
|
1546
|
+
throw new Error(
|
|
1547
|
+
"cannot stage hook runtime: release retention is full while recent runtimes are protected"
|
|
1548
|
+
);
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
function sourceManifest(sourceDir, version, nodePath) {
|
|
1552
|
+
const files = {};
|
|
1553
|
+
for (const [bin, relativePath] of Object.entries(SOURCE_ENTRIES)) {
|
|
1554
|
+
const source = join8(sourceDir, relativePath);
|
|
1555
|
+
if (!existsSync6(source) || !statSync2(source).isFile()) {
|
|
1556
|
+
throw new Error(`cannot stage hook runtime: missing self-contained ${bin} bundle`);
|
|
1557
|
+
}
|
|
1558
|
+
files[bin] = sha256(source);
|
|
1559
|
+
}
|
|
1560
|
+
return {
|
|
1561
|
+
schemaVersion: HOOK_RUNTIME_SCHEMA_VERSION,
|
|
1562
|
+
version,
|
|
1563
|
+
nodePath,
|
|
1564
|
+
files,
|
|
1565
|
+
native: {
|
|
1566
|
+
"native/keyring.cjs": createHash2("sha256").update(KEYRING_LOADER).digest("hex"),
|
|
1567
|
+
"native/keyring.node": sha256(keyringNativeBinary())
|
|
1568
|
+
}
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
1572
|
+
set -eu
|
|
1573
|
+
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
1574
|
+
IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
|
|
1575
|
+
case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
|
|
1576
|
+
prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
|
|
1577
|
+
case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
|
|
1578
|
+
[ "\${#prim_release_id}" -eq 64 ] || exit 69
|
|
1579
|
+
prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
|
|
1580
|
+
case "\${1-}" in
|
|
1581
|
+
${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
|
|
1582
|
+
*) exit 64 ;;
|
|
1583
|
+
esac
|
|
1584
|
+
shift
|
|
1585
|
+
IFS= read -r prim_node < "$prim_release/node" || exit 69
|
|
1586
|
+
case "$prim_node" in /*) ;; *) exit 69 ;; esac
|
|
1587
|
+
[ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
|
|
1588
|
+
exec "$prim_node" "$prim_entry" "$@"
|
|
1589
|
+
`;
|
|
1590
|
+
function privateDirectory(path) {
|
|
1591
|
+
const stat = lstatIfPresent(path);
|
|
1592
|
+
if (!stat?.isDirectory()) return false;
|
|
1593
|
+
if (process.platform === "win32") return true;
|
|
1594
|
+
const uid = process.getuid?.();
|
|
1595
|
+
return (Number(stat.mode) & 511) === DIRECTORY_MODE2 && (uid === void 0 || stat.uid === uid);
|
|
1596
|
+
}
|
|
1597
|
+
function privateFile(path, mode) {
|
|
1598
|
+
const stat = lstatIfPresent(path);
|
|
1599
|
+
if (!stat?.isFile()) return false;
|
|
1600
|
+
if (process.platform === "win32") return true;
|
|
1601
|
+
const uid = process.getuid?.();
|
|
1602
|
+
return (Number(stat.mode) & 511) === mode && (uid === void 0 || stat.uid === uid);
|
|
1603
|
+
}
|
|
1604
|
+
function hasSafeRuntimeLayout(paths, selected) {
|
|
1605
|
+
const releaseDirectories = /* @__PURE__ */ new Set([selected.dir]);
|
|
1606
|
+
for (const relativePath of [
|
|
1607
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
1608
|
+
...Object.keys(selected.manifest.native ?? {})
|
|
1609
|
+
]) {
|
|
1610
|
+
for (let directory = dirname6(relativePath); directory !== "."; directory = dirname6(directory)) {
|
|
1611
|
+
releaseDirectories.add(join8(selected.dir, directory));
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
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(join8(selected.dir, "manifest.json"), DATA_FILE_MODE) || !privateFile(join8(selected.dir, "package.json"), DATA_FILE_MODE) || !privateFile(join8(selected.dir, "node"), DATA_FILE_MODE)) {
|
|
1615
|
+
return false;
|
|
1616
|
+
}
|
|
1617
|
+
return [
|
|
1618
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
1619
|
+
...Object.keys(selected.manifest.native ?? {})
|
|
1620
|
+
].every((relativePath) => privateFile(join8(selected.dir, relativePath), DATA_FILE_MODE));
|
|
1621
|
+
}
|
|
1622
|
+
function sameNodeExecutable(recorded, desired) {
|
|
1623
|
+
try {
|
|
1624
|
+
if (!statSync2(recorded).isFile()) return false;
|
|
1625
|
+
accessSync(recorded, constants2.X_OK);
|
|
1626
|
+
return realpathSync2(recorded) === realpathSync2(desired);
|
|
1627
|
+
} catch {
|
|
1628
|
+
return false;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
function recordedNodeMatchesCurrentProcess(nodePath) {
|
|
1632
|
+
return sameNodeExecutable(nodePath, process.execPath);
|
|
1633
|
+
}
|
|
1634
|
+
function inspectHookRuntime(options = {}) {
|
|
1635
|
+
let paths;
|
|
1636
|
+
try {
|
|
1637
|
+
paths = hookRuntimePaths(options);
|
|
1638
|
+
} catch {
|
|
1639
|
+
return { state: "invalid" };
|
|
1640
|
+
}
|
|
1641
|
+
const launcher = lstatIfPresent(paths.launcher);
|
|
1642
|
+
const selector = lstatIfPresent(paths.current);
|
|
1643
|
+
if (!(launcher || selector)) return { state: "missing" };
|
|
1644
|
+
if (!(launcher && selector)) return { state: "invalid" };
|
|
1645
|
+
try {
|
|
1646
|
+
if (readFileSync6(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT) {
|
|
1647
|
+
return { state: "invalid" };
|
|
1648
|
+
}
|
|
1649
|
+
const selected = readSelectedRelease(paths);
|
|
1650
|
+
if (!selected) return { state: "invalid" };
|
|
1651
|
+
assertOwnedHookRuntime(paths);
|
|
1652
|
+
if (!hasSafeRuntimeLayout(paths, selected)) return { state: "invalid" };
|
|
1653
|
+
return recordedNodeMatchesCurrentProcess(selected.manifest.nodePath) ? { state: "ready", version: selected.manifest.version } : { state: "invalid" };
|
|
1654
|
+
} catch {
|
|
1655
|
+
return { state: "invalid" };
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
function writeRelease(sourceDir, releaseDir, manifest, releasesDir) {
|
|
1659
|
+
const stagingDir = mkdtempSync(join8(releasesDir, ".stage-"));
|
|
1660
|
+
chmodSync(stagingDir, DIRECTORY_MODE2);
|
|
1661
|
+
try {
|
|
1662
|
+
const directories = /* @__PURE__ */ new Set([stagingDir]);
|
|
1663
|
+
const syncStagedFile = (path) => {
|
|
1664
|
+
syncFile(path);
|
|
1665
|
+
for (let directory = dirname6(path); ; directory = dirname6(directory)) {
|
|
1666
|
+
directories.add(directory);
|
|
1667
|
+
if (directory === stagingDir) break;
|
|
1668
|
+
}
|
|
1669
|
+
};
|
|
1670
|
+
for (const [bin, targetRelative] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
1671
|
+
const source = join8(sourceDir, SOURCE_ENTRIES[bin]);
|
|
1672
|
+
const target = join8(stagingDir, targetRelative);
|
|
1673
|
+
mkdirSync4(dirname6(target), { recursive: true, mode: DIRECTORY_MODE2 });
|
|
1674
|
+
chmodSync(dirname6(target), DIRECTORY_MODE2);
|
|
1675
|
+
copyFileSync(source, target);
|
|
1676
|
+
chmodSync(target, DATA_FILE_MODE);
|
|
1677
|
+
if (sha256(target) !== manifest.files[bin]) {
|
|
1678
|
+
throw new Error(`cannot stage hook runtime: ${bin} changed while it was copied`);
|
|
1679
|
+
}
|
|
1680
|
+
syncStagedFile(target);
|
|
1681
|
+
}
|
|
1682
|
+
if (manifest.native) {
|
|
1683
|
+
const nativeDir = join8(stagingDir, "native");
|
|
1684
|
+
mkdirSync4(nativeDir, { mode: DIRECTORY_MODE2 });
|
|
1685
|
+
writeFileSync4(join8(nativeDir, "keyring.cjs"), KEYRING_LOADER, { mode: DATA_FILE_MODE });
|
|
1686
|
+
copyFileSync(keyringNativeBinary(), join8(nativeDir, "keyring.node"));
|
|
1687
|
+
chmodSync(join8(nativeDir, "keyring.node"), DATA_FILE_MODE);
|
|
1688
|
+
for (const [path, digest] of Object.entries(manifest.native)) {
|
|
1689
|
+
const target = join8(stagingDir, path);
|
|
1690
|
+
if (sha256(target) !== digest)
|
|
1691
|
+
throw new Error("Native credential store changed while copying");
|
|
1692
|
+
syncStagedFile(target);
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
const nodePath = join8(stagingDir, "node");
|
|
1696
|
+
writeFileSync4(nodePath, `${manifest.nodePath}
|
|
1697
|
+
`, {
|
|
1698
|
+
encoding: "utf8",
|
|
1699
|
+
flag: "wx",
|
|
1700
|
+
mode: DATA_FILE_MODE
|
|
1701
|
+
});
|
|
1702
|
+
syncStagedFile(nodePath);
|
|
1703
|
+
const packageJsonPath = join8(stagingDir, "package.json");
|
|
1704
|
+
writeFileSync4(packageJsonPath, runtimePackageJson(manifest), {
|
|
1705
|
+
encoding: "utf8",
|
|
1706
|
+
flag: "wx",
|
|
1707
|
+
mode: DATA_FILE_MODE
|
|
1708
|
+
});
|
|
1709
|
+
syncStagedFile(packageJsonPath);
|
|
1710
|
+
const manifestPath = join8(stagingDir, "manifest.json");
|
|
1711
|
+
writeFileSync4(manifestPath, exactManifest(manifest), {
|
|
1712
|
+
encoding: "utf8",
|
|
1713
|
+
flag: "wx",
|
|
1714
|
+
mode: DATA_FILE_MODE
|
|
1715
|
+
});
|
|
1716
|
+
syncStagedFile(manifestPath);
|
|
1717
|
+
for (const directory of [...directories].sort((left, right) => right.length - left.length)) {
|
|
1718
|
+
syncDirectory(directory);
|
|
1719
|
+
}
|
|
1720
|
+
try {
|
|
1721
|
+
renameSync2(stagingDir, releaseDir);
|
|
1722
|
+
} catch (error) {
|
|
1723
|
+
const code = error.code;
|
|
1724
|
+
if (code !== "EEXIST" && code !== "ENOTEMPTY" || !validateRelease(releaseDir, manifest)) {
|
|
1725
|
+
throw error;
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
} finally {
|
|
1729
|
+
rmSync4(stagingDir, { recursive: true, force: true });
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
function stableNodePath(execPath = process.execPath, searchPath = process.env.PATH ?? "") {
|
|
1733
|
+
let target;
|
|
1734
|
+
try {
|
|
1735
|
+
target = realpathSync2(execPath);
|
|
1736
|
+
} catch {
|
|
1737
|
+
return execPath;
|
|
1738
|
+
}
|
|
1739
|
+
for (const directory of searchPath.split(delimiter)) {
|
|
1740
|
+
if (!isAbsolute4(directory)) continue;
|
|
1741
|
+
const candidate = join8(directory, "node");
|
|
1742
|
+
try {
|
|
1743
|
+
if (realpathSync2(candidate) === target) return candidate;
|
|
1744
|
+
} catch {
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
return execPath;
|
|
1748
|
+
}
|
|
1749
|
+
function stageHookRuntime(options = {}) {
|
|
1750
|
+
const root = packageRoot();
|
|
1751
|
+
const sourceDir = options.sourceDir ?? (root ? join8(root, "dist", "hook-runtime") : null);
|
|
1752
|
+
const version = options.version ?? packageVersion();
|
|
1753
|
+
const nodePath = resolve2(options.nodePath ?? stableNodePath());
|
|
1754
|
+
if (!sourceDir || !version || compareSemver(version, version) !== 0 || !isAbsolute4(nodePath) || /[\r\n]/u.test(nodePath)) {
|
|
1755
|
+
throw new Error("cannot stage hook runtime: package identity is unavailable");
|
|
1756
|
+
}
|
|
1757
|
+
const manifest = sourceManifest(sourceDir, version, nodePath);
|
|
1758
|
+
const paths = hookRuntimePaths(options);
|
|
1759
|
+
const releaseName = `${RELEASE_PREFIX}${releaseId(manifest)}`;
|
|
1760
|
+
const releaseDir = join8(paths.releasesDir, releaseName);
|
|
1761
|
+
mkdirSync4(paths.releasesDir, { recursive: true, mode: DIRECTORY_MODE2 });
|
|
1762
|
+
chmodSync(paths.configDir, DIRECTORY_MODE2);
|
|
1763
|
+
chmodSync(paths.runtimeDir, DIRECTORY_MODE2);
|
|
1764
|
+
chmodSync(paths.releasesDir, DIRECTORY_MODE2);
|
|
1765
|
+
return withFileLockSync(paths.selectionLock, () => {
|
|
1766
|
+
const now = Date.now();
|
|
1767
|
+
const selected = readSelectedRelease(paths);
|
|
1768
|
+
if (selected) utimesSync(selected.dir, now / 1e3, now / 1e3);
|
|
1769
|
+
const precedence = selected ? compareSemver(selected.manifest.version, manifest.version) : -1;
|
|
1770
|
+
if (precedence === void 0) {
|
|
1771
|
+
throw new Error("cannot stage hook runtime: selected release version is malformed");
|
|
1772
|
+
}
|
|
1773
|
+
const selectRequested = !selected || precedence < 0 || precedence === 0 && !sameNodeExecutable(selected.manifest.nodePath, nodePath);
|
|
1774
|
+
const requestedExists = existsSync6(releaseDir);
|
|
1775
|
+
const protectedBefore = new Set(selected ? [selected.name] : []);
|
|
1776
|
+
if (selectRequested && requestedExists) protectedBefore.add(releaseName);
|
|
1777
|
+
pruneReleases(paths, protectedBefore, selectRequested && !requestedExists ? 1 : 0, now);
|
|
1778
|
+
if (selectRequested && !validateRelease(releaseDir, manifest)) {
|
|
1779
|
+
if (requestedExists) {
|
|
1780
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
1781
|
+
}
|
|
1782
|
+
writeRelease(sourceDir, releaseDir, manifest, paths.releasesDir);
|
|
1783
|
+
}
|
|
1784
|
+
const finalRelease = selectRequested ? { name: releaseName, dir: releaseDir, manifest } : selected;
|
|
1785
|
+
const launcherCurrent = (() => {
|
|
1786
|
+
try {
|
|
1787
|
+
return readFileSync6(paths.launcher, "utf8") === STABLE_HOOK_LAUNCHER_CONTENT;
|
|
1788
|
+
} catch {
|
|
1789
|
+
return false;
|
|
1790
|
+
}
|
|
1791
|
+
})();
|
|
1792
|
+
const selectorCurrent = selected?.name === finalRelease.name;
|
|
1793
|
+
if (!launcherCurrent) {
|
|
1794
|
+
atomicWriteFile(paths.launcher, STABLE_HOOK_LAUNCHER_CONTENT, {
|
|
1795
|
+
ensureParent: true,
|
|
1796
|
+
mode: LAUNCHER_MODE
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
const entrypointCurrent = gitHookEntrypointCurrent(paths);
|
|
1800
|
+
if (!entrypointCurrent) {
|
|
1801
|
+
atomicWriteFile(paths.gitHookEntrypoint, GIT_HOOK_ENTRYPOINT_CONTENT, {
|
|
1802
|
+
ensureParent: true,
|
|
1803
|
+
mode: LAUNCHER_MODE
|
|
1804
|
+
});
|
|
1805
|
+
}
|
|
1806
|
+
if (!selectorCurrent) {
|
|
1807
|
+
syncDirectory(paths.releasesDir);
|
|
1808
|
+
atomicWriteFile(paths.current, `${finalRelease.name}
|
|
1809
|
+
`, {
|
|
1810
|
+
ensureParent: true,
|
|
1811
|
+
mode: DATA_FILE_MODE
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
utimesSync(finalRelease.dir, now / 1e3, now / 1e3);
|
|
1815
|
+
pruneReleases(
|
|
1816
|
+
paths,
|
|
1817
|
+
/* @__PURE__ */ new Set([finalRelease.name, ...selected ? [selected.name] : []]),
|
|
1818
|
+
0,
|
|
1819
|
+
now
|
|
1820
|
+
);
|
|
1821
|
+
return {
|
|
1822
|
+
changed: !launcherCurrent || !entrypointCurrent || !selectorCurrent,
|
|
1823
|
+
releaseDir: finalRelease.dir,
|
|
1824
|
+
manifest: finalRelease.manifest,
|
|
1825
|
+
paths
|
|
1826
|
+
};
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
function gitHookEntrypointCurrent(paths) {
|
|
1830
|
+
try {
|
|
1831
|
+
return readFileSync6(paths.gitHookEntrypoint, "utf8") === GIT_HOOK_ENTRYPOINT_CONTENT;
|
|
1832
|
+
} catch {
|
|
1833
|
+
return false;
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
function inspectGitHookEntrypoint(options = {}) {
|
|
1837
|
+
let paths;
|
|
1838
|
+
try {
|
|
1839
|
+
paths = hookRuntimePaths(options);
|
|
1840
|
+
} catch {
|
|
1841
|
+
return "invalid";
|
|
1842
|
+
}
|
|
1843
|
+
try {
|
|
1844
|
+
const entrypoint = lstatIfPresent(paths.gitHookEntrypoint);
|
|
1845
|
+
if (!entrypoint) return "missing";
|
|
1846
|
+
if (!entrypoint.isFile() || (Number(entrypoint.mode) & 64) === 0 || !gitHookEntrypointCurrent(paths) || readFileSync6(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT || !lstatIfPresent(paths.current)?.isFile()) {
|
|
1847
|
+
return "invalid";
|
|
1848
|
+
}
|
|
1849
|
+
return "ready";
|
|
1850
|
+
} catch {
|
|
1851
|
+
return "invalid";
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
function lstatIfPresent(path) {
|
|
1855
|
+
try {
|
|
1856
|
+
return lstatSync2(path);
|
|
1857
|
+
} catch (error) {
|
|
1858
|
+
const code = error.code;
|
|
1859
|
+
if (code === "ENOENT" || code === "ENOTDIR") return void 0;
|
|
1860
|
+
throw error;
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
function assertOwnedHookRuntime(paths) {
|
|
1864
|
+
const entrypoint = lstatIfPresent(paths.gitHookEntrypoint);
|
|
1865
|
+
if (entrypoint && (!entrypoint.isFile() || !gitHookEntrypointCurrent(paths))) {
|
|
1866
|
+
throw new Error(
|
|
1867
|
+
`refusing to remove unrecognized Git hook entrypoint at ${paths.gitHookEntrypoint}`
|
|
1868
|
+
);
|
|
1869
|
+
}
|
|
1870
|
+
const launcher = lstatIfPresent(paths.launcher);
|
|
1871
|
+
if (launcher) {
|
|
1872
|
+
if (!launcher.isFile() || readFileSync6(paths.launcher, "utf8") !== STABLE_HOOK_LAUNCHER_CONTENT) {
|
|
1873
|
+
throw new Error(`refusing to remove unrecognized hook launcher at ${paths.launcher}`);
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
const runtime = lstatIfPresent(paths.runtimeDir);
|
|
1877
|
+
if (!runtime) return;
|
|
1878
|
+
if (!runtime.isDirectory()) {
|
|
1879
|
+
throw new Error(`refusing to remove non-directory hook runtime at ${paths.runtimeDir}`);
|
|
1880
|
+
}
|
|
1881
|
+
const allowed = /* @__PURE__ */ new Set(["current", "releases", "selection.lock"]);
|
|
1882
|
+
const unexpected = readdirSync(paths.runtimeDir).filter((entry) => !allowed.has(entry));
|
|
1883
|
+
if (unexpected.length > 0) {
|
|
1884
|
+
throw new Error(
|
|
1885
|
+
`refusing to remove hook runtime with unrecognized entries: ${unexpected.sort().join(", ")}`
|
|
1886
|
+
);
|
|
1887
|
+
}
|
|
1888
|
+
const current = lstatIfPresent(paths.current);
|
|
1889
|
+
const releases = lstatIfPresent(paths.releasesDir);
|
|
1890
|
+
if (current) {
|
|
1891
|
+
if (!current.isFile() || !releases || !readSelectedRelease(paths)) {
|
|
1892
|
+
throw new Error(`refusing to remove malformed hook runtime selection at ${paths.current}`);
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
if (!releases) return;
|
|
1896
|
+
if (!releases.isDirectory()) {
|
|
1897
|
+
throw new Error(`refusing to remove non-directory hook releases at ${paths.releasesDir}`);
|
|
1898
|
+
}
|
|
1899
|
+
for (const entry of readdirSync(paths.releasesDir, { withFileTypes: true })) {
|
|
1900
|
+
const releaseDir = join8(paths.releasesDir, entry.name);
|
|
1901
|
+
if (!entry.isDirectory() || !RELEASE_NAME_RE.test(entry.name) || !readReleaseManifest(releaseDir, entry.name)) {
|
|
1902
|
+
throw new Error(`refusing to remove unrecognized hook release ${releaseDir}`);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
function removeHookRuntime(options = {}) {
|
|
1907
|
+
const paths = hookRuntimePaths(options);
|
|
1908
|
+
const hadLauncher = lstatIfPresent(paths.launcher) !== void 0;
|
|
1909
|
+
const hadEntrypoint = lstatIfPresent(paths.gitHookEntrypoint) !== void 0;
|
|
1910
|
+
const hadRuntime = lstatIfPresent(paths.runtimeDir) !== void 0;
|
|
1911
|
+
if (!hadLauncher && !hadEntrypoint && !hadRuntime) return { changed: false, paths };
|
|
1912
|
+
assertOwnedHookRuntime(paths);
|
|
1913
|
+
if (!hadRuntime) {
|
|
1914
|
+
rmSync4(paths.gitHookEntrypoint, { force: true });
|
|
1915
|
+
rmSync4(paths.launcher, { force: true });
|
|
1916
|
+
return { changed: true, paths };
|
|
1917
|
+
}
|
|
1918
|
+
withFileLockSync(paths.selectionLock, () => {
|
|
1919
|
+
assertOwnedHookRuntime(paths);
|
|
1920
|
+
if (lstatIfPresent(paths.gitHookEntrypoint)) rmSync4(paths.gitHookEntrypoint, { force: true });
|
|
1921
|
+
if (lstatIfPresent(paths.launcher)) rmSync4(paths.launcher, { force: true });
|
|
1922
|
+
const quarantined = `${paths.runtimeDir}.uninstall-${String(process.pid)}-${randomBytes2(8).toString("hex")}`;
|
|
1923
|
+
renameSync2(paths.runtimeDir, quarantined);
|
|
1924
|
+
rmSync4(quarantined, { recursive: true, force: true });
|
|
1925
|
+
});
|
|
1926
|
+
return { changed: true, paths };
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1114
1929
|
// src/lib/workos-connect.ts
|
|
1115
1930
|
var DISCOVERY_PATH = "/api/cli/auth/connect/config";
|
|
1116
1931
|
var DEVICE_AUTHORIZATION_PATH = "/oauth2/device_authorization";
|
|
@@ -1339,10 +2154,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
1339
2154
|
"access_token",
|
|
1340
2155
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
1341
2156
|
);
|
|
1342
|
-
const
|
|
2157
|
+
const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
1343
2158
|
return {
|
|
1344
2159
|
accessToken,
|
|
1345
|
-
refreshToken,
|
|
2160
|
+
refreshToken: refreshToken2,
|
|
1346
2161
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
1347
2162
|
};
|
|
1348
2163
|
}
|
|
@@ -1351,7 +2166,7 @@ function providerError(value) {
|
|
|
1351
2166
|
return exactString(error, "error", MAX_USER_CODE_LENGTH);
|
|
1352
2167
|
}
|
|
1353
2168
|
async function defaultSleep2(milliseconds, signal) {
|
|
1354
|
-
await new Promise((
|
|
2169
|
+
await new Promise((resolve3, reject) => {
|
|
1355
2170
|
if (signal.aborted) {
|
|
1356
2171
|
reject(signal.reason);
|
|
1357
2172
|
return;
|
|
@@ -1362,7 +2177,7 @@ async function defaultSleep2(milliseconds, signal) {
|
|
|
1362
2177
|
};
|
|
1363
2178
|
const timer = setTimeout(() => {
|
|
1364
2179
|
signal.removeEventListener("abort", abort);
|
|
1365
|
-
|
|
2180
|
+
resolve3();
|
|
1366
2181
|
}, milliseconds);
|
|
1367
2182
|
signal.addEventListener("abort", abort, { once: true });
|
|
1368
2183
|
});
|
|
@@ -1657,30 +2472,82 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
|
|
|
1657
2472
|
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
1658
2473
|
}
|
|
1659
2474
|
|
|
2475
|
+
// src/lib/terminal-safe.ts
|
|
2476
|
+
function replaceIsolatedSurrogates(value) {
|
|
2477
|
+
let out = "";
|
|
2478
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
2479
|
+
const unit = value.charCodeAt(index);
|
|
2480
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
2481
|
+
const next = value.charCodeAt(index + 1);
|
|
2482
|
+
if (next >= 56320 && next <= 57343) {
|
|
2483
|
+
out += value[index] + value[index + 1];
|
|
2484
|
+
index += 1;
|
|
2485
|
+
} else {
|
|
2486
|
+
out += "\uFFFD";
|
|
2487
|
+
}
|
|
2488
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
2489
|
+
out += "\uFFFD";
|
|
2490
|
+
} else {
|
|
2491
|
+
out += value[index];
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
return out;
|
|
2495
|
+
}
|
|
2496
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
2497
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
2498
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
2499
|
+
point === 1564 || // Arabic letter mark
|
|
2500
|
+
point === 6158 || // Mongolian vowel separator
|
|
2501
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
2502
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
2503
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
2504
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
2505
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
2506
|
+
point >= 917504 && point <= 917631;
|
|
2507
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
2508
|
+
}
|
|
2509
|
+
function terminalSafeText(value) {
|
|
2510
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
2511
|
+
}
|
|
2512
|
+
function terminalSafeLine(value) {
|
|
2513
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2514
|
+
}
|
|
2515
|
+
function isTerminalSafeText(value) {
|
|
2516
|
+
return terminalSafeText(value) === value;
|
|
2517
|
+
}
|
|
2518
|
+
var stripControlChars = terminalSafeText;
|
|
2519
|
+
|
|
2520
|
+
// src/lib/session-identity.ts
|
|
2521
|
+
import { execFile } from "child_process";
|
|
2522
|
+
import { createHash as createHash6 } from "crypto";
|
|
2523
|
+
import { rmSync as rmSync8 } from "fs";
|
|
2524
|
+
import { join as join12 } from "path";
|
|
2525
|
+
import { promisify } from "util";
|
|
2526
|
+
|
|
1660
2527
|
// src/lib/machine-credentials.ts
|
|
1661
2528
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
1662
|
-
import { createHash as
|
|
2529
|
+
import { createHash as createHash5, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
|
|
1663
2530
|
import {
|
|
1664
|
-
chmodSync,
|
|
1665
|
-
existsSync as
|
|
2531
|
+
chmodSync as chmodSync2,
|
|
2532
|
+
existsSync as existsSync7,
|
|
1666
2533
|
linkSync,
|
|
1667
|
-
lstatSync as
|
|
1668
|
-
mkdirSync as
|
|
1669
|
-
readFileSync as
|
|
1670
|
-
rmSync as
|
|
1671
|
-
writeFileSync as
|
|
2534
|
+
lstatSync as lstatSync5,
|
|
2535
|
+
mkdirSync as mkdirSync5,
|
|
2536
|
+
readFileSync as readFileSync9,
|
|
2537
|
+
rmSync as rmSync7,
|
|
2538
|
+
writeFileSync as writeFileSync5
|
|
1672
2539
|
} from "fs";
|
|
1673
|
-
import { createRequire } from "module";
|
|
1674
|
-
import { dirname as
|
|
1675
|
-
import { fileURLToPath as
|
|
2540
|
+
import { createRequire as createRequire2 } from "module";
|
|
2541
|
+
import { dirname as dirname7, join as join11 } from "path";
|
|
2542
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
1676
2543
|
|
|
1677
2544
|
// src/lib/machine-broker.ts
|
|
1678
2545
|
import { spawn } from "child_process";
|
|
1679
|
-
import { createHash as
|
|
1680
|
-
import { lstatSync as
|
|
2546
|
+
import { createHash as createHash3, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
2547
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync7, rmSync as rmSync5 } from "fs";
|
|
1681
2548
|
import { createServer } from "http";
|
|
1682
|
-
import { basename as basename2, join as
|
|
1683
|
-
import { fileURLToPath as
|
|
2549
|
+
import { basename as basename2, join as join9 } from "path";
|
|
2550
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
1684
2551
|
|
|
1685
2552
|
// src/lib/loopback-fetch.ts
|
|
1686
2553
|
import { request } from "http";
|
|
@@ -1689,7 +2556,7 @@ function loopbackFetch(url, init = {}) {
|
|
|
1689
2556
|
const target = new URL(url);
|
|
1690
2557
|
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
1691
2558
|
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
1692
|
-
return new Promise((
|
|
2559
|
+
return new Promise((resolve3, reject) => {
|
|
1693
2560
|
const outgoing = request(
|
|
1694
2561
|
target,
|
|
1695
2562
|
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
@@ -1700,7 +2567,7 @@ function loopbackFetch(url, init = {}) {
|
|
|
1700
2567
|
if (typeof value === "string") headers.set(name, value);
|
|
1701
2568
|
const status = incoming.statusCode ?? 502;
|
|
1702
2569
|
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
1703
|
-
|
|
2570
|
+
resolve3(new Response(body, { status, headers }));
|
|
1704
2571
|
} catch (error) {
|
|
1705
2572
|
incoming.destroy();
|
|
1706
2573
|
reject(error);
|
|
@@ -1721,14 +2588,14 @@ var FORWARD_REQUEST_PROOF = "forward-request";
|
|
|
1721
2588
|
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
1722
2589
|
var IDLE_MS = 5 * 6e4;
|
|
1723
2590
|
function descriptorPath(directory, generation) {
|
|
1724
|
-
return
|
|
2591
|
+
return join9(directory, `machine_broker_${generation}.json`);
|
|
1725
2592
|
}
|
|
1726
2593
|
function readDescriptor(path) {
|
|
1727
2594
|
try {
|
|
1728
|
-
const stat =
|
|
2595
|
+
const stat = lstatSync3(path);
|
|
1729
2596
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
1730
2597
|
return void 0;
|
|
1731
|
-
const data = JSON.parse(
|
|
2598
|
+
const data = JSON.parse(readFileSync7(path, "utf8"));
|
|
1732
2599
|
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;
|
|
1733
2600
|
} catch {
|
|
1734
2601
|
return void 0;
|
|
@@ -1741,7 +2608,7 @@ function matches(left, right) {
|
|
|
1741
2608
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
1742
2609
|
}
|
|
1743
2610
|
function tokenHash(token) {
|
|
1744
|
-
return token ?
|
|
2611
|
+
return token ? createHash3("sha256").update(token).digest("hex") : void 0;
|
|
1745
2612
|
}
|
|
1746
2613
|
async function brokerRequest(descriptor, environment, options) {
|
|
1747
2614
|
const body = JSON.stringify({
|
|
@@ -1818,7 +2685,7 @@ async function acquireBrokerCredential(options) {
|
|
|
1818
2685
|
async function ensureBroker(options) {
|
|
1819
2686
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1820
2687
|
return withFileLock(
|
|
1821
|
-
|
|
2688
|
+
join9(options.directory, "machine-broker.lock"),
|
|
1822
2689
|
async () => {
|
|
1823
2690
|
const current = readDescriptor(path);
|
|
1824
2691
|
if (current) {
|
|
@@ -1831,14 +2698,14 @@ async function ensureBroker(options) {
|
|
|
1831
2698
|
options.signal.throwIfAborted();
|
|
1832
2699
|
}
|
|
1833
2700
|
}
|
|
1834
|
-
const bundled =
|
|
2701
|
+
const bundled = fileURLToPath3(import.meta.url);
|
|
1835
2702
|
const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
1836
2703
|
if (!entry)
|
|
1837
2704
|
throw new MachineAuthError(
|
|
1838
2705
|
"broker_unavailable",
|
|
1839
2706
|
"Reinstall Prim to restore its machine credential broker."
|
|
1840
2707
|
);
|
|
1841
|
-
await new Promise((
|
|
2708
|
+
await new Promise((resolve3, reject) => {
|
|
1842
2709
|
const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
|
|
1843
2710
|
detached: true,
|
|
1844
2711
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
@@ -1853,7 +2720,7 @@ async function ensureBroker(options) {
|
|
|
1853
2720
|
if (error) child.kill();
|
|
1854
2721
|
if (child.connected) child.disconnect();
|
|
1855
2722
|
child.unref();
|
|
1856
|
-
error ? reject(error) :
|
|
2723
|
+
error ? reject(error) : resolve3();
|
|
1857
2724
|
};
|
|
1858
2725
|
const abort = () => finish(
|
|
1859
2726
|
new MachineAuthError(
|
|
@@ -1969,26 +2836,26 @@ async function forwardBrokerRequest(options) {
|
|
|
1969
2836
|
}
|
|
1970
2837
|
|
|
1971
2838
|
// src/lib/machine-retry.ts
|
|
1972
|
-
import { createHash as
|
|
1973
|
-
import { lstatSync as
|
|
1974
|
-
import { join as
|
|
2839
|
+
import { createHash as createHash4 } from "crypto";
|
|
2840
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync8, readdirSync as readdirSync2, rmSync as rmSync6 } from "fs";
|
|
2841
|
+
import { join as join10 } from "path";
|
|
1975
2842
|
function clearMachineCooldowns(directory) {
|
|
1976
2843
|
let names;
|
|
1977
2844
|
try {
|
|
1978
|
-
names =
|
|
2845
|
+
names = readdirSync2(directory);
|
|
1979
2846
|
} catch {
|
|
1980
2847
|
return;
|
|
1981
2848
|
}
|
|
1982
2849
|
for (const name of names) {
|
|
1983
2850
|
if (!/^machine_retry_[0-9a-f]{64}\.json$/u.test(name)) continue;
|
|
1984
|
-
const path =
|
|
2851
|
+
const path = join10(directory, name);
|
|
1985
2852
|
try {
|
|
1986
|
-
const state = JSON.parse(
|
|
2853
|
+
const state = JSON.parse(readFileSync8(path, "utf8"));
|
|
1987
2854
|
if (state.serverRetryAfter === true) continue;
|
|
1988
2855
|
} catch {
|
|
1989
2856
|
}
|
|
1990
2857
|
try {
|
|
1991
|
-
|
|
2858
|
+
rmSync6(path, { force: true });
|
|
1992
2859
|
} catch {
|
|
1993
2860
|
}
|
|
1994
2861
|
}
|
|
@@ -1997,16 +2864,16 @@ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
|
1997
2864
|
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
1998
2865
|
async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
|
|
1999
2866
|
signal?.throwIfAborted();
|
|
2000
|
-
const key =
|
|
2001
|
-
const path =
|
|
2867
|
+
const key = createHash4("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
2868
|
+
const path = join10(directory, `machine_retry_${key}.json`);
|
|
2002
2869
|
let state = {
|
|
2003
2870
|
failures: 0,
|
|
2004
2871
|
retryAt: 0
|
|
2005
2872
|
};
|
|
2006
2873
|
try {
|
|
2007
|
-
const stat =
|
|
2874
|
+
const stat = lstatSync4(path);
|
|
2008
2875
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
2009
|
-
const data = JSON.parse(
|
|
2876
|
+
const data = JSON.parse(readFileSync8(path, "utf8"));
|
|
2010
2877
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
2011
2878
|
throw new Error("Invalid retry state");
|
|
2012
2879
|
state = data;
|
|
@@ -2030,7 +2897,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
2030
2897
|
);
|
|
2031
2898
|
try {
|
|
2032
2899
|
const result = await request2();
|
|
2033
|
-
|
|
2900
|
+
rmSync6(path, { force: true });
|
|
2034
2901
|
return result;
|
|
2035
2902
|
} catch (error) {
|
|
2036
2903
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -2058,7 +2925,10 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
2058
2925
|
}
|
|
2059
2926
|
|
|
2060
2927
|
// src/lib/machine-credentials.ts
|
|
2061
|
-
|
|
2928
|
+
function sessionScoped(deps) {
|
|
2929
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
2930
|
+
}
|
|
2931
|
+
var require3 = createRequire2(import.meta.url);
|
|
2062
2932
|
var SERVICE = "ai.primitive.prim.machine";
|
|
2063
2933
|
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
2064
2934
|
var PROFILE_FILE = "machine_profile.json";
|
|
@@ -2071,16 +2941,16 @@ function apiUrlFor(deps) {
|
|
|
2071
2941
|
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
2072
2942
|
}
|
|
2073
2943
|
function hash(value) {
|
|
2074
|
-
return
|
|
2944
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
2075
2945
|
}
|
|
2076
2946
|
function recordPath(directory, generation) {
|
|
2077
|
-
return
|
|
2947
|
+
return join11(directory, `machine_${generation}.json`);
|
|
2078
2948
|
}
|
|
2079
2949
|
function storageKey(directory, generation) {
|
|
2080
2950
|
return `${hash(directory)}:${generation}`;
|
|
2081
2951
|
}
|
|
2082
2952
|
function environmentContextPath(deps, clientId) {
|
|
2083
|
-
return
|
|
2953
|
+
return join11(
|
|
2084
2954
|
configurationDirectory(deps),
|
|
2085
2955
|
`machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
2086
2956
|
);
|
|
@@ -2140,22 +3010,28 @@ function readEnvironmentContext(environment, deps) {
|
|
|
2140
3010
|
return void 0;
|
|
2141
3011
|
}
|
|
2142
3012
|
}
|
|
2143
|
-
function
|
|
2144
|
-
let directory =
|
|
3013
|
+
function keyringLoaderPath(start, options = {}) {
|
|
3014
|
+
let directory = start;
|
|
2145
3015
|
for (let depth = 0; depth < 5; depth++) {
|
|
2146
|
-
const loader =
|
|
2147
|
-
if (
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
3016
|
+
const loader = join11(directory, "native", "keyring.cjs");
|
|
3017
|
+
if (existsSync7(loader)) return loader;
|
|
3018
|
+
directory = dirname7(directory);
|
|
3019
|
+
}
|
|
3020
|
+
try {
|
|
3021
|
+
createRequire2(join11(start, "noop.js")).resolve("@napi-rs/keyring");
|
|
3022
|
+
return void 0;
|
|
3023
|
+
} catch {
|
|
3024
|
+
return selectedHookRuntimeKeyringLoader(options);
|
|
2152
3025
|
}
|
|
2153
|
-
|
|
3026
|
+
}
|
|
3027
|
+
function keyringEntry(key) {
|
|
3028
|
+
const loader = keyringLoaderPath(dirname7(fileURLToPath4(import.meta.url)));
|
|
3029
|
+
const module = require3(loader ?? "@napi-rs/keyring");
|
|
2154
3030
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
2155
3031
|
}
|
|
2156
3032
|
function protectPath(path, directory) {
|
|
2157
3033
|
if (process.platform !== "win32") {
|
|
2158
|
-
|
|
3034
|
+
chmodSync2(path, directory ? 448 : 384);
|
|
2159
3035
|
return;
|
|
2160
3036
|
}
|
|
2161
3037
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
@@ -2172,8 +3048,8 @@ function protectPath(path, directory) {
|
|
|
2172
3048
|
);
|
|
2173
3049
|
}
|
|
2174
3050
|
function ensureDirectory(directory) {
|
|
2175
|
-
|
|
2176
|
-
if (
|
|
3051
|
+
mkdirSync5(directory, { recursive: true, mode: 448 });
|
|
3052
|
+
if (lstatSync5(directory).isSymbolicLink())
|
|
2177
3053
|
throw new MachineAuthError(
|
|
2178
3054
|
"unsafe_storage",
|
|
2179
3055
|
"Credential directory must not be a symbolic link."
|
|
@@ -2185,17 +3061,20 @@ function writePrivate(path, value) {
|
|
|
2185
3061
|
`, { mode: 384 });
|
|
2186
3062
|
protectPath(path, false);
|
|
2187
3063
|
}
|
|
3064
|
+
function readMachineMetadata(path) {
|
|
3065
|
+
return readPrivate(path);
|
|
3066
|
+
}
|
|
2188
3067
|
function readPrivate(path) {
|
|
2189
3068
|
let raw;
|
|
2190
3069
|
try {
|
|
2191
|
-
const stat =
|
|
3070
|
+
const stat = lstatSync5(path);
|
|
2192
3071
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
2193
3072
|
throw new MachineAuthError(
|
|
2194
3073
|
"unsafe_storage",
|
|
2195
3074
|
"Machine credential files must be owner-only regular files."
|
|
2196
3075
|
);
|
|
2197
3076
|
}
|
|
2198
|
-
raw =
|
|
3077
|
+
raw = readFileSync9(path, "utf8");
|
|
2199
3078
|
} catch (error) {
|
|
2200
3079
|
if (error.code === "ENOENT") return void 0;
|
|
2201
3080
|
throw error;
|
|
@@ -2240,7 +3119,7 @@ function parseProfile(value) {
|
|
|
2240
3119
|
};
|
|
2241
3120
|
}
|
|
2242
3121
|
function readMachineProfile(deps = {}) {
|
|
2243
|
-
const value = readPrivate(
|
|
3122
|
+
const value = readPrivate(join11(configurationDirectory(deps), PROFILE_FILE));
|
|
2244
3123
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
2245
3124
|
}
|
|
2246
3125
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -2249,20 +3128,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
2249
3128
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
2250
3129
|
function networkSecretBrokerKey(deps, clientId) {
|
|
2251
3130
|
const directory = configurationDirectory(deps);
|
|
2252
|
-
const path =
|
|
3131
|
+
const path = join11(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
2253
3132
|
const known = brokerKeys.get(path);
|
|
2254
3133
|
if (known) return known;
|
|
2255
3134
|
ensureDirectory(directory);
|
|
2256
3135
|
const read = () => {
|
|
2257
3136
|
try {
|
|
2258
|
-
const stat =
|
|
3137
|
+
const stat = lstatSync5(path);
|
|
2259
3138
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
2260
3139
|
throw new MachineAuthError(
|
|
2261
3140
|
"unsafe_storage",
|
|
2262
3141
|
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
2263
3142
|
true
|
|
2264
3143
|
);
|
|
2265
|
-
const value =
|
|
3144
|
+
const value = readFileSync9(path, "utf8").trim();
|
|
2266
3145
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
2267
3146
|
} catch (error) {
|
|
2268
3147
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -2281,16 +3160,16 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
2281
3160
|
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
2282
3161
|
true
|
|
2283
3162
|
);
|
|
2284
|
-
const staged = `${path}.${process.pid}.${
|
|
3163
|
+
const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
|
|
2285
3164
|
try {
|
|
2286
|
-
|
|
3165
|
+
writeFileSync5(staged, `${randomBytes4(32).toString("hex")}
|
|
2287
3166
|
`, { mode: 384, flag: "wx" });
|
|
2288
3167
|
protectPath(staged, false);
|
|
2289
3168
|
linkSync(staged, path);
|
|
2290
3169
|
} catch (error) {
|
|
2291
3170
|
if (error.code !== "EEXIST") throw error;
|
|
2292
3171
|
} finally {
|
|
2293
|
-
|
|
3172
|
+
rmSync7(staged, { force: true });
|
|
2294
3173
|
}
|
|
2295
3174
|
}
|
|
2296
3175
|
const key = read()?.key;
|
|
@@ -2349,7 +3228,7 @@ function environmentCredentials(deps) {
|
|
|
2349
3228
|
}
|
|
2350
3229
|
function hasMachineConfiguration(deps = {}) {
|
|
2351
3230
|
const env = deps.env ?? process.env;
|
|
2352
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 ||
|
|
3231
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync7(join11(configurationDirectory(deps), PROFILE_FILE));
|
|
2353
3232
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
2354
3233
|
throw new MachineAuthError(
|
|
2355
3234
|
"conflicting_credentials",
|
|
@@ -2361,6 +3240,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
2361
3240
|
}
|
|
2362
3241
|
function machineContext(deps = {}) {
|
|
2363
3242
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3243
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
2364
3244
|
const environment = environmentCredentials(deps);
|
|
2365
3245
|
if (environment) {
|
|
2366
3246
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -2375,6 +3255,7 @@ function machineContext(deps = {}) {
|
|
|
2375
3255
|
return profile;
|
|
2376
3256
|
}
|
|
2377
3257
|
function cachedMachineCredential(deps = {}) {
|
|
3258
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
2378
3259
|
const context = machineContext(deps);
|
|
2379
3260
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
2380
3261
|
}
|
|
@@ -2383,7 +3264,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
2383
3264
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
2384
3265
|
if (!generation) return false;
|
|
2385
3266
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
2386
|
-
return readPrivate(
|
|
3267
|
+
return readPrivate(join11(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
2387
3268
|
}
|
|
2388
3269
|
var environmentTerminal;
|
|
2389
3270
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -2456,7 +3337,7 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
|
|
|
2456
3337
|
const directory = configurationDirectory(deps);
|
|
2457
3338
|
ensureDirectory(directory);
|
|
2458
3339
|
return withFileLock(
|
|
2459
|
-
|
|
3340
|
+
join11(directory, "credentials.lock"),
|
|
2460
3341
|
async () => {
|
|
2461
3342
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
2462
3343
|
directory,
|
|
@@ -2512,11 +3393,11 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
|
|
|
2512
3393
|
profile = { ...profile, storage: "file" };
|
|
2513
3394
|
await persistRecord({ ...profile, ...tokens, clientSecret }, deps, signal);
|
|
2514
3395
|
}
|
|
2515
|
-
writePrivate(
|
|
2516
|
-
|
|
3396
|
+
writePrivate(join11(directory, PROFILE_FILE), profile);
|
|
3397
|
+
rmSync7(join11(directory, "machine_terminal.json"), { force: true });
|
|
2517
3398
|
cached = { ...profile, ...tokens };
|
|
2518
3399
|
if (previous) {
|
|
2519
|
-
writePrivate(
|
|
3400
|
+
writePrivate(join11(directory, "machine_retired.json"), [...retired, previous]);
|
|
2520
3401
|
}
|
|
2521
3402
|
await cleanupRetired(deps, signal);
|
|
2522
3403
|
return profile;
|
|
@@ -2526,6 +3407,7 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
|
|
|
2526
3407
|
}
|
|
2527
3408
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
2528
3409
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3410
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
2529
3411
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2530
3412
|
const apiUrl = apiUrlFor(deps);
|
|
2531
3413
|
const environment = environmentCredentials(deps);
|
|
@@ -2554,7 +3436,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2554
3436
|
}
|
|
2555
3437
|
}
|
|
2556
3438
|
return withFileLock(
|
|
2557
|
-
|
|
3439
|
+
join11(directory2, "credentials.lock"),
|
|
2558
3440
|
async () => {
|
|
2559
3441
|
if (machineSessionEnded(deps))
|
|
2560
3442
|
throw new MachineAuthError(
|
|
@@ -2636,7 +3518,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2636
3518
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2637
3519
|
try {
|
|
2638
3520
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2639
|
-
|
|
3521
|
+
rmSync7(contextPath, { force: true });
|
|
2640
3522
|
} catch {
|
|
2641
3523
|
}
|
|
2642
3524
|
throw error;
|
|
@@ -2646,7 +3528,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2646
3528
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2647
3529
|
try {
|
|
2648
3530
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2649
|
-
|
|
3531
|
+
rmSync7(contextPath, { force: true });
|
|
2650
3532
|
} catch {
|
|
2651
3533
|
}
|
|
2652
3534
|
}
|
|
@@ -2660,7 +3542,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2660
3542
|
const expected = machineContext(deps);
|
|
2661
3543
|
const directory = configurationDirectory(deps);
|
|
2662
3544
|
return withFileLock(
|
|
2663
|
-
|
|
3545
|
+
join11(directory, "credentials.lock"),
|
|
2664
3546
|
async () => {
|
|
2665
3547
|
const profile = readMachineProfile(deps);
|
|
2666
3548
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -2710,7 +3592,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2710
3592
|
await persistRecord(record, deps, signal);
|
|
2711
3593
|
} catch (error) {
|
|
2712
3594
|
if (error instanceof MachineAuthError && error.terminal)
|
|
2713
|
-
writePrivate(
|
|
3595
|
+
writePrivate(join11(directory, "machine_terminal.json"), profile.generation);
|
|
2714
3596
|
throw error;
|
|
2715
3597
|
}
|
|
2716
3598
|
}
|
|
@@ -2752,12 +3634,12 @@ async function verifyAcquiredMachineIdentity(machine, deps = {}) {
|
|
|
2752
3634
|
}
|
|
2753
3635
|
async function clearMachineCredentials(deps = {}) {
|
|
2754
3636
|
const directory = configurationDirectory(deps);
|
|
2755
|
-
if (!
|
|
2756
|
-
return withFileLock(
|
|
3637
|
+
if (!existsSync7(join11(directory, PROFILE_FILE))) return false;
|
|
3638
|
+
return withFileLock(join11(directory, "credentials.lock"), async () => {
|
|
2757
3639
|
const profile = readMachineProfile(deps);
|
|
2758
3640
|
if (!profile) return false;
|
|
2759
3641
|
await cleanupRetired(deps, AbortSignal.timeout(1e4));
|
|
2760
|
-
if (
|
|
3642
|
+
if (existsSync7(join11(directory, "machine_retired.json")))
|
|
2761
3643
|
throw new MachineAuthError(
|
|
2762
3644
|
"storage_unavailable",
|
|
2763
3645
|
"Unlock the credential store to remove retired machine credentials."
|
|
@@ -2773,9 +3655,9 @@ async function clearMachineCredentials(deps = {}) {
|
|
|
2773
3655
|
"Unlock the keychain to remove the saved machine credential."
|
|
2774
3656
|
);
|
|
2775
3657
|
}
|
|
2776
|
-
} else
|
|
2777
|
-
|
|
2778
|
-
|
|
3658
|
+
} else rmSync7(recordPath(directory, profile.generation), { force: true });
|
|
3659
|
+
rmSync7(join11(directory, PROFILE_FILE), { force: true });
|
|
3660
|
+
rmSync7(join11(directory, "machine_terminal.json"), { force: true });
|
|
2779
3661
|
cached = void 0;
|
|
2780
3662
|
return true;
|
|
2781
3663
|
});
|
|
@@ -2806,7 +3688,7 @@ function machinePendingBucket(identity) {
|
|
|
2806
3688
|
return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
2807
3689
|
}
|
|
2808
3690
|
function readRetiredProfiles(directory) {
|
|
2809
|
-
const value = readPrivate(
|
|
3691
|
+
const value = readPrivate(join11(directory, "machine_retired.json"));
|
|
2810
3692
|
if (value === void 0) return [];
|
|
2811
3693
|
if (!Array.isArray(value))
|
|
2812
3694
|
throw new MachineAuthError(
|
|
@@ -2817,20 +3699,20 @@ function readRetiredProfiles(directory) {
|
|
|
2817
3699
|
}
|
|
2818
3700
|
async function cleanupRetired(deps, signal) {
|
|
2819
3701
|
const directory = configurationDirectory(deps);
|
|
2820
|
-
const path =
|
|
3702
|
+
const path = join11(directory, "machine_retired.json");
|
|
2821
3703
|
const pending = [];
|
|
2822
3704
|
for (const profile of readRetiredProfiles(directory)) {
|
|
2823
3705
|
try {
|
|
2824
3706
|
if (profile.storage === "keychain") {
|
|
2825
3707
|
const entry = (deps.entry ?? keyringEntry)(storageKey(directory, profile.generation));
|
|
2826
3708
|
if (await entry.getPassword(signal) !== null) await entry.deletePassword(signal);
|
|
2827
|
-
} else
|
|
3709
|
+
} else rmSync7(recordPath(directory, profile.generation), { force: true });
|
|
2828
3710
|
} catch {
|
|
2829
3711
|
pending.push(profile);
|
|
2830
3712
|
}
|
|
2831
3713
|
}
|
|
2832
3714
|
if (pending.length) writePrivate(path, pending);
|
|
2833
|
-
else
|
|
3715
|
+
else rmSync7(path, { force: true });
|
|
2834
3716
|
}
|
|
2835
3717
|
function prepareMachineMetadataDirectory(directory) {
|
|
2836
3718
|
ensureDirectory(directory);
|
|
@@ -2839,25 +3721,1032 @@ function writeMachineMetadata(path, value) {
|
|
|
2839
3721
|
writePrivate(path, value);
|
|
2840
3722
|
}
|
|
2841
3723
|
|
|
2842
|
-
// src/lib/
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
var
|
|
2847
|
-
var
|
|
2848
|
-
var
|
|
2849
|
-
var
|
|
2850
|
-
var
|
|
2851
|
-
var
|
|
2852
|
-
var
|
|
2853
|
-
var
|
|
2854
|
-
|
|
2855
|
-
|
|
3724
|
+
// src/lib/session-identity.ts
|
|
3725
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
3726
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
3727
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
3728
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
3729
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
3730
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
3731
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
3732
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
3733
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
3734
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
3735
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
3736
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
3737
|
+
token: "/api/cli/session-identity/token",
|
|
3738
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
3739
|
+
link: "/api/cli/session-identity/link"
|
|
3740
|
+
};
|
|
3741
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
3742
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
3743
|
+
var GIT_TIMEOUT_MS4 = 1e4;
|
|
3744
|
+
var POLL_BUDGET_MS = 15e3;
|
|
3745
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
3746
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
3747
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
3748
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
3749
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
3750
|
+
function sessionIdentityRequested(env = process.env) {
|
|
3751
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
3752
|
+
}
|
|
3753
|
+
function sessionIdentityMode(deps = {}) {
|
|
3754
|
+
const env = deps.env ?? process.env;
|
|
3755
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
3756
|
+
}
|
|
3757
|
+
function failure(code, cause, remedy) {
|
|
3758
|
+
return { status: "failed", code, cause, remedy };
|
|
3759
|
+
}
|
|
3760
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
3761
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
3762
|
+
var ENVIRONMENT_CREDENTIAL_REMEDY = 'ask the organization admin who set up the environment to check its credential, or to mint a replacement with `prim auth enroll --new-environment "<name>" --print-env`; then start a new cloud session';
|
|
3763
|
+
var SESSION_REVOKED = failure(
|
|
3764
|
+
"session_revoked",
|
|
3765
|
+
"Primitive no longer accepts this session's member token: an organization admin revoked the session or the member's GitHub link, the member left the organization, or the token was renewed elsewhere",
|
|
3766
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
3767
|
+
);
|
|
3768
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
3769
|
+
"challenge_expired",
|
|
3770
|
+
"this session's identity check expired before it was exchanged for a token (a verified check stays usable, including for linking a GitHub account, for 30 minutes)",
|
|
3771
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
3772
|
+
);
|
|
3773
|
+
var CHALLENGE_GONE = failure(
|
|
3774
|
+
"challenge_not_found",
|
|
3775
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
3776
|
+
NEW_SESSION_REMEDY
|
|
3777
|
+
);
|
|
3778
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
3779
|
+
function rejectionFailure(reason, repository) {
|
|
3780
|
+
switch (reason) {
|
|
3781
|
+
case "identity_mismatch":
|
|
3782
|
+
return failure(
|
|
3783
|
+
"identity_mismatch",
|
|
3784
|
+
"the session branch was created by a GitHub account linked to a different Primitive member than the one signed in to Claude, so Primitive attributes this session to no one",
|
|
3785
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
3786
|
+
);
|
|
3787
|
+
case "push_after_expiry":
|
|
3788
|
+
return failure(
|
|
3789
|
+
"push_after_expiry",
|
|
3790
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
3791
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
3792
|
+
);
|
|
3793
|
+
case "repository_mismatch":
|
|
3794
|
+
return failure(
|
|
3795
|
+
"repository_mismatch",
|
|
3796
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
3797
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
3798
|
+
);
|
|
3799
|
+
case "conflicting_push":
|
|
3800
|
+
return failure(
|
|
3801
|
+
"conflicting_push",
|
|
3802
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
3803
|
+
NEW_SESSION_REMEDY
|
|
3804
|
+
);
|
|
3805
|
+
case "unsupported_sender":
|
|
3806
|
+
return failure(
|
|
3807
|
+
"unsupported_sender",
|
|
3808
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
3809
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
3810
|
+
);
|
|
3811
|
+
default:
|
|
3812
|
+
return failure(
|
|
3813
|
+
"challenge_rejected",
|
|
3814
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
3815
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
3816
|
+
);
|
|
3817
|
+
}
|
|
3818
|
+
}
|
|
3819
|
+
function sessionIdentityMessage(outcome) {
|
|
3820
|
+
if (outcome.status === "link_required")
|
|
3821
|
+
return `GitHub account @${outcome.githubLogin} started this Claude Code cloud session but is not linked to a Primitive account yet. To link it once, run \`prim auth link\` and sign in at the URL it prints with the code it shows; later sessions then identify you automatically.`;
|
|
3822
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
3823
|
+
}
|
|
3824
|
+
function hash2(value) {
|
|
3825
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
3826
|
+
}
|
|
3827
|
+
function sessionContext(deps) {
|
|
3828
|
+
const env = deps.env ?? process.env;
|
|
3829
|
+
const environment = environmentCredentials(deps);
|
|
3830
|
+
if (!environment)
|
|
3831
|
+
return failure(
|
|
3832
|
+
"environment_credential_missing",
|
|
3833
|
+
"the cloud environment has no environment credential",
|
|
3834
|
+
'ask an organization admin to create one with `prim auth enroll --new-environment "<name>" --print-env` and add it to the environment, then start a new cloud session'
|
|
3835
|
+
);
|
|
3836
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
3837
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
3838
|
+
return failure(
|
|
3839
|
+
"session_id_missing",
|
|
3840
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
3841
|
+
NEW_SESSION_REMEDY
|
|
3842
|
+
);
|
|
3843
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
3844
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
3845
|
+
const key = hash2(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
3846
|
+
return {
|
|
3847
|
+
directory,
|
|
3848
|
+
apiUrl,
|
|
3849
|
+
clientId: environment.clientId,
|
|
3850
|
+
generation: environment.generation,
|
|
3851
|
+
sessionId,
|
|
3852
|
+
tokenPath: join12(directory, `session_identity_${key}.json`),
|
|
3853
|
+
statePath: join12(directory, `session_identity_${key}.state.json`),
|
|
3854
|
+
lockPath: join12(directory, "session-identity.lock")
|
|
3855
|
+
};
|
|
3856
|
+
}
|
|
3857
|
+
function readRecord(path) {
|
|
3858
|
+
try {
|
|
3859
|
+
const value = readMachineMetadata(path);
|
|
3860
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
3861
|
+
} catch {
|
|
3862
|
+
return void 0;
|
|
3863
|
+
}
|
|
3864
|
+
}
|
|
3865
|
+
function finiteNumber(value) {
|
|
3866
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
3867
|
+
}
|
|
3868
|
+
function readToken(context) {
|
|
3869
|
+
const data = readRecord(context.tokenPath);
|
|
3870
|
+
if (!data || data.version !== 1 || data.apiUrl !== context.apiUrl || data.clientId !== context.clientId || data.generation !== context.generation || data.sessionId !== context.sessionId || !machineString(data.accessToken, 8192) || !data.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !finiteNumber(data.expiresAt) || !finiteNumber(data.refreshAfter) || !machineString(data.userId, 256) || !machineString(data.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.issuer, 2048) || !machineString(data.audience, 256))
|
|
3871
|
+
return void 0;
|
|
3872
|
+
const identity = data.identity;
|
|
3873
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
3874
|
+
return void 0;
|
|
3875
|
+
return data;
|
|
3876
|
+
}
|
|
3877
|
+
function readState(context) {
|
|
3878
|
+
const data = readRecord(context.statePath);
|
|
3879
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
3880
|
+
return void 0;
|
|
3881
|
+
return data;
|
|
3882
|
+
}
|
|
3883
|
+
function writeToken(context, record) {
|
|
3884
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
3885
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
3886
|
+
rmSync8(context.statePath, { force: true });
|
|
3887
|
+
}
|
|
3888
|
+
function writeState(context, state) {
|
|
3889
|
+
try {
|
|
3890
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
3891
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
3892
|
+
} catch {
|
|
3893
|
+
}
|
|
3894
|
+
}
|
|
3895
|
+
function tokenValid(record, now = Date.now()) {
|
|
3896
|
+
return now < record.expiresAt - RENEW_BEFORE_MS2;
|
|
3897
|
+
}
|
|
3898
|
+
function tokenFresh(record, now = Date.now()) {
|
|
3899
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
3900
|
+
}
|
|
3901
|
+
function toCredential(record) {
|
|
3902
|
+
return {
|
|
3903
|
+
issuer: record.issuer,
|
|
3904
|
+
audience: record.audience,
|
|
3905
|
+
...record.identity,
|
|
3906
|
+
accessToken: record.accessToken,
|
|
3907
|
+
expiresAt: record.expiresAt,
|
|
3908
|
+
apiUrl: record.apiUrl,
|
|
3909
|
+
generation: record.generation,
|
|
3910
|
+
storage: "environment",
|
|
3911
|
+
session: {
|
|
3912
|
+
userId: record.userId,
|
|
3913
|
+
displayName: record.displayName,
|
|
3914
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
3915
|
+
refreshAfter: record.refreshAfter
|
|
3916
|
+
}
|
|
3917
|
+
};
|
|
3918
|
+
}
|
|
3919
|
+
function identified(record, reused) {
|
|
3920
|
+
return {
|
|
3921
|
+
status: "ok",
|
|
3922
|
+
credential: toCredential(record),
|
|
3923
|
+
displayName: record.displayName,
|
|
3924
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
3925
|
+
reused
|
|
3926
|
+
};
|
|
3927
|
+
}
|
|
3928
|
+
function cachedSessionCredential(deps = {}) {
|
|
3929
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
3930
|
+
let context;
|
|
3931
|
+
try {
|
|
3932
|
+
context = sessionContext(deps);
|
|
3933
|
+
} catch {
|
|
3934
|
+
return void 0;
|
|
3935
|
+
}
|
|
3936
|
+
if ("status" in context) return void 0;
|
|
3937
|
+
const record = readToken(context);
|
|
3938
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
3939
|
+
}
|
|
3940
|
+
function outcomeFromState(state) {
|
|
3941
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
3942
|
+
return {
|
|
3943
|
+
status: "link_required",
|
|
3944
|
+
githubLogin: state.githubLogin,
|
|
3945
|
+
challengeId: state.challengeId,
|
|
3946
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
3947
|
+
};
|
|
3948
|
+
return failure(
|
|
3949
|
+
state.code,
|
|
3950
|
+
state.cause ?? "the last identity check failed",
|
|
3951
|
+
state.remedy ?? RETRY_REMEDY
|
|
3952
|
+
);
|
|
3953
|
+
}
|
|
3954
|
+
function parseInstant(value) {
|
|
3955
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
3956
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
3957
|
+
const parsed = Date.parse(value);
|
|
3958
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
3959
|
+
}
|
|
3960
|
+
return void 0;
|
|
3961
|
+
}
|
|
3962
|
+
async function sendJson(url, init, fetchImpl) {
|
|
3963
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
3964
|
+
let value;
|
|
3965
|
+
try {
|
|
3966
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
3967
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
3968
|
+
} catch {
|
|
3969
|
+
value = void 0;
|
|
3970
|
+
}
|
|
3971
|
+
return { status: response.status, value };
|
|
3972
|
+
}
|
|
3973
|
+
function environmentOnly(deps) {
|
|
3974
|
+
return { ...deps, environmentOnly: true };
|
|
3975
|
+
}
|
|
3976
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
3977
|
+
const send = async (credential2) => {
|
|
3978
|
+
const headers = { "Content-Type": "application/json" };
|
|
3979
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
3980
|
+
if (credential2.tokenInjection) {
|
|
3981
|
+
const response = await forwardMachineRequest(
|
|
3982
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
3983
|
+
signal,
|
|
3984
|
+
environmentOnly(deps)
|
|
3985
|
+
);
|
|
3986
|
+
const parsed = await response.json().catch(() => void 0);
|
|
3987
|
+
return {
|
|
3988
|
+
status: response.status,
|
|
3989
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
3990
|
+
};
|
|
3991
|
+
}
|
|
3992
|
+
return sendJson(
|
|
3993
|
+
`${credential2.apiUrl}${path}`,
|
|
3994
|
+
{
|
|
3995
|
+
method,
|
|
3996
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
3997
|
+
...text === void 0 ? {} : { body: text },
|
|
3998
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS4)
|
|
3999
|
+
},
|
|
4000
|
+
deps.fetch ?? fetch
|
|
4001
|
+
);
|
|
4002
|
+
};
|
|
4003
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
4004
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
4005
|
+
let answer = await send(credential);
|
|
4006
|
+
if (answer.status === 401) {
|
|
4007
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
4008
|
+
if (!credential)
|
|
4009
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
4010
|
+
answer = await send(credential);
|
|
4011
|
+
}
|
|
4012
|
+
return answer;
|
|
4013
|
+
}
|
|
4014
|
+
function environmentFailure(error, apiUrl) {
|
|
4015
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
4016
|
+
return failure(
|
|
4017
|
+
"environment_credential_rejected",
|
|
4018
|
+
"Primitive rejected the cloud environment's credential",
|
|
4019
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
4020
|
+
);
|
|
4021
|
+
const host = (() => {
|
|
4022
|
+
try {
|
|
4023
|
+
return new URL(apiUrl).hostname;
|
|
4024
|
+
} catch {
|
|
4025
|
+
return "Primitive";
|
|
4026
|
+
}
|
|
4027
|
+
})();
|
|
4028
|
+
return failure(
|
|
4029
|
+
"identity_unavailable",
|
|
4030
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
4031
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
4032
|
+
);
|
|
4033
|
+
}
|
|
4034
|
+
function answerError(answer) {
|
|
4035
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
4036
|
+
}
|
|
4037
|
+
async function git2(root, args, signal) {
|
|
4038
|
+
try {
|
|
4039
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
4040
|
+
cwd: root,
|
|
4041
|
+
encoding: "utf8",
|
|
4042
|
+
timeout: GIT_TIMEOUT_MS4,
|
|
4043
|
+
signal,
|
|
4044
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
4045
|
+
maxBuffer: 1024 * 1024
|
|
4046
|
+
});
|
|
4047
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
4048
|
+
} catch (error) {
|
|
4049
|
+
const failed = error;
|
|
4050
|
+
return {
|
|
4051
|
+
ok: false,
|
|
4052
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
4053
|
+
stdout: failed.stdout ?? "",
|
|
4054
|
+
stderr: failed.stderr ?? "",
|
|
4055
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
4056
|
+
};
|
|
4057
|
+
}
|
|
4058
|
+
}
|
|
4059
|
+
function gitDetail(stderr) {
|
|
4060
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
4061
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
4062
|
+
}
|
|
4063
|
+
async function defaultSleep3(milliseconds, signal) {
|
|
4064
|
+
await new Promise((resolve3, reject) => {
|
|
4065
|
+
const timer = setTimeout(resolve3, milliseconds);
|
|
4066
|
+
signal?.addEventListener(
|
|
4067
|
+
"abort",
|
|
4068
|
+
() => {
|
|
4069
|
+
clearTimeout(timer);
|
|
4070
|
+
reject(signal.reason);
|
|
4071
|
+
},
|
|
4072
|
+
{ once: true }
|
|
4073
|
+
);
|
|
4074
|
+
});
|
|
4075
|
+
}
|
|
4076
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
4077
|
+
const sleep = deps.sleep ?? defaultSleep3;
|
|
4078
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
4079
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
4080
|
+
let unreachable;
|
|
4081
|
+
for (; ; ) {
|
|
4082
|
+
const remaining = deadline - Date.now();
|
|
4083
|
+
if (remaining <= 0) break;
|
|
4084
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
4085
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
4086
|
+
let answer;
|
|
4087
|
+
try {
|
|
4088
|
+
answer = await environmentRequest(
|
|
4089
|
+
"GET",
|
|
4090
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
4091
|
+
void 0,
|
|
4092
|
+
deps,
|
|
4093
|
+
signal
|
|
4094
|
+
);
|
|
4095
|
+
} catch (error) {
|
|
4096
|
+
signal?.throwIfAborted();
|
|
4097
|
+
unreachable = error;
|
|
4098
|
+
continue;
|
|
4099
|
+
}
|
|
4100
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
4101
|
+
if (answer.status === 401 || answer.status === 403)
|
|
4102
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
4103
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
4104
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
4105
|
+
continue;
|
|
4106
|
+
}
|
|
4107
|
+
unreachable = void 0;
|
|
4108
|
+
const status = answer.value;
|
|
4109
|
+
if (status?.status === "verified")
|
|
4110
|
+
return {
|
|
4111
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
4112
|
+
};
|
|
4113
|
+
if (status?.status === "expired")
|
|
4114
|
+
return failure(
|
|
4115
|
+
"challenge_expired",
|
|
4116
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
4117
|
+
NEW_SESSION_REMEDY
|
|
4118
|
+
);
|
|
4119
|
+
if (status?.status === "rejected")
|
|
4120
|
+
return rejectionFailure(status.reason, repository);
|
|
4121
|
+
}
|
|
4122
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
4123
|
+
return failure(
|
|
4124
|
+
"webhook_timeout",
|
|
4125
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
4126
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
4127
|
+
);
|
|
4128
|
+
}
|
|
4129
|
+
function parseTokenAnswer(value) {
|
|
4130
|
+
if (!value) return void 0;
|
|
4131
|
+
const user = value.user;
|
|
4132
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
4133
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
4134
|
+
if (!machineString(value.accessToken, 8192) || !value.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !expiresAt || !refreshAfter || !user || !machineString(user.id, 256) || !machineString(user.displayName, 256) || !machineString(value.organizationId, 256))
|
|
4135
|
+
return void 0;
|
|
4136
|
+
return {
|
|
4137
|
+
accessToken: value.accessToken,
|
|
4138
|
+
expiresAt,
|
|
4139
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
4140
|
+
userId: user.id,
|
|
4141
|
+
displayName: user.displayName,
|
|
4142
|
+
organizationId: value.organizationId
|
|
4143
|
+
};
|
|
4144
|
+
}
|
|
4145
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
4146
|
+
"server_contract",
|
|
4147
|
+
"Primitive's answer did not identify the linked member",
|
|
4148
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
4149
|
+
);
|
|
4150
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
4151
|
+
let identity;
|
|
4152
|
+
let environment;
|
|
4153
|
+
try {
|
|
4154
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
4155
|
+
identity = await verifyMachineIdentity(
|
|
4156
|
+
context.apiUrl,
|
|
4157
|
+
answer.accessToken,
|
|
4158
|
+
context.clientId,
|
|
4159
|
+
signal,
|
|
4160
|
+
deps.fetch
|
|
4161
|
+
);
|
|
4162
|
+
} catch (error) {
|
|
4163
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
4164
|
+
return SERVER_CONTRACT_FAILURE;
|
|
4165
|
+
return environmentFailure(error, context.apiUrl);
|
|
4166
|
+
}
|
|
4167
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
4168
|
+
return SERVER_CONTRACT_FAILURE;
|
|
4169
|
+
return {
|
|
4170
|
+
version: 1,
|
|
4171
|
+
apiUrl: context.apiUrl,
|
|
4172
|
+
clientId: context.clientId,
|
|
4173
|
+
generation: context.generation,
|
|
4174
|
+
sessionId: context.sessionId,
|
|
4175
|
+
issuer: environment.issuer,
|
|
4176
|
+
audience: environment.audience,
|
|
4177
|
+
accessToken: answer.accessToken,
|
|
4178
|
+
expiresAt: answer.expiresAt,
|
|
4179
|
+
refreshAfter: answer.refreshAfter,
|
|
4180
|
+
userId: answer.userId,
|
|
4181
|
+
displayName: answer.displayName,
|
|
4182
|
+
organizationId: answer.organizationId,
|
|
4183
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
4184
|
+
identity,
|
|
4185
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
4186
|
+
};
|
|
4187
|
+
}
|
|
4188
|
+
async function refreshToken(context, record, deps, signal) {
|
|
4189
|
+
let answer;
|
|
4190
|
+
try {
|
|
4191
|
+
answer = await environmentRequest(
|
|
4192
|
+
"POST",
|
|
4193
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
4194
|
+
{ accessToken: record.accessToken },
|
|
4195
|
+
deps,
|
|
4196
|
+
signal
|
|
4197
|
+
);
|
|
4198
|
+
} catch (error) {
|
|
4199
|
+
signal?.throwIfAborted();
|
|
4200
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
4201
|
+
}
|
|
4202
|
+
const code = answerError(answer);
|
|
4203
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
4204
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
4205
|
+
if (answer.status === 401 || answer.status === 403)
|
|
4206
|
+
return {
|
|
4207
|
+
status: "refused",
|
|
4208
|
+
failure: environmentFailure(
|
|
4209
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
4210
|
+
context.apiUrl
|
|
4211
|
+
)
|
|
4212
|
+
};
|
|
4213
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
4214
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
4215
|
+
return { status: "unavailable" };
|
|
4216
|
+
return {
|
|
4217
|
+
status: "ok",
|
|
4218
|
+
record: {
|
|
4219
|
+
...record,
|
|
4220
|
+
accessToken: token.accessToken,
|
|
4221
|
+
expiresAt: token.expiresAt,
|
|
4222
|
+
refreshAfter: token.refreshAfter,
|
|
4223
|
+
displayName: token.displayName
|
|
4224
|
+
}
|
|
4225
|
+
};
|
|
4226
|
+
}
|
|
4227
|
+
function exchangeRefusal(answer, repository) {
|
|
4228
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
4229
|
+
if (answer.status !== 409) return void 0;
|
|
4230
|
+
switch (answerError(answer)) {
|
|
4231
|
+
case "identity_mismatch":
|
|
4232
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
4233
|
+
case "challenge_rejected":
|
|
4234
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
4235
|
+
case "challenge_expired":
|
|
4236
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
4237
|
+
case "challenge_already_exchanged":
|
|
4238
|
+
return failure(
|
|
4239
|
+
"challenge_already_exchanged",
|
|
4240
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
4241
|
+
NEW_SESSION_REMEDY
|
|
4242
|
+
);
|
|
4243
|
+
case "challenge_pending":
|
|
4244
|
+
return failure(
|
|
4245
|
+
"webhook_timeout",
|
|
4246
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
4247
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
4248
|
+
);
|
|
4249
|
+
default:
|
|
4250
|
+
return void 0;
|
|
4251
|
+
}
|
|
4252
|
+
}
|
|
4253
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
4254
|
+
let answer;
|
|
4255
|
+
try {
|
|
4256
|
+
answer = await environmentRequest(
|
|
4257
|
+
"POST",
|
|
4258
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
4259
|
+
{ challengeId: challenge.challengeId },
|
|
4260
|
+
deps,
|
|
4261
|
+
signal
|
|
4262
|
+
);
|
|
4263
|
+
} catch (error) {
|
|
4264
|
+
signal?.throwIfAborted();
|
|
4265
|
+
return environmentFailure(error, context.apiUrl);
|
|
4266
|
+
}
|
|
4267
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
4268
|
+
const login = answer.value?.githubLogin;
|
|
4269
|
+
return {
|
|
4270
|
+
status: "link_required",
|
|
4271
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
4272
|
+
challengeId: challenge.challengeId,
|
|
4273
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
4274
|
+
};
|
|
4275
|
+
}
|
|
4276
|
+
const refused = exchangeRefusal(
|
|
4277
|
+
answer,
|
|
4278
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
4279
|
+
);
|
|
4280
|
+
if (refused) return refused;
|
|
4281
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
4282
|
+
if (!token) {
|
|
4283
|
+
if (answer.status === 401 || answer.status === 403)
|
|
4284
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
4285
|
+
return answer.status >= 500 ? environmentFailure(
|
|
4286
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
4287
|
+
context.apiUrl
|
|
4288
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
4289
|
+
}
|
|
4290
|
+
return recordFor(
|
|
4291
|
+
context,
|
|
4292
|
+
token,
|
|
4293
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
4294
|
+
deps,
|
|
4295
|
+
signal
|
|
4296
|
+
);
|
|
4297
|
+
}
|
|
4298
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
4299
|
+
const env = deps.env ?? process.env;
|
|
4300
|
+
const repository = githubRepositoryFullName(root);
|
|
4301
|
+
if (!repository)
|
|
4302
|
+
return failure(
|
|
4303
|
+
"repository_unidentified",
|
|
4304
|
+
"this checkout does not name its GitHub repository",
|
|
4305
|
+
"run it in the repository the session cloned; for a checkout with no GitHub origin, commit its repository declaration with `prim claude install --scope project` from a clone whose origin is on GitHub"
|
|
4306
|
+
);
|
|
4307
|
+
const branch = currentBranch(root);
|
|
4308
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
4309
|
+
return failure(
|
|
4310
|
+
"not_session_branch",
|
|
4311
|
+
`this checkout is on ${branch ? `branch ${terminalSafeLine(branch).slice(0, 120)}` : "a detached HEAD"}, not the session's own claude/\u2026 branch, so prim cannot prove who started the session and pushed nothing`,
|
|
4312
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
4313
|
+
);
|
|
4314
|
+
attempt.branch = branch;
|
|
4315
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
4316
|
+
if (!baseSha) {
|
|
4317
|
+
const head = await git2(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
4318
|
+
baseSha = head.stdout.trim();
|
|
4319
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
4320
|
+
return failure(
|
|
4321
|
+
"no_commit",
|
|
4322
|
+
"this checkout has no commit to create the session branch at",
|
|
4323
|
+
NEW_SESSION_REMEDY
|
|
4324
|
+
);
|
|
4325
|
+
}
|
|
4326
|
+
const published = await git2(
|
|
4327
|
+
root,
|
|
4328
|
+
[
|
|
4329
|
+
"for-each-ref",
|
|
4330
|
+
"--count=1",
|
|
4331
|
+
"--format=%(refname)",
|
|
4332
|
+
"--contains",
|
|
4333
|
+
baseSha,
|
|
4334
|
+
"refs/remotes/origin/"
|
|
4335
|
+
],
|
|
4336
|
+
signal
|
|
4337
|
+
);
|
|
4338
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
4339
|
+
return failure(
|
|
4340
|
+
"unpublished_commits",
|
|
4341
|
+
`this checkout's commit ${baseSha.slice(0, 12)} is not on GitHub yet, and creating the session branch at it would publish it, so prim pushed nothing`,
|
|
4342
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
4343
|
+
);
|
|
4344
|
+
attempt.baseSha = baseSha;
|
|
4345
|
+
const remote = await git2(
|
|
4346
|
+
root,
|
|
4347
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
4348
|
+
signal
|
|
4349
|
+
);
|
|
4350
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
4351
|
+
if (remote.ok && recorded) {
|
|
4352
|
+
Object.assign(attempt, recorded);
|
|
4353
|
+
return { ...recorded, repository };
|
|
4354
|
+
}
|
|
4355
|
+
if (remote.ok)
|
|
4356
|
+
return failure(
|
|
4357
|
+
"branch_exists",
|
|
4358
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
4359
|
+
NEW_SESSION_REMEDY
|
|
4360
|
+
);
|
|
4361
|
+
if (remote.code !== 2)
|
|
4362
|
+
return failure(
|
|
4363
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
4364
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
4365
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
4366
|
+
);
|
|
4367
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
4368
|
+
Object.assign(attempt, recorded);
|
|
4369
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
4370
|
+
}
|
|
4371
|
+
let answer;
|
|
4372
|
+
try {
|
|
4373
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
4374
|
+
answer = await environmentRequest(
|
|
4375
|
+
"POST",
|
|
4376
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
4377
|
+
{
|
|
4378
|
+
repositoryFullName: repository,
|
|
4379
|
+
claudeSessionId: context.sessionId,
|
|
4380
|
+
branch,
|
|
4381
|
+
baseSha,
|
|
4382
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
4383
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
4384
|
+
},
|
|
4385
|
+
deps,
|
|
4386
|
+
signal
|
|
4387
|
+
);
|
|
4388
|
+
} catch (error) {
|
|
4389
|
+
signal?.throwIfAborted();
|
|
4390
|
+
return environmentFailure(error, context.apiUrl);
|
|
4391
|
+
}
|
|
4392
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
4393
|
+
return failure(
|
|
4394
|
+
"repository_not_connected",
|
|
4395
|
+
`${repository} is not connected to Primitive`,
|
|
4396
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
4397
|
+
);
|
|
4398
|
+
if (answer.status === 401 || answer.status === 403)
|
|
4399
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
4400
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
4401
|
+
return failure(
|
|
4402
|
+
"challenge_open",
|
|
4403
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
4404
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
4405
|
+
);
|
|
4406
|
+
if (answer.status === 429)
|
|
4407
|
+
return failure(
|
|
4408
|
+
"too_many_challenges",
|
|
4409
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
4410
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
4411
|
+
);
|
|
4412
|
+
const challengeId = answer.value?.challengeId;
|
|
4413
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
4414
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
4415
|
+
return answer.status >= 500 ? environmentFailure(
|
|
4416
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
4417
|
+
context.apiUrl
|
|
4418
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
4419
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
4420
|
+
attempt.challengeId = challengeId;
|
|
4421
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
4422
|
+
return pushSessionBranch(
|
|
4423
|
+
root,
|
|
4424
|
+
repository,
|
|
4425
|
+
branch,
|
|
4426
|
+
baseSha,
|
|
4427
|
+
{ challengeId, challengeExpiresAt },
|
|
4428
|
+
signal
|
|
4429
|
+
);
|
|
4430
|
+
}
|
|
4431
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
4432
|
+
const push = await git2(
|
|
4433
|
+
root,
|
|
4434
|
+
[
|
|
4435
|
+
"-c",
|
|
4436
|
+
"core.hooksPath=/dev/null",
|
|
4437
|
+
"-c",
|
|
4438
|
+
"push.followTags=false",
|
|
4439
|
+
"-c",
|
|
4440
|
+
"push.recurseSubmodules=no",
|
|
4441
|
+
"-c",
|
|
4442
|
+
"push.gpgSign=false",
|
|
4443
|
+
"-c",
|
|
4444
|
+
"push.pushOption=",
|
|
4445
|
+
"push",
|
|
4446
|
+
"--no-verify",
|
|
4447
|
+
"--no-follow-tags",
|
|
4448
|
+
"--no-recurse-submodules",
|
|
4449
|
+
"--no-signed",
|
|
4450
|
+
"--quiet",
|
|
4451
|
+
"origin",
|
|
4452
|
+
`${baseSha}:refs/heads/${branch}`
|
|
4453
|
+
],
|
|
4454
|
+
signal
|
|
4455
|
+
);
|
|
4456
|
+
if (!push.ok)
|
|
4457
|
+
return push.timedOut ? failure(
|
|
4458
|
+
"push_timeout",
|
|
4459
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS4 / 1e3} s`,
|
|
4460
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
4461
|
+
) : failure(
|
|
4462
|
+
"push_refused",
|
|
4463
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
4464
|
+
`check that the GitHub account that started this session can push to ${repository} and that the cloud environment lets the session push, then ${NEW_SESSION_REMEDY}`
|
|
4465
|
+
);
|
|
4466
|
+
return { ...challenge, repository };
|
|
4467
|
+
}
|
|
4468
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
4469
|
+
let context;
|
|
4470
|
+
try {
|
|
4471
|
+
context = sessionContext(deps);
|
|
4472
|
+
} catch (error) {
|
|
4473
|
+
return failure(
|
|
4474
|
+
"environment_credential_invalid",
|
|
4475
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
4476
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
4477
|
+
);
|
|
4478
|
+
}
|
|
4479
|
+
if ("status" in context) return context;
|
|
4480
|
+
const ctx = context;
|
|
4481
|
+
const startedAt = Date.now();
|
|
4482
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
4483
|
+
return withFileLock(
|
|
4484
|
+
ctx.lockPath,
|
|
4485
|
+
async () => {
|
|
4486
|
+
const record = readToken(ctx);
|
|
4487
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
4488
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
4489
|
+
if (record) {
|
|
4490
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
4491
|
+
if (refreshed.status === "ok") {
|
|
4492
|
+
writeToken(ctx, refreshed.record);
|
|
4493
|
+
return identified(refreshed.record, true);
|
|
4494
|
+
}
|
|
4495
|
+
if (refreshed.status === "refused") {
|
|
4496
|
+
rmSync8(ctx.tokenPath, { force: true });
|
|
4497
|
+
writeState(ctx, {
|
|
4498
|
+
sessionId: ctx.sessionId,
|
|
4499
|
+
status: "failed",
|
|
4500
|
+
code: refreshed.failure.code,
|
|
4501
|
+
cause: refreshed.failure.cause,
|
|
4502
|
+
remedy: refreshed.failure.remedy,
|
|
4503
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
4504
|
+
at: Date.now()
|
|
4505
|
+
});
|
|
4506
|
+
return refreshed.failure;
|
|
4507
|
+
}
|
|
4508
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
4509
|
+
}
|
|
4510
|
+
const state = readState(ctx);
|
|
4511
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
4512
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
4513
|
+
if (!options.explicit) {
|
|
4514
|
+
if (!root || !(record || state))
|
|
4515
|
+
return failure(
|
|
4516
|
+
"not_identified",
|
|
4517
|
+
"this session has not identified who started it yet",
|
|
4518
|
+
RETRY_REMEDY
|
|
4519
|
+
);
|
|
4520
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
4521
|
+
} else if (state && state.at >= startedAt) {
|
|
4522
|
+
return outcomeFromState(state);
|
|
4523
|
+
}
|
|
4524
|
+
if (!root)
|
|
4525
|
+
return failure(
|
|
4526
|
+
"repository_missing",
|
|
4527
|
+
"this is not a git repository",
|
|
4528
|
+
"run it in the repository the session cloned"
|
|
4529
|
+
);
|
|
4530
|
+
const attempt = { root };
|
|
4531
|
+
const remember = (outcome) => {
|
|
4532
|
+
writeState(ctx, {
|
|
4533
|
+
sessionId: ctx.sessionId,
|
|
4534
|
+
status: outcome.status,
|
|
4535
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
4536
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
4537
|
+
githubLogin: outcome.githubLogin
|
|
4538
|
+
},
|
|
4539
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
4540
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
4541
|
+
repositoryRoot: root,
|
|
4542
|
+
branch: attempt.branch ?? state?.branch,
|
|
4543
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
4544
|
+
at: Date.now()
|
|
4545
|
+
});
|
|
4546
|
+
return outcome;
|
|
4547
|
+
};
|
|
4548
|
+
let challenge;
|
|
4549
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
4550
|
+
attempt.challengeId = state.challengeId;
|
|
4551
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
4552
|
+
attempt.branch = state.branch;
|
|
4553
|
+
attempt.baseSha = state.baseSha;
|
|
4554
|
+
challenge = {
|
|
4555
|
+
challengeId: state.challengeId,
|
|
4556
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
4557
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
4558
|
+
};
|
|
4559
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
4560
|
+
attempt.challengeId = state.challengeId;
|
|
4561
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
4562
|
+
const exchanged2 = await exchangeChallenge(
|
|
4563
|
+
ctx,
|
|
4564
|
+
{
|
|
4565
|
+
challengeId: state.challengeId,
|
|
4566
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
4567
|
+
githubLogin: state.githubLogin
|
|
4568
|
+
},
|
|
4569
|
+
root,
|
|
4570
|
+
deps,
|
|
4571
|
+
options.signal
|
|
4572
|
+
);
|
|
4573
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
4574
|
+
writeToken(ctx, exchanged2);
|
|
4575
|
+
return identified(exchanged2, false);
|
|
4576
|
+
} else if (!options.explicit) {
|
|
4577
|
+
return state ? outcomeFromState(state) : failure(
|
|
4578
|
+
"not_identified",
|
|
4579
|
+
"this session has not identified who started it yet",
|
|
4580
|
+
RETRY_REMEDY
|
|
4581
|
+
);
|
|
4582
|
+
} else {
|
|
4583
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
4584
|
+
if ("status" in pushed) return remember(pushed);
|
|
4585
|
+
challenge = pushed;
|
|
4586
|
+
}
|
|
4587
|
+
const verified = await pollChallenge(
|
|
4588
|
+
ctx.apiUrl,
|
|
4589
|
+
challenge.challengeId,
|
|
4590
|
+
challenge.repository,
|
|
4591
|
+
// A hook process waits only briefly for a late notice.
|
|
4592
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
4593
|
+
options.signal
|
|
4594
|
+
);
|
|
4595
|
+
if ("status" in verified) return remember(verified);
|
|
4596
|
+
const exchanged = await exchangeChallenge(
|
|
4597
|
+
ctx,
|
|
4598
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
4599
|
+
root,
|
|
4600
|
+
deps,
|
|
4601
|
+
options.signal
|
|
4602
|
+
);
|
|
4603
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
4604
|
+
writeToken(ctx, exchanged);
|
|
4605
|
+
return identified(exchanged, false);
|
|
4606
|
+
},
|
|
4607
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
4608
|
+
);
|
|
4609
|
+
}
|
|
4610
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
4611
|
+
const cached2 = cachedSessionCredential(deps);
|
|
4612
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
4613
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
4614
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
4615
|
+
let outcome;
|
|
4616
|
+
try {
|
|
4617
|
+
outcome = await ensureSessionIdentity(
|
|
4618
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
4619
|
+
deps
|
|
4620
|
+
);
|
|
4621
|
+
} catch (error) {
|
|
4622
|
+
options.signal?.throwIfAborted();
|
|
4623
|
+
if (error instanceof MachineAuthError) throw error;
|
|
4624
|
+
throw new MachineAuthError(
|
|
4625
|
+
"identity_unavailable",
|
|
4626
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
4627
|
+
);
|
|
4628
|
+
}
|
|
4629
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
4630
|
+
throw new MachineAuthError(
|
|
4631
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
4632
|
+
sessionIdentityMessage(outcome)
|
|
4633
|
+
);
|
|
4634
|
+
}
|
|
4635
|
+
function linkRefusal(answer, githubLogin) {
|
|
4636
|
+
const login = (value) => machineString(value, 64) ? terminalSafeLine(value) : void 0;
|
|
4637
|
+
switch (answerError(answer)) {
|
|
4638
|
+
case "member_already_linked": {
|
|
4639
|
+
const current = login(answer.value?.linkedGithubLogin) ?? login(answer.value?.currentGithubLogin) ?? login(answer.value?.githubLogin);
|
|
4640
|
+
return failure(
|
|
4641
|
+
"member_already_linked",
|
|
4642
|
+
`your Primitive account is already linked to ${current ? `GitHub account @${current}` : "another GitHub account"}, and Primitive links one GitHub account per member`,
|
|
4643
|
+
`remove that link in Primitive's settings first, then run \`prim auth link\` again (in a new cloud session if this one has passed its 30 minutes)`
|
|
4644
|
+
);
|
|
4645
|
+
}
|
|
4646
|
+
case "github_account_linked_to_another_member":
|
|
4647
|
+
return failure(
|
|
4648
|
+
"github_account_linked_to_another_member",
|
|
4649
|
+
`GitHub account @${githubLogin} is already linked to another member of this organization`,
|
|
4650
|
+
`sign in as the member it is linked to; if that link is wrong, ask an organization admin to remove it in Primitive's settings, then ${NEW_SESSION_REMEDY}`
|
|
4651
|
+
);
|
|
4652
|
+
case "identity_mismatch":
|
|
4653
|
+
return failure(
|
|
4654
|
+
"identity_mismatch",
|
|
4655
|
+
"the person who signed in is a different Primitive member than the one signed in to Claude for this session, so Primitive refused the link and attributes this session to no one",
|
|
4656
|
+
`${NEW_SESSION_REMEDY}, and when \`prim auth link\` asks, sign in as yourself`
|
|
4657
|
+
);
|
|
4658
|
+
case "challenge_expired":
|
|
4659
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
4660
|
+
case "challenge_not_found":
|
|
4661
|
+
case "challenge_not_verified":
|
|
4662
|
+
return failure(
|
|
4663
|
+
"link_failed",
|
|
4664
|
+
"this session's identity check can no longer be linked",
|
|
4665
|
+
`${NEW_SESSION_REMEDY} and run \`prim auth link\` there as soon as it asks`
|
|
4666
|
+
);
|
|
4667
|
+
default:
|
|
4668
|
+
return void 0;
|
|
4669
|
+
}
|
|
4670
|
+
}
|
|
4671
|
+
async function linkSessionIdentity(challenge, humanAccessToken, options = {}, deps = {}) {
|
|
4672
|
+
const context = sessionContext(deps);
|
|
4673
|
+
if ("status" in context) return context;
|
|
4674
|
+
let answer;
|
|
4675
|
+
try {
|
|
4676
|
+
answer = await sendJson(
|
|
4677
|
+
`${context.apiUrl}${SESSION_IDENTITY_ROUTES.link}`,
|
|
4678
|
+
{
|
|
4679
|
+
method: "POST",
|
|
4680
|
+
headers: {
|
|
4681
|
+
Authorization: `Bearer ${humanAccessToken}`,
|
|
4682
|
+
"Content-Type": "application/json"
|
|
4683
|
+
},
|
|
4684
|
+
body: JSON.stringify({ challengeId: challenge.challengeId }),
|
|
4685
|
+
signal: options.signal ?? AbortSignal.timeout(3e4)
|
|
4686
|
+
},
|
|
4687
|
+
deps.fetch ?? fetch
|
|
4688
|
+
);
|
|
4689
|
+
} catch (error) {
|
|
4690
|
+
options.signal?.throwIfAborted();
|
|
4691
|
+
return environmentFailure(error, context.apiUrl);
|
|
4692
|
+
}
|
|
4693
|
+
if (answer.status !== 200 || answer.value?.linked !== true) {
|
|
4694
|
+
const code = answerError(answer);
|
|
4695
|
+
const refused = linkRefusal(answer, challenge.githubLogin);
|
|
4696
|
+
if (refused) return refused;
|
|
4697
|
+
return failure(
|
|
4698
|
+
"link_failed",
|
|
4699
|
+
`Primitive did not link GitHub account @${challenge.githubLogin}${code ? ` (${terminalSafeLine(code).slice(0, 120)})` : ` (HTTP ${answer.status})`}`,
|
|
4700
|
+
answer.status === 401 || answer.status === 403 ? "sign in as a member of the organization that owns this environment and run `prim auth link` again" : `${NEW_SESSION_REMEDY} and run \`prim auth link\` there as soon as it asks`
|
|
4701
|
+
);
|
|
4702
|
+
}
|
|
4703
|
+
const linkedLogin = machineString(answer.value.githubLogin, 64) ? answer.value.githubLogin : challenge.githubLogin;
|
|
4704
|
+
const root = options.cwd ? gitToplevel(options.cwd) ?? void 0 : void 0;
|
|
4705
|
+
return withFileLock(
|
|
4706
|
+
context.lockPath,
|
|
4707
|
+
async () => {
|
|
4708
|
+
const exchanged = await exchangeChallenge(
|
|
4709
|
+
context,
|
|
4710
|
+
{ ...challenge, githubLogin: linkedLogin },
|
|
4711
|
+
root ?? readState(context)?.repositoryRoot,
|
|
4712
|
+
deps,
|
|
4713
|
+
options.signal
|
|
4714
|
+
);
|
|
4715
|
+
if ("status" in exchanged) {
|
|
4716
|
+
if (exchanged.status === "link_required")
|
|
4717
|
+
return failure(
|
|
4718
|
+
"link_failed",
|
|
4719
|
+
`Primitive linked GitHub account @${linkedLogin} but still refused this session's token`,
|
|
4720
|
+
`${NEW_SESSION_REMEDY}; it should identify you automatically`
|
|
4721
|
+
);
|
|
4722
|
+
return exchanged;
|
|
4723
|
+
}
|
|
4724
|
+
writeToken(context, exchanged);
|
|
4725
|
+
return identified(exchanged, false);
|
|
4726
|
+
},
|
|
4727
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
4728
|
+
);
|
|
4729
|
+
}
|
|
4730
|
+
|
|
4731
|
+
// src/lib/credentials.ts
|
|
4732
|
+
import { createHash as createHash7 } from "crypto";
|
|
4733
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
4734
|
+
import { join as join13 } from "path";
|
|
4735
|
+
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
4736
|
+
var TOKEN_FILE_PATH = join13(CONFIG_DIRECTORY, "token");
|
|
4737
|
+
var REFRESH_TOKEN_PATH = join13(CONFIG_DIRECTORY, "refresh_token");
|
|
4738
|
+
var TOKEN_EXPIRES_PATH = join13(CONFIG_DIRECTORY, "token_expires_at");
|
|
4739
|
+
var TERMINAL_REFRESH_PATH = join13(CONFIG_DIRECTORY, "refresh_terminal");
|
|
4740
|
+
var CREDENTIAL_METADATA_PATH = join13(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
4741
|
+
var CREDENTIAL_FAMILY_PATH = join13(CONFIG_DIRECTORY, "credential_family.json");
|
|
4742
|
+
var CREDENTIAL_MIGRATION_PATH = join13(CONFIG_DIRECTORY, "credential_migration.json");
|
|
4743
|
+
var CREDENTIAL_LOCK_PATH = join13(CONFIG_DIRECTORY, "credentials.lock");
|
|
4744
|
+
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
2856
4745
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
2857
4746
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
2858
4747
|
function readTrimmed(path) {
|
|
2859
4748
|
try {
|
|
2860
|
-
const value =
|
|
4749
|
+
const value = readFileSync10(path, "utf8").trim();
|
|
2861
4750
|
return value || void 0;
|
|
2862
4751
|
} catch {
|
|
2863
4752
|
return void 0;
|
|
@@ -2879,16 +4768,16 @@ function resolveAuthCredential(options = {}) {
|
|
|
2879
4768
|
);
|
|
2880
4769
|
if (metadata.state === "legacy_broker") {
|
|
2881
4770
|
if (metadata.metadata) {
|
|
2882
|
-
const
|
|
2883
|
-
if (!
|
|
4771
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
4772
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
2884
4773
|
return void 0;
|
|
2885
4774
|
}
|
|
2886
4775
|
}
|
|
2887
4776
|
return { token: stored, source: "token_file" };
|
|
2888
4777
|
}
|
|
2889
4778
|
if (metadata.state === "invalid") return void 0;
|
|
2890
|
-
const
|
|
2891
|
-
if (!
|
|
4779
|
+
const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
4780
|
+
if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
|
|
2892
4781
|
return void 0;
|
|
2893
4782
|
}
|
|
2894
4783
|
return { token: stored, source: "token_file" };
|
|
@@ -2897,15 +4786,15 @@ function resolveStoredCredential(env = process.env) {
|
|
|
2897
4786
|
const directory = primConfigDirectory({ env });
|
|
2898
4787
|
return resolveAuthCredential({
|
|
2899
4788
|
env,
|
|
2900
|
-
tokenFilePath:
|
|
2901
|
-
refreshTokenPath:
|
|
2902
|
-
metadataPath:
|
|
2903
|
-
familyPath:
|
|
2904
|
-
migrationPath:
|
|
4789
|
+
tokenFilePath: join13(directory, "token"),
|
|
4790
|
+
refreshTokenPath: join13(directory, "refresh_token"),
|
|
4791
|
+
metadataPath: join13(directory, "credential_metadata.json"),
|
|
4792
|
+
familyPath: join13(directory, "credential_family.json"),
|
|
4793
|
+
migrationPath: join13(directory, "credential_migration.json")
|
|
2905
4794
|
});
|
|
2906
4795
|
}
|
|
2907
4796
|
function credentialFingerprint(value) {
|
|
2908
|
-
return
|
|
4797
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
2909
4798
|
}
|
|
2910
4799
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
2911
4800
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -2925,7 +4814,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
2925
4814
|
function readBoundedCredentialJson(path) {
|
|
2926
4815
|
let raw;
|
|
2927
4816
|
try {
|
|
2928
|
-
raw =
|
|
4817
|
+
raw = readFileSync10(path, "utf8");
|
|
2929
4818
|
} catch (error) {
|
|
2930
4819
|
return error.code === "ENOENT" ? void 0 : null;
|
|
2931
4820
|
}
|
|
@@ -3002,32 +4891,42 @@ function jwtOrganizationId(token) {
|
|
|
3002
4891
|
|
|
3003
4892
|
export {
|
|
3004
4893
|
syncDirectory,
|
|
3005
|
-
syncFile,
|
|
3006
4894
|
ensureDurableDirectory,
|
|
3007
4895
|
atomicWriteFile,
|
|
3008
4896
|
processIsAlive,
|
|
3009
4897
|
withFileLockSync,
|
|
3010
4898
|
withFileLock,
|
|
3011
4899
|
compareSemver,
|
|
3012
|
-
STABLE_HOOK_LAUNCHER_NAME,
|
|
3013
4900
|
binFile,
|
|
3014
4901
|
packageVersion,
|
|
3015
4902
|
packageRoot,
|
|
3016
|
-
shellQuote,
|
|
3017
4903
|
pinnedNpxArgs,
|
|
3018
4904
|
pinnedNpxCommand,
|
|
3019
4905
|
pinnedHookCommand,
|
|
3020
|
-
PRIM_CONFIG_SHELL_RESOLVER,
|
|
3021
4906
|
stableHookCommand,
|
|
3022
4907
|
quietWithoutLauncher,
|
|
3023
4908
|
detachedHookShimCommand,
|
|
3024
4909
|
commandMatchesBin,
|
|
3025
4910
|
hookCommandResolution,
|
|
3026
4911
|
hookCommandResolutions,
|
|
4912
|
+
MANAGED_GIT_HOOK_NAMES,
|
|
4913
|
+
GIT_HOOK_CONTRACT_VERSION,
|
|
4914
|
+
blockMarkers,
|
|
4915
|
+
managedHookBlock,
|
|
4916
|
+
canonicalHookBlock,
|
|
4917
|
+
hookBlockContractVersion,
|
|
4918
|
+
primConfigDirectory,
|
|
4919
|
+
hookRuntimePaths,
|
|
4920
|
+
inspectHookRuntime,
|
|
4921
|
+
stableNodePath,
|
|
4922
|
+
stageHookRuntime,
|
|
4923
|
+
inspectGitHookEntrypoint,
|
|
4924
|
+
assertOwnedHookRuntime,
|
|
4925
|
+
removeHookRuntime,
|
|
3027
4926
|
isClaudeCloudSession,
|
|
3028
4927
|
insideClaudeCode,
|
|
3029
4928
|
CLOUD_CREDENTIALS_REMEDY,
|
|
3030
|
-
|
|
4929
|
+
CLOUD_REJECTED_CREDENTIALS_NOTICE,
|
|
3031
4930
|
CLOUD_GITHUB_CONNECT_REMEDY,
|
|
3032
4931
|
cloudSetupPointer,
|
|
3033
4932
|
CLOUD_SETUP_POINTER,
|
|
@@ -3048,9 +4947,31 @@ export {
|
|
|
3048
4947
|
exchangeMachineCredentials,
|
|
3049
4948
|
parseMachineIdentity,
|
|
3050
4949
|
verifyMachineIdentity,
|
|
3051
|
-
primConfigDirectory,
|
|
3052
4950
|
clearMachineCooldowns,
|
|
3053
4951
|
SERVER_WAIT_PREFIX,
|
|
4952
|
+
gitToplevel,
|
|
4953
|
+
mainWorktreeRoot,
|
|
4954
|
+
currentBranch,
|
|
4955
|
+
parseGithubRepositoryName,
|
|
4956
|
+
originIdentifiesRepository,
|
|
4957
|
+
originGithubRepository,
|
|
4958
|
+
isGitIgnored,
|
|
4959
|
+
githubRepositoryFullName,
|
|
4960
|
+
canonicalGitRoot,
|
|
4961
|
+
relatedWorktreeTarget,
|
|
4962
|
+
resolveRepositoryContext,
|
|
4963
|
+
canonicalRepositoryPath,
|
|
4964
|
+
terminalSafeText,
|
|
4965
|
+
terminalSafeLine,
|
|
4966
|
+
isTerminalSafeText,
|
|
4967
|
+
stripControlChars,
|
|
4968
|
+
SESSION_IDENTITY_VARIABLE,
|
|
4969
|
+
SESSION_IDENTITY_VALUE,
|
|
4970
|
+
sessionIdentityMode,
|
|
4971
|
+
ENVIRONMENT_CREDENTIAL_REMEDY,
|
|
4972
|
+
sessionIdentityMessage,
|
|
4973
|
+
ensureSessionIdentity,
|
|
4974
|
+
linkSessionIdentity,
|
|
3054
4975
|
readMachineProfile,
|
|
3055
4976
|
NETWORK_TOKEN_AUTH,
|
|
3056
4977
|
environmentCredentials,
|
|
@@ -3096,18 +5017,6 @@ export {
|
|
|
3096
5017
|
endDemoPause,
|
|
3097
5018
|
clearDemoPause,
|
|
3098
5019
|
healDemoPause,
|
|
3099
|
-
gitToplevel,
|
|
3100
|
-
mainWorktreeRoot,
|
|
3101
|
-
currentBranch,
|
|
3102
|
-
parseGithubRepositoryName,
|
|
3103
|
-
originIdentifiesRepository,
|
|
3104
|
-
originGithubRepository,
|
|
3105
|
-
isGitIgnored,
|
|
3106
|
-
githubRepositoryFullName,
|
|
3107
|
-
canonicalGitRoot,
|
|
3108
|
-
relatedWorktreeTarget,
|
|
3109
|
-
resolveRepositoryContext,
|
|
3110
|
-
canonicalRepositoryPath,
|
|
3111
5020
|
PRIM_ACTIVE_DECLARATION,
|
|
3112
5021
|
repoActiveFlag,
|
|
3113
5022
|
setRepoActive,
|