@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
|
@@ -27417,6 +27417,8 @@ function isClaudeCloudSession(env = process.env) {
|
|
|
27417
27417
|
}
|
|
27418
27418
|
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';
|
|
27419
27419
|
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';
|
|
27420
|
+
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}.`;
|
|
27421
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
27420
27422
|
function cloudSetupPointer(message, env = process.env) {
|
|
27421
27423
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
27422
27424
|
}
|
|
@@ -27435,13 +27437,20 @@ var GIT_TIMEOUT_MS = 1e3;
|
|
|
27435
27437
|
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
27436
27438
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
27437
27439
|
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
27440
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
27441
|
+
function gitChildEnvironment(env = process.env) {
|
|
27442
|
+
return Object.fromEntries(
|
|
27443
|
+
Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
|
|
27444
|
+
);
|
|
27445
|
+
}
|
|
27438
27446
|
function gitToplevel(cwd) {
|
|
27439
27447
|
try {
|
|
27440
27448
|
return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
|
|
27441
27449
|
cwd,
|
|
27442
27450
|
encoding: "utf-8",
|
|
27443
27451
|
stdio: ["ignore", "pipe", "ignore"],
|
|
27444
|
-
timeout: GIT_TIMEOUT_MS
|
|
27452
|
+
timeout: GIT_TIMEOUT_MS,
|
|
27453
|
+
env: gitChildEnvironment()
|
|
27445
27454
|
}).trim();
|
|
27446
27455
|
} catch {
|
|
27447
27456
|
return null;
|
|
@@ -27453,7 +27462,8 @@ function gitValue(cwd, args) {
|
|
|
27453
27462
|
cwd,
|
|
27454
27463
|
encoding: "utf-8",
|
|
27455
27464
|
stdio: ["ignore", "pipe", "ignore"],
|
|
27456
|
-
timeout: GIT_TIMEOUT_MS
|
|
27465
|
+
timeout: GIT_TIMEOUT_MS,
|
|
27466
|
+
env: gitChildEnvironment()
|
|
27457
27467
|
}).trim();
|
|
27458
27468
|
return value || void 0;
|
|
27459
27469
|
} catch {
|
|
@@ -27786,18 +27796,18 @@ function publicDecisionResponse(value) {
|
|
|
27786
27796
|
}
|
|
27787
27797
|
|
|
27788
27798
|
// src/client.ts
|
|
27789
|
-
import { createHash as
|
|
27790
|
-
import { chmodSync as chmodSync4, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as
|
|
27799
|
+
import { createHash as createHash9 } from "crypto";
|
|
27800
|
+
import { chmodSync as chmodSync4, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync9 } from "fs";
|
|
27791
27801
|
import { dirname as dirname8 } from "path";
|
|
27792
27802
|
|
|
27793
27803
|
// src/lib/credentials.ts
|
|
27794
|
-
import { createHash as
|
|
27804
|
+
import { createHash as createHash8 } from "crypto";
|
|
27795
27805
|
import { readFileSync as readFileSync11 } from "fs";
|
|
27796
|
-
import { join as
|
|
27806
|
+
import { join as join15 } from "path";
|
|
27797
27807
|
|
|
27798
27808
|
// src/lib/machine-credentials.ts
|
|
27799
27809
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
27800
|
-
import { createHash as
|
|
27810
|
+
import { createHash as createHash7, randomBytes as randomBytes4, randomUUID as randomUUID3 } from "crypto";
|
|
27801
27811
|
import {
|
|
27802
27812
|
chmodSync as chmodSync2,
|
|
27803
27813
|
existsSync as existsSync10,
|
|
@@ -27805,11 +27815,11 @@ import {
|
|
|
27805
27815
|
lstatSync as lstatSync6,
|
|
27806
27816
|
mkdirSync as mkdirSync5,
|
|
27807
27817
|
readFileSync as readFileSync10,
|
|
27808
|
-
rmSync as
|
|
27818
|
+
rmSync as rmSync8,
|
|
27809
27819
|
writeFileSync as writeFileSync5
|
|
27810
27820
|
} from "fs";
|
|
27811
27821
|
import { createRequire as createRequire2 } from "module";
|
|
27812
|
-
import { dirname as dirname7, join as
|
|
27822
|
+
import { dirname as dirname7, join as join14 } from "path";
|
|
27813
27823
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
27814
27824
|
|
|
27815
27825
|
// src/lib/machine-broker.ts
|
|
@@ -27986,10 +27996,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
27986
27996
|
"access_token",
|
|
27987
27997
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
27988
27998
|
);
|
|
27989
|
-
const
|
|
27999
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
27990
28000
|
return {
|
|
27991
28001
|
accessToken,
|
|
27992
|
-
refreshToken:
|
|
28002
|
+
refreshToken: refreshToken3,
|
|
27993
28003
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
27994
28004
|
};
|
|
27995
28005
|
}
|
|
@@ -28564,32 +28574,995 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
28564
28574
|
}
|
|
28565
28575
|
}
|
|
28566
28576
|
|
|
28577
|
+
// src/lib/session-identity.ts
|
|
28578
|
+
import { execFile } from "child_process";
|
|
28579
|
+
import { createHash as createHash6 } from "crypto";
|
|
28580
|
+
import { rmSync as rmSync7 } from "fs";
|
|
28581
|
+
import { join as join13 } from "path";
|
|
28582
|
+
import { promisify } from "util";
|
|
28583
|
+
|
|
28584
|
+
// src/lib/terminal-safe.ts
|
|
28585
|
+
function replaceIsolatedSurrogates(value) {
|
|
28586
|
+
let out = "";
|
|
28587
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
28588
|
+
const unit = value.charCodeAt(index);
|
|
28589
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
28590
|
+
const next = value.charCodeAt(index + 1);
|
|
28591
|
+
if (next >= 56320 && next <= 57343) {
|
|
28592
|
+
out += value[index] + value[index + 1];
|
|
28593
|
+
index += 1;
|
|
28594
|
+
} else {
|
|
28595
|
+
out += "\uFFFD";
|
|
28596
|
+
}
|
|
28597
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
28598
|
+
out += "\uFFFD";
|
|
28599
|
+
} else {
|
|
28600
|
+
out += value[index];
|
|
28601
|
+
}
|
|
28602
|
+
}
|
|
28603
|
+
return out;
|
|
28604
|
+
}
|
|
28605
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
28606
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
28607
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
28608
|
+
point === 1564 || // Arabic letter mark
|
|
28609
|
+
point === 6158 || // Mongolian vowel separator
|
|
28610
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
28611
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
28612
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
28613
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
28614
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
28615
|
+
point >= 917504 && point <= 917631;
|
|
28616
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
28617
|
+
}
|
|
28618
|
+
function terminalSafeText(value) {
|
|
28619
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
28620
|
+
}
|
|
28621
|
+
function terminalSafeLine(value) {
|
|
28622
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
28623
|
+
}
|
|
28624
|
+
|
|
28625
|
+
// src/lib/session-identity.ts
|
|
28626
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
28627
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
28628
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
28629
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
28630
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
28631
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
28632
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
28633
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
28634
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
28635
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
28636
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
28637
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
28638
|
+
token: "/api/cli/session-identity/token",
|
|
28639
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
28640
|
+
link: "/api/cli/session-identity/link"
|
|
28641
|
+
};
|
|
28642
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
28643
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
28644
|
+
var GIT_TIMEOUT_MS3 = 1e4;
|
|
28645
|
+
var POLL_BUDGET_MS = 15e3;
|
|
28646
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
28647
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
28648
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
28649
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
28650
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
28651
|
+
function sessionIdentityRequested(env = process.env) {
|
|
28652
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
28653
|
+
}
|
|
28654
|
+
function sessionIdentityMode(deps = {}) {
|
|
28655
|
+
const env = deps.env ?? process.env;
|
|
28656
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
28657
|
+
}
|
|
28658
|
+
function failure(code, cause, remedy) {
|
|
28659
|
+
return { status: "failed", code, cause, remedy };
|
|
28660
|
+
}
|
|
28661
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
28662
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
28663
|
+
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';
|
|
28664
|
+
var SESSION_REVOKED = failure(
|
|
28665
|
+
"session_revoked",
|
|
28666
|
+
"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",
|
|
28667
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
28668
|
+
);
|
|
28669
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
28670
|
+
"challenge_expired",
|
|
28671
|
+
"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)",
|
|
28672
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
28673
|
+
);
|
|
28674
|
+
var CHALLENGE_GONE = failure(
|
|
28675
|
+
"challenge_not_found",
|
|
28676
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
28677
|
+
NEW_SESSION_REMEDY
|
|
28678
|
+
);
|
|
28679
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
28680
|
+
function rejectionFailure(reason, repository) {
|
|
28681
|
+
switch (reason) {
|
|
28682
|
+
case "identity_mismatch":
|
|
28683
|
+
return failure(
|
|
28684
|
+
"identity_mismatch",
|
|
28685
|
+
"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",
|
|
28686
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
28687
|
+
);
|
|
28688
|
+
case "push_after_expiry":
|
|
28689
|
+
return failure(
|
|
28690
|
+
"push_after_expiry",
|
|
28691
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
28692
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
28693
|
+
);
|
|
28694
|
+
case "repository_mismatch":
|
|
28695
|
+
return failure(
|
|
28696
|
+
"repository_mismatch",
|
|
28697
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
28698
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
28699
|
+
);
|
|
28700
|
+
case "conflicting_push":
|
|
28701
|
+
return failure(
|
|
28702
|
+
"conflicting_push",
|
|
28703
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
28704
|
+
NEW_SESSION_REMEDY
|
|
28705
|
+
);
|
|
28706
|
+
case "unsupported_sender":
|
|
28707
|
+
return failure(
|
|
28708
|
+
"unsupported_sender",
|
|
28709
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
28710
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
28711
|
+
);
|
|
28712
|
+
default:
|
|
28713
|
+
return failure(
|
|
28714
|
+
"challenge_rejected",
|
|
28715
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
28716
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
28717
|
+
);
|
|
28718
|
+
}
|
|
28719
|
+
}
|
|
28720
|
+
function sessionIdentityMessage(outcome) {
|
|
28721
|
+
if (outcome.status === "link_required")
|
|
28722
|
+
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.`;
|
|
28723
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
28724
|
+
}
|
|
28725
|
+
function hash(value) {
|
|
28726
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
28727
|
+
}
|
|
28728
|
+
function sessionContext(deps) {
|
|
28729
|
+
const env = deps.env ?? process.env;
|
|
28730
|
+
const environment = environmentCredentials(deps);
|
|
28731
|
+
if (!environment)
|
|
28732
|
+
return failure(
|
|
28733
|
+
"environment_credential_missing",
|
|
28734
|
+
"the cloud environment has no environment credential",
|
|
28735
|
+
'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'
|
|
28736
|
+
);
|
|
28737
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
28738
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
28739
|
+
return failure(
|
|
28740
|
+
"session_id_missing",
|
|
28741
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
28742
|
+
NEW_SESSION_REMEDY
|
|
28743
|
+
);
|
|
28744
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
28745
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
28746
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
28747
|
+
return {
|
|
28748
|
+
directory,
|
|
28749
|
+
apiUrl,
|
|
28750
|
+
clientId: environment.clientId,
|
|
28751
|
+
generation: environment.generation,
|
|
28752
|
+
sessionId,
|
|
28753
|
+
tokenPath: join13(directory, `session_identity_${key}.json`),
|
|
28754
|
+
statePath: join13(directory, `session_identity_${key}.state.json`),
|
|
28755
|
+
lockPath: join13(directory, "session-identity.lock")
|
|
28756
|
+
};
|
|
28757
|
+
}
|
|
28758
|
+
function readRecord(path) {
|
|
28759
|
+
try {
|
|
28760
|
+
const value = readMachineMetadata(path);
|
|
28761
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
28762
|
+
} catch {
|
|
28763
|
+
return void 0;
|
|
28764
|
+
}
|
|
28765
|
+
}
|
|
28766
|
+
function finiteNumber(value) {
|
|
28767
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
28768
|
+
}
|
|
28769
|
+
function readToken(context) {
|
|
28770
|
+
const data = readRecord(context.tokenPath);
|
|
28771
|
+
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))
|
|
28772
|
+
return void 0;
|
|
28773
|
+
const identity = data.identity;
|
|
28774
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
28775
|
+
return void 0;
|
|
28776
|
+
return data;
|
|
28777
|
+
}
|
|
28778
|
+
function readState(context) {
|
|
28779
|
+
const data = readRecord(context.statePath);
|
|
28780
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
28781
|
+
return void 0;
|
|
28782
|
+
return data;
|
|
28783
|
+
}
|
|
28784
|
+
function writeToken(context, record) {
|
|
28785
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
28786
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
28787
|
+
rmSync7(context.statePath, { force: true });
|
|
28788
|
+
}
|
|
28789
|
+
function writeState(context, state) {
|
|
28790
|
+
try {
|
|
28791
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
28792
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
28793
|
+
} catch {
|
|
28794
|
+
}
|
|
28795
|
+
}
|
|
28796
|
+
function tokenValid(record, now = Date.now()) {
|
|
28797
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
28798
|
+
}
|
|
28799
|
+
function tokenFresh(record, now = Date.now()) {
|
|
28800
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
28801
|
+
}
|
|
28802
|
+
function toCredential(record) {
|
|
28803
|
+
return {
|
|
28804
|
+
issuer: record.issuer,
|
|
28805
|
+
audience: record.audience,
|
|
28806
|
+
...record.identity,
|
|
28807
|
+
accessToken: record.accessToken,
|
|
28808
|
+
expiresAt: record.expiresAt,
|
|
28809
|
+
apiUrl: record.apiUrl,
|
|
28810
|
+
generation: record.generation,
|
|
28811
|
+
storage: "environment",
|
|
28812
|
+
session: {
|
|
28813
|
+
userId: record.userId,
|
|
28814
|
+
displayName: record.displayName,
|
|
28815
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
28816
|
+
refreshAfter: record.refreshAfter
|
|
28817
|
+
}
|
|
28818
|
+
};
|
|
28819
|
+
}
|
|
28820
|
+
function identified(record, reused) {
|
|
28821
|
+
return {
|
|
28822
|
+
status: "ok",
|
|
28823
|
+
credential: toCredential(record),
|
|
28824
|
+
displayName: record.displayName,
|
|
28825
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
28826
|
+
reused
|
|
28827
|
+
};
|
|
28828
|
+
}
|
|
28829
|
+
function cachedSessionCredential(deps = {}) {
|
|
28830
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
28831
|
+
let context;
|
|
28832
|
+
try {
|
|
28833
|
+
context = sessionContext(deps);
|
|
28834
|
+
} catch {
|
|
28835
|
+
return void 0;
|
|
28836
|
+
}
|
|
28837
|
+
if ("status" in context) return void 0;
|
|
28838
|
+
const record = readToken(context);
|
|
28839
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
28840
|
+
}
|
|
28841
|
+
function outcomeFromState(state) {
|
|
28842
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
28843
|
+
return {
|
|
28844
|
+
status: "link_required",
|
|
28845
|
+
githubLogin: state.githubLogin,
|
|
28846
|
+
challengeId: state.challengeId,
|
|
28847
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
28848
|
+
};
|
|
28849
|
+
return failure(
|
|
28850
|
+
state.code,
|
|
28851
|
+
state.cause ?? "the last identity check failed",
|
|
28852
|
+
state.remedy ?? RETRY_REMEDY
|
|
28853
|
+
);
|
|
28854
|
+
}
|
|
28855
|
+
function parseInstant(value) {
|
|
28856
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
28857
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
28858
|
+
const parsed = Date.parse(value);
|
|
28859
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
28860
|
+
}
|
|
28861
|
+
return void 0;
|
|
28862
|
+
}
|
|
28863
|
+
async function sendJson(url, init, fetchImpl) {
|
|
28864
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
28865
|
+
let value;
|
|
28866
|
+
try {
|
|
28867
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
28868
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
28869
|
+
} catch {
|
|
28870
|
+
value = void 0;
|
|
28871
|
+
}
|
|
28872
|
+
return { status: response.status, value };
|
|
28873
|
+
}
|
|
28874
|
+
function environmentOnly(deps) {
|
|
28875
|
+
return { ...deps, environmentOnly: true };
|
|
28876
|
+
}
|
|
28877
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
28878
|
+
const send = async (credential2) => {
|
|
28879
|
+
const headers = { "Content-Type": "application/json" };
|
|
28880
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
28881
|
+
if (credential2.tokenInjection) {
|
|
28882
|
+
const response = await forwardMachineRequest(
|
|
28883
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
28884
|
+
signal,
|
|
28885
|
+
environmentOnly(deps)
|
|
28886
|
+
);
|
|
28887
|
+
const parsed = await response.json().catch(() => void 0);
|
|
28888
|
+
return {
|
|
28889
|
+
status: response.status,
|
|
28890
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
28891
|
+
};
|
|
28892
|
+
}
|
|
28893
|
+
return sendJson(
|
|
28894
|
+
`${credential2.apiUrl}${path}`,
|
|
28895
|
+
{
|
|
28896
|
+
method,
|
|
28897
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
28898
|
+
...text === void 0 ? {} : { body: text },
|
|
28899
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS3)
|
|
28900
|
+
},
|
|
28901
|
+
deps.fetch ?? fetch
|
|
28902
|
+
);
|
|
28903
|
+
};
|
|
28904
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
28905
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
28906
|
+
let answer = await send(credential);
|
|
28907
|
+
if (answer.status === 401) {
|
|
28908
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
28909
|
+
if (!credential)
|
|
28910
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
28911
|
+
answer = await send(credential);
|
|
28912
|
+
}
|
|
28913
|
+
return answer;
|
|
28914
|
+
}
|
|
28915
|
+
function environmentFailure(error, apiUrl) {
|
|
28916
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
28917
|
+
return failure(
|
|
28918
|
+
"environment_credential_rejected",
|
|
28919
|
+
"Primitive rejected the cloud environment's credential",
|
|
28920
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
28921
|
+
);
|
|
28922
|
+
const host = (() => {
|
|
28923
|
+
try {
|
|
28924
|
+
return new URL(apiUrl).hostname;
|
|
28925
|
+
} catch {
|
|
28926
|
+
return "Primitive";
|
|
28927
|
+
}
|
|
28928
|
+
})();
|
|
28929
|
+
return failure(
|
|
28930
|
+
"identity_unavailable",
|
|
28931
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
28932
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
28933
|
+
);
|
|
28934
|
+
}
|
|
28935
|
+
function answerError(answer) {
|
|
28936
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
28937
|
+
}
|
|
28938
|
+
async function git(root, args, signal) {
|
|
28939
|
+
try {
|
|
28940
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
28941
|
+
cwd: root,
|
|
28942
|
+
encoding: "utf8",
|
|
28943
|
+
timeout: GIT_TIMEOUT_MS3,
|
|
28944
|
+
signal,
|
|
28945
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
28946
|
+
maxBuffer: 1024 * 1024
|
|
28947
|
+
});
|
|
28948
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
28949
|
+
} catch (error) {
|
|
28950
|
+
const failed = error;
|
|
28951
|
+
return {
|
|
28952
|
+
ok: false,
|
|
28953
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
28954
|
+
stdout: failed.stdout ?? "",
|
|
28955
|
+
stderr: failed.stderr ?? "",
|
|
28956
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
28957
|
+
};
|
|
28958
|
+
}
|
|
28959
|
+
}
|
|
28960
|
+
function gitDetail(stderr) {
|
|
28961
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
28962
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
28963
|
+
}
|
|
28964
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
28965
|
+
await new Promise((resolve7, reject) => {
|
|
28966
|
+
const timer = setTimeout(resolve7, milliseconds);
|
|
28967
|
+
signal?.addEventListener(
|
|
28968
|
+
"abort",
|
|
28969
|
+
() => {
|
|
28970
|
+
clearTimeout(timer);
|
|
28971
|
+
reject(signal.reason);
|
|
28972
|
+
},
|
|
28973
|
+
{ once: true }
|
|
28974
|
+
);
|
|
28975
|
+
});
|
|
28976
|
+
}
|
|
28977
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
28978
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
28979
|
+
const deadline2 = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
28980
|
+
let delay2 = POLL_FIRST_DELAY_MS;
|
|
28981
|
+
let unreachable;
|
|
28982
|
+
for (; ; ) {
|
|
28983
|
+
const remaining = deadline2 - Date.now();
|
|
28984
|
+
if (remaining <= 0) break;
|
|
28985
|
+
await sleep(Math.min(delay2, remaining), signal);
|
|
28986
|
+
delay2 = Math.min(POLL_MAX_DELAY_MS, Math.round(delay2 * 1.5));
|
|
28987
|
+
let answer;
|
|
28988
|
+
try {
|
|
28989
|
+
answer = await environmentRequest(
|
|
28990
|
+
"GET",
|
|
28991
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
28992
|
+
void 0,
|
|
28993
|
+
deps,
|
|
28994
|
+
signal
|
|
28995
|
+
);
|
|
28996
|
+
} catch (error) {
|
|
28997
|
+
signal?.throwIfAborted();
|
|
28998
|
+
unreachable = error;
|
|
28999
|
+
continue;
|
|
29000
|
+
}
|
|
29001
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
29002
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29003
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
29004
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
29005
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
29006
|
+
continue;
|
|
29007
|
+
}
|
|
29008
|
+
unreachable = void 0;
|
|
29009
|
+
const status = answer.value;
|
|
29010
|
+
if (status?.status === "verified")
|
|
29011
|
+
return {
|
|
29012
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
29013
|
+
};
|
|
29014
|
+
if (status?.status === "expired")
|
|
29015
|
+
return failure(
|
|
29016
|
+
"challenge_expired",
|
|
29017
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
29018
|
+
NEW_SESSION_REMEDY
|
|
29019
|
+
);
|
|
29020
|
+
if (status?.status === "rejected")
|
|
29021
|
+
return rejectionFailure(status.reason, repository);
|
|
29022
|
+
}
|
|
29023
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
29024
|
+
return failure(
|
|
29025
|
+
"webhook_timeout",
|
|
29026
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
29027
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
29028
|
+
);
|
|
29029
|
+
}
|
|
29030
|
+
function parseTokenAnswer(value) {
|
|
29031
|
+
if (!value) return void 0;
|
|
29032
|
+
const user = value.user;
|
|
29033
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
29034
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
29035
|
+
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))
|
|
29036
|
+
return void 0;
|
|
29037
|
+
return {
|
|
29038
|
+
accessToken: value.accessToken,
|
|
29039
|
+
expiresAt,
|
|
29040
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
29041
|
+
userId: user.id,
|
|
29042
|
+
displayName: user.displayName,
|
|
29043
|
+
organizationId: value.organizationId
|
|
29044
|
+
};
|
|
29045
|
+
}
|
|
29046
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
29047
|
+
"server_contract",
|
|
29048
|
+
"Primitive's answer did not identify the linked member",
|
|
29049
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
29050
|
+
);
|
|
29051
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
29052
|
+
let identity;
|
|
29053
|
+
let environment;
|
|
29054
|
+
try {
|
|
29055
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
29056
|
+
identity = await verifyMachineIdentity(
|
|
29057
|
+
context.apiUrl,
|
|
29058
|
+
answer.accessToken,
|
|
29059
|
+
context.clientId,
|
|
29060
|
+
signal,
|
|
29061
|
+
deps.fetch
|
|
29062
|
+
);
|
|
29063
|
+
} catch (error) {
|
|
29064
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
29065
|
+
return SERVER_CONTRACT_FAILURE;
|
|
29066
|
+
return environmentFailure(error, context.apiUrl);
|
|
29067
|
+
}
|
|
29068
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
29069
|
+
return SERVER_CONTRACT_FAILURE;
|
|
29070
|
+
return {
|
|
29071
|
+
version: 1,
|
|
29072
|
+
apiUrl: context.apiUrl,
|
|
29073
|
+
clientId: context.clientId,
|
|
29074
|
+
generation: context.generation,
|
|
29075
|
+
sessionId: context.sessionId,
|
|
29076
|
+
issuer: environment.issuer,
|
|
29077
|
+
audience: environment.audience,
|
|
29078
|
+
accessToken: answer.accessToken,
|
|
29079
|
+
expiresAt: answer.expiresAt,
|
|
29080
|
+
refreshAfter: answer.refreshAfter,
|
|
29081
|
+
userId: answer.userId,
|
|
29082
|
+
displayName: answer.displayName,
|
|
29083
|
+
organizationId: answer.organizationId,
|
|
29084
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
29085
|
+
identity,
|
|
29086
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
29087
|
+
};
|
|
29088
|
+
}
|
|
29089
|
+
async function refreshToken(context, record, deps, signal) {
|
|
29090
|
+
let answer;
|
|
29091
|
+
try {
|
|
29092
|
+
answer = await environmentRequest(
|
|
29093
|
+
"POST",
|
|
29094
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
29095
|
+
{ accessToken: record.accessToken },
|
|
29096
|
+
deps,
|
|
29097
|
+
signal
|
|
29098
|
+
);
|
|
29099
|
+
} catch (error) {
|
|
29100
|
+
signal?.throwIfAborted();
|
|
29101
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
29102
|
+
}
|
|
29103
|
+
const code = answerError(answer);
|
|
29104
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
29105
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
29106
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29107
|
+
return {
|
|
29108
|
+
status: "refused",
|
|
29109
|
+
failure: environmentFailure(
|
|
29110
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
29111
|
+
context.apiUrl
|
|
29112
|
+
)
|
|
29113
|
+
};
|
|
29114
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
29115
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
29116
|
+
return { status: "unavailable" };
|
|
29117
|
+
return {
|
|
29118
|
+
status: "ok",
|
|
29119
|
+
record: {
|
|
29120
|
+
...record,
|
|
29121
|
+
accessToken: token.accessToken,
|
|
29122
|
+
expiresAt: token.expiresAt,
|
|
29123
|
+
refreshAfter: token.refreshAfter,
|
|
29124
|
+
displayName: token.displayName
|
|
29125
|
+
}
|
|
29126
|
+
};
|
|
29127
|
+
}
|
|
29128
|
+
function exchangeRefusal(answer, repository) {
|
|
29129
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
29130
|
+
if (answer.status !== 409) return void 0;
|
|
29131
|
+
switch (answerError(answer)) {
|
|
29132
|
+
case "identity_mismatch":
|
|
29133
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
29134
|
+
case "challenge_rejected":
|
|
29135
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
29136
|
+
case "challenge_expired":
|
|
29137
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
29138
|
+
case "challenge_already_exchanged":
|
|
29139
|
+
return failure(
|
|
29140
|
+
"challenge_already_exchanged",
|
|
29141
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
29142
|
+
NEW_SESSION_REMEDY
|
|
29143
|
+
);
|
|
29144
|
+
case "challenge_pending":
|
|
29145
|
+
return failure(
|
|
29146
|
+
"webhook_timeout",
|
|
29147
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
29148
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
29149
|
+
);
|
|
29150
|
+
default:
|
|
29151
|
+
return void 0;
|
|
29152
|
+
}
|
|
29153
|
+
}
|
|
29154
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
29155
|
+
let answer;
|
|
29156
|
+
try {
|
|
29157
|
+
answer = await environmentRequest(
|
|
29158
|
+
"POST",
|
|
29159
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
29160
|
+
{ challengeId: challenge.challengeId },
|
|
29161
|
+
deps,
|
|
29162
|
+
signal
|
|
29163
|
+
);
|
|
29164
|
+
} catch (error) {
|
|
29165
|
+
signal?.throwIfAborted();
|
|
29166
|
+
return environmentFailure(error, context.apiUrl);
|
|
29167
|
+
}
|
|
29168
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
29169
|
+
const login = answer.value?.githubLogin;
|
|
29170
|
+
return {
|
|
29171
|
+
status: "link_required",
|
|
29172
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
29173
|
+
challengeId: challenge.challengeId,
|
|
29174
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
29175
|
+
};
|
|
29176
|
+
}
|
|
29177
|
+
const refused = exchangeRefusal(
|
|
29178
|
+
answer,
|
|
29179
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
29180
|
+
);
|
|
29181
|
+
if (refused) return refused;
|
|
29182
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
29183
|
+
if (!token) {
|
|
29184
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29185
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
29186
|
+
return answer.status >= 500 ? environmentFailure(
|
|
29187
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
29188
|
+
context.apiUrl
|
|
29189
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
29190
|
+
}
|
|
29191
|
+
return recordFor(
|
|
29192
|
+
context,
|
|
29193
|
+
token,
|
|
29194
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
29195
|
+
deps,
|
|
29196
|
+
signal
|
|
29197
|
+
);
|
|
29198
|
+
}
|
|
29199
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
29200
|
+
const env = deps.env ?? process.env;
|
|
29201
|
+
const repository = githubRepositoryFullName(root);
|
|
29202
|
+
if (!repository)
|
|
29203
|
+
return failure(
|
|
29204
|
+
"repository_unidentified",
|
|
29205
|
+
"this checkout does not name its GitHub repository",
|
|
29206
|
+
"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"
|
|
29207
|
+
);
|
|
29208
|
+
const branch = currentBranch(root);
|
|
29209
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
29210
|
+
return failure(
|
|
29211
|
+
"not_session_branch",
|
|
29212
|
+
`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`,
|
|
29213
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
29214
|
+
);
|
|
29215
|
+
attempt.branch = branch;
|
|
29216
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
29217
|
+
if (!baseSha) {
|
|
29218
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
29219
|
+
baseSha = head.stdout.trim();
|
|
29220
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
29221
|
+
return failure(
|
|
29222
|
+
"no_commit",
|
|
29223
|
+
"this checkout has no commit to create the session branch at",
|
|
29224
|
+
NEW_SESSION_REMEDY
|
|
29225
|
+
);
|
|
29226
|
+
}
|
|
29227
|
+
const published = await git(
|
|
29228
|
+
root,
|
|
29229
|
+
[
|
|
29230
|
+
"for-each-ref",
|
|
29231
|
+
"--count=1",
|
|
29232
|
+
"--format=%(refname)",
|
|
29233
|
+
"--contains",
|
|
29234
|
+
baseSha,
|
|
29235
|
+
"refs/remotes/origin/"
|
|
29236
|
+
],
|
|
29237
|
+
signal
|
|
29238
|
+
);
|
|
29239
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
29240
|
+
return failure(
|
|
29241
|
+
"unpublished_commits",
|
|
29242
|
+
`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`,
|
|
29243
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
29244
|
+
);
|
|
29245
|
+
attempt.baseSha = baseSha;
|
|
29246
|
+
const remote = await git(
|
|
29247
|
+
root,
|
|
29248
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
29249
|
+
signal
|
|
29250
|
+
);
|
|
29251
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
29252
|
+
if (remote.ok && recorded) {
|
|
29253
|
+
Object.assign(attempt, recorded);
|
|
29254
|
+
return { ...recorded, repository };
|
|
29255
|
+
}
|
|
29256
|
+
if (remote.ok)
|
|
29257
|
+
return failure(
|
|
29258
|
+
"branch_exists",
|
|
29259
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
29260
|
+
NEW_SESSION_REMEDY
|
|
29261
|
+
);
|
|
29262
|
+
if (remote.code !== 2)
|
|
29263
|
+
return failure(
|
|
29264
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
29265
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
29266
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
29267
|
+
);
|
|
29268
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
29269
|
+
Object.assign(attempt, recorded);
|
|
29270
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
29271
|
+
}
|
|
29272
|
+
let answer;
|
|
29273
|
+
try {
|
|
29274
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
29275
|
+
answer = await environmentRequest(
|
|
29276
|
+
"POST",
|
|
29277
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
29278
|
+
{
|
|
29279
|
+
repositoryFullName: repository,
|
|
29280
|
+
claudeSessionId: context.sessionId,
|
|
29281
|
+
branch,
|
|
29282
|
+
baseSha,
|
|
29283
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
29284
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
29285
|
+
},
|
|
29286
|
+
deps,
|
|
29287
|
+
signal
|
|
29288
|
+
);
|
|
29289
|
+
} catch (error) {
|
|
29290
|
+
signal?.throwIfAborted();
|
|
29291
|
+
return environmentFailure(error, context.apiUrl);
|
|
29292
|
+
}
|
|
29293
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
29294
|
+
return failure(
|
|
29295
|
+
"repository_not_connected",
|
|
29296
|
+
`${repository} is not connected to Primitive`,
|
|
29297
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
29298
|
+
);
|
|
29299
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29300
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
29301
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
29302
|
+
return failure(
|
|
29303
|
+
"challenge_open",
|
|
29304
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
29305
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
29306
|
+
);
|
|
29307
|
+
if (answer.status === 429)
|
|
29308
|
+
return failure(
|
|
29309
|
+
"too_many_challenges",
|
|
29310
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
29311
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
29312
|
+
);
|
|
29313
|
+
const challengeId = answer.value?.challengeId;
|
|
29314
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
29315
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
29316
|
+
return answer.status >= 500 ? environmentFailure(
|
|
29317
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
29318
|
+
context.apiUrl
|
|
29319
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
29320
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
29321
|
+
attempt.challengeId = challengeId;
|
|
29322
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
29323
|
+
return pushSessionBranch(
|
|
29324
|
+
root,
|
|
29325
|
+
repository,
|
|
29326
|
+
branch,
|
|
29327
|
+
baseSha,
|
|
29328
|
+
{ challengeId, challengeExpiresAt },
|
|
29329
|
+
signal
|
|
29330
|
+
);
|
|
29331
|
+
}
|
|
29332
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
29333
|
+
const push = await git(
|
|
29334
|
+
root,
|
|
29335
|
+
[
|
|
29336
|
+
"-c",
|
|
29337
|
+
"core.hooksPath=/dev/null",
|
|
29338
|
+
"-c",
|
|
29339
|
+
"push.followTags=false",
|
|
29340
|
+
"-c",
|
|
29341
|
+
"push.recurseSubmodules=no",
|
|
29342
|
+
"-c",
|
|
29343
|
+
"push.gpgSign=false",
|
|
29344
|
+
"-c",
|
|
29345
|
+
"push.pushOption=",
|
|
29346
|
+
"push",
|
|
29347
|
+
"--no-verify",
|
|
29348
|
+
"--no-follow-tags",
|
|
29349
|
+
"--no-recurse-submodules",
|
|
29350
|
+
"--no-signed",
|
|
29351
|
+
"--quiet",
|
|
29352
|
+
"origin",
|
|
29353
|
+
`${baseSha}:refs/heads/${branch}`
|
|
29354
|
+
],
|
|
29355
|
+
signal
|
|
29356
|
+
);
|
|
29357
|
+
if (!push.ok)
|
|
29358
|
+
return push.timedOut ? failure(
|
|
29359
|
+
"push_timeout",
|
|
29360
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS3 / 1e3} s`,
|
|
29361
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
29362
|
+
) : failure(
|
|
29363
|
+
"push_refused",
|
|
29364
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
29365
|
+
`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}`
|
|
29366
|
+
);
|
|
29367
|
+
return { ...challenge, repository };
|
|
29368
|
+
}
|
|
29369
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
29370
|
+
let context;
|
|
29371
|
+
try {
|
|
29372
|
+
context = sessionContext(deps);
|
|
29373
|
+
} catch (error) {
|
|
29374
|
+
return failure(
|
|
29375
|
+
"environment_credential_invalid",
|
|
29376
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
29377
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
29378
|
+
);
|
|
29379
|
+
}
|
|
29380
|
+
if ("status" in context) return context;
|
|
29381
|
+
const ctx = context;
|
|
29382
|
+
const startedAt = Date.now();
|
|
29383
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
29384
|
+
return withFileLock(
|
|
29385
|
+
ctx.lockPath,
|
|
29386
|
+
async () => {
|
|
29387
|
+
const record = readToken(ctx);
|
|
29388
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
29389
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
29390
|
+
if (record) {
|
|
29391
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
29392
|
+
if (refreshed.status === "ok") {
|
|
29393
|
+
writeToken(ctx, refreshed.record);
|
|
29394
|
+
return identified(refreshed.record, true);
|
|
29395
|
+
}
|
|
29396
|
+
if (refreshed.status === "refused") {
|
|
29397
|
+
rmSync7(ctx.tokenPath, { force: true });
|
|
29398
|
+
writeState(ctx, {
|
|
29399
|
+
sessionId: ctx.sessionId,
|
|
29400
|
+
status: "failed",
|
|
29401
|
+
code: refreshed.failure.code,
|
|
29402
|
+
cause: refreshed.failure.cause,
|
|
29403
|
+
remedy: refreshed.failure.remedy,
|
|
29404
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
29405
|
+
at: Date.now()
|
|
29406
|
+
});
|
|
29407
|
+
return refreshed.failure;
|
|
29408
|
+
}
|
|
29409
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
29410
|
+
}
|
|
29411
|
+
const state = readState(ctx);
|
|
29412
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
29413
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
29414
|
+
if (!options.explicit) {
|
|
29415
|
+
if (!root || !(record || state))
|
|
29416
|
+
return failure(
|
|
29417
|
+
"not_identified",
|
|
29418
|
+
"this session has not identified who started it yet",
|
|
29419
|
+
RETRY_REMEDY
|
|
29420
|
+
);
|
|
29421
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
29422
|
+
} else if (state && state.at >= startedAt) {
|
|
29423
|
+
return outcomeFromState(state);
|
|
29424
|
+
}
|
|
29425
|
+
if (!root)
|
|
29426
|
+
return failure(
|
|
29427
|
+
"repository_missing",
|
|
29428
|
+
"this is not a git repository",
|
|
29429
|
+
"run it in the repository the session cloned"
|
|
29430
|
+
);
|
|
29431
|
+
const attempt = { root };
|
|
29432
|
+
const remember = (outcome) => {
|
|
29433
|
+
writeState(ctx, {
|
|
29434
|
+
sessionId: ctx.sessionId,
|
|
29435
|
+
status: outcome.status,
|
|
29436
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
29437
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
29438
|
+
githubLogin: outcome.githubLogin
|
|
29439
|
+
},
|
|
29440
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
29441
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
29442
|
+
repositoryRoot: root,
|
|
29443
|
+
branch: attempt.branch ?? state?.branch,
|
|
29444
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
29445
|
+
at: Date.now()
|
|
29446
|
+
});
|
|
29447
|
+
return outcome;
|
|
29448
|
+
};
|
|
29449
|
+
let challenge;
|
|
29450
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
29451
|
+
attempt.challengeId = state.challengeId;
|
|
29452
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
29453
|
+
attempt.branch = state.branch;
|
|
29454
|
+
attempt.baseSha = state.baseSha;
|
|
29455
|
+
challenge = {
|
|
29456
|
+
challengeId: state.challengeId,
|
|
29457
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
29458
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
29459
|
+
};
|
|
29460
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
29461
|
+
attempt.challengeId = state.challengeId;
|
|
29462
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
29463
|
+
const exchanged2 = await exchangeChallenge(
|
|
29464
|
+
ctx,
|
|
29465
|
+
{
|
|
29466
|
+
challengeId: state.challengeId,
|
|
29467
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
29468
|
+
githubLogin: state.githubLogin
|
|
29469
|
+
},
|
|
29470
|
+
root,
|
|
29471
|
+
deps,
|
|
29472
|
+
options.signal
|
|
29473
|
+
);
|
|
29474
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
29475
|
+
writeToken(ctx, exchanged2);
|
|
29476
|
+
return identified(exchanged2, false);
|
|
29477
|
+
} else if (!options.explicit) {
|
|
29478
|
+
return state ? outcomeFromState(state) : failure(
|
|
29479
|
+
"not_identified",
|
|
29480
|
+
"this session has not identified who started it yet",
|
|
29481
|
+
RETRY_REMEDY
|
|
29482
|
+
);
|
|
29483
|
+
} else {
|
|
29484
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
29485
|
+
if ("status" in pushed) return remember(pushed);
|
|
29486
|
+
challenge = pushed;
|
|
29487
|
+
}
|
|
29488
|
+
const verified = await pollChallenge(
|
|
29489
|
+
ctx.apiUrl,
|
|
29490
|
+
challenge.challengeId,
|
|
29491
|
+
challenge.repository,
|
|
29492
|
+
// A hook process waits only briefly for a late notice.
|
|
29493
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
29494
|
+
options.signal
|
|
29495
|
+
);
|
|
29496
|
+
if ("status" in verified) return remember(verified);
|
|
29497
|
+
const exchanged = await exchangeChallenge(
|
|
29498
|
+
ctx,
|
|
29499
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
29500
|
+
root,
|
|
29501
|
+
deps,
|
|
29502
|
+
options.signal
|
|
29503
|
+
);
|
|
29504
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
29505
|
+
writeToken(ctx, exchanged);
|
|
29506
|
+
return identified(exchanged, false);
|
|
29507
|
+
},
|
|
29508
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
29509
|
+
);
|
|
29510
|
+
}
|
|
29511
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
29512
|
+
const cached2 = cachedSessionCredential(deps);
|
|
29513
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
29514
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
29515
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
29516
|
+
let outcome;
|
|
29517
|
+
try {
|
|
29518
|
+
outcome = await ensureSessionIdentity(
|
|
29519
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
29520
|
+
deps
|
|
29521
|
+
);
|
|
29522
|
+
} catch (error) {
|
|
29523
|
+
options.signal?.throwIfAborted();
|
|
29524
|
+
if (error instanceof MachineAuthError) throw error;
|
|
29525
|
+
throw new MachineAuthError(
|
|
29526
|
+
"identity_unavailable",
|
|
29527
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
29528
|
+
);
|
|
29529
|
+
}
|
|
29530
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
29531
|
+
throw new MachineAuthError(
|
|
29532
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
29533
|
+
sessionIdentityMessage(outcome)
|
|
29534
|
+
);
|
|
29535
|
+
}
|
|
29536
|
+
|
|
28567
29537
|
// src/lib/machine-credentials.ts
|
|
29538
|
+
function sessionScoped(deps) {
|
|
29539
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
29540
|
+
}
|
|
28568
29541
|
var require3 = createRequire2(import.meta.url);
|
|
28569
29542
|
var SERVICE = "ai.primitive.prim.machine";
|
|
28570
|
-
var
|
|
29543
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
28571
29544
|
var PROFILE_FILE = "machine_profile.json";
|
|
28572
|
-
var
|
|
29545
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
28573
29546
|
var cached;
|
|
28574
29547
|
function configurationDirectory(deps) {
|
|
28575
29548
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
28576
29549
|
}
|
|
28577
29550
|
function apiUrlFor(deps) {
|
|
28578
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
29551
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
28579
29552
|
}
|
|
28580
|
-
function
|
|
28581
|
-
return
|
|
29553
|
+
function hash2(value) {
|
|
29554
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
28582
29555
|
}
|
|
28583
29556
|
function recordPath(directory, generation) {
|
|
28584
|
-
return
|
|
29557
|
+
return join14(directory, `machine_${generation}.json`);
|
|
28585
29558
|
}
|
|
28586
29559
|
function storageKey(directory, generation) {
|
|
28587
|
-
return `${
|
|
29560
|
+
return `${hash2(directory)}:${generation}`;
|
|
28588
29561
|
}
|
|
28589
29562
|
function environmentContextPath(deps, clientId) {
|
|
28590
|
-
return
|
|
29563
|
+
return join14(
|
|
28591
29564
|
configurationDirectory(deps),
|
|
28592
|
-
`machine_context_${
|
|
29565
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
28593
29566
|
);
|
|
28594
29567
|
}
|
|
28595
29568
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -28650,7 +29623,7 @@ function readEnvironmentContext(environment, deps) {
|
|
|
28650
29623
|
function keyringEntry(key) {
|
|
28651
29624
|
let directory = dirname7(fileURLToPath4(import.meta.url));
|
|
28652
29625
|
for (let depth = 0; depth < 5; depth++) {
|
|
28653
|
-
const loader =
|
|
29626
|
+
const loader = join14(directory, "native", "keyring.cjs");
|
|
28654
29627
|
if (existsSync10(loader)) {
|
|
28655
29628
|
const module2 = require3(loader);
|
|
28656
29629
|
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
@@ -28692,6 +29665,9 @@ function writePrivate(path, value) {
|
|
|
28692
29665
|
`, { mode: 384 });
|
|
28693
29666
|
protectPath(path, false);
|
|
28694
29667
|
}
|
|
29668
|
+
function readMachineMetadata(path) {
|
|
29669
|
+
return readPrivate(path);
|
|
29670
|
+
}
|
|
28695
29671
|
function readPrivate(path) {
|
|
28696
29672
|
let raw;
|
|
28697
29673
|
try {
|
|
@@ -28747,7 +29723,7 @@ function parseProfile(value) {
|
|
|
28747
29723
|
};
|
|
28748
29724
|
}
|
|
28749
29725
|
function readMachineProfile(deps = {}) {
|
|
28750
|
-
const value = readPrivate(
|
|
29726
|
+
const value = readPrivate(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
28751
29727
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
28752
29728
|
}
|
|
28753
29729
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -28756,7 +29732,7 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
28756
29732
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
28757
29733
|
function networkSecretBrokerKey(deps, clientId) {
|
|
28758
29734
|
const directory = configurationDirectory(deps);
|
|
28759
|
-
const path =
|
|
29735
|
+
const path = join14(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
28760
29736
|
const known = brokerKeys.get(path);
|
|
28761
29737
|
if (known) return known;
|
|
28762
29738
|
ensureDirectory(directory);
|
|
@@ -28797,7 +29773,7 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
28797
29773
|
} catch (error) {
|
|
28798
29774
|
if (error.code !== "EEXIST") throw error;
|
|
28799
29775
|
} finally {
|
|
28800
|
-
|
|
29776
|
+
rmSync8(staged, { force: true });
|
|
28801
29777
|
}
|
|
28802
29778
|
}
|
|
28803
29779
|
const key = read()?.key;
|
|
@@ -28830,7 +29806,7 @@ function environmentCredentials(deps) {
|
|
|
28830
29806
|
"conflicting_credentials",
|
|
28831
29807
|
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
28832
29808
|
);
|
|
28833
|
-
const generation =
|
|
29809
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
28834
29810
|
const credentials = {
|
|
28835
29811
|
clientId,
|
|
28836
29812
|
generation,
|
|
@@ -28851,12 +29827,12 @@ function environmentCredentials(deps) {
|
|
|
28851
29827
|
return {
|
|
28852
29828
|
clientId,
|
|
28853
29829
|
clientSecret,
|
|
28854
|
-
generation:
|
|
29830
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
28855
29831
|
};
|
|
28856
29832
|
}
|
|
28857
29833
|
function hasMachineConfiguration(deps = {}) {
|
|
28858
29834
|
const env = deps.env ?? process.env;
|
|
28859
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync10(
|
|
29835
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync10(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
28860
29836
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
28861
29837
|
throw new MachineAuthError(
|
|
28862
29838
|
"conflicting_credentials",
|
|
@@ -28868,6 +29844,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
28868
29844
|
}
|
|
28869
29845
|
function machineContext(deps = {}) {
|
|
28870
29846
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
29847
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
28871
29848
|
const environment = environmentCredentials(deps);
|
|
28872
29849
|
if (environment) {
|
|
28873
29850
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -28882,6 +29859,7 @@ function machineContext(deps = {}) {
|
|
|
28882
29859
|
return profile;
|
|
28883
29860
|
}
|
|
28884
29861
|
function cachedMachineCredential(deps = {}) {
|
|
29862
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
28885
29863
|
const context = machineContext(deps);
|
|
28886
29864
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
28887
29865
|
}
|
|
@@ -28890,7 +29868,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
28890
29868
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
28891
29869
|
if (!generation) return false;
|
|
28892
29870
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
28893
|
-
return readPrivate(
|
|
29871
|
+
return readPrivate(join14(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
28894
29872
|
}
|
|
28895
29873
|
var environmentTerminal;
|
|
28896
29874
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -28954,6 +29932,7 @@ async function persistRecord(record, deps, signal) {
|
|
|
28954
29932
|
}
|
|
28955
29933
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
28956
29934
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
29935
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
28957
29936
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
28958
29937
|
const apiUrl = apiUrlFor(deps);
|
|
28959
29938
|
const environment = environmentCredentials(deps);
|
|
@@ -28982,7 +29961,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28982
29961
|
}
|
|
28983
29962
|
}
|
|
28984
29963
|
return withFileLock(
|
|
28985
|
-
|
|
29964
|
+
join14(directory2, "credentials.lock"),
|
|
28986
29965
|
async () => {
|
|
28987
29966
|
if (machineSessionEnded(deps))
|
|
28988
29967
|
throw new MachineAuthError(
|
|
@@ -28990,7 +29969,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28990
29969
|
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
28991
29970
|
true
|
|
28992
29971
|
);
|
|
28993
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
29972
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
28994
29973
|
return cached;
|
|
28995
29974
|
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
28996
29975
|
throw networkRejection.error;
|
|
@@ -29064,7 +30043,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29064
30043
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
29065
30044
|
try {
|
|
29066
30045
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
29067
|
-
|
|
30046
|
+
rmSync8(contextPath, { force: true });
|
|
29068
30047
|
} catch {
|
|
29069
30048
|
}
|
|
29070
30049
|
throw error;
|
|
@@ -29074,7 +30053,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29074
30053
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
29075
30054
|
try {
|
|
29076
30055
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
29077
|
-
|
|
30056
|
+
rmSync8(contextPath, { force: true });
|
|
29078
30057
|
} catch {
|
|
29079
30058
|
}
|
|
29080
30059
|
}
|
|
@@ -29088,7 +30067,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29088
30067
|
const expected = machineContext(deps);
|
|
29089
30068
|
const directory = configurationDirectory(deps);
|
|
29090
30069
|
return withFileLock(
|
|
29091
|
-
|
|
30070
|
+
join14(directory, "credentials.lock"),
|
|
29092
30071
|
async () => {
|
|
29093
30072
|
const profile = readMachineProfile(deps);
|
|
29094
30073
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -29103,7 +30082,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29103
30082
|
true
|
|
29104
30083
|
);
|
|
29105
30084
|
let record = await loadRecord(profile, deps, signal);
|
|
29106
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
30085
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
29107
30086
|
try {
|
|
29108
30087
|
const { tokens, identity } = await withMachineCooldown(
|
|
29109
30088
|
directory,
|
|
@@ -29138,7 +30117,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29138
30117
|
await persistRecord(record, deps, signal);
|
|
29139
30118
|
} catch (error) {
|
|
29140
30119
|
if (error instanceof MachineAuthError && error.terminal)
|
|
29141
|
-
writePrivate(
|
|
30120
|
+
writePrivate(join14(directory, "machine_terminal.json"), profile.generation);
|
|
29142
30121
|
throw error;
|
|
29143
30122
|
}
|
|
29144
30123
|
}
|
|
@@ -29167,17 +30146,23 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
|
29167
30146
|
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
29168
30147
|
});
|
|
29169
30148
|
}
|
|
30149
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
30150
|
+
ensureDirectory(directory);
|
|
30151
|
+
}
|
|
30152
|
+
function writeMachineMetadata(path, value) {
|
|
30153
|
+
writePrivate(path, value);
|
|
30154
|
+
}
|
|
29170
30155
|
|
|
29171
30156
|
// src/lib/credentials.ts
|
|
29172
30157
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
29173
|
-
var TOKEN_FILE_PATH =
|
|
29174
|
-
var REFRESH_TOKEN_PATH =
|
|
29175
|
-
var TOKEN_EXPIRES_PATH =
|
|
29176
|
-
var TERMINAL_REFRESH_PATH =
|
|
29177
|
-
var CREDENTIAL_METADATA_PATH =
|
|
29178
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
29179
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
29180
|
-
var CREDENTIAL_LOCK_PATH =
|
|
30158
|
+
var TOKEN_FILE_PATH = join15(CONFIG_DIRECTORY, "token");
|
|
30159
|
+
var REFRESH_TOKEN_PATH = join15(CONFIG_DIRECTORY, "refresh_token");
|
|
30160
|
+
var TOKEN_EXPIRES_PATH = join15(CONFIG_DIRECTORY, "token_expires_at");
|
|
30161
|
+
var TERMINAL_REFRESH_PATH = join15(CONFIG_DIRECTORY, "refresh_terminal");
|
|
30162
|
+
var CREDENTIAL_METADATA_PATH = join15(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
30163
|
+
var CREDENTIAL_FAMILY_PATH = join15(CONFIG_DIRECTORY, "credential_family.json");
|
|
30164
|
+
var CREDENTIAL_MIGRATION_PATH = join15(CONFIG_DIRECTORY, "credential_migration.json");
|
|
30165
|
+
var CREDENTIAL_LOCK_PATH = join15(CONFIG_DIRECTORY, "credentials.lock");
|
|
29181
30166
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
29182
30167
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
29183
30168
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
@@ -29205,22 +30190,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
29205
30190
|
);
|
|
29206
30191
|
if (metadata.state === "legacy_broker") {
|
|
29207
30192
|
if (metadata.metadata) {
|
|
29208
|
-
const
|
|
29209
|
-
if (!
|
|
30193
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
30194
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
29210
30195
|
return void 0;
|
|
29211
30196
|
}
|
|
29212
30197
|
}
|
|
29213
30198
|
return { token: stored, source: "token_file" };
|
|
29214
30199
|
}
|
|
29215
30200
|
if (metadata.state === "invalid") return void 0;
|
|
29216
|
-
const
|
|
29217
|
-
if (!
|
|
30201
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
30202
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
29218
30203
|
return void 0;
|
|
29219
30204
|
}
|
|
29220
30205
|
return { token: stored, source: "token_file" };
|
|
29221
30206
|
}
|
|
29222
30207
|
function credentialFingerprint(value) {
|
|
29223
|
-
return
|
|
30208
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
29224
30209
|
}
|
|
29225
30210
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
29226
30211
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -29314,7 +30299,7 @@ function jwtExpiresAt(token) {
|
|
|
29314
30299
|
// src/daemon/client-instance-id.ts
|
|
29315
30300
|
import { randomBytes as randomBytes5 } from "crypto";
|
|
29316
30301
|
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync12 } from "fs";
|
|
29317
|
-
import { join as
|
|
30302
|
+
import { join as join16 } from "path";
|
|
29318
30303
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
29319
30304
|
var INSTANCE_FILE_MODE = 384;
|
|
29320
30305
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -29365,8 +30350,8 @@ function atomicWrite(path, value) {
|
|
|
29365
30350
|
}
|
|
29366
30351
|
async function getOrCreateClientInstanceId(options) {
|
|
29367
30352
|
const configDir = options.configDir;
|
|
29368
|
-
const path =
|
|
29369
|
-
const lockPath =
|
|
30353
|
+
const path = join16(configDir, "client_instance_id");
|
|
30354
|
+
const lockPath = join16(configDir, "client-instance.lock");
|
|
29370
30355
|
ensurePrivateConfigDirectory(configDir);
|
|
29371
30356
|
return withFileLock(
|
|
29372
30357
|
lockPath,
|
|
@@ -29410,52 +30395,11 @@ async function ingestUploaderHeaders() {
|
|
|
29410
30395
|
return headers;
|
|
29411
30396
|
}
|
|
29412
30397
|
|
|
29413
|
-
// src/lib/terminal-safe.ts
|
|
29414
|
-
function replaceIsolatedSurrogates(value) {
|
|
29415
|
-
let out = "";
|
|
29416
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
29417
|
-
const unit = value.charCodeAt(index);
|
|
29418
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
29419
|
-
const next = value.charCodeAt(index + 1);
|
|
29420
|
-
if (next >= 56320 && next <= 57343) {
|
|
29421
|
-
out += value[index] + value[index + 1];
|
|
29422
|
-
index += 1;
|
|
29423
|
-
} else {
|
|
29424
|
-
out += "\uFFFD";
|
|
29425
|
-
}
|
|
29426
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
29427
|
-
out += "\uFFFD";
|
|
29428
|
-
} else {
|
|
29429
|
-
out += value[index];
|
|
29430
|
-
}
|
|
29431
|
-
}
|
|
29432
|
-
return out;
|
|
29433
|
-
}
|
|
29434
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
29435
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
29436
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
29437
|
-
point === 1564 || // Arabic letter mark
|
|
29438
|
-
point === 6158 || // Mongolian vowel separator
|
|
29439
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
29440
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
29441
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
29442
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
29443
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
29444
|
-
point >= 917504 && point <= 917631;
|
|
29445
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
29446
|
-
}
|
|
29447
|
-
function terminalSafeText(value) {
|
|
29448
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
29449
|
-
}
|
|
29450
|
-
function terminalSafeLine(value) {
|
|
29451
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
29452
|
-
}
|
|
29453
|
-
|
|
29454
30398
|
// src/client.ts
|
|
29455
30399
|
var CONFIG_DIR_MODE = 448;
|
|
29456
30400
|
var CREDENTIAL_FILE_MODE = 384;
|
|
29457
30401
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
29458
|
-
var
|
|
30402
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
29459
30403
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
29460
30404
|
function authExpiredMessage() {
|
|
29461
30405
|
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
@@ -29472,7 +30416,7 @@ function getSiteUrl() {
|
|
|
29472
30416
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
29473
30417
|
}
|
|
29474
30418
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
29475
|
-
return primApiUrl?.trim() ||
|
|
30419
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
29476
30420
|
}
|
|
29477
30421
|
function expiresAtFor(token, expiresIn) {
|
|
29478
30422
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
@@ -29488,7 +30432,7 @@ function atomicWrite2(path, content2) {
|
|
|
29488
30432
|
}
|
|
29489
30433
|
function removeCredentialFile(path) {
|
|
29490
30434
|
if (!existsSync11(path)) return false;
|
|
29491
|
-
|
|
30435
|
+
rmSync9(path, { force: true });
|
|
29492
30436
|
return true;
|
|
29493
30437
|
}
|
|
29494
30438
|
function getTokenExpiresAt() {
|
|
@@ -29503,23 +30447,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
29503
30447
|
const expiresAt = getTokenExpiresAt();
|
|
29504
30448
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
29505
30449
|
}
|
|
29506
|
-
function refreshFingerprint(
|
|
29507
|
-
return
|
|
30450
|
+
function refreshFingerprint(refreshToken3) {
|
|
30451
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
29508
30452
|
}
|
|
29509
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
30453
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
29510
30454
|
return {
|
|
29511
30455
|
version: 1,
|
|
29512
30456
|
family: "legacy_broker",
|
|
29513
30457
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29514
|
-
refreshTokenHash: refreshFingerprint(
|
|
30458
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29515
30459
|
};
|
|
29516
30460
|
}
|
|
29517
|
-
function credentialFamilyMetadata(accessToken,
|
|
30461
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
29518
30462
|
const hashes = {
|
|
29519
30463
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29520
|
-
refreshTokenHash: refreshFingerprint(
|
|
30464
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29521
30465
|
};
|
|
29522
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
30466
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
29523
30467
|
}
|
|
29524
30468
|
function writeCredentialMigrationSentinel() {
|
|
29525
30469
|
atomicWrite2(
|
|
@@ -29531,11 +30475,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
29531
30475
|
`
|
|
29532
30476
|
);
|
|
29533
30477
|
}
|
|
29534
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
29535
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
30478
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
30479
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
29536
30480
|
return { state: "invalid" };
|
|
29537
30481
|
}
|
|
29538
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30482
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29539
30483
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
29540
30484
|
return { state: "invalid" };
|
|
29541
30485
|
}
|
|
@@ -29552,17 +30496,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
29552
30496
|
const metadata = readStoredCredentialMetadata();
|
|
29553
30497
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
29554
30498
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
29555
|
-
const
|
|
29556
|
-
if (!(accessToken &&
|
|
29557
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30499
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
30500
|
+
if (!(accessToken && refreshToken3)) return;
|
|
30501
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29558
30502
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29559
30503
|
`);
|
|
29560
30504
|
}
|
|
29561
30505
|
function terminalFingerprint() {
|
|
29562
30506
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
29563
30507
|
}
|
|
29564
|
-
function writeTerminalFingerprint(
|
|
29565
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
30508
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
30509
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
29566
30510
|
`);
|
|
29567
30511
|
}
|
|
29568
30512
|
function clearTerminalFingerprint() {
|
|
@@ -29571,20 +30515,20 @@ function clearTerminalFingerprint() {
|
|
|
29571
30515
|
function isSessionEnded() {
|
|
29572
30516
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
29573
30517
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
29574
|
-
const
|
|
30518
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
29575
30519
|
const ended = terminalFingerprint();
|
|
29576
|
-
return Boolean(
|
|
30520
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
29577
30521
|
}
|
|
29578
30522
|
function withCredentialLock(operation, options = {}) {
|
|
29579
30523
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
29580
30524
|
}
|
|
29581
30525
|
function commitCredentialsUnlocked(credentials) {
|
|
29582
30526
|
const accessToken = credentials.accessToken.trim();
|
|
29583
|
-
const
|
|
29584
|
-
if (!accessToken || !
|
|
30527
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
30528
|
+
if (!accessToken || !refreshToken3) {
|
|
29585
30529
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
29586
30530
|
}
|
|
29587
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
30531
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
29588
30532
|
if (credentials.metadata !== void 0) {
|
|
29589
30533
|
preserveMarkerlessLegacyGeneration();
|
|
29590
30534
|
writeCredentialMigrationSentinel();
|
|
@@ -29592,10 +30536,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
29592
30536
|
`);
|
|
29593
30537
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
29594
30538
|
`);
|
|
29595
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
30539
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29596
30540
|
`);
|
|
29597
30541
|
} else {
|
|
29598
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
30542
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29599
30543
|
`);
|
|
29600
30544
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29601
30545
|
`);
|
|
@@ -29632,15 +30576,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
29632
30576
|
`
|
|
29633
30577
|
);
|
|
29634
30578
|
}
|
|
29635
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
30579
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
29636
30580
|
const current = readStoredCredentialMetadata();
|
|
29637
30581
|
if (expected.state === "legacy_broker") {
|
|
29638
30582
|
if (current.state !== "legacy_broker") return false;
|
|
29639
30583
|
if (!expected.metadata) return current.metadata === void 0;
|
|
29640
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
30584
|
+
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;
|
|
29641
30585
|
}
|
|
29642
30586
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
29643
|
-
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(
|
|
30587
|
+
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;
|
|
29644
30588
|
}
|
|
29645
30589
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
29646
30590
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -29809,7 +30753,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
29809
30753
|
);
|
|
29810
30754
|
}
|
|
29811
30755
|
var _refreshInFlight;
|
|
29812
|
-
function
|
|
30756
|
+
function refreshToken2(options = {}) {
|
|
29813
30757
|
if (hasMachineConfiguration())
|
|
29814
30758
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
29815
30759
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -29947,7 +30891,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
29947
30891
|
if (response.status === 401)
|
|
29948
30892
|
throw new HttpError(
|
|
29949
30893
|
401,
|
|
29950
|
-
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(
|
|
30894
|
+
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(
|
|
29951
30895
|
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
29952
30896
|
)
|
|
29953
30897
|
);
|
|
@@ -29968,7 +30912,7 @@ async function request2(method, path, body, options) {
|
|
|
29968
30912
|
let refreshAttempted = false;
|
|
29969
30913
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
29970
30914
|
refreshAttempted = true;
|
|
29971
|
-
const token = await
|
|
30915
|
+
const token = await refreshToken2({
|
|
29972
30916
|
signal: options?.signal,
|
|
29973
30917
|
quiet: options?.quietRefresh
|
|
29974
30918
|
});
|
|
@@ -29987,7 +30931,7 @@ async function request2(method, path, body, options) {
|
|
|
29987
30931
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
29988
30932
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
29989
30933
|
refreshAttempted = true;
|
|
29990
|
-
retryToken = await
|
|
30934
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
29991
30935
|
}
|
|
29992
30936
|
if (retryToken) {
|
|
29993
30937
|
_cachedCredential = {
|
|
@@ -30305,7 +31249,7 @@ function parseAgent(argv) {
|
|
|
30305
31249
|
|
|
30306
31250
|
// src/hooks/redact.ts
|
|
30307
31251
|
import { existsSync as existsSync12, readFileSync as readFileSync14, statSync as statSync3 } from "fs";
|
|
30308
|
-
import { join as
|
|
31252
|
+
import { join as join18 } from "path";
|
|
30309
31253
|
import { Worker } from "worker_threads";
|
|
30310
31254
|
|
|
30311
31255
|
// src/lib/ansi.ts
|
|
@@ -30521,7 +31465,7 @@ function approvalSummary(evidence, preview) {
|
|
|
30521
31465
|
// src/commands/cursor-install.ts
|
|
30522
31466
|
import { existsSync as existsSync14, readFileSync as readFileSync16 } from "fs";
|
|
30523
31467
|
import { homedir as homedir4 } from "os";
|
|
30524
|
-
import { isAbsolute as isAbsolute5, join as
|
|
31468
|
+
import { isAbsolute as isAbsolute5, join as join20 } from "path";
|
|
30525
31469
|
|
|
30526
31470
|
// src/lib/preflight-host.ts
|
|
30527
31471
|
import { execFileSync as execFileSync5 } from "child_process";
|
|
@@ -30529,7 +31473,7 @@ import { execFileSync as execFileSync5 } from "child_process";
|
|
|
30529
31473
|
// src/commands/claude-install.ts
|
|
30530
31474
|
import { existsSync as existsSync13, lstatSync as lstatSync8, readFileSync as readFileSync15 } from "fs";
|
|
30531
31475
|
import { homedir as homedir3 } from "os";
|
|
30532
|
-
import { join as
|
|
31476
|
+
import { join as join19 } from "path";
|
|
30533
31477
|
var CAPTURE_BIN = "prim-hook";
|
|
30534
31478
|
var GATE_BIN = "prim-pre-tool-use";
|
|
30535
31479
|
var POST_TOOL_USE_BIN = "prim-post-tool-use";
|
|
@@ -30538,7 +31482,7 @@ var SESSION_END_BIN = "prim-session-end";
|
|
|
30538
31482
|
var STATUSLINE_BIN = "prim-statusline";
|
|
30539
31483
|
var STATUSLINE_ARGS = "";
|
|
30540
31484
|
var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
|
|
30541
|
-
var USER_SCOPE_PATH =
|
|
31485
|
+
var USER_SCOPE_PATH = join19(homedir3(), ".claude", "settings.json");
|
|
30542
31486
|
function projectRoot() {
|
|
30543
31487
|
return gitToplevel() ?? process.cwd();
|
|
30544
31488
|
}
|
|
@@ -30618,11 +31562,11 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform =
|
|
|
30618
31562
|
const explicit = env.CURSOR_CONFIG_DIR?.trim();
|
|
30619
31563
|
if (explicit && isAbsolute5(explicit)) return explicit;
|
|
30620
31564
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
30621
|
-
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return
|
|
30622
|
-
return
|
|
31565
|
+
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join20(xdg, "cursor");
|
|
31566
|
+
return join20(home, ".cursor");
|
|
30623
31567
|
}
|
|
30624
31568
|
function cursorHooksPath(scope, root = projectRoot()) {
|
|
30625
|
-
return scope === "user" ?
|
|
31569
|
+
return scope === "user" ? join20(cursorConfigDirectory(), "hooks.json") : join20(root, ".cursor", "hooks.json");
|
|
30626
31570
|
}
|
|
30627
31571
|
function plainObject(value) {
|
|
30628
31572
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -30774,7 +31718,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
|
|
|
30774
31718
|
}
|
|
30775
31719
|
|
|
30776
31720
|
// src/hooks/normalize.ts
|
|
30777
|
-
import { createHash as
|
|
31721
|
+
import { createHash as createHash10 } from "crypto";
|
|
30778
31722
|
import { realpathSync as realpathSync3 } from "fs";
|
|
30779
31723
|
import { isAbsolute as isAbsolute6, resolve as resolve5 } from "path";
|
|
30780
31724
|
var HERMES_EVENT_MAP = {
|
|
@@ -30819,7 +31763,7 @@ function requiredId(value, field) {
|
|
|
30819
31763
|
}
|
|
30820
31764
|
function cursorToolUseId(value) {
|
|
30821
31765
|
if (SAFE_CORRELATION_ID_RE.test(value)) return value;
|
|
30822
|
-
return `cursor:tool:v1:${
|
|
31766
|
+
return `cursor:tool:v1:${createHash10("sha256").update(value).digest("hex")}`;
|
|
30823
31767
|
}
|
|
30824
31768
|
function workspaceCandidates(value) {
|
|
30825
31769
|
if (!Array.isArray(value)) return [];
|
|
@@ -30916,7 +31860,7 @@ function normalizeEnvelope(parsed, agent2) {
|
|
|
30916
31860
|
]);
|
|
30917
31861
|
return {
|
|
30918
31862
|
...parsed,
|
|
30919
|
-
tool_use_id: `codex:fallback:v1:${
|
|
31863
|
+
tool_use_id: `codex:fallback:v1:${createHash10("sha256").update(stableToolIdentity).digest("hex")}`
|
|
30920
31864
|
};
|
|
30921
31865
|
}
|
|
30922
31866
|
return parsed;
|
|
@@ -37384,7 +38328,7 @@ var TokenGroup = class {
|
|
|
37384
38328
|
}
|
|
37385
38329
|
token(input, stack) {
|
|
37386
38330
|
let { parser: parser3 } = stack.p;
|
|
37387
|
-
|
|
38331
|
+
readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
|
|
37388
38332
|
}
|
|
37389
38333
|
};
|
|
37390
38334
|
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
|
|
@@ -37398,7 +38342,7 @@ var LocalTokenGroup = class {
|
|
|
37398
38342
|
let start = input.pos, skipped = 0;
|
|
37399
38343
|
for (; ; ) {
|
|
37400
38344
|
let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
|
|
37401
|
-
|
|
38345
|
+
readToken2(this.data, input, stack, 0, this.data, this.precTable);
|
|
37402
38346
|
if (input.token.value > -1)
|
|
37403
38347
|
break;
|
|
37404
38348
|
if (this.elseToken == null)
|
|
@@ -37431,7 +38375,7 @@ var ExternalTokenizer = class {
|
|
|
37431
38375
|
this.extend = !!options.extend;
|
|
37432
38376
|
}
|
|
37433
38377
|
};
|
|
37434
|
-
function
|
|
38378
|
+
function readToken2(data, input, stack, group, precTable, precOffset) {
|
|
37435
38379
|
let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
|
|
37436
38380
|
scan: for (; ; ) {
|
|
37437
38381
|
if ((groupMask & data[state]) == 0)
|
|
@@ -39244,7 +40188,7 @@ var newline2 = 10;
|
|
|
39244
40188
|
var carriageReturn = 13;
|
|
39245
40189
|
var space2 = 32;
|
|
39246
40190
|
var tab = 9;
|
|
39247
|
-
var
|
|
40191
|
+
var hash3 = 35;
|
|
39248
40192
|
var parenOpen = 40;
|
|
39249
40193
|
var dot2 = 46;
|
|
39250
40194
|
var braceOpen = 123;
|
|
@@ -39297,7 +40241,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
|
|
|
39297
40241
|
input.advance();
|
|
39298
40242
|
spaces2++;
|
|
39299
40243
|
}
|
|
39300
|
-
if (input.next == newline2 || input.next == carriageReturn || input.next ==
|
|
40244
|
+
if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
|
|
39301
40245
|
input.acceptToken(blankLineStart, -spaces2);
|
|
39302
40246
|
} else if (isLineBreak(input.next)) {
|
|
39303
40247
|
input.acceptToken(newline$1, 1);
|
|
@@ -39316,7 +40260,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
|
|
|
39316
40260
|
input.advance();
|
|
39317
40261
|
chars++;
|
|
39318
40262
|
}
|
|
39319
|
-
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next !=
|
|
40263
|
+
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
|
|
39320
40264
|
if (depth < context.indent) input.acceptToken(dedent, -chars);
|
|
39321
40265
|
else input.acceptToken(indent);
|
|
39322
40266
|
}
|
|
@@ -39390,7 +40334,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
|
|
|
39390
40334
|
for (let off = 0; ; off++) {
|
|
39391
40335
|
let next = input.peek(off);
|
|
39392
40336
|
if (next == space2 || next == tab) continue;
|
|
39393
|
-
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next !=
|
|
40337
|
+
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
|
|
39394
40338
|
input.acceptToken(printKeyword);
|
|
39395
40339
|
return;
|
|
39396
40340
|
}
|
|
@@ -40644,7 +41588,7 @@ function unverifiedResult(message) {
|
|
|
40644
41588
|
}
|
|
40645
41589
|
|
|
40646
41590
|
// src/hooks/preflight-v4.ts
|
|
40647
|
-
import { createHash as
|
|
41591
|
+
import { createHash as createHash11 } from "crypto";
|
|
40648
41592
|
import { setTimeout as delay } from "timers/promises";
|
|
40649
41593
|
var PREFLIGHT_PROTOCOL_VERSION2 = 4;
|
|
40650
41594
|
var PREFLIGHT_WAIT_MS = 24e4;
|
|
@@ -40667,7 +41611,7 @@ function toolInputDigest(toolName, input) {
|
|
|
40667
41611
|
}
|
|
40668
41612
|
throw new Error("Tool input has no stable JSON identity");
|
|
40669
41613
|
}
|
|
40670
|
-
return
|
|
41614
|
+
return createHash11("sha256").update(canonical({ toolName, input: input ?? null })).digest("hex");
|
|
40671
41615
|
}
|
|
40672
41616
|
function isUnidentifiedPause(response) {
|
|
40673
41617
|
return response.state === "paused" && (response.verdict === "block" || response.verdict === "unavailable") && response.checkId === void 0 && response.evaluationId === void 0;
|