tryharness 0.7.83 → 0.7.86
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 +21 -19
- package/assets/dsh-plugin.mjs +75 -4
- package/assets/herdr-mod/harness/main.js +367 -0
- package/assets/herdr-mod/harness/mod.json +6 -0
- package/assets/opencode-plugin.js +87 -22
- package/assets/pi-extension.ts +81 -2
- package/cli.mjs +544 -208
- package/lib/adapters.mjs +62 -27
- package/lib/agentBinaries.mjs +6 -8
- package/lib/agentClaims.mjs +168 -0
- package/lib/agentReadTools.json +415 -0
- package/lib/agentSignIn.mjs +17 -18
- package/lib/agentWiring.mjs +114 -0
- package/lib/archetypes.js +10 -11
- package/lib/attention.mjs +100 -0
- package/lib/audit.mjs +1 -1
- package/lib/backupSetup.mjs +6 -28
- package/lib/bankrApprovals.mjs +86 -0
- package/lib/boardAccess.mjs +40 -66
- package/lib/boardBackup.mjs +86 -85
- package/lib/boardCommands.mjs +28 -0
- package/lib/boardFileCommands.mjs +29 -36
- package/lib/boardFiles.mjs +83 -15
- package/lib/boardMirror.mjs +78 -11
- package/lib/boardProtocol.json +191 -123
- package/lib/boardThreads.mjs +19 -37
- package/lib/boardTools.mjs +22 -15
- package/lib/boardWatches.mjs +43 -15
- package/lib/bridge.mjs +7 -3
- package/lib/browserAgentTools.mjs +59 -0
- package/lib/browserWake.mjs +0 -6
- package/lib/cards.mjs +52 -0
- package/lib/circling.mjs +189 -0
- package/lib/cleanup.mjs +234 -0
- package/lib/cloudBoot.mjs +21 -4
- package/lib/cloudSave.mjs +46 -5
- package/lib/compaction.mjs +8 -1
- package/lib/completion.mjs +358 -0
- package/lib/computerDevices.mjs +853 -0
- package/lib/connectionStatus.mjs +34 -0
- package/lib/connectors.mjs +139 -1
- package/lib/coordinator.mjs +108 -14
- package/lib/coreModels.mjs +36 -12
- package/lib/daemon.mjs +2426 -338
- package/lib/daemonLock.mjs +103 -0
- package/lib/deviceDoor.mjs +308 -0
- package/lib/deviceIdentity.mjs +114 -0
- package/lib/deviceList.mjs +172 -0
- package/lib/deviceSeal.mjs +74 -0
- package/lib/dispatcher.mjs +497 -26
- package/lib/dispatches.mjs +3 -3
- package/lib/environment.mjs +2 -1
- package/lib/environments.mjs +67 -41
- package/lib/events.mjs +318 -0
- package/lib/facts.mjs +170 -0
- package/lib/fileSource.mjs +540 -0
- package/lib/files.mjs +47 -2
- package/lib/gitHost.mjs +39 -1
- package/lib/goalCommands.mjs +12 -80
- package/lib/handover.mjs +21 -16
- package/lib/harnessOffers.mjs +140 -15
- package/lib/herdr.mjs +100 -15
- package/lib/herdrAppCall.mjs +19 -0
- package/lib/herdrCore.mjs +59 -0
- package/lib/herdrRuns.mjs +1126 -0
- package/lib/hookDialects.mjs +235 -50
- package/lib/identityLink.mjs +81 -0
- package/lib/inference.mjs +31 -2
- package/lib/jamAccess.mjs +82 -0
- package/lib/{projectBoard.mjs → jamBoard.mjs} +5 -4
- package/lib/{projectGit.mjs → jamGit.mjs} +53 -15
- package/lib/jamKey.mjs +274 -0
- package/lib/{projectPieces.mjs → jamPieces.mjs} +35 -29
- package/lib/{projectSettings.mjs → jamSettings.mjs} +12 -22
- package/lib/jamStore.mjs +973 -0
- package/lib/jamUpgrade.mjs +112 -0
- package/lib/jams.mjs +3079 -0
- package/lib/kanban.mjs +13 -7
- package/lib/landed.mjs +5 -1
- package/lib/library.mjs +41 -22
- package/lib/limits.mjs +91 -0
- package/lib/lineDiff.mjs +97 -0
- package/lib/lineup.mjs +18 -13
- package/lib/link.mjs +584 -0
- package/lib/localStack.mjs +75 -16
- package/lib/localmodels.mjs +58 -78
- package/lib/loopBackstop.mjs +2 -1
- package/lib/machine.mjs +544 -0
- package/lib/machineLink.mjs +446 -0
- package/lib/machineRoutes.mjs +68 -19
- package/lib/machineRuns.mjs +85 -4
- package/lib/machineSeal.mjs +6 -31
- package/lib/manager.mjs +134 -12
- package/lib/mcp-stdio.mjs +492 -215
- package/lib/mcpRelay.mjs +34 -35
- package/lib/members.json +1 -1
- package/lib/modelRoute.mjs +162 -0
- package/lib/nativeHost.mjs +81 -90
- package/lib/nativeSenses.mjs +258 -0
- package/lib/nerves.mjs +523 -0
- package/lib/network.mjs +117 -278
- package/lib/networkPlaces.mjs +578 -0
- package/lib/nextStep.mjs +95 -0
- package/lib/notify.mjs +2 -2
- package/lib/nudge.mjs +116 -10
- package/lib/originals.mjs +216 -0
- package/lib/outsideEvents.mjs +383 -0
- package/lib/outsideRuns.mjs +230 -0
- package/lib/ownMachines.mjs +674 -256
- package/lib/pain.mjs +215 -0
- package/lib/pairing.mjs +91 -11
- package/lib/paths.mjs +42 -3
- package/lib/peerProcess.mjs +21 -7
- package/lib/peopleLink.mjs +268 -0
- package/lib/personNotices.mjs +3 -2
- package/lib/phones.mjs +252 -542
- package/lib/placeCards.mjs +282 -0
- package/lib/placeChecks.mjs +95 -0
- package/lib/placeCommands.mjs +8 -17
- package/lib/placeRequests.mjs +152 -0
- package/lib/placeStore.mjs +295 -0
- package/lib/placeTool.d.ts +12 -0
- package/lib/placeTool.js +40 -0
- package/lib/places.mjs +63 -14
- package/lib/plans.mjs +53 -8
- package/lib/presence.mjs +270 -0
- package/lib/privateNetwork.d.ts +2 -0
- package/lib/privateNetwork.js +93 -0
- package/lib/proposals.mjs +300 -0
- package/lib/publicFetch.d.ts +32 -0
- package/lib/publicFetch.js +248 -0
- package/lib/reach.mjs +128 -0
- package/lib/rebuildable.mjs +72 -0
- package/lib/recall.mjs +216 -0
- package/lib/record.mjs +13 -0
- package/lib/reflexes.mjs +392 -0
- package/lib/relayLimits.mjs +31 -2
- package/lib/releaseNotice.mjs +198 -0
- package/lib/removeHarness.mjs +15 -4
- package/lib/repoLinks.mjs +204 -35
- package/lib/runAuthority.mjs +102 -39
- package/lib/runBrief.mjs +93 -40
- package/lib/runRequests.mjs +52 -14
- package/lib/runUsage.mjs +31 -0
- package/lib/runWorker.mjs +74 -25
- package/lib/runner.mjs +289 -45
- package/lib/runtime-install.mjs +37 -8
- package/lib/schedules.mjs +171 -47
- package/lib/screenWatches.mjs +221 -0
- package/lib/sealed.mjs +12 -30
- package/lib/sealedThreads.mjs +198 -392
- package/lib/secretStore.mjs +178 -0
- package/lib/secrets.mjs +11 -0
- package/lib/seen.mjs +3 -9
- package/lib/selfUpdate.mjs +51 -15
- package/lib/senseCall.mjs +1514 -0
- package/lib/senseHook.mjs +114 -0
- package/lib/senseTools.mjs +1298 -0
- package/lib/sessionBriefs.mjs +87 -0
- package/lib/sessionControl.mjs +63 -13
- package/lib/sessionFiles.mjs +85 -0
- package/lib/setupChoices.mjs +12 -3
- package/lib/setupMode.mjs +70 -25
- package/lib/sharedKeys.mjs +166 -0
- package/lib/sleep.mjs +396 -0
- package/lib/sources.mjs +306 -0
- package/lib/speech.mjs +166 -411
- package/lib/spoken.mjs +210 -0
- package/lib/steerHook.mjs +3 -1
- package/lib/steerQueue.mjs +40 -11
- package/lib/store.mjs +323 -130
- package/lib/stuck.mjs +85 -7
- package/lib/swarm.mjs +157 -49
- package/lib/swarmDevices.mjs +25 -85
- package/lib/swarmMemory.mjs +93 -9
- package/lib/t3.mjs +73 -3
- package/lib/taskCommands.mjs +51 -60
- package/lib/taskRooms.mjs +30 -4
- package/lib/taskRules.json +29 -0
- package/lib/taskRules.mjs +21 -0
- package/lib/taskRuns.mjs +74 -11
- package/lib/team.mjs +2 -1
- package/lib/threadActions.mjs +37 -9
- package/lib/threadAuthority.mjs +4 -4
- package/lib/threadBriefs.mjs +173 -43
- package/lib/threadNotes.mjs +320 -0
- package/lib/threadRecord.mjs +491 -0
- package/lib/threadRuns.mjs +216 -108
- package/lib/threadView.mjs +27 -30
- package/lib/threadWatches.mjs +1962 -0
- package/lib/timeSense.mjs +839 -0
- package/lib/tripwires.mjs +454 -0
- package/lib/ui.mjs +1 -1
- package/lib/vault.mjs +560 -45
- package/lib/vaultCommands.mjs +5 -3
- package/lib/vaultPeers.mjs +165 -0
- package/lib/vaultTools.d.ts +4 -1
- package/lib/vaultTools.js +22 -1
- package/lib/verdicts.mjs +12 -26
- package/lib/versions.mjs +117 -0
- package/lib/waitTool.mjs +278 -0
- package/lib/wakePicture.mjs +268 -0
- package/lib/wakeQueue.mjs +108 -0
- package/lib/watchResponses.mjs +533 -0
- package/lib/watches.mjs +290 -145
- package/lib/windowAsks.mjs +80 -17
- package/lib/worktrees.mjs +159 -9
- package/npm-shrinkwrap.json +138 -631
- package/package.json +7 -6
- package/release.json +211 -129
- package/lib/callSessions.mjs +0 -51
- package/lib/directLink.mjs +0 -349
- package/lib/peopleBoard.mjs +0 -131
- package/lib/projects.mjs +0 -2917
- package/lib/roomChannels.mjs +0 -667
package/lib/link.mjs
ADDED
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
// The link (docs/one-link-plan.md): the person's pages and phones reach this computer over WebRTC, one channel per
|
|
2
|
+
// open page, carrying the same sealed calls (HSC1) the relay carries. The calls are opened and answered by the same
|
|
3
|
+
// code (phones.mjs), so the channel grants nothing the relay does not; only the road changes.
|
|
4
|
+
//
|
|
5
|
+
// An introduction is itself a sealed call ("link.offer", phones.mjs): the page's offer arrives already opened and
|
|
6
|
+
// checked against the person's device list, and the answer goes back sealed. Harness's server carries both unread.
|
|
7
|
+
// Any channel that opens belongs to that device and that page: WebRTC's own encryption is keyed by the fingerprints
|
|
8
|
+
// in the offer and answer, which only the device and this computer saw in the clear.
|
|
9
|
+
|
|
10
|
+
import { randomBytes } from "node:crypto";
|
|
11
|
+
import { promises as dns } from "node:dns";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
|
|
14
|
+
// Roam's WebRTC (a native package per platform). A computer where it cannot load keeps working through Harness, with
|
|
15
|
+
// no channels: its pages and other computers reach it as before the link (docs/one-link-plan.md).
|
|
16
|
+
export const wrtc = await import("@roamhq/wrtc").then(
|
|
17
|
+
(loaded) => loaded.default ?? loaded,
|
|
18
|
+
() => null
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
// The channel's one label; a page that opens anything else is closed.
|
|
22
|
+
export const LINK_LABEL = "harness";
|
|
23
|
+
|
|
24
|
+
// With no fallback credential (none yet, or Harness could not give one): STUN alone, so only a direct path can open.
|
|
25
|
+
const STUN = [{ urls: "stun:stun.cloudflare.com:3478" }];
|
|
26
|
+
|
|
27
|
+
// A credential is asked for again once it has less than this left, so a channel opened with it lives an hour or more
|
|
28
|
+
// before the page replaces it (src/main/device/link.ts REPLACE_BEFORE_MS).
|
|
29
|
+
const REFRESH_BEFORE_MS = 2 * 60 * 60 * 1000;
|
|
30
|
+
// The same wait as this computer's other calls to Harness's server (computerDevices.mjs).
|
|
31
|
+
const CREDENTIAL_MS = 15_000;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* This computer's fallback credential (Cloudflare's TURN, src/server/link/turn.ts), from Harness's server with its own
|
|
35
|
+
* token, kept ready in the background: an offer is answered with what is held, never after a wait on Harness.
|
|
36
|
+
*/
|
|
37
|
+
export function createIceServers({ origin, token, fetchImpl = fetch }) {
|
|
38
|
+
let held = { iceServers: STUN, expiresAt: null };
|
|
39
|
+
let asking = null;
|
|
40
|
+
const ask = async () => {
|
|
41
|
+
try {
|
|
42
|
+
const response = await fetchImpl(
|
|
43
|
+
`${String(origin()).replace(/\/$/, "")}/api/computer/link`,
|
|
44
|
+
{
|
|
45
|
+
headers: { authorization: `Bearer ${token()}` },
|
|
46
|
+
signal: AbortSignal.timeout(CREDENTIAL_MS),
|
|
47
|
+
}
|
|
48
|
+
);
|
|
49
|
+
const body = await response.json().catch(() => null);
|
|
50
|
+
if (response.ok && Array.isArray(body?.iceServers))
|
|
51
|
+
held = { iceServers: body.iceServers, expiresAt: body.expiresAt };
|
|
52
|
+
} catch {
|
|
53
|
+
// Kept as it was; asked again with the next offer.
|
|
54
|
+
} finally {
|
|
55
|
+
asking = null;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
const due = () =>
|
|
59
|
+
!held.expiresAt || held.expiresAt - Date.now() < REFRESH_BEFORE_MS;
|
|
60
|
+
const current = () => {
|
|
61
|
+
if (due()) asking ??= ask();
|
|
62
|
+
return held.iceServers;
|
|
63
|
+
};
|
|
64
|
+
// Asked for at start, so the first page's offer already has it.
|
|
65
|
+
current();
|
|
66
|
+
return current;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// An address on the person's own network (or this machine), as WebRTC reports it.
|
|
70
|
+
const LOCAL_ADDRESS =
|
|
71
|
+
/^(10\.|127\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.|::1$|f[cd][0-9a-f]{2}:|fe80:)/i;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* How a channel reaches this computer, from WebRTC's own report of the pair of addresses in use: "the fallback" (a
|
|
75
|
+
* TURN server), "the local network" (the page's address is on the person's network or this machine), or "the internet".
|
|
76
|
+
* Null when WebRTC does not say. Kept in the log, without the addresses.
|
|
77
|
+
*/
|
|
78
|
+
export async function wayOf(peer) {
|
|
79
|
+
try {
|
|
80
|
+
const stats = [...(await peer.getStats()).values()];
|
|
81
|
+
const byId = new Map(stats.map((item) => [item.id, item]));
|
|
82
|
+
const chosen = stats.find(
|
|
83
|
+
(item) => item.type === "transport"
|
|
84
|
+
)?.selectedCandidatePairId;
|
|
85
|
+
const pair = byId.get(chosen);
|
|
86
|
+
const local = byId.get(pair?.localCandidateId);
|
|
87
|
+
const remote = byId.get(pair?.remoteCandidateId);
|
|
88
|
+
if (!local || !remote) return null;
|
|
89
|
+
if (
|
|
90
|
+
local.candidateType === "relay" ||
|
|
91
|
+
local.relayProtocol !== undefined ||
|
|
92
|
+
remote.candidateType === "relay"
|
|
93
|
+
)
|
|
94
|
+
return "the fallback";
|
|
95
|
+
// The page's address, when WebRTC shows it; it hides one it learned during the checks ("prflx"), and then this
|
|
96
|
+
// end's own says it: a page reaching this computer's loopback or private address is on its network.
|
|
97
|
+
const theirs = String(remote.address ?? remote.ip ?? "");
|
|
98
|
+
const ours = String(local.address ?? local.ip ?? "");
|
|
99
|
+
const onNetwork = theirs
|
|
100
|
+
? LOCAL_ADDRESS.test(theirs)
|
|
101
|
+
: local.candidateType === "host" && LOCAL_ADDRESS.test(ours);
|
|
102
|
+
return onNetwork ? "the local network" : "the internet";
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ---- whether a page runs on this machine (docs/one-link-plan.md L4.7a) ----
|
|
109
|
+
//
|
|
110
|
+
// Two signs, either enough: an address the page offers is one of this machine's own (Chrome offers its own as a
|
|
111
|
+
// ".local" name, resolved here through the system's mDNS, measured 4-5 ms on a Mac), or the channel came in on this
|
|
112
|
+
// computer's loopback address, which only a page on this machine can reach (and which needs no mDNS, as on Linux
|
|
113
|
+
// without Avahi). Only the yes or no is kept; no address leaves the computer.
|
|
114
|
+
|
|
115
|
+
const ownAddresses = () =>
|
|
116
|
+
new Set(
|
|
117
|
+
Object.values(os.networkInterfaces())
|
|
118
|
+
.flat()
|
|
119
|
+
.map((each) => String(each?.address ?? "").replace(/%.*$/, ""))
|
|
120
|
+
.filter(Boolean)
|
|
121
|
+
);
|
|
122
|
+
const LOOPBACK = /^(127\.|::1$)/;
|
|
123
|
+
|
|
124
|
+
/** The address in one ICE candidate line ("candidate:<foundation> <component> <protocol> <priority> <address> ..."). */
|
|
125
|
+
const addressOf = (line) =>
|
|
126
|
+
String(line ?? "")
|
|
127
|
+
.replace(/^a=/, "")
|
|
128
|
+
.split(/\s+/)[4] ?? "";
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* A ".local" name's addresses through the system's mDNS, each family asked on its own and the first to answer taken:
|
|
132
|
+
* Chrome registers only an IPv4 address for its name, and asking both at once waits out the IPv6 query (seconds, or
|
|
133
|
+
* past the time a question has; found by e2e hidden-page-seen).
|
|
134
|
+
*/
|
|
135
|
+
const resolveLocal = (name) =>
|
|
136
|
+
Promise.any(
|
|
137
|
+
[4, 6].map((family) =>
|
|
138
|
+
dns
|
|
139
|
+
.lookup(name, { family, all: true })
|
|
140
|
+
.then((all) =>
|
|
141
|
+
all.length
|
|
142
|
+
? all.map((each) => each.address)
|
|
143
|
+
: Promise.reject(new Error("none"))
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
).catch(() => []);
|
|
147
|
+
|
|
148
|
+
/** True when any of these addresses is this machine's, false when all that could be read are not, null when none could. */
|
|
149
|
+
async function onThisMachine(addresses) {
|
|
150
|
+
const own = ownAddresses();
|
|
151
|
+
let known = false;
|
|
152
|
+
for (const address of addresses) {
|
|
153
|
+
if (!address) continue;
|
|
154
|
+
let resolved = [];
|
|
155
|
+
if (address.endsWith(".local")) resolved = await resolveLocal(address);
|
|
156
|
+
else resolved = [address];
|
|
157
|
+
if (!resolved.length) continue;
|
|
158
|
+
known = true;
|
|
159
|
+
if (resolved.some((each) => own.has(each) || LOOPBACK.test(each)))
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
return known ? false : null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Whether this end of the channel in use is a loopback address: the page reached this computer from this machine. */
|
|
166
|
+
async function cameInOnLoopback(peer) {
|
|
167
|
+
try {
|
|
168
|
+
const stats = [...(await peer.getStats()).values()];
|
|
169
|
+
const byId = new Map(stats.map((item) => [item.id, item]));
|
|
170
|
+
const chosen = stats.find(
|
|
171
|
+
(item) => item.type === "transport"
|
|
172
|
+
)?.selectedCandidatePairId;
|
|
173
|
+
const local = byId.get(byId.get(chosen)?.localCandidateId);
|
|
174
|
+
return LOOPBACK.test(String(local?.address ?? local?.ip ?? ""));
|
|
175
|
+
} catch {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The relay's answer shape (src/server/bridge/sealed.ts relaySealed), from what the computer answered. */
|
|
181
|
+
function replyOf(result) {
|
|
182
|
+
if (result?.ok === true)
|
|
183
|
+
return { connected: true, ok: true, envelope: result.envelope };
|
|
184
|
+
return {
|
|
185
|
+
connected: true,
|
|
186
|
+
ok: false,
|
|
187
|
+
error:
|
|
188
|
+
typeof result?.error === "string"
|
|
189
|
+
? result.error.slice(0, 300)
|
|
190
|
+
: "the computer refused the request",
|
|
191
|
+
...(typeof result?.code === "string"
|
|
192
|
+
? { code: result.code.slice(0, 32) }
|
|
193
|
+
: {}),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const SESSION = /^[A-Za-z0-9_-]{8,64}$/;
|
|
198
|
+
|
|
199
|
+
// Must match src/main/device/link.ts PIECE_CHARS: under the smallest message a browser takes (256 KB).
|
|
200
|
+
export const PIECE_CHARS = 64 * 1024;
|
|
201
|
+
// A message larger than the sealed wire's largest call (1.4 MB of ciphertext) with room for its fields is not one.
|
|
202
|
+
const MAX_MESSAGE_CHARS = 2_000_000;
|
|
203
|
+
|
|
204
|
+
/** Splits one message into the pieces the channel carries; a small one goes whole. */
|
|
205
|
+
export function piecesOf(id, text) {
|
|
206
|
+
if (text.length <= PIECE_CHARS) return [text];
|
|
207
|
+
const count = Math.ceil(text.length / PIECE_CHARS);
|
|
208
|
+
return Array.from({ length: count }, (_, part) =>
|
|
209
|
+
JSON.stringify({
|
|
210
|
+
id,
|
|
211
|
+
part,
|
|
212
|
+
of: count,
|
|
213
|
+
data: text.slice(part * PIECE_CHARS, (part + 1) * PIECE_CHARS),
|
|
214
|
+
})
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// At most this many addresses from one page are taken: a browser offers a handful.
|
|
219
|
+
const MAX_CANDIDATES = 32;
|
|
220
|
+
// How many channels this computer keeps with one device (docs/one-link-plan.md settled item 5, L6.4): each open page
|
|
221
|
+
// holds its own. An idle channel cost this computer 0.25 to 0.6 MB (48 channels: 12.1 MB; 32 channels: 19 MB; two runs
|
|
222
|
+
// of smoke link-hard-cases, November 13), so 32 is at most about 20 MB for a browser with every one of them open: more
|
|
223
|
+
// pages than a person keeps in use at once, and a small bound on what one device can make this computer hold.
|
|
224
|
+
export const MOST_CHANNELS_PER_DEVICE = 32;
|
|
225
|
+
// How long a window has to answer this computer's question: the wait Harness's relay gave one window before the link
|
|
226
|
+
// replaced it (L4.7c).
|
|
227
|
+
const WINDOW_ASK_MS = 15_000;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The daemon's end of the link.
|
|
231
|
+
*
|
|
232
|
+
* - `handle(request)`: phones.mjs handle, for a sealed request as the relay delivers it ({ kind, envelope }).
|
|
233
|
+
* - `publicKey()`: this computer's relay key; a request sealed for another computer is refused, as on the relay.
|
|
234
|
+
* - `iceServers()`: the servers this end uses (createIceServers); STUN alone when none are given.
|
|
235
|
+
*
|
|
236
|
+
* Addresses are traded as they are found (trickle): waiting for WebRTC to finish finding them takes about 40 s here,
|
|
237
|
+
* as STUN from the loopback addresses never answers (measured November 11, @roamhq/wrtc on macOS).
|
|
238
|
+
* - `Peer`: the RTCPeerConnection to use (tests may pass their own).
|
|
239
|
+
*/
|
|
240
|
+
export function createLink({
|
|
241
|
+
handle,
|
|
242
|
+
publicKey,
|
|
243
|
+
log = () => {},
|
|
244
|
+
iceServers = () => STUN,
|
|
245
|
+
Peer = wrtc?.RTCPeerConnection,
|
|
246
|
+
}) {
|
|
247
|
+
// One line per device and page, "<deviceId>:<session>": the peer, the addresses found here and not yet sent to the
|
|
248
|
+
// page, and the page's asks waiting for one.
|
|
249
|
+
const lines = new Map();
|
|
250
|
+
// The browsers known to run on this machine. A browser's device keys stay in that browser, so every page of one found
|
|
251
|
+
// here runs here: its next pages are asked as soon as their channel opens, with nothing to look up (at first the
|
|
252
|
+
// channel is often made over the network, and a ".local" name takes seconds to resolve; found by e2e
|
|
253
|
+
// hidden-page-seen, where a woken page waited up to 9 s).
|
|
254
|
+
const browsersFoundHere = new Set();
|
|
255
|
+
|
|
256
|
+
const forget = (key, line) => {
|
|
257
|
+
if (lines.get(key) === line) lines.delete(key);
|
|
258
|
+
};
|
|
259
|
+
const wake = (line) => {
|
|
260
|
+
for (const resolve of line.waiting) resolve();
|
|
261
|
+
line.waiting.clear();
|
|
262
|
+
};
|
|
263
|
+
// A channel that closes leaves no question waiting on it.
|
|
264
|
+
const unanswered = (line) => {
|
|
265
|
+
for (const settle of [...line.asks.values()]) settle(null);
|
|
266
|
+
};
|
|
267
|
+
const shut = (key, line) => {
|
|
268
|
+
lines.delete(key);
|
|
269
|
+
wake(line);
|
|
270
|
+
unanswered(line);
|
|
271
|
+
line.peer.close();
|
|
272
|
+
};
|
|
273
|
+
/**
|
|
274
|
+
* A device past its share of channels loses the ones unused the longest, the new page's own aside. The page behind a
|
|
275
|
+
* closed one opens another with its next call (src/main/device/link.ts), so a tab left in the background costs this
|
|
276
|
+
* computer nothing and comes back when the person returns to it.
|
|
277
|
+
*/
|
|
278
|
+
const keepWithinCap = (device, newest) => {
|
|
279
|
+
const held = [...lines]
|
|
280
|
+
.filter(([key]) => key.startsWith(`${device.id}:`) && key !== newest)
|
|
281
|
+
.sort(([, one], [, other]) => one.usedAt - other.usedAt);
|
|
282
|
+
const over = held.length + 1 - MOST_CHANNELS_PER_DEVICE;
|
|
283
|
+
if (over <= 0) return;
|
|
284
|
+
for (const [key, line] of held.slice(0, over)) shut(key, line);
|
|
285
|
+
log(
|
|
286
|
+
`link: ${device.label || device.id} holds ${MOST_CHANNELS_PER_DEVICE} channels, the most this computer keeps with one device; closed the ${over === 1 ? "one" : over} unused the longest`
|
|
287
|
+
);
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
const serve = (channel, deviceId, line) => {
|
|
291
|
+
const pieces = new Map();
|
|
292
|
+
channel.onmessage = ({ data }) => receive(data);
|
|
293
|
+
|
|
294
|
+
const receive = async (data) => {
|
|
295
|
+
line.usedAt = Date.now();
|
|
296
|
+
let message;
|
|
297
|
+
try {
|
|
298
|
+
message = JSON.parse(typeof data === "string" ? data : "");
|
|
299
|
+
} catch {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (typeof message?.part === "number") {
|
|
303
|
+
const id = String(message.id ?? "");
|
|
304
|
+
const parts = pieces.get(id) ?? [];
|
|
305
|
+
parts[message.part] = String(message.data ?? "");
|
|
306
|
+
pieces.set(id, parts);
|
|
307
|
+
const size = parts.reduce((sum, part) => sum + (part?.length ?? 0), 0);
|
|
308
|
+
if (size > MAX_MESSAGE_CHARS) return pieces.delete(id);
|
|
309
|
+
if (parts.filter((part) => part !== undefined).length < message.of)
|
|
310
|
+
return;
|
|
311
|
+
pieces.delete(id);
|
|
312
|
+
return receive(parts.join(""));
|
|
313
|
+
}
|
|
314
|
+
const { id, request } = message || {};
|
|
315
|
+
if (typeof id !== "string") return;
|
|
316
|
+
// A window's answer to this computer's own question (ask, below).
|
|
317
|
+
if (typeof message === "object" && "answer" in message)
|
|
318
|
+
return line.asks.get(id)?.(message.answer);
|
|
319
|
+
const send = (reply) => {
|
|
320
|
+
if (channel.readyState !== "open") return;
|
|
321
|
+
for (const piece of piecesOf(id, JSON.stringify({ id, reply })))
|
|
322
|
+
channel.send(piece);
|
|
323
|
+
};
|
|
324
|
+
// Only a call sealed for this computer, from the device that introduced this channel.
|
|
325
|
+
if (
|
|
326
|
+
request?.kind !== "call" ||
|
|
327
|
+
request.machine !== publicKey() ||
|
|
328
|
+
request.envelope?.deviceId !== deviceId
|
|
329
|
+
)
|
|
330
|
+
return send(
|
|
331
|
+
replyOf({ ok: false, error: "not this computer or device" })
|
|
332
|
+
);
|
|
333
|
+
const { machine: _machine, ...forDaemon } = request;
|
|
334
|
+
try {
|
|
335
|
+
send(replyOf(await handle(forDaemon)));
|
|
336
|
+
} catch (error) {
|
|
337
|
+
send(
|
|
338
|
+
replyOf({
|
|
339
|
+
ok: false,
|
|
340
|
+
error: `the phone request failed: ${error.message}`,
|
|
341
|
+
})
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* A device's offer, already opened from its sealed call ("link.offer"): the answer to seal back, with the addresses
|
|
349
|
+
* this computer found so far. The rest go back in the answers to the page's "link.candidates".
|
|
350
|
+
*/
|
|
351
|
+
const offer = async (device, input) => {
|
|
352
|
+
if (!Peer) return { ok: false, error: "this computer has no WebRTC" };
|
|
353
|
+
const session = String(input?.session || "");
|
|
354
|
+
if (!SESSION.test(session) || typeof input?.sdp !== "string")
|
|
355
|
+
return { ok: false, error: "invalid link offer" };
|
|
356
|
+
const key = `${device.id}:${session}`;
|
|
357
|
+
const before = lines.get(key);
|
|
358
|
+
if (before) {
|
|
359
|
+
wake(before);
|
|
360
|
+
before.peer.close();
|
|
361
|
+
}
|
|
362
|
+
const peer = new Peer({ iceServers: iceServers() });
|
|
363
|
+
// The channel once the page opens it, and this computer's questions waiting for its answer.
|
|
364
|
+
const line = {
|
|
365
|
+
peer,
|
|
366
|
+
found: [],
|
|
367
|
+
waiting: new Set(),
|
|
368
|
+
channel: null,
|
|
369
|
+
asks: new Map(),
|
|
370
|
+
// When it last carried anything either way: what the cap goes by.
|
|
371
|
+
usedAt: Date.now(),
|
|
372
|
+
// Whether the page runs on this machine (L4.7a): true, false, or null while it cannot tell.
|
|
373
|
+
here: browsersFoundHere.has(device.id) ? true : null,
|
|
374
|
+
looked: Promise.resolve(),
|
|
375
|
+
// Settled the moment the page is known to run here, whatever lookups are still going.
|
|
376
|
+
isHere: null,
|
|
377
|
+
foundHere: () => {},
|
|
378
|
+
};
|
|
379
|
+
line.isHere =
|
|
380
|
+
line.here === true
|
|
381
|
+
? Promise.resolve()
|
|
382
|
+
: new Promise((resolve) => (line.foundHere = resolve));
|
|
383
|
+
lines.set(key, line);
|
|
384
|
+
keepWithinCap(device, key);
|
|
385
|
+
line.lookAt = (addresses) => look(addresses);
|
|
386
|
+
const name = device.label || device.id;
|
|
387
|
+
// Only the yes or no is written down, never an address.
|
|
388
|
+
const decided = (said, how) => {
|
|
389
|
+
if (said === null || line.here === said || line.here === true) return;
|
|
390
|
+
line.here = said;
|
|
391
|
+
if (!said) return;
|
|
392
|
+
browsersFoundHere.add(device.id);
|
|
393
|
+
line.foundHere();
|
|
394
|
+
log(
|
|
395
|
+
`link: ${name} ${line.here ? "runs on this computer" : "runs elsewhere"} (${how})`
|
|
396
|
+
);
|
|
397
|
+
};
|
|
398
|
+
const look = (addresses) => {
|
|
399
|
+
line.looked = line.looked.then(async () => {
|
|
400
|
+
if (line.here === true) return;
|
|
401
|
+
decided(await onThisMachine(addresses), "its addresses");
|
|
402
|
+
});
|
|
403
|
+
};
|
|
404
|
+
look(
|
|
405
|
+
input.sdp
|
|
406
|
+
.split(/\r?\n/)
|
|
407
|
+
.filter((each) => each.startsWith("a=candidate"))
|
|
408
|
+
.map(addressOf)
|
|
409
|
+
);
|
|
410
|
+
peer.onicecandidate = ({ candidate }) => {
|
|
411
|
+
if (!candidate) return;
|
|
412
|
+
line.found.push({
|
|
413
|
+
candidate: candidate.candidate,
|
|
414
|
+
sdpMid: candidate.sdpMid,
|
|
415
|
+
sdpMLineIndex: candidate.sdpMLineIndex,
|
|
416
|
+
});
|
|
417
|
+
wake(line);
|
|
418
|
+
};
|
|
419
|
+
peer.onconnectionstatechange = () => {
|
|
420
|
+
const state = peer.connectionState;
|
|
421
|
+
if (state === "connected") {
|
|
422
|
+
void wayOf(peer).then((way) =>
|
|
423
|
+
log(
|
|
424
|
+
`link: ${device.label || device.id} connected${way ? ` over ${way}` : ""}`
|
|
425
|
+
)
|
|
426
|
+
);
|
|
427
|
+
// Not queued behind the address lookups: a ".local" name can take seconds to resolve, and loopback settles it.
|
|
428
|
+
void cameInOnLoopback(peer).then(
|
|
429
|
+
(yes) => yes && decided(true, "loopback")
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
if (state !== "new" && state !== "connecting") wake(line);
|
|
433
|
+
if (state === "failed" || state === "closed") {
|
|
434
|
+
unanswered(line);
|
|
435
|
+
forget(key, line);
|
|
436
|
+
if (state === "failed") peer.close();
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
peer.ondatachannel = ({ channel }) => {
|
|
440
|
+
if (channel.label !== LINK_LABEL) return channel.close();
|
|
441
|
+
line.channel = channel;
|
|
442
|
+
serve(channel, device.id, line);
|
|
443
|
+
};
|
|
444
|
+
try {
|
|
445
|
+
await peer.setRemoteDescription({ type: "offer", sdp: input.sdp });
|
|
446
|
+
await peer.setLocalDescription(await peer.createAnswer());
|
|
447
|
+
} catch (error) {
|
|
448
|
+
forget(key, line);
|
|
449
|
+
peer.close();
|
|
450
|
+
return { ok: false, error: `the link offer failed: ${error.message}` };
|
|
451
|
+
}
|
|
452
|
+
return {
|
|
453
|
+
ok: true,
|
|
454
|
+
sdp: peer.localDescription.sdp,
|
|
455
|
+
candidates: line.found.splice(0),
|
|
456
|
+
};
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* The page's addresses found since its offer, and the ones found here since: answered as soon as this computer has
|
|
461
|
+
* one to give or the channel is connected (or failed). A page that never connects is answered by the relay's own
|
|
462
|
+
* deadline (a sealed call's 10 s), which ends its try.
|
|
463
|
+
*/
|
|
464
|
+
const candidates = async (device, input) => {
|
|
465
|
+
const line = lines.get(`${device.id}:${String(input?.session || "")}`);
|
|
466
|
+
if (!line) return { ok: false, error: "no link offer for that page" };
|
|
467
|
+
const given = Array.isArray(input?.candidates)
|
|
468
|
+
? input.candidates.slice(0, MAX_CANDIDATES)
|
|
469
|
+
: [];
|
|
470
|
+
line.lookAt?.(given.map((item) => addressOf(item?.candidate)));
|
|
471
|
+
for (const item of given)
|
|
472
|
+
await line.peer
|
|
473
|
+
.addIceCandidate({
|
|
474
|
+
candidate: String(item?.candidate ?? ""),
|
|
475
|
+
sdpMid: item?.sdpMid ?? null,
|
|
476
|
+
sdpMLineIndex: item?.sdpMLineIndex ?? null,
|
|
477
|
+
})
|
|
478
|
+
.catch(() => {});
|
|
479
|
+
const settled = () =>
|
|
480
|
+
line.found.length > 0 ||
|
|
481
|
+
!["new", "connecting"].includes(line.peer.connectionState);
|
|
482
|
+
if (!settled()) await new Promise((resolve) => line.waiting.add(resolve));
|
|
483
|
+
return {
|
|
484
|
+
ok: true,
|
|
485
|
+
candidates: line.found.splice(0),
|
|
486
|
+
state: line.peer.connectionState,
|
|
487
|
+
};
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Whether the page behind this channel runs on this machine (L4.7a), once the addresses it gave are looked at: true,
|
|
492
|
+
* false, or null when this computer cannot tell. Asked by the page itself ("link.here", phones.mjs).
|
|
493
|
+
*/
|
|
494
|
+
const here = async (device, input) => {
|
|
495
|
+
const line = lines.get(`${device.id}:${String(input?.session || "")}`);
|
|
496
|
+
if (!line) return { ok: false, error: "no link for that page" };
|
|
497
|
+
await Promise.race([line.looked, line.isHere]);
|
|
498
|
+
return { ok: true, here: line.here };
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
/** The browsers whose open channel comes from this machine: the ones this computer asks (L4.7c). */
|
|
502
|
+
const browsersHere = () => {
|
|
503
|
+
const ids = new Set();
|
|
504
|
+
for (const [key, line] of lines)
|
|
505
|
+
if (line.here === true && line.channel?.readyState === "open")
|
|
506
|
+
ids.add(key.split(":")[0]);
|
|
507
|
+
return ids;
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
/** Close every channel of one device (removed from the person's list) or, with no id, all of them. */
|
|
511
|
+
const close = (deviceId) => {
|
|
512
|
+
if (deviceId) browsersFoundHere.delete(deviceId);
|
|
513
|
+
else browsersFoundHere.clear();
|
|
514
|
+
for (const [key, line] of lines)
|
|
515
|
+
if (!deviceId || key.startsWith(`${deviceId}:`)) shut(key, line);
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* This computer's question to the person's open windows on this machine (phones.mjs ask), over the channels they
|
|
520
|
+
* hold: each window's envelope goes down each of its open channels found to be here, and the first answer that opens
|
|
521
|
+
* is the answer. A window that answered with a refusal gives that refusal when none opened. Null when no window here
|
|
522
|
+
* holds a channel or none answered in time: WINDOW_ASK_MS, or the question's own deadline (a door call's).
|
|
523
|
+
*/
|
|
524
|
+
const ask = (envelopes, { timeoutMs = WINDOW_ASK_MS } = {}) =>
|
|
525
|
+
new Promise((resolve) => {
|
|
526
|
+
const targets = [];
|
|
527
|
+
for (const envelope of envelopes)
|
|
528
|
+
for (const [key, line] of lines)
|
|
529
|
+
if (
|
|
530
|
+
key.startsWith(`${envelope.deviceId}:`) &&
|
|
531
|
+
line.here === true &&
|
|
532
|
+
line.channel?.readyState === "open"
|
|
533
|
+
)
|
|
534
|
+
targets.push({
|
|
535
|
+
line,
|
|
536
|
+
envelope,
|
|
537
|
+
id: randomBytes(12).toString("hex"),
|
|
538
|
+
});
|
|
539
|
+
if (!targets.length) return resolve(null);
|
|
540
|
+
let left = targets.length;
|
|
541
|
+
let refused = null;
|
|
542
|
+
const finish = (reply) => {
|
|
543
|
+
clearTimeout(timer);
|
|
544
|
+
for (const { line, id } of targets) line.asks.delete(id);
|
|
545
|
+
resolve(reply);
|
|
546
|
+
};
|
|
547
|
+
const timer = setTimeout(() => finish(null), timeoutMs);
|
|
548
|
+
for (const { line, envelope, id } of targets) {
|
|
549
|
+
line.usedAt = Date.now();
|
|
550
|
+
line.asks.set(id, (answer) => {
|
|
551
|
+
if (answer?.ok === true && answer.envelope)
|
|
552
|
+
return finish({
|
|
553
|
+
window: "open",
|
|
554
|
+
ok: true,
|
|
555
|
+
envelope: answer.envelope,
|
|
556
|
+
});
|
|
557
|
+
if (answer?.ok === false) refused = { window: "open", ...answer };
|
|
558
|
+
if (--left === 0) finish(refused);
|
|
559
|
+
});
|
|
560
|
+
const text = JSON.stringify({ id, ask: { envelopes: [envelope] } });
|
|
561
|
+
try {
|
|
562
|
+
for (const piece of piecesOf(id, text)) line.channel.send(piece);
|
|
563
|
+
} catch {
|
|
564
|
+
// Closed as it was asked: no answer from it.
|
|
565
|
+
line.asks.get(id)?.(null);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
return {
|
|
571
|
+
offer,
|
|
572
|
+
candidates,
|
|
573
|
+
here,
|
|
574
|
+
browsersHere,
|
|
575
|
+
ask,
|
|
576
|
+
close,
|
|
577
|
+
/** How many channels this computer holds: all, or one device's. */
|
|
578
|
+
count: (deviceId) =>
|
|
579
|
+
deviceId
|
|
580
|
+
? [...lines.keys()].filter((key) => key.startsWith(`${deviceId}:`))
|
|
581
|
+
.length
|
|
582
|
+
: lines.size,
|
|
583
|
+
};
|
|
584
|
+
}
|