@foldkit/vite-plugin 0.27.1-canary.606ca39eaf1c → 0.27.1-canary.76fa0d1ee2a5

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/README.md CHANGED
@@ -203,19 +203,19 @@ To include the overlay in production, list `@foldkit/devtools` in regular `depen
203
203
 
204
204
  During development, the plugin starts a WebSocket relay for the [`@foldkit/devtools-mcp`](https://www.npmjs.com/package/@foldkit/devtools-mcp) server. Through the relay, an AI agent can inspect a running Foldkit app and dispatch Messages.
205
205
 
206
- By default, the relay uses the dev server's listener at `/__foldkit/devtools-mcp`. The plugin publishes its address to a registry private to your user, and the MCP server finds it by project. You do not need to coordinate a port between them. The registry lives under `XDG_RUNTIME_DIR` when that is set, or under the operating system's temporary directory. `FOLDKIT_DEVTOOLS_RELAY_DIRECTORY` selects another directory.
206
+ By default, the relay listens at `/__foldkit/devtools-mcp` on its own loopback port. WebSocket handlers on the Vite dev server cannot close its connection. Each dev server publishes its relay's address to a private registry, so the MCP server can find it without a configured port.
207
207
 
208
- The relay follows Vite's `server.host` setting. If you expose the dev server with `--host`, a client still needs the random token in the published address to inspect a Model or dispatch a Message. The plugin will not publish that token into a registry directory owned by another user or readable by other users. It reports the problem in the console.
208
+ The registry lives under `XDG_RUNTIME_DIR` when set, `~/.cache` on macOS and Linux, or the user's temporary directory on Windows. `FOLDKIT_DEVTOOLS_RELAY_DIRECTORY` selects another directory. On Windows, that directory must be a direct child of the user's temporary directory.
209
209
 
210
- In middleware mode, the relay uses a free loopback port because there is no HTTP server to share. It also uses a free loopback port for HTTPS dev servers, whose self-signed certificates the MCP server cannot verify. The plugin publishes these addresses for discovery in the same way.
210
+ For automatic discovery, the relay publishes a random token with its address. The MCP client signs a connection challenge with the token and checks the relay's response before sending tool requests. The plugin refuses to publish the record if another user can read or replace the registry directory. It also rejects symlinks and junctions, checks directory ACLs on macOS, and uses PowerShell to check ownership, access rights, and reparse points on Windows. If the check fails, the plugin reports the problem in the console.
211
211
 
212
- To use a fixed port, set `devToolsMcpPort` in your Vite config:
212
+ An agent on another host cannot reach the automatic loopback relay. To connect from another host, or when the registry check fails, set a fixed port in your Vite config:
213
213
 
214
214
  ```typescript
215
215
  plugins: [foldkit({ devToolsMcpPort: 9988 })]
216
216
  ```
217
217
 
218
- Set `FOLDKIT_DEVTOOLS_MCP_PORT` to the same value for the MCP server. A fixed port opens a separate socket on every interface and does not require a token. Use this setting on platforms where directory ownership cannot be verified, including Windows, because the plugin cannot publish a relay address there.
218
+ Set `FOLDKIT_DEVTOOLS_MCP_PORT` to the same value for the MCP server. If the agent runs elsewhere, also set `FOLDKIT_DEVTOOLS_MCP_HOST` to the dev server's host. A fixed port listens on every interface without a token. Do not use it on a shared or untrusted network.
219
219
 
220
220
  `devToolsMcpPort: false` disables the relay. The relay does not start during Vitest runs or in production builds.
221
221
 
package/dist/index.d.ts CHANGED
@@ -8,13 +8,14 @@ export { type ViewIdentityTransformResult, foldkitViewIdentity, transformViewIde
8
8
  /** Options for the `foldkit` Vite plugin. */
9
9
  export type FoldkitPluginOptions = Readonly<{
10
10
  /**
11
- * By default, the dev server hosts the DevTools MCP relay and publishes its
12
- * address for the MCP server to find. Middleware and HTTPS servers use a
13
- * separate loopback listener. Published addresses carry an access token.
11
+ * By default, the DevTools MCP relay listens on a loopback port of its own
12
+ * and publishes its address for the MCP server to find. Automatically
13
+ * discovered addresses carry an access token.
14
14
  *
15
15
  * A number starts an unauthenticated listener on that port on every
16
16
  * interface; set `FOLDKIT_DEVTOOLS_MCP_PORT` in the MCP server to match.
17
- * `false` disables the relay. Vitest never starts it.
17
+ * Do not use a fixed port on a shared or untrusted network. `false`
18
+ * disables the relay. Vitest never starts it.
18
19
  */
19
20
  devToolsMcpPort?: number | false;
20
21
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA6CA,OAAO,KAAK,EAGV,MAAM,EAIP,MAAM,MAAM,CAAA;AAOb,OAAO,EAAE,KAAK,mBAAmB,EAAgB,MAAM,YAAY,CAAA;AAKnE,OAAO,EAAE,KAAK,iBAAiB,EAAc,MAAM,UAAU,CAAA;AAG7D,OAAO,EAAE,KAAK,eAAe,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AACzE,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,oBAAoB,EACpB,KAAK,eAAe,EACpB,KAAK,mBAAmB,EACxB,KAAK,uBAAuB,EAC5B,YAAY,GACb,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,KAAK,iBAAiB,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAC7D,OAAO,EACL,KAAK,2BAA2B,EAChC,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,mBAAmB,CAAA;AAE1B,6CAA6C;AAC7C,MAAM,MAAM,oBAAoB,GAAG,QAAQ,CAAC;IAC1C;;;;;;;;OAQG;IACH,eAAe,CAAC,EAAE,MAAM,GAAG,KAAK,CAAA;IAChC;;;;;;;OAOG;IACH,GAAG,CAAC,EAAE,IAAI,CACR,iBAAiB,EACjB,SAAS,GAAG,gBAAgB,GAAG,aAAa,GAAG,aAAa,CAC7D,GACC,CACI,QAAQ,CAAC;QACP,kFAAkF;QAClF,WAAW,EAAE,MAAM,CAAA;QACnB,WAAW,CAAC,EAAE,KAAK,CAAA;QACnB;;;;;;;;WAQG;QACH,KAAK,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC,mBAAmB,EAAE,aAAa,CAAC,CAAA;KAC3D,CAAC,GACF,QAAQ,CAAC;QACP,kEAAkE;QAClE,WAAW,CAAC,EAAE,KAAK,CAAA;QACnB,WAAW,CAAC,EAAE,MAAM,CAAA;QACpB,KAAK,CAAC,EAAE,KAAK,CAAA;KACd,CAAC,CACL,CAAA;IACH;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAC,CAAA;AA86BF,eAAO,MAAM,OAAO,aAAa,oBAAoB,KAAQ,KAAK,CAAC,MAAM,CA+IxE,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAgDA,OAAO,KAAK,EAEV,MAAM,EAIP,MAAM,MAAM,CAAA;AAQb,OAAO,EAAE,KAAK,mBAAmB,EAAgB,MAAM,YAAY,CAAA;AAMnE,OAAO,EAAE,KAAK,iBAAiB,EAAc,MAAM,UAAU,CAAA;AAG7D,OAAO,EAAE,KAAK,eAAe,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AACzE,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,oBAAoB,EACpB,KAAK,eAAe,EACpB,KAAK,mBAAmB,EACxB,KAAK,uBAAuB,EAC5B,YAAY,GACb,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,KAAK,iBAAiB,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAC7D,OAAO,EACL,KAAK,2BAA2B,EAChC,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,mBAAmB,CAAA;AAE1B,6CAA6C;AAC7C,MAAM,MAAM,oBAAoB,GAAG,QAAQ,CAAC;IAC1C;;;;;;;;;OASG;IACH,eAAe,CAAC,EAAE,MAAM,GAAG,KAAK,CAAA;IAChC;;;;;;;OAOG;IACH,GAAG,CAAC,EAAE,IAAI,CACR,iBAAiB,EACjB,SAAS,GAAG,gBAAgB,GAAG,aAAa,GAAG,aAAa,CAC7D,GACC,CACI,QAAQ,CAAC;QACP,kFAAkF;QAClF,WAAW,EAAE,MAAM,CAAA;QACnB,WAAW,CAAC,EAAE,KAAK,CAAA;QACnB;;;;;;;;WAQG;QACH,KAAK,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC,mBAAmB,EAAE,aAAa,CAAC,CAAA;KAC3D,CAAC,GACF,QAAQ,CAAC;QACP,kEAAkE;QAClE,WAAW,CAAC,EAAE,KAAK,CAAA;QACnB,WAAW,CAAC,EAAE,MAAM,CAAA;QACpB,KAAK,CAAC,EAAE,KAAK,CAAA;KACd,CAAC,CACL,CAAA;IACH;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAC,CAAA;AAy/BF,eAAO,MAAM,OAAO,aAAa,oBAAoB,KAAQ,KAAK,CAAC,MAAM,CA+IxE,CAAA"}
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
- import { Array, Clock, ConfigProvider, Console, Crypto, Data, Duration, Effect, Exit, Fiber, HashMap, HashSet, Layer, Match, Option, Predicate, Queue, Ref, Schedule, Schema, Stream, pipe, } from 'effect';
1
+ import { Array, Clock, ConfigProvider, Console, Crypto, Data, Duration, Effect, Exit, Fiber, HashMap, Layer, Match, Number, Option, Order, Predicate, Queue, Ref, Schedule, Schema, Stream, pipe, } from 'effect';
2
2
  import { Event as DevToolsEvent, EventFrame, RELAY_RECORD_VERSION, RequestFrame, Response, ResponseFrame, } from 'foldkit/devtools-protocol';
3
3
  import { PreserveModelMessage, RequestModelMessage, RestoreModelMessage, } from 'foldkit/model-preservation';
4
- import { timingSafeEqual } from 'node:crypto';
4
+ import { createHmac, timingSafeEqual } from 'node:crypto';
5
5
  import { createServer as createHttpServer, } from 'node:http';
6
6
  import { WebSocketServer } from 'ws';
7
+ import * as NodeChildProcessSpawner from '@effect/platform-node/NodeChildProcessSpawner';
7
8
  import * as NodeCrypto from '@effect/platform-node/NodeCrypto';
8
9
  import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem';
9
10
  import * as NodePath from '@effect/platform-node/NodePath';
@@ -12,6 +13,7 @@ import { foldkitBuildToken } from './buildToken.js';
12
13
  import { devToolsOverlayPlugin } from './devToolsOverlay.js';
13
14
  import { crawlFoldkitPackages } from './foldkitPackages.js';
14
15
  import { publishRelayRecord, retireRelayRecord } from './relayRegistry.js';
16
+ import { relayRegistryTrust } from './relayRegistryTrust.js';
15
17
  import { foldkitSsr } from './ssr.js';
16
18
  import { foldkitViewIdentity } from './viewIdentity.js';
17
19
  export { brandDistDirectory } from './brandDist.js';
@@ -84,21 +86,20 @@ const Event = Data.taggedEnum();
84
86
  const makeState = Effect.gen(function* () {
85
87
  const preservedModels = yield* Ref.make(HashMap.empty());
86
88
  const connectedRuntimes = yield* Ref.make(HashMap.empty());
87
- const mcpClients = yield* Ref.make(HashSet.empty());
88
- const clientConnections = yield* Ref.make(HashMap.empty());
89
- const trackedClients = yield* Ref.make(HashSet.empty());
89
+ const nextSequence = yield* Ref.make(0);
90
90
  const state = {
91
91
  preservedModels,
92
92
  connectedRuntimes,
93
- mcpClients,
94
- clientConnections,
95
- trackedClients,
93
+ nextSequence,
94
+ mcpClients: new Set(),
95
+ trackedClients: new WeakSet(),
96
96
  };
97
97
  return state;
98
98
  });
99
99
  const encodeResponseFrameJson = Schema.encodeUnknownSync(Schema.fromJsonString(ResponseFrame));
100
100
  class WebSocketSendFailed extends Data.TaggedError('WebSocketSendFailed') {
101
101
  }
102
+ const byConnectionOrder = Order.mapInput(Order.Number, ({ sequence }) => sequence);
102
103
  // HANDLERS
103
104
  const handlePreserveModelReceived = (state, payload) => Exit.match(Schema.decodeUnknownExit(PreserveModelMessage)(payload), {
104
105
  onFailure: error => Console.warn('[foldkit:preserve] failed to decode preserve-model payload', error),
@@ -144,40 +145,34 @@ const handleBrowserEventFrameReceived = (state, data, client) => Exit.match(Sche
144
145
  }),
145
146
  });
146
147
  const handleConnectedEvent = (state, event, client) => Effect.gen(function* () {
147
- yield* Ref.update(state.connectedRuntimes, HashMap.set(event.runtime.connectionId, event.runtime));
148
- yield* Ref.update(state.clientConnections, currentMap => {
149
- const existing = HashMap.get(currentMap, client).pipe(Option.getOrElse(() => HashSet.empty()));
150
- return HashMap.set(currentMap, client, HashSet.add(existing, event.runtime.connectionId));
151
- });
148
+ const sequence = yield* Ref.getAndUpdate(state.nextSequence, Number.increment);
149
+ const connectedRuntime = {
150
+ runtime: event.runtime,
151
+ sequence,
152
+ client,
153
+ };
154
+ yield* Ref.update(state.connectedRuntimes, HashMap.set(event.runtime.connectionId, connectedRuntime));
152
155
  yield* Console.log(`[foldkit:devTools] runtime connected: ${event.runtime.connectionId} (${event.runtime.title})`);
153
156
  });
154
157
  const handleDisconnectedEvent = (state, event) => Effect.gen(function* () {
155
158
  yield* Ref.update(state.connectedRuntimes, HashMap.remove(event.connectionId));
156
159
  yield* Console.log(`[foldkit:devTools] runtime disconnected: ${event.connectionId}`);
157
160
  });
158
- const pruneRuntime = (state, connectionId) => Effect.gen(function* () {
159
- yield* Ref.update(state.connectedRuntimes, HashMap.remove(connectionId));
160
- yield* Console.log(`[foldkit:devTools] runtime pruned (socket close): ${connectionId}`);
161
- });
162
- const pruneRuntimesForClient = (state, connectionIds) => Effect.forEach(Array.fromIterable(connectionIds), connectionId => pruneRuntime(state, connectionId), { discard: true });
163
161
  const handleViteClientClosed = (state, client) => Effect.gen(function* () {
164
- const connections = yield* Ref.get(state.clientConnections);
165
- yield* Option.match(HashMap.get(connections, client), {
166
- onNone: () => Effect.void,
167
- onSome: connectionIds => pruneRuntimesForClient(state, connectionIds),
168
- });
169
- yield* Ref.update(state.clientConnections, HashMap.remove(client));
170
- yield* Ref.update(state.trackedClients, HashSet.remove(client));
162
+ const prunedConnectionIds = yield* Ref.modify(state.connectedRuntimes, current => [
163
+ pipe(current, HashMap.filter(connectedRuntime => connectedRuntime.client === client), HashMap.keys, Array.fromIterable),
164
+ HashMap.filter(current, connectedRuntime => connectedRuntime.client !== client),
165
+ ]);
166
+ yield* Effect.forEach(prunedConnectionIds, connectionId => Console.log(`[foldkit:devTools] runtime pruned (socket close): ${connectionId}`), { discard: true });
171
167
  });
172
168
  const handleBrowserResponseFrameReceived = (state, data) => Exit.match(Schema.decodeUnknownExit(ResponseFrame)(data), {
173
169
  onFailure: error => Console.warn('[foldkit:devTools] failed to decode browser response frame', error),
174
170
  onSuccess: frame => broadcastResponseToMcpClients(state, frame),
175
171
  });
176
172
  const broadcastResponseToMcpClients = (state, frame) => Effect.gen(function* () {
177
- const clients = yield* Ref.get(state.mcpClients);
178
173
  const payload = encodeResponseFrameJson(frame);
179
174
  yield* Effect.sync(() => {
180
- for (const client of clients) {
175
+ for (const client of state.mcpClients) {
181
176
  if (client.readyState === client.OPEN) {
182
177
  client.send(payload);
183
178
  }
@@ -185,31 +180,47 @@ const broadcastResponseToMcpClients = (state, frame) => Effect.gen(function* ()
185
180
  });
186
181
  });
187
182
  const handleMcpClientConnected = (state, client) => Effect.gen(function* () {
188
- yield* Ref.update(state.mcpClients, HashSet.add(client));
189
- const total = HashSet.size(yield* Ref.get(state.mcpClients));
183
+ const total = yield* Effect.sync(() => state.mcpClients.add(client).size);
190
184
  yield* Console.log(`[foldkit:devTools] MCP client connected (${total} total)`);
191
185
  });
192
186
  const handleMcpClientDisconnected = (state, client) => Effect.gen(function* () {
193
- yield* Ref.update(state.mcpClients, HashSet.remove(client));
194
- const remaining = HashSet.size(yield* Ref.get(state.mcpClients));
187
+ const remaining = yield* Effect.sync(() => {
188
+ state.mcpClients.delete(client);
189
+ return state.mcpClients.size;
190
+ });
195
191
  yield* Console.log(`[foldkit:devTools] MCP client disconnected (${remaining} remaining)`);
196
192
  });
197
193
  const handleMcpRequestReceived = (server, state, client, raw) => Exit.match(Schema.decodeExit(Schema.fromJsonString(RequestFrame))(raw), {
198
194
  onFailure: error => Console.warn('[foldkit:devTools] failed to decode MCP request frame', error),
199
- onSuccess: frame => Match.value(frame.request).pipe(Match.tag('RequestListRuntimes', () => replyListRuntimes(state, client, frame.id)), Match.orElse(() => forwardRequestToBrowsers(server, frame))),
195
+ onSuccess: frame => Match.value(frame.request).pipe(Match.tag('RequestListRuntimes', () => replyListRuntimes(state, client, frame.id)), Match.orElse(() => routeRequestToRuntime(server, state, client, frame))),
196
+ });
197
+ const sendToRequester = (client, responseFrame) => Effect.sync(() => {
198
+ if (client.readyState === client.OPEN) {
199
+ client.send(encodeResponseFrameJson(responseFrame));
200
+ }
200
201
  });
201
202
  const replyListRuntimes = (state, client, requestId) => Effect.gen(function* () {
202
- const runtimes = pipe(yield* Ref.get(state.connectedRuntimes), HashMap.values, Array.fromIterable);
203
- const responseFrame = {
203
+ const runtimes = pipe(yield* Ref.get(state.connectedRuntimes), HashMap.values, Array.fromIterable, Array.sort(byConnectionOrder), Array.map(({ runtime }) => runtime));
204
+ yield* sendToRequester(client, {
204
205
  id: requestId,
205
206
  response: Response.ResponseRuntimes({ runtimes }),
206
- };
207
- yield* Effect.sync(() => {
208
- if (client.readyState === client.OPEN) {
209
- client.send(encodeResponseFrameJson(responseFrame));
210
- }
211
207
  });
212
208
  });
209
+ const routeRequestToRuntime = (server, state, client, frame) => Effect.gen(function* () {
210
+ const connectedRuntimes = yield* Ref.get(state.connectedRuntimes);
211
+ const maybeUnknownConnectionId = Option.filter(frame.maybeConnectionId, connectionId => !HashMap.has(connectedRuntimes, connectionId));
212
+ if (Option.isSome(maybeUnknownConnectionId)) {
213
+ yield* sendToRequester(client, {
214
+ id: frame.id,
215
+ response: Response.ResponseError({
216
+ reason: `No connected Foldkit Runtime has the id ${maybeUnknownConnectionId.value}. Call foldkit_list_runtimes for the current ids.`,
217
+ }),
218
+ });
219
+ }
220
+ else {
221
+ yield* forwardRequestToBrowsers(server, frame);
222
+ }
223
+ });
213
224
  const forwardRequestToBrowsers = (server, frame) => Effect.gen(function* () {
214
225
  const encoded = yield* Schema.encodeEffect(RequestFrame)(frame);
215
226
  yield* Effect.try({
@@ -230,19 +241,18 @@ const dispatchEvent = (server, state, event) => Match.value(event).pipe(Match.ta
230
241
  McpRequestReceived: ({ client, raw }) => handleMcpRequestReceived(server, state, client, raw),
231
242
  }));
232
243
  // VITE WS BRIDGE
233
- const ensureClientTracked = (state, client, enqueue) => Effect.gen(function* () {
234
- const tracked = yield* Ref.get(state.trackedClients);
235
- if (HashSet.has(tracked, client)) {
244
+ const trackClientClose = (state, client, enqueue) => {
245
+ if (state.trackedClients.has(client)) {
236
246
  return;
237
247
  }
238
- yield* Ref.update(state.trackedClients, HashSet.add(client));
239
- yield* Effect.sync(() => client.socket.on('close', () => enqueue(Event.ViteClientClosed({ client }))));
240
- });
248
+ state.trackedClients.add(client);
249
+ client.socket.on('close', () => enqueue(Event.ViteClientClosed({ client })));
250
+ };
241
251
  const registerViteWsHandlers = (server, state, enqueue) => Effect.sync(() => {
242
252
  server.ws.on('foldkit:preserve-model', payload => enqueue(Event.PreserveModelReceived({ payload })));
243
253
  server.ws.on('foldkit:request-model', payload => enqueue(Event.RequestModelReceived({ payload })));
244
254
  server.ws.on('foldkit:devTools:event', (data, client) => {
245
- Effect.runFork(ensureClientTracked(state, client, enqueue));
255
+ trackClientClose(state, client, enqueue);
246
256
  enqueue(Event.BrowserEventFrameReceived({ data, client }));
247
257
  });
248
258
  server.ws.on('foldkit:devTools:response', (data) => enqueue(Event.BrowserResponseFrameReceived({ data })));
@@ -258,6 +268,21 @@ const RELAY_LOOPBACK_HOST = '127.0.0.1';
258
268
  const RELAY_CONFIGURED_PORT_HOST = 'localhost';
259
269
  const RELAY_TOKEN_PARAMETER = 'token';
260
270
  const RELAY_TOKEN_BYTES = 32;
271
+ const RELAY_CHALLENGE_HEADER = 'x-foldkit-relay-challenge';
272
+ const RELAY_CLIENT_PROOF_HEADER = 'x-foldkit-relay-client-proof';
273
+ const RELAY_SERVER_PROOF_HEADER = 'X-Foldkit-Relay-Server-Proof';
274
+ const RELAY_CHALLENGE_PATTERN = /^[0-9a-f]{64}$/;
275
+ const RELAY_PROOF_PATTERN = /^[0-9a-f]{64}$/;
276
+ const BAD_REQUEST = 400;
277
+ const UNAUTHORIZED = 401;
278
+ const NOT_FOUND = 404;
279
+ const UPGRADE_REQUIRED = 426;
280
+ const UPGRADE_REQUIRED_BODY = 'Upgrade Required';
281
+ const REFUSED_UPGRADE_REASONS = {
282
+ [BAD_REQUEST]: 'Bad Request',
283
+ [UNAUTHORIZED]: 'Unauthorized',
284
+ [NOT_FOUND]: 'Not Found',
285
+ };
261
286
  class RelayBindFailed extends Data.TaggedError('RelayBindFailed') {
262
287
  }
263
288
  const isPortInUse = (error) => Predicate.hasProperty(error, 'code') && error.code === 'EADDRINUSE';
@@ -303,63 +328,81 @@ const requestPresentsToken = (url, token) => {
303
328
  return (expected.length === actual.length && timingSafeEqual(expected, actual));
304
329
  });
305
330
  };
306
- const refuseUpgrade = (socket) => {
307
- socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
308
- socket.destroy();
331
+ const computeRelayProof = (token, role, challenge) => createHmac('sha256', token).update(`${role}:${challenge}`).digest('hex');
332
+ const requestPresentsProof = (request, token) => {
333
+ const challenge = request.headers[RELAY_CHALLENGE_HEADER];
334
+ const presented = request.headers[RELAY_CLIENT_PROOF_HEADER];
335
+ if (!Predicate.isString(challenge) ||
336
+ !RELAY_CHALLENGE_PATTERN.test(challenge) ||
337
+ !Predicate.isString(presented) ||
338
+ !RELAY_PROOF_PATTERN.test(presented)) {
339
+ return false;
340
+ }
341
+ const expected = Buffer.from(computeRelayProof(token, 'client', challenge), 'hex');
342
+ const actual = Buffer.from(presented, 'hex');
343
+ return timingSafeEqual(expected, actual);
309
344
  };
310
- // NOTE: Vite resolves `server.resolvedUrls` in a listener it prepends to
311
- // `listening`, so they are set by the time the relay's own listener runs.
312
- const hostedRelayUrl = (server, token) => (httpServer) => {
313
- const maybeResolvedUrl = pipe(Option.fromNullishOr(server.resolvedUrls), Option.flatMap(resolvedUrls => Option.orElse(Array.head(resolvedUrls.local), () => Array.head(resolvedUrls.network))));
314
- const url = new URL(pipe(maybeResolvedUrl, Option.orElse(() => Option.map(boundPort(httpServer.address()), port => `http://${RELAY_LOOPBACK_HOST}:${port}/`)), Option.getOrThrowWith(relayHasNoBoundPort)));
315
- url.protocol = 'ws:';
316
- url.pathname = RELAY_PATH;
317
- return withRelayToken(url, token);
345
+ const refuseUpgrade = (socket, status) => {
346
+ socket.on('error', () => socket.destroy());
347
+ socket.once('finish', () => socket.destroy());
348
+ socket.end(`HTTP/1.1 ${status} ${REFUSED_UPGRADE_REASONS[status]}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
318
349
  };
319
- const loopbackRelayUrl = (token) => (httpServer) => {
350
+ const loopbackRelayUrl = (httpServer, token) => {
320
351
  const port = Option.getOrThrowWith(boundPort(httpServer.address()), relayHasNoBoundPort);
321
352
  const url = new URL(`ws://${RELAY_LOOPBACK_HOST}:${port}${RELAY_PATH}`);
322
353
  return withRelayToken(url, token);
323
354
  };
324
- const hostRelayOnServer = (httpServer, id, token, toUrl, enqueue) => Effect.callback(resume => {
355
+ const acceptRelayUpgrades = (httpServer, id, token, enqueue) => Effect.sync(() => {
325
356
  const wss = new WebSocketServer({ noServer: true });
326
357
  attachRelayHandlers(wss, enqueue);
327
- const onUpgrade = (request, socket, head) => {
358
+ wss.on('headers', (headers, request) => {
359
+ const challenge = request.headers[RELAY_CHALLENGE_HEADER];
360
+ if (Predicate.isString(challenge) &&
361
+ RELAY_CHALLENGE_PATTERN.test(challenge)) {
362
+ headers.push(`${RELAY_SERVER_PROOF_HEADER}: ${computeRelayProof(token, 'server', challenge)}`);
363
+ }
364
+ });
365
+ httpServer.on('upgrade', (request, socket, head) => {
328
366
  const maybeUrl = parseRequestUrl(request);
329
367
  if (Option.isNone(maybeUrl)) {
330
- socket.destroy();
368
+ refuseUpgrade(socket, BAD_REQUEST);
331
369
  return;
332
370
  }
333
371
  const url = maybeUrl.value;
334
372
  if (url.pathname !== RELAY_PATH) {
373
+ refuseUpgrade(socket, NOT_FOUND);
335
374
  return;
336
375
  }
337
- if (!requestPresentsToken(url, token)) {
338
- refuseUpgrade(socket);
376
+ if (!requestPresentsToken(url, token) &&
377
+ !requestPresentsProof(request, token)) {
378
+ refuseUpgrade(socket, UNAUTHORIZED);
339
379
  return;
340
380
  }
341
381
  wss.handleUpgrade(request, socket, head, client => {
342
382
  wss.emit('connection', client, request);
343
383
  });
384
+ });
385
+ return {
386
+ id,
387
+ wss,
388
+ url: loopbackRelayUrl(httpServer, token),
389
+ closeListener: () => {
390
+ httpServer.close();
391
+ },
344
392
  };
345
- httpServer.on('upgrade', onUpgrade);
346
- const detach = () => {
347
- httpServer.off('upgrade', onUpgrade);
348
- httpServer.off('listening', onListening);
349
- };
350
- const onListening = () => {
351
- resume(Effect.sync(() => ({ id, wss, url: toUrl(httpServer), detach })));
352
- };
353
- if (httpServer.listening) {
354
- onListening();
355
- }
356
- else {
357
- httpServer.once('listening', onListening);
358
- }
359
- return Effect.sync(detach);
360
393
  });
394
+ const answerPlainRequest = (_request, response) => {
395
+ response
396
+ .writeHead(UPGRADE_REQUIRED, {
397
+ Connection: 'Upgrade',
398
+ Upgrade: 'websocket',
399
+ 'Content-Type': 'text/plain',
400
+ 'Content-Length': Buffer.byteLength(UPGRADE_REQUIRED_BODY),
401
+ })
402
+ .end(UPGRADE_REQUIRED_BODY);
403
+ };
361
404
  const bindLoopbackHttpServer = Effect.callback(resume => {
362
- const httpServer = createHttpServer();
405
+ const httpServer = createHttpServer(answerPlainRequest);
363
406
  const onBindFailed = (cause) => {
364
407
  httpServer.close();
365
408
  resume(Effect.fail(new RelayBindFailed({ maybePort: Option.none(), cause })));
@@ -376,17 +419,7 @@ const bindLoopbackHttpServer = Effect.callback(resume => {
376
419
  httpServer.close();
377
420
  });
378
421
  });
379
- const bindLoopbackRelay = (id, token, enqueue) => Effect.gen(function* () {
380
- const httpServer = yield* bindLoopbackHttpServer;
381
- const relay = yield* hostRelayOnServer(httpServer, id, token, loopbackRelayUrl(token), enqueue);
382
- return {
383
- ...relay,
384
- detach: () => {
385
- relay.detach();
386
- httpServer.close();
387
- },
388
- };
389
- });
422
+ const bindLoopbackRelay = (id, token, enqueue) => Effect.flatMap(bindLoopbackHttpServer, httpServer => acceptRelayUpgrades(httpServer, id, token, enqueue));
390
423
  const bindStandaloneRelay = (port, id, enqueue) => Effect.callback(resume => {
391
424
  const wss = new WebSocketServer({ port });
392
425
  attachRelayHandlers(wss, enqueue);
@@ -400,7 +433,7 @@ const bindStandaloneRelay = (port, id, enqueue) => Effect.callback(resume => {
400
433
  id,
401
434
  wss,
402
435
  url: `ws://${RELAY_CONFIGURED_PORT_HOST}:${listeningPort}`,
403
- detach: () => undefined,
436
+ closeListener: () => undefined,
404
437
  }));
405
438
  };
406
439
  const onBindFailed = (cause) => {
@@ -426,49 +459,50 @@ const reportRelayBindFailed = (maybePort, cause) => {
426
459
  return Console.error(`[foldkit:devTools] MCP relay failed to start on ${where}; continuing without the relay`, cause);
427
460
  }
428
461
  };
429
- const unpublishedRelayMessage = (reason) => `[foldkit:devTools] Cannot publish the MCP relay address: ${reason}. Set matching devToolsMcpPort and FOLDKIT_DEVTOOLS_MCP_PORT values for MCP access, or set FOLDKIT_DEVTOOLS_RELAY_DIRECTORY to a private directory on a platform that verifies ownership.`;
462
+ const unpublishedRelayMessage = (reason) => `[foldkit:devTools] Cannot publish the MCP relay address: ${reason}. Set matching devToolsMcpPort and FOLDKIT_DEVTOOLS_MCP_PORT values for MCP access on a trusted network, or set FOLDKIT_DEVTOOLS_RELAY_DIRECTORY to a directory private to your user.`;
430
463
  const publishRelay = (root, relay) => Effect.gen(function* () {
431
464
  const startedAt = yield* Clock.currentTimeMillis;
432
- yield* publishRelayRecord({
465
+ const directory = yield* publishRelayRecord({
433
466
  version: RELAY_RECORD_VERSION,
434
467
  id: relay.id,
435
468
  root,
436
469
  url: relay.url,
437
470
  pid: process.pid,
438
471
  startedAt,
439
- });
440
- }).pipe(Effect.catchTag('RelayRegistryDirectoryRefused', ({ directory, reason }) => Console.error(unpublishedRelayMessage(`the registry directory ${directory} ${reason}`))), Effect.catch(error => Console.error(unpublishedRelayMessage('the registry could not be written'), error)));
472
+ }, relayRegistryTrust);
473
+ return Option.some(directory);
474
+ }).pipe(Effect.catchTag('RelayRegistryDirectoryRefused', ({ directory, reason }) => Effect.as(Console.error(unpublishedRelayMessage(`the registry directory ${directory} ${reason}`)), Option.none())), Effect.catch(error => Effect.as(Console.error(unpublishedRelayMessage('the registry could not be written'), error), Option.none())));
441
475
  const startMcpRelay = (server, devToolsMcpPort, enqueue) => {
442
476
  const root = server.config.root;
443
- // NOTE: The MCP server cannot verify a development HTTPS certificate, so
444
- // HTTPS uses a separate loopback listener.
445
- const maybeHttpServer = Option.filter(Option.fromNullishOr(server.httpServer), () => server.config.server.https === undefined);
446
- // NOTE: A configured port keeps the previous unauthenticated behavior.
447
- // An assigned port binds only to loopback and is found through the registry.
448
- const acquire = Effect.gen(function* () {
449
- const id = yield* relayId;
450
- if (devToolsMcpPort !== undefined) {
451
- return yield* bindStandaloneRelay(devToolsMcpPort, id, enqueue);
452
- }
453
- const token = yield* relayToken;
454
- return yield* Option.match(maybeHttpServer, {
455
- onNone: () => bindLoopbackRelay(id, token, enqueue),
456
- onSome: httpServer => hostRelayOnServer(httpServer, id, token, hostedRelayUrl(server, token), enqueue),
477
+ return Effect.gen(function* () {
478
+ const publishedDirectory = yield* Ref.make(Option.none());
479
+ // NOTE: A configured port accepts unauthenticated connections on every
480
+ // interface. An assigned port binds to loopback and requires discovery.
481
+ const acquire = Effect.gen(function* () {
482
+ const id = yield* relayId;
483
+ if (devToolsMcpPort !== undefined) {
484
+ return yield* bindStandaloneRelay(devToolsMcpPort, id, enqueue);
485
+ }
486
+ const token = yield* relayToken;
487
+ return yield* bindLoopbackRelay(id, token, enqueue);
457
488
  });
489
+ return yield* Effect.acquireRelease(acquire, relay => Effect.gen(function* () {
490
+ const maybeDirectory = yield* Ref.get(publishedDirectory);
491
+ if (Option.isSome(maybeDirectory)) {
492
+ yield* retireRelayRecord(relay.id, maybeDirectory.value).pipe(Effect.catch(error => Console.error('[foldkit:devTools] could not remove the MCP relay registry record', error)));
493
+ }
494
+ relay.closeListener();
495
+ for (const client of relay.wss.clients) {
496
+ client.terminate();
497
+ }
498
+ relay.wss.close();
499
+ yield* Console.log('[foldkit:devTools] MCP relay stopped');
500
+ })).pipe(Effect.retry({
501
+ while: ({ cause }) => isPortInUse(cause),
502
+ times: RELAY_BIND_RETRY_COUNT,
503
+ schedule: Schedule.spaced(RELAY_BIND_RETRY_DELAY),
504
+ }), Effect.tap(relay => Console.log(`[foldkit:devTools] MCP relay listening at ${relayUrlForLog(relay.url)}`)), Effect.tap(relay => Effect.uninterruptible(publishRelay(root, relay).pipe(Effect.flatMap(maybeDirectory => Ref.set(publishedDirectory, maybeDirectory))))), Effect.catchTag('RelayBindFailed', ({ maybePort, cause }) => reportRelayBindFailed(maybePort, cause)));
458
505
  });
459
- return Effect.acquireRelease(acquire.pipe(Effect.tap(relay => Console.log(`[foldkit:devTools] MCP relay listening at ${relayUrlForLog(relay.url)}`)), Effect.tap(relay => publishRelay(root, relay))), relay => Effect.gen(function* () {
460
- relay.detach();
461
- for (const client of relay.wss.clients) {
462
- client.terminate();
463
- }
464
- relay.wss.close();
465
- yield* retireRelayRecord(root, relay.id);
466
- yield* Console.log('[foldkit:devTools] MCP relay stopped');
467
- })).pipe(Effect.retry({
468
- while: ({ cause }) => isPortInUse(cause),
469
- times: RELAY_BIND_RETRY_COUNT,
470
- schedule: Schedule.spaced(RELAY_BIND_RETRY_DELAY),
471
- }), Effect.catchTag('RelayBindFailed', ({ maybePort, cause }) => reportRelayBindFailed(maybePort, cause)));
472
506
  };
473
507
  // NOTE: A Vitest run can override its mode, but still carries Vitest plugins.
474
508
  // Starting a relay there can contend with the project's dev server.
@@ -499,7 +533,7 @@ const main = (server, events, options) => Effect.gen(function* () {
499
533
  * an array; Vite flattens nested plugin arrays, so `plugins: [foldkit()]`
500
534
  * keeps working.
501
535
  */
502
- const relayRegistryLayer = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, NodeCrypto.layer);
536
+ const relayRegistryLayer = Layer.provideMerge(NodeChildProcessSpawner.layer, Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, NodeCrypto.layer));
503
537
  export const foldkit = (options = {}) => {
504
538
  // NOTE: During a Vite restart, old and new servers overlap. Separate queues
505
539
  // and fibers keep their events and shutdowns attached to the right server.
@@ -1,6 +1,9 @@
1
- import { Crypto, Effect, FileSystem, Option, Path, type PlatformError } from 'effect';
1
+ import { Effect, FileSystem, Path, type PlatformError } from 'effect';
2
+ import type { ChildProcessSpawner } from 'effect/process';
2
3
  import { RelayRecord } from 'foldkit/devtools-protocol';
3
- export type RelayPublisherServices = FileSystem.FileSystem | Path.Path | Crypto.Crypto;
4
+ import { type RelayRegistryTrust } from './relayRegistryTrust.js';
5
+ type RelayRegistryServices = FileSystem.FileSystem | Path.Path;
6
+ export type RelayPublisherServices = RelayRegistryServices | ChildProcessSpawner.ChildProcessSpawner;
4
7
  declare const RelayRegistryDirectoryRefused_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
5
8
  readonly _tag: "RelayRegistryDirectoryRefused";
6
9
  } & Readonly<A>;
@@ -9,9 +12,8 @@ export declare class RelayRegistryDirectoryRefused extends RelayRegistryDirector
9
12
  readonly reason: string;
10
13
  }> {
11
14
  }
12
- export declare const relayRegistryDirectoryRefusal: (info: FileSystem.File.Info, maybeCurrentUid: Option.Option<number>) => Option.Option<string>;
13
- export declare const publishRelayRecord: (record: RelayRecord) => Effect.Effect<void, PlatformError.PlatformError | RelayRegistryDirectoryRefused, RelayPublisherServices>;
14
- export declare const readRelayRecord: (root: string) => Effect.Effect<Option.Option<RelayRecord>, never, RelayPublisherServices>;
15
- export declare const retireRelayRecord: (root: string, id: string) => Effect.Effect<void, never, RelayPublisherServices>;
15
+ export declare const publishRelayRecord: (record: RelayRecord, trust: RelayRegistryTrust) => Effect.Effect<string, PlatformError.PlatformError | RelayRegistryDirectoryRefused, RelayPublisherServices>;
16
+ export declare const readRelayRecords: Effect.Effect<ReadonlyArray<RelayRecord>, never, RelayRegistryServices>;
17
+ export declare const retireRelayRecord: (id: string, directory: string) => Effect.Effect<void, PlatformError.PlatformError, RelayRegistryServices>;
16
18
  export {};
17
19
  //# sourceMappingURL=relayRegistry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"relayRegistry.d.ts","sourceRoot":"","sources":["../src/relayRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,MAAM,EAEN,MAAM,EAEN,UAAU,EACV,MAAM,EACN,IAAI,EACJ,KAAK,aAAa,EAEnB,MAAM,QAAQ,CAAA;AACf,OAAO,EAGL,WAAW,EACZ,MAAM,2BAA2B,CAAA;AAYlC,MAAM,MAAM,sBAAsB,GAC9B,UAAU,CAAC,UAAU,GACrB,IAAI,CAAC,IAAI,GACT,MAAM,CAAC,MAAM,CAAA;;;;AAEjB,qBAAa,6BAA8B,SAAQ,mCAEjD;IACA,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CACxB,CAAC;CAAG;AA0CL,eAAO,MAAM,6BAA6B,SAClC,UAAU,CAAC,IAAI,CAAC,IAAI,mBACT,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KACrC,MAAM,CAAC,MAAM,CAAC,MAAM,CAkBnB,CAAA;AAiCJ,eAAO,MAAM,kBAAkB,WACrB,WAAW,KAClB,MAAM,CAAC,MAAM,CACd,IAAI,EACJ,aAAa,CAAC,aAAa,GAAG,6BAA6B,EAC3D,sBAAsB,CAapB,CAAA;AAWJ,eAAO,MAAM,eAAe,SACpB,MAAM,KACX,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,sBAAsB,CAChB,CAAA;AAE1D,eAAO,MAAM,iBAAiB,SACtB,MAAM,MACR,MAAM,KACT,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,sBAAsB,CAkChD,CAAA"}
1
+ {"version":3,"file":"relayRegistry.d.ts","sourceRoot":"","sources":["../src/relayRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,MAAM,EACN,UAAU,EAEV,IAAI,EACJ,KAAK,aAAa,EAGnB,MAAM,QAAQ,CAAA;AACf,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA;AACzD,OAAO,EAGL,WAAW,EACZ,MAAM,2BAA2B,CAAA;AAGlC,OAAO,EACL,KAAK,kBAAkB,EAExB,MAAM,yBAAyB,CAAA;AAUhC,KAAK,qBAAqB,GAAG,UAAU,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAA;AAE9D,MAAM,MAAM,sBAAsB,GAC9B,qBAAqB,GACrB,mBAAmB,CAAC,mBAAmB,CAAA;;;;AAE3C,qBAAa,6BAA8B,SAAQ,mCAEjD;IACA,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CACxB,CAAC;CAAG;AAkIL,eAAO,MAAM,kBAAkB,WACrB,WAAW,SACZ,kBAAkB,KACxB,MAAM,CAAC,MAAM,CACd,MAAM,EACN,aAAa,CAAC,aAAa,GAAG,6BAA6B,EAC3D,sBAAsB,CA+CpB,CAAA;AAEJ,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAC1C,aAAa,CAAC,WAAW,CAAC,EAC1B,KAAK,EACL,qBAAqB,CAOrB,CAAA;AAEF,eAAO,MAAM,iBAAiB,OACxB,MAAM,aACC,MAAM,KAChB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,aAAa,CAAC,aAAa,EAAE,qBAAqB,CAKrE,CAAA"}
@@ -1,11 +1,11 @@
1
- import { Config, Crypto, Data, Effect, Exit, FileSystem, Option, Path, Schema, } from 'effect';
1
+ import { Array, Config, Data, Effect, FileSystem, Option, Path, Schema, String, } from 'effect';
2
2
  import { RELAY_REGISTRY_DIRECTORY_NAME, RELAY_REGISTRY_DIRECTORY_VARIABLE, RelayRecord, } from 'foldkit/devtools-protocol';
3
- import { tmpdir } from 'node:os';
3
+ import { homedir, tmpdir } from 'node:os';
4
+ import { windowsTempRootRefusal, } from './relayRegistryTrust.js';
4
5
  const RUNTIME_DIRECTORY_VARIABLE = 'XDG_RUNTIME_DIR';
5
6
  const RECORD_FILE_EXTENSION = '.json';
6
7
  const REGISTRY_DIRECTORY_MODE = 0o700;
7
8
  const RECORD_FILE_MODE = 0o600;
8
- const PERMISSIONS_BEYOND_OWNER = 0o077;
9
9
  const PENDING_RECORD_SUFFIX = '.pending';
10
10
  const RETIRING_RECORD_SUFFIX = '.retiring';
11
11
  export class RelayRegistryDirectoryRefused extends Data.TaggedError('RelayRegistryDirectoryRefused') {
@@ -16,86 +16,108 @@ const relayRegistryDirectory = Effect.gen(function* () {
16
16
  const path = yield* Path.Path;
17
17
  const maybeConfigured = yield* Config.option(Config.String(RELAY_REGISTRY_DIRECTORY_VARIABLE));
18
18
  const maybeRuntimeDirectory = yield* Config.option(Config.String(RUNTIME_DIRECTORY_VARIABLE));
19
- return Option.getOrElse(maybeConfigured, () => path.join(Option.getOrElse(maybeRuntimeDirectory, tmpdir), RELAY_REGISTRY_DIRECTORY_NAME));
19
+ return Option.getOrElse(maybeConfigured, () => {
20
+ const defaultParent = process.platform === 'win32' ? tmpdir() : path.join(homedir(), '.cache');
21
+ return path.join(Option.getOrElse(maybeRuntimeDirectory, () => defaultParent), RELAY_REGISTRY_DIRECTORY_NAME);
22
+ });
20
23
  }).pipe(Effect.orDie);
21
- const relayRecordPath = (root) => Effect.gen(function* () {
24
+ const relayRecordPath = (directory, id) => Effect.gen(function* () {
22
25
  const path = yield* Path.Path;
23
- const crypto = yield* Crypto.Crypto;
24
- const directory = yield* relayRegistryDirectory;
25
- const digest = yield* crypto
26
- .digest('SHA-1', new TextEncoder().encode(root))
27
- .pipe(Effect.orDie);
28
- return path.join(directory, `${Buffer.from(digest).toString('hex')}${RECORD_FILE_EXTENSION}`);
26
+ return path.join(directory, `${encodeURIComponent(id)}${RECORD_FILE_EXTENSION}`);
29
27
  });
30
- export const relayRegistryDirectoryRefusal = (info, maybeCurrentUid) => Option.match(maybeCurrentUid, {
31
- onNone: () => Option.some('has ownership that cannot be verified'),
32
- onSome: currentUid => {
33
- if (Option.isNone(info.uid)) {
34
- return Option.some('has ownership that cannot be verified');
35
- }
36
- if (info.uid.value !== currentUid) {
37
- return Option.some('is owned by another user');
38
- }
39
- if ((info.mode & PERMISSIONS_BEYOND_OWNER) !== 0) {
40
- return Option.some('is readable or writable by other users');
28
+ const isProcessAlive = (pid) => {
29
+ try {
30
+ process.kill(pid, 0);
31
+ return true;
32
+ }
33
+ catch (error) {
34
+ return error instanceof Error && 'code' in error && error.code === 'EPERM';
35
+ }
36
+ };
37
+ const readRecordFile = (filePath) => Effect.gen(function* () {
38
+ const fileSystem = yield* FileSystem.FileSystem;
39
+ const raw = yield* fileSystem.readFileString(filePath);
40
+ return decodeRelayRecord(raw);
41
+ }).pipe(Effect.orElseSucceed(() => Option.none()));
42
+ const recordFilePaths = (directory) => Effect.gen(function* () {
43
+ const fileSystem = yield* FileSystem.FileSystem;
44
+ const path = yield* Path.Path;
45
+ const fileNames = yield* fileSystem
46
+ .readDirectory(directory)
47
+ .pipe(Effect.orElseSucceed(() => []));
48
+ return Array.map(Array.filter(fileNames, String.endsWith(RECORD_FILE_EXTENSION)), fileName => path.join(directory, fileName));
49
+ });
50
+ // NOTE: A relay from an older plugin names its record by its root and can
51
+ // republish that path between the rename and the read. A hard link restores
52
+ // the republished record only if no newer record occupies the path.
53
+ const retireStaleRecord = (filePath, record) => Effect.gen(function* () {
54
+ const fileSystem = yield* FileSystem.FileSystem;
55
+ const retiringPath = `${filePath}.${encodeURIComponent(record.id)}${RETIRING_RECORD_SUFFIX}`;
56
+ const wasRecordMoved = yield* fileSystem
57
+ .rename(filePath, retiringPath)
58
+ .pipe(Effect.as(true), Effect.orElseSucceed(() => false));
59
+ if (!wasRecordMoved) {
60
+ return;
61
+ }
62
+ const maybeRetiringRecord = yield* readRecordFile(retiringPath);
63
+ const isOriginalRecord = Option.exists(maybeRetiringRecord, retiringRecord => retiringRecord.id === record.id);
64
+ if (!isOriginalRecord) {
65
+ yield* fileSystem.link(retiringPath, filePath).pipe(Effect.ignore);
66
+ }
67
+ yield* fileSystem.remove(retiringPath, { force: true }).pipe(Effect.ignore);
68
+ });
69
+ const removeDeadRecords = (directory) => Effect.gen(function* () {
70
+ const filePaths = yield* recordFilePaths(directory);
71
+ yield* Effect.forEach(filePaths, filePath => Effect.gen(function* () {
72
+ const maybeRecord = yield* readRecordFile(filePath);
73
+ if (Option.isSome(maybeRecord) &&
74
+ !isProcessAlive(maybeRecord.value.pid)) {
75
+ yield* retireStaleRecord(filePath, maybeRecord.value);
41
76
  }
42
- return Option.none();
43
- },
77
+ }), { discard: true });
44
78
  });
45
- const maybeProcessUid = Option.map(Option.fromNullishOr(process.getuid), getuid => getuid());
46
- const ensurePrivateRegistryDirectory = (directory) => Effect.gen(function* () {
79
+ export const publishRelayRecord = (record, trust) => Effect.gen(function* () {
47
80
  const fileSystem = yield* FileSystem.FileSystem;
81
+ const directory = yield* relayRegistryDirectory;
82
+ const maybeLocationRefusal = process.platform === 'win32'
83
+ ? windowsTempRootRefusal(directory, tmpdir())
84
+ : Option.none();
85
+ if (Option.isSome(maybeLocationRefusal)) {
86
+ return yield* Effect.fail(new RelayRegistryDirectoryRefused({
87
+ directory,
88
+ reason: maybeLocationRefusal.value,
89
+ }));
90
+ }
48
91
  yield* fileSystem.makeDirectory(directory, {
49
92
  recursive: true,
50
93
  mode: REGISTRY_DIRECTORY_MODE,
51
94
  });
52
- const info = yield* fileSystem.stat(directory);
53
- const maybeRefusal = relayRegistryDirectoryRefusal(info, maybeProcessUid);
54
- if (Option.isSome(maybeRefusal)) {
95
+ const inspection = yield* trust.inspect(directory);
96
+ if (Option.isSome(inspection.maybeRefusal)) {
55
97
  return yield* Effect.fail(new RelayRegistryDirectoryRefused({
56
98
  directory,
57
- reason: maybeRefusal.value,
99
+ reason: inspection.maybeRefusal.value,
58
100
  }));
59
101
  }
60
- });
61
- export const publishRelayRecord = (record) => Effect.gen(function* () {
62
- const fileSystem = yield* FileSystem.FileSystem;
63
- const directory = yield* relayRegistryDirectory;
64
- yield* ensurePrivateRegistryDirectory(directory);
65
- const recordPath = yield* relayRecordPath(record.root);
66
- const pendingPath = `${recordPath}.${record.id}${PENDING_RECORD_SUFFIX}`;
102
+ const trustedDirectory = inspection.directory;
103
+ yield* removeDeadRecords(trustedDirectory);
104
+ const recordPath = yield* relayRecordPath(trustedDirectory, record.id);
105
+ const pendingPath = `${recordPath}${PENDING_RECORD_SUFFIX}`;
67
106
  yield* fileSystem.writeFileString(pendingPath, encodeRelayRecord(record), {
107
+ flag: 'wx',
68
108
  mode: RECORD_FILE_MODE,
69
109
  });
70
110
  yield* fileSystem.rename(pendingPath, recordPath);
111
+ return trustedDirectory;
71
112
  });
72
- const readRelayRecordAt = (recordPath) => Effect.gen(function* () {
73
- const fileSystem = yield* FileSystem.FileSystem;
74
- const raw = yield* fileSystem.readFileString(recordPath);
75
- return decodeRelayRecord(raw);
76
- }).pipe(Effect.orElseSucceed(() => Option.none()));
77
- export const readRelayRecord = (root) => Effect.flatMap(relayRecordPath(root), readRelayRecordAt);
78
- export const retireRelayRecord = (root, id) => Effect.gen(function* () {
113
+ export const readRelayRecords = Effect.gen(function* () {
114
+ const directory = yield* relayRegistryDirectory;
115
+ const filePaths = yield* recordFilePaths(directory);
116
+ const maybeRecords = yield* Effect.forEach(filePaths, readRecordFile);
117
+ return Array.getSomes(maybeRecords);
118
+ });
119
+ export const retireRelayRecord = (id, directory) => Effect.gen(function* () {
79
120
  const fileSystem = yield* FileSystem.FileSystem;
80
- const recordPath = yield* relayRecordPath(root);
81
- const retiringPath = `${recordPath}.${id}${RETIRING_RECORD_SUFFIX}`;
82
- const maybeRecord = yield* readRelayRecordAt(recordPath);
83
- const isPublishedByRelay = Option.exists(maybeRecord, record => record.id === id);
84
- if (!isPublishedByRelay) {
85
- return;
86
- }
87
- // NOTE: A replacement may publish between the first read and rename. A
88
- // hard link restores its record only if no newer record occupies the path.
89
- const renameResult = yield* fileSystem
90
- .rename(recordPath, retiringPath)
91
- .pipe(Effect.exit);
92
- if (Exit.isFailure(renameResult)) {
93
- return;
94
- }
95
- const maybeRetiringRecord = yield* readRelayRecordAt(retiringPath);
96
- const isReplacement = Option.exists(maybeRetiringRecord, record => record.id !== id);
97
- if (isReplacement) {
98
- yield* fileSystem.link(retiringPath, recordPath).pipe(Effect.ignore);
99
- }
100
- yield* fileSystem.remove(retiringPath, { force: true }).pipe(Effect.ignore);
121
+ const recordPath = yield* relayRecordPath(directory, id);
122
+ yield* fileSystem.remove(recordPath, { force: true });
101
123
  });
@@ -0,0 +1,19 @@
1
+ import { Effect, FileSystem, Option } from 'effect';
2
+ import { ChildProcessSpawner } from 'effect/process';
3
+ export type RelayRegistryInspection = Readonly<{
4
+ directory: string;
5
+ maybeRefusal: Option.Option<string>;
6
+ }>;
7
+ export type RelayRegistryTrust = Readonly<{
8
+ inspect: (directory: string) => Effect.Effect<RelayRegistryInspection, never, ChildProcessSpawner.ChildProcessSpawner>;
9
+ }>;
10
+ type DirectoryInfo = Pick<FileSystem.File.Info, 'mode' | 'uid'>;
11
+ export declare const relayRegistryDirectoryRefusal: (info: DirectoryInfo, maybeCurrentUid: Option.Option<number>) => Option.Option<string>;
12
+ export declare const windowsDirectoryRefusal: (sddl: string, currentUserSid: string) => Option.Option<string>;
13
+ export declare const windowsDirectoryChainRefusal: (descriptors: ReadonlyArray<string>, currentUserSid: string) => Option.Option<string>;
14
+ export declare const powershellPath: (systemRoot: string) => string;
15
+ export declare const windowsTempRootRefusal: (directory: string, tempRoot: string) => Option.Option<string>;
16
+ export declare const probeWindowsDirectory: (maybeExecutable: Option.Option<string>, directory: string) => Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner>;
17
+ export declare const relayRegistryTrust: RelayRegistryTrust;
18
+ export {};
19
+ //# sourceMappingURL=relayRegistryTrust.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relayRegistryTrust.d.ts","sourceRoot":"","sources":["../src/relayRegistryTrust.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,MAAM,EACN,UAAU,EACV,MAAM,EAIP,MAAM,QAAQ,CAAA;AACf,OAAO,EAAgB,mBAAmB,EAAE,MAAM,gBAAgB,CAAA;AAyElE,MAAM,MAAM,uBAAuB,GAAG,QAAQ,CAAC;IAC7C,SAAS,EAAE,MAAM,CAAA;IACjB,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;CACpC,CAAC,CAAA;AAEF,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC;IACxC,OAAO,EAAE,CACP,SAAS,EAAE,MAAM,KACd,MAAM,CAAC,MAAM,CAChB,uBAAuB,EACvB,KAAK,EACL,mBAAmB,CAAC,mBAAmB,CACxC,CAAA;CACF,CAAC,CAAA;AAEF,KAAK,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,CAAA;AAE/D,eAAO,MAAM,6BAA6B,SAClC,aAAa,mBACF,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KACrC,MAAM,CAAC,MAAM,CAAC,MAAM,CAkBnB,CAAA;AA2OJ,eAAO,MAAM,uBAAuB,SAC5B,MAAM,kBACI,MAAM,KACrB,MAAM,CAAC,MAAM,CAAC,MAAM,CAwCtB,CAAA;AAuFD,eAAO,MAAM,4BAA4B,gBAC1B,aAAa,CAAC,MAAM,CAAC,kBAClB,MAAM,KACrB,MAAM,CAAC,MAAM,CAAC,MAAM,CAwEtB,CAAA;AAED,eAAO,MAAM,cAAc,eAAgB,MAAM,KAAG,MAOjD,CAAA;AAEH,eAAO,MAAM,sBAAsB,cACtB,MAAM,YACP,MAAM,KACf,MAAM,CAAC,MAAM,CAAC,MAAM,CAGgB,CAAA;AAuHvC,eAAO,MAAM,qBAAqB,oBACf,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,aAC3B,MAAM,KAChB,MAAM,CAAC,MAAM,CACd,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EACrB,KAAK,EACL,mBAAmB,CAAC,mBAAmB,CAQrC,CAAA;AA+BJ,eAAO,MAAM,kBAAkB,EAAE,kBAgFhC,CAAA"}
@@ -0,0 +1,456 @@
1
+ import { Array, Data, Duration, Effect, Option, Stream, String, pipe, } from 'effect';
2
+ import { ChildProcess, ChildProcessSpawner } from 'effect/process';
3
+ import { lstat, realpath } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, win32 } from 'node:path';
6
+ const PERMISSIONS_BEYOND_OWNER = 0o077;
7
+ const PARENT_WRITE_PERMISSIONS = 0o022;
8
+ const STICKY_DIRECTORY = 0o1000;
9
+ const ROOT_UID = 0;
10
+ const PROBE_TIMEOUT = Duration.seconds(10);
11
+ const PROBED_DIRECTORY_VARIABLE = 'FOLDKIT_DEVTOOLS_PROBED_DIRECTORY';
12
+ const DARWIN_ACL_ENTRY_PATTERN = /^\s*\d+:\s+.+\s(allow|deny)\s+\S+/;
13
+ const DARWIN_DIRECTORY_MODE_PATTERN = /^d[rwxstST-]{9}[+@ ]/;
14
+ const PROBE_SCRIPT = `$sections = [System.Security.AccessControl.AccessControlSections]::Owner -bor [System.Security.AccessControl.AccessControlSections]::Access; $directories = [System.Collections.Generic.List[string]]::new(); $directory = [System.IO.DirectoryInfo]::new($env:${PROBED_DIRECTORY_VARIABLE}); while ($null -ne $directory) { $directories.Insert(0, $directory.FullName); $directory = $directory.Parent }; foreach ($path in $directories) { $attributes = [System.IO.File]::GetAttributes($path); if (($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { 'REPARSE_POINT' } else { 'DIRECTORY' }; ([System.IO.Directory]::GetAccessControl($path)).GetSecurityDescriptorSddlForm($sections) }; & "$env:SystemRoot\\System32\\whoami.exe" /user /fo csv /nh`;
15
+ const UNVERIFIED_OWNERSHIP = 'has ownership that cannot be verified';
16
+ const UNVERIFIED_PERMISSIONS = 'has permissions that cannot be verified';
17
+ const OWNED_BY_ANOTHER_USER = 'is owned by another user';
18
+ const SHARED_WITH_OTHER_USERS = 'is readable or writable by other users';
19
+ const NOT_REGULAR_DIRECTORY = 'is not a regular directory';
20
+ const REPLACEABLE_PARENT = 'has a parent directory that another user can replace';
21
+ const REPARSE_PARENT = 'has a reparse-point directory in its path';
22
+ const OUTSIDE_WINDOWS_TEMP = 'is outside the Windows user temporary directory';
23
+ const SECURITY_DESCRIPTOR_PATTERN = /^O:(S-1-[0-9-]+|[A-Z]{2})(?:G:(?:S-1-[0-9-]+|[A-Z]{2}))?(?:D:([A-Z_]*)((?:\([^()]*\))*))?(?:S:.*)?$/;
24
+ const OWNER_GROUP = 1;
25
+ const ACCESS_CONTROL_FLAGS_GROUP = 2;
26
+ const ACCESS_CONTROL_ENTRIES_GROUP = 3;
27
+ const ACCESS_CONTROL_ENTRY_PATTERN = /\(([^()]*)\)/g;
28
+ const ACCESS_CONTROL_ENTRY_GROUP = 1;
29
+ const ACCESS_CONTROL_ENTRY_FIELD_COUNT = 6;
30
+ const NO_ACCESS_CONTROL_FLAG = 'NO_ACCESS_CONTROL';
31
+ const ALLOW_ENTRY_TYPES = ['A', 'OA'];
32
+ const DENY_ENTRY_TYPES = ['D', 'OD'];
33
+ const PRIVILEGED_ACCOUNTS = [
34
+ 'SY',
35
+ 'S-1-5-18',
36
+ 'BA',
37
+ 'S-1-5-32-544',
38
+ 'LA',
39
+ ];
40
+ const TRUSTED_INSTALLER_SID = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464';
41
+ const CREATOR_ACCOUNTS = [
42
+ 'CO',
43
+ 'S-1-3-0',
44
+ 'OW',
45
+ 'S-1-3-4',
46
+ ];
47
+ const QUOTED_CSV_FIELD_PATTERN = /"([^"]*)"/g;
48
+ const QUOTED_CSV_FIELD_GROUP = 1;
49
+ const SECURITY_IDENTIFIER_PATTERN = /^S-1-[0-9-]+$/;
50
+ class WindowsProbeFailed extends Data.TaggedError('WindowsProbeFailed') {
51
+ }
52
+ class DirectoryProbeFailed extends Data.TaggedError('DirectoryProbeFailed') {
53
+ }
54
+ export const relayRegistryDirectoryRefusal = (info, maybeCurrentUid) => Option.match(maybeCurrentUid, {
55
+ onNone: () => Option.some(UNVERIFIED_OWNERSHIP),
56
+ onSome: currentUid => {
57
+ if (Option.isNone(info.uid)) {
58
+ return Option.some(UNVERIFIED_OWNERSHIP);
59
+ }
60
+ if (info.uid.value !== currentUid) {
61
+ return Option.some(OWNED_BY_ANOTHER_USER);
62
+ }
63
+ if ((info.mode & PERMISSIONS_BEYOND_OWNER) !== 0) {
64
+ return Option.some(SHARED_WITH_OTHER_USERS);
65
+ }
66
+ return Option.none();
67
+ },
68
+ });
69
+ const posixDirectoryRefusal = (modeValue, uidValue) => {
70
+ const mode = globalThis.Number(modeValue);
71
+ const uid = globalThis.Number(uidValue);
72
+ if (!globalThis.Number.isSafeInteger(mode) ||
73
+ !globalThis.Number.isSafeInteger(uid)) {
74
+ return Option.some(UNVERIFIED_OWNERSHIP);
75
+ }
76
+ return relayRegistryDirectoryRefusal({ mode, uid: Option.some(uid) }, Option.fromNullishOr(process.getuid?.()));
77
+ };
78
+ const directoryChain = (directory, parentOf = dirname) => {
79
+ const directories = [];
80
+ let current = directory;
81
+ while (true) {
82
+ directories.push(current);
83
+ const parent = parentOf(current);
84
+ if (parent === current) {
85
+ return Array.reverse(directories);
86
+ }
87
+ current = parent;
88
+ }
89
+ };
90
+ const posixParentChainRefusal = (directory) => Effect.tryPromise({
91
+ try: async () => {
92
+ const currentUid = process.getuid?.();
93
+ if (currentUid === undefined) {
94
+ return Option.some(UNVERIFIED_OWNERSHIP);
95
+ }
96
+ for (const component of directoryChain(directory)) {
97
+ const entry = await lstat(component, { bigint: true });
98
+ const uid = globalThis.Number(entry.uid);
99
+ const mode = globalThis.Number(entry.mode);
100
+ if (entry.isSymbolicLink() ||
101
+ !entry.isDirectory() ||
102
+ !globalThis.Number.isSafeInteger(uid) ||
103
+ !globalThis.Number.isSafeInteger(mode)) {
104
+ return Option.some(UNVERIFIED_OWNERSHIP);
105
+ }
106
+ if (uid !== currentUid && uid !== ROOT_UID) {
107
+ return Option.some(REPLACEABLE_PARENT);
108
+ }
109
+ const isParent = component !== directory;
110
+ const isWritableByOtherUsers = (mode & PARENT_WRITE_PERMISSIONS) !== 0;
111
+ const isSticky = (mode & STICKY_DIRECTORY) !== 0;
112
+ if (isParent && isWritableByOtherUsers && !isSticky) {
113
+ return Option.some(REPLACEABLE_PARENT);
114
+ }
115
+ }
116
+ return Option.none();
117
+ },
118
+ catch: () => new DirectoryProbeFailed(),
119
+ });
120
+ const darwinAclOutputRefusal = (output, isLeaf) => {
121
+ const outputLines = String.split(output, /\r?\n/);
122
+ const lines = output.endsWith('\n')
123
+ ? Array.dropRight(outputLines, 1)
124
+ : outputLines;
125
+ const maybeSummary = Array.head(lines);
126
+ if (Option.isNone(maybeSummary) ||
127
+ !DARWIN_DIRECTORY_MODE_PATTERN.test(maybeSummary.value)) {
128
+ return Option.some(UNVERIFIED_PERMISSIONS);
129
+ }
130
+ for (const line of Array.drop(lines, 1)) {
131
+ const maybeAction = Option.flatMap(Option.fromNullishOr(DARWIN_ACL_ENTRY_PATTERN.exec(line)), entry => Array.get(entry, 1));
132
+ if (Option.isNone(maybeAction)) {
133
+ return Option.some(UNVERIFIED_PERMISSIONS);
134
+ }
135
+ if (maybeAction.value === 'allow') {
136
+ return Option.some(isLeaf ? SHARED_WITH_OTHER_USERS : REPLACEABLE_PARENT);
137
+ }
138
+ }
139
+ return Option.none();
140
+ };
141
+ const darwinAclChainRefusal = (directory) => Effect.gen(function* () {
142
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
143
+ for (const component of directoryChain(directory)) {
144
+ const probe = yield* spawner.spawn(ChildProcess.make('/bin/ls', ['-l', '-d', '-e', '-P', '-b', '--', component], {
145
+ env: { LC_ALL: 'C' },
146
+ extendEnv: true,
147
+ stdin: 'ignore',
148
+ stderr: 'ignore',
149
+ }));
150
+ const [output, exitCode] = yield* Effect.all([
151
+ pipe(probe.stdout, Stream.decodeText, Stream.mkString),
152
+ probe.exitCode,
153
+ ], { concurrency: 'unbounded' });
154
+ if (exitCode !== 0) {
155
+ return yield* Effect.fail(new DirectoryProbeFailed());
156
+ }
157
+ const maybeRefusal = darwinAclOutputRefusal(output, component === directory);
158
+ if (Option.isSome(maybeRefusal)) {
159
+ return maybeRefusal;
160
+ }
161
+ }
162
+ return Option.none();
163
+ }).pipe(Effect.scoped, Effect.mapError(() => new DirectoryProbeFailed()), Effect.timeoutOrElse({
164
+ duration: PROBE_TIMEOUT,
165
+ orElse: () => Effect.fail(new DirectoryProbeFailed()),
166
+ }));
167
+ const capturedGroup = (match, group) => Option.flatMap(Array.get(match, group), Option.fromNullishOr);
168
+ const parseAccessControlEntry = (entry) => {
169
+ const fields = String.split(entry, ';');
170
+ if (fields.length !== ACCESS_CONTROL_ENTRY_FIELD_COUNT) {
171
+ return Option.none();
172
+ }
173
+ const type = Array.headNonEmpty(fields);
174
+ const isKnownType = Array.contains(ALLOW_ENTRY_TYPES, type) ||
175
+ Array.contains(DENY_ENTRY_TYPES, type);
176
+ if (!isKnownType) {
177
+ return Option.none();
178
+ }
179
+ return Option.all({
180
+ type: Option.some(type),
181
+ flags: Array.get(fields, 1),
182
+ rights: Array.get(fields, 2),
183
+ account: Option.some(Array.lastNonEmpty(fields)),
184
+ });
185
+ };
186
+ const parseAccessControlEntries = (entries) => pipe(entries, String.matchAll(ACCESS_CONTROL_ENTRY_PATTERN), Array.fromIterable, Array.map(entry => Option.flatMap(capturedGroup(entry, ACCESS_CONTROL_ENTRY_GROUP), parseAccessControlEntry)), Option.all);
187
+ const parseSecurityDescriptor = (sddl) => Option.flatMap(Option.fromNullishOr(SECURITY_DESCRIPTOR_PATTERN.exec(sddl)), descriptor => Option.all({
188
+ owner: capturedGroup(descriptor, OWNER_GROUP),
189
+ flags: capturedGroup(descriptor, ACCESS_CONTROL_FLAGS_GROUP),
190
+ entries: Option.flatMap(capturedGroup(descriptor, ACCESS_CONTROL_ENTRIES_GROUP), parseAccessControlEntries),
191
+ }));
192
+ export const windowsDirectoryRefusal = (sddl, currentUserSid) => {
193
+ const maybeRawDescriptor = Option.fromNullishOr(SECURITY_DESCRIPTOR_PATTERN.exec(sddl));
194
+ if (Option.isNone(maybeRawDescriptor)) {
195
+ return Option.some(UNVERIFIED_OWNERSHIP);
196
+ }
197
+ const maybeDescriptor = parseSecurityDescriptor(sddl);
198
+ if (Option.isNone(maybeDescriptor)) {
199
+ return Option.some(UNVERIFIED_PERMISSIONS);
200
+ }
201
+ const { owner, flags, entries } = maybeDescriptor.value;
202
+ if (String.includes(NO_ACCESS_CONTROL_FLAG)(flags)) {
203
+ return Option.some(SHARED_WITH_OTHER_USERS);
204
+ }
205
+ const trustedOwners = [currentUserSid, ...PRIVILEGED_ACCOUNTS];
206
+ if (!Array.contains(trustedOwners, owner)) {
207
+ return Option.some(OWNED_BY_ANOTHER_USER);
208
+ }
209
+ const trustedAccounts = [...trustedOwners, ...CREATOR_ACCOUNTS];
210
+ const isSharedWithOtherUsers = Array.some(entries, ({ type, account }) => Array.contains(ALLOW_ENTRY_TYPES, type) &&
211
+ !Array.contains(trustedAccounts, account));
212
+ if (isSharedWithOtherUsers) {
213
+ return Option.some(SHARED_WITH_OTHER_USERS);
214
+ }
215
+ return Option.none();
216
+ };
217
+ const SDDL_ACCESS_RIGHT_CODES = [
218
+ 'GA',
219
+ 'GR',
220
+ 'GW',
221
+ 'GX',
222
+ 'RC',
223
+ 'LC',
224
+ 'SD',
225
+ 'WD',
226
+ 'WO',
227
+ 'FA',
228
+ 'FR',
229
+ 'FW',
230
+ 'FX',
231
+ ];
232
+ const HEX_ACCESS_RIGHTS_PATTERN = /^0x[0-9a-f]+$/i;
233
+ const SYMBOLIC_ACCESS_RIGHTS_PATTERN = /[A-Z]{2}/g;
234
+ const WRITE_DATA_ACCESS = 0x0000_0002;
235
+ const WRITE_ATTRIBUTES_ACCESS = 0x0000_0100;
236
+ const DELETE_ACCESS = 0x0001_0000;
237
+ const DELETE_CHILD_ACCESS = 0x0000_0040;
238
+ const CHANGE_PERMISSIONS_ACCESS = 0x0004_0000;
239
+ const TAKE_OWNERSHIP_ACCESS = 0x0008_0000;
240
+ const GENERIC_ALL_ACCESS = 0x1000_0000;
241
+ const GENERIC_WRITE_ACCESS = 0x4000_0000;
242
+ const KNOWN_FILE_ACCESS = 0xf11f_01ff;
243
+ const CHILD_REPLACEMENT_ACCESS = WRITE_DATA_ACCESS |
244
+ WRITE_ATTRIBUTES_ACCESS |
245
+ DELETE_ACCESS |
246
+ CHANGE_PERMISSIONS_ACCESS |
247
+ TAKE_OWNERSHIP_ACCESS |
248
+ GENERIC_ALL_ACCESS |
249
+ GENERIC_WRITE_ACCESS;
250
+ const PARENT_REPLACEMENT_ACCESS = DELETE_CHILD_ACCESS |
251
+ CHANGE_PERMISSIONS_ACCESS |
252
+ TAKE_OWNERSHIP_ACCESS |
253
+ GENERIC_ALL_ACCESS;
254
+ const symbolicAccessRights = (rights) => Option.flatMap(pipe(rights, String.matchAll(SYMBOLIC_ACCESS_RIGHTS_PATTERN), Array.fromIterable, Array.map(Array.head), Option.all), codes => {
255
+ const isComplete = Array.length(codes) * 2 === rights.length;
256
+ const areKnown = Array.every(codes, code => Array.contains(SDDL_ACCESS_RIGHT_CODES, code));
257
+ return isComplete && areKnown && Array.isArrayNonEmpty(codes)
258
+ ? Option.some(codes)
259
+ : Option.none();
260
+ });
261
+ const accessGrantsReplacement = (rights, mask, symbolicRights) => {
262
+ if (HEX_ACCESS_RIGHTS_PATTERN.test(rights)) {
263
+ const parsed = globalThis.Number.parseInt(rights.slice(2), 16);
264
+ const isKnownMask = globalThis.Number.isSafeInteger(parsed) &&
265
+ parsed <= 0xffff_ffff &&
266
+ ((parsed >>> 0) & ~KNOWN_FILE_ACCESS) === 0;
267
+ return isKnownMask ? Option.some((parsed & mask) !== 0) : Option.none();
268
+ }
269
+ return Option.map(symbolicAccessRights(rights), codes => Array.some(codes, code => Array.contains([...symbolicRights, 'GA', 'FA'], code)));
270
+ };
271
+ export const windowsDirectoryChainRefusal = (descriptors, currentUserSid) => {
272
+ if (Option.isNone(Array.head(descriptors))) {
273
+ return Option.some(UNVERIFIED_OWNERSHIP);
274
+ }
275
+ const maybeParentDescriptors = Option.all(Array.map(Array.dropRight(descriptors, 1), parseSecurityDescriptor));
276
+ if (Option.isNone(maybeParentDescriptors)) {
277
+ return Option.some(UNVERIFIED_PERMISSIONS);
278
+ }
279
+ const parentDescriptors = maybeParentDescriptors.value;
280
+ const trustedParentOwners = [
281
+ currentUserSid,
282
+ ...PRIVILEGED_ACCOUNTS,
283
+ TRUSTED_INSTALLER_SID,
284
+ ];
285
+ const trustedAccounts = [...trustedParentOwners, ...CREATOR_ACCOUNTS];
286
+ for (const [index, descriptor] of parentDescriptors.entries()) {
287
+ if (!Array.contains(trustedParentOwners, descriptor.owner)) {
288
+ return Option.some(REPLACEABLE_PARENT);
289
+ }
290
+ if (String.includes(NO_ACCESS_CONTROL_FLAG)(descriptor.flags)) {
291
+ return Option.some(REPLACEABLE_PARENT);
292
+ }
293
+ const isRoot = index === 0;
294
+ for (const entry of descriptor.entries) {
295
+ const isUntrustedAllow = Array.contains(ALLOW_ENTRY_TYPES, entry.type) &&
296
+ !Array.contains(trustedAccounts, entry.account) &&
297
+ !String.includes('IO')(entry.flags);
298
+ if (!isUntrustedAllow) {
299
+ continue;
300
+ }
301
+ const maybeCanReplaceSelf = isRoot
302
+ ? Option.some(false)
303
+ : accessGrantsReplacement(entry.rights, CHILD_REPLACEMENT_ACCESS, [
304
+ 'SD',
305
+ 'WD',
306
+ 'WO',
307
+ 'FW',
308
+ 'GW',
309
+ ]);
310
+ const maybeCanReplaceChild = accessGrantsReplacement(entry.rights, PARENT_REPLACEMENT_ACCESS, ['DC', 'WD', 'WO']);
311
+ const maybeCanReplace = Option.map(Option.all([maybeCanReplaceSelf, maybeCanReplaceChild]), Array.some(value => value));
312
+ if (Option.isNone(maybeCanReplace)) {
313
+ return Option.some(UNVERIFIED_PERMISSIONS);
314
+ }
315
+ if (maybeCanReplace.value) {
316
+ return Option.some(REPLACEABLE_PARENT);
317
+ }
318
+ }
319
+ }
320
+ return Option.none();
321
+ };
322
+ export const powershellPath = (systemRoot) => win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
323
+ export const windowsTempRootRefusal = (directory, tempRoot) => win32.relative(tempRoot, win32.dirname(directory)) === ''
324
+ ? Option.none()
325
+ : Option.some(OUTSIDE_WINDOWS_TEMP);
326
+ const currentUserSidFromCsv = (identity) => pipe(identity, String.matchAll(QUOTED_CSV_FIELD_PATTERN), Array.fromIterable, Array.map(field => capturedGroup(field, QUOTED_CSV_FIELD_GROUP)), Array.getSomes, Array.findLast(field => SECURITY_IDENTIFIER_PATTERN.test(field)));
327
+ const probeOutputRefusal = (output, directory) => {
328
+ const lines = pipe(output, String.split(/\r?\n/), Array.map(String.trim), Array.filter(String.isNonEmpty));
329
+ const maybeCurrentUserSid = Option.flatMap(Array.last(lines), currentUserSidFromCsv);
330
+ const directoryResults = Array.take(lines, Array.length(lines) - 1);
331
+ const expectedDirectoryCount = Array.length(directoryChain(directory, win32.dirname));
332
+ return Option.match(maybeCurrentUserSid, {
333
+ onNone: () => Effect.fail(new WindowsProbeFailed()),
334
+ onSome: currentUserSid => {
335
+ if (Array.length(directoryResults) !== expectedDirectoryCount * 2) {
336
+ return Effect.fail(new WindowsProbeFailed());
337
+ }
338
+ const results = Array.chunksOf(directoryResults, 2);
339
+ const kinds = Array.getSomes(Array.map(results, Array.head));
340
+ const descriptors = Array.getSomes(Array.map(results, Array.last));
341
+ if (Array.length(kinds) !== expectedDirectoryCount ||
342
+ Array.length(descriptors) !== expectedDirectoryCount) {
343
+ return Effect.fail(new WindowsProbeFailed());
344
+ }
345
+ if (Array.some(kinds, kind => kind !== 'DIRECTORY' && kind !== 'REPARSE_POINT')) {
346
+ return Effect.fail(new WindowsProbeFailed());
347
+ }
348
+ if (Array.some(kinds, kind => kind === 'REPARSE_POINT')) {
349
+ return Effect.succeed(Option.some(REPARSE_PARENT));
350
+ }
351
+ const maybeLeafDescriptor = Array.last(descriptors);
352
+ return Option.match(maybeLeafDescriptor, {
353
+ onNone: () => Effect.fail(new WindowsProbeFailed()),
354
+ onSome: leafDescriptor => Effect.succeed(Option.orElse(windowsDirectoryChainRefusal(descriptors, currentUserSid), () => windowsDirectoryRefusal(leafDescriptor, currentUserSid))),
355
+ });
356
+ },
357
+ });
358
+ };
359
+ const readWindowsDirectoryRefusal = (directory, executable) => Effect.gen(function* () {
360
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
361
+ const probe = yield* spawner.spawn(ChildProcess.make(executable, ['-NoProfile', '-NonInteractive', '-Command', PROBE_SCRIPT], {
362
+ env: { [PROBED_DIRECTORY_VARIABLE]: directory },
363
+ extendEnv: true,
364
+ stdin: 'ignore',
365
+ stderr: 'ignore',
366
+ }));
367
+ const [output, exitCode] = yield* Effect.all([pipe(probe.stdout, Stream.decodeText, Stream.mkString), probe.exitCode], { concurrency: 'unbounded' });
368
+ if (exitCode === 0) {
369
+ return yield* probeOutputRefusal(output, directory);
370
+ }
371
+ else {
372
+ return yield* Effect.fail(new WindowsProbeFailed());
373
+ }
374
+ }).pipe(Effect.scoped, Effect.mapError(() => new WindowsProbeFailed()), Effect.timeoutOrElse({
375
+ duration: PROBE_TIMEOUT,
376
+ orElse: () => Effect.fail(new WindowsProbeFailed()),
377
+ }));
378
+ export const probeWindowsDirectory = (maybeExecutable, directory) => Option.match(maybeExecutable, {
379
+ onNone: () => Effect.succeed(Option.some(UNVERIFIED_OWNERSHIP)),
380
+ onSome: executable => readWindowsDirectoryRefusal(directory, executable).pipe(Effect.orElseSucceed(() => Option.some(UNVERIFIED_OWNERSHIP))),
381
+ });
382
+ const probeDirectoryEntry = (directory) => Effect.tryPromise({
383
+ try: async () => {
384
+ const entry = await lstat(directory, { bigint: true });
385
+ if (entry.isSymbolicLink() || !entry.isDirectory()) {
386
+ return {
387
+ directory,
388
+ entry,
389
+ maybeRefusal: Option.some(NOT_REGULAR_DIRECTORY),
390
+ };
391
+ }
392
+ const canonicalDirectory = await realpath(directory);
393
+ const canonicalEntry = await lstat(canonicalDirectory, { bigint: true });
394
+ const isSameEntry = entry.dev === canonicalEntry.dev && entry.ino === canonicalEntry.ino;
395
+ return {
396
+ directory: canonicalDirectory,
397
+ entry: canonicalEntry,
398
+ maybeRefusal: isSameEntry
399
+ ? Option.none()
400
+ : Option.some(UNVERIFIED_OWNERSHIP),
401
+ };
402
+ },
403
+ catch: () => new DirectoryProbeFailed(),
404
+ });
405
+ export const relayRegistryTrust = {
406
+ inspect: directory => Effect.gen(function* () {
407
+ const probe = yield* probeDirectoryEntry(directory);
408
+ if (Option.isSome(probe.maybeRefusal)) {
409
+ return {
410
+ directory: probe.directory,
411
+ maybeRefusal: probe.maybeRefusal,
412
+ };
413
+ }
414
+ const maybeRefusal = process.platform === 'win32'
415
+ ? yield* Effect.gen(function* () {
416
+ const tempRoot = yield* Effect.tryPromise({
417
+ try: () => realpath(tmpdir()),
418
+ catch: () => new DirectoryProbeFailed(),
419
+ });
420
+ const maybeLocationRefusal = windowsTempRootRefusal(probe.directory, tempRoot);
421
+ if (Option.isSome(maybeLocationRefusal)) {
422
+ return maybeLocationRefusal;
423
+ }
424
+ return yield* probeWindowsDirectory(Option.map(Option.fromNullishOr(process.env['SystemRoot']), powershellPath), probe.directory);
425
+ })
426
+ : yield* posixParentChainRefusal(probe.directory).pipe(Effect.flatMap(maybeParentRefusal => {
427
+ if (Option.isSome(maybeParentRefusal)) {
428
+ return Effect.succeed(maybeParentRefusal);
429
+ }
430
+ const maybeLeafRefusal = posixDirectoryRefusal(probe.entry.mode, probe.entry.uid);
431
+ if (Option.isSome(maybeLeafRefusal)) {
432
+ return Effect.succeed(maybeLeafRefusal);
433
+ }
434
+ return process.platform === 'darwin'
435
+ ? darwinAclChainRefusal(probe.directory)
436
+ : Effect.succeed(Option.none());
437
+ }));
438
+ if (Option.isSome(maybeRefusal)) {
439
+ return { directory: probe.directory, maybeRefusal };
440
+ }
441
+ const confirmation = yield* probeDirectoryEntry(directory);
442
+ const isSameDirectory = Option.isNone(confirmation.maybeRefusal) &&
443
+ confirmation.directory === probe.directory &&
444
+ confirmation.entry.dev === probe.entry.dev &&
445
+ confirmation.entry.ino === probe.entry.ino;
446
+ return {
447
+ directory: probe.directory,
448
+ maybeRefusal: isSameDirectory
449
+ ? Option.none()
450
+ : Option.some(UNVERIFIED_OWNERSHIP),
451
+ };
452
+ }).pipe(Effect.orElseSucceed(() => ({
453
+ directory,
454
+ maybeRefusal: Option.some(UNVERIFIED_OWNERSHIP),
455
+ }))),
456
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldkit/vite-plugin",
3
- "version": "0.27.1-canary.606ca39eaf1c",
3
+ "version": "0.27.1-canary.76fa0d1ee2a5",
4
4
  "description": "Vite plugin for Foldkit with state-preserving live reload",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,7 +17,7 @@
17
17
  ],
18
18
  "peerDependencies": {
19
19
  "effect": "4.0.0",
20
- "foldkit": "0.168.0-canary.606ca39eaf1c",
20
+ "foldkit": "0.168.0-canary.76fa0d1ee2a5",
21
21
  "vite": "^8.0.0"
22
22
  },
23
23
  "dependencies": {
@@ -32,7 +32,7 @@
32
32
  "@types/ws": "^8.18.1",
33
33
  "@vitejs/plugin-basic-ssl": "^2.3.0",
34
34
  "effect": "4.0.0",
35
- "foldkit": "0.168.0-canary.606ca39eaf1c",
35
+ "foldkit": "0.168.0-canary.76fa0d1ee2a5",
36
36
  "happy-dom": "^20.14.5",
37
37
  "rimraf": "^6.1.3",
38
38
  "typescript": "^7.0.2",