@lumeweb/sia-testing 0.0.0-stage → 0.0.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.
Files changed (90) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +202 -2
  3. package/dist/esm/client.d.ts +8 -0
  4. package/dist/esm/client.js +6 -0
  5. package/dist/esm/http.d.ts +3 -0
  6. package/dist/esm/http.js +3 -0
  7. package/dist/esm/mock.d.ts +8 -0
  8. package/dist/esm/mock.js +7 -0
  9. package/dist/esm/model/index.js +509 -0
  10. package/dist/esm/model/state.js +188 -0
  11. package/dist/esm/msw.d.ts +2 -0
  12. package/dist/esm/msw.js +3 -0
  13. package/dist/esm/node.d.ts +4 -0
  14. package/dist/esm/node.js +4 -0
  15. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_md.js +169 -0
  16. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/_u64.js +12 -0
  17. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/sha2.js +199 -0
  18. package/dist/esm/node_modules/.pnpm/@noble_hashes@2.4.0/node_modules/@noble/hashes/utils.js +220 -0
  19. package/dist/esm/sdk/abort.js +23 -0
  20. package/dist/esm/sdk/control.js +129 -0
  21. package/dist/esm/sdk/index.js +454 -0
  22. package/dist/esm/sdk/link.js +55 -0
  23. package/dist/esm/sdk/object.js +24 -0
  24. package/dist/esm/sdk/payload-store.d.ts +9 -0
  25. package/dist/esm/sdk/payload-store.js +67 -0
  26. package/dist/esm/sdk/state.js +74 -0
  27. package/dist/esm/testing/application-client.d.ts +8 -0
  28. package/dist/esm/testing/application-client.js +295 -0
  29. package/dist/esm/testing/application-metadata.js +17 -0
  30. package/dist/esm/testing/application-transport.js +363 -0
  31. package/dist/esm/testing/auth-client.d.ts +20 -0
  32. package/dist/esm/testing/auth-client.js +63 -0
  33. package/dist/esm/testing/authentication.js +48 -0
  34. package/dist/esm/testing/byte-view.js +28 -0
  35. package/dist/esm/testing/chunked-files.d.ts +12 -0
  36. package/dist/esm/testing/chunked-files.js +50 -0
  37. package/dist/esm/testing/client.d.ts +8 -0
  38. package/dist/esm/testing/client.js +105 -0
  39. package/dist/esm/testing/controls.d.ts +44 -0
  40. package/dist/esm/testing/controls.js +255 -0
  41. package/dist/esm/testing/diagnostics.js +55 -0
  42. package/dist/esm/testing/files.d.ts +9 -0
  43. package/dist/esm/testing/files.js +86 -0
  44. package/dist/esm/testing/http-body.js +33 -0
  45. package/dist/esm/testing/http.d.ts +14 -0
  46. package/dist/esm/testing/http.js +181 -0
  47. package/dist/esm/testing/live/agent.d.ts +1 -0
  48. package/dist/esm/testing/live/agent.js +211 -0
  49. package/dist/esm/testing/live/approval.js +42 -0
  50. package/dist/esm/testing/live/cleanup.js +74 -0
  51. package/dist/esm/testing/live/journal.js +180 -0
  52. package/dist/esm/testing/live/lease.js +56 -0
  53. package/dist/esm/testing/live/private-files.js +50 -0
  54. package/dist/esm/testing/live/process.js +208 -0
  55. package/dist/esm/testing/live/profile.js +214 -0
  56. package/dist/esm/testing/live/recovery.js +164 -0
  57. package/dist/esm/testing/live/resource-limits.js +9 -0
  58. package/dist/esm/testing/live/run.js +390 -0
  59. package/dist/esm/testing/live/session.js +93 -0
  60. package/dist/esm/testing/live/types.d.ts +8 -0
  61. package/dist/esm/testing/mock.d.ts +8 -0
  62. package/dist/esm/testing/mock.js +1364 -0
  63. package/dist/esm/testing/msw.d.ts +21 -0
  64. package/dist/esm/testing/msw.js +61 -0
  65. package/dist/esm/testing/mutations.d.ts +59 -0
  66. package/dist/esm/testing/mutations.js +58 -0
  67. package/dist/esm/testing/node-payload-store.js +353 -0
  68. package/dist/esm/testing/node.d.ts +40 -0
  69. package/dist/esm/testing/node.js +148 -0
  70. package/dist/esm/testing/owner-client.d.ts +9 -0
  71. package/dist/esm/testing/owner-client.js +101 -0
  72. package/dist/esm/testing/owner-shares.js +80 -0
  73. package/dist/esm/testing/packed.d.ts +46 -0
  74. package/dist/esm/testing/packed.js +326 -0
  75. package/dist/esm/testing/reader-lifetime.js +40 -0
  76. package/dist/esm/testing/reply-loss.js +14 -0
  77. package/dist/esm/testing/runtime.d.ts +7 -0
  78. package/dist/esm/testing/runtime.js +13 -0
  79. package/dist/esm/testing/sdk-upload.d.ts +45 -0
  80. package/dist/esm/testing/sdk-upload.js +198 -0
  81. package/dist/esm/testing/streaming-source.js +72 -0
  82. package/dist/esm/testing/transport.d.ts +22 -0
  83. package/dist/esm/testing/transport.js +238 -0
  84. package/dist/esm/testing/types.d.ts +276 -0
  85. package/dist/esm/vitest.d.ts +23 -0
  86. package/dist/esm/vitest.js +34 -0
  87. package/docs/live-auth.md +154 -0
  88. package/docs/live-runs.md +188 -0
  89. package/docs/mock-contracts.md +647 -0
  90. package/package.json +91 -3
@@ -0,0 +1,181 @@
1
+ import { endpointShutdown } from "./diagnostics.js";
2
+ import { isLostReply } from "./reply-loss.js";
3
+ import { mockRuntime } from "./runtime.js";
4
+ import { createMockEndpoint } from "./transport.js";
5
+ import { incomingBody } from "./http-body.js";
6
+ import { createMockReader } from "./client.js";
7
+ import { Readable } from "node:stream";
8
+ import { createServer } from "node:http";
9
+ import { pipeline } from "node:stream/promises";
10
+
11
+ //#region src/testing/http.ts
12
+ /** Hosts scoped mock ports on a loopback listener with owned request cancellation. */
13
+ async function startMockServer(mock, options = {}) {
14
+ if (options.host !== void 0 && options.host !== "127.0.0.1" && options.host !== "::1") throw Object.assign(/* @__PURE__ */ new Error("Mock listener host must be loopback"), { code: "invalid-input" });
15
+ mockRuntime(mock).assertTransport();
16
+ const calls = /* @__PURE__ */ new Set();
17
+ const sockets = /* @__PURE__ */ new Map();
18
+ let stopping = false;
19
+ function socketState(socket) {
20
+ let state = sockets.get(socket);
21
+ if (!state) {
22
+ state = {
23
+ bodies: /* @__PURE__ */ new Map(),
24
+ replies: /* @__PURE__ */ new Set()
25
+ };
26
+ sockets.set(socket, state);
27
+ }
28
+ return state;
29
+ }
30
+ function releaseSocket(socket, state) {
31
+ if (!state.bodies.size && !state.replies.size && sockets.get(socket) === state) sockets.delete(socket);
32
+ }
33
+ function ownBody(incoming, outgoing) {
34
+ const socket = incoming.socket;
35
+ const state = socketState(socket);
36
+ state.bodies.set(incoming, outgoing);
37
+ let released = false;
38
+ const releaseBody = () => {
39
+ if (released) return;
40
+ released = true;
41
+ state.bodies.delete(incoming);
42
+ incoming.removeListener("end", releaseBody);
43
+ incoming.removeListener("close", releaseBody);
44
+ releaseSocket(socket, state);
45
+ };
46
+ incoming.once("end", releaseBody);
47
+ incoming.once("close", releaseBody);
48
+ return releaseBody;
49
+ }
50
+ function cancelBodies(state) {
51
+ if (!stopping) return;
52
+ for (const [incoming, outgoing] of state.bodies) {
53
+ if (incoming.complete || incoming.destroyed) continue;
54
+ const ownReply = state.replies.has(outgoing);
55
+ if (!(state.replies.size > (ownReply ? 1 : 0) || ownReply && outgoing.headersSent)) incoming.destroy();
56
+ }
57
+ }
58
+ const dispatch = (request) => stopping ? Promise.resolve(Response.json({ code: "closed" }, { status: 410 })) : configured.dispatch(request);
59
+ async function respond(incoming, outgoing, releaseBody) {
60
+ const origin = incoming.headers.origin;
61
+ if (origin) {
62
+ if (!(options.allowedOrigins?.includes(origin) ?? [
63
+ "127.0.0.1",
64
+ "[::1]",
65
+ "localhost"
66
+ ].includes(new URL(origin).hostname))) {
67
+ outgoing.writeHead(403).end();
68
+ return;
69
+ }
70
+ outgoing.setHeader("access-control-allow-origin", origin);
71
+ outgoing.setHeader("vary", "Origin");
72
+ }
73
+ outgoing.setHeader("access-control-allow-headers", "authorization, content-type");
74
+ outgoing.setHeader("access-control-allow-methods", "GET,POST,OPTIONS");
75
+ if (incoming.method === "OPTIONS") {
76
+ outgoing.writeHead(204).end();
77
+ return;
78
+ }
79
+ const abort = new AbortController();
80
+ const cancel = () => abort.abort();
81
+ calls.add(abort);
82
+ if (stopping) abort.abort(endpointShutdown());
83
+ outgoing.once("close", cancel);
84
+ try {
85
+ const pathname = new URL(incoming.url ?? "/", "http://localhost").pathname;
86
+ const root = new URL(configured.endpoint.url).pathname;
87
+ const parts = pathname.startsWith(root) ? pathname.substring(root.length).split("/") : [];
88
+ const rawUpload = parts.length === 2 && /^[a-f0-9-]{36}$/.test(parts[0]) && parts[1] === "app-upload-body";
89
+ const chunks = [];
90
+ let size = 0;
91
+ if (!rawUpload) for await (const value of incoming) {
92
+ size += value.length;
93
+ if (size > 16384) {
94
+ outgoing.writeHead(413).end();
95
+ return;
96
+ }
97
+ chunks.push(value);
98
+ }
99
+ const request = new Request(`http://${incoming.headers.host}${incoming.url}`, {
100
+ ...["GET", "HEAD"].includes(incoming.method ?? "GET") ? {} : rawUpload ? {
101
+ body: incomingBody(incoming, abort.signal),
102
+ duplex: "half"
103
+ } : { body: Buffer.concat(chunks) },
104
+ headers: Object.entries(incoming.headers).flatMap(([key, value]) => value === void 0 ? [] : [[key, Array.isArray(value) ? value.join(",") : value]]),
105
+ method: incoming.method ?? "GET",
106
+ signal: abort.signal
107
+ });
108
+ releaseBody();
109
+ let response;
110
+ try {
111
+ response = await dispatch(request);
112
+ } finally {
113
+ if (rawUpload && !incoming.complete && !incoming.destroyed) ownBody(incoming, outgoing);
114
+ }
115
+ outgoing.statusCode = response.status;
116
+ response.headers.forEach((value, key) => outgoing.setHeader(key, value));
117
+ outgoing.flushHeaders();
118
+ if (response.body) await pipeline(Readable.fromWeb(response.body), outgoing);
119
+ else outgoing.end();
120
+ } finally {
121
+ calls.delete(abort);
122
+ outgoing.removeListener("close", cancel);
123
+ }
124
+ }
125
+ const server = createServer((incoming, outgoing) => {
126
+ const releaseBody = ownBody(incoming, outgoing);
127
+ const socket = incoming.socket;
128
+ const state = socketState(socket);
129
+ state.replies.add(outgoing);
130
+ const releaseReply = () => {
131
+ if (!state.replies.delete(outgoing)) return;
132
+ outgoing.removeListener("finish", releaseReply);
133
+ outgoing.removeListener("close", releaseReply);
134
+ cancelBodies(state);
135
+ releaseSocket(socket, state);
136
+ };
137
+ outgoing.once("finish", releaseReply);
138
+ outgoing.once("close", releaseReply);
139
+ respond(incoming, outgoing, releaseBody).catch((error) => {
140
+ if (isLostReply(error)) {
141
+ outgoing.writeHead(200, {
142
+ "content-length": "4",
143
+ "content-type": "application/json"
144
+ });
145
+ outgoing.write("n", () => outgoing.destroy());
146
+ } else if (outgoing.headersSent) outgoing.destroy();
147
+ else outgoing.writeHead(500).end();
148
+ });
149
+ cancelBodies(state);
150
+ });
151
+ await new Promise((resolve, reject) => {
152
+ server.once("error", reject);
153
+ server.listen(options.port ?? 0, options.host ?? "127.0.0.1", () => {
154
+ server.removeListener("error", reject);
155
+ resolve();
156
+ });
157
+ });
158
+ const address = server.address();
159
+ if (!address || typeof address === "string") throw new Error("Mock listener has no address");
160
+ const configured = createMockEndpoint(mock, `http://${address.family === "IPv6" ? `[${address.address}]` : address.address}:${address.port}/`);
161
+ let closing;
162
+ return {
163
+ ...configured.endpoint,
164
+ close() {
165
+ closing ??= (async () => {
166
+ stopping = true;
167
+ const errors = (await Promise.allSettled([configured.close(), new Promise((resolve, reject) => {
168
+ for (const call of calls) call.abort(endpointShutdown());
169
+ for (const state of sockets.values()) cancelBodies(state);
170
+ server.close((error) => error ? reject(error) : resolve());
171
+ server.closeIdleConnections();
172
+ })])).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
173
+ if (errors.length) throw new AggregateError(errors, "Mock listener cleanup failed");
174
+ })();
175
+ return closing;
176
+ }
177
+ };
178
+ }
179
+
180
+ //#endregion
181
+ export { startMockServer };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,211 @@
1
+ import { maximumMetadataBytes, maximumSealedObjectBytes } from "./resource-limits.js";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { createRequire } from "node:module";
5
+ import { setTimeout } from "node:timers/promises";
6
+ import { deserialize, serialize } from "node:v8";
7
+
8
+ //#region src/testing/live/agent.ts
9
+ /** The SDK agent receives authority over IPC and keeps native SDK work inside its owned process. */
10
+ let sdk;
11
+ let api;
12
+ let profile;
13
+ let busy = false;
14
+ let uploadedBytes = 0;
15
+ let observedShardBytes = 0;
16
+ let objects = 0;
17
+ let shares = 0;
18
+ process.on("message", (message) => {
19
+ if (!message || typeof message !== "object" || !("id" in message) || typeof message.id !== "string" || !("operation" in message) || typeof message.operation !== "string" || !("value" in message)) return;
20
+ const id = message.id;
21
+ if (busy || (message.operation === "authenticate" ? sdk !== void 0 : sdk === void 0)) {
22
+ process.send?.({
23
+ code: "invalid-input",
24
+ id,
25
+ type: "error"
26
+ });
27
+ return;
28
+ }
29
+ busy = true;
30
+ (message.operation === "authenticate" ? authenticate(id, message.value) : resource(id, message.operation, message.value)).finally(() => {
31
+ busy = false;
32
+ });
33
+ });
34
+ process.on("disconnect", () => process.exit(0));
35
+ process.send?.({ type: "ready" });
36
+ async function authenticate(id, document) {
37
+ let code = "sdk-version";
38
+ try {
39
+ const entry = createRequire(import.meta.url).resolve("@siafoundation/sia-storage");
40
+ if (JSON.parse(await readFile(join(dirname(dirname(entry)), "package.json"), "utf8")).version !== "0.2.0") throw new Error("Unexpected SDK version");
41
+ api = await import("@siafoundation/sia-storage");
42
+ await api.initSia();
43
+ code = "authentication";
44
+ profile = document;
45
+ const builder = new api.Builder(document.apiBaseUrl, {
46
+ description: document.app.description,
47
+ id: Buffer.from(document.app.id, "hex"),
48
+ name: document.app.name,
49
+ serviceUrl: document.app.serviceUrl
50
+ });
51
+ if (document.auth.kind === "app-key") {
52
+ sdk = await builder.connected(new api.AppKey(Buffer.from(document.auth.appKeyHex, "hex"))) ?? void 0;
53
+ if (!sdk) throw new Error("App key is not registered");
54
+ } else if (document.auth.kind === "register") {
55
+ await builder.requestConnection();
56
+ process.send?.({
57
+ name: "approval",
58
+ requestId: id,
59
+ type: "event",
60
+ value: builder.responseUrl()
61
+ });
62
+ await builder.waitForApproval();
63
+ sdk = await builder.register(document.auth.phrase);
64
+ } else sdk = await builder.connectPreAuthorized(api.PreAuthorizedKey.import(Buffer.from(document.auth.preauthorizedKeyHex, "hex")), document.auth.phrase);
65
+ code = "not-ready";
66
+ let account = await sdk.account();
67
+ while (!account.ready) {
68
+ if (account.app.id !== document.app.id) throw new Error("Account belongs to another app");
69
+ await setTimeout(200);
70
+ account = await sdk.account();
71
+ }
72
+ if (account.app.id !== document.app.id) throw new Error("Account belongs to another app");
73
+ process.send?.({
74
+ id,
75
+ type: "result",
76
+ value: {
77
+ accountKey: account.accountKey,
78
+ appId: account.app.id,
79
+ appKeyHex: sdk.appKey().export().toString("hex"),
80
+ maxPinnedData: account.maxPinnedData,
81
+ ready: account.ready,
82
+ remainingStorage: account.remainingStorage
83
+ }
84
+ });
85
+ } catch {
86
+ process.send?.({
87
+ code,
88
+ id,
89
+ type: "error"
90
+ });
91
+ }
92
+ }
93
+ function expiry(value) {
94
+ if (typeof value !== "string") throw new Error("Invalid expiry");
95
+ const date = new Date(value);
96
+ if (!Number.isFinite(date.getTime()) || date.getTime() <= Date.now()) throw new Error("Invalid expiry");
97
+ return date;
98
+ }
99
+ function identifier(value) {
100
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) throw new Error("Invalid object ID");
101
+ return value;
102
+ }
103
+ function notFound(error) {
104
+ return error instanceof Error && error.message.startsWith("app error: Api(404, ");
105
+ }
106
+ async function resource(id, operation, value) {
107
+ let code = "invalid-input";
108
+ try {
109
+ if (!sdk || !api || !profile || !value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid resource request");
110
+ const input = value;
111
+ let result = null;
112
+ code = "resource-error";
113
+ if (operation === "upload") {
114
+ code = "invalid-input";
115
+ if (!(input.bytes instanceof Uint8Array) || !(input.metadata instanceof Uint8Array) || input.metadata.byteLength > 16384) throw new Error("Invalid upload snapshot");
116
+ if (objects >= profile.limits.maxObjects || uploadedBytes + input.bytes.byteLength > profile.limits.maxLogicalUploadBytes) {
117
+ code = "quota";
118
+ throw new Error("Upload budget exceeded");
119
+ }
120
+ code = "resource-error";
121
+ objects++;
122
+ uploadedBytes += input.bytes.byteLength;
123
+ const initial = new api.PinnedObject();
124
+ initial.updateMetadata(Buffer.from(input.metadata));
125
+ const uploaded = input.bytes.byteLength === 0 ? initial : await sdk.upload(initial, new Blob([Buffer.from(input.bytes)]).stream(), {
126
+ ...profile.encoding,
127
+ onShardUploaded(progress) {
128
+ observedShardBytes += progress.shardSize;
129
+ if (!Number.isSafeInteger(observedShardBytes) || observedShardBytes > profile.limits.maxObservedShardBytes) {
130
+ process.send?.({
131
+ code: "quota",
132
+ id,
133
+ type: "error"
134
+ });
135
+ process.exit(1);
136
+ }
137
+ }
138
+ });
139
+ const sealed = serialize(uploaded.seal(sdk.appKey())).toString("base64");
140
+ if (sealed.length > 1048576) throw new Error("Invalid sealed object size");
141
+ result = {
142
+ objectId: uploaded.id(),
143
+ observedShardBytes,
144
+ sealed,
145
+ sizeBytes: Number(uploaded.size())
146
+ };
147
+ } else if (operation === "pin") {
148
+ const objectId = identifier(input.objectId);
149
+ if (typeof input.sealed !== "string" || input.sealed.length > 16 * 1024 * 1024) throw new Error("Invalid sealed object");
150
+ const sealed = deserialize(Buffer.from(input.sealed, "base64"));
151
+ const object = api.PinnedObject.open(sdk.appKey(), sealed);
152
+ if (object.id() !== objectId) throw new Error("Object ID mismatch");
153
+ await sdk.pinObject(object);
154
+ } else if (operation === "create-share") {
155
+ if (shares >= profile.limits.maxShares) {
156
+ code = "quota";
157
+ throw new Error("Share budget exceeded");
158
+ }
159
+ if (typeof input.description !== "string" || input.description.length > 4096) throw new Error("Invalid share description");
160
+ shares++;
161
+ const key = await sdk.createSharingKey(input.description, input.expiresAt === void 0 ? void 0 : expiry(input.expiresAt));
162
+ result = {
163
+ seedHex: key.seed().toString("hex"),
164
+ shareId: key.publicKey
165
+ };
166
+ } else if (operation === "attach" || operation === "detach" || operation === "revoke") {
167
+ const seedHex = input.seedHex;
168
+ if (typeof seedHex !== "string" || !/^[a-f0-9]{64}$/.test(seedHex)) throw new Error("Invalid sharing seed");
169
+ const key = api.SharingKey.fromSeed(Buffer.from(seedHex, "hex"));
170
+ if (key.publicKey !== input.shareId) throw new Error("Share ID mismatch");
171
+ if (operation === "attach") await sdk.shareObject(key, await sdk.object(identifier(input.objectId)));
172
+ else if (operation === "detach") await sdk.unshareObject(key, identifier(input.objectId));
173
+ else try {
174
+ await sdk.revokeSharingKey(key);
175
+ } catch (error) {
176
+ if (!notFound(error)) throw error;
177
+ }
178
+ } else if (operation === "delete") try {
179
+ await sdk.deleteObject(identifier(input.objectId));
180
+ } catch (error) {
181
+ if (!notFound(error)) throw error;
182
+ }
183
+ else if (operation === "inspect") try {
184
+ await sdk.object(identifier(input.objectId));
185
+ result = "present";
186
+ } catch (error) {
187
+ if (notFound(error)) result = "missing";
188
+ else throw error;
189
+ }
190
+ else if (operation === "signed-url") {
191
+ const object = await sdk.object(identifier(input.objectId));
192
+ result = { url: sdk.objectShareUrl(object, expiry(input.expiresAt)) };
193
+ } else {
194
+ code = "invalid-input";
195
+ throw new Error("Unknown resource operation");
196
+ }
197
+ process.send?.({
198
+ id,
199
+ type: "result",
200
+ value: result
201
+ });
202
+ } catch {
203
+ process.send?.({
204
+ code,
205
+ id,
206
+ type: "error"
207
+ });
208
+ }
209
+ }
210
+
211
+ //#endregion
@@ -0,0 +1,42 @@
1
+ import { profileDocument } from "./profile.js";
2
+
3
+ //#region src/testing/live/approval.ts
4
+ /** Approval sends a borrowed connect key only to the profile's expected connection endpoint. */
5
+ async function approveLiveConnection(profile, responseUrl, approve = true, signal) {
6
+ const document = profileDocument(profile);
7
+ if (document.auth.kind !== "register") throw failure("invalid-approval");
8
+ let target;
9
+ try {
10
+ target = new URL(responseUrl);
11
+ const expected = new URL("auth/connect/", document.apiBaseUrl);
12
+ const id = target.pathname.substring(expected.pathname.length);
13
+ if (target.origin !== expected.origin || !target.pathname.startsWith(expected.pathname) || !/^[a-zA-Z0-9_-]{1,128}$/.test(id) || target.username || target.password || target.search || target.hash) throw failure("invalid-approval");
14
+ } catch {
15
+ throw failure("invalid-approval");
16
+ }
17
+ try {
18
+ const response = await fetch(target, {
19
+ body: JSON.stringify({ approve }),
20
+ headers: {
21
+ "authorization": `Basic ${Buffer.from(":" + document.auth.connectKey).toString("base64")}`,
22
+ "content-type": "application/json"
23
+ },
24
+ method: "POST",
25
+ redirect: "error",
26
+ ...signal === void 0 ? {} : { signal }
27
+ });
28
+ await response.body?.cancel();
29
+ if (!response.ok) throw failure("approval-denied");
30
+ } catch {
31
+ throw failure("approval-denied");
32
+ }
33
+ }
34
+ function failure(code) {
35
+ return Object.assign(/* @__PURE__ */ new Error("Sia connection approval failed"), {
36
+ code,
37
+ phase: "authentication"
38
+ });
39
+ }
40
+
41
+ //#endregion
42
+ export { approveLiveConnection };
@@ -0,0 +1,74 @@
1
+ import { appKeyProfile, profileDocument } from "./profile.js";
2
+ import { closeLiveSession, openLiveSession, sessionProcess } from "./session.js";
3
+ import { randomUUID } from "node:crypto";
4
+
5
+ //#region src/testing/live/cleanup.ts
6
+ /** Cleanup reconnects with acknowledged authority and touches only recorded object IDs and sharing seeds. */
7
+ async function cleanupKnownResources(options) {
8
+ const objects = options.objects.filter((object) => !object.deleted);
9
+ const shares = options.shares.filter((share) => !share.revoked);
10
+ if (!objects.length && !shares.length) return;
11
+ const profile = appKeyProfile(options.profile, options.appKeyHex, true);
12
+ const signal = AbortSignal.timeout(profileDocument(profile).limits.deadlineMs);
13
+ const errors = [];
14
+ let session;
15
+ try {
16
+ for (const share of [...shares].reverse()) try {
17
+ await mutation("revoke", { shareId: share.shareId }, {
18
+ seedHex: share.seedHex,
19
+ shareId: share.shareId
20
+ });
21
+ } catch (error) {
22
+ errors.push(error);
23
+ await discardSession();
24
+ }
25
+ for (const object of [...objects].reverse()) try {
26
+ if (!object.pinned) await mutation("pin", { objectId: object.objectId }, {
27
+ objectId: object.objectId,
28
+ sealed: object.sealed
29
+ });
30
+ await mutation("delete", { objectId: object.objectId }, { objectId: object.objectId });
31
+ } catch (error) {
32
+ errors.push(error);
33
+ await discardSession();
34
+ }
35
+ } catch (error) {
36
+ errors.push(error);
37
+ }
38
+ try {
39
+ if (session) await closeLiveSession(session);
40
+ } catch (error) {
41
+ errors.push(error);
42
+ }
43
+ if (errors.length) throw new AggregateError(errors, "Owned resource cleanup failed");
44
+ async function discardSession() {
45
+ try {
46
+ if (session) await closeLiveSession(session);
47
+ } catch (error) {
48
+ errors.push(error);
49
+ }
50
+ session = void 0;
51
+ }
52
+ async function mutation(operation, input, payload) {
53
+ session ??= await openLiveSession(profile, {
54
+ ...options.agentModule ? { agentModule: options.agentModule } : {},
55
+ signal
56
+ });
57
+ const id = randomUUID();
58
+ await options.journal.append({
59
+ id,
60
+ input,
61
+ kind: "intent",
62
+ operation
63
+ }, { cleanup: true });
64
+ await sessionProcess(session).request(operation, payload, { signal });
65
+ await options.journal.append({
66
+ id,
67
+ kind: "ack",
68
+ result: null
69
+ }, { cleanup: true });
70
+ }
71
+ }
72
+
73
+ //#endregion
74
+ export { cleanupKnownResources };
@@ -0,0 +1,180 @@
1
+ import { privatePath, readPrivateHandle } from "./private-files.js";
2
+ import { constants } from "node:fs";
3
+ import { open } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+
6
+ //#region src/testing/live/journal.ts
7
+ /** Durable intent and acknowledgement records identify the exact resources a run may clean up. */
8
+ const creationBytes = 16 * 1024 * 1024;
9
+ const maximumBytes = 17825792;
10
+ async function createJournal(path, header, workspaceRoot) {
11
+ let file;
12
+ let directory;
13
+ try {
14
+ const actual = await privatePath(path, workspaceRoot);
15
+ directory = await open(dirname(actual), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
16
+ const parent = await directory.stat();
17
+ if (!parent.isDirectory() || parent.uid !== process.getuid() || (parent.mode & 63) !== 0) throw failure("journal-invalid");
18
+ file = await open(actual, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_APPEND | constants.O_NOFOLLOW, 384);
19
+ const journal = writer(file, actual, 0, 0);
20
+ await journal.append(header);
21
+ await directory.sync();
22
+ await directory.close();
23
+ directory = void 0;
24
+ file = void 0;
25
+ return journal;
26
+ } catch {
27
+ await file?.close().catch(() => void 0);
28
+ await directory?.close().catch(() => void 0);
29
+ throw failure("journal-invalid");
30
+ }
31
+ }
32
+ async function resumeJournal(path) {
33
+ let file;
34
+ try {
35
+ const actual = await privatePath(path);
36
+ file = await open(actual, constants.O_RDWR | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK);
37
+ const bytes = await readPrivateHandle(file, maximumBytes);
38
+ const snapshot = parse(bytes);
39
+ const end = bytes.lastIndexOf(10) + 1;
40
+ if (snapshot.truncated) {
41
+ await file.truncate(end);
42
+ await file.sync();
43
+ }
44
+ const journal = writer(file, actual, snapshot.records.length, end);
45
+ file = void 0;
46
+ return {
47
+ journal,
48
+ snapshot
49
+ };
50
+ } catch {
51
+ await file?.close().catch(() => void 0);
52
+ throw failure("journal-invalid");
53
+ }
54
+ }
55
+ function asError(value) {
56
+ return value instanceof Error ? value : failure("journal-error");
57
+ }
58
+ function failure(code) {
59
+ return Object.assign(/* @__PURE__ */ new Error("Sia private journal operation failed"), {
60
+ code,
61
+ phase: "journal"
62
+ });
63
+ }
64
+ function parse(bytes) {
65
+ const end = bytes.lastIndexOf(10) + 1;
66
+ const records = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, end)).split("\n").filter((_line, index, lines) => index !== lines.length - 1).map((line, sequence) => {
67
+ const value = JSON.parse(line);
68
+ validate(value, sequence);
69
+ return value;
70
+ });
71
+ if (!records.length) throw failure("journal-invalid");
72
+ return Object.freeze({
73
+ records: Object.freeze(records),
74
+ truncated: end !== bytes.length
75
+ });
76
+ }
77
+ function validate(value, sequence) {
78
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw failure("journal-invalid");
79
+ const record = value;
80
+ if (record.sequence !== sequence || typeof record.kind !== "string") throw failure("journal-invalid");
81
+ const id = (field) => typeof record[field] === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(record[field]);
82
+ if (sequence === 0) {
83
+ if (record.kind !== "header" || record.version !== 1 || !id("runId") || typeof record.apiBaseUrl !== "string" || typeof record.appId !== "string" || !/^[a-f0-9]{64}$/.test(record.appId)) throw failure("journal-invalid");
84
+ new URL(record.apiBaseUrl);
85
+ return;
86
+ }
87
+ if (record.kind === "auth" && typeof record.appKeyHex === "string" && /^[a-f0-9]{64}$/.test(record.appKeyHex)) return;
88
+ if (record.kind === "intent" && id("id") && id("operation") && "input" in record) return;
89
+ if (record.kind === "ack" && id("id") && "result" in record) return;
90
+ if (record.kind === "failure" && id("id") && id("code") && typeof record.uncertain === "boolean") return;
91
+ if (record.kind === "complete" && [
92
+ "clean",
93
+ "pending",
94
+ "uncertain"
95
+ ].includes(record.cleanup)) return;
96
+ throw failure("journal-invalid");
97
+ }
98
+ function writer(file, path, firstSequence, firstBytes) {
99
+ let sequence = firstSequence;
100
+ let bytes = firstBytes;
101
+ let reservedBytes = 0;
102
+ let tail = Promise.resolve();
103
+ let closing;
104
+ /** Writes charge byte capacity before I/O so concurrent mutations cannot spend an acknowledgement's reservation. */
105
+ function append(event, options, allocation) {
106
+ if (closing || allocation?.released) return Promise.reject(failure("journal-closed"));
107
+ let line;
108
+ try {
109
+ line = JSON.stringify({
110
+ ...event,
111
+ sequence
112
+ });
113
+ validate(JSON.parse(line), sequence);
114
+ } catch {
115
+ return Promise.reject(failure("journal-invalid"));
116
+ }
117
+ line += "\n";
118
+ const size = Buffer.byteLength(line);
119
+ if (allocation && size > allocation.remaining) return Promise.reject(failure("journal-limit"));
120
+ const limit = allocation || options?.cleanup || event.kind === "complete" ? maximumBytes : creationBytes;
121
+ if (bytes + reservedBytes + (allocation ? 0 : size) > limit) return Promise.reject(failure("journal-limit"));
122
+ if (allocation) {
123
+ allocation.remaining -= size;
124
+ reservedBytes -= size;
125
+ }
126
+ sequence++;
127
+ bytes += size;
128
+ tail = tail.then(async () => {
129
+ await file.appendFile(line, "utf8");
130
+ await file.sync();
131
+ });
132
+ return tail;
133
+ }
134
+ return Object.freeze(Object.defineProperties({
135
+ append,
136
+ close() {
137
+ closing ??= (async () => {
138
+ const errors = [];
139
+ try {
140
+ await tail;
141
+ } catch (error) {
142
+ errors.push(asError(error));
143
+ }
144
+ try {
145
+ await file.close();
146
+ } catch (error) {
147
+ errors.push(asError(error));
148
+ }
149
+ if (errors.length === 1 && errors[0]) throw errors[0];
150
+ if (errors.length) throw new AggregateError(errors, "Journal write and close failed");
151
+ })();
152
+ return closing;
153
+ },
154
+ path,
155
+ reserve(amount) {
156
+ if (closing) throw failure("journal-closed");
157
+ if (!Number.isSafeInteger(amount) || amount <= 0) throw failure("journal-invalid");
158
+ if (bytes + reservedBytes + amount > creationBytes) throw failure("journal-limit");
159
+ reservedBytes += amount;
160
+ const allocation = {
161
+ released: false,
162
+ remaining: amount
163
+ };
164
+ return Object.freeze({
165
+ append: (event) => append(event, void 0, allocation),
166
+ release() {
167
+ if (allocation.released) return;
168
+ allocation.released = true;
169
+ reservedBytes -= allocation.remaining;
170
+ }
171
+ });
172
+ }
173
+ }, {
174
+ [Symbol.for("nodejs.util.inspect.custom")]: { value: () => "[Sia private journal]" },
175
+ toJSON: { value: () => "[Sia private journal]" }
176
+ }));
177
+ }
178
+
179
+ //#endregion
180
+ export { createJournal, resumeJournal };