@indigoai-us/hq-cli 5.345.215-beta.0 → 5.345.217
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/CHANGELOG.md +206 -1
- package/README.md +45 -0
- package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
- package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
- package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
- package/dist/command-catalog.generated.d.ts +105 -10
- package/dist/command-catalog.generated.js +127 -10
- package/dist/command-help.js +3 -1
- package/dist/command-registration-plan.d.ts +6 -0
- package/dist/command-registration-plan.js +1 -0
- package/dist/commands/auth.d.ts +1 -1
- package/dist/commands/auth.js +11 -52
- package/dist/commands/bot.js +75 -10
- package/dist/commands/capacity.d.ts +4 -1
- package/dist/commands/capacity.js +46 -10
- package/dist/commands/cloud-demote.d.ts +19 -4
- package/dist/commands/cloud-demote.js +85 -12
- package/dist/commands/cloud-provision.d.ts +5 -1
- package/dist/commands/cloud-provision.js +6 -2
- package/dist/commands/cloud.d.ts +36 -0
- package/dist/commands/cloud.js +110 -27
- package/dist/commands/core-delegate-w1b.js +15 -1
- package/dist/commands/core-policy.js +67 -8
- package/dist/commands/core.js +1 -0
- package/dist/commands/daemon.js +9 -1
- package/dist/commands/dm.js +7 -0
- package/dist/commands/doctor-usage.d.ts +8 -0
- package/dist/commands/doctor-usage.js +20 -0
- package/dist/commands/doctor.js +7 -1
- package/dist/commands/env.d.ts +18 -0
- package/dist/commands/env.js +82 -0
- package/dist/commands/files-browse.d.ts +11 -4
- package/dist/commands/files-browse.js +21 -4
- package/dist/commands/files.d.ts +1 -1
- package/dist/commands/files.js +25 -11
- package/dist/commands/install-global.js +2 -2
- package/dist/commands/integrations-auth-rules.d.ts +27 -0
- package/dist/commands/integrations-auth-rules.js +79 -0
- package/dist/commands/integrations-import.js +124 -12
- package/dist/commands/lanes.js +102 -26
- package/dist/commands/logout.d.ts +7 -0
- package/dist/commands/logout.js +41 -34
- package/dist/commands/mesh.d.ts +2 -0
- package/dist/commands/mesh.js +60 -35
- package/dist/commands/sources.d.ts +8 -2
- package/dist/commands/sources.js +65 -9
- package/dist/commands/sync-held.js +5 -2
- package/dist/commands/whoami.js +26 -1
- package/dist/data/command-states.json +15 -0
- package/dist/index.js +52 -4
- package/dist/lazy-commands.js +5 -6
- package/dist/lib/anywhere-person-setting.d.ts +2 -0
- package/dist/lib/anywhere-person-setting.js +6 -3
- package/dist/lib/billing/usage-card.d.ts +25 -4
- package/dist/lib/billing/usage-card.js +76 -9
- package/dist/lib/billing/usage-cost.d.ts +3 -3
- package/dist/lib/billing/usage-cost.js +35 -13
- package/dist/lib/billing/usage-only.js +4 -2
- package/dist/lib/billing/usage-rate-card.d.ts +2 -2
- package/dist/lib/billing/usage-rate-card.js +3 -0
- package/dist/lib/bot/fleet-cron.d.ts +8 -0
- package/dist/lib/bot/fleet-cron.js +126 -7
- package/dist/lib/bot/fleet-daemon.d.ts +46 -0
- package/dist/lib/bot/fleet-daemon.js +99 -1
- package/dist/lib/bot/inflight.d.ts +9 -0
- package/dist/lib/bot/inflight.js +10 -0
- package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
- package/dist/lib/bot/probe.js +7 -1
- package/dist/lib/bot/run.js +20 -1
- package/dist/lib/bot/runtime/codex.js +1 -1
- package/dist/lib/bot/runtime/grok-acp.d.ts +6 -1
- package/dist/lib/bot/runtime/grok-acp.js +32 -14
- package/dist/lib/bot/runtime/grok.js +1 -1
- package/dist/lib/bot/runtime/index.js +19 -9
- package/dist/lib/bot/runtime/messages-stream.js +2 -2
- package/dist/lib/bot/runtime/types.d.ts +15 -0
- package/dist/lib/bot/runtime/types.js +9 -0
- package/dist/lib/bot/runtime-failure.d.ts +23 -0
- package/dist/lib/bot/runtime-failure.js +43 -1
- package/dist/lib/capacity/accounts.d.ts +8 -0
- package/dist/lib/capacity/accounts.js +19 -0
- package/dist/lib/capacity/available.d.ts +154 -0
- package/dist/lib/capacity/available.js +905 -0
- package/dist/lib/capacity/codex-availability.d.ts +14 -1
- package/dist/lib/capacity/codex-availability.js +26 -1
- package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
- package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
- package/dist/lib/capacity/collectors/codex.js +10 -7
- package/dist/lib/capacity/ledger.d.ts +37 -1
- package/dist/lib/capacity/ledger.js +207 -30
- package/dist/lib/capacity/project.d.ts +26 -0
- package/dist/lib/capacity/project.js +137 -8
- package/dist/lib/capacity/refusal-rows.d.ts +31 -0
- package/dist/lib/capacity/refusal-rows.js +61 -0
- package/dist/lib/capacity/refusal.d.ts +53 -2
- package/dist/lib/capacity/refusal.js +284 -65
- package/dist/lib/capacity/route.js +46 -11
- package/dist/lib/capacity/widget.d.ts +12 -1
- package/dist/lib/capacity/widget.js +91 -3
- package/dist/lib/daemon/flag-monitor.d.ts +8 -0
- package/dist/lib/daemon/flag-monitor.js +17 -6
- package/dist/lib/daemon/flag.d.ts +65 -1
- package/dist/lib/daemon/flag.js +190 -40
- package/dist/lib/daemon/ops/policy.js +62 -5
- package/dist/lib/daemon/paths.d.ts +72 -2
- package/dist/lib/daemon/paths.js +154 -3
- package/dist/lib/daemon/resolver.d.ts +2 -0
- package/dist/lib/daemon/resolver.js +3 -0
- package/dist/lib/daemon/run.d.ts +9 -0
- package/dist/lib/daemon/run.js +79 -21
- package/dist/lib/daemon/selfcheck.d.ts +22 -0
- package/dist/lib/daemon/selfcheck.js +40 -1
- package/dist/lib/daemon/server.d.ts +5 -1
- package/dist/lib/daemon/server.js +17 -23
- package/dist/lib/daemon/state-file-switch.d.ts +57 -0
- package/dist/lib/daemon/state-file-switch.js +88 -0
- package/dist/lib/daemon/state-file.d.ts +198 -0
- package/dist/lib/daemon/state-file.js +419 -0
- package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
- package/dist/lib/daemon/tcc-eperm.js +310 -0
- package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
- package/dist/lib/daemon/timed-flag-monitors.js +75 -0
- package/dist/lib/delivery/admission.d.ts +86 -0
- package/dist/lib/delivery/admission.js +148 -0
- package/dist/lib/delivery/artifacts.d.ts +7 -1
- package/dist/lib/delivery/artifacts.js +29 -10
- package/dist/lib/delivery/attempt-id.d.ts +13 -0
- package/dist/lib/delivery/attempt-id.js +16 -0
- package/dist/lib/delivery/disposable-target.d.ts +42 -0
- package/dist/lib/delivery/disposable-target.js +111 -0
- package/dist/lib/delivery/effects.d.ts +136 -0
- package/dist/lib/delivery/effects.js +541 -0
- package/dist/lib/delivery/enrollment.d.ts +21 -17
- package/dist/lib/delivery/enrollment.js +83 -5
- package/dist/lib/delivery/escalations.d.ts +51 -0
- package/dist/lib/delivery/escalations.js +60 -0
- package/dist/lib/delivery/lease.d.ts +80 -0
- package/dist/lib/delivery/lease.js +134 -0
- package/dist/lib/delivery/migrations.d.ts +120 -4
- package/dist/lib/delivery/migrations.js +215 -15
- package/dist/lib/delivery/mqtt.d.ts +2 -0
- package/dist/lib/delivery/mqtt.js +7 -0
- package/dist/lib/delivery/reconciler.d.ts +65 -1
- package/dist/lib/delivery/reconciler.js +224 -13
- package/dist/lib/delivery/rpc/client.d.ts +22 -0
- package/dist/lib/delivery/rpc/client.js +159 -0
- package/dist/lib/delivery/rpc/port.d.ts +40 -0
- package/dist/lib/delivery/rpc/port.js +16 -0
- package/dist/lib/delivery/rpc/server.d.ts +30 -0
- package/dist/lib/delivery/rpc/server.js +205 -0
- package/dist/lib/delivery/rpc/wire.d.ts +85 -0
- package/dist/lib/delivery/rpc/wire.js +143 -0
- package/dist/lib/delivery/store.d.ts +2 -0
- package/dist/lib/delivery/store.js +4 -0
- package/dist/lib/delivery/windows-service-install.d.ts +262 -0
- package/dist/lib/delivery/windows-service-install.js +892 -0
- package/dist/lib/delivery/workers/macos.d.ts +16 -1
- package/dist/lib/delivery/workers/macos.js +54 -12
- package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
- package/dist/lib/delivery/workers/windows-service-live.js +711 -0
- package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
- package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
- package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
- package/dist/lib/delivery/workers/windows-service.js +584 -0
- package/dist/lib/delivery/workers/windows.d.ts +32 -22
- package/dist/lib/delivery/workers/windows.js +50 -64
- package/dist/lib/doctor/checks/host-core.d.ts +50 -0
- package/dist/lib/doctor/checks/host-core.js +269 -0
- package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
- package/dist/lib/doctor/checks/replay-recorder.js +261 -0
- package/dist/lib/doctor/registry.js +4 -0
- package/dist/lib/environment/profile.d.ts +239 -0
- package/dist/lib/environment/profile.js +251 -0
- package/dist/lib/hook-engine/reconcile.js +39 -13
- package/dist/lib/hook-engine/registration.d.ts +9 -0
- package/dist/lib/hook-engine/registration.js +19 -0
- package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
- package/dist/lib/hot-channels/adapters/meetings.js +36 -3
- package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
- package/dist/lib/hot-channels/adapters/slack.js +64 -21
- package/dist/lib/hot-channels/alert.d.ts +2 -0
- package/dist/lib/hot-channels/alert.js +8 -1
- package/dist/lib/hot-channels/contract.d.ts +12 -0
- package/dist/lib/hot-channels/contract.js +7 -0
- package/dist/lib/hot-channels/loop.js +1 -0
- package/dist/lib/hot-channels/run.d.ts +6 -0
- package/dist/lib/hot-channels/run.js +4 -0
- package/dist/lib/hot-channels/signals-pass.d.ts +74 -1
- package/dist/lib/hot-channels/signals-pass.js +82 -41
- package/dist/lib/hot-channels/signals-redo.js +10 -2
- package/dist/lib/install/claude-targets.d.ts +12 -1
- package/dist/lib/install/claude-targets.js +57 -5
- package/dist/lib/install/codex-targets.d.ts +2 -2
- package/dist/lib/install/codex-targets.js +36 -6
- package/dist/lib/install/hook-target.d.ts +3 -0
- package/dist/lib/install/hook-target.js +11 -0
- package/dist/lib/lanes/canonical-host.d.ts +35 -0
- package/dist/lib/lanes/canonical-host.js +65 -0
- package/dist/lib/lanes/host-capacity.d.ts +30 -0
- package/dist/lib/lanes/host-capacity.js +29 -3
- package/dist/lib/lanes/watcher.js +35 -0
- package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
- package/dist/lib/mesh/live/daemon/run.js +5 -2
- package/dist/lib/mesh/live/flush.d.ts +5 -1
- package/dist/lib/mesh/live/flush.js +12 -6
- package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
- package/dist/lib/mesh/live/reporting-privacy.js +56 -1
- package/dist/lib/mesh/live/spool.d.ts +7 -0
- package/dist/lib/mesh/live/spool.js +25 -0
- package/dist/lib/person-setting-cache.d.ts +38 -0
- package/dist/lib/person-setting-cache.js +98 -0
- package/dist/lib/safe-store.d.ts +245 -0
- package/dist/lib/safe-store.js +777 -0
- package/dist/lib/signals/engine.d.ts +29 -2
- package/dist/lib/signals/engine.js +103 -4
- package/dist/lib/signals/reply.js +73 -18
- package/dist/lib/signals/steps/adapters.js +7 -2
- package/dist/lib/signals/steps/extract.d.ts +13 -0
- package/dist/lib/signals/steps/extract.js +122 -6
- package/dist/main.js +46 -3
- package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
- package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
- package/dist/utils/auth-expiry.d.ts +8 -0
- package/dist/utils/auth-expiry.js +53 -0
- package/dist/utils/catalog-runtime-paths.d.ts +34 -0
- package/dist/utils/catalog-runtime-paths.js +53 -0
- package/dist/utils/cli-telemetry.d.ts +21 -0
- package/dist/utils/cli-telemetry.js +34 -0
- package/dist/utils/command-usage.d.ts +275 -0
- package/dist/utils/command-usage.js +797 -0
- package/dist/utils/files-browse-acl.js +1 -1
- package/dist/utils/hook-trust.d.ts +7 -0
- package/dist/utils/hook-trust.js +31 -4
- package/dist/utils/host-registration.d.ts +126 -0
- package/dist/utils/host-registration.js +378 -0
- package/dist/utils/resident-package-preload.js +2 -0
- package/package.json +10 -8
- package/scripts/bench-core.mjs +1096 -0
- package/scripts/check-function-manifest.mjs +702 -0
- package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
- package/dist/lib/delivery/workers/windows-boundary.js +0 -693
package/dist/lib/daemon/flag.js
CHANGED
|
@@ -2,40 +2,56 @@
|
|
|
2
2
|
* Feature flags read by the daemon. The daemon runs for weeks, so each read
|
|
3
3
|
* asks the registry again instead of holding a per-process answer, and it
|
|
4
4
|
* reads as each flag's fallback unless the registry or a local override decides it.
|
|
5
|
+
*
|
|
6
|
+
* The daemon's timed monitors pass one shared DaemonFlagSnapshotSource, so the
|
|
7
|
+
* flags they watch are decided from one registry request per refresh interval
|
|
8
|
+
* instead of one request per flag.
|
|
5
9
|
*/
|
|
10
|
+
import { performance } from "node:perf_hooks";
|
|
6
11
|
import { createFlagClient, readLocalOverride, } from "@indigoai-us/hq-flags-client";
|
|
7
12
|
import { ensureCognitoIdToken } from "../../utils/cognito-session.js";
|
|
8
13
|
import { resolveFlagRegistryEndpoint } from "../flag-registry-endpoint.js";
|
|
9
14
|
import { resolveProcessFlagCompanyContext } from "../flag-registry.js";
|
|
10
15
|
import { HQ_ANYWHERE_RUNTIME_FLAG, hqAnywhereRuntimeLocallyDisabled } from "../anywhere-runtime-flag-key.js";
|
|
16
|
+
import { DAEMON_FLAG_REFRESH_INTERVAL_MS } from "./flag-monitor.js";
|
|
11
17
|
/** Outposts hand running services to the next daemon on a CLI update instead of restarting them all. */
|
|
12
18
|
export const SUPERVISOR_HANDOFF_FLAG = "daemon.supervisor-handoff";
|
|
13
19
|
/** Self-updates build the new CLI beside the running one and swap it in, so `hq` never disappears mid-update. */
|
|
14
20
|
export const STAGED_SELF_UPDATE_FLAG = "cli.staged-self-update";
|
|
15
21
|
const READ_TIMEOUT_MS = 5_000;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
22
|
+
/**
|
|
23
|
+
* How long a loaded registry snapshot may answer further daemon flag reads
|
|
24
|
+
* that arrive between refresh ticks: the monitors' first reads at daemon
|
|
25
|
+
* start, a restarted hqd server's first read, and a request-driven refresh.
|
|
26
|
+
* It is the most a shared read can add to the time a flag change takes to
|
|
27
|
+
* reach one of those reads. A refresh tick never uses it: each tick discards
|
|
28
|
+
* the held snapshot and any request already in flight, so the tick's reads are
|
|
29
|
+
* decided from a request sent on that tick, as they were before sharing.
|
|
30
|
+
*
|
|
31
|
+
* One case differs from a monitor on its own timer: a monitor whose first
|
|
32
|
+
* read is still pending when the shared tick arrives skips that tick (its
|
|
33
|
+
* refresh joins its own pending read), so its next refresh is up to one
|
|
34
|
+
* pending read later than 30 seconds after its first. That applies to the hqd
|
|
35
|
+
* runtime gate just after the server starts, not to the kill switches.
|
|
36
|
+
*/
|
|
37
|
+
export const DAEMON_FLAG_SNAPSHOT_TTL_MS = 5_000;
|
|
38
|
+
function closeQuietly(client) {
|
|
39
|
+
try {
|
|
40
|
+
client?.close();
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// closing a one-shot client cannot change the answer
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function loadDaemonFlagRegistry(env, options) {
|
|
47
|
+
const errors = [];
|
|
32
48
|
let client;
|
|
33
49
|
try {
|
|
34
50
|
const company = resolveProcessFlagCompanyContext(env);
|
|
35
51
|
// Signed out reads as the flag fallback without reaching the registry.
|
|
36
52
|
const token = await (options.getToken ?? (() => ensureCognitoIdToken({ interactive: false })))();
|
|
37
53
|
if (typeof token !== "string" || token.trim() === "")
|
|
38
|
-
return
|
|
54
|
+
return { signedOut: true, errors };
|
|
39
55
|
client = (options.createClient ?? createFlagClient)({
|
|
40
56
|
endpoint: resolveFlagRegistryEndpoint(undefined, env),
|
|
41
57
|
getToken: () => token,
|
|
@@ -44,43 +60,177 @@ export async function readDaemonFlag(flagKey, options = {}) {
|
|
|
44
60
|
requestTimeoutMs: READ_TIMEOUT_MS,
|
|
45
61
|
...(company.companyUid ? { companyUid: company.companyUid } : {}),
|
|
46
62
|
...(company.companySlug ? { companyIdentifiers: [company.companySlug] } : {}),
|
|
47
|
-
onError,
|
|
63
|
+
onError: (error) => { errors.push(error); },
|
|
48
64
|
});
|
|
49
65
|
try {
|
|
50
66
|
await client.ready();
|
|
51
67
|
}
|
|
52
68
|
catch (error) {
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
const resolution = client.explain(flagKey, { fallback });
|
|
56
|
-
if (failed) {
|
|
57
|
-
if (options.throwOnError && !fallback) {
|
|
58
|
-
throw new Error("hq-flags registry read failed", { cause: reportedError });
|
|
59
|
-
}
|
|
60
|
-
return fallback;
|
|
69
|
+
errors.push(error);
|
|
61
70
|
}
|
|
62
|
-
if (resolution.source === "snapshot")
|
|
63
|
-
return resolution.value === true;
|
|
64
|
-
return fallback && resolution.value === true;
|
|
65
71
|
}
|
|
66
72
|
catch (error) {
|
|
67
|
-
if (
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
73
|
+
if (errors.length === 0)
|
|
74
|
+
errors.push(error);
|
|
75
|
+
}
|
|
76
|
+
return { signedOut: false, errors, ...(client ? { client } : {}) };
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Share registry requests between the daemon's timed flag reads.
|
|
80
|
+
*
|
|
81
|
+
* Reads that arrive while a request is in flight join it, and a loaded
|
|
82
|
+
* snapshot answers further reads for `ttlMs`. A failed or signed-out request
|
|
83
|
+
* is handed to the reads that joined it and is never kept, so the next read
|
|
84
|
+
* asks again and each flag keeps its own failure behavior.
|
|
85
|
+
*/
|
|
86
|
+
export function createDaemonFlagSnapshotSource(options = {}) {
|
|
87
|
+
const ttlMs = options.ttlMs ?? DAEMON_FLAG_SNAPSHOT_TTL_MS;
|
|
88
|
+
const intervalMs = options.intervalMs ?? DAEMON_FLAG_REFRESH_INTERVAL_MS;
|
|
89
|
+
const now = options.now ?? (() => performance.now());
|
|
90
|
+
let held;
|
|
91
|
+
let inFlight;
|
|
92
|
+
let closed = false;
|
|
93
|
+
const ticks = new Set();
|
|
94
|
+
let timer;
|
|
95
|
+
const drop = () => {
|
|
96
|
+
closeQuietly(held?.read.client);
|
|
97
|
+
held = undefined;
|
|
98
|
+
};
|
|
99
|
+
/** A request this source will not keep: the reads waiting on it decide in this turn, then it is closed. */
|
|
100
|
+
const unkept = (read) => {
|
|
101
|
+
const client = read.client;
|
|
102
|
+
if (client)
|
|
103
|
+
setImmediate(() => closeQuietly(client));
|
|
104
|
+
return read;
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
schedule(tick) {
|
|
108
|
+
// A distinct wrapper per call, so cancelling one registration never removes another.
|
|
109
|
+
const entry = () => tick();
|
|
110
|
+
ticks.add(entry);
|
|
111
|
+
if (!timer && !closed) {
|
|
112
|
+
timer = setInterval(() => {
|
|
113
|
+
// A tick is decided from a request sent on this tick, never from an earlier one.
|
|
114
|
+
drop();
|
|
115
|
+
inFlight = undefined;
|
|
116
|
+
for (const run of [...ticks]) {
|
|
117
|
+
try {
|
|
118
|
+
run();
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
// one monitor's refresh cannot stop the others
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}, intervalMs);
|
|
125
|
+
timer.unref?.();
|
|
126
|
+
}
|
|
127
|
+
return () => {
|
|
128
|
+
ticks.delete(entry);
|
|
129
|
+
if (ticks.size === 0 && timer) {
|
|
130
|
+
clearInterval(timer);
|
|
131
|
+
timer = undefined;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
load(env, readOptions) {
|
|
136
|
+
if (closed)
|
|
137
|
+
return loadDaemonFlagRegistry(env, readOptions).then(unkept);
|
|
138
|
+
let key;
|
|
139
|
+
try {
|
|
140
|
+
const company = resolveProcessFlagCompanyContext(env);
|
|
141
|
+
key = JSON.stringify([
|
|
142
|
+
resolveFlagRegistryEndpoint(undefined, env),
|
|
143
|
+
company.companyUid ?? null,
|
|
144
|
+
company.companySlug ?? null,
|
|
145
|
+
]);
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// The unshared read reports this failure the way it always has.
|
|
149
|
+
return loadDaemonFlagRegistry(env, readOptions).then(unkept);
|
|
150
|
+
}
|
|
151
|
+
if (held && held.key === key && now() - held.at < ttlMs)
|
|
152
|
+
return Promise.resolve(held.read);
|
|
153
|
+
if (inFlight && inFlight.key === key)
|
|
154
|
+
return inFlight.promise;
|
|
155
|
+
// Age counts from when the request was sent, so the bound covers the request time too.
|
|
156
|
+
const startedAt = now();
|
|
157
|
+
const promise = loadDaemonFlagRegistry(env, readOptions).then((read) => {
|
|
158
|
+
try {
|
|
159
|
+
options.onRead?.(read, env);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
// an observer cannot change the answer
|
|
163
|
+
}
|
|
164
|
+
const reusable = !closed && !read.signedOut && read.errors.length === 0 && read.client !== undefined;
|
|
165
|
+
// A request overtaken by a newer one (a tick started the newer one) is used once and not kept.
|
|
166
|
+
if (!reusable || (held && held.at > startedAt))
|
|
167
|
+
return unkept(read);
|
|
168
|
+
drop();
|
|
169
|
+
held = { key, at: startedAt, read };
|
|
170
|
+
return read;
|
|
171
|
+
}).finally(() => {
|
|
172
|
+
if (inFlight?.promise === promise)
|
|
173
|
+
inFlight = undefined;
|
|
174
|
+
});
|
|
175
|
+
inFlight = { key, promise };
|
|
176
|
+
return promise;
|
|
177
|
+
},
|
|
178
|
+
close() {
|
|
179
|
+
closed = true;
|
|
180
|
+
ticks.clear();
|
|
181
|
+
if (timer)
|
|
182
|
+
clearInterval(timer);
|
|
183
|
+
timer = undefined;
|
|
184
|
+
drop();
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
export async function readDaemonFlag(flagKey, options = {}) {
|
|
189
|
+
const env = options.env ?? process.env;
|
|
190
|
+
if (flagKey === HQ_ANYWHERE_RUNTIME_FLAG && hqAnywhereRuntimeLocallyDisabled(env))
|
|
191
|
+
return false;
|
|
192
|
+
const fallback = options.fallback ?? flagKey === HQ_ANYWHERE_RUNTIME_FLAG;
|
|
193
|
+
const override = readLocalOverride(flagKey, env);
|
|
194
|
+
const localOverrideMode = options.localOverrideMode ?? "respect";
|
|
195
|
+
if (override !== null && (localOverrideMode === "respect" || (localOverrideMode === "off-only" && !override)))
|
|
196
|
+
return override;
|
|
197
|
+
const shared = options.snapshots;
|
|
198
|
+
const read = await (shared ? shared.load(env, options) : loadDaemonFlagRegistry(env, options));
|
|
199
|
+
try {
|
|
200
|
+
let reportedError = read.errors[0];
|
|
201
|
+
let failed = read.errors.length > 0;
|
|
202
|
+
for (const error of read.errors) {
|
|
203
|
+
try {
|
|
204
|
+
options.onError?.(error);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
// an error reporter cannot change the answer
|
|
72
208
|
}
|
|
209
|
+
}
|
|
210
|
+
if (read.signedOut)
|
|
73
211
|
return fallback;
|
|
212
|
+
if (!failed) {
|
|
213
|
+
try {
|
|
214
|
+
const resolution = read.client.explain(flagKey, { fallback });
|
|
215
|
+
if (resolution.source === "snapshot")
|
|
216
|
+
return resolution.value === true;
|
|
217
|
+
return fallback && resolution.value === true;
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
failed = true;
|
|
221
|
+
reportedError = error;
|
|
222
|
+
options.onError?.(error);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (options.throwOnError && !fallback) {
|
|
226
|
+
throw new Error("hq-flags registry read failed", { cause: reportedError });
|
|
74
227
|
}
|
|
75
228
|
return fallback;
|
|
76
229
|
}
|
|
77
230
|
finally {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
catch {
|
|
82
|
-
// closing a one-shot client cannot change the answer
|
|
83
|
-
}
|
|
231
|
+
// A shared source owns its client and closes it when the snapshot is replaced.
|
|
232
|
+
if (!shared)
|
|
233
|
+
closeQuietly(read.client);
|
|
84
234
|
}
|
|
85
235
|
}
|
|
86
236
|
//# sourceMappingURL=flag.js.map
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import { spawn } from "node:child_process";
|
|
21
21
|
import * as fs from "node:fs";
|
|
22
22
|
import * as path from "node:path";
|
|
23
|
+
import { sessionMetaCompanies } from "../../core-utils/session-company.js";
|
|
23
24
|
export const SCOPE_AUTHORIZER = ".claude/hooks/mandatory-scope-authorizer.sh";
|
|
24
25
|
export const POLICY_TRIGGER = ".claude/hooks/inject-policy-on-trigger.sh";
|
|
25
26
|
const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
@@ -194,8 +195,17 @@ function runScript(script, payload, env, cwd, timeoutMs) {
|
|
|
194
195
|
* workspace/sessions/<sid>/meta.yaml (or scope-capability.json). hqd binds a
|
|
195
196
|
* session id of its own per company + caller, so a check never borrows the
|
|
196
197
|
* binding of an unrelated session.
|
|
198
|
+
*
|
|
199
|
+
* The synthetic session still has to carry the caller's lock set. hq-session.sh
|
|
200
|
+
* add company updates the real session's meta.yaml; policy.check used to stamp
|
|
201
|
+
* only company_slug A onto hqd-A-<id> and skip rewrites while that primary
|
|
202
|
+
* stayed put, so later reads of an added company B were blocked
|
|
203
|
+
* (feedback_a4a04ca0, feedback_cf07aef6). Copy the caller's company_slugs onto
|
|
204
|
+
* the synthetic session and remint the capability the authorizer actually
|
|
205
|
+
* reads. sessionMetaCompanies already ignores hqd-* ids, so this cannot borrow
|
|
206
|
+
* another check's bind.
|
|
197
207
|
*/
|
|
198
|
-
function bindCheckSession(hqRoot, company, callerSession, now) {
|
|
208
|
+
function bindCheckSession(hqRoot, company, callerSession, now, env) {
|
|
199
209
|
const caller = (callerSession ?? "default").replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80) || "default";
|
|
200
210
|
const scope = company ?? "personal";
|
|
201
211
|
const sid = `hqd-${scope}-${caller}`;
|
|
@@ -203,7 +213,18 @@ function bindCheckSession(hqRoot, company, callerSession, now) {
|
|
|
203
213
|
throw new PolicyOpError("bad_args", "sessionId has no usable characters");
|
|
204
214
|
const dir = path.join(hqRoot, "workspace", "sessions", sid);
|
|
205
215
|
const meta = path.join(dir, "meta.yaml");
|
|
206
|
-
const
|
|
216
|
+
const cap = path.join(dir, "scope-capability.json");
|
|
217
|
+
const callerLock = callerSession ? sessionMetaCompanies(hqRoot, callerSession, env) : [];
|
|
218
|
+
// The scope authorizer requires company_slugs[0] === company_slug, so the
|
|
219
|
+
// check company leads; this only reorders the caller's own lock set. A check
|
|
220
|
+
// company outside that lock is bound alone, never merged with the lock, so a
|
|
221
|
+
// caller cannot gain a company it did not lock.
|
|
222
|
+
const slugs = company
|
|
223
|
+
? callerLock.includes(company)
|
|
224
|
+
? [company, ...callerLock.filter((s) => s !== company)]
|
|
225
|
+
: [company]
|
|
226
|
+
: callerLock;
|
|
227
|
+
const slugLine = slugs.length > 1 ? `company_slugs: ${slugs.join(",")}\n` : "";
|
|
207
228
|
let current = "";
|
|
208
229
|
try {
|
|
209
230
|
current = fs.readFileSync(meta, "utf8");
|
|
@@ -212,14 +233,50 @@ function bindCheckSession(hqRoot, company, callerSession, now) {
|
|
|
212
233
|
if (err.code !== "ENOENT")
|
|
213
234
|
throw err;
|
|
214
235
|
}
|
|
215
|
-
|
|
236
|
+
const started = current.match(/^started_at:\s*(\S+)/m)?.[1] ?? now.toISOString();
|
|
237
|
+
const body = `session_id: ${sid}\nstarted_at: ${started}\nsenior: user\n${company ? `company_slug: ${company}\n` : ""}${slugLine}source: hqd\n`;
|
|
238
|
+
const primaryWrong = company
|
|
216
239
|
? !current.includes(`\ncompany_slug: ${company}\n`)
|
|
217
|
-
: !current.includes(`session_id: ${sid}\n`) || current.includes("\ncompany_slug:")
|
|
240
|
+
: !current.includes(`session_id: ${sid}\n`) || current.includes("\ncompany_slug:");
|
|
241
|
+
const slugsWrong = slugs.length > 1 ? !current.includes(`\ncompany_slugs: ${slugs.join(",")}\n`) : current.includes("\ncompany_slugs:");
|
|
242
|
+
if (primaryWrong || slugsWrong) {
|
|
218
243
|
fs.mkdirSync(dir, { recursive: true });
|
|
219
244
|
const tmp = `${meta}.${process.pid}.tmp`;
|
|
220
245
|
fs.writeFileSync(tmp, body);
|
|
221
246
|
fs.renameSync(tmp, meta);
|
|
222
247
|
}
|
|
248
|
+
if (company && slugs.length > 0) {
|
|
249
|
+
const desired = {
|
|
250
|
+
session_id: sid,
|
|
251
|
+
company_slug: company,
|
|
252
|
+
minted_at: now.toISOString(),
|
|
253
|
+
company_slugs: slugs,
|
|
254
|
+
};
|
|
255
|
+
let capCurrent = "";
|
|
256
|
+
try {
|
|
257
|
+
capCurrent = fs.readFileSync(cap, "utf8");
|
|
258
|
+
}
|
|
259
|
+
catch (err) {
|
|
260
|
+
if (err.code !== "ENOENT")
|
|
261
|
+
throw err;
|
|
262
|
+
}
|
|
263
|
+
let capSlugs;
|
|
264
|
+
try {
|
|
265
|
+
capSlugs = JSON.parse(capCurrent).company_slugs;
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
capSlugs = undefined;
|
|
269
|
+
}
|
|
270
|
+
if (JSON.stringify(capSlugs) !== JSON.stringify(slugs)) {
|
|
271
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
272
|
+
const tmp = `${cap}.${process.pid}.tmp`;
|
|
273
|
+
fs.writeFileSync(tmp, `${JSON.stringify(desired)}\n`);
|
|
274
|
+
fs.renameSync(tmp, cap);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
else if (fs.existsSync(cap)) {
|
|
278
|
+
fs.unlinkSync(cap);
|
|
279
|
+
}
|
|
223
280
|
return sid;
|
|
224
281
|
}
|
|
225
282
|
function extractContext(stdout) {
|
|
@@ -263,7 +320,7 @@ export async function policyCheck(args, deps) {
|
|
|
263
320
|
throw new PolicyOpError("policy_engine_unavailable", `scope authorizer not found at ${authorizer}`);
|
|
264
321
|
}
|
|
265
322
|
const event = args.event ?? "PreToolUse";
|
|
266
|
-
const session = bindCheckSession(hqRoot, args.company, args.sessionId, (deps.now ?? (() => new Date()))());
|
|
323
|
+
const session = bindCheckSession(hqRoot, args.company, args.sessionId, (deps.now ?? (() => new Date()))(), deps.env ?? process.env);
|
|
267
324
|
const payload = JSON.stringify({
|
|
268
325
|
session_id: session,
|
|
269
326
|
hook_event_name: event,
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* under ~/.hq/daemon and never under a synced HQ folder. Service logs can hold
|
|
4
4
|
* private output, so the folders are 0700 and the files 0600.
|
|
5
5
|
*/
|
|
6
|
+
import { type SafeStoreOperation, type SafeStorePoint, type SafeStoreRefusal, type SafeStoreRefusalCode } from "../safe-store.js";
|
|
6
7
|
export interface DaemonPaths {
|
|
7
8
|
root: string;
|
|
8
9
|
configPath: string;
|
|
@@ -21,8 +22,77 @@ export interface DaemonPaths {
|
|
|
21
22
|
unitProtocolPath: (unitId: string) => string;
|
|
22
23
|
}
|
|
23
24
|
export declare function daemonPaths(home?: string, env?: NodeJS.ProcessEnv): DaemonPaths;
|
|
24
|
-
/**
|
|
25
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Create `dir` (and any missing parents) readable only by its owner, and
|
|
27
|
+
* tighten it if it already exists. The folder is checked before any chmod: it
|
|
28
|
+
* must be a real folder (not a symlink or junction) owned by this user, or
|
|
29
|
+
* EACCES is thrown and nothing is changed. The tightening runs through a
|
|
30
|
+
* descriptor opened with O_DIRECTORY|O_NOFOLLOW (fchmod), so a folder swapped
|
|
31
|
+
* for a link after the check is not followed. Windows, which cannot open a
|
|
32
|
+
* folder, checks by lstat and tightens by path (modes are no-ops there).
|
|
33
|
+
*
|
|
34
|
+
* The check came with the daemon state file (#2624) and sits behind its
|
|
35
|
+
* switch (state-file-switch.ts, default on). With the switch off, a folder the
|
|
36
|
+
* check refuses is handled as before #2624: it is tightened by path with
|
|
37
|
+
* chmod (following a link), and a chmod failure (EPERM on a folder another
|
|
38
|
+
* user owns) is thrown. One exception, which is new and not pre-#2624
|
|
39
|
+
* behavior: for the daemon root itself (`daemonPaths().root`, ~/.hq/daemon or
|
|
40
|
+
* HQ_DAEMON_DIR) a chmod failure is reported on stderr and the folder is used
|
|
41
|
+
* as it is, so a symlinked or foreign-owned daemon root does not stop the
|
|
42
|
+
* daemon. Every other folder (requests, bundle stages, config, logs, ...)
|
|
43
|
+
* still throws. The switch is read only when the check refuses, so the usual
|
|
44
|
+
* call reads no flag.
|
|
45
|
+
*/
|
|
46
|
+
export declare function ensurePrivateDir(dir: string, options?: EnsurePrivateDirOptions): void;
|
|
47
|
+
export interface EnsurePrivateDirOptions {
|
|
48
|
+
/** The state file switch (tests). Default: daemonStateFileEnabled(). */
|
|
49
|
+
stateFileEnabled?: () => boolean;
|
|
50
|
+
/** Replaces fs.chmodSync in the switched-off fallback (tests). */
|
|
51
|
+
chmod?: (dir: string, mode: number) => void;
|
|
52
|
+
/** The daemon root (tests). Default: daemonPaths().root for this process. */
|
|
53
|
+
daemonRoot?: string;
|
|
54
|
+
}
|
|
55
|
+
/** Points and operations at which a test can act during a store write (see src/lib/safe-store.ts). */
|
|
56
|
+
export type StoreWriteHook = (point: SafeStorePoint, operation: SafeStoreOperation) => void;
|
|
57
|
+
export interface StoreFileWriteOptions {
|
|
58
|
+
/** Create the folder (0700) when missing and tighten it to 0700 through the held descriptor. */
|
|
59
|
+
create?: boolean;
|
|
60
|
+
/** Waits in milliseconds between rename attempts on EPERM, EACCES or EBUSY. Empty: no retry. */
|
|
61
|
+
renameRetryDelaysMs?: readonly number[];
|
|
62
|
+
/** Synchronous wait between rename attempts (tests). */
|
|
63
|
+
sleep?: (ms: number) => void;
|
|
64
|
+
/** Replaces fs.renameSync (tests). */
|
|
65
|
+
renameFile?: (from: string, to: string) => void;
|
|
66
|
+
/** Test seam (see SafeStorePoint). */
|
|
67
|
+
at?: StoreWriteHook;
|
|
68
|
+
/** Platform whose rules apply (tests). */
|
|
69
|
+
platform?: NodeJS.Platform;
|
|
70
|
+
}
|
|
71
|
+
/** A refused store operation as an error: `code` is the safe-store refusal code, or the errno of an io-error. */
|
|
72
|
+
export declare class StoreRefusedError extends Error {
|
|
73
|
+
readonly code: string;
|
|
74
|
+
readonly refusal: SafeStoreRefusalCode;
|
|
75
|
+
constructor(refused: SafeStoreRefusal);
|
|
76
|
+
}
|
|
77
|
+
/** The store folder itself is unusable: a link, not a folder, foreign, shared, or under an unsafe parent. */
|
|
78
|
+
export declare function isUnsafeFolderRefusal(code: SafeStoreRefusalCode): boolean;
|
|
79
|
+
/**
|
|
80
|
+
* Replace `file` with `text` through src/lib/safe-store.ts: the folder is held
|
|
81
|
+
* open and checked, the temporary file has a random name and O_EXCL, and the
|
|
82
|
+
* write is refused if the folder path is replaced (the helper's comment names
|
|
83
|
+
* the remaining window). A refusal is thrown as StoreRefusedError.
|
|
84
|
+
*/
|
|
85
|
+
export declare function writeStoreFile(file: string, text: string, options?: StoreFileWriteOptions): void;
|
|
86
|
+
/**
|
|
87
|
+
* A small file's contents and modification time, read through
|
|
88
|
+
* src/lib/safe-store.ts (a regular single-link file of this user in a checked
|
|
89
|
+
* folder, opened without following a link), or null when it is missing,
|
|
90
|
+
* refused or larger than `maxBytes`.
|
|
91
|
+
*/
|
|
92
|
+
export declare function readStoreFile(file: string, maxBytes: number): {
|
|
93
|
+
text: string;
|
|
94
|
+
mtimeMs: number;
|
|
95
|
+
} | null;
|
|
26
96
|
/** Open a log file for appending, creating it (and its folder) owner-only. */
|
|
27
97
|
export declare function openPrivateAppend(file: string): number;
|
|
28
98
|
export declare function appendPrivate(file: string, text: string): void;
|
package/dist/lib/daemon/paths.js
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
import * as fs from "node:fs";
|
|
7
7
|
import * as os from "node:os";
|
|
8
8
|
import * as path from "node:path";
|
|
9
|
+
import { openStoreDir, } from "../safe-store.js";
|
|
10
|
+
import { daemonStateFileEnabled } from "./state-file-switch.js";
|
|
9
11
|
export function daemonPaths(home = os.homedir(), env = process.env) {
|
|
10
12
|
const root = env.HQ_DAEMON_DIR?.trim() || path.join(home, ".hq", "daemon");
|
|
11
13
|
const logsDir = path.join(root, "logs");
|
|
@@ -24,10 +26,159 @@ export function daemonPaths(home = os.homedir(), env = process.env) {
|
|
|
24
26
|
unitProtocolPath: (unitId) => path.join(root, "protocol", `${unitId.replace(/[^A-Za-z0-9_.-]/g, "-")}.fifo`),
|
|
25
27
|
};
|
|
26
28
|
}
|
|
27
|
-
/**
|
|
28
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Create `dir` (and any missing parents) readable only by its owner, and
|
|
31
|
+
* tighten it if it already exists. The folder is checked before any chmod: it
|
|
32
|
+
* must be a real folder (not a symlink or junction) owned by this user, or
|
|
33
|
+
* EACCES is thrown and nothing is changed. The tightening runs through a
|
|
34
|
+
* descriptor opened with O_DIRECTORY|O_NOFOLLOW (fchmod), so a folder swapped
|
|
35
|
+
* for a link after the check is not followed. Windows, which cannot open a
|
|
36
|
+
* folder, checks by lstat and tightens by path (modes are no-ops there).
|
|
37
|
+
*
|
|
38
|
+
* The check came with the daemon state file (#2624) and sits behind its
|
|
39
|
+
* switch (state-file-switch.ts, default on). With the switch off, a folder the
|
|
40
|
+
* check refuses is handled as before #2624: it is tightened by path with
|
|
41
|
+
* chmod (following a link), and a chmod failure (EPERM on a folder another
|
|
42
|
+
* user owns) is thrown. One exception, which is new and not pre-#2624
|
|
43
|
+
* behavior: for the daemon root itself (`daemonPaths().root`, ~/.hq/daemon or
|
|
44
|
+
* HQ_DAEMON_DIR) a chmod failure is reported on stderr and the folder is used
|
|
45
|
+
* as it is, so a symlinked or foreign-owned daemon root does not stop the
|
|
46
|
+
* daemon. Every other folder (requests, bundle stages, config, logs, ...)
|
|
47
|
+
* still throws. The switch is read only when the check refuses, so the usual
|
|
48
|
+
* call reads no flag.
|
|
49
|
+
*/
|
|
50
|
+
export function ensurePrivateDir(dir, options = {}) {
|
|
29
51
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
30
|
-
|
|
52
|
+
try {
|
|
53
|
+
tightenCheckedDir(dir);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (!(error instanceof PrivateDirRefusedError))
|
|
57
|
+
throw error;
|
|
58
|
+
if ((options.stateFileEnabled ?? (() => daemonStateFileEnabled()))())
|
|
59
|
+
throw error;
|
|
60
|
+
const root = options.daemonRoot ?? daemonPaths().root;
|
|
61
|
+
tightenLegacyDir(dir, options.chmod ?? fs.chmodSync, path.resolve(dir) === path.resolve(root));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** ensurePrivateDir's refusal of a folder that is a link, not a folder, or another user's. */
|
|
65
|
+
class PrivateDirRefusedError extends Error {
|
|
66
|
+
code = "EACCES";
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Before #2624: tighten by path, which follows a link, and throw when that
|
|
70
|
+
* fails. Only the daemon root (`isDaemonRoot`) is used as it is after a failed
|
|
71
|
+
* chmod, with a warning; that part is new with the switch.
|
|
72
|
+
*/
|
|
73
|
+
function tightenLegacyDir(dir, chmod, isDaemonRoot) {
|
|
74
|
+
try {
|
|
75
|
+
chmod(dir, 0o700);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (!isDaemonRoot)
|
|
79
|
+
throw error;
|
|
80
|
+
process.stderr.write(`hq daemon: ${path.basename(dir)} could not be made private (${error.code ?? "error"}); using it as it is\n`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function tightenCheckedDir(dir) {
|
|
84
|
+
const refuse = () => {
|
|
85
|
+
throw new PrivateDirRefusedError(`${path.basename(dir)} is not a private folder of this user`);
|
|
86
|
+
};
|
|
87
|
+
const ownedFolder = (stat) => stat.isDirectory() && (typeof process.getuid !== "function" || stat.uid === process.getuid());
|
|
88
|
+
if (!ownedFolder(fs.lstatSync(dir)))
|
|
89
|
+
refuse();
|
|
90
|
+
const { O_RDONLY, O_DIRECTORY, O_NOFOLLOW } = fs.constants;
|
|
91
|
+
if (O_DIRECTORY === undefined || O_NOFOLLOW === undefined) {
|
|
92
|
+
fs.chmodSync(dir, 0o700);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
let fd;
|
|
96
|
+
try {
|
|
97
|
+
fd = fs.openSync(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
const code = error.code;
|
|
101
|
+
if (code === "ELOOP" || code === "ENOTDIR")
|
|
102
|
+
refuse();
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
const held = fs.fstatSync(fd);
|
|
107
|
+
if (!ownedFolder(held))
|
|
108
|
+
refuse();
|
|
109
|
+
if ((held.mode & 0o777) !== 0o700)
|
|
110
|
+
fs.fchmodSync(fd, 0o700);
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
fs.closeSync(fd);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** A refused store operation as an error: `code` is the safe-store refusal code, or the errno of an io-error. */
|
|
117
|
+
export class StoreRefusedError extends Error {
|
|
118
|
+
code;
|
|
119
|
+
refusal;
|
|
120
|
+
constructor(refused) {
|
|
121
|
+
super(refused.message);
|
|
122
|
+
this.name = "StoreRefusedError";
|
|
123
|
+
this.refusal = refused.code;
|
|
124
|
+
this.code = refused.code === "io-error" && refused.errno ? refused.errno : refused.code;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** The store folder itself is unusable: a link, not a folder, foreign, shared, or under an unsafe parent. */
|
|
128
|
+
export function isUnsafeFolderRefusal(code) {
|
|
129
|
+
return code === "folder-link" || code === "not-a-folder" || code === "folder-foreign-owner"
|
|
130
|
+
|| code === "folder-writable" || code === "parent-unsafe";
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Replace `file` with `text` through src/lib/safe-store.ts: the folder is held
|
|
134
|
+
* open and checked, the temporary file has a random name and O_EXCL, and the
|
|
135
|
+
* write is refused if the folder path is replaced (the helper's comment names
|
|
136
|
+
* the remaining window). A refusal is thrown as StoreRefusedError.
|
|
137
|
+
*/
|
|
138
|
+
export function writeStoreFile(file, text, options = {}) {
|
|
139
|
+
const opened = openStoreDir(path.dirname(file), {
|
|
140
|
+
...(options.create ? { create: true } : {}),
|
|
141
|
+
...(options.at ? { at: options.at } : {}),
|
|
142
|
+
...(options.platform ? { platform: options.platform } : {}),
|
|
143
|
+
});
|
|
144
|
+
if (!opened.ok)
|
|
145
|
+
throw new StoreRefusedError(opened);
|
|
146
|
+
const store = opened.value;
|
|
147
|
+
try {
|
|
148
|
+
const written = store.writeAtomic(path.basename(file), text, {
|
|
149
|
+
retryDelaysMs: options.renameRetryDelaysMs ?? [],
|
|
150
|
+
...(options.sleep ? { sleep: options.sleep } : {}),
|
|
151
|
+
...(options.renameFile ? { renameFile: options.renameFile } : {}),
|
|
152
|
+
});
|
|
153
|
+
if (!written.ok)
|
|
154
|
+
throw new StoreRefusedError(written);
|
|
155
|
+
}
|
|
156
|
+
finally {
|
|
157
|
+
store.close();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* A small file's contents and modification time, read through
|
|
162
|
+
* src/lib/safe-store.ts (a regular single-link file of this user in a checked
|
|
163
|
+
* folder, opened without following a link), or null when it is missing,
|
|
164
|
+
* refused or larger than `maxBytes`.
|
|
165
|
+
*/
|
|
166
|
+
export function readStoreFile(file, maxBytes) {
|
|
167
|
+
// mtimeMs is whole milliseconds, floored from the exact nanoseconds.
|
|
168
|
+
const opened = openStoreDir(path.dirname(file));
|
|
169
|
+
if (!opened.ok)
|
|
170
|
+
return null;
|
|
171
|
+
const store = opened.value;
|
|
172
|
+
try {
|
|
173
|
+
// The bytes and the modification time come from the same opened file.
|
|
174
|
+
const read = store.readWithFacts(path.basename(file), { maxBytes });
|
|
175
|
+
if (!read.ok)
|
|
176
|
+
return null;
|
|
177
|
+
return { text: read.value.data.toString("utf8"), mtimeMs: Number(read.value.facts.mtimeNs / 1000000n) };
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
store.close();
|
|
181
|
+
}
|
|
31
182
|
}
|
|
32
183
|
/** Open a log file for appending, creating it (and its folder) owner-only. */
|
|
33
184
|
export function openPrivateAppend(file) {
|
|
@@ -10,5 +10,7 @@ export declare function createResolver(registryPath: string, options?: {
|
|
|
10
10
|
log?: (level: "info" | "warn" | "error", message: string) => void;
|
|
11
11
|
readRegistry?: typeof readRegistry;
|
|
12
12
|
readCompaniesManifest?: typeof readCompaniesManifestMap;
|
|
13
|
+
/** Sees fs errors the resolver falls back from (hqd watches it for macOS EPERM). */
|
|
14
|
+
onFsError?: (err: unknown) => void;
|
|
13
15
|
}): (cwd: string) => ResolveResult;
|
|
14
16
|
//# sourceMappingURL=resolver.d.ts.map
|
|
@@ -26,6 +26,7 @@ export function createResolver(registryPath, options = {}) {
|
|
|
26
26
|
catch (err) {
|
|
27
27
|
const code = err.code;
|
|
28
28
|
if (code !== "ENOENT") {
|
|
29
|
+
options.onFsError?.(err);
|
|
29
30
|
cache.clear();
|
|
30
31
|
const detail = err instanceof Error ? err.message : String(err);
|
|
31
32
|
options.log?.("warn", `hqd registry unavailable; using personal context: ${detail}`);
|
|
@@ -65,6 +66,8 @@ export function createResolver(registryPath, options = {}) {
|
|
|
65
66
|
}
|
|
66
67
|
catch (err) {
|
|
67
68
|
const code = err.code;
|
|
69
|
+
if (code !== "ENOENT")
|
|
70
|
+
options.onFsError?.(err);
|
|
68
71
|
currentManifestStamp = code === "ENOENT" ? "missing" : `unavailable:${code ?? "unknown"}`;
|
|
69
72
|
}
|
|
70
73
|
if (currentManifestStamp !== manifestStamp) {
|