@bunizao/edgeport 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +117 -2
- package/dist/cli.js +490 -0
- package/package.json +37 -4
- package/src/agent.ts +314 -0
- package/src/cli.ts +60 -0
- package/src/first-load.ts +193 -0
- package/src/protocol.ts +127 -0
- package/src/socket.ts +105 -0
- package/src/worker.ts +398 -0
- package/wrangler.jsonc +15 -0
package/src/socket.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// A small WebSocket client wrapper that can send custom headers and go
|
|
2
|
+
// through HTTPS_PROXY on both Bun (native) and Node (undici).
|
|
3
|
+
|
|
4
|
+
export interface SocketLike {
|
|
5
|
+
readonly protocol: string;
|
|
6
|
+
readonly bufferedAmount: number;
|
|
7
|
+
send(data: string | Uint8Array): void;
|
|
8
|
+
close(code?: number, reason?: string): void;
|
|
9
|
+
onopen?: () => void;
|
|
10
|
+
onmessage?: (data: string | ArrayBuffer) => void;
|
|
11
|
+
onclose?: (code: number, reason: string) => void;
|
|
12
|
+
onerror?: (message: string) => void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface OpenOptions {
|
|
16
|
+
headers?: Record<string, string>;
|
|
17
|
+
protocols?: string[];
|
|
18
|
+
/** Connect directly even when a proxy is configured (local origins). */
|
|
19
|
+
direct?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
declare const Bun: unknown;
|
|
23
|
+
const isBun = typeof Bun !== 'undefined';
|
|
24
|
+
|
|
25
|
+
type NodeWebSocketCtor = new (url: string, init: { headers?: Record<string, string>; protocols?: string[]; dispatcher?: unknown }) => WebSocket;
|
|
26
|
+
let nodeWebSocket: NodeWebSocketCtor | undefined;
|
|
27
|
+
let nodeProxyDispatcher: unknown;
|
|
28
|
+
|
|
29
|
+
/** Must be awaited once before openSocket on Node. A no-op on Bun. */
|
|
30
|
+
export async function prepareSockets(): Promise<void> {
|
|
31
|
+
if (isBun || nodeWebSocket) return;
|
|
32
|
+
const undici = (await import('undici')) as unknown as { WebSocket: NodeWebSocketCtor; EnvHttpProxyAgent: new () => unknown };
|
|
33
|
+
nodeWebSocket = undici.WebSocket;
|
|
34
|
+
nodeProxyDispatcher = new undici.EnvHttpProxyAgent();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function proxyFor(url: string): string | undefined {
|
|
38
|
+
const target = new URL(url);
|
|
39
|
+
const secure = target.protocol === 'wss:' || target.protocol === 'https:';
|
|
40
|
+
const proxy = secure
|
|
41
|
+
? process.env.HTTPS_PROXY ?? process.env.https_proxy
|
|
42
|
+
: process.env.HTTP_PROXY ?? process.env.http_proxy;
|
|
43
|
+
if (!proxy) return undefined;
|
|
44
|
+
const host = target.hostname.replace(/^\[|\]$/g, '');
|
|
45
|
+
const noProxy = (process.env.NO_PROXY ?? process.env.no_proxy ?? '')
|
|
46
|
+
.split(',')
|
|
47
|
+
.map((entry) => entry.trim().toLowerCase())
|
|
48
|
+
.filter(Boolean);
|
|
49
|
+
if (host === 'localhost' || host === '127.0.0.1' || host === '::1') return undefined;
|
|
50
|
+
for (const entry of noProxy) {
|
|
51
|
+
if (entry === '*') return undefined;
|
|
52
|
+
const bare = entry.replace(/^\*?\./, '').replace(/:\d+$/, '');
|
|
53
|
+
if (host === bare || host.endsWith(`.${bare}`)) return undefined;
|
|
54
|
+
}
|
|
55
|
+
return proxy;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function openSocket(url: string, options: OpenOptions = {}): SocketLike {
|
|
59
|
+
let ws: WebSocket;
|
|
60
|
+
const proxy = options.direct ? undefined : proxyFor(url);
|
|
61
|
+
if (isBun) {
|
|
62
|
+
const init: Record<string, unknown> = { headers: options.headers };
|
|
63
|
+
if (options.protocols?.length) init.protocols = options.protocols;
|
|
64
|
+
if (proxy) init.proxy = proxy;
|
|
65
|
+
ws = new WebSocket(url, init as unknown as string[]);
|
|
66
|
+
} else {
|
|
67
|
+
if (!nodeWebSocket) throw new Error('call prepareSockets() before openSocket() on Node');
|
|
68
|
+
ws = new nodeWebSocket(url, {
|
|
69
|
+
headers: options.headers,
|
|
70
|
+
protocols: options.protocols,
|
|
71
|
+
dispatcher: proxy ? nodeProxyDispatcher : undefined,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
ws.binaryType = 'arraybuffer';
|
|
75
|
+
|
|
76
|
+
const wrapper: SocketLike = {
|
|
77
|
+
get protocol() {
|
|
78
|
+
return ws.protocol;
|
|
79
|
+
},
|
|
80
|
+
get bufferedAmount() {
|
|
81
|
+
return ws.bufferedAmount;
|
|
82
|
+
},
|
|
83
|
+
send(data) {
|
|
84
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(data);
|
|
85
|
+
},
|
|
86
|
+
close(code, reason) {
|
|
87
|
+
if (ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) return;
|
|
88
|
+
try {
|
|
89
|
+
ws.close(code, reason);
|
|
90
|
+
} catch {
|
|
91
|
+
ws.close();
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
ws.addEventListener('open', () => wrapper.onopen?.());
|
|
96
|
+
ws.addEventListener('message', (event) => {
|
|
97
|
+
const data = event.data as unknown;
|
|
98
|
+
if (typeof data === 'string') wrapper.onmessage?.(data);
|
|
99
|
+
else if (data instanceof ArrayBuffer) wrapper.onmessage?.(data);
|
|
100
|
+
else if (ArrayBuffer.isView(data)) wrapper.onmessage?.(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) as ArrayBuffer);
|
|
101
|
+
});
|
|
102
|
+
ws.addEventListener('close', (event) => wrapper.onclose?.(event.code, event.reason));
|
|
103
|
+
ws.addEventListener('error', (event) => wrapper.onerror?.((event as ErrorEvent).message ?? ''));
|
|
104
|
+
return wrapper;
|
|
105
|
+
}
|
package/src/worker.ts
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
// edgeport edge: a Worker plus one Durable Object per hostname.
|
|
2
|
+
//
|
|
3
|
+
// The agent (running next to your dev server) dials in over a WebSocket at
|
|
4
|
+
// AGENT_PATH. Every other request to the hostname is multiplexed over that
|
|
5
|
+
// socket as a stream: plain HTTP is relayed with streaming bodies in both
|
|
6
|
+
// directions, and browser WebSockets (for example Vite HMR) are bridged
|
|
7
|
+
// frame by frame.
|
|
8
|
+
|
|
9
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
10
|
+
import {
|
|
11
|
+
AGENT_PATH,
|
|
12
|
+
Frame,
|
|
13
|
+
HOP_BY_HOP,
|
|
14
|
+
PING_TEXT,
|
|
15
|
+
PONG_TEXT,
|
|
16
|
+
PROTOCOL_VERSION,
|
|
17
|
+
decode,
|
|
18
|
+
encode,
|
|
19
|
+
json,
|
|
20
|
+
sendableCloseCode,
|
|
21
|
+
text,
|
|
22
|
+
type HeaderList,
|
|
23
|
+
type ResponseHead,
|
|
24
|
+
type SocketAccept,
|
|
25
|
+
type SocketClose,
|
|
26
|
+
} from './protocol';
|
|
27
|
+
import { PreloadLearner, enhanceHtml, isHtmlNavigation } from './first-load';
|
|
28
|
+
|
|
29
|
+
export interface Env {
|
|
30
|
+
EDGEPORT: DurableObjectNamespace<Relay>;
|
|
31
|
+
/** Shared secret the agent presents as `Authorization: Bearer <secret>`. */
|
|
32
|
+
EDGEPORT_SECRET: string;
|
|
33
|
+
/** Set to "off" to leave HTML untouched (no learned preloads, no loading hint). */
|
|
34
|
+
EDGEPORT_FIRST_LOAD?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const ACCEPT_TIMEOUT_MS = 15_000;
|
|
38
|
+
const RESPONSE_TIMEOUT_MS = 100_000;
|
|
39
|
+
|
|
40
|
+
export default {
|
|
41
|
+
async fetch(request, env): Promise<Response> {
|
|
42
|
+
const host = new URL(request.url).hostname;
|
|
43
|
+
return env.EDGEPORT.get(env.EDGEPORT.idFromName(host)).fetch(request);
|
|
44
|
+
},
|
|
45
|
+
} satisfies ExportedHandler<Env>;
|
|
46
|
+
|
|
47
|
+
interface PendingRequest {
|
|
48
|
+
head: (head: ResponseHead) => void;
|
|
49
|
+
fail: (error: Error) => void;
|
|
50
|
+
writer?: WritableStreamDefaultWriter<Uint8Array>;
|
|
51
|
+
headSent: boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface PendingSocket {
|
|
55
|
+
accept: (accept: SocketAccept) => void;
|
|
56
|
+
fail: (error: Error) => void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface ClientAttachment {
|
|
60
|
+
id: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class Relay extends DurableObject<Env> {
|
|
64
|
+
private requests = new Map<number, PendingRequest>();
|
|
65
|
+
private opening = new Map<number, PendingSocket>();
|
|
66
|
+
private learner: PreloadLearner;
|
|
67
|
+
|
|
68
|
+
constructor(ctx: DurableObjectState, env: Env) {
|
|
69
|
+
super(ctx, env);
|
|
70
|
+
this.learner = new PreloadLearner(ctx.storage);
|
|
71
|
+
// Keepalives are answered without waking the object.
|
|
72
|
+
ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING_TEXT, PONG_TEXT));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async fetch(request: Request): Promise<Response> {
|
|
76
|
+
const url = new URL(request.url);
|
|
77
|
+
const upgrade = request.headers.get('upgrade')?.toLowerCase() === 'websocket';
|
|
78
|
+
|
|
79
|
+
if (url.pathname === AGENT_PATH) {
|
|
80
|
+
if (!upgrade) return new Response('edgeport agent endpoint expects a WebSocket\n', { status: 426 });
|
|
81
|
+
return this.acceptAgent(request);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const agent = this.agent();
|
|
85
|
+
if (!agent) return offline();
|
|
86
|
+
|
|
87
|
+
return upgrade ? this.bridgeSocket(request, agent, url) : this.relayRequest(request, agent, url);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ---- agent connection -------------------------------------------------
|
|
91
|
+
|
|
92
|
+
private async acceptAgent(request: Request): Promise<Response> {
|
|
93
|
+
const secret = this.env.EDGEPORT_SECRET;
|
|
94
|
+
const presented = request.headers.get('authorization')?.replace(/^Bearer\s+/i, '') ?? '';
|
|
95
|
+
if (!secret || !(await sameSecret(presented, secret))) {
|
|
96
|
+
return new Response('unauthorized\n', { status: 401 });
|
|
97
|
+
}
|
|
98
|
+
const version = Number(request.headers.get('x-edgeport-version') ?? PROTOCOL_VERSION);
|
|
99
|
+
if (version !== PROTOCOL_VERSION) {
|
|
100
|
+
return new Response(`edgeport protocol ${version} is not supported (edge speaks ${PROTOCOL_VERSION})\n`, { status: 400 });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// A new agent replaces the old one; whatever it was carrying is lost.
|
|
104
|
+
for (const old of this.ctx.getWebSockets('agent')) old.close(1012, 'replaced by a newer agent');
|
|
105
|
+
this.dropAllStreams('agent replaced');
|
|
106
|
+
|
|
107
|
+
const pair = new WebSocketPair();
|
|
108
|
+
this.ctx.acceptWebSocket(pair[1], ['agent']);
|
|
109
|
+
if (this.env.EDGEPORT_FIRST_LOAD !== 'off') {
|
|
110
|
+
const warm = await this.learner.warmList();
|
|
111
|
+
if (warm.length) pair[1].send(encode(Frame.Warm, 0, warm));
|
|
112
|
+
}
|
|
113
|
+
return new Response(null, { status: 101, webSocket: pair[0] });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private agent(): WebSocket | undefined {
|
|
117
|
+
return this.ctx.getWebSockets('agent').find((ws) => ws.readyState === WebSocket.READY_STATE_OPEN);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
|
|
121
|
+
const tags = this.ctx.getTags(ws);
|
|
122
|
+
if (tags.includes('agent')) {
|
|
123
|
+
if (typeof message === 'string') return; // only keepalives arrive as text
|
|
124
|
+
this.onAgentFrame(message);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const attachment = ws.deserializeAttachment() as ClientAttachment | null;
|
|
128
|
+
const agent = this.agent();
|
|
129
|
+
if (!attachment || !agent) {
|
|
130
|
+
ws.close(1011, 'edgeport agent is offline');
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
agent.send(
|
|
134
|
+
typeof message === 'string'
|
|
135
|
+
? encode(Frame.SocketText, attachment.id, message)
|
|
136
|
+
: encode(Frame.SocketBinary, attachment.id, new Uint8Array(message)),
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {
|
|
141
|
+
this.onSocketGone(ws, code, reason);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async webSocketError(ws: WebSocket): Promise<void> {
|
|
145
|
+
this.onSocketGone(ws, 1011, 'socket error');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private onSocketGone(ws: WebSocket, code: number, reason: string): void {
|
|
149
|
+
if (this.ctx.getTags(ws).includes('agent')) {
|
|
150
|
+
// A replaced agent closing must not take down its successor's streams.
|
|
151
|
+
const current = this.agent();
|
|
152
|
+
if (!current || current === ws) this.dropAllStreams('agent disconnected');
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const attachment = ws.deserializeAttachment() as ClientAttachment | null;
|
|
156
|
+
if (attachment) this.agent()?.send(encode(Frame.SocketClose, attachment.id, { code, reason }));
|
|
157
|
+
try {
|
|
158
|
+
ws.close(sendableCloseCode(code), reason);
|
|
159
|
+
} catch {
|
|
160
|
+
// already closed
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private onAgentFrame(data: ArrayBuffer): void {
|
|
165
|
+
const { type, id, payload } = decode(data);
|
|
166
|
+
switch (type) {
|
|
167
|
+
case Frame.ResponseHead: {
|
|
168
|
+
const pending = this.requests.get(id);
|
|
169
|
+
if (!pending || pending.headSent) return;
|
|
170
|
+
pending.headSent = true;
|
|
171
|
+
pending.head(json<ResponseHead>(payload));
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
case Frame.ResponseBody: {
|
|
175
|
+
// Copy: the payload is a view into a buffer the runtime may reuse.
|
|
176
|
+
void this.requests.get(id)?.writer?.write(payload.slice()).catch(() => this.abortStream(id));
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
case Frame.ResponseEnd: {
|
|
180
|
+
const pending = this.requests.get(id);
|
|
181
|
+
this.requests.delete(id);
|
|
182
|
+
void pending?.writer?.close().catch(() => {});
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
case Frame.Abort: {
|
|
186
|
+
const pending = this.requests.get(id);
|
|
187
|
+
if (pending) {
|
|
188
|
+
this.requests.delete(id);
|
|
189
|
+
const reason = new Error(text(payload) || 'aborted by agent');
|
|
190
|
+
if (pending.headSent) void pending.writer?.abort(reason).catch(() => {});
|
|
191
|
+
else pending.fail(reason);
|
|
192
|
+
}
|
|
193
|
+
this.opening.get(id)?.fail(new Error(text(payload) || 'origin refused the WebSocket'));
|
|
194
|
+
this.opening.delete(id);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
case Frame.SocketAccept: {
|
|
198
|
+
this.opening.get(id)?.accept(json<SocketAccept>(payload));
|
|
199
|
+
this.opening.delete(id);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
case Frame.SocketText:
|
|
203
|
+
this.client(id)?.send(text(payload));
|
|
204
|
+
return;
|
|
205
|
+
case Frame.SocketBinary:
|
|
206
|
+
this.client(id)?.send(payload.slice());
|
|
207
|
+
return;
|
|
208
|
+
case Frame.SocketClose: {
|
|
209
|
+
const { code, reason } = json<SocketClose>(payload);
|
|
210
|
+
try {
|
|
211
|
+
this.client(id)?.close(sendableCloseCode(code), reason ?? '');
|
|
212
|
+
} catch {
|
|
213
|
+
// already closed
|
|
214
|
+
}
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private client(id: number): WebSocket | undefined {
|
|
221
|
+
return this.ctx.getWebSockets(`client:${id}`)[0];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private dropAllStreams(reason: string): void {
|
|
225
|
+
for (const [id, pending] of this.requests) {
|
|
226
|
+
if (pending.headSent) void pending.writer?.abort(new Error(reason)).catch(() => {});
|
|
227
|
+
else pending.fail(new Error(reason));
|
|
228
|
+
this.requests.delete(id);
|
|
229
|
+
}
|
|
230
|
+
for (const [id, pending] of this.opening) {
|
|
231
|
+
pending.fail(new Error(reason));
|
|
232
|
+
this.opening.delete(id);
|
|
233
|
+
}
|
|
234
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
235
|
+
if (!this.ctx.getTags(ws).includes('agent')) {
|
|
236
|
+
try {
|
|
237
|
+
ws.close(1012, reason);
|
|
238
|
+
} catch {
|
|
239
|
+
// already closed
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
private abortStream(id: number): void {
|
|
246
|
+
if (!this.requests.delete(id)) return;
|
|
247
|
+
this.agent()?.send(encode(Frame.Abort, id, 'client went away'));
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
private newStreamId(): number {
|
|
251
|
+
for (;;) {
|
|
252
|
+
const id = crypto.getRandomValues(new Uint32Array(1))[0] || 1;
|
|
253
|
+
if (!this.requests.has(id) && !this.opening.has(id) && !this.client(id)) return id;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ---- plain HTTP ---------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
private async relayRequest(request: Request, agent: WebSocket, url: URL): Promise<Response> {
|
|
260
|
+
const firstLoad = this.env.EDGEPORT_FIRST_LOAD !== 'off';
|
|
261
|
+
const setCookie = firstLoad ? this.learner.observe(request, url) : undefined;
|
|
262
|
+
const id = this.newStreamId();
|
|
263
|
+
const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
|
|
264
|
+
|
|
265
|
+
const head = new Promise<ResponseHead>((resolve, reject) => {
|
|
266
|
+
this.requests.set(id, { head: resolve, fail: reject, writer: writable.getWriter(), headSent: false });
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
agent.send(encode(Frame.RequestHead, id, { method: request.method, path: url.pathname + url.search, headers: forwardable(request.headers) }));
|
|
270
|
+
void this.pumpRequestBody(request, agent, id);
|
|
271
|
+
|
|
272
|
+
let response: ResponseHead;
|
|
273
|
+
try {
|
|
274
|
+
response = await withTimeout(head, RESPONSE_TIMEOUT_MS, 'origin did not answer in time');
|
|
275
|
+
} catch (error) {
|
|
276
|
+
this.abortStream(id);
|
|
277
|
+
return badGateway(error instanceof Error ? error.message : String(error));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const headers = new Headers();
|
|
281
|
+
for (const [name, value] of response.headers) {
|
|
282
|
+
if (!HOP_BY_HOP.has(name.toLowerCase())) headers.append(name, value);
|
|
283
|
+
}
|
|
284
|
+
const bodyless = request.method === 'HEAD' || response.status === 204 || response.status === 304;
|
|
285
|
+
if (bodyless) void readable.cancel().catch(() => {});
|
|
286
|
+
let body: ReadableStream<Uint8Array> | null = bodyless ? null : readable;
|
|
287
|
+
if (body && firstLoad && isHtmlNavigation(request, headers)) {
|
|
288
|
+
body = enhanceHtml(body, await this.learner.preloadsFor(url));
|
|
289
|
+
headers.delete('content-length');
|
|
290
|
+
}
|
|
291
|
+
if (setCookie) headers.append('set-cookie', setCookie);
|
|
292
|
+
return new Response(body, {
|
|
293
|
+
status: response.status,
|
|
294
|
+
statusText: response.statusText,
|
|
295
|
+
headers,
|
|
296
|
+
// The origin already compressed what it wanted compressed.
|
|
297
|
+
encodeBody: 'manual',
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private async pumpRequestBody(request: Request, agent: WebSocket, id: number): Promise<void> {
|
|
302
|
+
try {
|
|
303
|
+
if (request.body) {
|
|
304
|
+
const reader = request.body.getReader();
|
|
305
|
+
for (;;) {
|
|
306
|
+
const { done, value } = await reader.read();
|
|
307
|
+
if (done) break;
|
|
308
|
+
if (!this.requests.has(id)) return;
|
|
309
|
+
agent.send(encode(Frame.RequestBody, id, value));
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
agent.send(encode(Frame.RequestEnd, id));
|
|
313
|
+
} catch {
|
|
314
|
+
this.abortStream(id);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ---- browser WebSockets -----------------------------------------------
|
|
319
|
+
|
|
320
|
+
private async bridgeSocket(request: Request, agent: WebSocket, url: URL): Promise<Response> {
|
|
321
|
+
const id = this.newStreamId();
|
|
322
|
+
const protocols = (request.headers.get('sec-websocket-protocol') ?? '')
|
|
323
|
+
.split(',')
|
|
324
|
+
.map((p) => p.trim())
|
|
325
|
+
.filter(Boolean);
|
|
326
|
+
|
|
327
|
+
const accepted = new Promise<SocketAccept>((resolve, reject) => {
|
|
328
|
+
this.opening.set(id, { accept: resolve, fail: reject });
|
|
329
|
+
});
|
|
330
|
+
agent.send(encode(Frame.SocketOpen, id, { path: url.pathname + url.search, headers: forwardable(request.headers, true), protocols }));
|
|
331
|
+
|
|
332
|
+
let accept: SocketAccept;
|
|
333
|
+
try {
|
|
334
|
+
accept = await withTimeout(accepted, ACCEPT_TIMEOUT_MS, 'origin did not accept the WebSocket in time');
|
|
335
|
+
} catch (error) {
|
|
336
|
+
this.opening.delete(id);
|
|
337
|
+
agent.send(encode(Frame.SocketClose, id, { code: 1001, reason: 'edge gave up' }));
|
|
338
|
+
return badGateway(error instanceof Error ? error.message : String(error));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const pair = new WebSocketPair();
|
|
342
|
+
this.ctx.acceptWebSocket(pair[1], [`client:${id}`]);
|
|
343
|
+
pair[1].serializeAttachment({ id } satisfies ClientAttachment);
|
|
344
|
+
const headers = new Headers();
|
|
345
|
+
if (accept.protocol) headers.set('sec-websocket-protocol', accept.protocol);
|
|
346
|
+
return new Response(null, { status: 101, webSocket: pair[0], headers });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ---- helpers --------------------------------------------------------------
|
|
351
|
+
|
|
352
|
+
function forwardable(headers: Headers, socket = false): HeaderList {
|
|
353
|
+
const list: HeaderList = [];
|
|
354
|
+
headers.forEach((value, name) => {
|
|
355
|
+
const lower = name.toLowerCase();
|
|
356
|
+
if (HOP_BY_HOP.has(lower)) return;
|
|
357
|
+
if (socket && lower.startsWith('sec-websocket-')) return;
|
|
358
|
+
list.push([name, value]);
|
|
359
|
+
});
|
|
360
|
+
return list;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function sameSecret(a: string, b: string): Promise<boolean> {
|
|
364
|
+
const enc = new TextEncoder();
|
|
365
|
+
const [da, db] = await Promise.all([
|
|
366
|
+
crypto.subtle.digest('SHA-256', enc.encode(a)),
|
|
367
|
+
crypto.subtle.digest('SHA-256', enc.encode(b)),
|
|
368
|
+
]);
|
|
369
|
+
return crypto.subtle.timingSafeEqual(da, db);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
|
|
373
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
374
|
+
return Promise.race([
|
|
375
|
+
promise.finally(() => clearTimeout(timer)),
|
|
376
|
+
new Promise<never>((_, reject) => {
|
|
377
|
+
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
378
|
+
}),
|
|
379
|
+
]);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function offline(): Response {
|
|
383
|
+
return new Response(
|
|
384
|
+
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">' +
|
|
385
|
+
'<title>edgeport: offline</title><body style="font:16px system-ui;margin:3rem auto;max-width:32rem;padding:0 1rem">' +
|
|
386
|
+
'<h1 style="font-size:1.25rem">No agent is connected</h1>' +
|
|
387
|
+
'<p>Start <code>edgeport</code> next to your dev server, then reload.</p>' +
|
|
388
|
+
'<script>setTimeout(()=>location.reload(),3000)</script>',
|
|
389
|
+
{ status: 502, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' } },
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function badGateway(message: string): Response {
|
|
394
|
+
return new Response(`edgeport: ${message}\n`, {
|
|
395
|
+
status: 502,
|
|
396
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
|
|
397
|
+
});
|
|
398
|
+
}
|
package/wrangler.jsonc
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "./node_modules/wrangler/config-schema.json",
|
|
3
|
+
"name": "edgeport",
|
|
4
|
+
"main": "src/worker.ts",
|
|
5
|
+
"compatibility_date": "2026-11-01",
|
|
6
|
+
// Serve the relay on a hostname in one of your zones. Each hostname gets its
|
|
7
|
+
// own Durable Object, so one Worker can carry several previews.
|
|
8
|
+
// "routes": [{ "pattern": "dev.example.com", "custom_domain": true }],
|
|
9
|
+
"workers_dev": true,
|
|
10
|
+
"durable_objects": {
|
|
11
|
+
"bindings": [{ "name": "EDGEPORT", "class_name": "Relay" }]
|
|
12
|
+
},
|
|
13
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Relay"] }],
|
|
14
|
+
"observability": { "enabled": true }
|
|
15
|
+
}
|