@qontinui/ui-bridge-native 0.9.0 → 0.11.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.
@@ -121,8 +121,7 @@ function utf8Bytes(input) {
121
121
  return Uint8Array.from(out);
122
122
  }
123
123
  var rotr = (x, n) => x >>> n | x << 32 - n;
124
- function sha256Hex(input) {
125
- const bytes = utf8Bytes(input);
124
+ function sha256Bytes(bytes) {
126
125
  const blockBytes = Math.ceil((bytes.length + 9) / 64) * 64;
127
126
  const buffer = new Uint8Array(blockBytes);
128
127
  buffer.set(bytes);
@@ -166,7 +165,38 @@ function sha256Hex(input) {
166
165
  h[6] = h[6] + g | 0;
167
166
  h[7] = h[7] + hh | 0;
168
167
  }
169
- return h.map((word) => (word >>> 0).toString(16).padStart(8, "0")).join("");
168
+ const digest = new Uint8Array(32);
169
+ const digestView = new DataView(digest.buffer);
170
+ h.forEach((word, i) => digestView.setUint32(i * 4, word >>> 0));
171
+ return digest;
172
+ }
173
+ function bytesToHex(bytes) {
174
+ let out = "";
175
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
176
+ return out;
177
+ }
178
+ function sha256Hex(input) {
179
+ return bytesToHex(sha256Bytes(utf8Bytes(input)));
180
+ }
181
+ var SHA256_BLOCK_BYTES = 64;
182
+ function hmacSha256(key, message) {
183
+ const normalizedKey = key.length > SHA256_BLOCK_BYTES ? sha256Bytes(key) : key;
184
+ const inner = new Uint8Array(SHA256_BLOCK_BYTES + message.length);
185
+ const outer = new Uint8Array(SHA256_BLOCK_BYTES + 32);
186
+ for (let i = 0; i < SHA256_BLOCK_BYTES; i++) {
187
+ const keyByte = i < normalizedKey.length ? normalizedKey[i] : 0;
188
+ inner[i] = keyByte ^ 54;
189
+ outer[i] = keyByte ^ 92;
190
+ }
191
+ inner.set(message, SHA256_BLOCK_BYTES);
192
+ outer.set(sha256Bytes(inner), SHA256_BLOCK_BYTES);
193
+ return sha256Bytes(outer);
194
+ }
195
+ function constantTimeEqual(a, b) {
196
+ if (a.length !== b.length) return false;
197
+ let diff = 0;
198
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
199
+ return diff === 0;
170
200
  }
171
201
 
172
202
  // src/core/vision-fields.ts
@@ -3619,7 +3649,7 @@ var NATIVE_PAGE_HEALTH_PRODUCER_ID = "sdk-native/page-health";
3619
3649
  function defaultProducer() {
3620
3650
  return {
3621
3651
  id: NATIVE_PAGE_HEALTH_PRODUCER_ID,
3622
- version: "0.9.0"
3652
+ version: "0.11.0"
3623
3653
  };
3624
3654
  }
3625
3655
  function pageHealthUnknown(code, detail, options = {}) {
@@ -4522,6 +4552,16 @@ function createServerHandlers(registry, executor, config) {
4522
4552
  // the envelope agree; an unmounted path answers 404 instead. Each error
4523
4553
  // message names an in-tree mobile replacement so operators aren't left
4524
4554
  // guessing what to use instead.
4555
+ // The real pairing route lives in the server's network entry, ahead of this
4556
+ // table, because only that entry knows the socket peer. This answer is what
4557
+ // JSON-RPC over a WebSocket and the cloud relay get, so neither can mint a
4558
+ // token or spend a code attempt.
4559
+ pair: async () => {
4560
+ return error2(
4561
+ "Pairing is served only on a direct HTTP connection to the device, not over JSON-RPC or the cloud relay.",
4562
+ "NOT_SUPPORTED"
4563
+ );
4564
+ },
4525
4565
  aiForms: async () => {
4526
4566
  return error2(
4527
4567
  'ai/forms (form discovery) is runner-only; mobile React Native has no DOM to walk. Use GET /ui-bridge/control/snapshot and filter for type === "input" instead.',
@@ -4916,7 +4956,7 @@ function createServerHandlers(registry, executor, config) {
4916
4956
  };
4917
4957
  if (config?.appInfo) {
4918
4958
  response.uiBridge = {
4919
- version: "0.9.0",
4959
+ version: "0.11.0",
4920
4960
  ...config.appInfo,
4921
4961
  capabilities: ["elements", "components", "actions", "design"],
4922
4962
  elementCount: stats.elements,
@@ -4928,6 +4968,516 @@ function createServerHandlers(registry, executor, config) {
4928
4968
  };
4929
4969
  }
4930
4970
 
4971
+ // src/server/pairing.ts
4972
+ var UI_BRIDGE_AUTH_HEADER = "X-UI-Bridge-Auth";
4973
+ var SIGNATURE_WINDOW_MS = 3e5;
4974
+ var PAIRING_CODE_TTL_MS = 12e4;
4975
+ var PAIRING_CODE_MAX_ATTEMPTS = 5;
4976
+ var SIGNED_BODY_MAX_CHARS = 256 * 1024;
4977
+ var SIGNED_METHOD_MAX_CHARS = 16;
4978
+ var SIGNED_TARGET_MAX_CHARS = 8192;
4979
+ var TOKEN_BYTES = 32;
4980
+ var NONCE_CACHE_MAX = 4096;
4981
+ var STORE_TIMEOUT_MS = 1e4;
4982
+ var CODE_SAMPLE_ATTEMPTS = 32;
4983
+ var CODE_SAMPLE_LIMIT = Math.floor(4294967296 / 1e6) * 1e6;
4984
+ var CLOCK_STEP_TOLERANCE_MS = 5e3;
4985
+ function monotonicNow() {
4986
+ const clock = globalThis.performance;
4987
+ return typeof clock?.now === "function" ? clock.now() : null;
4988
+ }
4989
+ var PairingError = class extends Error {
4990
+ constructor(code, message) {
4991
+ super(message);
4992
+ this.code = code;
4993
+ this.name = "PairingError";
4994
+ }
4995
+ };
4996
+ function canonicalSignatureInput(parts) {
4997
+ return [parts.method, parts.pathAndQuery, parts.ts, parts.nonce, parts.bodySha256Hex].join("\n");
4998
+ }
4999
+ function signatureHex(token, parts) {
5000
+ const input = canonicalSignatureInput({
5001
+ method: parts.method,
5002
+ pathAndQuery: parts.pathAndQuery,
5003
+ ts: parts.ts,
5004
+ nonce: parts.nonce,
5005
+ bodySha256Hex: sha256Hex(parts.body)
5006
+ });
5007
+ return bytesToHex(hmacSha256(utf8Bytes(token), utf8Bytes(input)));
5008
+ }
5009
+ function headerValues(headers, name) {
5010
+ if (!headers) return [];
5011
+ const wanted = name.toLowerCase();
5012
+ return Object.keys(headers).filter((key) => key.toLowerCase() === wanted).map((key) => headers[key]);
5013
+ }
5014
+ function ipv4Octets(address) {
5015
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(address);
5016
+ if (!match) return null;
5017
+ const octets = match.slice(1).map(Number);
5018
+ return octets.every((octet) => octet <= 255) ? octets : null;
5019
+ }
5020
+ function isLoopbackIpv4(address) {
5021
+ return ipv4Octets(address)?.[0] === 127;
5022
+ }
5023
+ function parseIpv6(address) {
5024
+ if (!address.includes(":")) return null;
5025
+ let text = address;
5026
+ const trailing = [];
5027
+ const lastColon = text.lastIndexOf(":");
5028
+ const tail = text.slice(lastColon + 1);
5029
+ if (tail.includes(".")) {
5030
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(tail);
5031
+ if (!match) return null;
5032
+ const octets = match.slice(1).map(Number);
5033
+ if (octets.some((octet) => octet > 255)) return null;
5034
+ trailing.push(octets[0] << 8 | octets[1], octets[2] << 8 | octets[3]);
5035
+ text = text.slice(0, lastColon + 1);
5036
+ if (!text.endsWith("::")) text = text.slice(0, -1);
5037
+ }
5038
+ const groupsOf = (part) => {
5039
+ if (part === "") return [];
5040
+ const groups = [];
5041
+ for (const group of part.split(":")) {
5042
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return null;
5043
+ groups.push(parseInt(group, 16));
5044
+ }
5045
+ return groups;
5046
+ };
5047
+ const gapAt = text.indexOf("::");
5048
+ if (gapAt !== text.lastIndexOf("::")) return null;
5049
+ const width = 8 - trailing.length;
5050
+ if (gapAt === -1) {
5051
+ const groups = groupsOf(text);
5052
+ return groups && groups.length === width ? [...groups, ...trailing] : null;
5053
+ }
5054
+ const head = groupsOf(text.slice(0, gapAt));
5055
+ const rest = groupsOf(text.slice(gapAt + 2));
5056
+ if (!head || !rest || head.length + rest.length >= width) return null;
5057
+ const zeros = new Array(width - head.length - rest.length).fill(0);
5058
+ return [...head, ...zeros, ...rest, ...trailing];
5059
+ }
5060
+ function isLoopbackIpv6(address) {
5061
+ const zone = address.indexOf("%");
5062
+ const groups = parseIpv6(zone === -1 ? address : address.slice(0, zone));
5063
+ if (!groups) return false;
5064
+ const leadingZeros = (count) => groups.slice(0, count).every((g) => g === 0);
5065
+ if (leadingZeros(7) && groups[7] === 1) return true;
5066
+ return leadingZeros(5) && groups[5] === 65535 && groups[6] >> 8 === 127;
5067
+ }
5068
+ function isLoopbackAddress(address) {
5069
+ return isLoopbackIpv4(address) || isLoopbackIpv6(address);
5070
+ }
5071
+ function isLoopbackHost(host) {
5072
+ const value = host.trim().toLowerCase();
5073
+ const bracketed = /^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(value);
5074
+ if (bracketed) {
5075
+ return isLoopbackIpv6(bracketed[1]) && isValidPort(bracketed[2]);
5076
+ }
5077
+ const plain = /^([^:]+)(?::(\d{1,5}))?$/.exec(value);
5078
+ if (!plain) return false;
5079
+ return (plain[1] === "localhost" || isLoopbackIpv4(plain[1])) && isValidPort(plain[2]);
5080
+ }
5081
+ function isValidPort(port) {
5082
+ return port === void 0 || Number(port) <= 65535;
5083
+ }
5084
+ function isUnrebindableHost(host) {
5085
+ const value = host.trim().toLowerCase();
5086
+ const bracketed = /^\[([^\]%]+)(?:%[^\]]*)?\](?::(\d{1,5}))?$/.exec(value);
5087
+ if (bracketed) return parseIpv6(bracketed[1]) !== null && isValidPort(bracketed[2]);
5088
+ const plain = /^([^:]+)(?::(\d{1,5}))?$/.exec(value);
5089
+ if (!plain) return false;
5090
+ const named = plain[1] === "localhost" || plain[1].endsWith(".local") || ipv4Octets(plain[1]) !== null;
5091
+ return named && isValidPort(plain[2]);
5092
+ }
5093
+ function carriesWebContext(request) {
5094
+ const { headers } = request;
5095
+ if (headerValues(headers, "origin").length > 0) return true;
5096
+ if (headerValues(headers, "referer").length > 0) return true;
5097
+ return headerValues(headers, "sec-fetch-site").some(
5098
+ (site) => site.trim().toLowerCase() !== "none"
5099
+ );
5100
+ }
5101
+ function isTrustedLoopbackRequest(request) {
5102
+ if (!request.remoteAddress || !isLoopbackAddress(request.remoteAddress)) return false;
5103
+ if (carriesWebContext(request)) return false;
5104
+ const hosts = headerValues(request.headers, "host");
5105
+ return hosts.length > 0 && hosts.every(isLoopbackHost);
5106
+ }
5107
+ function isWebReachableRequest(request) {
5108
+ if (carriesWebContext(request)) return true;
5109
+ const hosts = headerValues(request.headers, "host");
5110
+ return hosts.length === 0 || !hosts.every(isUnrebindableHost);
5111
+ }
5112
+ async function bounded(work) {
5113
+ let timer;
5114
+ try {
5115
+ return await Promise.race([
5116
+ Promise.resolve().then(work),
5117
+ new Promise((_, reject) => {
5118
+ timer = setTimeout(() => reject(new Error("store call timed out")), STORE_TIMEOUT_MS);
5119
+ })
5120
+ ]);
5121
+ } finally {
5122
+ if (timer !== void 0) clearTimeout(timer);
5123
+ }
5124
+ }
5125
+ var UNAVAILABLE = {
5126
+ ok: false,
5127
+ code: "PAIRING_UNAVAILABLE",
5128
+ error: "The pairing store is not available yet. Try again."
5129
+ };
5130
+ var TOKEN_NOT_LOADED = /* @__PURE__ */ Symbol("token-not-loaded");
5131
+ var PairingAuthority = class {
5132
+ constructor(store) {
5133
+ this.store = store;
5134
+ this.armedCode = null;
5135
+ /** A correct code waiting on the store step, restored if that step fails. */
5136
+ this.heldCode = null;
5137
+ this.disarmReason = null;
5138
+ this.consumedBy = null;
5139
+ this.consumedAt = null;
5140
+ this.lastWrite = Promise.resolve();
5141
+ /** Nonce to its timestamp, oldest insertion first. */
5142
+ this.nonces = /* @__PURE__ */ new Map();
5143
+ /**
5144
+ * The oldest timestamp still accepted. A nonce this process did not record
5145
+ * cannot be checked for a replay, so a signature from before it existed is
5146
+ * refused: otherwise an app restart, which empties the cache, would reopen
5147
+ * the whole window to a captured request. Eviction raises it for the same
5148
+ * reason. A clock step re-bases it to the new now, or a clock set back past it
5149
+ * would refuse every signature until the app restarted. That leaves one gap with
5150
+ * two arms: a request captured before a step back can replay once, if its
5151
+ * timestamp is at or above the new now and this process does not remember its
5152
+ * nonce, because it has forgotten it, or because the app restarted since and it
5153
+ * never recorded it. Without `performance.now` no step is seen, and the floor
5154
+ * holds until the clock passes it.
5155
+ */
5156
+ this.oldestAcceptedTs = Date.now();
5157
+ /**
5158
+ * The wall clock minus the monotonic clock at the last re-base. It moves only
5159
+ * then, so small steps add up until they cross the tolerance, and a clock step
5160
+ * leaves the floor at most twice the tolerance ahead of the clock: the clock can
5161
+ * swing from just over the baseline to just under it without crossing it.
5162
+ */
5163
+ this.clockOffset = this.readClockOffset();
5164
+ /** Moves when a revoke ends, so a read of the old token that spans one cannot admit. */
5165
+ this.tokenGeneration = 0;
5166
+ /** Revokes under way. The old token may already be dying, so nothing verifies. */
5167
+ this.revokesInFlight = 0;
5168
+ /** A revoke failed in a way that may have left the old token in the store. */
5169
+ this.storeSuspect = false;
5170
+ }
5171
+ /**
5172
+ * The stored token, `null` when there is none, or `TOKEN_NOT_LOADED`. Only
5173
+ * `readStore` tells these apart: an empty or non-string value is never a
5174
+ * token, because an empty key would verify anything signed with it.
5175
+ */
5176
+ async readToken() {
5177
+ return this.storeSuspect ? TOKEN_NOT_LOADED : this.readStore();
5178
+ }
5179
+ async readStore() {
5180
+ try {
5181
+ const token = await bounded(() => this.store.get());
5182
+ if (token === null) return null;
5183
+ return typeof token === "string" && token.length > 0 ? token : TOKEN_NOT_LOADED;
5184
+ } catch {
5185
+ return TOKEN_NOT_LOADED;
5186
+ }
5187
+ }
5188
+ async randomBytes(n) {
5189
+ const unusable = new PairingError(
5190
+ "PAIRING_UNAVAILABLE",
5191
+ "The secure random source returned no usable bytes."
5192
+ );
5193
+ let bytes;
5194
+ try {
5195
+ bytes = await bounded(() => this.store.randomBytes(n));
5196
+ } catch {
5197
+ throw unusable;
5198
+ }
5199
+ if (!ArrayBuffer.isView(bytes) || bytes.length !== n || bytes.every((byte) => byte === 0)) {
5200
+ throw unusable;
5201
+ }
5202
+ return bytes;
5203
+ }
5204
+ async mintAndStoreToken() {
5205
+ const token = bytesToHex(await this.randomBytes(TOKEN_BYTES));
5206
+ await bounded(() => this.store.set(token));
5207
+ return token;
5208
+ }
5209
+ /** Run token writes one at a time, so two first pairs cannot mint two tokens. */
5210
+ exclusive(work) {
5211
+ const run = this.lastWrite.then(work, work);
5212
+ this.lastWrite = run.catch(() => void 0);
5213
+ return run;
5214
+ }
5215
+ /** Check a `<ts>.<nonce>.<sig>` value against this request and the stored token. */
5216
+ async verifySignature(request, header) {
5217
+ const match = /^(\d{1,16})\.([A-Za-z0-9_-]{16,64})\.([0-9a-f]{64})$/.exec(header);
5218
+ if (!match) return "refused";
5219
+ const [, ts, nonce, sig] = match;
5220
+ const tsMs = Number(ts);
5221
+ this.noticeClockStep();
5222
+ if (Math.abs(Date.now() - tsMs) > SIGNATURE_WINDOW_MS) return "timestamp_refused";
5223
+ if (tsMs < this.oldestAcceptedTs) return "timestamp_refused";
5224
+ const pathAndQuery = signedTarget(request);
5225
+ const body = signedBody(request);
5226
+ if (pathAndQuery === null || body === null) return "refused";
5227
+ if (body.length > SIGNED_BODY_MAX_CHARS) return "body_too_large";
5228
+ if (request.method.length > SIGNED_METHOD_MAX_CHARS) return "target_too_long";
5229
+ if (pathAndQuery.length > SIGNED_TARGET_MAX_CHARS) return "target_too_long";
5230
+ const generation = this.tokenGeneration;
5231
+ const token = await this.readToken();
5232
+ if (this.revokesInFlight > 0) return "refused";
5233
+ if (token === TOKEN_NOT_LOADED) return "store_unavailable";
5234
+ if (token === null) return "refused";
5235
+ const expected = signatureHex(token, { method: request.method, pathAndQuery, ts, nonce, body });
5236
+ if (!constantTimeEqual(expected, sig)) return "refused";
5237
+ if (generation !== this.tokenGeneration) return "refused";
5238
+ if (this.nonces.has(nonce)) return "refused";
5239
+ this.rememberNonce(nonce, tsMs);
5240
+ return "valid";
5241
+ }
5242
+ readClockOffset() {
5243
+ const monotonic = monotonicNow();
5244
+ return monotonic === null ? null : Date.now() - monotonic;
5245
+ }
5246
+ /**
5247
+ * Re-base the floor when the wall clock has stepped against the monotonic one.
5248
+ * A nonce remembered from above the new now is clamped to just below the new
5249
+ * floor. Left as it is, forgetting it later would raise the floor back to a time
5250
+ * before the step, and the lockout would return when the cache overflowed.
5251
+ */
5252
+ noticeClockStep() {
5253
+ const offset = this.readClockOffset();
5254
+ if (offset === null || this.clockOffset === null) return;
5255
+ if (Math.abs(offset - this.clockOffset) > CLOCK_STEP_TOLERANCE_MS) {
5256
+ this.clockOffset = offset;
5257
+ this.oldestAcceptedTs = Date.now();
5258
+ for (const [nonce, tsMs] of this.nonces) {
5259
+ if (tsMs >= this.oldestAcceptedTs) this.nonces.set(nonce, this.oldestAcceptedTs - 1);
5260
+ }
5261
+ }
5262
+ }
5263
+ rememberNonce(nonce, tsMs) {
5264
+ if (this.nonces.size >= NONCE_CACHE_MAX) {
5265
+ const now = Date.now();
5266
+ for (const [seen, seenTs] of this.nonces) {
5267
+ if (seenTs + SIGNATURE_WINDOW_MS < now) this.forgetNonce(seen, seenTs);
5268
+ }
5269
+ }
5270
+ while (this.nonces.size >= NONCE_CACHE_MAX) {
5271
+ const [seen, seenTs] = this.nonces.entries().next().value;
5272
+ this.forgetNonce(seen, seenTs);
5273
+ }
5274
+ this.nonces.set(nonce, tsMs);
5275
+ }
5276
+ /** Forgetting a nonce must not readmit it, so its timestamp stops being accepted. */
5277
+ forgetNonce(nonce, tsMs) {
5278
+ this.nonces.delete(nonce);
5279
+ this.oldestAcceptedTs = Math.max(this.oldestAcceptedTs, tsMs + 1);
5280
+ }
5281
+ /**
5282
+ * The route's decision. A trusted loopback caller needs no code. Anyone else
5283
+ * spends the armed code, and an unarmed one refuses without comparing.
5284
+ */
5285
+ async pair(input) {
5286
+ if (!input.trustedLoopback) {
5287
+ const refusal = this.spendCode(input.body);
5288
+ if (refusal) return refusal;
5289
+ }
5290
+ const spent = input.trustedLoopback ? null : this.heldCode;
5291
+ const outcome = await this.exclusive(async () => {
5292
+ const existing = await this.readToken();
5293
+ if (existing === TOKEN_NOT_LOADED) return UNAVAILABLE;
5294
+ if (existing !== null) return { ok: true, token: existing };
5295
+ try {
5296
+ return { ok: true, token: await this.mintAndStoreToken() };
5297
+ } catch {
5298
+ return UNAVAILABLE;
5299
+ }
5300
+ });
5301
+ if (spent) this.settleSpentCode(spent, outcome.ok, input.peer);
5302
+ return outcome;
5303
+ }
5304
+ /**
5305
+ * The store step has answered. A failure gives the code back, since the user
5306
+ * typed the right one and the phone let them down, unless the app has since
5307
+ * cancelled it or armed another.
5308
+ */
5309
+ settleSpentCode(spent, paired, peer) {
5310
+ const stillHeld = this.heldCode === spent;
5311
+ if (stillHeld) this.heldCode = null;
5312
+ if (paired) {
5313
+ if (stillHeld) this.disarmReason = "consumed";
5314
+ this.consumedBy = peer ?? "unknown";
5315
+ this.consumedAt = Date.now();
5316
+ } else if (stillHeld) {
5317
+ this.armedCode = spent;
5318
+ }
5319
+ }
5320
+ /** No await in here: the attempt count has to move with the comparison. */
5321
+ spendCode(body) {
5322
+ this.expireCode();
5323
+ const armed = this.armedCode;
5324
+ if (!armed) {
5325
+ return {
5326
+ ok: false,
5327
+ code: "PAIRING_NOT_ARMED",
5328
+ error: "No pairing code is armed. Arm one in the app, or pair over a cable."
5329
+ };
5330
+ }
5331
+ const code = body?.code;
5332
+ if (typeof code !== "string" || !/^\d{6}$/.test(code)) {
5333
+ return {
5334
+ ok: false,
5335
+ code: "PAIRING_CODE_REQUIRED",
5336
+ error: 'Send the 6-digit code shown in the app, as { "code": "123456" }.'
5337
+ };
5338
+ }
5339
+ if (constantTimeEqual(armed.code, code)) {
5340
+ this.armedCode = null;
5341
+ this.heldCode = armed;
5342
+ return null;
5343
+ }
5344
+ armed.wrongAttempts += 1;
5345
+ if (armed.wrongAttempts >= PAIRING_CODE_MAX_ATTEMPTS) {
5346
+ this.armedCode = null;
5347
+ this.disarmReason = "attempts_exhausted";
5348
+ }
5349
+ return { ok: false, code: "PAIRING_CODE_INVALID", error: "That code is not correct." };
5350
+ }
5351
+ /** Either clock ends the code, so a clock set back cannot extend it. */
5352
+ expireCode() {
5353
+ if (!this.armedCode) return;
5354
+ const { expiresAt, monotonicDeadline } = this.armedCode;
5355
+ const monotonic = monotonicNow();
5356
+ const monotonicExpired = monotonic !== null && monotonicDeadline !== null && monotonic >= monotonicDeadline;
5357
+ if (Date.now() >= expiresAt || monotonicExpired) {
5358
+ this.armedCode = null;
5359
+ this.disarmReason = "expired";
5360
+ }
5361
+ }
5362
+ /** Arm a fresh code, replacing any live one. */
5363
+ async arm() {
5364
+ const stored = await this.readToken();
5365
+ if (stored === TOKEN_NOT_LOADED) {
5366
+ throw new PairingError("PAIRING_UNAVAILABLE", "The pairing store is not available yet.");
5367
+ }
5368
+ const code = await this.drawCode();
5369
+ const expiresAt = Date.now() + PAIRING_CODE_TTL_MS;
5370
+ const monotonic = monotonicNow();
5371
+ this.armedCode = {
5372
+ code,
5373
+ expiresAt,
5374
+ monotonicDeadline: monotonic === null ? null : monotonic + PAIRING_CODE_TTL_MS,
5375
+ wrongAttempts: 0
5376
+ };
5377
+ this.heldCode = null;
5378
+ this.disarmReason = null;
5379
+ this.consumedBy = null;
5380
+ this.consumedAt = null;
5381
+ return { code, expiresAt };
5382
+ }
5383
+ /** A uniform 6-digit code, by rejection sampling so that no digit is favoured. */
5384
+ async drawCode() {
5385
+ for (let attempt = 0; attempt < CODE_SAMPLE_ATTEMPTS; attempt++) {
5386
+ const bytes = await this.randomBytes(4);
5387
+ const value = new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0);
5388
+ if (value < CODE_SAMPLE_LIMIT) return String(value % 1e6).padStart(6, "0");
5389
+ }
5390
+ throw new PairingError(
5391
+ "PAIRING_UNAVAILABLE",
5392
+ "The secure random source returned no usable bytes."
5393
+ );
5394
+ }
5395
+ /** Cancel a live code. */
5396
+ disarm() {
5397
+ this.dropCode("cancelled");
5398
+ }
5399
+ dropCode(reason) {
5400
+ if (this.armedCode || this.heldCode) {
5401
+ this.armedCode = null;
5402
+ this.heldCode = null;
5403
+ this.disarmReason = reason;
5404
+ }
5405
+ }
5406
+ /**
5407
+ * Replace the token, so every signature made with the old one stops verifying.
5408
+ * If it cannot be replaced it is cleared. If that fails too, signatures and
5409
+ * pairing stay refused until a revoke succeeds: the user asked for the old
5410
+ * token to die, and a store that would not say so cannot be trusted to have
5411
+ * done it.
5412
+ *
5413
+ * Nothing verifies from the moment this starts until it ends. The generation
5414
+ * moves when it ends, whichever way, so a check that read the old token before
5415
+ * then cannot admit its request afterwards. A request a check has already
5416
+ * admitted runs to its end.
5417
+ */
5418
+ async revoke() {
5419
+ this.revokesInFlight += 1;
5420
+ this.dropCode("revoked");
5421
+ try {
5422
+ await this.exclusive(async () => {
5423
+ const stored = await this.readStore();
5424
+ if (stored === TOKEN_NOT_LOADED) {
5425
+ throw new PairingError("PAIRING_UNAVAILABLE", "The pairing store is not available yet.");
5426
+ }
5427
+ try {
5428
+ await this.mintAndStoreToken();
5429
+ this.storeSuspect = false;
5430
+ } catch {
5431
+ try {
5432
+ await bounded(() => this.store.clear());
5433
+ this.storeSuspect = false;
5434
+ } catch {
5435
+ this.storeSuspect = true;
5436
+ }
5437
+ throw new PairingError("PAIRING_UNAVAILABLE", "The pairing token could not be replaced.");
5438
+ }
5439
+ });
5440
+ } finally {
5441
+ this.revokesInFlight -= 1;
5442
+ this.tokenGeneration += 1;
5443
+ }
5444
+ }
5445
+ /** What Settings shows. */
5446
+ getState() {
5447
+ this.expireCode();
5448
+ return {
5449
+ configured: true,
5450
+ armed: this.armedCode !== null,
5451
+ expiresAt: this.armedCode?.expiresAt ?? null,
5452
+ attemptsRemaining: this.armedCode ? PAIRING_CODE_MAX_ATTEMPTS - this.armedCode.wrongAttempts : null,
5453
+ consumedBy: this.consumedBy,
5454
+ consumedAt: this.consumedAt,
5455
+ disarmReason: this.disarmReason
5456
+ };
5457
+ }
5458
+ };
5459
+ var UNCONFIGURED_PAIRING_STATE = {
5460
+ configured: false,
5461
+ armed: false,
5462
+ expiresAt: null,
5463
+ attemptsRemaining: null,
5464
+ consumedBy: null,
5465
+ consumedAt: null,
5466
+ disarmReason: null
5467
+ };
5468
+ function signedTarget(request) {
5469
+ if (request.rawTarget === void 0) {
5470
+ return Object.keys(request.query ?? {}).length === 0 ? request.path : null;
5471
+ }
5472
+ const queryAt = request.rawTarget.indexOf("?");
5473
+ const path = queryAt === -1 ? request.rawTarget : request.rawTarget.slice(0, queryAt);
5474
+ return path === request.path ? request.rawTarget : null;
5475
+ }
5476
+ function signedBody(request) {
5477
+ if (request.rawBody !== void 0) return request.rawBody;
5478
+ return request.body === void 0 ? "" : null;
5479
+ }
5480
+
4931
5481
  // src/server/observability.ts
4932
5482
  var RingBuffer = class {
4933
5483
  constructor(capacity) {
@@ -5258,7 +5808,20 @@ function isUnsubscribe(msg) {
5258
5808
  var ERROR_CODE_HTTP_STATUS = /* @__PURE__ */ new Map([
5259
5809
  ["NOT_SUPPORTED", 501],
5260
5810
  ["NOT_FOUND", 404],
5261
- ["METHOD_NOT_ALLOWED", 405]
5811
+ ["METHOD_NOT_ALLOWED", 405],
5812
+ // Device pairing, all answered by the network entry. A 401 means this caller
5813
+ // has not proved it may act; a 403 means proving it would change nothing; a 503
5814
+ // means the phone cannot check yet.
5815
+ ["PAIRING_REQUIRED", 401],
5816
+ ["PAIRING_UNCONFIGURED", 401],
5817
+ ["PAIRING_NOT_ARMED", 401],
5818
+ ["PAIRING_CODE_INVALID", 401],
5819
+ ["PAIRING_TIMESTAMP_REFUSED", 401],
5820
+ ["PAIRING_WS_LOOPBACK_ONLY", 403],
5821
+ ["PAIRING_WEB_CALLER_REFUSED", 403],
5822
+ ["PAIRING_BODY_TOO_LARGE", 413],
5823
+ ["PAIRING_TARGET_TOO_LONG", 414],
5824
+ ["PAIRING_UNAVAILABLE", 503]
5262
5825
  ]);
5263
5826
  function httpStatusForResponse(response) {
5264
5827
  if (response.success) return 200;
@@ -5284,6 +5847,10 @@ function parsePath(pattern, actual) {
5284
5847
  var WS_ROUTES = [
5285
5848
  // Health
5286
5849
  { pattern: "health", handler: "health", httpMethods: ["GET"] },
5850
+ // Device pairing. Always NOT_SUPPORTED from this table: the real route is in
5851
+ // `handleNetworkRequest`, because route context carries no peer, and this
5852
+ // entry is what JSON-RPC and the relay reach instead.
5853
+ { pattern: "pair", handler: "pair", httpMethods: ["POST"] },
5287
5854
  // Elements
5288
5855
  { pattern: "control/elements", handler: "getElements", httpMethods: ["GET"] },
5289
5856
  // Flat alias — matches the runner UI Bridge's `/ui-bridge/elements` path so
@@ -5446,6 +6013,7 @@ function allowedMethodsForPath(path, testHooks) {
5446
6013
  }
5447
6014
  var HANDLER_DESCRIPTIONS = {
5448
6015
  health: "Liveness probe; returns app metadata + element count",
6016
+ pair: "Get the pairing token: loopback with no code, otherwise body { code }. Direct HTTP only",
5449
6017
  getElements: "Flat list of registered UI elements",
5450
6018
  getElement: "Single element by id",
5451
6019
  getElementState: "Dynamic state (value, focused, checked) for one element",
@@ -5547,10 +6115,24 @@ function buildHelpPayload(testHooks) {
5547
6115
  ]
5548
6116
  };
5549
6117
  }
6118
+ var HEALTH_PATH = "/ui-bridge/health";
6119
+ var PAIR_PATH = "/ui-bridge/pair";
6120
+ function jsonRpcIdOf(rawMessage) {
6121
+ try {
6122
+ const id = JSON.parse(rawMessage)?.id;
6123
+ return typeof id === "number" || typeof id === "string" ? id : 0;
6124
+ } catch {
6125
+ return 0;
6126
+ }
6127
+ }
5550
6128
  var NativeUIBridgeServer = class {
5551
6129
  constructor(registry, executor, config = {}) {
5552
6130
  this.registry = registry;
5553
6131
  this.executor = executor;
6132
+ /** Whether this run's adapter has called `onWebSocketUpgrade` at all. */
6133
+ this.upgradeGateSeen = false;
6134
+ /** Warned once per run rather than per request, which would flood the error ring. */
6135
+ this.warnedMissingPeer = false;
5554
6136
  this.running = false;
5555
6137
  /**
5556
6138
  * Per-connection cleanup thunks for in-flight waiters (waitForElement,
@@ -5563,6 +6145,9 @@ var NativeUIBridgeServer = class {
5563
6145
  cors: true,
5564
6146
  ...config
5565
6147
  };
6148
+ if (this.config.pairingStore) {
6149
+ this.pairing = new PairingAuthority(this.config.pairingStore);
6150
+ }
5566
6151
  this.consoleErrorBuffer = new ConsoleErrorBuffer();
5567
6152
  this.networkRequestBuffer = new NetworkRequestBuffer();
5568
6153
  if (this.config.appInfo) {
@@ -5608,6 +6193,14 @@ var NativeUIBridgeServer = class {
5608
6193
  setAdapter(adapter) {
5609
6194
  this.adapter = adapter;
5610
6195
  }
6196
+ /**
6197
+ * Set the device's stable id. An app usually loads it from storage after the
6198
+ * server has started, and this spares it a restart that would drop every
6199
+ * socket and any armed code.
6200
+ */
6201
+ setDeviceId(deviceId) {
6202
+ this.config.deviceId = deviceId;
6203
+ }
5611
6204
  /**
5612
6205
  * Set a navigation provider for programmatic route navigation.
5613
6206
  * This enables `control/page/navigate` and `control/page/back` on native.
@@ -5841,7 +6434,18 @@ var NativeUIBridgeServer = class {
5841
6434
  this.consoleErrorBuffer.install();
5842
6435
  this.networkRequestBuffer.install();
5843
6436
  }
5844
- await this.adapter.start(this.config.serverPort, this.handleRequest.bind(this));
6437
+ this.upgradeGateSeen = false;
6438
+ this.warnedMissingPeer = false;
6439
+ if (this.config.allowUnauthenticatedNetwork) {
6440
+ console.warn(
6441
+ "[ui-bridge-native] allowUnauthenticatedNetwork is on: anyone who can reach this port can drive the app over HTTP."
6442
+ );
6443
+ } else if (!this.pairing) {
6444
+ console.warn(
6445
+ "[ui-bridge-native] No pairingStore configured: non-loopback callers are refused with PAIRING_UNCONFIGURED."
6446
+ );
6447
+ }
6448
+ await this.adapter.start(this.config.serverPort, this.handleNetworkRequest.bind(this));
5845
6449
  this.running = true;
5846
6450
  console.log(`[ui-bridge-native] HTTP server started on port ${this.config.serverPort}`);
5847
6451
  }
@@ -5870,6 +6474,26 @@ var NativeUIBridgeServer = class {
5870
6474
  setEventBridge(bridge) {
5871
6475
  this.eventBridge = bridge;
5872
6476
  }
6477
+ /**
6478
+ * The entry a socket's messages come through. An adapter that never called
6479
+ * `onWebSocketUpgrade` admitted the socket with no check, and a message carries
6480
+ * no peer to check now, so it is refused: the same fail-closed reading as a
6481
+ * missing peer address. An adapter that gates sees a call before its first socket.
6482
+ */
6483
+ async handleNetworkWebSocketMessage(connId, rawMessage) {
6484
+ if (!this.upgradeGateSeen) {
6485
+ return JSON.stringify({
6486
+ id: jsonRpcIdOf(rawMessage),
6487
+ result: {
6488
+ success: false,
6489
+ error: "This server adapter does not gate WebSocket upgrades (onWebSocketUpgrade).",
6490
+ code: "PAIRING_UNCONFIGURED",
6491
+ timestamp: Date.now()
6492
+ }
6493
+ });
6494
+ }
6495
+ return this.handleWebSocketMessage(connId, rawMessage);
6496
+ }
5873
6497
  /**
5874
6498
  * Handle a JSON-RPC message from a WebSocket client.
5875
6499
  * Parses the message, routes to the appropriate handler, and returns
@@ -6398,21 +7022,272 @@ var NativeUIBridgeServer = class {
6398
7022
  timestamp: Date.now()
6399
7023
  };
6400
7024
  }
7025
+ // ── Device pairing ──────────────────────────────────────────────────────
7026
+ /**
7027
+ * What `start()` hands the adapter: every request off the socket comes through
7028
+ * here, and `handleRequest` sits behind it.
7029
+ *
7030
+ * | Caller | Admitted |
7031
+ * |----------------------------------------------------------|----------|
7032
+ * | Loopback peer, no web context, loopback `Host` | yes |
7033
+ * | Anyone with a valid `X-UI-Bridge-Auth` signature | yes |
7034
+ * | Anyone, `GET /ui-bridge/health` (trimmed) | yes |
7035
+ * | Anyone with no web context, `POST /ui-bridge/pair` | yes |
7036
+ * | A web page, `POST /ui-bridge/pair` | 403 `PAIRING_WEB_CALLER_REFUSED` |
7037
+ * | Signature outside the window or below the floor | 401 `PAIRING_TIMESTAMP_REFUSED` |
7038
+ * | Signed body over `SIGNED_BODY_MAX_CHARS` | 413 `PAIRING_BODY_TOO_LARGE` |
7039
+ * | Signed method or target over its cap | 414 `PAIRING_TARGET_TOO_LONG` |
7040
+ * | Everyone else | 401 `PAIRING_REQUIRED` |
7041
+ * | No store configured, not loopback | 401 `PAIRING_UNCONFIGURED` |
7042
+ * | Under `allowUnauthenticatedNetwork`, a web page or a rebindable `Host` | 403 `PAIRING_WEB_CALLER_REFUSED` |
7043
+ *
7044
+ * The gate is here rather than in `handleRequest` because `CloudRelayClient`
7045
+ * calls that directly and must keep working: relay access already means the
7046
+ * same user account, checked by the backend.
7047
+ */
7048
+ async handleNetworkRequest(request) {
7049
+ try {
7050
+ if (request.method === "POST" && request.path === PAIR_PATH) {
7051
+ return await this.handlePair(request);
7052
+ }
7053
+ const admission = await this.admit(request);
7054
+ if (request.method === "GET" && request.path === HEALTH_PATH) {
7055
+ return await this.handleNetworkHealth(request, admission);
7056
+ }
7057
+ if (!admission.admitted) {
7058
+ return this.refusal(admission.code, admission.error, { data: admission.data });
7059
+ }
7060
+ return await this.handleRequest(request);
7061
+ } catch {
7062
+ return this.refusal("INTERNAL_ERROR", "Internal server error", { status: 500 });
7063
+ }
7064
+ }
7065
+ /**
7066
+ * The WebSocket door: trusted loopback or nothing, whatever else the request
7067
+ * carries. A signature covers no upgrade intent, so one swallowed GET re-sent
7068
+ * with `Upgrade: websocket` would become a permanent control socket, and a socket
7069
+ * outlives the signature's window. `allowUnauthenticatedNetwork` opens HTTP only,
7070
+ * and no runner dials a device's socket.
7071
+ */
7072
+ handleWebSocketUpgrade(request) {
7073
+ this.upgradeGateSeen = true;
7074
+ if (this.isTrustedLoopback(request)) return { admit: true };
7075
+ return {
7076
+ admit: false,
7077
+ response: this.refusal(
7078
+ "PAIRING_WS_LOOPBACK_ONLY",
7079
+ "WebSocket upgrades are accepted only from this machine. Use signed HTTP from anywhere else."
7080
+ )
7081
+ };
7082
+ }
7083
+ isTrustedLoopback(request) {
7084
+ if (!request.remoteAddress && !this.warnedMissingPeer) {
7085
+ this.warnedMissingPeer = true;
7086
+ console.warn(
7087
+ "[ui-bridge-native] A request arrived with no peer address and is treated as not loopback. The server adapter must pass remoteAddress."
7088
+ );
7089
+ }
7090
+ return isTrustedLoopbackRequest(request);
7091
+ }
7092
+ async admit(request) {
7093
+ if (this.isTrustedLoopback(request)) return { admitted: true, as: "loopback" };
7094
+ if (this.config.allowUnauthenticatedNetwork) {
7095
+ if (isWebReachableRequest(request)) {
7096
+ return {
7097
+ admitted: false,
7098
+ code: "PAIRING_WEB_CALLER_REFUSED",
7099
+ error: "A web page cannot drive this device."
7100
+ };
7101
+ }
7102
+ return { admitted: true, as: "unauthenticated-network" };
7103
+ }
7104
+ if (!this.pairing) {
7105
+ return {
7106
+ admitted: false,
7107
+ code: "PAIRING_UNCONFIGURED",
7108
+ error: "This app has not configured device pairing, so it accepts only local callers."
7109
+ };
7110
+ }
7111
+ const required = {
7112
+ admitted: false,
7113
+ code: "PAIRING_REQUIRED",
7114
+ error: "This device requires pairing. Sign the request with the token from POST /ui-bridge/pair."
7115
+ };
7116
+ const signatures = headerValues(request.headers, UI_BRIDGE_AUTH_HEADER);
7117
+ if (signatures.length !== 1) return required;
7118
+ const verdict = await this.pairing.verifySignature(request, signatures[0]);
7119
+ if (verdict === "valid") return { admitted: true, as: "signed" };
7120
+ if (verdict === "store_unavailable") {
7121
+ return {
7122
+ admitted: false,
7123
+ code: "PAIRING_UNAVAILABLE",
7124
+ error: "The pairing store is not available yet. Try again."
7125
+ };
7126
+ }
7127
+ if (verdict === "timestamp_refused") {
7128
+ return {
7129
+ admitted: false,
7130
+ code: "PAIRING_TIMESTAMP_REFUSED",
7131
+ error: "The signature timestamp is not acceptable. Re-sync to data.serverTime and sign again.",
7132
+ data: { serverTime: Date.now() }
7133
+ };
7134
+ }
7135
+ if (verdict === "body_too_large") {
7136
+ return {
7137
+ admitted: false,
7138
+ code: "PAIRING_BODY_TOO_LARGE",
7139
+ error: `A signed body may be at most ${SIGNED_BODY_MAX_CHARS} characters.`
7140
+ };
7141
+ }
7142
+ if (verdict === "target_too_long") {
7143
+ return {
7144
+ admitted: false,
7145
+ code: "PAIRING_TARGET_TOO_LONG",
7146
+ error: `A signed target may be at most ${SIGNED_TARGET_MAX_CHARS} characters.`
7147
+ };
7148
+ }
7149
+ return required;
7150
+ }
7151
+ corsHeaders() {
7152
+ if (!this.config.cors) return {};
7153
+ return {
7154
+ "Access-Control-Allow-Origin": this.config.allowedOrigins ? this.config.allowedOrigins.join(",") : "*",
7155
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
7156
+ "Access-Control-Allow-Headers": "Content-Type, Authorization"
7157
+ };
7158
+ }
7159
+ /** No CORS header: a page must not be able to read what the gate says. */
7160
+ refusal(code, error3, extra = {}) {
7161
+ const body = {
7162
+ success: false,
7163
+ error: error3,
7164
+ code,
7165
+ timestamp: Date.now(),
7166
+ ...extra.data ? { data: extra.data } : {}
7167
+ };
7168
+ return {
7169
+ status: extra.status ?? httpStatusForResponse(body),
7170
+ headers: { "Content-Type": "application/json" },
7171
+ body: JSON.stringify(body)
7172
+ };
7173
+ }
7174
+ /**
7175
+ * Open health. An admitted caller gets the full answer. Anyone else gets what
7176
+ * discovery needs and nothing about the app's contents, and that answer is
7177
+ * built without going through `handleRequest`, whose keep-awake auto-arm is no
7178
+ * business of an anonymous LAN probe. It carries no CORS header, so a web page
7179
+ * cannot read the stable device id.
7180
+ */
7181
+ async handleNetworkHealth(request, admission) {
7182
+ const pairing = {
7183
+ required: !(admission.admitted && (admission.as === "loopback" || admission.as === "unauthenticated-network")),
7184
+ authenticated: admission.admitted && admission.as !== "unauthenticated-network"
7185
+ };
7186
+ const identity = {
7187
+ deviceId: this.config.deviceId ?? null,
7188
+ serverTime: Date.now(),
7189
+ pairing
7190
+ };
7191
+ if (admission.admitted) {
7192
+ const response = await this.handleRequest(request);
7193
+ const parsed = JSON.parse(response.body);
7194
+ if (!parsed.success || !parsed.data) return response;
7195
+ return {
7196
+ ...response,
7197
+ body: JSON.stringify({ ...parsed, data: { ...parsed.data, ...identity } })
7198
+ };
7199
+ }
7200
+ const health = await this.handlers.health({ params: {}, query: {}, body: void 0 });
7201
+ const full = health.data ?? {};
7202
+ const trimmed = { status: full.status, ...identity };
7203
+ if (full.uiBridge) {
7204
+ const { version, appId, appName, appType, framework } = full.uiBridge;
7205
+ trimmed.uiBridge = { version, appId, appName, appType, framework };
7206
+ }
7207
+ return {
7208
+ status: 200,
7209
+ headers: { "Content-Type": "application/json" },
7210
+ body: JSON.stringify({ success: true, data: trimmed, timestamp: Date.now() })
7211
+ };
7212
+ }
7213
+ /**
7214
+ * `POST /ui-bridge/pair`, the only way to a token, and only ever from here.
7215
+ * Its answer carries no CORS header, because no web page has any business
7216
+ * reading a token, and it answers only after the store write has finished. A web
7217
+ * page is refused first of all, so it cannot burn an attempt or the armed code.
7218
+ */
7219
+ async handlePair(request) {
7220
+ if (carriesWebContext(request)) {
7221
+ return this.refusal("PAIRING_WEB_CALLER_REFUSED", "A web page cannot pair with this device.");
7222
+ }
7223
+ if (!this.pairing) {
7224
+ return this.refusal(
7225
+ "PAIRING_UNCONFIGURED",
7226
+ "This app has not configured device pairing, so it cannot issue a token."
7227
+ );
7228
+ }
7229
+ const deviceId = this.config.deviceId;
7230
+ if (!deviceId) {
7231
+ return this.refusal("PAIRING_UNAVAILABLE", "The device id is not available yet. Try again.");
7232
+ }
7233
+ const outcome = await this.pairing.pair({
7234
+ trustedLoopback: this.isTrustedLoopback(request),
7235
+ peer: request.remoteAddress,
7236
+ body: request.body
7237
+ });
7238
+ if (!outcome.ok) return this.refusal(outcome.code, outcome.error);
7239
+ const body = {
7240
+ success: true,
7241
+ data: { token: outcome.token, deviceId, serverTime: Date.now() },
7242
+ timestamp: Date.now()
7243
+ };
7244
+ return {
7245
+ status: 200,
7246
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
7247
+ body: JSON.stringify(body)
7248
+ };
7249
+ }
7250
+ /**
7251
+ * Arm a 6-digit code for a LAN pairing. In memory and single use. It stops
7252
+ * working after about 2 minutes, or after 5 wrong attempts from anyone. Rejects
7253
+ * with a `PairingError` when no store is configured or it has not loaded.
7254
+ */
7255
+ async armPairingCode() {
7256
+ return this.requirePairing().arm();
7257
+ }
7258
+ /** Cancel a live code. */
7259
+ disarmPairingCode() {
7260
+ this.pairing?.disarm();
7261
+ }
7262
+ /** What Settings shows, including the peer that consumed the last code. */
7263
+ getPairingState() {
7264
+ return this.pairing?.getState() ?? UNCONFIGURED_PAIRING_STATE;
7265
+ }
7266
+ /**
7267
+ * Replace the token, so every signature made with the old one stops verifying.
7268
+ * There are no network sockets to close, because none is ever admitted.
7269
+ */
7270
+ async revokePairing() {
7271
+ await this.requirePairing().revoke();
7272
+ }
7273
+ requirePairing() {
7274
+ if (!this.pairing) {
7275
+ throw new PairingError("PAIRING_UNCONFIGURED", "No pairingStore is configured.");
7276
+ }
7277
+ return this.pairing;
7278
+ }
6401
7279
  /**
6402
- * Handle incoming HTTP request
7280
+ * Handle incoming HTTP request, past the gate.
6403
7281
  *
6404
7282
  * Exposed as public so that CloudRelayClient can call it directly (without
6405
- * loopback TCP overhead) when processing tunneled requests.
7283
+ * loopback TCP overhead) when processing tunneled requests. Anything reached
7284
+ * from a socket goes through `handleNetworkRequest` first.
6406
7285
  */
6407
7286
  async handleRequest(request) {
6408
7287
  const headers = {
6409
- "Content-Type": "application/json"
7288
+ "Content-Type": "application/json",
7289
+ ...this.corsHeaders()
6410
7290
  };
6411
- if (this.config.cors) {
6412
- headers["Access-Control-Allow-Origin"] = this.config.allowedOrigins ? this.config.allowedOrigins.join(",") : "*";
6413
- headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";
6414
- headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization";
6415
- }
6416
7291
  if (request.method === "OPTIONS") {
6417
7292
  return { status: 204, headers, body: "" };
6418
7293
  }
@@ -6882,7 +7757,6 @@ var DeviceAnnouncer = class {
6882
7757
  */
6883
7758
  this.publishInFlight = false;
6884
7759
  this.config = config;
6885
- this.pairingToken = generateHex(16);
6886
7760
  }
6887
7761
  // ── mDNS ──────────────────────────────────────────────────────────────────
6888
7762
  /**
@@ -6918,8 +7792,7 @@ var DeviceAnnouncer = class {
6918
7792
  result = await zeroconf.publishService("uibridge", "tcp", "local.", serviceName, port, {
6919
7793
  device_id: this.config.deviceId,
6920
7794
  app_id: this.config.appId,
6921
- version: this.config.version ?? "unknown",
6922
- pairing_token: this.pairingToken
7795
+ version: this.config.version ?? "unknown"
6923
7796
  });
6924
7797
  } finally {
6925
7798
  this.publishInFlight = false;
@@ -7043,13 +7916,6 @@ var DeviceAnnouncer = class {
7043
7916
  this.reconnectDelay = Math.min(this.reconnectDelay * 2, RECONNECT_MAX_DELAY_MS);
7044
7917
  }
7045
7918
  };
7046
- function generateHex(bytes) {
7047
- const arr = new Uint8Array(bytes);
7048
- for (let i = 0; i < bytes; i++) {
7049
- arr[i] = Math.floor(Math.random() * 256);
7050
- }
7051
- return Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
7052
- }
7053
7919
  function getPlatform() {
7054
7920
  return reactNative.Platform?.OS ?? "unknown";
7055
7921
  }
@@ -7421,6 +8287,26 @@ function readWindowViewport() {
7421
8287
  const win = reactNative.Dimensions.get("window");
7422
8288
  return { width: win.width, height: win.height };
7423
8289
  }
8290
+ function useStablePairingStore(store) {
8291
+ const latestRef = react.useRef(store);
8292
+ react.useEffect(() => {
8293
+ latestRef.current = store;
8294
+ });
8295
+ const hasStore = store !== void 0;
8296
+ return react.useMemo(() => {
8297
+ if (!hasStore) return void 0;
8298
+ const current = () => {
8299
+ if (!latestRef.current) throw new Error("pairingStore was removed");
8300
+ return latestRef.current;
8301
+ };
8302
+ return {
8303
+ get: () => current().get(),
8304
+ set: (token) => current().set(token),
8305
+ clear: () => current().clear(),
8306
+ randomBytes: (n) => current().randomBytes(n)
8307
+ };
8308
+ }, [hasStore]);
8309
+ }
7424
8310
  function UIBridgeNativeProvider({
7425
8311
  children,
7426
8312
  features: featuresProp = EMPTY_FEATURES,
@@ -7434,10 +8320,13 @@ function UIBridgeNativeProvider({
7434
8320
  cloudRelayConfig,
7435
8321
  enableMdnsAnnounce,
7436
8322
  zeroconf,
7437
- deviceId
8323
+ deviceId,
8324
+ pairingStore: pairingStoreProp,
8325
+ allowUnauthenticatedNetwork
7438
8326
  }) {
7439
8327
  const features = useValueStable(featuresProp);
7440
8328
  const config = useValueStable(configProp);
8329
+ const pairingStore = useStablePairingStore(pairingStoreProp);
7441
8330
  const registryRef = react.useRef(null);
7442
8331
  const executorRef = react.useRef(null);
7443
8332
  const modalDetectorRef = react.useRef(null);
@@ -7468,6 +8357,11 @@ function UIBridgeNativeProvider({
7468
8357
  const eventBridgeRef = react.useRef(null);
7469
8358
  const announcerRef = react.useRef(null);
7470
8359
  const cloudRelayRef = react.useRef(null);
8360
+ const deviceIdRef = react.useRef(deviceId);
8361
+ react.useEffect(() => {
8362
+ deviceIdRef.current = deviceId;
8363
+ serverRef.current?.setDeviceId(deviceId);
8364
+ }, [deviceId]);
7471
8365
  const startServer = react.useCallback(async () => {
7472
8366
  if (!features.server) return;
7473
8367
  if (!serverAdapter) {
@@ -7488,7 +8382,10 @@ function UIBridgeNativeProvider({
7488
8382
  // Injected device-viewport getter for POST /control/page-health and the
7489
8383
  // design handlers. Same source as the registry's clipping bounds — see
7490
8384
  // `readWindowViewport`.
7491
- viewportProvider: readWindowViewport
8385
+ viewportProvider: readWindowViewport,
8386
+ pairingStore,
8387
+ allowUnauthenticatedNetwork,
8388
+ deviceId: deviceIdRef.current
7492
8389
  });
7493
8390
  server.setAdapter(serverAdapter);
7494
8391
  if (navigationProvider) {
@@ -7530,8 +8427,9 @@ function UIBridgeNativeProvider({
7530
8427
  server.abortWaitersForConnection(connId);
7531
8428
  eventBridge.removeConnection(connId);
7532
8429
  };
8430
+ wsAdapter.onWebSocketUpgrade = (req) => server.handleWebSocketUpgrade(req);
7533
8431
  wsAdapter.onWebSocketMessage = async (connId, message) => {
7534
- return server.handleWebSocketMessage(connId, message);
8432
+ return server.handleNetworkWebSocketMessage(connId, message);
7535
8433
  };
7536
8434
  eventBridge.start();
7537
8435
  eventBridgeRef.current = eventBridge;
@@ -7539,6 +8437,7 @@ function UIBridgeNativeProvider({
7539
8437
  try {
7540
8438
  await server.start();
7541
8439
  serverRef.current = server;
8440
+ server.setDeviceId(deviceIdRef.current);
7542
8441
  setServerRunning(true);
7543
8442
  } catch (err) {
7544
8443
  console.warn("[ui-bridge-native] Failed to start HTTP server:", err);
@@ -7555,7 +8454,9 @@ function UIBridgeNativeProvider({
7555
8454
  navigationProvider,
7556
8455
  screenshotProvider,
7557
8456
  keepAwakeProvider,
7558
- routeProvider
8457
+ routeProvider,
8458
+ pairingStore,
8459
+ allowUnauthenticatedNetwork
7559
8460
  ]);
7560
8461
  const stopServer = react.useCallback(() => {
7561
8462
  if (eventBridgeRef.current) {
@@ -7663,6 +8564,25 @@ function UIBridgeNativeProvider({
7663
8564
  const getCurrentRoute = react.useCallback(() => {
7664
8565
  return routeProvider?.getCurrentRoute() ?? null;
7665
8566
  }, [routeProvider]);
8567
+ const armPairingCode = react.useCallback(async () => {
8568
+ if (!serverRef.current) {
8569
+ throw new PairingError("PAIRING_UNCONFIGURED", "The UI Bridge server is not running.");
8570
+ }
8571
+ return serverRef.current.armPairingCode();
8572
+ }, []);
8573
+ const disarmPairingCode = react.useCallback(() => {
8574
+ serverRef.current?.disarmPairingCode();
8575
+ }, []);
8576
+ const getPairingState = react.useCallback(
8577
+ () => serverRef.current?.getPairingState() ?? UNCONFIGURED_PAIRING_STATE,
8578
+ []
8579
+ );
8580
+ const revokePairing = react.useCallback(async () => {
8581
+ if (!serverRef.current) {
8582
+ throw new PairingError("PAIRING_UNCONFIGURED", "The UI Bridge server is not running.");
8583
+ }
8584
+ await serverRef.current.revokePairing();
8585
+ }, []);
7666
8586
  react.useEffect(() => {
7667
8587
  if (!routeProvider) return;
7668
8588
  let lastRoute = routeProvider.getCurrentRoute();
@@ -7715,7 +8635,11 @@ function UIBridgeNativeProvider({
7715
8635
  serverRunning,
7716
8636
  startServer,
7717
8637
  stopServer,
7718
- getCurrentRoute
8638
+ getCurrentRoute,
8639
+ armPairingCode,
8640
+ disarmPairingCode,
8641
+ getPairingState,
8642
+ revokePairing
7719
8643
  }),
7720
8644
  [
7721
8645
  features,
@@ -7733,7 +8657,11 @@ function UIBridgeNativeProvider({
7733
8657
  serverRunning,
7734
8658
  startServer,
7735
8659
  stopServer,
7736
- getCurrentRoute
8660
+ getCurrentRoute,
8661
+ armPairingCode,
8662
+ disarmPairingCode,
8663
+ getPairingState,
8664
+ revokePairing
7737
8665
  ]
7738
8666
  );
7739
8667
  return /* @__PURE__ */ jsxRuntime.jsx(UIBridgeNativeContext, { value: contextValue, children });