@le-space/core 0.4.1 → 0.4.3

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.
Files changed (3) hide show
  1. package/index.d.ts +43 -2
  2. package/index.js +244 -18
  3. package/package.json +3 -3
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _le_space_shared_types from '@le-space/shared-types';
2
- import { RootfsResolution, RootfsManifest, RootfsManifestState, CrnRecord, RootfsRequiredPortForward, PortForwardAggregate, PortForwardFlags, PortForwardAggregateEntry, MessageReference, InstanceExecution, MessageStatus, DeploymentInspectionResult, MessageInspectionResult, AlephBroadcastMessage, AlephBroadcastResponse, MessageSigner, MessageHasher, DeploymentProgressListener, AlephAggregateContent, AlephInstanceContent, DeploymentIntentEnvelope, DeploymentResult, InstanceAllocation, InstanceRuntimeDetails, InstanceWebAccess, RuntimeDiagnostics, PortMapping, VmBootstrapConfigRecord, VmBootstrapConfigAggregate } from '@le-space/shared-types';
2
+ import { RootfsResolution, RootfsManifest, RootfsManifestState, CrnRecord, RootfsRequiredPortForward, PortForwardAggregate, PortForwardFlags, PortForwardAggregateEntry, MessageReference, InstanceExecution, MessageStatus, DeploymentInspectionResult, MessageInspectionResult, AlephBroadcastMessage, AlephBroadcastResponse, MessageSigner, MessageHasher, DeploymentProgressListener, AlephAggregateContent, AlephInstanceContent, DeploymentIntentEnvelope, DeploymentResult, InstanceAllocation, InstanceRuntimeDetails, InstanceWebAccess, RuntimeDiagnostics, PortMapping, VmBootstrapConfigRecord, VmBootstrapConfigAggregate, VmBootstrapConfigSignalRecord, VmBootstrapConfigSignalType } from '@le-space/shared-types';
3
3
 
4
4
  declare const DEFAULT_ALEPH_CHANNEL = "TEST";
5
5
 
@@ -513,6 +513,7 @@ declare function describeRuntimeAvailability(runtime: {
513
513
  ipv6?: string | null;
514
514
  proxyUrl?: string | null;
515
515
  mappedPorts?: Record<string, unknown>;
516
+ requirePublicGuestIpv6ForProxy?: boolean;
516
517
  }): RuntimeDiagnostics;
517
518
  declare function fetchVmRuntime(args: {
518
519
  itemHash: string;
@@ -522,6 +523,7 @@ declare function fetchVmRuntime(args: {
522
523
  crnListUrl?: string;
523
524
  schedulerAllocationUrl?: string;
524
525
  twoN6HashUrl?: string;
526
+ requirePublicGuestIpv6ForProxy?: boolean;
525
527
  }): Promise<Omit<InstanceRuntimeDetails, 'messageStatus'>>;
526
528
  declare function waitForVmRuntime(args: {
527
529
  itemHash: string;
@@ -531,6 +533,7 @@ declare function waitForVmRuntime(args: {
531
533
  crnListUrl?: string;
532
534
  schedulerAllocationUrl?: string;
533
535
  twoN6HashUrl?: string;
536
+ requirePublicGuestIpv6ForProxy?: boolean;
534
537
  attempts?: number;
535
538
  delayMs?: number;
536
539
  sleep?: (ms: number) => Promise<void>;
@@ -757,6 +760,9 @@ declare function publishRelayBootstrapRegistration(args: {
757
760
  }): Promise<RelayBootstrapPublicationResult>;
758
761
 
759
762
  declare const VM_BOOTSTRAP_CONFIG_AGGREGATE_KEY = "vm-bootstrap-config";
763
+ declare const VM_BOOTSTRAP_CONFIG_SIGNAL_REF = "vm-bootstrap-config";
764
+ declare const VM_BOOTSTRAP_CONFIG_SIGNAL_POST_TYPE = "vm-bootstrap-config-status";
765
+ declare const VM_BOOTSTRAP_CONFIG_HISTORY_RETENTION_MS: number;
760
766
  declare function fetchVmBootstrapConfigAggregate(address: string, options: {
761
767
  apiHost?: string;
762
768
  fetch: JsonFetchLike$1;
@@ -766,7 +772,18 @@ declare function createVmBootstrapConfigAggregateContent(args: {
766
772
  record: VmBootstrapConfigRecord;
767
773
  existingAggregate?: VmBootstrapConfigAggregate | null;
768
774
  now?: number;
775
+ maxRecordAgeMs?: number;
769
776
  }): AlephAggregateContent<VmBootstrapConfigAggregate>;
777
+ declare function listStaleVmBootstrapConfigAggregateMessageHashes(args: {
778
+ address: string;
779
+ currentAggregateItemHash?: string | null;
780
+ olderThanMs?: number;
781
+ fetch: JsonFetchLike$1;
782
+ apiHost?: string;
783
+ pagination?: number;
784
+ maxPages?: number;
785
+ nowMs?: number;
786
+ }): Promise<string[]>;
770
787
  declare function publishVmBootstrapConfig(args: {
771
788
  sender: string;
772
789
  record: VmBootstrapConfigRecord;
@@ -795,6 +812,30 @@ declare function deleteVmBootstrapConfig(args: {
795
812
  aggregateStatus: MessageStatus;
796
813
  aggregate: VmBootstrapConfigAggregate;
797
814
  }>;
815
+ declare function fetchVmBootstrapConfigSignals(args: {
816
+ deploymentToken?: string;
817
+ ownerAddress?: string;
818
+ instanceItemHash?: string;
819
+ fetch: JsonFetchLike$1;
820
+ apiHost?: string;
821
+ ref?: string;
822
+ postType?: string;
823
+ page?: number;
824
+ pagination?: number;
825
+ }): Promise<VmBootstrapConfigSignalRecord[]>;
826
+ declare function waitForVmBootstrapConfigSignal(args: {
827
+ deploymentToken: string;
828
+ ownerAddress: string;
829
+ instanceItemHash: string;
830
+ expectedStatus?: VmBootstrapConfigSignalType;
831
+ fetch: JsonFetchLike$1;
832
+ apiHost?: string;
833
+ ref?: string;
834
+ postType?: string;
835
+ attempts?: number;
836
+ delayMs?: number;
837
+ sleep?: (ms: number) => Promise<void>;
838
+ }): Promise<VmBootstrapConfigSignalRecord | null>;
798
839
 
799
840
  type JsonFetchLike = FetchLike;
800
841
  type RelayMetadataShape = {
@@ -863,4 +904,4 @@ declare function reconcileOwnerRelayBootstrapRegistrations(args: {
863
904
  } | null;
864
905
  }): Promise<OwnerRelayBootstrapReconcileResult>;
865
906
 
866
- export { type CrnCapacitySpec, DEFAULT_ALEPH_API_HOST, DEFAULT_ALEPH_CHANNEL, DEFAULT_COUNTRY_LOOKUP_BASE_URL, DEFAULT_CRN_LIST_URL, DEFAULT_DNS_RESOLVE_URL, DEFAULT_INSTANCE_PORT_FORWARDS, DEFAULT_IPFS_GATEWAY_BASE_URL, DEFAULT_SCHEDULER_ALLOCATION_URL, DEFAULT_TWO_N_SIX_HASH_URL, type FetchLike, type FetchLikeResponse, type HttpProbeResult, ITEM_HASH_RE, type JsonFetchLike$1 as JsonFetchLike, type JsonFetchLikeResponse, type OwnerRelayBootstrapReconcileResult, type PaymentQuote, type RelayBootstrapPublicationResult, type RelayBootstrapVisibilityResult, type RelayMetadataShape, type RetentionRecord, SSH_PUBLIC_KEY_PATTERN, SUCCESSFUL_DEPLOYMENTS_AGGREGATE_KEY, type TcpProbeResult, type TierSpec, VM_BOOTSTRAP_CONFIG_AGGREGATE_KEY, appendDeploymentTokenToSshPublicKey, broadcastAlephMessage, buildPaymentQuote, cleanupFailedDeployment, configureOrbitdbRelaySetup, configureUcGoPeer, createDeploymentIntent, createDeploymentToken, createInstanceContent, createPortForwardAggregateContent, createRelayBootstrapRegistrationId, createReleaseMetadata, createUnsignedAggregateMessage, createUnsignedForgetMessage, createUnsignedInstanceMessage, createVmBootstrapConfigAggregateContent, deleteVmBootstrapConfig, deployInstance, describeRejectedDeployment, describeRuntimeAvailability, enrichCrnsWithGeo, ensureInstancePortForwards, extractInsufficientBalanceMessage, extractProxyUrl, extractReferenceHashes, fetch2n6WebAccessUrl, fetchAggregateKey, fetchCrnExecutionMap, fetchCrns, fetchMessageEnvelope, fetchPortForwardAggregate, fetchRelayMetadataForRuntime, fetchSchedulerAllocation, fetchUcGoPeerMetadata, fetchVmBootstrapConfigAggregate, fetchVmRuntime, filterDeployableCrns, findCrnByHash, forgetAlephMessages, inspectDeploymentResult, inspectMessageResult, isInvalidMessageFormatResponse, isRetryableBroadcastFailure, isValidSshPublicKey, listGeocodedCrns, mergePortFlagMaps, mergeRequiredPortForwards, messageTypeFromEnvelope, normalizeBroadcastStatus, normalizeExecution, normalizeExistingPortForwardEntry, normalizeMessageStatus, normalizeProxyUrl, normalizeSshPublicKey, notifyCrnAllocation, notifyCrnAllocationWithRetry, portForwardLabel, postBroadcastPayload, probeRootfsGateway, publishAggregateKey, publishRelayBootstrapRegistration, publishVmBootstrapConfig, quoteRequiredBudgetUnits, rankCandidateCrns, reconcileOwnerRelayBootstrapRegistrations, requestedPortFlags, requiredInstancePortForwards, resolveRootfsReference, retainSuccessfulDeployments, selectPreferredCrn, selectedTier, signAlephMessage, signaturePayload, tierSpec, validateRootfsManifest, verifyRootfsExists, verifyUcGoPeerReachability, waitForDeploymentResult, waitForRelayBootstrapRegistration, waitForSetupEndpoint, waitForVmRuntime };
907
+ export { type CrnCapacitySpec, DEFAULT_ALEPH_API_HOST, DEFAULT_ALEPH_CHANNEL, DEFAULT_COUNTRY_LOOKUP_BASE_URL, DEFAULT_CRN_LIST_URL, DEFAULT_DNS_RESOLVE_URL, DEFAULT_INSTANCE_PORT_FORWARDS, DEFAULT_IPFS_GATEWAY_BASE_URL, DEFAULT_SCHEDULER_ALLOCATION_URL, DEFAULT_TWO_N_SIX_HASH_URL, type FetchLike, type FetchLikeResponse, type HttpProbeResult, ITEM_HASH_RE, type JsonFetchLike$1 as JsonFetchLike, type JsonFetchLikeResponse, type OwnerRelayBootstrapReconcileResult, type PaymentQuote, type RelayBootstrapPublicationResult, type RelayBootstrapVisibilityResult, type RelayMetadataShape, type RetentionRecord, SSH_PUBLIC_KEY_PATTERN, SUCCESSFUL_DEPLOYMENTS_AGGREGATE_KEY, type TcpProbeResult, type TierSpec, VM_BOOTSTRAP_CONFIG_AGGREGATE_KEY, VM_BOOTSTRAP_CONFIG_HISTORY_RETENTION_MS, VM_BOOTSTRAP_CONFIG_SIGNAL_POST_TYPE, VM_BOOTSTRAP_CONFIG_SIGNAL_REF, appendDeploymentTokenToSshPublicKey, broadcastAlephMessage, buildPaymentQuote, cleanupFailedDeployment, configureOrbitdbRelaySetup, configureUcGoPeer, createDeploymentIntent, createDeploymentToken, createInstanceContent, createPortForwardAggregateContent, createRelayBootstrapRegistrationId, createReleaseMetadata, createUnsignedAggregateMessage, createUnsignedForgetMessage, createUnsignedInstanceMessage, createVmBootstrapConfigAggregateContent, deleteVmBootstrapConfig, deployInstance, describeRejectedDeployment, describeRuntimeAvailability, enrichCrnsWithGeo, ensureInstancePortForwards, extractInsufficientBalanceMessage, extractProxyUrl, extractReferenceHashes, fetch2n6WebAccessUrl, fetchAggregateKey, fetchCrnExecutionMap, fetchCrns, fetchMessageEnvelope, fetchPortForwardAggregate, fetchRelayMetadataForRuntime, fetchSchedulerAllocation, fetchUcGoPeerMetadata, fetchVmBootstrapConfigAggregate, fetchVmBootstrapConfigSignals, fetchVmRuntime, filterDeployableCrns, findCrnByHash, forgetAlephMessages, inspectDeploymentResult, inspectMessageResult, isInvalidMessageFormatResponse, isRetryableBroadcastFailure, isValidSshPublicKey, listGeocodedCrns, listStaleVmBootstrapConfigAggregateMessageHashes, mergePortFlagMaps, mergeRequiredPortForwards, messageTypeFromEnvelope, normalizeBroadcastStatus, normalizeExecution, normalizeExistingPortForwardEntry, normalizeMessageStatus, normalizeProxyUrl, normalizeSshPublicKey, notifyCrnAllocation, notifyCrnAllocationWithRetry, portForwardLabel, postBroadcastPayload, probeRootfsGateway, publishAggregateKey, publishRelayBootstrapRegistration, publishVmBootstrapConfig, quoteRequiredBudgetUnits, rankCandidateCrns, reconcileOwnerRelayBootstrapRegistrations, requestedPortFlags, requiredInstancePortForwards, resolveRootfsReference, retainSuccessfulDeployments, selectPreferredCrn, selectedTier, signAlephMessage, signaturePayload, tierSpec, validateRootfsManifest, verifyRootfsExists, verifyUcGoPeerReachability, waitForDeploymentResult, waitForRelayBootstrapRegistration, waitForSetupEndpoint, waitForVmBootstrapConfigSignal, waitForVmRuntime };
package/index.js CHANGED
@@ -739,25 +739,22 @@ async function postBroadcastPayload(body, options) {
739
739
  };
740
740
  }
741
741
  async function broadcastAlephMessage(message, options) {
742
- const attempts = [
743
- { sync: options.sync ?? false, message },
744
- { ...message, sync: options.sync ?? false },
745
- { ...message }
746
- ];
747
- for (let index = 0; index < attempts.length; index += 1) {
748
- const result = await postBroadcastPayload(attempts[index], {
742
+ const requestBody = { sync: options.sync ?? false, message };
743
+ const maxAttempts = 3;
744
+ for (let index = 0; index < maxAttempts; index += 1) {
745
+ const result = await postBroadcastPayload(requestBody, {
749
746
  apiHost: options.apiHost,
750
747
  fetch: options.fetch
751
748
  });
752
749
  if (result.httpStatus === 202 || normalizeBroadcastStatus(result.httpStatus, result.response?.message_status) !== "unknown" || result.httpStatus >= 200 && result.httpStatus < 300) {
753
750
  return result;
754
751
  }
755
- const canRetry = index < attempts.length - 1 && (isInvalidMessageFormatResponse({ status: result.httpStatus }, result.response) || isRetryableBroadcastFailure({ status: result.httpStatus }, result.response));
752
+ const canRetry = index < maxAttempts - 1 && isRetryableBroadcastFailure({ status: result.httpStatus }, result.response);
756
753
  if (!canRetry) {
757
754
  throw new Error(`Broadcast failed: ${result.httpStatus} ${JSON.stringify(result.response ?? {})}`);
758
755
  }
759
756
  }
760
- throw new Error("Broadcast failed: no compatible request format was accepted");
757
+ throw new Error("Broadcast failed: retry budget exhausted");
761
758
  }
762
759
 
763
760
  // src/forget.ts
@@ -1510,6 +1507,26 @@ function asString4(value) {
1510
1507
  function asNumber2(value) {
1511
1508
  return typeof value === "number" && Number.isFinite(value) ? value : null;
1512
1509
  }
1510
+ function normalizeIpv6(value) {
1511
+ if (typeof value !== "string") return null;
1512
+ const normalized = value.trim().toLowerCase();
1513
+ if (!normalized) return null;
1514
+ const zoneIndex = normalized.indexOf("%");
1515
+ return zoneIndex >= 0 ? normalized.slice(0, zoneIndex) : normalized;
1516
+ }
1517
+ function isLikelyGlobalIpv6(value) {
1518
+ const normalized = normalizeIpv6(value);
1519
+ if (!normalized || normalized === "::" || normalized === "::1") return false;
1520
+ const firstHextetText = normalized.split(":", 1)[0];
1521
+ if (!firstHextetText) return false;
1522
+ const firstHextet = Number.parseInt(firstHextetText, 16);
1523
+ if (!Number.isFinite(firstHextet)) return false;
1524
+ if ((firstHextet & 65024) === 64512) return false;
1525
+ if ((firstHextet & 65472) === 65152) return false;
1526
+ if ((firstHextet & 65280) === 65280) return false;
1527
+ if ((firstHextet & 65472) === 65216) return false;
1528
+ return true;
1529
+ }
1513
1530
  function findCrnByHash(crns, crnHash) {
1514
1531
  return crns.find((crn) => crn.hash === crnHash) ?? null;
1515
1532
  }
@@ -1590,10 +1607,23 @@ function describeRuntimeAvailability(runtime) {
1590
1607
  const execution = runtime.execution ?? null;
1591
1608
  const mappedPorts = runtime.mappedPorts ?? {};
1592
1609
  const hostIpv4 = runtime.hostIpv4 ?? null;
1610
+ const ipv6 = runtime.ipv6 ?? null;
1611
+ const executionGuestIpv6 = execution?.networking?.ipv6_ip ?? null;
1593
1612
  const proxyUrl = runtime.proxyUrl ?? null;
1594
1613
  const schedulerSource = runtime.allocation?.source ?? null;
1595
1614
  const webAccessActive = runtime.webAccess?.active ?? null;
1596
1615
  const mappedPortCount = Object.keys(mappedPorts).length;
1616
+ if (hostIpv4 && mappedPortCount > 0 && runtime.requirePublicGuestIpv6ForProxy === true && proxyUrl && executionGuestIpv6 && !isLikelyGlobalIpv6(executionGuestIpv6)) {
1617
+ return {
1618
+ state: "execution-invalid-public-ipv6",
1619
+ reason: `The CRN exposed runtime networking, but the guest IPv6 (${executionGuestIpv6}) is not globally routable. Proxy-backed HTTPS activation cannot succeed until the CRN reports a public guest IPv6.`,
1620
+ schedulerSource,
1621
+ executionSeen: Boolean(execution),
1622
+ webAccessActive,
1623
+ mappedPortCount,
1624
+ proxyUrl
1625
+ };
1626
+ }
1597
1627
  if (hostIpv4 && mappedPortCount > 0) {
1598
1628
  return {
1599
1629
  state: "ready",
@@ -1710,7 +1740,8 @@ async function fetchVmRuntime(args) {
1710
1740
  hostIpv4,
1711
1741
  ipv6,
1712
1742
  proxyUrl,
1713
- mappedPorts
1743
+ mappedPorts,
1744
+ requirePublicGuestIpv6ForProxy: args.requirePublicGuestIpv6ForProxy
1714
1745
  });
1715
1746
  return {
1716
1747
  allocation,
@@ -1734,7 +1765,7 @@ async function waitForVmRuntime(args) {
1734
1765
  let lastRuntime = await fetchVmRuntime(args);
1735
1766
  args.onAttempt?.(lastRuntime, 1, attempts);
1736
1767
  for (let attempt = 0; attempt < attempts - 1; attempt += 1) {
1737
- if (lastRuntime.hostIpv4 && Object.keys(lastRuntime.mappedPorts ?? {}).length > 0) {
1768
+ if (lastRuntime.diagnostics?.state === "ready" || lastRuntime.diagnostics?.state === "execution-invalid-public-ipv6") {
1738
1769
  return lastRuntime;
1739
1770
  }
1740
1771
  await sleep2(delayMs);
@@ -2637,6 +2668,55 @@ async function publishRelayBootstrapRegistration(args) {
2637
2668
 
2638
2669
  // src/bootstrap-config.ts
2639
2670
  var VM_BOOTSTRAP_CONFIG_AGGREGATE_KEY = "vm-bootstrap-config";
2671
+ var VM_BOOTSTRAP_CONFIG_SIGNAL_REF = "vm-bootstrap-config";
2672
+ var VM_BOOTSTRAP_CONFIG_SIGNAL_POST_TYPE = "vm-bootstrap-config-status";
2673
+ var VM_BOOTSTRAP_CONFIG_HISTORY_RETENTION_MS = 6 * 60 * 60 * 1e3;
2674
+ function parseJsonObject(value) {
2675
+ try {
2676
+ const parsed = JSON.parse(value);
2677
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2678
+ } catch {
2679
+ return null;
2680
+ }
2681
+ }
2682
+ function parseTimestampMs(value) {
2683
+ if (typeof value === "number" && Number.isFinite(value)) {
2684
+ return value > 1e12 ? value : value * 1e3;
2685
+ }
2686
+ if (typeof value === "string" && value.trim()) {
2687
+ const numeric = Number(value);
2688
+ if (Number.isFinite(numeric)) {
2689
+ return numeric > 1e12 ? numeric : numeric * 1e3;
2690
+ }
2691
+ const parsed = Date.parse(value);
2692
+ return Number.isFinite(parsed) ? parsed : null;
2693
+ }
2694
+ return null;
2695
+ }
2696
+ function normalizeVmBootstrapConfigRecord(deploymentTokenKey, value, options = {}) {
2697
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2698
+ const candidate = value;
2699
+ const deploymentToken = typeof candidate.deploymentToken === "string" ? candidate.deploymentToken.trim() : "";
2700
+ const profile = typeof candidate.profile === "string" ? candidate.profile.trim() : "";
2701
+ const ownerAddress = typeof candidate.ownerAddress === "string" ? candidate.ownerAddress.trim() : "";
2702
+ const instanceItemHash = typeof candidate.instanceItemHash === "string" ? candidate.instanceItemHash.trim() : "";
2703
+ const createdAt = typeof candidate.createdAt === "string" ? candidate.createdAt.trim() : "";
2704
+ const expiresAt = typeof candidate.expiresAt === "string" ? candidate.expiresAt.trim() : "";
2705
+ if (!deploymentTokenKey.trim() || !deploymentToken || deploymentToken !== deploymentTokenKey.trim() || !profile || !ownerAddress || !instanceItemHash || !createdAt || !expiresAt) {
2706
+ return null;
2707
+ }
2708
+ const nowMs = Math.max(0, Number(options.nowMs ?? Date.now()));
2709
+ const maxRecordAgeMs = Math.max(
2710
+ 6e4,
2711
+ Number(options.maxRecordAgeMs ?? VM_BOOTSTRAP_CONFIG_HISTORY_RETENTION_MS)
2712
+ );
2713
+ const createdAtMs = parseTimestampMs(createdAt);
2714
+ const expiresAtMs = parseTimestampMs(expiresAt);
2715
+ if (createdAtMs == null || expiresAtMs == null) return null;
2716
+ if (expiresAtMs <= nowMs) return null;
2717
+ if (createdAtMs < nowMs - maxRecordAgeMs) return null;
2718
+ return candidate;
2719
+ }
2640
2720
  async function fetchVmBootstrapConfigAggregate(address, options) {
2641
2721
  const requestUrl = new URL(`/api/v0/aggregates/${address}.json`, options.apiHost ?? DEFAULT_ALEPH_API_HOST);
2642
2722
  requestUrl.searchParams.set("keys", VM_BOOTSTRAP_CONFIG_AGGREGATE_KEY);
@@ -2650,16 +2730,21 @@ async function fetchVmBootstrapConfigAggregate(address, options) {
2650
2730
  if (!aggregate || typeof aggregate !== "object" || Array.isArray(aggregate)) return {};
2651
2731
  return aggregate;
2652
2732
  }
2653
- function normalizeVmBootstrapConfigAggregate(aggregate) {
2733
+ function normalizeVmBootstrapConfigAggregate(aggregate, options = {}) {
2654
2734
  if (!aggregate || typeof aggregate !== "object") return {};
2655
2735
  return Object.fromEntries(
2656
- Object.entries(aggregate).filter(
2657
- (entry) => Boolean(entry[1] && typeof entry[1] === "object" && !Array.isArray(entry[1]))
2658
- )
2736
+ Object.entries(aggregate).map(([deploymentToken, record]) => [
2737
+ deploymentToken,
2738
+ normalizeVmBootstrapConfigRecord(deploymentToken, record, options)
2739
+ ]).filter((entry) => entry[1] != null)
2659
2740
  );
2660
2741
  }
2661
2742
  function createVmBootstrapConfigAggregateContent(args) {
2662
- const content = normalizeVmBootstrapConfigAggregate(args.existingAggregate);
2743
+ const nowMs = Math.max(0, Number(args.now ?? Date.now() / 1e3) * 1e3);
2744
+ const content = normalizeVmBootstrapConfigAggregate(args.existingAggregate, {
2745
+ nowMs,
2746
+ maxRecordAgeMs: args.maxRecordAgeMs
2747
+ });
2663
2748
  content[args.record.deploymentToken] = args.record;
2664
2749
  return {
2665
2750
  address: args.sender,
@@ -2704,6 +2789,55 @@ async function publishVmBootstrapConfigAggregate(args) {
2704
2789
  aggregateStatus
2705
2790
  };
2706
2791
  }
2792
+ function normalizeAggregateMessageHashRecord(value) {
2793
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2794
+ const candidate = value;
2795
+ const itemHash = typeof candidate.item_hash === "string" ? candidate.item_hash.trim() : "";
2796
+ if (!itemHash) return null;
2797
+ const content = candidate.content && typeof candidate.content === "object" && !Array.isArray(candidate.content) ? candidate.content : typeof candidate.item_content === "string" ? parseJsonObject(candidate.item_content) : null;
2798
+ if (!content || content.key !== VM_BOOTSTRAP_CONFIG_AGGREGATE_KEY) return null;
2799
+ const timeMs = parseTimestampMs(candidate.time);
2800
+ if (timeMs == null) return null;
2801
+ return { itemHash, timeMs };
2802
+ }
2803
+ async function listStaleVmBootstrapConfigAggregateMessageHashes(args) {
2804
+ const address = args.address.trim();
2805
+ if (!address) return [];
2806
+ const currentAggregateItemHash = args.currentAggregateItemHash?.trim() ?? "";
2807
+ const olderThanMs = Math.max(
2808
+ 6e4,
2809
+ Number(args.olderThanMs ?? VM_BOOTSTRAP_CONFIG_HISTORY_RETENTION_MS)
2810
+ );
2811
+ const cutoffMs = Math.max(0, Number(args.nowMs ?? Date.now()) - olderThanMs);
2812
+ const pagination = Math.max(1, Number(args.pagination ?? 100));
2813
+ const maxPages = Math.max(1, Number(args.maxPages ?? 10));
2814
+ const hashes = /* @__PURE__ */ new Set();
2815
+ for (let page = 1; page <= maxPages; page += 1) {
2816
+ const requestUrl = new URL("/api/v0/messages.json", args.apiHost ?? DEFAULT_ALEPH_API_HOST);
2817
+ requestUrl.searchParams.set("msgType", "AGGREGATE");
2818
+ requestUrl.searchParams.set("addresses", address);
2819
+ requestUrl.searchParams.set("message_statuses", "processed,pending,rejected,removing");
2820
+ requestUrl.searchParams.set("pagination", String(pagination));
2821
+ requestUrl.searchParams.set("page", String(page));
2822
+ requestUrl.searchParams.set("sortOrder", "-1");
2823
+ const response = await args.fetch(requestUrl.toString(), { cache: "no-cache" });
2824
+ if (!response.ok) {
2825
+ throw new Error(`VM bootstrap config aggregate history request failed: ${response.status}`);
2826
+ }
2827
+ const payload = await response.json();
2828
+ const messages = Array.isArray(payload.messages) ? payload.messages : [];
2829
+ if (messages.length === 0) break;
2830
+ for (const message of messages) {
2831
+ const normalized = normalizeAggregateMessageHashRecord(message);
2832
+ if (!normalized) continue;
2833
+ if (normalized.itemHash === currentAggregateItemHash) continue;
2834
+ if (normalized.timeMs > cutoffMs) continue;
2835
+ hashes.add(normalized.itemHash);
2836
+ }
2837
+ if (messages.length < pagination) break;
2838
+ }
2839
+ return [...hashes];
2840
+ }
2707
2841
  async function publishVmBootstrapConfig(args) {
2708
2842
  const aggregate = await fetchVmBootstrapConfigAggregate(args.sender, {
2709
2843
  apiHost: args.apiHost,
@@ -2712,7 +2846,8 @@ async function publishVmBootstrapConfig(args) {
2712
2846
  const content = createVmBootstrapConfigAggregateContent({
2713
2847
  sender: args.sender,
2714
2848
  record: args.record,
2715
- existingAggregate: aggregate
2849
+ existingAggregate: aggregate,
2850
+ maxRecordAgeMs: VM_BOOTSTRAP_CONFIG_HISTORY_RETENTION_MS
2716
2851
  });
2717
2852
  const result = await publishVmBootstrapConfigAggregate({
2718
2853
  sender: args.sender,
@@ -2734,7 +2869,9 @@ async function deleteVmBootstrapConfig(args) {
2734
2869
  apiHost: args.apiHost,
2735
2870
  fetch: args.fetch
2736
2871
  });
2737
- const content = normalizeVmBootstrapConfigAggregate(aggregate);
2872
+ const content = normalizeVmBootstrapConfigAggregate(aggregate, {
2873
+ maxRecordAgeMs: VM_BOOTSTRAP_CONFIG_HISTORY_RETENTION_MS
2874
+ });
2738
2875
  delete content[args.deploymentToken];
2739
2876
  const publishResult = await publishVmBootstrapConfigAggregate({
2740
2877
  sender: args.sender,
@@ -2756,6 +2893,89 @@ async function deleteVmBootstrapConfig(args) {
2756
2893
  aggregate: content
2757
2894
  };
2758
2895
  }
2896
+ function normalizeVmBootstrapConfigSignalRecord(value) {
2897
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2898
+ const candidate = value;
2899
+ const deploymentToken = typeof candidate.deploymentToken === "string" ? candidate.deploymentToken.trim() : "";
2900
+ const status = typeof candidate.status === "string" ? candidate.status.trim() : "";
2901
+ const profile = typeof candidate.profile === "string" ? candidate.profile.trim() : "";
2902
+ const ownerAddress = typeof candidate.ownerAddress === "string" ? candidate.ownerAddress.trim() : "";
2903
+ const instanceItemHash = typeof candidate.instanceItemHash === "string" ? candidate.instanceItemHash.trim() : "";
2904
+ const updatedAt = typeof candidate.updatedAt === "string" ? candidate.updatedAt.trim() : "";
2905
+ if (!deploymentToken || !status || !profile || !ownerAddress || !instanceItemHash || !updatedAt) {
2906
+ return null;
2907
+ }
2908
+ return {
2909
+ deploymentToken,
2910
+ status,
2911
+ profile,
2912
+ ownerAddress,
2913
+ instanceItemHash,
2914
+ updatedAt,
2915
+ publisherAddress: typeof candidate.publisherAddress === "string" && candidate.publisherAddress.trim() ? candidate.publisherAddress.trim() : null,
2916
+ authorization: candidate.authorization,
2917
+ peerId: typeof candidate.peerId === "string" && candidate.peerId.trim() ? candidate.peerId.trim() : null,
2918
+ probeMultiaddrs: Array.isArray(candidate.probeMultiaddrs) ? candidate.probeMultiaddrs.filter(
2919
+ (entry) => typeof entry === "string" && entry.trim().length > 0
2920
+ ) : [],
2921
+ browserBootstrapMultiaddrs: Array.isArray(candidate.browserBootstrapMultiaddrs) ? candidate.browserBootstrapMultiaddrs.filter(
2922
+ (entry) => typeof entry === "string" && entry.trim().length > 0
2923
+ ) : []
2924
+ };
2925
+ }
2926
+ async function fetchVmBootstrapConfigSignals(args) {
2927
+ const requestUrl = new URL("/api/v0/posts.json", args.apiHost ?? DEFAULT_ALEPH_API_HOST);
2928
+ requestUrl.searchParams.set("refs", args.ref ?? VM_BOOTSTRAP_CONFIG_SIGNAL_REF);
2929
+ requestUrl.searchParams.set("types", args.postType ?? VM_BOOTSTRAP_CONFIG_SIGNAL_POST_TYPE);
2930
+ requestUrl.searchParams.set("pagination", String(Math.max(1, Number(args.pagination ?? 100))));
2931
+ requestUrl.searchParams.set("page", String(Math.max(1, Number(args.page ?? 1))));
2932
+ requestUrl.searchParams.set("sortOrder", "-1");
2933
+ const response = await args.fetch(requestUrl.toString(), { cache: "no-cache" });
2934
+ if (!response.ok) {
2935
+ throw new Error(`VM bootstrap config signal request failed: ${response.status}`);
2936
+ }
2937
+ const payload = await response.json();
2938
+ const expectedDeploymentToken = args.deploymentToken?.trim() ?? "";
2939
+ const expectedOwnerAddress = args.ownerAddress?.trim().toLowerCase() ?? "";
2940
+ const expectedInstanceItemHash = args.instanceItemHash?.trim() ?? "";
2941
+ return (payload.posts ?? []).map((entry) => {
2942
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return null;
2943
+ const parsed = "content" in entry && entry.content && typeof entry.content === "object" && !Array.isArray(entry.content) ? entry.content : "item_content" in entry && typeof entry.item_content === "string" ? parseJsonObject(entry.item_content) : null;
2944
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
2945
+ const content = "deploymentToken" in parsed ? parsed : "content" in parsed && parsed.content && typeof parsed.content === "object" && !Array.isArray(parsed.content) ? parsed.content : null;
2946
+ if (!content || typeof content !== "object" || Array.isArray(content)) return null;
2947
+ return normalizeVmBootstrapConfigSignalRecord(content);
2948
+ }).filter((entry) => {
2949
+ if (!entry) return false;
2950
+ if (expectedDeploymentToken && entry.deploymentToken !== expectedDeploymentToken) return false;
2951
+ if (expectedOwnerAddress && entry.ownerAddress.toLowerCase() !== expectedOwnerAddress) return false;
2952
+ if (expectedInstanceItemHash && entry.instanceItemHash !== expectedInstanceItemHash) return false;
2953
+ return true;
2954
+ });
2955
+ }
2956
+ async function waitForVmBootstrapConfigSignal(args) {
2957
+ const attempts = Math.max(1, Number(args.attempts ?? 24));
2958
+ const delayMs = Math.max(0, Number(args.delayMs ?? 2500));
2959
+ const sleep2 = args.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
2960
+ const expectedStatus = args.expectedStatus ?? "applied";
2961
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
2962
+ const signals = await fetchVmBootstrapConfigSignals({
2963
+ deploymentToken: args.deploymentToken,
2964
+ ownerAddress: args.ownerAddress,
2965
+ instanceItemHash: args.instanceItemHash,
2966
+ fetch: args.fetch,
2967
+ apiHost: args.apiHost,
2968
+ ref: args.ref,
2969
+ postType: args.postType
2970
+ }).catch(() => []);
2971
+ const match = signals.find((entry) => entry.status === expectedStatus) ?? null;
2972
+ if (match) return match;
2973
+ if (attempt < attempts - 1) {
2974
+ await sleep2(delayMs);
2975
+ }
2976
+ }
2977
+ return null;
2978
+ }
2759
2979
 
2760
2980
  // src/bootstrap-reconcile.ts
2761
2981
  function createRelayBootstrapRegistrationId(profile, instanceName, itemHash) {
@@ -2962,6 +3182,9 @@ export {
2962
3182
  SSH_PUBLIC_KEY_PATTERN,
2963
3183
  SUCCESSFUL_DEPLOYMENTS_AGGREGATE_KEY,
2964
3184
  VM_BOOTSTRAP_CONFIG_AGGREGATE_KEY,
3185
+ VM_BOOTSTRAP_CONFIG_HISTORY_RETENTION_MS,
3186
+ VM_BOOTSTRAP_CONFIG_SIGNAL_POST_TYPE,
3187
+ VM_BOOTSTRAP_CONFIG_SIGNAL_REF,
2965
3188
  appendDeploymentTokenToSshPublicKey,
2966
3189
  broadcastAlephMessage,
2967
3190
  buildPaymentQuote,
@@ -2997,6 +3220,7 @@ export {
2997
3220
  fetchSchedulerAllocation,
2998
3221
  fetchUcGoPeerMetadata,
2999
3222
  fetchVmBootstrapConfigAggregate,
3223
+ fetchVmBootstrapConfigSignals,
3000
3224
  fetchVmRuntime,
3001
3225
  filterDeployableCrns,
3002
3226
  findCrnByHash,
@@ -3007,6 +3231,7 @@ export {
3007
3231
  isRetryableBroadcastFailure,
3008
3232
  isValidSshPublicKey,
3009
3233
  listGeocodedCrns,
3234
+ listStaleVmBootstrapConfigAggregateMessageHashes,
3010
3235
  mergePortFlagMaps,
3011
3236
  mergeRequiredPortForwards,
3012
3237
  messageTypeFromEnvelope,
@@ -3042,5 +3267,6 @@ export {
3042
3267
  waitForDeploymentResult,
3043
3268
  waitForRelayBootstrapRegistration,
3044
3269
  waitForSetupEndpoint,
3270
+ waitForVmBootstrapConfigSignal,
3045
3271
  waitForVmRuntime
3046
3272
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/core",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Reusable Aleph deployment, runtime, and guest lifecycle logic.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -16,7 +16,7 @@
16
16
  "access": "public"
17
17
  },
18
18
  "dependencies": {
19
- "@le-space/aleph-bootstrap": "0.4.1",
20
- "@le-space/shared-types": "0.4.1"
19
+ "@le-space/aleph-bootstrap": "0.4.3",
20
+ "@le-space/shared-types": "0.4.3"
21
21
  }
22
22
  }