@indigoai-us/hq-cli 5.345.270 → 5.345.272
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 +56 -0
- package/contracts/host-canary-release.json +7 -7
- package/dist/command-catalog.generated.d.ts +2 -2
- package/dist/command-catalog.generated.js +2 -2
- package/dist/commands/core-checkpoint-stop-gate-native.js +2 -13
- package/dist/commands/core-session-journal-native.js +20 -4
- package/dist/commands/signals-run.d.ts +4 -1
- package/dist/commands/signals-run.js +6 -8
- package/dist/commands/sync-core.js +2 -1
- package/dist/lib/daemon/daemon-restart.d.ts +70 -0
- package/dist/lib/daemon/daemon-restart.js +114 -0
- package/dist/lib/daemon/hook-requests-work-mesh-shims.d.ts +41 -0
- package/dist/lib/daemon/hook-requests-work-mesh-shims.js +237 -0
- package/dist/lib/daemon/hook-requests.d.ts +4 -1
- package/dist/lib/daemon/hook-requests.js +23 -1
- package/dist/lib/daemon/hq-child-bootstrap.mjs +1 -0
- package/dist/lib/daemon/installed-cli-restart.js +14 -4
- package/dist/lib/daemon/run.d.ts +1 -1
- package/dist/lib/daemon/run.js +65 -51
- package/dist/lib/daemon/supervisor.js +0 -2
- package/dist/lib/hook-engine/coverage.d.ts +21 -0
- package/dist/lib/hook-engine/coverage.js +98 -5
- package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
- package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
- package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
- package/dist/lib/hot-channels/signals-pass.js +13 -3
- package/dist/lib/signals/engine.d.ts +0 -2
- package/dist/lib/signals/engine.js +12 -7
- package/dist/lib/signals/reply.js +35 -82
- package/dist/lib/signals/run-lock.d.ts +8 -0
- package/dist/lib/signals/run-lock.js +42 -7
- package/dist/lib/signals/run-record.js +2 -1
- package/dist/lib/signals/settings.d.ts +9 -4
- package/dist/lib/signals/settings.js +7 -5
- package/dist/lib/signals/steps/extract.d.ts +37 -10
- package/dist/lib/signals/steps/extract.js +88 -111
- package/dist/lib/signals/steps/types.d.ts +3 -2
- package/dist/lib/sync-core/reconcile.d.ts +7 -1
- package/dist/lib/sync-core/reconcile.js +105 -18
- package/dist/lib/sync-core/release.d.ts +52 -2
- package/dist/lib/sync-core/release.js +172 -11
- package/dist/lib/sync-core/rollout-state.d.ts +11 -0
- package/dist/lib/sync-core/rollout-state.js +16 -0
- package/dist/utils/client-health-contract.d.ts +32 -0
- package/dist/utils/client-health-contract.js +35 -0
- package/dist/utils/client-health.d.ts +43 -0
- package/dist/utils/client-health.js +106 -3
- package/dist/utils/login-browser.d.ts +1 -0
- package/dist/utils/login-browser.js +31 -6
- package/dist/utils/spawn-detached-hidden.d.ts +66 -0
- package/dist/utils/spawn-detached-hidden.js +222 -0
- package/package.json +7 -7
|
@@ -33,6 +33,7 @@
|
|
|
33
33
|
import { isExpiring, loadCachedTokens } from "./cognito-session.js";
|
|
34
34
|
import { type VersionInfo } from "./feedback-versions.js";
|
|
35
35
|
import { type ClientHealthArch, type ClientHealthFailureReason, type ClientHealthHeartbeat, type ClientHealthLocalFilesOverview, type ClientHealthPlatform, type ClientHealthSyncEngineVault } from "./client-health-contract.js";
|
|
36
|
+
import { type SyncCoreBinaryOutcome } from "../lib/sync-core/rollout-state.js";
|
|
36
37
|
import { type DaemonPaths } from "../lib/daemon/paths.js";
|
|
37
38
|
export declare const CLIENT_HEALTH_STATE_FILE = "cli-client-health.json";
|
|
38
39
|
/**
|
|
@@ -182,12 +183,48 @@ export interface BuildCliHeartbeatInput {
|
|
|
182
183
|
localFilesOverview?: ClientHealthLocalFilesOverview | null;
|
|
183
184
|
syncEngine?: CliSyncEngine | null;
|
|
184
185
|
daemonCliVersion?: string | null;
|
|
186
|
+
/** The live daemon's state file facts; null with no live daemon. */
|
|
187
|
+
daemon?: CliDaemonFacts | null;
|
|
188
|
+
/** True when this process was started by the daemon (a daemon unit): `versions.cli` is then what its units run. */
|
|
189
|
+
daemonUnit?: boolean;
|
|
185
190
|
}
|
|
186
191
|
export interface CliSyncEngine {
|
|
187
192
|
release: string;
|
|
188
193
|
vaults: number;
|
|
189
194
|
byVault?: ClientHealthSyncEngineVault[];
|
|
195
|
+
pinned?: string;
|
|
196
|
+
pinSource?: "server" | "built-in" | "last-good";
|
|
197
|
+
reconcileAt?: string;
|
|
198
|
+
reconcileOutcome?: SyncCoreBinaryOutcome;
|
|
199
|
+
reconcileWarnings?: number;
|
|
190
200
|
}
|
|
201
|
+
export interface CliDaemonFacts {
|
|
202
|
+
startedAt?: string;
|
|
203
|
+
hosted: boolean;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* How long the daemon's state file may go without a rewrite before HQ stops
|
|
207
|
+
* trusting it. A running daemon rewrites state.json on every reconcile pass
|
|
208
|
+
* (15 s), so a state this old belongs to a daemon that is no longer running,
|
|
209
|
+
* even when its pid now names another live process.
|
|
210
|
+
*/
|
|
211
|
+
export declare const DAEMON_STATE_FRESH_MS: number;
|
|
212
|
+
/**
|
|
213
|
+
* The live daemon's start time and whether an app hosts it, read only from
|
|
214
|
+
* its lock and state files; null when none runs. The state counts only when
|
|
215
|
+
* it was written by the daemon instance that holds the lock (same pid, and
|
|
216
|
+
* started no earlier than the lock was taken) and was rewritten within
|
|
217
|
+
* {@link DAEMON_STATE_FRESH_MS}.
|
|
218
|
+
*/
|
|
219
|
+
export declare function readCliDaemonFacts(paths?: DaemonPaths, alive?: (pid: number) => boolean, now?: () => number): CliDaemonFacts | null;
|
|
220
|
+
/**
|
|
221
|
+
* True for the hq process a daemon (or its staged launcher) started for a
|
|
222
|
+
* unit. A daemon running this release records the unit's parent in
|
|
223
|
+
* HQ_DAEMON_UNIT_PARENT_PID, and a bot or session below the unit inherits it
|
|
224
|
+
* with a different parent, so it does not count. An older daemon sets no
|
|
225
|
+
* marker; its units are recognised by HQ_DAEMON_CLI_VERSION alone, as before.
|
|
226
|
+
*/
|
|
227
|
+
export declare function isDirectDaemonUnit(env: NodeJS.ProcessEnv, parentPid?: number): boolean;
|
|
191
228
|
export declare function readCliSyncEngine(stateDir: string, now?: Date, paths?: DaemonPaths, alive?: (pid: number) => boolean): CliSyncEngine | null;
|
|
192
229
|
/** Classify sync failures using typed error identity/code fields only. */
|
|
193
230
|
export declare function classifySyncFailure(err: unknown): ClientHealthFailureReason;
|
|
@@ -218,6 +255,12 @@ export interface ClientHealthDeps {
|
|
|
218
255
|
syncEngine?: () => CliSyncEngine | null;
|
|
219
256
|
daemonPaths?: DaemonPaths;
|
|
220
257
|
daemonCliVersion?: () => Promise<string | null>;
|
|
258
|
+
daemonFacts?: () => CliDaemonFacts | null;
|
|
259
|
+
daemonAlive?: (pid: number) => boolean;
|
|
260
|
+
/** This process's environment, read for HQ_DAEMON_CLI_VERSION and HQ_DAEMON_UNIT_PARENT_PID. */
|
|
261
|
+
env?: NodeJS.ProcessEnv;
|
|
262
|
+
/** This process's parent pid at startup; see {@link isDirectDaemonUnit}. */
|
|
263
|
+
parentPid?: number;
|
|
221
264
|
/** Override for {@link JOURNAL_OBSERVATION_TTL_MS}. */
|
|
222
265
|
journalObservationTtlMs?: number;
|
|
223
266
|
/** Override for {@link JOURNAL_OBSERVATION_LOCK_STALE_MS}. */
|
|
@@ -42,12 +42,13 @@ import { vaultApiFetch } from "./vault-api.js";
|
|
|
42
42
|
import { collectVersions } from "./feedback-versions.js";
|
|
43
43
|
import { resolveDaemonCliVersion } from "./daemon-cli-version.js";
|
|
44
44
|
import { isAuthError } from "./auth-error.js";
|
|
45
|
-
import { CLIENT_HEALTH_CONTRACT_VERSION, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES, CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS, parseClientHealthHeartbeat, SEMVER, } from "./client-health-contract.js";
|
|
45
|
+
import { CLIENT_HEALTH_CONTRACT_VERSION, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS, CLIENT_HEALTH_MAX_RECONCILE_WARNINGS, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES, CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS, parseClientHealthHeartbeat, SEMVER, } from "./client-health-contract.js";
|
|
46
46
|
import { collectLocalFilesOverview } from "./local-files-overview.js";
|
|
47
47
|
import { readSyncCoreRolloutStateFile } from "../lib/sync-core/rollout-state.js";
|
|
48
|
+
const ISO_UTC_MS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
|
|
48
49
|
import { readEngineStatus, SYNC_CORE_STATUS_WORK_LIMIT, syncCoreUnitId } from "../lib/sync-core/engine-home.js";
|
|
49
50
|
import { daemonPaths } from "../lib/daemon/paths.js";
|
|
50
|
-
import { isProcessAlive, runningDaemonPid } from "../lib/daemon/lock.js";
|
|
51
|
+
import { isProcessAlive, liveDaemonLock, runningDaemonPid } from "../lib/daemon/lock.js";
|
|
51
52
|
import { readEngineHoldKinds } from "../lib/sync-core/engine-holds.js";
|
|
52
53
|
/** Same bound as CLI telemetry: a heartbeat may never stall a command. */
|
|
53
54
|
const CLIENT_HEALTH_TIMEOUT_MS = 1_200;
|
|
@@ -430,6 +431,62 @@ function acquireJournalObservationLock(stateDir, nowMs, staleMs) {
|
|
|
430
431
|
}
|
|
431
432
|
};
|
|
432
433
|
}
|
|
434
|
+
/**
|
|
435
|
+
* How long the daemon's state file may go without a rewrite before HQ stops
|
|
436
|
+
* trusting it. A running daemon rewrites state.json on every reconcile pass
|
|
437
|
+
* (15 s), so a state this old belongs to a daemon that is no longer running,
|
|
438
|
+
* even when its pid now names another live process.
|
|
439
|
+
*/
|
|
440
|
+
export const DAEMON_STATE_FRESH_MS = 2 * 60_000;
|
|
441
|
+
/** How far the state's start may precede its lock's ts (whole-second rounding and clock skew). */
|
|
442
|
+
const DAEMON_LOCK_TS_SLACK_MS = 2_000;
|
|
443
|
+
/**
|
|
444
|
+
* The live daemon's start time and whether an app hosts it, read only from
|
|
445
|
+
* its lock and state files; null when none runs. The state counts only when
|
|
446
|
+
* it was written by the daemon instance that holds the lock (same pid, and
|
|
447
|
+
* started no earlier than the lock was taken) and was rewritten within
|
|
448
|
+
* {@link DAEMON_STATE_FRESH_MS}.
|
|
449
|
+
*/
|
|
450
|
+
export function readCliDaemonFacts(paths = daemonPaths(), alive = isProcessAlive, now = Date.now) {
|
|
451
|
+
try {
|
|
452
|
+
const lock = liveDaemonLock(paths.lockPath, alive);
|
|
453
|
+
if (lock === null)
|
|
454
|
+
return null;
|
|
455
|
+
const state = JSON.parse(fs.readFileSync(paths.statePath, "utf8"));
|
|
456
|
+
if (!state || state.pid !== lock.pid)
|
|
457
|
+
return null;
|
|
458
|
+
const updatedAt = typeof state.updatedAt === "number" && Number.isFinite(state.updatedAt) ? state.updatedAt : undefined;
|
|
459
|
+
if (updatedAt === undefined || now() - updatedAt > DAEMON_STATE_FRESH_MS)
|
|
460
|
+
return null;
|
|
461
|
+
const hosted = typeof state.host === "string" && state.host.length > 0;
|
|
462
|
+
const startedAtMs = typeof state.startedAt === "number" && Number.isFinite(state.startedAt) && state.startedAt > 0 ? state.startedAt : undefined;
|
|
463
|
+
if (startedAtMs === undefined)
|
|
464
|
+
return { hosted };
|
|
465
|
+
if (startedAtMs + DAEMON_LOCK_TS_SLACK_MS < lock.ts * 1000)
|
|
466
|
+
return null;
|
|
467
|
+
return { startedAt: new Date(startedAtMs).toISOString(), hosted };
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
const startupParentPid = process.ppid;
|
|
474
|
+
/**
|
|
475
|
+
* True for the hq process a daemon (or its staged launcher) started for a
|
|
476
|
+
* unit. A daemon running this release records the unit's parent in
|
|
477
|
+
* HQ_DAEMON_UNIT_PARENT_PID, and a bot or session below the unit inherits it
|
|
478
|
+
* with a different parent, so it does not count. An older daemon sets no
|
|
479
|
+
* marker; its units are recognised by HQ_DAEMON_CLI_VERSION alone, as before.
|
|
480
|
+
*/
|
|
481
|
+
export function isDirectDaemonUnit(env, parentPid = startupParentPid) {
|
|
482
|
+
if (!env.HQ_DAEMON_CLI_VERSION?.trim())
|
|
483
|
+
return false;
|
|
484
|
+
const marker = env.HQ_DAEMON_UNIT_PARENT_PID?.trim();
|
|
485
|
+
if (!marker)
|
|
486
|
+
return true;
|
|
487
|
+
const spawner = Number(marker);
|
|
488
|
+
return Number.isInteger(spawner) && spawner > 1 && spawner === parentPid;
|
|
489
|
+
}
|
|
433
490
|
function readDaemonUnitStatuses(paths, alive) {
|
|
434
491
|
try {
|
|
435
492
|
const daemonPid = runningDaemonPid(paths.lockPath, alive);
|
|
@@ -495,7 +552,19 @@ export function readCliSyncEngine(stateDir, now = new Date(), paths = daemonPath
|
|
|
495
552
|
add(vault.uid, () => syncEngineVaultFacts(vault, "legacy", units, now));
|
|
496
553
|
for (const { uid } of [...(state.skipped ?? []), ...(state.held ?? [])])
|
|
497
554
|
add(uid, () => ({ vaultUid: uid, owner: "legacy" }));
|
|
498
|
-
return {
|
|
555
|
+
return {
|
|
556
|
+
release: state.release,
|
|
557
|
+
vaults,
|
|
558
|
+
byVault,
|
|
559
|
+
...(state.binaryOutcome
|
|
560
|
+
? {
|
|
561
|
+
...(state.pin ? { pinned: state.pin.release, pinSource: state.pin.source } : {}),
|
|
562
|
+
reconcileAt: state.readAt,
|
|
563
|
+
reconcileOutcome: state.binaryOutcome,
|
|
564
|
+
reconcileWarnings: state.warnings ?? 0,
|
|
565
|
+
}
|
|
566
|
+
: {}),
|
|
567
|
+
};
|
|
499
568
|
}
|
|
500
569
|
/** Classify sync failures using typed error identity/code fields only. */
|
|
501
570
|
export function classifySyncFailure(err) {
|
|
@@ -616,6 +685,28 @@ export function buildCliHeartbeat(input) {
|
|
|
616
685
|
if (input.daemonCliVersion && SEMVER.test(input.daemonCliVersion)) {
|
|
617
686
|
heartbeat.daemonCliVersion = input.daemonCliVersion;
|
|
618
687
|
}
|
|
688
|
+
if (input.daemon) {
|
|
689
|
+
if (input.daemon.startedAt && ISO_UTC_MS.test(input.daemon.startedAt))
|
|
690
|
+
heartbeat.daemonStartedAt = input.daemon.startedAt;
|
|
691
|
+
heartbeat.daemonHosted = input.daemon.hosted;
|
|
692
|
+
}
|
|
693
|
+
if (input.daemonUnit && versions.cli)
|
|
694
|
+
heartbeat.daemonUnitCliVersion = versions.cli;
|
|
695
|
+
const engine = input.syncEngine;
|
|
696
|
+
if (engine) {
|
|
697
|
+
const pinned = engine.pinned?.replace(/^v/, "");
|
|
698
|
+
if (pinned && SEMVER.test(pinned))
|
|
699
|
+
heartbeat.syncEnginePinned = pinned;
|
|
700
|
+
if (engine.pinSource)
|
|
701
|
+
heartbeat.syncEnginePinSource = engine.pinSource;
|
|
702
|
+
if (engine.reconcileAt && ISO_UTC_MS.test(engine.reconcileAt))
|
|
703
|
+
heartbeat.syncEngineReconcileAt = engine.reconcileAt;
|
|
704
|
+
if (engine.reconcileOutcome)
|
|
705
|
+
heartbeat.syncEngineReconcileOutcome = engine.reconcileOutcome;
|
|
706
|
+
if (engine.reconcileWarnings !== undefined) {
|
|
707
|
+
heartbeat.syncEngineReconcileWarnings = Math.min(engine.reconcileWarnings, CLIENT_HEALTH_MAX_RECONCILE_WARNINGS);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
619
710
|
return heartbeat;
|
|
620
711
|
}
|
|
621
712
|
const defaultPoster = (heartbeat, token, signal) => vaultApiFetch({
|
|
@@ -792,6 +883,16 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
|
|
|
792
883
|
catch {
|
|
793
884
|
daemonCliVersion = null;
|
|
794
885
|
}
|
|
886
|
+
let daemon = null;
|
|
887
|
+
try {
|
|
888
|
+
daemon = deps.daemonFacts
|
|
889
|
+
? deps.daemonFacts()
|
|
890
|
+
: readCliDaemonFacts(deps.daemonPaths ?? daemonPaths(), deps.daemonAlive ?? isProcessAlive, () => now.getTime());
|
|
891
|
+
}
|
|
892
|
+
catch {
|
|
893
|
+
daemon = null;
|
|
894
|
+
}
|
|
895
|
+
const daemonUnit = isDirectDaemonUnit(deps.env ?? process.env, deps.parentPid ?? startupParentPid);
|
|
795
896
|
const heartbeat = buildCliHeartbeat({
|
|
796
897
|
kind,
|
|
797
898
|
state,
|
|
@@ -803,6 +904,8 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
|
|
|
803
904
|
failureReason,
|
|
804
905
|
syncEngine,
|
|
805
906
|
daemonCliVersion,
|
|
907
|
+
daemon,
|
|
908
|
+
daemonUnit,
|
|
806
909
|
});
|
|
807
910
|
if (!heartbeat)
|
|
808
911
|
return;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CognitoAuthConfig, CognitoTokens } from "@indigoai-us/hq-cloud";
|
|
2
|
+
export declare function usesHqChoicePage(config: CognitoAuthConfig, env?: NodeJS.ProcessEnv): boolean;
|
|
2
3
|
/** Keep desktop login unchanged; manual login uses the same PKCE loopback flow. */
|
|
3
4
|
export declare function loginWithBrowserPreference(requested: CognitoAuthConfig, browser?: boolean): Promise<CognitoTokens>;
|
|
4
5
|
//# sourceMappingURL=login-browser.d.ts.map
|
|
@@ -1,8 +1,24 @@
|
|
|
1
1
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import { createServer } from "node:http";
|
|
3
3
|
import { browserLogin, saveCachedTokens, CognitoAuthError } from "@indigoai-us/hq-cloud";
|
|
4
|
+
import open from "open";
|
|
4
5
|
import { isHeadless } from "./headless.js";
|
|
5
6
|
import { interactiveLoginConfig } from "./cognito-callback-port.js";
|
|
7
|
+
const HQ_CHOICE_PAGE_URL = "https://hqforwork.com/authorize/desktop";
|
|
8
|
+
const HQ_CHOICE_PAGE_CLIENT_ID = "7acei2c8v870enheptb1j5foln";
|
|
9
|
+
const HQ_CHOICE_PAGE_POOL_DOMAIN = "vault-indigo-hq-prod";
|
|
10
|
+
const HQ_CHOICE_PAGE_REGION = "us-east-1";
|
|
11
|
+
const HQ_CHOICE_PAGE_SCOPE = "openid email profile";
|
|
12
|
+
export function usesHqChoicePage(config, env = process.env) {
|
|
13
|
+
if (config.identityProvider)
|
|
14
|
+
return false;
|
|
15
|
+
if (env.HQ_COGNITO_IDENTITY_PROVIDER !== undefined && !env.HQ_COGNITO_IDENTITY_PROVIDER.trim())
|
|
16
|
+
return false;
|
|
17
|
+
return config.clientId === HQ_CHOICE_PAGE_CLIENT_ID
|
|
18
|
+
&& config.userPoolDomain === HQ_CHOICE_PAGE_POOL_DOMAIN
|
|
19
|
+
&& config.region === HQ_CHOICE_PAGE_REGION
|
|
20
|
+
&& (config.scopes ?? ["openid", "email", "profile"]).join(" ") === HQ_CHOICE_PAGE_SCOPE;
|
|
21
|
+
}
|
|
6
22
|
function assertHumanLoginAllowed() {
|
|
7
23
|
// Preserve hq-cloud's company-machine boundary on the manual URL path.
|
|
8
24
|
if (["1", "true", "yes"].includes(process.env.HQ_MACHINE_AUTH_REQUIRED?.trim().toLowerCase() ?? "")) {
|
|
@@ -15,7 +31,9 @@ export async function loginWithBrowserPreference(requested, browser = true) {
|
|
|
15
31
|
// The manual URL path builds the same redirect_uri and authorize URL, so
|
|
16
32
|
// both paths share one config: registered port plus the account chooser.
|
|
17
33
|
const config = interactiveLoginConfig(requested);
|
|
18
|
-
|
|
34
|
+
const choicePage = usesHqChoicePage(config);
|
|
35
|
+
const openBrowser = browser && !isHeadless();
|
|
36
|
+
if (openBrowser && !choicePage)
|
|
19
37
|
return browserLogin(config);
|
|
20
38
|
assertHumanLoginAllowed();
|
|
21
39
|
const port = config.port ?? 3000;
|
|
@@ -23,7 +41,7 @@ export async function loginWithBrowserPreference(requested, browser = true) {
|
|
|
23
41
|
const base = `https://${config.userPoolDomain}.auth.${config.region}.amazoncognito.com`;
|
|
24
42
|
const verifier = randomBytes(32).toString("base64url");
|
|
25
43
|
const state = randomBytes(16).toString("base64url");
|
|
26
|
-
const url = new URL(`${base}/oauth2/authorize`);
|
|
44
|
+
const url = new URL(choicePage ? HQ_CHOICE_PAGE_URL : `${base}/oauth2/authorize`);
|
|
27
45
|
url.search = new URLSearchParams({
|
|
28
46
|
client_id: config.clientId,
|
|
29
47
|
response_type: "code",
|
|
@@ -35,7 +53,7 @@ export async function loginWithBrowserPreference(requested, browser = true) {
|
|
|
35
53
|
}).toString();
|
|
36
54
|
if (config.identityProvider)
|
|
37
55
|
url.searchParams.set("identity_provider", config.identityProvider);
|
|
38
|
-
if (config.prompt)
|
|
56
|
+
if (config.prompt && !choicePage)
|
|
39
57
|
url.searchParams.set("prompt", config.prompt);
|
|
40
58
|
const code = await new Promise((resolve, reject) => {
|
|
41
59
|
let settled = false;
|
|
@@ -76,15 +94,21 @@ export async function loginWithBrowserPreference(requested, browser = true) {
|
|
|
76
94
|
let attempts = 0;
|
|
77
95
|
let listening = 0;
|
|
78
96
|
let lastError;
|
|
97
|
+
let ipv4Error;
|
|
79
98
|
const ready = () => {
|
|
80
99
|
if (++attempts !== servers.length)
|
|
81
100
|
return;
|
|
82
|
-
if (!listening) {
|
|
83
|
-
finish(lastError ?? new Error("Cannot bind login callback port"));
|
|
101
|
+
if (!listening || (openBrowser && ipv4Error)) {
|
|
102
|
+
finish(ipv4Error ?? lastError ?? new Error("Cannot bind login callback port"));
|
|
84
103
|
return;
|
|
85
104
|
}
|
|
86
105
|
try {
|
|
87
106
|
assertHumanLoginAllowed();
|
|
107
|
+
if (openBrowser) {
|
|
108
|
+
console.log(`Opening browser for HQ sign-in. If your browser doesn't open, visit:\n${url.toString()}`);
|
|
109
|
+
open(url.toString()).catch(() => undefined);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
88
112
|
console.log(`Open this URL to sign in:\n${url.toString()}`);
|
|
89
113
|
console.log(`Waiting for sign-in. For a remote host, forward local port ${port} to this host's port ${port} before opening the URL.`);
|
|
90
114
|
}
|
|
@@ -93,7 +117,8 @@ export async function loginWithBrowserPreference(requested, browser = true) {
|
|
|
93
117
|
}
|
|
94
118
|
};
|
|
95
119
|
servers.forEach((server, index) => {
|
|
96
|
-
server.once("error", (error) => { lastError = error;
|
|
120
|
+
server.once("error", (error) => { lastError = error; if (index === 0)
|
|
121
|
+
ipv4Error = error; ready(); });
|
|
97
122
|
server.listen(port, index === 0 ? "127.0.0.1" : "::1", () => { listening++; ready(); });
|
|
98
123
|
});
|
|
99
124
|
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import * as childProcess from "node:child_process";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import type { SpawnPlan } from "./windows-spawn.js";
|
|
4
|
+
export type SpawnDetachedHiddenDeps = {
|
|
5
|
+
platform: NodeJS.Platform;
|
|
6
|
+
spawn: typeof childProcess.spawn;
|
|
7
|
+
writeFileSync: typeof fs.writeFileSync;
|
|
8
|
+
rmSync: typeof fs.rmSync;
|
|
9
|
+
existsSync: (candidate: string) => boolean;
|
|
10
|
+
tmpdir: () => string;
|
|
11
|
+
pid: number;
|
|
12
|
+
now: () => number;
|
|
13
|
+
randomHex: () => string;
|
|
14
|
+
env: NodeJS.ProcessEnv;
|
|
15
|
+
cwd: string;
|
|
16
|
+
};
|
|
17
|
+
/** Join a spawn plan into one CreateProcess command line. */
|
|
18
|
+
export declare function commandLineFromSpawnPlan(plan: SpawnPlan): string;
|
|
19
|
+
/** wscript exit codes set by the launcher script (diagnostic only). */
|
|
20
|
+
export declare const HIDDEN_LAUNCH_EXIT: {
|
|
21
|
+
/** Win32_Process.Create returned 0. */
|
|
22
|
+
readonly created: 0;
|
|
23
|
+
/** WMI setup or Create failed; ShellExecute was called. It reports no result, so this is not proof of launch. */
|
|
24
|
+
readonly shellExecuteAttempted: 2;
|
|
25
|
+
/** WMI failed and the fallback file does not exist; nothing was started. */
|
|
26
|
+
readonly failed: 3;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Build the launcher script. It holds only the command line and cwd; the
|
|
30
|
+
* environment is read at run time from wscript's own process env, which
|
|
31
|
+
* Node sets to the caller's env. No env value is written to disk.
|
|
32
|
+
*
|
|
33
|
+
* WScript.Shell.Run expands %VAR% in the command string at run time.
|
|
34
|
+
* Win32_Process.Create uses CreateProcess, so percent signs stay literal.
|
|
35
|
+
*
|
|
36
|
+
* WMI starts the process from WmiPrvSE.exe, so the child inherits neither
|
|
37
|
+
* this script's working directory nor its environment. The cwd is passed as
|
|
38
|
+
* CurrentDirectory. Win32_ProcessStartup.EnvironmentVariables is merged with
|
|
39
|
+
* the system and user environment, and the values passed here win on a name
|
|
40
|
+
* clash (checked on Windows 11 for PATH, TEMP and a user-scope variable).
|
|
41
|
+
*
|
|
42
|
+
* If any WMI setup step fails, Create is skipped. Only rc = 0 from Create
|
|
43
|
+
* counts as started. Otherwise the script calls ShellExecute with SW_HIDE
|
|
44
|
+
* (inheriting wscript's env), and only for a file that exists, because
|
|
45
|
+
* ShellExecute opens a blocking "cannot find" dialog for a missing one.
|
|
46
|
+
* The script deletes itself on every path.
|
|
47
|
+
*/
|
|
48
|
+
export declare function hiddenCreateProcessScript(plan: SpawnPlan, cwd: string): string;
|
|
49
|
+
/**
|
|
50
|
+
* Start a process that outlives this one without a Windows console.
|
|
51
|
+
*
|
|
52
|
+
* `detached: true` sets DETACHED_PROCESS, and Windows then ignores
|
|
53
|
+
* CREATE_NO_WINDOW (`windowsHide`). Spawning `hq.cmd` that way flashes
|
|
54
|
+
* cmd.exe / node consoles on every checkpoint-stop-gate job. Dropping
|
|
55
|
+
* `detached` is not an option: libuv puts non-detached children in a
|
|
56
|
+
* kill-on-close job object, so the job would die with this process.
|
|
57
|
+
*
|
|
58
|
+
* On Windows, launch GUI `wscript.exe` (no console of its own) with the
|
|
59
|
+
* caller's env, and let WMI Win32_Process.Create start the real command
|
|
60
|
+
* hidden with that env and cwd (CreateProcess, so %VAR% is not expanded).
|
|
61
|
+
* The path is chosen synchronously: if wscript.exe is missing or the spawn
|
|
62
|
+
* throws, use the plain detached spawn. The caller usually exits right
|
|
63
|
+
* after this returns, so nothing here depends on later child events.
|
|
64
|
+
*/
|
|
65
|
+
export declare function spawnDetachedHidden(plan: SpawnPlan, env: NodeJS.ProcessEnv, deps?: SpawnDetachedHiddenDeps): void;
|
|
66
|
+
//# sourceMappingURL=spawn-detached-hidden.d.ts.map
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import * as childProcess from "node:child_process";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
const defaultDeps = () => ({
|
|
6
|
+
platform: process.platform,
|
|
7
|
+
spawn: childProcess.spawn,
|
|
8
|
+
writeFileSync: fs.writeFileSync,
|
|
9
|
+
rmSync: fs.rmSync,
|
|
10
|
+
existsSync: fs.existsSync,
|
|
11
|
+
tmpdir: os.tmpdir,
|
|
12
|
+
pid: process.pid,
|
|
13
|
+
now: () => Date.now(),
|
|
14
|
+
randomHex: () => Math.random().toString(16).slice(2),
|
|
15
|
+
env: process.env,
|
|
16
|
+
cwd: process.cwd(),
|
|
17
|
+
});
|
|
18
|
+
/** Quote a program path for a command line unless it is already quoted. */
|
|
19
|
+
function quoteProgram(value) {
|
|
20
|
+
if (value.startsWith('"') || !/\s/.test(value))
|
|
21
|
+
return value;
|
|
22
|
+
return `"${value}"`;
|
|
23
|
+
}
|
|
24
|
+
/** Join a spawn plan into one CreateProcess command line. */
|
|
25
|
+
export function commandLineFromSpawnPlan(plan) {
|
|
26
|
+
if (plan.shell || plan.windowsVerbatimArguments) {
|
|
27
|
+
return [quoteProgram(plan.cmd), ...plan.args].join(" ");
|
|
28
|
+
}
|
|
29
|
+
return [quoteWinArg(plan.cmd), ...plan.args.map(quoteWinArg)].join(" ");
|
|
30
|
+
}
|
|
31
|
+
function quoteWinArg(value) {
|
|
32
|
+
if (value === "")
|
|
33
|
+
return '""';
|
|
34
|
+
if (!/[\s"]/.test(value))
|
|
35
|
+
return value;
|
|
36
|
+
return `"${value.replace(/(\\*)"/g, "$1$1\\\"").replace(/(\\+)$/, "$1$1")}"`;
|
|
37
|
+
}
|
|
38
|
+
function vbsStringLiteral(value) {
|
|
39
|
+
if (/[\r\n\0]/.test(value)) {
|
|
40
|
+
throw Object.assign(new Error("Windows hidden spawn cannot accept newline or NUL in the command line"), {
|
|
41
|
+
code: "EINVAL",
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return `"${value.replace(/"/g, '""')}"`;
|
|
45
|
+
}
|
|
46
|
+
function systemRoot(env) {
|
|
47
|
+
return (env.SystemRoot || env.SYSTEMROOT || env.windir || env.WINDIR || "C:\\Windows").replace(/[\\/]+$/, "");
|
|
48
|
+
}
|
|
49
|
+
function wscriptPath(env) {
|
|
50
|
+
return path.win32.join(systemRoot(env), "System32", "wscript.exe");
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Resolve a bare `cmd.exe` (COMSPEC unset) to %SystemRoot%\System32\cmd.exe,
|
|
54
|
+
* so CreateProcess and the FileExists check see a real path.
|
|
55
|
+
*/
|
|
56
|
+
function withResolvedCmd(plan, env) {
|
|
57
|
+
if (!/^(?:cmd|cmd\.exe)$/i.test(plan.cmd))
|
|
58
|
+
return plan;
|
|
59
|
+
return { ...plan, cmd: path.win32.join(systemRoot(env), "System32", "cmd.exe") };
|
|
60
|
+
}
|
|
61
|
+
/** Split a plan into the file and parameters for Shell.Application.ShellExecute. */
|
|
62
|
+
function shellExecuteParts(plan) {
|
|
63
|
+
const file = plan.cmd.replace(/^"(.*)"$/, "$1");
|
|
64
|
+
if (plan.shell || plan.windowsVerbatimArguments)
|
|
65
|
+
return { file, parameters: plan.args.join(" ") };
|
|
66
|
+
return { file, parameters: plan.args.map(quoteWinArg).join(" ") };
|
|
67
|
+
}
|
|
68
|
+
/** wscript exit codes set by the launcher script (diagnostic only). */
|
|
69
|
+
export const HIDDEN_LAUNCH_EXIT = {
|
|
70
|
+
/** Win32_Process.Create returned 0. */
|
|
71
|
+
created: 0,
|
|
72
|
+
/** WMI setup or Create failed; ShellExecute was called. It reports no result, so this is not proof of launch. */
|
|
73
|
+
shellExecuteAttempted: 2,
|
|
74
|
+
/** WMI failed and the fallback file does not exist; nothing was started. */
|
|
75
|
+
failed: 3,
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Build the launcher script. It holds only the command line and cwd; the
|
|
79
|
+
* environment is read at run time from wscript's own process env, which
|
|
80
|
+
* Node sets to the caller's env. No env value is written to disk.
|
|
81
|
+
*
|
|
82
|
+
* WScript.Shell.Run expands %VAR% in the command string at run time.
|
|
83
|
+
* Win32_Process.Create uses CreateProcess, so percent signs stay literal.
|
|
84
|
+
*
|
|
85
|
+
* WMI starts the process from WmiPrvSE.exe, so the child inherits neither
|
|
86
|
+
* this script's working directory nor its environment. The cwd is passed as
|
|
87
|
+
* CurrentDirectory. Win32_ProcessStartup.EnvironmentVariables is merged with
|
|
88
|
+
* the system and user environment, and the values passed here win on a name
|
|
89
|
+
* clash (checked on Windows 11 for PATH, TEMP and a user-scope variable).
|
|
90
|
+
*
|
|
91
|
+
* If any WMI setup step fails, Create is skipped. Only rc = 0 from Create
|
|
92
|
+
* counts as started. Otherwise the script calls ShellExecute with SW_HIDE
|
|
93
|
+
* (inheriting wscript's env), and only for a file that exists, because
|
|
94
|
+
* ShellExecute opens a blocking "cannot find" dialog for a missing one.
|
|
95
|
+
* The script deletes itself on every path.
|
|
96
|
+
*/
|
|
97
|
+
export function hiddenCreateProcessScript(plan, cwd) {
|
|
98
|
+
const commandLine = vbsStringLiteral(commandLineFromSpawnPlan(plan));
|
|
99
|
+
const directory = vbsStringLiteral(cwd);
|
|
100
|
+
const fallback = shellExecuteParts(plan);
|
|
101
|
+
return [
|
|
102
|
+
"Option Explicit",
|
|
103
|
+
"Dim sh, svc, cfg, pid, rc, code, env, n, item, ready",
|
|
104
|
+
`code = ${HIDDEN_LAUNCH_EXIT.failed}`,
|
|
105
|
+
"rc = -1",
|
|
106
|
+
"ready = False",
|
|
107
|
+
"n = 0",
|
|
108
|
+
"ReDim env(-1)",
|
|
109
|
+
"On Error Resume Next",
|
|
110
|
+
'Set sh = CreateObject("WScript.Shell")',
|
|
111
|
+
'For Each item In sh.Environment("PROCESS")',
|
|
112
|
+
' If Len(item) > 0 And Left(item, 1) <> "=" Then',
|
|
113
|
+
" ReDim Preserve env(n)",
|
|
114
|
+
" env(n) = item",
|
|
115
|
+
" n = n + 1",
|
|
116
|
+
" End If",
|
|
117
|
+
"Next",
|
|
118
|
+
'Set svc = GetObject("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2")',
|
|
119
|
+
'Set cfg = svc.Get("Win32_ProcessStartup").SpawnInstance_',
|
|
120
|
+
"cfg.ShowWindow = 0",
|
|
121
|
+
"cfg.EnvironmentVariables = env",
|
|
122
|
+
"If Err.Number = 0 And n > 0 Then ready = True",
|
|
123
|
+
"Err.Clear",
|
|
124
|
+
"If ready Then",
|
|
125
|
+
" Err.Clear",
|
|
126
|
+
` rc = svc.Get("Win32_Process").Create(${commandLine}, ${directory}, cfg, pid)`,
|
|
127
|
+
"End If",
|
|
128
|
+
"Err.Clear",
|
|
129
|
+
"If rc = 0 Then",
|
|
130
|
+
` code = ${HIDDEN_LAUNCH_EXIT.created}`,
|
|
131
|
+
`ElseIf CreateObject("Scripting.FileSystemObject").FileExists(${vbsStringLiteral(fallback.file)}) Then`,
|
|
132
|
+
` CreateObject("Shell.Application").ShellExecute ${vbsStringLiteral(fallback.file)}, ${vbsStringLiteral(fallback.parameters)}, ${directory}, "open", 0`,
|
|
133
|
+
` code = ${HIDDEN_LAUNCH_EXIT.shellExecuteAttempted}`,
|
|
134
|
+
"End If",
|
|
135
|
+
"Err.Clear",
|
|
136
|
+
'CreateObject("Scripting.FileSystemObject").DeleteFile WScript.ScriptFullName, True',
|
|
137
|
+
"WScript.Quit code",
|
|
138
|
+
"",
|
|
139
|
+
].join("\r\n");
|
|
140
|
+
}
|
|
141
|
+
function spawnDetachedDirect(plan, env, deps) {
|
|
142
|
+
const child = deps.spawn(plan.cmd, plan.args, {
|
|
143
|
+
detached: true,
|
|
144
|
+
windowsHide: true,
|
|
145
|
+
stdio: "ignore",
|
|
146
|
+
env,
|
|
147
|
+
cwd: deps.cwd,
|
|
148
|
+
shell: plan.shell,
|
|
149
|
+
...(plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
|
150
|
+
});
|
|
151
|
+
child.once("error", (error) => {
|
|
152
|
+
process.stderr.write(`${error.message}\n`);
|
|
153
|
+
});
|
|
154
|
+
child.unref();
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Start a process that outlives this one without a Windows console.
|
|
158
|
+
*
|
|
159
|
+
* `detached: true` sets DETACHED_PROCESS, and Windows then ignores
|
|
160
|
+
* CREATE_NO_WINDOW (`windowsHide`). Spawning `hq.cmd` that way flashes
|
|
161
|
+
* cmd.exe / node consoles on every checkpoint-stop-gate job. Dropping
|
|
162
|
+
* `detached` is not an option: libuv puts non-detached children in a
|
|
163
|
+
* kill-on-close job object, so the job would die with this process.
|
|
164
|
+
*
|
|
165
|
+
* On Windows, launch GUI `wscript.exe` (no console of its own) with the
|
|
166
|
+
* caller's env, and let WMI Win32_Process.Create start the real command
|
|
167
|
+
* hidden with that env and cwd (CreateProcess, so %VAR% is not expanded).
|
|
168
|
+
* The path is chosen synchronously: if wscript.exe is missing or the spawn
|
|
169
|
+
* throws, use the plain detached spawn. The caller usually exits right
|
|
170
|
+
* after this returns, so nothing here depends on later child events.
|
|
171
|
+
*/
|
|
172
|
+
export function spawnDetachedHidden(plan, env, deps = defaultDeps()) {
|
|
173
|
+
const childEnv = env;
|
|
174
|
+
if (deps.platform !== "win32") {
|
|
175
|
+
spawnDetachedDirect(plan, childEnv, deps);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const resolved = withResolvedCmd(plan, childEnv);
|
|
179
|
+
const wscript = wscriptPath(childEnv);
|
|
180
|
+
if (!deps.existsSync(wscript)) {
|
|
181
|
+
spawnDetachedDirect(resolved, childEnv, deps);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const scriptPath = path.join(deps.tmpdir(), `hq-hidden.${deps.pid}.${deps.now()}.${deps.randomHex()}.vbs`);
|
|
185
|
+
const removeScript = () => {
|
|
186
|
+
try {
|
|
187
|
+
deps.rmSync(scriptPath, { force: true });
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
// Best effort; the script normally deletes itself.
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
// WSH reads a BOM-less file in the ANSI code page, so a path with
|
|
194
|
+
// non-ASCII characters (José, etc.) would garble. UTF-16LE with BOM
|
|
195
|
+
// is the encoding WSH treats as Unicode.
|
|
196
|
+
deps.writeFileSync(scriptPath, `\uFEFF${hiddenCreateProcessScript(resolved, deps.cwd)}`, {
|
|
197
|
+
encoding: "utf16le",
|
|
198
|
+
});
|
|
199
|
+
let child;
|
|
200
|
+
try {
|
|
201
|
+
child = deps.spawn(wscript, ["//B", "//Nologo", scriptPath], {
|
|
202
|
+
detached: true,
|
|
203
|
+
windowsHide: true,
|
|
204
|
+
stdio: "ignore",
|
|
205
|
+
env: childEnv,
|
|
206
|
+
cwd: deps.cwd,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
removeScript();
|
|
211
|
+
spawnDetachedDirect(resolved, childEnv, deps);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
child.once("error", (error) => {
|
|
215
|
+
// wscript did not start (nothing was launched). Clean up if we are
|
|
216
|
+
// still alive; the synchronous existsSync check is the primary guard.
|
|
217
|
+
removeScript();
|
|
218
|
+
process.stderr.write(`${error.message}\n`);
|
|
219
|
+
});
|
|
220
|
+
child.unref();
|
|
221
|
+
}
|
|
222
|
+
//# sourceMappingURL=spawn-detached-hidden.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@indigoai-us/hq-cli",
|
|
3
|
-
"version": "5.345.
|
|
3
|
+
"version": "5.345.272",
|
|
4
4
|
"description": "HQ by Indigo management CLI — modules and cloud sync",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|
|
@@ -128,11 +128,11 @@
|
|
|
128
128
|
"*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}": "eslint --cache --no-error-on-unmatched-pattern"
|
|
129
129
|
},
|
|
130
130
|
"optionalDependencies": {
|
|
131
|
-
"@indigoai-us/hq-hook-win32-x64": "5.345.
|
|
132
|
-
"@indigoai-us/hq-hook-win32-arm64": "5.345.
|
|
133
|
-
"@indigoai-us/hq-hook-darwin-x64": "5.345.
|
|
134
|
-
"@indigoai-us/hq-hook-darwin-arm64": "5.345.
|
|
135
|
-
"@indigoai-us/hq-hook-linux-x64": "5.345.
|
|
136
|
-
"@indigoai-us/hq-hook-linux-arm64": "5.345.
|
|
131
|
+
"@indigoai-us/hq-hook-win32-x64": "5.345.272",
|
|
132
|
+
"@indigoai-us/hq-hook-win32-arm64": "5.345.272",
|
|
133
|
+
"@indigoai-us/hq-hook-darwin-x64": "5.345.272",
|
|
134
|
+
"@indigoai-us/hq-hook-darwin-arm64": "5.345.272",
|
|
135
|
+
"@indigoai-us/hq-hook-linux-x64": "5.345.272",
|
|
136
|
+
"@indigoai-us/hq-hook-linux-arm64": "5.345.272"
|
|
137
137
|
}
|
|
138
138
|
}
|