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

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
@@ -18382,11 +18382,16 @@ async function resolveTinyCloudHosts(subject, options2 = {}) {
18382
18382
  fetch: fetchFn,
18383
18383
  verifyRecords: options2.verifyRecords
18384
18384
  });
18385
- return {
18386
- hosts: location.multiaddrs.map((addr) => multiaddrToHttpUrl(addr)),
18387
- location
18388
- };
18385
+ const hosts = location.multiaddrs.map((addr) => multiaddrToHttpUrl(addr));
18386
+ if (location.source === "fallback" && !fallbackDeprecationWarned) {
18387
+ fallbackDeprecationWarned = true;
18388
+ console.warn(
18389
+ `[tinycloud:location] Deprecated: no registry host for this account, using fallback ${hosts[0]}. The silent fallback will be removed in a future major; opt in to registryPolicy "fail-closed" now.`
18390
+ );
18391
+ }
18392
+ return { hosts, location };
18389
18393
  }
18394
+ var fallbackDeprecationWarned = false;
18390
18395
  function memoizeFetch(fetchFn) {
18391
18396
  const cache2 = /* @__PURE__ */ new Map();
18392
18397
  return (async (input, init) => {
@@ -18599,11 +18604,18 @@ function publishedHttpOrigins(record2) {
18599
18604
  return origins;
18600
18605
  }
18601
18606
  async function boundedResponseText(response, label, maxBytes) {
18607
+ const bytes2 = await boundedResponseBytes(response, maxBytes);
18608
+ if (bytes2 === null) {
18609
+ throw new LocationRecordValidationError(`${label} response is too large`);
18610
+ }
18611
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
18612
+ }
18613
+ async function boundedResponseBytes(response, maxBytes) {
18602
18614
  const declaredLength = response.headers.get("content-length");
18603
18615
  if (declaredLength !== null && (!/^\d+$/.test(declaredLength) || Number(declaredLength) > maxBytes)) {
18604
- throw new LocationRecordValidationError(`${label} response is too large`);
18616
+ return null;
18605
18617
  }
18606
- if (response.body === null) return "";
18618
+ if (response.body === null) return new Uint8Array();
18607
18619
  const reader = response.body.getReader();
18608
18620
  const chunks = [];
18609
18621
  let total = 0;
@@ -18615,7 +18627,7 @@ async function boundedResponseText(response, label, maxBytes) {
18615
18627
  total += value.byteLength;
18616
18628
  if (total > maxBytes) {
18617
18629
  await reader.cancel().catch(() => void 0);
18618
- throw new LocationRecordValidationError(`${label} response is too large`);
18630
+ return null;
18619
18631
  }
18620
18632
  chunks.push(value);
18621
18633
  }
@@ -18628,7 +18640,7 @@ async function boundedResponseText(response, label, maxBytes) {
18628
18640
  bytes2.set(chunk, offset);
18629
18641
  offset += chunk.byteLength;
18630
18642
  }
18631
- return new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
18643
+ return bytes2;
18632
18644
  }
18633
18645
  function boundedSignal(parent, timeoutMs) {
18634
18646
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
@@ -19307,6 +19319,318 @@ function multiaddrOrigin(address) {
19307
19319
  return null;
19308
19320
  }
19309
19321
  }
19322
+
19323
+ // src/registry-policy.ts
19324
+ var DEFAULT_REGISTRY_OWNER_CHAIN_ID = 1;
19325
+ var DEFAULT_NEW_USER_HOST = DEFAULT_TINYCLOUD_FALLBACK_HOST;
19326
+ var DEFAULT_REGISTRY_LOOKUP_TIMEOUT_MS = 3e3;
19327
+ var DEFAULT_REGISTRY_SEQUENCE_STORAGE_KEY = "tinycloud.registrySequences.v1";
19328
+ var MAX_SUBJECT_LENGTH = 74;
19329
+ function registryOwnerSubjectV1(address, registryChainId = DEFAULT_REGISTRY_OWNER_CHAIN_ID) {
19330
+ return pkhDid(address, registryChainId);
19331
+ }
19332
+ function createInMemoryRegistrySequenceStore() {
19333
+ const sequences = /* @__PURE__ */ new Map();
19334
+ return {
19335
+ get: (subject) => sequences.get(subject),
19336
+ set: (subject, sequence) => {
19337
+ if ((sequences.get(subject) ?? -1) < sequence) sequences.set(subject, sequence);
19338
+ }
19339
+ };
19340
+ }
19341
+ function createLocalStorageRegistrySequenceStore(storage, storageKey = DEFAULT_REGISTRY_SEQUENCE_STORAGE_KEY) {
19342
+ const backing = storage ?? defaultWebStorage();
19343
+ const memory = createInMemoryRegistrySequenceStore();
19344
+ if (!backing) {
19345
+ return memory;
19346
+ }
19347
+ const read2 = () => {
19348
+ const sequences = /* @__PURE__ */ new Map();
19349
+ const raw = backing.getItem(storageKey);
19350
+ if (raw === null) return sequences;
19351
+ let parsed;
19352
+ try {
19353
+ parsed = JSON.parse(raw);
19354
+ } catch {
19355
+ parsed = void 0;
19356
+ }
19357
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
19358
+ for (const [subject, sequence] of Object.entries(parsed)) {
19359
+ if (!isSequence(sequence)) break;
19360
+ sequences.set(subject, sequence);
19361
+ }
19362
+ if (sequences.size === Object.keys(parsed).length) return sequences;
19363
+ }
19364
+ throw new Error(`Corrupt registry sequence store "${storageKey}"`);
19365
+ };
19366
+ return {
19367
+ get: async (subject) => {
19368
+ const sequence = Math.max(read2().get(subject) ?? -1, await memory.get(subject) ?? -1);
19369
+ return sequence < 0 ? void 0 : sequence;
19370
+ },
19371
+ set: async (subject, sequence) => {
19372
+ await memory.set(subject, sequence);
19373
+ const sequences = read2();
19374
+ if ((sequences.get(subject) ?? -1) >= sequence) return;
19375
+ sequences.set(subject, sequence);
19376
+ backing.setItem(storageKey, JSON.stringify(Object.fromEntries(sequences)));
19377
+ }
19378
+ };
19379
+ }
19380
+ function isSequence(value) {
19381
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
19382
+ }
19383
+ async function resolveOwnerHosts(subject, options2 = {}) {
19384
+ if (typeof subject !== "string" || // Bounds the work below; covers any did:pkh with a safe-integer chain ID.
19385
+ subject.length > MAX_SUBJECT_LENGTH || !isCanonicalSubject(subject)) {
19386
+ throw new RegistryLookupInputError(
19387
+ "invalid-subject",
19388
+ "subject must be did:pkh:eip155:<chainId>:<EIP-55 address> or an Ed25519 did:key"
19389
+ );
19390
+ }
19391
+ const store = options2.sequenceStore;
19392
+ const remembered = store === void 0 ? void 0 : await store.get(subject);
19393
+ const registryUrl = options2.registryUrl ?? DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL;
19394
+ const url = `${registryUrl.replace(/\/$/, "")}/v1/locations/${encodeURIComponent(subject)}`;
19395
+ const observed = await observeRegistry(
19396
+ url,
19397
+ options2.fetch ?? globalThis.fetch,
19398
+ options2.timeoutMs ?? DEFAULT_REGISTRY_LOOKUP_TIMEOUT_MS
19399
+ );
19400
+ if (observed.kind === "oversize" || observed.kind === "invalid-utf8") {
19401
+ const oversize = observed.kind === "oversize";
19402
+ return {
19403
+ status: "unavailable",
19404
+ subject,
19405
+ source: "offchain",
19406
+ reason: oversize ? "oversize-response" : "malformed-response",
19407
+ message: oversize ? "location registry response is too large" : "location registry response is not UTF-8",
19408
+ hosts: []
19409
+ };
19410
+ }
19411
+ const verdict = await classifyRegistryLookup(subject, observed, {
19412
+ rememberedSequence: remembered ?? null
19413
+ });
19414
+ if (store !== void 0 && verdict.status === "registered" && (remembered === void 0 || verdict.sequence > remembered)) {
19415
+ try {
19416
+ await store.set(subject, verdict.sequence);
19417
+ } catch (error) {
19418
+ if (!sequenceWriteWarned) {
19419
+ sequenceWriteWarned = true;
19420
+ console.warn("[tinycloud:registry] could not remember the registry sequence:", error);
19421
+ }
19422
+ }
19423
+ }
19424
+ return verdict;
19425
+ }
19426
+ var sequenceWriteWarned = false;
19427
+ async function observeRegistry(url, fetchFn, timeoutMs) {
19428
+ const controller = new AbortController();
19429
+ let cancelTimer = () => void 0;
19430
+ const timedOut = new Promise((resolve) => {
19431
+ const timer = setTimeout(() => {
19432
+ controller.abort();
19433
+ resolve({ kind: "timeout" });
19434
+ }, timeoutMs);
19435
+ cancelTimer = () => clearTimeout(timer);
19436
+ });
19437
+ try {
19438
+ return await Promise.race([readRegistry(url, fetchFn, controller.signal), timedOut]);
19439
+ } finally {
19440
+ cancelTimer();
19441
+ }
19442
+ }
19443
+ async function readRegistry(url, fetchFn, signal) {
19444
+ let response;
19445
+ try {
19446
+ response = await fetchFn(url, {
19447
+ redirect: "error",
19448
+ headers: { accept: "application/json" },
19449
+ signal
19450
+ });
19451
+ } catch {
19452
+ return { kind: "network-error" };
19453
+ }
19454
+ if (response.status !== 200 && response.status !== 404) {
19455
+ await response.body?.cancel().catch(() => void 0);
19456
+ return { kind: "http", status: response.status, body: "" };
19457
+ }
19458
+ let bytes2;
19459
+ try {
19460
+ bytes2 = await boundedResponseBytes(response, REGISTRY_LOOKUP_MAX_BODY_BYTES);
19461
+ } catch {
19462
+ return { kind: "network-error" };
19463
+ }
19464
+ if (bytes2 === null) return { kind: "oversize" };
19465
+ try {
19466
+ return {
19467
+ kind: "http",
19468
+ status: response.status,
19469
+ body: new TextDecoder("utf-8", { fatal: true }).decode(bytes2)
19470
+ };
19471
+ } catch {
19472
+ return { kind: "invalid-utf8" };
19473
+ }
19474
+ }
19475
+ var NodeNotFoundError = class extends Error {
19476
+ constructor(subject, verdict) {
19477
+ super(
19478
+ verdict.status === "registered" ? `No usable TinyCloud host is registered for ${subject}` : `${subject} is not registered and newUserHost is null`
19479
+ );
19480
+ this.subject = subject;
19481
+ this.verdict = verdict;
19482
+ this.code = "node_not_found";
19483
+ this.name = "NodeNotFoundError";
19484
+ }
19485
+ };
19486
+ var RegistryUnavailableError = class extends Error {
19487
+ constructor(subject, verdict, detail = {}) {
19488
+ super(`Location registry unavailable for ${subject}: ${detail.message ?? verdict?.message}`);
19489
+ this.subject = subject;
19490
+ this.verdict = verdict;
19491
+ this.code = "registry_unavailable";
19492
+ this.name = "RegistryUnavailableError";
19493
+ if (detail.cause !== void 0) this.cause = detail.cause;
19494
+ }
19495
+ };
19496
+ var NodeRegistryEntryExistsError = class extends Error {
19497
+ constructor(subject, host, verdict) {
19498
+ super(`The registry entry for ${subject} does not list ${host}`);
19499
+ this.subject = subject;
19500
+ this.host = host;
19501
+ this.verdict = verdict;
19502
+ this.code = "node_registry_entry_exists";
19503
+ this.name = "NodeRegistryEntryExistsError";
19504
+ this.registeredHosts = secureRecordHosts(verdict);
19505
+ }
19506
+ };
19507
+ async function lookupOwnerRegistryVerdict(subject, options2 = {}) {
19508
+ if (options2.registryUrl === null) {
19509
+ throw new RegistryUnavailableError(subject, void 0, {
19510
+ message: "no location registry is configured"
19511
+ });
19512
+ }
19513
+ try {
19514
+ return await resolveOwnerHosts(subject, {
19515
+ registryUrl: options2.registryUrl,
19516
+ sequenceStore: options2.sequenceStore,
19517
+ fetch: options2.fetch,
19518
+ timeoutMs: options2.timeoutMs
19519
+ });
19520
+ } catch (error) {
19521
+ throw new RegistryUnavailableError(subject, void 0, {
19522
+ message: error instanceof Error ? error.message : String(error),
19523
+ cause: error
19524
+ });
19525
+ }
19526
+ }
19527
+ async function resolveFailClosedTinyCloudHosts(address, options2 = {}) {
19528
+ const newUserHost = options2.newUserHost === null ? null : exactHttpOrigin(options2.newUserHost ?? DEFAULT_NEW_USER_HOST, "newUserHost");
19529
+ const subject = registryOwnerSubjectV1(address, options2.registryChainId);
19530
+ const resolve = async () => {
19531
+ let verdict;
19532
+ let unavailable;
19533
+ try {
19534
+ verdict = await lookupOwnerRegistryVerdict(subject, options2);
19535
+ } catch (error) {
19536
+ if (!(error instanceof RegistryUnavailableError)) throw error;
19537
+ unavailable = error;
19538
+ }
19539
+ if (options2.autoDiscoverLocalNode ?? true) {
19540
+ const linkNames = verdict?.status === "registered" ? secureRecordHosts(verdict).flatMap((host) => LOCAL_LINK_ORIGIN.exec(host)?.[1] ?? []) : [];
19541
+ for (const candidate of [
19542
+ { localNodeUrl: options2.localNodeUrl, localLinkName: options2.localLinkName },
19543
+ ...linkNames.map((localLinkName) => ({ localLinkName }))
19544
+ ]) {
19545
+ const local = await discoverLocalTinyCloudNode({
19546
+ ...candidate,
19547
+ expectedNodeDid: options2.expectedNodeDid,
19548
+ identityStore: options2.localNodeIdentityStore,
19549
+ fetch: options2.fetch
19550
+ });
19551
+ if (local) return { hosts: [local.url], ...verdict === void 0 ? {} : { verdict } };
19552
+ }
19553
+ }
19554
+ if (verdict === void 0) throw unavailable;
19555
+ return { hosts: hostsForVerdict(verdict, newUserHost), verdict };
19556
+ };
19557
+ for (let attempt = 1; ; attempt++) {
19558
+ let failure;
19559
+ try {
19560
+ return await resolve();
19561
+ } catch (error) {
19562
+ if (!(error instanceof NodeNotFoundError) && !(error instanceof RegistryUnavailableError)) {
19563
+ throw error;
19564
+ }
19565
+ failure = error;
19566
+ }
19567
+ if (!options2.onNodeNotFound) throw failure;
19568
+ const decision = await options2.onNodeNotFound({ error: failure, attempt });
19569
+ switch (decision?.action) {
19570
+ case "retry":
19571
+ continue;
19572
+ case "use-host":
19573
+ return {
19574
+ hosts: [exactHttpOrigin(decision.host, "onNodeNotFound host")],
19575
+ ...failure.verdict === void 0 ? {} : { verdict: failure.verdict }
19576
+ };
19577
+ case "abort":
19578
+ throw failure;
19579
+ default:
19580
+ throw new TypeError("onNodeNotFound returned an unknown action");
19581
+ }
19582
+ }
19583
+ }
19584
+ var LOCAL_LINK_ORIGIN = /^https:\/\/([a-z0-9-]+)\.local\.tinycloud\.link$/;
19585
+ function secureRecordHosts(verdict) {
19586
+ const hosts = /* @__PURE__ */ new Set();
19587
+ for (const host of verdict.hosts) {
19588
+ for (const url of host.urls) {
19589
+ try {
19590
+ hosts.add(exactHttpOrigin(url, "registry host"));
19591
+ } catch {
19592
+ }
19593
+ }
19594
+ }
19595
+ return [...hosts];
19596
+ }
19597
+ function hostsForVerdict(verdict, newUserHost) {
19598
+ switch (verdict.status) {
19599
+ case "registered": {
19600
+ const hosts = secureRecordHosts(verdict);
19601
+ if (hosts.length === 0) throw new NodeNotFoundError(verdict.subject, verdict);
19602
+ return hosts;
19603
+ }
19604
+ case "unregistered":
19605
+ if (newUserHost === null) throw new NodeNotFoundError(verdict.subject, verdict);
19606
+ return [newUserHost];
19607
+ case "unavailable":
19608
+ throw new RegistryUnavailableError(verdict.subject, verdict);
19609
+ }
19610
+ }
19611
+ function assertSpaceCreationAllowed(verdict, host) {
19612
+ switch (verdict.status) {
19613
+ case "unregistered":
19614
+ return;
19615
+ case "unavailable":
19616
+ throw new RegistryUnavailableError(verdict.subject, verdict);
19617
+ case "registered": {
19618
+ const origin2 = httpOrigin(host);
19619
+ if (origin2 !== void 0 && secureRecordHosts(verdict).includes(origin2)) {
19620
+ return;
19621
+ }
19622
+ throw new NodeRegistryEntryExistsError(verdict.subject, host, verdict);
19623
+ }
19624
+ }
19625
+ }
19626
+ function httpOrigin(host) {
19627
+ try {
19628
+ const url = new URL(host);
19629
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : void 0;
19630
+ } catch {
19631
+ return void 0;
19632
+ }
19633
+ }
19310
19634
  export {
19311
19635
  ACCOUNT_INDEX_SCHEMA2 as ACCOUNT_INDEX_SCHEMA,
19312
19636
  ACCOUNT_MANIFEST_PERMISSIONS2 as ACCOUNT_MANIFEST_PERMISSIONS,
@@ -19355,6 +19679,10 @@ export {
19355
19679
  DEFAULT_LOCAL_NODE_URL,
19356
19680
  DEFAULT_MANIFEST_SPACE,
19357
19681
  DEFAULT_MANIFEST_VERSION,
19682
+ DEFAULT_NEW_USER_HOST,
19683
+ DEFAULT_REGISTRY_LOOKUP_TIMEOUT_MS,
19684
+ DEFAULT_REGISTRY_OWNER_CHAIN_ID,
19685
+ DEFAULT_REGISTRY_SEQUENCE_STORAGE_KEY,
19358
19686
  DEFAULT_SIGNED_READ_URL_EXPIRY_MS,
19359
19687
  DEFAULT_TINYCLOUD_FALLBACK_HOST,
19360
19688
  DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL,
@@ -19411,6 +19739,8 @@ export {
19411
19739
  NATIVE_PROJECTION_V1_DOMAIN,
19412
19740
  NETWORK_NAME_PATTERN,
19413
19741
  NetworkIdError,
19742
+ NodeNotFoundError,
19743
+ NodeRegistryEntryExistsError,
19414
19744
  OPENKEY_ACTION_ID_SEPARATOR,
19415
19745
  OWNER_NODE_BINDING_TIMEOUT_MS,
19416
19746
  OpenKeyManageKeyError,
@@ -19450,6 +19780,7 @@ export {
19450
19780
  ROOT_STATUS_RENEWAL_V1_DOMAIN,
19451
19781
  ROOT_STATUS_V1_DOMAIN,
19452
19782
  RegistryLookupInputError,
19783
+ RegistryUnavailableError,
19453
19784
  SECRETS_SPACE,
19454
19785
  SECRET_NAME_RE2 as SECRET_NAME_RE,
19455
19786
  SECRET_RECORDS_SCHEMA,
@@ -19519,6 +19850,7 @@ export {
19519
19850
  admitPolicyCredentialV4,
19520
19851
  appSecretScope,
19521
19852
  applyPrefix,
19853
+ assertSpaceCreationAllowed,
19522
19854
  authorizationVerdictOf2 as authorizationVerdictOf,
19523
19855
  bootstrapEncryptionNetworkId,
19524
19856
  bootstrapSpaceId,
@@ -19567,7 +19899,9 @@ export {
19567
19899
  createEmailDomainCredentialRequirement,
19568
19900
  createHolderBinding,
19569
19901
  createInMemoryLocalNodeIdentityStore,
19902
+ createInMemoryRegistrySequenceStore,
19570
19903
  createLocalStorageLocalNodeIdentityStore,
19904
+ createLocalStorageRegistrySequenceStore,
19571
19905
  createOpenKeyCallbackSigningStrategy,
19572
19906
  createOpenKeyManageKeySigningStrategy,
19573
19907
  createPolicyEnforcementDelegation,
@@ -19651,6 +19985,7 @@ export {
19651
19985
  jcsCanonicalize,
19652
19986
  loadManifest,
19653
19987
  locationPayloadForRecord,
19988
+ lookupOwnerRegistryVerdict,
19654
19989
  mailboxBelongsToDomain,
19655
19990
  makePkhSpaceId,
19656
19991
  makePublicSpaceId,
@@ -19699,11 +20034,14 @@ export {
19699
20034
  publishLocationRecord,
19700
20035
  recapCaveatsEqual,
19701
20036
  registerPolicyV3,
20037
+ registryOwnerSubjectV1,
19702
20038
  renewPolicyRootStatusV3,
19703
20039
  requestTinyCloudManageKeyScope,
19704
20040
  resolveCloudLocation,
20041
+ resolveFailClosedTinyCloudHosts,
19705
20042
  resolveManifest,
19706
20043
  resolveManifestKnowledgeRoot,
20044
+ resolveOwnerHosts,
19707
20045
  resolveSecretListPrefix,
19708
20046
  resolveSecretPath2 as resolveSecretPath,
19709
20047
  resolveTinyCloudHosts,