@le-space/browser 0.9.9 → 0.10.0
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.d.ts +43 -4
- package/index.js +446 -7
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { AttestWasm, ConfidentialProgress, SnpTrustedExecution, UnlockResult, confidentialTrustedExecution, pinsOf, unlockInstance } from '@le-space/attest-wasm/instance';
|
|
2
|
+
|
|
1
3
|
declare const DEFAULT_ALEPH_API_HOSTS: readonly string[];
|
|
2
4
|
declare const DEFAULT_ALEPH_API_HOST: string;
|
|
3
5
|
declare const DEFAULT_CRN_LIST_URL = "https://crns-list.aleph.sh/crns.json";
|
|
@@ -122,10 +124,19 @@ interface BrowserPackagePlan {
|
|
|
122
124
|
}
|
|
123
125
|
declare const BROWSER_PACKAGE_PLAN: BrowserPackagePlan;
|
|
124
126
|
interface EthereumProviderLike {
|
|
127
|
+
isMetaMask?: boolean;
|
|
125
128
|
request<T = unknown>(args: {
|
|
126
129
|
method: string;
|
|
127
130
|
params?: unknown[] | Record<string, unknown>;
|
|
128
131
|
}): Promise<T>;
|
|
132
|
+
on?(event: string, listener: (...args: unknown[]) => void): void;
|
|
133
|
+
removeListener?(event: string, listener: (...args: unknown[]) => void): void;
|
|
134
|
+
}
|
|
135
|
+
interface WalletState {
|
|
136
|
+
connected: boolean;
|
|
137
|
+
address: string | null;
|
|
138
|
+
chainId: string | null;
|
|
139
|
+
isMetaMask: boolean;
|
|
129
140
|
}
|
|
130
141
|
interface EthereumTransactionRequest {
|
|
131
142
|
from: string;
|
|
@@ -230,7 +241,17 @@ interface Crn {
|
|
|
230
241
|
gpu_support?: boolean;
|
|
231
242
|
system_usage?: CrnUsage | null;
|
|
232
243
|
payment_receiver_address?: string | null;
|
|
244
|
+
/** Registered owner (corechannel aggregate). */
|
|
245
|
+
owner?: string | null;
|
|
233
246
|
version?: string | null;
|
|
247
|
+
/** CPU features from the node's /about/usage/system, e.g. ["sev", "sev_es", "sev_snp"]. */
|
|
248
|
+
cpu_features?: string[] | null;
|
|
249
|
+
/** TEE properties from /about/usage/system; present on SEV-SNP nodes. */
|
|
250
|
+
tee?: {
|
|
251
|
+
sev_snp?: {
|
|
252
|
+
supported_vcpu_types?: string[];
|
|
253
|
+
};
|
|
254
|
+
} | null;
|
|
234
255
|
city?: string | null;
|
|
235
256
|
region?: string | null;
|
|
236
257
|
country?: string | null;
|
|
@@ -485,7 +506,19 @@ declare function createAlephBrowserClient(options?: CreateAlephBrowserClientOpti
|
|
|
485
506
|
|
|
486
507
|
declare function ethCall(to: string, data: `0x${string}`, provider: EthereumProviderLike | null | undefined): Promise<string>;
|
|
487
508
|
declare function sendTransaction(tx: EthereumTransactionRequest, provider: EthereumProviderLike | null | undefined): Promise<string>;
|
|
488
|
-
declare function personalSign(address: string, message: string, provider
|
|
509
|
+
declare function personalSign(address: string, message: string, provider?: EthereumProviderLike | null | undefined): Promise<string>;
|
|
510
|
+
|
|
511
|
+
interface ConnectWalletOptions {
|
|
512
|
+
/**
|
|
513
|
+
* Applied to the address the wallet reports. This package has no runtime
|
|
514
|
+
* dependencies, so checksumming is the caller's to supply — `@le-space/ui`
|
|
515
|
+
* passes viem's `getAddress`.
|
|
516
|
+
*/
|
|
517
|
+
normaliseAddress?: (address: string) => string;
|
|
518
|
+
}
|
|
519
|
+
declare function getEthereumProvider(): EthereumProviderLike | null;
|
|
520
|
+
declare function connectWallet(provider?: EthereumProviderLike | null | undefined, options?: ConnectWalletOptions): Promise<WalletState>;
|
|
521
|
+
declare function watchWallet(onChange: () => void, provider?: EthereumProviderLike | null | undefined): () => void;
|
|
489
522
|
|
|
490
523
|
declare function paymentChainFromChainId(chainId: string | null, chainConfig: Record<PaymentChain, EvmChainConfig>): PaymentChain | null;
|
|
491
524
|
declare function formatBudgetUnits(value: bigint, decimals?: number): number;
|
|
@@ -548,7 +581,13 @@ declare function verifyRootfsExists(itemHash: string, apiHost?: string): Promise
|
|
|
548
581
|
declare function resolveRootfsReference(itemHash: string, apiHost?: string, gatewayBaseUrl?: string): Promise<RootfsResolution | null>;
|
|
549
582
|
|
|
550
583
|
declare const DEFAULT_ALEPH_AGGREGATE_ADDRESS = "0xFba561a84A537fCaa567bb7A2257e7142701ae2A";
|
|
551
|
-
|
|
552
|
-
|
|
584
|
+
/**
|
|
585
|
+
* Which pricing entry of the aggregate to read: `instance` for a normal VM,
|
|
586
|
+
* `instance_confidential` for one on AMD SEV / SEV-SNP (twice the compute
|
|
587
|
+
* price on 2026-10-15).
|
|
588
|
+
*/
|
|
589
|
+
type InstancePricingKind = 'instance' | 'instance_confidential';
|
|
590
|
+
declare function parseInstancePricing(payload: unknown, kind?: InstancePricingKind): InstancePricing;
|
|
591
|
+
declare function fetchInstancePricing(apiHost?: string, aggregateAddress?: string, kind?: InstancePricingKind): Promise<PricingState>;
|
|
553
592
|
|
|
554
|
-
export { type AlephBroadcastMessage, type AlephBroadcastResponse, type AlephBrowserClient, type AlephMessageEnvelope, type AlephMessageType, type AlephSenderChain, type AllocationNotifyResult, BROWSER_PACKAGE_PLAN, type BalanceResponse, type BroadcastResult, type BrowserExtractionPhase, type BrowserPackagePlan, type ComputeUnit, type CreateAlephBrowserClientOptions, type Crn, type CrnExecutionLookupResult, type CrnListResponse, type CrnListResult, type CrnLocation, type CrnProbeVerdict, type CrnSource, type CrnSourcePreference, type CrnUsage, DEFAULT_2N6_API_HOST, DEFAULT_ALEPH_AGGREGATE_ADDRESS, DEFAULT_ALEPH_API_HOST, DEFAULT_ALEPH_API_HOSTS, DEFAULT_ALEPH_SCHEDULER_API_HOST, DEFAULT_CRN_AGGREGATE_ADDRESS, DEFAULT_CRN_AGGREGATE_KEY, DEFAULT_CRN_LIST_URL, DEFAULT_IPFS_GATEWAY_BASE_URL, DEFAULT_ROOTFS_MANIFEST_URL, type DeploymentInspectionResult, type EthereumProviderLike, type EthereumTransactionRequest, type EvmChainConfig, type FetchCrnsOptions, type GatewayProbeStatus, ITEM_HASH_RE, type InstanceAllocation, type InstanceAllocationNode, type InstanceAllocationPeriod, type InstanceExecution, type InstanceExecutionNetworking, type InstanceExecutionStatus, type InstanceMessage, type InstancePortMapping, type InstancePricing, type LoadRootfsManifestOptions, type MessageReference, type MessageStatus, type PaymentChain, type PaymentMode, type PrepaidReservation, type PrepaidVaultSnapshot, type Price, type PricingState, type ReferenceStatus, type RelaySetupRequest, type RelaySetupResult, type RootfsManifest, type RootfsManifestState, type RootfsRequiredPortForward, type RootfsResolution, type Tier, approvePrepaidBudget, broadcastAlephMessage, broadcastInstanceMessage, configureOrbitdbRelaySetup, consumeDeploymentReservation, createAlephBrowserClient, depositPrepaidBudget, ethCall, fetch2n6WebAccessUrl, fetchBalance, fetchCrnExecutionMap, fetchCrns, fetchCrnsFromAggregate, fetchCrnsFromList, fetchCrnsWithSource, fetchInstancePricing, fetchInstances, fetchMessageEnvelope, fetchSchedulerAllocation, fetchWithTimeout, filterReachableCrns, formatBudgetUnits, inspectDeploymentResult, loadPrepaidReservation, loadPrepaidVaultSnapshot, loadRootfsManifest, mapResourceNodesToCrns, normalizeExecution, normalizeMessageStatus, notifyCrnAllocation, parseInstancePricing, paymentChainFromChainId, personalSign, probeCrnAvailability, refundExpiredReservation, reserveDeploymentBudget, resolveRootfsReference, sendTransaction, validateRootfsManifest, verifyRootfsExists, waitForDeploymentResult };
|
|
593
|
+
export { type AlephBroadcastMessage, type AlephBroadcastResponse, type AlephBrowserClient, type AlephMessageEnvelope, type AlephMessageType, type AlephSenderChain, type AllocationNotifyResult, BROWSER_PACKAGE_PLAN, type BalanceResponse, type BroadcastResult, type BrowserExtractionPhase, type BrowserPackagePlan, type ComputeUnit, type ConnectWalletOptions, type CreateAlephBrowserClientOptions, type Crn, type CrnExecutionLookupResult, type CrnListResponse, type CrnListResult, type CrnLocation, type CrnProbeVerdict, type CrnSource, type CrnSourcePreference, type CrnUsage, DEFAULT_2N6_API_HOST, DEFAULT_ALEPH_AGGREGATE_ADDRESS, DEFAULT_ALEPH_API_HOST, DEFAULT_ALEPH_API_HOSTS, DEFAULT_ALEPH_SCHEDULER_API_HOST, DEFAULT_CRN_AGGREGATE_ADDRESS, DEFAULT_CRN_AGGREGATE_KEY, DEFAULT_CRN_LIST_URL, DEFAULT_IPFS_GATEWAY_BASE_URL, DEFAULT_ROOTFS_MANIFEST_URL, type DeploymentInspectionResult, type EthereumProviderLike, type EthereumTransactionRequest, type EvmChainConfig, type FetchCrnsOptions, type GatewayProbeStatus, ITEM_HASH_RE, type InstanceAllocation, type InstanceAllocationNode, type InstanceAllocationPeriod, type InstanceExecution, type InstanceExecutionNetworking, type InstanceExecutionStatus, type InstanceMessage, type InstancePortMapping, type InstancePricing, type InstancePricingKind, type LoadRootfsManifestOptions, type MessageReference, type MessageStatus, type PaymentChain, type PaymentMode, type PrepaidReservation, type PrepaidVaultSnapshot, type Price, type PricingState, type ReferenceStatus, type RelaySetupRequest, type RelaySetupResult, type RootfsManifest, type RootfsManifestState, type RootfsRequiredPortForward, type RootfsResolution, type Tier, type WalletState, approvePrepaidBudget, broadcastAlephMessage, broadcastInstanceMessage, configureOrbitdbRelaySetup, connectWallet, consumeDeploymentReservation, createAlephBrowserClient, depositPrepaidBudget, ethCall, fetch2n6WebAccessUrl, fetchBalance, fetchCrnExecutionMap, fetchCrns, fetchCrnsFromAggregate, fetchCrnsFromList, fetchCrnsWithSource, fetchInstancePricing, fetchInstances, fetchMessageEnvelope, fetchSchedulerAllocation, fetchWithTimeout, filterReachableCrns, formatBudgetUnits, getEthereumProvider, inspectDeploymentResult, loadPrepaidReservation, loadPrepaidVaultSnapshot, loadRootfsManifest, mapResourceNodesToCrns, normalizeExecution, normalizeMessageStatus, notifyCrnAllocation, parseInstancePricing, paymentChainFromChainId, personalSign, probeCrnAvailability, refundExpiredReservation, reserveDeploymentBudget, resolveRootfsReference, sendTransaction, validateRootfsManifest, verifyRootfsExists, waitForDeploymentResult, watchWallet };
|
package/index.js
CHANGED
|
@@ -689,6 +689,38 @@ function createAlephBrowserClient(options = {}) {
|
|
|
689
689
|
};
|
|
690
690
|
}
|
|
691
691
|
|
|
692
|
+
// src/wallet.ts
|
|
693
|
+
function getEthereumProvider() {
|
|
694
|
+
return globalThis.window?.ethereum ?? null;
|
|
695
|
+
}
|
|
696
|
+
async function connectWallet(provider = getEthereumProvider(), options = {}) {
|
|
697
|
+
if (!provider) {
|
|
698
|
+
throw new Error("MetaMask provider not found.");
|
|
699
|
+
}
|
|
700
|
+
const accounts = await provider.request({ method: "eth_requestAccounts" });
|
|
701
|
+
const chainId = await provider.request({ method: "eth_chainId" });
|
|
702
|
+
const account = accounts?.[0];
|
|
703
|
+
const address = account ? options.normaliseAddress?.(account) ?? account : null;
|
|
704
|
+
return {
|
|
705
|
+
connected: Boolean(address),
|
|
706
|
+
address,
|
|
707
|
+
chainId,
|
|
708
|
+
isMetaMask: Boolean(provider.isMetaMask)
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
function watchWallet(onChange, provider = getEthereumProvider()) {
|
|
712
|
+
if (!provider?.on || !provider?.removeListener) {
|
|
713
|
+
return () => {
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
provider.on("accountsChanged", onChange);
|
|
717
|
+
provider.on("chainChanged", onChange);
|
|
718
|
+
return () => {
|
|
719
|
+
provider.removeListener?.("accountsChanged", onChange);
|
|
720
|
+
provider.removeListener?.("chainChanged", onChange);
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
|
|
692
724
|
// src/evm.ts
|
|
693
725
|
function ensureHexQuantity(value) {
|
|
694
726
|
return `0x${value.toString(16)}`;
|
|
@@ -725,7 +757,7 @@ async function sendTransaction(tx, provider) {
|
|
|
725
757
|
]
|
|
726
758
|
});
|
|
727
759
|
}
|
|
728
|
-
async function personalSign(address, message, provider) {
|
|
760
|
+
async function personalSign(address, message, provider = getEthereumProvider()) {
|
|
729
761
|
assertProvider(provider);
|
|
730
762
|
const hexMessage = `0x${Array.from(new TextEncoder().encode(message)).map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
731
763
|
return provider.request({
|
|
@@ -1094,16 +1126,16 @@ async function resolveRootfsReference(itemHash, apiHost = DEFAULT_ALEPH_API_HOST
|
|
|
1094
1126
|
|
|
1095
1127
|
// src/pricing.ts
|
|
1096
1128
|
var DEFAULT_ALEPH_AGGREGATE_ADDRESS = "0xFba561a84A537fCaa567bb7A2257e7142701ae2A";
|
|
1097
|
-
function parseInstancePricing(payload) {
|
|
1129
|
+
function parseInstancePricing(payload, kind = "instance") {
|
|
1098
1130
|
const data = payload;
|
|
1099
1131
|
const pricing = data.data?.pricing ?? data.pricing;
|
|
1100
|
-
const instance = pricing?.
|
|
1132
|
+
const instance = pricing?.[kind];
|
|
1101
1133
|
if (!instance?.price?.compute_unit || !instance.compute_unit || !Array.isArray(instance.tiers)) {
|
|
1102
|
-
throw new Error(
|
|
1134
|
+
throw new Error(`Aleph pricing aggregate does not contain ${kind} pricing.`);
|
|
1103
1135
|
}
|
|
1104
1136
|
return instance;
|
|
1105
1137
|
}
|
|
1106
|
-
async function fetchInstancePricing(apiHost = DEFAULT_ALEPH_API_HOST, aggregateAddress = DEFAULT_ALEPH_AGGREGATE_ADDRESS) {
|
|
1138
|
+
async function fetchInstancePricing(apiHost = DEFAULT_ALEPH_API_HOST, aggregateAddress = DEFAULT_ALEPH_AGGREGATE_ADDRESS, kind = "instance") {
|
|
1107
1139
|
const response = await fetchWithTimeout(`${apiHost}/api/v0/aggregates/${aggregateAddress}.json?keys=pricing`, {
|
|
1108
1140
|
cache: "no-cache"
|
|
1109
1141
|
});
|
|
@@ -1116,10 +1148,411 @@ async function fetchInstancePricing(apiHost = DEFAULT_ALEPH_API_HOST, aggregateA
|
|
|
1116
1148
|
throw new Error("Pricing aggregate response did not include a pricing key.");
|
|
1117
1149
|
}
|
|
1118
1150
|
return {
|
|
1119
|
-
pricing: parseInstancePricing({ pricing: pricingAggregate }),
|
|
1151
|
+
pricing: parseInstancePricing({ pricing: pricingAggregate }, kind),
|
|
1120
1152
|
fetchedAt: Date.now()
|
|
1121
1153
|
};
|
|
1122
1154
|
}
|
|
1155
|
+
|
|
1156
|
+
// ../attest-wasm/js/index.mjs
|
|
1157
|
+
async function verifyAttestation({
|
|
1158
|
+
wasm,
|
|
1159
|
+
report,
|
|
1160
|
+
product,
|
|
1161
|
+
expectedMeasurements,
|
|
1162
|
+
expectedPolicy,
|
|
1163
|
+
minTcb,
|
|
1164
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
1165
|
+
nowSeconds = Date.now() / 1e3,
|
|
1166
|
+
sleep
|
|
1167
|
+
}) {
|
|
1168
|
+
if (!Array.isArray(expectedMeasurements) || expectedMeasurements.length === 0) {
|
|
1169
|
+
throw new Error("verifyAttestation needs the launch measurements the INSTANCE message pins");
|
|
1170
|
+
}
|
|
1171
|
+
product = product ?? wasm.detectProduct(report);
|
|
1172
|
+
if (!product) throw new Error("the report does not name its AMD product line (older firmware); pass product");
|
|
1173
|
+
const info = wasm.reportInfo(report, product);
|
|
1174
|
+
const [vcek, crl] = await Promise.all([
|
|
1175
|
+
fetchBytes(fetchImpl, info.vcekUrl, "VCEK", { sleep }),
|
|
1176
|
+
fetchBytes(fetchImpl, info.crlUrl, "CRL", { sleep })
|
|
1177
|
+
]);
|
|
1178
|
+
return wasm.verifyReport(
|
|
1179
|
+
report,
|
|
1180
|
+
product,
|
|
1181
|
+
vcek,
|
|
1182
|
+
crl,
|
|
1183
|
+
nowSeconds,
|
|
1184
|
+
expectedMeasurements,
|
|
1185
|
+
expectedPolicy == null ? null : String(expectedPolicy),
|
|
1186
|
+
minTcb ? Uint8Array.from(minTcb) : null
|
|
1187
|
+
);
|
|
1188
|
+
}
|
|
1189
|
+
var cache = /* @__PURE__ */ new Map();
|
|
1190
|
+
var CRL_TTL_MS = 60 * 60 * 1e3;
|
|
1191
|
+
async function fetchBytes(fetchImpl, url, what, { attempts = 5, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) } = {}) {
|
|
1192
|
+
const hit = cache.get(url);
|
|
1193
|
+
if (hit && (what === "VCEK" || Date.now() - hit.at < CRL_TTL_MS)) return hit.bytes;
|
|
1194
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
1195
|
+
const response = await fetchImpl(url);
|
|
1196
|
+
if (response.ok) {
|
|
1197
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
1198
|
+
cache.set(url, { bytes, at: Date.now() });
|
|
1199
|
+
return bytes;
|
|
1200
|
+
}
|
|
1201
|
+
if ((response.status === 429 || response.status === 503) && attempt < attempts) {
|
|
1202
|
+
const retryAfter = Number(response.headers?.get?.("retry-after"));
|
|
1203
|
+
await sleep(Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 60) * 1e3 : 2e3 * 2 ** (attempt - 1));
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
throw new Error(`AMD KDS answered ${response.status} for the ${what}: ${url}`);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// ../attest-wasm/js/ratls.mjs
|
|
1211
|
+
var encoder = new TextEncoder();
|
|
1212
|
+
var decoder = new TextDecoder();
|
|
1213
|
+
var hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1214
|
+
var fromHex = (text) => Uint8Array.from(text.match(/../g) ?? [], (pair) => parseInt(pair, 16));
|
|
1215
|
+
function concat(a, b) {
|
|
1216
|
+
const out = new Uint8Array(a.length + b.length);
|
|
1217
|
+
out.set(a, 0);
|
|
1218
|
+
out.set(b, a.length);
|
|
1219
|
+
return out;
|
|
1220
|
+
}
|
|
1221
|
+
function websocketTransport(url, { WebSocketImpl = globalThis.WebSocket } = {}) {
|
|
1222
|
+
const socket = new WebSocketImpl(url);
|
|
1223
|
+
socket.binaryType = "arraybuffer";
|
|
1224
|
+
const opened = new Promise((resolve, reject) => {
|
|
1225
|
+
socket.addEventListener("open", () => resolve(), { once: true });
|
|
1226
|
+
socket.addEventListener("error", () => reject(new Error(`WebSocket to ${url} failed`)), { once: true });
|
|
1227
|
+
});
|
|
1228
|
+
return {
|
|
1229
|
+
opened,
|
|
1230
|
+
send: (bytes) => socket.send(bytes),
|
|
1231
|
+
onData: (callback) => socket.addEventListener("message", (event) => callback(new Uint8Array(event.data))),
|
|
1232
|
+
onClose: (callback) => socket.addEventListener("close", () => callback()),
|
|
1233
|
+
close: () => socket.close()
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
async function openAttestedChannel({ wasm, transport, expectedMeasurements, expectedPolicy, timeoutMs = 3e4 }) {
|
|
1237
|
+
const session = new wasm.RaTlsSession(expectedMeasurements, expectedPolicy == null ? null : String(expectedPolicy));
|
|
1238
|
+
let plaintext = new Uint8Array(0);
|
|
1239
|
+
let failure = null;
|
|
1240
|
+
let closed = false;
|
|
1241
|
+
const waiters = /* @__PURE__ */ new Set();
|
|
1242
|
+
const wake = () => {
|
|
1243
|
+
for (const waiter of waiters) waiter();
|
|
1244
|
+
};
|
|
1245
|
+
const flush = () => {
|
|
1246
|
+
const out = session.takeOutgoing();
|
|
1247
|
+
if (out.length > 0) transport.send(out);
|
|
1248
|
+
};
|
|
1249
|
+
transport.onData((bytes) => {
|
|
1250
|
+
try {
|
|
1251
|
+
session.pushIncoming(bytes);
|
|
1252
|
+
flush();
|
|
1253
|
+
const more = session.isHandshaking() ? new Uint8Array(0) : session.takePlaintext();
|
|
1254
|
+
if (more.length > 0) plaintext = concat(plaintext, more);
|
|
1255
|
+
} catch (error) {
|
|
1256
|
+
failure = error instanceof Error ? error : new Error(String(error));
|
|
1257
|
+
transport.close();
|
|
1258
|
+
}
|
|
1259
|
+
wake();
|
|
1260
|
+
});
|
|
1261
|
+
transport.onClose(() => {
|
|
1262
|
+
closed = true;
|
|
1263
|
+
wake();
|
|
1264
|
+
});
|
|
1265
|
+
const until = (predicate, what) => new Promise((resolve, reject) => {
|
|
1266
|
+
const deadline = setTimeout(() => {
|
|
1267
|
+
waiters.delete(check);
|
|
1268
|
+
reject(new Error(`timed out waiting for ${what}`));
|
|
1269
|
+
}, timeoutMs);
|
|
1270
|
+
const check = () => {
|
|
1271
|
+
if (failure) {
|
|
1272
|
+
clearTimeout(deadline);
|
|
1273
|
+
waiters.delete(check);
|
|
1274
|
+
reject(failure);
|
|
1275
|
+
} else if (predicate()) {
|
|
1276
|
+
clearTimeout(deadline);
|
|
1277
|
+
waiters.delete(check);
|
|
1278
|
+
resolve();
|
|
1279
|
+
} else if (closed) {
|
|
1280
|
+
clearTimeout(deadline);
|
|
1281
|
+
waiters.delete(check);
|
|
1282
|
+
reject(new Error(`the connection closed while waiting for ${what}`));
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
waiters.add(check);
|
|
1286
|
+
check();
|
|
1287
|
+
});
|
|
1288
|
+
if (transport.opened) await transport.opened;
|
|
1289
|
+
flush();
|
|
1290
|
+
await until(() => !session.isHandshaking(), "the attested TLS handshake");
|
|
1291
|
+
const request = async (method, path, { headers = {}, body } = {}) => {
|
|
1292
|
+
const payload = body == null ? new Uint8Array(0) : typeof body === "string" ? encoder.encode(body) : body;
|
|
1293
|
+
const lines = [`${method} ${path} HTTP/1.1`, "host: attestation.aleph.invalid", `content-length: ${payload.length}`];
|
|
1294
|
+
for (const [name, value] of Object.entries(headers)) lines.push(`${name}: ${value}`);
|
|
1295
|
+
plaintext = new Uint8Array(0);
|
|
1296
|
+
session.writePlaintext(concat(encoder.encode(`${lines.join("\r\n")}\r
|
|
1297
|
+
\r
|
|
1298
|
+
`), payload));
|
|
1299
|
+
flush();
|
|
1300
|
+
let response = null;
|
|
1301
|
+
await until(() => (response = parseResponse(plaintext)) !== null, `the answer to ${method} ${path}`);
|
|
1302
|
+
plaintext = new Uint8Array(0);
|
|
1303
|
+
return response;
|
|
1304
|
+
};
|
|
1305
|
+
return {
|
|
1306
|
+
session,
|
|
1307
|
+
request,
|
|
1308
|
+
certReport: session.certReport(),
|
|
1309
|
+
servedPublicKey: session.servedPublicKey(),
|
|
1310
|
+
close: () => {
|
|
1311
|
+
session.close();
|
|
1312
|
+
try {
|
|
1313
|
+
flush();
|
|
1314
|
+
} catch {
|
|
1315
|
+
}
|
|
1316
|
+
transport.close();
|
|
1317
|
+
}
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
function parseResponse(bytes) {
|
|
1321
|
+
const text = decoder.decode(bytes);
|
|
1322
|
+
const end = text.indexOf("\r\n\r\n");
|
|
1323
|
+
if (end < 0) return null;
|
|
1324
|
+
const [statusLine, ...headerLines] = text.slice(0, end).split("\r\n");
|
|
1325
|
+
const status = Number(statusLine.split(" ")[1]);
|
|
1326
|
+
const headers = {};
|
|
1327
|
+
for (const line of headerLines) {
|
|
1328
|
+
const colon = line.indexOf(":");
|
|
1329
|
+
if (colon > 0) headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
|
|
1330
|
+
}
|
|
1331
|
+
const head = encoder.encode(text.slice(0, end + 4)).length;
|
|
1332
|
+
const rest = bytes.slice(head);
|
|
1333
|
+
if (headers["transfer-encoding"]?.toLowerCase() === "chunked") {
|
|
1334
|
+
const chunks = [];
|
|
1335
|
+
let offset = 0;
|
|
1336
|
+
for (; ; ) {
|
|
1337
|
+
const lineEnd = decoder.decode(rest.slice(offset)).indexOf("\r\n");
|
|
1338
|
+
if (lineEnd < 0) return null;
|
|
1339
|
+
const size = parseInt(decoder.decode(rest.slice(offset, offset + lineEnd)), 16);
|
|
1340
|
+
offset += lineEnd + 2;
|
|
1341
|
+
if (size === 0) break;
|
|
1342
|
+
if (rest.length < offset + size + 2) return null;
|
|
1343
|
+
chunks.push(rest.slice(offset, offset + size));
|
|
1344
|
+
offset += size + 2;
|
|
1345
|
+
}
|
|
1346
|
+
return { status, headers, body: chunks.reduce(concat, new Uint8Array(0)) };
|
|
1347
|
+
}
|
|
1348
|
+
const length = Number(headers["content-length"] ?? 0);
|
|
1349
|
+
if (rest.length < length) return null;
|
|
1350
|
+
return { status, headers, body: rest.slice(0, length) };
|
|
1351
|
+
}
|
|
1352
|
+
async function attestGuest({
|
|
1353
|
+
wasm,
|
|
1354
|
+
transport,
|
|
1355
|
+
product,
|
|
1356
|
+
expectedMeasurements,
|
|
1357
|
+
expectedPolicy,
|
|
1358
|
+
minTcb,
|
|
1359
|
+
fetch: fetch2,
|
|
1360
|
+
verify = verifyAttestation,
|
|
1361
|
+
nonce = globalThis.crypto.getRandomValues(new Uint8Array(32)),
|
|
1362
|
+
timeoutMs
|
|
1363
|
+
}) {
|
|
1364
|
+
const channel = await openAttestedChannel({ wasm, transport, expectedMeasurements, expectedPolicy, timeoutMs });
|
|
1365
|
+
try {
|
|
1366
|
+
const check = (report) => verify({ wasm, report, product, expectedMeasurements, expectedPolicy, minTcb, fetch: fetch2 });
|
|
1367
|
+
const certVerified = await check(channel.certReport);
|
|
1368
|
+
const response = await channel.request("GET", `/.well-known/attestation?nonce=${hex(nonce)}`);
|
|
1369
|
+
if (response.status !== 200) throw new Error(`the guest answered ${response.status} to the freshness challenge`);
|
|
1370
|
+
const dto = JSON.parse(decoder.decode(response.body));
|
|
1371
|
+
if (dto.tee_type !== "sev-snp") throw new Error(`the fresh report is ${dto.tee_type}, not sev-snp`);
|
|
1372
|
+
const freshReport = fromHex(String(dto.data ?? ""));
|
|
1373
|
+
const freshVerified = await check(freshReport);
|
|
1374
|
+
wasm.verifyFreshBinding(freshReport, channel.servedPublicKey, nonce);
|
|
1375
|
+
return { channel, servedPublicKey: channel.servedPublicKey, certVerified, freshVerified };
|
|
1376
|
+
} catch (error) {
|
|
1377
|
+
channel.close();
|
|
1378
|
+
throw error;
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
function canonicalSecretsJson(secrets) {
|
|
1382
|
+
const sorted = {};
|
|
1383
|
+
for (const key of Object.keys(secrets).sort()) sorted[key] = String(secrets[key]);
|
|
1384
|
+
return JSON.stringify(sorted);
|
|
1385
|
+
}
|
|
1386
|
+
async function injectSecrets({ wasm, attested, secrets, sign }) {
|
|
1387
|
+
const canonical = canonicalSecretsJson(secrets);
|
|
1388
|
+
const payload = wasm.injectSecretPayload(attested.servedPublicKey, canonical);
|
|
1389
|
+
const signature = await sign(payload);
|
|
1390
|
+
const response = await attested.channel.request("POST", "/confidential/inject-secret", {
|
|
1391
|
+
headers: { "content-type": "application/json" },
|
|
1392
|
+
body: JSON.stringify({ secrets: JSON.parse(canonical), signature })
|
|
1393
|
+
});
|
|
1394
|
+
const text = decoder.decode(response.body);
|
|
1395
|
+
if (response.status < 200 || response.status >= 300) {
|
|
1396
|
+
throw new Error(`the guest refused the secrets (${response.status}): ${text}`);
|
|
1397
|
+
}
|
|
1398
|
+
return JSON.parse(text);
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
// ../attest-wasm/js/runtime.mjs
|
|
1402
|
+
var VM_IMAGES_ADDRESS = "0xFba561a84A537fCaa567bb7A2257e7142701ae2A";
|
|
1403
|
+
var DEFAULT_SNP_POLICY = 196608;
|
|
1404
|
+
var DEFAULT_API = "https://api2.aleph.im";
|
|
1405
|
+
var DEFAULT_IPFS = "https://ipfs.aleph.im/ipfs";
|
|
1406
|
+
var hex2 = (bytes) => Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1407
|
+
async function resolveInstanceRuntime({ apiHost = DEFAULT_API, name, fetch: fetchImpl = globalThis.fetch } = {}) {
|
|
1408
|
+
const response = await fetchImpl(`${apiHost}/api/v0/aggregates/${VM_IMAGES_ADDRESS}.json?keys=vm-images`);
|
|
1409
|
+
if (!response.ok) throw new Error(`vm-images aggregate answered ${response.status}`);
|
|
1410
|
+
const images = (await response.json()).data?.["vm-images"] ?? {};
|
|
1411
|
+
const key = name ?? images.defaults?.instance_runtime;
|
|
1412
|
+
const entry = images.instance_runtimes?.[key];
|
|
1413
|
+
if (!entry?.hash) throw new Error(`no instance runtime ${JSON.stringify(key)} in vm-images`);
|
|
1414
|
+
return { name: key, itemHash: entry.hash, deprecated: entry.deprecated === true };
|
|
1415
|
+
}
|
|
1416
|
+
async function fetchStoreBytes({ apiHost = DEFAULT_API, ipfsGateway = DEFAULT_IPFS, itemHash, fetch: fetchImpl = globalThis.fetch }) {
|
|
1417
|
+
const message = await (await fetchImpl(`${apiHost}/api/v0/messages/${itemHash}`)).json();
|
|
1418
|
+
const content = message.message?.content ?? message.content;
|
|
1419
|
+
if ((message.message?.type ?? message.type) !== "STORE" || !content?.item_hash) throw new Error(`${itemHash} is not a STORE message`);
|
|
1420
|
+
const url = content.item_type === "ipfs" ? `${ipfsGateway}/${content.item_hash}` : `${apiHost}/api/v0/storage/raw/${content.item_hash}`;
|
|
1421
|
+
const response = await fetchImpl(url);
|
|
1422
|
+
if (!response.ok) throw new Error(`fetching ${itemHash} answered ${response.status}`);
|
|
1423
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
1424
|
+
}
|
|
1425
|
+
function untar(bytes) {
|
|
1426
|
+
const files = /* @__PURE__ */ new Map();
|
|
1427
|
+
const decoder2 = new TextDecoder();
|
|
1428
|
+
for (let offset = 0; offset + 512 <= bytes.length; ) {
|
|
1429
|
+
const header = bytes.subarray(offset, offset + 512);
|
|
1430
|
+
if (header.every((byte) => byte === 0)) break;
|
|
1431
|
+
const field = (start2, length) => decoder2.decode(header.subarray(start2, start2 + length)).replace(/\0.*$/s, "").trim();
|
|
1432
|
+
const prefix = field(345, 155);
|
|
1433
|
+
const name = (prefix ? `${prefix}/` : "") + field(0, 100);
|
|
1434
|
+
const size = parseInt(field(124, 12) || "0", 8);
|
|
1435
|
+
const type = field(156, 1);
|
|
1436
|
+
const start = offset + 512;
|
|
1437
|
+
if (type === "" || type === "0") files.set(name.replace(/^\.\//, ""), bytes.subarray(start, start + size));
|
|
1438
|
+
offset = start + Math.ceil(size / 512) * 512;
|
|
1439
|
+
}
|
|
1440
|
+
return files;
|
|
1441
|
+
}
|
|
1442
|
+
async function gunzip(bytes) {
|
|
1443
|
+
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
|
|
1444
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
1445
|
+
}
|
|
1446
|
+
async function fetchInstanceRuntime({ itemHash, apiHost, ipfsGateway, fetch: fetch2 }) {
|
|
1447
|
+
const manifest = JSON.parse(new TextDecoder().decode(await fetchStoreBytes({ apiHost, ipfsGateway, itemHash, fetch: fetch2 })));
|
|
1448
|
+
if (manifest.format !== "aleph-instance-runtime" || manifest.platform !== "sev_snp") {
|
|
1449
|
+
throw new Error(`${itemHash} is not an SEV-SNP instance runtime manifest`);
|
|
1450
|
+
}
|
|
1451
|
+
const bundle = await fetchStoreBytes({ apiHost, ipfsGateway, itemHash: manifest.bundle.ref, fetch: fetch2 });
|
|
1452
|
+
const digest = hex2(await globalThis.crypto.subtle.digest("SHA-256", bundle));
|
|
1453
|
+
if (digest !== manifest.bundle.sha256 || manifest.bundle.size && bundle.length !== manifest.bundle.size) {
|
|
1454
|
+
throw new Error(`the runtime bundle does not match its manifest (sha256 ${digest})`);
|
|
1455
|
+
}
|
|
1456
|
+
const files = untar(await gunzip(bundle));
|
|
1457
|
+
const member = (role) => {
|
|
1458
|
+
const data = files.get(manifest.bundle.members[role]);
|
|
1459
|
+
if (!data) throw new Error(`the runtime bundle has no ${role} (${manifest.bundle.members[role]})`);
|
|
1460
|
+
return data;
|
|
1461
|
+
};
|
|
1462
|
+
return { itemHash, manifest, ovmf: member("ovmf"), kernel: member("kernel"), initrd: member("initrd") };
|
|
1463
|
+
}
|
|
1464
|
+
function trustedExecution({ wasm, runtime, owner, vcpus, policy = DEFAULT_SNP_POLICY }) {
|
|
1465
|
+
const cmdline = wasm.instanceCmdline(runtime.manifest.boot.cmdline_template, owner);
|
|
1466
|
+
const measurements = wasm.launchMeasurements(runtime.ovmf, runtime.kernel, runtime.initrd, cmdline, vcpus, runtime.manifest.boot.cpu_models);
|
|
1467
|
+
return {
|
|
1468
|
+
mode: "sev_snp",
|
|
1469
|
+
policy,
|
|
1470
|
+
runtime: runtime.itemHash,
|
|
1471
|
+
measurements: measurements.map(({ vcpuType, launch }) => ({ platform: "sev_snp", registers: { launch }, vcpu_type: vcpuType }))
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
// ../attest-wasm/js/instance.mjs
|
|
1476
|
+
var DEFAULT_API2 = "https://api2.aleph.im";
|
|
1477
|
+
async function confidentialTrustedExecution({
|
|
1478
|
+
wasm,
|
|
1479
|
+
owner,
|
|
1480
|
+
vcpus,
|
|
1481
|
+
policy = DEFAULT_SNP_POLICY,
|
|
1482
|
+
runtimeName,
|
|
1483
|
+
apiHost = DEFAULT_API2,
|
|
1484
|
+
fetch: fetch2,
|
|
1485
|
+
onProgress = () => {
|
|
1486
|
+
}
|
|
1487
|
+
}) {
|
|
1488
|
+
onProgress({ phase: "runtime", detail: "Resolving the SEV-SNP runtime" });
|
|
1489
|
+
const resolved = await resolveInstanceRuntime({ apiHost, name: runtimeName, fetch: fetch2 });
|
|
1490
|
+
onProgress({ phase: "bundle", detail: `Downloading runtime ${resolved.name}` });
|
|
1491
|
+
const runtime = await fetchInstanceRuntime({ itemHash: resolved.itemHash, apiHost, fetch: fetch2 });
|
|
1492
|
+
onProgress({ phase: "measure", detail: "Computing the launch measurements" });
|
|
1493
|
+
return trustedExecution({ wasm, runtime, owner, vcpus, policy });
|
|
1494
|
+
}
|
|
1495
|
+
function pinsOf(tee) {
|
|
1496
|
+
const expectedMeasurements = (tee?.measurements ?? []).filter((entry) => entry?.platform === "sev_snp" && typeof entry?.registers?.launch === "string").map((entry) => entry.registers.launch);
|
|
1497
|
+
if (expectedMeasurements.length === 0) throw new Error("the trusted_execution block pins no SEV-SNP measurements");
|
|
1498
|
+
return { expectedMeasurements, expectedPolicy: tee.policy };
|
|
1499
|
+
}
|
|
1500
|
+
var NOT_YET = /closed|timed out|Bad Gateway|WebSocket to .* failed|ECONNREFUSED|ECONNRESET/i;
|
|
1501
|
+
var VERDICT = /rejected|bind|measurement|policy|floor|KDS answered 4|signature|refused the secrets/i;
|
|
1502
|
+
async function unlockInstance({
|
|
1503
|
+
wasm,
|
|
1504
|
+
relayUrl,
|
|
1505
|
+
crnHash,
|
|
1506
|
+
instanceItemHash,
|
|
1507
|
+
trustedExecution: tee,
|
|
1508
|
+
passphrase,
|
|
1509
|
+
secrets = {},
|
|
1510
|
+
sign,
|
|
1511
|
+
attempts = 12,
|
|
1512
|
+
delayMs = 1e4,
|
|
1513
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
1514
|
+
transport = (url) => websocketTransport(url),
|
|
1515
|
+
verify,
|
|
1516
|
+
fetch: fetch2,
|
|
1517
|
+
onProgress = () => {
|
|
1518
|
+
}
|
|
1519
|
+
}) {
|
|
1520
|
+
if (!passphrase) throw new Error("unlocking needs the passphrase of the encrypted rootfs");
|
|
1521
|
+
if ("luks_passphrase" in secrets) throw new Error("pass the passphrase as passphrase, not in secrets");
|
|
1522
|
+
const { expectedMeasurements, expectedPolicy } = pinsOf(tee);
|
|
1523
|
+
const url = `${relayUrl}${relayUrl.includes("?") ? "&" : "?"}crn=${crnHash}&vm=${instanceItemHash}`;
|
|
1524
|
+
let attested = null;
|
|
1525
|
+
for (let attempt = 1; !attested; attempt += 1) {
|
|
1526
|
+
onProgress({ phase: "attest", detail: `Attesting the guest (${attempt}/${attempts})` });
|
|
1527
|
+
try {
|
|
1528
|
+
attested = await attestGuest({
|
|
1529
|
+
wasm,
|
|
1530
|
+
transport: transport(url),
|
|
1531
|
+
expectedMeasurements,
|
|
1532
|
+
expectedPolicy,
|
|
1533
|
+
fetch: fetch2,
|
|
1534
|
+
...verify ? { verify } : {}
|
|
1535
|
+
});
|
|
1536
|
+
} catch (error) {
|
|
1537
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1538
|
+
if (VERDICT.test(message) || !NOT_YET.test(message) || attempt >= attempts) throw error;
|
|
1539
|
+
onProgress({ phase: "wait", detail: `The guest is not answering yet: ${message}` });
|
|
1540
|
+
await sleep(delayMs);
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
try {
|
|
1544
|
+
onProgress({ phase: "unlock", detail: "Sign the unlock in your wallet" });
|
|
1545
|
+
const injected = await injectSecrets({ wasm, attested, secrets: { ...secrets, luks_passphrase: passphrase }, sign });
|
|
1546
|
+
return {
|
|
1547
|
+
injected: injected.injected ?? [],
|
|
1548
|
+
measurement: attested.freshVerified.measurement,
|
|
1549
|
+
policy: attested.freshVerified.policy,
|
|
1550
|
+
launchTcb: attested.freshVerified.launchTcb
|
|
1551
|
+
};
|
|
1552
|
+
} finally {
|
|
1553
|
+
attested.channel.close();
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1123
1556
|
export {
|
|
1124
1557
|
BROWSER_PACKAGE_PLAN,
|
|
1125
1558
|
DEFAULT_2N6_API_HOST,
|
|
@@ -1136,7 +1569,9 @@ export {
|
|
|
1136
1569
|
approvePrepaidBudget,
|
|
1137
1570
|
broadcastAlephMessage,
|
|
1138
1571
|
broadcastInstanceMessage,
|
|
1572
|
+
confidentialTrustedExecution,
|
|
1139
1573
|
configureOrbitdbRelaySetup,
|
|
1574
|
+
connectWallet,
|
|
1140
1575
|
consumeDeploymentReservation,
|
|
1141
1576
|
createAlephBrowserClient,
|
|
1142
1577
|
depositPrepaidBudget,
|
|
@@ -1155,6 +1590,7 @@ export {
|
|
|
1155
1590
|
fetchWithTimeout,
|
|
1156
1591
|
filterReachableCrns,
|
|
1157
1592
|
formatBudgetUnits,
|
|
1593
|
+
getEthereumProvider,
|
|
1158
1594
|
inspectDeploymentResult,
|
|
1159
1595
|
loadPrepaidReservation,
|
|
1160
1596
|
loadPrepaidVaultSnapshot,
|
|
@@ -1166,12 +1602,15 @@ export {
|
|
|
1166
1602
|
parseInstancePricing,
|
|
1167
1603
|
paymentChainFromChainId,
|
|
1168
1604
|
personalSign,
|
|
1605
|
+
pinsOf,
|
|
1169
1606
|
probeCrnAvailability,
|
|
1170
1607
|
refundExpiredReservation,
|
|
1171
1608
|
reserveDeploymentBudget,
|
|
1172
1609
|
resolveRootfsReference,
|
|
1173
1610
|
sendTransaction,
|
|
1611
|
+
unlockInstance,
|
|
1174
1612
|
validateRootfsManifest,
|
|
1175
1613
|
verifyRootfsExists,
|
|
1176
|
-
waitForDeploymentResult
|
|
1614
|
+
waitForDeploymentResult,
|
|
1615
|
+
watchWallet
|
|
1177
1616
|
};
|