@foldkit/vite-plugin 0.27.1-canary.d8b5fc47e803 → 0.27.1-canary.e1bac2b2ac98
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 +5 -5
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +158 -123
- package/dist/relayRegistry.d.ts +8 -6
- package/dist/relayRegistry.d.ts.map +1 -1
- package/dist/relayRegistry.js +87 -65
- package/dist/relayRegistryTrust.d.ts +19 -0
- package/dist/relayRegistryTrust.d.ts.map +1 -0
- package/dist/relayRegistryTrust.js +456 -0
- package/package.json +3 -3
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
|
|
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
|
|
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
|
-
|
|
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
|
|
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.
|
|
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
|
|
12
|
-
* address for the MCP server to find.
|
|
13
|
-
*
|
|
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
|
-
*
|
|
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
|
/**
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
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;AA0/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,
|
|
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';
|
|
@@ -68,6 +70,7 @@ const FORCE_INCLUDED_EFFECT_ENTRIES = [
|
|
|
68
70
|
'effect/String',
|
|
69
71
|
'effect/Struct',
|
|
70
72
|
'effect/SubscriptionRef',
|
|
73
|
+
'effect/Tuple',
|
|
71
74
|
'effect/Types',
|
|
72
75
|
];
|
|
73
76
|
// NOTE: Adding includes to an environment whose optimizer is otherwise disabled
|
|
@@ -84,21 +87,20 @@ const Event = Data.taggedEnum();
|
|
|
84
87
|
const makeState = Effect.gen(function* () {
|
|
85
88
|
const preservedModels = yield* Ref.make(HashMap.empty());
|
|
86
89
|
const connectedRuntimes = yield* Ref.make(HashMap.empty());
|
|
87
|
-
const
|
|
88
|
-
const clientConnections = yield* Ref.make(HashMap.empty());
|
|
89
|
-
const trackedClients = yield* Ref.make(HashSet.empty());
|
|
90
|
+
const nextSequence = yield* Ref.make(0);
|
|
90
91
|
const state = {
|
|
91
92
|
preservedModels,
|
|
92
93
|
connectedRuntimes,
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
trackedClients,
|
|
94
|
+
nextSequence,
|
|
95
|
+
mcpClients: new Set(),
|
|
96
|
+
trackedClients: new WeakSet(),
|
|
96
97
|
};
|
|
97
98
|
return state;
|
|
98
99
|
});
|
|
99
100
|
const encodeResponseFrameJson = Schema.encodeUnknownSync(Schema.fromJsonString(ResponseFrame));
|
|
100
101
|
class WebSocketSendFailed extends Data.TaggedError('WebSocketSendFailed') {
|
|
101
102
|
}
|
|
103
|
+
const byConnectionOrder = Order.mapInput(Order.Number, ({ sequence }) => sequence);
|
|
102
104
|
// HANDLERS
|
|
103
105
|
const handlePreserveModelReceived = (state, payload) => Exit.match(Schema.decodeUnknownExit(PreserveModelMessage)(payload), {
|
|
104
106
|
onFailure: error => Console.warn('[foldkit:preserve] failed to decode preserve-model payload', error),
|
|
@@ -144,40 +146,34 @@ const handleBrowserEventFrameReceived = (state, data, client) => Exit.match(Sche
|
|
|
144
146
|
}),
|
|
145
147
|
});
|
|
146
148
|
const handleConnectedEvent = (state, event, client) => Effect.gen(function* () {
|
|
147
|
-
yield* Ref.
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
149
|
+
const sequence = yield* Ref.getAndUpdate(state.nextSequence, Number.increment);
|
|
150
|
+
const connectedRuntime = {
|
|
151
|
+
runtime: event.runtime,
|
|
152
|
+
sequence,
|
|
153
|
+
client,
|
|
154
|
+
};
|
|
155
|
+
yield* Ref.update(state.connectedRuntimes, HashMap.set(event.runtime.connectionId, connectedRuntime));
|
|
152
156
|
yield* Console.log(`[foldkit:devTools] runtime connected: ${event.runtime.connectionId} (${event.runtime.title})`);
|
|
153
157
|
});
|
|
154
158
|
const handleDisconnectedEvent = (state, event) => Effect.gen(function* () {
|
|
155
159
|
yield* Ref.update(state.connectedRuntimes, HashMap.remove(event.connectionId));
|
|
156
160
|
yield* Console.log(`[foldkit:devTools] runtime disconnected: ${event.connectionId}`);
|
|
157
161
|
});
|
|
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
162
|
const handleViteClientClosed = (state, client) => Effect.gen(function* () {
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
});
|
|
169
|
-
yield* Ref.update(state.clientConnections, HashMap.remove(client));
|
|
170
|
-
yield* Ref.update(state.trackedClients, HashSet.remove(client));
|
|
163
|
+
const prunedConnectionIds = yield* Ref.modify(state.connectedRuntimes, current => [
|
|
164
|
+
pipe(current, HashMap.filter(connectedRuntime => connectedRuntime.client === client), HashMap.keys, Array.fromIterable),
|
|
165
|
+
HashMap.filter(current, connectedRuntime => connectedRuntime.client !== client),
|
|
166
|
+
]);
|
|
167
|
+
yield* Effect.forEach(prunedConnectionIds, connectionId => Console.log(`[foldkit:devTools] runtime pruned (socket close): ${connectionId}`), { discard: true });
|
|
171
168
|
});
|
|
172
169
|
const handleBrowserResponseFrameReceived = (state, data) => Exit.match(Schema.decodeUnknownExit(ResponseFrame)(data), {
|
|
173
170
|
onFailure: error => Console.warn('[foldkit:devTools] failed to decode browser response frame', error),
|
|
174
171
|
onSuccess: frame => broadcastResponseToMcpClients(state, frame),
|
|
175
172
|
});
|
|
176
173
|
const broadcastResponseToMcpClients = (state, frame) => Effect.gen(function* () {
|
|
177
|
-
const clients = yield* Ref.get(state.mcpClients);
|
|
178
174
|
const payload = encodeResponseFrameJson(frame);
|
|
179
175
|
yield* Effect.sync(() => {
|
|
180
|
-
for (const client of
|
|
176
|
+
for (const client of state.mcpClients) {
|
|
181
177
|
if (client.readyState === client.OPEN) {
|
|
182
178
|
client.send(payload);
|
|
183
179
|
}
|
|
@@ -185,31 +181,47 @@ const broadcastResponseToMcpClients = (state, frame) => Effect.gen(function* ()
|
|
|
185
181
|
});
|
|
186
182
|
});
|
|
187
183
|
const handleMcpClientConnected = (state, client) => Effect.gen(function* () {
|
|
188
|
-
yield*
|
|
189
|
-
const total = HashSet.size(yield* Ref.get(state.mcpClients));
|
|
184
|
+
const total = yield* Effect.sync(() => state.mcpClients.add(client).size);
|
|
190
185
|
yield* Console.log(`[foldkit:devTools] MCP client connected (${total} total)`);
|
|
191
186
|
});
|
|
192
187
|
const handleMcpClientDisconnected = (state, client) => Effect.gen(function* () {
|
|
193
|
-
yield*
|
|
194
|
-
|
|
188
|
+
const remaining = yield* Effect.sync(() => {
|
|
189
|
+
state.mcpClients.delete(client);
|
|
190
|
+
return state.mcpClients.size;
|
|
191
|
+
});
|
|
195
192
|
yield* Console.log(`[foldkit:devTools] MCP client disconnected (${remaining} remaining)`);
|
|
196
193
|
});
|
|
197
194
|
const handleMcpRequestReceived = (server, state, client, raw) => Exit.match(Schema.decodeExit(Schema.fromJsonString(RequestFrame))(raw), {
|
|
198
195
|
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(() =>
|
|
196
|
+
onSuccess: frame => Match.value(frame.request).pipe(Match.tag('RequestListRuntimes', () => replyListRuntimes(state, client, frame.id)), Match.orElse(() => routeRequestToRuntime(server, state, client, frame))),
|
|
197
|
+
});
|
|
198
|
+
const sendToRequester = (client, responseFrame) => Effect.sync(() => {
|
|
199
|
+
if (client.readyState === client.OPEN) {
|
|
200
|
+
client.send(encodeResponseFrameJson(responseFrame));
|
|
201
|
+
}
|
|
200
202
|
});
|
|
201
203
|
const replyListRuntimes = (state, client, requestId) => Effect.gen(function* () {
|
|
202
|
-
const runtimes = pipe(yield* Ref.get(state.connectedRuntimes), HashMap.values, Array.fromIterable);
|
|
203
|
-
|
|
204
|
+
const runtimes = pipe(yield* Ref.get(state.connectedRuntimes), HashMap.values, Array.fromIterable, Array.sort(byConnectionOrder), Array.map(({ runtime }) => runtime));
|
|
205
|
+
yield* sendToRequester(client, {
|
|
204
206
|
id: requestId,
|
|
205
207
|
response: Response.ResponseRuntimes({ runtimes }),
|
|
206
|
-
};
|
|
207
|
-
yield* Effect.sync(() => {
|
|
208
|
-
if (client.readyState === client.OPEN) {
|
|
209
|
-
client.send(encodeResponseFrameJson(responseFrame));
|
|
210
|
-
}
|
|
211
208
|
});
|
|
212
209
|
});
|
|
210
|
+
const routeRequestToRuntime = (server, state, client, frame) => Effect.gen(function* () {
|
|
211
|
+
const connectedRuntimes = yield* Ref.get(state.connectedRuntimes);
|
|
212
|
+
const maybeUnknownConnectionId = Option.filter(frame.maybeConnectionId, connectionId => !HashMap.has(connectedRuntimes, connectionId));
|
|
213
|
+
if (Option.isSome(maybeUnknownConnectionId)) {
|
|
214
|
+
yield* sendToRequester(client, {
|
|
215
|
+
id: frame.id,
|
|
216
|
+
response: Response.ResponseError({
|
|
217
|
+
reason: `No connected Foldkit Runtime has the id ${maybeUnknownConnectionId.value}. Call foldkit_list_runtimes for the current ids.`,
|
|
218
|
+
}),
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
yield* forwardRequestToBrowsers(server, frame);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
213
225
|
const forwardRequestToBrowsers = (server, frame) => Effect.gen(function* () {
|
|
214
226
|
const encoded = yield* Schema.encodeEffect(RequestFrame)(frame);
|
|
215
227
|
yield* Effect.try({
|
|
@@ -230,19 +242,18 @@ const dispatchEvent = (server, state, event) => Match.value(event).pipe(Match.ta
|
|
|
230
242
|
McpRequestReceived: ({ client, raw }) => handleMcpRequestReceived(server, state, client, raw),
|
|
231
243
|
}));
|
|
232
244
|
// VITE WS BRIDGE
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
if (HashSet.has(tracked, client)) {
|
|
245
|
+
const trackClientClose = (state, client, enqueue) => {
|
|
246
|
+
if (state.trackedClients.has(client)) {
|
|
236
247
|
return;
|
|
237
248
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
}
|
|
249
|
+
state.trackedClients.add(client);
|
|
250
|
+
client.socket.on('close', () => enqueue(Event.ViteClientClosed({ client })));
|
|
251
|
+
};
|
|
241
252
|
const registerViteWsHandlers = (server, state, enqueue) => Effect.sync(() => {
|
|
242
253
|
server.ws.on('foldkit:preserve-model', payload => enqueue(Event.PreserveModelReceived({ payload })));
|
|
243
254
|
server.ws.on('foldkit:request-model', payload => enqueue(Event.RequestModelReceived({ payload })));
|
|
244
255
|
server.ws.on('foldkit:devTools:event', (data, client) => {
|
|
245
|
-
|
|
256
|
+
trackClientClose(state, client, enqueue);
|
|
246
257
|
enqueue(Event.BrowserEventFrameReceived({ data, client }));
|
|
247
258
|
});
|
|
248
259
|
server.ws.on('foldkit:devTools:response', (data) => enqueue(Event.BrowserResponseFrameReceived({ data })));
|
|
@@ -258,6 +269,21 @@ const RELAY_LOOPBACK_HOST = '127.0.0.1';
|
|
|
258
269
|
const RELAY_CONFIGURED_PORT_HOST = 'localhost';
|
|
259
270
|
const RELAY_TOKEN_PARAMETER = 'token';
|
|
260
271
|
const RELAY_TOKEN_BYTES = 32;
|
|
272
|
+
const RELAY_CHALLENGE_HEADER = 'x-foldkit-relay-challenge';
|
|
273
|
+
const RELAY_CLIENT_PROOF_HEADER = 'x-foldkit-relay-client-proof';
|
|
274
|
+
const RELAY_SERVER_PROOF_HEADER = 'X-Foldkit-Relay-Server-Proof';
|
|
275
|
+
const RELAY_CHALLENGE_PATTERN = /^[0-9a-f]{64}$/;
|
|
276
|
+
const RELAY_PROOF_PATTERN = /^[0-9a-f]{64}$/;
|
|
277
|
+
const BAD_REQUEST = 400;
|
|
278
|
+
const UNAUTHORIZED = 401;
|
|
279
|
+
const NOT_FOUND = 404;
|
|
280
|
+
const UPGRADE_REQUIRED = 426;
|
|
281
|
+
const UPGRADE_REQUIRED_BODY = 'Upgrade Required';
|
|
282
|
+
const REFUSED_UPGRADE_REASONS = {
|
|
283
|
+
[BAD_REQUEST]: 'Bad Request',
|
|
284
|
+
[UNAUTHORIZED]: 'Unauthorized',
|
|
285
|
+
[NOT_FOUND]: 'Not Found',
|
|
286
|
+
};
|
|
261
287
|
class RelayBindFailed extends Data.TaggedError('RelayBindFailed') {
|
|
262
288
|
}
|
|
263
289
|
const isPortInUse = (error) => Predicate.hasProperty(error, 'code') && error.code === 'EADDRINUSE';
|
|
@@ -303,63 +329,81 @@ const requestPresentsToken = (url, token) => {
|
|
|
303
329
|
return (expected.length === actual.length && timingSafeEqual(expected, actual));
|
|
304
330
|
});
|
|
305
331
|
};
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
332
|
+
const computeRelayProof = (token, role, challenge) => createHmac('sha256', token).update(`${role}:${challenge}`).digest('hex');
|
|
333
|
+
const requestPresentsProof = (request, token) => {
|
|
334
|
+
const challenge = request.headers[RELAY_CHALLENGE_HEADER];
|
|
335
|
+
const presented = request.headers[RELAY_CLIENT_PROOF_HEADER];
|
|
336
|
+
if (!Predicate.isString(challenge) ||
|
|
337
|
+
!RELAY_CHALLENGE_PATTERN.test(challenge) ||
|
|
338
|
+
!Predicate.isString(presented) ||
|
|
339
|
+
!RELAY_PROOF_PATTERN.test(presented)) {
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
const expected = Buffer.from(computeRelayProof(token, 'client', challenge), 'hex');
|
|
343
|
+
const actual = Buffer.from(presented, 'hex');
|
|
344
|
+
return timingSafeEqual(expected, actual);
|
|
309
345
|
};
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
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);
|
|
346
|
+
const refuseUpgrade = (socket, status) => {
|
|
347
|
+
socket.on('error', () => socket.destroy());
|
|
348
|
+
socket.once('finish', () => socket.destroy());
|
|
349
|
+
socket.end(`HTTP/1.1 ${status} ${REFUSED_UPGRADE_REASONS[status]}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
318
350
|
};
|
|
319
|
-
const loopbackRelayUrl = (token) =>
|
|
351
|
+
const loopbackRelayUrl = (httpServer, token) => {
|
|
320
352
|
const port = Option.getOrThrowWith(boundPort(httpServer.address()), relayHasNoBoundPort);
|
|
321
353
|
const url = new URL(`ws://${RELAY_LOOPBACK_HOST}:${port}${RELAY_PATH}`);
|
|
322
354
|
return withRelayToken(url, token);
|
|
323
355
|
};
|
|
324
|
-
const
|
|
356
|
+
const acceptRelayUpgrades = (httpServer, id, token, enqueue) => Effect.sync(() => {
|
|
325
357
|
const wss = new WebSocketServer({ noServer: true });
|
|
326
358
|
attachRelayHandlers(wss, enqueue);
|
|
327
|
-
|
|
359
|
+
wss.on('headers', (headers, request) => {
|
|
360
|
+
const challenge = request.headers[RELAY_CHALLENGE_HEADER];
|
|
361
|
+
if (Predicate.isString(challenge) &&
|
|
362
|
+
RELAY_CHALLENGE_PATTERN.test(challenge)) {
|
|
363
|
+
headers.push(`${RELAY_SERVER_PROOF_HEADER}: ${computeRelayProof(token, 'server', challenge)}`);
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
httpServer.on('upgrade', (request, socket, head) => {
|
|
328
367
|
const maybeUrl = parseRequestUrl(request);
|
|
329
368
|
if (Option.isNone(maybeUrl)) {
|
|
330
|
-
socket
|
|
369
|
+
refuseUpgrade(socket, BAD_REQUEST);
|
|
331
370
|
return;
|
|
332
371
|
}
|
|
333
372
|
const url = maybeUrl.value;
|
|
334
373
|
if (url.pathname !== RELAY_PATH) {
|
|
374
|
+
refuseUpgrade(socket, NOT_FOUND);
|
|
335
375
|
return;
|
|
336
376
|
}
|
|
337
|
-
if (!requestPresentsToken(url, token)
|
|
338
|
-
|
|
377
|
+
if (!requestPresentsToken(url, token) &&
|
|
378
|
+
!requestPresentsProof(request, token)) {
|
|
379
|
+
refuseUpgrade(socket, UNAUTHORIZED);
|
|
339
380
|
return;
|
|
340
381
|
}
|
|
341
382
|
wss.handleUpgrade(request, socket, head, client => {
|
|
342
383
|
wss.emit('connection', client, request);
|
|
343
384
|
});
|
|
385
|
+
});
|
|
386
|
+
return {
|
|
387
|
+
id,
|
|
388
|
+
wss,
|
|
389
|
+
url: loopbackRelayUrl(httpServer, token),
|
|
390
|
+
closeListener: () => {
|
|
391
|
+
httpServer.close();
|
|
392
|
+
},
|
|
344
393
|
};
|
|
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
394
|
});
|
|
395
|
+
const answerPlainRequest = (_request, response) => {
|
|
396
|
+
response
|
|
397
|
+
.writeHead(UPGRADE_REQUIRED, {
|
|
398
|
+
Connection: 'Upgrade',
|
|
399
|
+
Upgrade: 'websocket',
|
|
400
|
+
'Content-Type': 'text/plain',
|
|
401
|
+
'Content-Length': Buffer.byteLength(UPGRADE_REQUIRED_BODY),
|
|
402
|
+
})
|
|
403
|
+
.end(UPGRADE_REQUIRED_BODY);
|
|
404
|
+
};
|
|
361
405
|
const bindLoopbackHttpServer = Effect.callback(resume => {
|
|
362
|
-
const httpServer = createHttpServer();
|
|
406
|
+
const httpServer = createHttpServer(answerPlainRequest);
|
|
363
407
|
const onBindFailed = (cause) => {
|
|
364
408
|
httpServer.close();
|
|
365
409
|
resume(Effect.fail(new RelayBindFailed({ maybePort: Option.none(), cause })));
|
|
@@ -376,17 +420,7 @@ const bindLoopbackHttpServer = Effect.callback(resume => {
|
|
|
376
420
|
httpServer.close();
|
|
377
421
|
});
|
|
378
422
|
});
|
|
379
|
-
const bindLoopbackRelay = (id, token, enqueue) => Effect.
|
|
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
|
-
});
|
|
423
|
+
const bindLoopbackRelay = (id, token, enqueue) => Effect.flatMap(bindLoopbackHttpServer, httpServer => acceptRelayUpgrades(httpServer, id, token, enqueue));
|
|
390
424
|
const bindStandaloneRelay = (port, id, enqueue) => Effect.callback(resume => {
|
|
391
425
|
const wss = new WebSocketServer({ port });
|
|
392
426
|
attachRelayHandlers(wss, enqueue);
|
|
@@ -400,7 +434,7 @@ const bindStandaloneRelay = (port, id, enqueue) => Effect.callback(resume => {
|
|
|
400
434
|
id,
|
|
401
435
|
wss,
|
|
402
436
|
url: `ws://${RELAY_CONFIGURED_PORT_HOST}:${listeningPort}`,
|
|
403
|
-
|
|
437
|
+
closeListener: () => undefined,
|
|
404
438
|
}));
|
|
405
439
|
};
|
|
406
440
|
const onBindFailed = (cause) => {
|
|
@@ -426,49 +460,50 @@ const reportRelayBindFailed = (maybePort, cause) => {
|
|
|
426
460
|
return Console.error(`[foldkit:devTools] MCP relay failed to start on ${where}; continuing without the relay`, cause);
|
|
427
461
|
}
|
|
428
462
|
};
|
|
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
|
|
463
|
+
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
464
|
const publishRelay = (root, relay) => Effect.gen(function* () {
|
|
431
465
|
const startedAt = yield* Clock.currentTimeMillis;
|
|
432
|
-
yield* publishRelayRecord({
|
|
466
|
+
const directory = yield* publishRelayRecord({
|
|
433
467
|
version: RELAY_RECORD_VERSION,
|
|
434
468
|
id: relay.id,
|
|
435
469
|
root,
|
|
436
470
|
url: relay.url,
|
|
437
471
|
pid: process.pid,
|
|
438
472
|
startedAt,
|
|
439
|
-
});
|
|
440
|
-
|
|
473
|
+
}, relayRegistryTrust);
|
|
474
|
+
return Option.some(directory);
|
|
475
|
+
}).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
476
|
const startMcpRelay = (server, devToolsMcpPort, enqueue) => {
|
|
442
477
|
const root = server.config.root;
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
return yield* Option.match(maybeHttpServer, {
|
|
455
|
-
onNone: () => bindLoopbackRelay(id, token, enqueue),
|
|
456
|
-
onSome: httpServer => hostRelayOnServer(httpServer, id, token, hostedRelayUrl(server, token), enqueue),
|
|
478
|
+
return Effect.gen(function* () {
|
|
479
|
+
const publishedDirectory = yield* Ref.make(Option.none());
|
|
480
|
+
// NOTE: A configured port accepts unauthenticated connections on every
|
|
481
|
+
// interface. An assigned port binds to loopback and requires discovery.
|
|
482
|
+
const acquire = Effect.gen(function* () {
|
|
483
|
+
const id = yield* relayId;
|
|
484
|
+
if (devToolsMcpPort !== undefined) {
|
|
485
|
+
return yield* bindStandaloneRelay(devToolsMcpPort, id, enqueue);
|
|
486
|
+
}
|
|
487
|
+
const token = yield* relayToken;
|
|
488
|
+
return yield* bindLoopbackRelay(id, token, enqueue);
|
|
457
489
|
});
|
|
490
|
+
return yield* Effect.acquireRelease(acquire, relay => Effect.gen(function* () {
|
|
491
|
+
const maybeDirectory = yield* Ref.get(publishedDirectory);
|
|
492
|
+
if (Option.isSome(maybeDirectory)) {
|
|
493
|
+
yield* retireRelayRecord(relay.id, maybeDirectory.value).pipe(Effect.catch(error => Console.error('[foldkit:devTools] could not remove the MCP relay registry record', error)));
|
|
494
|
+
}
|
|
495
|
+
relay.closeListener();
|
|
496
|
+
for (const client of relay.wss.clients) {
|
|
497
|
+
client.terminate();
|
|
498
|
+
}
|
|
499
|
+
relay.wss.close();
|
|
500
|
+
yield* Console.log('[foldkit:devTools] MCP relay stopped');
|
|
501
|
+
})).pipe(Effect.retry({
|
|
502
|
+
while: ({ cause }) => isPortInUse(cause),
|
|
503
|
+
times: RELAY_BIND_RETRY_COUNT,
|
|
504
|
+
schedule: Schedule.spaced(RELAY_BIND_RETRY_DELAY),
|
|
505
|
+
}), 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
506
|
});
|
|
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
507
|
};
|
|
473
508
|
// NOTE: A Vitest run can override its mode, but still carries Vitest plugins.
|
|
474
509
|
// Starting a relay there can contend with the project's dev server.
|
|
@@ -499,7 +534,7 @@ const main = (server, events, options) => Effect.gen(function* () {
|
|
|
499
534
|
* an array; Vite flattens nested plugin arrays, so `plugins: [foldkit()]`
|
|
500
535
|
* keeps working.
|
|
501
536
|
*/
|
|
502
|
-
const relayRegistryLayer = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, NodeCrypto.layer);
|
|
537
|
+
const relayRegistryLayer = Layer.provideMerge(NodeChildProcessSpawner.layer, Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, NodeCrypto.layer));
|
|
503
538
|
export const foldkit = (options = {}) => {
|
|
504
539
|
// NOTE: During a Vite restart, old and new servers overlap. Separate queues
|
|
505
540
|
// and fibers keep their events and shutdowns attached to the right server.
|
package/dist/relayRegistry.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import {
|
|
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
|
-
|
|
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
|
|
13
|
-
export declare const
|
|
14
|
-
export declare const
|
|
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,
|
|
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"}
|
package/dist/relayRegistry.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
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, () =>
|
|
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 = (
|
|
24
|
+
const relayRecordPath = (directory, id) => Effect.gen(function* () {
|
|
22
25
|
const path = yield* Path.Path;
|
|
23
|
-
|
|
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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
43
|
-
},
|
|
77
|
+
}), { discard: true });
|
|
44
78
|
});
|
|
45
|
-
const
|
|
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
|
|
53
|
-
|
|
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
|
-
|
|
62
|
-
const
|
|
63
|
-
const
|
|
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
|
|
73
|
-
const
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
export const retireRelayRecord = (
|
|
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(
|
|
81
|
-
|
|
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.
|
|
3
|
+
"version": "0.27.1-canary.e1bac2b2ac98",
|
|
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.
|
|
20
|
+
"foldkit": "0.168.0-canary.e1bac2b2ac98",
|
|
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.
|
|
35
|
+
"foldkit": "0.168.0-canary.e1bac2b2ac98",
|
|
36
36
|
"happy-dom": "^20.14.5",
|
|
37
37
|
"rimraf": "^6.1.3",
|
|
38
38
|
"typescript": "^7.0.2",
|