@openllmsh/sdk 0.0.0-stage → 2.10.12-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +43 -0
- package/LICENSE +202 -0
- package/README.md +142 -2
- package/assets/openllm-light.svg +18 -0
- package/assets/openllm.svg +18 -0
- package/client/chat.ts +140 -0
- package/client/devices.ts +269 -0
- package/client/http.ts +72 -0
- package/client/index.ts +129 -0
- package/client/relay-mux.ts +547 -0
- package/client/types.ts +51 -0
- package/client/vault.ts +239 -0
- package/connect/chat.ts +58 -0
- package/connect/client.ts +240 -0
- package/connect/config.ts +47 -0
- package/connect/errors.ts +121 -0
- package/connect/index.ts +23 -0
- package/connect/oauth.ts +265 -0
- package/connect/routes.ts +234 -0
- package/connect/store.ts +107 -0
- package/mcp/handle.ts +24 -0
- package/mcp/index.ts +76 -0
- package/mcp/server.ts +319 -0
- package/mcp/tools/marketplace.ts +439 -0
- package/mcp/tools/memory-client.ts +297 -0
- package/mcp/tools/memory-config.ts +32 -0
- package/mcp/tools/memory.ts +369 -0
- package/mcp/tools/model-priority.ts +88 -0
- package/mcp/tools/openllm.ts +883 -0
- package/mcp/types.ts +28 -0
- package/openapi/call.ts +90 -0
- package/openapi/index.ts +8 -0
- package/openapi/openapi.json +80213 -0
- package/openapi/operations.ts +2075 -0
- package/package.json +39 -4
- package/protocol/CONTRIBUTING.md +21 -0
- package/protocol/README.md +134 -0
- package/protocol/access.ts +186 -0
- package/protocol/agent-prompt-text.ts +32 -0
- package/protocol/agent.ts +991 -0
- package/protocol/api-key-syntax.ts +105 -0
- package/protocol/assets/openllm-light.svg +18 -0
- package/protocol/assets/openllm.svg +18 -0
- package/protocol/audio.ts +29 -0
- package/protocol/auth.ts +142 -0
- package/protocol/changelog.ts +155 -0
- package/protocol/chat.ts +458 -0
- package/protocol/client-registry.ts +356 -0
- package/protocol/config.ts +345 -0
- package/protocol/control-channel.ts +115 -0
- package/protocol/cooldown-reason.ts +78 -0
- package/protocol/cost.ts +10 -0
- package/protocol/daemon-port.ts +31 -0
- package/protocol/daemon.ts +1524 -0
- package/protocol/default-chains.ts +66 -0
- package/protocol/device-state.ts +85 -0
- package/protocol/doctor-report-local.ts +443 -0
- package/protocol/doctor-report-policy.ts +119 -0
- package/protocol/doctor-report.ts +947 -0
- package/protocol/errors.ts +14 -0
- package/protocol/execution-selection.ts +141 -0
- package/protocol/hop-grant.ts +33 -0
- package/protocol/image-edit-parse.ts +263 -0
- package/protocol/images.ts +298 -0
- package/protocol/index.ts +74 -0
- package/protocol/inference-headers.ts +3 -0
- package/protocol/keepalive.ts +69 -0
- package/protocol/local-auth.ts +300 -0
- package/protocol/local-device-control.ts +133 -0
- package/protocol/local-provider.ts +288 -0
- package/protocol/local-session.ts +118 -0
- package/protocol/marketplace.ts +187 -0
- package/protocol/media-attempt.ts +81 -0
- package/protocol/media-bytes.ts +28 -0
- package/protocol/media-default.ts +357 -0
- package/protocol/media-dimensions.ts +132 -0
- package/protocol/media-input.ts +61 -0
- package/protocol/media-model.ts +142 -0
- package/protocol/media-option-issue.ts +90 -0
- package/protocol/media-types.ts +70 -0
- package/protocol/model-match.ts +1051 -0
- package/protocol/model-settings.ts +327 -0
- package/protocol/models.ts +767 -0
- package/protocol/mux.ts +722 -0
- package/protocol/plan-surface.ts +59 -0
- package/protocol/provider-models.ts +16 -0
- package/protocol/provider-status.ts +206 -0
- package/protocol/provider-tier.ts +67 -0
- package/protocol/provider-usage.ts +263 -0
- package/protocol/providers.ts +901 -0
- package/protocol/public-usage-index.ts +354 -0
- package/protocol/realtime-generated.ts +31 -0
- package/protocol/realtime.ts +324 -0
- package/protocol/registry-pointer.ts +118 -0
- package/protocol/relay.ts +702 -0
- package/protocol/replay-session.ts +11 -0
- package/protocol/responses.ts +280 -0
- package/protocol/semver.ts +182 -0
- package/protocol/setup-mode.ts +22 -0
- package/protocol/sha256-hex.ts +98 -0
- package/protocol/stats.ts +406 -0
- package/protocol/streaming.ts +19 -0
- package/protocol/subscription-daemon-floors.ts +33 -0
- package/protocol/subscription-provider-compat.ts +104 -0
- package/protocol/subscription-provider.ts +32 -0
- package/protocol/team-grant.ts +17 -0
- package/protocol/team-shareable.ts +61 -0
- package/protocol/transcription-encoding.ts +76 -0
- package/protocol/url-locality-dns.ts +37 -0
- package/protocol/url-locality.ts +288 -0
- package/protocol/usage-snapshots.ts +9 -0
- package/protocol/vendor-cli-install.ts +29 -0
- package/protocol/video-job-plan.ts +50 -0
- package/protocol/videos.ts +227 -0
- package/tsconfig.json +14 -0
- package/tunnel/ARCHITECTURE.md +111 -0
- package/tunnel/LICENSE +33 -0
- package/tunnel/README.md +45 -0
- package/tunnel/assets/openllm-light.svg +18 -0
- package/tunnel/assets/openllm.svg +18 -0
- package/tunnel/channel-envelope.ts +139 -0
- package/tunnel/codec.ts +191 -0
- package/tunnel/device-anchor.ts +229 -0
- package/tunnel/device-control.ts +118 -0
- package/tunnel/device-grant.ts +173 -0
- package/tunnel/fleet.ts +77 -0
- package/tunnel/index.ts +22 -0
- package/tunnel/mux.ts +580 -0
- package/tunnel/peer-link.ts +390 -0
- package/tunnel/rtc-auth.ts +415 -0
- package/tunnel/rtc-duplex.ts +187 -0
- package/tunnel/rtc-ice.ts +136 -0
- package/tunnel/secure.ts +1298 -0
- package/tunnel/stream-reset-error.ts +14 -0
- package/tunnel/streams.ts +1430 -0
- package/tunnel/team-grant.ts +302 -0
- package/tunnel/wire-bytes.ts +102 -0
- package/vault/ARCHITECTURE.md +470 -0
- package/vault/LICENSE +33 -0
- package/vault/api-key.ts +190 -0
- package/vault/argon2.ts +106 -0
- package/vault/cli-auth-seal.ts +157 -0
- package/vault/cred-seal.ts +146 -0
- package/vault/credential.ts +55 -0
- package/vault/crypto.ts +210 -0
- package/vault/daemon-attest.ts +229 -0
- package/vault/derive.ts +113 -0
- package/vault/device-access.ts +87 -0
- package/vault/device-anchor.ts +185 -0
- package/vault/device-control.ts +174 -0
- package/vault/handoff.ts +396 -0
- package/vault/index.ts +21 -0
- package/vault/passkey.ts +243 -0
- package/vault/phrase.ts +65 -0
- package/vault/pin.ts +153 -0
- package/vault/public-key-seal.ts +131 -0
- package/vault/seed.ts +272 -0
- package/vault/team.ts +355 -0
- package/vault/vault-item.ts +131 -0
- package/vault/vault-migrate-digest.ts +29 -0
- package/vault/wrapped.ts +77 -0
- package/wire/ARCHITECTURE.md +90 -0
- package/wire/CONTRIBUTING.md +19 -0
- package/wire/LICENSE +33 -0
- package/wire/README.md +51 -0
- package/wire/adapters/messages/anthropic-map.ts +37 -0
- package/wire/adapters/messages/index.ts +7 -0
- package/wire/adapters/messages/reasoning-from-items.ts +38 -0
- package/wire/adapters/messages/reasoning-signature.ts +243 -0
- package/wire/adapters/messages/request.ts +574 -0
- package/wire/adapters/messages/response.ts +215 -0
- package/wire/adapters/messages/streaming.ts +1027 -0
- package/wire/adapters/messages/usage.ts +43 -0
- package/wire/adapters/responses/index.ts +3 -0
- package/wire/adapters/responses/request.ts +395 -0
- package/wire/adapters/responses/response.ts +88 -0
- package/wire/adapters/responses/streaming.ts +344 -0
- package/wire/assets/openllm-light.svg +18 -0
- package/wire/assets/openllm.svg +18 -0
- package/wire/features/account-rank.ts +166 -0
- package/wire/features/compaction/compact-request.ts +862 -0
- package/wire/features/compaction/compaction-text.ts +43 -0
- package/wire/features/context-demote.ts +47 -0
- package/wire/features/context-overflow-strategy.ts +26 -0
- package/wire/features/context-skip.ts +170 -0
- package/wire/features/conversation-affinity.ts +144 -0
- package/wire/features/max-tokens-backfill.ts +141 -0
- package/wire/features/model-caps.ts +53 -0
- package/wire/features/model-settings.ts +24 -0
- package/wire/features/output-limit-clamp.ts +64 -0
- package/wire/features/quota-gate.ts +85 -0
- package/wire/index.ts +44 -0
- package/wire/lib/attempt-outcome.ts +43 -0
- package/wire/lib/canonical/content-part.ts +38 -0
- package/wire/lib/canonical/count-tokens-capability.ts +138 -0
- package/wire/lib/canonical/encoding-select.ts +82 -0
- package/wire/lib/canonical/image-signature.ts +202 -0
- package/wire/lib/canonical/image-sse.ts +216 -0
- package/wire/lib/canonical/message.ts +43 -0
- package/wire/lib/canonical/token-estimate.ts +266 -0
- package/wire/lib/encrypted-content.ts +66 -0
- package/wire/lib/error-class.ts +154 -0
- package/wire/lib/error-envelope.ts +56 -0
- package/wire/lib/forwarded-headers.ts +180 -0
- package/wire/lib/provider-error-rules.ts +48 -0
- package/wire/lib/refusal.ts +38 -0
- package/wire/lib/responses-apply-patch.ts +104 -0
- package/wire/lib/responses-namespace.ts +53 -0
- package/wire/lib/secret-scrub.ts +101 -0
- package/wire/lib/streaming/accumulate.ts +221 -0
- package/wire/lib/streaming/finish-reason.ts +33 -0
- package/wire/lib/streaming/peek.ts +154 -0
- package/wire/lib/streaming/provider-decode.ts +259 -0
- package/wire/lib/streaming/response-stream.ts +71 -0
- package/wire/lib/streaming/sse.ts +699 -0
- package/wire/lib/streaming/strip-tool-calls.ts +95 -0
- package/wire/lib/streaming/upstream-error.ts +58 -0
- package/wire/lib/strip-subagent-isolation.ts +284 -0
- package/wire/lib/thinking-signature.ts +156 -0
- package/wire/lib/token-ruler/bpe-core.ts +426 -0
- package/wire/lib/token-ruler/index.ts +2 -0
- package/wire/lib/token-ruler/ruler.ts +79 -0
- package/wire/lib/token-ruler/vocab/claude-ranks.ts +16 -0
- package/wire/lib/token-ruler/vocab/claude.ts +22 -0
- package/wire/lib/token-ruler/vocab/o200k-ranks.ts +18 -0
- package/wire/lib/token-ruler/vocab/o200k.ts +19 -0
- package/wire/lib/tool-name-map.ts +271 -0
- package/wire/lib/tool-schema.ts +353 -0
- package/wire/lib/usage-observer.ts +125 -0
- package/wire/providers/anthropic/adaptive-thinking.ts +291 -0
- package/wire/providers/anthropic/beta-headers.ts +165 -0
- package/wire/providers/anthropic/index.ts +10 -0
- package/wire/providers/anthropic/request.ts +607 -0
- package/wire/providers/anthropic/response.ts +155 -0
- package/wire/providers/anthropic/streaming.ts +315 -0
- package/wire/providers/anthropic/web-search-domains.ts +49 -0
- package/wire/providers/chatgpt/common.ts +136 -0
- package/wire/providers/chatgpt/index.ts +9 -0
- package/wire/providers/chatgpt/request.ts +959 -0
- package/wire/providers/chatgpt/streaming.ts +1007 -0
- package/wire/providers/chatgpt/web-search.ts +63 -0
- package/wire/providers/grok/web-search.ts +87 -0
- package/wire/providers/kimi/web-search.ts +145 -0
- package/wire/providers/upstream-deny.ts +355 -0
- package/wire/providers/upstream-request.ts +619 -0
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure RTC fingerprint-binding helpers for the browser⇄daemon data channel.
|
|
3
|
+
*
|
|
4
|
+
* Trust root: the daemon's long-lived X25519 public key (published on
|
|
5
|
+
* DaemonStatus, pinned by the browser via the cloud status path). The relay
|
|
6
|
+
* only carries SDP + sealed proofs and must not be able to MITM DTLS.
|
|
7
|
+
*
|
|
8
|
+
* Protocol (sealed-box challenge/response, no new crypto primitives):
|
|
9
|
+
* 1. Browser mints nonce N (16B), reads its DTLS fingerprint Fb, generates
|
|
10
|
+
* an ephemeral X25519 keypair, and seals the offer inner to the daemon
|
|
11
|
+
* pubkey. That ciphertext is `fingerprint_proof` on `rtc_offer`
|
|
12
|
+
* (alongside the SDP offer).
|
|
13
|
+
* 2. Daemon opens the seal with its private key, checks shape, then seals
|
|
14
|
+
* { v:1, n, fb, fd }
|
|
15
|
+
* to the browser's ephemeral pubkey. That ciphertext is
|
|
16
|
+
* `fingerprint_proof` on `rtc_answer`.
|
|
17
|
+
* 3. Browser opens the answer seal, checks N matches (replay), Fb matches
|
|
18
|
+
* its local fingerprint, and Fd matches the fingerprint in the answer
|
|
19
|
+
* SDP — only then completes DTLS / marks the channel open.
|
|
20
|
+
*
|
|
21
|
+
* Offer-inner version:
|
|
22
|
+
* - v2 `{v:2, n, fb, epk, grant, team_grant?}` — nested full device-grant
|
|
23
|
+
* envelope (base64 from `encodeDeviceGrant`). Reuses standard grant validation
|
|
24
|
+
* (ts window, nonce, key_id, cid, aud, sig) with `cid=channel_id` and
|
|
25
|
+
* `aud=daemon_pubkey`. Sealing to the daemon's public key authenticates
|
|
26
|
+
* nobody, so a `dpk` grant also signs `use: "rtc"` and `bind = fb`: a
|
|
27
|
+
* grant harvested from a plaintext `channel_open` cannot ride an offer
|
|
28
|
+
* carrying someone else's DTLS fingerprint.
|
|
29
|
+
*
|
|
30
|
+
* Hosts supply seal/open via the existing sealed-box implementations
|
|
31
|
+
* (`lib/daemon-seal.ts` / `packages/cli/daemon/src/keypair.ts`). Fingerprint
|
|
32
|
+
* strings are normalized (lowercase, strip separators) so SDP
|
|
33
|
+
* `a=fingerprint:sha-256 AA:BB:…` and bare hex compare equal.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import type { TIceServer } from "@openllmsh/sdk/protocol";
|
|
37
|
+
import { FRAME_HEADER_BYTES } from "./codec";
|
|
38
|
+
import { isB64OfLength, isNonEmptyString } from "./wire-bytes";
|
|
39
|
+
|
|
40
|
+
export const RTC_AUTH_VERSION = 2 as const;
|
|
41
|
+
/** Default STUN server shared by browser and daemon RTC peers. */
|
|
42
|
+
export const RTC_DEFAULT_STUN = "stun:stun.l.google.com:19302";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Default STUN fallback list for STUN-only sessions.
|
|
46
|
+
*
|
|
47
|
+
* Keep multiple independent providers here so a single provider failure does not
|
|
48
|
+
* zero out server-reflexive candidates. This is a resilience improvement for
|
|
49
|
+
* provider diversity, but it does not replace TURN for fully UDP-blocked
|
|
50
|
+
* networks.
|
|
51
|
+
*/
|
|
52
|
+
export const RTC_DEFAULT_STUN_SERVERS: ReadonlyArray<string> = [
|
|
53
|
+
RTC_DEFAULT_STUN,
|
|
54
|
+
"stun:stun1.l.google.com:19302",
|
|
55
|
+
"stun:stun.cloudflare.com:3478",
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
/** Return a fresh default ICE configuration for callers that need STUN-only. */
|
|
59
|
+
export const defaultIceServers = (): ReadonlyArray<TIceServer> =>
|
|
60
|
+
RTC_DEFAULT_STUN_SERVERS.map((url) => ({ urls: url }));
|
|
61
|
+
|
|
62
|
+
/** Map immutable protocol ICE entries into werift's mutable input shape. */
|
|
63
|
+
export const weriftIceServers = (
|
|
64
|
+
servers: ReadonlyArray<TIceServer>,
|
|
65
|
+
): Array<{
|
|
66
|
+
urls: string | string[];
|
|
67
|
+
username?: string;
|
|
68
|
+
credential?: string;
|
|
69
|
+
}> =>
|
|
70
|
+
servers.map((server) => ({
|
|
71
|
+
urls: typeof server.urls === "string" ? server.urls : [...server.urls],
|
|
72
|
+
...(server.username !== undefined ? { username: server.username } : {}),
|
|
73
|
+
...(server.credential !== undefined
|
|
74
|
+
? { credential: server.credential }
|
|
75
|
+
: {}),
|
|
76
|
+
}));
|
|
77
|
+
|
|
78
|
+
const isIceUrl = (value: string): boolean => {
|
|
79
|
+
try {
|
|
80
|
+
const url = new URL(value);
|
|
81
|
+
return ["stun:", "stuns:", "turn:", "turns:"].includes(url.protocol);
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const iceUrls = (value: unknown): string | string[] | null => {
|
|
88
|
+
if (typeof value === "string") {
|
|
89
|
+
const url = value.trim();
|
|
90
|
+
return isIceUrl(url) ? url : null;
|
|
91
|
+
}
|
|
92
|
+
if (!Array.isArray(value)) return null;
|
|
93
|
+
const urls = value
|
|
94
|
+
.filter((url): url is string => typeof url === "string")
|
|
95
|
+
.map((url) => url.trim())
|
|
96
|
+
.filter(isIceUrl);
|
|
97
|
+
return urls.length > 0 ? urls : null;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/** Parse an ICE-server configuration string into RTCPeerConnection entries.
|
|
101
|
+
*
|
|
102
|
+
* Accepts, in order of precedence of the input shape:
|
|
103
|
+
* - undefined / empty → the default Google STUN entry;
|
|
104
|
+
* - a JSON array of ice-server objects
|
|
105
|
+
* (`[{urls, username?, credential?}, …]` — the TURN-ready form served by
|
|
106
|
+
* the cloud via the `/api/daemon/channel` handshake and set directly via
|
|
107
|
+
* `OPENLLM_RTC_ICE_SERVERS`);
|
|
108
|
+
* - a legacy comma-separated STUN URL list (the historical
|
|
109
|
+
* `OPENLLM_RTC_STUN` form).
|
|
110
|
+
*
|
|
111
|
+
* Malformed input (bad JSON, wrong shape, no usable urls) falls back to the
|
|
112
|
+
* default so a config typo degrades to STUN-only instead of killing RTC. */
|
|
113
|
+
export const parseIceServers = (
|
|
114
|
+
raw: string | undefined,
|
|
115
|
+
): ReadonlyArray<TIceServer> => {
|
|
116
|
+
const trimmed = raw?.trim();
|
|
117
|
+
if (trimmed === undefined || trimmed.length === 0) return defaultIceServers();
|
|
118
|
+
if (trimmed.startsWith("[")) {
|
|
119
|
+
try {
|
|
120
|
+
const parsed: unknown = JSON.parse(trimmed);
|
|
121
|
+
if (Array.isArray(parsed)) {
|
|
122
|
+
const servers: TIceServer[] = [];
|
|
123
|
+
for (const entry of parsed) {
|
|
124
|
+
if (entry === null || typeof entry !== "object") continue;
|
|
125
|
+
const record = entry as Record<string, unknown>;
|
|
126
|
+
const urls = iceUrls(record.urls);
|
|
127
|
+
if (urls === null) continue;
|
|
128
|
+
const username =
|
|
129
|
+
typeof record.username === "string" &&
|
|
130
|
+
record.username.trim().length > 0
|
|
131
|
+
? record.username.trim()
|
|
132
|
+
: undefined;
|
|
133
|
+
const credential =
|
|
134
|
+
typeof record.credential === "string" &&
|
|
135
|
+
record.credential.trim().length > 0
|
|
136
|
+
? record.credential.trim()
|
|
137
|
+
: undefined;
|
|
138
|
+
servers.push({
|
|
139
|
+
urls,
|
|
140
|
+
...(username !== undefined ? { username } : {}),
|
|
141
|
+
...(credential !== undefined ? { credential } : {}),
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
if (servers.length > 0) return servers;
|
|
145
|
+
}
|
|
146
|
+
} catch {
|
|
147
|
+
// fall through to the default — a malformed JSON list must not kill RTC
|
|
148
|
+
}
|
|
149
|
+
return defaultIceServers();
|
|
150
|
+
}
|
|
151
|
+
const legacy = trimmed
|
|
152
|
+
.split(",")
|
|
153
|
+
.map((value) => value.trim())
|
|
154
|
+
.filter(isIceUrl)
|
|
155
|
+
.map((urls) => ({ urls }));
|
|
156
|
+
return legacy.length > 0 ? legacy : defaultIceServers();
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/** Resolve the effective ICE servers for an RTC peer, in precedence order:
|
|
160
|
+
* 1. a locally-set env value (`OPENLLM_RTC_ICE_SERVERS`, or the legacy
|
|
161
|
+
* `OPENLLM_RTC_STUN` STUN list) — parsed via {@link parseIceServers};
|
|
162
|
+
* 2. the cloud-served `ice_servers` from the channel handshake;
|
|
163
|
+
* 3. the default STUN entry.
|
|
164
|
+
* Shared by both daemon RTC ends so browser/daemon agree on the surface. */
|
|
165
|
+
export const resolveIceServers = (
|
|
166
|
+
envRaw: string | undefined,
|
|
167
|
+
handshake: ReadonlyArray<TIceServer> | null,
|
|
168
|
+
): ReadonlyArray<TIceServer> => {
|
|
169
|
+
const trimmed = envRaw?.trim();
|
|
170
|
+
if (trimmed !== undefined && trimmed.length > 0) {
|
|
171
|
+
return parseIceServers(trimmed);
|
|
172
|
+
}
|
|
173
|
+
if (handshake !== null && handshake.length > 0) return handshake;
|
|
174
|
+
return defaultIceServers();
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
/** 16 random bytes, base64-encoded in the inner JSON. */
|
|
178
|
+
export const RTC_AUTH_NONCE_BYTES = 16;
|
|
179
|
+
/**
|
|
180
|
+
* Floor for the negotiated mux DATA payload under SCTP. Matches the plan's
|
|
181
|
+
* "safe floor if SDP omits max-message-size".
|
|
182
|
+
*/
|
|
183
|
+
export const RTC_SAFE_MAX_PAYLOAD_BYTES = 16 * 1024;
|
|
184
|
+
/** Header bytes reserved so a mux frame fits inside an SCTP message. */
|
|
185
|
+
export const RTC_MUX_HEADER_OVERHEAD = FRAME_HEADER_BYTES;
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Current offer inner. `grant` is the full `encodeDeviceGrant(...)` envelope
|
|
189
|
+
* string (base64 JSON). Nested rather than flat sig fields so the daemon
|
|
190
|
+
* reuses `checkDeviceGrant` (ts window, nonce LRU, key_id/cid/aud/sig)
|
|
191
|
+
* without a parallel validation path.
|
|
192
|
+
*/
|
|
193
|
+
export type TRtcOfferInner = {
|
|
194
|
+
readonly v: typeof RTC_AUTH_VERSION;
|
|
195
|
+
readonly n: string;
|
|
196
|
+
readonly fb: string;
|
|
197
|
+
readonly epk: string;
|
|
198
|
+
/** Full device-grant envelope (base64), required only for browser offers. */
|
|
199
|
+
readonly grant?: string;
|
|
200
|
+
/** Opaque origin-signed team grant, sealed end-to-end with the offer. */
|
|
201
|
+
readonly teamGrant?: string;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
export type TRtcAnswerInner = {
|
|
205
|
+
readonly v: typeof RTC_AUTH_VERSION;
|
|
206
|
+
readonly n: string;
|
|
207
|
+
/** echo of the browser fingerprint (normalized) */
|
|
208
|
+
readonly fb: string;
|
|
209
|
+
/** daemon DTLS fingerprint (normalized) */
|
|
210
|
+
readonly fd: string;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
/** Strip algorithm prefix + separators; lowercase. Empty input → "". */
|
|
214
|
+
export const normalizeFingerprint = (raw: string): string => {
|
|
215
|
+
const trimmed = raw.trim();
|
|
216
|
+
// SDP form: "sha-256 AA:BB:..." or just "AA:BB:..."
|
|
217
|
+
const withoutAlgo = trimmed.includes(" ")
|
|
218
|
+
? (trimmed.split(/\s+/).pop() ?? "")
|
|
219
|
+
: trimmed;
|
|
220
|
+
return withoutAlgo.replace(/:/g, "").toLowerCase();
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Extract effective DTLS fingerprints from an SDP blob.
|
|
225
|
+
*
|
|
226
|
+
* Returns all `a=fingerprint:` lines from the first `m=application` section that has
|
|
227
|
+
* fingerprints; otherwise returns session-level fingerprints (before any `m=`). The
|
|
228
|
+
* values are raw (algorithm + hex) and preserve order.
|
|
229
|
+
*/
|
|
230
|
+
export const fingerprintsFromSdp = (sdp: string): readonly string[] => {
|
|
231
|
+
const sessionFingerprints: string[] = [];
|
|
232
|
+
let applicationFingerprints: string[] | null = null;
|
|
233
|
+
let inApplicationSection = false;
|
|
234
|
+
let hasMediaSection = false;
|
|
235
|
+
|
|
236
|
+
for (const line of sdp.split(/\r?\n/)) {
|
|
237
|
+
const trimmed = line.trim();
|
|
238
|
+
const media = /^m=([^\s]+)/i.exec(trimmed);
|
|
239
|
+
if (media !== null) {
|
|
240
|
+
hasMediaSection = true;
|
|
241
|
+
inApplicationSection = media[1].toLowerCase() === "application";
|
|
242
|
+
if (inApplicationSection && applicationFingerprints === null) {
|
|
243
|
+
applicationFingerprints = [];
|
|
244
|
+
}
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const match = /^a=fingerprint:(.+)$/i.exec(trimmed);
|
|
249
|
+
if (match === null) continue;
|
|
250
|
+
if (inApplicationSection) {
|
|
251
|
+
applicationFingerprints?.push(match[1].trim());
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (!hasMediaSection) {
|
|
255
|
+
sessionFingerprints.push(match[1].trim());
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return applicationFingerprints !== null && applicationFingerprints.length > 0
|
|
260
|
+
? applicationFingerprints
|
|
261
|
+
: sessionFingerprints;
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* True when the effective SDP fingerprint set is non-empty and every entry
|
|
266
|
+
* matches the sealed/claimed fingerprint after normalization. Conflicting
|
|
267
|
+
* fingerprint lines are rejected rather than accepting a matching subset.
|
|
268
|
+
*/
|
|
269
|
+
export const sdpFingerprintsMatch = (
|
|
270
|
+
sdp: string,
|
|
271
|
+
claimedFingerprint: string,
|
|
272
|
+
): boolean => {
|
|
273
|
+
const claimed = normalizeFingerprint(claimedFingerprint);
|
|
274
|
+
const fingerprints = fingerprintsFromSdp(sdp);
|
|
275
|
+
return (
|
|
276
|
+
claimed.length > 0 &&
|
|
277
|
+
fingerprints.length > 0 &&
|
|
278
|
+
fingerprints.every(
|
|
279
|
+
(fingerprint) => normalizeFingerprint(fingerprint) === claimed,
|
|
280
|
+
)
|
|
281
|
+
);
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Extract `a=fingerprint:` value from an SDP blob. Returns the first raw value from
|
|
286
|
+
* the effective set (session-level or `m=application`) or null if absent. Caller
|
|
287
|
+
* normalizes for comparison.
|
|
288
|
+
*/
|
|
289
|
+
export const fingerprintFromSdp = (sdp: string): string | null => {
|
|
290
|
+
const fingerprints = fingerprintsFromSdp(sdp);
|
|
291
|
+
return fingerprints.length > 0 ? fingerprints[0] : null;
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Extract SCTP `a=max-message-size:` from SDP. Returns null if absent or
|
|
296
|
+
* unparseable. Some browsers omit it (then use {@link RTC_SAFE_MAX_PAYLOAD_BYTES}).
|
|
297
|
+
*/
|
|
298
|
+
export const maxMessageSizeFromSdp = (sdp: string): number | null => {
|
|
299
|
+
for (const line of sdp.split(/\r?\n/)) {
|
|
300
|
+
const m = /^a=max-message-size:(\d+)$/i.exec(line.trim());
|
|
301
|
+
if (m !== null) {
|
|
302
|
+
const n = Number(m[1]);
|
|
303
|
+
if (Number.isFinite(n) && n > 0) return n;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return null;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Mux DATA payload cap for an RTC channel: min(SDP max-message-size − header,
|
|
311
|
+
* MAX_PAYLOAD_BYTES) with a safe floor when SDP omits the attribute.
|
|
312
|
+
* `wireMax` is typically {@link MAX_PAYLOAD_BYTES} from the codec.
|
|
313
|
+
*
|
|
314
|
+
* Returns `null` when the advertised SCTP limit cannot fit even a 1-byte DATA
|
|
315
|
+
* frame (limit ≤ header overhead) — callers must abort session setup rather
|
|
316
|
+
* than mount a mux that can never drain.
|
|
317
|
+
*/
|
|
318
|
+
export const negotiateRtcPayloadCap = (
|
|
319
|
+
sdpMaxMessageSize: number | null,
|
|
320
|
+
wireMax: number,
|
|
321
|
+
): number | null => {
|
|
322
|
+
if (sdpMaxMessageSize === null) {
|
|
323
|
+
return Math.min(RTC_SAFE_MAX_PAYLOAD_BYTES, wireMax);
|
|
324
|
+
}
|
|
325
|
+
const usable = sdpMaxMessageSize - RTC_MUX_HEADER_OVERHEAD;
|
|
326
|
+
if (usable < 1) return null;
|
|
327
|
+
return Math.min(usable, wireMax);
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
const isValidNonce = (value: unknown): value is string =>
|
|
331
|
+
isB64OfLength(value, RTC_AUTH_NONCE_BYTES);
|
|
332
|
+
|
|
333
|
+
export const encodeOfferInner = (inner: TRtcOfferInner): string =>
|
|
334
|
+
JSON.stringify({
|
|
335
|
+
v: RTC_AUTH_VERSION,
|
|
336
|
+
n: inner.n,
|
|
337
|
+
fb: normalizeFingerprint(inner.fb),
|
|
338
|
+
epk: inner.epk,
|
|
339
|
+
...(inner.grant !== undefined ? { grant: inner.grant } : {}),
|
|
340
|
+
...(inner.teamGrant !== undefined ? { team_grant: inner.teamGrant } : {}),
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
export const decodeOfferInner = (json: string): TRtcOfferInner | null => {
|
|
344
|
+
try {
|
|
345
|
+
const parsed: unknown = JSON.parse(json);
|
|
346
|
+
if (parsed === null || typeof parsed !== "object") return null;
|
|
347
|
+
const o = parsed as Record<string, unknown>;
|
|
348
|
+
if (
|
|
349
|
+
!isValidNonce(o.n) ||
|
|
350
|
+
!isNonEmptyString(o.fb) ||
|
|
351
|
+
!isNonEmptyString(o.epk)
|
|
352
|
+
) {
|
|
353
|
+
return null;
|
|
354
|
+
}
|
|
355
|
+
if (o.v !== RTC_AUTH_VERSION) return null;
|
|
356
|
+
return {
|
|
357
|
+
v: RTC_AUTH_VERSION,
|
|
358
|
+
n: o.n,
|
|
359
|
+
fb: normalizeFingerprint(o.fb),
|
|
360
|
+
epk: o.epk,
|
|
361
|
+
...(isNonEmptyString(o.grant) ? { grant: o.grant } : {}),
|
|
362
|
+
...(isNonEmptyString(o.team_grant) ? { teamGrant: o.team_grant } : {}),
|
|
363
|
+
};
|
|
364
|
+
} catch {
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
export const encodeAnswerInner = (inner: TRtcAnswerInner): string =>
|
|
370
|
+
JSON.stringify({
|
|
371
|
+
v: RTC_AUTH_VERSION,
|
|
372
|
+
n: inner.n,
|
|
373
|
+
fb: normalizeFingerprint(inner.fb),
|
|
374
|
+
fd: normalizeFingerprint(inner.fd),
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
export const decodeAnswerInner = (json: string): TRtcAnswerInner | null => {
|
|
378
|
+
try {
|
|
379
|
+
const parsed: unknown = JSON.parse(json);
|
|
380
|
+
if (parsed === null || typeof parsed !== "object") return null;
|
|
381
|
+
const o = parsed as Record<string, unknown>;
|
|
382
|
+
if (o.v !== RTC_AUTH_VERSION) return null;
|
|
383
|
+
if (
|
|
384
|
+
!isNonEmptyString(o.n) ||
|
|
385
|
+
!isNonEmptyString(o.fb) ||
|
|
386
|
+
!isNonEmptyString(o.fd)
|
|
387
|
+
) {
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
return {
|
|
391
|
+
v: RTC_AUTH_VERSION,
|
|
392
|
+
n: o.n,
|
|
393
|
+
fb: normalizeFingerprint(o.fb),
|
|
394
|
+
fd: normalizeFingerprint(o.fd),
|
|
395
|
+
};
|
|
396
|
+
} catch {
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Browser-side check of a decoded answer against the offer it sent and the
|
|
403
|
+
* fingerprints observed in local/remote SDP.
|
|
404
|
+
*/
|
|
405
|
+
export const verifyAnswerInner = (
|
|
406
|
+
answer: TRtcAnswerInner,
|
|
407
|
+
expected: {
|
|
408
|
+
readonly nonce: string;
|
|
409
|
+
readonly browserFingerprint: string;
|
|
410
|
+
readonly daemonFingerprint: string;
|
|
411
|
+
},
|
|
412
|
+
): boolean =>
|
|
413
|
+
answer.n === expected.nonce &&
|
|
414
|
+
answer.fb === normalizeFingerprint(expected.browserFingerprint) &&
|
|
415
|
+
answer.fd === normalizeFingerprint(expected.daemonFingerprint);
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ~20-line TDuplex over an RTCDataChannel (browser DOM or werift).
|
|
3
|
+
*
|
|
4
|
+
* The mux contract is message-oriented: one complete binary message per
|
|
5
|
+
* `onBytes` call. RTCDataChannel is already message-oriented when used with
|
|
6
|
+
* binary payloads, so this adapter only bridges the event surface.
|
|
7
|
+
*
|
|
8
|
+
* werift notes (v0.24.x, verified under Bun):
|
|
9
|
+
* - no `binaryType` property — payloads arrive as Buffer/Uint8Array via
|
|
10
|
+
* `onmessage` callback (or addEventListener where available);
|
|
11
|
+
* - `onmessage` receives `{ data: string | Buffer }`.
|
|
12
|
+
*
|
|
13
|
+
* Callers must set an ordered, negotiated (or offerer-created) data channel
|
|
14
|
+
* and open it before the mux starts writing. Closing the duplex closes the
|
|
15
|
+
* channel; a null `onBytes` delivery signals peer death to the mux.
|
|
16
|
+
*/
|
|
17
|
+
import type { TDuplex } from "./mux";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Minimal surface shared by the browser `RTCDataChannel` and werift's channel.
|
|
21
|
+
* Intentionally narrower than the full DOM type so werift is assignable without
|
|
22
|
+
* casting at every call site.
|
|
23
|
+
*/
|
|
24
|
+
export type TRtcDataChannelLike = {
|
|
25
|
+
readonly readyState: string;
|
|
26
|
+
readonly bufferedAmount: number;
|
|
27
|
+
bufferedAmountLowThreshold?: number;
|
|
28
|
+
send: (data: string | ArrayBuffer | ArrayBufferView) => void;
|
|
29
|
+
close: () => void;
|
|
30
|
+
/**
|
|
31
|
+
* DOM: EventTarget. werift: may only expose the `onmessage` property. We
|
|
32
|
+
* prefer addEventListener when present and fall back to the property.
|
|
33
|
+
*/
|
|
34
|
+
addEventListener?: (
|
|
35
|
+
type: string,
|
|
36
|
+
listener: (event: { data: unknown }) => void,
|
|
37
|
+
) => void;
|
|
38
|
+
removeEventListener?: (
|
|
39
|
+
type: string,
|
|
40
|
+
listener: (event: { data: unknown }) => void,
|
|
41
|
+
) => void;
|
|
42
|
+
onmessage: ((event: { data: unknown }) => void) | null;
|
|
43
|
+
onclose: ((event?: unknown) => void) | null;
|
|
44
|
+
onerror: ((event?: unknown) => void) | null;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const toUint8 = (data: unknown): Uint8Array | null => {
|
|
48
|
+
if (data instanceof Uint8Array) return data;
|
|
49
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
50
|
+
if (ArrayBuffer.isView(data)) {
|
|
51
|
+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
52
|
+
}
|
|
53
|
+
// Text payloads are not part of the mux contract — drop them.
|
|
54
|
+
return null;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Wrap an open (or soon-to-open) data channel as a {@link TDuplex}.
|
|
59
|
+
*
|
|
60
|
+
* Sends that fire before `readyState === "open"` are dropped (the mux only
|
|
61
|
+
* writes after the channel is open in practice; a defensive no-op keeps a
|
|
62
|
+
* racy close from throwing into the mux state machine).
|
|
63
|
+
*/
|
|
64
|
+
export const rtcDuplex = (dc: TRtcDataChannelLike): TDuplex => {
|
|
65
|
+
let listener: ((bytes: Uint8Array | null) => void) | null = null;
|
|
66
|
+
const drainListeners = new Set<() => void>();
|
|
67
|
+
let peerGone = false;
|
|
68
|
+
let channelClosed = false;
|
|
69
|
+
let drainPoll: ReturnType<typeof setInterval> | null = null;
|
|
70
|
+
const highWaterMark = 1024 * 1024;
|
|
71
|
+
const lowWaterMark = highWaterMark / 2;
|
|
72
|
+
try {
|
|
73
|
+
dc.bufferedAmountLowThreshold = lowWaterMark;
|
|
74
|
+
} catch {
|
|
75
|
+
// werift versions without the DOM setter still expose bufferedAmount.
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const stopDrainPoll = (): void => {
|
|
79
|
+
if (drainPoll === null) return;
|
|
80
|
+
clearInterval(drainPoll);
|
|
81
|
+
drainPoll = null;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const closeChannel = (): void => {
|
|
85
|
+
if (channelClosed) return;
|
|
86
|
+
channelClosed = true;
|
|
87
|
+
stopDrainPoll();
|
|
88
|
+
try {
|
|
89
|
+
dc.close();
|
|
90
|
+
} catch {
|
|
91
|
+
// already closed
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const deliver = (bytes: Uint8Array | null): void => {
|
|
96
|
+
try {
|
|
97
|
+
listener?.(bytes);
|
|
98
|
+
} catch {
|
|
99
|
+
// Mux onBytes boundary is never allowed to throw into the host.
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const onMessage = (event: { data: unknown }): void => {
|
|
104
|
+
// Local close marks channelClosed before peer events drain; ignore any
|
|
105
|
+
// queued message after closeChannel() so deliver() cannot run post-close.
|
|
106
|
+
if (channelClosed || peerGone) return;
|
|
107
|
+
const bytes = toUint8(event.data);
|
|
108
|
+
if (bytes === null) return;
|
|
109
|
+
deliver(bytes);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const onPeerGone = (): void => {
|
|
113
|
+
// Same post-close guard as onMessage — a queued close/error must not
|
|
114
|
+
// deliver terminal null after the local side already closed the channel.
|
|
115
|
+
if (channelClosed || peerGone) return;
|
|
116
|
+
peerGone = true;
|
|
117
|
+
stopDrainPoll();
|
|
118
|
+
// Deliver AFTER flipping peerGone so re-entrant close is a no-op, but the
|
|
119
|
+
// terminal null still reaches the mux.
|
|
120
|
+
deliver(null);
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const onBufferedAmountLow = (): void => {
|
|
124
|
+
for (const callback of drainListeners) callback();
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const supportsDrainEvent = typeof dc.addEventListener === "function";
|
|
128
|
+
const startDrainPoll = (): void => {
|
|
129
|
+
if (supportsDrainEvent || drainPoll !== null) return;
|
|
130
|
+
drainPoll = setInterval(() => {
|
|
131
|
+
if (channelClosed || peerGone || drainListeners.size === 0) {
|
|
132
|
+
stopDrainPoll();
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (dc.bufferedAmount <= lowWaterMark) onBufferedAmountLow();
|
|
136
|
+
}, 25);
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
if (supportsDrainEvent) {
|
|
140
|
+
dc.addEventListener?.("message", onMessage);
|
|
141
|
+
dc.addEventListener?.("close", onPeerGone);
|
|
142
|
+
dc.addEventListener?.("error", onPeerGone);
|
|
143
|
+
dc.addEventListener?.("bufferedamountlow", onBufferedAmountLow);
|
|
144
|
+
} else {
|
|
145
|
+
dc.onmessage = onMessage;
|
|
146
|
+
dc.onclose = onPeerGone;
|
|
147
|
+
dc.onerror = onPeerGone;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
send: (bytes) => {
|
|
152
|
+
if (peerGone || channelClosed) return;
|
|
153
|
+
if (dc.readyState !== "open") {
|
|
154
|
+
// Non-open (closing/closed/connecting) is a transport failure: mux
|
|
155
|
+
// resolves write() once duplex.send returns, so silent drop would
|
|
156
|
+
// look like success while bytes vanish and flow-control credit is
|
|
157
|
+
// consumed. Surface peer-gone so the mux tears streams down.
|
|
158
|
+
onPeerGone();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
// Pass a copy-friendly view; WebRTC/werift copy into the SCTP stack.
|
|
163
|
+
dc.send(bytes);
|
|
164
|
+
} catch {
|
|
165
|
+
onPeerGone();
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
bufferedAmount: () => dc.bufferedAmount,
|
|
169
|
+
highWaterMark,
|
|
170
|
+
onDrain: (callback) => {
|
|
171
|
+
drainListeners.add(callback);
|
|
172
|
+
startDrainPoll();
|
|
173
|
+
return () => {
|
|
174
|
+
drainListeners.delete(callback);
|
|
175
|
+
if (drainListeners.size === 0) stopDrainPoll();
|
|
176
|
+
};
|
|
177
|
+
},
|
|
178
|
+
onBytes: (callback) => {
|
|
179
|
+
listener = callback;
|
|
180
|
+
},
|
|
181
|
+
close: () => {
|
|
182
|
+
closeChannel();
|
|
183
|
+
// Do not deliver null here — local close is not peer death; the mux's
|
|
184
|
+
// own close() already tears streams down before calling duplex.close().
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
};
|