@tinycloud/sdk-core 3.3.0-beta.17 → 3.3.0-beta.18

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/index.cjs CHANGED
@@ -170,6 +170,8 @@ __export(index_exports, {
170
170
  PermissionNotInManifestError: () => PermissionNotInManifestError,
171
171
  PrefixedKVService: () => import_sdk_services9.PrefixedKVService,
172
172
  ProtocolMismatchError: () => ProtocolMismatchError,
173
+ REGISTRY_LOOKUP_MAX_BODY_BYTES: () => REGISTRY_LOOKUP_MAX_BODY_BYTES,
174
+ REGISTRY_NOT_FOUND_BODY: () => REGISTRY_NOT_FOUND_BODY,
173
175
  REQUESTER_ENGINE_RETRY_ATTEMPTS: () => REQUESTER_ENGINE_RETRY_ATTEMPTS,
174
176
  REQUESTER_ENGINE_RETRY_MAX_DELAY_MS: () => REQUESTER_ENGINE_RETRY_MAX_DELAY_MS,
175
177
  REQUESTER_NEAR_EXPIRY_SECONDS: () => REQUESTER_NEAR_EXPIRY_SECONDS,
@@ -178,6 +180,7 @@ __export(index_exports, {
178
180
  ROOT_STATUS_CHECKPOINT_V1_SCHEMA: () => ROOT_STATUS_CHECKPOINT_V1_SCHEMA,
179
181
  ROOT_STATUS_RENEWAL_V1_DOMAIN: () => ROOT_STATUS_RENEWAL_V1_DOMAIN,
180
182
  ROOT_STATUS_V1_DOMAIN: () => ROOT_STATUS_V1_DOMAIN,
183
+ RegistryLookupInputError: () => RegistryLookupInputError,
181
184
  SECRETS_SPACE: () => SECRETS_SPACE,
182
185
  SECRET_NAME_RE: () => import_sdk_services9.SECRET_NAME_RE,
183
186
  SECRET_RECORDS_SCHEMA: () => import_bootstrap4.SECRET_RECORDS_SCHEMA,
@@ -277,6 +280,7 @@ __export(index_exports, {
277
280
  canonicalizeUnifiedPolicyCapability: () => canonicalizeUnifiedPolicyCapability,
278
281
  checkDecryptInvocationInput: () => import_sdk_services9.checkDecryptInvocationInput,
279
282
  checkNodeInfo: () => checkNodeInfo,
283
+ classifyRegistryLookup: () => classifyRegistryLookup,
280
284
  clearTinyCloudDebugLogs: () => import_sdk_services9.clearTinyCloudDebugLogs,
281
285
  compactAttenuationContains: () => compactAttenuationContains,
282
286
  composeBootstrapSpaceManifest: () => import_bootstrap4.composeBootstrapSpaceManifest,
@@ -19250,4 +19254,385 @@ function decodeBase64Url4(value) {
19250
19254
  }
19251
19255
  return Uint8Array.from(bytes2);
19252
19256
  }
19257
+
19258
+ // src/registry-verdict.ts
19259
+ var import_ed2551912 = require("@noble/curves/ed25519");
19260
+ var import_viem7 = require("viem");
19261
+ var RegistryLookupInputError = class extends TypeError {
19262
+ constructor(code3, message) {
19263
+ super(message);
19264
+ this.code = code3;
19265
+ this.name = "RegistryLookupInputError";
19266
+ }
19267
+ };
19268
+ var REGISTRY_LOOKUP_MAX_BODY_BYTES = 64 * 1024;
19269
+ var REGISTRY_NOT_FOUND_BODY = '{"error":"location record not found"}';
19270
+ var MAX_JSON_DEPTH = 32;
19271
+ var JSON_SIMPLE_ESCAPES = {
19272
+ '"': '"',
19273
+ "\\": "\\",
19274
+ "/": "/",
19275
+ b: "\b",
19276
+ f: "\f",
19277
+ n: "\n",
19278
+ r: "\r",
19279
+ t: " "
19280
+ };
19281
+ var SECP256K1_N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
19282
+ var BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
19283
+ var IPV4_OCTET = "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])";
19284
+ var IPV4 = new RegExp(`^${IPV4_OCTET}(\\.${IPV4_OCTET}){3}$`);
19285
+ var DNS_LABEL = "[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?";
19286
+ var DNS_NAME = new RegExp(`^${DNS_LABEL}(\\.${DNS_LABEL})*$`);
19287
+ var HOST_MULTIADDR = /^\/(ip4|ip6|dns|dns4|dns6)\/([^/]+)\/tcp\/([1-9][0-9]{0,4})\/(https|http|tls\/http)$/;
19288
+ var RFC3339_DATE_TIME = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?(Z|[+-]([0-9]{2}):([0-9]{2}))$/;
19289
+ async function classifyRegistryLookup(subject, response, options2 = {}) {
19290
+ if (!isCanonicalSubject(subject)) {
19291
+ throw new RegistryLookupInputError(
19292
+ "invalid-subject",
19293
+ "subject must be did:pkh:eip155:<chainId>:<EIP-55 address> or an Ed25519 did:key"
19294
+ );
19295
+ }
19296
+ const remembered = options2.rememberedSequence ?? null;
19297
+ if (remembered !== null && (!Number.isSafeInteger(remembered) || remembered < 0)) {
19298
+ throw new RegistryLookupInputError(
19299
+ "invalid-remembered-sequence",
19300
+ "rememberedSequence must be a non-negative safe integer"
19301
+ );
19302
+ }
19303
+ const unavailable = (reason, message) => ({
19304
+ status: "unavailable",
19305
+ subject,
19306
+ source: "offchain",
19307
+ reason,
19308
+ message,
19309
+ hosts: []
19310
+ });
19311
+ if (response.kind === "network-error") {
19312
+ return unavailable("network-error", "location registry could not be reached");
19313
+ }
19314
+ if (response.kind === "timeout") {
19315
+ return unavailable("timeout", "location registry lookup timed out");
19316
+ }
19317
+ if (response.status !== 200 && response.status !== 404) {
19318
+ return unavailable("http-status", `location registry returned HTTP ${response.status}`);
19319
+ }
19320
+ if (response.body.length > REGISTRY_LOOKUP_MAX_BODY_BYTES || new TextEncoder().encode(response.body).byteLength > REGISTRY_LOOKUP_MAX_BODY_BYTES) {
19321
+ return unavailable("oversize-response", "location registry response is too large");
19322
+ }
19323
+ if (response.status === 404) {
19324
+ const body = response.body;
19325
+ let start = 0;
19326
+ let end = body.length;
19327
+ while (start < end && " \n\r".includes(body[start])) start++;
19328
+ while (end > start && " \n\r".includes(body[end - 1])) end--;
19329
+ if (body.slice(start, end) !== REGISTRY_NOT_FOUND_BODY) {
19330
+ return unavailable(
19331
+ "malformed-response",
19332
+ "location registry 404 is not the registry's not-found response"
19333
+ );
19334
+ }
19335
+ if (remembered !== null) {
19336
+ return unavailable(
19337
+ "not-found-after-registered",
19338
+ `location registry has no record, but sequence ${remembered} was seen before`
19339
+ );
19340
+ }
19341
+ return { status: "unregistered", subject, source: "offchain", hosts: [] };
19342
+ }
19343
+ let record2;
19344
+ try {
19345
+ record2 = parseRecordResponse(response.body);
19346
+ } catch (error) {
19347
+ return unavailable(
19348
+ "malformed-response",
19349
+ error instanceof Error ? error.message : "location registry response is invalid"
19350
+ );
19351
+ }
19352
+ if (record2.subject !== subject) {
19353
+ return unavailable(
19354
+ "subject-mismatch",
19355
+ "location record subject does not match requested subject"
19356
+ );
19357
+ }
19358
+ if (!await verifyRecordSignature(record2)) {
19359
+ return unavailable("invalid-signature", "location record signature is invalid");
19360
+ }
19361
+ if (remembered !== null && record2.sequence < remembered) {
19362
+ return unavailable(
19363
+ "rollback",
19364
+ `location record sequence ${record2.sequence} is below remembered sequence ${remembered}`
19365
+ );
19366
+ }
19367
+ const hosts = [];
19368
+ for (const address of record2.multiaddrs) {
19369
+ const origin2 = multiaddrOrigin(address);
19370
+ if (origin2 !== null) hosts.push({ urls: [origin2], source: "offchain" });
19371
+ }
19372
+ return {
19373
+ status: "registered",
19374
+ subject,
19375
+ source: "offchain",
19376
+ sequence: record2.sequence,
19377
+ hosts
19378
+ };
19379
+ }
19380
+ function isCanonicalSubject(subject) {
19381
+ if (typeof subject !== "string") return false;
19382
+ const pkh = /^did:pkh:eip155:([1-9][0-9]*):(0x[0-9a-fA-F]{40})$/.exec(subject);
19383
+ if (pkh !== null) {
19384
+ try {
19385
+ return pkhDid(pkh[2], Number(pkh[1])) === subject;
19386
+ } catch {
19387
+ return false;
19388
+ }
19389
+ }
19390
+ return ed25519KeyFromDidKey(subject) !== null;
19391
+ }
19392
+ function ed25519KeyFromDidKey(did) {
19393
+ if (!did.startsWith("did:key:z")) return null;
19394
+ const identifier = did.slice("did:key:".length);
19395
+ let bytes2;
19396
+ try {
19397
+ bytes2 = bases.base58btc.decode(identifier);
19398
+ } catch {
19399
+ return null;
19400
+ }
19401
+ if (bytes2.length !== 34 || bytes2[0] !== 237 || bytes2[1] !== 1) {
19402
+ return null;
19403
+ }
19404
+ return bytes2.slice(2);
19405
+ }
19406
+ var JsonInteger = class {
19407
+ constructor(lexeme) {
19408
+ this.lexeme = lexeme;
19409
+ }
19410
+ };
19411
+ function parseStrictJson(text3) {
19412
+ let i = 0;
19413
+ const fail2 = (what) => {
19414
+ throw new SyntaxError(`location registry response is not strict JSON: ${what} at ${i}`);
19415
+ };
19416
+ const skipWhitespace2 = () => {
19417
+ while (i < text3.length && " \n\r".includes(text3[i])) i++;
19418
+ };
19419
+ const readHex4 = () => {
19420
+ const hex3 = text3.slice(i, i + 4);
19421
+ if (!/^[0-9a-fA-F]{4}$/.test(hex3)) fail2("bad \\u escape");
19422
+ i += 4;
19423
+ return parseInt(hex3, 16);
19424
+ };
19425
+ const parseString = () => {
19426
+ i++;
19427
+ let out = "";
19428
+ for (; ; ) {
19429
+ if (i >= text3.length) fail2("unterminated string");
19430
+ const code3 = text3.charCodeAt(i);
19431
+ if (code3 === 34) {
19432
+ i++;
19433
+ return out;
19434
+ }
19435
+ if (code3 < 32) fail2("control character in string");
19436
+ if (code3 === 92) {
19437
+ const escape2 = text3[i + 1];
19438
+ i += 2;
19439
+ if (escape2 !== void 0 && Object.prototype.hasOwnProperty.call(JSON_SIMPLE_ESCAPES, escape2)) {
19440
+ out += JSON_SIMPLE_ESCAPES[escape2];
19441
+ continue;
19442
+ }
19443
+ if (escape2 !== "u") fail2("bad escape");
19444
+ const unit = readHex4();
19445
+ if (unit >= 55296 && unit <= 56319) {
19446
+ if (text3[i] !== "\\" || text3[i + 1] !== "u") fail2("unpaired surrogate");
19447
+ i += 2;
19448
+ const low = readHex4();
19449
+ if (low < 56320 || low > 57343) fail2("unpaired surrogate");
19450
+ out += String.fromCharCode(unit, low);
19451
+ } else if (unit >= 56320 && unit <= 57343) {
19452
+ fail2("unpaired surrogate");
19453
+ } else {
19454
+ out += String.fromCharCode(unit);
19455
+ }
19456
+ continue;
19457
+ }
19458
+ out += text3[i];
19459
+ i++;
19460
+ }
19461
+ };
19462
+ const parseValue = (depth) => {
19463
+ skipWhitespace2();
19464
+ const c = text3[i];
19465
+ if (c === "{" || c === "[") {
19466
+ if (depth >= MAX_JSON_DEPTH) fail2("nesting too deep");
19467
+ i++;
19468
+ skipWhitespace2();
19469
+ const close = c === "{" ? "}" : "]";
19470
+ const object4 = /* @__PURE__ */ new Map();
19471
+ const array = [];
19472
+ if (text3[i] === close) {
19473
+ i++;
19474
+ return c === "{" ? object4 : array;
19475
+ }
19476
+ for (; ; ) {
19477
+ if (c === "{") {
19478
+ skipWhitespace2();
19479
+ if (text3[i] !== '"') fail2("expected key");
19480
+ const key = parseString();
19481
+ if (object4.has(key)) fail2("duplicate key");
19482
+ skipWhitespace2();
19483
+ if (text3[i] !== ":") fail2("expected ':'");
19484
+ i++;
19485
+ object4.set(key, parseValue(depth + 1));
19486
+ } else {
19487
+ array.push(parseValue(depth + 1));
19488
+ }
19489
+ skipWhitespace2();
19490
+ if (text3[i] === ",") {
19491
+ i++;
19492
+ continue;
19493
+ }
19494
+ if (text3[i] !== close) fail2(`expected ',' or '${close}'`);
19495
+ i++;
19496
+ return c === "{" ? object4 : array;
19497
+ }
19498
+ }
19499
+ if (c === '"') return parseString();
19500
+ for (const [literal, value2] of [["true", true], ["false", false], ["null", null]]) {
19501
+ if (text3.startsWith(literal, i)) {
19502
+ i += literal.length;
19503
+ return value2;
19504
+ }
19505
+ }
19506
+ const number = /-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y;
19507
+ number.lastIndex = i;
19508
+ const match = number.exec(text3);
19509
+ if (match === null) return fail2("unexpected token");
19510
+ if (match[2] !== void 0 || match[3] !== void 0) fail2("non-integer number");
19511
+ i += match[0].length;
19512
+ return new JsonInteger(match[0]);
19513
+ };
19514
+ const value = parseValue(0);
19515
+ skipWhitespace2();
19516
+ if (i !== text3.length) fail2("trailing data");
19517
+ return value;
19518
+ }
19519
+ function parseRecordResponse(body) {
19520
+ const root = parseStrictJson(body);
19521
+ const record2 = root instanceof Map ? root.get("record") : void 0;
19522
+ if (!(record2 instanceof Map)) {
19523
+ throw new SyntaxError("location registry response has no record object");
19524
+ }
19525
+ const version = record2.get("version");
19526
+ const subject = record2.get("subject");
19527
+ const multiaddrs = record2.get("multiaddrs");
19528
+ const updatedAt = record2.get("updated_at");
19529
+ const sequence = record2.get("sequence");
19530
+ const signature = record2.get("signature");
19531
+ if (!(version instanceof JsonInteger) || version.lexeme !== "1") {
19532
+ throw new SyntaxError("record.version must be the integer 1");
19533
+ }
19534
+ if (typeof subject !== "string") {
19535
+ throw new SyntaxError("record.subject must be a string");
19536
+ }
19537
+ if (!Array.isArray(multiaddrs) || !multiaddrs.every((entry) => typeof entry === "string" && entry.length > 0)) {
19538
+ throw new SyntaxError("record.multiaddrs must be an array of non-empty strings");
19539
+ }
19540
+ if (typeof updatedAt !== "string" || !isRfc3339DateTime(updatedAt)) {
19541
+ throw new SyntaxError("record.updated_at must be an RFC 3339 date-time");
19542
+ }
19543
+ if (!(sequence instanceof JsonInteger) || !/^(0|[1-9][0-9]*)$/.test(sequence.lexeme) || !Number.isSafeInteger(Number(sequence.lexeme))) {
19544
+ throw new SyntaxError("record.sequence must be a non-negative safe integer");
19545
+ }
19546
+ if (typeof signature !== "string" || signature.length === 0) {
19547
+ throw new SyntaxError("record.signature must be a non-empty string");
19548
+ }
19549
+ return {
19550
+ subject,
19551
+ multiaddrs,
19552
+ updated_at: updatedAt,
19553
+ sequence: Number(sequence.lexeme),
19554
+ signature
19555
+ };
19556
+ }
19557
+ function isRfc3339DateTime(value) {
19558
+ const match = RFC3339_DATE_TIME.exec(value);
19559
+ if (match === null) return false;
19560
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
19561
+ const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
19562
+ const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
19563
+ return daysInMonth !== void 0 && day >= 1 && day <= daysInMonth && hour <= 23 && minute <= 59 && second <= 59 && (match[8] === "Z" || Number(match[9]) <= 23 && Number(match[10]) <= 59);
19564
+ }
19565
+ async function verifyRecordSignature(record2) {
19566
+ const payload = canonicalLocationPayload({
19567
+ version: 1,
19568
+ subject: record2.subject,
19569
+ multiaddrs: record2.multiaddrs,
19570
+ updated_at: record2.updated_at,
19571
+ sequence: record2.sequence
19572
+ });
19573
+ const { signature } = record2;
19574
+ if (record2.subject.startsWith("did:pkh:")) {
19575
+ if (!/^0x[0-9a-fA-F]{130}$/.test(signature)) return false;
19576
+ const r = BigInt(`0x${signature.slice(2, 66)}`);
19577
+ const s = BigInt(`0x${signature.slice(66, 130)}`);
19578
+ const v = parseInt(signature.slice(130), 16);
19579
+ if (r === 0n || r >= SECP256K1_N || s === 0n || s > SECP256K1_N / 2n) return false;
19580
+ if (v !== 0 && v !== 1 && v !== 27 && v !== 28) return false;
19581
+ const address = record2.subject.slice(record2.subject.lastIndexOf(":") + 1);
19582
+ try {
19583
+ return await (0, import_viem7.verifyMessage)({
19584
+ address,
19585
+ message: payload,
19586
+ signature
19587
+ });
19588
+ } catch {
19589
+ return false;
19590
+ }
19591
+ }
19592
+ const publicKey = ed25519KeyFromDidKey(record2.subject);
19593
+ if (publicKey === null || !/^[A-Za-z0-9_-]{86}$/.test(signature)) return false;
19594
+ const bytes2 = new Uint8Array(64);
19595
+ let buffer = 0;
19596
+ let bits = 0;
19597
+ let length2 = 0;
19598
+ for (const char of signature) {
19599
+ buffer = (buffer << 6 | BASE64URL.indexOf(char)) & 65535;
19600
+ bits += 6;
19601
+ if (bits >= 8) {
19602
+ bits -= 8;
19603
+ bytes2[length2++] = buffer >> bits & 255;
19604
+ }
19605
+ }
19606
+ try {
19607
+ return import_ed2551912.ed25519.verify(bytes2, new TextEncoder().encode(payload), publicKey, { zip215: false });
19608
+ } catch {
19609
+ return false;
19610
+ }
19611
+ }
19612
+ function multiaddrOrigin(address) {
19613
+ const match = HOST_MULTIADDR.exec(address);
19614
+ if (match === null) return null;
19615
+ const [, protocol, host, portText, transport] = match;
19616
+ const port = Number(portText);
19617
+ if (port > 65535) return null;
19618
+ let authority;
19619
+ if (protocol === "ip4") {
19620
+ if (!IPV4.test(host)) return null;
19621
+ authority = host;
19622
+ } else if (protocol === "ip6") {
19623
+ if (!/^[0-9A-Fa-f:.]+$/.test(host) || !host.includes(":")) return null;
19624
+ authority = `[${host}]`;
19625
+ } else {
19626
+ if (host.length > 253 || !DNS_NAME.test(host) || /^(0[xX][0-9a-fA-F]*|[0-9]+)$/.test(host.slice(host.lastIndexOf(".") + 1))) {
19627
+ return null;
19628
+ }
19629
+ authority = host;
19630
+ }
19631
+ const scheme = transport === "http" ? "http" : "https";
19632
+ try {
19633
+ return new URL(`${scheme}://${authority}:${port}`).origin;
19634
+ } catch {
19635
+ return null;
19636
+ }
19637
+ }
19253
19638
  //# sourceMappingURL=index.cjs.map