@bitkyc08/opencodex 2.96.0 → 2.97.0
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/bin/ocx.mjs +214 -19
- package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
- package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
- package/gui/dist/assets/index-CynE_Rue.js +94 -0
- package/gui/dist/assets/{quota-summary-6HsrHQAy.js → quota-summary-VHFSlUuM.js} +1 -1
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/command-code.ts +15 -16
- package/src/adapters/cursor/transport-retry.ts +2 -2
- package/src/adapters/devin/cloud-direct/chat.ts +15 -6
- package/src/adapters/kiro/stream.ts +63 -4
- package/src/adapters/kiro-constants.ts +15 -1
- package/src/adapters/kiro-events.ts +31 -1
- package/src/adapters/kiro-retry.ts +3 -3
- package/src/adapters/ollama-native.ts +11 -1
- package/src/adapters/openai-responses/empty-assistant.ts +15 -3
- package/src/adapters/openai-responses/passthrough.ts +5 -4
- package/src/adapters/openai-responses/reasoning.ts +9 -4
- package/src/adapters/openai-responses/request-strips.ts +1 -1
- package/src/adapters/physical-send.ts +3 -3
- package/src/adapters/zed-openai-stream.ts +2 -1
- package/src/bridge/errors.ts +11 -2
- package/src/bridge/response-json.ts +2 -1
- package/src/bridge/sse.ts +14 -6
- package/src/chat/failure-verdict.ts +21 -0
- package/src/chat/outbound.ts +139 -21
- package/src/claude/outbound.ts +49 -2
- package/src/cli/capabilities-base.ts +25 -3
- package/src/cli/capabilities-command.ts +12 -3
- package/src/cli/capability-contracts.ts +2 -0
- package/src/cli/codex-launch-auth.ts +30 -1
- package/src/cli/codex-launcher.ts +12 -5
- package/src/cli/codex-shim-autorestore.ts +5 -4
- package/src/cli/dispatch.ts +11 -176
- package/src/cli/help.ts +2 -2
- package/src/cli/index.ts +5 -1
- package/src/cli/link.ts +1 -1
- package/src/cli/registry.ts +11 -3
- package/src/cli/root.ts +8 -0
- package/src/cli/sync-command.ts +243 -0
- package/src/cli/sync-fanout-process.ts +92 -0
- package/src/cli/sync-fanout.ts +150 -0
- package/src/cli/sync-flags.ts +10 -0
- package/src/cli/sync-link-status.ts +39 -0
- package/src/cli/sync-update-guard.ts +18 -0
- package/src/client/connect.ts +31 -14
- package/src/client/link-home.ts +3 -2
- package/src/client/machine-listener.ts +3 -0
- package/src/client/restore-ownership.ts +19 -1
- package/src/client/runtime-restart.ts +12 -4
- package/src/client/runtime.ts +40 -11
- package/src/client/stop-routing.ts +62 -0
- package/src/client/sync-runtime.ts +65 -0
- package/src/clients/config-export.ts +32 -3
- package/src/codex/auth-context.ts +49 -103
- package/src/codex/catalog/antigravity-discovery.ts +16 -5
- package/src/codex/catalog/provider-models.ts +6 -8
- package/src/codex/forward-transport-headers.ts +35 -6
- package/src/codex/inject/config-toml.ts +88 -0
- package/src/codex/inject/multi-agent-v2.ts +30 -4
- package/src/codex/inject/plan.ts +34 -7
- package/src/codex/inject-coordination.ts +11 -0
- package/src/codex/inject.ts +18 -7
- package/src/codex/lineage.ts +13 -7
- package/src/codex/quota.ts +22 -6
- package/src/codex/request-owned-affinity-key.ts +11 -0
- package/src/codex/request-owned-affinity.ts +118 -0
- package/src/codex/request-owned-main-pin.ts +86 -0
- package/src/codex/role-capability.ts +52 -41
- package/src/codex/routing/active-account.ts +13 -5
- package/src/codex/routing/selection.ts +40 -1
- package/src/codex/routing/thread-affinity-store.ts +916 -0
- package/src/codex/routing/thread-affinity.ts +90 -12
- package/src/codex/toml-source-lines.ts +72 -13
- package/src/combos/failover.ts +6 -109
- package/src/combos/request.ts +2 -2
- package/src/combos/resolve.ts +29 -11
- package/src/config/process-state.ts +5 -0
- package/src/config/schema/leaf-validators.ts +1 -0
- package/src/generated/compatibility-version.json +433 -165
- package/src/images/loop.ts +2 -1
- package/src/lib/client-error-body.ts +184 -0
- package/src/lib/client-retry-after.ts +66 -0
- package/src/lib/config-ownership.ts +4 -0
- package/src/lib/context-overflow-verdict.ts +113 -0
- package/src/lib/desktop-cli-handoff.d.mts +1 -1
- package/src/lib/desktop-cli-handoff.mjs +11 -1
- package/src/lib/empty-tool-catalog.ts +25 -3
- package/src/lib/error-destination.ts +47 -0
- package/src/lib/failure-detail.ts +66 -0
- package/src/lib/model-identity.ts +44 -0
- package/src/lib/private-sqlite-path.ts +124 -0
- package/src/lib/response-service-tier.ts +17 -0
- package/src/lib/retry-after.ts +3 -0
- package/src/lib/spend-ledger-owner.ts +43 -4
- package/src/lib/upstream-condition.ts +142 -0
- package/src/lib/upstream-retry.ts +14 -11
- package/src/lib/windows-owner-acl.ts +13 -6
- package/src/link/remote-platform.ts +14 -0
- package/src/link/remote-windows.ts +51 -9
- package/src/link/ssh-argv.ts +63 -10
- package/src/oauth/generic-account-failover.ts +13 -11
- package/src/oauth/index.ts +36 -74
- package/src/oauth/oauth-errors.ts +67 -0
- package/src/oauth/store.ts +1 -1
- package/src/protocols/codecs/ollama.ts +197 -0
- package/src/protocols/encoders/adapter-events.ts +4 -0
- package/src/protocols/encoders/chat.ts +18 -10
- package/src/protocols/trace.ts +18 -0
- package/src/providers/fastwire.ts +3 -2
- package/src/providers/quota/anthropic-usage-windows.ts +13 -3
- package/src/providers/quota/vendor-probes-key.ts +60 -24
- package/src/providers/request-pacing.ts +3 -2
- package/src/responses/apply-patch-envelope.ts +45 -19
- package/src/responses/compaction-history-framing.ts +5 -1
- package/src/responses/freeform-wrapper-scan.ts +5 -3
- package/src/responses/progressive-freeform-input.ts +354 -45
- package/src/routing/fallback-policy.ts +3 -1
- package/src/server/admission-model-scope.ts +17 -6
- package/src/server/admitted-http-turn.ts +56 -0
- package/src/server/auth-cors.ts +5 -0
- package/src/server/chat-completions.ts +45 -20
- package/src/server/chat-native-sse.ts +52 -7
- package/src/server/chat-native.ts +60 -35
- package/src/server/claude-bridge-pool-session.ts +59 -0
- package/src/server/claude-messages.ts +51 -24
- package/src/server/context-history.ts +5 -1
- package/src/server/inbound-body-admission.ts +11 -4
- package/src/server/index/ollama-routes.ts +89 -0
- package/src/server/index/serve-options.ts +21 -4
- package/src/server/index/websocket-handler.ts +4 -2
- package/src/server/index.ts +6 -36
- package/src/server/inference/client-encoder-delivery.ts +4 -2
- package/src/server/json-serialized-bytes.ts +44 -0
- package/src/server/management/agent-settings-routes.ts +24 -21
- package/src/server/management/codex-cli-update-routes.ts +2 -1
- package/src/server/management/route-registry.ts +1 -1
- package/src/server/messages-native-scope.ts +2 -1
- package/src/server/messages-native-tool-guard.ts +1 -1
- package/src/server/messages-native.ts +12 -7
- package/src/server/messages-shared.ts +6 -2
- package/src/server/native-final-log.ts +93 -0
- package/src/server/ollama-inbound.ts +349 -0
- package/src/server/ollama-native-paths.ts +21 -0
- package/src/server/ollama-route-policy.ts +73 -0
- package/src/server/relay.ts +22 -3
- package/src/server/request-decompress.ts +4 -2
- package/src/server/request-log-failure-attribution.ts +22 -0
- package/src/server/request-log-failure-detail.ts +80 -0
- package/src/server/request-log-terminal-status.ts +4 -2
- package/src/server/request-log.ts +79 -42
- package/src/server/response-log-body.ts +6 -1
- package/src/server/responses/account-change-state.ts +17 -6
- package/src/server/responses/adapter-continuation.ts +9 -4
- package/src/server/responses/adapter-delivery.ts +5 -4
- package/src/server/responses/adapter-dispatch.ts +31 -30
- package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
- package/src/server/responses/codex-auth-error.ts +19 -18
- package/src/server/responses/codex-ws-exchange.ts +11 -8
- package/src/server/responses/codex-ws-metadata.ts +94 -21
- package/src/server/responses/codex-ws-request.ts +3 -1
- package/src/server/responses/compact.ts +53 -23
- package/src/server/responses/compaction-recovery.ts +4 -2
- package/src/server/responses/compaction-routing.ts +9 -4
- package/src/server/responses/core-auth.ts +32 -14
- package/src/server/responses/core-codex-account.ts +17 -6
- package/src/server/responses/core-combo-failure.ts +5 -1
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +41 -27
- package/src/server/responses/core-errors.ts +22 -20
- package/src/server/responses/core-lifetime.ts +6 -3
- package/src/server/responses/core-normalize.ts +1 -0
- package/src/server/responses/core-options.ts +7 -0
- package/src/server/responses/core-pipeline.ts +4 -3
- package/src/server/responses/fetch-helpers.ts +7 -1
- package/src/server/responses/input-admission.ts +28 -2
- package/src/server/responses/native-injection.ts +1 -1
- package/src/server/responses/native-response-json.ts +13 -4
- package/src/server/responses/native-response-output.ts +1 -2
- package/src/server/responses/non-replayable-error.ts +2 -1
- package/src/server/responses/pacing-overload.ts +3 -2
- package/src/server/responses/passthrough-delivery.ts +55 -14
- package/src/server/responses/passthrough-dispatch.ts +19 -17
- package/src/server/responses/passthrough-error.ts +9 -9
- package/src/server/responses/policy-fallback.ts +2 -1
- package/src/server/responses/request-prepare.ts +67 -48
- package/src/server/responses/request-transport.ts +35 -31
- package/src/server/responses/run-turn-execution.ts +6 -6
- package/src/server/responses/sidecar-execution.ts +16 -12
- package/src/server/responses/spend-storage-error.ts +2 -1
- package/src/server/responses/ws-upstream.ts +9 -0
- package/src/server/responses-custom-tool-repair.ts +14 -3
- package/src/server/responses-terminal-repair.ts +5 -2
- package/src/server/responses-undeclared-tool-guard.ts +39 -16
- package/src/server/safe-response-headers.ts +162 -13
- package/src/server/turn-state-handles.ts +164 -0
- package/src/server/workflow-refusal.ts +2 -1
- package/src/service/ownership-mutation-lease.d.mts +11 -2
- package/src/service/ownership-mutation-lease.mjs +53 -11
- package/src/types/config.ts +2 -0
- package/src/update/index.ts +133 -25
- package/src/update/npm-install.d.mts +8 -0
- package/src/update/npm-install.mjs +20 -1
- package/src/update/orchestrated-admission.d.mts +4 -0
- package/src/update/orchestrated-admission.mjs +12 -0
- package/src/update/orchestrated-arguments.d.mts +12 -0
- package/src/update/orchestrated-arguments.mjs +64 -0
- package/src/update/orchestrated-child.d.mts +12 -0
- package/src/update/orchestrated-child.mjs +70 -0
- package/src/update/orchestrated-entry.ts +234 -0
- package/src/update/orchestrated-identity-probe-entry.ts +20 -0
- package/src/update/orchestrated-identity.ts +53 -0
- package/src/update/orchestrated-live-identity.ts +48 -0
- package/src/update/orchestrated-node-driver.mjs +99 -0
- package/src/update/orchestrated-outcome.d.mts +21 -0
- package/src/update/orchestrated-outcome.mjs +40 -0
- package/src/update/orchestrated-plan.ts +49 -0
- package/src/update/orchestrated-pnpm.d.mts +8 -0
- package/src/update/orchestrated-pnpm.mjs +33 -0
- package/src/update/orchestrated-session.d.mts +37 -0
- package/src/update/orchestrated-session.mjs +264 -0
- package/src/update/orchestrated-token.d.mts +10 -0
- package/src/update/orchestrated-token.mjs +21 -0
- package/src/update/orchestrated-token.ts +3 -0
- package/src/update/orchestrated-tree.d.mts +1 -0
- package/src/update/orchestrated-tree.mjs +14 -0
- package/src/update/pnpm-global-install.d.mts +6 -0
- package/src/update/pnpm-global-install.mjs +9 -2
- package/src/update/posix-install-supervisor-entry.mjs +6 -0
- package/src/update/posix-install-supervisor.d.mts +10 -0
- package/src/update/posix-install-supervisor.mjs +88 -0
- package/src/update/sync-update-mutex.d.mts +10 -0
- package/src/update/sync-update-mutex.mjs +164 -0
- package/src/update/sync-update-mutex.ts +1 -0
- package/src/update/test-home-guard.mjs +33 -0
- package/src/update/transactional-install.mjs +2 -2
- package/src/usage/error-detail.ts +225 -0
- package/src/usage/log.ts +60 -27
- package/src/web-search/loop.ts +31 -5
- package/gui/dist/assets/index-ebuVUtB7.js +0 -94
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { closeSync, lstatSync, openSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
/** The files SQLite opens next to a database: the rollback journal, and the WAL and its index. */
|
|
4
|
+
export const SQLITE_SIDECAR_SUFFIXES = ["-journal", "-wal", "-shm"] as const;
|
|
5
|
+
|
|
6
|
+
/** A database or sidecar name holds something other than a private regular file. Carries no path. */
|
|
7
|
+
export class UnsafeSqlitePathError extends Error {
|
|
8
|
+
constructor() {
|
|
9
|
+
super("SQLite storage path is not a private regular file");
|
|
10
|
+
this.name = "UnsafeSqlitePathError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const FILE_ATTRIBUTE_REPARSE_POINT = 0x400;
|
|
15
|
+
const INVALID_FILE_ATTRIBUTES = 0xffffffff;
|
|
16
|
+
type ReparseProbe = (path: string) => boolean;
|
|
17
|
+
let nativeAttributes: ((path: string) => number) | undefined;
|
|
18
|
+
let probeForTests: ReparseProbe | null = null;
|
|
19
|
+
/**
|
|
20
|
+
* Whether the native attribute query runs: on Windows, except ARM64, whose Bun build cannot execute
|
|
21
|
+
* `bun:ffi` (the limitation src/lib/windows-user-principal.ts works around). There `lstat` still
|
|
22
|
+
* reports symbolic links, junctions and app execution aliases as links; other reparse tags are not
|
|
23
|
+
* visible without native code.
|
|
24
|
+
*/
|
|
25
|
+
export function nativeReparseProbeApplies(platform: string, arch: string): boolean {
|
|
26
|
+
return platform === "win32" && arch !== "arm64";
|
|
27
|
+
}
|
|
28
|
+
// Read once at load: tests replace `process.platform` to drive Windows-only branches on POSIX, and
|
|
29
|
+
// the native query must follow the system the process actually runs on.
|
|
30
|
+
const NATIVE_ATTRIBUTES = nativeReparseProbeApplies(process.platform, process.arch);
|
|
31
|
+
|
|
32
|
+
function errorCode(error: unknown): unknown {
|
|
33
|
+
return error !== null && typeof error === "object" && "code" in error ? error.code : undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Whether the entry at `path` itself is a Windows reparse point: a symbolic link, a junction, or any
|
|
38
|
+
* other tag. `GetFileAttributesW` reports the named entry rather than what it points to, so this
|
|
39
|
+
* sees what `lstat` cannot classify. Throws when the attribute cannot be read.
|
|
40
|
+
*/
|
|
41
|
+
export function isWindowsReparsePoint(path: string): boolean {
|
|
42
|
+
if (!nativeAttributes) {
|
|
43
|
+
// Loaded on first use, only on Windows; the repository's other Windows file checks use the same call.
|
|
44
|
+
const ffi = require("bun:ffi") as typeof import("bun:ffi");
|
|
45
|
+
const kernel = ffi.dlopen("kernel32.dll", {
|
|
46
|
+
GetFileAttributesW: { args: [ffi.FFIType.ptr], returns: ffi.FFIType.u32 },
|
|
47
|
+
});
|
|
48
|
+
nativeAttributes = (name: string) => {
|
|
49
|
+
const wide = Buffer.from(`${name}\0`, "utf16le");
|
|
50
|
+
return kernel.symbols.GetFileAttributesW(ffi.ptr(wide)) >>> 0;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
const attributes = nativeAttributes(path);
|
|
54
|
+
if (attributes === INVALID_FILE_ATTRIBUTES) throw new Error("file attributes unavailable");
|
|
55
|
+
return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) !== 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Test seam: replace the reparse-point probe on every platform; null restores the default. */
|
|
59
|
+
export function setSqlitePathReparseProbeForTests(probe: ReparseProbe | null): void {
|
|
60
|
+
probeForTests = probe;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function isReparsePoint(path: string): boolean {
|
|
64
|
+
if (probeForTests) return probeForTests(path);
|
|
65
|
+
return NATIVE_ATTRIBUTES && isWindowsReparsePoint(path);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Refuse unless nothing is at `path` or it is a private regular file: not a link or other reparse
|
|
70
|
+
* point, not a directory, a single directory entry, and on POSIX owned by this user. Returns
|
|
71
|
+
* whether an entry exists. A probe that cannot answer refuses.
|
|
72
|
+
*/
|
|
73
|
+
export function assertPrivateSqliteEntryOrMissing(path: string): boolean {
|
|
74
|
+
let stat;
|
|
75
|
+
try {
|
|
76
|
+
stat = lstatSync(path);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (errorCode(error) === "ENOENT") return false;
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
let reparse: boolean;
|
|
82
|
+
try {
|
|
83
|
+
reparse = isReparsePoint(path);
|
|
84
|
+
} catch {
|
|
85
|
+
throw new UnsafeSqlitePathError();
|
|
86
|
+
}
|
|
87
|
+
if (
|
|
88
|
+
reparse
|
|
89
|
+
|| !stat.isFile()
|
|
90
|
+
|| stat.isSymbolicLink()
|
|
91
|
+
|| stat.nlink !== 1
|
|
92
|
+
|| (process.platform !== "win32" && stat.uid !== process.getuid!())
|
|
93
|
+
) throw new UnsafeSqlitePathError();
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Refuse unless every sidecar of `databasePath` is absent or a private regular file. SQLite's POSIX
|
|
99
|
+
* VFS opens them with O_NOFOLLOW; its Windows VFS opens them by name with CreateFileW, which follows
|
|
100
|
+
* a link planted there. Check before opening the database and before every write transaction: the
|
|
101
|
+
* rollback journal is created and deleted per transaction. Something planted after the check, while
|
|
102
|
+
* SQLite opens the file, is outside what this can see.
|
|
103
|
+
*/
|
|
104
|
+
export function assertPrivateSqliteSidecars(databasePath: string): void {
|
|
105
|
+
for (const suffix of SQLITE_SIDECAR_SUFFIXES) assertPrivateSqliteEntryOrMissing(databasePath + suffix);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Make sure `databasePath` is a private regular file without creating anything through a link at
|
|
110
|
+
* its name or at a sidecar's. POSIX O_CREAT|O_EXCL refuses a link at the final component, but
|
|
111
|
+
* Windows CREATE_NEW follows a dangling file symlink and creates its target, so every entry is
|
|
112
|
+
* checked before the create. An entry planted between the check and the create is not covered;
|
|
113
|
+
* callers check the file again after hardening it.
|
|
114
|
+
*/
|
|
115
|
+
export function preparePrivateSqliteDatabase(databasePath: string): void {
|
|
116
|
+
assertPrivateSqliteSidecars(databasePath);
|
|
117
|
+
if (assertPrivateSqliteEntryOrMissing(databasePath)) return;
|
|
118
|
+
try {
|
|
119
|
+
closeSync(openSync(databasePath, "wx", 0o600));
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
122
|
+
}
|
|
123
|
+
if (!assertPrivateSqliteEntryOrMissing(databasePath)) throw new UnsafeSqlitePathError();
|
|
124
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response service tiers a request-log row may record. A provider can return any string in
|
|
3
|
+
* `service_tier` (or an Anthropic `speed`), so only these closed members are kept; anything else
|
|
4
|
+
* is omitted. Pricing and Fast confirmation read the raw observation separately.
|
|
5
|
+
*/
|
|
6
|
+
export const RESPONSE_SERVICE_TIERS = ["auto", "default", "flex", "scale", "priority", "fast", "standard", "ultrafast"] as const;
|
|
7
|
+
|
|
8
|
+
export type ResponseServiceTier = typeof RESPONSE_SERVICE_TIERS[number];
|
|
9
|
+
|
|
10
|
+
const TIERS: ReadonlySet<string> = new Set(RESPONSE_SERVICE_TIERS);
|
|
11
|
+
|
|
12
|
+
/** The closed member a tier names (case-insensitive), or undefined. */
|
|
13
|
+
export function boundedServiceTier(value: unknown): ResponseServiceTier | undefined {
|
|
14
|
+
if (typeof value !== "string") return undefined;
|
|
15
|
+
const folded = value.trim().toLowerCase();
|
|
16
|
+
return TIERS.has(folded) ? folded as ResponseServiceTier : undefined;
|
|
17
|
+
}
|
package/src/lib/retry-after.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { parseRetryAfterMs } from "../combos";
|
|
2
2
|
import { classifyError, parseRetryAfterFromMessage } from "./errors";
|
|
3
|
+
import { formatClientRetryAfter } from "./client-retry-after";
|
|
4
|
+
|
|
5
|
+
export { formatClientRetryAfter, MAX_CLIENT_RETRY_AFTER_SECONDS } from "./client-retry-after";
|
|
3
6
|
|
|
4
7
|
/** Small default when a retryable 429 has no upstream Retry-After (#507). */
|
|
5
8
|
export const DEFAULT_RETRYABLE_429_RETRY_AFTER_SEC = "2";
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/** Process-lifetime single-writer ownership for the shared spend journal. */
|
|
2
2
|
import { Database } from "bun:sqlite";
|
|
3
|
-
import { chmodSync,
|
|
3
|
+
import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
|
|
4
4
|
import { join, resolve } from "node:path";
|
|
5
5
|
import { getConfigDir } from "../config/paths";
|
|
6
6
|
import { recordOwnedConfigPath } from "./config-ownership";
|
|
7
|
+
import { assertPrivateSqliteSidecars, preparePrivateSqliteDatabase } from "./private-sqlite-path";
|
|
7
8
|
import { assertNotRealHomeUnderTest } from "./test-home-guard";
|
|
8
9
|
import { hardenSecretDir, hardenSecretPath } from "./windows-secret-acl";
|
|
9
10
|
|
|
@@ -47,6 +48,26 @@ let boundLedgerHome: string | null = null;
|
|
|
47
48
|
*/
|
|
48
49
|
let ownerGeneration = 0;
|
|
49
50
|
const releaseHooks: Array<() => void> = [];
|
|
51
|
+
const acquiredHooks: Array<(home: string) => void> = [];
|
|
52
|
+
|
|
53
|
+
/** Run once after each new ownership generation is acquired. */
|
|
54
|
+
export function onSpendLedgerOwnerAcquired(hook: (home: string) => void): void {
|
|
55
|
+
acquiredHooks.push(hook);
|
|
56
|
+
}
|
|
57
|
+
const releasingHooks: Array<() => void> = [];
|
|
58
|
+
let releasing = false;
|
|
59
|
+
|
|
60
|
+
/** Run before the final lease is released, while existing storage tokens remain valid. */
|
|
61
|
+
export function onSpendLedgerOwnerReleasing(hook: () => void): void {
|
|
62
|
+
releasingHooks.push(hook);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function assertNotReleasing(): void {
|
|
66
|
+
if (releasing) throw new SpendLedgerOwnerError(
|
|
67
|
+
"SPEND_LEDGER_OWNER_NOT_HELD",
|
|
68
|
+
"Spend-ledger ownership is required before the shared ledger can be used.",
|
|
69
|
+
);
|
|
70
|
+
}
|
|
50
71
|
|
|
51
72
|
/**
|
|
52
73
|
* Run when the last lease on a state directory goes away.
|
|
@@ -95,8 +116,9 @@ function prepareOwnerPath(configDir: string): { home: string; path: string } {
|
|
|
95
116
|
// its sidecars were left behind by a later uninstall because nothing recorded them.
|
|
96
117
|
recordOwnedConfigPath(home, path);
|
|
97
118
|
for (const suffix of OWNER_SIDECARS) recordOwnedConfigPath(home, `${path}${suffix}`);
|
|
98
|
-
|
|
99
|
-
|
|
119
|
+
// Refuses a link or reparse point at the database or a sidecar before anything is created:
|
|
120
|
+
// Windows creates a new file through a link at its name.
|
|
121
|
+
preparePrivateSqliteDatabase(path);
|
|
100
122
|
assertPrivateFile(path);
|
|
101
123
|
if (process.platform !== "win32") chmodSync(path, 0o600);
|
|
102
124
|
hardenSecretPath(path, { required: true });
|
|
@@ -142,6 +164,7 @@ export function spendLedgerRestartEnvironment(
|
|
|
142
164
|
* can evict a live owner or mistake a reused process identity for this lease.
|
|
143
165
|
*/
|
|
144
166
|
export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedgerOwnerLease {
|
|
167
|
+
assertNotReleasing();
|
|
145
168
|
const requestedHome = stateDirectoryIdentity(configDir);
|
|
146
169
|
const busyTimeout = restartHandoffWaitMs();
|
|
147
170
|
if (boundLedgerHome !== null && boundLedgerHome !== requestedHome) {
|
|
@@ -175,6 +198,7 @@ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedger
|
|
|
175
198
|
|
|
176
199
|
let database: Database | undefined;
|
|
177
200
|
try {
|
|
201
|
+
assertPrivateSqliteSidecars(prepared.path);
|
|
178
202
|
database = new Database(prepared.path, { create: true });
|
|
179
203
|
database.exec(`PRAGMA locking_mode = NORMAL; PRAGMA busy_timeout = ${busyTimeout}; BEGIN IMMEDIATE`);
|
|
180
204
|
} catch (cause) {
|
|
@@ -194,7 +218,11 @@ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedger
|
|
|
194
218
|
|
|
195
219
|
activeOwner = { home: prepared.home, database, references: 1 };
|
|
196
220
|
ownerGeneration += 1;
|
|
197
|
-
|
|
221
|
+
const owner = activeOwner;
|
|
222
|
+
for (const hook of acquiredHooks) {
|
|
223
|
+
try { hook(owner.home); } catch { /* one hook must not prevent acquisition */ }
|
|
224
|
+
}
|
|
225
|
+
return leaseFor(owner);
|
|
198
226
|
}
|
|
199
227
|
|
|
200
228
|
function leaseFor(owner: ActiveOwner): SpendLedgerOwnerLease {
|
|
@@ -204,6 +232,16 @@ function leaseFor(owner: ActiveOwner): SpendLedgerOwnerLease {
|
|
|
204
232
|
if (released) return;
|
|
205
233
|
released = true;
|
|
206
234
|
if (activeOwner !== owner || owner.references < 1) return;
|
|
235
|
+
if (owner.references === 1) {
|
|
236
|
+
releasing = true;
|
|
237
|
+
try {
|
|
238
|
+
for (const hook of releasingHooks) {
|
|
239
|
+
try { hook(); } catch { /* a flush hook must not prevent release */ }
|
|
240
|
+
}
|
|
241
|
+
} finally {
|
|
242
|
+
releasing = false;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
207
245
|
owner.references -= 1;
|
|
208
246
|
if (owner.references > 0) return;
|
|
209
247
|
activeOwner = null;
|
|
@@ -265,6 +303,7 @@ function trustedStorage(storage: SpendLedgerStorage): { readonly path: string; r
|
|
|
265
303
|
* choose the destination, which is the thing ownership is supposed to decide.
|
|
266
304
|
*/
|
|
267
305
|
export function mintSpendLedgerStorage(fileName: string): SpendLedgerStorage {
|
|
306
|
+
assertNotReleasing();
|
|
268
307
|
if (fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") {
|
|
269
308
|
throw new SpendLedgerOwnerError(
|
|
270
309
|
"SPEND_LEDGER_OWNER_UNAVAILABLE",
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Presentation-only classification of an upstream failure into a small closed set of conditions.
|
|
3
|
+
*
|
|
4
|
+
* The output is what request logs and client-facing error text may name. It never carries input
|
|
5
|
+
* bytes: callers pass bounded structured tokens (status, type, code, reason) and optionally the
|
|
6
|
+
* upstream message, which is read here only through fixed lowercase keyword sets and never stored
|
|
7
|
+
* or returned. Routing, retry and recovery keep using their own classifiers (src/lib/errors.ts);
|
|
8
|
+
* this module must not feed them.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { isDefiniteContextOverflow } from "./context-overflow-verdict";
|
|
12
|
+
|
|
13
|
+
export const UPSTREAM_CONDITIONS = [
|
|
14
|
+
"auth_failed",
|
|
15
|
+
"access_denied",
|
|
16
|
+
"context_overflow",
|
|
17
|
+
"location_unsupported",
|
|
18
|
+
"account_verification_required",
|
|
19
|
+
"billing_exhausted",
|
|
20
|
+
"model_unavailable",
|
|
21
|
+
"rate_limited",
|
|
22
|
+
"upstream_unavailable",
|
|
23
|
+
"upstream_failed",
|
|
24
|
+
"request_rejected",
|
|
25
|
+
] as const;
|
|
26
|
+
|
|
27
|
+
export type UpstreamCondition = typeof UPSTREAM_CONDITIONS[number];
|
|
28
|
+
|
|
29
|
+
const CONDITION_SET: ReadonlySet<string> = new Set(UPSTREAM_CONDITIONS);
|
|
30
|
+
|
|
31
|
+
export function isUpstreamCondition(value: unknown): value is UpstreamCondition {
|
|
32
|
+
return typeof value === "string" && CONDITION_SET.has(value);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface UpstreamConditionEvidence {
|
|
36
|
+
status: number;
|
|
37
|
+
type?: string;
|
|
38
|
+
code?: string;
|
|
39
|
+
reason?: string;
|
|
40
|
+
message?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Structured tokens are compared after lowercasing; anything longer than this is not a token.
|
|
44
|
+
const MAX_TOKEN_LENGTH = 128;
|
|
45
|
+
// Keyword matching reads at most this much of the message.
|
|
46
|
+
const MAX_MESSAGE_SCAN = 4096;
|
|
47
|
+
|
|
48
|
+
const STRUCTURED: ReadonlyArray<readonly [UpstreamCondition, ReadonlySet<string>]> = [
|
|
49
|
+
["context_overflow", new Set(["context_length_exceeded", "string_above_max_length", "context_window_exceeded", "prompt_too_long"])],
|
|
50
|
+
["location_unsupported", new Set(["location_not_supported", "unsupported_country_region_territory", "unsupported_country", "user_location_is_not_supported"])],
|
|
51
|
+
["account_verification_required", new Set(["validation_required", "verification_required", "organization_verification_required"])],
|
|
52
|
+
["billing_exhausted", new Set(["insufficient_quota", "billing_hard_limit_reached", "usage_limit_reached", "usage_limit_exceeded", "1308", "monthly_request_count", "overage_request_limit_exceeded", "payment_required", "insufficient_balance", "credit_balance_too_low"])],
|
|
53
|
+
["model_unavailable", new Set(["model_not_found", "unsupported_model", "model_not_available", "model_not_supported", "deployment_not_found"])],
|
|
54
|
+
["rate_limited", new Set(["rate_limit_exceeded", "rate_limit_error", "too_many_requests", "throttling", "throttled", "rate_limited"])],
|
|
55
|
+
["upstream_unavailable", new Set(["server_is_overloaded", "overloaded_error", "service_unavailable", "unavailable"])],
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
// Context overflow from message text uses the same verdict the combo router trusts, so a validation
|
|
59
|
+
// error that merely quotes "prompt is too long" (an invalid tool name, for example) is not an overflow.
|
|
60
|
+
const KEYWORDS: Readonly<Record<"location_unsupported" | "account_verification_required" | "billing_exhausted" | "model_unavailable" | "rate_limited", readonly string[]>> = {
|
|
61
|
+
location_unsupported: ["location is not supported", "unsupported location", "not supported in your region", "region is not supported", "country, region, or territory", "not available in your country", "not available in your region"],
|
|
62
|
+
account_verification_required: ["verify your organization", "organization must be verified", "verification required", "verify your account", "account verification"],
|
|
63
|
+
billing_exhausted: ["insufficient quota", "quota exceeded", "quota exhausted", "exceeded your current quota", "run out of credits", "out of credits", "insufficient credits", "credit balance", "insufficient balance", "billing", "payment required"],
|
|
64
|
+
model_unavailable: ["model not found", "model does not exist", "unsupported model", "not allowed to use this model", "does not have access to model", "model is not available", "no such model"],
|
|
65
|
+
rate_limited: ["rate limit", "too many requests", "throttl"],
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
function token(value: string | undefined): string | undefined {
|
|
69
|
+
if (typeof value !== "string") return undefined;
|
|
70
|
+
const trimmed = value.trim();
|
|
71
|
+
return trimmed && trimmed.length <= MAX_TOKEN_LENGTH ? trimmed.toLowerCase() : undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function structuredCondition(tokens: readonly string[]): UpstreamCondition | undefined {
|
|
75
|
+
for (const [condition, set] of STRUCTURED) {
|
|
76
|
+
if (tokens.some(value => set.has(value))) return condition;
|
|
77
|
+
}
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function mentions(message: string, condition: keyof typeof KEYWORDS): boolean {
|
|
82
|
+
return KEYWORDS[condition].some(keyword => message.includes(keyword));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function statusFallback(status: number): UpstreamCondition | undefined {
|
|
86
|
+
if (status === 401) return "auth_failed";
|
|
87
|
+
if (status === 403) return "access_denied";
|
|
88
|
+
if (status === 402) return "billing_exhausted";
|
|
89
|
+
if (status === 404) return "model_unavailable";
|
|
90
|
+
if (status === 429) return "rate_limited";
|
|
91
|
+
if (status === 503 || status === 529) return "upstream_unavailable";
|
|
92
|
+
if (status >= 500) return "upstream_failed";
|
|
93
|
+
if (status >= 400) return "request_rejected";
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Precedence: 401 is authoritative; structured tokens next; keyword evidence only for 4xx
|
|
99
|
+
* statuses (a 5xx stays a server failure whatever its text says); a bare status last.
|
|
100
|
+
*/
|
|
101
|
+
export function classifyUpstreamCondition(evidence: UpstreamConditionEvidence): UpstreamCondition | undefined {
|
|
102
|
+
const { status } = evidence;
|
|
103
|
+
if (!Number.isInteger(status)) return undefined;
|
|
104
|
+
if (status === 401) return "auth_failed";
|
|
105
|
+
const tokens = [token(evidence.code), token(evidence.type), token(evidence.reason)].filter((value): value is string => value !== undefined);
|
|
106
|
+
const structured = structuredCondition(tokens);
|
|
107
|
+
if (structured) return structured;
|
|
108
|
+
const message = typeof evidence.message === "string" ? evidence.message.slice(0, MAX_MESSAGE_SCAN).toLowerCase() : "";
|
|
109
|
+
if (message && status >= 400 && status < 500) {
|
|
110
|
+
if (isDefiniteContextOverflow(status, evidence.message!.slice(0, MAX_MESSAGE_SCAN))) return "context_overflow";
|
|
111
|
+
if (mentions(message, "location_unsupported")) return "location_unsupported";
|
|
112
|
+
if (mentions(message, "account_verification_required")) return "account_verification_required";
|
|
113
|
+
// A 429 that names a rate limit is a rate limit even when it also mentions quota.
|
|
114
|
+
if (status === 429 && mentions(message, "rate_limited")) return "rate_limited";
|
|
115
|
+
if (mentions(message, "billing_exhausted")) return "billing_exhausted";
|
|
116
|
+
if (mentions(message, "model_unavailable")) return "model_unavailable";
|
|
117
|
+
if (mentions(message, "rate_limited")) return "rate_limited";
|
|
118
|
+
}
|
|
119
|
+
return statusFallback(status);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const MESSAGES: Readonly<Record<UpstreamCondition, string>> = {
|
|
123
|
+
auth_failed: "The provider rejected the configured credentials.",
|
|
124
|
+
access_denied: "The provider denied access to this request.",
|
|
125
|
+
context_overflow: "The request exceeds the model's context window.",
|
|
126
|
+
location_unsupported: "The provider does not serve this request from the current location.",
|
|
127
|
+
account_verification_required: "The provider requires account verification before serving this model.",
|
|
128
|
+
billing_exhausted: "The provider account has no remaining quota or credits.",
|
|
129
|
+
model_unavailable: "The requested model is not available from the provider.",
|
|
130
|
+
rate_limited: "The provider rate limit was reached; retry later.",
|
|
131
|
+
upstream_unavailable: "The provider is temporarily unavailable; retry later.",
|
|
132
|
+
upstream_failed: "The provider failed to complete the request.",
|
|
133
|
+
request_rejected: "The provider rejected the request.",
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const PROVIDER_ID = /^[A-Za-z0-9._-]{1,64}$/;
|
|
137
|
+
|
|
138
|
+
/** Proxy-written text for a condition; the provider id comes from configuration, never from an error. */
|
|
139
|
+
export function upstreamConditionMessage(condition: UpstreamCondition, providerId?: string): string {
|
|
140
|
+
const base = MESSAGES[condition];
|
|
141
|
+
return providerId !== undefined && PROVIDER_ID.test(providerId) ? `${base} (provider: ${providerId})` : base;
|
|
142
|
+
}
|
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
* the shared abort helpers from here).
|
|
17
17
|
*/
|
|
18
18
|
import { clearableDeadline } from "./abort";
|
|
19
|
+
import { errorDestinationLabel, errorDestinationText, type ErrorDestinationLabel } from "./error-destination";
|
|
20
|
+
export { errorDestinationLabel, providerErrorDestinationLabel, errorDestinationText } from "./error-destination";
|
|
19
21
|
import { redactSecretString } from "./redact";
|
|
20
22
|
|
|
21
23
|
/**
|
|
@@ -198,9 +200,9 @@ export function createTransientSendBudget(): TransientSendBudget {
|
|
|
198
200
|
*/
|
|
199
201
|
export class SendBudgetExhaustedError extends Error {
|
|
200
202
|
readonly code = "request_send_budget_exhausted";
|
|
201
|
-
constructor(label?:
|
|
202
|
-
super(label
|
|
203
|
-
? `request send budget exhausted before dispatch (${label})`
|
|
203
|
+
constructor(label?: ErrorDestinationLabel) {
|
|
204
|
+
super(label !== undefined
|
|
205
|
+
? `request send budget exhausted before dispatch (${errorDestinationText(label)})`
|
|
204
206
|
: "request send budget exhausted before dispatch");
|
|
205
207
|
this.name = "SendBudgetExhaustedError";
|
|
206
208
|
}
|
|
@@ -215,7 +217,7 @@ export class SendBudgetExhaustedError extends Error {
|
|
|
215
217
|
*/
|
|
216
218
|
export class InvalidSendBudgetError extends Error {
|
|
217
219
|
constructor(value: unknown) {
|
|
218
|
-
super(`invalid upstream send budget: ${
|
|
220
|
+
super(`invalid upstream send budget: ${typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : "invalid"}`);
|
|
219
221
|
this.name = "InvalidSendBudgetError";
|
|
220
222
|
}
|
|
221
223
|
}
|
|
@@ -516,6 +518,8 @@ export interface ResetRetryOptions {
|
|
|
516
518
|
abortSignal?: AbortSignal;
|
|
517
519
|
/** Short host/path label for the retry warn log (no secrets/query strings). */
|
|
518
520
|
label?: string;
|
|
521
|
+
/** Client error labels are separate from the operational retry-log label. */
|
|
522
|
+
destination?: ErrorDestinationLabel;
|
|
519
523
|
/** Total upstream sends allowed, including the first one. Not a per-layer retry count. */
|
|
520
524
|
attempts?: number;
|
|
521
525
|
/**
|
|
@@ -585,14 +589,13 @@ export class UpstreamRetryEvidenceError extends Error {
|
|
|
585
589
|
/** True when a connection-reset retry already reached the origin. */
|
|
586
590
|
public readonly resetSeen = false,
|
|
587
591
|
) {
|
|
588
|
-
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
589
592
|
const kinds: string[] = [];
|
|
590
593
|
if (transientStatuses.length > 0) kinds.push("transient 5xx response(s)");
|
|
591
594
|
if (resetSeen) kinds.push("a credential-visible connection reset");
|
|
592
595
|
super(
|
|
593
596
|
kinds.length > 0
|
|
594
|
-
? `upstream fetch failed after ${kinds.join(" and ")}
|
|
595
|
-
:
|
|
597
|
+
? `upstream fetch failed after ${kinds.join(" and ")}`
|
|
598
|
+
: "upstream fetch failed",
|
|
596
599
|
{ cause },
|
|
597
600
|
);
|
|
598
601
|
this.name = "UpstreamRetryEvidenceError";
|
|
@@ -652,7 +655,7 @@ export async function fetchWithResetRetry(
|
|
|
652
655
|
// Zero is zero. The old Math.max(1, ...) floor meant an exhausted budget still bought one
|
|
653
656
|
// more send on every recovery leg, which is most of what made a bounded per-layer retry
|
|
654
657
|
// compose into an unbounded per-request count.
|
|
655
|
-
if (attempts === 0) throw new SendBudgetExhaustedError(opts.label);
|
|
658
|
+
if (attempts === 0) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
|
|
656
659
|
try {
|
|
657
660
|
let lastError: unknown;
|
|
658
661
|
let sawReset = false;
|
|
@@ -665,7 +668,7 @@ export async function fetchWithResetRetry(
|
|
|
665
668
|
// Reported before the await, one physical send at a time: a send that rejects has still
|
|
666
669
|
// been made, and this helper leaves through four exits (return, reset give-up, non-reset
|
|
667
670
|
// rethrow, abort), so a per-send report is the only shape that is correct on all of them.
|
|
668
|
-
if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.label);
|
|
671
|
+
if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
|
|
669
672
|
if (!opts.onSendsConsumed?.beforeSend) opts.onSendsConsumed?.(1);
|
|
670
673
|
try {
|
|
671
674
|
let response: Response;
|
|
@@ -747,7 +750,7 @@ export async function fetchWithTransientRetry(
|
|
|
747
750
|
const countedFetch: ReplayableFetch = (recovery) => {
|
|
748
751
|
// Incremented BEFORE the await so a rejected send still consumes budget; counting only
|
|
749
752
|
// successes would let a reset storm loop without bound.
|
|
750
|
-
if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.label);
|
|
753
|
+
if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
|
|
751
754
|
sent += 1;
|
|
752
755
|
const run = () => doFetch(recovery);
|
|
753
756
|
return opts.onSendsConsumed?.execute ? opts.onSendsConsumed.execute(run) : run();
|
|
@@ -769,7 +772,7 @@ export async function fetchWithTransientRetry(
|
|
|
769
772
|
// and throws from one, and a caller sharing the budget across request legs must be told the
|
|
770
773
|
// real count on every one of them.
|
|
771
774
|
try {
|
|
772
|
-
if (budget === 0) throw new SendBudgetExhaustedError(opts.label);
|
|
775
|
+
if (budget === 0) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
|
|
773
776
|
let attemptStart = Date.now();
|
|
774
777
|
let res = await fetchWithResetRetry(countedFetch, innerResetOptions());
|
|
775
778
|
for (let attempt = 0; sent < budget; attempt++) {
|
|
@@ -17,7 +17,8 @@ export interface WindowsPrivateEntry {
|
|
|
17
17
|
* - "write-private": the POSIX mode&022==0 analog for objects we did NOT create — the
|
|
18
18
|
* serving token or a kernel-equivalent owner (SYSTEM, Administrators, TrustedInstaller)
|
|
19
19
|
* must own the object, and no grantee outside the trusted write set may hold write,
|
|
20
|
-
* create, delete or DACL/owner control
|
|
20
|
+
* create, delete or DACL/owner control, including inherit-only templates for
|
|
21
|
+
* children this process may create. Read grants to anyone are fine.
|
|
21
22
|
* - "trusted-ancestry": the POSIX uid∈{euid,0} + non-shared-writable ancestor analog.
|
|
22
23
|
* The owner must be the serving token or a kernel-equivalent owner (SYSTEM,
|
|
23
24
|
* Administrators, TrustedInstaller — each can already take ownership of any object,
|
|
@@ -26,6 +27,9 @@ export interface WindowsPrivateEntry {
|
|
|
26
27
|
* (FILE_ADD_FILE / FILE_ADD_SUBDIRECTORY without delete or write-existing): that is
|
|
27
28
|
* the closest NTFS analog of a root-owned sticky directory such as C:\, whose stock
|
|
28
29
|
* ACL grants Authenticated Users add-subdirectory while refusing every other write.
|
|
30
|
+
* This policy checks existing ancestors only and ignores inherit-only templates;
|
|
31
|
+
* callers must use write-private or the stricter private policy for every direct
|
|
32
|
+
* parent of a new child.
|
|
29
33
|
*/
|
|
30
34
|
export type WindowsAclPolicy = "private" | "private-runtime-directory" | "write-private" | "trusted-ancestry";
|
|
31
35
|
export interface WindowsAclEntry extends WindowsPrivateEntry {
|
|
@@ -243,9 +247,9 @@ function privateEntryOk(entry: ParsedEntry | null, directory: boolean, run: Pars
|
|
|
243
247
|
* Confined-write and trusted-ancestry policies for objects this process did not create.
|
|
244
248
|
*
|
|
245
249
|
* Deny ACEs are permitted because they can only remove access; allow ACEs must be
|
|
246
|
-
* ordinary non-callback CommonAce entries.
|
|
247
|
-
* templates
|
|
248
|
-
*
|
|
250
|
+
* ordinary non-callback CommonAce entries. Write-private also checks inherit-only
|
|
251
|
+
* templates: newly created children receive those grants before hardening. Existing
|
|
252
|
+
* trusted ancestors are not creation parents; each descendant is checked separately.
|
|
249
253
|
*/
|
|
250
254
|
function confinedEntryOk(entry: ParsedEntry | null, run: ParsedAclRun, policy: WindowsAclPolicy): boolean {
|
|
251
255
|
if (!entry || entry.aces === null || (entry.controlFlags & 0x4 /* SE_DACL_PRESENT */) === 0) return false;
|
|
@@ -262,9 +266,12 @@ function confinedEntryOk(entry: ParsedEntry | null, run: ParsedAclRun, policy: W
|
|
|
262
266
|
if (ace.type === 1) continue; // ACCESS_DENIED: removes access, never grants it.
|
|
263
267
|
if (ace.type !== 0) return false; // only ACCESS_ALLOWED records can be evaluated.
|
|
264
268
|
if (ace.flags === null || ace.mask === null || ace.sid === null) return false;
|
|
265
|
-
if ((ace.flags & INHERIT_ONLY_ACE) !== 0) continue;
|
|
269
|
+
if (policy === "trusted-ancestry" && (ace.flags & INHERIT_ONLY_ACE) !== 0) continue;
|
|
266
270
|
if (ace.sid === run.user || TRUSTED_WRITE_SIDS.has(ace.sid)) continue;
|
|
267
|
-
|
|
271
|
+
// Create rights on a sticky trusted ancestor are safe for that ancestor itself,
|
|
272
|
+
// but an inherit-only template would grant them inside a newly created child.
|
|
273
|
+
const createOk = policy === "trusted-ancestry" && STICKY_OWNERS.has(owner)
|
|
274
|
+
&& (ace.flags & INHERIT_ONLY_ACE) === 0 ? CREATE_MASK : 0;
|
|
268
275
|
const allowed = (READ_MASK | createOk) >>> 0;
|
|
269
276
|
if (((ace.mask >>> 0) & ~allowed) !== 0) return false;
|
|
270
277
|
}
|
|
@@ -14,6 +14,7 @@ const SSH_TRANSPORT_FAILURE = 255;
|
|
|
14
14
|
|
|
15
15
|
/** Remote argv that prints the kernel name; under cmd or PowerShell, `sh` itself is refused. */
|
|
16
16
|
export const REMOTE_UNAME_ARGV: readonly string[] = ["sh", "-c", "uname -s 2>/dev/null", "ocx-platform"];
|
|
17
|
+
const REMOTE_FRAMED_UNAME_ARGV: readonly string[] = ["sh", "-c", "printf 'ocx-platform:%s\\n' \"$(uname -s 2>/dev/null)\"", "ocx-platform"];
|
|
17
18
|
|
|
18
19
|
/** Does this output come from cmd.exe or PowerShell refusing a POSIX command? */
|
|
19
20
|
export function isWindowsShellRefusal(output: string): boolean {
|
|
@@ -64,3 +65,16 @@ export async function requireRemotePlatform(runner: Pick<SshRunner, "run">, alia
|
|
|
64
65
|
if (platform === "unknown") throw new Error("Remote platform could not be determined");
|
|
65
66
|
return platform;
|
|
66
67
|
}
|
|
68
|
+
|
|
69
|
+
/** Fan-out ignores login-shell output and trusts only one framed uname line. */
|
|
70
|
+
export async function requireRemotePlatformFramed(runner: Pick<SshRunner, "run">, alias: string, knownHostsFile: string): Promise<"posix" | "windows"> {
|
|
71
|
+
const windows = await runner.run(buildWindowsProbeArgv({ alias, knownHostsFile }), { timeoutMs: 10_000 });
|
|
72
|
+
if (windows.code === SSH_TRANSPORT_FAILURE) throw new Error("SSH platform discovery failed");
|
|
73
|
+
if (windows.code === 0 && windows.stdout.split(/\r?\n/).some(line => line.trim() === "Windows_NT")) return "windows";
|
|
74
|
+
const result = await runner.run(buildExecArgv({ alias, knownHostsFile, argv: REMOTE_FRAMED_UNAME_ARGV }), { timeoutMs: 10_000 });
|
|
75
|
+
if (result.code === SSH_TRANSPORT_FAILURE) throw new Error("SSH platform discovery failed");
|
|
76
|
+
const frames = result.stdout.split(/\r?\n/).filter(line => line.startsWith("ocx-platform:"));
|
|
77
|
+
const name = frames.length === 1 ? frames[0]!.slice("ocx-platform:".length) : "";
|
|
78
|
+
if (result.code !== 0 || !POSIX_UNAME.test(name)) throw new Error("Remote platform could not be determined");
|
|
79
|
+
return WINDOWS_UNAME.test(name) ? "windows" : "posix";
|
|
80
|
+
}
|