@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/agent.ts
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
// edgeport agent: dials the edge over one outbound WebSocket and serves
|
|
2
|
+
// every stream it carries from a local origin (your dev server).
|
|
3
|
+
//
|
|
4
|
+
// Only outbound HTTPS is needed, through an HTTP proxy if HTTPS_PROXY is set,
|
|
5
|
+
// so it runs in locked-down sandboxes and cloud dev containers where
|
|
6
|
+
// tunnel daemons that need their own ports cannot connect.
|
|
7
|
+
|
|
8
|
+
import http from 'node:http';
|
|
9
|
+
import https from 'node:https';
|
|
10
|
+
import {
|
|
11
|
+
AGENT_PATH,
|
|
12
|
+
Frame,
|
|
13
|
+
HOP_BY_HOP,
|
|
14
|
+
PING_TEXT,
|
|
15
|
+
PROTOCOL_VERSION,
|
|
16
|
+
decode,
|
|
17
|
+
encode,
|
|
18
|
+
json,
|
|
19
|
+
sendableCloseCode,
|
|
20
|
+
text,
|
|
21
|
+
type HeaderList,
|
|
22
|
+
type RequestHead,
|
|
23
|
+
type SocketClose,
|
|
24
|
+
type SocketOpen,
|
|
25
|
+
} from './protocol';
|
|
26
|
+
import { openSocket, type SocketLike } from './socket';
|
|
27
|
+
|
|
28
|
+
export interface AgentOptions {
|
|
29
|
+
/** Public URL of the edge, e.g. `https://dev.example.com`. */
|
|
30
|
+
edge: string;
|
|
31
|
+
/** Shared secret configured on the edge as EDGEPORT_SECRET. */
|
|
32
|
+
secret: string;
|
|
33
|
+
/** Local origin to serve, e.g. `http://127.0.0.1:4321`. */
|
|
34
|
+
origin: string;
|
|
35
|
+
/** Host header to send to the origin. Defaults to the edge's public host. */
|
|
36
|
+
hostHeader?: string;
|
|
37
|
+
log?: (line: string) => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const PING_INTERVAL_MS = 20_000;
|
|
41
|
+
const HIGH_WATER = 4 * 1024 * 1024;
|
|
42
|
+
|
|
43
|
+
export class Agent {
|
|
44
|
+
private socket?: SocketLike;
|
|
45
|
+
private stopped = false;
|
|
46
|
+
private attempt = 0;
|
|
47
|
+
private pingTimer?: ReturnType<typeof setInterval>;
|
|
48
|
+
private requests = new Map<number, http.ClientRequest>();
|
|
49
|
+
private responses = new Map<number, http.IncomingMessage>();
|
|
50
|
+
private sockets = new Map<number, SocketLike>();
|
|
51
|
+
private readonly origin: URL;
|
|
52
|
+
private readonly edge: URL;
|
|
53
|
+
private readonly log: (line: string) => void;
|
|
54
|
+
|
|
55
|
+
constructor(private readonly options: AgentOptions) {
|
|
56
|
+
this.origin = new URL(options.origin);
|
|
57
|
+
this.edge = new URL(options.edge);
|
|
58
|
+
this.log = options.log ?? ((line) => console.log(line));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
start(): void {
|
|
62
|
+
this.stopped = false;
|
|
63
|
+
this.connect();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
stop(): void {
|
|
67
|
+
this.stopped = true;
|
|
68
|
+
clearInterval(this.pingTimer);
|
|
69
|
+
this.socket?.close(1000, 'agent stopping');
|
|
70
|
+
this.resetStreams();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private connect(): void {
|
|
74
|
+
const url = new URL(AGENT_PATH, this.edge);
|
|
75
|
+
url.protocol = url.protocol === 'http:' ? 'ws:' : 'wss:';
|
|
76
|
+
|
|
77
|
+
let socket: SocketLike;
|
|
78
|
+
try {
|
|
79
|
+
socket = openSocket(url.toString(), {
|
|
80
|
+
headers: { authorization: `Bearer ${this.options.secret}`, 'x-edgeport-version': String(PROTOCOL_VERSION) },
|
|
81
|
+
});
|
|
82
|
+
} catch (error) {
|
|
83
|
+
this.log(`edgeport: ${error instanceof Error ? error.message : error}`);
|
|
84
|
+
this.reconnect();
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
this.socket = socket;
|
|
88
|
+
|
|
89
|
+
socket.onopen = () => {
|
|
90
|
+
this.attempt = 0;
|
|
91
|
+
this.log(`edgeport: ${this.edge.origin} -> ${this.origin.origin}`);
|
|
92
|
+
clearInterval(this.pingTimer);
|
|
93
|
+
this.pingTimer = setInterval(() => socket.send(PING_TEXT), PING_INTERVAL_MS);
|
|
94
|
+
};
|
|
95
|
+
socket.onmessage = (data) => {
|
|
96
|
+
if (typeof data === 'string') return; // keepalive replies
|
|
97
|
+
try {
|
|
98
|
+
this.onFrame(data);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
this.log(`edgeport: bad frame: ${error instanceof Error ? error.message : error}`);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
socket.onclose = (code, reason) => {
|
|
104
|
+
if (this.socket !== socket) return;
|
|
105
|
+
clearInterval(this.pingTimer);
|
|
106
|
+
this.resetStreams();
|
|
107
|
+
if (this.stopped) return;
|
|
108
|
+
this.log(`edgeport: disconnected (${code}${reason ? ` ${reason}` : ''})`);
|
|
109
|
+
if (code === 1008 || reason === 'unauthorized') {
|
|
110
|
+
this.log('edgeport: the edge rejected the secret');
|
|
111
|
+
}
|
|
112
|
+
this.reconnect();
|
|
113
|
+
};
|
|
114
|
+
socket.onerror = (message) => {
|
|
115
|
+
if (message) this.log(`edgeport: ${message}`);
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private reconnect(): void {
|
|
120
|
+
if (this.stopped) return;
|
|
121
|
+
const delay = Math.min(10_000, 500 * 2 ** this.attempt++);
|
|
122
|
+
setTimeout(() => this.connect(), delay);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private resetStreams(): void {
|
|
126
|
+
for (const request of this.requests.values()) request.destroy();
|
|
127
|
+
for (const response of this.responses.values()) response.destroy();
|
|
128
|
+
for (const socket of this.sockets.values()) socket.close(1001, 'edgeport agent reconnecting');
|
|
129
|
+
this.requests.clear();
|
|
130
|
+
this.responses.clear();
|
|
131
|
+
this.sockets.clear();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private send(frame: Uint8Array): void {
|
|
135
|
+
this.socket?.send(frame);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private onFrame(data: ArrayBuffer): void {
|
|
139
|
+
const { type, id, payload } = decode(data);
|
|
140
|
+
switch (type) {
|
|
141
|
+
case Frame.RequestHead:
|
|
142
|
+
this.startRequest(id, json<RequestHead>(payload));
|
|
143
|
+
return;
|
|
144
|
+
case Frame.RequestBody:
|
|
145
|
+
this.requests.get(id)?.write(Buffer.from(payload));
|
|
146
|
+
return;
|
|
147
|
+
case Frame.RequestEnd:
|
|
148
|
+
this.requests.get(id)?.end();
|
|
149
|
+
return;
|
|
150
|
+
case Frame.Abort:
|
|
151
|
+
this.requests.get(id)?.destroy();
|
|
152
|
+
this.responses.get(id)?.destroy();
|
|
153
|
+
this.requests.delete(id);
|
|
154
|
+
this.responses.delete(id);
|
|
155
|
+
return;
|
|
156
|
+
case Frame.Warm:
|
|
157
|
+
void this.warm(json<string[]>(payload));
|
|
158
|
+
return;
|
|
159
|
+
case Frame.SocketOpen:
|
|
160
|
+
this.openOriginSocket(id, json<SocketOpen>(payload));
|
|
161
|
+
return;
|
|
162
|
+
case Frame.SocketText:
|
|
163
|
+
this.sockets.get(id)?.send(text(payload));
|
|
164
|
+
return;
|
|
165
|
+
case Frame.SocketBinary:
|
|
166
|
+
this.sockets.get(id)?.send(payload.slice());
|
|
167
|
+
return;
|
|
168
|
+
case Frame.SocketClose: {
|
|
169
|
+
const { code, reason } = json<SocketClose>(payload);
|
|
170
|
+
const socket = this.sockets.get(id);
|
|
171
|
+
this.sockets.delete(id);
|
|
172
|
+
socket?.close(sendableCloseCode(code), reason ?? '');
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
private originHeaders(headers: HeaderList): Record<string, string | string[]> {
|
|
179
|
+
const out: Record<string, string | string[]> = {};
|
|
180
|
+
for (const [name, value] of headers) {
|
|
181
|
+
const lower = name.toLowerCase();
|
|
182
|
+
if (HOP_BY_HOP.has(lower) || lower === 'host') continue;
|
|
183
|
+
const existing = out[lower];
|
|
184
|
+
if (existing === undefined) out[lower] = value;
|
|
185
|
+
else out[lower] = Array.isArray(existing) ? [...existing, value] : [existing, value];
|
|
186
|
+
}
|
|
187
|
+
out.host = this.options.hostHeader ?? this.edge.host;
|
|
188
|
+
out['x-forwarded-host'] ??= this.edge.host;
|
|
189
|
+
out['x-forwarded-proto'] ??= this.edge.protocol.replace(':', '');
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private startRequest(id: number, head: RequestHead): void {
|
|
194
|
+
const transport = this.origin.protocol === 'https:' ? https : http;
|
|
195
|
+
const request = transport.request({
|
|
196
|
+
protocol: this.origin.protocol,
|
|
197
|
+
hostname: this.origin.hostname,
|
|
198
|
+
port: this.origin.port || undefined,
|
|
199
|
+
method: head.method,
|
|
200
|
+
path: head.path,
|
|
201
|
+
headers: this.originHeaders(head.headers),
|
|
202
|
+
// Never route the local hop through HTTPS_PROXY.
|
|
203
|
+
agent: false,
|
|
204
|
+
});
|
|
205
|
+
this.requests.set(id, request);
|
|
206
|
+
|
|
207
|
+
request.on('response', (response) => {
|
|
208
|
+
this.responses.set(id, response);
|
|
209
|
+
const headers: HeaderList = [];
|
|
210
|
+
const raw = response.rawHeaders;
|
|
211
|
+
for (let i = 0; i < raw.length; i += 2) headers.push([raw[i]!, raw[i + 1]!]);
|
|
212
|
+
this.send(encode(Frame.ResponseHead, id, { status: response.statusCode ?? 502, statusText: response.statusMessage, headers }));
|
|
213
|
+
|
|
214
|
+
response.on('data', (chunk: Buffer) => {
|
|
215
|
+
this.send(encode(Frame.ResponseBody, id, new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)));
|
|
216
|
+
if ((this.socket?.bufferedAmount ?? 0) > HIGH_WATER) {
|
|
217
|
+
response.pause();
|
|
218
|
+
const wait = setInterval(() => {
|
|
219
|
+
if ((this.socket?.bufferedAmount ?? 0) < HIGH_WATER / 2 || !this.responses.has(id)) {
|
|
220
|
+
clearInterval(wait);
|
|
221
|
+
response.resume();
|
|
222
|
+
}
|
|
223
|
+
}, 25);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
response.on('end', () => {
|
|
227
|
+
if (!this.responses.delete(id)) return;
|
|
228
|
+
this.requests.delete(id);
|
|
229
|
+
this.send(encode(Frame.ResponseEnd, id));
|
|
230
|
+
});
|
|
231
|
+
response.on('error', () => this.failStream(id, 'origin response failed'));
|
|
232
|
+
});
|
|
233
|
+
request.on('error', (error) => this.failStream(id, `origin unreachable: ${error.message}`));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Fetch each path once from the origin and discard it, a few at a time. */
|
|
237
|
+
private async warm(paths: string[]): Promise<void> {
|
|
238
|
+
const started = Date.now();
|
|
239
|
+
let next = 0;
|
|
240
|
+
let ok = 0;
|
|
241
|
+
const worker = async () => {
|
|
242
|
+
while (next < paths.length && !this.stopped) {
|
|
243
|
+
const path = paths[next++]!;
|
|
244
|
+
const done = await new Promise<boolean>((resolve) => {
|
|
245
|
+
const transport = this.origin.protocol === 'https:' ? https : http;
|
|
246
|
+
const request = transport.request(
|
|
247
|
+
{
|
|
248
|
+
protocol: this.origin.protocol,
|
|
249
|
+
hostname: this.origin.hostname,
|
|
250
|
+
port: this.origin.port || undefined,
|
|
251
|
+
path,
|
|
252
|
+
headers: { host: this.options.hostHeader ?? this.edge.host, accept: '*/*' },
|
|
253
|
+
agent: false,
|
|
254
|
+
},
|
|
255
|
+
(response) => {
|
|
256
|
+
response.resume();
|
|
257
|
+
response.on('end', () => resolve((response.statusCode ?? 500) < 400));
|
|
258
|
+
response.on('error', () => resolve(false));
|
|
259
|
+
},
|
|
260
|
+
);
|
|
261
|
+
request.on('error', () => resolve(false));
|
|
262
|
+
request.setTimeout(30_000, () => request.destroy());
|
|
263
|
+
request.end();
|
|
264
|
+
});
|
|
265
|
+
if (done) ok++;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
await Promise.all(Array.from({ length: 6 }, worker));
|
|
269
|
+
if (paths.length) this.log(`edgeport: warmed ${ok}/${paths.length} paths in ${((Date.now() - started) / 1000).toFixed(1)}s`);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private failStream(id: number, message: string): void {
|
|
273
|
+
const pending = this.requests.has(id) || this.responses.has(id);
|
|
274
|
+
this.requests.delete(id);
|
|
275
|
+
this.responses.delete(id);
|
|
276
|
+
if (pending) this.send(encode(Frame.Abort, id, message));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
private openOriginSocket(id: number, open: SocketOpen): void {
|
|
280
|
+
const url = new URL(open.path, this.origin);
|
|
281
|
+
url.protocol = this.origin.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
282
|
+
|
|
283
|
+
const headers: Record<string, string> = {};
|
|
284
|
+
for (const [name, value] of Object.entries(this.originHeaders(open.headers))) {
|
|
285
|
+
headers[name] = Array.isArray(value) ? value.join(', ') : value;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
let socket: SocketLike;
|
|
289
|
+
try {
|
|
290
|
+
socket = openSocket(url.toString(), { headers, protocols: open.protocols, direct: true });
|
|
291
|
+
} catch (error) {
|
|
292
|
+
this.send(encode(Frame.Abort, id, error instanceof Error ? error.message : String(error)));
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
let accepted = false;
|
|
296
|
+
socket.onopen = () => {
|
|
297
|
+
accepted = true;
|
|
298
|
+
this.sockets.set(id, socket);
|
|
299
|
+
this.send(encode(Frame.SocketAccept, id, { protocol: socket.protocol || undefined }));
|
|
300
|
+
};
|
|
301
|
+
socket.onmessage = (data) => {
|
|
302
|
+
if (!this.sockets.has(id)) return;
|
|
303
|
+
this.send(typeof data === 'string' ? encode(Frame.SocketText, id, data) : encode(Frame.SocketBinary, id, new Uint8Array(data)));
|
|
304
|
+
};
|
|
305
|
+
socket.onclose = (code, reason) => {
|
|
306
|
+
if (!accepted) {
|
|
307
|
+
this.send(encode(Frame.Abort, id, `origin refused the WebSocket (${code})`));
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (!this.sockets.delete(id)) return;
|
|
311
|
+
this.send(encode(Frame.SocketClose, id, { code, reason }));
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { Agent } from './agent';
|
|
4
|
+
import { prepareSockets } from './socket';
|
|
5
|
+
|
|
6
|
+
const usage = `Usage: edgeport <origin> --edge <url> [--host-header <host>]
|
|
7
|
+
|
|
8
|
+
Expose a local dev server at your own Cloudflare hostname over one outbound
|
|
9
|
+
WebSocket. Works behind HTTPS proxies and in cloud dev containers.
|
|
10
|
+
|
|
11
|
+
Arguments:
|
|
12
|
+
<origin> Local server to expose, e.g. http://127.0.0.1:4321
|
|
13
|
+
(a bare port such as 4321 means http://127.0.0.1:4321)
|
|
14
|
+
|
|
15
|
+
Options:
|
|
16
|
+
--edge <url> Public URL of your deployed edgeport Worker
|
|
17
|
+
(env EDGEPORT_EDGE)
|
|
18
|
+
--host-header <host> Host header sent to the origin (default: the edge host)
|
|
19
|
+
-h, --help Show this help
|
|
20
|
+
|
|
21
|
+
Environment:
|
|
22
|
+
EDGEPORT_SECRET Shared secret, the same value as the Worker's
|
|
23
|
+
EDGEPORT_SECRET (required)
|
|
24
|
+
HTTPS_PROXY, NO_PROXY Used for the connection to the edge
|
|
25
|
+
`;
|
|
26
|
+
|
|
27
|
+
const { values, positionals } = parseArgs({
|
|
28
|
+
allowPositionals: true,
|
|
29
|
+
options: {
|
|
30
|
+
edge: { type: 'string' },
|
|
31
|
+
'host-header': { type: 'string' },
|
|
32
|
+
help: { type: 'boolean', short: 'h' },
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
if (values.help) {
|
|
37
|
+
process.stdout.write(usage);
|
|
38
|
+
process.exit(0);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const fail = (message: string): never => {
|
|
42
|
+
process.stderr.write(`edgeport: ${message}\n\n${usage}`);
|
|
43
|
+
process.exit(2);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const rawOrigin = positionals[0] ?? fail('missing <origin>');
|
|
47
|
+
const origin = /^\d+$/.test(rawOrigin) ? `http://127.0.0.1:${rawOrigin}` : rawOrigin;
|
|
48
|
+
const edge = values.edge ?? process.env.EDGEPORT_EDGE ?? fail('missing --edge');
|
|
49
|
+
const secret = process.env.EDGEPORT_SECRET ?? fail('EDGEPORT_SECRET is not set');
|
|
50
|
+
|
|
51
|
+
await prepareSockets();
|
|
52
|
+
const agent = new Agent({ edge, secret, origin, hostHeader: values['host-header'] });
|
|
53
|
+
agent.start();
|
|
54
|
+
|
|
55
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
|
56
|
+
process.on(signal, () => {
|
|
57
|
+
agent.stop();
|
|
58
|
+
process.exit(0);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// First-load help for dev servers that serve one unbundled module per file
|
|
2
|
+
// (Vite and friends). Through a relay every module costs a round trip, and
|
|
3
|
+
// the browser only discovers the next level of imports after the previous
|
|
4
|
+
// level arrives, so a cold page load is a waterfall of round trips.
|
|
5
|
+
//
|
|
6
|
+
// Two things make it better:
|
|
7
|
+
// - Learned preloads: after a page loads, the edge remembers which module
|
|
8
|
+
// scripts that page pulled in. On the next load of the same page it adds
|
|
9
|
+
// <link rel="modulepreload"> for all of them to the HTML, so the browser
|
|
10
|
+
// asks for them in parallel instead of level by level. Dev servers mark
|
|
11
|
+
// source modules `no-cache`, so this speeds up every full reload, not only
|
|
12
|
+
// the first one.
|
|
13
|
+
// - A loading hint: a thin progress bar and a small label that appear only
|
|
14
|
+
// if the page takes longer than half a second, and fade out once it loads.
|
|
15
|
+
|
|
16
|
+
const LEARN_WINDOW_MS = 20_000;
|
|
17
|
+
const MAX_PRELOADS = 400;
|
|
18
|
+
const STORAGE_PREFIX = 'preload:';
|
|
19
|
+
|
|
20
|
+
interface Session {
|
|
21
|
+
page: string;
|
|
22
|
+
until: number;
|
|
23
|
+
urls: Set<string>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class PreloadLearner {
|
|
27
|
+
private sessions = new Map<string, Session>();
|
|
28
|
+
private cache = new Map<string, string[]>();
|
|
29
|
+
|
|
30
|
+
constructor(private readonly storage: DurableObjectStorage) {}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Called for every relayed request. For a page navigation without a client
|
|
34
|
+
* cookie it returns a Set-Cookie value to add to the response: requests from
|
|
35
|
+
* one browser can arrive from several IPs, so the cookie ties them together.
|
|
36
|
+
*/
|
|
37
|
+
observe(request: Request, url: URL): string | undefined {
|
|
38
|
+
const dest = request.headers.get('sec-fetch-dest');
|
|
39
|
+
let client = readCookie(request, CLIENT_COOKIE);
|
|
40
|
+
let setCookie: string | undefined;
|
|
41
|
+
if (!client && dest === 'document') {
|
|
42
|
+
client = crypto.randomUUID();
|
|
43
|
+
setCookie = `${CLIENT_COOKIE}=${client}; Path=/; Max-Age=31536000; SameSite=Lax; HttpOnly${url.protocol === 'https:' ? '; Secure' : ''}`;
|
|
44
|
+
}
|
|
45
|
+
if (!client) return undefined;
|
|
46
|
+
const now = Date.now();
|
|
47
|
+
if (request.method !== 'GET') return setCookie;
|
|
48
|
+
|
|
49
|
+
if (dest === 'document') {
|
|
50
|
+
this.flush(client);
|
|
51
|
+
this.sessions.set(client, { page: pageKey(url), until: now + LEARN_WINDOW_MS, urls: new Set() });
|
|
52
|
+
return setCookie;
|
|
53
|
+
}
|
|
54
|
+
if (dest !== 'script') return undefined;
|
|
55
|
+
const session = this.sessions.get(client);
|
|
56
|
+
if (!session) return undefined;
|
|
57
|
+
if (now > session.until) {
|
|
58
|
+
this.flush(client);
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
// Skip HMR-stamped URLs: they change on every edit.
|
|
62
|
+
if (url.searchParams.has('t')) return undefined;
|
|
63
|
+
if (session.urls.size < MAX_PRELOADS) {
|
|
64
|
+
session.urls.add(url.pathname + url.search);
|
|
65
|
+
// Persist as it grows, so a page that is never left still teaches.
|
|
66
|
+
this.scheduleFlush(client);
|
|
67
|
+
}
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private timers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
72
|
+
|
|
73
|
+
private scheduleFlush(client: string): void {
|
|
74
|
+
clearTimeout(this.timers.get(client) ?? null);
|
|
75
|
+
this.timers.set(
|
|
76
|
+
client,
|
|
77
|
+
setTimeout(() => {
|
|
78
|
+
this.timers.delete(client);
|
|
79
|
+
const session = this.sessions.get(client);
|
|
80
|
+
if (session) this.save(session);
|
|
81
|
+
}, 2_000),
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private save(session: Session): void {
|
|
86
|
+
if (session.urls.size === 0) return;
|
|
87
|
+
const urls = [...session.urls];
|
|
88
|
+
this.cache.set(session.page, urls);
|
|
89
|
+
void this.storage.put(STORAGE_PREFIX + session.page, urls).catch(() => {});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private flush(client: string): void {
|
|
93
|
+
const session = this.sessions.get(client);
|
|
94
|
+
if (!session) return;
|
|
95
|
+
this.sessions.delete(client);
|
|
96
|
+
clearTimeout(this.timers.get(client) ?? null);
|
|
97
|
+
this.timers.delete(client);
|
|
98
|
+
this.save(session);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Every learned page and its modules, for warming a freshly connected origin. */
|
|
102
|
+
async warmList(limit = 1_000): Promise<string[]> {
|
|
103
|
+
const all = new Set<string>();
|
|
104
|
+
const stored = await this.storage.list<string[]>({ prefix: STORAGE_PREFIX }).catch(() => new Map<string, string[]>());
|
|
105
|
+
for (const [key, urls] of stored) {
|
|
106
|
+
all.add(key.slice(STORAGE_PREFIX.length));
|
|
107
|
+
for (const url of urls) all.add(url);
|
|
108
|
+
if (all.size >= limit) break;
|
|
109
|
+
}
|
|
110
|
+
return [...all].slice(0, limit);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async preloadsFor(url: URL): Promise<string[]> {
|
|
114
|
+
const key = pageKey(url);
|
|
115
|
+
const cached = this.cache.get(key);
|
|
116
|
+
if (cached) return cached;
|
|
117
|
+
const stored = (await this.storage.get<string[]>(STORAGE_PREFIX + key).catch(() => undefined)) ?? [];
|
|
118
|
+
this.cache.set(key, stored);
|
|
119
|
+
return stored;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const CLIENT_COOKIE = '__edgeport_client';
|
|
124
|
+
|
|
125
|
+
function readCookie(request: Request, name: string): string | undefined {
|
|
126
|
+
const header = request.headers.get('cookie');
|
|
127
|
+
if (!header) return undefined;
|
|
128
|
+
for (const part of header.split(';')) {
|
|
129
|
+
const [key, ...rest] = part.trim().split('=');
|
|
130
|
+
if (key === name) return rest.join('=') || undefined;
|
|
131
|
+
}
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function pageKey(url: URL): string {
|
|
136
|
+
return url.pathname;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function isHtmlNavigation(request: Request, headers: Headers): boolean {
|
|
140
|
+
return (
|
|
141
|
+
request.method === 'GET' &&
|
|
142
|
+
request.headers.get('sec-fetch-dest') === 'document' &&
|
|
143
|
+
(headers.get('content-type') ?? '').toLowerCase().includes('text/html') &&
|
|
144
|
+
!headers.has('content-encoding')
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function enhanceHtml(body: ReadableStream<Uint8Array>, preloads: string[]): ReadableStream<Uint8Array> {
|
|
149
|
+
const links = preloads.map((href) => `<link rel="modulepreload" href="${escapeAttr(href)}">`).join('');
|
|
150
|
+
const html = links + LOADING_HINT;
|
|
151
|
+
let inserted = false;
|
|
152
|
+
// Right after <meta charset>, which must stay within the first 1024 bytes;
|
|
153
|
+
// otherwise at the end of <head>.
|
|
154
|
+
const response = new HTMLRewriter()
|
|
155
|
+
.on('head meta[charset]', {
|
|
156
|
+
element(meta) {
|
|
157
|
+
if (inserted) return;
|
|
158
|
+
inserted = true;
|
|
159
|
+
meta.after(html, { html: true });
|
|
160
|
+
},
|
|
161
|
+
})
|
|
162
|
+
.on('head', {
|
|
163
|
+
element(head) {
|
|
164
|
+
head.onEndTag((end) => {
|
|
165
|
+
if (inserted) return;
|
|
166
|
+
inserted = true;
|
|
167
|
+
end.before(html, { html: true });
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
})
|
|
171
|
+
.transform(new Response(body));
|
|
172
|
+
return response.body!;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function escapeAttr(value: string): string {
|
|
176
|
+
return value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Kept dependency-free and small. Shows nothing for loads under 500 ms and
|
|
180
|
+
// respects prefers-reduced-motion. Removes itself after the load event.
|
|
181
|
+
const LOADING_HINT = `<script data-edgeport>(()=>{if(window.__edgeportHint)return;window.__edgeportHint=1;
|
|
182
|
+
var d=document,done=false,bar,pill,n=0,timer,still=matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
183
|
+
function count(){try{n=performance.getEntriesByType('resource').length}catch(e){}}
|
|
184
|
+
function paint(){count();if(!bar)return;bar.style.transform='scaleX('+(0.08+0.82*(1-Math.exp(-n/60)))+')';pill.textContent=n>1?'Loading over edgeport \\u00b7 '+n+' files':'Loading over edgeport\\u2026'}
|
|
185
|
+
function show(){if(done)return;var r=d.documentElement;
|
|
186
|
+
bar=d.createElement('div');pill=d.createElement('div');bar.setAttribute('aria-hidden','true');pill.setAttribute('role','status');
|
|
187
|
+
bar.style.cssText='position:fixed;inset:0 0 auto 0;height:2px;z-index:2147483647;background:#f6821f;transform-origin:0 50%;transform:scaleX(0);pointer-events:none;transition:'+(still?'opacity .2s':'transform .4s cubic-bezier(.2,.7,.2,1),opacity .4s ease');
|
|
188
|
+
pill.style.cssText='position:fixed;left:50%;bottom:calc(16px + env(safe-area-inset-bottom));transform:translateX(-50%);z-index:2147483647;padding:6px 12px;border-radius:999px;font:500 12px/1.3 -apple-system,system-ui,sans-serif;font-variant-numeric:tabular-nums;color:#fff;background:rgba(20,20,20,.72);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);pointer-events:none;opacity:0;transition:opacity .3s ease;white-space:nowrap';
|
|
189
|
+
r.appendChild(bar);r.appendChild(pill);paint();requestAnimationFrame(function(){pill.style.opacity='1'});timer=setInterval(paint,150)}
|
|
190
|
+
var wait=setTimeout(show,500);
|
|
191
|
+
addEventListener('load',function(){done=true;clearTimeout(wait);clearInterval(timer);if(!bar)return;
|
|
192
|
+
bar.style.transform='scaleX(1)';setTimeout(function(){bar.style.opacity='0';pill.style.opacity='0';setTimeout(function(){bar.remove();pill.remove()},450)},250)});
|
|
193
|
+
})()</script>`;
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Wire format shared by the edge Worker and the agent.
|
|
2
|
+
//
|
|
3
|
+
// Every frame on the agent socket is binary:
|
|
4
|
+
// byte 0 frame type
|
|
5
|
+
// bytes 1..4 stream id (uint32, big endian); 0 for connection-level frames
|
|
6
|
+
// bytes 5.. payload (raw bytes, UTF-8 text or JSON, depending on the type)
|
|
7
|
+
//
|
|
8
|
+
// One stream carries either one HTTP exchange or one proxied WebSocket.
|
|
9
|
+
|
|
10
|
+
export const AGENT_PATH = '/_edgeport/connect';
|
|
11
|
+
export const PING_TEXT = 'edgeport:ping';
|
|
12
|
+
export const PONG_TEXT = 'edgeport:pong';
|
|
13
|
+
export const PROTOCOL_VERSION = 1;
|
|
14
|
+
|
|
15
|
+
export const Frame = {
|
|
16
|
+
// edge -> agent
|
|
17
|
+
RequestHead: 1,
|
|
18
|
+
RequestBody: 2,
|
|
19
|
+
RequestEnd: 3,
|
|
20
|
+
// agent -> edge
|
|
21
|
+
ResponseHead: 4,
|
|
22
|
+
ResponseBody: 5,
|
|
23
|
+
ResponseEnd: 6,
|
|
24
|
+
// either direction: the stream failed or its client went away
|
|
25
|
+
Abort: 7,
|
|
26
|
+
// edge -> agent: a browser opened a WebSocket
|
|
27
|
+
SocketOpen: 8,
|
|
28
|
+
// agent -> edge: the origin accepted it
|
|
29
|
+
SocketAccept: 9,
|
|
30
|
+
// either direction
|
|
31
|
+
SocketText: 10,
|
|
32
|
+
SocketBinary: 11,
|
|
33
|
+
SocketClose: 12,
|
|
34
|
+
// edge -> agent, stream 0: JSON list of paths worth fetching once from the
|
|
35
|
+
// origin right away, so its transform cache is warm before a browser asks
|
|
36
|
+
Warm: 13,
|
|
37
|
+
} as const;
|
|
38
|
+
export type Frame = (typeof Frame)[keyof typeof Frame];
|
|
39
|
+
|
|
40
|
+
export type HeaderList = [string, string][];
|
|
41
|
+
|
|
42
|
+
export interface RequestHead {
|
|
43
|
+
method: string;
|
|
44
|
+
/** Path and query, e.g. `/blog?page=2`. */
|
|
45
|
+
path: string;
|
|
46
|
+
headers: HeaderList;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ResponseHead {
|
|
50
|
+
status: number;
|
|
51
|
+
statusText?: string;
|
|
52
|
+
headers: HeaderList;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface SocketOpen {
|
|
56
|
+
path: string;
|
|
57
|
+
headers: HeaderList;
|
|
58
|
+
protocols: string[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface SocketAccept {
|
|
62
|
+
protocol?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface SocketClose {
|
|
66
|
+
code?: number;
|
|
67
|
+
reason?: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const encoder = new TextEncoder();
|
|
71
|
+
const decoder = new TextDecoder();
|
|
72
|
+
|
|
73
|
+
export function encode(type: Frame, id: number, payload?: Uint8Array | string | object): Uint8Array {
|
|
74
|
+
let body: Uint8Array;
|
|
75
|
+
if (payload === undefined) body = new Uint8Array(0);
|
|
76
|
+
else if (payload instanceof Uint8Array) body = payload;
|
|
77
|
+
else if (typeof payload === 'string') body = encoder.encode(payload);
|
|
78
|
+
else body = encoder.encode(JSON.stringify(payload));
|
|
79
|
+
|
|
80
|
+
const frame = new Uint8Array(5 + body.byteLength);
|
|
81
|
+
frame[0] = type;
|
|
82
|
+
new DataView(frame.buffer).setUint32(1, id >>> 0, false);
|
|
83
|
+
frame.set(body, 5);
|
|
84
|
+
return frame;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface DecodedFrame {
|
|
88
|
+
type: Frame;
|
|
89
|
+
id: number;
|
|
90
|
+
payload: Uint8Array;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function decode(data: ArrayBuffer | Uint8Array): DecodedFrame {
|
|
94
|
+
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
95
|
+
if (bytes.byteLength < 5) throw new Error('edgeport: short frame');
|
|
96
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
97
|
+
return { type: bytes[0] as Frame, id: view.getUint32(1, false), payload: bytes.subarray(5) };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function text(payload: Uint8Array): string {
|
|
101
|
+
return decoder.decode(payload);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function json<T>(payload: Uint8Array): T {
|
|
105
|
+
return JSON.parse(decoder.decode(payload)) as T;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Headers that describe one hop and must not be forwarded. */
|
|
109
|
+
export const HOP_BY_HOP = new Set([
|
|
110
|
+
'connection',
|
|
111
|
+
'keep-alive',
|
|
112
|
+
'proxy-authenticate',
|
|
113
|
+
'proxy-authorization',
|
|
114
|
+
'proxy-connection',
|
|
115
|
+
'te',
|
|
116
|
+
'trailer',
|
|
117
|
+
'transfer-encoding',
|
|
118
|
+
'upgrade',
|
|
119
|
+
'http2-settings',
|
|
120
|
+
]);
|
|
121
|
+
|
|
122
|
+
/** Close codes a peer may not send itself; replace them before forwarding. */
|
|
123
|
+
export function sendableCloseCode(code: number | undefined): number {
|
|
124
|
+
if (code === undefined || code === 1005 || code === 1006 || code === 1015) return 1000;
|
|
125
|
+
if (code === 1000 || (code >= 3000 && code <= 4999) || (code >= 1001 && code <= 1014 && code !== 1004)) return code;
|
|
126
|
+
return 1000;
|
|
127
|
+
}
|