@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
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The daemon's state file: one JSON file, rewritten atomically after each
|
|
3
|
+
* flag registry request the daemon's timed flag monitors share, that hooks
|
|
4
|
+
* read instead of starting Node or calling the network.
|
|
5
|
+
*
|
|
6
|
+
* It holds three sections and nothing else:
|
|
7
|
+
* - flags: every flag value the registry returned for the daemon's scope
|
|
8
|
+
* (person, or one company uid), with the time the registry answered;
|
|
9
|
+
* - vault_access: per company slug, the caller's role, whether the access
|
|
10
|
+
* list is enforced, and the granted paths with their permission. It is
|
|
11
|
+
* copied from <hqRoot>/.hq/vault-access.json, field by field;
|
|
12
|
+
* - machine_checks: the latest results of the machine checks the daemon has
|
|
13
|
+
* today (id, status, time, optional one-line summary).
|
|
14
|
+
*
|
|
15
|
+
* No token, key or other secret is written. The vault access list tells which
|
|
16
|
+
* companies and paths a person can reach, so the file lives in the per-host
|
|
17
|
+
* daemon folder (~/.hq/daemon, 0700) with mode 0600, never in a repo or a
|
|
18
|
+
* synced folder, and its contents are never logged.
|
|
19
|
+
*
|
|
20
|
+
* The file states its own maximum age. A reader treats a missing, unreadable,
|
|
21
|
+
* truncated, other-schema, expired or future-dated file as stale: guards keep
|
|
22
|
+
* working without it and flag-gated extras use their defaults. The reader is
|
|
23
|
+
* crates/hq-hook/src/state.rs.
|
|
24
|
+
*
|
|
25
|
+
* The writer makes no registry request. It observes the daemon's shared flag
|
|
26
|
+
* snapshot source (flag.ts), so the file holds the same registry answer the
|
|
27
|
+
* kill-switch monitors are decided from, and a kill switch is no later than
|
|
28
|
+
* it is without this file.
|
|
29
|
+
*
|
|
30
|
+
* The file is behind a switch, default on (state-file-switch.ts): flag
|
|
31
|
+
* `daemon-state-file`, env `HQ_FLAG_DAEMON_STATE_FILE=false`, or the file
|
|
32
|
+
* `~/.hq/daemon-state-file.off`. While it is off nothing is written.
|
|
33
|
+
*/
|
|
34
|
+
import { type StoreWriteHook } from "./paths.js";
|
|
35
|
+
import type { DaemonFlagRegistryRead } from "./flag.js";
|
|
36
|
+
import type { SelfCheckResult } from "./selfcheck.js";
|
|
37
|
+
import { type DaemonStateFileOffReason } from "./state-file-switch.js";
|
|
38
|
+
export declare const DAEMON_STATE_SCHEMA = "hq-state.v1";
|
|
39
|
+
export declare const DAEMON_STATE_FILE = "hq-state.json";
|
|
40
|
+
/** Written into the file: a reader treats the file, or its flags, as stale past this age. */
|
|
41
|
+
export declare const DAEMON_STATE_MAX_AGE_SECONDS = 600;
|
|
42
|
+
export type DaemonStateFlagValue = boolean | "off" | "shadow" | "on";
|
|
43
|
+
export interface DaemonStateFlagScope {
|
|
44
|
+
/** When the registry answered with these values. */
|
|
45
|
+
fetched_at: string;
|
|
46
|
+
values: Record<string, DaemonStateFlagValue>;
|
|
47
|
+
}
|
|
48
|
+
export interface DaemonStateVaultGrant {
|
|
49
|
+
path: string;
|
|
50
|
+
permission: "read" | "write" | "admin";
|
|
51
|
+
}
|
|
52
|
+
export interface DaemonStateVaultCompany {
|
|
53
|
+
role: "owner" | "admin" | "member" | "guest" | "unknown";
|
|
54
|
+
enforced: boolean;
|
|
55
|
+
grants: DaemonStateVaultGrant[];
|
|
56
|
+
}
|
|
57
|
+
export interface DaemonStateVaultAccess {
|
|
58
|
+
/** When the access list was last refreshed from the server (the manifest's modification time). */
|
|
59
|
+
refreshed_at: string;
|
|
60
|
+
companies: Record<string, DaemonStateVaultCompany>;
|
|
61
|
+
}
|
|
62
|
+
export interface DaemonStateMachineCheck {
|
|
63
|
+
id: string;
|
|
64
|
+
status: "ok" | "warn" | "fail" | "unknown";
|
|
65
|
+
checked_at: string;
|
|
66
|
+
summary?: string;
|
|
67
|
+
}
|
|
68
|
+
export interface DaemonStateFile {
|
|
69
|
+
schema: typeof DAEMON_STATE_SCHEMA;
|
|
70
|
+
written_at: string;
|
|
71
|
+
max_age_seconds: number;
|
|
72
|
+
flags: {
|
|
73
|
+
scopes: Record<string, DaemonStateFlagScope>;
|
|
74
|
+
};
|
|
75
|
+
vault_access: DaemonStateVaultAccess | null;
|
|
76
|
+
machine_checks: {
|
|
77
|
+
results: DaemonStateMachineCheck[];
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** `HQ_STATE_FILE` when set (tests and isolated daemons), else `<daemon folder>/hq-state.json`. */
|
|
81
|
+
export declare function daemonStateFilePath(home?: string, env?: NodeJS.ProcessEnv): string;
|
|
82
|
+
/** `<daemon folder>/hq-state.json`: the one state path whose folder the daemon creates and tightens. */
|
|
83
|
+
export declare function defaultDaemonStateFilePath(home?: string, env?: NodeJS.ProcessEnv): string;
|
|
84
|
+
/**
|
|
85
|
+
* A grant path as the access list means it: forward slashes, no empty or `.`
|
|
86
|
+
* segments, a trailing slash kept (it marks a create-only folder). Null for a
|
|
87
|
+
* path that is absolute, empty, too long, or has a `..` segment.
|
|
88
|
+
*/
|
|
89
|
+
export declare function normalizeVaultGrantPath(raw: unknown): string | null;
|
|
90
|
+
/** Booleans for every key; a mode string only for a `hook-engine-port-<id>` key (as flag-snapshot-file.ts stores them). */
|
|
91
|
+
export declare function daemonStateFlagValues(flags: Readonly<Record<string, unknown>>): Record<string, DaemonStateFlagValue>;
|
|
92
|
+
/**
|
|
93
|
+
* The vault access section from the manifest refresh-vault-access.sh writes.
|
|
94
|
+
* Only the documented fields are copied, so nothing else in that file can
|
|
95
|
+
* reach the state file. Grant paths are normalized and a path with a `..`
|
|
96
|
+
* segment is dropped. Null when the manifest is missing or not valid, and when
|
|
97
|
+
* it is a symlink, has another link, is not this user's, or group or others can
|
|
98
|
+
* write it, or when its folder is not safe (src/lib/safe-store.ts read rules).
|
|
99
|
+
*/
|
|
100
|
+
export declare function readVaultAccessManifest(hqRoot: string | undefined): DaemonStateVaultAccess | null;
|
|
101
|
+
/**
|
|
102
|
+
* The one machine check the daemon has today: the sync-engine self-check. Its
|
|
103
|
+
* latest run's result is written on every run, healthy or not. The unit ids
|
|
104
|
+
* carry vault ids, so only their count reaches the state file.
|
|
105
|
+
*/
|
|
106
|
+
export declare function selfCheckMachineChecks(result: SelfCheckResult | null): DaemonStateMachineCheck[];
|
|
107
|
+
/** The exact bytes written: one line of JSON with the keys in schema order. */
|
|
108
|
+
export declare function renderDaemonStateFile(state: DaemonStateFile): string;
|
|
109
|
+
export interface WriteDaemonStateFileDeps {
|
|
110
|
+
platform?: NodeJS.Platform;
|
|
111
|
+
rename?: (from: string, to: string) => void;
|
|
112
|
+
/** Synchronous wait between Windows rename attempts. */
|
|
113
|
+
sleep?: (ms: number) => void;
|
|
114
|
+
/**
|
|
115
|
+
* The daemon's default state file. The writer creates and tightens the
|
|
116
|
+
* folder of that path only; any other folder (HQ_STATE_FILE) is left as it
|
|
117
|
+
* is. Omitted: `file` is treated as the default.
|
|
118
|
+
*/
|
|
119
|
+
defaultFile?: string;
|
|
120
|
+
/** Test seam: called at each named point of the write (see src/lib/safe-store.ts). */
|
|
121
|
+
at?: StoreWriteHook;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Write the state file so a reader sees the previous file or the new one,
|
|
125
|
+
* never part of one: a temporary file in the same folder, flushed, then
|
|
126
|
+
* renamed over the destination, through src/lib/safe-store.ts (writeAtomic),
|
|
127
|
+
* which holds the checked folder open and refuses the write if the folder
|
|
128
|
+
* path is replaced; its comment names the remaining window.
|
|
129
|
+
*
|
|
130
|
+
* POSIX rename replaces the destination atomically. On Windows the rename
|
|
131
|
+
* (MoveFileEx with replace) fails with EPERM, EACCES or EBUSY while another
|
|
132
|
+
* process holds the destination open without delete sharing, which a virus
|
|
133
|
+
* scanner can do for a moment. Those failures are retried for about 300 ms.
|
|
134
|
+
* If the rename still fails the previous file stays in place and the error is
|
|
135
|
+
* thrown; the file is never written in place.
|
|
136
|
+
*
|
|
137
|
+
* The temporary file has a random name and is created with O_EXCL|O_NOFOLLOW,
|
|
138
|
+
* and a symlink or hardlink at the destination is replaced by the rename,
|
|
139
|
+
* never written through.
|
|
140
|
+
*
|
|
141
|
+
* The folder must be a real folder (not a symlink) that belongs to this user
|
|
142
|
+
* and is not writable by group or others, or the write is refused. Only the
|
|
143
|
+
* daemon's default folder is created and tightened.
|
|
144
|
+
*/
|
|
145
|
+
export declare function writeDaemonStateFile(file: string, state: DaemonStateFile, deps?: WriteDaemonStateFileDeps): void;
|
|
146
|
+
/**
|
|
147
|
+
* The file as written, or null for anything that is not a complete
|
|
148
|
+
* current-schema file, and for a file the shared store rules refuse (a link,
|
|
149
|
+
* a hardlink, not this user's, group or world writable, larger than the
|
|
150
|
+
* engine reads, or in an unsafe folder). Age is not checked.
|
|
151
|
+
*/
|
|
152
|
+
export declare function readDaemonStateFile(file: string): DaemonStateFile | null;
|
|
153
|
+
type Log = (level: "info" | "warn" | "error", message: string) => void;
|
|
154
|
+
export interface DaemonStateWriterOptions {
|
|
155
|
+
/** Where the state file is written. */
|
|
156
|
+
file: string;
|
|
157
|
+
/** The daemon's default state file, whose folder this writer may create and tighten. */
|
|
158
|
+
defaultFile?: string;
|
|
159
|
+
log?: Log;
|
|
160
|
+
maxAgeSeconds?: number;
|
|
161
|
+
/** Wall clock for the timestamps written into the file. */
|
|
162
|
+
wallClock?: () => Date;
|
|
163
|
+
/** The vault access section; null when there is none to write. */
|
|
164
|
+
readVaultAccess?: () => DaemonStateVaultAccess | null;
|
|
165
|
+
readMachineChecks?: () => DaemonStateMachineCheck[];
|
|
166
|
+
/** Test seam for the write (Windows rename behavior). */
|
|
167
|
+
writeDeps?: WriteDaemonStateFileDeps;
|
|
168
|
+
/**
|
|
169
|
+
* Why the state file is switched off for this registry answer, or null while
|
|
170
|
+
* it is on. Default: daemonStateFileOffReason (state-file-switch.ts) with the
|
|
171
|
+
* daemon's env and the `daemon-state-file` value the answer carries. While
|
|
172
|
+
* off nothing is written and the daemon folder is not created or checked.
|
|
173
|
+
*/
|
|
174
|
+
offReason?: (read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv) => DaemonStateFileOffReason | null;
|
|
175
|
+
}
|
|
176
|
+
export interface DaemonStateWriter {
|
|
177
|
+
/**
|
|
178
|
+
* Pass as `onRead` to createDaemonFlagSnapshotSource. Every registry request
|
|
179
|
+
* the daemon's timed flag monitors share is written to the state file, so the
|
|
180
|
+
* file comes from the same answer the kill switches are decided from and the
|
|
181
|
+
* writer makes no request of its own.
|
|
182
|
+
*/
|
|
183
|
+
onRegistryRead(read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv): void;
|
|
184
|
+
close(): void;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Remove the daemon's own state file when the switch goes off, so a reader
|
|
188
|
+
* that cannot see the off signal (the switch was turned off only by the
|
|
189
|
+
* registry flag, and the hook's flag snapshot does not hold `false` yet) does
|
|
190
|
+
* not keep reading the last file until it expires (600 s, at most 660 s).
|
|
191
|
+
* Only through a checked private folder (src/lib/safe-store.ts: no symlinked,
|
|
192
|
+
* shared or foreign folder) and only a regular single-link file of this user;
|
|
193
|
+
* a link is never followed. Never creates the folder.
|
|
194
|
+
*/
|
|
195
|
+
export declare function removeDaemonStateFile(file: string): "removed" | "absent" | "refused";
|
|
196
|
+
export declare function createDaemonStateWriter(options: DaemonStateWriterOptions): DaemonStateWriter;
|
|
197
|
+
export {};
|
|
198
|
+
//# sourceMappingURL=state-file.d.ts.map
|
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The daemon's state file: one JSON file, rewritten atomically after each
|
|
3
|
+
* flag registry request the daemon's timed flag monitors share, that hooks
|
|
4
|
+
* read instead of starting Node or calling the network.
|
|
5
|
+
*
|
|
6
|
+
* It holds three sections and nothing else:
|
|
7
|
+
* - flags: every flag value the registry returned for the daemon's scope
|
|
8
|
+
* (person, or one company uid), with the time the registry answered;
|
|
9
|
+
* - vault_access: per company slug, the caller's role, whether the access
|
|
10
|
+
* list is enforced, and the granted paths with their permission. It is
|
|
11
|
+
* copied from <hqRoot>/.hq/vault-access.json, field by field;
|
|
12
|
+
* - machine_checks: the latest results of the machine checks the daemon has
|
|
13
|
+
* today (id, status, time, optional one-line summary).
|
|
14
|
+
*
|
|
15
|
+
* No token, key or other secret is written. The vault access list tells which
|
|
16
|
+
* companies and paths a person can reach, so the file lives in the per-host
|
|
17
|
+
* daemon folder (~/.hq/daemon, 0700) with mode 0600, never in a repo or a
|
|
18
|
+
* synced folder, and its contents are never logged.
|
|
19
|
+
*
|
|
20
|
+
* The file states its own maximum age. A reader treats a missing, unreadable,
|
|
21
|
+
* truncated, other-schema, expired or future-dated file as stale: guards keep
|
|
22
|
+
* working without it and flag-gated extras use their defaults. The reader is
|
|
23
|
+
* crates/hq-hook/src/state.rs.
|
|
24
|
+
*
|
|
25
|
+
* The writer makes no registry request. It observes the daemon's shared flag
|
|
26
|
+
* snapshot source (flag.ts), so the file holds the same registry answer the
|
|
27
|
+
* kill-switch monitors are decided from, and a kill switch is no later than
|
|
28
|
+
* it is without this file.
|
|
29
|
+
*
|
|
30
|
+
* The file is behind a switch, default on (state-file-switch.ts): flag
|
|
31
|
+
* `daemon-state-file`, env `HQ_FLAG_DAEMON_STATE_FILE=false`, or the file
|
|
32
|
+
* `~/.hq/daemon-state-file.off`. While it is off nothing is written.
|
|
33
|
+
*/
|
|
34
|
+
import * as fs from "node:fs";
|
|
35
|
+
import * as path from "node:path";
|
|
36
|
+
import { openStoreDir } from "../safe-store.js";
|
|
37
|
+
import { resolveProcessFlagCompanyContext } from "../flag-registry.js";
|
|
38
|
+
import { daemonPaths, isUnsafeFolderRefusal, readStoreFile, StoreRefusedError, writeStoreFile } from "./paths.js";
|
|
39
|
+
import { DAEMON_STATE_FILE_FLAG, daemonStateFileOffReason } from "./state-file-switch.js";
|
|
40
|
+
export const DAEMON_STATE_SCHEMA = "hq-state.v1";
|
|
41
|
+
export const DAEMON_STATE_FILE = "hq-state.json";
|
|
42
|
+
/** Written into the file: a reader treats the file, or its flags, as stale past this age. */
|
|
43
|
+
export const DAEMON_STATE_MAX_AGE_SECONDS = 600;
|
|
44
|
+
const WINDOWS_RENAME_RETRY_DELAYS_MS = [10, 20, 40, 80, 160];
|
|
45
|
+
/** The engine reads at most this much of the state file (MAX_FILE_BYTES in crates/hq-hook/src/state.rs). */
|
|
46
|
+
const MAX_STATE_FILE_BYTES = 8 * 1024 * 1024;
|
|
47
|
+
/** The vault access manifest is small; a larger file is not read. */
|
|
48
|
+
const MAX_MANIFEST_BYTES = 8 * 1024 * 1024;
|
|
49
|
+
const PERSON_SCOPE = "person";
|
|
50
|
+
const COMPANY_UID_RE = /^cmp_[A-Za-z0-9]{3,128}$/;
|
|
51
|
+
const COMPANY_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
52
|
+
const HOOK_ENGINE_PORT_FLAG_PREFIX = "hook-engine-port-";
|
|
53
|
+
const HOOK_ENGINE_PORT_MODES = new Set(["off", "shadow", "on"]);
|
|
54
|
+
const VAULT_PERMISSIONS = new Set(["read", "write", "admin"]);
|
|
55
|
+
const VAULT_ROLES = new Set(["owner", "admin", "member", "guest", "unknown"]);
|
|
56
|
+
const MACHINE_CHECK_STATUSES = new Set(["ok", "warn", "fail", "unknown"]);
|
|
57
|
+
/** `HQ_STATE_FILE` when set (tests and isolated daemons), else `<daemon folder>/hq-state.json`. */
|
|
58
|
+
export function daemonStateFilePath(home, env = process.env) {
|
|
59
|
+
const explicit = env.HQ_STATE_FILE?.trim();
|
|
60
|
+
if (explicit)
|
|
61
|
+
return explicit;
|
|
62
|
+
return defaultDaemonStateFilePath(home, env);
|
|
63
|
+
}
|
|
64
|
+
/** `<daemon folder>/hq-state.json`: the one state path whose folder the daemon creates and tightens. */
|
|
65
|
+
export function defaultDaemonStateFilePath(home, env = process.env) {
|
|
66
|
+
return path.join(daemonPaths(home, env).root, DAEMON_STATE_FILE);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A grant path as the access list means it: forward slashes, no empty or `.`
|
|
70
|
+
* segments, a trailing slash kept (it marks a create-only folder). Null for a
|
|
71
|
+
* path that is absolute, empty, too long, or has a `..` segment.
|
|
72
|
+
*/
|
|
73
|
+
export function normalizeVaultGrantPath(raw) {
|
|
74
|
+
if (typeof raw !== "string" || !raw || raw.length > 1024 || raw.includes("\0"))
|
|
75
|
+
return null;
|
|
76
|
+
const slashed = raw.replace(/\\/g, "/");
|
|
77
|
+
if (slashed.startsWith("/") || /^[A-Za-z]:/.test(slashed))
|
|
78
|
+
return null;
|
|
79
|
+
const segments = slashed.split("/").filter((segment) => segment !== "" && segment !== ".");
|
|
80
|
+
if (segments.length === 0 || segments.includes(".."))
|
|
81
|
+
return null;
|
|
82
|
+
return segments.join("/") + (slashed.endsWith("/") ? "/" : "");
|
|
83
|
+
}
|
|
84
|
+
function isRecord(value) {
|
|
85
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
86
|
+
}
|
|
87
|
+
function isIsoTime(value) {
|
|
88
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value));
|
|
89
|
+
}
|
|
90
|
+
/** Booleans for every key; a mode string only for a `hook-engine-port-<id>` key (as flag-snapshot-file.ts stores them). */
|
|
91
|
+
export function daemonStateFlagValues(flags) {
|
|
92
|
+
const values = {};
|
|
93
|
+
for (const key of Object.keys(flags).sort()) {
|
|
94
|
+
const value = flags[key];
|
|
95
|
+
if (!key.trim())
|
|
96
|
+
continue;
|
|
97
|
+
if (typeof value === "boolean")
|
|
98
|
+
values[key] = value;
|
|
99
|
+
else if (key.startsWith(HOOK_ENGINE_PORT_FLAG_PREFIX)
|
|
100
|
+
&& key.length > HOOK_ENGINE_PORT_FLAG_PREFIX.length
|
|
101
|
+
&& HOOK_ENGINE_PORT_MODES.has(value))
|
|
102
|
+
values[key] = value;
|
|
103
|
+
}
|
|
104
|
+
return values;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The vault access section from the manifest refresh-vault-access.sh writes.
|
|
108
|
+
* Only the documented fields are copied, so nothing else in that file can
|
|
109
|
+
* reach the state file. Grant paths are normalized and a path with a `..`
|
|
110
|
+
* segment is dropped. Null when the manifest is missing or not valid, and when
|
|
111
|
+
* it is a symlink, has another link, is not this user's, or group or others can
|
|
112
|
+
* write it, or when its folder is not safe (src/lib/safe-store.ts read rules).
|
|
113
|
+
*/
|
|
114
|
+
export function readVaultAccessManifest(hqRoot) {
|
|
115
|
+
if (!hqRoot)
|
|
116
|
+
return null;
|
|
117
|
+
const read = readStoreFile(path.join(hqRoot, ".hq", "vault-access.json"), MAX_MANIFEST_BYTES);
|
|
118
|
+
if (!read)
|
|
119
|
+
return null;
|
|
120
|
+
let parsed;
|
|
121
|
+
try {
|
|
122
|
+
parsed = JSON.parse(read.text);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
const refreshedAt = new Date(read.mtimeMs).toISOString();
|
|
128
|
+
if (!isRecord(parsed) || parsed.version !== 1 || !isRecord(parsed.companies))
|
|
129
|
+
return null;
|
|
130
|
+
const companies = {};
|
|
131
|
+
for (const slug of Object.keys(parsed.companies).sort()) {
|
|
132
|
+
const entry = parsed.companies[slug];
|
|
133
|
+
if (!COMPANY_SLUG_RE.test(slug) || !isRecord(entry))
|
|
134
|
+
continue;
|
|
135
|
+
const grants = [];
|
|
136
|
+
for (const grant of Array.isArray(entry.grants) ? entry.grants : []) {
|
|
137
|
+
if (!isRecord(grant) || !VAULT_PERMISSIONS.has(grant.permission))
|
|
138
|
+
continue;
|
|
139
|
+
const grantPath = normalizeVaultGrantPath(grant.path);
|
|
140
|
+
if (grantPath === null)
|
|
141
|
+
continue;
|
|
142
|
+
grants.push({ path: grantPath, permission: grant.permission });
|
|
143
|
+
}
|
|
144
|
+
companies[slug] = {
|
|
145
|
+
role: (VAULT_ROLES.has(entry.role) ? entry.role : "unknown"),
|
|
146
|
+
enforced: entry.enforced !== false,
|
|
147
|
+
grants,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
return { refreshed_at: refreshedAt, companies };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The one machine check the daemon has today: the sync-engine self-check. Its
|
|
154
|
+
* latest run's result is written on every run, healthy or not. The unit ids
|
|
155
|
+
* carry vault ids, so only their count reaches the state file.
|
|
156
|
+
*/
|
|
157
|
+
export function selfCheckMachineChecks(result) {
|
|
158
|
+
if (!result)
|
|
159
|
+
return [];
|
|
160
|
+
return [{
|
|
161
|
+
id: "sync-core-selfcheck",
|
|
162
|
+
status: result.problems > 0 ? "warn" : "ok",
|
|
163
|
+
checked_at: new Date(result.checkedAt).toISOString(),
|
|
164
|
+
summary: `${result.problems} sync engine unit(s) needed attention`,
|
|
165
|
+
}];
|
|
166
|
+
}
|
|
167
|
+
function machineChecksOf(results) {
|
|
168
|
+
const out = [];
|
|
169
|
+
for (const result of results) {
|
|
170
|
+
if (!isRecord(result) || typeof result.id !== "string" || !result.id.trim())
|
|
171
|
+
continue;
|
|
172
|
+
if (!MACHINE_CHECK_STATUSES.has(result.status) || !isIsoTime(result.checked_at))
|
|
173
|
+
continue;
|
|
174
|
+
out.push({
|
|
175
|
+
id: result.id,
|
|
176
|
+
status: result.status,
|
|
177
|
+
checked_at: result.checked_at,
|
|
178
|
+
...(typeof result.summary === "string" && result.summary ? { summary: result.summary.slice(0, 240) } : {}),
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
/** The exact bytes written: one line of JSON with the keys in schema order. */
|
|
184
|
+
export function renderDaemonStateFile(state) {
|
|
185
|
+
const scopes = {};
|
|
186
|
+
for (const scope of Object.keys(state.flags.scopes).sort()) {
|
|
187
|
+
const entry = state.flags.scopes[scope];
|
|
188
|
+
scopes[scope] = { fetched_at: entry.fetched_at, values: daemonStateFlagValues(entry.values) };
|
|
189
|
+
}
|
|
190
|
+
const ordered = {
|
|
191
|
+
schema: DAEMON_STATE_SCHEMA,
|
|
192
|
+
written_at: state.written_at,
|
|
193
|
+
max_age_seconds: state.max_age_seconds,
|
|
194
|
+
flags: { scopes },
|
|
195
|
+
vault_access: state.vault_access
|
|
196
|
+
? { refreshed_at: state.vault_access.refreshed_at, companies: state.vault_access.companies }
|
|
197
|
+
: null,
|
|
198
|
+
machine_checks: { results: machineChecksOf(state.machine_checks.results) },
|
|
199
|
+
};
|
|
200
|
+
return `${JSON.stringify(ordered)}\n`;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Write the state file so a reader sees the previous file or the new one,
|
|
204
|
+
* never part of one: a temporary file in the same folder, flushed, then
|
|
205
|
+
* renamed over the destination, through src/lib/safe-store.ts (writeAtomic),
|
|
206
|
+
* which holds the checked folder open and refuses the write if the folder
|
|
207
|
+
* path is replaced; its comment names the remaining window.
|
|
208
|
+
*
|
|
209
|
+
* POSIX rename replaces the destination atomically. On Windows the rename
|
|
210
|
+
* (MoveFileEx with replace) fails with EPERM, EACCES or EBUSY while another
|
|
211
|
+
* process holds the destination open without delete sharing, which a virus
|
|
212
|
+
* scanner can do for a moment. Those failures are retried for about 300 ms.
|
|
213
|
+
* If the rename still fails the previous file stays in place and the error is
|
|
214
|
+
* thrown; the file is never written in place.
|
|
215
|
+
*
|
|
216
|
+
* The temporary file has a random name and is created with O_EXCL|O_NOFOLLOW,
|
|
217
|
+
* and a symlink or hardlink at the destination is replaced by the rename,
|
|
218
|
+
* never written through.
|
|
219
|
+
*
|
|
220
|
+
* The folder must be a real folder (not a symlink) that belongs to this user
|
|
221
|
+
* and is not writable by group or others, or the write is refused. Only the
|
|
222
|
+
* daemon's default folder is created and tightened.
|
|
223
|
+
*/
|
|
224
|
+
export function writeDaemonStateFile(file, state, deps = {}) {
|
|
225
|
+
const ownFolder = deps.defaultFile === undefined || path.resolve(deps.defaultFile) === path.resolve(file);
|
|
226
|
+
const platform = deps.platform ?? process.platform;
|
|
227
|
+
try {
|
|
228
|
+
writeStoreFile(file, renderDaemonStateFile(state), {
|
|
229
|
+
create: ownFolder,
|
|
230
|
+
platform,
|
|
231
|
+
...(deps.rename ? { renameFile: deps.rename } : {}),
|
|
232
|
+
...(deps.sleep ? { sleep: deps.sleep } : {}),
|
|
233
|
+
...(deps.at ? { at: deps.at } : {}),
|
|
234
|
+
renameRetryDelaysMs: platform === "win32" ? WINDOWS_RENAME_RETRY_DELAYS_MS : [],
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (!(error instanceof StoreRefusedError) || !isUnsafeFolderRefusal(error.refusal))
|
|
239
|
+
throw error;
|
|
240
|
+
throw Object.assign(new Error("state file folder is not a private folder of this user"), { code: "EACCES" });
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* The file as written, or null for anything that is not a complete
|
|
245
|
+
* current-schema file, and for a file the shared store rules refuse (a link,
|
|
246
|
+
* a hardlink, not this user's, group or world writable, larger than the
|
|
247
|
+
* engine reads, or in an unsafe folder). Age is not checked.
|
|
248
|
+
*/
|
|
249
|
+
export function readDaemonStateFile(file) {
|
|
250
|
+
const read = readStoreFile(file, MAX_STATE_FILE_BYTES);
|
|
251
|
+
if (!read)
|
|
252
|
+
return null;
|
|
253
|
+
let parsed;
|
|
254
|
+
try {
|
|
255
|
+
parsed = JSON.parse(read.text);
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
if (!isRecord(parsed) || parsed.schema !== DAEMON_STATE_SCHEMA || !isIsoTime(parsed.written_at))
|
|
261
|
+
return null;
|
|
262
|
+
if (typeof parsed.max_age_seconds !== "number" || !(parsed.max_age_seconds > 0))
|
|
263
|
+
return null;
|
|
264
|
+
if (!isRecord(parsed.flags) || !isRecord(parsed.flags.scopes))
|
|
265
|
+
return null;
|
|
266
|
+
const scopes = {};
|
|
267
|
+
for (const [scope, entry] of Object.entries(parsed.flags.scopes)) {
|
|
268
|
+
if (scope !== PERSON_SCOPE && !COMPANY_UID_RE.test(scope))
|
|
269
|
+
return null;
|
|
270
|
+
if (!isRecord(entry) || !isIsoTime(entry.fetched_at) || !isRecord(entry.values))
|
|
271
|
+
return null;
|
|
272
|
+
scopes[scope] = { fetched_at: entry.fetched_at, values: daemonStateFlagValues(entry.values) };
|
|
273
|
+
}
|
|
274
|
+
const vault = parsed.vault_access;
|
|
275
|
+
const checks = isRecord(parsed.machine_checks) && Array.isArray(parsed.machine_checks.results)
|
|
276
|
+
? machineChecksOf(parsed.machine_checks.results)
|
|
277
|
+
: [];
|
|
278
|
+
return {
|
|
279
|
+
schema: DAEMON_STATE_SCHEMA,
|
|
280
|
+
written_at: parsed.written_at,
|
|
281
|
+
max_age_seconds: parsed.max_age_seconds,
|
|
282
|
+
flags: { scopes },
|
|
283
|
+
vault_access: isRecord(vault) && isIsoTime(vault.refreshed_at) && isRecord(vault.companies)
|
|
284
|
+
? { refreshed_at: vault.refreshed_at, companies: vault.companies }
|
|
285
|
+
: null,
|
|
286
|
+
machine_checks: { results: checks },
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
/** `person`, a company uid, or null for a slug that resolves to no uid (its flags are not written). */
|
|
290
|
+
function daemonFlagScope(env) {
|
|
291
|
+
const company = resolveProcessFlagCompanyContext(env);
|
|
292
|
+
return company.companyUid ?? (company.companySlug ? null : PERSON_SCOPE);
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Remove the daemon's own state file when the switch goes off, so a reader
|
|
296
|
+
* that cannot see the off signal (the switch was turned off only by the
|
|
297
|
+
* registry flag, and the hook's flag snapshot does not hold `false` yet) does
|
|
298
|
+
* not keep reading the last file until it expires (600 s, at most 660 s).
|
|
299
|
+
* Only through a checked private folder (src/lib/safe-store.ts: no symlinked,
|
|
300
|
+
* shared or foreign folder) and only a regular single-link file of this user;
|
|
301
|
+
* a link is never followed. Never creates the folder.
|
|
302
|
+
*/
|
|
303
|
+
export function removeDaemonStateFile(file) {
|
|
304
|
+
const opened = openStoreDir(path.dirname(file));
|
|
305
|
+
if (!opened.ok)
|
|
306
|
+
return opened.code === "folder-missing" ? "absent" : "refused";
|
|
307
|
+
const store = opened.value;
|
|
308
|
+
try {
|
|
309
|
+
let stat;
|
|
310
|
+
try {
|
|
311
|
+
stat = fs.lstatSync(file);
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
if (error.code === "ENOENT")
|
|
315
|
+
return "absent";
|
|
316
|
+
throw error;
|
|
317
|
+
}
|
|
318
|
+
const mine = typeof process.getuid !== "function" || stat.uid === process.getuid();
|
|
319
|
+
if (!stat.isFile() || stat.nlink !== 1 || !mine)
|
|
320
|
+
return "refused";
|
|
321
|
+
const removed = store.remove(path.basename(file));
|
|
322
|
+
if (!removed.ok)
|
|
323
|
+
return "refused";
|
|
324
|
+
return removed.value ? "removed" : "absent";
|
|
325
|
+
}
|
|
326
|
+
finally {
|
|
327
|
+
store.close();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/** The switch for one registry answer: the local signals, then the value the answer carries. */
|
|
331
|
+
function defaultOffReason(read, env) {
|
|
332
|
+
const answered = !read.signedOut && read.errors.length === 0 ? read.client?.snapshot?.() ?? null : null;
|
|
333
|
+
return daemonStateFileOffReason({ env, registryValue: answered?.flags[DAEMON_STATE_FILE_FLAG] });
|
|
334
|
+
}
|
|
335
|
+
export function createDaemonStateWriter(options) {
|
|
336
|
+
const maxAgeSeconds = options.maxAgeSeconds ?? DAEMON_STATE_MAX_AGE_SECONDS;
|
|
337
|
+
const wallClock = options.wallClock ?? (() => new Date());
|
|
338
|
+
const log = options.log ?? (() => { });
|
|
339
|
+
let closed = false;
|
|
340
|
+
let lastProblem;
|
|
341
|
+
// The file left from before the switch went off is removed once per off period.
|
|
342
|
+
let removedWhileOff = false;
|
|
343
|
+
const ownFile = options.defaultFile === undefined || path.resolve(options.defaultFile) === path.resolve(options.file);
|
|
344
|
+
const report = (problem, level = "warn") => {
|
|
345
|
+
if (problem === lastProblem)
|
|
346
|
+
return;
|
|
347
|
+
lastProblem = problem;
|
|
348
|
+
if (problem)
|
|
349
|
+
log(level, `state file: ${problem}`);
|
|
350
|
+
else
|
|
351
|
+
log("info", "state file: written again");
|
|
352
|
+
};
|
|
353
|
+
const errorName = (error) => (error instanceof Error ? error.name : "UnknownError");
|
|
354
|
+
return {
|
|
355
|
+
onRegistryRead(read, env) {
|
|
356
|
+
if (closed)
|
|
357
|
+
return;
|
|
358
|
+
try {
|
|
359
|
+
const snapshot = !read.signedOut && read.errors.length === 0 ? read.client?.snapshot?.() ?? null : null;
|
|
360
|
+
const off = (options.offReason ?? defaultOffReason)(read, env);
|
|
361
|
+
if (off) {
|
|
362
|
+
let removed = "";
|
|
363
|
+
if (!removedWhileOff && ownFile) {
|
|
364
|
+
removedWhileOff = true;
|
|
365
|
+
const outcome = removeDaemonStateFile(options.file);
|
|
366
|
+
if (outcome === "removed")
|
|
367
|
+
removed = "; the previous file was removed";
|
|
368
|
+
else if (outcome === "refused")
|
|
369
|
+
removed = "; the previous file was left in place (not a private file of this user)";
|
|
370
|
+
}
|
|
371
|
+
report(`switched off (${off}); not written${removed}`, "info");
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
removedWhileOff = false;
|
|
375
|
+
const now = wallClock();
|
|
376
|
+
const scope = daemonFlagScope(env);
|
|
377
|
+
// The file holds only what this request returned, for the daemon's own
|
|
378
|
+
// scope. Nothing is carried from the file on disk or from an earlier
|
|
379
|
+
// request: a file planted or loosened by another process is never
|
|
380
|
+
// rewritten as the daemon's own, and when the daemon is signed out or
|
|
381
|
+
// the request failed the flags are absent, so readers use each flag's
|
|
382
|
+
// default.
|
|
383
|
+
const scopes = {};
|
|
384
|
+
if (snapshot && scope) {
|
|
385
|
+
scopes[scope] = { fetched_at: now.toISOString(), values: daemonStateFlagValues(snapshot.flags) };
|
|
386
|
+
}
|
|
387
|
+
try {
|
|
388
|
+
writeDaemonStateFile(options.file, {
|
|
389
|
+
schema: DAEMON_STATE_SCHEMA,
|
|
390
|
+
written_at: now.toISOString(),
|
|
391
|
+
max_age_seconds: maxAgeSeconds,
|
|
392
|
+
flags: { scopes },
|
|
393
|
+
vault_access: options.readVaultAccess?.() ?? null,
|
|
394
|
+
machine_checks: { results: options.readMachineChecks?.() ?? [] },
|
|
395
|
+
}, { ...options.writeDeps, ...(options.defaultFile ? { defaultFile: options.defaultFile } : {}) });
|
|
396
|
+
}
|
|
397
|
+
catch (error) {
|
|
398
|
+
// Never the contents: the file holds the vault access list.
|
|
399
|
+
const code = error.code;
|
|
400
|
+
report(`could not be written (${typeof code === "string" ? code : errorName(error)}); readers keep the previous file`);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (read.signedOut)
|
|
404
|
+
report("signed out; flags are absent");
|
|
405
|
+
else if (!snapshot)
|
|
406
|
+
report(`flag registry read failed (${errorName(read.errors[0])}); flags are absent`);
|
|
407
|
+
else
|
|
408
|
+
report(undefined);
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
// a failing section reader or log sink cannot reach the flag read that called this
|
|
412
|
+
}
|
|
413
|
+
},
|
|
414
|
+
close() {
|
|
415
|
+
closed = true;
|
|
416
|
+
},
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
//# sourceMappingURL=state-file.js.map
|