@tinycloud/sdk-core 3.3.0-beta.15 → 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.js CHANGED
@@ -18926,6 +18926,387 @@ function decodeBase64Url4(value) {
18926
18926
  }
18927
18927
  return Uint8Array.from(bytes2);
18928
18928
  }
18929
+
18930
+ // src/registry-verdict.ts
18931
+ import { ed25519 as ed2551912 } from "@noble/curves/ed25519";
18932
+ import { verifyMessage as verifyMessage3 } from "viem";
18933
+ var RegistryLookupInputError = class extends TypeError {
18934
+ constructor(code3, message) {
18935
+ super(message);
18936
+ this.code = code3;
18937
+ this.name = "RegistryLookupInputError";
18938
+ }
18939
+ };
18940
+ var REGISTRY_LOOKUP_MAX_BODY_BYTES = 64 * 1024;
18941
+ var REGISTRY_NOT_FOUND_BODY = '{"error":"location record not found"}';
18942
+ var MAX_JSON_DEPTH = 32;
18943
+ var JSON_SIMPLE_ESCAPES = {
18944
+ '"': '"',
18945
+ "\\": "\\",
18946
+ "/": "/",
18947
+ b: "\b",
18948
+ f: "\f",
18949
+ n: "\n",
18950
+ r: "\r",
18951
+ t: " "
18952
+ };
18953
+ var SECP256K1_N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
18954
+ var BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
18955
+ var IPV4_OCTET = "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])";
18956
+ var IPV4 = new RegExp(`^${IPV4_OCTET}(\\.${IPV4_OCTET}){3}$`);
18957
+ var DNS_LABEL = "[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?";
18958
+ var DNS_NAME = new RegExp(`^${DNS_LABEL}(\\.${DNS_LABEL})*$`);
18959
+ var HOST_MULTIADDR = /^\/(ip4|ip6|dns|dns4|dns6)\/([^/]+)\/tcp\/([1-9][0-9]{0,4})\/(https|http|tls\/http)$/;
18960
+ 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}))$/;
18961
+ async function classifyRegistryLookup(subject, response, options2 = {}) {
18962
+ if (!isCanonicalSubject(subject)) {
18963
+ throw new RegistryLookupInputError(
18964
+ "invalid-subject",
18965
+ "subject must be did:pkh:eip155:<chainId>:<EIP-55 address> or an Ed25519 did:key"
18966
+ );
18967
+ }
18968
+ const remembered = options2.rememberedSequence ?? null;
18969
+ if (remembered !== null && (!Number.isSafeInteger(remembered) || remembered < 0)) {
18970
+ throw new RegistryLookupInputError(
18971
+ "invalid-remembered-sequence",
18972
+ "rememberedSequence must be a non-negative safe integer"
18973
+ );
18974
+ }
18975
+ const unavailable = (reason, message) => ({
18976
+ status: "unavailable",
18977
+ subject,
18978
+ source: "offchain",
18979
+ reason,
18980
+ message,
18981
+ hosts: []
18982
+ });
18983
+ if (response.kind === "network-error") {
18984
+ return unavailable("network-error", "location registry could not be reached");
18985
+ }
18986
+ if (response.kind === "timeout") {
18987
+ return unavailable("timeout", "location registry lookup timed out");
18988
+ }
18989
+ if (response.status !== 200 && response.status !== 404) {
18990
+ return unavailable("http-status", `location registry returned HTTP ${response.status}`);
18991
+ }
18992
+ if (response.body.length > REGISTRY_LOOKUP_MAX_BODY_BYTES || new TextEncoder().encode(response.body).byteLength > REGISTRY_LOOKUP_MAX_BODY_BYTES) {
18993
+ return unavailable("oversize-response", "location registry response is too large");
18994
+ }
18995
+ if (response.status === 404) {
18996
+ const body = response.body;
18997
+ let start = 0;
18998
+ let end = body.length;
18999
+ while (start < end && " \n\r".includes(body[start])) start++;
19000
+ while (end > start && " \n\r".includes(body[end - 1])) end--;
19001
+ if (body.slice(start, end) !== REGISTRY_NOT_FOUND_BODY) {
19002
+ return unavailable(
19003
+ "malformed-response",
19004
+ "location registry 404 is not the registry's not-found response"
19005
+ );
19006
+ }
19007
+ if (remembered !== null) {
19008
+ return unavailable(
19009
+ "not-found-after-registered",
19010
+ `location registry has no record, but sequence ${remembered} was seen before`
19011
+ );
19012
+ }
19013
+ return { status: "unregistered", subject, source: "offchain", hosts: [] };
19014
+ }
19015
+ let record2;
19016
+ try {
19017
+ record2 = parseRecordResponse(response.body);
19018
+ } catch (error) {
19019
+ return unavailable(
19020
+ "malformed-response",
19021
+ error instanceof Error ? error.message : "location registry response is invalid"
19022
+ );
19023
+ }
19024
+ if (record2.subject !== subject) {
19025
+ return unavailable(
19026
+ "subject-mismatch",
19027
+ "location record subject does not match requested subject"
19028
+ );
19029
+ }
19030
+ if (!await verifyRecordSignature(record2)) {
19031
+ return unavailable("invalid-signature", "location record signature is invalid");
19032
+ }
19033
+ if (remembered !== null && record2.sequence < remembered) {
19034
+ return unavailable(
19035
+ "rollback",
19036
+ `location record sequence ${record2.sequence} is below remembered sequence ${remembered}`
19037
+ );
19038
+ }
19039
+ const hosts = [];
19040
+ for (const address of record2.multiaddrs) {
19041
+ const origin2 = multiaddrOrigin(address);
19042
+ if (origin2 !== null) hosts.push({ urls: [origin2], source: "offchain" });
19043
+ }
19044
+ return {
19045
+ status: "registered",
19046
+ subject,
19047
+ source: "offchain",
19048
+ sequence: record2.sequence,
19049
+ hosts
19050
+ };
19051
+ }
19052
+ function isCanonicalSubject(subject) {
19053
+ if (typeof subject !== "string") return false;
19054
+ const pkh = /^did:pkh:eip155:([1-9][0-9]*):(0x[0-9a-fA-F]{40})$/.exec(subject);
19055
+ if (pkh !== null) {
19056
+ try {
19057
+ return pkhDid(pkh[2], Number(pkh[1])) === subject;
19058
+ } catch {
19059
+ return false;
19060
+ }
19061
+ }
19062
+ return ed25519KeyFromDidKey(subject) !== null;
19063
+ }
19064
+ function ed25519KeyFromDidKey(did) {
19065
+ if (!did.startsWith("did:key:z")) return null;
19066
+ const identifier = did.slice("did:key:".length);
19067
+ let bytes2;
19068
+ try {
19069
+ bytes2 = bases.base58btc.decode(identifier);
19070
+ } catch {
19071
+ return null;
19072
+ }
19073
+ if (bytes2.length !== 34 || bytes2[0] !== 237 || bytes2[1] !== 1) {
19074
+ return null;
19075
+ }
19076
+ return bytes2.slice(2);
19077
+ }
19078
+ var JsonInteger = class {
19079
+ constructor(lexeme) {
19080
+ this.lexeme = lexeme;
19081
+ }
19082
+ };
19083
+ function parseStrictJson(text3) {
19084
+ let i = 0;
19085
+ const fail2 = (what) => {
19086
+ throw new SyntaxError(`location registry response is not strict JSON: ${what} at ${i}`);
19087
+ };
19088
+ const skipWhitespace2 = () => {
19089
+ while (i < text3.length && " \n\r".includes(text3[i])) i++;
19090
+ };
19091
+ const readHex4 = () => {
19092
+ const hex3 = text3.slice(i, i + 4);
19093
+ if (!/^[0-9a-fA-F]{4}$/.test(hex3)) fail2("bad \\u escape");
19094
+ i += 4;
19095
+ return parseInt(hex3, 16);
19096
+ };
19097
+ const parseString = () => {
19098
+ i++;
19099
+ let out = "";
19100
+ for (; ; ) {
19101
+ if (i >= text3.length) fail2("unterminated string");
19102
+ const code3 = text3.charCodeAt(i);
19103
+ if (code3 === 34) {
19104
+ i++;
19105
+ return out;
19106
+ }
19107
+ if (code3 < 32) fail2("control character in string");
19108
+ if (code3 === 92) {
19109
+ const escape2 = text3[i + 1];
19110
+ i += 2;
19111
+ if (escape2 !== void 0 && Object.prototype.hasOwnProperty.call(JSON_SIMPLE_ESCAPES, escape2)) {
19112
+ out += JSON_SIMPLE_ESCAPES[escape2];
19113
+ continue;
19114
+ }
19115
+ if (escape2 !== "u") fail2("bad escape");
19116
+ const unit = readHex4();
19117
+ if (unit >= 55296 && unit <= 56319) {
19118
+ if (text3[i] !== "\\" || text3[i + 1] !== "u") fail2("unpaired surrogate");
19119
+ i += 2;
19120
+ const low = readHex4();
19121
+ if (low < 56320 || low > 57343) fail2("unpaired surrogate");
19122
+ out += String.fromCharCode(unit, low);
19123
+ } else if (unit >= 56320 && unit <= 57343) {
19124
+ fail2("unpaired surrogate");
19125
+ } else {
19126
+ out += String.fromCharCode(unit);
19127
+ }
19128
+ continue;
19129
+ }
19130
+ out += text3[i];
19131
+ i++;
19132
+ }
19133
+ };
19134
+ const parseValue = (depth) => {
19135
+ skipWhitespace2();
19136
+ const c = text3[i];
19137
+ if (c === "{" || c === "[") {
19138
+ if (depth >= MAX_JSON_DEPTH) fail2("nesting too deep");
19139
+ i++;
19140
+ skipWhitespace2();
19141
+ const close = c === "{" ? "}" : "]";
19142
+ const object4 = /* @__PURE__ */ new Map();
19143
+ const array = [];
19144
+ if (text3[i] === close) {
19145
+ i++;
19146
+ return c === "{" ? object4 : array;
19147
+ }
19148
+ for (; ; ) {
19149
+ if (c === "{") {
19150
+ skipWhitespace2();
19151
+ if (text3[i] !== '"') fail2("expected key");
19152
+ const key = parseString();
19153
+ if (object4.has(key)) fail2("duplicate key");
19154
+ skipWhitespace2();
19155
+ if (text3[i] !== ":") fail2("expected ':'");
19156
+ i++;
19157
+ object4.set(key, parseValue(depth + 1));
19158
+ } else {
19159
+ array.push(parseValue(depth + 1));
19160
+ }
19161
+ skipWhitespace2();
19162
+ if (text3[i] === ",") {
19163
+ i++;
19164
+ continue;
19165
+ }
19166
+ if (text3[i] !== close) fail2(`expected ',' or '${close}'`);
19167
+ i++;
19168
+ return c === "{" ? object4 : array;
19169
+ }
19170
+ }
19171
+ if (c === '"') return parseString();
19172
+ for (const [literal, value2] of [["true", true], ["false", false], ["null", null]]) {
19173
+ if (text3.startsWith(literal, i)) {
19174
+ i += literal.length;
19175
+ return value2;
19176
+ }
19177
+ }
19178
+ const number = /-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y;
19179
+ number.lastIndex = i;
19180
+ const match = number.exec(text3);
19181
+ if (match === null) return fail2("unexpected token");
19182
+ if (match[2] !== void 0 || match[3] !== void 0) fail2("non-integer number");
19183
+ i += match[0].length;
19184
+ return new JsonInteger(match[0]);
19185
+ };
19186
+ const value = parseValue(0);
19187
+ skipWhitespace2();
19188
+ if (i !== text3.length) fail2("trailing data");
19189
+ return value;
19190
+ }
19191
+ function parseRecordResponse(body) {
19192
+ const root = parseStrictJson(body);
19193
+ const record2 = root instanceof Map ? root.get("record") : void 0;
19194
+ if (!(record2 instanceof Map)) {
19195
+ throw new SyntaxError("location registry response has no record object");
19196
+ }
19197
+ const version = record2.get("version");
19198
+ const subject = record2.get("subject");
19199
+ const multiaddrs = record2.get("multiaddrs");
19200
+ const updatedAt = record2.get("updated_at");
19201
+ const sequence = record2.get("sequence");
19202
+ const signature = record2.get("signature");
19203
+ if (!(version instanceof JsonInteger) || version.lexeme !== "1") {
19204
+ throw new SyntaxError("record.version must be the integer 1");
19205
+ }
19206
+ if (typeof subject !== "string") {
19207
+ throw new SyntaxError("record.subject must be a string");
19208
+ }
19209
+ if (!Array.isArray(multiaddrs) || !multiaddrs.every((entry) => typeof entry === "string" && entry.length > 0)) {
19210
+ throw new SyntaxError("record.multiaddrs must be an array of non-empty strings");
19211
+ }
19212
+ if (typeof updatedAt !== "string" || !isRfc3339DateTime(updatedAt)) {
19213
+ throw new SyntaxError("record.updated_at must be an RFC 3339 date-time");
19214
+ }
19215
+ if (!(sequence instanceof JsonInteger) || !/^(0|[1-9][0-9]*)$/.test(sequence.lexeme) || !Number.isSafeInteger(Number(sequence.lexeme))) {
19216
+ throw new SyntaxError("record.sequence must be a non-negative safe integer");
19217
+ }
19218
+ if (typeof signature !== "string" || signature.length === 0) {
19219
+ throw new SyntaxError("record.signature must be a non-empty string");
19220
+ }
19221
+ return {
19222
+ subject,
19223
+ multiaddrs,
19224
+ updated_at: updatedAt,
19225
+ sequence: Number(sequence.lexeme),
19226
+ signature
19227
+ };
19228
+ }
19229
+ function isRfc3339DateTime(value) {
19230
+ const match = RFC3339_DATE_TIME.exec(value);
19231
+ if (match === null) return false;
19232
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
19233
+ const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
19234
+ const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
19235
+ 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);
19236
+ }
19237
+ async function verifyRecordSignature(record2) {
19238
+ const payload = canonicalLocationPayload({
19239
+ version: 1,
19240
+ subject: record2.subject,
19241
+ multiaddrs: record2.multiaddrs,
19242
+ updated_at: record2.updated_at,
19243
+ sequence: record2.sequence
19244
+ });
19245
+ const { signature } = record2;
19246
+ if (record2.subject.startsWith("did:pkh:")) {
19247
+ if (!/^0x[0-9a-fA-F]{130}$/.test(signature)) return false;
19248
+ const r = BigInt(`0x${signature.slice(2, 66)}`);
19249
+ const s = BigInt(`0x${signature.slice(66, 130)}`);
19250
+ const v = parseInt(signature.slice(130), 16);
19251
+ if (r === 0n || r >= SECP256K1_N || s === 0n || s > SECP256K1_N / 2n) return false;
19252
+ if (v !== 0 && v !== 1 && v !== 27 && v !== 28) return false;
19253
+ const address = record2.subject.slice(record2.subject.lastIndexOf(":") + 1);
19254
+ try {
19255
+ return await verifyMessage3({
19256
+ address,
19257
+ message: payload,
19258
+ signature
19259
+ });
19260
+ } catch {
19261
+ return false;
19262
+ }
19263
+ }
19264
+ const publicKey = ed25519KeyFromDidKey(record2.subject);
19265
+ if (publicKey === null || !/^[A-Za-z0-9_-]{86}$/.test(signature)) return false;
19266
+ const bytes2 = new Uint8Array(64);
19267
+ let buffer = 0;
19268
+ let bits = 0;
19269
+ let length2 = 0;
19270
+ for (const char of signature) {
19271
+ buffer = (buffer << 6 | BASE64URL.indexOf(char)) & 65535;
19272
+ bits += 6;
19273
+ if (bits >= 8) {
19274
+ bits -= 8;
19275
+ bytes2[length2++] = buffer >> bits & 255;
19276
+ }
19277
+ }
19278
+ try {
19279
+ return ed2551912.verify(bytes2, new TextEncoder().encode(payload), publicKey, { zip215: false });
19280
+ } catch {
19281
+ return false;
19282
+ }
19283
+ }
19284
+ function multiaddrOrigin(address) {
19285
+ const match = HOST_MULTIADDR.exec(address);
19286
+ if (match === null) return null;
19287
+ const [, protocol, host, portText, transport] = match;
19288
+ const port = Number(portText);
19289
+ if (port > 65535) return null;
19290
+ let authority;
19291
+ if (protocol === "ip4") {
19292
+ if (!IPV4.test(host)) return null;
19293
+ authority = host;
19294
+ } else if (protocol === "ip6") {
19295
+ if (!/^[0-9A-Fa-f:.]+$/.test(host) || !host.includes(":")) return null;
19296
+ authority = `[${host}]`;
19297
+ } else {
19298
+ if (host.length > 253 || !DNS_NAME.test(host) || /^(0[xX][0-9a-fA-F]*|[0-9]+)$/.test(host.slice(host.lastIndexOf(".") + 1))) {
19299
+ return null;
19300
+ }
19301
+ authority = host;
19302
+ }
19303
+ const scheme = transport === "http" ? "http" : "https";
19304
+ try {
19305
+ return new URL(`${scheme}://${authority}:${port}`).origin;
19306
+ } catch {
19307
+ return null;
19308
+ }
19309
+ }
18929
19310
  export {
18930
19311
  ACCOUNT_INDEX_SCHEMA2 as ACCOUNT_INDEX_SCHEMA,
18931
19312
  ACCOUNT_MANIFEST_PERMISSIONS2 as ACCOUNT_MANIFEST_PERMISSIONS,
@@ -19058,6 +19439,8 @@ export {
19058
19439
  PermissionNotInManifestError,
19059
19440
  PrefixedKVService,
19060
19441
  ProtocolMismatchError,
19442
+ REGISTRY_LOOKUP_MAX_BODY_BYTES,
19443
+ REGISTRY_NOT_FOUND_BODY,
19061
19444
  REQUESTER_ENGINE_RETRY_ATTEMPTS,
19062
19445
  REQUESTER_ENGINE_RETRY_MAX_DELAY_MS,
19063
19446
  REQUESTER_NEAR_EXPIRY_SECONDS,
@@ -19066,6 +19449,7 @@ export {
19066
19449
  ROOT_STATUS_CHECKPOINT_V1_SCHEMA,
19067
19450
  ROOT_STATUS_RENEWAL_V1_DOMAIN,
19068
19451
  ROOT_STATUS_V1_DOMAIN,
19452
+ RegistryLookupInputError,
19069
19453
  SECRETS_SPACE,
19070
19454
  SECRET_NAME_RE2 as SECRET_NAME_RE,
19071
19455
  SECRET_RECORDS_SCHEMA,
@@ -19165,6 +19549,7 @@ export {
19165
19549
  canonicalizeUnifiedPolicyCapability,
19166
19550
  checkDecryptInvocationInput,
19167
19551
  checkNodeInfo,
19552
+ classifyRegistryLookup,
19168
19553
  clearTinyCloudDebugLogs,
19169
19554
  compactAttenuationContains,
19170
19555
  composeBootstrapSpaceManifest,