@primitive.ai/prim 0.1.0-alpha.123 → 0.1.0-alpha.124
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 +63 -0
- package/dist/{chunk-5ME3WD3P.js → chunk-3OKVMKK2.js} +6 -3
- package/dist/chunk-5BZWFN62.js +206 -0
- package/dist/{chunk-FXXMDO7D.js → chunk-5KPDY5GF.js} +4 -4
- package/dist/{chunk-HLMC7VS4.js → chunk-5MH2C5QG.js} +3878 -2644
- package/dist/{chunk-NMZSCSMY.js → chunk-6PSCGY2A.js} +11 -1
- package/dist/{chunk-OXW6PSPT.js → chunk-6VJ7C2B5.js} +15 -3
- package/dist/{chunk-DQ4I3FLF.js → chunk-6W72SEXC.js} +3 -3
- package/dist/{chunk-4M23K2KZ.js → chunk-6WKJWW6D.js} +2 -2
- package/dist/{chunk-3WQ7SBOZ.js → chunk-A6YTFBQ4.js} +3 -3
- package/dist/{chunk-NL5VU7EU.js → chunk-DGZX3MID.js} +3 -3
- package/dist/{chunk-4NUGCUQC.js → chunk-EER7VG3P.js} +2 -2
- package/dist/{chunk-JZC2LHS6.js → chunk-EWV7VIZ3.js} +1 -1
- package/dist/{chunk-WN7OURQ3.js → chunk-KMWXI7KO.js} +1 -1
- package/dist/{chunk-LOFMI3D4.js → chunk-KTXJJE5K.js} +2 -2
- package/dist/{chunk-4GYJHN26.js → chunk-Q2PVD5W2.js} +1575 -549
- package/dist/{chunk-S3ZIMGXV.js → chunk-QZWLZH6D.js} +76 -2
- package/dist/{chunk-CWV5ZQR6.js → chunk-TS2NX6YT.js} +5 -5
- package/dist/{chunk-GOMEWFMG.js → chunk-WLVEXOHC.js} +143 -61
- package/dist/{chunk-RUEIVZ6T.js → chunk-WQFJ5TEG.js} +2 -2
- package/dist/{chunk-T2T45KF6.js → chunk-ZMH6GJUG.js} +4 -4
- package/dist/daemon/server.js +7795 -5449
- package/dist/hook-runtime/daemon/server.js +7795 -5449
- package/dist/hook-runtime/hooks/post-commit.js +5828 -4329
- package/dist/hook-runtime/hooks/post-rewrite.js +4331 -2833
- package/dist/hook-runtime/hooks/post-tool-use.js +5241 -2891
- package/dist/hook-runtime/hooks/pre-commit.js +1253 -280
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +4177 -1971
- package/dist/hook-runtime/hooks/prim-hook.js +4718 -2478
- package/dist/hook-runtime/hooks/session-end.js +392 -139
- package/dist/hook-runtime/hooks/session-start.js +4206 -1997
- package/dist/hook-runtime/index.js +6155 -3542
- package/dist/hook-runtime/statusline-main.js +368 -122
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +31 -21
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +16 -12
- package/dist/index.js +229 -149
- package/dist/statusline-main.js +368 -122
- package/package.json +3 -1
- package/dist/chunk-RRAC76LJ.js +0 -36
|
@@ -1,8 +1,196 @@
|
|
|
1
|
+
// src/lib/bin-path.ts
|
|
2
|
+
import { existsSync, readFileSync } from "fs";
|
|
3
|
+
import { dirname, isAbsolute, join } from "path";
|
|
4
|
+
import { fileURLToPath } from "url";
|
|
5
|
+
|
|
6
|
+
// src/lib/semver.ts
|
|
7
|
+
function parseSemver(value) {
|
|
8
|
+
if (typeof value !== "string" || value.length > 256) return;
|
|
9
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(
|
|
10
|
+
value
|
|
11
|
+
);
|
|
12
|
+
if (!match) return;
|
|
13
|
+
const prerelease = match[4]?.split(".") ?? [];
|
|
14
|
+
if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
|
|
18
|
+
}
|
|
19
|
+
function compareSemver(left, right) {
|
|
20
|
+
const a = parseSemver(left);
|
|
21
|
+
const b = parseSemver(right);
|
|
22
|
+
if (!a || !b) return;
|
|
23
|
+
for (let i = 0; i < a.core.length; i += 1) {
|
|
24
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
25
|
+
}
|
|
26
|
+
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
27
|
+
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
|
|
28
|
+
}
|
|
29
|
+
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
|
|
30
|
+
const x = a.prerelease[i];
|
|
31
|
+
const y = b.prerelease[i];
|
|
32
|
+
if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
|
|
33
|
+
if (x === y) continue;
|
|
34
|
+
const xNumeric = /^\d+$/u.test(x);
|
|
35
|
+
const yNumeric = /^\d+$/u.test(y);
|
|
36
|
+
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
37
|
+
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
|
|
38
|
+
return x < y ? -1 : 1;
|
|
39
|
+
}
|
|
40
|
+
return 0;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/lib/bin-path.ts
|
|
44
|
+
var PKG_NAME = "@primitive.ai/prim";
|
|
45
|
+
var ROOT_WALK_LIMIT = 6;
|
|
46
|
+
var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
|
|
47
|
+
var resolvedRoot;
|
|
48
|
+
function locateRoot() {
|
|
49
|
+
if (resolvedRoot !== void 0) {
|
|
50
|
+
return resolvedRoot;
|
|
51
|
+
}
|
|
52
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
53
|
+
for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
|
|
54
|
+
const manifestPath = join(dir, "package.json");
|
|
55
|
+
if (existsSync(manifestPath)) {
|
|
56
|
+
try {
|
|
57
|
+
const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
|
|
58
|
+
if (manifest.name === PKG_NAME && manifest.bin) {
|
|
59
|
+
resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
|
|
60
|
+
return resolvedRoot;
|
|
61
|
+
}
|
|
62
|
+
} catch {
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const parent = dirname(dir);
|
|
66
|
+
if (parent === dir) {
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
dir = parent;
|
|
70
|
+
}
|
|
71
|
+
resolvedRoot = null;
|
|
72
|
+
return resolvedRoot;
|
|
73
|
+
}
|
|
74
|
+
function binFile(bin) {
|
|
75
|
+
const root = locateRoot();
|
|
76
|
+
const rel = root?.bin[bin];
|
|
77
|
+
if (!root || !rel) {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
return isAbsolute(rel) ? rel : join(root.dir, rel);
|
|
81
|
+
}
|
|
82
|
+
function packageVersion() {
|
|
83
|
+
return locateRoot()?.version ?? null;
|
|
84
|
+
}
|
|
85
|
+
function packageRoot() {
|
|
86
|
+
return locateRoot()?.dir ?? null;
|
|
87
|
+
}
|
|
88
|
+
function shellQuote(value) {
|
|
89
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
90
|
+
}
|
|
91
|
+
function shellWord(value) {
|
|
92
|
+
return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(value) ? value : shellQuote(value);
|
|
93
|
+
}
|
|
94
|
+
function pinnedNpxArgs(bin, args = [], options = {}) {
|
|
95
|
+
const version = packageVersion();
|
|
96
|
+
if (!version) throw new Error("cannot determine Primitive package version");
|
|
97
|
+
return [
|
|
98
|
+
"--yes",
|
|
99
|
+
"--ignore-scripts",
|
|
100
|
+
...options.preferOnline ? ["--prefer-online"] : [],
|
|
101
|
+
"-p",
|
|
102
|
+
`${PKG_NAME}@${version}`,
|
|
103
|
+
bin,
|
|
104
|
+
...args
|
|
105
|
+
];
|
|
106
|
+
}
|
|
107
|
+
function pinnedNpxCommand(bin, args = [], options = {}) {
|
|
108
|
+
return ["npx", ...pinnedNpxArgs(bin, args, options)].map(shellWord).join(" ");
|
|
109
|
+
}
|
|
110
|
+
function pinnedHookCommand(bin, args = "") {
|
|
111
|
+
const suffix = args ? ` ${args}` : "";
|
|
112
|
+
const fallback = `${pinnedNpxCommand(bin)}${suffix}`;
|
|
113
|
+
const file = binFile(bin);
|
|
114
|
+
if (!file) return fallback;
|
|
115
|
+
return `if [ -x ${shellQuote(process.execPath)} ] && [ -f ${shellQuote(file)} ]; then ${shellQuote(process.execPath)} ${shellQuote(file)}${suffix}; else ${fallback}; fi`;
|
|
116
|
+
}
|
|
117
|
+
var STABLE_HOOK_ARGUMENTS_RE = /^[-A-Za-z0-9_ ]*$/u;
|
|
118
|
+
var STABLE_HOOK_BIN_RE = /^[A-Za-z0-9][A-Za-z0-9-]*$/u;
|
|
119
|
+
var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
120
|
+
'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
|
|
121
|
+
'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
|
|
122
|
+
'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
|
|
123
|
+
'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
|
|
124
|
+
"fi; fi; "
|
|
125
|
+
].join("");
|
|
126
|
+
function stableHookCommand(bin, args = "") {
|
|
127
|
+
if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
|
|
128
|
+
throw new Error("invalid stable hook command");
|
|
129
|
+
}
|
|
130
|
+
const resolver = [
|
|
131
|
+
// #242 and earlier identify managed commands by this package marker. Keep
|
|
132
|
+
// it as inert data during the rolling window so an older uninstall or
|
|
133
|
+
// reinstall can remove the stable entry without invoking npm or PATH.
|
|
134
|
+
`prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
|
|
135
|
+
PRIM_CONFIG_SHELL_RESOLVER,
|
|
136
|
+
`case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
|
|
137
|
+
'exec "$prim_launcher" "$@"'
|
|
138
|
+
].join("");
|
|
139
|
+
const suffix = args ? ` ${args}` : "";
|
|
140
|
+
return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
|
|
141
|
+
}
|
|
142
|
+
function detachedHookShimCommand(bin, args = "") {
|
|
143
|
+
return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
|
|
144
|
+
}
|
|
145
|
+
function commandMatchesBin(command, bin) {
|
|
146
|
+
if (!command) {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
const c = command.trim();
|
|
150
|
+
if (c === bin || c.startsWith(`${bin} `)) {
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
const exactBin = new RegExp(`(?:^|\\s)${bin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s|;|$)`);
|
|
154
|
+
return c.includes(`command -v ${bin} `) || c.includes(`-p ${PKG_NAME}@`) && exactBin.test(c) || c.includes(STABLE_HOOK_LAUNCHER_NAME) && exactBin.test(c);
|
|
155
|
+
}
|
|
156
|
+
function exactPinnedNpxVersion(command, bin) {
|
|
157
|
+
const escapedBin = bin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
158
|
+
const shellQuoted = `'(?:[^']|'"'"')*'`;
|
|
159
|
+
const safeArgs = "(?: [A-Za-z0-9_@%+=:,./-]+)*";
|
|
160
|
+
const direct = new RegExp(
|
|
161
|
+
`^npx --yes --ignore-scripts -p @primitive\\.ai/prim@(?<version>[0-9A-Za-z.+-]+) ${escapedBin}${safeArgs}$`,
|
|
162
|
+
"u"
|
|
163
|
+
).exec(command);
|
|
164
|
+
const wrapped = new RegExp(
|
|
165
|
+
`^if \\[ -x (?<node>${shellQuoted}) \\] && \\[ -f (?<entry>${shellQuoted}) \\]; then \\k<node> \\k<entry>(?<args>${safeArgs}); else npx --yes --ignore-scripts -p @primitive\\.ai/prim@(?<version>[0-9A-Za-z.+-]+) ${escapedBin}\\k<args>; fi$`,
|
|
166
|
+
"u"
|
|
167
|
+
).exec(command);
|
|
168
|
+
const version = direct?.groups?.version ?? wrapped?.groups?.version;
|
|
169
|
+
return version && compareSemver(version, version) !== void 0 ? version : void 0;
|
|
170
|
+
}
|
|
171
|
+
function hookCommandResolution(command, bin) {
|
|
172
|
+
const trimmed = command?.trim();
|
|
173
|
+
if (!trimmed || !commandMatchesBin(trimmed, bin)) return void 0;
|
|
174
|
+
if (trimmed.includes(STABLE_HOOK_LAUNCHER_NAME)) return { kind: "stable_launcher" };
|
|
175
|
+
const version = exactPinnedNpxVersion(trimmed, bin);
|
|
176
|
+
return version ? { kind: "exact_npx_fallback", version } : { kind: "legacy_path" };
|
|
177
|
+
}
|
|
178
|
+
function hookCommandResolutions(commands, bins) {
|
|
179
|
+
const resolutions = [];
|
|
180
|
+
for (const command of commands) {
|
|
181
|
+
for (const bin of bins) {
|
|
182
|
+
const resolution = hookCommandResolution(command, bin);
|
|
183
|
+
if (resolution) resolutions.push(resolution);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return resolutions;
|
|
187
|
+
}
|
|
188
|
+
|
|
1
189
|
// src/lib/git.ts
|
|
2
190
|
import { execFileSync } from "child_process";
|
|
3
191
|
import { createHash } from "crypto";
|
|
4
192
|
import { lstatSync, realpathSync } from "fs";
|
|
5
|
-
import { basename, dirname, isAbsolute, relative, resolve, sep } from "path";
|
|
193
|
+
import { basename, dirname as dirname2, isAbsolute as isAbsolute2, relative, resolve, sep } from "path";
|
|
6
194
|
var GIT_TIMEOUT_MS = 1e3;
|
|
7
195
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
8
196
|
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
@@ -31,7 +219,7 @@ function mainWorktreeRoot(cwd) {
|
|
|
31
219
|
}
|
|
32
220
|
).trim().split("\n").map((value) => resolve(cwd ?? process.cwd(), value));
|
|
33
221
|
if (gitDir === void 0 || commonDir === void 0 || gitDir === commonDir) return null;
|
|
34
|
-
return basename(commonDir) === ".git" ?
|
|
222
|
+
return basename(commonDir) === ".git" ? dirname2(commonDir) : null;
|
|
35
223
|
} catch {
|
|
36
224
|
return null;
|
|
37
225
|
}
|
|
@@ -75,13 +263,13 @@ function canonicalGitRoot(cwd) {
|
|
|
75
263
|
}
|
|
76
264
|
}
|
|
77
265
|
function relatedWorktreeTarget(path, cwd, origin) {
|
|
78
|
-
let parent =
|
|
266
|
+
let parent = dirname2(resolve(cwd, path));
|
|
79
267
|
while (true) {
|
|
80
268
|
try {
|
|
81
269
|
realpathSync.native(parent);
|
|
82
270
|
break;
|
|
83
271
|
} catch {
|
|
84
|
-
const next =
|
|
272
|
+
const next = dirname2(parent);
|
|
85
273
|
if (next === parent) return null;
|
|
86
274
|
parent = next;
|
|
87
275
|
}
|
|
@@ -164,7 +352,7 @@ function nearestExistingAncestor(path) {
|
|
|
164
352
|
} catch (error) {
|
|
165
353
|
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
166
354
|
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
167
|
-
const parent =
|
|
355
|
+
const parent = dirname2(cursor);
|
|
168
356
|
if (parent === cursor) return null;
|
|
169
357
|
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
170
358
|
cursor = parent;
|
|
@@ -186,7 +374,7 @@ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
|
186
374
|
const target = resolve(resolved.real, ...resolved.suffix);
|
|
187
375
|
const rel = relative(context.repoRoot, target);
|
|
188
376
|
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
189
|
-
if (
|
|
377
|
+
if (isAbsolute2(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
190
378
|
return { ok: false, reason: "outside_repository" };
|
|
191
379
|
}
|
|
192
380
|
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
@@ -205,7 +393,7 @@ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonical
|
|
|
205
393
|
return null;
|
|
206
394
|
}
|
|
207
395
|
try {
|
|
208
|
-
const parent = realpathSync.native(
|
|
396
|
+
const parent = realpathSync.native(dirname2(absolute));
|
|
209
397
|
if (!lstatSync(parent).isDirectory()) return null;
|
|
210
398
|
target = resolve(parent, basename(absolute));
|
|
211
399
|
} catch {
|
|
@@ -213,7 +401,7 @@ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonical
|
|
|
213
401
|
}
|
|
214
402
|
}
|
|
215
403
|
const rel = relative(repositoryRoot, target);
|
|
216
|
-
if (!rel ||
|
|
404
|
+
if (!rel || isAbsolute2(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
217
405
|
return null;
|
|
218
406
|
}
|
|
219
407
|
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
@@ -231,9 +419,9 @@ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
|
231
419
|
|
|
232
420
|
// src/lib/activation.ts
|
|
233
421
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
234
|
-
import { existsSync, readFileSync } from "fs";
|
|
422
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
235
423
|
import { homedir } from "os";
|
|
236
|
-
import { join } from "path";
|
|
424
|
+
import { join as join2 } from "path";
|
|
237
425
|
|
|
238
426
|
// src/lib/demo-pause.ts
|
|
239
427
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
@@ -426,10 +614,10 @@ function hasProjectPrimInstall(cwd) {
|
|
|
426
614
|
const root = gitToplevel(cwd);
|
|
427
615
|
if (root === null || root === homedir()) return false;
|
|
428
616
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
429
|
-
const path =
|
|
430
|
-
if (
|
|
617
|
+
const path = join2(root, rel);
|
|
618
|
+
if (existsSync2(path)) {
|
|
431
619
|
try {
|
|
432
|
-
const content =
|
|
620
|
+
const content = readFileSync2(path, "utf-8");
|
|
433
621
|
if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
|
|
434
622
|
} catch {
|
|
435
623
|
}
|
|
@@ -448,220 +636,259 @@ function decisionIngestionStatus(cwd) {
|
|
|
448
636
|
return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
|
|
449
637
|
}
|
|
450
638
|
|
|
451
|
-
// src/lib/
|
|
452
|
-
import {
|
|
453
|
-
import {
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
639
|
+
// src/lib/atomic-file.ts
|
|
640
|
+
import { randomUUID } from "crypto";
|
|
641
|
+
import {
|
|
642
|
+
constants,
|
|
643
|
+
closeSync,
|
|
644
|
+
fchmodSync,
|
|
645
|
+
fsyncSync,
|
|
646
|
+
mkdirSync,
|
|
647
|
+
openSync,
|
|
648
|
+
renameSync,
|
|
649
|
+
rmSync,
|
|
650
|
+
writeFileSync
|
|
651
|
+
} from "fs";
|
|
652
|
+
import { dirname as dirname3 } from "path";
|
|
653
|
+
var DEFAULT_FILE_MODE = 438;
|
|
654
|
+
function syncDirectory(path) {
|
|
655
|
+
if (process.platform === "win32") return;
|
|
656
|
+
const fd = openSync(path, constants.O_RDONLY);
|
|
657
|
+
try {
|
|
658
|
+
fsyncSync(fd);
|
|
659
|
+
} finally {
|
|
660
|
+
closeSync(fd);
|
|
466
661
|
}
|
|
467
|
-
return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
|
|
468
662
|
}
|
|
469
|
-
function
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
}
|
|
476
|
-
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
477
|
-
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
|
|
478
|
-
}
|
|
479
|
-
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
|
|
480
|
-
const x = a.prerelease[i];
|
|
481
|
-
const y = b.prerelease[i];
|
|
482
|
-
if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
|
|
483
|
-
if (x === y) continue;
|
|
484
|
-
const xNumeric = /^\d+$/u.test(x);
|
|
485
|
-
const yNumeric = /^\d+$/u.test(y);
|
|
486
|
-
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
487
|
-
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
|
|
488
|
-
return x < y ? -1 : 1;
|
|
663
|
+
function syncFile(path) {
|
|
664
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
665
|
+
try {
|
|
666
|
+
fsyncSync(fd);
|
|
667
|
+
} finally {
|
|
668
|
+
closeSync(fd);
|
|
489
669
|
}
|
|
490
|
-
return 0;
|
|
491
670
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
671
|
+
function syncCreatedParentChain(firstCreatedParent, parent) {
|
|
672
|
+
const createdDirectories = [];
|
|
673
|
+
let current = parent;
|
|
674
|
+
while (current !== firstCreatedParent) {
|
|
675
|
+
createdDirectories.push(current);
|
|
676
|
+
const next = dirname3(current);
|
|
677
|
+
if (next === current) {
|
|
678
|
+
throw new Error("recursive mkdir returned a path outside the target parent chain");
|
|
679
|
+
}
|
|
680
|
+
current = next;
|
|
681
|
+
}
|
|
682
|
+
createdDirectories.push(firstCreatedParent);
|
|
683
|
+
syncDirectory(dirname3(firstCreatedParent));
|
|
684
|
+
for (const directory of createdDirectories.reverse().slice(0, -1)) {
|
|
685
|
+
syncDirectory(directory);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
function ensureDurableDirectory(path, mode) {
|
|
689
|
+
const firstCreatedParent = mkdirSync(path, { recursive: true, mode });
|
|
690
|
+
if (firstCreatedParent) {
|
|
691
|
+
syncCreatedParentChain(firstCreatedParent, path);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
function atomicWriteFile(target, content, options = {}) {
|
|
695
|
+
const parent = dirname3(target);
|
|
696
|
+
if (options.ensureParent) {
|
|
697
|
+
ensureDurableDirectory(parent);
|
|
698
|
+
}
|
|
699
|
+
const temporaryPath = `${target}.${randomUUID()}.tmp`;
|
|
700
|
+
let temporaryCreated = false;
|
|
701
|
+
try {
|
|
702
|
+
const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
|
|
703
|
+
const fd = openSync(temporaryPath, flags, options.mode ?? DEFAULT_FILE_MODE);
|
|
704
|
+
temporaryCreated = true;
|
|
705
|
+
try {
|
|
706
|
+
if (options.mode !== void 0) fchmodSync(fd, options.mode);
|
|
707
|
+
writeFileSync(fd, content);
|
|
708
|
+
fsyncSync(fd);
|
|
709
|
+
} finally {
|
|
710
|
+
closeSync(fd);
|
|
711
|
+
}
|
|
712
|
+
options.validate?.(temporaryPath);
|
|
713
|
+
renameSync(temporaryPath, target);
|
|
714
|
+
syncDirectory(parent);
|
|
715
|
+
} catch (error) {
|
|
716
|
+
if (temporaryCreated) {
|
|
506
717
|
try {
|
|
507
|
-
|
|
508
|
-
if (manifest.name === PKG_NAME && manifest.bin) {
|
|
509
|
-
resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
|
|
510
|
-
return resolvedRoot;
|
|
511
|
-
}
|
|
718
|
+
rmSync(temporaryPath, { force: true });
|
|
512
719
|
} catch {
|
|
513
720
|
}
|
|
514
721
|
}
|
|
515
|
-
|
|
516
|
-
if (parent === dir) {
|
|
517
|
-
break;
|
|
518
|
-
}
|
|
519
|
-
dir = parent;
|
|
722
|
+
throw error;
|
|
520
723
|
}
|
|
521
|
-
resolvedRoot = null;
|
|
522
|
-
return resolvedRoot;
|
|
523
724
|
}
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
if (!
|
|
528
|
-
|
|
725
|
+
|
|
726
|
+
// src/lib/process-liveness.ts
|
|
727
|
+
function processIsAlive(pid, probe = process.kill) {
|
|
728
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
729
|
+
try {
|
|
730
|
+
probe(pid, 0);
|
|
731
|
+
return true;
|
|
732
|
+
} catch (error) {
|
|
733
|
+
return error.code === "EPERM";
|
|
529
734
|
}
|
|
530
|
-
return isAbsolute2(rel) ? rel : join2(root.dir, rel);
|
|
531
|
-
}
|
|
532
|
-
function packageVersion() {
|
|
533
|
-
return locateRoot()?.version ?? null;
|
|
534
735
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
return [
|
|
548
|
-
"--yes",
|
|
549
|
-
"--ignore-scripts",
|
|
550
|
-
...options.preferOnline ? ["--prefer-online"] : [],
|
|
551
|
-
"-p",
|
|
552
|
-
`${PKG_NAME}@${version}`,
|
|
553
|
-
bin,
|
|
554
|
-
...args
|
|
555
|
-
];
|
|
736
|
+
|
|
737
|
+
// src/lib/file-lock.ts
|
|
738
|
+
import { randomBytes } from "crypto";
|
|
739
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
|
|
740
|
+
import { dirname as dirname4, join as join3 } from "path";
|
|
741
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
742
|
+
var DEFAULT_POLL_MS = 50;
|
|
743
|
+
var DEFAULT_INIT_GRACE_MS = 2e3;
|
|
744
|
+
var DIRECTORY_MODE = 448;
|
|
745
|
+
var FILE_MODE = 384;
|
|
746
|
+
function ownerPath(lockDir) {
|
|
747
|
+
return join3(lockDir, "owner.json");
|
|
556
748
|
}
|
|
557
|
-
function
|
|
558
|
-
|
|
749
|
+
function readOwner(lockDir) {
|
|
750
|
+
try {
|
|
751
|
+
const owner = JSON.parse(readFileSync3(ownerPath(lockDir), "utf8"));
|
|
752
|
+
if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
|
|
753
|
+
return null;
|
|
754
|
+
}
|
|
755
|
+
return owner;
|
|
756
|
+
} catch {
|
|
757
|
+
return null;
|
|
758
|
+
}
|
|
559
759
|
}
|
|
560
|
-
function
|
|
561
|
-
|
|
562
|
-
const fallback = `${pinnedNpxCommand(bin)}${suffix}`;
|
|
563
|
-
const file = binFile(bin);
|
|
564
|
-
if (!file) return fallback;
|
|
565
|
-
return `if [ -x ${shellQuote(process.execPath)} ] && [ -f ${shellQuote(file)} ]; then ${shellQuote(process.execPath)} ${shellQuote(file)}${suffix}; else ${fallback}; fi`;
|
|
760
|
+
function sameOwner(a, b) {
|
|
761
|
+
return a?.pid === b.pid && a.nonce === b.nonce && a.createdAt === b.createdAt;
|
|
566
762
|
}
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
763
|
+
function tryTakeLock(lockDir, now) {
|
|
764
|
+
try {
|
|
765
|
+
mkdirSync2(lockDir, { mode: DIRECTORY_MODE });
|
|
766
|
+
} catch (error) {
|
|
767
|
+
if (error.code === "EEXIST") return null;
|
|
768
|
+
throw error;
|
|
769
|
+
}
|
|
770
|
+
const owner = {
|
|
771
|
+
pid: process.pid,
|
|
772
|
+
nonce: randomBytes(16).toString("hex"),
|
|
773
|
+
createdAt: now
|
|
774
|
+
};
|
|
775
|
+
try {
|
|
776
|
+
writeFileSync2(ownerPath(lockDir), `${JSON.stringify(owner)}
|
|
777
|
+
`, {
|
|
778
|
+
encoding: "utf8",
|
|
779
|
+
mode: FILE_MODE,
|
|
780
|
+
flag: "wx"
|
|
781
|
+
});
|
|
782
|
+
return owner;
|
|
783
|
+
} catch (error) {
|
|
784
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
785
|
+
throw error;
|
|
579
786
|
}
|
|
580
|
-
const resolver = [
|
|
581
|
-
// #242 and earlier identify managed commands by this package marker. Keep
|
|
582
|
-
// it as inert data during the rolling window so an older uninstall or
|
|
583
|
-
// reinstall can remove the stable entry without invoking npm or PATH.
|
|
584
|
-
`prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
|
|
585
|
-
PRIM_CONFIG_SHELL_RESOLVER,
|
|
586
|
-
`case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
|
|
587
|
-
'exec "$prim_launcher" "$@"'
|
|
588
|
-
].join("");
|
|
589
|
-
const suffix = args ? ` ${args}` : "";
|
|
590
|
-
return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
|
|
591
|
-
}
|
|
592
|
-
function detachedHookShimCommand(bin, args = "") {
|
|
593
|
-
return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
|
|
594
787
|
}
|
|
595
|
-
function
|
|
596
|
-
|
|
597
|
-
|
|
788
|
+
function recoverStaleLock(lockDir, now, alive, initGraceMs) {
|
|
789
|
+
const owner = readOwner(lockDir);
|
|
790
|
+
if (owner) {
|
|
791
|
+
if (alive(owner.pid)) return false;
|
|
792
|
+
if (!sameOwner(readOwner(lockDir), owner)) return false;
|
|
793
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
794
|
+
return true;
|
|
598
795
|
}
|
|
599
|
-
|
|
600
|
-
|
|
796
|
+
try {
|
|
797
|
+
const before = statSync(lockDir).mtimeMs;
|
|
798
|
+
if (now - before < initGraceMs) return false;
|
|
799
|
+
if (readOwner(lockDir)) return false;
|
|
800
|
+
if (statSync(lockDir).mtimeMs !== before) return false;
|
|
801
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
802
|
+
return true;
|
|
803
|
+
} catch {
|
|
601
804
|
return true;
|
|
602
805
|
}
|
|
603
|
-
const exactBin = new RegExp(`(?:^|\\s)${bin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s|;|$)`);
|
|
604
|
-
return c.includes(`command -v ${bin} `) || c.includes(`-p ${PKG_NAME}@`) && exactBin.test(c) || c.includes(STABLE_HOOK_LAUNCHER_NAME) && exactBin.test(c);
|
|
605
806
|
}
|
|
606
|
-
function
|
|
607
|
-
|
|
608
|
-
const
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
`^npx --yes --ignore-scripts -p @primitive\\.ai/prim@(?<version>[0-9A-Za-z.+-]+) ${escapedBin}${safeArgs}$`,
|
|
612
|
-
"u"
|
|
613
|
-
).exec(command);
|
|
614
|
-
const wrapped = new RegExp(
|
|
615
|
-
`^if \\[ -x (?<node>${shellQuoted}) \\] && \\[ -f (?<entry>${shellQuoted}) \\]; then \\k<node> \\k<entry>(?<args>${safeArgs}); else npx --yes --ignore-scripts -p @primitive\\.ai/prim@(?<version>[0-9A-Za-z.+-]+) ${escapedBin}\\k<args>; fi$`,
|
|
616
|
-
"u"
|
|
617
|
-
).exec(command);
|
|
618
|
-
const version = direct?.groups?.version ?? wrapped?.groups?.version;
|
|
619
|
-
return version && compareSemver(version, version) !== void 0 ? version : void 0;
|
|
807
|
+
function abortError(signal) {
|
|
808
|
+
if (signal.reason instanceof Error) return signal.reason;
|
|
809
|
+
const error = new Error("The operation was aborted");
|
|
810
|
+
error.name = "AbortError";
|
|
811
|
+
return error;
|
|
620
812
|
}
|
|
621
|
-
function
|
|
622
|
-
|
|
623
|
-
if (!trimmed || !commandMatchesBin(trimmed, bin)) return void 0;
|
|
624
|
-
if (trimmed.includes(STABLE_HOOK_LAUNCHER_NAME)) return { kind: "stable_launcher" };
|
|
625
|
-
const version = exactPinnedNpxVersion(trimmed, bin);
|
|
626
|
-
return version ? { kind: "exact_npx_fallback", version } : { kind: "legacy_path" };
|
|
813
|
+
function throwIfAborted(signal) {
|
|
814
|
+
if (signal?.aborted) throw abortError(signal);
|
|
627
815
|
}
|
|
628
|
-
function
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
const resolution = hookCommandResolution(command, bin);
|
|
633
|
-
if (resolution) resolutions.push(resolution);
|
|
634
|
-
}
|
|
816
|
+
async function defaultSleep(ms, signal) {
|
|
817
|
+
if (!signal) {
|
|
818
|
+
await new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
819
|
+
return;
|
|
635
820
|
}
|
|
636
|
-
|
|
821
|
+
throwIfAborted(signal);
|
|
822
|
+
await new Promise((resolve2, reject) => {
|
|
823
|
+
const timer = setTimeout(() => {
|
|
824
|
+
signal.removeEventListener("abort", onAbort);
|
|
825
|
+
resolve2();
|
|
826
|
+
}, ms);
|
|
827
|
+
const onAbort = () => {
|
|
828
|
+
clearTimeout(timer);
|
|
829
|
+
reject(abortError(signal));
|
|
830
|
+
};
|
|
831
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
832
|
+
});
|
|
637
833
|
}
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
import { isAbsolute as isAbsolute3, join as join3, normalize } from "path";
|
|
642
|
-
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
643
|
-
function absolutePath(value, variable) {
|
|
644
|
-
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
645
|
-
throw new Error(`${variable} contains unsafe characters`);
|
|
646
|
-
}
|
|
647
|
-
if (!value || value.trim() !== value || !isAbsolute3(value)) return;
|
|
648
|
-
const normalized = normalize(value);
|
|
649
|
-
return normalized === value ? value : void 0;
|
|
834
|
+
var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
835
|
+
function defaultSleepSync(ms) {
|
|
836
|
+
Atomics.wait(syncSleeper, 0, 0, ms);
|
|
650
837
|
}
|
|
651
|
-
function
|
|
652
|
-
|
|
653
|
-
const
|
|
654
|
-
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
838
|
+
function withFileLockSync(lockDir, operation, options = {}) {
|
|
839
|
+
mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
|
|
840
|
+
const nowMs = options.nowMs ?? Date.now;
|
|
841
|
+
const alive = options.processAlive ?? processIsAlive;
|
|
842
|
+
const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
843
|
+
let owner = null;
|
|
844
|
+
while (!owner) {
|
|
845
|
+
const now = nowMs();
|
|
846
|
+
owner = tryTakeLock(lockDir, now);
|
|
847
|
+
if (owner) break;
|
|
848
|
+
recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
|
|
849
|
+
if (now >= deadline) {
|
|
850
|
+
throw new Error(`timed out waiting for file lock ${lockDir}`);
|
|
851
|
+
}
|
|
852
|
+
(options.sleep ?? defaultSleepSync)(options.pollMs ?? DEFAULT_POLL_MS);
|
|
853
|
+
}
|
|
854
|
+
try {
|
|
855
|
+
return operation();
|
|
856
|
+
} finally {
|
|
857
|
+
if (sameOwner(readOwner(lockDir), owner)) {
|
|
858
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
859
|
+
}
|
|
660
860
|
}
|
|
661
|
-
return { path: join3(home, ".config", "prim"), source: "default" };
|
|
662
861
|
}
|
|
663
|
-
function
|
|
664
|
-
|
|
862
|
+
async function withFileLock(lockDir, operation, options = {}) {
|
|
863
|
+
mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
|
|
864
|
+
const nowMs = options.nowMs ?? Date.now;
|
|
865
|
+
const alive = options.processAlive ?? processIsAlive;
|
|
866
|
+
const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
867
|
+
let owner = null;
|
|
868
|
+
while (!owner) {
|
|
869
|
+
throwIfAborted(options.signal);
|
|
870
|
+
const now = nowMs();
|
|
871
|
+
owner = tryTakeLock(lockDir, now);
|
|
872
|
+
if (owner) break;
|
|
873
|
+
recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
|
|
874
|
+
if (now >= deadline) {
|
|
875
|
+
throw new Error(`timed out waiting for file lock ${lockDir}`);
|
|
876
|
+
}
|
|
877
|
+
if (options.sleep) {
|
|
878
|
+
await options.sleep(options.pollMs ?? DEFAULT_POLL_MS);
|
|
879
|
+
throwIfAborted(options.signal);
|
|
880
|
+
} else {
|
|
881
|
+
await defaultSleep(options.pollMs ?? DEFAULT_POLL_MS, options.signal);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
try {
|
|
885
|
+
throwIfAborted(options.signal);
|
|
886
|
+
return await operation();
|
|
887
|
+
} finally {
|
|
888
|
+
if (sameOwner(readOwner(lockDir), owner)) {
|
|
889
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
890
|
+
}
|
|
891
|
+
}
|
|
665
892
|
}
|
|
666
893
|
|
|
667
894
|
// src/lib/workos-connect.ts
|
|
@@ -903,7 +1130,7 @@ function providerError(value) {
|
|
|
903
1130
|
const error = recordFrom(value, "token error").error;
|
|
904
1131
|
return exactString(error, "error", MAX_USER_CODE_LENGTH);
|
|
905
1132
|
}
|
|
906
|
-
async function
|
|
1133
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
907
1134
|
await new Promise((resolve2, reject) => {
|
|
908
1135
|
if (signal.aborted) {
|
|
909
1136
|
reject(signal.reason);
|
|
@@ -923,7 +1150,7 @@ async function defaultSleep(milliseconds, signal) {
|
|
|
923
1150
|
async function pollWorkosDeviceAuthorization(configuration, authorization, options = {}) {
|
|
924
1151
|
const fetchImpl = options.fetch ?? fetch;
|
|
925
1152
|
const now = options.now ?? Date.now;
|
|
926
|
-
const sleep = options.sleep ??
|
|
1153
|
+
const sleep = options.sleep ?? defaultSleep2;
|
|
927
1154
|
const signal = options.signal ?? AbortSignal.timeout(authorization.expiresIn * 1e3);
|
|
928
1155
|
const deadline = now() + authorization.expiresIn * 1e3;
|
|
929
1156
|
let intervalSeconds = authorization.interval;
|
|
@@ -964,408 +1191,1213 @@ async function pollWorkosDeviceAuthorization(configuration, authorization, optio
|
|
|
964
1191
|
throw new WorkosConnectProtocolError("expired_token", "Device authorization expired");
|
|
965
1192
|
}
|
|
966
1193
|
|
|
967
|
-
// src/lib/
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
function
|
|
1194
|
+
// src/lib/machine-protocol.ts
|
|
1195
|
+
var MachineAuthError = class extends Error {
|
|
1196
|
+
constructor(code, message, terminal = false, retryAt) {
|
|
1197
|
+
super(message);
|
|
1198
|
+
this.code = code;
|
|
1199
|
+
this.terminal = terminal;
|
|
1200
|
+
this.retryAt = retryAt;
|
|
1201
|
+
this.name = "MachineAuthError";
|
|
1202
|
+
}
|
|
1203
|
+
};
|
|
1204
|
+
function machineRetryAt(response, now = Date.now()) {
|
|
1205
|
+
const value = response.headers.get("Retry-After")?.trim();
|
|
1206
|
+
if (!value || value.length > 128) return void 0;
|
|
1207
|
+
const timestamp = /^\d+$/u.test(value) ? now + Number(value) * 1e3 : Date.parse(value);
|
|
1208
|
+
return Number.isSafeInteger(timestamp) && timestamp > now ? timestamp : void 0;
|
|
1209
|
+
}
|
|
1210
|
+
function machineString(value, maximum = 4096) {
|
|
1211
|
+
return typeof value === "string" && value.length > 0 && value.length <= maximum && value.trim() === value && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
1212
|
+
}
|
|
1213
|
+
function machineRecord(value) {
|
|
1214
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1215
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
1216
|
+
}
|
|
1217
|
+
return value;
|
|
1218
|
+
}
|
|
1219
|
+
function machineApiUrl(value) {
|
|
1220
|
+
const url = new URL(value);
|
|
1221
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
1222
|
+
if (url.protocol !== "https:" && !(local && url.protocol === "http:") || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
1223
|
+
throw new MachineAuthError("invalid_configuration", "The API URL must be an HTTPS origin.");
|
|
1224
|
+
}
|
|
1225
|
+
return url.origin;
|
|
1226
|
+
}
|
|
1227
|
+
function parseMachineConfiguration(value) {
|
|
1228
|
+
const record = machineRecord(value);
|
|
1229
|
+
if (record.protocol_version !== 1 || !machineString(record.issuer, 2048) || !machineString(record.audience, 256) || !/^client_[\w-]+$/u.test(record.audience)) {
|
|
1230
|
+
throw new MachineAuthError("invalid_configuration", "Invalid M2M discovery configuration.");
|
|
1231
|
+
}
|
|
1232
|
+
const issuer = new URL(record.issuer);
|
|
1233
|
+
if (issuer.protocol !== "https:" || issuer.origin !== record.issuer) {
|
|
1234
|
+
throw new MachineAuthError(
|
|
1235
|
+
"invalid_configuration",
|
|
1236
|
+
"The WorkOS issuer must be an HTTPS origin."
|
|
1237
|
+
);
|
|
1238
|
+
}
|
|
1239
|
+
return { issuer: record.issuer, audience: record.audience };
|
|
1240
|
+
}
|
|
1241
|
+
function machineSignal(signal) {
|
|
1242
|
+
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1243
|
+
}
|
|
1244
|
+
async function fetchMachine(url, options, fetchImpl) {
|
|
984
1245
|
try {
|
|
985
|
-
|
|
986
|
-
return value || void 0;
|
|
1246
|
+
return await fetchImpl(url, options);
|
|
987
1247
|
} catch {
|
|
988
|
-
|
|
1248
|
+
options.signal?.throwIfAborted();
|
|
1249
|
+
throw new MachineAuthError(
|
|
1250
|
+
"authentication_unavailable",
|
|
1251
|
+
"Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
1252
|
+
);
|
|
989
1253
|
}
|
|
990
1254
|
}
|
|
991
|
-
function
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1255
|
+
async function readMachineJson(response, maximumBytes) {
|
|
1256
|
+
try {
|
|
1257
|
+
return await readBoundedJson(response, maximumBytes);
|
|
1258
|
+
} catch {
|
|
1259
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
1263
|
+
const response = await fetchMachine(
|
|
1264
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/m2m/config`,
|
|
1265
|
+
{
|
|
1266
|
+
signal: machineSignal(signal),
|
|
1267
|
+
redirect: "error"
|
|
1268
|
+
},
|
|
1269
|
+
fetchImpl
|
|
1000
1270
|
);
|
|
1001
|
-
if (
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1271
|
+
if (!response.ok)
|
|
1272
|
+
throw new MachineAuthError(
|
|
1273
|
+
response.status === 404 ? "server_upgrade_required" : "discovery_unavailable",
|
|
1274
|
+
response.status === 404 ? "This server does not support machine authentication yet." : "Machine authentication discovery is unavailable."
|
|
1275
|
+
);
|
|
1276
|
+
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
1277
|
+
}
|
|
1278
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
1279
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1280
|
+
throw new MachineAuthError(
|
|
1281
|
+
"invalid_credentials",
|
|
1282
|
+
"A machine client ID and secret are required.",
|
|
1283
|
+
true
|
|
1284
|
+
);
|
|
1009
1285
|
}
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1286
|
+
const response = await fetchMachine(
|
|
1287
|
+
`${configuration.issuer}/oauth2/token`,
|
|
1288
|
+
{
|
|
1289
|
+
method: "POST",
|
|
1290
|
+
redirect: "error",
|
|
1291
|
+
signal: machineSignal(signal),
|
|
1292
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1293
|
+
body: new URLSearchParams({
|
|
1294
|
+
grant_type: "client_credentials",
|
|
1295
|
+
client_id: clientId,
|
|
1296
|
+
client_secret: clientSecret
|
|
1297
|
+
})
|
|
1298
|
+
},
|
|
1299
|
+
fetchImpl
|
|
1300
|
+
);
|
|
1301
|
+
if (!response.ok) {
|
|
1302
|
+
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
1303
|
+
throw new MachineAuthError(
|
|
1304
|
+
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
1305
|
+
terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
|
|
1306
|
+
terminal,
|
|
1307
|
+
terminal ? void 0 : machineRetryAt(response)
|
|
1308
|
+
);
|
|
1309
|
+
}
|
|
1310
|
+
const data = machineRecord(await readMachineJson(response, 64 * 1024));
|
|
1311
|
+
if (!machineString(data.access_token, 60 * 1024) || typeof data.token_type !== "string" || data.token_type.toLowerCase() !== "bearer" || !Number.isSafeInteger(data.expires_in) || data.expires_in <= 0 || data.expires_in > 86400) {
|
|
1312
|
+
throw new MachineAuthError(
|
|
1313
|
+
"invalid_response",
|
|
1314
|
+
"The token service returned an invalid access token."
|
|
1315
|
+
);
|
|
1316
|
+
}
|
|
1317
|
+
let claims;
|
|
1318
|
+
try {
|
|
1319
|
+
claims = machineRecord(
|
|
1320
|
+
JSON.parse(Buffer.from(data.access_token.split(".")[1] ?? "", "base64url").toString("utf8"))
|
|
1321
|
+
);
|
|
1322
|
+
} catch {
|
|
1323
|
+
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
1324
|
+
}
|
|
1325
|
+
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()) {
|
|
1326
|
+
throw new MachineAuthError(
|
|
1327
|
+
"token_identity_mismatch",
|
|
1328
|
+
"The token does not match the configured machine and deployment."
|
|
1329
|
+
);
|
|
1330
|
+
}
|
|
1331
|
+
return {
|
|
1332
|
+
accessToken: data.access_token,
|
|
1333
|
+
expiresAt: Math.min(Date.now() + data.expires_in * 1e3, claims.exp * 1e3)
|
|
1334
|
+
};
|
|
1335
|
+
}
|
|
1336
|
+
function parseMachineIdentity(value, clientId) {
|
|
1337
|
+
const data = machineRecord(value);
|
|
1338
|
+
const principal = machineRecord(data.principal);
|
|
1339
|
+
if (data.authenticated !== true || data.captureAuthorityKind !== "workos_m2m" || data.organizationBindingVersion !== 2 || principal.kind !== "machine" || principal.clientId !== clientId || !machineString(principal.machineId, 256) || !machineString(principal.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.workosOrganizationId, 256) || !Array.isArray(principal.scopes) || !principal.scopes.every((scope) => machineString(scope, 128))) {
|
|
1340
|
+
throw new MachineAuthError(
|
|
1341
|
+
"machine_identity_rejected",
|
|
1342
|
+
"The API did not verify a machine identity.",
|
|
1343
|
+
true
|
|
1344
|
+
);
|
|
1345
|
+
}
|
|
1346
|
+
return {
|
|
1347
|
+
machineId: principal.machineId,
|
|
1348
|
+
clientId,
|
|
1349
|
+
displayName: principal.displayName,
|
|
1350
|
+
organizationId: data.organizationId,
|
|
1351
|
+
workosOrganizationId: data.workosOrganizationId,
|
|
1352
|
+
scopes: principal.scopes
|
|
1353
|
+
};
|
|
1354
|
+
}
|
|
1355
|
+
async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetchImpl = fetch) {
|
|
1356
|
+
const response = await fetchMachine(
|
|
1357
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
1358
|
+
{
|
|
1359
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
1360
|
+
redirect: "error",
|
|
1361
|
+
signal: machineSignal(signal)
|
|
1362
|
+
},
|
|
1363
|
+
fetchImpl
|
|
1364
|
+
);
|
|
1365
|
+
if (!response.ok) {
|
|
1366
|
+
const terminal = response.status === 401 || response.status === 403;
|
|
1367
|
+
throw new MachineAuthError(
|
|
1368
|
+
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
1369
|
+
terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
|
|
1370
|
+
terminal
|
|
1371
|
+
);
|
|
1372
|
+
}
|
|
1373
|
+
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
// src/lib/paths.ts
|
|
1377
|
+
import { homedir as homedir2 } from "os";
|
|
1378
|
+
import { isAbsolute as isAbsolute3, join as join4, normalize } from "path";
|
|
1379
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
1380
|
+
function absolutePath(value, variable) {
|
|
1381
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
1382
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
1383
|
+
}
|
|
1384
|
+
if (!value || value.trim() !== value || !isAbsolute3(value)) return;
|
|
1385
|
+
const normalized = normalize(value);
|
|
1386
|
+
return normalized === value ? value : void 0;
|
|
1387
|
+
}
|
|
1388
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
1389
|
+
const env = options.env ?? process.env;
|
|
1390
|
+
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
1391
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
1392
|
+
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
1393
|
+
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
1394
|
+
const home = absolutePath(options.homeDir ?? homedir2(), "HOME");
|
|
1395
|
+
if (!home) {
|
|
1396
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
1397
|
+
}
|
|
1398
|
+
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
1399
|
+
}
|
|
1400
|
+
function primConfigDirectory(options = {}) {
|
|
1401
|
+
return resolvePrimConfigDirectory(options).path;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// src/lib/machine-credentials.ts
|
|
1405
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
1406
|
+
import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
|
|
1407
|
+
import { chmodSync, existsSync as existsSync4, lstatSync as lstatSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, rmSync as rmSync5 } from "fs";
|
|
1408
|
+
import { createRequire } from "module";
|
|
1409
|
+
import { dirname as dirname5, join as join7 } from "path";
|
|
1410
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
1411
|
+
|
|
1412
|
+
// src/lib/machine-broker.ts
|
|
1413
|
+
import { spawn } from "child_process";
|
|
1414
|
+
import { createHash as createHash2, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
1415
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync3 } from "fs";
|
|
1416
|
+
import { createServer } from "http";
|
|
1417
|
+
import { basename as basename2, join as join5 } from "path";
|
|
1418
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1419
|
+
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
1420
|
+
var IDLE_MS = 5 * 6e4;
|
|
1421
|
+
function descriptorPath(directory, generation) {
|
|
1422
|
+
return join5(directory, `machine_broker_${generation}.json`);
|
|
1423
|
+
}
|
|
1424
|
+
function readDescriptor(path) {
|
|
1425
|
+
try {
|
|
1426
|
+
const stat = lstatSync2(path);
|
|
1427
|
+
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
1428
|
+
return void 0;
|
|
1429
|
+
const data = JSON.parse(readFileSync4(path, "utf8"));
|
|
1430
|
+
return Number.isInteger(data.port) && data.port > 0 && data.port <= 65535 && /^[a-f0-9]{64}$/u.test(data.nonce) && Number.isInteger(data.pid) ? data : void 0;
|
|
1431
|
+
} catch {
|
|
1013
1432
|
return void 0;
|
|
1014
1433
|
}
|
|
1015
|
-
return { token: stored, source: "token_file" };
|
|
1016
|
-
}
|
|
1017
|
-
function credentialFingerprint(value) {
|
|
1018
|
-
return createHash2("sha256").update(value).digest("hex");
|
|
1019
1434
|
}
|
|
1020
|
-
function
|
|
1021
|
-
|
|
1022
|
-
|
|
1435
|
+
function signature(secret, nonce, body) {
|
|
1436
|
+
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
1437
|
+
}
|
|
1438
|
+
function matches(left, right) {
|
|
1439
|
+
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
1440
|
+
}
|
|
1441
|
+
function tokenHash(token) {
|
|
1442
|
+
return token ? createHash2("sha256").update(token).digest("hex") : void 0;
|
|
1443
|
+
}
|
|
1444
|
+
async function brokerRequest(descriptor, environment, options) {
|
|
1445
|
+
const body = JSON.stringify({
|
|
1446
|
+
generation: environment.generation,
|
|
1447
|
+
force: options.force === true,
|
|
1448
|
+
observedTokenHash: tokenHash(options.observedToken),
|
|
1449
|
+
timestamp: Date.now()
|
|
1450
|
+
});
|
|
1451
|
+
const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
1452
|
+
method: "POST",
|
|
1453
|
+
body,
|
|
1454
|
+
redirect: "error",
|
|
1455
|
+
signal: options.signal,
|
|
1456
|
+
headers: {
|
|
1457
|
+
"Content-Type": "application/json",
|
|
1458
|
+
"X-Prim-Proof": signature(environment.clientSecret, descriptor.nonce, body)
|
|
1459
|
+
}
|
|
1460
|
+
});
|
|
1461
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_RESPONSE_BYTES));
|
|
1462
|
+
if (typeof envelope.body !== "string" || !matches(signature(environment.clientSecret, descriptor.nonce, envelope.body), envelope.proof))
|
|
1463
|
+
throw new MachineAuthError(
|
|
1464
|
+
"broker_unavailable",
|
|
1465
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
1466
|
+
);
|
|
1467
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
1468
|
+
if (data.error) {
|
|
1469
|
+
const error = machineRecord(data.error);
|
|
1470
|
+
throw new MachineAuthError(
|
|
1471
|
+
String(error.code),
|
|
1472
|
+
String(error.message),
|
|
1473
|
+
error.terminal === true,
|
|
1474
|
+
typeof error.retryAt === "number" ? error.retryAt : void 0
|
|
1475
|
+
);
|
|
1476
|
+
}
|
|
1477
|
+
const credential = data.credential;
|
|
1478
|
+
if (credential?.generation !== environment.generation || credential.clientId !== environment.clientId || credential.storage !== "environment")
|
|
1479
|
+
throw new MachineAuthError(
|
|
1480
|
+
"identity_changed",
|
|
1481
|
+
"Machine identity changed; restart the operation."
|
|
1482
|
+
);
|
|
1483
|
+
return credential;
|
|
1484
|
+
}
|
|
1485
|
+
async function acquireBrokerCredential(options) {
|
|
1486
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1487
|
+
const existing = readDescriptor(path);
|
|
1488
|
+
if (existing) {
|
|
1489
|
+
try {
|
|
1490
|
+
return await brokerRequest(existing, options.environment, options);
|
|
1491
|
+
} catch (error) {
|
|
1492
|
+
options.signal.throwIfAborted();
|
|
1493
|
+
if (error instanceof MachineAuthError) throw error;
|
|
1494
|
+
}
|
|
1023
1495
|
}
|
|
1024
|
-
const
|
|
1025
|
-
|
|
1026
|
-
|
|
1496
|
+
const descriptor = await withFileLock(
|
|
1497
|
+
join5(options.directory, "machine-broker.lock"),
|
|
1498
|
+
async () => {
|
|
1499
|
+
const current = readDescriptor(path);
|
|
1500
|
+
if (current) {
|
|
1501
|
+
try {
|
|
1502
|
+
const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
|
|
1503
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
|
|
1504
|
+
redirect: "error"
|
|
1505
|
+
});
|
|
1506
|
+
if (response.ok && await response.text() === current.nonce) return current;
|
|
1507
|
+
} catch {
|
|
1508
|
+
options.signal.throwIfAborted();
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
const bundled = fileURLToPath2(import.meta.url);
|
|
1512
|
+
const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
1513
|
+
if (!entry)
|
|
1514
|
+
throw new MachineAuthError(
|
|
1515
|
+
"broker_unavailable",
|
|
1516
|
+
"Reinstall Prim to restore its machine credential broker."
|
|
1517
|
+
);
|
|
1518
|
+
await new Promise((resolve2, reject) => {
|
|
1519
|
+
const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
|
|
1520
|
+
detached: true,
|
|
1521
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
1522
|
+
windowsHide: true,
|
|
1523
|
+
env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
|
|
1524
|
+
});
|
|
1525
|
+
let settled = false;
|
|
1526
|
+
const finish = (error) => {
|
|
1527
|
+
if (settled) return;
|
|
1528
|
+
settled = true;
|
|
1529
|
+
options.signal.removeEventListener("abort", abort);
|
|
1530
|
+
if (error) child.kill();
|
|
1531
|
+
if (child.connected) child.disconnect();
|
|
1532
|
+
child.unref();
|
|
1533
|
+
error ? reject(error) : resolve2();
|
|
1534
|
+
};
|
|
1535
|
+
const abort = () => finish(
|
|
1536
|
+
new MachineAuthError(
|
|
1537
|
+
"broker_unavailable",
|
|
1538
|
+
"Machine credential broker startup was cancelled."
|
|
1539
|
+
)
|
|
1540
|
+
);
|
|
1541
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
1542
|
+
child.once(
|
|
1543
|
+
"error",
|
|
1544
|
+
() => finish(
|
|
1545
|
+
new MachineAuthError(
|
|
1546
|
+
"broker_unavailable",
|
|
1547
|
+
"Machine credential broker could not start."
|
|
1548
|
+
)
|
|
1549
|
+
)
|
|
1550
|
+
);
|
|
1551
|
+
child.once(
|
|
1552
|
+
"exit",
|
|
1553
|
+
() => finish(
|
|
1554
|
+
new MachineAuthError(
|
|
1555
|
+
"broker_unavailable",
|
|
1556
|
+
"Machine credential broker exited during startup."
|
|
1557
|
+
)
|
|
1558
|
+
)
|
|
1559
|
+
);
|
|
1560
|
+
child.once("message", (message) => {
|
|
1561
|
+
if (message === "ready") finish();
|
|
1562
|
+
});
|
|
1563
|
+
if (options.signal.aborted) abort();
|
|
1564
|
+
});
|
|
1565
|
+
const started = readDescriptor(path);
|
|
1566
|
+
if (!started)
|
|
1567
|
+
throw new MachineAuthError(
|
|
1568
|
+
"broker_unavailable",
|
|
1569
|
+
"Machine credential broker did not become ready."
|
|
1570
|
+
);
|
|
1571
|
+
return started;
|
|
1572
|
+
},
|
|
1573
|
+
{ signal: options.signal }
|
|
1574
|
+
);
|
|
1575
|
+
try {
|
|
1576
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
1577
|
+
} catch (error) {
|
|
1578
|
+
options.signal.throwIfAborted();
|
|
1579
|
+
if (error instanceof MachineAuthError) throw error;
|
|
1580
|
+
throw new MachineAuthError(
|
|
1581
|
+
"broker_unavailable",
|
|
1582
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
1583
|
+
);
|
|
1027
1584
|
}
|
|
1028
|
-
return {
|
|
1029
|
-
version: 1,
|
|
1030
|
-
family: "legacy_broker",
|
|
1031
|
-
accessTokenHash: record.accessTokenHash,
|
|
1032
|
-
refreshTokenHash: record.refreshTokenHash
|
|
1033
|
-
};
|
|
1034
1585
|
}
|
|
1035
|
-
|
|
1036
|
-
|
|
1586
|
+
|
|
1587
|
+
// src/lib/machine-retry.ts
|
|
1588
|
+
import { createHash as createHash3 } from "crypto";
|
|
1589
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync5, rmSync as rmSync4 } from "fs";
|
|
1590
|
+
import { join as join6 } from "path";
|
|
1591
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request) {
|
|
1592
|
+
signal?.throwIfAborted();
|
|
1593
|
+
const key = createHash3("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
1594
|
+
const path = join6(directory, `machine_retry_${key}.json`);
|
|
1595
|
+
let state = { failures: 0, retryAt: 0 };
|
|
1037
1596
|
try {
|
|
1038
|
-
|
|
1597
|
+
const stat = lstatSync3(path);
|
|
1598
|
+
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
1599
|
+
const data = JSON.parse(readFileSync5(path, "utf8"));
|
|
1600
|
+
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
1601
|
+
throw new Error("Invalid retry state");
|
|
1602
|
+
state = data;
|
|
1039
1603
|
} catch (error) {
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1604
|
+
if (error.code !== "ENOENT")
|
|
1605
|
+
throw new MachineAuthError("invalid_storage", "Machine retry state is unreadable.");
|
|
1606
|
+
}
|
|
1607
|
+
if (state.retryAt > Date.now())
|
|
1608
|
+
throw new MachineAuthError(
|
|
1609
|
+
"token_service_unavailable",
|
|
1610
|
+
"Machine authentication is cooling down after a temporary failure. Retry later.",
|
|
1611
|
+
false,
|
|
1612
|
+
state.retryAt
|
|
1613
|
+
);
|
|
1043
1614
|
try {
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
return
|
|
1615
|
+
const result = await request();
|
|
1616
|
+
rmSync4(path, { force: true });
|
|
1617
|
+
return result;
|
|
1618
|
+
} catch (error) {
|
|
1619
|
+
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
1620
|
+
"authentication_unavailable",
|
|
1621
|
+
"token_service_unavailable",
|
|
1622
|
+
"verification_unavailable",
|
|
1623
|
+
"discovery_unavailable"
|
|
1624
|
+
].includes(error.code)) {
|
|
1625
|
+
const failures = Math.min(16, state.failures + 1);
|
|
1626
|
+
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
1627
|
+
const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
|
|
1628
|
+
atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
|
|
1629
|
+
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
1630
|
+
}
|
|
1631
|
+
throw error;
|
|
1047
1632
|
}
|
|
1048
1633
|
}
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1634
|
+
|
|
1635
|
+
// src/lib/machine-credentials.ts
|
|
1636
|
+
var require2 = createRequire(import.meta.url);
|
|
1637
|
+
var SERVICE = "ai.primitive.prim.machine";
|
|
1638
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
1639
|
+
var PROFILE_FILE = "machine_profile.json";
|
|
1640
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
1641
|
+
var cached;
|
|
1642
|
+
function configurationDirectory(deps) {
|
|
1643
|
+
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
1644
|
+
}
|
|
1645
|
+
function apiUrlFor(deps) {
|
|
1646
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
1647
|
+
}
|
|
1648
|
+
function hash(value) {
|
|
1649
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
1650
|
+
}
|
|
1651
|
+
function recordPath(directory, generation) {
|
|
1652
|
+
return join7(directory, `machine_${generation}.json`);
|
|
1653
|
+
}
|
|
1654
|
+
function storageKey(directory, generation) {
|
|
1655
|
+
return `${hash(directory)}:${generation}`;
|
|
1656
|
+
}
|
|
1657
|
+
function environmentContextPath(deps, clientId) {
|
|
1658
|
+
return join7(
|
|
1659
|
+
configurationDirectory(deps),
|
|
1660
|
+
`machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1661
|
+
);
|
|
1662
|
+
}
|
|
1663
|
+
function writeEnvironmentContext(credential, deps) {
|
|
1664
|
+
const {
|
|
1665
|
+
apiUrl,
|
|
1666
|
+
issuer,
|
|
1667
|
+
audience,
|
|
1668
|
+
generation,
|
|
1669
|
+
machineId,
|
|
1670
|
+
clientId,
|
|
1671
|
+
organizationId,
|
|
1672
|
+
workosOrganizationId,
|
|
1673
|
+
displayName,
|
|
1674
|
+
scopes,
|
|
1675
|
+
expiresAt
|
|
1676
|
+
} = credential;
|
|
1053
1677
|
try {
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1678
|
+
writePrivate(environmentContextPath(deps, clientId), {
|
|
1679
|
+
version: 1,
|
|
1680
|
+
apiUrl,
|
|
1681
|
+
issuer,
|
|
1682
|
+
audience,
|
|
1683
|
+
generation,
|
|
1684
|
+
machineId,
|
|
1685
|
+
clientId,
|
|
1686
|
+
organizationId,
|
|
1687
|
+
workosOrganizationId,
|
|
1688
|
+
displayName,
|
|
1689
|
+
scopes,
|
|
1690
|
+
expiresAt
|
|
1691
|
+
});
|
|
1061
1692
|
} catch {
|
|
1062
|
-
return { state: "invalid" };
|
|
1063
1693
|
}
|
|
1064
1694
|
}
|
|
1065
|
-
function
|
|
1066
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1067
|
-
const record = value;
|
|
1068
|
-
const keys = Object.keys(record).sort();
|
|
1069
|
-
return keys.length === 2 && keys[0] === "state" && keys[1] === "version" && record.version === CREDENTIAL_MIGRATION_VERSION && record.state === CREDENTIAL_MIGRATION_STATE;
|
|
1070
|
-
}
|
|
1071
|
-
function readCredentialMigrationState(path = CREDENTIAL_MIGRATION_PATH) {
|
|
1072
|
-
const parsed = readBoundedCredentialJson(path);
|
|
1073
|
-
if (parsed === void 0) return "absent";
|
|
1074
|
-
return parsed !== null && isCredentialMigrationSentinel(parsed) ? "valid" : "invalid";
|
|
1075
|
-
}
|
|
1076
|
-
function readStoredCredentialMetadata(metadataPath = CREDENTIAL_METADATA_PATH, familyPath = CREDENTIAL_FAMILY_PATH, migrationPath = CREDENTIAL_MIGRATION_PATH) {
|
|
1077
|
-
const family = readCredentialFamily(familyPath);
|
|
1078
|
-
if (family) return family;
|
|
1079
|
-
const parsed = readBoundedCredentialJson(metadataPath);
|
|
1080
|
-
if (parsed === void 0) {
|
|
1081
|
-
return readCredentialMigrationState(migrationPath) === "absent" ? { state: "legacy_broker" } : { state: "invalid" };
|
|
1082
|
-
}
|
|
1083
|
-
if (parsed === null) return { state: "invalid" };
|
|
1695
|
+
function readEnvironmentContext(environment, deps) {
|
|
1084
1696
|
try {
|
|
1697
|
+
const data = machineRecord(readPrivate(environmentContextPath(deps, environment.clientId)));
|
|
1698
|
+
if (data.generation !== environment.generation || data.clientId !== environment.clientId || data.apiUrl !== apiUrlFor(deps) || typeof data.expiresAt !== "number" || !Number.isFinite(data.expiresAt) || data.expiresAt <= Date.now())
|
|
1699
|
+
return void 0;
|
|
1700
|
+
const configuration = parseMachineConfiguration({
|
|
1701
|
+
protocol_version: data.version,
|
|
1702
|
+
issuer: data.issuer,
|
|
1703
|
+
audience: data.audience
|
|
1704
|
+
});
|
|
1705
|
+
const identity = parseStoredIdentity(data);
|
|
1085
1706
|
return {
|
|
1086
|
-
|
|
1087
|
-
|
|
1707
|
+
...configuration,
|
|
1708
|
+
...identity,
|
|
1709
|
+
apiUrl: data.apiUrl,
|
|
1710
|
+
generation: environment.generation
|
|
1088
1711
|
};
|
|
1089
1712
|
} catch {
|
|
1090
|
-
return
|
|
1713
|
+
return void 0;
|
|
1091
1714
|
}
|
|
1092
1715
|
}
|
|
1093
|
-
function
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1716
|
+
function keyringEntry(key) {
|
|
1717
|
+
let directory = dirname5(fileURLToPath3(import.meta.url));
|
|
1718
|
+
for (let depth = 0; depth < 5; depth++) {
|
|
1719
|
+
const loader = join7(directory, "native", "keyring.cjs");
|
|
1720
|
+
if (existsSync4(loader)) {
|
|
1721
|
+
const module2 = require2(loader);
|
|
1722
|
+
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1723
|
+
}
|
|
1724
|
+
directory = dirname5(directory);
|
|
1102
1725
|
}
|
|
1726
|
+
const module = require2("@napi-rs/keyring");
|
|
1727
|
+
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1103
1728
|
}
|
|
1104
|
-
function
|
|
1105
|
-
|
|
1106
|
-
|
|
1729
|
+
function protectPath(path, directory) {
|
|
1730
|
+
if (process.platform !== "win32") {
|
|
1731
|
+
chmodSync(path, directory ? 448 : 384);
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
const encodedPath = Buffer.from(path).toString("base64");
|
|
1735
|
+
const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
|
|
1736
|
+
execFileSync4(
|
|
1737
|
+
"powershell.exe",
|
|
1738
|
+
[
|
|
1739
|
+
"-NoProfile",
|
|
1740
|
+
"-NonInteractive",
|
|
1741
|
+
"-EncodedCommand",
|
|
1742
|
+
Buffer.from(script, "utf16le").toString("base64")
|
|
1743
|
+
],
|
|
1744
|
+
{ stdio: "pipe", encoding: "utf8", windowsHide: true }
|
|
1745
|
+
);
|
|
1107
1746
|
}
|
|
1108
|
-
function
|
|
1109
|
-
|
|
1110
|
-
|
|
1747
|
+
function ensureDirectory(directory) {
|
|
1748
|
+
mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
1749
|
+
if (lstatSync4(directory).isSymbolicLink())
|
|
1750
|
+
throw new MachineAuthError(
|
|
1751
|
+
"unsafe_storage",
|
|
1752
|
+
"Credential directory must not be a symbolic link."
|
|
1753
|
+
);
|
|
1754
|
+
protectPath(directory, true);
|
|
1111
1755
|
}
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
constants,
|
|
1117
|
-
closeSync,
|
|
1118
|
-
fchmodSync,
|
|
1119
|
-
fsyncSync,
|
|
1120
|
-
mkdirSync,
|
|
1121
|
-
openSync,
|
|
1122
|
-
renameSync,
|
|
1123
|
-
rmSync,
|
|
1124
|
-
writeFileSync
|
|
1125
|
-
} from "fs";
|
|
1126
|
-
import { dirname as dirname3 } from "path";
|
|
1127
|
-
var DEFAULT_FILE_MODE = 438;
|
|
1128
|
-
function syncDirectory(path) {
|
|
1129
|
-
const fd = openSync(path, constants.O_RDONLY);
|
|
1130
|
-
try {
|
|
1131
|
-
fsyncSync(fd);
|
|
1132
|
-
} finally {
|
|
1133
|
-
closeSync(fd);
|
|
1134
|
-
}
|
|
1756
|
+
function writePrivate(path, value) {
|
|
1757
|
+
atomicWriteFile(path, `${JSON.stringify(value)}
|
|
1758
|
+
`, { mode: 384 });
|
|
1759
|
+
protectPath(path, false);
|
|
1135
1760
|
}
|
|
1136
|
-
function
|
|
1137
|
-
|
|
1761
|
+
function readPrivate(path) {
|
|
1762
|
+
let raw;
|
|
1138
1763
|
try {
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
const createdDirectories = [];
|
|
1146
|
-
let current = parent;
|
|
1147
|
-
while (current !== firstCreatedParent) {
|
|
1148
|
-
createdDirectories.push(current);
|
|
1149
|
-
const next = dirname3(current);
|
|
1150
|
-
if (next === current) {
|
|
1151
|
-
throw new Error("recursive mkdir returned a path outside the target parent chain");
|
|
1764
|
+
const stat = lstatSync4(path);
|
|
1765
|
+
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1766
|
+
throw new MachineAuthError(
|
|
1767
|
+
"unsafe_storage",
|
|
1768
|
+
"Machine credential files must be owner-only regular files."
|
|
1769
|
+
);
|
|
1152
1770
|
}
|
|
1153
|
-
|
|
1771
|
+
raw = readFileSync6(path, "utf8");
|
|
1772
|
+
} catch (error) {
|
|
1773
|
+
if (error.code === "ENOENT") return void 0;
|
|
1774
|
+
throw error;
|
|
1154
1775
|
}
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1776
|
+
try {
|
|
1777
|
+
return JSON.parse(raw);
|
|
1778
|
+
} catch {
|
|
1779
|
+
throw new MachineAuthError("invalid_storage", "Stored machine credentials are malformed.");
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
function parseStoredIdentity(data) {
|
|
1783
|
+
return parseMachineIdentity(
|
|
1784
|
+
{
|
|
1785
|
+
authenticated: true,
|
|
1786
|
+
organizationBindingVersion: 2,
|
|
1787
|
+
captureAuthorityKind: "workos_m2m",
|
|
1788
|
+
organizationId: data.organizationId,
|
|
1789
|
+
workosOrganizationId: data.workosOrganizationId,
|
|
1790
|
+
principal: { ...data, kind: "machine" }
|
|
1791
|
+
},
|
|
1792
|
+
String(data.clientId)
|
|
1793
|
+
);
|
|
1794
|
+
}
|
|
1795
|
+
function parseProfile(value) {
|
|
1796
|
+
const data = machineRecord(value);
|
|
1797
|
+
const config = parseMachineConfiguration({
|
|
1798
|
+
protocol_version: data.version,
|
|
1799
|
+
issuer: data.issuer,
|
|
1800
|
+
audience: data.audience
|
|
1801
|
+
});
|
|
1802
|
+
if (typeof data.apiUrl !== "string" || machineApiUrl(data.apiUrl) !== data.apiUrl || !machineString(data.generation, 64) || !/^[a-f0-9-]{36}$/u.test(data.generation) || data.storage !== "keychain" && data.storage !== "file" || !machineString(data.clientId, 256)) {
|
|
1803
|
+
throw new MachineAuthError("invalid_storage", "Stored machine profile is malformed.");
|
|
1159
1804
|
}
|
|
1805
|
+
const identity = parseStoredIdentity(data);
|
|
1806
|
+
return {
|
|
1807
|
+
...config,
|
|
1808
|
+
...identity,
|
|
1809
|
+
version: 1,
|
|
1810
|
+
apiUrl: data.apiUrl,
|
|
1811
|
+
generation: data.generation,
|
|
1812
|
+
storage: data.storage
|
|
1813
|
+
};
|
|
1160
1814
|
}
|
|
1161
|
-
function
|
|
1162
|
-
const
|
|
1163
|
-
|
|
1164
|
-
|
|
1815
|
+
function readMachineProfile(deps = {}) {
|
|
1816
|
+
const value = readPrivate(join7(configurationDirectory(deps), PROFILE_FILE));
|
|
1817
|
+
return value === void 0 ? void 0 : parseProfile(value);
|
|
1818
|
+
}
|
|
1819
|
+
function environmentCredentials(deps) {
|
|
1820
|
+
const env = deps.env ?? process.env;
|
|
1821
|
+
const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
|
|
1822
|
+
if (clientId === void 0 && clientSecret === void 0) return void 0;
|
|
1823
|
+
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1824
|
+
throw new MachineAuthError(
|
|
1825
|
+
"incomplete_machine_credentials",
|
|
1826
|
+
"Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
|
|
1827
|
+
);
|
|
1165
1828
|
}
|
|
1829
|
+
return {
|
|
1830
|
+
clientId,
|
|
1831
|
+
clientSecret,
|
|
1832
|
+
generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1833
|
+
};
|
|
1166
1834
|
}
|
|
1167
|
-
function
|
|
1168
|
-
const
|
|
1169
|
-
|
|
1170
|
-
|
|
1835
|
+
function hasMachineConfiguration(deps = {}) {
|
|
1836
|
+
const env = deps.env ?? process.env;
|
|
1837
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync4(join7(configurationDirectory(deps), PROFILE_FILE));
|
|
1838
|
+
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1839
|
+
throw new MachineAuthError(
|
|
1840
|
+
"conflicting_credentials",
|
|
1841
|
+
"Unset PRIM_TOKEN when using machine credentials."
|
|
1842
|
+
);
|
|
1171
1843
|
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1844
|
+
if (configured) environmentCredentials(deps);
|
|
1845
|
+
return configured;
|
|
1846
|
+
}
|
|
1847
|
+
function machineContext(deps = {}) {
|
|
1848
|
+
if (!hasMachineConfiguration(deps)) return void 0;
|
|
1849
|
+
const environment = environmentCredentials(deps);
|
|
1850
|
+
if (environment) {
|
|
1851
|
+
if (environmentTerminal === environment.generation) return void 0;
|
|
1852
|
+
return cached?.generation === environment.generation && cached.expiresAt > Date.now() ? cached : readEnvironmentContext(environment, deps);
|
|
1853
|
+
}
|
|
1854
|
+
const profile = readMachineProfile(deps);
|
|
1855
|
+
if (profile && profile.apiUrl !== apiUrlFor(deps))
|
|
1856
|
+
throw new MachineAuthError(
|
|
1857
|
+
"deployment_mismatch",
|
|
1858
|
+
"Machine credentials belong to another API deployment. Configure this deployment or inject its credentials."
|
|
1859
|
+
);
|
|
1860
|
+
return profile;
|
|
1861
|
+
}
|
|
1862
|
+
function cachedMachineCredential(deps = {}) {
|
|
1863
|
+
const context = machineContext(deps);
|
|
1864
|
+
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1865
|
+
}
|
|
1866
|
+
function machineSessionEnded(deps = {}) {
|
|
1867
|
+
if (!hasMachineConfiguration(deps)) return false;
|
|
1868
|
+
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1869
|
+
if (!generation) return false;
|
|
1870
|
+
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1871
|
+
return readPrivate(join7(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1872
|
+
}
|
|
1873
|
+
var environmentTerminal;
|
|
1874
|
+
async function loadRecord(profile, deps, signal) {
|
|
1875
|
+
const directory = configurationDirectory(deps);
|
|
1876
|
+
let value;
|
|
1174
1877
|
try {
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1878
|
+
if (profile.storage === "keychain") {
|
|
1879
|
+
const raw = await (deps.entry ?? keyringEntry)(
|
|
1880
|
+
storageKey(directory, profile.generation)
|
|
1881
|
+
).getPassword(signal);
|
|
1882
|
+
if (!raw || raw.length > 96 * 1024) throw new Error("missing");
|
|
1883
|
+
value = JSON.parse(raw);
|
|
1884
|
+
} else value = readPrivate(recordPath(directory, profile.generation));
|
|
1885
|
+
const data = machineRecord(value);
|
|
1886
|
+
const stored = parseProfile(data);
|
|
1887
|
+
if ([
|
|
1888
|
+
"apiUrl",
|
|
1889
|
+
"issuer",
|
|
1890
|
+
"audience",
|
|
1891
|
+
"generation",
|
|
1892
|
+
"storage",
|
|
1893
|
+
"machineId",
|
|
1894
|
+
"clientId",
|
|
1895
|
+
"organizationId",
|
|
1896
|
+
"workosOrganizationId"
|
|
1897
|
+
].some(
|
|
1898
|
+
(key) => stored[key] !== profile[key]
|
|
1899
|
+
) || !machineString(data.clientSecret) || !machineString(data.accessToken, 64 * 1024) || typeof data.expiresAt !== "number" || !Number.isFinite(data.expiresAt))
|
|
1900
|
+
throw new Error("mismatch");
|
|
1901
|
+
return {
|
|
1902
|
+
...stored,
|
|
1903
|
+
clientSecret: data.clientSecret,
|
|
1904
|
+
accessToken: data.accessToken,
|
|
1905
|
+
expiresAt: data.expiresAt
|
|
1906
|
+
};
|
|
1907
|
+
} catch {
|
|
1908
|
+
throw new MachineAuthError(
|
|
1909
|
+
"storage_unavailable",
|
|
1910
|
+
`Cannot read machine credentials from ${profile.storage}. Unlock or repair that store; Prim will not use another credential.`
|
|
1911
|
+
);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
async function persistRecord(record, deps, signal) {
|
|
1915
|
+
const directory = configurationDirectory(deps);
|
|
1916
|
+
if (record.storage === "keychain") {
|
|
1178
1917
|
try {
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1918
|
+
await (deps.entry ?? keyringEntry)(storageKey(directory, record.generation)).setPassword(
|
|
1919
|
+
JSON.stringify(record),
|
|
1920
|
+
signal
|
|
1921
|
+
);
|
|
1922
|
+
} catch {
|
|
1923
|
+
throw new MachineAuthError(
|
|
1924
|
+
"storage_unavailable",
|
|
1925
|
+
"Cannot update the machine credential store. Unlock it and retry."
|
|
1926
|
+
);
|
|
1184
1927
|
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1928
|
+
} else writePrivate(recordPath(directory, record.generation), record);
|
|
1929
|
+
}
|
|
1930
|
+
async function configureMachine(clientId, clientSecret, deps = {}, signal) {
|
|
1931
|
+
if ((deps.env ?? process.env).PRIM_TOKEN?.trim() || environmentCredentials(deps)) {
|
|
1932
|
+
throw new MachineAuthError(
|
|
1933
|
+
"conflicting_credentials",
|
|
1934
|
+
"Unset injected credentials before configuring a saved machine."
|
|
1935
|
+
);
|
|
1936
|
+
}
|
|
1937
|
+
const apiUrl = apiUrlFor(deps);
|
|
1938
|
+
const directory = configurationDirectory(deps);
|
|
1939
|
+
ensureDirectory(directory);
|
|
1940
|
+
return withFileLock(
|
|
1941
|
+
join7(directory, "credentials.lock"),
|
|
1942
|
+
async () => {
|
|
1943
|
+
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
1944
|
+
directory,
|
|
1945
|
+
apiUrl,
|
|
1946
|
+
clientId,
|
|
1947
|
+
signal,
|
|
1948
|
+
async () => {
|
|
1949
|
+
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
1950
|
+
const tokens2 = await exchangeMachineCredentials(
|
|
1951
|
+
configuration2,
|
|
1952
|
+
clientId,
|
|
1953
|
+
clientSecret,
|
|
1954
|
+
signal,
|
|
1955
|
+
deps.fetch
|
|
1956
|
+
);
|
|
1957
|
+
const identity2 = await verifyMachineIdentity(
|
|
1958
|
+
apiUrl,
|
|
1959
|
+
tokens2.accessToken,
|
|
1960
|
+
clientId,
|
|
1961
|
+
signal,
|
|
1962
|
+
deps.fetch
|
|
1963
|
+
);
|
|
1964
|
+
return { configuration: configuration2, tokens: tokens2, identity: identity2 };
|
|
1965
|
+
}
|
|
1966
|
+
);
|
|
1967
|
+
const previous = readMachineProfile(deps);
|
|
1968
|
+
const retired = readRetiredProfiles(directory);
|
|
1969
|
+
let profile = {
|
|
1970
|
+
...configuration,
|
|
1971
|
+
...identity,
|
|
1972
|
+
version: 1,
|
|
1973
|
+
apiUrl,
|
|
1974
|
+
generation: randomUUID2(),
|
|
1975
|
+
storage: "keychain"
|
|
1976
|
+
};
|
|
1190
1977
|
try {
|
|
1191
|
-
|
|
1978
|
+
await persistRecord({ ...profile, ...tokens, clientSecret }, deps, signal);
|
|
1979
|
+
} catch (error) {
|
|
1980
|
+
if (signal?.aborted) throw signal.reason;
|
|
1981
|
+
if (previous?.storage === "keychain") throw error;
|
|
1982
|
+
profile = { ...profile, storage: "file" };
|
|
1983
|
+
await persistRecord({ ...profile, ...tokens, clientSecret }, deps, signal);
|
|
1984
|
+
}
|
|
1985
|
+
writePrivate(join7(directory, PROFILE_FILE), profile);
|
|
1986
|
+
rmSync5(join7(directory, "machine_terminal.json"), { force: true });
|
|
1987
|
+
cached = { ...profile, ...tokens };
|
|
1988
|
+
if (previous) {
|
|
1989
|
+
writePrivate(join7(directory, "machine_retired.json"), [...retired, previous]);
|
|
1990
|
+
}
|
|
1991
|
+
await cleanupRetired(deps, signal);
|
|
1992
|
+
return profile;
|
|
1993
|
+
},
|
|
1994
|
+
{ signal }
|
|
1995
|
+
);
|
|
1996
|
+
}
|
|
1997
|
+
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1998
|
+
if (!hasMachineConfiguration(deps)) return void 0;
|
|
1999
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2000
|
+
const apiUrl = apiUrlFor(deps);
|
|
2001
|
+
const environment = environmentCredentials(deps);
|
|
2002
|
+
if (environment) {
|
|
2003
|
+
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
2004
|
+
const directory2 = configurationDirectory(deps);
|
|
2005
|
+
ensureDirectory(directory2);
|
|
2006
|
+
if (!deps.fetch && !deps.localEnvironment) {
|
|
2007
|
+
try {
|
|
2008
|
+
cached = await acquireBrokerCredential({
|
|
2009
|
+
directory: directory2,
|
|
2010
|
+
apiUrl,
|
|
2011
|
+
environment,
|
|
2012
|
+
env: deps.env ?? process.env,
|
|
2013
|
+
force: options.force,
|
|
2014
|
+
observedToken: observedToken2,
|
|
2015
|
+
signal
|
|
2016
|
+
});
|
|
2017
|
+
writeEnvironmentContext(cached, deps);
|
|
2018
|
+
return cached;
|
|
2019
|
+
} catch (error) {
|
|
2020
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
2021
|
+
environmentTerminal = environment.generation;
|
|
2022
|
+
throw error;
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
return withFileLock(
|
|
2026
|
+
join7(directory2, "credentials.lock"),
|
|
2027
|
+
async () => {
|
|
2028
|
+
if (machineSessionEnded(deps))
|
|
2029
|
+
throw new MachineAuthError(
|
|
2030
|
+
"machine_credentials_rejected",
|
|
2031
|
+
"Rotate the injected machine credentials.",
|
|
2032
|
+
true
|
|
2033
|
+
);
|
|
2034
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
|
|
2035
|
+
return cached;
|
|
2036
|
+
try {
|
|
2037
|
+
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
2038
|
+
directory2,
|
|
2039
|
+
apiUrl,
|
|
2040
|
+
environment.clientId,
|
|
2041
|
+
signal,
|
|
2042
|
+
async () => {
|
|
2043
|
+
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
2044
|
+
const tokens2 = await exchangeMachineCredentials(
|
|
2045
|
+
configuration2,
|
|
2046
|
+
environment.clientId,
|
|
2047
|
+
environment.clientSecret,
|
|
2048
|
+
signal,
|
|
2049
|
+
deps.fetch
|
|
2050
|
+
);
|
|
2051
|
+
const identity2 = await verifyMachineIdentity(
|
|
2052
|
+
apiUrl,
|
|
2053
|
+
tokens2.accessToken,
|
|
2054
|
+
environment.clientId,
|
|
2055
|
+
signal,
|
|
2056
|
+
deps.fetch
|
|
2057
|
+
);
|
|
2058
|
+
return { configuration: configuration2, tokens: tokens2, identity: identity2 };
|
|
2059
|
+
}
|
|
2060
|
+
);
|
|
2061
|
+
cached = {
|
|
2062
|
+
...configuration,
|
|
2063
|
+
...tokens,
|
|
2064
|
+
...identity,
|
|
2065
|
+
apiUrl,
|
|
2066
|
+
generation: environment.generation,
|
|
2067
|
+
storage: "environment"
|
|
2068
|
+
};
|
|
2069
|
+
writeEnvironmentContext(cached, deps);
|
|
2070
|
+
return cached;
|
|
2071
|
+
} catch (error) {
|
|
2072
|
+
if (error instanceof MachineAuthError && error.terminal) {
|
|
2073
|
+
environmentTerminal = environment.generation;
|
|
2074
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2075
|
+
try {
|
|
2076
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2077
|
+
rmSync5(contextPath, { force: true });
|
|
2078
|
+
} catch {
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
throw error;
|
|
2082
|
+
}
|
|
2083
|
+
},
|
|
2084
|
+
{ signal }
|
|
2085
|
+
);
|
|
2086
|
+
}
|
|
2087
|
+
const observedToken = cachedMachineCredential(deps)?.accessToken;
|
|
2088
|
+
const expected = machineContext(deps);
|
|
2089
|
+
const directory = configurationDirectory(deps);
|
|
2090
|
+
return withFileLock(
|
|
2091
|
+
join7(directory, "credentials.lock"),
|
|
2092
|
+
async () => {
|
|
2093
|
+
const profile = readMachineProfile(deps);
|
|
2094
|
+
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
2095
|
+
throw new MachineAuthError(
|
|
2096
|
+
"identity_changed",
|
|
2097
|
+
"Machine identity changed; retry the operation."
|
|
2098
|
+
);
|
|
2099
|
+
if (machineSessionEnded(deps))
|
|
2100
|
+
throw new MachineAuthError(
|
|
2101
|
+
"machine_credentials_rejected",
|
|
2102
|
+
"Configure rotated or enabled machine credentials.",
|
|
2103
|
+
true
|
|
2104
|
+
);
|
|
2105
|
+
let record = await loadRecord(profile, deps, signal);
|
|
2106
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
|
|
2107
|
+
try {
|
|
2108
|
+
const { tokens, identity } = await withMachineCooldown(
|
|
2109
|
+
directory,
|
|
2110
|
+
apiUrl,
|
|
2111
|
+
profile.clientId,
|
|
2112
|
+
signal,
|
|
2113
|
+
async () => {
|
|
2114
|
+
const tokens2 = await exchangeMachineCredentials(
|
|
2115
|
+
profile,
|
|
2116
|
+
profile.clientId,
|
|
2117
|
+
record.clientSecret,
|
|
2118
|
+
signal,
|
|
2119
|
+
deps.fetch
|
|
2120
|
+
);
|
|
2121
|
+
const identity2 = await verifyMachineIdentity(
|
|
2122
|
+
apiUrl,
|
|
2123
|
+
tokens2.accessToken,
|
|
2124
|
+
profile.clientId,
|
|
2125
|
+
signal,
|
|
2126
|
+
deps.fetch
|
|
2127
|
+
);
|
|
2128
|
+
return { tokens: tokens2, identity: identity2 };
|
|
2129
|
+
}
|
|
2130
|
+
);
|
|
2131
|
+
if (identity.machineId !== profile.machineId || identity.organizationId !== profile.organizationId || identity.workosOrganizationId !== profile.workosOrganizationId)
|
|
2132
|
+
throw new MachineAuthError(
|
|
2133
|
+
"identity_changed",
|
|
2134
|
+
"Machine identity changed; configure the new identity explicitly.",
|
|
2135
|
+
true
|
|
2136
|
+
);
|
|
2137
|
+
record = { ...record, ...identity, ...tokens };
|
|
2138
|
+
await persistRecord(record, deps, signal);
|
|
2139
|
+
} catch (error) {
|
|
2140
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
2141
|
+
writePrivate(join7(directory, "machine_terminal.json"), profile.generation);
|
|
2142
|
+
throw error;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
const { clientSecret: _secret, ...credential } = record;
|
|
2146
|
+
cached = credential;
|
|
2147
|
+
return credential;
|
|
2148
|
+
},
|
|
2149
|
+
{ signal }
|
|
2150
|
+
);
|
|
2151
|
+
}
|
|
2152
|
+
async function clearMachineCredentials(deps = {}) {
|
|
2153
|
+
const directory = configurationDirectory(deps);
|
|
2154
|
+
if (!existsSync4(join7(directory, PROFILE_FILE))) return false;
|
|
2155
|
+
return withFileLock(join7(directory, "credentials.lock"), async () => {
|
|
2156
|
+
const profile = readMachineProfile(deps);
|
|
2157
|
+
if (!profile) return false;
|
|
2158
|
+
await cleanupRetired(deps, AbortSignal.timeout(1e4));
|
|
2159
|
+
if (existsSync4(join7(directory, "machine_retired.json")))
|
|
2160
|
+
throw new MachineAuthError(
|
|
2161
|
+
"storage_unavailable",
|
|
2162
|
+
"Unlock the credential store to remove retired machine credentials."
|
|
2163
|
+
);
|
|
2164
|
+
if (profile.storage === "keychain") {
|
|
2165
|
+
try {
|
|
2166
|
+
const entry = (deps.entry ?? keyringEntry)(storageKey(directory, profile.generation));
|
|
2167
|
+
const signal = AbortSignal.timeout(1e4);
|
|
2168
|
+
if (await entry.getPassword(signal) !== null) await entry.deletePassword(signal);
|
|
1192
2169
|
} catch {
|
|
2170
|
+
throw new MachineAuthError(
|
|
2171
|
+
"storage_unavailable",
|
|
2172
|
+
"Unlock the keychain to remove the saved machine credential."
|
|
2173
|
+
);
|
|
1193
2174
|
}
|
|
2175
|
+
} else rmSync5(recordPath(directory, profile.generation), { force: true });
|
|
2176
|
+
rmSync5(join7(directory, PROFILE_FILE), { force: true });
|
|
2177
|
+
rmSync5(join7(directory, "machine_terminal.json"), { force: true });
|
|
2178
|
+
cached = void 0;
|
|
2179
|
+
return true;
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
function machineCaptureActor(deps = {}) {
|
|
2183
|
+
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2184
|
+
const context = machineContext(deps);
|
|
2185
|
+
if (context)
|
|
2186
|
+
return {
|
|
2187
|
+
kind: "machine",
|
|
2188
|
+
apiUrl: context.apiUrl,
|
|
2189
|
+
clientId: context.clientId,
|
|
2190
|
+
issuer: context.issuer,
|
|
2191
|
+
machineId: context.machineId,
|
|
2192
|
+
organizationId: context.organizationId
|
|
2193
|
+
};
|
|
2194
|
+
const injected = environmentCredentials(deps);
|
|
2195
|
+
return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
|
|
2196
|
+
}
|
|
2197
|
+
function machineJournalBucket(identity) {
|
|
2198
|
+
return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
2199
|
+
}
|
|
2200
|
+
function readRetiredProfiles(directory) {
|
|
2201
|
+
const value = readPrivate(join7(directory, "machine_retired.json"));
|
|
2202
|
+
if (value === void 0) return [];
|
|
2203
|
+
if (!Array.isArray(value))
|
|
2204
|
+
throw new MachineAuthError(
|
|
2205
|
+
"storage_unavailable",
|
|
2206
|
+
"Invalid retired machine credential metadata."
|
|
2207
|
+
);
|
|
2208
|
+
return value.map(parseProfile);
|
|
2209
|
+
}
|
|
2210
|
+
async function cleanupRetired(deps, signal) {
|
|
2211
|
+
const directory = configurationDirectory(deps);
|
|
2212
|
+
const path = join7(directory, "machine_retired.json");
|
|
2213
|
+
const pending = [];
|
|
2214
|
+
for (const profile of readRetiredProfiles(directory)) {
|
|
2215
|
+
try {
|
|
2216
|
+
if (profile.storage === "keychain") {
|
|
2217
|
+
const entry = (deps.entry ?? keyringEntry)(storageKey(directory, profile.generation));
|
|
2218
|
+
if (await entry.getPassword(signal) !== null) await entry.deletePassword(signal);
|
|
2219
|
+
} else rmSync5(recordPath(directory, profile.generation), { force: true });
|
|
2220
|
+
} catch {
|
|
2221
|
+
pending.push(profile);
|
|
1194
2222
|
}
|
|
1195
|
-
throw error;
|
|
1196
2223
|
}
|
|
2224
|
+
if (pending.length) writePrivate(path, pending);
|
|
2225
|
+
else rmSync5(path, { force: true });
|
|
1197
2226
|
}
|
|
1198
2227
|
|
|
1199
|
-
// src/lib/
|
|
1200
|
-
|
|
1201
|
-
|
|
2228
|
+
// src/lib/credentials.ts
|
|
2229
|
+
import { createHash as createHash5 } from "crypto";
|
|
2230
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
2231
|
+
import { join as join8 } from "path";
|
|
2232
|
+
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
2233
|
+
var TOKEN_FILE_PATH = join8(CONFIG_DIRECTORY, "token");
|
|
2234
|
+
var REFRESH_TOKEN_PATH = join8(CONFIG_DIRECTORY, "refresh_token");
|
|
2235
|
+
var TOKEN_EXPIRES_PATH = join8(CONFIG_DIRECTORY, "token_expires_at");
|
|
2236
|
+
var TERMINAL_REFRESH_PATH = join8(CONFIG_DIRECTORY, "refresh_terminal");
|
|
2237
|
+
var CREDENTIAL_METADATA_PATH = join8(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
2238
|
+
var CREDENTIAL_FAMILY_PATH = join8(CONFIG_DIRECTORY, "credential_family.json");
|
|
2239
|
+
var CREDENTIAL_MIGRATION_PATH = join8(CONFIG_DIRECTORY, "credential_migration.json");
|
|
2240
|
+
var CREDENTIAL_LOCK_PATH = join8(CONFIG_DIRECTORY, "credentials.lock");
|
|
2241
|
+
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
2242
|
+
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
2243
|
+
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
2244
|
+
function readTrimmed(path) {
|
|
1202
2245
|
try {
|
|
1203
|
-
|
|
1204
|
-
return
|
|
1205
|
-
} catch
|
|
1206
|
-
return
|
|
2246
|
+
const value = readFileSync7(path, "utf8").trim();
|
|
2247
|
+
return value || void 0;
|
|
2248
|
+
} catch {
|
|
2249
|
+
return void 0;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
function resolveAuthCredential(options = {}) {
|
|
2253
|
+
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
2254
|
+
const machine = cachedMachineCredential({ env: options.env });
|
|
2255
|
+
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
2256
|
+
}
|
|
2257
|
+
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
2258
|
+
if (envToken) return { token: envToken, source: "environment" };
|
|
2259
|
+
const stored = readTrimmed(options.tokenFilePath ?? TOKEN_FILE_PATH);
|
|
2260
|
+
if (!stored) return void 0;
|
|
2261
|
+
const metadata = readStoredCredentialMetadata(
|
|
2262
|
+
options.metadataPath ?? CREDENTIAL_METADATA_PATH,
|
|
2263
|
+
options.familyPath ?? CREDENTIAL_FAMILY_PATH,
|
|
2264
|
+
options.migrationPath ?? CREDENTIAL_MIGRATION_PATH
|
|
2265
|
+
);
|
|
2266
|
+
if (metadata.state === "legacy_broker") {
|
|
2267
|
+
if (metadata.metadata) {
|
|
2268
|
+
const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
2269
|
+
if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
|
|
2270
|
+
return void 0;
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
return { token: stored, source: "token_file" };
|
|
2274
|
+
}
|
|
2275
|
+
if (metadata.state === "invalid") return void 0;
|
|
2276
|
+
const refreshToken = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
2277
|
+
if (!refreshToken || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken)) {
|
|
2278
|
+
return void 0;
|
|
1207
2279
|
}
|
|
2280
|
+
return { token: stored, source: "token_file" };
|
|
1208
2281
|
}
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
import { randomBytes } from "crypto";
|
|
1212
|
-
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync4, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
|
|
1213
|
-
import { dirname as dirname4, join as join5 } from "path";
|
|
1214
|
-
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
1215
|
-
var DEFAULT_POLL_MS = 50;
|
|
1216
|
-
var DEFAULT_INIT_GRACE_MS = 2e3;
|
|
1217
|
-
var DIRECTORY_MODE = 448;
|
|
1218
|
-
var FILE_MODE = 384;
|
|
1219
|
-
function ownerPath(lockDir) {
|
|
1220
|
-
return join5(lockDir, "owner.json");
|
|
2282
|
+
function credentialFingerprint(value) {
|
|
2283
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
1221
2284
|
}
|
|
1222
|
-
function
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
|
|
1226
|
-
return null;
|
|
1227
|
-
}
|
|
1228
|
-
return owner;
|
|
1229
|
-
} catch {
|
|
1230
|
-
return null;
|
|
2285
|
+
function parseLegacyBrokerCredentialMetadata(value) {
|
|
2286
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
2287
|
+
throw new Error("credential family is invalid");
|
|
1231
2288
|
}
|
|
2289
|
+
const record = value;
|
|
2290
|
+
if (record.version !== 1 || record.family !== "legacy_broker" || typeof record.accessTokenHash !== "string" || typeof record.refreshTokenHash !== "string" || !/^[a-f0-9]{64}$/u.test(record.accessTokenHash) || !/^[a-f0-9]{64}$/u.test(record.refreshTokenHash)) {
|
|
2291
|
+
throw new Error("credential family is invalid");
|
|
2292
|
+
}
|
|
2293
|
+
return {
|
|
2294
|
+
version: 1,
|
|
2295
|
+
family: "legacy_broker",
|
|
2296
|
+
accessTokenHash: record.accessTokenHash,
|
|
2297
|
+
refreshTokenHash: record.refreshTokenHash
|
|
2298
|
+
};
|
|
1232
2299
|
}
|
|
1233
|
-
function
|
|
1234
|
-
|
|
1235
|
-
}
|
|
1236
|
-
function tryTakeLock(lockDir, now) {
|
|
2300
|
+
function readBoundedCredentialJson(path) {
|
|
2301
|
+
let raw;
|
|
1237
2302
|
try {
|
|
1238
|
-
|
|
2303
|
+
raw = readFileSync7(path, "utf8");
|
|
1239
2304
|
} catch (error) {
|
|
1240
|
-
|
|
1241
|
-
throw error;
|
|
2305
|
+
return error.code === "ENOENT" ? void 0 : null;
|
|
1242
2306
|
}
|
|
1243
|
-
|
|
1244
|
-
pid: process.pid,
|
|
1245
|
-
nonce: randomBytes(16).toString("hex"),
|
|
1246
|
-
createdAt: now
|
|
1247
|
-
};
|
|
2307
|
+
if (Buffer.byteLength(raw, "utf8") > MAX_CREDENTIAL_METADATA_BYTES) return null;
|
|
1248
2308
|
try {
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
mode: FILE_MODE,
|
|
1253
|
-
flag: "wx"
|
|
1254
|
-
});
|
|
1255
|
-
return owner;
|
|
1256
|
-
} catch (error) {
|
|
1257
|
-
rmSync2(lockDir, { recursive: true, force: true });
|
|
1258
|
-
throw error;
|
|
2309
|
+
return JSON.parse(raw);
|
|
2310
|
+
} catch {
|
|
2311
|
+
return null;
|
|
1259
2312
|
}
|
|
1260
2313
|
}
|
|
1261
|
-
function
|
|
1262
|
-
const
|
|
1263
|
-
if (
|
|
1264
|
-
|
|
1265
|
-
if (!sameOwner(readOwner(lockDir), owner)) return false;
|
|
1266
|
-
rmSync2(lockDir, { recursive: true, force: true });
|
|
1267
|
-
return true;
|
|
1268
|
-
}
|
|
2314
|
+
function readCredentialFamily(path) {
|
|
2315
|
+
const parsed = readBoundedCredentialJson(path);
|
|
2316
|
+
if (parsed === void 0) return void 0;
|
|
2317
|
+
if (parsed === null) return { state: "invalid" };
|
|
1269
2318
|
try {
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
2319
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && parsed.family === "legacy_broker") {
|
|
2320
|
+
return { state: "legacy_broker", metadata: parseLegacyBrokerCredentialMetadata(parsed) };
|
|
2321
|
+
}
|
|
2322
|
+
return {
|
|
2323
|
+
state: "workos_connect",
|
|
2324
|
+
metadata: parseWorkosConnectCredentialMetadata(parsed)
|
|
2325
|
+
};
|
|
1276
2326
|
} catch {
|
|
1277
|
-
return
|
|
2327
|
+
return { state: "invalid" };
|
|
1278
2328
|
}
|
|
1279
2329
|
}
|
|
1280
|
-
function
|
|
1281
|
-
if (
|
|
1282
|
-
const
|
|
1283
|
-
|
|
1284
|
-
return
|
|
1285
|
-
}
|
|
1286
|
-
function throwIfAborted(signal) {
|
|
1287
|
-
if (signal?.aborted) throw abortError(signal);
|
|
1288
|
-
}
|
|
1289
|
-
async function defaultSleep2(ms, signal) {
|
|
1290
|
-
if (!signal) {
|
|
1291
|
-
await new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1292
|
-
return;
|
|
1293
|
-
}
|
|
1294
|
-
throwIfAborted(signal);
|
|
1295
|
-
await new Promise((resolve2, reject) => {
|
|
1296
|
-
const timer = setTimeout(() => {
|
|
1297
|
-
signal.removeEventListener("abort", onAbort);
|
|
1298
|
-
resolve2();
|
|
1299
|
-
}, ms);
|
|
1300
|
-
const onAbort = () => {
|
|
1301
|
-
clearTimeout(timer);
|
|
1302
|
-
reject(abortError(signal));
|
|
1303
|
-
};
|
|
1304
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
1305
|
-
});
|
|
2330
|
+
function isCredentialMigrationSentinel(value) {
|
|
2331
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2332
|
+
const record = value;
|
|
2333
|
+
const keys = Object.keys(record).sort();
|
|
2334
|
+
return keys.length === 2 && keys[0] === "state" && keys[1] === "version" && record.version === CREDENTIAL_MIGRATION_VERSION && record.state === CREDENTIAL_MIGRATION_STATE;
|
|
1306
2335
|
}
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
2336
|
+
function readCredentialMigrationState(path = CREDENTIAL_MIGRATION_PATH) {
|
|
2337
|
+
const parsed = readBoundedCredentialJson(path);
|
|
2338
|
+
if (parsed === void 0) return "absent";
|
|
2339
|
+
return parsed !== null && isCredentialMigrationSentinel(parsed) ? "valid" : "invalid";
|
|
1310
2340
|
}
|
|
1311
|
-
function
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
const
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
while (!owner) {
|
|
1318
|
-
const now = nowMs();
|
|
1319
|
-
owner = tryTakeLock(lockDir, now);
|
|
1320
|
-
if (owner) break;
|
|
1321
|
-
recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
|
|
1322
|
-
if (now >= deadline) {
|
|
1323
|
-
throw new Error(`timed out waiting for file lock ${lockDir}`);
|
|
1324
|
-
}
|
|
1325
|
-
(options.sleep ?? defaultSleepSync)(options.pollMs ?? DEFAULT_POLL_MS);
|
|
2341
|
+
function readStoredCredentialMetadata(metadataPath = CREDENTIAL_METADATA_PATH, familyPath = CREDENTIAL_FAMILY_PATH, migrationPath = CREDENTIAL_MIGRATION_PATH) {
|
|
2342
|
+
const family = readCredentialFamily(familyPath);
|
|
2343
|
+
if (family) return family;
|
|
2344
|
+
const parsed = readBoundedCredentialJson(metadataPath);
|
|
2345
|
+
if (parsed === void 0) {
|
|
2346
|
+
return readCredentialMigrationState(migrationPath) === "absent" ? { state: "legacy_broker" } : { state: "invalid" };
|
|
1326
2347
|
}
|
|
2348
|
+
if (parsed === null) return { state: "invalid" };
|
|
1327
2349
|
try {
|
|
1328
|
-
return
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
2350
|
+
return {
|
|
2351
|
+
state: "workos_connect",
|
|
2352
|
+
metadata: parseWorkosConnectCredentialMetadata(parsed)
|
|
2353
|
+
};
|
|
2354
|
+
} catch {
|
|
2355
|
+
return { state: "invalid" };
|
|
1333
2356
|
}
|
|
1334
2357
|
}
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
const alive = options.processAlive ?? processIsAlive;
|
|
1339
|
-
const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
1340
|
-
let owner = null;
|
|
1341
|
-
while (!owner) {
|
|
1342
|
-
throwIfAborted(options.signal);
|
|
1343
|
-
const now = nowMs();
|
|
1344
|
-
owner = tryTakeLock(lockDir, now);
|
|
1345
|
-
if (owner) break;
|
|
1346
|
-
recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
|
|
1347
|
-
if (now >= deadline) {
|
|
1348
|
-
throw new Error(`timed out waiting for file lock ${lockDir}`);
|
|
1349
|
-
}
|
|
1350
|
-
if (options.sleep) {
|
|
1351
|
-
await options.sleep(options.pollMs ?? DEFAULT_POLL_MS);
|
|
1352
|
-
throwIfAborted(options.signal);
|
|
1353
|
-
} else {
|
|
1354
|
-
await defaultSleep2(options.pollMs ?? DEFAULT_POLL_MS, options.signal);
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
2358
|
+
function decodeJwtPayload(token) {
|
|
2359
|
+
const parts = token.split(".");
|
|
2360
|
+
if (parts.length !== 3) return void 0;
|
|
1357
2361
|
try {
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
}
|
|
2362
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
2363
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return void 0;
|
|
2364
|
+
return payload;
|
|
2365
|
+
} catch {
|
|
2366
|
+
return void 0;
|
|
1364
2367
|
}
|
|
1365
2368
|
}
|
|
2369
|
+
function jwtExpiresAt(token) {
|
|
2370
|
+
const exp = decodeJwtPayload(token)?.exp;
|
|
2371
|
+
return typeof exp === "number" && Number.isFinite(exp) ? exp * 1e3 : void 0;
|
|
2372
|
+
}
|
|
2373
|
+
function jwtOrganizationId(token) {
|
|
2374
|
+
const orgId = decodeJwtPayload(token)?.org_id;
|
|
2375
|
+
return typeof orgId === "string" && orgId.length > 0 ? orgId : void 0;
|
|
2376
|
+
}
|
|
1366
2377
|
|
|
1367
2378
|
export {
|
|
1368
|
-
|
|
2379
|
+
syncDirectory,
|
|
2380
|
+
syncFile,
|
|
2381
|
+
ensureDurableDirectory,
|
|
2382
|
+
atomicWriteFile,
|
|
2383
|
+
processIsAlive,
|
|
2384
|
+
withFileLockSync,
|
|
2385
|
+
withFileLock,
|
|
2386
|
+
compareSemver,
|
|
2387
|
+
STABLE_HOOK_LAUNCHER_NAME,
|
|
2388
|
+
binFile,
|
|
2389
|
+
packageVersion,
|
|
2390
|
+
packageRoot,
|
|
2391
|
+
shellQuote,
|
|
2392
|
+
pinnedNpxArgs,
|
|
2393
|
+
pinnedNpxCommand,
|
|
2394
|
+
pinnedHookCommand,
|
|
2395
|
+
PRIM_CONFIG_SHELL_RESOLVER,
|
|
2396
|
+
stableHookCommand,
|
|
2397
|
+
detachedHookShimCommand,
|
|
2398
|
+
commandMatchesBin,
|
|
2399
|
+
hookCommandResolution,
|
|
2400
|
+
hookCommandResolutions,
|
|
1369
2401
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES,
|
|
1370
2402
|
WorkosConnectProtocolError,
|
|
1371
2403
|
readBoundedJson,
|
|
@@ -1374,6 +2406,22 @@ export {
|
|
|
1374
2406
|
requestWorkosDeviceAuthorization,
|
|
1375
2407
|
parseWorkosConnectTokens,
|
|
1376
2408
|
pollWorkosDeviceAuthorization,
|
|
2409
|
+
MachineAuthError,
|
|
2410
|
+
machineApiUrl,
|
|
2411
|
+
parseMachineIdentity,
|
|
2412
|
+
verifyMachineIdentity,
|
|
2413
|
+
primConfigDirectory,
|
|
2414
|
+
readMachineProfile,
|
|
2415
|
+
environmentCredentials,
|
|
2416
|
+
hasMachineConfiguration,
|
|
2417
|
+
machineContext,
|
|
2418
|
+
cachedMachineCredential,
|
|
2419
|
+
machineSessionEnded,
|
|
2420
|
+
configureMachine,
|
|
2421
|
+
acquireMachineCredential,
|
|
2422
|
+
clearMachineCredentials,
|
|
2423
|
+
machineCaptureActor,
|
|
2424
|
+
machineJournalBucket,
|
|
1377
2425
|
TOKEN_FILE_PATH,
|
|
1378
2426
|
REFRESH_TOKEN_PATH,
|
|
1379
2427
|
TOKEN_EXPIRES_PATH,
|
|
@@ -1414,27 +2462,5 @@ export {
|
|
|
1414
2462
|
setRepositoryBindingState,
|
|
1415
2463
|
repositoryBindingState,
|
|
1416
2464
|
isRepoActiveForCapture,
|
|
1417
|
-
decisionIngestionStatus
|
|
1418
|
-
syncDirectory,
|
|
1419
|
-
syncFile,
|
|
1420
|
-
ensureDurableDirectory,
|
|
1421
|
-
atomicWriteFile,
|
|
1422
|
-
processIsAlive,
|
|
1423
|
-
withFileLockSync,
|
|
1424
|
-
withFileLock,
|
|
1425
|
-
compareSemver,
|
|
1426
|
-
STABLE_HOOK_LAUNCHER_NAME,
|
|
1427
|
-
binFile,
|
|
1428
|
-
packageVersion,
|
|
1429
|
-
packageRoot,
|
|
1430
|
-
shellQuote,
|
|
1431
|
-
pinnedNpxArgs,
|
|
1432
|
-
pinnedNpxCommand,
|
|
1433
|
-
pinnedHookCommand,
|
|
1434
|
-
PRIM_CONFIG_SHELL_RESOLVER,
|
|
1435
|
-
stableHookCommand,
|
|
1436
|
-
detachedHookShimCommand,
|
|
1437
|
-
commandMatchesBin,
|
|
1438
|
-
hookCommandResolution,
|
|
1439
|
-
hookCommandResolutions
|
|
2465
|
+
decisionIngestionStatus
|
|
1440
2466
|
};
|