opencode-ahp 0.1.7 → 0.1.9

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/src/options.ts CHANGED
@@ -35,24 +35,19 @@ export interface Options {
35
35
  token: string | null;
36
36
  /** Origin allowlist; the token is always required regardless. */
37
37
  allowedOrigins: string[] | "*";
38
+ /**
39
+ * Directory allowlist — absolute path prefixes (design §3.3). Empty
40
+ * (default) → unrestricted. Non-empty: a client-named path must resolve
41
+ * under one of the prefixes (after symlink resolution) — the
42
+ * `createSession.workingDirectories` target and the unconfined
43
+ * `resource*` commands. A non-absolute entry is a configuration error:
44
+ * the host fails closed (AHP off).
45
+ */
46
+ allowedWorkingDirectories: string[];
38
47
  /** Native TLS via Bun.serve on the same listener (off-LAN). */
39
48
  tls: TlsOptions | null;
40
49
  /** Plain-HTTP health endpoint (no auth). */
41
50
  healthPath: string;
42
- /**
43
- * Keep the opencode location loaded against the idle timeout (default
44
- * `experimental.location_idle_timeout`, 60 minutes) via a periodic durable
45
- * touch of an internal anchor session. With this on, the
46
- * `location_idle_timeout: false` config entry is not needed. The anchor
47
- * shows in the TUI session list as "opencode-ahp (keep-alive)"; AHP
48
- * clients never see it.
49
- */
50
- keepAlive: boolean;
51
- /**
52
- * Minutes between keep-alive touches; must be well below the effective
53
- * idle timeout. 10 leaves sixfold headroom under the 60-minute default.
54
- */
55
- keepAliveIntervalMinutes: number;
56
51
  /** Global actions kept for reconnect replay; older gaps → snapshot. */
57
52
  replayWindow: number;
58
53
  /**
@@ -73,10 +68,11 @@ export const BUILTIN_OPTIONS: Options = {
73
68
  path: "/ahp",
74
69
  token: null,
75
70
  allowedOrigins: "*",
71
+ // No restriction by default (an opt-in hardening); a non-absolute entry
72
+ // is a configuration error the plugin entry fails closed on.
73
+ allowedWorkingDirectories: [],
76
74
  tls: null,
77
75
  healthPath: "/healthz",
78
- keepAlive: true,
79
- keepAliveIntervalMinutes: 10,
80
76
  replayWindow: 1000,
81
77
  // Event capture is off by default (a busy turn emits dozens of lines);
82
78
  // the LAN test server script enables it.
@@ -111,6 +107,13 @@ function validateAllowedOrigins(v: unknown): string[] | "*" | null {
111
107
  return null;
112
108
  }
113
109
 
110
+ /** A directory-allowlist value: an array of non-empty strings. */
111
+ function validateAllowedDirs(v: unknown): string[] | null {
112
+ if (!Array.isArray(v)) return null;
113
+ if (!v.every((x) => typeof x === "string" && x.length > 0)) return null;
114
+ return [...v];
115
+ }
116
+
114
117
  function validateTls(v: unknown): TlsOptions | null {
115
118
  if (!isRecord(v) || !isString(v["keyPath"]) || !isString(v["certPath"])) return null;
116
119
  return { keyPath: v["keyPath"], certPath: v["certPath"] };
@@ -252,14 +255,11 @@ export function resolveOptions(
252
255
  allowedOrigins:
253
256
  pickNullable("allowedOrigins", validateAllowedOrigins, BUILTIN_OPTIONS.allowedOrigins) ??
254
257
  BUILTIN_OPTIONS.allowedOrigins,
258
+ allowedWorkingDirectories:
259
+ pickNullable("allowedWorkingDirectories", validateAllowedDirs, BUILTIN_OPTIONS.allowedWorkingDirectories) ??
260
+ BUILTIN_OPTIONS.allowedWorkingDirectories,
255
261
  tls: pickNullable("tls", validateTls, BUILTIN_OPTIONS.tls),
256
262
  healthPath: pick("healthPath", isUrlPath, BUILTIN_OPTIONS.healthPath),
257
- keepAlive: pick("keepAlive", isBool, BUILTIN_OPTIONS.keepAlive),
258
- keepAliveIntervalMinutes: pick(
259
- "keepAliveIntervalMinutes",
260
- isPosInt,
261
- BUILTIN_OPTIONS.keepAliveIntervalMinutes,
262
- ),
263
263
  replayWindow: pick("replayWindow", isPosInt, BUILTIN_OPTIONS.replayWindow),
264
264
  logEvents: pick("logEvents", isBool, BUILTIN_OPTIONS.logEvents),
265
265
  capabilities: resolveCapabilities(file["capabilities"], ctx["capabilities"]),
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Directory allowlist (design §3.3): the optional
3
+ * `allowedWorkingDirectories` option — an allowlist of absolute path
4
+ * prefixes. When configured, client-named paths must resolve under one of
5
+ * the prefixes (after symlink resolution): the
6
+ * `createSession.workingDirectories` target and the unconfined `resource*`
7
+ * commands (`resourceResolve` / `resourceList` / `resourceMkdir`).
8
+ *
9
+ * Pure decision logic — filesystem access is injected
10
+ * (`PathPolicyEnv`), so unit tests never touch the disk.
11
+ */
12
+
13
+ import { isAbsolute, normalize } from "node:path";
14
+ import { isPathInside } from "./host-util.js";
15
+
16
+ /**
17
+ * The filesystem half of the decision, injected to keep this module pure:
18
+ * canonicalize the symlinks of the EXISTING prefix portion of `path` —
19
+ * walk up to the deepest existing ancestor, canonicalize it, and re-append
20
+ * the missing tail. The result may not yet exist (the tail is never
21
+ * created). May throw (e.g. EACCES on an existing ancestor).
22
+ */
23
+ export interface PathPolicyEnv {
24
+ resolveExisting: (path: string) => Promise<string>;
25
+ }
26
+
27
+ /**
28
+ * The directory allowlist. `prefixes` are already normalized (see
29
+ * `normalizeDirPrefix`; the plugin entry additionally canonicalizes the
30
+ * ones that exist), `env` supplies the target resolution. An empty prefix
31
+ * list is the unrestricted policy.
32
+ */
33
+ export class PathPolicy {
34
+ private constructor(
35
+ private readonly prefixes: readonly string[],
36
+ private readonly env?: PathPolicyEnv,
37
+ ) {}
38
+
39
+ /** No prefixes — every path is permitted. */
40
+ static unrestricted(): PathPolicy {
41
+ return new PathPolicy([]);
42
+ }
43
+
44
+ static restricted(prefixes: readonly string[], env: PathPolicyEnv): PathPolicy {
45
+ return new PathPolicy(prefixes, env);
46
+ }
47
+
48
+ /**
49
+ * Whether `path` is permitted: its symlink-resolved form (existing
50
+ * prefix portion canonicalized, missing tail re-appended) must be a
51
+ * prefix itself or strictly inside one. When the resolved form cannot
52
+ * be determined (the resolver throws — e.g. EACCES on an existing
53
+ * ancestor) the decision defers: the underlying operation runs and
54
+ * produces its own errno error.
55
+ */
56
+ async allows(path: string): Promise<boolean> {
57
+ if (this.prefixes.length === 0) return true;
58
+ let resolved: string;
59
+ try {
60
+ resolved = await this.env!.resolveExisting(path);
61
+ } catch {
62
+ return true;
63
+ }
64
+ return this.prefixes.some((prefix) => isPathInside(resolved, prefix));
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Lexically normalize an allowlist prefix: resolve `.`/`..` segments,
70
+ * drop the trailing slash (root stays `/`). Throws when `p` is not
71
+ * absolute — a relative prefix would silently scope the host to the wrong
72
+ * place, so it is a configuration error (the plugin entry fails closed:
73
+ * AHP off, opencode keeps serving).
74
+ */
75
+ export function normalizeDirPrefix(p: string): string {
76
+ if (!isAbsolute(p)) throw new Error(`not an absolute path: ${p}`);
77
+ let n = normalize(p);
78
+ // POSIX preserves a leading double slash; on Linux it is just `/`.
79
+ if (n.startsWith("//")) n = n.slice(1);
80
+ if (n.length > 1 && n.endsWith("/")) n = n.slice(0, -1);
81
+ return n;
82
+ }
package/src/transport.ts CHANGED
@@ -157,7 +157,9 @@ interface BunUpgradeResult {
157
157
  }
158
158
  interface BunServer {
159
159
  port: number;
160
- stop(): void;
160
+ /** `force`: synchronously drain every connection instead of letting
161
+ * open WebSockets outlive the stop (Bun server.stop(force?)). */
162
+ stop(force?: boolean): void;
161
163
  upgrade(req: BunRequest, options?: { data?: unknown }): BunUpgradeResult;
162
164
  }
163
165
  interface BunServeOptions {
@@ -270,7 +272,14 @@ export function createListener(opts: ListenerOptions, callbacks: TransportCallba
270
272
  if (ws && ws.readyState === 1) ws.close(code, reason);
271
273
  },
272
274
  stop() {
273
- server.stop();
275
+ // Force stop: a graceful stop lets open WebSockets drain on their
276
+ // own, and the port stays bound while they do — a location reload
277
+ // racing that window fails to rebind ("Is port in use?"), leaving
278
+ // the fresh host listener-less while the stale socket keeps serving
279
+ // (observed on the LAN test server). Teardown means
280
+ // "the location is going" anyway, so dropping the connections is
281
+ // the right semantics regardless.
282
+ server.stop(true);
274
283
  openSockets.clear();
275
284
  },
276
285
  };
package/src/keep-alive.ts DELETED
@@ -1,125 +0,0 @@
1
- /**
2
- * Location keep-alive.
3
- *
4
- * opencode v2 unloads idle locations after `experimental.location_idle_timeout`
5
- * (default 60 minutes). `LocationActivity` (packages/core/src/location-activity.ts)
6
- * "touches" a location on every **durable** session event and evicts it on a
7
- * one-minute sweep only when it is past its TTL, unoccupied, and unretained.
8
- * `Session.setMetadata` publishes the durable `session.metadata.updated` event
9
- * unconditionally, so periodically updating the metadata of a dedicated anchor
10
- * session keeps the location — and with it the AHP listener — loaded without
11
- * any user config (`location_idle_timeout: false` is no longer required).
12
- *
13
- * The anchor session is visible in the opencode TUI session list (the plugin
14
- * surface cannot archive it); the AHP host filters it out by its
15
- * deterministic ID from every client-facing surface.
16
- *
17
- * Cold boot is an architectural limit, not a keep-alive problem: plugins load
18
- * per location (`Node.makeLocationNode`) and cannot run before the location
19
- * boots, and no config boots a location at server start. The anchor session's
20
- * first touch therefore only helps once the location is up — the one-time boot
21
- * step stays (open the project once, or a headless location-boot request).
22
- *
23
- * Pure module: session access and the timer are dependency-injected, so this
24
- * is unit-tested without an OpenCode runtime (house pattern).
25
- */
26
-
27
- import { errorMessage } from "./error.js";
28
-
29
- /**
30
- * Deterministic anchor-session ID. Valid per the `Session.ID` schema (any
31
- * `ses`-prefixed string); deterministic so reloads reuse the same session
32
- * instead of accumulating one per boot cycle, and so the AHP facade can
33
- * filter it by a constant (no metadata reads, no list scans).
34
- */
35
- export const KEEPALIVE_SESSION_ID = "ses_ahp_keepalive";
36
-
37
- export interface KeepAliveDeps {
38
- /**
39
- * Get-or-create the anchor session. Resolves when the session is usable;
40
- * rejects (→ keep-alive stays off, logged) when it is not.
41
- */
42
- readonly ensureSession: () => Promise<void>;
43
- /** One durable touch of the anchor session (`session.metadata.updated`). */
44
- readonly touch: () => Promise<void>;
45
- /**
46
- * Interval between touches in ms. Must be well below the effective
47
- * `location_idle_timeout` (default 60 minutes) — the default 10 minutes
48
- * leaves sixfold headroom.
49
- */
50
- readonly intervalMs: number;
51
- readonly log: (msg: string) => void;
52
- /** Injectable for tests; defaults to `setInterval`. */
53
- readonly schedule?: (fn: () => void, ms: number) => unknown;
54
- /** Injectable for tests; defaults to `clearInterval`. */
55
- readonly unschedule?: (handle: unknown) => void;
56
- }
57
-
58
- /**
59
- * Periodic durable touch of the anchor session. Every failure path logs and
60
- * stays up (R2): a failing touch retries on the next tick, a failing anchor
61
- * setup leaves the keep-alive off (opencode's idle timeout applies as before).
62
- */
63
- export class KeepAlive {
64
- private timer: unknown = null;
65
- private inFlight = false;
66
- private stopped = false;
67
- private ready = false;
68
-
69
- constructor(private readonly deps: KeepAliveDeps) {}
70
-
71
- /**
72
- * Ensures the anchor session and starts ticking. Never throws.
73
- * @returns true when the keep-alive is active.
74
- */
75
- async start(): Promise<boolean> {
76
- try {
77
- await this.deps.ensureSession();
78
- } catch (e) {
79
- this.deps.log(
80
- `keep-alive could not prepare its anchor session (${errorMessage(e)}); ` +
81
- `opencode's idle timeout applies (experimental.location_idle_timeout)`,
82
- );
83
- return false;
84
- }
85
- this.ready = true;
86
- this.startTicking();
87
- this.deps.log(
88
- `keep-alive active: the anchor session is touched every ${Math.round(this.deps.intervalMs / 60_000)} min, ` +
89
- `holding the location against the idle timeout`,
90
- );
91
- return true;
92
- }
93
-
94
- /** Starts the periodic touch. Idempotent; a no-op before a ready session. */
95
- startTicking(): void {
96
- if (!this.ready || this.timer !== null || this.stopped) return;
97
- const schedule = this.deps.schedule ?? ((fn: () => void, ms: number) => setInterval(fn, ms));
98
- this.timer = schedule(() => {
99
- void this.tick();
100
- }, this.deps.intervalMs);
101
- }
102
-
103
- /** One touch. Guarded against overlap; never throws. */
104
- async tick(): Promise<void> {
105
- if (!this.ready || this.stopped || this.inFlight) return;
106
- this.inFlight = true;
107
- try {
108
- await this.deps.touch();
109
- } catch (e) {
110
- this.deps.log(`keep-alive touch failed (${errorMessage(e)}); retrying on the next tick`);
111
- } finally {
112
- this.inFlight = false;
113
- }
114
- }
115
-
116
- /** Stops the periodic touch (location teardown). Idempotent. */
117
- stop(): void {
118
- this.stopped = true;
119
- if (this.timer !== null) {
120
- const unschedule = this.deps.unschedule ?? ((handle: unknown) => clearInterval(handle as ReturnType<typeof setInterval>));
121
- unschedule(this.timer);
122
- this.timer = null;
123
- }
124
- }
125
- }