1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250 | /** Bootstrap: room secret from the URL fragment → crypto → signaling → mesh → UI. */
import { registerSW } from "virtual:pwa-register";
import "./app/style.css";
import { CallManager } from "./app/call";
import { ChatStore, type SelfAssertion } from "./app/chat";
import { loadHistory, saveHistory } from "./app/history";
import { lobby, touchRoom } from "./app/rooms";
import { UI, type SelfIdentityInfo } from "./app/ui";
import { newRoomSecret, RoomCrypto } from "./lib/crypto";
import { Identity } from "./lib/identity";
import { Mesh } from "./lib/mesh";
import { Signaling } from "./lib/signaling";
import { IceConfig } from "./lib/turn";
import { runSelfTest } from "./lib/selftest";
/** Namespaces this app's rooms on the shared signaling server (PROTOCOL.md §1). */
const APP_SALT = "chat.ardegazu.ro/v1";
const SIGNAL_URL: string =
import.meta.env.VITE_SIGNAL_URL ??
(import.meta.env.DEV
? `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws` // vite proxy → go --dev
: "wss://signal.ardegazu.ro/ws");
const TURN_CREDS_URL = SIGNAL_URL.replace(/^ws/, "http").replace(/\/ws$/, "/turn-credentials");
export const VERSION = __APP_VERSION__;
/** What version is live on the server right now? (bypasses the SW precache) */
async function fetchLiveVersion(): Promise<number | null> {
try {
const res = await fetch(`./version.json?cb=${Date.now()}`, { cache: "no-store" });
const v = (await res.json())?.version;
return typeof v === "number" ? v : null;
} catch {
return null;
}
}
function setupUpdates(): void {
const updateSW = registerSW({
immediate: true,
async onNeedRefresh() {
if (document.getElementById("upd-banner")) return;
const live = await fetchLiveVersion();
const b = document.createElement("button");
b.id = "upd-banner";
b.className = "update-banner";
b.textContent =
live && live !== VERSION
? `⬆ version ${live} is ready (you're on ${VERSION}) — tap to update`
: "⬆ a new version is ready — tap to update";
b.addEventListener("click", () => {
b.textContent = "updating…";
// Own the reload: vite-pwa only reloads for updates it discovered
// itself, not ones surfaced by our periodic reg.update() checks.
let reloaded = false;
const reload = () => {
if (!reloaded) {
reloaded = true;
location.reload();
}
};
navigator.serviceWorker?.addEventListener("controllerchange", reload, { once: true });
setTimeout(reload, 4000); // fallback if controllerchange never fires
void updateSW(false); // sends skip-waiting to the new worker
});
document.body.appendChild(b);
},
onRegisteredSW(_url, reg) {
if (!reg) return;
// look for updates every 5 minutes and whenever the app comes back
setInterval(() => void reg.update().catch(() => {}), 5 * 60_000);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") void reg.update().catch(() => {});
});
},
});
}
async function boot(): Promise<void> {
setupUpdates();
if (import.meta.env.DEV) void runSelfTest();
// fragment: #<secret>[&relay] — never sent to any server
const frag = location.hash.slice(1);
const [secretPart, ...flags] = frag.split("&");
const forceRelay = flags.includes("relay");
let secret = secretPart;
const root0 = document.getElementById("app")!;
if (!/^[A-Za-z0-9_-]{43}$/.test(secret)) {
// no room link → lobby: pick one of your rooms or start a new one
secret = await lobby(root0, newRoomSecret);
}
history.replaceState(null, "", `#${secret}${forceRelay ? "&relay" : ""}`);
const roomEntry = touchRoom(secret);
// opening a different room link while running → clean re-boot into that room
window.addEventListener("hashchange", () => location.reload());
const roomCrypto = await RoomCrypto.create(secret, APP_SALT);
// persistent identity: one Ed25519 seed, kept in localStorage and savable
// into a password manager (see the identity sheet in the roster)
let identity: Identity | null = null;
let idSeed = "";
try {
idSeed = localStorage.getItem("sueta:id") ?? "";
if (idSeed) identity = await Identity.fromSeed(idSeed).catch(() => null);
if (!identity) {
idSeed = Identity.newSeed();
identity = await Identity.fromSeed(idSeed);
localStorage.setItem("sueta:id", idSeed);
}
} catch {
identity = null; // no Ed25519 or no storage — run identity-less
}
const selfAssertion: SelfAssertion | null = identity
? { pub: identity.publicKeyB64, sig: await identity.assert(APP_SALT, roomCrypto.roomId, roomCrypto.peerId) }
: null;
const selfInfo: SelfIdentityInfo | null = identity
? { seed: idSeed, fp: identity.fingerprint, pub: identity.publicKeyB64 }
: null;
let storedName: string | null = null;
try {
storedName = localStorage.getItem("sueta:name");
} catch {} // Safari private mode
const root = root0;
// placeholder store so UI can construct; real name filled after the prompt
let ui!: UI;
let store!: ChatStore;
const ice = new IceConfig(TURN_CREDS_URL, forceRelay);
const signaling = new Signaling(SIGNAL_URL, roomCrypto.roomId, roomCrypto.peerId, {
peers: (list) => mesh.onPeers(list),
peerJoined: (p) => mesh.onPeerJoined(p),
peerLeft: (p) => mesh.onPeerLeft(p),
signal: (from, env) => void mesh.onSignal(from, env),
status: (up) => ui?.setSignaling(up),
error: (code) => ui?.toast(`server: ${code}`),
});
let call!: CallManager;
const mesh = new Mesh({
crypto: roomCrypto,
signaling,
ice,
myName: () => store?.myName ?? storedName ?? "?",
events: {
peerState: (peer, state, name) => {
ui?.setPeer(peer, state, name);
call?.onPeerState(peer, state);
},
peerGone: (peer) => {
ui?.removePeer(peer);
call?.onPeerGone(peer);
},
message: (from, payload) => {
if ((payload as { kind?: string })?.kind === "call") call?.onWire(from, payload);
else store?.onMessage(from, payload);
},
binary: (from, data) => store?.onBinary(from, data),
channelOpen: (peer) => {
store?.onChannelOpen(peer);
call?.onChannelOpen(peer);
},
track: (peer, stream) => call?.onTrack(peer, stream),
},
});
call = new CallManager(mesh, () => store?.myName ?? "?");
store = new ChatStore(mesh, storedName ?? "", { appSalt: APP_SALT, roomId: roomCrypto.roomId }, selfAssertion);
ui = new UI(root, store, {
send: (text, thread) => store.sendText(text, thread),
sendImage: (file, thread) => store.sendImage(file, thread),
react: (id, emoji) => store.toggleReaction(id, emoji),
rename: (name) => {
store.setName(name);
try {
localStorage.setItem("sueta:name", name);
} catch {}
},
inviteURL: () => `${location.origin}${location.pathname}#${secret}`,
roomLabel: () => roomEntry.label,
goLobby: () => {
history.replaceState(null, "", location.pathname);
location.reload();
},
joinCall: (video) => call.join(video),
leaveCall: () => call.leave(),
toggleMic: () => call.toggleMic(),
toggleCam: () => call.toggleCam(),
identity: () => selfInfo,
importIdentity: (seed: string) => {
if (!/^[A-Za-z0-9_-]{43}$/.test(seed)) return false;
try {
localStorage.setItem("sueta:id", seed);
} catch {
return false;
}
location.reload();
return true;
},
});
ui.bindSelf(roomCrypto.peerId);
store.onPeerName = (peer, name) => ui.setPeerName(peer, name);
store.onPeerIdentity = (peer, id) => ui.setPeerIdentity(peer, id);
store.onHistory = (n) => ui.toast(`⇣ synced ${n} message${n === 1 ? "" : "s"} from the room`);
store.onIncoming = (m) => ui.notifyIncoming(m);
call.onRoster = (self, members) => ui.updateCall(self, members, call.localStream);
call.onCallStarted = (from, name, seq) => store.addCallLine(from, name, seq);
call.onError = (m) => ui.toast(m);
call.onNotice = (m) => ui.toast(m);
// device-local history: restore this room's past, then save on every change
const saved = await loadHistory(roomCrypto.roomId);
if (saved) store.importPersist(saved);
let saveTimer: ReturnType<typeof setTimeout> | null = null;
store.onChange = () => {
ui.scheduleRender();
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(() => void saveHistory(roomCrypto.roomId, store.exportPersist()), 1500);
};
// iOS can kill background pages before the debounce fires — flush on hide
window.addEventListener("pagehide", () => {
if (saveTimer) clearTimeout(saveTimer);
void saveHistory(roomCrypto.roomId, store.exportPersist());
});
// console/debug handle — grants nothing an open console doesn't already have
(window as unknown as Record<string, unknown>).__sueta = { mesh, signaling, roomCrypto, identity: selfInfo, call };
const name = await ui.askName(storedName);
store.setName(name);
try {
localStorage.setItem("sueta:name", name);
} catch {}
signaling.connect();
window.addEventListener("beforeunload", () => {
call.leave();
mesh.close();
signaling.close();
});
}
void boot();
|