@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.128
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-NVDPKW7Z.js → chunk-3KPTVK4N.js} +3 -51
- package/dist/{chunk-URYZDQFH.js → chunk-4DYEBYKM.js} +3 -5
- package/dist/{chunk-HZI5PBN4.js → chunk-6QAXVFRJ.js} +1129 -39
- package/dist/{chunk-A5VTE43F.js → chunk-ANMNGGTN.js} +2 -2
- package/dist/{chunk-TNWI3JWK.js → chunk-B3ICJZXV.js} +4 -2
- package/dist/{chunk-RV3JFSMX.js → chunk-C357P37M.js} +4 -4
- package/dist/{chunk-KFRGVHGB.js → chunk-E57UVUJL.js} +6 -6
- package/dist/{chunk-MGKSZSTV.js → chunk-EQWUCFXK.js} +3 -3
- package/dist/{chunk-72NIZMZN.js → chunk-M6KIDB5R.js} +8 -3
- package/dist/{chunk-O65UVJZH.js → chunk-N6PZE7HX.js} +2 -2
- package/dist/{chunk-WGTUNUIS.js → chunk-NYDM4HSS.js} +5 -5
- package/dist/{chunk-R4EYLEIK.js → chunk-P4O7L7JZ.js} +2 -2
- package/dist/{chunk-UUQT5GMO.js → chunk-PRJ7P6J5.js} +1 -1
- package/dist/{chunk-H74RDXKP.js → chunk-PTZ6BWSU.js} +2 -2
- package/dist/{chunk-F3FDVHR7.js → chunk-QQ3G5SXX.js} +1 -1
- package/dist/{chunk-VVFVENU4.js → chunk-RDT2IV2Z.js} +6 -6
- package/dist/{chunk-L6IL4N6Y.js → chunk-VLT2KGPE.js} +34 -34
- package/dist/{chunk-H6X52UVF.js → chunk-WEGZGF3K.js} +1 -1
- package/dist/{chunk-C4QNBSWB.js → chunk-XINFTNA2.js} +8 -8
- package/dist/{chunk-JCKOW45X.js → chunk-ZCT23NBS.js} +2 -2
- package/dist/daemon/server.js +1311 -364
- package/dist/hook-runtime/daemon/server.js +1311 -364
- package/dist/hook-runtime/hooks/post-commit.js +395 -242
- package/dist/hook-runtime/hooks/post-rewrite.js +391 -238
- package/dist/hook-runtime/hooks/post-tool-use.js +1442 -498
- package/dist/hook-runtime/hooks/pre-commit.js +1293 -349
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1087 -143
- package/dist/hook-runtime/hooks/prim-hook.js +1457 -513
- package/dist/hook-runtime/hooks/session-end.js +369 -216
- package/dist/hook-runtime/hooks/session-start.js +1209 -219
- package/dist/hook-runtime/index.js +2406 -1036
- package/dist/hook-runtime/statusline-main.js +360 -207
- 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 +63 -20
- package/dist/index.js +387 -43
- package/dist/statusline-main.js +360 -207
- package/package.json +1 -1
|
@@ -87,15 +87,17 @@ function isClaudeCloudSession(env = process.env) {
|
|
|
87
87
|
}
|
|
88
88
|
var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
|
|
89
89
|
var CLOUD_REJECTED_CREDENTIALS_REMEDY = 'correct the credentials in the cloud environment\'s settings, or if the installation was revoked mint a replacement on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`; then start a new cloud session';
|
|
90
|
+
var CLOUD_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
|
|
91
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
90
92
|
function cloudSetupPointer(message, env = process.env) {
|
|
91
93
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
92
94
|
}
|
|
93
95
|
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
94
96
|
|
|
95
97
|
// src/client.ts
|
|
96
|
-
import { createHash as
|
|
97
|
-
import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as
|
|
98
|
-
import { dirname as
|
|
98
|
+
import { createHash as createHash7 } from "crypto";
|
|
99
|
+
import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync7 } from "fs";
|
|
100
|
+
import { dirname as dirname6 } from "path";
|
|
99
101
|
|
|
100
102
|
// src/lib/atomic-file.ts
|
|
101
103
|
import { randomUUID } from "crypto";
|
|
@@ -177,25 +179,25 @@ function atomicWriteFile(target, content, options = {}) {
|
|
|
177
179
|
}
|
|
178
180
|
|
|
179
181
|
// src/lib/credentials.ts
|
|
180
|
-
import { createHash as
|
|
181
|
-
import { readFileSync as
|
|
182
|
-
import { join as
|
|
182
|
+
import { createHash as createHash6 } from "crypto";
|
|
183
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
184
|
+
import { join as join9 } from "path";
|
|
183
185
|
|
|
184
186
|
// src/lib/machine-credentials.ts
|
|
185
|
-
import { execFileSync } from "child_process";
|
|
186
|
-
import { createHash as
|
|
187
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
188
|
+
import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
|
|
187
189
|
import {
|
|
188
190
|
chmodSync,
|
|
189
191
|
existsSync as existsSync3,
|
|
190
192
|
linkSync,
|
|
191
|
-
lstatSync as
|
|
193
|
+
lstatSync as lstatSync4,
|
|
192
194
|
mkdirSync as mkdirSync3,
|
|
193
|
-
readFileSync as
|
|
194
|
-
rmSync as
|
|
195
|
+
readFileSync as readFileSync6,
|
|
196
|
+
rmSync as rmSync6,
|
|
195
197
|
writeFileSync as writeFileSync3
|
|
196
198
|
} from "fs";
|
|
197
199
|
import { createRequire } from "module";
|
|
198
|
-
import { dirname as
|
|
200
|
+
import { dirname as dirname5, join as join8 } from "path";
|
|
199
201
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
200
202
|
|
|
201
203
|
// src/lib/file-lock.ts
|
|
@@ -567,10 +569,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
567
569
|
"access_token",
|
|
568
570
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
569
571
|
);
|
|
570
|
-
const
|
|
572
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
571
573
|
return {
|
|
572
574
|
accessToken,
|
|
573
|
-
refreshToken:
|
|
575
|
+
refreshToken: refreshToken3,
|
|
574
576
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
575
577
|
};
|
|
576
578
|
}
|
|
@@ -1167,38 +1169,1202 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
1167
1169
|
}),
|
|
1168
1170
|
{ mode: 384 }
|
|
1169
1171
|
);
|
|
1170
|
-
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
1171
|
-
}
|
|
1172
|
-
throw error;
|
|
1172
|
+
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
1173
|
+
}
|
|
1174
|
+
throw error;
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
// src/lib/session-identity.ts
|
|
1179
|
+
import { execFile } from "child_process";
|
|
1180
|
+
import { createHash as createHash4 } from "crypto";
|
|
1181
|
+
import { rmSync as rmSync5 } from "fs";
|
|
1182
|
+
import { join as join7 } from "path";
|
|
1183
|
+
import { promisify } from "util";
|
|
1184
|
+
|
|
1185
|
+
// src/lib/git.ts
|
|
1186
|
+
import { execFileSync } from "child_process";
|
|
1187
|
+
import { createHash as createHash3 } from "crypto";
|
|
1188
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
|
|
1189
|
+
import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
|
|
1190
|
+
var GIT_TIMEOUT_MS = 1e3;
|
|
1191
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
1192
|
+
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
1193
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
1194
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
1195
|
+
function gitChildEnvironment(env = process.env) {
|
|
1196
|
+
return Object.fromEntries(
|
|
1197
|
+
Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
function gitToplevel(cwd) {
|
|
1201
|
+
try {
|
|
1202
|
+
return execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1203
|
+
cwd,
|
|
1204
|
+
encoding: "utf-8",
|
|
1205
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1206
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1207
|
+
env: gitChildEnvironment()
|
|
1208
|
+
}).trim();
|
|
1209
|
+
} catch {
|
|
1210
|
+
return null;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
function gitValue(cwd, args) {
|
|
1214
|
+
try {
|
|
1215
|
+
const value = execFileSync("git", args, {
|
|
1216
|
+
cwd,
|
|
1217
|
+
encoding: "utf-8",
|
|
1218
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1219
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1220
|
+
env: gitChildEnvironment()
|
|
1221
|
+
}).trim();
|
|
1222
|
+
return value || void 0;
|
|
1223
|
+
} catch {
|
|
1224
|
+
return void 0;
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
function currentBranch(cwd) {
|
|
1228
|
+
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
1229
|
+
}
|
|
1230
|
+
function parseGithubRepositoryName(path) {
|
|
1231
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
1232
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
1233
|
+
return null;
|
|
1234
|
+
}
|
|
1235
|
+
return `${parts[0]}/${parts[1]}`;
|
|
1236
|
+
}
|
|
1237
|
+
function githubRepositoryFromRemote(remote) {
|
|
1238
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
1239
|
+
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
1240
|
+
remote
|
|
1241
|
+
);
|
|
1242
|
+
const path = match?.[1] ?? match?.[2];
|
|
1243
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
1244
|
+
}
|
|
1245
|
+
function checkoutSettingsText(repoRoot) {
|
|
1246
|
+
const path = join6(repoRoot, ".claude", "settings.json");
|
|
1247
|
+
try {
|
|
1248
|
+
if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
|
|
1249
|
+
const stat = lstatSync3(path);
|
|
1250
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
1251
|
+
return readFileSync5(path, "utf8");
|
|
1252
|
+
} catch {
|
|
1253
|
+
return null;
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
function checkoutDeclaration(repoRoot, name) {
|
|
1257
|
+
const text = checkoutSettingsText(repoRoot);
|
|
1258
|
+
if (text === null) return null;
|
|
1259
|
+
let parsed;
|
|
1260
|
+
try {
|
|
1261
|
+
parsed = JSON.parse(text);
|
|
1262
|
+
} catch {
|
|
1263
|
+
return null;
|
|
1264
|
+
}
|
|
1265
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
1266
|
+
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
1267
|
+
return typeof value === "string" ? value : null;
|
|
1268
|
+
}
|
|
1269
|
+
function declaredGithubRepository(repoRoot) {
|
|
1270
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
1271
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
1272
|
+
}
|
|
1273
|
+
function githubRepositoryFullName(cwd) {
|
|
1274
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
1275
|
+
if (remote) {
|
|
1276
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
1277
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
1278
|
+
}
|
|
1279
|
+
const root = gitToplevel(cwd);
|
|
1280
|
+
return root ? declaredGithubRepository(root) : null;
|
|
1281
|
+
}
|
|
1282
|
+
function canonicalGitRoot(cwd) {
|
|
1283
|
+
try {
|
|
1284
|
+
const top = gitToplevel(cwd);
|
|
1285
|
+
return top ? realpathSync.native(top) : null;
|
|
1286
|
+
} catch {
|
|
1287
|
+
return null;
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
function normalizeOriginRemote(remote) {
|
|
1291
|
+
const value = remote.trim();
|
|
1292
|
+
if (!value) return void 0;
|
|
1293
|
+
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
1294
|
+
if (scp?.host && scp.path) {
|
|
1295
|
+
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1296
|
+
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
1297
|
+
}
|
|
1298
|
+
try {
|
|
1299
|
+
const url = new URL(value);
|
|
1300
|
+
url.username = "";
|
|
1301
|
+
url.password = "";
|
|
1302
|
+
url.search = "";
|
|
1303
|
+
url.hash = "";
|
|
1304
|
+
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1305
|
+
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
1306
|
+
return void 0;
|
|
1307
|
+
} catch {
|
|
1308
|
+
return void 0;
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
function nearestExistingAncestor(path) {
|
|
1312
|
+
const suffix = [];
|
|
1313
|
+
let cursor = path;
|
|
1314
|
+
while (true) {
|
|
1315
|
+
try {
|
|
1316
|
+
lstatSync3(cursor);
|
|
1317
|
+
break;
|
|
1318
|
+
} catch (error) {
|
|
1319
|
+
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
1320
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
1321
|
+
const parent = dirname4(cursor);
|
|
1322
|
+
if (parent === cursor) return null;
|
|
1323
|
+
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
1324
|
+
cursor = parent;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
try {
|
|
1328
|
+
return { real: realpathSync.native(cursor), suffix };
|
|
1329
|
+
} catch {
|
|
1330
|
+
return null;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
1334
|
+
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
1335
|
+
return { ok: false, reason: "invalid_path" };
|
|
1336
|
+
}
|
|
1337
|
+
const absolute = resolve(baseDir, filePath);
|
|
1338
|
+
const resolved = nearestExistingAncestor(absolute);
|
|
1339
|
+
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
1340
|
+
const target = resolve(resolved.real, ...resolved.suffix);
|
|
1341
|
+
const rel = relative(context.repoRoot, target);
|
|
1342
|
+
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
1343
|
+
if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
1344
|
+
return { ok: false, reason: "outside_repository" };
|
|
1345
|
+
}
|
|
1346
|
+
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
1347
|
+
}
|
|
1348
|
+
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
|
|
1349
|
+
if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
1350
|
+
return null;
|
|
1351
|
+
const absolute = resolve(cwd, filePath);
|
|
1352
|
+
let target;
|
|
1353
|
+
try {
|
|
1354
|
+
const stat = lstatSync3(absolute);
|
|
1355
|
+
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
1356
|
+
target = realpathSync.native(absolute);
|
|
1357
|
+
} catch (error) {
|
|
1358
|
+
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
1359
|
+
return null;
|
|
1360
|
+
}
|
|
1361
|
+
try {
|
|
1362
|
+
const parent = realpathSync.native(dirname4(absolute));
|
|
1363
|
+
if (!lstatSync3(parent).isDirectory()) return null;
|
|
1364
|
+
target = resolve(parent, basename2(absolute));
|
|
1365
|
+
} catch {
|
|
1366
|
+
return null;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
const rel = relative(repositoryRoot, target);
|
|
1370
|
+
if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
1371
|
+
return null;
|
|
1372
|
+
}
|
|
1373
|
+
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
1374
|
+
}
|
|
1375
|
+
function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
1376
|
+
if (typeof contextOrCwd === "string") {
|
|
1377
|
+
return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
|
|
1378
|
+
}
|
|
1379
|
+
return canonicalRepositoryPathScoped(
|
|
1380
|
+
filePath,
|
|
1381
|
+
contextOrCwd,
|
|
1382
|
+
baseDirOrRoot ?? contextOrCwd.repoRoot
|
|
1383
|
+
);
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
// src/lib/terminal-safe.ts
|
|
1387
|
+
function replaceIsolatedSurrogates(value) {
|
|
1388
|
+
let out = "";
|
|
1389
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1390
|
+
const unit = value.charCodeAt(index);
|
|
1391
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
1392
|
+
const next = value.charCodeAt(index + 1);
|
|
1393
|
+
if (next >= 56320 && next <= 57343) {
|
|
1394
|
+
out += value[index] + value[index + 1];
|
|
1395
|
+
index += 1;
|
|
1396
|
+
} else {
|
|
1397
|
+
out += "\uFFFD";
|
|
1398
|
+
}
|
|
1399
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
1400
|
+
out += "\uFFFD";
|
|
1401
|
+
} else {
|
|
1402
|
+
out += value[index];
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
return out;
|
|
1406
|
+
}
|
|
1407
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
1408
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
1409
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
1410
|
+
point === 1564 || // Arabic letter mark
|
|
1411
|
+
point === 6158 || // Mongolian vowel separator
|
|
1412
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
1413
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
1414
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
1415
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
1416
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
1417
|
+
point >= 917504 && point <= 917631;
|
|
1418
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
1419
|
+
}
|
|
1420
|
+
function terminalSafeText(value) {
|
|
1421
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
1422
|
+
}
|
|
1423
|
+
function terminalSafeLine(value) {
|
|
1424
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
// src/lib/session-identity.ts
|
|
1428
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
1429
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
1430
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
1431
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
1432
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
1433
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
1434
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
1435
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
1436
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
1437
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
1438
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
1439
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
1440
|
+
token: "/api/cli/session-identity/token",
|
|
1441
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
1442
|
+
link: "/api/cli/session-identity/link"
|
|
1443
|
+
};
|
|
1444
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
1445
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
1446
|
+
var GIT_TIMEOUT_MS2 = 1e4;
|
|
1447
|
+
var POLL_BUDGET_MS = 15e3;
|
|
1448
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
1449
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
1450
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
1451
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
1452
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
1453
|
+
function sessionIdentityRequested(env = process.env) {
|
|
1454
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
1455
|
+
}
|
|
1456
|
+
function sessionIdentityMode(deps = {}) {
|
|
1457
|
+
const env = deps.env ?? process.env;
|
|
1458
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
1459
|
+
}
|
|
1460
|
+
function failure(code, cause, remedy) {
|
|
1461
|
+
return { status: "failed", code, cause, remedy };
|
|
1462
|
+
}
|
|
1463
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
1464
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
1465
|
+
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';
|
|
1466
|
+
var SESSION_REVOKED = failure(
|
|
1467
|
+
"session_revoked",
|
|
1468
|
+
"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",
|
|
1469
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
1470
|
+
);
|
|
1471
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
1472
|
+
"challenge_expired",
|
|
1473
|
+
"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)",
|
|
1474
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
1475
|
+
);
|
|
1476
|
+
var CHALLENGE_GONE = failure(
|
|
1477
|
+
"challenge_not_found",
|
|
1478
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
1479
|
+
NEW_SESSION_REMEDY
|
|
1480
|
+
);
|
|
1481
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
1482
|
+
function rejectionFailure(reason, repository) {
|
|
1483
|
+
switch (reason) {
|
|
1484
|
+
case "identity_mismatch":
|
|
1485
|
+
return failure(
|
|
1486
|
+
"identity_mismatch",
|
|
1487
|
+
"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",
|
|
1488
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
1489
|
+
);
|
|
1490
|
+
case "push_after_expiry":
|
|
1491
|
+
return failure(
|
|
1492
|
+
"push_after_expiry",
|
|
1493
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
1494
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
1495
|
+
);
|
|
1496
|
+
case "repository_mismatch":
|
|
1497
|
+
return failure(
|
|
1498
|
+
"repository_mismatch",
|
|
1499
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
1500
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
1501
|
+
);
|
|
1502
|
+
case "conflicting_push":
|
|
1503
|
+
return failure(
|
|
1504
|
+
"conflicting_push",
|
|
1505
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
1506
|
+
NEW_SESSION_REMEDY
|
|
1507
|
+
);
|
|
1508
|
+
case "unsupported_sender":
|
|
1509
|
+
return failure(
|
|
1510
|
+
"unsupported_sender",
|
|
1511
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
1512
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
1513
|
+
);
|
|
1514
|
+
default:
|
|
1515
|
+
return failure(
|
|
1516
|
+
"challenge_rejected",
|
|
1517
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
1518
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
1519
|
+
);
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
function sessionIdentityMessage(outcome) {
|
|
1523
|
+
if (outcome.status === "link_required")
|
|
1524
|
+
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.`;
|
|
1525
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
1526
|
+
}
|
|
1527
|
+
function hash(value) {
|
|
1528
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
1529
|
+
}
|
|
1530
|
+
function sessionContext(deps) {
|
|
1531
|
+
const env = deps.env ?? process.env;
|
|
1532
|
+
const environment = environmentCredentials(deps);
|
|
1533
|
+
if (!environment)
|
|
1534
|
+
return failure(
|
|
1535
|
+
"environment_credential_missing",
|
|
1536
|
+
"the cloud environment has no environment credential",
|
|
1537
|
+
'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'
|
|
1538
|
+
);
|
|
1539
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
1540
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
1541
|
+
return failure(
|
|
1542
|
+
"session_id_missing",
|
|
1543
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
1544
|
+
NEW_SESSION_REMEDY
|
|
1545
|
+
);
|
|
1546
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
1547
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
1548
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
1549
|
+
return {
|
|
1550
|
+
directory,
|
|
1551
|
+
apiUrl,
|
|
1552
|
+
clientId: environment.clientId,
|
|
1553
|
+
generation: environment.generation,
|
|
1554
|
+
sessionId,
|
|
1555
|
+
tokenPath: join7(directory, `session_identity_${key}.json`),
|
|
1556
|
+
statePath: join7(directory, `session_identity_${key}.state.json`),
|
|
1557
|
+
lockPath: join7(directory, "session-identity.lock")
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
function readRecord(path) {
|
|
1561
|
+
try {
|
|
1562
|
+
const value = readMachineMetadata(path);
|
|
1563
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
1564
|
+
} catch {
|
|
1565
|
+
return void 0;
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
function finiteNumber(value) {
|
|
1569
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1570
|
+
}
|
|
1571
|
+
function readToken(context) {
|
|
1572
|
+
const data = readRecord(context.tokenPath);
|
|
1573
|
+
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))
|
|
1574
|
+
return void 0;
|
|
1575
|
+
const identity = data.identity;
|
|
1576
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
1577
|
+
return void 0;
|
|
1578
|
+
return data;
|
|
1579
|
+
}
|
|
1580
|
+
function readState(context) {
|
|
1581
|
+
const data = readRecord(context.statePath);
|
|
1582
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
1583
|
+
return void 0;
|
|
1584
|
+
return data;
|
|
1585
|
+
}
|
|
1586
|
+
function writeToken(context, record) {
|
|
1587
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1588
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
1589
|
+
rmSync5(context.statePath, { force: true });
|
|
1590
|
+
}
|
|
1591
|
+
function writeState(context, state) {
|
|
1592
|
+
try {
|
|
1593
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1594
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
1595
|
+
} catch {
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
function tokenValid(record, now = Date.now()) {
|
|
1599
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
1600
|
+
}
|
|
1601
|
+
function tokenFresh(record, now = Date.now()) {
|
|
1602
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
1603
|
+
}
|
|
1604
|
+
function toCredential(record) {
|
|
1605
|
+
return {
|
|
1606
|
+
issuer: record.issuer,
|
|
1607
|
+
audience: record.audience,
|
|
1608
|
+
...record.identity,
|
|
1609
|
+
accessToken: record.accessToken,
|
|
1610
|
+
expiresAt: record.expiresAt,
|
|
1611
|
+
apiUrl: record.apiUrl,
|
|
1612
|
+
generation: record.generation,
|
|
1613
|
+
storage: "environment",
|
|
1614
|
+
session: {
|
|
1615
|
+
userId: record.userId,
|
|
1616
|
+
displayName: record.displayName,
|
|
1617
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1618
|
+
refreshAfter: record.refreshAfter
|
|
1619
|
+
}
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
function identified(record, reused) {
|
|
1623
|
+
return {
|
|
1624
|
+
status: "ok",
|
|
1625
|
+
credential: toCredential(record),
|
|
1626
|
+
displayName: record.displayName,
|
|
1627
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1628
|
+
reused
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
function cachedSessionCredential(deps = {}) {
|
|
1632
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
1633
|
+
let context;
|
|
1634
|
+
try {
|
|
1635
|
+
context = sessionContext(deps);
|
|
1636
|
+
} catch {
|
|
1637
|
+
return void 0;
|
|
1638
|
+
}
|
|
1639
|
+
if ("status" in context) return void 0;
|
|
1640
|
+
const record = readToken(context);
|
|
1641
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
1642
|
+
}
|
|
1643
|
+
function outcomeFromState(state) {
|
|
1644
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
1645
|
+
return {
|
|
1646
|
+
status: "link_required",
|
|
1647
|
+
githubLogin: state.githubLogin,
|
|
1648
|
+
challengeId: state.challengeId,
|
|
1649
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
1650
|
+
};
|
|
1651
|
+
return failure(
|
|
1652
|
+
state.code,
|
|
1653
|
+
state.cause ?? "the last identity check failed",
|
|
1654
|
+
state.remedy ?? RETRY_REMEDY
|
|
1655
|
+
);
|
|
1656
|
+
}
|
|
1657
|
+
function parseInstant(value) {
|
|
1658
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
1659
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
1660
|
+
const parsed = Date.parse(value);
|
|
1661
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1662
|
+
}
|
|
1663
|
+
return void 0;
|
|
1664
|
+
}
|
|
1665
|
+
async function sendJson(url, init, fetchImpl) {
|
|
1666
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
1667
|
+
let value;
|
|
1668
|
+
try {
|
|
1669
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
1670
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
1671
|
+
} catch {
|
|
1672
|
+
value = void 0;
|
|
1673
|
+
}
|
|
1674
|
+
return { status: response.status, value };
|
|
1675
|
+
}
|
|
1676
|
+
function environmentOnly(deps) {
|
|
1677
|
+
return { ...deps, environmentOnly: true };
|
|
1678
|
+
}
|
|
1679
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
1680
|
+
const send = async (credential2) => {
|
|
1681
|
+
const headers = { "Content-Type": "application/json" };
|
|
1682
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
1683
|
+
if (credential2.tokenInjection) {
|
|
1684
|
+
const response = await forwardMachineRequest(
|
|
1685
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
1686
|
+
signal,
|
|
1687
|
+
environmentOnly(deps)
|
|
1688
|
+
);
|
|
1689
|
+
const parsed = await response.json().catch(() => void 0);
|
|
1690
|
+
return {
|
|
1691
|
+
status: response.status,
|
|
1692
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1695
|
+
return sendJson(
|
|
1696
|
+
`${credential2.apiUrl}${path}`,
|
|
1697
|
+
{
|
|
1698
|
+
method,
|
|
1699
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
1700
|
+
...text === void 0 ? {} : { body: text },
|
|
1701
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
|
|
1702
|
+
},
|
|
1703
|
+
deps.fetch ?? fetch
|
|
1704
|
+
);
|
|
1705
|
+
};
|
|
1706
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
1707
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
1708
|
+
let answer = await send(credential);
|
|
1709
|
+
if (answer.status === 401) {
|
|
1710
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
1711
|
+
if (!credential)
|
|
1712
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
1713
|
+
answer = await send(credential);
|
|
1714
|
+
}
|
|
1715
|
+
return answer;
|
|
1716
|
+
}
|
|
1717
|
+
function environmentFailure(error, apiUrl) {
|
|
1718
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
1719
|
+
return failure(
|
|
1720
|
+
"environment_credential_rejected",
|
|
1721
|
+
"Primitive rejected the cloud environment's credential",
|
|
1722
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
1723
|
+
);
|
|
1724
|
+
const host = (() => {
|
|
1725
|
+
try {
|
|
1726
|
+
return new URL(apiUrl).hostname;
|
|
1727
|
+
} catch {
|
|
1728
|
+
return "Primitive";
|
|
1729
|
+
}
|
|
1730
|
+
})();
|
|
1731
|
+
return failure(
|
|
1732
|
+
"identity_unavailable",
|
|
1733
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
1734
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
1735
|
+
);
|
|
1736
|
+
}
|
|
1737
|
+
function answerError(answer) {
|
|
1738
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
1739
|
+
}
|
|
1740
|
+
async function git(root, args, signal) {
|
|
1741
|
+
try {
|
|
1742
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
1743
|
+
cwd: root,
|
|
1744
|
+
encoding: "utf8",
|
|
1745
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
1746
|
+
signal,
|
|
1747
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
1748
|
+
maxBuffer: 1024 * 1024
|
|
1749
|
+
});
|
|
1750
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
1751
|
+
} catch (error) {
|
|
1752
|
+
const failed = error;
|
|
1753
|
+
return {
|
|
1754
|
+
ok: false,
|
|
1755
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
1756
|
+
stdout: failed.stdout ?? "",
|
|
1757
|
+
stderr: failed.stderr ?? "",
|
|
1758
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
1759
|
+
};
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
function gitDetail(stderr) {
|
|
1763
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
1764
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
1765
|
+
}
|
|
1766
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
1767
|
+
await new Promise((resolve3, reject) => {
|
|
1768
|
+
const timer = setTimeout(resolve3, milliseconds);
|
|
1769
|
+
signal?.addEventListener(
|
|
1770
|
+
"abort",
|
|
1771
|
+
() => {
|
|
1772
|
+
clearTimeout(timer);
|
|
1773
|
+
reject(signal.reason);
|
|
1774
|
+
},
|
|
1775
|
+
{ once: true }
|
|
1776
|
+
);
|
|
1777
|
+
});
|
|
1778
|
+
}
|
|
1779
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
1780
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
1781
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
1782
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
1783
|
+
let unreachable;
|
|
1784
|
+
for (; ; ) {
|
|
1785
|
+
const remaining = deadline - Date.now();
|
|
1786
|
+
if (remaining <= 0) break;
|
|
1787
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
1788
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
1789
|
+
let answer;
|
|
1790
|
+
try {
|
|
1791
|
+
answer = await environmentRequest(
|
|
1792
|
+
"GET",
|
|
1793
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
1794
|
+
void 0,
|
|
1795
|
+
deps,
|
|
1796
|
+
signal
|
|
1797
|
+
);
|
|
1798
|
+
} catch (error) {
|
|
1799
|
+
signal?.throwIfAborted();
|
|
1800
|
+
unreachable = error;
|
|
1801
|
+
continue;
|
|
1802
|
+
}
|
|
1803
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
1804
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1805
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
1806
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
1807
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
1808
|
+
continue;
|
|
1809
|
+
}
|
|
1810
|
+
unreachable = void 0;
|
|
1811
|
+
const status = answer.value;
|
|
1812
|
+
if (status?.status === "verified")
|
|
1813
|
+
return {
|
|
1814
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
1815
|
+
};
|
|
1816
|
+
if (status?.status === "expired")
|
|
1817
|
+
return failure(
|
|
1818
|
+
"challenge_expired",
|
|
1819
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
1820
|
+
NEW_SESSION_REMEDY
|
|
1821
|
+
);
|
|
1822
|
+
if (status?.status === "rejected")
|
|
1823
|
+
return rejectionFailure(status.reason, repository);
|
|
1824
|
+
}
|
|
1825
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
1826
|
+
return failure(
|
|
1827
|
+
"webhook_timeout",
|
|
1828
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
1829
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
1830
|
+
);
|
|
1831
|
+
}
|
|
1832
|
+
function parseTokenAnswer(value) {
|
|
1833
|
+
if (!value) return void 0;
|
|
1834
|
+
const user = value.user;
|
|
1835
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
1836
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
1837
|
+
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))
|
|
1838
|
+
return void 0;
|
|
1839
|
+
return {
|
|
1840
|
+
accessToken: value.accessToken,
|
|
1841
|
+
expiresAt,
|
|
1842
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
1843
|
+
userId: user.id,
|
|
1844
|
+
displayName: user.displayName,
|
|
1845
|
+
organizationId: value.organizationId
|
|
1846
|
+
};
|
|
1847
|
+
}
|
|
1848
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
1849
|
+
"server_contract",
|
|
1850
|
+
"Primitive's answer did not identify the linked member",
|
|
1851
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
1852
|
+
);
|
|
1853
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
1854
|
+
let identity;
|
|
1855
|
+
let environment;
|
|
1856
|
+
try {
|
|
1857
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
1858
|
+
identity = await verifyMachineIdentity(
|
|
1859
|
+
context.apiUrl,
|
|
1860
|
+
answer.accessToken,
|
|
1861
|
+
context.clientId,
|
|
1862
|
+
signal,
|
|
1863
|
+
deps.fetch
|
|
1864
|
+
);
|
|
1865
|
+
} catch (error) {
|
|
1866
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
1867
|
+
return SERVER_CONTRACT_FAILURE;
|
|
1868
|
+
return environmentFailure(error, context.apiUrl);
|
|
1869
|
+
}
|
|
1870
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
1871
|
+
return SERVER_CONTRACT_FAILURE;
|
|
1872
|
+
return {
|
|
1873
|
+
version: 1,
|
|
1874
|
+
apiUrl: context.apiUrl,
|
|
1875
|
+
clientId: context.clientId,
|
|
1876
|
+
generation: context.generation,
|
|
1877
|
+
sessionId: context.sessionId,
|
|
1878
|
+
issuer: environment.issuer,
|
|
1879
|
+
audience: environment.audience,
|
|
1880
|
+
accessToken: answer.accessToken,
|
|
1881
|
+
expiresAt: answer.expiresAt,
|
|
1882
|
+
refreshAfter: answer.refreshAfter,
|
|
1883
|
+
userId: answer.userId,
|
|
1884
|
+
displayName: answer.displayName,
|
|
1885
|
+
organizationId: answer.organizationId,
|
|
1886
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
1887
|
+
identity,
|
|
1888
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
1889
|
+
};
|
|
1890
|
+
}
|
|
1891
|
+
async function refreshToken(context, record, deps, signal) {
|
|
1892
|
+
let answer;
|
|
1893
|
+
try {
|
|
1894
|
+
answer = await environmentRequest(
|
|
1895
|
+
"POST",
|
|
1896
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
1897
|
+
{ accessToken: record.accessToken },
|
|
1898
|
+
deps,
|
|
1899
|
+
signal
|
|
1900
|
+
);
|
|
1901
|
+
} catch (error) {
|
|
1902
|
+
signal?.throwIfAborted();
|
|
1903
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
1904
|
+
}
|
|
1905
|
+
const code = answerError(answer);
|
|
1906
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
1907
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
1908
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1909
|
+
return {
|
|
1910
|
+
status: "refused",
|
|
1911
|
+
failure: environmentFailure(
|
|
1912
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
1913
|
+
context.apiUrl
|
|
1914
|
+
)
|
|
1915
|
+
};
|
|
1916
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
1917
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
1918
|
+
return { status: "unavailable" };
|
|
1919
|
+
return {
|
|
1920
|
+
status: "ok",
|
|
1921
|
+
record: {
|
|
1922
|
+
...record,
|
|
1923
|
+
accessToken: token.accessToken,
|
|
1924
|
+
expiresAt: token.expiresAt,
|
|
1925
|
+
refreshAfter: token.refreshAfter,
|
|
1926
|
+
displayName: token.displayName
|
|
1927
|
+
}
|
|
1928
|
+
};
|
|
1929
|
+
}
|
|
1930
|
+
function exchangeRefusal(answer, repository) {
|
|
1931
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
1932
|
+
if (answer.status !== 409) return void 0;
|
|
1933
|
+
switch (answerError(answer)) {
|
|
1934
|
+
case "identity_mismatch":
|
|
1935
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
1936
|
+
case "challenge_rejected":
|
|
1937
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
1938
|
+
case "challenge_expired":
|
|
1939
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
1940
|
+
case "challenge_already_exchanged":
|
|
1941
|
+
return failure(
|
|
1942
|
+
"challenge_already_exchanged",
|
|
1943
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
1944
|
+
NEW_SESSION_REMEDY
|
|
1945
|
+
);
|
|
1946
|
+
case "challenge_pending":
|
|
1947
|
+
return failure(
|
|
1948
|
+
"webhook_timeout",
|
|
1949
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
1950
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
1951
|
+
);
|
|
1952
|
+
default:
|
|
1953
|
+
return void 0;
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
1957
|
+
let answer;
|
|
1958
|
+
try {
|
|
1959
|
+
answer = await environmentRequest(
|
|
1960
|
+
"POST",
|
|
1961
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
1962
|
+
{ challengeId: challenge.challengeId },
|
|
1963
|
+
deps,
|
|
1964
|
+
signal
|
|
1965
|
+
);
|
|
1966
|
+
} catch (error) {
|
|
1967
|
+
signal?.throwIfAborted();
|
|
1968
|
+
return environmentFailure(error, context.apiUrl);
|
|
1969
|
+
}
|
|
1970
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
1971
|
+
const login = answer.value?.githubLogin;
|
|
1972
|
+
return {
|
|
1973
|
+
status: "link_required",
|
|
1974
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
1975
|
+
challengeId: challenge.challengeId,
|
|
1976
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
1977
|
+
};
|
|
1978
|
+
}
|
|
1979
|
+
const refused = exchangeRefusal(
|
|
1980
|
+
answer,
|
|
1981
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
1982
|
+
);
|
|
1983
|
+
if (refused) return refused;
|
|
1984
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
1985
|
+
if (!token) {
|
|
1986
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1987
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
1988
|
+
return answer.status >= 500 ? environmentFailure(
|
|
1989
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
1990
|
+
context.apiUrl
|
|
1991
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
1992
|
+
}
|
|
1993
|
+
return recordFor(
|
|
1994
|
+
context,
|
|
1995
|
+
token,
|
|
1996
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
1997
|
+
deps,
|
|
1998
|
+
signal
|
|
1999
|
+
);
|
|
2000
|
+
}
|
|
2001
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
2002
|
+
const env = deps.env ?? process.env;
|
|
2003
|
+
const repository = githubRepositoryFullName(root);
|
|
2004
|
+
if (!repository)
|
|
2005
|
+
return failure(
|
|
2006
|
+
"repository_unidentified",
|
|
2007
|
+
"this checkout does not name its GitHub repository",
|
|
2008
|
+
"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"
|
|
2009
|
+
);
|
|
2010
|
+
const branch = currentBranch(root);
|
|
2011
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
2012
|
+
return failure(
|
|
2013
|
+
"not_session_branch",
|
|
2014
|
+
`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`,
|
|
2015
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
2016
|
+
);
|
|
2017
|
+
attempt.branch = branch;
|
|
2018
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
2019
|
+
if (!baseSha) {
|
|
2020
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
2021
|
+
baseSha = head.stdout.trim();
|
|
2022
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
2023
|
+
return failure(
|
|
2024
|
+
"no_commit",
|
|
2025
|
+
"this checkout has no commit to create the session branch at",
|
|
2026
|
+
NEW_SESSION_REMEDY
|
|
2027
|
+
);
|
|
2028
|
+
}
|
|
2029
|
+
const published = await git(
|
|
2030
|
+
root,
|
|
2031
|
+
[
|
|
2032
|
+
"for-each-ref",
|
|
2033
|
+
"--count=1",
|
|
2034
|
+
"--format=%(refname)",
|
|
2035
|
+
"--contains",
|
|
2036
|
+
baseSha,
|
|
2037
|
+
"refs/remotes/origin/"
|
|
2038
|
+
],
|
|
2039
|
+
signal
|
|
2040
|
+
);
|
|
2041
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
2042
|
+
return failure(
|
|
2043
|
+
"unpublished_commits",
|
|
2044
|
+
`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`,
|
|
2045
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
2046
|
+
);
|
|
2047
|
+
attempt.baseSha = baseSha;
|
|
2048
|
+
const remote = await git(
|
|
2049
|
+
root,
|
|
2050
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
2051
|
+
signal
|
|
2052
|
+
);
|
|
2053
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
2054
|
+
if (remote.ok && recorded) {
|
|
2055
|
+
Object.assign(attempt, recorded);
|
|
2056
|
+
return { ...recorded, repository };
|
|
2057
|
+
}
|
|
2058
|
+
if (remote.ok)
|
|
2059
|
+
return failure(
|
|
2060
|
+
"branch_exists",
|
|
2061
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
2062
|
+
NEW_SESSION_REMEDY
|
|
2063
|
+
);
|
|
2064
|
+
if (remote.code !== 2)
|
|
2065
|
+
return failure(
|
|
2066
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
2067
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
2068
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
2069
|
+
);
|
|
2070
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
2071
|
+
Object.assign(attempt, recorded);
|
|
2072
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
2073
|
+
}
|
|
2074
|
+
let answer;
|
|
2075
|
+
try {
|
|
2076
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
2077
|
+
answer = await environmentRequest(
|
|
2078
|
+
"POST",
|
|
2079
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
2080
|
+
{
|
|
2081
|
+
repositoryFullName: repository,
|
|
2082
|
+
claudeSessionId: context.sessionId,
|
|
2083
|
+
branch,
|
|
2084
|
+
baseSha,
|
|
2085
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
2086
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
2087
|
+
},
|
|
2088
|
+
deps,
|
|
2089
|
+
signal
|
|
2090
|
+
);
|
|
2091
|
+
} catch (error) {
|
|
2092
|
+
signal?.throwIfAborted();
|
|
2093
|
+
return environmentFailure(error, context.apiUrl);
|
|
2094
|
+
}
|
|
2095
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
2096
|
+
return failure(
|
|
2097
|
+
"repository_not_connected",
|
|
2098
|
+
`${repository} is not connected to Primitive`,
|
|
2099
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
2100
|
+
);
|
|
2101
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2102
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2103
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
2104
|
+
return failure(
|
|
2105
|
+
"challenge_open",
|
|
2106
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
2107
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
2108
|
+
);
|
|
2109
|
+
if (answer.status === 429)
|
|
2110
|
+
return failure(
|
|
2111
|
+
"too_many_challenges",
|
|
2112
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
2113
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
2114
|
+
);
|
|
2115
|
+
const challengeId = answer.value?.challengeId;
|
|
2116
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
2117
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
2118
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2119
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2120
|
+
context.apiUrl
|
|
2121
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2122
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
2123
|
+
attempt.challengeId = challengeId;
|
|
2124
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
2125
|
+
return pushSessionBranch(
|
|
2126
|
+
root,
|
|
2127
|
+
repository,
|
|
2128
|
+
branch,
|
|
2129
|
+
baseSha,
|
|
2130
|
+
{ challengeId, challengeExpiresAt },
|
|
2131
|
+
signal
|
|
2132
|
+
);
|
|
2133
|
+
}
|
|
2134
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
2135
|
+
const push = await git(
|
|
2136
|
+
root,
|
|
2137
|
+
[
|
|
2138
|
+
"-c",
|
|
2139
|
+
"core.hooksPath=/dev/null",
|
|
2140
|
+
"-c",
|
|
2141
|
+
"push.followTags=false",
|
|
2142
|
+
"-c",
|
|
2143
|
+
"push.recurseSubmodules=no",
|
|
2144
|
+
"-c",
|
|
2145
|
+
"push.gpgSign=false",
|
|
2146
|
+
"-c",
|
|
2147
|
+
"push.pushOption=",
|
|
2148
|
+
"push",
|
|
2149
|
+
"--no-verify",
|
|
2150
|
+
"--no-follow-tags",
|
|
2151
|
+
"--no-recurse-submodules",
|
|
2152
|
+
"--no-signed",
|
|
2153
|
+
"--quiet",
|
|
2154
|
+
"origin",
|
|
2155
|
+
`${baseSha}:refs/heads/${branch}`
|
|
2156
|
+
],
|
|
2157
|
+
signal
|
|
2158
|
+
);
|
|
2159
|
+
if (!push.ok)
|
|
2160
|
+
return push.timedOut ? failure(
|
|
2161
|
+
"push_timeout",
|
|
2162
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
|
|
2163
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
2164
|
+
) : failure(
|
|
2165
|
+
"push_refused",
|
|
2166
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
2167
|
+
`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}`
|
|
2168
|
+
);
|
|
2169
|
+
return { ...challenge, repository };
|
|
2170
|
+
}
|
|
2171
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
2172
|
+
let context;
|
|
2173
|
+
try {
|
|
2174
|
+
context = sessionContext(deps);
|
|
2175
|
+
} catch (error) {
|
|
2176
|
+
return failure(
|
|
2177
|
+
"environment_credential_invalid",
|
|
2178
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
2179
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
2180
|
+
);
|
|
2181
|
+
}
|
|
2182
|
+
if ("status" in context) return context;
|
|
2183
|
+
const ctx = context;
|
|
2184
|
+
const startedAt = Date.now();
|
|
2185
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
2186
|
+
return withFileLock(
|
|
2187
|
+
ctx.lockPath,
|
|
2188
|
+
async () => {
|
|
2189
|
+
const record = readToken(ctx);
|
|
2190
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
2191
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
2192
|
+
if (record) {
|
|
2193
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
2194
|
+
if (refreshed.status === "ok") {
|
|
2195
|
+
writeToken(ctx, refreshed.record);
|
|
2196
|
+
return identified(refreshed.record, true);
|
|
2197
|
+
}
|
|
2198
|
+
if (refreshed.status === "refused") {
|
|
2199
|
+
rmSync5(ctx.tokenPath, { force: true });
|
|
2200
|
+
writeState(ctx, {
|
|
2201
|
+
sessionId: ctx.sessionId,
|
|
2202
|
+
status: "failed",
|
|
2203
|
+
code: refreshed.failure.code,
|
|
2204
|
+
cause: refreshed.failure.cause,
|
|
2205
|
+
remedy: refreshed.failure.remedy,
|
|
2206
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
2207
|
+
at: Date.now()
|
|
2208
|
+
});
|
|
2209
|
+
return refreshed.failure;
|
|
2210
|
+
}
|
|
2211
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
2212
|
+
}
|
|
2213
|
+
const state = readState(ctx);
|
|
2214
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
2215
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
2216
|
+
if (!options.explicit) {
|
|
2217
|
+
if (!root || !(record || state))
|
|
2218
|
+
return failure(
|
|
2219
|
+
"not_identified",
|
|
2220
|
+
"this session has not identified who started it yet",
|
|
2221
|
+
RETRY_REMEDY
|
|
2222
|
+
);
|
|
2223
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
2224
|
+
} else if (state && state.at >= startedAt) {
|
|
2225
|
+
return outcomeFromState(state);
|
|
2226
|
+
}
|
|
2227
|
+
if (!root)
|
|
2228
|
+
return failure(
|
|
2229
|
+
"repository_missing",
|
|
2230
|
+
"this is not a git repository",
|
|
2231
|
+
"run it in the repository the session cloned"
|
|
2232
|
+
);
|
|
2233
|
+
const attempt = { root };
|
|
2234
|
+
const remember = (outcome) => {
|
|
2235
|
+
writeState(ctx, {
|
|
2236
|
+
sessionId: ctx.sessionId,
|
|
2237
|
+
status: outcome.status,
|
|
2238
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
2239
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
2240
|
+
githubLogin: outcome.githubLogin
|
|
2241
|
+
},
|
|
2242
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
2243
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
2244
|
+
repositoryRoot: root,
|
|
2245
|
+
branch: attempt.branch ?? state?.branch,
|
|
2246
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
2247
|
+
at: Date.now()
|
|
2248
|
+
});
|
|
2249
|
+
return outcome;
|
|
2250
|
+
};
|
|
2251
|
+
let challenge;
|
|
2252
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
2253
|
+
attempt.challengeId = state.challengeId;
|
|
2254
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2255
|
+
attempt.branch = state.branch;
|
|
2256
|
+
attempt.baseSha = state.baseSha;
|
|
2257
|
+
challenge = {
|
|
2258
|
+
challengeId: state.challengeId,
|
|
2259
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2260
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
2261
|
+
};
|
|
2262
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
2263
|
+
attempt.challengeId = state.challengeId;
|
|
2264
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2265
|
+
const exchanged2 = await exchangeChallenge(
|
|
2266
|
+
ctx,
|
|
2267
|
+
{
|
|
2268
|
+
challengeId: state.challengeId,
|
|
2269
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2270
|
+
githubLogin: state.githubLogin
|
|
2271
|
+
},
|
|
2272
|
+
root,
|
|
2273
|
+
deps,
|
|
2274
|
+
options.signal
|
|
2275
|
+
);
|
|
2276
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
2277
|
+
writeToken(ctx, exchanged2);
|
|
2278
|
+
return identified(exchanged2, false);
|
|
2279
|
+
} else if (!options.explicit) {
|
|
2280
|
+
return state ? outcomeFromState(state) : failure(
|
|
2281
|
+
"not_identified",
|
|
2282
|
+
"this session has not identified who started it yet",
|
|
2283
|
+
RETRY_REMEDY
|
|
2284
|
+
);
|
|
2285
|
+
} else {
|
|
2286
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
2287
|
+
if ("status" in pushed) return remember(pushed);
|
|
2288
|
+
challenge = pushed;
|
|
2289
|
+
}
|
|
2290
|
+
const verified = await pollChallenge(
|
|
2291
|
+
ctx.apiUrl,
|
|
2292
|
+
challenge.challengeId,
|
|
2293
|
+
challenge.repository,
|
|
2294
|
+
// A hook process waits only briefly for a late notice.
|
|
2295
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
2296
|
+
options.signal
|
|
2297
|
+
);
|
|
2298
|
+
if ("status" in verified) return remember(verified);
|
|
2299
|
+
const exchanged = await exchangeChallenge(
|
|
2300
|
+
ctx,
|
|
2301
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
2302
|
+
root,
|
|
2303
|
+
deps,
|
|
2304
|
+
options.signal
|
|
2305
|
+
);
|
|
2306
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
2307
|
+
writeToken(ctx, exchanged);
|
|
2308
|
+
return identified(exchanged, false);
|
|
2309
|
+
},
|
|
2310
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
2311
|
+
);
|
|
2312
|
+
}
|
|
2313
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
2314
|
+
const cached2 = cachedSessionCredential(deps);
|
|
2315
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
2316
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
2317
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2318
|
+
let outcome;
|
|
2319
|
+
try {
|
|
2320
|
+
outcome = await ensureSessionIdentity(
|
|
2321
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
2322
|
+
deps
|
|
2323
|
+
);
|
|
2324
|
+
} catch (error) {
|
|
2325
|
+
options.signal?.throwIfAborted();
|
|
2326
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2327
|
+
throw new MachineAuthError(
|
|
2328
|
+
"identity_unavailable",
|
|
2329
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
2330
|
+
);
|
|
1173
2331
|
}
|
|
2332
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
2333
|
+
throw new MachineAuthError(
|
|
2334
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
2335
|
+
sessionIdentityMessage(outcome)
|
|
2336
|
+
);
|
|
1174
2337
|
}
|
|
1175
2338
|
|
|
1176
2339
|
// src/lib/machine-credentials.ts
|
|
2340
|
+
function sessionScoped(deps) {
|
|
2341
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
2342
|
+
}
|
|
1177
2343
|
var require2 = createRequire(import.meta.url);
|
|
1178
2344
|
var SERVICE = "ai.primitive.prim.machine";
|
|
1179
|
-
var
|
|
2345
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
1180
2346
|
var PROFILE_FILE = "machine_profile.json";
|
|
1181
|
-
var
|
|
2347
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
1182
2348
|
var cached;
|
|
1183
2349
|
function configurationDirectory(deps) {
|
|
1184
2350
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
1185
2351
|
}
|
|
1186
2352
|
function apiUrlFor(deps) {
|
|
1187
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
2353
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
1188
2354
|
}
|
|
1189
|
-
function
|
|
1190
|
-
return
|
|
2355
|
+
function hash2(value) {
|
|
2356
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
1191
2357
|
}
|
|
1192
2358
|
function recordPath(directory, generation) {
|
|
1193
|
-
return
|
|
2359
|
+
return join8(directory, `machine_${generation}.json`);
|
|
1194
2360
|
}
|
|
1195
2361
|
function storageKey(directory, generation) {
|
|
1196
|
-
return `${
|
|
2362
|
+
return `${hash2(directory)}:${generation}`;
|
|
1197
2363
|
}
|
|
1198
2364
|
function environmentContextPath(deps, clientId) {
|
|
1199
|
-
return
|
|
2365
|
+
return join8(
|
|
1200
2366
|
configurationDirectory(deps),
|
|
1201
|
-
`machine_context_${
|
|
2367
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1202
2368
|
);
|
|
1203
2369
|
}
|
|
1204
2370
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -1257,14 +2423,14 @@ function readEnvironmentContext(environment, deps) {
|
|
|
1257
2423
|
}
|
|
1258
2424
|
}
|
|
1259
2425
|
function keyringEntry(key) {
|
|
1260
|
-
let directory =
|
|
2426
|
+
let directory = dirname5(fileURLToPath3(import.meta.url));
|
|
1261
2427
|
for (let depth = 0; depth < 5; depth++) {
|
|
1262
|
-
const loader =
|
|
2428
|
+
const loader = join8(directory, "native", "keyring.cjs");
|
|
1263
2429
|
if (existsSync3(loader)) {
|
|
1264
2430
|
const module2 = require2(loader);
|
|
1265
2431
|
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1266
2432
|
}
|
|
1267
|
-
directory =
|
|
2433
|
+
directory = dirname5(directory);
|
|
1268
2434
|
}
|
|
1269
2435
|
const module = require2("@napi-rs/keyring");
|
|
1270
2436
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
@@ -1276,7 +2442,7 @@ function protectPath(path, directory) {
|
|
|
1276
2442
|
}
|
|
1277
2443
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
1278
2444
|
const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
|
|
1279
|
-
|
|
2445
|
+
execFileSync2(
|
|
1280
2446
|
"powershell.exe",
|
|
1281
2447
|
[
|
|
1282
2448
|
"-NoProfile",
|
|
@@ -1289,7 +2455,7 @@ function protectPath(path, directory) {
|
|
|
1289
2455
|
}
|
|
1290
2456
|
function ensureDirectory(directory) {
|
|
1291
2457
|
mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
1292
|
-
if (
|
|
2458
|
+
if (lstatSync4(directory).isSymbolicLink())
|
|
1293
2459
|
throw new MachineAuthError(
|
|
1294
2460
|
"unsafe_storage",
|
|
1295
2461
|
"Credential directory must not be a symbolic link."
|
|
@@ -1301,17 +2467,20 @@ function writePrivate(path, value) {
|
|
|
1301
2467
|
`, { mode: 384 });
|
|
1302
2468
|
protectPath(path, false);
|
|
1303
2469
|
}
|
|
2470
|
+
function readMachineMetadata(path) {
|
|
2471
|
+
return readPrivate(path);
|
|
2472
|
+
}
|
|
1304
2473
|
function readPrivate(path) {
|
|
1305
2474
|
let raw;
|
|
1306
2475
|
try {
|
|
1307
|
-
const stat =
|
|
2476
|
+
const stat = lstatSync4(path);
|
|
1308
2477
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1309
2478
|
throw new MachineAuthError(
|
|
1310
2479
|
"unsafe_storage",
|
|
1311
2480
|
"Machine credential files must be owner-only regular files."
|
|
1312
2481
|
);
|
|
1313
2482
|
}
|
|
1314
|
-
raw =
|
|
2483
|
+
raw = readFileSync6(path, "utf8");
|
|
1315
2484
|
} catch (error) {
|
|
1316
2485
|
if (error.code === "ENOENT") return void 0;
|
|
1317
2486
|
throw error;
|
|
@@ -1356,7 +2525,7 @@ function parseProfile(value) {
|
|
|
1356
2525
|
};
|
|
1357
2526
|
}
|
|
1358
2527
|
function readMachineProfile(deps = {}) {
|
|
1359
|
-
const value = readPrivate(
|
|
2528
|
+
const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
|
|
1360
2529
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1361
2530
|
}
|
|
1362
2531
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -1365,20 +2534,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
1365
2534
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
1366
2535
|
function networkSecretBrokerKey(deps, clientId) {
|
|
1367
2536
|
const directory = configurationDirectory(deps);
|
|
1368
|
-
const path =
|
|
2537
|
+
const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
1369
2538
|
const known = brokerKeys.get(path);
|
|
1370
2539
|
if (known) return known;
|
|
1371
2540
|
ensureDirectory(directory);
|
|
1372
2541
|
const read = () => {
|
|
1373
2542
|
try {
|
|
1374
|
-
const stat =
|
|
2543
|
+
const stat = lstatSync4(path);
|
|
1375
2544
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
1376
2545
|
throw new MachineAuthError(
|
|
1377
2546
|
"unsafe_storage",
|
|
1378
2547
|
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
1379
2548
|
true
|
|
1380
2549
|
);
|
|
1381
|
-
const value =
|
|
2550
|
+
const value = readFileSync6(path, "utf8").trim();
|
|
1382
2551
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
1383
2552
|
} catch (error) {
|
|
1384
2553
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -1406,7 +2575,7 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
1406
2575
|
} catch (error) {
|
|
1407
2576
|
if (error.code !== "EEXIST") throw error;
|
|
1408
2577
|
} finally {
|
|
1409
|
-
|
|
2578
|
+
rmSync6(staged, { force: true });
|
|
1410
2579
|
}
|
|
1411
2580
|
}
|
|
1412
2581
|
const key = read()?.key;
|
|
@@ -1439,7 +2608,7 @@ function environmentCredentials(deps) {
|
|
|
1439
2608
|
"conflicting_credentials",
|
|
1440
2609
|
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
1441
2610
|
);
|
|
1442
|
-
const generation =
|
|
2611
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
1443
2612
|
const credentials = {
|
|
1444
2613
|
clientId,
|
|
1445
2614
|
generation,
|
|
@@ -1460,12 +2629,12 @@ function environmentCredentials(deps) {
|
|
|
1460
2629
|
return {
|
|
1461
2630
|
clientId,
|
|
1462
2631
|
clientSecret,
|
|
1463
|
-
generation:
|
|
2632
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1464
2633
|
};
|
|
1465
2634
|
}
|
|
1466
2635
|
function hasMachineConfiguration(deps = {}) {
|
|
1467
2636
|
const env = deps.env ?? process.env;
|
|
1468
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(
|
|
2637
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join8(configurationDirectory(deps), PROFILE_FILE));
|
|
1469
2638
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1470
2639
|
throw new MachineAuthError(
|
|
1471
2640
|
"conflicting_credentials",
|
|
@@ -1477,6 +2646,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
1477
2646
|
}
|
|
1478
2647
|
function machineContext(deps = {}) {
|
|
1479
2648
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2649
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1480
2650
|
const environment = environmentCredentials(deps);
|
|
1481
2651
|
if (environment) {
|
|
1482
2652
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -1491,6 +2661,7 @@ function machineContext(deps = {}) {
|
|
|
1491
2661
|
return profile;
|
|
1492
2662
|
}
|
|
1493
2663
|
function cachedMachineCredential(deps = {}) {
|
|
2664
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1494
2665
|
const context = machineContext(deps);
|
|
1495
2666
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1496
2667
|
}
|
|
@@ -1499,7 +2670,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
1499
2670
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1500
2671
|
if (!generation) return false;
|
|
1501
2672
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1502
|
-
return readPrivate(
|
|
2673
|
+
return readPrivate(join8(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1503
2674
|
}
|
|
1504
2675
|
var environmentTerminal;
|
|
1505
2676
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -1563,6 +2734,7 @@ async function persistRecord(record, deps, signal) {
|
|
|
1563
2734
|
}
|
|
1564
2735
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1565
2736
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2737
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
1566
2738
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1567
2739
|
const apiUrl = apiUrlFor(deps);
|
|
1568
2740
|
const environment = environmentCredentials(deps);
|
|
@@ -1591,7 +2763,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1591
2763
|
}
|
|
1592
2764
|
}
|
|
1593
2765
|
return withFileLock(
|
|
1594
|
-
|
|
2766
|
+
join8(directory2, "credentials.lock"),
|
|
1595
2767
|
async () => {
|
|
1596
2768
|
if (machineSessionEnded(deps))
|
|
1597
2769
|
throw new MachineAuthError(
|
|
@@ -1599,7 +2771,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1599
2771
|
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1600
2772
|
true
|
|
1601
2773
|
);
|
|
1602
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
2774
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
1603
2775
|
return cached;
|
|
1604
2776
|
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
1605
2777
|
throw networkRejection.error;
|
|
@@ -1673,7 +2845,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1673
2845
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1674
2846
|
try {
|
|
1675
2847
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1676
|
-
|
|
2848
|
+
rmSync6(contextPath, { force: true });
|
|
1677
2849
|
} catch {
|
|
1678
2850
|
}
|
|
1679
2851
|
throw error;
|
|
@@ -1683,7 +2855,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1683
2855
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1684
2856
|
try {
|
|
1685
2857
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1686
|
-
|
|
2858
|
+
rmSync6(contextPath, { force: true });
|
|
1687
2859
|
} catch {
|
|
1688
2860
|
}
|
|
1689
2861
|
}
|
|
@@ -1697,7 +2869,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1697
2869
|
const expected = machineContext(deps);
|
|
1698
2870
|
const directory = configurationDirectory(deps);
|
|
1699
2871
|
return withFileLock(
|
|
1700
|
-
|
|
2872
|
+
join8(directory, "credentials.lock"),
|
|
1701
2873
|
async () => {
|
|
1702
2874
|
const profile = readMachineProfile(deps);
|
|
1703
2875
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -1712,7 +2884,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1712
2884
|
true
|
|
1713
2885
|
);
|
|
1714
2886
|
let record = await loadRecord(profile, deps, signal);
|
|
1715
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
2887
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
1716
2888
|
try {
|
|
1717
2889
|
const { tokens, identity } = await withMachineCooldown(
|
|
1718
2890
|
directory,
|
|
@@ -1747,7 +2919,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1747
2919
|
await persistRecord(record, deps, signal);
|
|
1748
2920
|
} catch (error) {
|
|
1749
2921
|
if (error instanceof MachineAuthError && error.terminal)
|
|
1750
|
-
writePrivate(
|
|
2922
|
+
writePrivate(join8(directory, "machine_terminal.json"), profile.generation);
|
|
1751
2923
|
throw error;
|
|
1752
2924
|
}
|
|
1753
2925
|
}
|
|
@@ -1776,23 +2948,29 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
|
1776
2948
|
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
1777
2949
|
});
|
|
1778
2950
|
}
|
|
2951
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
2952
|
+
ensureDirectory(directory);
|
|
2953
|
+
}
|
|
2954
|
+
function writeMachineMetadata(path, value) {
|
|
2955
|
+
writePrivate(path, value);
|
|
2956
|
+
}
|
|
1779
2957
|
|
|
1780
2958
|
// src/lib/credentials.ts
|
|
1781
2959
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
1782
|
-
var TOKEN_FILE_PATH =
|
|
1783
|
-
var REFRESH_TOKEN_PATH =
|
|
1784
|
-
var TOKEN_EXPIRES_PATH =
|
|
1785
|
-
var TERMINAL_REFRESH_PATH =
|
|
1786
|
-
var CREDENTIAL_METADATA_PATH =
|
|
1787
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
1788
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
1789
|
-
var CREDENTIAL_LOCK_PATH =
|
|
2960
|
+
var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
|
|
2961
|
+
var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
|
|
2962
|
+
var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
|
|
2963
|
+
var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
|
|
2964
|
+
var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
2965
|
+
var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
|
|
2966
|
+
var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
|
|
2967
|
+
var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
|
|
1790
2968
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
1791
2969
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
1792
2970
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
1793
2971
|
function readTrimmed(path) {
|
|
1794
2972
|
try {
|
|
1795
|
-
const value =
|
|
2973
|
+
const value = readFileSync7(path, "utf8").trim();
|
|
1796
2974
|
return value || void 0;
|
|
1797
2975
|
} catch {
|
|
1798
2976
|
return void 0;
|
|
@@ -1814,22 +2992,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
1814
2992
|
);
|
|
1815
2993
|
if (metadata.state === "legacy_broker") {
|
|
1816
2994
|
if (metadata.metadata) {
|
|
1817
|
-
const
|
|
1818
|
-
if (!
|
|
2995
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
2996
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
1819
2997
|
return void 0;
|
|
1820
2998
|
}
|
|
1821
2999
|
}
|
|
1822
3000
|
return { token: stored, source: "token_file" };
|
|
1823
3001
|
}
|
|
1824
3002
|
if (metadata.state === "invalid") return void 0;
|
|
1825
|
-
const
|
|
1826
|
-
if (!
|
|
3003
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3004
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
1827
3005
|
return void 0;
|
|
1828
3006
|
}
|
|
1829
3007
|
return { token: stored, source: "token_file" };
|
|
1830
3008
|
}
|
|
1831
3009
|
function credentialFingerprint(value) {
|
|
1832
|
-
return
|
|
3010
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
1833
3011
|
}
|
|
1834
3012
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
1835
3013
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -1849,7 +3027,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
1849
3027
|
function readBoundedCredentialJson(path) {
|
|
1850
3028
|
let raw;
|
|
1851
3029
|
try {
|
|
1852
|
-
raw =
|
|
3030
|
+
raw = readFileSync7(path, "utf8");
|
|
1853
3031
|
} catch (error) {
|
|
1854
3032
|
return error.code === "ENOENT" ? void 0 : null;
|
|
1855
3033
|
}
|
|
@@ -1922,8 +3100,8 @@ function jwtExpiresAt(token) {
|
|
|
1922
3100
|
|
|
1923
3101
|
// src/daemon/client-instance-id.ts
|
|
1924
3102
|
import { randomBytes as randomBytes4 } from "crypto";
|
|
1925
|
-
import { chmodSync as chmodSync2, lstatSync as
|
|
1926
|
-
import { join as
|
|
3103
|
+
import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync8 } from "fs";
|
|
3104
|
+
import { join as join10 } from "path";
|
|
1927
3105
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
1928
3106
|
var INSTANCE_FILE_MODE = 384;
|
|
1929
3107
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -1936,7 +3114,7 @@ function isClientInstanceId(value) {
|
|
|
1936
3114
|
}
|
|
1937
3115
|
function ensurePrivateConfigDirectory(configDir) {
|
|
1938
3116
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
1939
|
-
const metadata =
|
|
3117
|
+
const metadata = lstatSync5(configDir);
|
|
1940
3118
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
1941
3119
|
throw new Error("prim config path must be a private directory");
|
|
1942
3120
|
}
|
|
@@ -1946,7 +3124,7 @@ function ensurePrivateConfigDirectory(configDir) {
|
|
|
1946
3124
|
function readExisting(path) {
|
|
1947
3125
|
let metadata;
|
|
1948
3126
|
try {
|
|
1949
|
-
metadata =
|
|
3127
|
+
metadata = lstatSync5(path);
|
|
1950
3128
|
} catch (error) {
|
|
1951
3129
|
if (error.code === "ENOENT") {
|
|
1952
3130
|
return;
|
|
@@ -1960,7 +3138,7 @@ function readExisting(path) {
|
|
|
1960
3138
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
1961
3139
|
throw new Error("stored client instance identity is invalid");
|
|
1962
3140
|
}
|
|
1963
|
-
const raw =
|
|
3141
|
+
const raw = readFileSync8(path, "utf8");
|
|
1964
3142
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
1965
3143
|
if (raw !== value && raw !== `${value}
|
|
1966
3144
|
` || !isClientInstanceId(value)) {
|
|
@@ -1974,8 +3152,8 @@ function atomicWrite(path, value) {
|
|
|
1974
3152
|
}
|
|
1975
3153
|
async function getOrCreateClientInstanceId(options) {
|
|
1976
3154
|
const configDir = options.configDir;
|
|
1977
|
-
const path =
|
|
1978
|
-
const lockPath =
|
|
3155
|
+
const path = join10(configDir, "client_instance_id");
|
|
3156
|
+
const lockPath = join10(configDir, "client-instance.lock");
|
|
1979
3157
|
ensurePrivateConfigDirectory(configDir);
|
|
1980
3158
|
return withFileLock(
|
|
1981
3159
|
lockPath,
|
|
@@ -2019,59 +3197,18 @@ async function ingestUploaderHeaders() {
|
|
|
2019
3197
|
return headers;
|
|
2020
3198
|
}
|
|
2021
3199
|
|
|
2022
|
-
// src/lib/terminal-safe.ts
|
|
2023
|
-
function replaceIsolatedSurrogates(value) {
|
|
2024
|
-
let out = "";
|
|
2025
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
2026
|
-
const unit = value.charCodeAt(index);
|
|
2027
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
2028
|
-
const next = value.charCodeAt(index + 1);
|
|
2029
|
-
if (next >= 56320 && next <= 57343) {
|
|
2030
|
-
out += value[index] + value[index + 1];
|
|
2031
|
-
index += 1;
|
|
2032
|
-
} else {
|
|
2033
|
-
out += "\uFFFD";
|
|
2034
|
-
}
|
|
2035
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
2036
|
-
out += "\uFFFD";
|
|
2037
|
-
} else {
|
|
2038
|
-
out += value[index];
|
|
2039
|
-
}
|
|
2040
|
-
}
|
|
2041
|
-
return out;
|
|
2042
|
-
}
|
|
2043
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
2044
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
2045
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
2046
|
-
point === 1564 || // Arabic letter mark
|
|
2047
|
-
point === 6158 || // Mongolian vowel separator
|
|
2048
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
2049
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
2050
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
2051
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
2052
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
2053
|
-
point >= 917504 && point <= 917631;
|
|
2054
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
2055
|
-
}
|
|
2056
|
-
function terminalSafeText(value) {
|
|
2057
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
2058
|
-
}
|
|
2059
|
-
function terminalSafeLine(value) {
|
|
2060
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2061
|
-
}
|
|
2062
|
-
|
|
2063
3200
|
// src/client.ts
|
|
2064
3201
|
var CONFIG_DIR_MODE = 448;
|
|
2065
3202
|
var CREDENTIAL_FILE_MODE = 384;
|
|
2066
3203
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
2067
|
-
var
|
|
3204
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
2068
3205
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
2069
3206
|
function authExpiredMessage() {
|
|
2070
3207
|
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
2071
3208
|
}
|
|
2072
3209
|
function readTrimmed2(path) {
|
|
2073
3210
|
try {
|
|
2074
|
-
const value =
|
|
3211
|
+
const value = readFileSync9(path, "utf8").trim();
|
|
2075
3212
|
return value || void 0;
|
|
2076
3213
|
} catch {
|
|
2077
3214
|
return void 0;
|
|
@@ -2081,13 +3218,13 @@ function getSiteUrl() {
|
|
|
2081
3218
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
2082
3219
|
}
|
|
2083
3220
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
2084
|
-
return primApiUrl?.trim() ||
|
|
3221
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
2085
3222
|
}
|
|
2086
3223
|
function expiresAtFor(token, expiresIn) {
|
|
2087
3224
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
2088
3225
|
}
|
|
2089
3226
|
function ensureConfigDirectory() {
|
|
2090
|
-
const directory =
|
|
3227
|
+
const directory = dirname6(TOKEN_FILE_PATH);
|
|
2091
3228
|
mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
2092
3229
|
chmodSync3(directory, CONFIG_DIR_MODE);
|
|
2093
3230
|
}
|
|
@@ -2097,7 +3234,7 @@ function atomicWrite2(path, content) {
|
|
|
2097
3234
|
}
|
|
2098
3235
|
function removeCredentialFile(path) {
|
|
2099
3236
|
if (!existsSync4(path)) return false;
|
|
2100
|
-
|
|
3237
|
+
rmSync7(path, { force: true });
|
|
2101
3238
|
return true;
|
|
2102
3239
|
}
|
|
2103
3240
|
function getTokenExpiresAt() {
|
|
@@ -2112,23 +3249,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
2112
3249
|
const expiresAt = getTokenExpiresAt();
|
|
2113
3250
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
2114
3251
|
}
|
|
2115
|
-
function refreshFingerprint(
|
|
2116
|
-
return
|
|
3252
|
+
function refreshFingerprint(refreshToken3) {
|
|
3253
|
+
return createHash7("sha256").update(refreshToken3).digest("hex");
|
|
2117
3254
|
}
|
|
2118
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
3255
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
2119
3256
|
return {
|
|
2120
3257
|
version: 1,
|
|
2121
3258
|
family: "legacy_broker",
|
|
2122
3259
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2123
|
-
refreshTokenHash: refreshFingerprint(
|
|
3260
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2124
3261
|
};
|
|
2125
3262
|
}
|
|
2126
|
-
function credentialFamilyMetadata(accessToken,
|
|
3263
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
2127
3264
|
const hashes = {
|
|
2128
3265
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2129
|
-
refreshTokenHash: refreshFingerprint(
|
|
3266
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2130
3267
|
};
|
|
2131
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
3268
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
2132
3269
|
}
|
|
2133
3270
|
function writeCredentialMigrationSentinel() {
|
|
2134
3271
|
atomicWrite2(
|
|
@@ -2140,11 +3277,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
2140
3277
|
`
|
|
2141
3278
|
);
|
|
2142
3279
|
}
|
|
2143
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
2144
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
3280
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
3281
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
2145
3282
|
return { state: "invalid" };
|
|
2146
3283
|
}
|
|
2147
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
3284
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2148
3285
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
2149
3286
|
return { state: "invalid" };
|
|
2150
3287
|
}
|
|
@@ -2161,17 +3298,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
2161
3298
|
const metadata = readStoredCredentialMetadata();
|
|
2162
3299
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
2163
3300
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
2164
|
-
const
|
|
2165
|
-
if (!(accessToken &&
|
|
2166
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
3301
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
3302
|
+
if (!(accessToken && refreshToken3)) return;
|
|
3303
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2167
3304
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2168
3305
|
`);
|
|
2169
3306
|
}
|
|
2170
3307
|
function terminalFingerprint() {
|
|
2171
3308
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
2172
3309
|
}
|
|
2173
|
-
function writeTerminalFingerprint(
|
|
2174
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
3310
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
3311
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
2175
3312
|
`);
|
|
2176
3313
|
}
|
|
2177
3314
|
function clearTerminalFingerprint() {
|
|
@@ -2180,20 +3317,20 @@ function clearTerminalFingerprint() {
|
|
|
2180
3317
|
function isSessionEnded() {
|
|
2181
3318
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
2182
3319
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
2183
|
-
const
|
|
3320
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
2184
3321
|
const ended = terminalFingerprint();
|
|
2185
|
-
return Boolean(
|
|
3322
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
2186
3323
|
}
|
|
2187
3324
|
function withCredentialLock(operation, options = {}) {
|
|
2188
3325
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
2189
3326
|
}
|
|
2190
3327
|
function commitCredentialsUnlocked(credentials) {
|
|
2191
3328
|
const accessToken = credentials.accessToken.trim();
|
|
2192
|
-
const
|
|
2193
|
-
if (!accessToken || !
|
|
3329
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
3330
|
+
if (!accessToken || !refreshToken3) {
|
|
2194
3331
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
2195
3332
|
}
|
|
2196
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
3333
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
2197
3334
|
if (credentials.metadata !== void 0) {
|
|
2198
3335
|
preserveMarkerlessLegacyGeneration();
|
|
2199
3336
|
writeCredentialMigrationSentinel();
|
|
@@ -2201,10 +3338,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
2201
3338
|
`);
|
|
2202
3339
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
2203
3340
|
`);
|
|
2204
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
3341
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2205
3342
|
`);
|
|
2206
3343
|
} else {
|
|
2207
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
3344
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2208
3345
|
`);
|
|
2209
3346
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2210
3347
|
`);
|
|
@@ -2241,15 +3378,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
2241
3378
|
`
|
|
2242
3379
|
);
|
|
2243
3380
|
}
|
|
2244
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
3381
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
2245
3382
|
const current = readStoredCredentialMetadata();
|
|
2246
3383
|
if (expected.state === "legacy_broker") {
|
|
2247
3384
|
if (current.state !== "legacy_broker") return false;
|
|
2248
3385
|
if (!expected.metadata) return current.metadata === void 0;
|
|
2249
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
3386
|
+
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
2250
3387
|
}
|
|
2251
3388
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
2252
|
-
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
3389
|
+
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
2253
3390
|
}
|
|
2254
3391
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
2255
3392
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -2418,7 +3555,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
2418
3555
|
);
|
|
2419
3556
|
}
|
|
2420
3557
|
var _refreshInFlight;
|
|
2421
|
-
function
|
|
3558
|
+
function refreshToken2(options = {}) {
|
|
2422
3559
|
if (hasMachineConfiguration())
|
|
2423
3560
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
2424
3561
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -2556,7 +3693,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2556
3693
|
if (response.status === 401)
|
|
2557
3694
|
throw new HttpError(
|
|
2558
3695
|
401,
|
|
2559
|
-
selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
3696
|
+
selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
2560
3697
|
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
2561
3698
|
)
|
|
2562
3699
|
);
|
|
@@ -2577,7 +3714,7 @@ async function request2(method, path, body, options) {
|
|
|
2577
3714
|
let refreshAttempted = false;
|
|
2578
3715
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
2579
3716
|
refreshAttempted = true;
|
|
2580
|
-
const token = await
|
|
3717
|
+
const token = await refreshToken2({
|
|
2581
3718
|
signal: options?.signal,
|
|
2582
3719
|
quiet: options?.quietRefresh
|
|
2583
3720
|
});
|
|
@@ -2596,7 +3733,7 @@ async function request2(method, path, body, options) {
|
|
|
2596
3733
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
2597
3734
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
2598
3735
|
refreshAttempted = true;
|
|
2599
|
-
retryToken = await
|
|
3736
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
2600
3737
|
}
|
|
2601
3738
|
if (retryToken) {
|
|
2602
3739
|
_cachedCredential = {
|
|
@@ -2616,13 +3753,13 @@ function getClient() {
|
|
|
2616
3753
|
}
|
|
2617
3754
|
|
|
2618
3755
|
// src/daemon/principal.ts
|
|
2619
|
-
import { createHash as
|
|
3756
|
+
import { createHash as createHash8 } from "crypto";
|
|
2620
3757
|
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
2621
3758
|
function boundedClaim(value) {
|
|
2622
3759
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
2623
3760
|
}
|
|
2624
3761
|
function sha256(value) {
|
|
2625
|
-
return
|
|
3762
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
2626
3763
|
}
|
|
2627
3764
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
2628
3765
|
if (hasMachineConfiguration()) {
|
|
@@ -2673,8 +3810,8 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
2673
3810
|
|
|
2674
3811
|
// src/daemon/client.ts
|
|
2675
3812
|
import { createConnection } from "net";
|
|
2676
|
-
import { join as
|
|
2677
|
-
var SOCK_PATH =
|
|
3813
|
+
import { join as join12 } from "path";
|
|
3814
|
+
var SOCK_PATH = join12(primConfigDirectory(), "sock");
|
|
2678
3815
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
2679
3816
|
var nextRequestId = 1;
|
|
2680
3817
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -2791,213 +3928,20 @@ async function daemonOrDirectGet(method, path, client, timeoutMs = DAEMON_HTTP_T
|
|
|
2791
3928
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
2792
3929
|
import { existsSync as existsSync6, readFileSync as readFileSync11 } from "fs";
|
|
2793
3930
|
import { homedir as homedir2 } from "os";
|
|
2794
|
-
import { join as
|
|
3931
|
+
import { join as join14 } from "path";
|
|
2795
3932
|
|
|
2796
3933
|
// src/lib/cloud-prepared.ts
|
|
2797
|
-
import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as
|
|
2798
|
-
import { join as
|
|
3934
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync8, writeFileSync as writeFileSync4 } from "fs";
|
|
3935
|
+
import { join as join13 } from "path";
|
|
2799
3936
|
|
|
2800
3937
|
// src/lib/demo-pause.ts
|
|
2801
|
-
import { execFileSync as execFileSync2 } from "child_process";
|
|
2802
|
-
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
2803
|
-
|
|
2804
|
-
// src/lib/git.ts
|
|
2805
3938
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
2806
|
-
|
|
2807
|
-
import { lstatSync as lstatSync5, readFileSync as readFileSync10, realpathSync } from "fs";
|
|
2808
|
-
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, join as join12, relative, resolve as resolve2, sep } from "path";
|
|
2809
|
-
var GIT_TIMEOUT_MS = 1e3;
|
|
2810
|
-
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
2811
|
-
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
2812
|
-
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
2813
|
-
function gitToplevel(cwd) {
|
|
2814
|
-
try {
|
|
2815
|
-
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
2816
|
-
cwd,
|
|
2817
|
-
encoding: "utf-8",
|
|
2818
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
2819
|
-
timeout: GIT_TIMEOUT_MS
|
|
2820
|
-
}).trim();
|
|
2821
|
-
} catch {
|
|
2822
|
-
return null;
|
|
2823
|
-
}
|
|
2824
|
-
}
|
|
2825
|
-
function gitValue(cwd, args) {
|
|
2826
|
-
try {
|
|
2827
|
-
const value = execFileSync3("git", args, {
|
|
2828
|
-
cwd,
|
|
2829
|
-
encoding: "utf-8",
|
|
2830
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
2831
|
-
timeout: GIT_TIMEOUT_MS
|
|
2832
|
-
}).trim();
|
|
2833
|
-
return value || void 0;
|
|
2834
|
-
} catch {
|
|
2835
|
-
return void 0;
|
|
2836
|
-
}
|
|
2837
|
-
}
|
|
2838
|
-
function currentBranch(cwd) {
|
|
2839
|
-
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
2840
|
-
}
|
|
2841
|
-
function parseGithubRepositoryName(path) {
|
|
2842
|
-
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
2843
|
-
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
2844
|
-
return null;
|
|
2845
|
-
}
|
|
2846
|
-
return `${parts[0]}/${parts[1]}`;
|
|
2847
|
-
}
|
|
2848
|
-
function githubRepositoryFromRemote(remote) {
|
|
2849
|
-
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
2850
|
-
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
2851
|
-
remote
|
|
2852
|
-
);
|
|
2853
|
-
const path = match?.[1] ?? match?.[2];
|
|
2854
|
-
return path ? parseGithubRepositoryName(path) : null;
|
|
2855
|
-
}
|
|
2856
|
-
function checkoutSettingsText(repoRoot) {
|
|
2857
|
-
const path = join12(repoRoot, ".claude", "settings.json");
|
|
2858
|
-
try {
|
|
2859
|
-
if (!lstatSync5(join12(repoRoot, ".claude")).isDirectory()) return null;
|
|
2860
|
-
const stat = lstatSync5(path);
|
|
2861
|
-
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
2862
|
-
return readFileSync10(path, "utf8");
|
|
2863
|
-
} catch {
|
|
2864
|
-
return null;
|
|
2865
|
-
}
|
|
2866
|
-
}
|
|
2867
|
-
function checkoutDeclaration(repoRoot, name) {
|
|
2868
|
-
const text = checkoutSettingsText(repoRoot);
|
|
2869
|
-
if (text === null) return null;
|
|
2870
|
-
let parsed;
|
|
2871
|
-
try {
|
|
2872
|
-
parsed = JSON.parse(text);
|
|
2873
|
-
} catch {
|
|
2874
|
-
return null;
|
|
2875
|
-
}
|
|
2876
|
-
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
2877
|
-
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
2878
|
-
return typeof value === "string" ? value : null;
|
|
2879
|
-
}
|
|
2880
|
-
function declaredGithubRepository(repoRoot) {
|
|
2881
|
-
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
2882
|
-
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
2883
|
-
}
|
|
2884
|
-
function githubRepositoryFullName(cwd) {
|
|
2885
|
-
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
2886
|
-
if (remote) {
|
|
2887
|
-
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
2888
|
-
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
2889
|
-
}
|
|
2890
|
-
const root = gitToplevel(cwd);
|
|
2891
|
-
return root ? declaredGithubRepository(root) : null;
|
|
2892
|
-
}
|
|
2893
|
-
function canonicalGitRoot(cwd) {
|
|
2894
|
-
try {
|
|
2895
|
-
const top = gitToplevel(cwd);
|
|
2896
|
-
return top ? realpathSync.native(top) : null;
|
|
2897
|
-
} catch {
|
|
2898
|
-
return null;
|
|
2899
|
-
}
|
|
2900
|
-
}
|
|
2901
|
-
function normalizeOriginRemote(remote) {
|
|
2902
|
-
const value = remote.trim();
|
|
2903
|
-
if (!value) return void 0;
|
|
2904
|
-
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
2905
|
-
if (scp?.host && scp.path) {
|
|
2906
|
-
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
2907
|
-
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
2908
|
-
}
|
|
2909
|
-
try {
|
|
2910
|
-
const url = new URL(value);
|
|
2911
|
-
url.username = "";
|
|
2912
|
-
url.password = "";
|
|
2913
|
-
url.search = "";
|
|
2914
|
-
url.hash = "";
|
|
2915
|
-
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
2916
|
-
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
2917
|
-
return void 0;
|
|
2918
|
-
} catch {
|
|
2919
|
-
return void 0;
|
|
2920
|
-
}
|
|
2921
|
-
}
|
|
2922
|
-
function nearestExistingAncestor(path) {
|
|
2923
|
-
const suffix = [];
|
|
2924
|
-
let cursor = path;
|
|
2925
|
-
while (true) {
|
|
2926
|
-
try {
|
|
2927
|
-
lstatSync5(cursor);
|
|
2928
|
-
break;
|
|
2929
|
-
} catch (error) {
|
|
2930
|
-
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
2931
|
-
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
2932
|
-
const parent = dirname6(cursor);
|
|
2933
|
-
if (parent === cursor) return null;
|
|
2934
|
-
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
2935
|
-
cursor = parent;
|
|
2936
|
-
}
|
|
2937
|
-
}
|
|
2938
|
-
try {
|
|
2939
|
-
return { real: realpathSync.native(cursor), suffix };
|
|
2940
|
-
} catch {
|
|
2941
|
-
return null;
|
|
2942
|
-
}
|
|
2943
|
-
}
|
|
2944
|
-
function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
2945
|
-
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
2946
|
-
return { ok: false, reason: "invalid_path" };
|
|
2947
|
-
}
|
|
2948
|
-
const absolute = resolve2(baseDir, filePath);
|
|
2949
|
-
const resolved = nearestExistingAncestor(absolute);
|
|
2950
|
-
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
2951
|
-
const target = resolve2(resolved.real, ...resolved.suffix);
|
|
2952
|
-
const rel = relative(context.repoRoot, target);
|
|
2953
|
-
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
2954
|
-
if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
2955
|
-
return { ok: false, reason: "outside_repository" };
|
|
2956
|
-
}
|
|
2957
|
-
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
2958
|
-
}
|
|
2959
|
-
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
|
|
2960
|
-
if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
2961
|
-
return null;
|
|
2962
|
-
const absolute = resolve2(cwd, filePath);
|
|
2963
|
-
let target;
|
|
2964
|
-
try {
|
|
2965
|
-
const stat = lstatSync5(absolute);
|
|
2966
|
-
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
2967
|
-
target = realpathSync.native(absolute);
|
|
2968
|
-
} catch (error) {
|
|
2969
|
-
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
2970
|
-
return null;
|
|
2971
|
-
}
|
|
2972
|
-
try {
|
|
2973
|
-
const parent = realpathSync.native(dirname6(absolute));
|
|
2974
|
-
if (!lstatSync5(parent).isDirectory()) return null;
|
|
2975
|
-
target = resolve2(parent, basename2(absolute));
|
|
2976
|
-
} catch {
|
|
2977
|
-
return null;
|
|
2978
|
-
}
|
|
2979
|
-
}
|
|
2980
|
-
const rel = relative(repositoryRoot, target);
|
|
2981
|
-
if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
2982
|
-
return null;
|
|
2983
|
-
}
|
|
2984
|
-
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
2985
|
-
}
|
|
2986
|
-
function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
2987
|
-
if (typeof contextOrCwd === "string") {
|
|
2988
|
-
return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
|
|
2989
|
-
}
|
|
2990
|
-
return canonicalRepositoryPathScoped(
|
|
2991
|
-
filePath,
|
|
2992
|
-
contextOrCwd,
|
|
2993
|
-
baseDirOrRoot ?? contextOrCwd.repoRoot
|
|
2994
|
-
);
|
|
2995
|
-
}
|
|
3939
|
+
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
2996
3940
|
|
|
2997
3941
|
// src/lib/activation.ts
|
|
2998
3942
|
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
2999
3943
|
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
3000
|
-
var
|
|
3944
|
+
var GIT_TIMEOUT_MS3 = 1e3;
|
|
3001
3945
|
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
3002
3946
|
function isValidRepoSyncId(value) {
|
|
3003
3947
|
return typeof value === "string" && REPO_SYNC_ID_RE.test(value);
|
|
@@ -3008,7 +3952,7 @@ function localGitConfigValue(cwd, key) {
|
|
|
3008
3952
|
cwd,
|
|
3009
3953
|
encoding: "utf-8",
|
|
3010
3954
|
stdio: ["ignore", "pipe", "ignore"],
|
|
3011
|
-
timeout:
|
|
3955
|
+
timeout: GIT_TIMEOUT_MS3
|
|
3012
3956
|
}).trim();
|
|
3013
3957
|
return value || void 0;
|
|
3014
3958
|
} catch {
|