@bom0792/herdgate 0.9.31 → 0.9.35
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/DEPLOY.md +85 -126
- package/DESIGN.md +9 -4
- package/README.md +23 -2
- package/bin/cloud-config.mjs +9 -2
- package/bin/herdgate.mjs +216 -8
- package/dist-readme.md +3 -1
- package/package.json +35 -9
- package/plugin/server/e2e.d.mts +2 -2
- package/plugin/server/e2e.mjs +51 -32
- package/plugin/server/index.mjs +128 -32
- package/plugin/server/pi-receipts.d.mts +28 -0
- package/plugin/server/pi-receipts.mjs +77 -0
- package/plugin/server/pi-worker.d.mts +47 -0
- package/plugin/server/pi-worker.mjs +127 -0
- package/scripts/build-host-bundle.sh +14 -8
- package/scripts/build-release.sh +47 -0
- package/scripts/deploy-vps.sh +5 -78
- package/src/cloud/gateway.ts +163 -134
- package/src/cloud/main.ts +72 -15
- package/src/cloud/pairing.ts +7 -2
- package/src/cloud/push.ts +54 -0
- package/src/cloud/sshd.ts +76 -38
- package/src/cloud/util.ts +5 -5
- package/src/web/app.js +88 -61
- package/src/web/e2e.js +51 -32
- package/src/web/sw.js +1 -1
- package/templates/cloud/.dockerignore +7 -0
- package/templates/cloud/Caddyfile.example +3 -0
- package/templates/cloud/Dockerfile +10 -0
- package/templates/cloud/README.md +74 -0
- package/templates/cloud/compose.env.example +18 -0
- package/templates/cloud/compose.yml +41 -0
- package/templates/cloud/gitignore.example +4 -0
- package/templates/cloud/herdgate-cloud-edge.service +18 -0
- package/templates/cloud/herdgate-cloud.service +26 -0
- package/tsconfig.cloud.json +11 -0
- package/tsconfig.json +18 -0
- package/src/web/herdgate-host.zip +0 -0
package/src/web/app.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// - the token lives in localStorage on this device and is never sent anywhere but the
|
|
12
12
|
// cloud's own WS endpoint.
|
|
13
13
|
|
|
14
|
-
const BUILD = "v0.9.
|
|
14
|
+
const BUILD = "v0.9.33-web.1";
|
|
15
15
|
|
|
16
16
|
const $ = (id) => document.getElementById(id);
|
|
17
17
|
const TOKEN_KEY = "herdgate.token";
|
|
@@ -37,7 +37,7 @@ function clearLegacyPair() {
|
|
|
37
37
|
localStorage.removeItem(DEVICE_SECRET_KEY);
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
import { DeviceChannel, generateKeyPair
|
|
40
|
+
import { DeviceChannel, generateKeyPair } from "/e2e.js";
|
|
41
41
|
|
|
42
42
|
// E2E payloads: this device's Noise_XX identity (kept locally, never sent to the cloud
|
|
43
43
|
// in the clear) and the host fingerprints it has pinned (TOFU per room).
|
|
@@ -70,21 +70,26 @@ function e2eB64d(s) {
|
|
|
70
70
|
// Per-room channel state; reset when the socket drops. The channel only carries
|
|
71
71
|
// traffic after the host's `e2e.ready` ack — nothing may race the handshake's
|
|
72
72
|
// last step, or the transport counters desync for good.
|
|
73
|
-
const e2e = { ch: null, initing: false, ready: false, epoch: 0 };
|
|
73
|
+
const e2e = { ch: null, initing: false, ready: false, verified: false, epoch: 0, keyChanged: false, beganAt: 0 };
|
|
74
|
+
const pinnedHost = () => state.deviceRoom && localStorage.getItem(e2eFpKey(state.deviceRoom));
|
|
74
75
|
function e2eReset() {
|
|
75
76
|
e2e.epoch++;
|
|
76
77
|
e2e.ch = null;
|
|
77
78
|
e2e.initing = false;
|
|
78
79
|
e2e.ready = false;
|
|
80
|
+
e2e.verified = false;
|
|
81
|
+
e2e.keyChanged = false;
|
|
82
|
+
e2e.beganAt = 0;
|
|
79
83
|
}
|
|
80
84
|
|
|
81
85
|
/** Begin (or restart) the Noise_XX handshake with this room's host. */
|
|
82
86
|
async function e2eBegin() {
|
|
83
|
-
if (e2e.
|
|
87
|
+
if (e2e.ready || e2e.initing || e2e.keyChanged || Date.now() - e2e.beganAt < 5000) return;
|
|
84
88
|
if (!(state.deviceSecret && state.deviceId && state.roomId)) return;
|
|
85
89
|
if (state.ws?.readyState !== WebSocket.OPEN) return;
|
|
86
90
|
const epoch = e2e.epoch;
|
|
87
91
|
e2e.initing = true;
|
|
92
|
+
e2e.beganAt = Date.now();
|
|
88
93
|
try {
|
|
89
94
|
const self = await e2eSelfKey();
|
|
90
95
|
const ch = new DeviceChannel(self);
|
|
@@ -92,6 +97,8 @@ async function e2eBegin() {
|
|
|
92
97
|
if (epoch !== e2e.epoch) return;
|
|
93
98
|
e2e.ch = ch;
|
|
94
99
|
send({ t: "frame", payload: { op: "e2e.init", e: init.e } });
|
|
100
|
+
} catch {
|
|
101
|
+
// A pinned room stays closed to plaintext even if WebCrypto is unavailable.
|
|
95
102
|
} finally {
|
|
96
103
|
if (epoch === e2e.epoch) e2e.initing = false;
|
|
97
104
|
}
|
|
@@ -222,16 +229,15 @@ function renderRoom() {
|
|
|
222
229
|
// E2E status: the pinned host fingerprint, or a loud note when it changed.
|
|
223
230
|
const e2eNote = $("e2e-note");
|
|
224
231
|
const pinned = state.roomId ? localStorage.getItem(e2eFpKey(state.roomId)) : null;
|
|
225
|
-
const current = e2e.
|
|
226
|
-
|
|
227
|
-
if (pinned && current && current !== pinned) {
|
|
232
|
+
const current = e2e.verified ? e2e.ch.hostFingerprint : null;
|
|
233
|
+
if (e2e.keyChanged) {
|
|
228
234
|
e2eNote.hidden = false;
|
|
229
235
|
e2eNote.className = "error small";
|
|
230
|
-
e2eNote.textContent =
|
|
231
|
-
} else if (
|
|
236
|
+
e2eNote.textContent = "Host key changed. Pane data is blocked. Verify the key with the host administrator.";
|
|
237
|
+
} else if (current || pinned) {
|
|
232
238
|
e2eNote.hidden = false;
|
|
233
239
|
e2eNote.className = "muted small";
|
|
234
|
-
e2eNote.textContent = `end-to-end encrypted · host key ${
|
|
240
|
+
e2eNote.textContent = current ? `end-to-end encrypted · host key ${current}` : "Waiting for an encrypted connection to the pinned host…";
|
|
235
241
|
} else {
|
|
236
242
|
e2eNote.hidden = true;
|
|
237
243
|
}
|
|
@@ -326,7 +332,7 @@ function renderLiveTerminals(box, online) {
|
|
|
326
332
|
tbody.className = "termbody";
|
|
327
333
|
tblock.append(tbody);
|
|
328
334
|
tblock.addEventListener("toggle", () => {
|
|
329
|
-
if (tblock.open && !state.terms)
|
|
335
|
+
if (tblock.open && !state.terms) sendPayload({ op: "term.list" });
|
|
330
336
|
});
|
|
331
337
|
box.append(tblock);
|
|
332
338
|
state.termBody = tbody;
|
|
@@ -617,10 +623,10 @@ function startTerm(target) {
|
|
|
617
623
|
stopTerm(false);
|
|
618
624
|
state.termTarget = target;
|
|
619
625
|
state.termAnsi = null;
|
|
620
|
-
|
|
626
|
+
sendPayload({ op: "term.read", target, lines: 40 });
|
|
621
627
|
state.termTimer = setInterval(() => {
|
|
622
628
|
if (!state.termTarget || !state.roomId) return stopTerm();
|
|
623
|
-
|
|
629
|
+
sendPayload({ op: "term.read", target: state.termTarget, lines: 40 });
|
|
624
630
|
}, 2_000);
|
|
625
631
|
renderTerms();
|
|
626
632
|
}
|
|
@@ -665,7 +671,7 @@ function renderTerms() {
|
|
|
665
671
|
btn.type = "button";
|
|
666
672
|
btn.className = "link";
|
|
667
673
|
btn.textContent = "refresh the pane list";
|
|
668
|
-
btn.addEventListener("click", () =>
|
|
674
|
+
btn.addEventListener("click", () => sendPayload({ op: "term.list" }));
|
|
669
675
|
list.append(btn);
|
|
670
676
|
const panes = state.terms ?? null;
|
|
671
677
|
if (panes === null) {
|
|
@@ -855,6 +861,7 @@ function connect() {
|
|
|
855
861
|
if (state.ws !== ws) return;
|
|
856
862
|
state.ws = null;
|
|
857
863
|
e2eReset();
|
|
864
|
+
if (state.roomId && pinnedHost()) clearRoomPayload();
|
|
858
865
|
if (event.code === 4001 && ["unknown device credentials", "revoked"].includes(event.reason)) {
|
|
859
866
|
dropDevice();
|
|
860
867
|
return;
|
|
@@ -921,40 +928,37 @@ async function onMessage(m, ws) {
|
|
|
921
928
|
await onE2eReply(payload);
|
|
922
929
|
return;
|
|
923
930
|
}
|
|
924
|
-
if (payload
|
|
931
|
+
if (payload?.op === "e2e.ready") {
|
|
932
|
+
if (!e2e.ch?.ready() || e2e.ready || e2e.initing || e2e.keyChanged) return;
|
|
925
933
|
e2e.ready = true;
|
|
926
934
|
renderRoom();
|
|
927
|
-
askView();
|
|
935
|
+
void askView();
|
|
928
936
|
return;
|
|
929
937
|
}
|
|
930
|
-
if (payload
|
|
931
|
-
|
|
932
|
-
|
|
938
|
+
if (payload?.op === "e2e") {
|
|
939
|
+
const ch = e2e.ch;
|
|
940
|
+
if (!e2e.ready || !ch?.ready()) return;
|
|
933
941
|
try {
|
|
934
|
-
inner = await
|
|
935
|
-
|
|
936
|
-
if (
|
|
937
|
-
//
|
|
938
|
-
|
|
939
|
-
|
|
942
|
+
const inner = await ch.recv(payload);
|
|
943
|
+
if (state.ws !== ws || e2e.ch !== ch) return;
|
|
944
|
+
if (!e2e.verified) {
|
|
945
|
+
// The plaintext ready ack only starts transport. A valid encrypted
|
|
946
|
+
// response proves the peer has the static key before we store the pin.
|
|
947
|
+
localStorage.setItem(e2eFpKey(state.deviceRoom), ch.hostFingerprint);
|
|
948
|
+
e2e.verified = true;
|
|
949
|
+
renderRoom();
|
|
940
950
|
}
|
|
941
|
-
|
|
951
|
+
applyPayload(inner);
|
|
952
|
+
} catch {
|
|
953
|
+
if (state.ws === ws && e2e.ch === ch) restartEncryptedRoom();
|
|
942
954
|
}
|
|
943
|
-
if (state.ws === ws) applyPayload(inner);
|
|
944
955
|
return;
|
|
945
956
|
}
|
|
946
|
-
if (
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
}
|
|
952
|
-
if (payload && typeof payload === "object" && payload.op === "view" && e2e.ch?.ready() && e2e.ready) {
|
|
953
|
-
// Plaintext view while an encrypted session is up: the host lost its side —
|
|
954
|
-
// renegotiate (its publisher restarted).
|
|
955
|
-
e2eReset();
|
|
956
|
-
void e2eBegin();
|
|
957
|
-
applyPayload(payload);
|
|
957
|
+
if (e2e.keyChanged) return;
|
|
958
|
+
if (pinnedHost() || e2e.ch?.ready()) {
|
|
959
|
+
// Plaintext after a publisher restart may trigger renegotiation, but is never displayed.
|
|
960
|
+
if (e2e.ready && (payload?.code === "e2e" || payload?.op === "view")) restartEncryptedRoom();
|
|
961
|
+
else if (!e2e.ready) void e2eBegin();
|
|
958
962
|
return;
|
|
959
963
|
}
|
|
960
964
|
applyPayload(payload);
|
|
@@ -989,17 +993,40 @@ function retryLater() {
|
|
|
989
993
|
}
|
|
990
994
|
|
|
991
995
|
/** Ask the host for its view: the only op this app ever sends (encrypted when up). */
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
996
|
+
function clearRoomPayload() {
|
|
997
|
+
state.view = null;
|
|
998
|
+
state.viewError = null;
|
|
999
|
+
state.terms = null;
|
|
1000
|
+
state.termAnsi = null;
|
|
1001
|
+
renderRoom();
|
|
1002
|
+
renderTerms();
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
function restartEncryptedRoom() {
|
|
1006
|
+
e2eReset();
|
|
1007
|
+
clearRoomPayload();
|
|
1008
|
+
void e2eBegin();
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
async function sendPayload(message) {
|
|
1012
|
+
const ws = state.ws;
|
|
1013
|
+
if (ws?.readyState !== WebSocket.OPEN || !state.roomId || e2e.keyChanged) return;
|
|
1014
|
+
const ch = e2e.ch;
|
|
1015
|
+
if (ch?.ready() && e2e.ready) {
|
|
1016
|
+
try {
|
|
1017
|
+
const payload = await ch.send(message);
|
|
1018
|
+
if (state.ws === ws && e2e.ch === ch) send({ t: "frame", payload });
|
|
1019
|
+
} catch {
|
|
1020
|
+
if (state.ws === ws && e2e.ch === ch) restartEncryptedRoom();
|
|
1021
|
+
}
|
|
999
1022
|
return;
|
|
1000
1023
|
}
|
|
1001
|
-
void e2eBegin();
|
|
1002
|
-
send({ t: "frame", payload:
|
|
1024
|
+
void e2eBegin();
|
|
1025
|
+
if (!pinnedHost() && !ch?.ready()) send({ t: "frame", payload: message });
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function askView() {
|
|
1029
|
+
return sendPayload({ op: "view" });
|
|
1003
1030
|
}
|
|
1004
1031
|
function applyPayload(payload) {
|
|
1005
1032
|
// The plaintext (or decrypted) payload from the host lands here.
|
|
@@ -1062,23 +1089,23 @@ async function subscribePush() {
|
|
|
1062
1089
|
async function onE2eReply(payload) {
|
|
1063
1090
|
const ch = e2e.ch;
|
|
1064
1091
|
const roomId = state.deviceRoom;
|
|
1065
|
-
if (!ch || !roomId) return;
|
|
1092
|
+
if (!ch || !roomId || ch.ready() || e2e.initing || e2e.keyChanged) return;
|
|
1093
|
+
e2e.initing = true;
|
|
1066
1094
|
try {
|
|
1067
|
-
const finish = await ch.acceptReply(payload);
|
|
1095
|
+
const finish = await ch.acceptReply(payload, pinnedHost());
|
|
1068
1096
|
if (e2e.ch !== ch) return;
|
|
1097
|
+
clearRoomPayload();
|
|
1069
1098
|
send({ t: "frame", payload: { op: "e2e.finish", c: finish.c } });
|
|
1070
|
-
} catch {
|
|
1071
|
-
if (e2e.ch
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
if (
|
|
1099
|
+
} catch (err) {
|
|
1100
|
+
if (e2e.ch !== ch) return;
|
|
1101
|
+
e2eReset();
|
|
1102
|
+
if (err?.code === "host-key-changed") {
|
|
1103
|
+
e2e.keyChanged = true;
|
|
1104
|
+
clearRoomPayload();
|
|
1105
|
+
}
|
|
1106
|
+
} finally {
|
|
1107
|
+
if (e2e.ch === ch) e2e.initing = false;
|
|
1079
1108
|
}
|
|
1080
|
-
// The channel is up: ask for the view over it.
|
|
1081
|
-
askView();
|
|
1082
1109
|
}
|
|
1083
1110
|
|
|
1084
1111
|
function send(message) {
|
package/src/web/e2e.js
CHANGED
|
@@ -47,11 +47,15 @@ export function concat(...parts) {
|
|
|
47
47
|
return out;
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
/**
|
|
51
|
-
|
|
50
|
+
/** Legacy pin matching is used only to upgrade existing browser pins. */
|
|
51
|
+
function legacyFingerprint(pub) {
|
|
52
52
|
return b64e(pub.slice(0, 8)).replace(/[^A-Za-z0-9]/g, "").toLowerCase().slice(0, 12);
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
export async function fingerprint(pub) {
|
|
56
|
+
return "SHA256:" + b64e(await sha256(pub)).replace(/=+$/, "");
|
|
57
|
+
}
|
|
58
|
+
|
|
55
59
|
// ---- WebCrypto plumbing ----------------------------------------------------
|
|
56
60
|
|
|
57
61
|
const subtle = globalThis.crypto.subtle;
|
|
@@ -90,31 +94,38 @@ export async function generateKeyPair() {
|
|
|
90
94
|
class CipherState {
|
|
91
95
|
k = null;
|
|
92
96
|
n = 0;
|
|
97
|
+
#tail = Promise.resolve();
|
|
93
98
|
setKey(k) {
|
|
94
99
|
this.k = k;
|
|
95
100
|
}
|
|
96
|
-
nonce() {
|
|
97
|
-
// 96-bit: 4 zero bytes ‖ BE64(n)
|
|
101
|
+
nonce(n) {
|
|
102
|
+
// 96-bit: 4 zero bytes ‖ BE64(n); sessions are bounded below 2^32.
|
|
98
103
|
const iv = new Uint8Array(12);
|
|
99
|
-
new DataView(iv.buffer).setUint32(8,
|
|
104
|
+
new DataView(iv.buffer).setUint32(8, n);
|
|
100
105
|
return iv;
|
|
101
106
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
await subtle.encrypt({ name: "AES-GCM", iv: this.nonce(), additionalData: ad, tagLength: 128 }, key, plaintext),
|
|
107
|
-
);
|
|
108
|
-
this.n += 1;
|
|
109
|
-
return ct;
|
|
107
|
+
#enqueue(operation) {
|
|
108
|
+
const result = this.#tail.then(operation);
|
|
109
|
+
this.#tail = result.catch(() => {});
|
|
110
|
+
return result;
|
|
110
111
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
112
|
+
encrypt(ad, plaintext) {
|
|
113
|
+
return this.#enqueue(async () => {
|
|
114
|
+
if (this.n >= 0xffffffff) throw new Error("e2e: nonce exhausted");
|
|
115
|
+
const n = this.n++;
|
|
116
|
+
const key = await subtle.importKey("raw", this.k, "AES-GCM", false, ["encrypt"]);
|
|
117
|
+
const ct = new Uint8Array(await subtle.encrypt({ name: "AES-GCM", iv: this.nonce(n), additionalData: ad, tagLength: 128 }, key, plaintext));
|
|
118
|
+
return { ct, n };
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
decrypt(ad, ciphertext, n) {
|
|
122
|
+
return this.#enqueue(async () => {
|
|
123
|
+
if (this.n >= 0xffffffff || (n !== undefined && n !== this.n)) throw new Error("e2e: invalid nonce counter");
|
|
124
|
+
const key = await subtle.importKey("raw", this.k, "AES-GCM", false, ["decrypt"]);
|
|
125
|
+
const pt = new Uint8Array(await subtle.decrypt({ name: "AES-GCM", iv: this.nonce(this.n), additionalData: ad, tagLength: 128 }, key, ciphertext));
|
|
126
|
+
this.n += 1;
|
|
127
|
+
return pt;
|
|
128
|
+
});
|
|
118
129
|
}
|
|
119
130
|
}
|
|
120
131
|
|
|
@@ -151,7 +162,7 @@ class Handshake {
|
|
|
151
162
|
}
|
|
152
163
|
/** The `s` token: transport under the current key, else in the clear (ENC0). */
|
|
153
164
|
async writeTokenStatic(pubRaw) {
|
|
154
|
-
const out = this.cs.k ? await this.cs.encrypt(this.h, pubRaw) : pubRaw;
|
|
165
|
+
const out = this.cs.k ? (await this.cs.encrypt(this.h, pubRaw)).ct : pubRaw;
|
|
155
166
|
await this.mixHash(out);
|
|
156
167
|
return out;
|
|
157
168
|
}
|
|
@@ -189,14 +200,18 @@ export class DeviceChannel {
|
|
|
189
200
|
return { e: b64e(this.#e.pub) };
|
|
190
201
|
}
|
|
191
202
|
/** Feed the host's `{op:"e2e.reply", e, c}`; returns the msg3 payload. */
|
|
192
|
-
async acceptReply(msg) {
|
|
203
|
+
async acceptReply(msg, expectedHost = null) {
|
|
193
204
|
const eHost = b64d(msg.e);
|
|
194
205
|
if (eHost.length !== PUB_LEN) throw new Error("e2e: bad host ephemeral");
|
|
195
206
|
await this.#hs.mixHash(eHost);
|
|
196
207
|
await this.#hs.mixKey(await dh(this.#e.jwk, eHost)); // ee
|
|
197
208
|
const sHost = await this.#hs.readTokenStatic(b64d(msg.c)); // s
|
|
198
209
|
if (sHost.length !== PUB_LEN) throw new Error("e2e: bad host static");
|
|
199
|
-
|
|
210
|
+
const fp = await fingerprint(sHost);
|
|
211
|
+
if (expectedHost && expectedHost !== fp && (expectedHost.startsWith("SHA256:") || expectedHost !== legacyFingerprint(sHost))) {
|
|
212
|
+
throw Object.assign(new Error("e2e: host key changed"), { code: "host-key-changed" });
|
|
213
|
+
}
|
|
214
|
+
this.hostFingerprint = fp;
|
|
200
215
|
await this.#hs.mixKey(await dh(this.#e.jwk, sHost)); // es (e_dev × s_host)
|
|
201
216
|
const c = await this.#hs.writeTokenStatic(this.#self.pub); // s_dev
|
|
202
217
|
await this.#hs.mixKey(await dh(this.#self.jwk, eHost)); // se (e_host × s_dev)
|
|
@@ -210,12 +225,11 @@ export class DeviceChannel {
|
|
|
210
225
|
return Boolean(this.sendCs && this.recvCs);
|
|
211
226
|
}
|
|
212
227
|
async send(obj) {
|
|
213
|
-
const ct = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
|
|
214
|
-
return { op: "e2e", n
|
|
228
|
+
const { ct, n } = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
|
|
229
|
+
return { op: "e2e", n, c: b64e(ct) };
|
|
215
230
|
}
|
|
216
231
|
async recv(msg) {
|
|
217
|
-
|
|
218
|
-
return JSON.parse(utf8d(pt));
|
|
232
|
+
return receive(this.recvCs, this.#hs.h, msg);
|
|
219
233
|
}
|
|
220
234
|
}
|
|
221
235
|
|
|
@@ -247,7 +261,7 @@ export class HostChannel {
|
|
|
247
261
|
async acceptFinish(msg) {
|
|
248
262
|
const sDev = await this.#hs.readTokenStatic(b64d(msg.c)); // s_dev
|
|
249
263
|
if (sDev.length !== PUB_LEN) throw new Error("e2e: bad device static");
|
|
250
|
-
this.deviceFingerprint = fingerprint(sDev);
|
|
264
|
+
this.deviceFingerprint = await fingerprint(sDev);
|
|
251
265
|
await this.#hs.mixKey(await dh(this.#e.jwk, sDev)); // se (e_host × s_dev)
|
|
252
266
|
const [c1, c2] = await this.#hs.split();
|
|
253
267
|
this.recvCs = c1; // device → host (c1 encrypts initiator→responder)
|
|
@@ -258,11 +272,16 @@ export class HostChannel {
|
|
|
258
272
|
return Boolean(this.sendCs && this.recvCs);
|
|
259
273
|
}
|
|
260
274
|
async send(obj) {
|
|
261
|
-
const ct = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
|
|
262
|
-
return { op: "e2e", n
|
|
275
|
+
const { ct, n } = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
|
|
276
|
+
return { op: "e2e", n, c: b64e(ct) };
|
|
263
277
|
}
|
|
264
278
|
async recv(msg) {
|
|
265
|
-
|
|
266
|
-
return JSON.parse(utf8d(pt));
|
|
279
|
+
return receive(this.recvCs, this.#hs.h, msg);
|
|
267
280
|
}
|
|
268
281
|
}
|
|
282
|
+
|
|
283
|
+
async function receive(cipher, handshakeHash, msg) {
|
|
284
|
+
if (!Number.isInteger(msg.n) || msg.n < 0 || msg.n >= 0xffffffff) throw new Error("e2e: invalid nonce counter");
|
|
285
|
+
const plaintext = await cipher.decrypt(handshakeHash, b64d(msg.c), msg.n);
|
|
286
|
+
return JSON.parse(utf8d(plaintext));
|
|
287
|
+
}
|
package/src/web/sw.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
//
|
|
4
4
|
// Bump VERSION when a shell file changes; old caches are dropped on activate.
|
|
5
5
|
|
|
6
|
-
const VERSION = "herdgate-
|
|
6
|
+
const VERSION = "herdgate-v17";
|
|
7
7
|
const SHELL = ["/", "/app.css", "/e2e.js", "/app.js", "/app.webmanifest", "/icons/icon.svg"];
|
|
8
8
|
|
|
9
9
|
self.addEventListener("install", (event) => {
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
FROM node:22-alpine@sha256:0e1754758c2df4cfa3e68d59e2e1b7374bb7fd9ea6328eaaacf15cc934af8202
|
|
2
|
+
WORKDIR /opt/herdgate
|
|
3
|
+
COPY package.json package-lock.json ./
|
|
4
|
+
COPY scripts/patch-ssh2.mjs ./scripts/
|
|
5
|
+
RUN npm ci --omit=dev --omit=optional --ignore-scripts && node scripts/patch-ssh2.mjs && npm cache clean --force
|
|
6
|
+
COPY runtime/ ./runtime/
|
|
7
|
+
ENV NODE_ENV=production HERDGATE_BIND=0.0.0.0 HERDGATE_PORT=8787 HERDGATE_STATE=/data/state.json
|
|
8
|
+
USER node
|
|
9
|
+
EXPOSE 8787
|
|
10
|
+
CMD ["node", "runtime/cloud/main.js"]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Herdgate Cloud — self-hosted Gate + PWA
|
|
2
|
+
|
|
3
|
+
This archive runs the Gate, PWA and SSH-over-WSS relay. It includes the matching host installer at `/herdgate-host.zip` and a separate tokenless TCP edge entrypoint for native Herdr Mobile clients. It contains no owner token, room/device state, host keys, TLS credentials or site-specific settings. The Gate is single-instance; do not point two processes at the same state directory.
|
|
4
|
+
|
|
5
|
+
## Docker Compose (Linux, new install)
|
|
6
|
+
|
|
7
|
+
From the extracted archive, as your normal non-root user:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
cp -n compose.env.example .env
|
|
11
|
+
# Edit .env: set HERDGATE_PUBLIC_HOST to your DNS name and UID/GID to id -u / id -g.
|
|
12
|
+
install -d -m 700 data
|
|
13
|
+
(umask 077; set -C; openssl rand -base64 32 > owner-token)
|
|
14
|
+
docker compose up -d --build --wait
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The token-generation command fails rather than overwriting an existing file. Do not put `owner-token` or `data/` under the web root or in a release. Compose mounts the token read-only and runs as the configured UID/GID so it can read the private file and write to `data/`. If using Docker user namespaces, arrange equivalent permissions for the mapped UID/GID. Keep this token in a password manager; it is the owner login for the PWA.
|
|
18
|
+
|
|
19
|
+
Point your HTTPS reverse proxy or named cloudflared tunnel at `http://127.0.0.1:8787` (or your `HERDGATE_HTTP_PORT`). Preserve the public `Host` header and WebSocket upgrades. Gate's HTTP port is bound to host loopback and its raw SSH port is not published. The included `Caddyfile.example` is a site block to adapt, not a replacement for existing proxy configuration. No DNS, firewall, or TLS changes are performed by the bundle.
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
curl -fsS -H 'Host: gate.example.com' http://127.0.0.1:8787/healthz
|
|
23
|
+
curl -fsS https://gate.example.com/healthz
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Linux/systemd (alternative to Docker)
|
|
27
|
+
|
|
28
|
+
Requires Node 22+ and npm. JavaScript is already compiled; the target does not need TypeScript or native Node type stripping.
|
|
29
|
+
|
|
30
|
+
1. Extract the archive into `/opt/herdgate-cloud` (root-owned, readable by the service) and install the locked runtime dependencies there: `npm ci --omit=dev --omit=optional --ignore-scripts && node scripts/patch-ssh2.mjs`.
|
|
31
|
+
2. Create `/etc/herdgate` with root-only permissions. Generate a new `/etc/herdgate/owner-token` (0600, root-owned) with `openssl rand -base64 32`, using `umask 077` and `set -C` as above. Do not pass it as a command-line argument. systemd uses `LoadCredential` to hand the service a readable copy.
|
|
32
|
+
3. Create `/etc/herdgate/cloud.env` with only non-secret settings:
|
|
33
|
+
|
|
34
|
+
```dotenv
|
|
35
|
+
HERDGATE_PUBLIC_HOST=gate.example.com
|
|
36
|
+
HERDGATE_PUBLIC_URL=https://gate.example.com
|
|
37
|
+
# For a separate native Mobile TCP edge:
|
|
38
|
+
# HERDGATE_SSH_HOST=ssh.example.com
|
|
39
|
+
# HERDGATE_SSH_PUBLIC_PORT=2299
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
4. Install the included `herdgate-cloud.service` in `/etc/systemd/system/` (adjust `/usr/bin/node` if necessary). Run `sudo systemctl daemon-reload` and `sudo systemctl enable --now herdgate-cloud`. systemd manages `/var/lib/herdgate-cloud` as the private state directory. Use the same HTTPS reverse-proxy and health checks as for Compose.
|
|
43
|
+
|
|
44
|
+
## Pair hosts and connect clients
|
|
45
|
+
|
|
46
|
+
Open `https://gate.example.com/`, sign in with the owner token and approve the host's pairing request. Obtain the matching installer from `https://gate.example.com/herdgate-host.zip`, or on the publisher use the Herdgate CLI from npm:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
herdgate cloud add mygate https://gate.example.com
|
|
50
|
+
herdgate pair --cloud mygate # approve the code in the PWA
|
|
51
|
+
herdgate setup --cloud mygate
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`cloud add` does not move an existing pairing. Do not aim an already-paired publisher at a new, empty Gate and expect its previous room to exist. For SSH, register only the controller's public key on the specific approved device ID, use that ID as the SSH username, and pin the Gate's SSH fingerprint from its startup log when first initialized.
|
|
55
|
+
|
|
56
|
+
### Optional: native Herdr Mobile on cellular
|
|
57
|
+
|
|
58
|
+
The compiled `runtime/cloud/ssh-tcp-edge.js` forwards TCP to `wss://<gate>/v1/ssh/ws`. On a VPS, install the archive and locked runtime dependencies as above, but run **only** the included `herdgate-cloud-edge.service`, not `herdgate-cloud.service`. It reads `/etc/herdgate/edge.env`:
|
|
59
|
+
|
|
60
|
+
```dotenv
|
|
61
|
+
HERDGATE_URL=https://gate.example.com
|
|
62
|
+
HERDGATE_TCP_EDGE_BIND=0.0.0.0
|
|
63
|
+
HERDGATE_TCP_EDGE_PORT=2299
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Expose only the edge port as needed and enter its reachable IP or DNS-only hostname and port in Mobile. On the Gate set `HERDGATE_SSH_HOST` and `HERDGATE_SSH_PUBLIC_PORT` if the PWA should advertise the edge address. All edge tunnels arrive at the Gate from one address: raise the Gate budget with `HERDGATE_SSH_TUNNELS_PER_IP`/`HERDGATE_SSH_TUNNELS_TOTAL` to fit your expected concurrent Mobile sessions. The edge does not terminate SSH, and needs no owner/room token, state directory, or private key; do not copy them to it. The Gate retains its SSH host key and decides authentication and scope.
|
|
67
|
+
|
|
68
|
+
## Optional: PWA push wake
|
|
69
|
+
|
|
70
|
+
Wake notifications are off by default. Only opt in with `HERDGATE_ENABLE_PUSH=1` (in Compose `.env` or systemd `cloud.env`) if needed. `HERDGATE_NO_PUSH=1` overrides that opt-in. Set `HERDGATE_PUSH_SUB` to your VAPID contact URI. Herdgate accepts only HTTPS endpoints on `fcm.googleapis.com`, `updates.push.services.mozilla.com` and `web.push.apple.com`; requests require a public IPv4 address and do not follow redirects. An unsupported subscription does not prevent normal PWA use.
|
|
71
|
+
|
|
72
|
+
## Back up, upgrade or migrate
|
|
73
|
+
|
|
74
|
+
Stop only the Gate to take a consistent **private** backup of `state.json`, `ssh_host_ed25519.json`, `vapid.json` (if present) and the owner-token file. Keep the same public origin when moving an existing Gate. Never use a staging archive as a backup, and never run a new instance alongside the old one against the same state. An upgrade replaces application files/image only; use the original state directory and token, not a fresh one. For Compose, retain `data/`, `.env` and `owner-token` and rebuild from the new archive; use the previous image/archive with that same data if rollback is needed and the state format is compatible. Verify `/healthz`, PWA sign-in, publisher reconnect and the pinned SSH host key. Publisher/CLI updates do not upgrade the Gate or TCP edge.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Public DNS hostname only; no scheme, path, port or credentials.
|
|
2
|
+
HERDGATE_PUBLIC_HOST=gate.example.com
|
|
3
|
+
# Local HTTP port for Caddy, nginx or cloudflared on the Docker host.
|
|
4
|
+
HERDGATE_HTTP_PORT=8787
|
|
5
|
+
# On Linux set these to id -u and id -g of the non-root user owning data/ and owner-token.
|
|
6
|
+
HERDGATE_UID=1000
|
|
7
|
+
HERDGATE_GID=1000
|
|
8
|
+
# Optional: hint to native SSH clients (for example the public TCP edge hostname).
|
|
9
|
+
# HERDGATE_SSH_HOST=ssh.example.com
|
|
10
|
+
# Optional: enable restricted PWA push wake, off by default.
|
|
11
|
+
# HERDGATE_ENABLE_PUSH=1
|
|
12
|
+
# HERDGATE_PUSH_SUB=mailto:admin@example.com
|
|
13
|
+
# Behind a header-forwarding proxy: per-client abuse budgets from the real IP.
|
|
14
|
+
# HERDGATE_TRUSTED_PROXY=1
|
|
15
|
+
# HERDGATE_REAL_IP_HEADER=CF-Connecting-IP
|
|
16
|
+
# A raw TCP edge shares one address; size the SSH-over-WSS budget for it.
|
|
17
|
+
# HERDGATE_SSH_TUNNELS_PER_IP=24
|
|
18
|
+
# HERDGATE_SSH_TUNNELS_TOTAL=64
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
name: herdgate-cloud
|
|
2
|
+
services:
|
|
3
|
+
gate:
|
|
4
|
+
build: .
|
|
5
|
+
user: "${HERDGATE_UID:-1000}:${HERDGATE_GID:-1000}"
|
|
6
|
+
environment:
|
|
7
|
+
HERDGATE_ACCOUNT_TOKEN_FILE: /run/secrets/herdgate-owner-token
|
|
8
|
+
HERDGATE_PUBLIC_HOST: "${HERDGATE_PUBLIC_HOST:?set the public hostname in .env}"
|
|
9
|
+
HERDGATE_PUBLIC_URL: "https://${HERDGATE_PUBLIC_HOST:?set the public hostname in .env}"
|
|
10
|
+
HERDGATE_SSH_HOST: "${HERDGATE_SSH_HOST:-}"
|
|
11
|
+
HERDGATE_SSH_PUBLIC_PORT: "${HERDGATE_SSH_PUBLIC_PORT:-2299}"
|
|
12
|
+
HERDGATE_ENABLE_PUSH: "${HERDGATE_ENABLE_PUSH:-0}"
|
|
13
|
+
HERDGATE_NO_PUSH: "${HERDGATE_NO_PUSH:-0}"
|
|
14
|
+
HERDGATE_PUSH_SUB: "${HERDGATE_PUSH_SUB:-mailto:owner@herdgate.invalid}"
|
|
15
|
+
HERDGATE_TRUSTED_PROXY: "${HERDGATE_TRUSTED_PROXY:-0}"
|
|
16
|
+
HERDGATE_REAL_IP_HEADER: "${HERDGATE_REAL_IP_HEADER:-CF-Connecting-IP}"
|
|
17
|
+
HERDGATE_SSH_TUNNELS_PER_IP: "${HERDGATE_SSH_TUNNELS_PER_IP:-6}"
|
|
18
|
+
HERDGATE_SSH_TUNNELS_TOTAL: "${HERDGATE_SSH_TUNNELS_TOTAL:-64}"
|
|
19
|
+
volumes:
|
|
20
|
+
- type: bind
|
|
21
|
+
source: ./data
|
|
22
|
+
target: /data
|
|
23
|
+
bind:
|
|
24
|
+
create_host_path: false
|
|
25
|
+
- type: bind
|
|
26
|
+
source: ./owner-token
|
|
27
|
+
target: /run/secrets/herdgate-owner-token
|
|
28
|
+
read_only: true
|
|
29
|
+
bind:
|
|
30
|
+
create_host_path: false
|
|
31
|
+
ports:
|
|
32
|
+
- "127.0.0.1:${HERDGATE_HTTP_PORT:-8787}:8787"
|
|
33
|
+
read_only: true
|
|
34
|
+
cap_drop: [ALL]
|
|
35
|
+
security_opt: [no-new-privileges:true]
|
|
36
|
+
healthcheck:
|
|
37
|
+
test: ["CMD", "node", "-e", "require('node:http').get('http://127.0.0.1:8787/healthz', {headers: {Host: process.env.HERDGATE_PUBLIC_HOST}}, r => {r.resume(); if (r.statusCode !== 200) process.exitCode = 1}).on('error', () => { process.exitCode = 1 })"]
|
|
38
|
+
interval: 15s
|
|
39
|
+
timeout: 5s
|
|
40
|
+
retries: 3
|
|
41
|
+
restart: unless-stopped
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[Unit]
|
|
2
|
+
Description=Herdgate Cloud public SSH TCP edge (no credentials)
|
|
3
|
+
After=network.target
|
|
4
|
+
|
|
5
|
+
[Service]
|
|
6
|
+
DynamicUser=yes
|
|
7
|
+
WorkingDirectory=/opt/herdgate-cloud
|
|
8
|
+
EnvironmentFile=/etc/herdgate/edge.env
|
|
9
|
+
ExecStart=/usr/bin/node runtime/cloud/ssh-tcp-edge.js
|
|
10
|
+
Restart=on-failure
|
|
11
|
+
RestartSec=3s
|
|
12
|
+
NoNewPrivileges=yes
|
|
13
|
+
PrivateTmp=yes
|
|
14
|
+
ProtectSystem=strict
|
|
15
|
+
ProtectHome=yes
|
|
16
|
+
|
|
17
|
+
[Install]
|
|
18
|
+
WantedBy=multi-user.target
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[Unit]
|
|
2
|
+
Description=Herdgate Cloud (Gateway and PWA)
|
|
3
|
+
After=network.target
|
|
4
|
+
|
|
5
|
+
[Service]
|
|
6
|
+
DynamicUser=yes
|
|
7
|
+
StateDirectory=herdgate-cloud
|
|
8
|
+
StateDirectoryMode=0700
|
|
9
|
+
UMask=0077
|
|
10
|
+
WorkingDirectory=/opt/herdgate-cloud
|
|
11
|
+
Environment=NODE_ENV=production
|
|
12
|
+
Environment=HERDGATE_BIND=127.0.0.1 HERDGATE_PORT=8787
|
|
13
|
+
Environment=HERDGATE_STATE=/var/lib/herdgate-cloud/state.json
|
|
14
|
+
EnvironmentFile=/etc/herdgate/cloud.env
|
|
15
|
+
LoadCredential=owner-token:/etc/herdgate/owner-token
|
|
16
|
+
Environment=HERDGATE_ACCOUNT_TOKEN_FILE=%d/owner-token
|
|
17
|
+
ExecStart=/usr/bin/node runtime/cloud/main.js
|
|
18
|
+
Restart=on-failure
|
|
19
|
+
RestartSec=3s
|
|
20
|
+
NoNewPrivileges=yes
|
|
21
|
+
PrivateTmp=yes
|
|
22
|
+
ProtectSystem=strict
|
|
23
|
+
ProtectHome=yes
|
|
24
|
+
|
|
25
|
+
[Install]
|
|
26
|
+
WantedBy=multi-user.target
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "./tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"noEmit": false,
|
|
5
|
+
"noEmitOnError": true,
|
|
6
|
+
"rewriteRelativeImportExtensions": true,
|
|
7
|
+
"rootDir": "./src",
|
|
8
|
+
"outDir": "./dist/cloud-runtime"
|
|
9
|
+
},
|
|
10
|
+
"include": ["src/cloud/**/*.ts", "src/protocol/**/*.ts"]
|
|
11
|
+
}
|