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