@continuonai/rcan-ts 0.5.0 → 0.6.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/dist/browser.mjs CHANGED
@@ -99,7 +99,8 @@ var RobotURI = class _RobotURI {
99
99
  };
100
100
 
101
101
  // src/version.ts
102
- var SPEC_VERSION = "1.5";
102
+ var SPEC_VERSION = "1.6";
103
+ var SDK_VERSION = "0.6.0";
103
104
  function validateVersionCompat(incomingVersion, localVersion = SPEC_VERSION) {
104
105
  const parseParts = (v) => {
105
106
  const parts = v.split(".");
@@ -171,6 +172,12 @@ var RCANMessage = class _RCANMessage {
171
172
  __publicField(this, "presenceVerified");
172
173
  __publicField(this, "proximityMeters");
173
174
  __publicField(this, "readOnly");
175
+ /** v1.6: GAP-14 level of assurance */
176
+ __publicField(this, "loa");
177
+ /** v1.6: GAP-17 transport encoding hint */
178
+ __publicField(this, "transportEncoding");
179
+ /** v1.6: GAP-18 multi-modal media chunks */
180
+ __publicField(this, "mediaChunks");
174
181
  if (!data.cmd || data.cmd.trim() === "") {
175
182
  throw new RCANMessageError("'cmd' is required");
176
183
  }
@@ -195,6 +202,9 @@ var RCANMessage = class _RCANMessage {
195
202
  this.presenceVerified = data.presenceVerified;
196
203
  this.proximityMeters = data.proximityMeters;
197
204
  this.readOnly = data.readOnly;
205
+ this.loa = data.loa;
206
+ this.transportEncoding = data.transportEncoding;
207
+ this.mediaChunks = data.mediaChunks;
198
208
  if (this.confidence !== void 0) {
199
209
  if (this.confidence < 0 || this.confidence > 1) {
200
210
  throw new RCANMessageError(
@@ -233,6 +243,9 @@ var RCANMessage = class _RCANMessage {
233
243
  if (this.presenceVerified !== void 0) obj.presenceVerified = this.presenceVerified;
234
244
  if (this.proximityMeters !== void 0) obj.proximityMeters = this.proximityMeters;
235
245
  if (this.readOnly !== void 0) obj.readOnly = this.readOnly;
246
+ if (this.loa !== void 0) obj.loa = this.loa;
247
+ if (this.transportEncoding !== void 0) obj.transportEncoding = this.transportEncoding;
248
+ if (this.mediaChunks !== void 0) obj.mediaChunks = this.mediaChunks;
236
249
  return obj;
237
250
  }
238
251
  /** Serialize to JSON string */
@@ -272,7 +285,10 @@ var RCANMessage = class _RCANMessage {
272
285
  qos: obj.qos,
273
286
  presenceVerified: obj.presenceVerified,
274
287
  proximityMeters: obj.proximityMeters,
275
- readOnly: obj.readOnly
288
+ readOnly: obj.readOnly,
289
+ loa: obj.loa,
290
+ transportEncoding: obj.transportEncoding,
291
+ mediaChunks: obj.mediaChunks
276
292
  });
277
293
  }
278
294
  };
@@ -2030,23 +2046,645 @@ function makeFaultReport(params) {
2030
2046
  });
2031
2047
  }
2032
2048
 
2049
+ // src/identity.ts
2050
+ var LevelOfAssurance = /* @__PURE__ */ ((LevelOfAssurance2) => {
2051
+ LevelOfAssurance2[LevelOfAssurance2["ANONYMOUS"] = 1] = "ANONYMOUS";
2052
+ LevelOfAssurance2[LevelOfAssurance2["EMAIL_VERIFIED"] = 2] = "EMAIL_VERIFIED";
2053
+ LevelOfAssurance2[LevelOfAssurance2["HARDWARE_TOKEN"] = 3] = "HARDWARE_TOKEN";
2054
+ return LevelOfAssurance2;
2055
+ })(LevelOfAssurance || {});
2056
+ var DEFAULT_LOA_POLICY = {
2057
+ minLoaDiscover: 1 /* ANONYMOUS */,
2058
+ minLoaStatus: 1 /* ANONYMOUS */,
2059
+ minLoaChat: 1 /* ANONYMOUS */,
2060
+ minLoaControl: 1 /* ANONYMOUS */,
2061
+ minLoaSafety: 1 /* ANONYMOUS */
2062
+ };
2063
+ var PRODUCTION_LOA_POLICY = {
2064
+ minLoaDiscover: 1 /* ANONYMOUS */,
2065
+ minLoaStatus: 1 /* ANONYMOUS */,
2066
+ minLoaChat: 1 /* ANONYMOUS */,
2067
+ minLoaControl: 2 /* EMAIL_VERIFIED */,
2068
+ minLoaSafety: 3 /* HARDWARE_TOKEN */
2069
+ };
2070
+ function extractLoaFromJwt(token) {
2071
+ try {
2072
+ const parts = token.split(".");
2073
+ if (parts.length < 2) return 1 /* ANONYMOUS */;
2074
+ const payloadB64 = (parts[1] ?? "").replace(/-/g, "+").replace(/_/g, "/");
2075
+ const padded = payloadB64 + "=".repeat((4 - payloadB64.length % 4) % 4);
2076
+ let json;
2077
+ if (typeof atob !== "undefined") {
2078
+ json = atob(padded);
2079
+ } else {
2080
+ json = Buffer.from(padded, "base64").toString("utf-8");
2081
+ }
2082
+ const claims = JSON.parse(json);
2083
+ const loa = claims["loa"];
2084
+ if (typeof loa === "number" && loa >= 1 && loa <= 3) {
2085
+ return loa;
2086
+ }
2087
+ } catch {
2088
+ }
2089
+ return 1 /* ANONYMOUS */;
2090
+ }
2091
+ function minLoaForScope(scope, policy) {
2092
+ const s = scope.toLowerCase();
2093
+ switch (s) {
2094
+ case "discover":
2095
+ return policy.minLoaDiscover;
2096
+ case "status":
2097
+ return policy.minLoaStatus;
2098
+ case "chat":
2099
+ return policy.minLoaChat;
2100
+ case "control":
2101
+ return policy.minLoaControl;
2102
+ case "safety":
2103
+ return policy.minLoaSafety;
2104
+ default:
2105
+ return null;
2106
+ }
2107
+ }
2108
+ function validateLoaForScope(loa, scope, policy = DEFAULT_LOA_POLICY) {
2109
+ const min = minLoaForScope(scope, policy);
2110
+ if (min === null) {
2111
+ return { valid: true, reason: "unknown scope; allowed by default" };
2112
+ }
2113
+ if (loa >= min) {
2114
+ return { valid: true, reason: "ok" };
2115
+ }
2116
+ return {
2117
+ valid: false,
2118
+ reason: `LOA_INSUFFICIENT: scope=${scope} requires LoA>=${min}, caller has LoA=${loa}`
2119
+ };
2120
+ }
2121
+
2122
+ // src/federation.ts
2123
+ var RegistryTier = /* @__PURE__ */ ((RegistryTier2) => {
2124
+ RegistryTier2["ROOT"] = "root";
2125
+ RegistryTier2["AUTHORITATIVE"] = "authoritative";
2126
+ RegistryTier2["COMMUNITY"] = "community";
2127
+ return RegistryTier2;
2128
+ })(RegistryTier || {});
2129
+ var FederationSyncType = /* @__PURE__ */ ((FederationSyncType2) => {
2130
+ FederationSyncType2["CONSENT"] = "consent";
2131
+ FederationSyncType2["REVOCATION"] = "revocation";
2132
+ FederationSyncType2["KEY"] = "key";
2133
+ return FederationSyncType2;
2134
+ })(FederationSyncType || {});
2135
+ var CACHE_TTL_MS2 = 24 * 60 * 60 * 1e3;
2136
+ var TrustAnchorCache = class {
2137
+ constructor() {
2138
+ __publicField(this, "store", /* @__PURE__ */ new Map());
2139
+ }
2140
+ /** Store or refresh a registry identity. */
2141
+ set(identity) {
2142
+ this.store.set(identity.registryUrl, {
2143
+ identity,
2144
+ expiresAt: Date.now() + CACHE_TTL_MS2
2145
+ });
2146
+ }
2147
+ /**
2148
+ * Look up a registry URL.
2149
+ * Returns undefined when absent or when the TTL has expired.
2150
+ */
2151
+ lookup(url) {
2152
+ const entry = this.store.get(url);
2153
+ if (!entry) return void 0;
2154
+ if (Date.now() > entry.expiresAt) {
2155
+ this.store.delete(url);
2156
+ return void 0;
2157
+ }
2158
+ return entry.identity;
2159
+ }
2160
+ /**
2161
+ * Discover a registry via DNS TXT record `_rcan-registry.<domain>`.
2162
+ *
2163
+ * The TXT record is expected to contain a JSON object with the
2164
+ * RegistryIdentity fields. Returns the identity and caches it.
2165
+ *
2166
+ * Node.js only — returns undefined in environments without `dns.promises`.
2167
+ */
2168
+ async discoverViaDns(domain) {
2169
+ const hostname = `_rcan-registry.${domain}`;
2170
+ let records;
2171
+ try {
2172
+ const dnsModule = __require("dns");
2173
+ records = await dnsModule.promises.resolveTxt(hostname);
2174
+ } catch {
2175
+ return void 0;
2176
+ }
2177
+ for (const record of records) {
2178
+ const text = record.join("");
2179
+ try {
2180
+ const parsed = JSON.parse(text);
2181
+ if (parsed.registryUrl && parsed.tier && parsed.publicKeyPem && parsed.domain) {
2182
+ const identity = {
2183
+ registryUrl: parsed.registryUrl,
2184
+ tier: parsed.tier,
2185
+ publicKeyPem: parsed.publicKeyPem,
2186
+ domain: parsed.domain,
2187
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
2188
+ };
2189
+ this.set(identity);
2190
+ return identity;
2191
+ }
2192
+ } catch {
2193
+ }
2194
+ }
2195
+ return void 0;
2196
+ }
2197
+ /**
2198
+ * Verify a JWT was issued by the registry at `url`.
2199
+ *
2200
+ * Validates the `iss` claim and checks the registry is in the trust cache.
2201
+ * Full cryptographic signature verification requires the registry's public
2202
+ * key material — callers should perform additional checks using `publicKeyPem`
2203
+ * from the returned identity.
2204
+ */
2205
+ async verifyRegistryJwt(token, url) {
2206
+ const identity = this.lookup(url);
2207
+ if (!identity) {
2208
+ throw new Error(`REGISTRY_UNKNOWN: ${url} is not in the trust cache`);
2209
+ }
2210
+ let iss;
2211
+ try {
2212
+ const parts = token.split(".");
2213
+ const payloadB64 = (parts[1] ?? "").replace(/-/g, "+").replace(/_/g, "/");
2214
+ const padded = payloadB64 + "=".repeat((4 - payloadB64.length % 4) % 4);
2215
+ let json;
2216
+ if (typeof atob !== "undefined") {
2217
+ json = atob(padded);
2218
+ } else {
2219
+ json = Buffer.from(padded, "base64").toString("utf-8");
2220
+ }
2221
+ const claims = JSON.parse(json);
2222
+ iss = typeof claims["iss"] === "string" ? claims["iss"] : void 0;
2223
+ } catch {
2224
+ throw new Error("REGISTRY_JWT_MALFORMED: cannot decode token payload");
2225
+ }
2226
+ if (iss !== url) {
2227
+ throw new Error(
2228
+ `REGISTRY_JWT_ISS_MISMATCH: expected iss=${url}, got iss=${iss ?? "(none)"}`
2229
+ );
2230
+ }
2231
+ return identity;
2232
+ }
2233
+ };
2234
+ function generateId5() {
2235
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
2236
+ return crypto.randomUUID();
2237
+ }
2238
+ const bytes = Array.from({ length: 16 }, () => Math.floor(Math.random() * 256));
2239
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
2240
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
2241
+ const hex = bytes.map((b) => b.toString(16).padStart(2, "0"));
2242
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
2243
+ }
2244
+ function makeFederationSync(source, target, syncType, payload) {
2245
+ return new RCANMessage({
2246
+ rcan: "1.6",
2247
+ rcanVersion: "1.6",
2248
+ cmd: "federation_sync",
2249
+ target,
2250
+ params: {
2251
+ msg_type: 12 /* FEDERATION_SYNC */,
2252
+ msg_id: generateId5(),
2253
+ source_registry: source,
2254
+ target_registry: target,
2255
+ sync_type: syncType,
2256
+ payload
2257
+ },
2258
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2259
+ });
2260
+ }
2261
+ async function validateCrossRegistryCommand(msg, localRegistry, trustCache) {
2262
+ const msgType = msg.params?.["msg_type"];
2263
+ const isEstop = msgType === 6 /* SAFETY */ || msgType === 6 || msg.cmd === "estop" || msg.cmd === "ESTOP";
2264
+ if (isEstop) {
2265
+ return { valid: true, reason: "ESTOP always permitted (P66 invariant)" };
2266
+ }
2267
+ const sourceRegistry = msg.params?.["source_registry"] ?? msg.params?.["from_registry"];
2268
+ if (!sourceRegistry || sourceRegistry === localRegistry) {
2269
+ return { valid: true, reason: "local registry; no federation check needed" };
2270
+ }
2271
+ const identity = trustCache.lookup(sourceRegistry);
2272
+ if (!identity) {
2273
+ return {
2274
+ valid: false,
2275
+ reason: `REGISTRY_UNKNOWN: ${sourceRegistry} is not in the local trust cache`
2276
+ };
2277
+ }
2278
+ let loa = 1 /* ANONYMOUS */;
2279
+ const registryJwt = msg.params?.["registry_jwt"];
2280
+ if (registryJwt) {
2281
+ loa = extractLoaFromJwt(registryJwt);
2282
+ } else if (typeof msg.loa === "number") {
2283
+ loa = msg.loa;
2284
+ }
2285
+ if (loa < 2 /* EMAIL_VERIFIED */) {
2286
+ return {
2287
+ valid: false,
2288
+ reason: `LOA_INSUFFICIENT: cross-registry commands require LoA>=2 (EMAIL_VERIFIED), got LoA=${loa}`
2289
+ };
2290
+ }
2291
+ return { valid: true, reason: "cross-registry command accepted" };
2292
+ }
2293
+
2294
+ // src/transport.ts
2295
+ var TransportError = class _TransportError extends Error {
2296
+ constructor(message) {
2297
+ super(message);
2298
+ this.name = "TransportError";
2299
+ Object.setPrototypeOf(this, _TransportError.prototype);
2300
+ }
2301
+ };
2302
+ var TransportEncoding = /* @__PURE__ */ ((TransportEncoding2) => {
2303
+ TransportEncoding2["HTTP"] = "http";
2304
+ TransportEncoding2["COMPACT"] = "compact";
2305
+ TransportEncoding2["MINIMAL"] = "minimal";
2306
+ TransportEncoding2["BLE"] = "ble";
2307
+ return TransportEncoding2;
2308
+ })(TransportEncoding || {});
2309
+ var COMPACT_ENCODE = {
2310
+ msg_type: "t",
2311
+ msg_id: "i",
2312
+ timestamp: "ts",
2313
+ from_rrn: "f",
2314
+ to_rrn: "to",
2315
+ scope: "s",
2316
+ payload: "p",
2317
+ signature: "sig"
2318
+ };
2319
+ var COMPACT_DECODE = Object.fromEntries(
2320
+ Object.entries(COMPACT_ENCODE).map(([k, v]) => [v, k])
2321
+ );
2322
+ function encodeCompact(message) {
2323
+ const full = message.toJSON();
2324
+ const compact = {};
2325
+ for (const [key, value] of Object.entries(full)) {
2326
+ const short = COMPACT_ENCODE[key];
2327
+ compact[short ?? key] = value;
2328
+ }
2329
+ if (compact["p"] && typeof compact["p"] === "object") {
2330
+ const params = compact["p"];
2331
+ const compactParams = {};
2332
+ for (const [k, v] of Object.entries(params)) {
2333
+ const short = COMPACT_ENCODE[k];
2334
+ compactParams[short ?? k] = v;
2335
+ }
2336
+ compact["p"] = compactParams;
2337
+ }
2338
+ const json = JSON.stringify(compact);
2339
+ const encoder = new TextEncoder();
2340
+ return encoder.encode(json);
2341
+ }
2342
+ function decodeCompact(data) {
2343
+ const decoder = new TextDecoder();
2344
+ const json = decoder.decode(data);
2345
+ const compact = JSON.parse(json);
2346
+ const full = {};
2347
+ for (const [key, value] of Object.entries(compact)) {
2348
+ const long = COMPACT_DECODE[key];
2349
+ full[long ?? key] = value;
2350
+ }
2351
+ if (full["payload"] && typeof full["payload"] === "object") {
2352
+ const params = full["payload"];
2353
+ const expandedParams = {};
2354
+ for (const [k, v] of Object.entries(params)) {
2355
+ const long = COMPACT_DECODE[k];
2356
+ expandedParams[long ?? k] = v;
2357
+ }
2358
+ full["payload"] = expandedParams;
2359
+ }
2360
+ return new RCANMessage({
2361
+ rcan: full["rcan"] ?? "1.6",
2362
+ rcanVersion: full["rcanVersion"],
2363
+ cmd: full["cmd"],
2364
+ target: full["target"],
2365
+ params: full["params"] ?? full["payload"] ?? {},
2366
+ timestamp: full["timestamp"],
2367
+ confidence: full["confidence"],
2368
+ signature: full["signature"]
2369
+ });
2370
+ }
2371
+ var MINIMAL_SIZE = 32;
2372
+ var SAFETY_TYPE = 6;
2373
+ async function sha256Bytes(input) {
2374
+ const encoded = new TextEncoder().encode(input);
2375
+ const ab = new ArrayBuffer(encoded.byteLength);
2376
+ new Uint8Array(ab).set(encoded);
2377
+ const hashBuffer = await crypto.subtle.digest("SHA-256", ab);
2378
+ return new Uint8Array(hashBuffer);
2379
+ }
2380
+ async function encodeMinimal(message) {
2381
+ const msgType = message.params?.["msg_type"] ?? 0;
2382
+ if (msgType !== SAFETY_TYPE) {
2383
+ throw new TransportError(
2384
+ `encodeMinimal only supports SAFETY (type 6) messages; got type=${msgType}`
2385
+ );
2386
+ }
2387
+ const fromRrn = message.params?.["from_rrn"] ?? message.target ?? "";
2388
+ const toRrn = message.params?.["to_rrn"] ?? message.target ?? "";
2389
+ const fromHash = await sha256Bytes(fromRrn);
2390
+ const toHash = await sha256Bytes(toRrn);
2391
+ const sig = (message.signature?.sig ?? "").replace(/[^A-Za-z0-9+/=]/g, "");
2392
+ let sigBytes;
2393
+ try {
2394
+ if (typeof atob !== "undefined") {
2395
+ const raw = atob(sig.slice(0, 16));
2396
+ sigBytes = new Uint8Array(raw.length);
2397
+ for (let i = 0; i < raw.length; i++) sigBytes[i] = raw.charCodeAt(i);
2398
+ } else {
2399
+ sigBytes = Buffer.from(sig.slice(0, 16), "base64");
2400
+ }
2401
+ } catch {
2402
+ sigBytes = new Uint8Array(8);
2403
+ }
2404
+ const ts = message.timestamp ? Math.floor(new Date(message.timestamp).getTime() / 1e3) : Math.floor(Date.now() / 1e3);
2405
+ const unix32 = ts >>> 0;
2406
+ const out = new Uint8Array(MINIMAL_SIZE);
2407
+ const view = new DataView(out.buffer);
2408
+ view.setUint16(0, SAFETY_TYPE, false);
2409
+ out.set(fromHash.subarray(0, 8), 2);
2410
+ out.set(toHash.subarray(0, 8), 10);
2411
+ view.setUint32(18, unix32, false);
2412
+ const sigSlice = new Uint8Array(8);
2413
+ sigSlice.set(sigBytes.subarray(0, Math.min(8, sigBytes.length)));
2414
+ out.set(sigSlice, 22);
2415
+ let checksum = 0;
2416
+ for (let i = 0; i < 30; i++) checksum ^= out[i] ?? 0;
2417
+ view.setUint16(30, checksum & 65535, false);
2418
+ if (out.length !== MINIMAL_SIZE) {
2419
+ throw new TransportError(
2420
+ `encodeMinimal assertion failed: expected ${MINIMAL_SIZE} bytes, got ${out.length}`
2421
+ );
2422
+ }
2423
+ return out;
2424
+ }
2425
+ function decodeMinimal(data) {
2426
+ if (data.length !== MINIMAL_SIZE) {
2427
+ throw new TransportError(
2428
+ `decodeMinimal: expected ${MINIMAL_SIZE} bytes, got ${data.length}`
2429
+ );
2430
+ }
2431
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
2432
+ const msgType = view.getUint16(0, false);
2433
+ const fromHash = data.subarray(2, 10);
2434
+ const toHash = data.subarray(10, 18);
2435
+ const unix32 = view.getUint32(18, false);
2436
+ const sigTrunc = data.subarray(22, 30);
2437
+ const timestamp = new Date(unix32 * 1e3).toISOString();
2438
+ const toHex2 = (b) => Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
2439
+ return {
2440
+ params: {
2441
+ msg_type: msgType,
2442
+ from_hash: toHex2(fromHash),
2443
+ to_hash: toHex2(toHash),
2444
+ timestamp_s: unix32,
2445
+ sig_truncated: toHex2(sigTrunc)
2446
+ },
2447
+ timestamp
2448
+ };
2449
+ }
2450
+ var DEFAULT_MTU = 251;
2451
+ var BLE_HEADER_SIZE = 3;
2452
+ function encodeBleFrames(message, mtu = DEFAULT_MTU) {
2453
+ const payload = encodeCompact(message);
2454
+ const chunkSize = mtu - BLE_HEADER_SIZE;
2455
+ if (chunkSize <= 0) {
2456
+ throw new TransportError(`MTU ${mtu} is too small (need at least ${BLE_HEADER_SIZE + 1})`);
2457
+ }
2458
+ const totalChunks = Math.ceil(payload.length / chunkSize);
2459
+ const frames = [];
2460
+ for (let i = 0; i < totalChunks; i++) {
2461
+ const chunk = payload.subarray(i * chunkSize, (i + 1) * chunkSize);
2462
+ const frame = new Uint8Array(BLE_HEADER_SIZE + chunk.length);
2463
+ frame[0] = i;
2464
+ frame[1] = totalChunks;
2465
+ frame[2] = i === totalChunks - 1 ? 1 : 0;
2466
+ frame.set(chunk, BLE_HEADER_SIZE);
2467
+ frames.push(frame);
2468
+ }
2469
+ return frames;
2470
+ }
2471
+ function decodeBleFrames(frames) {
2472
+ if (frames.length === 0) {
2473
+ throw new TransportError("decodeBleFrames: no frames provided");
2474
+ }
2475
+ const sorted = [...frames].sort((a, b) => (a[0] ?? 0) - (b[0] ?? 0));
2476
+ const expectedTotal = sorted[0]?.[1] ?? sorted.length;
2477
+ if (sorted.length !== expectedTotal) {
2478
+ throw new TransportError(
2479
+ `decodeBleFrames: expected ${expectedTotal} frames, got ${sorted.length}`
2480
+ );
2481
+ }
2482
+ const payloadChunks = sorted.map((f) => f.subarray(BLE_HEADER_SIZE));
2483
+ const totalLen = payloadChunks.reduce((s, c) => s + c.length, 0);
2484
+ const payload = new Uint8Array(totalLen);
2485
+ let offset = 0;
2486
+ for (const chunk of payloadChunks) {
2487
+ payload.set(chunk, offset);
2488
+ offset += chunk.length;
2489
+ }
2490
+ return decodeCompact(payload);
2491
+ }
2492
+ function selectTransport(available, message) {
2493
+ const msgType = message.params?.["msg_type"] ?? 0;
2494
+ const isSafety = msgType === SAFETY_TYPE;
2495
+ const has = (enc) => available.includes(enc);
2496
+ if (isSafety) {
2497
+ if (has("minimal" /* MINIMAL */)) return "minimal" /* MINIMAL */;
2498
+ if (has("ble" /* BLE */)) return "ble" /* BLE */;
2499
+ if (has("compact" /* COMPACT */)) return "compact" /* COMPACT */;
2500
+ if (has("http" /* HTTP */)) return "http" /* HTTP */;
2501
+ } else {
2502
+ if (has("http" /* HTTP */)) return "http" /* HTTP */;
2503
+ if (has("compact" /* COMPACT */)) return "compact" /* COMPACT */;
2504
+ if (has("ble" /* BLE */)) return "ble" /* BLE */;
2505
+ }
2506
+ throw new TransportError(
2507
+ `No suitable transport available from: [${available.join(", ")}]`
2508
+ );
2509
+ }
2510
+
2511
+ // src/multimodal.ts
2512
+ var MediaEncoding = /* @__PURE__ */ ((MediaEncoding2) => {
2513
+ MediaEncoding2["BASE64"] = "base64";
2514
+ MediaEncoding2["REF"] = "ref";
2515
+ return MediaEncoding2;
2516
+ })(MediaEncoding || {});
2517
+ function generateId6() {
2518
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
2519
+ return crypto.randomUUID();
2520
+ }
2521
+ const bytes = Array.from({ length: 16 }, () => Math.floor(Math.random() * 256));
2522
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
2523
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
2524
+ const hex = bytes.map((b) => b.toString(16).padStart(2, "0"));
2525
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
2526
+ }
2527
+ async function computeSha256Hex(data) {
2528
+ const ab = new ArrayBuffer(data.byteLength);
2529
+ new Uint8Array(ab).set(data);
2530
+ const hashBuffer = await crypto.subtle.digest("SHA-256", ab);
2531
+ const hashArray = new Uint8Array(hashBuffer);
2532
+ return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
2533
+ }
2534
+ function uint8ToBase64(data) {
2535
+ if (typeof Buffer !== "undefined") {
2536
+ return Buffer.from(data).toString("base64");
2537
+ }
2538
+ let binary = "";
2539
+ for (let i = 0; i < data.length; i++) binary += String.fromCharCode(data[i] ?? 0);
2540
+ return btoa(binary);
2541
+ }
2542
+ function rebuildMessage(base, overrides) {
2543
+ const data = { ...base.toJSON(), ...overrides };
2544
+ return RCANMessage.fromJSON(data);
2545
+ }
2546
+ async function addMediaInline(message, data, mimeType) {
2547
+ const hashSha256 = await computeSha256Hex(data);
2548
+ const dataB64 = uint8ToBase64(data);
2549
+ const chunk = {
2550
+ chunkId: generateId6(),
2551
+ mimeType,
2552
+ encoding: "base64" /* BASE64 */,
2553
+ hashSha256,
2554
+ dataB64,
2555
+ sizeBytes: data.length
2556
+ };
2557
+ const existing = message.mediaChunks ?? [];
2558
+ return rebuildMessage(message, { mediaChunks: [...existing, chunk] });
2559
+ }
2560
+ function addMediaRef(message, refUrl, mimeType, hashSha256, sizeBytes) {
2561
+ const chunk = {
2562
+ chunkId: generateId6(),
2563
+ mimeType,
2564
+ encoding: "ref" /* REF */,
2565
+ hashSha256,
2566
+ refUrl,
2567
+ sizeBytes
2568
+ };
2569
+ const existing = message.mediaChunks ?? [];
2570
+ return rebuildMessage(message, { mediaChunks: [...existing, chunk] });
2571
+ }
2572
+ async function validateMediaChunks(message) {
2573
+ const chunks = message.mediaChunks ?? [];
2574
+ if (chunks.length === 0) {
2575
+ return { valid: true, reason: "no media chunks" };
2576
+ }
2577
+ for (let i = 0; i < chunks.length; i++) {
2578
+ const chunk = chunks[i];
2579
+ if (!chunk.chunkId) return { valid: false, reason: `chunk[${i}]: missing chunkId` };
2580
+ if (!chunk.mimeType) return { valid: false, reason: `chunk[${i}]: missing mimeType` };
2581
+ if (!chunk.hashSha256) return { valid: false, reason: `chunk[${i}]: missing hashSha256` };
2582
+ if (chunk.sizeBytes < 0) return { valid: false, reason: `chunk[${i}]: sizeBytes must be >= 0` };
2583
+ if (chunk.encoding === "base64" /* BASE64 */) {
2584
+ if (!chunk.dataB64) {
2585
+ return { valid: false, reason: `chunk[${i}]: BASE64 encoding requires dataB64` };
2586
+ }
2587
+ let decoded;
2588
+ try {
2589
+ if (typeof Buffer !== "undefined") {
2590
+ decoded = Buffer.from(chunk.dataB64, "base64");
2591
+ } else {
2592
+ const raw = atob(chunk.dataB64);
2593
+ decoded = new Uint8Array(raw.length);
2594
+ for (let j = 0; j < raw.length; j++) decoded[j] = raw.charCodeAt(j);
2595
+ }
2596
+ } catch {
2597
+ return { valid: false, reason: `chunk[${i}]: failed to decode base64 data` };
2598
+ }
2599
+ const actualHash = await computeSha256Hex(decoded);
2600
+ if (actualHash !== chunk.hashSha256) {
2601
+ return {
2602
+ valid: false,
2603
+ reason: `chunk[${i}]: SHA-256 mismatch (expected ${chunk.hashSha256}, got ${actualHash})`
2604
+ };
2605
+ }
2606
+ } else if (chunk.encoding === "ref" /* REF */) {
2607
+ if (!chunk.refUrl) {
2608
+ return { valid: false, reason: `chunk[${i}]: REF encoding requires refUrl` };
2609
+ }
2610
+ } else {
2611
+ return { valid: false, reason: `chunk[${i}]: unknown encoding '${chunk.encoding}'` };
2612
+ }
2613
+ }
2614
+ return { valid: true, reason: "ok" };
2615
+ }
2616
+ async function makeTrainingDataMessage(media) {
2617
+ let msg = new RCANMessage({
2618
+ rcan: "1.6",
2619
+ rcanVersion: "1.6",
2620
+ cmd: "training_data",
2621
+ target: "rcan://training/data",
2622
+ params: {
2623
+ msg_type: 10 /* TRAINING_DATA */,
2624
+ msg_id: generateId6()
2625
+ },
2626
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2627
+ });
2628
+ for (const item of media) {
2629
+ msg = await addMediaInline(msg, item.data, item.mimeType);
2630
+ }
2631
+ return msg;
2632
+ }
2633
+ async function makeStreamChunk(streamId, data, mimeType, chunkIndex, isFinal) {
2634
+ const hashSha256 = await computeSha256Hex(data);
2635
+ const dataB64 = uint8ToBase64(data);
2636
+ const chunk = {
2637
+ chunkId: generateId6(),
2638
+ mimeType,
2639
+ encoding: "base64" /* BASE64 */,
2640
+ hashSha256,
2641
+ dataB64,
2642
+ sizeBytes: data.length
2643
+ };
2644
+ const streamChunkMeta = {
2645
+ streamId,
2646
+ chunkIndex,
2647
+ isFinal,
2648
+ chunk
2649
+ };
2650
+ let msg = new RCANMessage({
2651
+ rcan: "1.6",
2652
+ rcanVersion: "1.6",
2653
+ cmd: "stream_chunk",
2654
+ target: "rcan://streaming/chunk",
2655
+ params: {
2656
+ msg_type: 7 /* SENSOR_DATA */,
2657
+ msg_id: generateId6(),
2658
+ stream_chunk: streamChunkMeta
2659
+ },
2660
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2661
+ });
2662
+ msg = rebuildMessage(msg, { mediaChunks: [chunk] });
2663
+ return msg;
2664
+ }
2665
+
2033
2666
  // src/index.ts
2034
- var VERSION = "0.5.0";
2035
- var RCAN_VERSION = "1.5";
2667
+ var VERSION = "0.6.0";
2668
+ var RCAN_VERSION = "1.6";
2036
2669
  export {
2037
2670
  AuditChain,
2038
2671
  AuditError,
2039
2672
  ClockDriftError,
2040
2673
  CommitmentRecord,
2041
2674
  ConfidenceGate,
2675
+ DEFAULT_LOA_POLICY,
2042
2676
  DataCategory,
2043
2677
  FaultCode,
2678
+ FederationSyncType,
2044
2679
  GateError,
2045
2680
  HiTLGate,
2046
2681
  KeyStore,
2682
+ LevelOfAssurance,
2683
+ MediaEncoding,
2047
2684
  MessageType,
2048
2685
  NodeClient,
2049
2686
  OfflineModeManager,
2687
+ PRODUCTION_LOA_POLICY,
2050
2688
  QoSAckTimeoutError,
2051
2689
  QoSLevel,
2052
2690
  QoSManager,
@@ -2068,17 +2706,31 @@ export {
2068
2706
  RCANVersionIncompatibleError,
2069
2707
  RCAN_VERSION,
2070
2708
  RegistryClient,
2709
+ RegistryTier,
2071
2710
  ReplayCache,
2072
2711
  RevocationCache,
2073
2712
  RobotURI,
2074
2713
  RobotURIError,
2075
2714
  SAFETY_MESSAGE_TYPE,
2715
+ SDK_VERSION,
2076
2716
  SPEC_VERSION,
2717
+ TransportEncoding,
2718
+ TransportError,
2719
+ TrustAnchorCache,
2077
2720
  VERSION,
2078
2721
  addDelegationHop,
2722
+ addMediaInline,
2723
+ addMediaRef,
2079
2724
  assertClockSynced,
2080
2725
  checkClockSync,
2081
2726
  checkRevocation,
2727
+ decodeBleFrames,
2728
+ decodeCompact,
2729
+ decodeMinimal,
2730
+ encodeBleFrames,
2731
+ encodeCompact,
2732
+ encodeMinimal,
2733
+ extractLoaFromJwt,
2082
2734
  fetchCanonicalSchema,
2083
2735
  isSafetyMessage,
2084
2736
  makeCloudRelayMessage,
@@ -2089,19 +2741,26 @@ export {
2089
2741
  makeEstopMessage,
2090
2742
  makeEstopWithQoS,
2091
2743
  makeFaultReport,
2744
+ makeFederationSync,
2092
2745
  makeKeyRotationMessage,
2093
2746
  makeResumeMessage,
2094
2747
  makeRevocationBroadcast,
2095
2748
  makeStopMessage,
2749
+ makeStreamChunk,
2096
2750
  makeTrainingConsentDeny,
2097
2751
  makeTrainingConsentGrant,
2098
2752
  makeTrainingConsentRequest,
2753
+ makeTrainingDataMessage,
2099
2754
  makeTransparencyMessage,
2755
+ selectTransport,
2100
2756
  validateConfig,
2101
2757
  validateConfigAgainstSchema,
2102
2758
  validateConfigUpdate,
2103
2759
  validateConsentMessage,
2760
+ validateCrossRegistryCommand,
2104
2761
  validateDelegationChain,
2762
+ validateLoaForScope,
2763
+ validateMediaChunks,
2105
2764
  validateMessage,
2106
2765
  validateNodeAgainstSchema,
2107
2766
  validateReplay,