@primitive.ai/prim 0.1.0-alpha.125 → 0.1.0-alpha.127
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 +140 -1
- package/SKILL.md +6 -1
- package/dist/{chunk-JFWJN2ME.js → chunk-72NIZMZN.js} +114 -5
- package/dist/{chunk-2BEUR3DU.js → chunk-A5VTE43F.js} +2 -2
- package/dist/{chunk-6OPSSJHO.js → chunk-C4QNBSWB.js} +24 -9
- package/dist/{chunk-BFYJLI7V.js → chunk-F3FDVHR7.js} +1 -1
- package/dist/{chunk-YP4OXKNX.js → chunk-H6X52UVF.js} +1 -1
- package/dist/{chunk-ND6TYHNI.js → chunk-H74RDXKP.js} +2 -2
- package/dist/{chunk-NJBN3WXF.js → chunk-HZI5PBN4.js} +785 -154
- package/dist/{chunk-FYYHBOOM.js → chunk-JCKOW45X.js} +2 -2
- package/dist/{chunk-DT7E3SD5.js → chunk-KFRGVHGB.js} +4 -4
- package/dist/{chunk-TI37ME2D.js → chunk-L6IL4N6Y.js} +16 -7
- package/dist/{chunk-HPA7RGSZ.js → chunk-MGKSZSTV.js} +7 -8
- package/dist/{chunk-ZKXNJB6U.js → chunk-NVDPKW7Z.js} +69 -29
- package/dist/{chunk-NBNQI3YJ.js → chunk-O65UVJZH.js} +6 -3
- package/dist/{chunk-74DQDWLW.js → chunk-R4EYLEIK.js} +7 -2
- package/dist/{chunk-R35M4RCY.js → chunk-RV3JFSMX.js} +4 -4
- package/dist/{chunk-PPZ56EVJ.js → chunk-TNWI3JWK.js} +1 -1
- package/dist/{chunk-6KXQQ7CQ.js → chunk-URYZDQFH.js} +3 -3
- package/dist/{chunk-L32WYFJT.js → chunk-UUQT5GMO.js} +135 -12
- package/dist/{chunk-EZXIKEMA.js → chunk-VVFVENU4.js} +6 -4
- package/dist/{chunk-O73J3KQQ.js → chunk-WGTUNUIS.js} +5 -2
- package/dist/daemon/server.js +805 -218
- package/dist/hook-runtime/daemon/server.js +805 -218
- package/dist/hook-runtime/hooks/post-commit.js +286 -59
- package/dist/hook-runtime/hooks/post-rewrite.js +278 -51
- package/dist/hook-runtime/hooks/post-tool-use.js +672 -194
- package/dist/hook-runtime/hooks/pre-commit.js +536 -88
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +616 -165
- package/dist/hook-runtime/hooks/prim-hook.js +642 -167
- package/dist/hook-runtime/hooks/session-end.js +263 -47
- package/dist/hook-runtime/hooks/session-start.js +1103 -476
- package/dist/hook-runtime/index.js +3645 -2120
- package/dist/hook-runtime/statusline-main.js +257 -29
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +15 -15
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +14 -15
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +49 -18
- package/dist/index.js +1014 -271
- package/dist/statusline-main.js +257 -29
- package/package.json +1 -1
|
@@ -54,7 +54,7 @@ var require_ucs2length = __commonJS({
|
|
|
54
54
|
|
|
55
55
|
// src/lib/machine-broker.ts
|
|
56
56
|
import { spawn } from "child_process";
|
|
57
|
-
import { createHash as createHash3, createHmac, randomBytes as
|
|
57
|
+
import { createHash as createHash3, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
58
58
|
import { lstatSync as lstatSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
|
|
59
59
|
import { createServer } from "http";
|
|
60
60
|
import { basename, join as join6 } from "path";
|
|
@@ -334,14 +334,64 @@ async function withFileLock(lockDir, operation, options = {}) {
|
|
|
334
334
|
}
|
|
335
335
|
}
|
|
336
336
|
|
|
337
|
+
// src/lib/loopback-fetch.ts
|
|
338
|
+
import { request } from "http";
|
|
339
|
+
import { Readable } from "stream";
|
|
340
|
+
function loopbackFetch(url, init = {}) {
|
|
341
|
+
const target = new URL(url);
|
|
342
|
+
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
343
|
+
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
344
|
+
return new Promise((resolve3, reject) => {
|
|
345
|
+
const outgoing = request(
|
|
346
|
+
target,
|
|
347
|
+
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
348
|
+
(incoming) => {
|
|
349
|
+
try {
|
|
350
|
+
const headers = new Headers();
|
|
351
|
+
for (const [name, value] of Object.entries(incoming.headers))
|
|
352
|
+
if (typeof value === "string") headers.set(name, value);
|
|
353
|
+
const status = incoming.statusCode ?? 502;
|
|
354
|
+
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
355
|
+
resolve3(new Response(body, { status, headers }));
|
|
356
|
+
} catch (error) {
|
|
357
|
+
incoming.destroy();
|
|
358
|
+
reject(error);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
);
|
|
362
|
+
outgoing.once("error", reject);
|
|
363
|
+
outgoing.end(init.body);
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
|
|
337
367
|
// src/lib/machine-credentials.ts
|
|
338
368
|
import { execFileSync } from "child_process";
|
|
339
|
-
import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
|
|
340
|
-
import {
|
|
369
|
+
import { createHash as createHash2, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
|
|
370
|
+
import {
|
|
371
|
+
chmodSync,
|
|
372
|
+
existsSync as existsSync3,
|
|
373
|
+
linkSync,
|
|
374
|
+
lstatSync as lstatSync2,
|
|
375
|
+
mkdirSync as mkdirSync3,
|
|
376
|
+
readFileSync as readFileSync4,
|
|
377
|
+
rmSync as rmSync4,
|
|
378
|
+
writeFileSync as writeFileSync3
|
|
379
|
+
} from "fs";
|
|
341
380
|
import { createRequire } from "module";
|
|
342
381
|
import { dirname as dirname4, join as join5 } from "path";
|
|
343
382
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
344
383
|
|
|
384
|
+
// src/lib/cloud-env.ts
|
|
385
|
+
function isClaudeCloudSession(env = process.env) {
|
|
386
|
+
return env.CLAUDE_CODE_REMOTE === "true";
|
|
387
|
+
}
|
|
388
|
+
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';
|
|
389
|
+
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';
|
|
390
|
+
function cloudSetupPointer(message, env = process.env) {
|
|
391
|
+
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
392
|
+
}
|
|
393
|
+
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
394
|
+
|
|
345
395
|
// src/lib/workos-connect.ts
|
|
346
396
|
var TOKEN_PATH = "/oauth2/token";
|
|
347
397
|
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
@@ -537,9 +587,19 @@ function parseMachineConfiguration(value) {
|
|
|
537
587
|
...record.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
538
588
|
};
|
|
539
589
|
}
|
|
590
|
+
function rejectedCredentialsMessage(message, env = process.env) {
|
|
591
|
+
return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
592
|
+
}
|
|
540
593
|
function machineSignal(signal) {
|
|
541
594
|
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
542
595
|
}
|
|
596
|
+
function hostOf(url) {
|
|
597
|
+
try {
|
|
598
|
+
return new URL(url).hostname;
|
|
599
|
+
} catch {
|
|
600
|
+
return "Primitive";
|
|
601
|
+
}
|
|
602
|
+
}
|
|
543
603
|
async function fetchMachine(url, options, fetchImpl) {
|
|
544
604
|
try {
|
|
545
605
|
return await fetchImpl(url, options);
|
|
@@ -547,7 +607,9 @@ async function fetchMachine(url, options, fetchImpl) {
|
|
|
547
607
|
options.signal?.throwIfAborted();
|
|
548
608
|
throw new MachineAuthError(
|
|
549
609
|
"authentication_unavailable",
|
|
550
|
-
|
|
610
|
+
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
611
|
+
// Primitive's are blocked by default: name the one that failed.
|
|
612
|
+
isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
551
613
|
);
|
|
552
614
|
}
|
|
553
615
|
}
|
|
@@ -574,8 +636,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
|
574
636
|
);
|
|
575
637
|
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
576
638
|
}
|
|
577
|
-
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
578
|
-
|
|
639
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
|
|
640
|
+
const network = options.secretInjection === "network";
|
|
641
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
|
|
579
642
|
throw new MachineAuthError(
|
|
580
643
|
"invalid_credentials",
|
|
581
644
|
"A machine client ID and secret are required.",
|
|
@@ -589,11 +652,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
589
652
|
redirect: "error",
|
|
590
653
|
signal: machineSignal(signal),
|
|
591
654
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
client_secret: clientSecret
|
|
596
|
-
|
|
655
|
+
// With a network secret the agent proxy authenticates the client with
|
|
656
|
+
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
657
|
+
body: new URLSearchParams(
|
|
658
|
+
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
659
|
+
)
|
|
597
660
|
},
|
|
598
661
|
fetchImpl
|
|
599
662
|
);
|
|
@@ -601,7 +664,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
601
664
|
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
602
665
|
throw new MachineAuthError(
|
|
603
666
|
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
604
|
-
terminal ?
|
|
667
|
+
terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
|
|
668
|
+
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
669
|
+
) : "The machine token service is temporarily unavailable.",
|
|
605
670
|
terminal,
|
|
606
671
|
terminal ? void 0 : machineRetryAt(response)
|
|
607
672
|
);
|
|
@@ -621,6 +686,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
621
686
|
} catch {
|
|
622
687
|
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
623
688
|
}
|
|
689
|
+
if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
|
|
690
|
+
throw new MachineAuthError(
|
|
691
|
+
"token_client_mismatch",
|
|
692
|
+
"The token service issued a token for another machine client."
|
|
693
|
+
);
|
|
624
694
|
if (claims.iss !== configuration.issuer || claims.aud !== configuration.audience || claims.sub !== clientId || claims.client_id !== clientId || !machineString(claims.org_id, 256) || typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1e3 <= Date.now()) {
|
|
625
695
|
throw new MachineAuthError(
|
|
626
696
|
"token_identity_mismatch",
|
|
@@ -666,22 +736,66 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
|
|
|
666
736
|
const terminal = response.status === 401 || response.status === 403;
|
|
667
737
|
throw new MachineAuthError(
|
|
668
738
|
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
669
|
-
terminal ?
|
|
739
|
+
terminal ? rejectedCredentialsMessage(
|
|
740
|
+
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
741
|
+
) : "Machine verification is temporarily unavailable.",
|
|
670
742
|
terminal
|
|
671
743
|
);
|
|
672
744
|
}
|
|
673
745
|
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
674
746
|
}
|
|
747
|
+
function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
|
|
748
|
+
const rejected = () => new MachineAuthError(
|
|
749
|
+
"network_token_rejected",
|
|
750
|
+
`Primitive did not accept this machine: the cloud environment's proxy attached no token it accepts, or the installation was revoked. Check the environment's OAuth 2.0 client credentials network secret: allowed website ${new URL(apiUrl).hostname}, the client ID (${clientId}), the client secret, and the token URL.`,
|
|
751
|
+
true
|
|
752
|
+
);
|
|
753
|
+
if (status === 401 || status === 403) throw rejected();
|
|
754
|
+
if (status < 200 || status > 299)
|
|
755
|
+
throw new MachineAuthError(
|
|
756
|
+
"verification_unavailable",
|
|
757
|
+
"Machine verification is temporarily unavailable."
|
|
758
|
+
);
|
|
759
|
+
let data;
|
|
760
|
+
try {
|
|
761
|
+
data = machineRecord(value);
|
|
762
|
+
} catch {
|
|
763
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
764
|
+
}
|
|
765
|
+
if (data.authenticated !== true) throw rejected();
|
|
766
|
+
const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
|
|
767
|
+
if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
|
|
768
|
+
throw new MachineAuthError(
|
|
769
|
+
"network_secret_mismatch",
|
|
770
|
+
`The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
|
|
771
|
+
true
|
|
772
|
+
);
|
|
773
|
+
return parseMachineIdentity(data, clientId);
|
|
774
|
+
}
|
|
775
|
+
async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
|
|
776
|
+
const response = await fetchMachine(
|
|
777
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
778
|
+
{ redirect: "error", signal: machineSignal(signal) },
|
|
779
|
+
fetchImpl
|
|
780
|
+
);
|
|
781
|
+
const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
|
|
782
|
+
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
783
|
+
}
|
|
675
784
|
|
|
676
785
|
// src/lib/machine-retry.ts
|
|
677
786
|
import { createHash } from "crypto";
|
|
678
|
-
import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
|
|
787
|
+
import { lstatSync, readFileSync as readFileSync3, readdirSync, rmSync as rmSync3 } from "fs";
|
|
679
788
|
import { join as join3 } from "path";
|
|
680
|
-
|
|
789
|
+
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
790
|
+
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
791
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
681
792
|
signal?.throwIfAborted();
|
|
682
793
|
const key = createHash("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
683
794
|
const path = join3(directory, `machine_retry_${key}.json`);
|
|
684
|
-
let state = {
|
|
795
|
+
let state = {
|
|
796
|
+
failures: 0,
|
|
797
|
+
retryAt: 0
|
|
798
|
+
};
|
|
685
799
|
try {
|
|
686
800
|
const stat = lstatSync(path);
|
|
687
801
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
@@ -696,12 +810,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
696
810
|
if (state.retryAt > Date.now())
|
|
697
811
|
throw new MachineAuthError(
|
|
698
812
|
"token_service_unavailable",
|
|
699
|
-
"Machine authentication is cooling down after a temporary failure. Retry later."
|
|
813
|
+
!isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
|
|
814
|
+
// Cloud setup keeps this wait too, so pointing at it would loop.
|
|
815
|
+
`${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
|
|
816
|
+
) : (
|
|
817
|
+
// The cooldown hides the failure that started it; cloud setup
|
|
818
|
+
// retries at once and names the cause.
|
|
819
|
+
cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
|
|
820
|
+
),
|
|
700
821
|
false,
|
|
701
822
|
state.retryAt
|
|
702
823
|
);
|
|
703
824
|
try {
|
|
704
|
-
const result = await
|
|
825
|
+
const result = await request3();
|
|
705
826
|
rmSync3(path, { force: true });
|
|
706
827
|
return result;
|
|
707
828
|
} catch (error) {
|
|
@@ -713,8 +834,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
713
834
|
].includes(error.code)) {
|
|
714
835
|
const failures = Math.min(16, state.failures + 1);
|
|
715
836
|
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
716
|
-
const retryAt = error.retryAt
|
|
717
|
-
atomicWriteFile(
|
|
837
|
+
const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
|
|
838
|
+
atomicWriteFile(
|
|
839
|
+
path,
|
|
840
|
+
JSON.stringify({
|
|
841
|
+
failures,
|
|
842
|
+
retryAt,
|
|
843
|
+
...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
|
|
844
|
+
}),
|
|
845
|
+
{ mode: 384 }
|
|
846
|
+
);
|
|
718
847
|
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
719
848
|
}
|
|
720
849
|
throw error;
|
|
@@ -935,10 +1064,98 @@ function readMachineProfile(deps = {}) {
|
|
|
935
1064
|
const value = readPrivate(join5(configurationDirectory(deps), PROFILE_FILE));
|
|
936
1065
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
937
1066
|
}
|
|
1067
|
+
var NETWORK_SECRET_AUTH = "network-secret";
|
|
1068
|
+
var NETWORK_TOKEN_AUTH = "network-token";
|
|
1069
|
+
var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
1070
|
+
var brokerKeys = /* @__PURE__ */ new Map();
|
|
1071
|
+
function networkSecretBrokerKey(deps, clientId) {
|
|
1072
|
+
const directory = configurationDirectory(deps);
|
|
1073
|
+
const path = join5(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
1074
|
+
const known = brokerKeys.get(path);
|
|
1075
|
+
if (known) return known;
|
|
1076
|
+
ensureDirectory(directory);
|
|
1077
|
+
const read = () => {
|
|
1078
|
+
try {
|
|
1079
|
+
const stat = lstatSync2(path);
|
|
1080
|
+
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
1081
|
+
throw new MachineAuthError(
|
|
1082
|
+
"unsafe_storage",
|
|
1083
|
+
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
1084
|
+
true
|
|
1085
|
+
);
|
|
1086
|
+
const value = readFileSync4(path, "utf8").trim();
|
|
1087
|
+
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
1088
|
+
} catch (error) {
|
|
1089
|
+
if (error.code === "ENOENT") return void 0;
|
|
1090
|
+
throw error;
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1094
|
+
const existing = read();
|
|
1095
|
+
if (existing?.key) {
|
|
1096
|
+
brokerKeys.set(path, existing.key);
|
|
1097
|
+
return existing.key;
|
|
1098
|
+
}
|
|
1099
|
+
if (existing)
|
|
1100
|
+
throw new MachineAuthError(
|
|
1101
|
+
"unsafe_storage",
|
|
1102
|
+
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
1103
|
+
true
|
|
1104
|
+
);
|
|
1105
|
+
const staged = `${path}.${process.pid}.${randomBytes2(6).toString("hex")}`;
|
|
1106
|
+
try {
|
|
1107
|
+
writeFileSync3(staged, `${randomBytes2(32).toString("hex")}
|
|
1108
|
+
`, { mode: 384, flag: "wx" });
|
|
1109
|
+
protectPath(staged, false);
|
|
1110
|
+
linkSync(staged, path);
|
|
1111
|
+
} catch (error) {
|
|
1112
|
+
if (error.code !== "EEXIST") throw error;
|
|
1113
|
+
} finally {
|
|
1114
|
+
rmSync4(staged, { force: true });
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
const key = read()?.key;
|
|
1118
|
+
if (!key)
|
|
1119
|
+
throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
|
|
1120
|
+
brokerKeys.set(path, key);
|
|
1121
|
+
return key;
|
|
1122
|
+
}
|
|
938
1123
|
function environmentCredentials(deps) {
|
|
939
1124
|
const env = deps.env ?? process.env;
|
|
940
|
-
const {
|
|
941
|
-
|
|
1125
|
+
const {
|
|
1126
|
+
PRIM_M2M_CLIENT_ID: clientId,
|
|
1127
|
+
PRIM_M2M_CLIENT_SECRET: clientSecret,
|
|
1128
|
+
PRIM_M2M_CLIENT_AUTH: auth
|
|
1129
|
+
} = env;
|
|
1130
|
+
if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
|
|
1131
|
+
if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
|
|
1132
|
+
throw new MachineAuthError(
|
|
1133
|
+
"incomplete_machine_credentials",
|
|
1134
|
+
`PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
|
|
1135
|
+
);
|
|
1136
|
+
if (auth !== void 0) {
|
|
1137
|
+
if (!clientId || !/^client_[\w-]+$/u.test(clientId))
|
|
1138
|
+
throw new MachineAuthError(
|
|
1139
|
+
"incomplete_machine_credentials",
|
|
1140
|
+
`Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
|
|
1141
|
+
);
|
|
1142
|
+
if (clientSecret !== void 0)
|
|
1143
|
+
throw new MachineAuthError(
|
|
1144
|
+
"conflicting_credentials",
|
|
1145
|
+
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
1146
|
+
);
|
|
1147
|
+
const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
1148
|
+
const credentials = {
|
|
1149
|
+
clientId,
|
|
1150
|
+
generation,
|
|
1151
|
+
...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
|
|
1152
|
+
};
|
|
1153
|
+
Object.defineProperty(credentials, "clientSecret", {
|
|
1154
|
+
enumerable: true,
|
|
1155
|
+
get: () => networkSecretBrokerKey(deps, clientId)
|
|
1156
|
+
});
|
|
1157
|
+
return credentials;
|
|
1158
|
+
}
|
|
942
1159
|
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
943
1160
|
throw new MachineAuthError(
|
|
944
1161
|
"incomplete_machine_credentials",
|
|
@@ -953,7 +1170,7 @@ function environmentCredentials(deps) {
|
|
|
953
1170
|
}
|
|
954
1171
|
function hasMachineConfiguration(deps = {}) {
|
|
955
1172
|
const env = deps.env ?? process.env;
|
|
956
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join5(configurationDirectory(deps), PROFILE_FILE));
|
|
1173
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join5(configurationDirectory(deps), PROFILE_FILE));
|
|
957
1174
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
958
1175
|
throw new MachineAuthError(
|
|
959
1176
|
"conflicting_credentials",
|
|
@@ -990,6 +1207,8 @@ function machineSessionEnded(deps = {}) {
|
|
|
990
1207
|
return readPrivate(join5(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
991
1208
|
}
|
|
992
1209
|
var environmentTerminal;
|
|
1210
|
+
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
1211
|
+
var networkRejection;
|
|
993
1212
|
async function loadRecord(profile, deps, signal) {
|
|
994
1213
|
const directory = configurationDirectory(deps);
|
|
995
1214
|
let value;
|
|
@@ -1053,6 +1272,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1053
1272
|
const apiUrl = apiUrlFor(deps);
|
|
1054
1273
|
const environment = environmentCredentials(deps);
|
|
1055
1274
|
if (environment) {
|
|
1275
|
+
const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
|
|
1056
1276
|
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
1057
1277
|
const directory2 = configurationDirectory(deps);
|
|
1058
1278
|
ensureDirectory(directory2);
|
|
@@ -1070,7 +1290,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1070
1290
|
writeEnvironmentContext(cached, deps);
|
|
1071
1291
|
return cached;
|
|
1072
1292
|
} catch (error) {
|
|
1073
|
-
if (error instanceof MachineAuthError && error.terminal)
|
|
1293
|
+
if (error instanceof MachineAuthError && error.terminal && !networkManaged)
|
|
1074
1294
|
environmentTerminal = environment.generation;
|
|
1075
1295
|
throw error;
|
|
1076
1296
|
}
|
|
@@ -1081,11 +1301,13 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1081
1301
|
if (machineSessionEnded(deps))
|
|
1082
1302
|
throw new MachineAuthError(
|
|
1083
1303
|
"machine_credentials_rejected",
|
|
1084
|
-
"Rotate the injected machine credentials.",
|
|
1304
|
+
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1085
1305
|
true
|
|
1086
1306
|
);
|
|
1087
1307
|
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
|
|
1088
1308
|
return cached;
|
|
1309
|
+
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
1310
|
+
throw networkRejection.error;
|
|
1089
1311
|
try {
|
|
1090
1312
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
1091
1313
|
directory2,
|
|
@@ -1094,13 +1316,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1094
1316
|
signal,
|
|
1095
1317
|
async () => {
|
|
1096
1318
|
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
1319
|
+
if (environment.tokenInjection) {
|
|
1320
|
+
const identity3 = await verifyInjectedMachineIdentity(
|
|
1321
|
+
apiUrl,
|
|
1322
|
+
environment.clientId,
|
|
1323
|
+
signal,
|
|
1324
|
+
deps.fetch
|
|
1325
|
+
);
|
|
1326
|
+
const tokens3 = {
|
|
1327
|
+
accessToken: "",
|
|
1328
|
+
expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
|
|
1329
|
+
};
|
|
1330
|
+
return { configuration: configuration2, tokens: tokens3, identity: identity3 };
|
|
1331
|
+
}
|
|
1097
1332
|
const tokens2 = await exchangeMachineCredentials(
|
|
1098
1333
|
configuration2,
|
|
1099
1334
|
environment.clientId,
|
|
1100
|
-
|
|
1335
|
+
// The broker key is not a client secret; the proxy supplies that.
|
|
1336
|
+
environment.secretInjection ? "" : environment.clientSecret,
|
|
1101
1337
|
signal,
|
|
1102
|
-
deps.fetch
|
|
1103
|
-
|
|
1338
|
+
deps.fetch,
|
|
1339
|
+
{ secretInjection: environment.secretInjection }
|
|
1340
|
+
).catch((error) => {
|
|
1341
|
+
if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
|
|
1342
|
+
throw new MachineAuthError(
|
|
1343
|
+
"network_secret_mismatch",
|
|
1344
|
+
`The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
|
|
1345
|
+
true
|
|
1346
|
+
);
|
|
1347
|
+
throw error;
|
|
1348
|
+
});
|
|
1104
1349
|
const identity2 = await verifyMachineIdentity(
|
|
1105
1350
|
apiUrl,
|
|
1106
1351
|
tokens2.accessToken,
|
|
@@ -1117,11 +1362,27 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1117
1362
|
...identity,
|
|
1118
1363
|
apiUrl,
|
|
1119
1364
|
generation: environment.generation,
|
|
1120
|
-
storage: "environment"
|
|
1365
|
+
storage: "environment",
|
|
1366
|
+
...environment.tokenInjection ? { tokenInjection: "network" } : {}
|
|
1121
1367
|
};
|
|
1122
1368
|
writeEnvironmentContext(cached, deps);
|
|
1123
1369
|
return cached;
|
|
1124
1370
|
} catch (error) {
|
|
1371
|
+
if (networkManaged && error instanceof MachineAuthError && error.terminal) {
|
|
1372
|
+
networkRejection = {
|
|
1373
|
+
generation: environment.generation,
|
|
1374
|
+
until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
|
|
1375
|
+
error
|
|
1376
|
+
};
|
|
1377
|
+
if (cached?.generation === environment.generation) cached = void 0;
|
|
1378
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1379
|
+
try {
|
|
1380
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1381
|
+
rmSync4(contextPath, { force: true });
|
|
1382
|
+
} catch {
|
|
1383
|
+
}
|
|
1384
|
+
throw error;
|
|
1385
|
+
}
|
|
1125
1386
|
if (error instanceof MachineAuthError && error.terminal) {
|
|
1126
1387
|
environmentTerminal = environment.generation;
|
|
1127
1388
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
@@ -1202,12 +1463,44 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1202
1463
|
{ signal }
|
|
1203
1464
|
);
|
|
1204
1465
|
}
|
|
1466
|
+
async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
1467
|
+
const environment = environmentCredentials(deps);
|
|
1468
|
+
if (!environment?.tokenInjection)
|
|
1469
|
+
throw new MachineAuthError(
|
|
1470
|
+
"identity_changed",
|
|
1471
|
+
"Machine identity changed; restart the operation."
|
|
1472
|
+
);
|
|
1473
|
+
const directory = configurationDirectory(deps);
|
|
1474
|
+
ensureDirectory(directory);
|
|
1475
|
+
return forwardBrokerRequest({
|
|
1476
|
+
directory,
|
|
1477
|
+
apiUrl: apiUrlFor(deps),
|
|
1478
|
+
environment,
|
|
1479
|
+
env: deps.env ?? process.env,
|
|
1480
|
+
request: request3,
|
|
1481
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
1482
|
+
});
|
|
1483
|
+
}
|
|
1205
1484
|
function machineJournalBucket(identity) {
|
|
1206
1485
|
return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
|
|
1207
1486
|
}
|
|
1487
|
+
function identityPending(actor) {
|
|
1488
|
+
return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
|
|
1489
|
+
}
|
|
1490
|
+
function machinePendingBucket(identity) {
|
|
1491
|
+
return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
1492
|
+
}
|
|
1208
1493
|
|
|
1209
1494
|
// src/lib/machine-broker.ts
|
|
1210
1495
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
1496
|
+
var MAX_CREDENTIAL_REQUEST_BYTES = 2048;
|
|
1497
|
+
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
1498
|
+
var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
1499
|
+
var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
|
|
1500
|
+
var FORWARD_REQUEST_PROOF = "forward-request";
|
|
1501
|
+
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
1502
|
+
var FORWARD_TIMEOUT_MS = 3e4;
|
|
1503
|
+
var FORWARD_METHODS = ["GET", "POST", "DELETE"];
|
|
1211
1504
|
var IDLE_MS = 5 * 6e4;
|
|
1212
1505
|
function descriptorPath(directory, generation) {
|
|
1213
1506
|
return join6(directory, `machine_broker_${generation}.json`);
|
|
@@ -1223,8 +1516,8 @@ function readDescriptor(path) {
|
|
|
1223
1516
|
return void 0;
|
|
1224
1517
|
}
|
|
1225
1518
|
}
|
|
1226
|
-
function signature(secret, nonce, body) {
|
|
1227
|
-
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
1519
|
+
function signature(secret, nonce, body, purpose) {
|
|
1520
|
+
return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
|
|
1228
1521
|
}
|
|
1229
1522
|
function matches(left, right) {
|
|
1230
1523
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
@@ -1239,10 +1532,9 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
1239
1532
|
observedTokenHash: tokenHash(options.observedToken),
|
|
1240
1533
|
timestamp: Date.now()
|
|
1241
1534
|
});
|
|
1242
|
-
const response = await
|
|
1535
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
1243
1536
|
method: "POST",
|
|
1244
1537
|
body,
|
|
1245
|
-
redirect: "error",
|
|
1246
1538
|
signal: options.signal,
|
|
1247
1539
|
headers: {
|
|
1248
1540
|
"Content-Type": "application/json",
|
|
@@ -1273,6 +1565,15 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
1273
1565
|
);
|
|
1274
1566
|
return credential;
|
|
1275
1567
|
}
|
|
1568
|
+
function brokerEnvironment(options) {
|
|
1569
|
+
const routed = options.environment.secretInjection || options.environment.tokenInjection;
|
|
1570
|
+
return {
|
|
1571
|
+
...options.env,
|
|
1572
|
+
PRIM_API_URL: options.apiUrl,
|
|
1573
|
+
PRIM_CONFIG_DIR: options.directory,
|
|
1574
|
+
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1276
1577
|
async function acquireBrokerCredential(options) {
|
|
1277
1578
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1278
1579
|
const existing = readDescriptor(path);
|
|
@@ -1284,15 +1585,28 @@ async function acquireBrokerCredential(options) {
|
|
|
1284
1585
|
if (error instanceof MachineAuthError) throw error;
|
|
1285
1586
|
}
|
|
1286
1587
|
}
|
|
1287
|
-
const descriptor = await
|
|
1588
|
+
const descriptor = await ensureBroker(options);
|
|
1589
|
+
try {
|
|
1590
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
1591
|
+
} catch (error) {
|
|
1592
|
+
options.signal.throwIfAborted();
|
|
1593
|
+
if (error instanceof MachineAuthError) throw error;
|
|
1594
|
+
throw new MachineAuthError(
|
|
1595
|
+
"broker_unavailable",
|
|
1596
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
1597
|
+
);
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
async function ensureBroker(options) {
|
|
1601
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1602
|
+
return withFileLock(
|
|
1288
1603
|
join6(options.directory, "machine-broker.lock"),
|
|
1289
1604
|
async () => {
|
|
1290
1605
|
const current = readDescriptor(path);
|
|
1291
1606
|
if (current) {
|
|
1292
1607
|
try {
|
|
1293
|
-
const response = await
|
|
1294
|
-
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
1295
|
-
redirect: "error"
|
|
1608
|
+
const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
|
|
1609
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
1296
1610
|
});
|
|
1297
1611
|
if (response.ok && await response.text() === current.nonce) return current;
|
|
1298
1612
|
} catch {
|
|
@@ -1311,7 +1625,7 @@ async function acquireBrokerCredential(options) {
|
|
|
1311
1625
|
detached: true,
|
|
1312
1626
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
1313
1627
|
windowsHide: true,
|
|
1314
|
-
env:
|
|
1628
|
+
env: brokerEnvironment(options)
|
|
1315
1629
|
});
|
|
1316
1630
|
let settled = false;
|
|
1317
1631
|
const finish = (error) => {
|
|
@@ -1363,44 +1677,202 @@ async function acquireBrokerCredential(options) {
|
|
|
1363
1677
|
},
|
|
1364
1678
|
{ signal: options.signal }
|
|
1365
1679
|
);
|
|
1680
|
+
}
|
|
1681
|
+
async function forwardOnce(descriptor, environment, request3, signal) {
|
|
1682
|
+
const body = JSON.stringify({
|
|
1683
|
+
generation: environment.generation,
|
|
1684
|
+
timestamp: Date.now(),
|
|
1685
|
+
method: request3.method,
|
|
1686
|
+
path: request3.path,
|
|
1687
|
+
headers: request3.headers ?? {},
|
|
1688
|
+
...request3.body === void 0 ? {} : { body: request3.body }
|
|
1689
|
+
});
|
|
1690
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
|
|
1691
|
+
method: "POST",
|
|
1692
|
+
body,
|
|
1693
|
+
signal,
|
|
1694
|
+
headers: {
|
|
1695
|
+
"Content-Type": "application/json",
|
|
1696
|
+
"X-Prim-Proof": signature(
|
|
1697
|
+
environment.clientSecret,
|
|
1698
|
+
descriptor.nonce,
|
|
1699
|
+
body,
|
|
1700
|
+
FORWARD_REQUEST_PROOF
|
|
1701
|
+
)
|
|
1702
|
+
}
|
|
1703
|
+
});
|
|
1704
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
|
|
1705
|
+
if (typeof envelope.body !== "string" || !matches(
|
|
1706
|
+
signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
|
|
1707
|
+
envelope.proof
|
|
1708
|
+
))
|
|
1709
|
+
throw new MachineAuthError(
|
|
1710
|
+
"broker_unavailable",
|
|
1711
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
1712
|
+
);
|
|
1713
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
1714
|
+
if (data.error) {
|
|
1715
|
+
const error = machineRecord(data.error);
|
|
1716
|
+
throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
|
|
1717
|
+
}
|
|
1718
|
+
const status = data.status;
|
|
1719
|
+
if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
|
|
1720
|
+
throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
|
|
1721
|
+
const headers = new Headers();
|
|
1722
|
+
for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
|
|
1723
|
+
if (typeof value === "string") headers.set(name, value);
|
|
1724
|
+
const text = typeof data.body === "string" ? data.body : "";
|
|
1725
|
+
return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
|
|
1726
|
+
}
|
|
1727
|
+
async function forwardBrokerRequest(options) {
|
|
1728
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1729
|
+
const unavailable = () => new MachineAuthError(
|
|
1730
|
+
"broker_unavailable",
|
|
1731
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
1732
|
+
);
|
|
1733
|
+
const existing = readDescriptor(path);
|
|
1734
|
+
if (existing) {
|
|
1735
|
+
try {
|
|
1736
|
+
return await forwardOnce(existing, options.environment, options.request, options.signal);
|
|
1737
|
+
} catch (error) {
|
|
1738
|
+
options.signal.throwIfAborted();
|
|
1739
|
+
if (error instanceof MachineAuthError) throw error;
|
|
1740
|
+
if (error.code !== "ECONNREFUSED") throw unavailable();
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
const descriptor = await ensureBroker(options);
|
|
1366
1744
|
try {
|
|
1367
|
-
return await
|
|
1745
|
+
return await forwardOnce(descriptor, options.environment, options.request, options.signal);
|
|
1368
1746
|
} catch (error) {
|
|
1369
1747
|
options.signal.throwIfAborted();
|
|
1370
1748
|
if (error instanceof MachineAuthError) throw error;
|
|
1371
|
-
throw
|
|
1372
|
-
|
|
1373
|
-
|
|
1749
|
+
throw unavailable();
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
function forwardableHeaders(value) {
|
|
1753
|
+
const headers = {};
|
|
1754
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return headers;
|
|
1755
|
+
for (const [name, content] of Object.entries(value)) {
|
|
1756
|
+
const lower = name.toLowerCase();
|
|
1757
|
+
if (typeof content === "string" && content.length <= 256 && !/[\p{Cc}]/u.test(content) && (lower === "content-type" || /^x-prim-[a-z0-9-]+$/u.test(lower)))
|
|
1758
|
+
headers[name] = content;
|
|
1759
|
+
}
|
|
1760
|
+
return headers;
|
|
1761
|
+
}
|
|
1762
|
+
async function forwardToApi(apiUrl, data, signal, fetchImpl = fetch) {
|
|
1763
|
+
const refuse = (message) => ({
|
|
1764
|
+
error: { code: "invalid_request", message, terminal: false }
|
|
1765
|
+
});
|
|
1766
|
+
if (typeof data.method !== "string" || !FORWARD_METHODS.includes(data.method))
|
|
1767
|
+
return refuse("The forwarded request's method is not allowed.");
|
|
1768
|
+
if (data.body !== void 0 && typeof data.body !== "string")
|
|
1769
|
+
return refuse("The forwarded request's body is not text.");
|
|
1770
|
+
let target;
|
|
1771
|
+
try {
|
|
1772
|
+
if (typeof data.path !== "string" || !data.path.startsWith("/")) throw new Error("path");
|
|
1773
|
+
target = new URL(data.path, `${apiUrl}/`);
|
|
1774
|
+
if (target.origin !== apiUrl || target.username || target.password) throw new Error("origin");
|
|
1775
|
+
} catch {
|
|
1776
|
+
return refuse("The forwarded request does not target the configured API.");
|
|
1777
|
+
}
|
|
1778
|
+
try {
|
|
1779
|
+
const answer = await fetchImpl(target, {
|
|
1780
|
+
method: data.method,
|
|
1781
|
+
headers: forwardableHeaders(data.headers),
|
|
1782
|
+
body: data.method === "GET" ? void 0 : data.body,
|
|
1783
|
+
redirect: "error",
|
|
1784
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(FORWARD_TIMEOUT_MS)])
|
|
1785
|
+
});
|
|
1786
|
+
const headers = {};
|
|
1787
|
+
for (const name of ["content-type", "retry-after"]) {
|
|
1788
|
+
const value = answer.headers.get(name);
|
|
1789
|
+
if (value) headers[name] = value;
|
|
1790
|
+
}
|
|
1791
|
+
const chunks = [];
|
|
1792
|
+
let received = 0;
|
|
1793
|
+
if (answer.body)
|
|
1794
|
+
for await (const chunk of answer.body) {
|
|
1795
|
+
received += chunk.length;
|
|
1796
|
+
if (received > MAX_API_RESPONSE_BYTES)
|
|
1797
|
+
return {
|
|
1798
|
+
error: {
|
|
1799
|
+
code: "invalid_response",
|
|
1800
|
+
message: "The API answered with more than prim accepts.",
|
|
1801
|
+
terminal: false
|
|
1802
|
+
}
|
|
1803
|
+
};
|
|
1804
|
+
chunks.push(chunk);
|
|
1805
|
+
}
|
|
1806
|
+
return { status: answer.status, headers, body: Buffer.concat(chunks).toString("utf8") };
|
|
1807
|
+
} catch (error) {
|
|
1808
|
+
const timedOut = error instanceof Error && error.name === "TimeoutError";
|
|
1809
|
+
return {
|
|
1810
|
+
error: {
|
|
1811
|
+
code: timedOut ? "request_timeout" : "authentication_unavailable",
|
|
1812
|
+
message: timedOut ? "Primitive did not answer through the cloud environment's proxy in time. The request may or may not have been applied." : "The request to Primitive through the cloud environment's proxy failed. Check the connection and retry.",
|
|
1813
|
+
terminal: false
|
|
1814
|
+
}
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
async function credentialResult(apiUrl, data, signal) {
|
|
1819
|
+
try {
|
|
1820
|
+
const current = cachedMachineCredential();
|
|
1821
|
+
const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
|
|
1822
|
+
const credential = await acquireMachineCredential(
|
|
1823
|
+
{ force, signal },
|
|
1824
|
+
{ localEnvironment: true }
|
|
1374
1825
|
);
|
|
1826
|
+
if (!credential || credential.apiUrl !== apiUrl) throw new Error("Missing machine identity");
|
|
1827
|
+
return { credential };
|
|
1828
|
+
} catch (error) {
|
|
1829
|
+
return {
|
|
1830
|
+
error: error instanceof MachineAuthError ? {
|
|
1831
|
+
code: error.code,
|
|
1832
|
+
message: error.message,
|
|
1833
|
+
terminal: error.terminal,
|
|
1834
|
+
retryAt: error.retryAt
|
|
1835
|
+
} : {
|
|
1836
|
+
code: "broker_unavailable",
|
|
1837
|
+
message: "Machine authentication is temporarily unavailable.",
|
|
1838
|
+
terminal: false
|
|
1839
|
+
}
|
|
1840
|
+
};
|
|
1375
1841
|
}
|
|
1376
1842
|
}
|
|
1377
|
-
|
|
1378
|
-
const environment =
|
|
1379
|
-
|
|
1380
|
-
const directory = primConfigDirectory();
|
|
1381
|
-
const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
|
|
1382
|
-
const path = descriptorPath(directory, environment.generation);
|
|
1383
|
-
const nonce = randomBytes2(32).toString("hex");
|
|
1384
|
-
const server = createServer(async (request2, response) => {
|
|
1843
|
+
function createBrokerServer(options) {
|
|
1844
|
+
const { environment, apiUrl, nonce } = options;
|
|
1845
|
+
const server = createServer(async (request3, response) => {
|
|
1385
1846
|
response.setHeader("Cache-Control", "no-store");
|
|
1386
|
-
if (
|
|
1847
|
+
if (request3.method === "GET" && request3.url === "/health") {
|
|
1387
1848
|
response.end(nonce);
|
|
1388
1849
|
return;
|
|
1389
1850
|
}
|
|
1390
|
-
|
|
1851
|
+
const forwarding = request3.url === "/forward" && environment.tokenInjection === "network";
|
|
1852
|
+
if (request3.method !== "POST" || request3.url !== "/credential" && !forwarding) {
|
|
1391
1853
|
response.writeHead(404).end();
|
|
1392
1854
|
return;
|
|
1393
1855
|
}
|
|
1394
|
-
|
|
1856
|
+
const limit = forwarding ? MAX_FORWARD_REQUEST_BYTES : MAX_CREDENTIAL_REQUEST_BYTES;
|
|
1395
1857
|
try {
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1858
|
+
const chunks = [];
|
|
1859
|
+
let received = 0;
|
|
1860
|
+
for await (const chunk of request3) {
|
|
1861
|
+
received += chunk.length;
|
|
1862
|
+
if (received > limit) {
|
|
1399
1863
|
response.writeHead(413).end();
|
|
1400
1864
|
return;
|
|
1401
1865
|
}
|
|
1866
|
+
chunks.push(chunk);
|
|
1402
1867
|
}
|
|
1403
|
-
|
|
1868
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
1869
|
+
const proof = signature(
|
|
1870
|
+
environment.clientSecret,
|
|
1871
|
+
nonce,
|
|
1872
|
+
raw,
|
|
1873
|
+
forwarding ? FORWARD_REQUEST_PROOF : void 0
|
|
1874
|
+
);
|
|
1875
|
+
if (!matches(proof, request3.headers["x-prim-proof"])) {
|
|
1404
1876
|
response.writeHead(403).end();
|
|
1405
1877
|
return;
|
|
1406
1878
|
}
|
|
@@ -1409,40 +1881,24 @@ async function startMachineBroker() {
|
|
|
1409
1881
|
response.writeHead(403).end();
|
|
1410
1882
|
return;
|
|
1411
1883
|
}
|
|
1412
|
-
|
|
1884
|
+
options.onRequest?.();
|
|
1413
1885
|
const controller = new AbortController();
|
|
1414
1886
|
response.once("close", () => {
|
|
1415
1887
|
if (!response.writableFinished) controller.abort();
|
|
1416
1888
|
});
|
|
1417
|
-
|
|
1418
|
-
try {
|
|
1419
|
-
const current = cachedMachineCredential();
|
|
1420
|
-
const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
|
|
1421
|
-
const credential = await acquireMachineCredential(
|
|
1422
|
-
{ force, signal: controller.signal },
|
|
1423
|
-
{ localEnvironment: true }
|
|
1424
|
-
);
|
|
1425
|
-
if (!credential || credential.apiUrl !== apiUrl)
|
|
1426
|
-
throw new Error("Missing machine identity");
|
|
1427
|
-
result = { credential };
|
|
1428
|
-
} catch (error) {
|
|
1429
|
-
result = {
|
|
1430
|
-
error: error instanceof MachineAuthError ? {
|
|
1431
|
-
code: error.code,
|
|
1432
|
-
message: error.message,
|
|
1433
|
-
terminal: error.terminal,
|
|
1434
|
-
retryAt: error.retryAt
|
|
1435
|
-
} : {
|
|
1436
|
-
code: "broker_unavailable",
|
|
1437
|
-
message: "Machine authentication is temporarily unavailable.",
|
|
1438
|
-
terminal: false
|
|
1439
|
-
}
|
|
1440
|
-
};
|
|
1441
|
-
}
|
|
1889
|
+
const result = forwarding ? await forwardToApi(apiUrl, data, controller.signal) : await credentialResult(apiUrl, data, controller.signal);
|
|
1442
1890
|
const body = JSON.stringify(result);
|
|
1443
1891
|
response.setHeader("Content-Type", "application/json");
|
|
1444
1892
|
response.end(
|
|
1445
|
-
JSON.stringify({
|
|
1893
|
+
JSON.stringify({
|
|
1894
|
+
body,
|
|
1895
|
+
proof: signature(
|
|
1896
|
+
environment.clientSecret,
|
|
1897
|
+
nonce,
|
|
1898
|
+
body,
|
|
1899
|
+
forwarding ? FORWARD_ANSWER_PROOF : void 0
|
|
1900
|
+
)
|
|
1901
|
+
})
|
|
1446
1902
|
);
|
|
1447
1903
|
} catch {
|
|
1448
1904
|
response.writeHead(400).end();
|
|
@@ -1451,6 +1907,21 @@ async function startMachineBroker() {
|
|
|
1451
1907
|
server.maxConnections = 64;
|
|
1452
1908
|
server.requestTimeout = 1e4;
|
|
1453
1909
|
server.headersTimeout = 1e4;
|
|
1910
|
+
return server;
|
|
1911
|
+
}
|
|
1912
|
+
async function startMachineBroker() {
|
|
1913
|
+
const environment = environmentCredentials({});
|
|
1914
|
+
if (!environment) throw new Error("Machine broker requires injected credentials");
|
|
1915
|
+
const directory = primConfigDirectory();
|
|
1916
|
+
const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
|
|
1917
|
+
const path = descriptorPath(directory, environment.generation);
|
|
1918
|
+
const nonce = randomBytes3(32).toString("hex");
|
|
1919
|
+
const server = createBrokerServer({
|
|
1920
|
+
environment,
|
|
1921
|
+
apiUrl,
|
|
1922
|
+
nonce,
|
|
1923
|
+
onRequest: () => idle.refresh()
|
|
1924
|
+
});
|
|
1454
1925
|
const close = () => {
|
|
1455
1926
|
clearTimeout(idle);
|
|
1456
1927
|
server.closeAllConnections();
|
|
@@ -1502,7 +1973,7 @@ function readTrimmed(path) {
|
|
|
1502
1973
|
function resolveAuthCredential(options = {}) {
|
|
1503
1974
|
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
1504
1975
|
const machine = cachedMachineCredential({ env: options.env });
|
|
1505
|
-
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1976
|
+
return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1506
1977
|
}
|
|
1507
1978
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
1508
1979
|
if (envToken) return { token: envToken, source: "environment" };
|
|
@@ -1711,9 +2182,9 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
1711
2182
|
}
|
|
1712
2183
|
|
|
1713
2184
|
// src/daemon/server.ts
|
|
1714
|
-
import { chmodSync as chmodSync8, existsSync as
|
|
2185
|
+
import { chmodSync as chmodSync8, existsSync as existsSync12, mkdirSync as mkdirSync10, readFileSync as readFileSync15, unlinkSync as unlinkSync3 } from "fs";
|
|
1715
2186
|
import { createServer as createServer2 } from "net";
|
|
1716
|
-
import { join as
|
|
2187
|
+
import { join as join20 } from "path";
|
|
1717
2188
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
1718
2189
|
|
|
1719
2190
|
// src/decisions/identity.ts
|
|
@@ -1799,7 +2270,7 @@ import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirS
|
|
|
1799
2270
|
import { dirname as dirname5 } from "path";
|
|
1800
2271
|
|
|
1801
2272
|
// src/daemon/client-instance-id.ts
|
|
1802
|
-
import { randomBytes as
|
|
2273
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
1803
2274
|
import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
|
|
1804
2275
|
import { join as join8 } from "path";
|
|
1805
2276
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
@@ -1862,7 +2333,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
1862
2333
|
if (existing !== void 0) {
|
|
1863
2334
|
return existing;
|
|
1864
2335
|
}
|
|
1865
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
2336
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
|
|
1866
2337
|
"base64url"
|
|
1867
2338
|
)}`;
|
|
1868
2339
|
if (!isClientInstanceId(generated)) {
|
|
@@ -1945,6 +2416,9 @@ var CREDENTIAL_FILE_MODE = 384;
|
|
|
1945
2416
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
1946
2417
|
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
1947
2418
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
2419
|
+
function authExpiredMessage() {
|
|
2420
|
+
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
2421
|
+
}
|
|
1948
2422
|
function readTrimmed2(path) {
|
|
1949
2423
|
try {
|
|
1950
2424
|
const value = readFileSync8(path, "utf8").trim();
|
|
@@ -2326,7 +2800,7 @@ var CliManagementResponseError = class extends Error {
|
|
|
2326
2800
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
2327
2801
|
async function managementResponseValue(response) {
|
|
2328
2802
|
if (response.status === 401) {
|
|
2329
|
-
throw new HttpError(401,
|
|
2803
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2330
2804
|
}
|
|
2331
2805
|
let value;
|
|
2332
2806
|
try {
|
|
@@ -2348,23 +2822,50 @@ function selectedCredential() {
|
|
|
2348
2822
|
}
|
|
2349
2823
|
return _cachedCredential;
|
|
2350
2824
|
}
|
|
2825
|
+
async function requestHeaders(method, path) {
|
|
2826
|
+
return {
|
|
2827
|
+
"Content-Type": "application/json",
|
|
2828
|
+
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
2829
|
+
};
|
|
2830
|
+
}
|
|
2351
2831
|
async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
2352
2832
|
return fetch(`${siteUrl}${path}`, {
|
|
2353
2833
|
method,
|
|
2354
|
-
headers: {
|
|
2355
|
-
Authorization: `Bearer ${token}`,
|
|
2356
|
-
"Content-Type": "application/json",
|
|
2357
|
-
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
2358
|
-
},
|
|
2834
|
+
headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
|
|
2359
2835
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
2360
2836
|
signal: options?.signal,
|
|
2361
2837
|
redirect: options?.redirect
|
|
2362
2838
|
});
|
|
2363
2839
|
}
|
|
2840
|
+
async function fetchAsMachine(credential, method, path, body, options) {
|
|
2841
|
+
if (!credential.tokenInjection)
|
|
2842
|
+
return fetchWithToken(
|
|
2843
|
+
method,
|
|
2844
|
+
path,
|
|
2845
|
+
body,
|
|
2846
|
+
{ ...options, redirect: "error" },
|
|
2847
|
+
credential.accessToken,
|
|
2848
|
+
credential.apiUrl
|
|
2849
|
+
);
|
|
2850
|
+
try {
|
|
2851
|
+
return await forwardMachineRequest(
|
|
2852
|
+
{
|
|
2853
|
+
method,
|
|
2854
|
+
path,
|
|
2855
|
+
headers: await requestHeaders(method, path),
|
|
2856
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
2857
|
+
},
|
|
2858
|
+
options.signal
|
|
2859
|
+
);
|
|
2860
|
+
} catch (error) {
|
|
2861
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
2862
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
2863
|
+
}
|
|
2864
|
+
}
|
|
2364
2865
|
async function responseValue(response) {
|
|
2365
2866
|
if (!response.ok) {
|
|
2366
2867
|
if (response.status === 401) {
|
|
2367
|
-
throw new HttpError(401,
|
|
2868
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2368
2869
|
}
|
|
2369
2870
|
const errorBody = await response.json().catch(() => null);
|
|
2370
2871
|
const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
|
|
@@ -2391,14 +2892,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2391
2892
|
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
2392
2893
|
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
|
|
2393
2894
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2394
|
-
let response = await
|
|
2395
|
-
method,
|
|
2396
|
-
path,
|
|
2397
|
-
body,
|
|
2398
|
-
{ ...requestOptions, redirect: "error" },
|
|
2399
|
-
current.accessToken,
|
|
2400
|
-
selected.apiUrl
|
|
2401
|
-
);
|
|
2895
|
+
let response = await fetchAsMachine(current, method, path, body, requestOptions);
|
|
2402
2896
|
if (response.status === 401) {
|
|
2403
2897
|
const renewed = await acquireMachineCredential({
|
|
2404
2898
|
force: true,
|
|
@@ -2407,19 +2901,14 @@ async function machineClient(options = {}, management = false) {
|
|
|
2407
2901
|
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
|
|
2408
2902
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2409
2903
|
}
|
|
2410
|
-
response = await
|
|
2411
|
-
method,
|
|
2412
|
-
path,
|
|
2413
|
-
body,
|
|
2414
|
-
{ ...requestOptions, redirect: "error" },
|
|
2415
|
-
renewed.accessToken,
|
|
2416
|
-
renewed.apiUrl
|
|
2417
|
-
);
|
|
2904
|
+
response = await fetchAsMachine(renewed, method, path, body, requestOptions);
|
|
2418
2905
|
}
|
|
2419
2906
|
if (response.status === 401)
|
|
2420
2907
|
throw new HttpError(
|
|
2421
2908
|
401,
|
|
2422
|
-
"Machine access was rejected.
|
|
2909
|
+
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(
|
|
2910
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
2911
|
+
)
|
|
2423
2912
|
);
|
|
2424
2913
|
return parse(response);
|
|
2425
2914
|
};
|
|
@@ -2429,7 +2918,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2429
2918
|
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
2430
2919
|
};
|
|
2431
2920
|
}
|
|
2432
|
-
async function
|
|
2921
|
+
async function request2(method, path, body, options) {
|
|
2433
2922
|
const machine = await machineClient(options);
|
|
2434
2923
|
if (machine)
|
|
2435
2924
|
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
@@ -2445,10 +2934,10 @@ async function request(method, path, body, options) {
|
|
|
2445
2934
|
if (token) credential = { token, source: "token_file" };
|
|
2446
2935
|
}
|
|
2447
2936
|
if (!credential) {
|
|
2448
|
-
throw new HttpError(401,
|
|
2937
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2449
2938
|
}
|
|
2450
2939
|
if (isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
2451
|
-
throw new HttpError(401,
|
|
2940
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2452
2941
|
}
|
|
2453
2942
|
const tokenUsed = credential.token;
|
|
2454
2943
|
let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
|
|
@@ -2471,8 +2960,8 @@ async function request(method, path, body, options) {
|
|
|
2471
2960
|
}
|
|
2472
2961
|
function getClient() {
|
|
2473
2962
|
return {
|
|
2474
|
-
get: (path, options) =>
|
|
2475
|
-
post: (path, body, options) =>
|
|
2963
|
+
get: (path, options) => request2("GET", path, void 0, options),
|
|
2964
|
+
post: (path, body, options) => request2("POST", path, body, options)
|
|
2476
2965
|
};
|
|
2477
2966
|
}
|
|
2478
2967
|
async function getPinnedClient(options = {}) {
|
|
@@ -2488,7 +2977,7 @@ async function getPinnedClient(options = {}) {
|
|
|
2488
2977
|
if (token2) credential = { token: token2, source: "token_file" };
|
|
2489
2978
|
}
|
|
2490
2979
|
if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
2491
|
-
throw new HttpError(401,
|
|
2980
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2492
2981
|
}
|
|
2493
2982
|
const token = credential.token;
|
|
2494
2983
|
const pinnedRequest = async (method, path, body, requestOptions) => responseValue(await fetchWithToken(method, path, body, requestOptions, token, siteUrl));
|
|
@@ -2500,10 +2989,10 @@ async function getPinnedClient(options = {}) {
|
|
|
2500
2989
|
|
|
2501
2990
|
// src/flusher.ts
|
|
2502
2991
|
import { createReadStream, renameSync as renameSync3, statSync as statSync2, unlinkSync } from "fs";
|
|
2503
|
-
import { dirname as dirname10, join as
|
|
2992
|
+
import { dirname as dirname10, join as join16 } from "path";
|
|
2504
2993
|
|
|
2505
2994
|
// src/dead-letter.ts
|
|
2506
|
-
import { createHash as createHash7, randomBytes as
|
|
2995
|
+
import { createHash as createHash7, randomBytes as randomBytes5 } from "crypto";
|
|
2507
2996
|
import {
|
|
2508
2997
|
constants as constants2,
|
|
2509
2998
|
chmodSync as chmodSync4,
|
|
@@ -2515,7 +3004,7 @@ import {
|
|
|
2515
3004
|
openSync as openSync2,
|
|
2516
3005
|
renameSync as renameSync2,
|
|
2517
3006
|
rmSync as rmSync7,
|
|
2518
|
-
writeFileSync as
|
|
3007
|
+
writeFileSync as writeFileSync4
|
|
2519
3008
|
} from "fs";
|
|
2520
3009
|
import { dirname as dirname6, join as join10 } from "path";
|
|
2521
3010
|
var DIRECTORY_MODE2 = 448;
|
|
@@ -2542,14 +3031,14 @@ function persistDeadLetter(directory, path, quarantineId, record, persistDirecto
|
|
|
2542
3031
|
}
|
|
2543
3032
|
const temporaryPath = join10(
|
|
2544
3033
|
directory,
|
|
2545
|
-
`.${quarantineId}.${String(process.pid)}.${
|
|
3034
|
+
`.${quarantineId}.${String(process.pid)}.${randomBytes5(8).toString("hex")}.tmp`
|
|
2546
3035
|
);
|
|
2547
3036
|
const flags = constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY | constants2.O_NOFOLLOW;
|
|
2548
3037
|
try {
|
|
2549
3038
|
const fd = openSync2(temporaryPath, flags, FILE_MODE2);
|
|
2550
3039
|
try {
|
|
2551
3040
|
fchmodSync2(fd, FILE_MODE2);
|
|
2552
|
-
|
|
3041
|
+
writeFileSync4(fd, `${JSON.stringify(record)}
|
|
2553
3042
|
`, "utf8");
|
|
2554
3043
|
fsyncSync2(fd);
|
|
2555
3044
|
} finally {
|
|
@@ -2605,7 +3094,7 @@ import {
|
|
|
2605
3094
|
chmodSync as chmodSync5,
|
|
2606
3095
|
existsSync as existsSync6,
|
|
2607
3096
|
readFileSync as readFileSync9,
|
|
2608
|
-
readdirSync,
|
|
3097
|
+
readdirSync as readdirSync2,
|
|
2609
3098
|
rmSync as rmSync8,
|
|
2610
3099
|
rmdirSync
|
|
2611
3100
|
} from "fs";
|
|
@@ -2669,7 +3158,7 @@ function sweepOrphanedDrainCheckpoints(bucketDirectory) {
|
|
|
2669
3158
|
const directory = join11(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
|
|
2670
3159
|
let names;
|
|
2671
3160
|
try {
|
|
2672
|
-
names =
|
|
3161
|
+
names = readdirSync2(directory);
|
|
2673
3162
|
} catch {
|
|
2674
3163
|
return;
|
|
2675
3164
|
}
|
|
@@ -29376,9 +29865,25 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
|
|
|
29376
29865
|
|
|
29377
29866
|
// src/lib/activation.ts
|
|
29378
29867
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
29379
|
-
import { existsSync as
|
|
29868
|
+
import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
|
|
29380
29869
|
import { homedir as homedir2 } from "os";
|
|
29870
|
+
import { join as join14 } from "path";
|
|
29871
|
+
|
|
29872
|
+
// src/lib/cloud-prepared.ts
|
|
29873
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync10, rmSync as rmSync9, writeFileSync as writeFileSync5 } from "fs";
|
|
29381
29874
|
import { join as join12 } from "path";
|
|
29875
|
+
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
29876
|
+
function cloudPreparedPath(env = process.env) {
|
|
29877
|
+
return join12(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
29878
|
+
}
|
|
29879
|
+
function isPreparedCloudSession(env = process.env) {
|
|
29880
|
+
if (!isClaudeCloudSession(env)) return false;
|
|
29881
|
+
try {
|
|
29882
|
+
return existsSync7(cloudPreparedPath(env));
|
|
29883
|
+
} catch {
|
|
29884
|
+
return false;
|
|
29885
|
+
}
|
|
29886
|
+
}
|
|
29382
29887
|
|
|
29383
29888
|
// src/lib/demo-pause.ts
|
|
29384
29889
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
@@ -29444,11 +29949,12 @@ function healDemoPause(cwd, pause, options = {}) {
|
|
|
29444
29949
|
// src/lib/git.ts
|
|
29445
29950
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
29446
29951
|
import { createHash as createHash8 } from "crypto";
|
|
29447
|
-
import { lstatSync as lstatSync5, realpathSync } from "fs";
|
|
29448
|
-
import { basename as basename3, dirname as dirname8, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
|
|
29952
|
+
import { lstatSync as lstatSync5, readFileSync as readFileSync11, realpathSync } from "fs";
|
|
29953
|
+
import { basename as basename3, dirname as dirname8, isAbsolute as isAbsolute3, join as join13, relative, resolve as resolve2, sep } from "path";
|
|
29449
29954
|
var GIT_TIMEOUT_MS2 = 1e3;
|
|
29955
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
29450
29956
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
29451
|
-
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
29957
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
29452
29958
|
function gitToplevel(cwd) {
|
|
29453
29959
|
try {
|
|
29454
29960
|
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
@@ -29474,23 +29980,83 @@ function gitValue(cwd, args) {
|
|
|
29474
29980
|
return void 0;
|
|
29475
29981
|
}
|
|
29476
29982
|
}
|
|
29477
|
-
function
|
|
29478
|
-
const
|
|
29479
|
-
if (
|
|
29983
|
+
function parseGithubRepositoryName(path) {
|
|
29984
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
29985
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
29986
|
+
return null;
|
|
29987
|
+
}
|
|
29988
|
+
return `${parts[0]}/${parts[1]}`;
|
|
29989
|
+
}
|
|
29990
|
+
function githubRepositoryFromRemote(remote) {
|
|
29991
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
29480
29992
|
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
29481
29993
|
remote
|
|
29482
29994
|
);
|
|
29483
29995
|
const path = match?.[1] ?? match?.[2];
|
|
29484
|
-
|
|
29485
|
-
|
|
29486
|
-
|
|
29996
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
29997
|
+
}
|
|
29998
|
+
function checkoutSettingsText(repoRoot) {
|
|
29999
|
+
const path = join13(repoRoot, ".claude", "settings.json");
|
|
30000
|
+
try {
|
|
30001
|
+
if (!lstatSync5(join13(repoRoot, ".claude")).isDirectory()) return null;
|
|
30002
|
+
const stat = lstatSync5(path);
|
|
30003
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
30004
|
+
return readFileSync11(path, "utf8");
|
|
30005
|
+
} catch {
|
|
29487
30006
|
return null;
|
|
29488
30007
|
}
|
|
29489
|
-
|
|
30008
|
+
}
|
|
30009
|
+
function checkoutDeclaration(repoRoot, name) {
|
|
30010
|
+
const text = checkoutSettingsText(repoRoot);
|
|
30011
|
+
if (text === null) return null;
|
|
30012
|
+
let parsed;
|
|
30013
|
+
try {
|
|
30014
|
+
parsed = JSON.parse(text);
|
|
30015
|
+
} catch {
|
|
30016
|
+
return null;
|
|
30017
|
+
}
|
|
30018
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
30019
|
+
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
30020
|
+
return typeof value === "string" ? value : null;
|
|
30021
|
+
}
|
|
30022
|
+
function declaredGithubRepository(repoRoot) {
|
|
30023
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
30024
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
30025
|
+
}
|
|
30026
|
+
function githubRepositoryFullName(cwd) {
|
|
30027
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
30028
|
+
if (remote) {
|
|
30029
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
30030
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
30031
|
+
}
|
|
30032
|
+
const root = gitToplevel(cwd);
|
|
30033
|
+
return root ? declaredGithubRepository(root) : null;
|
|
30034
|
+
}
|
|
30035
|
+
function normalizeOriginRemote(remote) {
|
|
30036
|
+
const value = remote.trim();
|
|
30037
|
+
if (!value) return void 0;
|
|
30038
|
+
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
30039
|
+
if (scp?.host && scp.path) {
|
|
30040
|
+
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
30041
|
+
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
30042
|
+
}
|
|
30043
|
+
try {
|
|
30044
|
+
const url = new URL(value);
|
|
30045
|
+
url.username = "";
|
|
30046
|
+
url.password = "";
|
|
30047
|
+
url.search = "";
|
|
30048
|
+
url.hash = "";
|
|
30049
|
+
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
30050
|
+
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
30051
|
+
return void 0;
|
|
30052
|
+
} catch {
|
|
30053
|
+
return void 0;
|
|
30054
|
+
}
|
|
29490
30055
|
}
|
|
29491
30056
|
|
|
29492
30057
|
// src/lib/activation.ts
|
|
29493
30058
|
var PRIM_ACTIVE_KEY = "prim.active";
|
|
30059
|
+
var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
|
|
29494
30060
|
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
29495
30061
|
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
29496
30062
|
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
@@ -29554,14 +30120,13 @@ function repositoryBindingState(cwd) {
|
|
|
29554
30120
|
if (marker !== void 0) return "invalid";
|
|
29555
30121
|
return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
|
|
29556
30122
|
}
|
|
29557
|
-
function
|
|
29558
|
-
const root = gitToplevel(cwd);
|
|
30123
|
+
function projectPrimInstallAt(root) {
|
|
29559
30124
|
if (root === null || root === homedir2()) return false;
|
|
29560
30125
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
29561
|
-
const path =
|
|
29562
|
-
if (
|
|
30126
|
+
const path = join14(root, rel);
|
|
30127
|
+
if (existsSync8(path)) {
|
|
29563
30128
|
try {
|
|
29564
|
-
const content =
|
|
30129
|
+
const content = readFileSync12(path, "utf-8");
|
|
29565
30130
|
if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
|
|
29566
30131
|
} catch {
|
|
29567
30132
|
}
|
|
@@ -29569,12 +30134,27 @@ function hasProjectPrimInstall(cwd) {
|
|
|
29569
30134
|
}
|
|
29570
30135
|
return false;
|
|
29571
30136
|
}
|
|
30137
|
+
var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
|
|
30138
|
+
function declaresInactiveAt(root) {
|
|
30139
|
+
if (root === null || root === homedir2()) return false;
|
|
30140
|
+
if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
|
|
30141
|
+
const text = checkoutSettingsText(root);
|
|
30142
|
+
if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
|
|
30143
|
+
try {
|
|
30144
|
+
JSON.parse(text);
|
|
30145
|
+
return false;
|
|
30146
|
+
} catch {
|
|
30147
|
+
return true;
|
|
30148
|
+
}
|
|
30149
|
+
}
|
|
29572
30150
|
function isRepoActiveForCapture(cwd, options = {}) {
|
|
29573
30151
|
let { active: flag, pause } = readCaptureConfig(cwd);
|
|
29574
30152
|
if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
|
|
29575
30153
|
if (flag === "true") return true;
|
|
29576
30154
|
if (flag === "false") return false;
|
|
29577
|
-
|
|
30155
|
+
const root = gitToplevel(cwd);
|
|
30156
|
+
if (declaresInactiveAt(root)) return false;
|
|
30157
|
+
return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
|
|
29578
30158
|
}
|
|
29579
30159
|
function decisionIngestionStatus(cwd) {
|
|
29580
30160
|
return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
|
|
@@ -29860,11 +30440,15 @@ function classifyJournalBuckets(buckets, binding) {
|
|
|
29860
30440
|
continue;
|
|
29861
30441
|
}
|
|
29862
30442
|
if (binding.captureAuthorityKind === "workos_m2m") {
|
|
29863
|
-
|
|
29864
|
-
|
|
30443
|
+
const apiUrl = machineApiUrl(getSiteUrl());
|
|
30444
|
+
if (binding.clientId && (bucket === machineJournalBucket({
|
|
30445
|
+
apiUrl,
|
|
29865
30446
|
clientId: binding.clientId,
|
|
29866
30447
|
authorizedUserId: binding.authorizedUserId
|
|
29867
|
-
})
|
|
30448
|
+
}) || // What this client captured before its identity was verified. Those
|
|
30449
|
+
// belong to whoever the server says the client is, which is now
|
|
30450
|
+
// known; no verified identity's bucket is opened this way.
|
|
30451
|
+
bucket === machinePendingBucket({ apiUrl, clientId: binding.clientId })))
|
|
29868
30452
|
deliverableBuckets.add(bucket);
|
|
29869
30453
|
else
|
|
29870
30454
|
retainedBuckets.push({
|
|
@@ -29887,14 +30471,17 @@ function classifyJournalBuckets(buckets, binding) {
|
|
|
29887
30471
|
}
|
|
29888
30472
|
function buildOrganizationBoundMoveRequest(batch, binding) {
|
|
29889
30473
|
const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
|
|
29890
|
-
const
|
|
30474
|
+
const request3 = {
|
|
29891
30475
|
batch: batch.map((move) => {
|
|
29892
30476
|
if (typeof move !== "object" || move === null || Array.isArray(move)) {
|
|
29893
30477
|
return move;
|
|
29894
30478
|
}
|
|
29895
30479
|
const { captureActor, ...wireMove } = move;
|
|
29896
30480
|
if (binding.captureAuthorityKind === "workos_m2m") {
|
|
29897
|
-
if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.
|
|
30481
|
+
if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.apiUrl !== machineApiUrl(getSiteUrl()) || // An identity-pending actor names only its client and is bound to
|
|
30482
|
+
// the identity verified for it. Any other actor is a claim about a
|
|
30483
|
+
// verified identity and must match this one exactly.
|
|
30484
|
+
!identityPending(captureActor) && (captureActor.authorizedUserId !== binding.authorizedUserId || captureActor.machineId && captureActor.machineId !== binding.machineId || captureActor.organizationId && captureActor.organizationId !== binding.organizationId))
|
|
29898
30485
|
throw new InvalidJournalEnvelopeError();
|
|
29899
30486
|
} else if (captureActor) throw new InvalidJournalEnvelopeError();
|
|
29900
30487
|
return {
|
|
@@ -29910,10 +30497,10 @@ function buildOrganizationBoundMoveRequest(batch, binding) {
|
|
|
29910
30497
|
};
|
|
29911
30498
|
})
|
|
29912
30499
|
};
|
|
29913
|
-
if (!isMoveIngestRequest(
|
|
30500
|
+
if (!isMoveIngestRequest(request3)) {
|
|
29914
30501
|
throw new InvalidJournalEnvelopeError();
|
|
29915
30502
|
}
|
|
29916
|
-
return
|
|
30503
|
+
return request3;
|
|
29917
30504
|
}
|
|
29918
30505
|
async function inspectJournalDelivery(buckets, options = {}) {
|
|
29919
30506
|
const bucketList = [...new Set(buckets)];
|
|
@@ -29948,17 +30535,17 @@ async function inspectJournalDelivery(buckets, options = {}) {
|
|
|
29948
30535
|
import {
|
|
29949
30536
|
appendFileSync,
|
|
29950
30537
|
closeSync as closeSync3,
|
|
29951
|
-
existsSync as
|
|
30538
|
+
existsSync as existsSync9,
|
|
29952
30539
|
fstatSync,
|
|
29953
|
-
mkdirSync as
|
|
30540
|
+
mkdirSync as mkdirSync7,
|
|
29954
30541
|
openSync as openSync3,
|
|
29955
30542
|
opendirSync,
|
|
29956
|
-
readFileSync as
|
|
30543
|
+
readFileSync as readFileSync13,
|
|
29957
30544
|
readSync,
|
|
29958
|
-
readdirSync as
|
|
30545
|
+
readdirSync as readdirSync3
|
|
29959
30546
|
} from "fs";
|
|
29960
|
-
import { dirname as dirname9, join as
|
|
29961
|
-
var JOURNAL_DIR =
|
|
30547
|
+
import { dirname as dirname9, join as join15 } from "path";
|
|
30548
|
+
var JOURNAL_DIR = join15(primConfigDirectory(), "moves");
|
|
29962
30549
|
var JOURNAL_BASENAME = "journal.ndjson";
|
|
29963
30550
|
var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
|
|
29964
30551
|
var PENDING_STATS_MAX_FILES = 128;
|
|
@@ -29970,7 +30557,7 @@ function envSlug(apiUrl) {
|
|
|
29970
30557
|
return slug;
|
|
29971
30558
|
}
|
|
29972
30559
|
function currentEnvDir() {
|
|
29973
|
-
return
|
|
30560
|
+
return join15(JOURNAL_DIR, envSlug(getSiteUrl()));
|
|
29974
30561
|
}
|
|
29975
30562
|
function parseMoves(content) {
|
|
29976
30563
|
const moves = [];
|
|
@@ -29988,15 +30575,15 @@ function parseMoves(content) {
|
|
|
29988
30575
|
function listBuckets() {
|
|
29989
30576
|
const out = [];
|
|
29990
30577
|
const envDir = currentEnvDir();
|
|
29991
|
-
if (!
|
|
30578
|
+
if (!existsSync9(envDir)) {
|
|
29992
30579
|
return out;
|
|
29993
30580
|
}
|
|
29994
|
-
for (const entry of
|
|
30581
|
+
for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
|
|
29995
30582
|
if (!entry.isDirectory()) {
|
|
29996
30583
|
continue;
|
|
29997
30584
|
}
|
|
29998
|
-
const path =
|
|
29999
|
-
if (
|
|
30585
|
+
const path = join15(envDir, entry.name, JOURNAL_BASENAME);
|
|
30586
|
+
if (existsSync9(path)) {
|
|
30000
30587
|
out.push({ bucket: entry.name, path });
|
|
30001
30588
|
}
|
|
30002
30589
|
}
|
|
@@ -30058,7 +30645,7 @@ function parseFlushingPid(name) {
|
|
|
30058
30645
|
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
30059
30646
|
}
|
|
30060
30647
|
function listFlushingInDir(dir, bucket, options = {}) {
|
|
30061
|
-
if (!
|
|
30648
|
+
if (!existsSync9(dir)) {
|
|
30062
30649
|
return [];
|
|
30063
30650
|
}
|
|
30064
30651
|
const out = [];
|
|
@@ -30072,7 +30659,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
30072
30659
|
entry = entries.readSync();
|
|
30073
30660
|
continue;
|
|
30074
30661
|
}
|
|
30075
|
-
const path =
|
|
30662
|
+
const path = join15(dir, entry.name);
|
|
30076
30663
|
let sample;
|
|
30077
30664
|
try {
|
|
30078
30665
|
sample = sampleJournalFile(path, remainingBytes, { fromDrainCheckpoint: true });
|
|
@@ -30099,18 +30686,18 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
30099
30686
|
}
|
|
30100
30687
|
function listFlushing(options = {}) {
|
|
30101
30688
|
const envDir = currentEnvDir();
|
|
30102
|
-
if (!
|
|
30689
|
+
if (!existsSync9(envDir)) {
|
|
30103
30690
|
return [];
|
|
30104
30691
|
}
|
|
30105
30692
|
const out = [];
|
|
30106
30693
|
let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
|
|
30107
30694
|
const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
|
|
30108
|
-
for (const entry of
|
|
30695
|
+
for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
|
|
30109
30696
|
if (out.length >= maxFiles) {
|
|
30110
30697
|
break;
|
|
30111
30698
|
}
|
|
30112
30699
|
if (entry.isDirectory()) {
|
|
30113
|
-
const found = listFlushingInDir(
|
|
30700
|
+
const found = listFlushingInDir(join15(envDir, entry.name), entry.name, {
|
|
30114
30701
|
sampleBytes: remainingBytes,
|
|
30115
30702
|
maxFiles: maxFiles - out.length
|
|
30116
30703
|
});
|
|
@@ -30125,12 +30712,12 @@ function listFlushing(options = {}) {
|
|
|
30125
30712
|
}
|
|
30126
30713
|
function sweepOrphanedDrainProgress() {
|
|
30127
30714
|
const envDir = currentEnvDir();
|
|
30128
|
-
if (!
|
|
30715
|
+
if (!existsSync9(envDir)) {
|
|
30129
30716
|
return;
|
|
30130
30717
|
}
|
|
30131
|
-
for (const entry of
|
|
30718
|
+
for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
|
|
30132
30719
|
if (entry.isDirectory()) {
|
|
30133
|
-
sweepOrphanedDrainCheckpoints(
|
|
30720
|
+
sweepOrphanedDrainCheckpoints(join15(envDir, entry.name));
|
|
30134
30721
|
}
|
|
30135
30722
|
}
|
|
30136
30723
|
}
|
|
@@ -30309,11 +30896,11 @@ async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
|
|
|
30309
30896
|
const postBatch = async (batch2) => {
|
|
30310
30897
|
const moves = batch2.map((entry) => entry.move);
|
|
30311
30898
|
try {
|
|
30312
|
-
const
|
|
30313
|
-
if (Buffer.byteLength(JSON.stringify(
|
|
30899
|
+
const request3 = buildOrganizationBoundMoveRequest(moves, binding);
|
|
30900
|
+
if (Buffer.byteLength(JSON.stringify(request3)) > MAX_INGEST_REQUEST_BYTES) {
|
|
30314
30901
|
throw new IngestRequestTooLargeError();
|
|
30315
30902
|
}
|
|
30316
|
-
const response = await client2.post("/api/cli/moves/ingest",
|
|
30903
|
+
const response = await client2.post("/api/cli/moves/ingest", request3, {
|
|
30317
30904
|
signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
|
|
30318
30905
|
});
|
|
30319
30906
|
requireDurableIngestAcknowledgement(response, moves.length, collectionScopeRoots(moves));
|
|
@@ -30544,7 +31131,7 @@ async function flushOnce() {
|
|
|
30544
31131
|
return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
|
|
30545
31132
|
}
|
|
30546
31133
|
var flushInFlight;
|
|
30547
|
-
var FLUSH_LOCK_PATH =
|
|
31134
|
+
var FLUSH_LOCK_PATH = join16(dirname10(JOURNAL_DIR), ".flush.lock");
|
|
30548
31135
|
var FLUSH_LOCK_TIMEOUT_MS = 250;
|
|
30549
31136
|
function isFlushLockContended(error) {
|
|
30550
31137
|
return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
|
|
@@ -30746,14 +31333,14 @@ var StatuslineIngestionCache = class {
|
|
|
30746
31333
|
|
|
30747
31334
|
// src/daemon/client.ts
|
|
30748
31335
|
import { createConnection } from "net";
|
|
30749
|
-
import { join as
|
|
30750
|
-
var SOCK_PATH =
|
|
31336
|
+
import { join as join17 } from "path";
|
|
31337
|
+
var SOCK_PATH = join17(primConfigDirectory(), "sock");
|
|
30751
31338
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
30752
31339
|
var nextRequestId = 1;
|
|
30753
31340
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
30754
31341
|
const id = nextRequestId++;
|
|
30755
31342
|
const caller = resolveDaemonPrincipal();
|
|
30756
|
-
const
|
|
31343
|
+
const request3 = {
|
|
30757
31344
|
id,
|
|
30758
31345
|
method,
|
|
30759
31346
|
params,
|
|
@@ -30792,7 +31379,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
30792
31379
|
});
|
|
30793
31380
|
socket.on("connect", () => {
|
|
30794
31381
|
try {
|
|
30795
|
-
socket?.write(`${JSON.stringify(
|
|
31382
|
+
socket?.write(`${JSON.stringify(request3)}
|
|
30796
31383
|
`);
|
|
30797
31384
|
} catch {
|
|
30798
31385
|
clearTimeout(timer);
|
|
@@ -30837,7 +31424,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
30837
31424
|
}
|
|
30838
31425
|
|
|
30839
31426
|
// src/daemon/decision-digest-cache.ts
|
|
30840
|
-
import { randomBytes as
|
|
31427
|
+
import { randomBytes as randomBytes6 } from "crypto";
|
|
30841
31428
|
var DECISION_DIGEST_CACHE_WARMING = "daemon Decision cache warming";
|
|
30842
31429
|
var DECISION_DIGEST_CACHE_LIMIT = 100;
|
|
30843
31430
|
var DECISION_DIGEST_CACHE_WINDOW = "24h";
|
|
@@ -30867,7 +31454,7 @@ function errorMessage(error) {
|
|
|
30867
31454
|
return error instanceof Error ? error.message : String(error);
|
|
30868
31455
|
}
|
|
30869
31456
|
function privatePageToken() {
|
|
30870
|
-
return
|
|
31457
|
+
return randomBytes6(16).toString("hex");
|
|
30871
31458
|
}
|
|
30872
31459
|
var DecisionDigestCache = class {
|
|
30873
31460
|
constructor(load, now = Date.now, options = {}) {
|
|
@@ -31018,8 +31605,8 @@ function assertCallerEnvMatches(callerEnv, boundEnv) {
|
|
|
31018
31605
|
}
|
|
31019
31606
|
|
|
31020
31607
|
// src/daemon/health.ts
|
|
31021
|
-
import { chmodSync as chmodSync6, existsSync as
|
|
31022
|
-
import { dirname as dirname11, join as
|
|
31608
|
+
import { chmodSync as chmodSync6, existsSync as existsSync10, mkdirSync as mkdirSync8, renameSync as renameSync4, writeFileSync as writeFileSync6 } from "fs";
|
|
31609
|
+
import { dirname as dirname11, join as join18 } from "path";
|
|
31023
31610
|
var CONFIG_DIR_MODE2 = 448;
|
|
31024
31611
|
var HEALTH_FILE_MODE = 384;
|
|
31025
31612
|
var INGESTION_SLA_MS = 3e4;
|
|
@@ -31027,7 +31614,7 @@ var HEARTBEAT_FRESH_MS = 9e4;
|
|
|
31027
31614
|
var HEARTBEAT_RETRY_CAP_MS = 3e4;
|
|
31028
31615
|
var INGESTION_RETRY_BASE_MS = 5e3;
|
|
31029
31616
|
var INGESTION_RETRY_CAP_MS = 15e3;
|
|
31030
|
-
var DAEMON_HEALTH_PATH =
|
|
31617
|
+
var DAEMON_HEALTH_PATH = join18(primConfigDirectory(), "daemon-health.json");
|
|
31031
31618
|
function createDaemonHealthState(version, pid, startedAt2, siteUrl) {
|
|
31032
31619
|
return {
|
|
31033
31620
|
schemaVersion: 1,
|
|
@@ -31069,11 +31656,11 @@ function ingestionRetryDelayMs(consecutiveFailures, random = Math.random) {
|
|
|
31069
31656
|
}
|
|
31070
31657
|
function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
|
|
31071
31658
|
const dir = dirname11(path);
|
|
31072
|
-
if (!
|
|
31073
|
-
|
|
31659
|
+
if (!existsSync10(dir)) {
|
|
31660
|
+
mkdirSync8(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
|
|
31074
31661
|
}
|
|
31075
|
-
const tmp =
|
|
31076
|
-
|
|
31662
|
+
const tmp = join18(dir, `.${process.pid}.daemon-health.tmp`);
|
|
31663
|
+
writeFileSync6(tmp, `${JSON.stringify(state, null, 2)}
|
|
31077
31664
|
`, { mode: HEALTH_FILE_MODE });
|
|
31078
31665
|
chmodSync6(tmp, HEALTH_FILE_MODE);
|
|
31079
31666
|
renameSync4(tmp, path);
|
|
@@ -31083,22 +31670,22 @@ function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
|
|
|
31083
31670
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
31084
31671
|
import {
|
|
31085
31672
|
chmodSync as chmodSync7,
|
|
31086
|
-
existsSync as
|
|
31087
|
-
mkdirSync as
|
|
31088
|
-
readFileSync as
|
|
31673
|
+
existsSync as existsSync11,
|
|
31674
|
+
mkdirSync as mkdirSync9,
|
|
31675
|
+
readFileSync as readFileSync14,
|
|
31089
31676
|
renameSync as renameSync5,
|
|
31090
|
-
rmSync as
|
|
31677
|
+
rmSync as rmSync10,
|
|
31091
31678
|
statSync as statSync3,
|
|
31092
31679
|
unlinkSync as unlinkSync2,
|
|
31093
|
-
writeFileSync as
|
|
31680
|
+
writeFileSync as writeFileSync7
|
|
31094
31681
|
} from "fs";
|
|
31095
|
-
import { join as
|
|
31682
|
+
import { join as join19 } from "path";
|
|
31096
31683
|
var DIR_MODE = 448;
|
|
31097
31684
|
var FILE_MODE4 = 384;
|
|
31098
31685
|
var DAEMON_STARTUP_GRACE_MS = 5e3;
|
|
31099
31686
|
function readLockRecord(path) {
|
|
31100
31687
|
try {
|
|
31101
|
-
const value = JSON.parse(
|
|
31688
|
+
const value = JSON.parse(readFileSync14(path, "utf-8"));
|
|
31102
31689
|
if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.instanceId === "string" && typeof value.startedAt === "number") {
|
|
31103
31690
|
return value;
|
|
31104
31691
|
}
|
|
@@ -31108,17 +31695,17 @@ function readLockRecord(path) {
|
|
|
31108
31695
|
}
|
|
31109
31696
|
function numericPid(path) {
|
|
31110
31697
|
try {
|
|
31111
|
-
const pid = Number(
|
|
31698
|
+
const pid = Number(readFileSync14(path, "utf-8").trim());
|
|
31112
31699
|
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
31113
31700
|
} catch {
|
|
31114
31701
|
return;
|
|
31115
31702
|
}
|
|
31116
31703
|
}
|
|
31117
31704
|
function readDaemonOwner(configDir) {
|
|
31118
|
-
return readLockRecord(
|
|
31705
|
+
return readLockRecord(join19(configDir, "daemon.lock", "owner.json"));
|
|
31119
31706
|
}
|
|
31120
31707
|
function readDaemonPid(configDir) {
|
|
31121
|
-
const path =
|
|
31708
|
+
const path = join19(configDir, "daemon.pid");
|
|
31122
31709
|
const pid = numericPid(path);
|
|
31123
31710
|
if (pid === void 0) {
|
|
31124
31711
|
return;
|
|
@@ -31133,16 +31720,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31133
31720
|
const pid = opts.pid ?? process.pid;
|
|
31134
31721
|
const now = opts.now ?? Date.now();
|
|
31135
31722
|
const isAlive = opts.isAlive ?? processIsAlive;
|
|
31136
|
-
const lockDir =
|
|
31137
|
-
const ownerPath2 =
|
|
31138
|
-
const pidPath =
|
|
31723
|
+
const lockDir = join19(configDir, "daemon.lock");
|
|
31724
|
+
const ownerPath2 = join19(lockDir, "owner.json");
|
|
31725
|
+
const pidPath = join19(configDir, "daemon.pid");
|
|
31139
31726
|
const instanceId2 = randomUUID3();
|
|
31140
|
-
if (!
|
|
31141
|
-
|
|
31727
|
+
if (!existsSync11(configDir)) {
|
|
31728
|
+
mkdirSync9(configDir, { recursive: true, mode: DIR_MODE });
|
|
31142
31729
|
}
|
|
31143
31730
|
for (; ; ) {
|
|
31144
31731
|
try {
|
|
31145
|
-
|
|
31732
|
+
mkdirSync9(lockDir, { mode: DIR_MODE });
|
|
31146
31733
|
break;
|
|
31147
31734
|
} catch (err) {
|
|
31148
31735
|
if (err.code !== "EEXIST") {
|
|
@@ -31169,7 +31756,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31169
31756
|
const stale = `${lockDir}.stale.${String(pid)}.${instanceId2}`;
|
|
31170
31757
|
try {
|
|
31171
31758
|
renameSync5(lockDir, stale);
|
|
31172
|
-
|
|
31759
|
+
rmSync10(stale, { recursive: true, force: true });
|
|
31173
31760
|
} catch (renameErr) {
|
|
31174
31761
|
if (renameErr.code !== "ENOENT") {
|
|
31175
31762
|
throw renameErr;
|
|
@@ -31186,15 +31773,15 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31186
31773
|
instanceId: instanceId2
|
|
31187
31774
|
};
|
|
31188
31775
|
const record = { pid, instanceId: instanceId2, startedAt: now };
|
|
31189
|
-
|
|
31776
|
+
writeFileSync7(ownerPath2, `${JSON.stringify(record)}
|
|
31190
31777
|
`, { mode: FILE_MODE4 });
|
|
31191
31778
|
chmodSync7(ownerPath2, FILE_MODE4);
|
|
31192
31779
|
const legacyPid = numericPid(pidPath);
|
|
31193
31780
|
if (legacyPid !== void 0 && legacyPid !== pid && isAlive(legacyPid)) {
|
|
31194
|
-
|
|
31781
|
+
rmSync10(lockDir, { recursive: true, force: true });
|
|
31195
31782
|
throw new Error(`daemon already running (pid=${String(legacyPid)})`);
|
|
31196
31783
|
}
|
|
31197
|
-
|
|
31784
|
+
writeFileSync7(pidPath, String(pid), { mode: FILE_MODE4 });
|
|
31198
31785
|
chmodSync7(pidPath, FILE_MODE4);
|
|
31199
31786
|
return ownership2;
|
|
31200
31787
|
}
|
|
@@ -31225,7 +31812,7 @@ function releaseDaemonOwnership(ownership2, socketPath) {
|
|
|
31225
31812
|
}
|
|
31226
31813
|
}
|
|
31227
31814
|
}
|
|
31228
|
-
|
|
31815
|
+
rmSync10(ownership2.lockDir, { recursive: true, force: true });
|
|
31229
31816
|
if (cleanupError) {
|
|
31230
31817
|
throw cleanupError;
|
|
31231
31818
|
}
|
|
@@ -31262,15 +31849,15 @@ function isLegacyHeartbeatResponse(value) {
|
|
|
31262
31849
|
) && hasOptionalField(value, "unavailable", (candidate) => typeof candidate === "string");
|
|
31263
31850
|
}
|
|
31264
31851
|
function buildPresenceHeartbeatRequest(sessionId, clientInstanceId2) {
|
|
31265
|
-
const
|
|
31852
|
+
const request3 = {
|
|
31266
31853
|
sessionId,
|
|
31267
31854
|
clientInstanceId: clientInstanceId2,
|
|
31268
31855
|
decisionLifecycleProtocolVersion: DECISION_LIFECYCLE_PROTOCOL_VERSION
|
|
31269
31856
|
};
|
|
31270
|
-
if (!isPresenceHeartbeatRequest(
|
|
31857
|
+
if (!isPresenceHeartbeatRequest(request3)) {
|
|
31271
31858
|
throw new Error("presence heartbeat identity or session is invalid");
|
|
31272
31859
|
}
|
|
31273
|
-
return
|
|
31860
|
+
return request3;
|
|
31274
31861
|
}
|
|
31275
31862
|
function normalizePresenceHeartbeatResponse(value) {
|
|
31276
31863
|
if (isPresenceHeartbeatResponse(value)) {
|
|
@@ -31320,7 +31907,7 @@ function parseStatuslineRequest(buffer) {
|
|
|
31320
31907
|
|
|
31321
31908
|
// src/daemon/server.ts
|
|
31322
31909
|
var CONFIG_DIR = primConfigDirectory();
|
|
31323
|
-
var SOCK_PATH2 =
|
|
31910
|
+
var SOCK_PATH2 = join20(CONFIG_DIR, "sock");
|
|
31324
31911
|
var CONFIG_DIR_MODE3 = 448;
|
|
31325
31912
|
var SOCKET_MODE = 384;
|
|
31326
31913
|
var MAX_SOCKET_CONNECTIONS = 64;
|
|
@@ -31389,7 +31976,7 @@ function resolveRuntimeVersion() {
|
|
|
31389
31976
|
}
|
|
31390
31977
|
try {
|
|
31391
31978
|
const here = fileURLToPath4(new URL(".", import.meta.url));
|
|
31392
|
-
const pkg = JSON.parse(
|
|
31979
|
+
const pkg = JSON.parse(readFileSync15(join20(here, "..", "..", "package.json"), "utf-8"));
|
|
31393
31980
|
return pkg.version ?? "unknown";
|
|
31394
31981
|
} catch {
|
|
31395
31982
|
return "unknown";
|
|
@@ -31428,7 +32015,7 @@ function assertCallerPrincipalMatches(caller) {
|
|
|
31428
32015
|
return credentialKey;
|
|
31429
32016
|
}
|
|
31430
32017
|
function ensureDaemonDirectoryPermissions() {
|
|
31431
|
-
|
|
32018
|
+
mkdirSync10(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
|
|
31432
32019
|
chmodSync8(CONFIG_DIR, CONFIG_DIR_MODE3);
|
|
31433
32020
|
}
|
|
31434
32021
|
function persistHealth() {
|
|
@@ -31515,7 +32102,7 @@ async function takeOwnership() {
|
|
|
31515
32102
|
(pid) => pid !== void 0 && processIsAlive(pid)
|
|
31516
32103
|
)
|
|
31517
32104
|
);
|
|
31518
|
-
if (
|
|
32105
|
+
if (existsSync12(SOCK_PATH2) || candidatePids.size > 0) {
|
|
31519
32106
|
const snapshot = await daemonRequest(
|
|
31520
32107
|
"status_snapshot",
|
|
31521
32108
|
{},
|
|
@@ -31965,15 +32552,15 @@ function handleConnection(conn) {
|
|
|
31965
32552
|
}
|
|
31966
32553
|
try {
|
|
31967
32554
|
const line = utf8Decoder2.decode(jsonBuffer.subarray(0, newlineIdx));
|
|
31968
|
-
const
|
|
31969
|
-
if (!
|
|
32555
|
+
const request3 = parseDaemonRequestEnvelope(JSON.parse(line));
|
|
32556
|
+
if (!request3) {
|
|
31970
32557
|
conn.end();
|
|
31971
32558
|
return;
|
|
31972
32559
|
}
|
|
31973
32560
|
dispatched = true;
|
|
31974
32561
|
conn.pause();
|
|
31975
|
-
void dispatchRequest(
|
|
31976
|
-
writeJsonResponse({ id:
|
|
32562
|
+
void dispatchRequest(request3).then(writeJsonResponse, () => {
|
|
32563
|
+
writeJsonResponse({ id: request3.id, ok: false, error: "daemon request failed" });
|
|
31977
32564
|
});
|
|
31978
32565
|
} catch {
|
|
31979
32566
|
conn.end();
|