Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions packages/core/src/npm-request-diagnostic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { AsyncLocalStorage } from "node:async_hooks"
import http from "node:http"

type OwnerEvent = { owner: string; target: "loopback" | "redacted"; path: "plugin-package" | "other" }
let installed: (() => { restored: boolean; conflict: boolean }) | undefined

/** Private diagnostic: observes node:http.request only, never headers or raw URLs. */
export function observeRequestOwner(input: {
enabled: boolean
owner: () => string | undefined
report: (event: OwnerEvent) => void
}) {
if (!input.enabled) return { dispose: () => ({ restored: false, conflict: false }) }
if (installed) throw new Error("request owner observer already installed")
const original = http.request
let disposed = false
const wrapper = function (this: unknown, ...args: Parameters<typeof http.request>) {
// Invoke exactly once, with the original receiver and arguments. Original
// exceptions propagate unchanged; observational failures must not escape.
const request = Reflect.apply(original, this, args)
if (disposed) return request
try {
// The returned request reflects overload resolution, including overrides.
// Never serialize its host/path values. Unknown targets stay redacted.
const host = request.host
input.report({
owner: input.owner() ?? "unattributed",
target: typeof host === "string" && /^(127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/.test(host) ? "loopback" : "redacted",
path: typeof request.path === "string" && request.path.includes("opencode-ai") ? "plugin-package" : "other",
})
} catch {}
return request
} as typeof http.request
const dispose = () => {
if (disposed) return { restored: false, conflict: false }
disposed = true
const owned = http.request === wrapper
if (owned) http.request = original
installed = undefined
return { restored: owned, conflict: !owned }
}
http.request = wrapper
installed = dispose
return { dispose }
}

const requestOwner = new AsyncLocalStorage<string>()
export function withRequestOwner<A>(owner: string, admission: string | undefined, run: () => Promise<A>): Promise<A> {
// Only generated opaque IDs may enter the observer. No path/config data.
const safeOwner = /^\d+-\d+$/.test(owner) ? owner : "unattributed"
const safeAdmission = admission && /^\d+-admission-\d+$/.test(admission) ? admission : "unattributed"
return requestOwner.run(`${safeOwner}/${safeAdmission}`, run)
}
export function installRequestOwnerDiagnostic() {
return observeRequestOwner({
enabled: process.env.OPENCODE_TEST_INSTALL_OWNER_DIAGNOSTICS === "1",
owner: () => requestOwner.getStore(),
report: (event) => console.log("INSTALL_OWNER", JSON.stringify({ phase: "http-request-owner", at: Date.now(), ...event })),
})
}
23 changes: 20 additions & 3 deletions packages/core/src/npm.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { withRequestOwner } from "./npm-request-diagnostic"
export { installRequestOwnerDiagnostic } from "./npm-request-diagnostic"
import { createHash } from "node:crypto"
export * as Npm from "./npm"

import path from "path"
Expand Down Expand Up @@ -39,6 +42,7 @@ export interface Interface {
}

export class Service extends Context.Service<Service, Interface>()("@opencode/Npm") {}
export const DiagnosticAdmission = Context.Reference<string | undefined>("@opencode/Npm/DiagnosticAdmission", { defaultValue: () => undefined })

const illegal = process.platform === "win32" ? new Set(["<", ">", ":", '"', "|", "?", "*"]) : undefined

Expand Down Expand Up @@ -69,6 +73,8 @@ interface ArboristTree {
edgesOut: Map<string, { to?: ArboristNode }>
}

let ownerSequence = 0

const layer = Layer.effect(
Service,
Effect.gen(function* () {
Expand All @@ -79,10 +85,19 @@ const layer = Layer.effect(
const directory = (pkg: string) => path.join(global.cache, "packages", sanitize(pkg))
const reify = (input: { dir: string; add?: string[] }) =>
Effect.gen(function* () {
const diagnostic = process.env.OPENCODE_TEST_INSTALL_OWNER_DIAGNOSTICS === "1"
const admission = yield* DiagnosticAdmission
const owner = diagnostic ? `${process.pid}-${++ownerSequence}` : ""
const safeDir = diagnostic ? createHash("sha256").update(input.dir).digest("hex").slice(0, 16) : ""
if (diagnostic) console.log("INSTALL_OWNER", JSON.stringify({ phase: "reify-before-lock", at: Date.now(), admission: admission ?? "unattributed", owner, dir: safeDir, disabled: process.env.OPENCODE_DISABLE_CONFIG_DEP_INSTALL === undefined ? "absent" : ["1", "true"].includes(process.env.OPENCODE_DISABLE_CONFIG_DEP_INSTALL.toLowerCase()) }))
yield* flock.acquire(`npm-install:${input.dir}`)
if (diagnostic) console.log("INSTALL_OWNER", JSON.stringify({ phase: "reify-after-lock", at: Date.now(), admission: admission ?? "unattributed", owner, dir: safeDir, disabled: process.env.OPENCODE_DISABLE_CONFIG_DEP_INSTALL === undefined ? "absent" : ["1", "true"].includes(process.env.OPENCODE_DISABLE_CONFIG_DEP_INSTALL.toLowerCase()) }))
const { Arborist } = yield* Effect.promise(() => import("@npmcli/arborist"))
const add = input.add ?? []
const npmOptions = yield* NpmConfig.load(input.dir)
const registry = typeof npmOptions.registry === "string" ? npmOptions.registry : ""
const loopback = /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(?::[0-9]+)?(?:\/|$)/.test(registry)
if (diagnostic) console.log("INSTALL_OWNER", JSON.stringify({ phase: "npm-config-ready", at: Date.now(), admission: admission ?? "unattributed", owner, dir: safeDir, disabled: process.env.OPENCODE_DISABLE_CONFIG_DEP_INSTALL === undefined ? "absent" : ["1", "true"].includes(process.env.OPENCODE_DISABLE_CONFIG_DEP_INSTALL.toLowerCase()), registry: loopback ? new URL(registry).origin : "non-loopback-redacted" }))
// Arborist has no Effect-aware cancellation: interrupting the fiber alone would
// abandon the reify promise while registry fetches keep running in the
// background. Thread an AbortSignal through Arborist -> pacote ->
Expand All @@ -100,13 +115,15 @@ const layer = Layer.effect(
ignoreScripts: true,
})
return yield* Effect.tryPromise({
try: () =>
arborist.reify({
try: () => {
const run = () => arborist.reify({
...fetchOptions,
add,
save: true,
saveType: "prod",
}),
})
return diagnostic ? withRequestOwner(owner, admission, run) : run()
},
catch: (cause) =>
new InstallFailedError({
cause,
Expand Down
3 changes: 3 additions & 0 deletions packages/core/test/fixture/mock-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ export class MockRegistry {

private handle(req: http.IncomingMessage, res: http.ServerResponse) {
const rawUrl = req.url || ""
if (process.env.OPENCODE_TEST_INSTALL_OWNER_DIAGNOSTICS === "1") {
console.log("INSTALL_OWNER", JSON.stringify({ phase: "registry-request", at: Date.now(), pid: process.pid, registry: this.url, method: req.method, path: req.url?.includes("opencode-ai") ? "plugin-package" : req.url?.includes("security/advisories") ? "npm-audit" : "other-redacted" }))
}
this.requests.push({
method: req.method || "GET",
url: rawUrl,
Expand Down
82 changes: 82 additions & 0 deletions packages/core/test/fixture/npm-request-diagnostic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { expect, test } from "bun:test"
import http from "node:http"
import { observeRequestOwner } from "../../src/npm-request-diagnostic"
test("request owner observer preserves calls and owns only its active lifetime", () => {
const before = http.request
const active: {dispose:()=>unknown}[]=[]
const observe = (input: Parameters<typeof observeRequestOwner>[0]) => { const value=observeRequestOwner(input); active.push(value); return value }
try {
expect(observe({enabled:false,owner:()=>undefined,report:()=>{}}).dispose()).toEqual({restored:false,conflict:false})
expect(http.request).toBe(before)
const calls: {self:unknown,args:unknown[]}[]=[]
const result={host:"127.0.0.1",path:"/@opencode-ai/plugin"}
const sentinel=new Error("original failure")
http.request=function(this:unknown,...args:any[]){calls.push({self:this,args});if(args[0]==="throw")throw sentinel;return result} as any
const original=http.request
const events:unknown[]=[]
const observer=observe({enabled:true,owner:()=>"alpha",report:e=>events.push(e)})
const receiver={}
const url=new URL("http://private.invalid/raw-secret")
const override={hostname:"127.0.0.1",port:1234,headers:{authorization:"SECRET"}}
const callback=()=>{}
const args=[url,override,callback]
expect(Reflect.apply(http.request,receiver,args)).toBe(result)
expect(calls[0].self).toBe(receiver)
expect(calls[0].args).toEqual(args)
expect(calls[0].args[0]).toBe(url)
expect(calls[0].args[1]).toBe(override)
expect(calls[0].args[2]).toBe(callback)
expect(JSON.stringify(override)).toBe('{"hostname":"127.0.0.1","port":1234,"headers":{"authorization":"SECRET"}}')
expect(events).toEqual([{owner:"alpha",target:"loopback",path:"plugin-package"}])
expect(()=>Reflect.apply(http.request,receiver,["throw"])).toThrow(sentinel)
expect(()=>observe({enabled:true,owner:()=>undefined,report:()=>{}})).toThrow("already installed")
expect(observer.dispose()).toEqual({restored:true,conflict:false})
expect(http.request).toBe(original)
const throwing=observe({enabled:true,owner:()=>{throw sentinel},report:()=>{throw sentinel}})
expect(Reflect.apply(http.request,receiver,[url])).toBe(result)
throwing.dispose()
const reportThrowing=observe({enabled:true,owner:()=>"beta",report:()=>{throw sentinel}})
expect(Reflect.apply(http.request,receiver,[url])).toBe(result)
reportThrowing.dispose()
const oldEvents:unknown[]=[]
const conflicted=observe({enabled:true,owner:()=>"old",report:e=>oldEvents.push(e)})
const captured=http.request
const oldReports=oldEvents.length
const later=function(this:unknown,...args:unknown[]){return Reflect.apply(captured,this,args)} as any
http.request=later
expect(conflicted.dispose()).toEqual({restored:false,conflict:true})
expect(http.request).toBe(later)
expect(Reflect.apply(http.request,receiver,[url])).toBe(result)
expect(oldEvents.length).toBe(oldReports)
const freshEvents:unknown[]=[]
const fresh=observe({enabled:true,owner:()=>"fresh",report:e=>freshEvents.push(e)})
expect(Reflect.apply(http.request,receiver,[url])).toBe(result)
expect(freshEvents).toHaveLength(1)
expect(oldEvents.length).toBe(oldReports)
fresh.dispose()
http.request=before
console.log("PASS optin/single-install/receiver-args-identity/result/errors/observer-containment/owned-restore/conflict-no-clobber")

} finally {
for (const observer of active.reverse()) observer.dispose()
http.request=before
}

})

test("observer assertion failure cleanup releases singleton and restores request", () => {
const original=http.request
let observer: ReturnType<typeof observeRequestOwner> | undefined
expect(() => {
try {
observer=observeRequestOwner({enabled:true,owner:()=>undefined,report:()=>{}})
throw new Error("simulated assertion failure")
} finally {
observer?.dispose()
http.request=original
}
}).toThrow("simulated assertion failure")
expect(http.request).toBe(original)
const next=observeRequestOwner({enabled:true,owner:()=>undefined,report:()=>{}})
try { expect(http.request).not.toBe(original) } finally { next.dispose();http.request=original }
})
11 changes: 10 additions & 1 deletion packages/opencode/src/config/config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { httpClient } from "@opencode-ai/core/effect/app-node-platform"
import { serviceUse } from "@opencode-ai/core/effect/service-use"
Expand Down Expand Up @@ -172,6 +173,8 @@ function writableGlobal(info: Info) {
return next
}

let diagnosticAdmissionSequence = 0

const layer = Layer.effect(
Service,
Effect.gen(function* () {
Expand Down Expand Up @@ -471,7 +474,12 @@ const layer = Layer.effect(

yield* ensureGitignore(dir).pipe(Effect.orDie)

if (!Flag.OPENCODE_DISABLE_CONFIG_DEP_INSTALL) {
const installDisabled = Flag.OPENCODE_DISABLE_CONFIG_DEP_INSTALL
const diagnosticAdmission = process.env.OPENCODE_TEST_INSTALL_OWNER_DIAGNOSTICS === "1" ? `${process.pid}-admission-${++diagnosticAdmissionSequence}` : undefined
if (diagnosticAdmission) {
console.log("INSTALL_OWNER", JSON.stringify({ phase: "config-admission", admission: diagnosticAdmission, at: Date.now(), pid: process.pid, dir: createHash("sha256").update(dir).digest("hex").slice(0, 16), disabled: installDisabled }))
}
if (!installDisabled) {
// Bound the background install (design proposal: 60s, override with
// OPENCODE_CONFIG_DEP_INSTALL_TIMEOUT_MS). A stalled registry install must
// not keep waitForDependencies — and therefore plugin loading and instance
Expand All @@ -492,6 +500,7 @@ const layer = Layer.effect(
],
})
.pipe(
Effect.provideService(Npm.DiagnosticAdmission, diagnosticAdmission),
Effect.timeout(Duration.millis(timeoutMs)),
Effect.catchTag("TimeoutError", () =>
Effect.logWarning("background dependency install timed out, continuing without it", {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { test, expect, describe, afterEach, beforeEach } from "bun:test"
import { test, expect, describe, afterEach, beforeEach, beforeAll, afterAll } from "bun:test"
import path from "path"
import fs from "fs/promises"
import { Effect, Layer, Logger } from "effect"
Expand All @@ -22,6 +22,23 @@ import { AccountTest } from "../fake/account"
import { tmpdir } from "../fixture/fixture"
import { MockRegistry } from "../fixture/mock-registry"

// Diagnostic-only branch. This opt-in is process-wide while this file runs.
const priorOwnerDiagnostics = process.env.OPENCODE_TEST_INSTALL_OWNER_DIAGNOSTICS
let ownerObserver: ReturnType<typeof Npm.installRequestOwnerDiagnostic> | undefined
beforeAll(() => {
process.env.OPENCODE_TEST_INSTALL_OWNER_DIAGNOSTICS = "1"
ownerObserver = Npm.installRequestOwnerDiagnostic()
})
afterAll(() => {
try {
const outcome = ownerObserver?.dispose()
if (outcome?.conflict) console.log("INSTALL_OWNER", JSON.stringify({ phase: "observer-dispose-conflict" }))
} finally {
if (priorOwnerDiagnostics === undefined) delete process.env.OPENCODE_TEST_INSTALL_OWNER_DIAGNOSTICS
else process.env.OPENCODE_TEST_INSTALL_OWNER_DIAGNOSTICS = priorOwnerDiagnostics
}
})

const unexpectedHttp = HttpClient.make((request) =>
Effect.die(`unexpected http request: ${request.method} ${request.url}`),
)
Expand Down Expand Up @@ -256,6 +273,7 @@ describe("Config Dependency Install Integration with MockRegistry", () => {
})

test("skips dependency install when OPENCODE_DISABLE_CONFIG_DEP_INSTALL is set", async () => {
console.log("INSTALL_OWNER", JSON.stringify({ phase: "disabled-case-start", pid: process.pid }))
process.env.OPENCODE_DISABLE_CONFIG_DEP_INSTALL = "1"

await using tmp = await tmpdir()
Expand All @@ -282,6 +300,7 @@ describe("Config Dependency Install Integration with MockRegistry", () => {

expect(result._tag).toBe("Success")
// Mock registry must NOT have received any requests
console.log("INSTALL_OWNER", JSON.stringify({ phase: "disabled-case-requests", pid: process.pid, registry: registry.url, requests: registry.requests.map((r) => ({ path: r.url.includes("opencode-ai") ? "plugin-package" : "other-redacted", method: r.method, timestamp: r.timestamp })) }))
expect(registry.requests).toEqual([])
})

Expand Down
Loading