@le-space/sealed-image 0.0.0-stage → 0.12.8
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/README.md +37 -2
- package/package.json +33 -4
- package/src/build.mjs +497 -0
- package/src/derive.mjs +29 -0
- package/src/forget-guard.mjs +56 -0
- package/src/index.mjs +4 -0
- package/src/versions.mjs +93 -0
package/README.md
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @le-space/sealed-image
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An image of one's own on Aleph. A measured builder (an Aleph V-PROGRAM, in
|
|
4
|
+
`builder/` of this package's source) holds one public plain image on a
|
|
5
|
+
verified volume and seals a copy of it with a passphrase the caller derived.
|
|
6
|
+
The caller attests the builder, sends the passphrase once over that attested
|
|
7
|
+
channel, fetches the sealed image back in runs over an attest relay (each run
|
|
8
|
+
attested anew, resumed where a connection broke off), stores it on Aleph as
|
|
9
|
+
its own STORE (with retries over another API node) and waits until Aleph
|
|
10
|
+
confirms it.
|
|
11
|
+
|
|
12
|
+
- `derivePassphrase(root, { label, plainSha256 })`: HKDF-SHA256, one
|
|
13
|
+
passphrase per root key, app label and plain image.
|
|
14
|
+
- `buildOnFreshBuilder(...)`: starts a builder from the pinned V-PROGRAM
|
|
15
|
+
content (`@le-space/aleph-vm`'s `runOnFreshVProgram`), builds, uploads, and
|
|
16
|
+
forgets the builder; starts one more when another address claimed the first.
|
|
17
|
+
- `buildSealedImage(...)`: the same with a builder that already runs.
|
|
18
|
+
- `fetchSealed`, `storeMessage`, `storeOnAleph`, `checkBuilder`, `claimText`.
|
|
19
|
+
- `keepPrevious`, `releasePrevious`, `forgettable`, `forgetQueued`,
|
|
20
|
+
`fallbackPatch`: the previous image as the way back until a new one started
|
|
21
|
+
well.
|
|
22
|
+
- `builderVolumesToForget`: the guard for forgetting a builder's volumes.
|
|
23
|
+
- Limits: `MAX_PLAIN_BYTES` (992 MiB), `MAX_SEALED_BYTES` (1 GiB),
|
|
24
|
+
`PIECE_BYTES`, `RUN_BYTES`, `LANES`, `RUN_TRIES`, `UPLOAD_HOSTS`.
|
|
25
|
+
|
|
26
|
+
Errors are `SealedImageError` with a `code` (`busy`, `claimed`,
|
|
27
|
+
`build-failed`, `piece-missing`, `image-gone`, `upload-refused`,
|
|
28
|
+
`upload-broken`, `store-rejected`, `store-pending`, `other-image`, …);
|
|
29
|
+
progress is `{ step, data }` with `step` one of `start`, `attest`, `build`,
|
|
30
|
+
`fetch`, `sign`, `upload`, `confirm`, and never holds the passphrase. The app
|
|
31
|
+
words both.
|
|
32
|
+
|
|
33
|
+
A sealed image that was fetched but not yet confirmed on Aleph is kept while
|
|
34
|
+
the page is open (`keptInThisPage`, or your own `kept`): a second try only
|
|
35
|
+
uploads it again.
|
|
36
|
+
|
|
37
|
+
The builder, its publish workflow and its limits:
|
|
38
|
+
[Confidential VMs and sealed images](https://nikrause.github.io/relay-button/docs/reference/sealed-images).
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@le-space/sealed-image",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.12.8",
|
|
4
|
+
"description": "An image of one's own on Aleph: a measured builder seals a public plain image with a passphrase the caller derives; the caller fetches it in runs over an attested relay and stores it as a STORE.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"files": [
|
|
8
|
+
"src",
|
|
9
|
+
"README.md"
|
|
10
|
+
],
|
|
11
|
+
"main": "./src/index.mjs",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.mjs",
|
|
14
|
+
"./build": "./src/build.mjs",
|
|
15
|
+
"./derive": "./src/derive.mjs",
|
|
16
|
+
"./versions": "./src/versions.mjs",
|
|
17
|
+
"./forget-guard": "./src/forget-guard.mjs",
|
|
18
|
+
"./package.json": "./package.json"
|
|
19
|
+
},
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/NiKrause/relay-button"
|
|
26
|
+
},
|
|
27
|
+
"homepage": "https://github.com/NiKrause/relay-button",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/NiKrause/relay-button/issues"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@le-space/aleph-vm": "0.12.8",
|
|
33
|
+
"@le-space/core": "0.12.8"
|
|
34
|
+
}
|
|
35
|
+
}
|
package/src/build.mjs
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
// A sealed image of one's own: a measured builder (the V-PROGRAM in
|
|
2
|
+
// ../builder) holds one public plain image on a verified volume and seals a
|
|
3
|
+
// copy of it with a passphrase the caller derived (derive.mjs). The caller
|
|
4
|
+
// attests the builder first, sends the passphrase over that attested channel
|
|
5
|
+
// once, fetches the sealed image back in runs (each over a connection
|
|
6
|
+
// attested anew, because an attest relay carries only so much per
|
|
7
|
+
// connection), stores it on Aleph itself under its own address, and waits
|
|
8
|
+
// until Aleph confirms the STORE.
|
|
9
|
+
//
|
|
10
|
+
// Nothing here holds app texts: errors carry a `code` (SealedImageError),
|
|
11
|
+
// progress is reported as `{ step, data }`, and the app words both.
|
|
12
|
+
import { ALEPH_API, callJson, checkTemplate, messageStatus, refusedAttestation, runOnFreshVProgram, sha256Hex, signAsDelegate } from '@le-space/aleph-vm';
|
|
13
|
+
|
|
14
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
15
|
+
const CID = /^[A-Za-z0-9]{40,64}$/;
|
|
16
|
+
const sleeper = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
17
|
+
|
|
18
|
+
/** @typedef {import('@le-space/aleph-vm').AppKey} AppKey */
|
|
19
|
+
/** @typedef {import('@le-space/aleph-vm').Channel} Channel */
|
|
20
|
+
/**
|
|
21
|
+
* The builder an app trusts, and the plain image it asks for.
|
|
22
|
+
*
|
|
23
|
+
* `measurements` and `policy` are what the attestation must show; `route` is
|
|
24
|
+
* how an attest relay reaches a running builder; `plain` names the public
|
|
25
|
+
* image the builder holds by its SHA-256 (the builder refuses to seal any
|
|
26
|
+
* other), where it lies on Aleph (`store`) and the commit it was built from;
|
|
27
|
+
* `vprogram` is a running builder's V-PROGRAM on Aleph. `claim` is the first
|
|
28
|
+
* line of the text the build request is signed with; it must be the one the
|
|
29
|
+
* builder was published with (`sealed image build` for builders from this
|
|
30
|
+
* repository).
|
|
31
|
+
*
|
|
32
|
+
* Or, with `program` (the V-PROGRAM content of a published builder) and `crn`
|
|
33
|
+
* (the node that runs V-PROGRAMs), no builder runs between builds: each build
|
|
34
|
+
* starts one from that content and forgets it afterwards (buildOnFreshBuilder).
|
|
35
|
+
* @typedef {{ route?: string, program?: Record<string, any>, crn?: string, measurements: string[], policy: number | string, vprogram?: string, claim?: string, plain: { sha256: string, store?: string, commit?: string } }} Builder
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
/** What builders published from this repository sign build requests with (builder/claim.mjs). */
|
|
39
|
+
export const CLAIM = 'sealed image build';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The largest sealed image: Aleph takes 1 GiB in one upload. The builder adds
|
|
43
|
+
* 32 MiB (the LUKS2 header and room to grow), so a plain image may have
|
|
44
|
+
* MAX_PLAIN_BYTES at most (builder/builder.mjs refuses a larger one).
|
|
45
|
+
*/
|
|
46
|
+
export const MAX_SEALED_BYTES = 1024 * 1024 * 1024;
|
|
47
|
+
export const SEAL_OVERHEAD_BYTES = 32 * 1024 * 1024;
|
|
48
|
+
export const MAX_PLAIN_BYTES = MAX_SEALED_BYTES - SEAL_OVERHEAD_BYTES;
|
|
49
|
+
|
|
50
|
+
export class SealedImageError extends Error {
|
|
51
|
+
/** @param {string} message @param {string} code what failed, for code that must tell errors apart whatever the language @param {Record<string, any>} [detail] */
|
|
52
|
+
constructor(message, code, detail) {
|
|
53
|
+
super(message);
|
|
54
|
+
this.name = 'SealedImageError';
|
|
55
|
+
this.code = code;
|
|
56
|
+
if (detail) this.detail = detail;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* What the caller signs (personal_sign) with a build request: the first signed
|
|
62
|
+
* request claims the builder for its address (builder/claim.mjs, claimText:
|
|
63
|
+
* the two must stay the same). Never the passphrase.
|
|
64
|
+
* @param {string} sha256 @param {string} address @param {string} [claim]
|
|
65
|
+
*/
|
|
66
|
+
export const claimText = (sha256, address, claim = CLAIM) => `${claim}\nsha256: ${sha256}\naddress: ${address.toLowerCase()}`;
|
|
67
|
+
|
|
68
|
+
/** A builder entry that is complete, or an error (`no-builder`, `no-plain`) that says what is missing. @template {Builder} B @param {B} builder @returns {B} */
|
|
69
|
+
export function checkBuilder(builder) {
|
|
70
|
+
// A running builder has a route; one started for each build has its
|
|
71
|
+
// V-PROGRAM content and the node, and gets its route when it starts.
|
|
72
|
+
const reachable = Boolean(builder?.route) || (Boolean(builder?.program?.verification) && HEX64.test(builder?.crn ?? ''));
|
|
73
|
+
if (!reachable || !builder.measurements?.length || builder.policy == null) throw new SealedImageError('no builder: a route, or V-PROGRAM content and node, with measurements and policy', 'no-builder');
|
|
74
|
+
if (!HEX64.test(builder.plain?.sha256 ?? '')) throw new SealedImageError('the builder names no plain image (its SHA-256)', 'no-plain');
|
|
75
|
+
return builder;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The STORE message for the sealed image `cid`, owned and paid by `payer`
|
|
80
|
+
* (the app's own address by default), signed by the app's key.
|
|
81
|
+
* @param {AppKey} app @param {string} cid
|
|
82
|
+
* @param {{ channel: string, time?: number, payer?: string }} o
|
|
83
|
+
*/
|
|
84
|
+
export async function storeMessage(app, cid, { channel, time = Date.now() / 1000, payer = app.address }) {
|
|
85
|
+
if (!CID.test(cid)) throw new SealedImageError('not a content address', 'bad-cid');
|
|
86
|
+
const item_content = JSON.stringify({ address: payer, time, item_type: 'ipfs', item_hash: cid, payment: { type: 'credit' } });
|
|
87
|
+
// Sent by the app's key, in the payer's name (the payer authorized the key).
|
|
88
|
+
return signAsDelegate({ sender: payer, chain: 'ETH', type: 'STORE', item_hash: await sha256Hex(item_content), item_type: 'inline', item_content, time, channel }, app);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The host of an API URL, for showing. @param {string} url */
|
|
92
|
+
const apiHost = (url) => {
|
|
93
|
+
try {
|
|
94
|
+
return new URL(url).host;
|
|
95
|
+
} catch {
|
|
96
|
+
return '';
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Stores `image` on Aleph beside its signed STORE `message`, and says which
|
|
102
|
+
* content address the node made.
|
|
103
|
+
* @param {Blob} image @param {any} message @param {string} [api] @param {{ fetch?: typeof fetch }} [o]
|
|
104
|
+
* @returns {Promise<{ status: number, cid: string | null, reason: string }>}
|
|
105
|
+
*/
|
|
106
|
+
export async function storeOnAleph(image, message, api = ALEPH_API, { fetch: fetchImpl = globalThis.fetch } = {}) {
|
|
107
|
+
const form = new FormData();
|
|
108
|
+
form.append('file', image, 'rootfs');
|
|
109
|
+
form.append('metadata', JSON.stringify({ message, sync: true }));
|
|
110
|
+
const response = await fetchImpl(`${api}/api/v0/ipfs/add_file`, { method: 'POST', body: form });
|
|
111
|
+
const text = await response.text().catch(() => '');
|
|
112
|
+
let answer = null;
|
|
113
|
+
try {
|
|
114
|
+
answer = JSON.parse(text);
|
|
115
|
+
} catch {
|
|
116
|
+
/* not JSON: kept as the reason below */
|
|
117
|
+
}
|
|
118
|
+
const reason = response.ok ? '' : String(answer?.error ?? answer?.message ?? text).replace(/\s+/g, ' ').slice(0, 300);
|
|
119
|
+
return { status: response.status, cid: answer?.hash ?? null, reason };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The sealed image comes back in pieces of this size, each one request over
|
|
124
|
+
* an attested channel. The channel collects an answer by joining what
|
|
125
|
+
* arrives, so its cost grows with the square of the piece: a quarter MiB
|
|
126
|
+
* keeps that small and still needs few round trips.
|
|
127
|
+
*/
|
|
128
|
+
export const PIECE_BYTES = 256 * 1024;
|
|
129
|
+
/**
|
|
130
|
+
* What one run asks for. A relay that lets an image builder carry more per
|
|
131
|
+
* connection (relay-button#230: 256 MiB, 10 minutes) brings a run over one
|
|
132
|
+
* connection, attested once. A relay with the default limits (4 MiB, 120 s)
|
|
133
|
+
* closes it earlier; the run then goes on from its last piece over a new
|
|
134
|
+
* connection at once.
|
|
135
|
+
*/
|
|
136
|
+
export const RUN_BYTES = 32 * 1024 * 1024;
|
|
137
|
+
/**
|
|
138
|
+
* Connections side by side. A relay allows one client four at a time, and a
|
|
139
|
+
* closed one counts until the relay has seen it close: three leave room for
|
|
140
|
+
* that, and for the next run's connection while the last one closes.
|
|
141
|
+
*/
|
|
142
|
+
export const LANES = 3;
|
|
143
|
+
/**
|
|
144
|
+
* How often a run may fail in a row, without a single piece coming back,
|
|
145
|
+
* before the fetch gives up. A try that brings pieces starts the count anew,
|
|
146
|
+
* and the next try goes on where the last one broke off.
|
|
147
|
+
*/
|
|
148
|
+
export const RUN_TRIES = 10;
|
|
149
|
+
/** The longest wait between two tries of a run. */
|
|
150
|
+
export const RETRY_MAX_MS = 30_000;
|
|
151
|
+
/** Where the sealed image is uploaded, try by try: Aleph's API, then another node, then the first again. */
|
|
152
|
+
export const UPLOAD_HOSTS = [ALEPH_API, 'https://api3.aleph.im', ALEPH_API];
|
|
153
|
+
|
|
154
|
+
/** An error that ends a fetch: a refused attestation, or one of this package's that is not "unreachable". */
|
|
155
|
+
const final = (error) => refusedAttestation(error) || (error instanceof SealedImageError && error.code !== 'unreachable');
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The sealed image of `job`, `size` bytes, as a Blob: in runs of `runBytes`,
|
|
159
|
+
* each over a fresh channel from `open` and in pieces of `pieceBytes`, up to
|
|
160
|
+
* `lanes` runs at a time. A run that breaks off goes on where it stopped; a
|
|
161
|
+
* job the builder no longer has, or a builder that fails its attestation,
|
|
162
|
+
* ends it.
|
|
163
|
+
* @param {{ open: () => Promise<Channel>, job: string, size: number, pieceBytes?: number, runBytes?: number, lanes?: number, runTries?: number, sleep?: (ms: number) => Promise<void>, retryMs?: number, onBytes?: (n: number) => void }} a
|
|
164
|
+
*/
|
|
165
|
+
export async function fetchSealed({ open, job, size, pieceBytes = PIECE_BYTES, runBytes = RUN_BYTES, lanes = LANES, runTries = RUN_TRIES, sleep = sleeper, retryMs = 2000, onBytes = () => {} }) {
|
|
166
|
+
const runs = [];
|
|
167
|
+
for (let start = 0; start < size; start += runBytes) runs.push({ start, end: Math.min(start + runBytes, size) });
|
|
168
|
+
const parts = new Array(runs.length);
|
|
169
|
+
let next = 0;
|
|
170
|
+
let failed = null;
|
|
171
|
+
|
|
172
|
+
const fetchRun = async (run) => {
|
|
173
|
+
let last = '';
|
|
174
|
+
const pieces = [];
|
|
175
|
+
let at = run.start;
|
|
176
|
+
for (let failures = 0; failures < runTries && !failed; ) {
|
|
177
|
+
if (failures) await sleep(Math.min(retryMs * failures, RETRY_MAX_MS));
|
|
178
|
+
let channel = null;
|
|
179
|
+
const before = at;
|
|
180
|
+
try {
|
|
181
|
+
channel = await open();
|
|
182
|
+
for (; at < run.end; ) {
|
|
183
|
+
const end = Math.min(at + pieceBytes, run.end) - 1;
|
|
184
|
+
const piece = await channel.request('GET', `/job/${job}/image`, { headers: { range: `bytes=${at}-${end}` } });
|
|
185
|
+
if ([404, 409, 410, 416].includes(piece.status)) throw new SealedImageError(`the builder no longer has the image (${piece.status})`, 'image-gone', { status: piece.status });
|
|
186
|
+
if (piece.status !== 206 || piece.body.length !== end - at + 1) throw new Error(String(piece.status));
|
|
187
|
+
pieces.push(piece.body);
|
|
188
|
+
at = end + 1;
|
|
189
|
+
onBytes(piece.body.length);
|
|
190
|
+
}
|
|
191
|
+
return pieces;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
// The image gone, or an attestation refused: trying again cannot help.
|
|
194
|
+
// A builder or relay not answering for a moment can.
|
|
195
|
+
if (final(error)) throw error;
|
|
196
|
+
last = error instanceof Error ? error.message : String(error);
|
|
197
|
+
// Pieces came back: a relay's limit or a short break, not a dead
|
|
198
|
+
// line. Go on at once; only tries without any piece wait and count.
|
|
199
|
+
failures = at > before ? 0 : failures + 1;
|
|
200
|
+
} finally {
|
|
201
|
+
channel?.close();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
throw new SealedImageError(`a piece of the image did not arrive: ${last.slice(0, 120)}`, 'piece-missing', { last: last.slice(0, 120) });
|
|
205
|
+
};
|
|
206
|
+
const lane = async () => {
|
|
207
|
+
while (!failed && next < runs.length) {
|
|
208
|
+
const index = next++;
|
|
209
|
+
try {
|
|
210
|
+
parts[index] = await fetchRun(runs[index]);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
failed ??= error;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(lanes, runs.length)) }, lane));
|
|
217
|
+
if (failed) throw failed;
|
|
218
|
+
return new Blob(parts.flat(), { type: 'application/octet-stream' });
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* An image that was fetched but is not confirmed on Aleph yet, kept while the
|
|
223
|
+
* page is open: a second try uploads it again instead of building and
|
|
224
|
+
* fetching it again. It holds nothing readable without the passphrase.
|
|
225
|
+
* @typedef {{ current: null | { key: string, cid: string, size: number, image: Blob, attested: null | { measurement: string, at: string }, message?: any } }} Kept
|
|
226
|
+
*/
|
|
227
|
+
/** @type {Kept} */
|
|
228
|
+
export const keptInThisPage = { current: null };
|
|
229
|
+
|
|
230
|
+
/** The key a kept image is held under: one per address and plain image. @param {string} address @param {string} sha256 */
|
|
231
|
+
export const keptKey = (address, sha256) => `${address.toLowerCase()}/${sha256}`;
|
|
232
|
+
|
|
233
|
+
/** Aleph's word on the STORE: processed, or an error. */
|
|
234
|
+
async function awaitStore(itemHash, { read, sleep, tries, delayMs }) {
|
|
235
|
+
for (let i = 0; i < tries; i++) {
|
|
236
|
+
const status = await read(itemHash);
|
|
237
|
+
if (status === 'processed') return;
|
|
238
|
+
if (status === 'rejected' || status === 'forgotten') throw new SealedImageError(`Aleph did not take the STORE (${status})`, 'store-rejected', { status });
|
|
239
|
+
await sleep(delayMs);
|
|
240
|
+
}
|
|
241
|
+
throw new SealedImageError('Aleph has not confirmed the STORE yet', 'store-pending');
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* @typedef {{
|
|
246
|
+
* step: 'start' | 'attest' | 'build' | 'fetch' | 'sign' | 'upload' | 'confirm',
|
|
247
|
+
* data?: Record<string, any>
|
|
248
|
+
* }} Progress
|
|
249
|
+
*/
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Has `builder` seal its plain image with `passphrase`, fetches the sealed
|
|
253
|
+
* image, stores it on Aleph as a STORE of `payer` (sent by the app's key) and
|
|
254
|
+
* waits for Aleph to confirm it. Returns
|
|
255
|
+
* `{ storeHash, cid, size, plainSha256, builtAt, attested }`; the passphrase
|
|
256
|
+
* stays with the caller.
|
|
257
|
+
*
|
|
258
|
+
* `open` resolves to an attested channel to the builder (and must reject
|
|
259
|
+
* unless the attestation shows the builder's measurement). It is called for
|
|
260
|
+
* the build, where the passphrase goes through it, and again for every run of
|
|
261
|
+
* the sealed image that comes back; a channel may say which measurement the
|
|
262
|
+
* hardware reported (`measurement`), which is returned as `attested`.
|
|
263
|
+
* @param {{
|
|
264
|
+
* passphrase: string, app: AppKey, payer?: string, channel: string, builder: Builder,
|
|
265
|
+
* open: () => Promise<Channel>,
|
|
266
|
+
* onProgress?: (p: Progress) => void,
|
|
267
|
+
* store?: typeof storeOnAleph,
|
|
268
|
+
* read?: (itemHash: string) => Promise<string | null>,
|
|
269
|
+
* sleep?: (ms: number) => Promise<void>,
|
|
270
|
+
* now?: () => number,
|
|
271
|
+
* kept?: Kept,
|
|
272
|
+
* pollMs?: number, buildTries?: number, confirmTries?: number, pieceBytes?: number, runBytes?: number, lanes?: number, runTries?: number, retryMs?: number
|
|
273
|
+
* }} a
|
|
274
|
+
*/
|
|
275
|
+
export async function buildSealedImage({ passphrase, app, payer = app.address, channel: alephChannel, builder, open, onProgress = () => {}, store = storeOnAleph, read = (h) => messageStatus(h), sleep = sleeper, now = Date.now, kept = keptInThisPage, pollMs = 5000, buildTries = 240, confirmTries = 180, pieceBytes = PIECE_BYTES, runBytes = RUN_BYTES, lanes = LANES, runTries = RUN_TRIES, retryMs = 2000 }) {
|
|
276
|
+
const { plain } = checkBuilder(builder);
|
|
277
|
+
if (typeof passphrase !== 'string' || passphrase.length < 32 || passphrase.length > 256 || /[\r\n\0]/.test(passphrase)) throw new SealedImageError('the passphrase must be one line of 32 to 256 characters', 'bad-passphrase');
|
|
278
|
+
const key = keptKey(app.address, plain.sha256);
|
|
279
|
+
if (kept.current?.key !== key) kept.current = null;
|
|
280
|
+
|
|
281
|
+
if (!kept.current) kept.current = await sealAndFetch();
|
|
282
|
+
const { cid, size, image, attested } = kept.current;
|
|
283
|
+
|
|
284
|
+
// A STORE that was signed and uploaded before is only waited for again.
|
|
285
|
+
let message = kept.current.message;
|
|
286
|
+
if (!message) {
|
|
287
|
+
onProgress({ step: 'sign', data: { cid } });
|
|
288
|
+
message = await storeMessage(app, cid, { channel: alephChannel, time: now() / 1000, payer });
|
|
289
|
+
onProgress({ step: 'sign', data: { cid, storeHash: message.item_hash } });
|
|
290
|
+
const stored = await uploadWithRetries(image, message, size);
|
|
291
|
+
if (stored.status >= 300) throw new SealedImageError(`Aleph did not take the image (${stored.status})${stored.reason ? `: ${stored.reason}` : ''}`, 'upload-refused', { status: stored.status, reason: stored.reason });
|
|
292
|
+
// The node names the content address it made from what it received.
|
|
293
|
+
if (stored.cid && stored.cid !== cid) {
|
|
294
|
+
kept.current = null;
|
|
295
|
+
throw new SealedImageError('Aleph stored another image than the builder sealed', 'other-image', { cid: stored.cid });
|
|
296
|
+
}
|
|
297
|
+
kept.current.message = message;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
onProgress({ step: 'confirm', data: { storeHash: message.item_hash } });
|
|
301
|
+
try {
|
|
302
|
+
await awaitStore(message.item_hash, { read, sleep, tries: confirmTries, delayMs: pollMs });
|
|
303
|
+
onProgress({ step: 'confirm', data: { storeHash: message.item_hash, processed: true } });
|
|
304
|
+
} catch (error) {
|
|
305
|
+
// Refused: the next try signs and uploads anew. Not confirmed yet: it waits again.
|
|
306
|
+
if (error instanceof SealedImageError && error.code === 'store-rejected') delete kept.current.message;
|
|
307
|
+
throw error;
|
|
308
|
+
}
|
|
309
|
+
kept.current = null;
|
|
310
|
+
return {
|
|
311
|
+
storeHash: String(message.item_hash),
|
|
312
|
+
cid,
|
|
313
|
+
size,
|
|
314
|
+
plainSha256: plain.sha256,
|
|
315
|
+
builtAt: new Date(now()).toISOString(),
|
|
316
|
+
attested: attested ? { vprogram: builder.vprogram ?? null, measurement: attested.measurement, at: attested.at } : null
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Upload the sealed image, more than once if the connection breaks: one
|
|
321
|
+
* request of up to 1 GiB, which an unsteady line can lose. Before trying
|
|
322
|
+
* again it asks Aleph whether the STORE arrived after all; the second try
|
|
323
|
+
* goes to another API node. Only a gateway that gave up (502, 503, 504) is
|
|
324
|
+
* tried again; any other answer is final.
|
|
325
|
+
*/
|
|
326
|
+
async function uploadWithRetries(image, message, size) {
|
|
327
|
+
let last = null;
|
|
328
|
+
for (let attempt = 0; attempt < UPLOAD_HOSTS.length; attempt++) {
|
|
329
|
+
const host = UPLOAD_HOSTS[attempt];
|
|
330
|
+
if (attempt) {
|
|
331
|
+
await sleep(Math.min(retryMs * 5 * attempt, RETRY_MAX_MS));
|
|
332
|
+
const status = await read(message.item_hash).catch(() => null);
|
|
333
|
+
if (status === 'processed' || status === 'pending') return { status: 200, cid: null, reason: '' };
|
|
334
|
+
}
|
|
335
|
+
onProgress({ step: 'upload', data: { size, host: apiHost(host), attempt: attempt + 1 } });
|
|
336
|
+
try {
|
|
337
|
+
const stored = await store(image, message, host);
|
|
338
|
+
if (![502, 503, 504].includes(stored.status)) return stored;
|
|
339
|
+
last = stored;
|
|
340
|
+
} catch (error) {
|
|
341
|
+
last = { status: 0, cid: null, reason: String(error instanceof Error ? error.message : error).slice(0, 200) };
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (last?.status) return last;
|
|
345
|
+
throw new SealedImageError(`the upload broke off ${UPLOAD_HOSTS.length} times: ${last?.reason ?? ''}`, 'upload-broken', { reason: last?.reason ?? '' });
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Has the builder seal the image and fetches it; the builder drops it afterwards, whatever happened. */
|
|
349
|
+
async function sealAndFetch() {
|
|
350
|
+
onProgress({ step: 'attest', data: {} });
|
|
351
|
+
let opened = 0;
|
|
352
|
+
const counted = async () => {
|
|
353
|
+
const c = await open();
|
|
354
|
+
opened++;
|
|
355
|
+
return c;
|
|
356
|
+
};
|
|
357
|
+
let channel = await counted();
|
|
358
|
+
const attested = typeof channel.measurement === 'string' && channel.measurement ? { measurement: channel.measurement, at: new Date(now()).toISOString() } : null;
|
|
359
|
+
onProgress({ step: 'attest', data: { relay: channel.relay ?? null, measurement: attested?.measurement ?? null } });
|
|
360
|
+
let job = '';
|
|
361
|
+
try {
|
|
362
|
+
onProgress({ step: 'build', data: { plainSha256: plain.sha256 } });
|
|
363
|
+
// Sent once, over the channel that was just attested, and never again.
|
|
364
|
+
// Signed by the app's key: the first signed request claims the builder.
|
|
365
|
+
const signature = await app.signMessage({ message: claimText(plain.sha256, app.address, builder.claim) });
|
|
366
|
+
const started = await callJson(channel, 'POST', '/build', { sha256: plain.sha256, passphrase, address: app.address, signature });
|
|
367
|
+
const said = started.answer?.error ? String(started.answer.error).slice(0, 200) : '';
|
|
368
|
+
if (started.status === 503 && /busy/i.test(said)) throw new SealedImageError('the builder is busy with other images', 'busy');
|
|
369
|
+
if (started.status === 403 && /claimed/i.test(said)) throw new SealedImageError('another address claimed the builder', 'claimed');
|
|
370
|
+
job = started.answer?.job ?? '';
|
|
371
|
+
if (started.status !== 202 || !/^[0-9a-f]{48}$/.test(job)) throw new SealedImageError(`the builder did not accept the build (${started.status})${said ? `: ${said}` : ''}`, 'not-accepted', { status: started.status, error: said });
|
|
372
|
+
|
|
373
|
+
// A relay ends a connection after a while: asking goes on over a new one.
|
|
374
|
+
let built = null;
|
|
375
|
+
let drops = 0;
|
|
376
|
+
for (let i = 0; i < buildTries && !built; i++) {
|
|
377
|
+
await sleep(pollMs);
|
|
378
|
+
let state;
|
|
379
|
+
try {
|
|
380
|
+
channel ??= await counted();
|
|
381
|
+
state = await callJson(channel, 'GET', `/job/${job}`);
|
|
382
|
+
} catch (error) {
|
|
383
|
+
channel?.close();
|
|
384
|
+
channel = null;
|
|
385
|
+
if (refusedAttestation(error)) throw error;
|
|
386
|
+
if (++drops > 5) throw new SealedImageError('the connection to the builder broke off again and again', 'dropped');
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
drops = 0;
|
|
390
|
+
if (state.status !== 200) throw new SealedImageError(`the builder does not know the build (${state.status})`, 'job-unknown', { status: state.status });
|
|
391
|
+
if (state.answer?.state === 'failed') throw new SealedImageError(`the build failed${state.answer.error ? `: ${String(state.answer.error).slice(0, 200)}` : ''}`, 'build-failed', { error: state.answer.error ? String(state.answer.error).slice(0, 200) : '' });
|
|
392
|
+
if (state.answer?.state === 'built') built = state.answer;
|
|
393
|
+
}
|
|
394
|
+
if (!built) throw new SealedImageError('the build took too long', 'build-slow');
|
|
395
|
+
const size = Number(built.size);
|
|
396
|
+
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_SEALED_BYTES) throw new SealedImageError('the builder named no valid size', 'bad-size');
|
|
397
|
+
if (!CID.test(built.cid ?? '')) throw new SealedImageError('the builder named no valid content address', 'bad-cid');
|
|
398
|
+
onProgress({ step: 'build', data: { plainSha256: plain.sha256, cid: built.cid, size } });
|
|
399
|
+
channel?.close();
|
|
400
|
+
channel = null;
|
|
401
|
+
|
|
402
|
+
// The sealed image holds nothing readable without the passphrase, and
|
|
403
|
+
// every run of it arrives over a channel attested like the first.
|
|
404
|
+
let got = 0;
|
|
405
|
+
const shown = () => onProgress({ step: 'fetch', data: { got, size, lanes, attested: opened } });
|
|
406
|
+
shown();
|
|
407
|
+
const image = await fetchSealed({ open: counted, job, size, pieceBytes, runBytes, lanes, runTries, sleep, retryMs, onBytes: (n) => { got += n; shown(); } });
|
|
408
|
+
return { key, cid: built.cid, size, image, attested };
|
|
409
|
+
} finally {
|
|
410
|
+
channel?.close();
|
|
411
|
+
// Whatever happened: the builder need not keep this image. Tried a few
|
|
412
|
+
// times: an image left behind takes one of the builder's few jobs
|
|
413
|
+
// until it expires (minutes; builder/builder.mjs).
|
|
414
|
+
for (let attempt = 0; job && attempt < 4; attempt++) {
|
|
415
|
+
if (attempt) await sleep(retryMs * attempt);
|
|
416
|
+
let last = null;
|
|
417
|
+
try {
|
|
418
|
+
last = await open();
|
|
419
|
+
const dropped = await callJson(last, 'DELETE', `/job/${job}`);
|
|
420
|
+
if (dropped.status === 200 || dropped.status === 404) job = '';
|
|
421
|
+
} catch {
|
|
422
|
+
/* tried again; at worst the builder removes it after ten minutes */
|
|
423
|
+
} finally {
|
|
424
|
+
last?.close();
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Build on a builder started for this build, and forget that builder
|
|
433
|
+
* afterwards, whatever happened (@le-space/aleph-vm's runOnFreshVProgram).
|
|
434
|
+
* The caller notes the builder between start and forget (`onStarted`,
|
|
435
|
+
* `onForgotten`), so a closed window leaves nothing running for longer than
|
|
436
|
+
* the next opening. An image already fetched in this page (an upload that
|
|
437
|
+
* failed) needs no builder: it is only uploaded again. If another address
|
|
438
|
+
* claimed the builder first, it is forgotten and one more is started, once.
|
|
439
|
+
* @param {Omit<Parameters<typeof buildSealedImage>[0], 'open'> & {
|
|
440
|
+
* builder: Builder & { program: Record<string, any>, crn: string },
|
|
441
|
+
* opener: (running: Builder & { route: string, vprogram: string }) => () => Promise<Channel>,
|
|
442
|
+
* onStarted?: (vprogram: string) => Promise<void> | void,
|
|
443
|
+
* onForgotten?: (vprogram: string) => Promise<void> | void,
|
|
444
|
+
* post?: (message: any) => Promise<any>,
|
|
445
|
+
* upTries?: number, upMs?: number
|
|
446
|
+
* }} a
|
|
447
|
+
*/
|
|
448
|
+
export async function buildOnFreshBuilder(a) {
|
|
449
|
+
for (let attempt = 0; ; attempt++) {
|
|
450
|
+
try {
|
|
451
|
+
return await buildOnOneBuilder(a);
|
|
452
|
+
} catch (error) {
|
|
453
|
+
if (!(error instanceof SealedImageError && error.code === 'claimed') || attempt >= 1) throw error;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** One builder, started, used and forgotten. @param {Parameters<typeof buildOnFreshBuilder>[0]} a */
|
|
459
|
+
async function buildOnOneBuilder({ builder, opener, onStarted, onForgotten, post, upTries, upMs, ...rest }) {
|
|
460
|
+
const { app, payer = app.address, channel, onProgress = () => {}, sleep = sleeper, kept = keptInThisPage } = rest;
|
|
461
|
+
checkBuilder(builder);
|
|
462
|
+
checkTemplate(/** @type {any} */ (builder));
|
|
463
|
+
if (kept.current?.key === keptKey(app.address, builder.plain.sha256)) {
|
|
464
|
+
return buildSealedImage({ ...rest, builder, open: () => Promise.reject(new SealedImageError('no builder needed: the image is only uploaded again', 'no-builder')) });
|
|
465
|
+
}
|
|
466
|
+
return runOnFreshVProgram({
|
|
467
|
+
app,
|
|
468
|
+
template: /** @type {any} */ (builder),
|
|
469
|
+
channel,
|
|
470
|
+
payer,
|
|
471
|
+
opener: /** @type {any} */ (opener),
|
|
472
|
+
onStarted,
|
|
473
|
+
onForgotten,
|
|
474
|
+
onProgress: (p) => onProgress(/** @type {Progress} */ (p)),
|
|
475
|
+
...(post ? { post } : {}),
|
|
476
|
+
sleep,
|
|
477
|
+
...(upTries ? { upTries } : {}),
|
|
478
|
+
...(upMs !== undefined ? { upMs } : {}),
|
|
479
|
+
reason: 'sealed image built',
|
|
480
|
+
work: ({ open, running }) => buildSealedImage({ ...rest, builder: /** @type {Builder} */ (running), open })
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// Aleph starts a V-PROGRAM only when its payer holds a day of everything it
|
|
485
|
+
// then pays for: the builder and what already runs (min_runtime_days: 1).
|
|
486
|
+
// Measured 2026-11-14: the builder (6 GiB, 2 vCPUs) 23.75 credits a second,
|
|
487
|
+
// the STORE of a sealed image (868 MiB) 0.045 a second; used when Aleph's
|
|
488
|
+
// price estimate cannot be asked.
|
|
489
|
+
export const BUILDER_CREDITS_PER_HOUR = 85_500;
|
|
490
|
+
export const IMAGE_STORE_CREDITS_PER_HOUR = 170;
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* The credits a payer must hold for Aleph to start a builder: a day of the
|
|
494
|
+
* builder, of the sealed image's storage and of what it already spends.
|
|
495
|
+
* @param {{ builderPerHour?: number | null, storePerHour?: number, spendingPerHour?: number }} [o]
|
|
496
|
+
*/
|
|
497
|
+
export const creditsForBuild = ({ builderPerHour, storePerHour = IMAGE_STORE_CREDITS_PER_HOUR, spendingPerHour = 0 } = {}) => Math.ceil(((builderPerHour ?? BUILDER_CREDITS_PER_HOUR) + storePerHour + spendingPerHour) * 24);
|
package/src/derive.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The passphrase of a private image, derived from a root key the caller holds
|
|
2
|
+
// (an app's master secret): HKDF-SHA256 with no salt, the info
|
|
3
|
+
// `<label>/<plain image SHA-256>`, 32 bytes, as base64url without padding
|
|
4
|
+
// (43 characters). One passphrase per root key, app label and plain image,
|
|
5
|
+
// so a new plain image gets a new passphrase and no two apps share one.
|
|
6
|
+
//
|
|
7
|
+
// WebCrypto only: the same in a browser and in Node. Paperless anywhere's
|
|
8
|
+
// label is `paperless-anywhere/image-passphrase/v1`.
|
|
9
|
+
|
|
10
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
11
|
+
const LABEL = /^[\x21-\x7e]{1,200}$/;
|
|
12
|
+
|
|
13
|
+
/** @param {Uint8Array} bytes */
|
|
14
|
+
const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {Uint8Array} root 32 bytes, kept by the caller
|
|
18
|
+
* @param {{ label: string, plainSha256: string }} o `label`: one per app and purpose, e.g. `belege/bridge-image-passphrase/v1`
|
|
19
|
+
* @returns {Promise<string>}
|
|
20
|
+
*/
|
|
21
|
+
export async function derivePassphrase(root, { label, plainSha256 }) {
|
|
22
|
+
if (!(root instanceof Uint8Array) || root.length !== 32) throw new Error('the root key must be 32 bytes');
|
|
23
|
+
if (!LABEL.test(label ?? '')) throw new Error('the label: printable ASCII without spaces');
|
|
24
|
+
if (!HEX64.test(plainSha256 ?? '')) throw new Error('the plain image is named by its SHA-256 (64 hex)');
|
|
25
|
+
const key = await crypto.subtle.importKey('raw', root, 'HKDF', false, ['deriveBits']);
|
|
26
|
+
const info = new TextEncoder().encode(`${label}/${plainSha256}`);
|
|
27
|
+
const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info }, key, 256);
|
|
28
|
+
return base64url(new Uint8Array(bits));
|
|
29
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// What may be forgotten when a builder is deleted (the workflow
|
|
2
|
+
// sealed-image-builder.yml, action "delete" with "forget_volumes"): only the
|
|
3
|
+
// STOREs that builder's V-PROGRAM names as its volumes, and never an image.
|
|
4
|
+
//
|
|
5
|
+
// On 14 Nov 2026 a hand-written list of "builder volumes" forgot older
|
|
6
|
+
// Paperless anywhere images too, among them one a vault still started from.
|
|
7
|
+
// So a STORE is forgotten only when all of this holds; one refusal stops all
|
|
8
|
+
// of it.
|
|
9
|
+
// - The V-PROGRAM being deleted names it (workload, volume or a hash tree).
|
|
10
|
+
// - The account that sent the V-PROGRAM sent it, and Aleph has it processed.
|
|
11
|
+
// - It is smaller than any image: a builder's volumes are about 300 MB at
|
|
12
|
+
// most, a sealed image is about 900 MB to 1 GiB. A plain-image volume
|
|
13
|
+
// larger than the limit is refused, which forgets nothing (safe).
|
|
14
|
+
// - The kept list (the pinned builders in builder/publications, an app's
|
|
15
|
+
// pins, release notes) does not name it.
|
|
16
|
+
|
|
17
|
+
/** Bigger than any builder volume, smaller than any sealed image. */
|
|
18
|
+
export const BUILDER_VOLUME_MAX_BYTES = 600 * 1024 * 1024;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The refs a V-PROGRAM's content names as its volumes.
|
|
22
|
+
* @param {any} content the V-PROGRAM's content
|
|
23
|
+
* @returns {string[]}
|
|
24
|
+
*/
|
|
25
|
+
export function volumeRefs(content) {
|
|
26
|
+
const refs = [content?.workload?.ref, content?.workload?.hash_tree, ...(content?.volumes ?? []).flatMap((v) => [v?.ref, v?.hash_tree])];
|
|
27
|
+
return [...new Set(refs.filter((r) => typeof r === 'string' && r.length > 0))];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Why `store` must not be forgotten, or null when it may.
|
|
32
|
+
* @param {{ hash: string, status?: string, type?: string, sender?: string, size?: number | null }} store
|
|
33
|
+
* @param {{ account: string, named: Set<string>, kept: Set<string> }} o `named`: the STOREs the V-PROGRAM names; `kept`: hashes that must stay (pins, releases)
|
|
34
|
+
*/
|
|
35
|
+
export function forgetRefusal(store, { account, named, kept }) {
|
|
36
|
+
const h = store.hash;
|
|
37
|
+
if (!/^[0-9a-f]{64}$/.test(h)) return `${h}: no item hash`;
|
|
38
|
+
if (!named.has(h)) return `${h}: not a volume of the builder being deleted`;
|
|
39
|
+
if (kept.has(h)) return `${h}: named in the kept list`;
|
|
40
|
+
if (store.type !== 'STORE' || store.status !== 'processed') return `${h}: not a processed STORE (${store.status} ${store.type})`;
|
|
41
|
+
if (String(store.sender).toLowerCase() !== String(account).toLowerCase()) return `${h}: sent by ${store.sender}, not by ${account}`;
|
|
42
|
+
if (typeof store.size !== 'number' || !(store.size > 0)) return `${h}: size unknown, so it might be an image`;
|
|
43
|
+
if (store.size > BUILDER_VOLUME_MAX_BYTES) return `${h}: ${Math.round(store.size / 1e6)} MB, an image rather than a builder volume`;
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The STOREs to forget, or the reasons not to forget any.
|
|
49
|
+
* @param {Parameters<typeof forgetRefusal>[0][]} stores
|
|
50
|
+
* @param {Parameters<typeof forgetRefusal>[1]} o
|
|
51
|
+
* @returns {{ forget: string[], refused: string[] }}
|
|
52
|
+
*/
|
|
53
|
+
export function builderVolumesToForget(stores, o) {
|
|
54
|
+
const refused = stores.map((s) => forgetRefusal(s, o)).filter((r) => r !== null);
|
|
55
|
+
return refused.length ? { forget: [], refused } : { forget: stores.map((s) => s.hash), refused: [] };
|
|
56
|
+
}
|
package/src/index.mjs
ADDED
package/src/versions.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Versions of a private image in an app's profile. A private image replaced
|
|
2
|
+
// by a newer build is kept until the newer one has started well (attested,
|
|
3
|
+
// unlocked, the app answering, any restore done): until then it is the way
|
|
4
|
+
// back. After a good start it is forgotten; a FORGET that fails stays queued
|
|
5
|
+
// and is tried again later. Nothing here forgets an image a VM or a start
|
|
6
|
+
// uses; checking that a queued STORE is one the app itself stored is the
|
|
7
|
+
// caller's (its forget function).
|
|
8
|
+
//
|
|
9
|
+
// The profile fields: `rootfsItemHash` (the STORE a VM starts from),
|
|
10
|
+
// `luksPassphrase` and `luksFor` (its passphrase and the STORE it belongs
|
|
11
|
+
// to), `ownImage` (the build: plainSha256, rootfsItemHash, cid, builtAt, and
|
|
12
|
+
// `previous`, the way back), `oldOwnImages` (STOREs queued to forget),
|
|
13
|
+
// `running` and `starting` (what a VM uses now).
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The image fields a profile starts from, to keep as the way back.
|
|
17
|
+
* @param {Record<string, any>} profile
|
|
18
|
+
*/
|
|
19
|
+
const imageOf = (profile) => ({
|
|
20
|
+
rootfsItemHash: profile.rootfsItemHash,
|
|
21
|
+
luksPassphrase: profile.luksPassphrase,
|
|
22
|
+
luksFor: profile.luksFor,
|
|
23
|
+
ownImage: profile.ownImage ? { ...profile.ownImage, previous: undefined } : null
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* What a new build's profile fields become: the image it replaces is kept as
|
|
28
|
+
* `ownImage.previous`. Built twice before a good start, the older way back
|
|
29
|
+
* stays, and the one in between (never started well) is queued to forget.
|
|
30
|
+
* @param {Record<string, any>} profile before the build
|
|
31
|
+
* @param {Record<string, any>} built the build's fields (rootfsItemHash, luksPassphrase, luksFor, ownImage)
|
|
32
|
+
* @returns {Record<string, any>} the fields to save
|
|
33
|
+
*/
|
|
34
|
+
export function keepPrevious(profile, built) {
|
|
35
|
+
const old = profile?.ownImage && profile.rootfsItemHash && profile.rootfsItemHash !== built.rootfsItemHash ? profile.rootfsItemHash : null;
|
|
36
|
+
if (!old) return built;
|
|
37
|
+
const earlier = profile.ownImage.previous;
|
|
38
|
+
const previous = earlier ?? imageOf(profile);
|
|
39
|
+
const queue = earlier ? [...(profile.oldOwnImages ?? []), old] : profile.oldOwnImages ?? [];
|
|
40
|
+
return { ...built, ownImage: { ...built.ownImage, previous }, ...(queue.length ? { oldOwnImages: [...new Set(queue)] } : {}) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* After a start: was it good enough to give up the way back?
|
|
45
|
+
* @param {any} running what the start returned: `instanceHash`, and `restore.status` when it restored
|
|
46
|
+
*/
|
|
47
|
+
export const startWentWell = (running) => Boolean(running?.instanceHash) && running?.restore?.status !== 'failed';
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Once the new image started well: the way back goes into the queue to forget.
|
|
51
|
+
* @param {Record<string, any>} profile @returns {Record<string, any> | null} the patch, or null
|
|
52
|
+
*/
|
|
53
|
+
export function releasePrevious(profile) {
|
|
54
|
+
const prev = profile?.ownImage?.previous?.rootfsItemHash;
|
|
55
|
+
if (!prev) return null;
|
|
56
|
+
const { previous, ...ownImage } = profile.ownImage;
|
|
57
|
+
return { ownImage, oldOwnImages: [...new Set([...(profile.oldOwnImages ?? []), prev])] };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The queued images that may be forgotten now: never the one the profile
|
|
62
|
+
* starts from, the way back, or one a start or a running VM uses.
|
|
63
|
+
* @param {Record<string, any>} profile
|
|
64
|
+
*/
|
|
65
|
+
export function forgettable(profile) {
|
|
66
|
+
const inUse = new Set([profile?.rootfsItemHash, profile?.ownImage?.previous?.rootfsItemHash, profile?.running?.rootfsItemHash, profile?.starting?.rootfsItemHash].filter(Boolean));
|
|
67
|
+
return (profile?.oldOwnImages ?? []).filter((h) => /^[0-9a-f]{64}$/.test(h) && !inUse.has(h));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Forget what may be forgotten; resolves to the queue that stays (those
|
|
72
|
+
* that failed, and those still in use).
|
|
73
|
+
* @param {Record<string, any>} profile
|
|
74
|
+
* @param {(store: string) => Promise<boolean>} forget true when forgotten
|
|
75
|
+
* @returns {Promise<string[]>}
|
|
76
|
+
*/
|
|
77
|
+
export async function forgetQueued(profile, forget) {
|
|
78
|
+
const now = forgettable(profile);
|
|
79
|
+
const done = new Set();
|
|
80
|
+
for (const h of now) if (await forget(h).catch(() => false)) done.add(h);
|
|
81
|
+
return (profile?.oldOwnImages ?? []).filter((h) => !done.has(h));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Start from the way back: the previous image becomes the one to start, and
|
|
86
|
+
* the newer one is kept as the way back in turn (nothing is lost).
|
|
87
|
+
* @param {Record<string, any>} profile @returns {Record<string, any> | null}
|
|
88
|
+
*/
|
|
89
|
+
export function fallbackPatch(profile) {
|
|
90
|
+
const prev = profile?.ownImage?.previous;
|
|
91
|
+
if (!prev?.rootfsItemHash) return null;
|
|
92
|
+
return { ...prev, ownImage: { ...(prev.ownImage ?? {}), previous: imageOf(profile) } };
|
|
93
|
+
}
|