@le-space/core 0.2.0 → 0.3.2

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/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import "./chunk-4VNS5WPM.js";
2
+
1
3
  // src/constants.ts
2
4
  var DEFAULT_ALEPH_CHANNEL = "TEST";
3
5
 
@@ -486,6 +488,20 @@ function extractReferenceHashes(details) {
486
488
  if (!Array.isArray(errors)) return [];
487
489
  return errors.filter((value) => typeof value === "string");
488
490
  }
491
+ function extractInsufficientBalanceMessage(details) {
492
+ if (!details || typeof details !== "object" || !("errors" in details)) {
493
+ return null;
494
+ }
495
+ const errors = details.errors;
496
+ const firstError = Array.isArray(errors) && errors[0] && typeof errors[0] === "object" ? errors[0] : null;
497
+ const accountBalance = typeof firstError?.account_balance === "number" || typeof firstError?.account_balance === "string" ? Number(firstError.account_balance) : Number.NaN;
498
+ const requiredBalance = typeof firstError?.required_balance === "number" || typeof firstError?.required_balance === "string" ? Number(firstError.required_balance) : Number.NaN;
499
+ if (!Number.isFinite(accountBalance) || !Number.isFinite(requiredBalance)) {
500
+ return null;
501
+ }
502
+ const shortfall = requiredBalance - accountBalance;
503
+ return shortfall > 0 ? `insufficient Aleph balance: ${accountBalance.toFixed(3)} available, ${requiredBalance.toFixed(3)} required, ${shortfall.toFixed(3)} short` : `insufficient Aleph balance: ${accountBalance.toFixed(3)} available, ${requiredBalance.toFixed(3)} required`;
504
+ }
489
505
  function describeRejectedDeployment(payload, references, rootfsRef) {
490
506
  const errorCode = typeof payload.error_code === "number" ? payload.error_code : null;
491
507
  const pendingReferences = references.filter((reference) => reference.status === "pending");
@@ -500,6 +516,10 @@ function describeRejectedDeployment(payload, references, rootfsRef) {
500
516
  if (missingReferences.length > 0) {
501
517
  return `Aleph rejected this deployment because referenced message(s) were not found on Aleph: ${missingReferences.map((reference) => reference.itemHash).join(", ")}.`;
502
518
  }
519
+ const insufficientBalanceMessage = extractInsufficientBalanceMessage(payload.details);
520
+ if (insufficientBalanceMessage) {
521
+ return `Aleph rejected this deployment due to ${insufficientBalanceMessage}.`;
522
+ }
503
523
  const referencedHashes = extractReferenceHashes(payload.details);
504
524
  if (referencedHashes.length > 0) {
505
525
  return `Aleph rejected this deployment${errorCode ? ` (error ${errorCode})` : ""}. Referenced message(s): ${referencedHashes.join(", ")}.`;
@@ -578,15 +598,6 @@ function normalizeExecution(item, crnUrl) {
578
598
  }
579
599
 
580
600
  // src/deployment-inspection.ts
581
- function insufficientBalanceMessage(details) {
582
- const firstError = details && Array.isArray(details.errors) && details.errors[0] && typeof details.errors[0] === "object" ? details.errors[0] : null;
583
- const accountBalance = firstError?.account_balance;
584
- const requiredBalance = firstError?.required_balance;
585
- if (accountBalance != null && requiredBalance != null) {
586
- return `insufficient Aleph balance: account has ${accountBalance}, required is ${requiredBalance}`;
587
- }
588
- return null;
589
- }
590
601
  async function fetchMessageEnvelope(itemHash, options) {
591
602
  const response = await options.fetch(`${options.apiHost ?? DEFAULT_ALEPH_API_HOST}/api/v0/messages/${itemHash}`, {
592
603
  cache: "no-cache"
@@ -611,7 +622,7 @@ async function inspectMessageResult(itemHash, options) {
611
622
  const details = payload.details && typeof payload.details === "object" ? payload.details : null;
612
623
  let rejectionReason = null;
613
624
  if (status === "rejected") {
614
- const balanceMessage = errorCode === 5 ? insufficientBalanceMessage(details) : null;
625
+ const balanceMessage = extractInsufficientBalanceMessage(details);
615
626
  rejectionReason = balanceMessage ? `${label} ${itemHash} was rejected by Aleph due to ${balanceMessage}.` : `${label} ${itemHash} was rejected by Aleph${errorCode ? ` (error ${errorCode})` : ""}.`;
616
627
  }
617
628
  return {
@@ -1312,6 +1323,14 @@ function quoteRequiredBudgetUnits(quote) {
1312
1323
  if (!quote) return 0n;
1313
1324
  return BigInt(Math.ceil(quote.required * 1e18));
1314
1325
  }
1326
+ function describeRejectedInstanceBroadcast(response) {
1327
+ const balanceMessage = extractInsufficientBalanceMessage(response.details);
1328
+ if (balanceMessage) {
1329
+ return `Aleph rejected this deployment due to ${balanceMessage}.`;
1330
+ }
1331
+ const errorCode = typeof response.error_code === "number" ? response.error_code : null;
1332
+ return `Aleph rejected this deployment${errorCode ? ` (error ${errorCode})` : ""}.`;
1333
+ }
1315
1334
  function createInstanceContent(args) {
1316
1335
  const sshKey = normalizeSshPublicKey(args.sshPublicKey);
1317
1336
  if (!sshKey) {
@@ -1449,9 +1468,9 @@ async function deployInstance(args) {
1449
1468
  label: status === "processed" ? "Deployment accepted by Aleph" : status === "rejected" ? "Deployment rejected by Aleph" : "Deployment submitted to Aleph",
1450
1469
  progress: status === "processed" ? 88 : status === "rejected" ? 100 : 78,
1451
1470
  status: status === "processed" ? "success" : status === "rejected" ? "error" : "warning",
1452
- detail: status === "rejected" ? String(response.details ?? "Aleph rejected this deployment.") : null,
1471
+ detail: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null,
1453
1472
  itemHash: message.item_hash,
1454
- error: status === "rejected" ? String(response.details ?? "Aleph rejected this deployment.") : null,
1473
+ error: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null,
1455
1474
  timestamp: Date.now()
1456
1475
  });
1457
1476
  return {
@@ -1460,7 +1479,7 @@ async function deployInstance(args) {
1460
1479
  status,
1461
1480
  message,
1462
1481
  response,
1463
- rejectionReason: status === "rejected" ? String(response.details ?? "Aleph rejected this deployment.") : null
1482
+ rejectionReason: status === "rejected" ? describeRejectedInstanceBroadcast(response) : null
1464
1483
  };
1465
1484
  }
1466
1485
 
@@ -1857,7 +1876,13 @@ async function configureUcGoPeer(args) {
1857
1876
  ws_port: args.wsPort ?? void 0,
1858
1877
  udp_port: args.udpPort ?? void 0,
1859
1878
  quic_port: args.quicPort ?? void 0,
1860
- webrtc_port: args.webrtcPort ?? void 0
1879
+ webrtc_port: args.webrtcPort ?? void 0,
1880
+ bootstrap_publisher_private_key: args.bootstrapPublisherPrivateKey ?? void 0,
1881
+ bootstrap_publisher_libp2p_identity_b64: args.bootstrapPublisherLibp2pIdentityBase64 ?? void 0,
1882
+ bootstrap_owner_private_key: args.bootstrapOwnerPrivateKey ?? void 0,
1883
+ bootstrap_owner_authorization_b64: args.bootstrapOwnerAuthorizationBase64 ?? void 0,
1884
+ bootstrap_registration_id: args.bootstrapRegistrationId ?? void 0,
1885
+ no_start: args.noStart === true ? true : void 0
1861
1886
  };
1862
1887
  try {
1863
1888
  const response = await args.fetch(
@@ -1897,7 +1922,13 @@ async function configureOrbitdbRelaySetup(args) {
1897
1922
  metrics_port: args.metricsPort ?? void 0,
1898
1923
  metrics_https_port: args.metricsHttpsPort ?? void 0,
1899
1924
  webrtc_port: args.webrtcPort ?? void 0,
1900
- quic_port: args.quicPort ?? void 0
1925
+ quic_port: args.quicPort ?? void 0,
1926
+ bootstrap_publisher_private_key: args.bootstrapPublisherPrivateKey ?? void 0,
1927
+ bootstrap_publisher_libp2p_identity_hex: args.bootstrapPublisherLibp2pIdentityHex ?? void 0,
1928
+ bootstrap_owner_private_key: args.bootstrapOwnerPrivateKey ?? void 0,
1929
+ bootstrap_owner_authorization_b64: args.bootstrapOwnerAuthorizationBase64 ?? void 0,
1930
+ bootstrap_registration_id: args.bootstrapRegistrationId ?? void 0,
1931
+ no_start: args.noStart === true ? true : void 0
1901
1932
  };
1902
1933
  try {
1903
1934
  const response = await args.fetch(
@@ -2022,6 +2053,459 @@ async function verifyUcGoPeerReachability(args) {
2022
2053
  checks
2023
2054
  };
2024
2055
  }
2056
+
2057
+ // ../aleph-bootstrap/src/index.ts
2058
+ var DEFAULT_ALEPH_API_HOST2 = "https://api2.aleph.im";
2059
+ var DEFAULT_ALEPH_BOOTSTRAP_CHANNEL = "simple-todo";
2060
+ var DEFAULT_ALEPH_BOOTSTRAP_REF = "simple-todo-bootstrap";
2061
+ var DEFAULT_ALEPH_BOOTSTRAP_POST_TYPE = "relay-bootstrap";
2062
+ var DEFAULT_BOOTSTRAP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
2063
+ var DEFAULT_BOOTSTRAP_PAGINATION = 50;
2064
+ var RELAY_BOOTSTRAP_SIGNATURE_SCHEME = "personal_sign";
2065
+ function serializeOwnerAuthorizationPayload(payload) {
2066
+ return JSON.stringify({
2067
+ ownerAddress: payload.ownerAddress,
2068
+ publisherAddress: payload.publisherAddress,
2069
+ peerId: payload.peerId,
2070
+ registrationId: payload.registrationId,
2071
+ profile: payload.profile,
2072
+ version: payload.version,
2073
+ instanceItemHash: payload.instanceItemHash,
2074
+ issuedAt: payload.issuedAt,
2075
+ expiresAt: payload.expiresAt
2076
+ });
2077
+ }
2078
+ function serializeRelayProofPayload(payload) {
2079
+ return JSON.stringify({
2080
+ peerId: payload.peerId,
2081
+ multiaddrs: dedupeMultiaddrs(payload.multiaddrs),
2082
+ browserMultiaddrs: payload.browserMultiaddrs ? dedupeMultiaddrs(payload.browserMultiaddrs) : void 0,
2083
+ registrationId: payload.registrationId,
2084
+ profile: payload.profile,
2085
+ version: payload.version,
2086
+ updatedAt: payload.updatedAt
2087
+ });
2088
+ }
2089
+ function asTrimmedString(value) {
2090
+ return typeof value === "string" && value.trim() ? value.trim() : null;
2091
+ }
2092
+ function asNumber3(value) {
2093
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2094
+ if (typeof value === "string" && value.trim()) {
2095
+ const parsed = Number(value);
2096
+ return Number.isFinite(parsed) ? parsed : null;
2097
+ }
2098
+ return null;
2099
+ }
2100
+ function normalizeHost(host) {
2101
+ return host.trim().toLowerCase();
2102
+ }
2103
+ function normalizeSignature(signature) {
2104
+ const trimmed = signature.trim();
2105
+ return trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
2106
+ }
2107
+ function splitMultiaddr(addr) {
2108
+ return addr.split("/").filter(Boolean);
2109
+ }
2110
+ function isPrivateIpv4(ip) {
2111
+ const parts = ip.split(".").map((part) => Number(part));
2112
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
2113
+ return false;
2114
+ }
2115
+ if (parts[0] === 10) return true;
2116
+ if (parts[0] === 127) return true;
2117
+ if (parts[0] === 0) return true;
2118
+ if (parts[0] === 169 && parts[1] === 254) return true;
2119
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
2120
+ if (parts[0] === 192 && parts[1] === 168) return true;
2121
+ if (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) return true;
2122
+ return false;
2123
+ }
2124
+ function isPrivateIpv6(ip) {
2125
+ const normalized = ip.trim().toLowerCase();
2126
+ return normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
2127
+ }
2128
+ function isLocalHostname(host) {
2129
+ const normalized = normalizeHost(host);
2130
+ return normalized === "localhost" || normalized.endsWith(".localhost") || normalized.endsWith(".local");
2131
+ }
2132
+ function hasPeerId(addr) {
2133
+ return splitMultiaddr(addr).includes("p2p");
2134
+ }
2135
+ function isBrowserDialableMultiaddr(addr) {
2136
+ const normalized = addr.toLowerCase();
2137
+ return normalized.includes("/ws") || normalized.includes("/wss") || normalized.includes("/webtransport") || normalized.includes("/webrtc-direct");
2138
+ }
2139
+ function dedupeMultiaddrs(addrs) {
2140
+ const seen = /* @__PURE__ */ new Set();
2141
+ const result = [];
2142
+ for (const value of addrs) {
2143
+ const trimmed = value.trim();
2144
+ if (!trimmed || seen.has(trimmed)) continue;
2145
+ seen.add(trimmed);
2146
+ result.push(trimmed);
2147
+ }
2148
+ return result;
2149
+ }
2150
+ function isPublicMultiaddr(addr) {
2151
+ const parts = splitMultiaddr(addr);
2152
+ for (let index = 0; index < parts.length; index += 1) {
2153
+ const protocol = parts[index];
2154
+ const value = parts[index + 1];
2155
+ if (protocol === "ip4" && value) {
2156
+ return !isPrivateIpv4(value);
2157
+ }
2158
+ if (protocol === "ip6" && value) {
2159
+ return !isPrivateIpv6(value);
2160
+ }
2161
+ if ((protocol === "dns4" || protocol === "dns6" || protocol === "dnsaddr") && value) {
2162
+ return !isLocalHostname(value);
2163
+ }
2164
+ }
2165
+ return false;
2166
+ }
2167
+ function filterPublicMultiaddrs(addrs, options = {}) {
2168
+ return dedupeMultiaddrs(addrs).filter((addr) => {
2169
+ if (!isPublicMultiaddr(addr)) return false;
2170
+ if (options.requirePeerId !== false && !hasPeerId(addr)) return false;
2171
+ if (options.browserDialableOnly && !isBrowserDialableMultiaddr(addr)) {
2172
+ return false;
2173
+ }
2174
+ return true;
2175
+ });
2176
+ }
2177
+ function normalizeRelayBootstrapContent(value) {
2178
+ if (!value || typeof value !== "object") return null;
2179
+ const content = value;
2180
+ const peerId = asTrimmedString(content.peerId);
2181
+ const updatedAt = asNumber3(content.updatedAt);
2182
+ if (!peerId || updatedAt == null) return null;
2183
+ const multiaddrs = Array.isArray(content.multiaddrs) ? content.multiaddrs.filter((entry) => typeof entry === "string") : [];
2184
+ const browserMultiaddrs = Array.isArray(content.browserMultiaddrs) ? content.browserMultiaddrs.filter((entry) => typeof entry === "string") : void 0;
2185
+ return {
2186
+ peerId,
2187
+ multiaddrs: dedupeMultiaddrs(multiaddrs),
2188
+ browserMultiaddrs: browserMultiaddrs ? dedupeMultiaddrs(browserMultiaddrs) : void 0,
2189
+ registrationId: asTrimmedString(content.registrationId) ?? void 0,
2190
+ profile: asTrimmedString(content.profile) ?? void 0,
2191
+ version: asTrimmedString(content.version) ?? void 0,
2192
+ ownerAddress: asTrimmedString(content.ownerAddress) ?? void 0,
2193
+ publisherAddress: asTrimmedString(content.publisherAddress) ?? void 0,
2194
+ authorization: normalizeRelayBootstrapAuthorizationRecord(content.authorization) ?? void 0,
2195
+ relayProof: normalizeRelayBootstrapProofRecord(content.relayProof) ?? void 0,
2196
+ updatedAt
2197
+ };
2198
+ }
2199
+ function normalizeRelayBootstrapAuthorizationPayload(value) {
2200
+ if (!value || typeof value !== "object") return null;
2201
+ const payload = value;
2202
+ const ownerAddress = asTrimmedString(payload.ownerAddress);
2203
+ const publisherAddress = asTrimmedString(payload.publisherAddress);
2204
+ const peerId = asTrimmedString(payload.peerId);
2205
+ const issuedAt = asNumber3(payload.issuedAt);
2206
+ const expiresAt = asNumber3(payload.expiresAt) ?? void 0;
2207
+ if (!ownerAddress || !publisherAddress || !peerId || issuedAt == null) {
2208
+ return null;
2209
+ }
2210
+ return {
2211
+ ownerAddress,
2212
+ publisherAddress,
2213
+ peerId,
2214
+ registrationId: asTrimmedString(payload.registrationId) ?? void 0,
2215
+ profile: asTrimmedString(payload.profile) ?? void 0,
2216
+ version: asTrimmedString(payload.version) ?? void 0,
2217
+ instanceItemHash: asTrimmedString(payload.instanceItemHash) ?? void 0,
2218
+ issuedAt,
2219
+ expiresAt
2220
+ };
2221
+ }
2222
+ function normalizeRelayBootstrapAuthorizationRecord(value) {
2223
+ if (!value || typeof value !== "object") return null;
2224
+ const record = value;
2225
+ const scheme = asTrimmedString(record.scheme);
2226
+ const signature = asTrimmedString(record.signature);
2227
+ const payload = normalizeRelayBootstrapAuthorizationPayload(record.payload);
2228
+ if (!scheme || !signature || !payload) return null;
2229
+ return { scheme, signature, payload };
2230
+ }
2231
+ function normalizeRelayBootstrapProofPayload(value) {
2232
+ if (!value || typeof value !== "object") return null;
2233
+ const payload = value;
2234
+ const peerId = asTrimmedString(payload.peerId);
2235
+ const updatedAt = asNumber3(payload.updatedAt);
2236
+ if (!peerId || updatedAt == null) return null;
2237
+ const multiaddrs = Array.isArray(payload.multiaddrs) ? payload.multiaddrs.filter((entry) => typeof entry === "string") : [];
2238
+ const browserMultiaddrs = Array.isArray(payload.browserMultiaddrs) ? payload.browserMultiaddrs.filter((entry) => typeof entry === "string") : void 0;
2239
+ return {
2240
+ peerId,
2241
+ multiaddrs: dedupeMultiaddrs(multiaddrs),
2242
+ browserMultiaddrs: browserMultiaddrs ? dedupeMultiaddrs(browserMultiaddrs) : void 0,
2243
+ registrationId: asTrimmedString(payload.registrationId) ?? void 0,
2244
+ profile: asTrimmedString(payload.profile) ?? void 0,
2245
+ version: asTrimmedString(payload.version) ?? void 0,
2246
+ updatedAt
2247
+ };
2248
+ }
2249
+ function normalizeRelayBootstrapProofRecord(value) {
2250
+ if (!value || typeof value !== "object") return null;
2251
+ const record = value;
2252
+ const scheme = asTrimmedString(record.scheme);
2253
+ const signature = asTrimmedString(record.signature);
2254
+ const payload = normalizeRelayBootstrapProofPayload(record.payload);
2255
+ if (!scheme || !signature || !payload) return null;
2256
+ return { scheme, signature, payload };
2257
+ }
2258
+ function normalizeRelayBootstrapPostRecord(value) {
2259
+ if (!value || typeof value !== "object") return null;
2260
+ const entry = value;
2261
+ return {
2262
+ hash: asTrimmedString(entry.hash),
2263
+ itemHash: asTrimmedString(entry.item_hash),
2264
+ address: asTrimmedString(entry.address),
2265
+ ref: asTrimmedString(entry.ref),
2266
+ type: asTrimmedString(entry.type),
2267
+ time: asNumber3(entry.time),
2268
+ content: normalizeRelayBootstrapContent(entry.content)
2269
+ };
2270
+ }
2271
+ function buildRelayBootstrapPostContent(args) {
2272
+ const now = args.now ?? Date.now() / 1e3;
2273
+ const updatedAt = args.now ?? Date.now();
2274
+ return {
2275
+ type: args.postType ?? DEFAULT_ALEPH_BOOTSTRAP_POST_TYPE,
2276
+ address: args.sender,
2277
+ ...args.ref ? { ref: args.ref } : {},
2278
+ content: {
2279
+ peerId: args.peerId,
2280
+ multiaddrs: filterPublicMultiaddrs(args.multiaddrs),
2281
+ browserMultiaddrs: args.browserMultiaddrs ? filterPublicMultiaddrs(args.browserMultiaddrs, {
2282
+ browserDialableOnly: true
2283
+ }) : void 0,
2284
+ registrationId: args.registrationId,
2285
+ profile: args.profile,
2286
+ version: args.version,
2287
+ ownerAddress: args.ownerAddress,
2288
+ publisherAddress: args.publisherAddress,
2289
+ authorization: args.authorization,
2290
+ relayProof: args.relayProof,
2291
+ updatedAt: Math.round(updatedAt)
2292
+ },
2293
+ time: now
2294
+ };
2295
+ }
2296
+ async function createRelayBootstrapPost(args) {
2297
+ const nowMillis = args.now ?? Date.now();
2298
+ const nowSeconds = nowMillis / 1e3;
2299
+ const itemContent = buildRelayBootstrapPostContent({
2300
+ sender: args.sender,
2301
+ peerId: args.peerId,
2302
+ multiaddrs: args.multiaddrs,
2303
+ browserMultiaddrs: args.browserMultiaddrs,
2304
+ registrationId: args.registrationId,
2305
+ ref: args.ref ?? DEFAULT_ALEPH_BOOTSTRAP_REF,
2306
+ postType: args.postType ?? DEFAULT_ALEPH_BOOTSTRAP_POST_TYPE,
2307
+ profile: args.profile,
2308
+ version: args.version,
2309
+ ownerAddress: args.ownerAddress,
2310
+ publisherAddress: args.publisherAddress,
2311
+ authorization: args.authorization,
2312
+ relayProof: args.relayProof,
2313
+ now: nowMillis
2314
+ });
2315
+ itemContent.time = nowSeconds;
2316
+ const serialized = JSON.stringify(itemContent);
2317
+ const itemHash = await args.hasher(serialized);
2318
+ return {
2319
+ channel: args.channel ?? DEFAULT_ALEPH_BOOTSTRAP_CHANNEL,
2320
+ sender: args.sender,
2321
+ chain: "ETH",
2322
+ type: "POST",
2323
+ time: nowSeconds,
2324
+ item_type: "inline",
2325
+ item_content: serialized,
2326
+ item_hash: itemHash
2327
+ };
2328
+ }
2329
+ async function signRelayBootstrapAuthorization(args) {
2330
+ const payload = {
2331
+ ownerAddress: args.ownerAddress,
2332
+ publisherAddress: args.publisherAddress,
2333
+ peerId: args.peerId,
2334
+ registrationId: args.registrationId,
2335
+ profile: args.profile,
2336
+ version: args.version,
2337
+ instanceItemHash: args.instanceItemHash,
2338
+ issuedAt: args.issuedAt ?? Date.now(),
2339
+ expiresAt: args.expiresAt
2340
+ };
2341
+ const serialized = serializeOwnerAuthorizationPayload(payload);
2342
+ const signature = await args.signer(args.ownerAddress, serialized);
2343
+ return {
2344
+ scheme: RELAY_BOOTSTRAP_SIGNATURE_SCHEME,
2345
+ payload,
2346
+ signature: normalizeSignature(signature)
2347
+ };
2348
+ }
2349
+ async function signRelayBootstrapProof(args) {
2350
+ const payload = {
2351
+ peerId: args.peerId,
2352
+ multiaddrs: filterPublicMultiaddrs(args.multiaddrs),
2353
+ browserMultiaddrs: args.browserMultiaddrs ? filterPublicMultiaddrs(args.browserMultiaddrs, {
2354
+ browserDialableOnly: true
2355
+ }) : void 0,
2356
+ registrationId: args.registrationId,
2357
+ profile: args.profile,
2358
+ version: args.version,
2359
+ updatedAt: args.updatedAt ?? Date.now()
2360
+ };
2361
+ const serialized = serializeRelayProofPayload(payload);
2362
+ const signature = await args.signer(args.publisherAddress, serialized);
2363
+ return {
2364
+ scheme: RELAY_BOOTSTRAP_SIGNATURE_SCHEME,
2365
+ payload,
2366
+ signature: normalizeSignature(signature)
2367
+ };
2368
+ }
2369
+ async function fetchAlephBootstrapPosts(options = {}) {
2370
+ const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
2371
+ if (typeof fetchImpl !== "function") {
2372
+ throw new Error(
2373
+ "A fetch implementation is required to query Aleph bootstrap posts."
2374
+ );
2375
+ }
2376
+ const url = new URL(
2377
+ "/api/v0/posts.json",
2378
+ options.apiHost ?? DEFAULT_ALEPH_API_HOST2
2379
+ );
2380
+ url.searchParams.set(
2381
+ "channels",
2382
+ options.channel ?? DEFAULT_ALEPH_BOOTSTRAP_CHANNEL
2383
+ );
2384
+ url.searchParams.set("refs", options.ref ?? DEFAULT_ALEPH_BOOTSTRAP_REF);
2385
+ url.searchParams.set(
2386
+ "types",
2387
+ options.postType ?? DEFAULT_ALEPH_BOOTSTRAP_POST_TYPE
2388
+ );
2389
+ url.searchParams.set(
2390
+ "pagination",
2391
+ String(options.pagination ?? DEFAULT_BOOTSTRAP_PAGINATION)
2392
+ );
2393
+ url.searchParams.set("page", String(options.page ?? 1));
2394
+ const response = await fetchImpl(url.toString(), {
2395
+ method: "GET",
2396
+ headers: { accept: "application/json" }
2397
+ });
2398
+ if (!response.ok) {
2399
+ throw new Error(`Aleph bootstrap post lookup failed: ${response.status}`);
2400
+ }
2401
+ const payload = await response.json();
2402
+ return (payload.posts ?? []).map((entry) => normalizeRelayBootstrapPostRecord(entry)).filter((entry) => entry != null);
2403
+ }
2404
+
2405
+ // src/bootstrap-registration.ts
2406
+ async function publishRelayBootstrapRegistration(args) {
2407
+ const publisherAddress = args.publisherAddress ?? args.sender;
2408
+ const ownerAddress = args.ownerAddress;
2409
+ let ownerAuthorization = args.ownerAuthorization;
2410
+ let relayProof = args.relayProof;
2411
+ if (!ownerAuthorization && ownerAddress && args.ownerSigner) {
2412
+ ownerAuthorization = await signRelayBootstrapAuthorization({
2413
+ ownerAddress,
2414
+ publisherAddress,
2415
+ peerId: args.peerId,
2416
+ registrationId: args.registrationId,
2417
+ profile: args.profile,
2418
+ version: args.version,
2419
+ instanceItemHash: args.instanceItemHash,
2420
+ issuedAt: args.authorizationIssuedAt ?? args.now ?? Date.now(),
2421
+ expiresAt: args.authorizationExpiresAt,
2422
+ signer: args.ownerSigner
2423
+ });
2424
+ }
2425
+ if (!relayProof && args.publisherSigner) {
2426
+ relayProof = await signRelayBootstrapProof({
2427
+ publisherAddress,
2428
+ peerId: args.peerId,
2429
+ multiaddrs: args.multiaddrs,
2430
+ browserMultiaddrs: args.browserMultiaddrs,
2431
+ registrationId: args.registrationId,
2432
+ profile: args.profile,
2433
+ version: args.version,
2434
+ updatedAt: args.now ?? Date.now(),
2435
+ signer: args.publisherSigner
2436
+ });
2437
+ }
2438
+ const unsigned = await createRelayBootstrapPost({
2439
+ sender: args.sender,
2440
+ peerId: args.peerId,
2441
+ multiaddrs: args.multiaddrs,
2442
+ browserMultiaddrs: args.browserMultiaddrs,
2443
+ registrationId: args.registrationId,
2444
+ channel: args.channel,
2445
+ ref: args.ref,
2446
+ postType: args.postType,
2447
+ profile: args.profile,
2448
+ version: args.version,
2449
+ ownerAddress,
2450
+ publisherAddress,
2451
+ authorization: ownerAuthorization,
2452
+ relayProof,
2453
+ now: args.now,
2454
+ hasher: args.hasher
2455
+ });
2456
+ const content = JSON.parse(unsigned.item_content);
2457
+ if ((content.content?.multiaddrs?.length ?? 0) === 0) {
2458
+ return {
2459
+ status: "skipped",
2460
+ reason: "No public relay multiaddrs remained after filtering.",
2461
+ publishedMultiaddrs: [],
2462
+ publishedBrowserMultiaddrs: content.content?.browserMultiaddrs ?? []
2463
+ };
2464
+ }
2465
+ const message = await signAlephMessage(unsigned, args.signer);
2466
+ const { response, httpStatus } = await broadcastAlephMessage(message, {
2467
+ apiHost: args.apiHost ?? DEFAULT_ALEPH_API_HOST2,
2468
+ sync: args.sync ?? true,
2469
+ fetch: args.fetch
2470
+ });
2471
+ let forgottenHashes = [];
2472
+ let forgetResult;
2473
+ if (args.forgetPrevious && args.registrationId) {
2474
+ const previousPosts = await fetchAlephBootstrapPosts({
2475
+ apiHost: args.apiHost ?? DEFAULT_ALEPH_API_HOST2,
2476
+ channel: args.channel,
2477
+ ref: args.ref,
2478
+ postType: args.postType,
2479
+ fetch: args.fetch
2480
+ });
2481
+ forgottenHashes = previousPosts.filter(
2482
+ (post) => post.address?.toLowerCase() === args.sender.toLowerCase() && post.content?.registrationId === args.registrationId && (post.itemHash ?? post.hash) != null && (post.itemHash ?? post.hash) !== unsigned.item_hash
2483
+ ).map((post) => post.itemHash ?? post.hash ?? "").filter(Boolean);
2484
+ if (forgottenHashes.length > 0) {
2485
+ forgetResult = await forgetAlephMessages({
2486
+ sender: args.sender,
2487
+ hashes: forgottenHashes,
2488
+ reason: args.forgetPreviousReason ?? `Replace older relay bootstrap records for ${args.registrationId}`,
2489
+ signer: args.signer,
2490
+ hasher: args.hasher,
2491
+ fetch: args.fetch,
2492
+ apiHost: args.apiHost ?? DEFAULT_ALEPH_API_HOST2,
2493
+ sync: args.sync ?? true
2494
+ });
2495
+ }
2496
+ }
2497
+ return {
2498
+ status: "published",
2499
+ itemHash: unsigned.item_hash,
2500
+ message,
2501
+ response,
2502
+ httpStatus,
2503
+ publishedMultiaddrs: content.content?.multiaddrs ?? [],
2504
+ publishedBrowserMultiaddrs: content.content?.browserMultiaddrs ?? [],
2505
+ forgottenHashes,
2506
+ forgetResult
2507
+ };
2508
+ }
2025
2509
  export {
2026
2510
  DEFAULT_ALEPH_API_HOST,
2027
2511
  DEFAULT_ALEPH_CHANNEL,
@@ -2052,6 +2536,7 @@ export {
2052
2536
  describeRuntimeAvailability,
2053
2537
  enrichCrnsWithGeo,
2054
2538
  ensureInstancePortForwards,
2539
+ extractInsufficientBalanceMessage,
2055
2540
  extractProxyUrl,
2056
2541
  extractReferenceHashes,
2057
2542
  fetch2n6WebAccessUrl,
@@ -2087,6 +2572,7 @@ export {
2087
2572
  postBroadcastPayload,
2088
2573
  probeRootfsGateway,
2089
2574
  publishAggregateKey,
2575
+ publishRelayBootstrapRegistration,
2090
2576
  quoteRequiredBudgetUnits,
2091
2577
  rankCandidateCrns,
2092
2578
  requestedPortFlags,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.2",
4
4
  "description": "Reusable Aleph deployment, runtime, and guest lifecycle logic.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -16,6 +16,7 @@
16
16
  "access": "public"
17
17
  },
18
18
  "dependencies": {
19
- "@le-space/shared-types": "0.2.0"
19
+ "@le-space/aleph-bootstrap": "0.3.2",
20
+ "@le-space/shared-types": "0.3.2"
20
21
  }
21
22
  }