@vibecontrols/plugin-sdk 2026.530.5 → 2026.531.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.
@@ -30,6 +30,13 @@ declare const FULL_TRUST_CAPS: Required<PluginCapabilities>;
30
30
  type PluginTag = "backend" | "frontend" | "cli" | "provider" | "adapter" | "integration";
31
31
  type PrerequisiteKind = "binary" | "npm" | "pip" | "cargo" | "manual";
32
32
  type SupportedOS = "linux" | "darwin" | "win32";
33
+ /**
34
+ * Provider-registry type a META plugin's providers register under, mirroring
35
+ * the agent `ServiceRegistry`'s provider types. Declared on `MetaProviderRef`
36
+ * so the agent can ELECT a platform default (not merely install it) without
37
+ * having to scan every registry type to discover which one a provider owns.
38
+ */
39
+ type ProviderType = "tunnel" | "session" | "ai" | "plan";
33
40
  interface Prerequisite {
34
41
  name: string;
35
42
  kind: PrerequisiteKind;
@@ -57,6 +64,15 @@ interface MetaProviderRef {
57
64
  * meta. Empty/undefined = opt-in only (never auto-installed at bootstrap).
58
65
  */
59
66
  defaultOn?: ReadonlyArray<SupportedOS>;
67
+ /**
68
+ * The agent `ServiceRegistry` provider type this entry registers under
69
+ * (e.g. "session" for tmux/wezterm/zellij). When set, the agent elects the
70
+ * `defaultOn`-matching provider of this type as the registry default for the
71
+ * current platform (win32 → wezterm, linux/darwin → tmux) instead of only
72
+ * installing it. Optional — when omitted the agent infers the type by
73
+ * scanning the registry, so older metas keep working.
74
+ */
75
+ providerType?: ProviderType;
60
76
  }
61
77
  /**
62
78
  * Context passed to a plugin's `onNuke` hook. The agent calls `onNuke`
@@ -181,6 +197,90 @@ interface HostServices {
181
197
  * agent overrides only if it needs to override scope behaviour.
182
198
  */
183
199
  paths?: PathHelpers;
200
+ /**
201
+ * Iframe-bridge primitives. The agent injects implementations of the
202
+ * single-use signed iframe-ticket + scoped UI-cookie family that the
203
+ * `/ui/<plugin>` and other iframe-mount surfaces use. Meta plugins
204
+ * that mount their own auth-shim against an upstream proxy (e.g. the
205
+ * generic `/plan/<sid>/*` reverse proxy in `vibe-plugin-plan`) consume
206
+ * these instead of importing agent internals — keeps the agent
207
+ * provider-agnostic.
208
+ *
209
+ * Cookie-name convention: the host plants `vt_ui_<sid>` for the scoped
210
+ * UI cookie family. Meta plugins must NOT hardcode an upstream proxy's
211
+ * own cookie name; the upstream's 200/401 verdict is the authority.
212
+ *
213
+ * Optional — older agents may not provide this; plugins must check.
214
+ */
215
+ iframeBridge?: IframeBridge;
216
+ }
217
+ /**
218
+ * Iframe-bridge primitives exposed by the agent host. Mirror the
219
+ * helpers in vibecontrols-agent/src/core/iframe-tokens.ts +
220
+ * core/ui-server.ts + middleware/auth.ts.
221
+ *
222
+ * Used by meta plugins (e.g. plan) that mount their own auth-shim in
223
+ * front of a provider's reverse proxy: the meta plugin owns the
224
+ * generic `/plan/<sid>/*` bridge, the provider owns the proxy itself,
225
+ * and the agent stays provider-agnostic — its `/plan/*` route is a
226
+ * blind `pluginRoutesApp.handle(request)` delegator.
227
+ */
228
+ interface IframeBridge {
229
+ /**
230
+ * The agent's current API key. Plugins inject this server-side into
231
+ * forwarded sub-requests so the upstream proxy authenticates them.
232
+ * MUST NOT be sent to the browser. Resolved lazily each call so key
233
+ * rotations are picked up without snapshotting.
234
+ */
235
+ getAgentApiKey(): string;
236
+ /**
237
+ * Verify a single-use signed iframe ticket against an expected request
238
+ * path. Consumes the ticket's JTI on success — replays return false.
239
+ */
240
+ verifyIframeToken(token: string, expectedPath: string): boolean;
241
+ /**
242
+ * Verify a scoped UI-cookie token against an expected sid (the cookie
243
+ * is `vt_ui_<sid>`). NOT single-use — long-lived (≤ TTL) credential
244
+ * the browser sends with every sub-request after the bootstrap exchange.
245
+ */
246
+ verifyUiCookieToken(token: string, sid: string): boolean;
247
+ /**
248
+ * Mint a scoped UI-cookie token for `sid` with the given TTL (seconds).
249
+ * Returns the token (caller assembles the `Set-Cookie` header) plus the
250
+ * absolute expiry in epoch milliseconds.
251
+ */
252
+ issueUiCookieToken(sid: string, ttlSeconds: number): {
253
+ token: string;
254
+ expiresAt: number;
255
+ };
256
+ /**
257
+ * Extract an iframe ticket from a Request — honours
258
+ * `x-vibe-iframe-token` header first, then `?vt=` query. Returns null
259
+ * if neither is present. `path` is reserved for future per-path
260
+ * source selection; pass the request's URL pathname.
261
+ */
262
+ getIframeTokenFromRequest(req: Request, path: string): string | null;
263
+ /**
264
+ * Extract the `vt_ui_<sid>` cookie value from a Request, or null when
265
+ * absent. Cookie-name lookup, not signature verification — pair with
266
+ * `verifyUiCookieToken` to authenticate.
267
+ */
268
+ getUiCookieFromRequest(req: Request, sid: string): string | null;
269
+ /**
270
+ * True when `sid` is safe to interpolate into a cookie name + Path
271
+ * attribute (charset gate matching the agent's UI-cookie family).
272
+ * Plugins should fall through to ticket-only flow when this returns
273
+ * false to avoid cookie-name / Path injection.
274
+ */
275
+ isValidUiPluginName(sid: string): boolean;
276
+ /**
277
+ * The agent's canonical `Content-Security-Policy` `frame-ancestors`
278
+ * source list (incl. the `VIBE_UI_FRAME_ANCESTORS` override). Plugins
279
+ * that serve their own bootstrap HTML MUST reuse this — keeps the
280
+ * allowed embedders consistent with `/ui/<plugin>` and prevents
281
+ * drift-prone copies.
282
+ */
283
+ frameAncestorsCsp(): string;
184
284
  }
185
285
  interface ProfileContext {
186
286
  name: string;
@@ -246,4 +346,4 @@ interface VibePlugin {
246
346
  }
247
347
  type VibePluginFactory = (ctx: ProfileContext) => VibePlugin;
248
348
 
249
- export { FULL_TRUST_CAPS, type HostServices, type MetaProviderRef, type NukeResult, type PluginCapabilities, type PluginNukeContext, type PluginTag, type Prerequisite, type PrerequisiteKind, type ProfileContext, type SdkLogger, type ServiceRegistry, type StorageProvider, type SupportedOS, type VibePlugin, type VibePluginFactory };
349
+ export { FULL_TRUST_CAPS, type HostServices, type IframeBridge, type MetaProviderRef, type NukeResult, type PluginCapabilities, type PluginNukeContext, type PluginTag, type Prerequisite, type PrerequisiteKind, type ProfileContext, type ProviderType, type SdkLogger, type ServiceRegistry, type StorageProvider, type SupportedOS, type VibePlugin, type VibePluginFactory };
@@ -0,0 +1,34 @@
1
+ import * as node_fs from 'node:fs';
2
+
3
+ interface SafePathResult {
4
+ path: string;
5
+ realPath: string;
6
+ }
7
+ declare const MAX_FILE_READ_BYTES: number;
8
+ declare const MAX_DIRECTORY_ENTRIES: number;
9
+ declare function isSensitivePath(filePath: string): boolean;
10
+ declare function isProtectedPath(filePath: string): boolean;
11
+ declare function resolveSafePath(inputPath: string, options?: {
12
+ mustExist?: boolean;
13
+ forWrite?: boolean;
14
+ }): Promise<SafePathResult>;
15
+ declare function assertReadableFileSize(filePath: string): Promise<void>;
16
+ /**
17
+ * A8 — atomic, symlink-safe file read.
18
+ *
19
+ * Closes the resolve-then-open TOCTOU window in the prior implementation
20
+ * (a symlink swap between `lstat` and `readFile` could redirect the read
21
+ * to /etc/passwd or any other root-owned file).
22
+ *
23
+ * POSIX: `open(2)` with `O_NOFOLLOW` errors with `ELOOP` if the final
24
+ * path component is a symlink, and we read via the resulting fd so the
25
+ * file identity is pinned for the duration of the read.
26
+ *
27
+ * Windows: `O_NOFOLLOW` isn't honoured the same way — we lstat, reject
28
+ * symlinks explicitly, then re-stat by realpath and confirm the same
29
+ * inode before reading.
30
+ */
31
+ declare function safeReadFile(filePath: string): Buffer;
32
+ declare function listDirectoryCapped(filePath: string): Promise<node_fs.Dirent<string>[]>;
33
+
34
+ export { MAX_DIRECTORY_ENTRIES, MAX_FILE_READ_BYTES, type SafePathResult, assertReadableFileSize, isProtectedPath, isSensitivePath, listDirectoryCapped, resolveSafePath, safeReadFile };
@@ -0,0 +1,255 @@
1
+ import { realpathSync, promises, lstatSync, statSync, openSync, constants, readSync, closeSync, fstatSync } from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+
5
+ // src/host/fs-safety.ts
6
+ function positiveIntFromEnv(name, fallback) {
7
+ const parsed = parseInt(process.env[name] ?? "", 10);
8
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
9
+ }
10
+ var MAX_FILE_READ_BYTES = positiveIntFromEnv(
11
+ "VIBECONTROLS_MAX_FILE_READ_BYTES",
12
+ 10 * 1024 * 1024
13
+ );
14
+ var MAX_DIRECTORY_ENTRIES = positiveIntFromEnv("VIBECONTROLS_MAX_DIRECTORY_ENTRIES", 2e3);
15
+ var SENSITIVE_PATTERNS = [
16
+ /(?:^|\/)\.env(?:\..*)?$/,
17
+ /\.pem$/,
18
+ /\.key$/,
19
+ /(?:^|\/)id_rsa(?:$|\.)/,
20
+ /(?:^|\/)\.ssh(?:\/|$)/,
21
+ /(?:^|\/)\.git\/config$/,
22
+ /(?:^|\/)\.npmrc$/
23
+ ];
24
+ var POSIX_PROTECTED_PATHS = ["/", "/etc", "/usr", "/bin", "/sbin", "/var", "/opt"];
25
+ var WIN32_PROTECTED_PATHS = [
26
+ "C:\\Windows",
27
+ "C:\\Program Files",
28
+ "C:\\Program Files (x86)",
29
+ "C:\\ProgramData"
30
+ ];
31
+ function protectedPathsForHost() {
32
+ return process.platform === "win32" ? WIN32_PROTECTED_PATHS : POSIX_PROTECTED_PATHS;
33
+ }
34
+ function normalizeForCompare(p) {
35
+ return process.platform === "win32" ? p.toLowerCase() : p;
36
+ }
37
+ function configuredRoots() {
38
+ const raw = process.env.VIBECONTROLS_ALLOWED_ROOTS;
39
+ if (raw) {
40
+ return raw.split(path.delimiter).map((entry) => entry.trim()).filter(Boolean);
41
+ }
42
+ return [process.cwd(), os.homedir(), os.tmpdir()].filter(Boolean);
43
+ }
44
+ async function realpathIfExists(candidate) {
45
+ try {
46
+ return await promises.realpath(candidate);
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ async function allowedRootRealpaths() {
52
+ const roots = [];
53
+ for (const root of configuredRoots()) {
54
+ const resolved = path.resolve(root);
55
+ const real = await realpathIfExists(resolved) ?? resolved;
56
+ if (!roots.includes(real)) roots.push(real);
57
+ }
58
+ return roots;
59
+ }
60
+ function isWithinRoot(target, root) {
61
+ const relative = path.relative(root, target);
62
+ return relative === "" || !!relative && !relative.startsWith("..") && !path.isAbsolute(relative);
63
+ }
64
+ async function assertUnderAllowedRoot(realPath) {
65
+ const roots = await allowedRootRealpaths();
66
+ if (!roots.some((root) => isWithinRoot(realPath, root))) {
67
+ throw new Error("Access denied: path is outside allowed directories");
68
+ }
69
+ }
70
+ async function nearestExistingParent(candidate) {
71
+ let current = path.dirname(candidate);
72
+ while (current && current !== path.dirname(current)) {
73
+ const real = await realpathIfExists(current);
74
+ if (real) return real;
75
+ current = path.dirname(current);
76
+ }
77
+ const rootReal = await realpathIfExists(current || path.parse(candidate).root);
78
+ if (!rootReal) throw new Error("Path parent does not exist");
79
+ return rootReal;
80
+ }
81
+ async function assertFinalIsNotSymlink(candidate) {
82
+ const stat = await promises.lstat(path.resolve(candidate)).catch(() => null);
83
+ if (stat?.isSymbolicLink()) {
84
+ throw new Error("Access denied: symbolic links are not allowed");
85
+ }
86
+ }
87
+ function isSensitivePath(filePath) {
88
+ return SENSITIVE_PATTERNS.some((pattern) => pattern.test(filePath));
89
+ }
90
+ function looksLikePosixProtected(raw) {
91
+ if (!raw.startsWith("/")) return false;
92
+ const fwd = raw.replace(/\\/g, "/").replace(/\/+/g, "/");
93
+ return POSIX_PROTECTED_PATHS.some((p) => fwd === p || fwd.startsWith(p === "/" ? "/" : `${p}/`));
94
+ }
95
+ function isProtectedPath(filePath) {
96
+ const normalized = path.resolve(filePath);
97
+ const realIfExists = (() => {
98
+ try {
99
+ return realpathSync(normalized);
100
+ } catch {
101
+ return null;
102
+ }
103
+ })();
104
+ const candidates = realIfExists ? [normalized, realIfExists] : [normalized];
105
+ const tmpRaw = os.tmpdir();
106
+ const homeRaw = os.homedir();
107
+ const tmpReal = (() => {
108
+ try {
109
+ return realpathSync(tmpRaw);
110
+ } catch {
111
+ return tmpRaw;
112
+ }
113
+ })();
114
+ const homeReal = (() => {
115
+ try {
116
+ return realpathSync(homeRaw);
117
+ } catch {
118
+ return homeRaw;
119
+ }
120
+ })();
121
+ const sep = path.sep;
122
+ const allowPrefixes = [tmpRaw, tmpReal, homeRaw, homeReal];
123
+ for (const candidate of candidates) {
124
+ const cmp = normalizeForCompare(candidate);
125
+ if (allowPrefixes.some((prefix) => {
126
+ const pCmp = normalizeForCompare(prefix);
127
+ return cmp === pCmp || cmp.startsWith(pCmp + sep);
128
+ })) {
129
+ return false;
130
+ }
131
+ }
132
+ if (candidates.some((candidate) => {
133
+ const cmp = normalizeForCompare(candidate);
134
+ return protectedPathsForHost().some((protectedPath) => {
135
+ const pCmp = normalizeForCompare(protectedPath);
136
+ return cmp === pCmp || cmp.startsWith(pCmp + sep);
137
+ });
138
+ })) {
139
+ return true;
140
+ }
141
+ return looksLikePosixProtected(filePath);
142
+ }
143
+ async function resolveSafePath(inputPath, options = {}) {
144
+ if (!inputPath || inputPath.includes("\0")) {
145
+ throw new Error("Invalid path");
146
+ }
147
+ const normalized = path.resolve(inputPath);
148
+ await assertFinalIsNotSymlink(normalized);
149
+ const realPath = await realpathIfExists(normalized);
150
+ if (realPath) {
151
+ await assertUnderAllowedRoot(realPath);
152
+ return { path: normalized, realPath };
153
+ }
154
+ if (options.mustExist) {
155
+ throw new Error("Path not found");
156
+ }
157
+ if (!options.forWrite) {
158
+ await assertUnderAllowedRoot(normalized);
159
+ return { path: normalized, realPath: normalized };
160
+ }
161
+ const parentReal = await nearestExistingParent(normalized);
162
+ await assertUnderAllowedRoot(parentReal);
163
+ return { path: normalized, realPath: normalized };
164
+ }
165
+ async function assertReadableFileSize(filePath) {
166
+ const stats = await promises.stat(filePath);
167
+ if (stats.isFile() && stats.size > MAX_FILE_READ_BYTES) {
168
+ throw new Error(
169
+ `File is too large to read safely (${stats.size} bytes, max ${MAX_FILE_READ_BYTES})`
170
+ );
171
+ }
172
+ }
173
+ function safeReadFile(filePath) {
174
+ if (process.platform === "win32") {
175
+ const lstat = lstatSync(filePath);
176
+ if (lstat.isSymbolicLink()) {
177
+ throw new Error("Access denied: symbolic links are not allowed");
178
+ }
179
+ const real = realpathSync.native(filePath);
180
+ const realStat = statSync(real);
181
+ if (realStat.ino !== lstat.ino) {
182
+ throw new Error("Access denied: path swapped under check");
183
+ }
184
+ if (realStat.size > MAX_FILE_READ_BYTES) {
185
+ throw new Error(
186
+ `File is too large to read safely (${realStat.size} bytes, max ${MAX_FILE_READ_BYTES})`
187
+ );
188
+ }
189
+ const fd2 = openSync(real, constants.O_RDONLY);
190
+ try {
191
+ const buf = Buffer.allocUnsafe(realStat.size);
192
+ let read = 0;
193
+ while (read < realStat.size) {
194
+ const n = readSync(fd2, buf, read, realStat.size - read, read);
195
+ if (n <= 0) break;
196
+ read += n;
197
+ }
198
+ return read === realStat.size ? buf : buf.subarray(0, read);
199
+ } finally {
200
+ closeSync(fd2);
201
+ }
202
+ }
203
+ let fd;
204
+ try {
205
+ fd = openSync(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
206
+ } catch (err) {
207
+ const code = err.code;
208
+ if (code === "ELOOP" || code === "EMLINK") {
209
+ throw new Error("Access denied: symbolic links are not allowed", {
210
+ cause: err
211
+ });
212
+ }
213
+ throw err;
214
+ }
215
+ try {
216
+ const stat = fstatSync(fd);
217
+ if (stat.size > MAX_FILE_READ_BYTES) {
218
+ throw new Error(
219
+ `File is too large to read safely (${stat.size} bytes, max ${MAX_FILE_READ_BYTES})`
220
+ );
221
+ }
222
+ const buf = Buffer.allocUnsafe(stat.size);
223
+ let read = 0;
224
+ while (read < stat.size) {
225
+ const n = readSync(fd, buf, read, stat.size - read, read);
226
+ if (n <= 0) break;
227
+ read += n;
228
+ }
229
+ return read === stat.size ? buf : buf.subarray(0, read);
230
+ } finally {
231
+ closeSync(fd);
232
+ }
233
+ }
234
+ async function listDirectoryCapped(filePath) {
235
+ const dir = await promises.opendir(filePath);
236
+ const entries = [];
237
+ try {
238
+ for await (const entry of dir) {
239
+ entries.push(entry);
240
+ if (entries.length > MAX_DIRECTORY_ENTRIES) {
241
+ throw new Error(`Directory has too many entries (>${MAX_DIRECTORY_ENTRIES})`);
242
+ }
243
+ }
244
+ } finally {
245
+ const closeResult = dir.close?.();
246
+ if (closeResult && typeof closeResult.catch === "function") {
247
+ await closeResult.catch(() => void 0);
248
+ }
249
+ }
250
+ return entries;
251
+ }
252
+
253
+ export { MAX_DIRECTORY_ENTRIES, MAX_FILE_READ_BYTES, assertReadableFileSize, isProtectedPath, isSensitivePath, listDirectoryCapped, resolveSafePath, safeReadFile };
254
+ //# sourceMappingURL=fs-safety.js.map
255
+ //# sourceMappingURL=fs-safety.js.map
@@ -0,0 +1,9 @@
1
+ interface RequestIpServer {
2
+ requestIP(request: Request): {
3
+ address: string;
4
+ } | null;
5
+ }
6
+ declare function isLikelyLocalRequest(request: Request, server?: RequestIpServer | null): boolean;
7
+ declare function denyNonLocalMutation(request: Request, envOverride: string, server?: RequestIpServer | null): string | null;
8
+
9
+ export { denyNonLocalMutation, isLikelyLocalRequest };
@@ -0,0 +1,23 @@
1
+ // src/host/request-security.ts
2
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"]);
3
+ function normalizedHost(hostname) {
4
+ return hostname.toLowerCase().replace(/^\[|\]$/g, "");
5
+ }
6
+ function isLikelyLocalRequest(request, server) {
7
+ const headers = request.headers;
8
+ if (headers.has("cf-connecting-ip") || headers.has("x-forwarded-for") || headers.has("x-real-ip") || headers.has("forwarded")) {
9
+ return false;
10
+ }
11
+ const peerAddress = server?.requestIP(request)?.address;
12
+ if (!peerAddress) return false;
13
+ return LOOPBACK_HOSTS.has(normalizedHost(peerAddress));
14
+ }
15
+ function denyNonLocalMutation(request, envOverride, server) {
16
+ if (isLikelyLocalRequest(request, server)) return null;
17
+ if (process.env[envOverride] === "1") return null;
18
+ return `This operation is local-only by default. Set ${envOverride}=1 to allow it over a tunnel.`;
19
+ }
20
+
21
+ export { denyNonLocalMutation, isLikelyLocalRequest };
22
+ //# sourceMappingURL=request-security.js.map
23
+ //# sourceMappingURL=request-security.js.map
package/dist/index.js CHANGED
@@ -461,7 +461,7 @@ function isPortFree(port) {
461
461
  server.close(() => resolve(true));
462
462
  });
463
463
  try {
464
- server.listen({ port, host: "127.0.0.1" });
464
+ server.listen({ port, host: "0.0.0.0" });
465
465
  } catch {
466
466
  resolve(false);
467
467
  }
@@ -57,7 +57,7 @@ function isPortFree(port) {
57
57
  server.close(() => resolve(true));
58
58
  });
59
59
  try {
60
- server.listen({ port, host: "127.0.0.1" });
60
+ server.listen({ port, host: "0.0.0.0" });
61
61
  } catch {
62
62
  resolve(false);
63
63
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibecontrols/plugin-sdk",
3
- "version": "2026.530.5",
3
+ "version": "2026.531.1",
4
4
  "type": "module",
5
5
  "description": "VibeControls Plugin SDK — shared contract, lifecycle, CLI, telemetry, storage helpers for all vibe-plugin-* packages.",
6
6
  "engines": {
@@ -87,6 +87,14 @@
87
87
  "./host/paths": {
88
88
  "import": "./dist/host/paths.js",
89
89
  "types": "./dist/host/paths.d.ts"
90
+ },
91
+ "./host/fs-safety": {
92
+ "import": "./dist/host/fs-safety.js",
93
+ "types": "./dist/host/fs-safety.d.ts"
94
+ },
95
+ "./host/request-security": {
96
+ "import": "./dist/host/request-security.js",
97
+ "types": "./dist/host/request-security.d.ts"
90
98
  }
91
99
  },
92
100
  "scripts": {