@bitkyc08/opencodex 2.99.0 → 2.100.1
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/AGENTS_INSTALL.md +19 -1
- package/README.md +37 -33
- package/SPONSORS.md +5 -1
- package/bin/ocx.mjs +1 -1
- package/gui/dist/assets/{App-C1hGwaN1.css → App-COo8Yopd.css} +1 -1
- package/gui/dist/assets/App-g3Cm2xhZ.js +59 -0
- package/gui/dist/assets/Tray-BMDkAiXy.js +1 -0
- package/gui/dist/assets/brand-mark-nr3ziR-T.js +1 -0
- package/gui/dist/assets/index-Bziu8gTy.css +2 -0
- package/gui/dist/assets/index-OYzhQUNP.js +94 -0
- package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-DKCVUUTi.js} +1 -1
- package/gui/dist/classic/assets/App-CgPBKUP-.js +58 -0
- package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-BedmOsE7.js} +1 -1
- package/gui/dist/classic/assets/index-BR-HhNrp.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/native/ocx-child/Cargo.lock +215 -0
- package/native/ocx-child/Cargo.toml +31 -0
- package/native/ocx-child/src/cli.rs +1901 -0
- package/native/ocx-child/src/codex_home.rs +429 -0
- package/native/ocx-child/src/codex_settings.rs +231 -0
- package/native/ocx-child/src/daemon.rs +363 -0
- package/native/ocx-child/src/http_wire.rs +619 -0
- package/native/ocx-child/src/journal.rs +977 -0
- package/native/ocx-child/src/lib.rs +22 -0
- package/native/ocx-child/src/main.rs +9 -0
- package/native/ocx-child/src/parity.rs +102 -0
- package/native/ocx-child/src/platform.rs +1487 -0
- package/native/ocx-child/src/relay.rs +1288 -0
- package/native/ocx-child/src/relay_auth.rs +166 -0
- package/native/ocx-child/src/routes.rs +236 -0
- package/native/ocx-child/src/state.rs +190 -0
- package/native/ocx-child/src/test_hooks.rs +58 -0
- package/native/ocx-child/src/toml_surgeon.rs +1156 -0
- package/package.json +8 -2
- package/src/adapters/anthropic-image-normalize.ts +1 -1
- package/src/adapters/anthropic.ts +28 -2
- package/src/adapters/claude-cli/adapter.ts +5 -25
- package/src/adapters/claude-cli/instruction-images.ts +31 -0
- package/src/adapters/claude-cli/stable-replay.ts +42 -14
- package/src/adapters/claude-cli/usage-admission.ts +53 -64
- package/src/adapters/client-fingerprint.ts +1 -1
- package/src/adapters/coding-agent/protocol.ts +1 -1
- package/src/adapters/devin/live-models.ts +3 -0
- package/src/adapters/google-http.ts +3 -0
- package/src/adapters/google-vertex-key-project.ts +10 -2
- package/src/adapters/google.ts +40 -8
- package/src/adapters/kiro/usage.ts +3 -13
- package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
- package/src/adapters/openai-chat-images.ts +100 -0
- package/src/adapters/openai-chat.ts +6 -9
- package/src/adapters/openai-responses/passthrough.ts +5 -2
- package/src/adapters/openai-responses/request-strips.ts +32 -0
- package/src/adapters/openai-responses/tool-schema.ts +9 -4
- package/src/chat/inbound.ts +1 -1
- package/src/claude/auth-detect.ts +26 -8
- package/src/claude/inbound-content-options.ts +18 -3
- package/src/claude/inbound.ts +5 -2
- package/src/cli/bundled-bun-diagnostic.ts +91 -0
- package/src/cli/capabilities-agents-routing.ts +2 -2
- package/src/cli/capabilities-observe-system.ts +60 -0
- package/src/cli/combo-input.ts +6 -0
- package/src/cli/combo-result.ts +1 -1
- package/src/cli/combo.ts +4 -0
- package/src/cli/config-command.ts +16 -2
- package/src/cli/connect.ts +12 -10
- package/src/cli/dispatch.ts +4 -0
- package/src/cli/doctor.ts +11 -0
- package/src/cli/help.ts +1 -0
- package/src/cli/init.ts +4 -0
- package/src/cli/link-enrollment.ts +152 -25
- package/src/cli/link-local-control.ts +49 -0
- package/src/cli/link.ts +37 -10
- package/src/cli/provider-lifecycle-runtime.ts +4 -2
- package/src/cli/registry.ts +13 -0
- package/src/cli/star-prompt.ts +2 -0
- package/src/cli/status.ts +1 -1
- package/src/cli/telemetry-profile.ts +206 -0
- package/src/cli/telemetry.ts +260 -0
- package/src/client/hub-relay.ts +26 -0
- package/src/client/machine-api.ts +3 -0
- package/src/clients/config-export/t3code.ts +44 -5
- package/src/clients/omo-role-models.ts +1 -1
- package/src/codex/catalog/bundled.ts +44 -2
- package/src/codex/runtime.ts +12 -0
- package/src/codex/shim-restore-lock.ts +67 -30
- package/src/combos/types.ts +21 -1
- package/src/config/atomic-write.ts +24 -1
- package/src/config/diagnostics.ts +15 -0
- package/src/config/live-reconcile.ts +17 -0
- package/src/config/load-degrade.ts +16 -0
- package/src/config/provider-validation.ts +29 -0
- package/src/config/schema/config-schema.ts +24 -0
- package/src/config/schema/leaf-validators.ts +17 -0
- package/src/config/telemetry-carry.ts +30 -0
- package/src/config.ts +13 -1
- package/src/generated/compatibility-version.json +422 -170
- package/src/generated/model-metadata.ts +3 -3
- package/src/integrations/aside-profiles.ts +7 -1
- package/src/integrations/owned-refresh.ts +9 -2
- package/src/lab/artifacts/secure-fs.ts +12 -11
- package/src/lab/fabric/scratch.ts +11 -9
- package/src/lab/public/community.ts +2 -3
- package/src/lab/public/file-safety.ts +18 -20
- package/src/lab/public/mutation-lock.ts +109 -337
- package/src/lab/public/private-file.ts +4 -3
- package/src/lib/bun-runtime-preflight.ts +1 -1
- package/src/lib/codex-catalog-read-only.ts +122 -0
- package/src/lib/config-ownership.ts +56 -18
- package/src/lib/errors.ts +11 -0
- package/src/lib/gcp-adc.ts +167 -48
- package/src/lib/jsonc.ts +4 -2
- package/src/lib/local-control-socket.ts +88 -0
- package/src/lib/privacy.ts +15 -0
- package/src/lib/provider-client-headers.ts +3 -0
- package/src/lib/token-estimate.ts +13 -2
- package/src/link/child-binary-source.ts +228 -0
- package/src/link/ephemeral-child.ts +45 -0
- package/src/link/remote-plant.ts +306 -0
- package/src/link/remote-windows.ts +59 -5
- package/src/link/ssh-argv.ts +71 -8
- package/src/link/status-projection.ts +2 -0
- package/src/link/store.ts +5 -1
- package/src/oauth/anthropic-model-quota.ts +12 -0
- package/src/oauth/anthropic-routing.ts +11 -4
- package/src/oauth/claude-keychain-read.ts +165 -0
- package/src/oauth/kiro-iam-identity-center.ts +4 -1
- package/src/oauth/local-token-detect.ts +14 -17
- package/src/protocols/envelope.ts +20 -2
- package/src/providers/api-key-selection.ts +8 -2
- package/src/providers/claude-cli-identity.ts +9 -3
- package/src/providers/claude-cli-usage-state.ts +93 -0
- package/src/providers/claude-cli-usage.ts +3 -2
- package/src/providers/github-copilot-auto.ts +25 -5
- package/src/providers/meta-muse-plan-refusal.ts +94 -0
- package/src/providers/model-rename-fields.ts +3 -0
- package/src/providers/quota/anthropic-family-headers.ts +8 -1
- package/src/providers/quota/anthropic-usage-windows.ts +49 -2
- package/src/providers/quota/vendor-probes-key.ts +23 -4
- package/src/providers/quota/vendor-probes-oauth.ts +59 -0
- package/src/providers/quota/workbuddy.ts +2 -2
- package/src/providers/quota-types.ts +7 -0
- package/src/providers/quota.ts +25 -18
- package/src/providers/registry/entries-core.ts +7 -4
- package/src/providers/registry/entries-extended.ts +42 -8
- package/src/providers/registry/model-ids.ts +1 -0
- package/src/providers/registry/model-seeds.ts +10 -2
- package/src/providers/registry/types.ts +6 -0
- package/src/providers/resolved-model-policy.ts +4 -0
- package/src/providers/routed-config.ts +30 -3
- package/src/providers/stale-no-vision-seed-migration.ts +7 -0
- package/src/providers/vertex-environment-authority.ts +50 -0
- package/src/providers/workbuddy-credit-balance.ts +38 -6
- package/src/quota-pool/assemble.ts +14 -6
- package/src/responses/retained-compaction.ts +31 -5
- package/src/router.ts +1 -0
- package/src/server/adapter-resolve.ts +11 -6
- package/src/server/audio-dictation.ts +21 -7
- package/src/server/auth-cors.ts +19 -0
- package/src/server/background-lifecycle.ts +71 -0
- package/src/server/chat-completions.ts +2 -0
- package/src/server/claude-messages.ts +30 -3
- package/src/server/index/live-sideband.ts +15 -1
- package/src/server/index/local-control-listener.ts +515 -0
- package/src/server/index/optional-listeners.ts +21 -1
- package/src/server/index/serve-options.ts +4 -3
- package/src/server/index/websocket-handler.ts +2 -0
- package/src/server/index.ts +3 -0
- package/src/server/management/combo-routes.ts +6 -1
- package/src/server/management/context.ts +1 -0
- package/src/server/management/link-child-preflight.ts +74 -0
- package/src/server/management/link-enrollment.ts +190 -25
- package/src/server/management/link-route-state.ts +6 -1
- package/src/server/management/link-routes.ts +27 -9
- package/src/server/management/model-rows.ts +4 -0
- package/src/server/management/oauth-account-routes.ts +9 -4
- package/src/server/management/provider-overwrite-carry.ts +9 -2
- package/src/server/management/provider-routes.ts +14 -0
- package/src/server/management/provider-thinking-display-patch.ts +54 -0
- package/src/server/management/route-registry.ts +7 -0
- package/src/server/management/session-routes.ts +4 -1
- package/src/server/management/telemetry-routes.ts +37 -0
- package/src/server/management/usage-aggregate-cache.ts +290 -67
- package/src/server/management-api.ts +11 -2
- package/src/server/messages-native-preflight.ts +166 -0
- package/src/server/messages-native.ts +143 -43
- package/src/server/messages-shared.ts +14 -0
- package/src/server/proxy-liveness.ts +99 -6
- package/src/server/request-log-conversation.ts +18 -2
- package/src/server/request-log.ts +7 -2
- package/src/server/responses/adapter-continuation.ts +1 -0
- package/src/server/responses/adapter-dispatch.ts +11 -28
- package/src/server/responses/adapter-failure-message.ts +68 -0
- package/src/server/responses/combo-stream-preflight.ts +14 -2
- package/src/server/responses/compact.ts +13 -1
- package/src/server/responses/core-auth.ts +26 -5
- package/src/server/responses/core-codex-account.ts +8 -1
- package/src/server/responses/core-combo-failure.ts +6 -1
- package/src/server/responses/core-combo-native.ts +150 -37
- package/src/server/responses/core-combo.ts +15 -9
- package/src/server/responses/core-normalize.ts +1 -0
- package/src/server/responses/core-options.ts +7 -1
- package/src/server/responses/core-pipeline.ts +21 -1
- package/src/server/responses/fetch-helpers.ts +5 -0
- package/src/server/responses/opengateway-completion-guard.ts +7 -3
- package/src/server/responses/passthrough-delivery.ts +8 -1
- package/src/server/responses/passthrough-error.ts +22 -0
- package/src/server/responses/request-prepare.ts +7 -1
- package/src/server/responses/request-transport.ts +28 -5
- package/src/server/responses/run-turn-execution.ts +13 -0
- package/src/server/sse-frame-buffer.ts +5 -0
- package/src/server/ws-bridge.ts +10 -0
- package/src/service/launchd.ts +78 -4
- package/src/telemetry/aggregate.ts +348 -0
- package/src/telemetry/consent.ts +128 -0
- package/src/telemetry/contract.ts +403 -0
- package/src/telemetry/disclosure.ts +19 -0
- package/src/telemetry/install-id.ts +226 -0
- package/src/telemetry/payload.ts +129 -0
- package/src/telemetry/profile/client.ts +150 -0
- package/src/telemetry/profile/contract.ts +288 -0
- package/src/telemetry/profile/disclosure.ts +14 -0
- package/src/telemetry/profile/paths.ts +13 -0
- package/src/telemetry/profile/routes.ts +99 -0
- package/src/telemetry/profile/service.ts +234 -0
- package/src/telemetry/profile/state.ts +189 -0
- package/src/telemetry/profile/sync.ts +276 -0
- package/src/telemetry/routes.ts +183 -0
- package/src/telemetry/scheduler.ts +386 -0
- package/src/telemetry/sender.ts +97 -0
- package/src/telemetry/state.ts +334 -0
- package/src/types/combo-jev-effort-mode.ts +11 -0
- package/src/types/config.ts +3 -0
- package/src/types/provider.ts +11 -1
- package/src/types/request.ts +2 -0
- package/src/types/telemetry.ts +15 -0
- package/src/types/wire.ts +10 -0
- package/src/types.ts +5 -0
- package/src/update/index.ts +7 -1
- package/src/update/minisign.d.mts +17 -0
- package/src/update/minisign.mjs +88 -0
- package/src/update/signed-supply.d.mts +59 -0
- package/src/update/signed-supply.mjs +289 -0
- package/src/update/trust-root.json +38 -0
- package/src/update/update-bounded-json.d.mts +4 -0
- package/src/update/update-bounded-json.mjs +113 -0
- package/src/update/update-bytes.d.mts +2 -0
- package/src/update/update-bytes.mjs +23 -0
- package/src/update/update-candidate-id.d.mts +2 -0
- package/src/update/update-candidate-id.mjs +23 -0
- package/src/update/update-checkpoint-codec.d.mts +33 -0
- package/src/update/update-checkpoint-codec.mjs +217 -0
- package/src/update/update-contracts.d.mts +24 -0
- package/src/update/update-contracts.mjs +207 -0
- package/src/update/update-signature-threshold.d.mts +12 -0
- package/src/update/update-signature-threshold.mjs +47 -0
- package/src/update/update-signed-version.d.mts +5 -0
- package/src/update/update-signed-version.mjs +25 -0
- package/src/update/update-trust-anchor.d.mts +2 -0
- package/src/update/update-trust-anchor.mjs +2 -0
- package/src/usage/cache-diagnostic.ts +195 -50
- package/src/usage/expected-prices.ts +20 -2
- package/src/usage/filter-index.ts +1469 -0
- package/src/usage/ledger-scanner.ts +245 -4
- package/src/usage/source-filter.ts +10 -2
- package/src/usage/summary.ts +16 -0
- package/src/web-search/parse.ts +265 -38
- package/gui/dist/assets/App-BepstgEN.js +0 -59
- package/gui/dist/assets/Tray-BinxbEZo.js +0 -1
- package/gui/dist/assets/brand-mark-wzPe3R-J.js +0 -1
- package/gui/dist/assets/index-C-9X2yaI.js +0 -94
- package/gui/dist/assets/index-bnUWypyz.css +0 -2
- package/gui/dist/classic/assets/App-DX88_GCW.js +0 -58
- package/gui/dist/classic/assets/index-fSP71pLB.js +0 -94
- package/gui/dist/classic/assets/quota-summary-y2fl0WBv.js +0 -1
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Publish the OpenCodex-owned Codex catalog over a read-only destination (#8358).
|
|
3
|
+
*
|
|
4
|
+
* On a Windows Child, `%USERPROFILE%\.codex\opencodex-catalog.json` can carry the
|
|
5
|
+
* read-only FILE ATTRIBUTE — set by a sync client, a backup agent, or a manual
|
|
6
|
+
* property edit. Windows answers the atomic replace with `EPERM` (or `EACCES`)
|
|
7
|
+
* rather than replacing the entry, so every catalog write exited with a one-line
|
|
8
|
+
* `catalog sync skipped: EPERM ...` and Remote Link enrollment reported only the
|
|
9
|
+
* generic "Child enrollment" phase.
|
|
10
|
+
*
|
|
11
|
+
* OpenCodex owns that file, so the repair is scoped by artifact name: the shared
|
|
12
|
+
* atomic writer applies it only to `opencodex-catalog.json` and only on win32.
|
|
13
|
+
* Every other destination keeps the ordinary write contract.
|
|
14
|
+
*
|
|
15
|
+
* Windows synthesizes a file's `mode` from the read-only attribute: 0o444 when the
|
|
16
|
+
* attribute is set, 0o666 when clear, regardless of the mode the writer requested.
|
|
17
|
+
* Clearing the owner-write bit with `chmod` is what removes the attribute, so the
|
|
18
|
+
* retry works on both a real NTFS volume and a simulated one.
|
|
19
|
+
*/
|
|
20
|
+
import { chmodSync, statSync } from "node:fs";
|
|
21
|
+
import { basename } from "node:path";
|
|
22
|
+
|
|
23
|
+
/** A retried catalog publication that still fails after the attribute was cleared. */
|
|
24
|
+
export class CodexCatalogReadOnlyError extends Error {
|
|
25
|
+
/** The cause's errno code, so disk-failure classification (management convergence) still applies. */
|
|
26
|
+
readonly code: string;
|
|
27
|
+
constructor(readonly path: string, options?: ErrorOptions) {
|
|
28
|
+
super(`Codex catalog is read-only: ${path}`, options);
|
|
29
|
+
this.name = "CodexCatalogReadOnlyError";
|
|
30
|
+
const cause = (options?.cause as NodeJS.ErrnoException | undefined)?.code;
|
|
31
|
+
this.code = typeof cause === "string" ? cause : "EPERM";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The artifact name OpenCodex writes and owns. Nothing else inherits this repair. */
|
|
36
|
+
export const CODEX_CATALOG_FILE_NAME = "opencodex-catalog.json";
|
|
37
|
+
|
|
38
|
+
export function isOwnedCodexCatalogPath(path: string): boolean {
|
|
39
|
+
return basename(path) === CODEX_CATALOG_FILE_NAME;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CatalogReadOnlyRepair {
|
|
43
|
+
readonly platform: NodeJS.Platform;
|
|
44
|
+
/** Whether the destination currently carries the read-only attribute. */
|
|
45
|
+
readonly isReadOnly: (path: string) => boolean;
|
|
46
|
+
/** Clear it. Must leave the file writable for its owner. */
|
|
47
|
+
readonly makeWritable: (path: string) => void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isReadOnlyByAttribute(path: string): boolean {
|
|
51
|
+
// An unreadable stat is not evidence of read-only, so it keeps the original error.
|
|
52
|
+
try { return (statSync(path).mode & 0o222) === 0; } catch { return false; }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function makeWritableByAttribute(path: string): void {
|
|
56
|
+
// Only the owner-write bit is meaningful to Windows chmod; setting it is what
|
|
57
|
+
// clears FILE_ATTRIBUTE_READONLY.
|
|
58
|
+
chmodSync(path, 0o666);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function defaultCatalogReadOnlyRepair(
|
|
62
|
+
platform: NodeJS.Platform = process.platform,
|
|
63
|
+
): CatalogReadOnlyRepair {
|
|
64
|
+
return { platform, isReadOnly: isReadOnlyByAttribute, makeWritable: makeWritableByAttribute };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
let repairOverride: CatalogReadOnlyRepair | null | undefined;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Test seam: drive the Windows branch on a POSIX runner. `null` disables it,
|
|
71
|
+
* `undefined` restores the production rule. Scoped here rather than to
|
|
72
|
+
* `process.platform` so an unrelated suite that forces `win32` for ACL work does
|
|
73
|
+
* not start chmod-ing catalogs on a Linux runner.
|
|
74
|
+
*/
|
|
75
|
+
export function setCatalogReadOnlyRepairForTests(repair: CatalogReadOnlyRepair | null | undefined): void {
|
|
76
|
+
repairOverride = repair;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The repair that applies to this destination, or null when the shared writer must
|
|
81
|
+
* keep its ordinary semantics: any file other than the OpenCodex-owned catalog, and
|
|
82
|
+
* every platform except Windows.
|
|
83
|
+
*/
|
|
84
|
+
export function catalogReadOnlyRepairFor(
|
|
85
|
+
target: string,
|
|
86
|
+
platform: NodeJS.Platform = process.platform,
|
|
87
|
+
): CatalogReadOnlyRepair | null {
|
|
88
|
+
if (!isOwnedCodexCatalogPath(target)) return null;
|
|
89
|
+
if (repairOverride !== undefined) return repairOverride;
|
|
90
|
+
return platform === "win32" ? defaultCatalogReadOnlyRepair(platform) : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function isPermissionDenial(error: unknown): boolean {
|
|
94
|
+
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
|
95
|
+
return code === "EPERM" || code === "EACCES";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Publish once; on the specific Windows read-only refusal, clear the attribute and
|
|
100
|
+
* publish once more. A second failure names the file and the attribute instead of
|
|
101
|
+
* repeating the raw rename error, so callers can report the actual cause.
|
|
102
|
+
*/
|
|
103
|
+
export function publishWithReadOnlyRepair(
|
|
104
|
+
rename: () => void,
|
|
105
|
+
target: string,
|
|
106
|
+
repair: CatalogReadOnlyRepair = defaultCatalogReadOnlyRepair(),
|
|
107
|
+
): void {
|
|
108
|
+
try { rename(); return; }
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (repair.platform !== "win32" || !isPermissionDenial(error) || !repair.isReadOnly(target)) throw error;
|
|
111
|
+
}
|
|
112
|
+
// A clear that fails leaves the attribute in place: that is still the read-only catalog.
|
|
113
|
+
try { repair.makeWritable(target); }
|
|
114
|
+
catch (clearError) { throw new CodexCatalogReadOnlyError(target, { cause: clearError }); }
|
|
115
|
+
try { rename(); }
|
|
116
|
+
catch (retryError) {
|
|
117
|
+
// Only a destination that still refuses is named read-only; a full disk or a scanner
|
|
118
|
+
// lock after the clear keeps its own error so the report names the real cause.
|
|
119
|
+
if (isPermissionDenial(retryError)) throw new CodexCatalogReadOnlyError(target, { cause: retryError });
|
|
120
|
+
throw retryError;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -149,6 +149,13 @@ let lastReconciledGeneration = 0;
|
|
|
149
149
|
*/
|
|
150
150
|
const lockedManifestIdentity = new Map<string, string>();
|
|
151
151
|
const warnedFullManifest = new Set<string>();
|
|
152
|
+
/**
|
|
153
|
+
* The metadata state in which a creation wait already ran out for a home, keyed as
|
|
154
|
+
* {@link ownershipCache}. An unowned home whose manifest and owner marker keep the same identity
|
|
155
|
+
* has no publication left to wait for (a stopped creation, or a corrupt marker), so a registration
|
|
156
|
+
* must not pay the bounded wait again; either file changing re-arms a single wait.
|
|
157
|
+
*/
|
|
158
|
+
const expiredCreationWait = new Map<string, string>();
|
|
152
159
|
/**
|
|
153
160
|
* Open while this process runs `ocx uninstall` itself. Its own registrations then skip the
|
|
154
161
|
* tombstone check: the same process runs removeOwnedConfigState afterwards, whose locked snapshot
|
|
@@ -190,6 +197,27 @@ function manifestIdentity(configDir: string): string | undefined {
|
|
|
190
197
|
}
|
|
191
198
|
}
|
|
192
199
|
|
|
200
|
+
/**
|
|
201
|
+
* Which file each ownership metadata name refers to while a manifest exists, in the same
|
|
202
|
+
* dev:ino:size:mtime terms {@link manifestIdentity} uses, or null when no manifest exists: without
|
|
203
|
+
* one the publication wait ends in a single pass, so there is no spent wait to remember. The
|
|
204
|
+
* manifest is replaced atomically and the owner marker written once, so either file changing
|
|
205
|
+
* produces a new identity and re-arms a single wait.
|
|
206
|
+
*/
|
|
207
|
+
function creationWaitIdentity(configDir: string): string | null {
|
|
208
|
+
const describe = (name: string): string | null => {
|
|
209
|
+
try {
|
|
210
|
+
const entry = lstatSync(join(configDir, name), { bigint: true });
|
|
211
|
+
return `${entry.dev}:${entry.ino}:${entry.size}:${entry.mtimeNs}`;
|
|
212
|
+
} catch (error) {
|
|
213
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
214
|
+
return code === "ENOENT" ? null : `unreadable:${code ?? "unknown"}`;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
const manifest = describe(CONFIG_UNINSTALL_MANIFEST);
|
|
218
|
+
return manifest === null ? null : `${manifest}|${describe(CONFIG_OWNER_FILE)}`;
|
|
219
|
+
}
|
|
220
|
+
|
|
193
221
|
export function listLiveConfigOwnershipRoots(currentConfigDir: string): ReadonlySet<string> {
|
|
194
222
|
const currentRoot = ownershipCacheKey(currentConfigDir);
|
|
195
223
|
const roots = new Set<string>([currentRoot]);
|
|
@@ -211,6 +239,7 @@ export function reconcileConfigOwnershipRoots(context: GenerationContext): numbe
|
|
|
211
239
|
existsSync(join(root, ...rel.split("/"))));
|
|
212
240
|
if (hasLiveOwnedPath) continue;
|
|
213
241
|
ownershipCache.delete(root);
|
|
242
|
+
expiredCreationWait.delete(root);
|
|
214
243
|
removed += 1;
|
|
215
244
|
}
|
|
216
245
|
lastReconciledGeneration = context.generation;
|
|
@@ -525,24 +554,31 @@ export function initializeConfigOwnership(configDir: string): boolean {
|
|
|
525
554
|
const cacheKey = ownershipCacheKey(configDir);
|
|
526
555
|
if (!existsSync(configDir)) {
|
|
527
556
|
ownershipCache.delete(cacheKey);
|
|
557
|
+
expiredCreationWait.delete(cacheKey);
|
|
528
558
|
mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
529
559
|
}
|
|
530
560
|
let ownership = ownershipCache.get(cacheKey);
|
|
531
|
-
if (ownership === undefined) {
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
//
|
|
536
|
-
//
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
561
|
+
if (ownership === undefined || ownership === null) {
|
|
562
|
+
// A previously unowned home can enter creation later; use the same bounded publication wait,
|
|
563
|
+
// but spend it at most once per unchanged metadata pair. A manifest left without a valid
|
|
564
|
+
// owner marker — a stopped creation, or a corrupt marker — is not a creation still in
|
|
565
|
+
// progress, and registrations run on the request path: charging each of them the full wait
|
|
566
|
+
// stalls every request to that home. Either file changing re-arms a single wait.
|
|
567
|
+
const observed = creationWaitIdentity(configDir);
|
|
568
|
+
if (observed !== null && expiredCreationWait.get(cacheKey) === observed) {
|
|
569
|
+
// A spent wait suppresses only the wait itself, never the reload: the identity it keeps
|
|
570
|
+
// may already name a completed pair. One plain load stays cheap for an unchanged invalid
|
|
571
|
+
// pair and lets a valid one register instead of sticking unowned.
|
|
572
|
+
ownership = loadOwnership(configDir);
|
|
573
|
+
if (ownership !== null) expiredCreationWait.delete(cacheKey);
|
|
574
|
+
} else {
|
|
575
|
+
ownership = loadOrCreateOwnership(configDir);
|
|
576
|
+
const current = creationWaitIdentity(configDir);
|
|
577
|
+
// Record only the identity the wait actually ran out on: unchanged across it, so its last
|
|
578
|
+
// failed read describes the same state. A pair that changed during the wait, including one
|
|
579
|
+
// that completed just after that read, spends its own wait on the next registration.
|
|
580
|
+
if (ownership === null && current !== null && current === observed) expiredCreationWait.set(cacheKey, current);
|
|
581
|
+
else expiredCreationWait.delete(cacheKey);
|
|
546
582
|
}
|
|
547
583
|
ownershipCache.set(cacheKey, ownership);
|
|
548
584
|
}
|
|
@@ -573,13 +609,13 @@ function loadOwnershipForUninstall(configDir: string): { owner: ConfigOwner; man
|
|
|
573
609
|
return loadOwnership(configDir) ?? tombstonedManifestWithoutOwner(configDir);
|
|
574
610
|
}
|
|
575
611
|
|
|
576
|
-
/** How long
|
|
612
|
+
/** How long an uncached or unowned registration waits for another process creating the same home. */
|
|
577
613
|
const CONCURRENT_CREATION_WAIT_MS = 100;
|
|
578
614
|
|
|
579
615
|
/**
|
|
580
616
|
* Load the ownership metadata, or create it in an empty root. Two processes can start on the same
|
|
581
617
|
* absent home: the loser of the exclusive manifest write, or one that sees the manifest before the
|
|
582
|
-
* owner marker (creation writes them in that order), waits briefly and loads the winner's metadata
|
|
618
|
+
* complete owner marker (creation writes them in that order), waits briefly and loads the winner's metadata
|
|
583
619
|
* instead of caching the home as unowned for the rest of its life.
|
|
584
620
|
*/
|
|
585
621
|
function loadOrCreateOwnership(configDir: string): { owner: ConfigOwner; manifest: ConfigUninstallManifest } | null {
|
|
@@ -593,7 +629,9 @@ function loadOrCreateOwnership(configDir: string): { owner: ConfigOwner; manifes
|
|
|
593
629
|
} catch (error) {
|
|
594
630
|
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
595
631
|
}
|
|
596
|
-
|
|
632
|
+
// Exclusive create publishes the owner file name before its JSON bytes are complete.
|
|
633
|
+
// Only a valid matching pair proves ownership; file presence alone must not end this wait.
|
|
634
|
+
const creating = existsSync(join(configDir, CONFIG_UNINSTALL_MANIFEST))
|
|
597
635
|
&& !tombstonedManifestWithoutOwner(configDir);
|
|
598
636
|
if (!creating || Date.now() >= deadline) return loadOwnership(configDir);
|
|
599
637
|
Bun.sleepSync(5);
|
package/src/lib/errors.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { formatRetryAfterAdvice, parseRetryAfterFromMessage } from "./retry-delay";
|
|
2
|
+
import { isMetaMusePlanFailure, META_MUSE_PLAN_REFUSAL_MESSAGE } from "../providers/meta-muse-plan-refusal";
|
|
2
3
|
|
|
3
4
|
export interface OcxErrorPayload {
|
|
4
5
|
message: string;
|
|
@@ -545,6 +546,16 @@ export function classifyError(status: number, type: string, message: string): Oc
|
|
|
545
546
|
) {
|
|
546
547
|
return { message, type: "authentication_error", code: "invalid_api_key" };
|
|
547
548
|
}
|
|
549
|
+
// Meta scopes a Muse Code subscription key to its own client and refuses every other caller with
|
|
550
|
+
// one fixed 403 (#8352). The key is valid and no login lifts the restriction, so the verdict is a
|
|
551
|
+
// plan/entitlement class rather than a rejected credential. This sits above the generic
|
|
552
|
+
// `permission_denied` branch because the envelope carries that code as its own detail.
|
|
553
|
+
if (isMetaMusePlanFailure(status, message)) {
|
|
554
|
+
// One proxy sentence says what Meta's refusal means and what path does work; the upstream
|
|
555
|
+
// body names the restriction but not the alternative, and relaying it verbatim reads as a
|
|
556
|
+
// rejected credential.
|
|
557
|
+
return { message: META_MUSE_PLAN_REFUSAL_MESSAGE, type: "permission_error", code: "subscription_required" };
|
|
558
|
+
}
|
|
548
559
|
// An explicit permission enum must not acquire a more specific inferred reason.
|
|
549
560
|
if (type === "PERMISSION_DENIED" || text.includes("permission_denied")) {
|
|
550
561
|
return { message, type: "permission_error", code: "permission_denied" };
|
package/src/lib/gcp-adc.ts
CHANGED
|
@@ -21,8 +21,10 @@
|
|
|
21
21
|
import { Buffer } from "node:buffer";
|
|
22
22
|
import * as os from "node:os";
|
|
23
23
|
import * as path from "node:path";
|
|
24
|
-
import { readFileSync
|
|
24
|
+
import { readFileSync } from "node:fs";
|
|
25
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
25
26
|
import { GCP_CREDENTIAL_MARKER_PREFIX, providerKeychainEntry } from "../providers/api-key-resolve";
|
|
27
|
+
import { vertexAmbientKeyIsCurrent, type VertexAmbientKeyAuthority } from "../providers/vertex-environment-authority";
|
|
26
28
|
export { isGcpCredentialMaterial } from "./gcp-credential-input";
|
|
27
29
|
import {
|
|
28
30
|
captureConfigGeneration,
|
|
@@ -89,6 +91,7 @@ export function parseGcpCredentialJson(value: string): AdcFileCredentials | unde
|
|
|
89
91
|
interface CachedToken {
|
|
90
92
|
token: string;
|
|
91
93
|
expiresAtMs: number;
|
|
94
|
+
generation: number;
|
|
92
95
|
}
|
|
93
96
|
|
|
94
97
|
interface ServiceAccountCredentials {
|
|
@@ -114,7 +117,12 @@ interface TokenResponse {
|
|
|
114
117
|
}
|
|
115
118
|
|
|
116
119
|
const tokenCache = new Map<string, CachedToken>();
|
|
117
|
-
|
|
120
|
+
type VertexTokenAuthority = { token: string; source: string; generation: number; markerAccount?: string };
|
|
121
|
+
type TokenWaiter = { beforeSend?: () => void };
|
|
122
|
+
type InflightToken = { controller: AbortController; promise: Promise<VertexTokenAuthority>; waiters: Set<TokenWaiter>; settled: boolean };
|
|
123
|
+
const inflight = new Map<string, InflightToken>();
|
|
124
|
+
const sourceObservations = new Map<string, { source: string; generation: number }>();
|
|
125
|
+
let sourceEpoch = 0;
|
|
118
126
|
let lastReconciledGeneration = 0;
|
|
119
127
|
let liveSources = new Set<string>();
|
|
120
128
|
|
|
@@ -165,23 +173,24 @@ function userAdcPath(): string {
|
|
|
165
173
|
return path.join(gcloudConfigDir(), "application_default_credentials.json");
|
|
166
174
|
}
|
|
167
175
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
try {
|
|
175
|
-
const st = statSync(filePath);
|
|
176
|
-
return `${prefix}:${filePath}:${st.size}:${Math.floor(st.mtimeMs)}`;
|
|
177
|
-
} catch {
|
|
178
|
-
return `${prefix}:${filePath}`;
|
|
179
|
-
}
|
|
176
|
+
// Cache identity is keyed and process-local: neither credential contents nor their digest is public.
|
|
177
|
+
const sourceDigestKey = randomBytes(32);
|
|
178
|
+
function sourceTag(kind: string, identity: string, content: string): string {
|
|
179
|
+
const digest = createHmac("sha256", sourceDigestKey)
|
|
180
|
+
.update(kind).update("\0").update(identity).update("\0").update(content).digest("hex");
|
|
181
|
+
return `${kind}:${digest}`;
|
|
180
182
|
}
|
|
181
183
|
|
|
182
|
-
function readJsonFile<T>(filePath: string): T | undefined {
|
|
183
|
-
|
|
184
|
-
|
|
184
|
+
function readJsonFile<T>(filePath: string): { value: T; content: string } | undefined {
|
|
185
|
+
let content: string;
|
|
186
|
+
try {
|
|
187
|
+
content = readFileSync(filePath, "utf8");
|
|
188
|
+
} catch (error) {
|
|
189
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
190
|
+
throw new Error("Vertex ADC credential file could not be read");
|
|
191
|
+
}
|
|
192
|
+
try { return { value: JSON.parse(content) as T, content }; }
|
|
193
|
+
catch { throw new Error("Vertex ADC credential file is invalid"); }
|
|
185
194
|
}
|
|
186
195
|
|
|
187
196
|
/**
|
|
@@ -205,17 +214,17 @@ function loadAdcCredentials(markerAccount: string | undefined): { source: string
|
|
|
205
214
|
if (markerAccount) {
|
|
206
215
|
const creds = readMarkerCredential(markerAccount);
|
|
207
216
|
if (!creds) throw new Error("GCP credential marker is set but its credential could not be read from the OS credential store");
|
|
208
|
-
return { source:
|
|
217
|
+
return { source: sourceTag("marker", markerAccount, JSON.stringify(creds)), creds };
|
|
209
218
|
}
|
|
210
219
|
const gacPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
|
211
220
|
if (gacPath) {
|
|
212
221
|
const creds = readJsonFile<AdcFileCredentials>(gacPath);
|
|
213
222
|
if (!creds) throw new Error(`GOOGLE_APPLICATION_CREDENTIALS points to a missing file: ${gacPath}`);
|
|
214
|
-
return { source:
|
|
223
|
+
return { source: sourceTag("gac", gacPath, creds.content), creds: creds.value };
|
|
215
224
|
}
|
|
216
225
|
const userPath = userAdcPath();
|
|
217
226
|
const creds = readJsonFile<AdcFileCredentials>(userPath);
|
|
218
|
-
if (creds) return { source:
|
|
227
|
+
if (creds) return { source: sourceTag("user", userPath, creds.content), creds: creds.value };
|
|
219
228
|
return undefined;
|
|
220
229
|
}
|
|
221
230
|
|
|
@@ -226,12 +235,24 @@ function loadAdcCredentials(markerAccount: string | undefined): { source: string
|
|
|
226
235
|
* token from a different source. Falls back to "metadata" when no marker/file/env ADC is present.
|
|
227
236
|
*/
|
|
228
237
|
function currentAdcSourceKey(markerAccount: string | undefined): string {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
238
|
+
try {
|
|
239
|
+
return loadAdcCredentials(markerAccount)?.source ?? "metadata";
|
|
240
|
+
} catch {
|
|
241
|
+
return "invalid";
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Every observed source transition gets a fresh incarnation, including A→B→A. */
|
|
246
|
+
function observeAdcSource(markerAccount: string | undefined): { source: string; generation: number } {
|
|
247
|
+
const scope = markerAccount ? `marker:${markerAccount}` : "host";
|
|
248
|
+
const source = currentAdcSourceKey(markerAccount);
|
|
249
|
+
const previous = sourceObservations.get(scope);
|
|
250
|
+
if (previous?.source === source) return previous;
|
|
251
|
+
const next = { source, generation: ++sourceEpoch };
|
|
252
|
+
sourceObservations.delete(scope);
|
|
253
|
+
sourceObservations.set(scope, next);
|
|
254
|
+
if (sourceObservations.size > 512) sourceObservations.delete(sourceObservations.keys().next().value!);
|
|
255
|
+
return next;
|
|
235
256
|
}
|
|
236
257
|
|
|
237
258
|
function base64UrlEncode(bytes: Uint8Array | string): string {
|
|
@@ -286,10 +307,11 @@ function tokenTimeoutSignal(parent: AbortSignal | undefined): AbortSignal {
|
|
|
286
307
|
* bad grant) fail fast. The error message carries only the status code, never the response body
|
|
287
308
|
* (which can leak grant/account details) or the token/key.
|
|
288
309
|
*/
|
|
289
|
-
async function postForToken(body: URLSearchParams, signal: AbortSignal | undefined, fetchImpl: FetchImpl): Promise<TokenResponse> {
|
|
310
|
+
async function postForToken(body: URLSearchParams, signal: AbortSignal | undefined, fetchImpl: FetchImpl, beforeSend: () => void): Promise<TokenResponse> {
|
|
290
311
|
let lastError: unknown;
|
|
291
312
|
for (let attempt = 0; attempt < TOKEN_ATTEMPTS; attempt++) {
|
|
292
313
|
if (signal?.aborted) throw signal.reason ?? new Error("Google OAuth token exchange aborted");
|
|
314
|
+
beforeSend();
|
|
293
315
|
let response: Response;
|
|
294
316
|
try {
|
|
295
317
|
response = await fetchImpl(OAUTH_TOKEN_URL, {
|
|
@@ -316,17 +338,17 @@ async function postForToken(body: URLSearchParams, signal: AbortSignal | undefin
|
|
|
316
338
|
throw lastError instanceof Error ? lastError : new Error("Google OAuth token exchange failed");
|
|
317
339
|
}
|
|
318
340
|
|
|
319
|
-
async function exchangeJwtForToken(creds: ServiceAccountCredentials, signal: AbortSignal | undefined, fetchImpl: FetchImpl): Promise<TokenResponse> {
|
|
341
|
+
async function exchangeJwtForToken(creds: ServiceAccountCredentials, signal: AbortSignal | undefined, fetchImpl: FetchImpl, beforeSend: () => void): Promise<TokenResponse> {
|
|
320
342
|
const now = Math.floor(Date.now() / 1000);
|
|
321
343
|
const assertion = await signJwtRs256(
|
|
322
344
|
{ iss: creds.client_email, scope: CLOUD_PLATFORM_SCOPE, aud: OAUTH_TOKEN_URL, exp: now + 3600, iat: now },
|
|
323
345
|
creds.private_key,
|
|
324
346
|
creds.private_key_id,
|
|
325
347
|
);
|
|
326
|
-
return postForToken(new URLSearchParams({ grant_type: JWT_BEARER_GRANT, assertion }), signal, fetchImpl);
|
|
348
|
+
return postForToken(new URLSearchParams({ grant_type: JWT_BEARER_GRANT, assertion }), signal, fetchImpl, beforeSend);
|
|
327
349
|
}
|
|
328
350
|
|
|
329
|
-
async function exchangeRefreshToken(creds: AuthorizedUserCredentials, signal: AbortSignal | undefined, fetchImpl: FetchImpl): Promise<TokenResponse> {
|
|
351
|
+
async function exchangeRefreshToken(creds: AuthorizedUserCredentials, signal: AbortSignal | undefined, fetchImpl: FetchImpl, beforeSend: () => void): Promise<TokenResponse> {
|
|
330
352
|
return postForToken(
|
|
331
353
|
new URLSearchParams({
|
|
332
354
|
client_id: creds.client_id,
|
|
@@ -336,6 +358,7 @@ async function exchangeRefreshToken(creds: AuthorizedUserCredentials, signal: Ab
|
|
|
336
358
|
}),
|
|
337
359
|
signal,
|
|
338
360
|
fetchImpl,
|
|
361
|
+
beforeSend,
|
|
339
362
|
);
|
|
340
363
|
}
|
|
341
364
|
|
|
@@ -355,14 +378,15 @@ async function fetchMetadataToken(signal: AbortSignal | undefined, fetchImpl: Fe
|
|
|
355
378
|
}
|
|
356
379
|
}
|
|
357
380
|
|
|
358
|
-
async function resolveAccessTokenUncached(markerAccount: string | undefined, signal: AbortSignal | undefined, fetchImpl: FetchImpl): Promise<{ source: string; token: TokenResponse }> {
|
|
381
|
+
async function resolveAccessTokenUncached(markerAccount: string | undefined, signal: AbortSignal | undefined, fetchImpl: FetchImpl, beforeSend: () => void): Promise<{ source: string; token: TokenResponse }> {
|
|
359
382
|
const adc = loadAdcCredentials(markerAccount);
|
|
360
383
|
if (adc) {
|
|
361
384
|
const token = adc.creds.type === "service_account"
|
|
362
|
-
? await exchangeJwtForToken(adc.creds, signal, fetchImpl)
|
|
363
|
-
: await exchangeRefreshToken(adc.creds, signal, fetchImpl);
|
|
385
|
+
? await exchangeJwtForToken(adc.creds, signal, fetchImpl, beforeSend)
|
|
386
|
+
: await exchangeRefreshToken(adc.creds, signal, fetchImpl, beforeSend);
|
|
364
387
|
return { source: adc.source, token };
|
|
365
388
|
}
|
|
389
|
+
beforeSend();
|
|
366
390
|
const metadata = await fetchMetadataToken(signal, fetchImpl);
|
|
367
391
|
if (metadata) return { source: "metadata", token: metadata };
|
|
368
392
|
throw new Error(
|
|
@@ -371,19 +395,21 @@ async function resolveAccessTokenUncached(markerAccount: string | undefined, sig
|
|
|
371
395
|
}
|
|
372
396
|
|
|
373
397
|
/** Returns a Bearer access token for the `Authorization` header on Vertex AI calls (cached + refreshed). */
|
|
374
|
-
export async function
|
|
398
|
+
export async function getVertexAccessTokenWithAuthority(options?: { signal?: AbortSignal; fetch?: FetchImpl; markerAccount?: string; beforeSend?: () => void }): Promise<VertexTokenAuthority> {
|
|
375
399
|
// The marker travels as an argument, never as process-global state: a module-level "active
|
|
376
400
|
// marker" written by the router would race across concurrent requests for different providers
|
|
377
401
|
// and could resolve one provider's Vertex call with another provider's service account. The
|
|
378
402
|
// adapter passes `gcpCredentialMarkerAccount(provider.apiKey)` per request instead.
|
|
379
403
|
const markerAccount = options?.markerAccount;
|
|
404
|
+
options?.signal?.throwIfAborted();
|
|
380
405
|
const fetchImpl = options?.fetch ?? globalThis.fetch.bind(globalThis);
|
|
381
406
|
const skew = getRefreshSkewMs();
|
|
382
407
|
const now = Date.now();
|
|
383
408
|
|
|
384
409
|
// Only serve a cached token that matches the source the next resolve would actually use; prune
|
|
385
410
|
// expired or now-stale (different-source) entries so a credential-source change is honored.
|
|
386
|
-
const
|
|
411
|
+
const expected = observeAdcSource(markerAccount);
|
|
412
|
+
const expectedSource = expected.source;
|
|
387
413
|
// A cached bearer token is usable only while the explicitly selected store entry remains
|
|
388
414
|
// readable. Removal or a locked store must fail closed before the cache can return it.
|
|
389
415
|
if (markerAccount && !readMarkerCredential(markerAccount)) {
|
|
@@ -392,37 +418,130 @@ export async function getVertexAccessToken(options?: { signal?: AbortSignal; fet
|
|
|
392
418
|
}
|
|
393
419
|
const writerGeneration = captureConfigGeneration();
|
|
394
420
|
for (const [source, cached] of tokenCache) {
|
|
395
|
-
if (source === expectedSource && cached.expiresAtMs - skew > now)
|
|
421
|
+
if (source === expectedSource && cached.generation === expected.generation && cached.expiresAtMs - skew > now) {
|
|
422
|
+
return { token: cached.token, source, generation: expected.generation, markerAccount };
|
|
423
|
+
}
|
|
396
424
|
if (cached.expiresAtMs - skew <= now) tokenCache.delete(source);
|
|
397
425
|
}
|
|
398
426
|
|
|
399
427
|
// Dedup in-flight fetches PER source, not globally: if the credential source changes while a
|
|
400
428
|
// fetch is in flight, a new caller must not reuse the old source's promise (cross-source bleed).
|
|
401
|
-
const cacheKey = expectedSource
|
|
402
|
-
|
|
403
|
-
if (
|
|
404
|
-
|
|
405
|
-
|
|
429
|
+
const cacheKey = `${expectedSource}:${expected.generation}`;
|
|
430
|
+
let entry = inflight.get(cacheKey);
|
|
431
|
+
if (!entry) {
|
|
432
|
+
const controller = new AbortController();
|
|
433
|
+
entry = { controller, waiters: new Set(), settled: false, promise: undefined as unknown as Promise<VertexTokenAuthority> };
|
|
434
|
+
const owned = entry;
|
|
435
|
+
const beforeSend = () => {
|
|
436
|
+
const current = observeAdcSource(markerAccount);
|
|
437
|
+
if (current.source !== expected.source || current.generation !== expected.generation) throw new Error("Vertex ADC source changed before token exchange");
|
|
438
|
+
let failure: unknown;
|
|
439
|
+
for (const waiter of owned.waiters) {
|
|
440
|
+
try { waiter.beforeSend?.(); return; }
|
|
441
|
+
catch (error) { failure = error; }
|
|
442
|
+
}
|
|
443
|
+
throw failure ?? new Error("Vertex token exchange has no authorized waiter");
|
|
444
|
+
};
|
|
445
|
+
owned.promise = Promise.resolve().then(async () => {
|
|
406
446
|
try {
|
|
407
|
-
const { source, token } = await resolveAccessTokenUncached(markerAccount,
|
|
447
|
+
const { source, token } = await resolveAccessTokenUncached(markerAccount, controller.signal, fetchImpl, beforeSend);
|
|
448
|
+
const current = observeAdcSource(markerAccount);
|
|
449
|
+
if (source !== expectedSource || current.source !== source || current.generation !== expected.generation) {
|
|
450
|
+
throw new Error("Vertex ADC source changed during token exchange");
|
|
451
|
+
}
|
|
408
452
|
const expiresAtMs = Date.now() + Math.max(0, token.expires_in * 1000);
|
|
409
453
|
if (writerGeneration >= lastReconciledGeneration || liveSources.has(source)) {
|
|
410
|
-
tokenCache.set(source, { token: token.access_token, expiresAtMs });
|
|
454
|
+
tokenCache.set(source, { token: token.access_token, expiresAtMs, generation: expected.generation });
|
|
411
455
|
sweepExpiredOnWrite(Date.now());
|
|
412
456
|
}
|
|
413
|
-
return token.access_token;
|
|
457
|
+
return { token: token.access_token, source, generation: expected.generation, markerAccount };
|
|
414
458
|
} finally {
|
|
415
|
-
|
|
459
|
+
owned.settled = true;
|
|
460
|
+
if (inflight.get(cacheKey) === owned) inflight.delete(cacheKey);
|
|
416
461
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
462
|
+
});
|
|
463
|
+
inflight.set(cacheKey, owned);
|
|
464
|
+
}
|
|
465
|
+
const owned = entry;
|
|
466
|
+
const waiter: TokenWaiter = { beforeSend: options?.beforeSend };
|
|
467
|
+
owned.waiters.add(waiter);
|
|
468
|
+
return new Promise<VertexTokenAuthority>((resolve, reject) => {
|
|
469
|
+
let finished = false;
|
|
470
|
+
const finish = () => {
|
|
471
|
+
if (finished) return false;
|
|
472
|
+
finished = true;
|
|
473
|
+
options?.signal?.removeEventListener("abort", onAbort);
|
|
474
|
+
owned.waiters.delete(waiter);
|
|
475
|
+
if (owned.waiters.size === 0 && !owned.settled) {
|
|
476
|
+
if (inflight.get(cacheKey) === owned) inflight.delete(cacheKey);
|
|
477
|
+
owned.controller.abort();
|
|
478
|
+
}
|
|
479
|
+
return true;
|
|
480
|
+
};
|
|
481
|
+
const onAbort = () => { if (finish()) reject(options?.signal?.reason ?? new Error("Google OAuth token exchange aborted")); };
|
|
482
|
+
options?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
483
|
+
owned.promise.then(value => {
|
|
484
|
+
if (!finish()) return;
|
|
485
|
+
try { waiter.beforeSend?.(); resolve(value); } catch (error) { reject(error); }
|
|
486
|
+
}, error => { if (finish()) reject(error); });
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Compatibility wrapper for callers that only need the access token. */
|
|
491
|
+
export async function getVertexAccessToken(options?: { signal?: AbortSignal; fetch?: FetchImpl; markerAccount?: string }): Promise<string> {
|
|
492
|
+
return (await getVertexAccessTokenWithAuthority(options)).token;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
type VertexRequestAuthority = { source?: string; generation?: number; markerAccount?: string; ambientKey?: VertexAmbientKeyAuthority; target: string; headerDigest: string };
|
|
496
|
+
const requestAuthorities = new WeakMap<object, VertexRequestAuthority>();
|
|
497
|
+
const requestDigestKey = randomBytes(32);
|
|
498
|
+
function requestDigest(value: string): string {
|
|
499
|
+
return createHmac("sha256", requestDigestKey).update(value).digest("hex");
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** Bind the exact credential and target used by a built Vertex request without storing the secret. */
|
|
503
|
+
export function bindVertexRequestAuthority(request: object, target: string, header: string,
|
|
504
|
+
authority: { source: string; generation: number; markerAccount?: string } | { ambientKey: VertexAmbientKeyAuthority }): void {
|
|
505
|
+
requestAuthorities.set(request, {
|
|
506
|
+
target, headerDigest: requestDigest(header),
|
|
507
|
+
...authority,
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Rebuilds reuse the original request object, so transfer or clear its previous authority. */
|
|
512
|
+
export function copyVertexRequestAuthority(from: object, to: object): void {
|
|
513
|
+
const authority = requestAuthorities.get(from);
|
|
514
|
+
if (authority) requestAuthorities.set(to, authority);
|
|
515
|
+
else requestAuthorities.delete(to);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export function hasVertexRequestAuthority(request: object): boolean {
|
|
519
|
+
return requestAuthorities.has(request);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Fail closed if the locally observable credential source or final request changed. */
|
|
523
|
+
export function vertexRequestAuthorityIsCurrent(request: object, target?: string, headers?: Headers): boolean {
|
|
524
|
+
const authority = requestAuthorities.get(request);
|
|
525
|
+
if (!authority) return true;
|
|
526
|
+
if (authority.source) {
|
|
527
|
+
const current = observeAdcSource(authority.markerAccount);
|
|
528
|
+
if (current.source !== authority.source || current.generation !== authority.generation) return false;
|
|
529
|
+
}
|
|
530
|
+
if (authority.ambientKey && !vertexAmbientKeyIsCurrent(authority.ambientKey)) return false;
|
|
531
|
+
if (target !== undefined && target !== authority.target) return false;
|
|
532
|
+
if (headers) {
|
|
533
|
+
const actual = authority.source ? headers.get("authorization") : headers.get("x-goog-api-key");
|
|
534
|
+
if (!actual || requestDigest(actual) !== authority.headerDigest) return false;
|
|
535
|
+
}
|
|
536
|
+
return true;
|
|
420
537
|
}
|
|
421
538
|
|
|
422
539
|
/** Test seam: restores complete process-local token and reconciliation state. */
|
|
423
540
|
export function __resetVertexTokenCache(): void {
|
|
424
541
|
tokenCache.clear();
|
|
542
|
+
for (const entry of inflight.values()) entry.controller.abort();
|
|
425
543
|
inflight.clear();
|
|
544
|
+
sourceObservations.clear();
|
|
426
545
|
lastReconciledGeneration = 0;
|
|
427
546
|
liveSources = new Set();
|
|
428
547
|
}
|
package/src/lib/jsonc.ts
CHANGED
|
@@ -99,11 +99,13 @@ function stripTrailingCommas(text: string): string {
|
|
|
99
99
|
* stripped unconditionally: never probed with a strict `JSON.parse` first,
|
|
100
100
|
* because materializing a deeply nested document before the rewrite guard's
|
|
101
101
|
* depth ceiling would bypass that guard's resource contract. The passes are
|
|
102
|
-
* identity on valid strict JSON
|
|
102
|
+
* identity on valid strict JSON. One leading byte-order mark is removed first;
|
|
103
|
+
* `//`, `/*`, and a comma before `}` or `]`
|
|
103
104
|
* can only appear inside strings there, which the strippers never touch.
|
|
104
105
|
*/
|
|
105
106
|
export function canonicalizeJsonc(text: string): string {
|
|
106
|
-
|
|
107
|
+
const source = text.startsWith("\uFEFF") ? text.slice(1) : text;
|
|
108
|
+
return stripTrailingCommas(stripJsonComments(source));
|
|
107
109
|
}
|
|
108
110
|
|
|
109
111
|
/**
|