@qontinui/ui-bridge-native 0.8.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.
- package/README.md +50 -2
- package/dist/core/index.js +13 -3
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.mjs +13 -3
- package/dist/core/index.mjs.map +1 -1
- package/dist/core/sha256.d.ts +29 -7
- package/dist/core/sha256.d.ts.map +1 -1
- package/dist/debug/index.js.map +1 -1
- package/dist/debug/index.mjs.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +996 -32
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +986 -34
- package/dist/index.mjs.map +1 -1
- package/dist/observation/observation.d.ts +15 -1
- package/dist/observation/observation.d.ts.map +1 -1
- package/dist/react/UIBridgeNativeProvider.d.ts +25 -3
- package/dist/react/UIBridgeNativeProvider.d.ts.map +1 -1
- package/dist/react/index.js +967 -32
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +968 -33
- package/dist/react/index.mjs.map +1 -1
- package/dist/server/handlers.d.ts.map +1 -1
- package/dist/server/http-server.d.ts +120 -2
- package/dist/server/http-server.d.ts.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +934 -16
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +916 -17
- package/dist/server/index.mjs.map +1 -1
- package/dist/server/pairing.d.ts +295 -0
- package/dist/server/pairing.d.ts.map +1 -0
- package/dist/server/types.d.ts +20 -0
- package/dist/server/types.d.ts.map +1 -1
- package/dist/transport/DeviceAnnouncer.d.ts +0 -2
- package/dist/transport/DeviceAnnouncer.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/react/index.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
|
@@ -3422,7 +3452,14 @@ var UNKNOWN_CODES = [
|
|
|
3422
3452
|
"below_confidence_floor",
|
|
3423
3453
|
"model_reply_unparseable",
|
|
3424
3454
|
"needs_multi_frame_input",
|
|
3425
|
-
"stale_input"
|
|
3455
|
+
"stale_input",
|
|
3456
|
+
"frontier_open",
|
|
3457
|
+
"ledger_schema_absent",
|
|
3458
|
+
"ledger_write_failing",
|
|
3459
|
+
"no_observations",
|
|
3460
|
+
"to_node_unobserved",
|
|
3461
|
+
"performance_observer_unsupported",
|
|
3462
|
+
"no_event_before_timeout"
|
|
3426
3463
|
];
|
|
3427
3464
|
function isUnknownCode(value) {
|
|
3428
3465
|
return typeof value === "string" && UNKNOWN_CODES.includes(value);
|
|
@@ -3612,7 +3649,7 @@ var NATIVE_PAGE_HEALTH_PRODUCER_ID = "sdk-native/page-health";
|
|
|
3612
3649
|
function defaultProducer() {
|
|
3613
3650
|
return {
|
|
3614
3651
|
id: NATIVE_PAGE_HEALTH_PRODUCER_ID,
|
|
3615
|
-
version: "0.
|
|
3652
|
+
version: "0.11.0"
|
|
3616
3653
|
};
|
|
3617
3654
|
}
|
|
3618
3655
|
function pageHealthUnknown(code, detail, options = {}) {
|
|
@@ -4515,6 +4552,16 @@ function createServerHandlers(registry, executor, config) {
|
|
|
4515
4552
|
// the envelope agree; an unmounted path answers 404 instead. Each error
|
|
4516
4553
|
// message names an in-tree mobile replacement so operators aren't left
|
|
4517
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
|
+
},
|
|
4518
4565
|
aiForms: async () => {
|
|
4519
4566
|
return error2(
|
|
4520
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.',
|
|
@@ -4909,7 +4956,7 @@ function createServerHandlers(registry, executor, config) {
|
|
|
4909
4956
|
};
|
|
4910
4957
|
if (config?.appInfo) {
|
|
4911
4958
|
response.uiBridge = {
|
|
4912
|
-
version: "0.
|
|
4959
|
+
version: "0.11.0",
|
|
4913
4960
|
...config.appInfo,
|
|
4914
4961
|
capabilities: ["elements", "components", "actions", "design"],
|
|
4915
4962
|
elementCount: stats.elements,
|
|
@@ -4921,6 +4968,516 @@ function createServerHandlers(registry, executor, config) {
|
|
|
4921
4968
|
};
|
|
4922
4969
|
}
|
|
4923
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
|
+
|
|
4924
5481
|
// src/server/observability.ts
|
|
4925
5482
|
var RingBuffer = class {
|
|
4926
5483
|
constructor(capacity) {
|
|
@@ -5251,7 +5808,20 @@ function isUnsubscribe(msg) {
|
|
|
5251
5808
|
var ERROR_CODE_HTTP_STATUS = /* @__PURE__ */ new Map([
|
|
5252
5809
|
["NOT_SUPPORTED", 501],
|
|
5253
5810
|
["NOT_FOUND", 404],
|
|
5254
|
-
["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]
|
|
5255
5825
|
]);
|
|
5256
5826
|
function httpStatusForResponse(response) {
|
|
5257
5827
|
if (response.success) return 200;
|
|
@@ -5277,6 +5847,10 @@ function parsePath(pattern, actual) {
|
|
|
5277
5847
|
var WS_ROUTES = [
|
|
5278
5848
|
// Health
|
|
5279
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"] },
|
|
5280
5854
|
// Elements
|
|
5281
5855
|
{ pattern: "control/elements", handler: "getElements", httpMethods: ["GET"] },
|
|
5282
5856
|
// Flat alias — matches the runner UI Bridge's `/ui-bridge/elements` path so
|
|
@@ -5439,6 +6013,7 @@ function allowedMethodsForPath(path, testHooks) {
|
|
|
5439
6013
|
}
|
|
5440
6014
|
var HANDLER_DESCRIPTIONS = {
|
|
5441
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",
|
|
5442
6017
|
getElements: "Flat list of registered UI elements",
|
|
5443
6018
|
getElement: "Single element by id",
|
|
5444
6019
|
getElementState: "Dynamic state (value, focused, checked) for one element",
|
|
@@ -5540,10 +6115,24 @@ function buildHelpPayload(testHooks) {
|
|
|
5540
6115
|
]
|
|
5541
6116
|
};
|
|
5542
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
|
+
}
|
|
5543
6128
|
var NativeUIBridgeServer = class {
|
|
5544
6129
|
constructor(registry, executor, config = {}) {
|
|
5545
6130
|
this.registry = registry;
|
|
5546
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;
|
|
5547
6136
|
this.running = false;
|
|
5548
6137
|
/**
|
|
5549
6138
|
* Per-connection cleanup thunks for in-flight waiters (waitForElement,
|
|
@@ -5556,6 +6145,9 @@ var NativeUIBridgeServer = class {
|
|
|
5556
6145
|
cors: true,
|
|
5557
6146
|
...config
|
|
5558
6147
|
};
|
|
6148
|
+
if (this.config.pairingStore) {
|
|
6149
|
+
this.pairing = new PairingAuthority(this.config.pairingStore);
|
|
6150
|
+
}
|
|
5559
6151
|
this.consoleErrorBuffer = new ConsoleErrorBuffer();
|
|
5560
6152
|
this.networkRequestBuffer = new NetworkRequestBuffer();
|
|
5561
6153
|
if (this.config.appInfo) {
|
|
@@ -5601,6 +6193,14 @@ var NativeUIBridgeServer = class {
|
|
|
5601
6193
|
setAdapter(adapter) {
|
|
5602
6194
|
this.adapter = adapter;
|
|
5603
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
|
+
}
|
|
5604
6204
|
/**
|
|
5605
6205
|
* Set a navigation provider for programmatic route navigation.
|
|
5606
6206
|
* This enables `control/page/navigate` and `control/page/back` on native.
|
|
@@ -5834,7 +6434,18 @@ var NativeUIBridgeServer = class {
|
|
|
5834
6434
|
this.consoleErrorBuffer.install();
|
|
5835
6435
|
this.networkRequestBuffer.install();
|
|
5836
6436
|
}
|
|
5837
|
-
|
|
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));
|
|
5838
6449
|
this.running = true;
|
|
5839
6450
|
console.log(`[ui-bridge-native] HTTP server started on port ${this.config.serverPort}`);
|
|
5840
6451
|
}
|
|
@@ -5863,6 +6474,26 @@ var NativeUIBridgeServer = class {
|
|
|
5863
6474
|
setEventBridge(bridge) {
|
|
5864
6475
|
this.eventBridge = bridge;
|
|
5865
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
|
+
}
|
|
5866
6497
|
/**
|
|
5867
6498
|
* Handle a JSON-RPC message from a WebSocket client.
|
|
5868
6499
|
* Parses the message, routes to the appropriate handler, and returns
|
|
@@ -6391,21 +7022,272 @@ var NativeUIBridgeServer = class {
|
|
|
6391
7022
|
timestamp: Date.now()
|
|
6392
7023
|
};
|
|
6393
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
|
+
}
|
|
6394
7279
|
/**
|
|
6395
|
-
* Handle incoming HTTP request
|
|
7280
|
+
* Handle incoming HTTP request, past the gate.
|
|
6396
7281
|
*
|
|
6397
7282
|
* Exposed as public so that CloudRelayClient can call it directly (without
|
|
6398
|
-
* 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.
|
|
6399
7285
|
*/
|
|
6400
7286
|
async handleRequest(request) {
|
|
6401
7287
|
const headers = {
|
|
6402
|
-
"Content-Type": "application/json"
|
|
7288
|
+
"Content-Type": "application/json",
|
|
7289
|
+
...this.corsHeaders()
|
|
6403
7290
|
};
|
|
6404
|
-
if (this.config.cors) {
|
|
6405
|
-
headers["Access-Control-Allow-Origin"] = this.config.allowedOrigins ? this.config.allowedOrigins.join(",") : "*";
|
|
6406
|
-
headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";
|
|
6407
|
-
headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization";
|
|
6408
|
-
}
|
|
6409
7291
|
if (request.method === "OPTIONS") {
|
|
6410
7292
|
return { status: 204, headers, body: "" };
|
|
6411
7293
|
}
|
|
@@ -6875,7 +7757,6 @@ var DeviceAnnouncer = class {
|
|
|
6875
7757
|
*/
|
|
6876
7758
|
this.publishInFlight = false;
|
|
6877
7759
|
this.config = config;
|
|
6878
|
-
this.pairingToken = generateHex(16);
|
|
6879
7760
|
}
|
|
6880
7761
|
// ── mDNS ──────────────────────────────────────────────────────────────────
|
|
6881
7762
|
/**
|
|
@@ -6911,8 +7792,7 @@ var DeviceAnnouncer = class {
|
|
|
6911
7792
|
result = await zeroconf.publishService("uibridge", "tcp", "local.", serviceName, port, {
|
|
6912
7793
|
device_id: this.config.deviceId,
|
|
6913
7794
|
app_id: this.config.appId,
|
|
6914
|
-
version: this.config.version ?? "unknown"
|
|
6915
|
-
pairing_token: this.pairingToken
|
|
7795
|
+
version: this.config.version ?? "unknown"
|
|
6916
7796
|
});
|
|
6917
7797
|
} finally {
|
|
6918
7798
|
this.publishInFlight = false;
|
|
@@ -7036,13 +7916,6 @@ var DeviceAnnouncer = class {
|
|
|
7036
7916
|
this.reconnectDelay = Math.min(this.reconnectDelay * 2, RECONNECT_MAX_DELAY_MS);
|
|
7037
7917
|
}
|
|
7038
7918
|
};
|
|
7039
|
-
function generateHex(bytes) {
|
|
7040
|
-
const arr = new Uint8Array(bytes);
|
|
7041
|
-
for (let i = 0; i < bytes; i++) {
|
|
7042
|
-
arr[i] = Math.floor(Math.random() * 256);
|
|
7043
|
-
}
|
|
7044
|
-
return Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
7045
|
-
}
|
|
7046
7919
|
function getPlatform() {
|
|
7047
7920
|
return reactNative.Platform?.OS ?? "unknown";
|
|
7048
7921
|
}
|
|
@@ -7414,6 +8287,26 @@ function readWindowViewport() {
|
|
|
7414
8287
|
const win = reactNative.Dimensions.get("window");
|
|
7415
8288
|
return { width: win.width, height: win.height };
|
|
7416
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
|
+
}
|
|
7417
8310
|
function UIBridgeNativeProvider({
|
|
7418
8311
|
children,
|
|
7419
8312
|
features: featuresProp = EMPTY_FEATURES,
|
|
@@ -7427,10 +8320,13 @@ function UIBridgeNativeProvider({
|
|
|
7427
8320
|
cloudRelayConfig,
|
|
7428
8321
|
enableMdnsAnnounce,
|
|
7429
8322
|
zeroconf,
|
|
7430
|
-
deviceId
|
|
8323
|
+
deviceId,
|
|
8324
|
+
pairingStore: pairingStoreProp,
|
|
8325
|
+
allowUnauthenticatedNetwork
|
|
7431
8326
|
}) {
|
|
7432
8327
|
const features = useValueStable(featuresProp);
|
|
7433
8328
|
const config = useValueStable(configProp);
|
|
8329
|
+
const pairingStore = useStablePairingStore(pairingStoreProp);
|
|
7434
8330
|
const registryRef = react.useRef(null);
|
|
7435
8331
|
const executorRef = react.useRef(null);
|
|
7436
8332
|
const modalDetectorRef = react.useRef(null);
|
|
@@ -7461,6 +8357,11 @@ function UIBridgeNativeProvider({
|
|
|
7461
8357
|
const eventBridgeRef = react.useRef(null);
|
|
7462
8358
|
const announcerRef = react.useRef(null);
|
|
7463
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]);
|
|
7464
8365
|
const startServer = react.useCallback(async () => {
|
|
7465
8366
|
if (!features.server) return;
|
|
7466
8367
|
if (!serverAdapter) {
|
|
@@ -7481,7 +8382,10 @@ function UIBridgeNativeProvider({
|
|
|
7481
8382
|
// Injected device-viewport getter for POST /control/page-health and the
|
|
7482
8383
|
// design handlers. Same source as the registry's clipping bounds — see
|
|
7483
8384
|
// `readWindowViewport`.
|
|
7484
|
-
viewportProvider: readWindowViewport
|
|
8385
|
+
viewportProvider: readWindowViewport,
|
|
8386
|
+
pairingStore,
|
|
8387
|
+
allowUnauthenticatedNetwork,
|
|
8388
|
+
deviceId: deviceIdRef.current
|
|
7485
8389
|
});
|
|
7486
8390
|
server.setAdapter(serverAdapter);
|
|
7487
8391
|
if (navigationProvider) {
|
|
@@ -7523,8 +8427,9 @@ function UIBridgeNativeProvider({
|
|
|
7523
8427
|
server.abortWaitersForConnection(connId);
|
|
7524
8428
|
eventBridge.removeConnection(connId);
|
|
7525
8429
|
};
|
|
8430
|
+
wsAdapter.onWebSocketUpgrade = (req) => server.handleWebSocketUpgrade(req);
|
|
7526
8431
|
wsAdapter.onWebSocketMessage = async (connId, message) => {
|
|
7527
|
-
return server.
|
|
8432
|
+
return server.handleNetworkWebSocketMessage(connId, message);
|
|
7528
8433
|
};
|
|
7529
8434
|
eventBridge.start();
|
|
7530
8435
|
eventBridgeRef.current = eventBridge;
|
|
@@ -7532,6 +8437,7 @@ function UIBridgeNativeProvider({
|
|
|
7532
8437
|
try {
|
|
7533
8438
|
await server.start();
|
|
7534
8439
|
serverRef.current = server;
|
|
8440
|
+
server.setDeviceId(deviceIdRef.current);
|
|
7535
8441
|
setServerRunning(true);
|
|
7536
8442
|
} catch (err) {
|
|
7537
8443
|
console.warn("[ui-bridge-native] Failed to start HTTP server:", err);
|
|
@@ -7548,7 +8454,9 @@ function UIBridgeNativeProvider({
|
|
|
7548
8454
|
navigationProvider,
|
|
7549
8455
|
screenshotProvider,
|
|
7550
8456
|
keepAwakeProvider,
|
|
7551
|
-
routeProvider
|
|
8457
|
+
routeProvider,
|
|
8458
|
+
pairingStore,
|
|
8459
|
+
allowUnauthenticatedNetwork
|
|
7552
8460
|
]);
|
|
7553
8461
|
const stopServer = react.useCallback(() => {
|
|
7554
8462
|
if (eventBridgeRef.current) {
|
|
@@ -7656,6 +8564,25 @@ function UIBridgeNativeProvider({
|
|
|
7656
8564
|
const getCurrentRoute = react.useCallback(() => {
|
|
7657
8565
|
return routeProvider?.getCurrentRoute() ?? null;
|
|
7658
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
|
+
}, []);
|
|
7659
8586
|
react.useEffect(() => {
|
|
7660
8587
|
if (!routeProvider) return;
|
|
7661
8588
|
let lastRoute = routeProvider.getCurrentRoute();
|
|
@@ -7708,7 +8635,11 @@ function UIBridgeNativeProvider({
|
|
|
7708
8635
|
serverRunning,
|
|
7709
8636
|
startServer,
|
|
7710
8637
|
stopServer,
|
|
7711
|
-
getCurrentRoute
|
|
8638
|
+
getCurrentRoute,
|
|
8639
|
+
armPairingCode,
|
|
8640
|
+
disarmPairingCode,
|
|
8641
|
+
getPairingState,
|
|
8642
|
+
revokePairing
|
|
7712
8643
|
}),
|
|
7713
8644
|
[
|
|
7714
8645
|
features,
|
|
@@ -7726,7 +8657,11 @@ function UIBridgeNativeProvider({
|
|
|
7726
8657
|
serverRunning,
|
|
7727
8658
|
startServer,
|
|
7728
8659
|
stopServer,
|
|
7729
|
-
getCurrentRoute
|
|
8660
|
+
getCurrentRoute,
|
|
8661
|
+
armPairingCode,
|
|
8662
|
+
disarmPairingCode,
|
|
8663
|
+
getPairingState,
|
|
8664
|
+
revokePairing
|
|
7730
8665
|
]
|
|
7731
8666
|
);
|
|
7732
8667
|
return /* @__PURE__ */ jsxRuntime.jsx(UIBridgeNativeContext, { value: contextValue, children });
|