@bom0792/herdgate 0.0.0-stage → 0.9.6
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 +167 -2
- package/app-mod/herdgate/main.js +395 -0
- package/app-mod/herdgate/mod.json +5 -0
- package/bin/herdgate.mjs +91 -0
- package/dist-readme.md +48 -0
- package/package.json +36 -3
- package/plugin/herdr-plugin.toml +36 -0
- package/plugin/server/common.mjs +79 -0
- package/plugin/server/e2e.d.mts +43 -0
- package/plugin/server/e2e.mjs +268 -0
- package/plugin/server/index.mjs +454 -0
- package/plugin/server/ssh.mjs +241 -0
- package/scripts/build-host-bundle.sh +12 -0
- package/scripts/deploy-vps.sh +74 -0
- package/scripts/patch-ssh2.mjs +32 -0
- package/src/agent/adapter.ts +23 -0
- package/src/agent/index.ts +183 -0
- package/src/cloud/gateway.ts +946 -0
- package/src/cloud/main.ts +88 -0
- package/src/cloud/pairing.ts +81 -0
- package/src/cloud/ssh-bridge.ts +212 -0
- package/src/cloud/sshd.ts +412 -0
- package/src/cloud/static.ts +142 -0
- package/src/cloud/stores.ts +180 -0
- package/src/cloud/util.ts +47 -0
- package/src/cloud/vapid.ts +105 -0
- package/src/dev/edge-sim.ts +99 -0
- package/src/dev/main.ts +33 -0
- package/src/host/herdr.ts +316 -0
- package/src/host/main.ts +105 -0
- package/src/host/ssh.ts +317 -0
- package/src/index.ts +5 -0
- package/src/protocol/agent.ts +84 -0
- package/src/protocol/device.ts +90 -0
- package/src/protocol/envelope.ts +58 -0
- package/src/protocol/index.ts +3 -0
- package/src/web/app.css +312 -0
- package/src/web/app.js +835 -0
- package/src/web/app.webmanifest +15 -0
- package/src/web/e2e.js +268 -0
- package/src/web/herdgate-host.zip +0 -0
- package/src/web/icons/icon-192.png +0 -0
- package/src/web/icons/icon-512.png +0 -0
- package/src/web/icons/icon.svg +6 -0
- package/src/web/index.html +99 -0
- package/src/web/sw.js +98 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloud state: accounts (config-provided), rooms (one host) and devices.
|
|
3
|
+
* Persisted to one JSON file with an atomic tmp+rename write; room tokens are
|
|
4
|
+
* stored **hashed** (sha256), the plaintext exists only at mint time.
|
|
5
|
+
*
|
|
6
|
+
* v0 is a single JSON file — the interfaces are shaped so a Postgres/Redis
|
|
7
|
+
* implementation can replace it without touching the gateway.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { dirname } from "node:path";
|
|
12
|
+
import type { Scope } from "../protocol/envelope.ts";
|
|
13
|
+
import { randomId, randomToken, sameSecret, sha256Hex } from "./util.ts";
|
|
14
|
+
|
|
15
|
+
export interface Account {
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
/** Config-provided; the only plaintext secret the cloud holds. */
|
|
19
|
+
token: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface RoomRecord {
|
|
23
|
+
id: string;
|
|
24
|
+
accountId: string;
|
|
25
|
+
name: string;
|
|
26
|
+
tokenHash: string;
|
|
27
|
+
created: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface DeviceRecord {
|
|
31
|
+
id: string;
|
|
32
|
+
roomId: string;
|
|
33
|
+
accountId: string;
|
|
34
|
+
name: string;
|
|
35
|
+
scope: Scope;
|
|
36
|
+
created: string;
|
|
37
|
+
/** sha256 of the device's own secret; the plaintext exists only at pair time. */
|
|
38
|
+
secretHash?: string;
|
|
39
|
+
/** The device's web-push subscription endpoint for silent wake pings (VAPID). */
|
|
40
|
+
push?: { endpoint: string; at: string };
|
|
41
|
+
/** SSH public keys this device may log in with (authorized_keys lines, parsed). */
|
|
42
|
+
sshKeys?: { algo: string; b64: string; comment?: string; at: string }[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface StateFile {
|
|
46
|
+
v: 1;
|
|
47
|
+
rooms: RoomRecord[];
|
|
48
|
+
devices: DeviceRecord[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export class State {
|
|
52
|
+
readonly accounts: Account[];
|
|
53
|
+
rooms: RoomRecord[] = [];
|
|
54
|
+
devices: DeviceRecord[] = [];
|
|
55
|
+
readonly #path: string | null;
|
|
56
|
+
|
|
57
|
+
constructor(accounts: Account[], path?: string) {
|
|
58
|
+
this.accounts = accounts;
|
|
59
|
+
this.#path = path ?? null;
|
|
60
|
+
if (this.#path) this.#load();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
#load(): void {
|
|
64
|
+
try {
|
|
65
|
+
const f = JSON.parse(readFileSync(this.#path!, "utf8")) as StateFile;
|
|
66
|
+
if (f.v === 1) {
|
|
67
|
+
this.rooms = f.rooms ?? [];
|
|
68
|
+
this.devices = f.devices ?? [];
|
|
69
|
+
}
|
|
70
|
+
} catch (e) {
|
|
71
|
+
if (!(e instanceof Error && "code" in e && (e as { code?: string }).code === "ENOENT")) {
|
|
72
|
+
throw e;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
#save(): void {
|
|
78
|
+
if (!this.#path) return;
|
|
79
|
+
const file: StateFile = { v: 1, rooms: this.rooms, devices: this.devices };
|
|
80
|
+
const tmp = `${this.#path}.tmp-${Math.random().toString(36).slice(2)}`;
|
|
81
|
+
mkdirSync(dirname(this.#path), { recursive: true });
|
|
82
|
+
writeFileSync(tmp, JSON.stringify(file), { mode: 0o600 });
|
|
83
|
+
renameSync(tmp, this.#path);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
accountByToken(token: string): Account | null {
|
|
87
|
+
return this.accounts.find((a) => a.token === token) ?? null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
roomByTokenHash(hash: string): RoomRecord | null {
|
|
91
|
+
return this.rooms.find((r) => r.tokenHash === hash) ?? null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
roomsOfAccount(accountId: string): RoomRecord[] {
|
|
95
|
+
return this.rooms.filter((r) => r.accountId === accountId);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
addRoom(accountId: string, name: string): { room: RoomRecord; token: string } {
|
|
99
|
+
const token = randomToken(32);
|
|
100
|
+
const room: RoomRecord = {
|
|
101
|
+
id: randomId("r"),
|
|
102
|
+
accountId,
|
|
103
|
+
name,
|
|
104
|
+
tokenHash: sha256Hex(token),
|
|
105
|
+
created: new Date().toISOString(),
|
|
106
|
+
};
|
|
107
|
+
this.rooms.push(room);
|
|
108
|
+
this.#save();
|
|
109
|
+
return { room, token };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
devicesOfRoom(roomId: string): DeviceRecord[] {
|
|
113
|
+
return this.devices.filter((d) => d.roomId === roomId);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
deviceById(id: string): DeviceRecord | null {
|
|
117
|
+
return this.devices.find((d) => d.id === id) ?? null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Remember (or forget, with a null endpoint) where to wake a device. */
|
|
121
|
+
setDevicePush(id: string, endpoint: string | null): boolean {
|
|
122
|
+
const d = this.deviceById(id);
|
|
123
|
+
if (!d) return false;
|
|
124
|
+
d.push = endpoint ? { endpoint, at: new Date().toISOString() } : undefined;
|
|
125
|
+
if (!endpoint) delete d.push;
|
|
126
|
+
this.#save();
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A paired device presenting its own secret (not the account token). */
|
|
131
|
+
deviceByCredentials(id: string, secret: string): DeviceRecord | null {
|
|
132
|
+
const d = this.deviceById(id);
|
|
133
|
+
if (!d || !d.secretHash) return null;
|
|
134
|
+
return sameSecret(d.secretHash, sha256Hex(secret)) ? d : null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Authorize an SSH public key for a device (deduped, capped). */
|
|
138
|
+
addDeviceSshKey(id: string, algo: string, b64: string, comment?: string): boolean {
|
|
139
|
+
const d = this.deviceById(id);
|
|
140
|
+
if (!d) return false;
|
|
141
|
+
d.sshKeys ??= [];
|
|
142
|
+
if (d.sshKeys.some((k) => k.algo === algo && k.b64 === b64)) return true;
|
|
143
|
+
if (d.sshKeys.length >= 5) return false;
|
|
144
|
+
d.sshKeys.push({ algo, b64, comment: comment?.slice(0, 200) || undefined, at: new Date().toISOString() });
|
|
145
|
+
this.#save();
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
removeDeviceSshKey(id: string, b64: string): boolean {
|
|
150
|
+
const d = this.deviceById(id);
|
|
151
|
+
if (!d?.sshKeys) return false;
|
|
152
|
+
const n = d.sshKeys.length;
|
|
153
|
+
d.sshKeys = d.sshKeys.filter((k) => k.b64 !== b64);
|
|
154
|
+
if (d.sshKeys.length === n) return false;
|
|
155
|
+
if (d.sshKeys.length === 0) delete d.sshKeys;
|
|
156
|
+
this.#save();
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
accountById(id: string): Account | null {
|
|
161
|
+
return this.accounts.find((a) => a.id === id) ?? null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Mints the device and its one-time secret (returned plaintext, stored hashed). */
|
|
165
|
+
addDevice(room: RoomRecord, name: string, scope: Scope): { device: DeviceRecord; secret: string } {
|
|
166
|
+
const secret = randomToken(32);
|
|
167
|
+
const d: DeviceRecord = {
|
|
168
|
+
id: randomId("d"),
|
|
169
|
+
roomId: room.id,
|
|
170
|
+
accountId: room.accountId,
|
|
171
|
+
name,
|
|
172
|
+
scope,
|
|
173
|
+
created: new Date().toISOString(),
|
|
174
|
+
secretHash: sha256Hex(secret),
|
|
175
|
+
};
|
|
176
|
+
this.devices.push(d);
|
|
177
|
+
this.#save();
|
|
178
|
+
return { device: d, secret };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Small crypto/format helpers for the cloud side. */
|
|
2
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
export function sha256Hex(s: string): string {
|
|
5
|
+
return createHash("sha256").update(s, "utf8").digest("hex");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function randomToken(bytes = 32): string {
|
|
9
|
+
return randomBytes(bytes).toString("base64url");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Constant-time string comparison (both hashed first to equalise length). */
|
|
13
|
+
export function sameSecret(a: string, b: string): boolean {
|
|
14
|
+
const ha = Buffer.from(sha256Hex(a), "utf8");
|
|
15
|
+
const hb = Buffer.from(sha256Hex(b), "utf8");
|
|
16
|
+
return timingSafeEqual(ha, hb);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Short, human-typable codes without lookalikes (no 0/O/1/I). */
|
|
20
|
+
const CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
|
21
|
+
export function randomCode(len = 8): string {
|
|
22
|
+
const buf = randomBytes(len);
|
|
23
|
+
let out = "";
|
|
24
|
+
for (let i = 0; i < len; i++) out += CODE_ALPHABET[buf[i] % CODE_ALPHABET.length];
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function randomId(prefix: string): string {
|
|
29
|
+
return `${prefix}_${randomBytes(4).toString("hex")}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Reads a JSON object body with a size cap; `null` when not a small object. */
|
|
33
|
+
export async function readJsonBody(req: import("node:http").IncomingMessage, maxBytes = 4096): Promise<Record<string, unknown> | null> {
|
|
34
|
+
const chunks: Buffer[] = [];
|
|
35
|
+
let size = 0;
|
|
36
|
+
for await (const c of req) {
|
|
37
|
+
size += (c as Buffer).length;
|
|
38
|
+
if (size > maxBytes) return null;
|
|
39
|
+
chunks.push(c as Buffer);
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const v = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
43
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) ? v as Record<string, unknown> : null;
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal VAPID (RFC 8292) for silent wake pushes: sign a JWT with an ES256 key and
|
|
3
|
+
* build the `Authorization: vapid t=…, k=…` header. No payload is ever sent — the
|
|
4
|
+
* push exists to wake the phone's service worker, so this is all the protocol we need.
|
|
5
|
+
*
|
|
6
|
+
* Keys are generated once and persisted by the caller (main.ts) so the public key the
|
|
7
|
+
* browsers subscribed to never changes behind their backs.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createHash, createPrivateKey, createPublicKey, sign, verify, generateKeyPairSync } from "node:crypto";
|
|
11
|
+
import type { JsonWebKey } from "node:crypto";
|
|
12
|
+
|
|
13
|
+
export interface VapidKeys {
|
|
14
|
+
/** JWK private key (P-256, d + x + y). Persist this. */
|
|
15
|
+
privateJwk: JsonWebKey;
|
|
16
|
+
/** Raw public point (65 bytes), base64url — what browsers subscribe against. */
|
|
17
|
+
publicBase64Url: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function generateVapidKeys(): VapidKeys {
|
|
21
|
+
const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
|
|
22
|
+
const privateJwk = privateKey.export({ format: "jwk" }) as JsonWebKey;
|
|
23
|
+
const raw = publicKey.export({ format: "jwk" }) as { x: string; y: string };
|
|
24
|
+
// 0x04 ‖ X ‖ Y — the uncompressed point browsers use as applicationServerKey.
|
|
25
|
+
const point = Buffer.concat([Buffer.from([0x04]), b64uDecode(raw.x), b64uDecode(raw.y)]);
|
|
26
|
+
return { privateJwk, publicBase64Url: b64uEncode(point) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function loadVapidKeys(privateJwk: JsonWebKey): VapidKeys {
|
|
30
|
+
const pub = createPublicKey({ key: privateJwk, format: "jwk" });
|
|
31
|
+
const jwk = pub.export({ format: "jwk" }) as { x: string; y: string };
|
|
32
|
+
const point = Buffer.concat([Buffer.from([0x04]), b64uDecode(jwk.x), b64uDecode(jwk.y)]);
|
|
33
|
+
return { privateJwk, publicBase64Url: b64uEncode(point) };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const b64uEncode = (b: Buffer | Uint8Array): string => Buffer.from(b).toString("base64url");
|
|
37
|
+
const b64uDecode = (s: string): Buffer => Buffer.from(s, "base64url");
|
|
38
|
+
|
|
39
|
+
/** ES256 signature in the JOSE raw r‖s form (not DER). */
|
|
40
|
+
function es256Sign(data: Buffer, privateJwk: JsonWebKey): Buffer {
|
|
41
|
+
const key = createPrivateKey({ key: privateJwk, format: "jwk" });
|
|
42
|
+
const der = sign("sha256", data, key);
|
|
43
|
+
// DER: 0x30 len 0x02 rlen r 0x02 slen s → strip to 32-byte r + 32-byte s.
|
|
44
|
+
let o = 2;
|
|
45
|
+
const rLen = der[o + 1];
|
|
46
|
+
const r = der.subarray(o + 2, o + 2 + rLen);
|
|
47
|
+
o += 2 + rLen;
|
|
48
|
+
const sLen = der[o + 1];
|
|
49
|
+
const s = der.subarray(o + 2, o + 2 + sLen);
|
|
50
|
+
// DER may carry a leading 0x00 (positive marker): keep the low 32 bytes, left-pad.
|
|
51
|
+
const pad = (b: Buffer): Buffer => {
|
|
52
|
+
const x = b.length > 32 ? b.subarray(b.length - 32) : b;
|
|
53
|
+
return Buffer.concat([Buffer.alloc(32 - x.length), x]);
|
|
54
|
+
};
|
|
55
|
+
return Buffer.concat([pad(r), pad(s)]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The Authorization header value for a wake push to `endpoint`.
|
|
60
|
+
* `sub` is a contact mailto (required by the spec); `exp` is hours-limited.
|
|
61
|
+
*/
|
|
62
|
+
export function vapidHeader(endpoint: string, keys: VapidKeys, sub: string, now = Date.now()): string {
|
|
63
|
+
const aud = new URL(endpoint).origin;
|
|
64
|
+
const header = b64uEncode(Buffer.from(JSON.stringify({ typ: "JWT", alg: "ES256" })));
|
|
65
|
+
const claims = b64uEncode(Buffer.from(JSON.stringify({ aud, exp: Math.floor(now / 1000) + 12 * 3600, sub })));
|
|
66
|
+
const sig = es256Sign(Buffer.from(`${header}.${claims}`), keys.privateJwk);
|
|
67
|
+
return `vapid t=${header}.${claims}.${b64uEncode(sig)}, k=${keys.publicBase64Url}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** For tests: verify a vapid header against its own k (returns the claims or null). */
|
|
71
|
+
export function vapidVerify(header: string): Record<string, unknown> | null {
|
|
72
|
+
const m = header.match(/^vapid t=([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+), k=([A-Za-z0-9_-]+)$/);
|
|
73
|
+
if (!m) return null;
|
|
74
|
+
const [h, c, sig] = m[1].split(".");
|
|
75
|
+
const key = createPublicKey({
|
|
76
|
+
key: { kty: "EC", crv: "P-256", x: b64uDecode(m[2]).subarray(1, 33).toString("base64url"), y: b64uDecode(m[2]).subarray(33, 65).toString("base64url") },
|
|
77
|
+
format: "jwk",
|
|
78
|
+
});
|
|
79
|
+
const ok = (() => {
|
|
80
|
+
try {
|
|
81
|
+
// Node's verify needs DER; rebuild it from the raw r‖s.
|
|
82
|
+
const raw = b64uDecode(sig);
|
|
83
|
+
// Rebuild DER: a positive INTEGER whose high bit is set needs the 00 prefix
|
|
84
|
+
// back — without it OpenSSL reads the value as negative and verification fails.
|
|
85
|
+
const integer = (b: Buffer): Buffer => {
|
|
86
|
+
// Minimal DER: strip every leading 0x00, then re-add one iff the (now) top
|
|
87
|
+
// bit is set — otherwise OpenSSL reads the value as negative.
|
|
88
|
+
let x = b;
|
|
89
|
+
while (x.length > 1 && x[0] === 0x00) x = x.subarray(1);
|
|
90
|
+
if (x[0] & 0x80) x = Buffer.concat([Buffer.from([0x00]), x]);
|
|
91
|
+
return Buffer.concat([Buffer.from([0x02, x.length]), x]);
|
|
92
|
+
};
|
|
93
|
+
const body = Buffer.concat([integer(raw.subarray(0, 32)), integer(raw.subarray(32, 64))]);
|
|
94
|
+
const der = Buffer.concat([Buffer.from([0x30, body.length]), body]);
|
|
95
|
+
return verify("sha256", Buffer.from(`${h}.${c}`), key, der);
|
|
96
|
+
} catch {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
})();
|
|
100
|
+
if (!ok) return null;
|
|
101
|
+
return JSON.parse(Buffer.from(c, "base64url").toString("utf8")) as Record<string, unknown>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Hash an endpoint for logging without leaking it. */
|
|
105
|
+
export const endpointTag = (endpoint: string): string => createHash("sha256").update(endpoint).digest("hex").slice(0, 8);
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* edge-sim: a local stand-in for the Cloudflare edge, so "public" behavior is testable
|
|
3
|
+
* without a tunnel.
|
|
4
|
+
*
|
|
5
|
+
* cloudflared talks to the origin over plain HTTP to loopback, terminating TLS at the
|
|
6
|
+
* edge and presenting the tunnel hostname in `Host`. This simulator does exactly that on
|
|
7
|
+
* one box:
|
|
8
|
+
*
|
|
9
|
+
* client ──TLS──▶ edge-sim (terminates, rewrites Host to the pinned name) ──HTTP──▶ gateway
|
|
10
|
+
*
|
|
11
|
+
* It exercises the gateway's real public contract: `expectedHost` pinning (wrong host →
|
|
12
|
+
* 421), the PWA over TLS, and both WebSocket legs through an Upgrade pass-through.
|
|
13
|
+
* For a real deployment see DEPLOY.md — the config this file proves is the config
|
|
14
|
+
* cloudflared runs.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createServer as createHttpsServer } from "node:https";
|
|
18
|
+
import { request as httpRequest } from "node:http";
|
|
19
|
+
import { createServer as createHttp, type IncomingMessage, type ServerResponse } from "node:http";
|
|
20
|
+
import { connect as tcpConnect } from "node:net";
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
|
|
23
|
+
export interface EdgeSimOptions {
|
|
24
|
+
/** The hostname the edge presents to the origin (`Host` is rewritten to this). */
|
|
25
|
+
pinnedHost: string;
|
|
26
|
+
/** The gateway's plain-HTTP endpoint. */
|
|
27
|
+
targetPort: number;
|
|
28
|
+
targetHost?: string;
|
|
29
|
+
certPath: string;
|
|
30
|
+
keyPath: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface EdgeSim {
|
|
34
|
+
port: number;
|
|
35
|
+
close(): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function startEdgeSim(o: EdgeSimOptions): Promise<EdgeSim> {
|
|
39
|
+
const targetHost = o.targetHost ?? "127.0.0.1";
|
|
40
|
+
|
|
41
|
+
/** Proxy one normal request: same method/path/body, `Host` pinned. */
|
|
42
|
+
const proxy = (req: IncomingMessage, res: ServerResponse): void => {
|
|
43
|
+
const upstream = httpRequest(
|
|
44
|
+
{ host: targetHost, port: o.targetPort, path: req.url, method: req.method, headers: { ...req.headers, host: o.pinnedHost } },
|
|
45
|
+
(up) => {
|
|
46
|
+
res.writeHead(up.statusCode ?? 502, up.headers);
|
|
47
|
+
up.pipe(res);
|
|
48
|
+
},
|
|
49
|
+
);
|
|
50
|
+
upstream.on("error", (e: NodeJS.ErrnoException) => {
|
|
51
|
+
res.destroy();
|
|
52
|
+
req.destroy();
|
|
53
|
+
// Loud on purpose: the edge must never silently swallow an origin failure.
|
|
54
|
+
throw Object.assign(new Error(`edge-sim upstream: ${e.message}`), { code: e.code });
|
|
55
|
+
});
|
|
56
|
+
req.pipe(upstream);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Proxy one Upgrade (WebSocket): splice the raw sockets, `Host` pinned. */
|
|
60
|
+
const proxyUpgrade = (req: IncomingMessage, clientSocket: import("node:stream").Duplex, head: Buffer): void => {
|
|
61
|
+
const upstream = tcpConnect(o.targetPort, targetHost, () => {
|
|
62
|
+
const lines = [`Host: ${o.pinnedHost}`];
|
|
63
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
|
64
|
+
const name = req.rawHeaders[i];
|
|
65
|
+
if (name.toLowerCase() === "host") continue;
|
|
66
|
+
lines.push(`${name}: ${req.rawHeaders[i + 1]}`);
|
|
67
|
+
}
|
|
68
|
+
upstream.write(`${req.method} ${req.url} HTTP/1.1\r\n${lines.join("\r\n")}\r\n\r\n`);
|
|
69
|
+
if (head.length > 0) upstream.write(head);
|
|
70
|
+
clientSocket.pipe(upstream);
|
|
71
|
+
upstream.pipe(clientSocket);
|
|
72
|
+
});
|
|
73
|
+
const fail = (): void => {
|
|
74
|
+
clientSocket.destroy();
|
|
75
|
+
upstream.destroy();
|
|
76
|
+
};
|
|
77
|
+
upstream.on("error", fail);
|
|
78
|
+
clientSocket.on("error", fail);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const server = createHttpsServer({ cert: readFileSync(o.certPath), key: readFileSync(o.keyPath) }, proxy);
|
|
82
|
+
server.on("upgrade", proxyUpgrade);
|
|
83
|
+
|
|
84
|
+
await new Promise<void>((resolve, reject) => {
|
|
85
|
+
server.once("error", reject);
|
|
86
|
+
server.listen(0, "127.0.0.1", () => resolve());
|
|
87
|
+
});
|
|
88
|
+
const addr = server.address();
|
|
89
|
+
const port = typeof addr === "object" && addr ? addr.port : 0;
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
port,
|
|
93
|
+
close: () =>
|
|
94
|
+
new Promise<void>((done) => {
|
|
95
|
+
server.closeAllConnections?.();
|
|
96
|
+
server.close(() => done());
|
|
97
|
+
}),
|
|
98
|
+
};
|
|
99
|
+
}
|
package/src/dev/main.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* edge-sim CLI: run the Cloudflare-edge simulator for a local gateway.
|
|
3
|
+
*
|
|
4
|
+
* HERDGATE_TARGET_PORT the gateway's plain-HTTP port (required)
|
|
5
|
+
* HERDGATE_PINNED_HOST the Host the edge presents (default: gate.local)
|
|
6
|
+
* HERDGATE_EDGE_CERT TLS cert (required)
|
|
7
|
+
* HERDGATE_EDGE_KEY TLS key (required)
|
|
8
|
+
*
|
|
9
|
+
* The pair of throwaway dev certs is generated with openssl (see DEPLOY.md's
|
|
10
|
+
* "Rehearse before going live"). Real deployments use cloudflared + a real cert; this
|
|
11
|
+
* exists so the public contract (host pinning, TLS PWA, wss legs) is exercised on this
|
|
12
|
+
* machine first.
|
|
13
|
+
*/
|
|
14
|
+
import { startEdgeSim } from "./edge-sim.ts";
|
|
15
|
+
|
|
16
|
+
const env = process.env;
|
|
17
|
+
const targetPort = Number(env.HERDGATE_TARGET_PORT ?? 0);
|
|
18
|
+
if (!targetPort || !env.HERDGATE_EDGE_CERT || !env.HERDGATE_EDGE_KEY) {
|
|
19
|
+
console.error("edge-sim: HERDGATE_TARGET_PORT, HERDGATE_EDGE_CERT, HERDGATE_EDGE_KEY are required");
|
|
20
|
+
process.exit(2);
|
|
21
|
+
}
|
|
22
|
+
const edge = await startEdgeSim({
|
|
23
|
+
pinnedHost: env.HERDGATE_PINNED_HOST ?? "gate.local",
|
|
24
|
+
targetPort,
|
|
25
|
+
certPath: env.HERDGATE_EDGE_CERT,
|
|
26
|
+
keyPath: env.HERDGATE_EDGE_KEY,
|
|
27
|
+
});
|
|
28
|
+
console.log(`edge-sim: https://127.0.0.1:${edge.port} → 127.0.0.1:${targetPort} (Host: ${env.HERDGATE_PINNED_HOST ?? "gate.local"})`);
|
|
29
|
+
const bye = (): void => {
|
|
30
|
+
void edge.close().then(() => process.exit(0));
|
|
31
|
+
};
|
|
32
|
+
process.on("SIGINT", bye);
|
|
33
|
+
process.on("SIGTERM", bye);
|