@blamejs/core 0.7.18 → 0.7.20
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/CHANGELOG.md +427 -423
- package/README.md +150 -150
- package/bin/blamejs.js +0 -0
- package/index.js +310 -308
- package/lib/api-key.js +660 -660
- package/lib/api-snapshot.js +338 -338
- package/lib/app-shutdown.js +385 -385
- package/lib/app.js +365 -365
- package/lib/archive.js +250 -250
- package/lib/atomic-file.js +544 -544
- package/lib/audit-chain.js +177 -177
- package/lib/audit-sign.js +344 -344
- package/lib/audit-tools.js +677 -677
- package/lib/audit.js +766 -766
- package/lib/auth/jwt-external.js +365 -0
- package/lib/auth/jwt.js +337 -311
- package/lib/auth/lockout.js +436 -436
- package/lib/auth/oauth.js +721 -721
- package/lib/auth/passkey.js +181 -181
- package/lib/auth/password.js +628 -594
- package/lib/backup/bundle.js +217 -217
- package/lib/backup/crypto.js +176 -176
- package/lib/backup/index.js +515 -515
- package/lib/backup/manifest.js +282 -282
- package/lib/break-glass.js +1338 -1338
- package/lib/bundler.js +441 -441
- package/lib/cache-redis.js +256 -256
- package/lib/cache.js +1206 -1206
- package/lib/canonical-json.js +115 -115
- package/lib/chain-writer.js +234 -234
- package/lib/cli-helpers.js +206 -206
- package/lib/cli.js +2334 -2334
- package/lib/cluster-provider-db.js +317 -317
- package/lib/cluster-storage.js +226 -226
- package/lib/cluster.js +703 -703
- package/lib/config-drift.js +301 -301
- package/lib/consent.js +222 -222
- package/lib/constants.js +191 -191
- package/lib/cookies.js +350 -315
- package/lib/credential-hash.js +322 -322
- package/lib/crypto.js +266 -266
- package/lib/csv.js +275 -275
- package/lib/db-declare-row-policy.js +267 -267
- package/lib/db-declare-view.js +420 -420
- package/lib/db-query.js +406 -406
- package/lib/db-schema.js +319 -319
- package/lib/db.js +1288 -1288
- package/lib/deprecate.js +222 -222
- package/lib/dev.js +335 -335
- package/lib/dual-control.js +473 -473
- package/lib/error-page.js +420 -420
- package/lib/external-db-migrate.js +441 -441
- package/lib/external-db.js +1061 -1061
- package/lib/file-type.js +273 -273
- package/lib/forms.js +422 -422
- package/lib/framework-error.js +293 -293
- package/lib/framework-schema.js +717 -717
- package/lib/handlers.js +350 -350
- package/lib/http-client-cookie-jar.js +508 -508
- package/lib/http-client.js +1195 -1195
- package/lib/i18n.js +878 -878
- package/lib/jobs.js +185 -185
- package/lib/log-stream-cloudwatch.js +369 -369
- package/lib/log-stream-local.js +146 -146
- package/lib/log-stream-otlp-grpc.js +410 -410
- package/lib/log-stream-otlp.js +286 -286
- package/lib/log-stream-syslog.js +302 -302
- package/lib/log-stream-webhook.js +199 -199
- package/lib/log-stream.js +330 -330
- package/lib/log.js +500 -500
- package/lib/mail-bounce.js +528 -528
- package/lib/mail-dkim.js +369 -369
- package/lib/mail.js +981 -981
- package/lib/metrics.js +683 -683
- package/lib/middleware/api-encrypt.js +936 -936
- package/lib/middleware/attach-user.js +157 -157
- package/lib/middleware/bearer-auth.js +152 -0
- package/lib/middleware/body-parser.js +1170 -1170
- package/lib/middleware/bot-guard.js +178 -178
- package/lib/middleware/compression.js +452 -452
- package/lib/middleware/cors.js +314 -314
- package/lib/middleware/csp-nonce.js +348 -348
- package/lib/middleware/csrf-protect.js +399 -316
- package/lib/middleware/db-role-for.js +264 -264
- package/lib/middleware/fetch-metadata.js +129 -0
- package/lib/middleware/health.js +392 -392
- package/lib/middleware/index.js +85 -79
- package/lib/middleware/rate-limit.js +358 -358
- package/lib/middleware/request-id.js +61 -61
- package/lib/middleware/request-log.js +168 -168
- package/lib/middleware/require-auth.js +104 -104
- package/lib/middleware/security-headers.js +121 -116
- package/lib/middleware/sse.js +166 -166
- package/lib/migrations.js +383 -383
- package/lib/mtls-ca.js +518 -518
- package/lib/mtls-engine-default.js +481 -481
- package/lib/network-dns.js +632 -632
- package/lib/network-heartbeat.js +290 -290
- package/lib/network-nts.js +574 -574
- package/lib/network-proxy.js +265 -265
- package/lib/network-tls.js +328 -328
- package/lib/network.js +233 -233
- package/lib/notify.js +612 -612
- package/lib/ntp-check.js +229 -229
- package/lib/numeric-bounds.js +111 -111
- package/lib/object-store/azure-blob-bucket-ops.js +349 -349
- package/lib/object-store/azure-blob.js +488 -488
- package/lib/object-store/gcs-bucket-ops.js +351 -351
- package/lib/object-store/gcs.js +519 -519
- package/lib/object-store/http-put.js +153 -153
- package/lib/object-store/index.js +197 -197
- package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
- package/lib/object-store/sigv4.js +903 -903
- package/lib/observability.js +151 -151
- package/lib/otel-export.js +269 -269
- package/lib/pagination.js +464 -464
- package/lib/parsers/index.js +80 -80
- package/lib/parsers/safe-env.js +642 -642
- package/lib/parsers/safe-ini.js +292 -292
- package/lib/parsers/safe-toml.js +784 -784
- package/lib/parsers/safe-xml.js +390 -390
- package/lib/parsers/safe-yaml.js +1015 -1015
- package/lib/permissions.js +708 -708
- package/lib/pqc-agent.js +87 -87
- package/lib/pqc-gate.js +279 -279
- package/lib/protobuf-encoder.js +190 -190
- package/lib/protocol-dispatcher.js +161 -161
- package/lib/pubsub-redis.js +167 -167
- package/lib/pubsub.js +429 -429
- package/lib/queue-local.js +476 -476
- package/lib/queue-redis.js +745 -745
- package/lib/queue-sqs.js +319 -319
- package/lib/queue.js +695 -695
- package/lib/redis-client.js +519 -519
- package/lib/request-helpers.js +340 -340
- package/lib/restore-bundle.js +237 -237
- package/lib/restore-rollback.js +259 -259
- package/lib/restore.js +409 -409
- package/lib/retry.js +376 -376
- package/lib/router.js +748 -748
- package/lib/safe-async.js +735 -735
- package/lib/safe-buffer.js +237 -237
- package/lib/safe-json.js +541 -541
- package/lib/safe-schema.js +1266 -1266
- package/lib/safe-url.js +159 -159
- package/lib/scheduler.js +706 -706
- package/lib/security-assert.js +373 -373
- package/lib/seeders.js +618 -618
- package/lib/session.js +535 -478
- package/lib/slug.js +269 -269
- package/lib/ssrf-guard.js +401 -401
- package/lib/static.js +7 -5
- package/lib/storage.js +471 -471
- package/lib/subject.js +281 -281
- package/lib/template.js +791 -791
- package/lib/testing.js +798 -798
- package/lib/time.js +310 -310
- package/lib/totp.js +302 -302
- package/lib/tracing.js +494 -494
- package/lib/uuid.js +132 -132
- package/lib/validate-opts.js +340 -340
- package/lib/vault/index.js +308 -308
- package/lib/vault/rotate.js +784 -784
- package/lib/vault/wrap.js +296 -296
- package/lib/vendor/noble-ciphers.cjs +9 -9
- package/lib/webhook.js +595 -595
- package/lib/websocket.js +1048 -1048
- package/package.json +77 -77
- package/sbom.cyclonedx.json +7 -7
package/lib/restore.js
CHANGED
|
@@ -1,409 +1,409 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* restore — operator-facing restore from a backup bundle in storage.
|
|
4
|
-
*
|
|
5
|
-
* Mirror of lib/backup. Pulls a bundle from a storage backend,
|
|
6
|
-
* decrypts it via lib/restore-bundle into a staging directory, then
|
|
7
|
-
* swaps that staging into place as the new dataDir via
|
|
8
|
-
* lib/restore-rollback (saving the previous dataDir as a versioned
|
|
9
|
-
* rollback point). Operators stop the framework first, run restore,
|
|
10
|
-
* then start the framework — same workflow as a database restore.
|
|
11
|
-
*
|
|
12
|
-
* var restore = b.restore.create({
|
|
13
|
-
* dataDir: "./data",
|
|
14
|
-
* storage: b.backup.localStorage({ root: "./backups" }),
|
|
15
|
-
* passphrase: Buffer.from("operator backup passphrase"),
|
|
16
|
-
* rollbackRoot: "./data.rollbacks", // optional; default <dataDir>.rollbacks
|
|
17
|
-
* audit: true,
|
|
18
|
-
* });
|
|
19
|
-
*
|
|
20
|
-
* await restore.list(); // → [{ bundleId, createdAt, size }]
|
|
21
|
-
* await restore.inspect(bundleId); // → manifest (no decrypt; no passphrase
|
|
22
|
-
* // needed for inspect)
|
|
23
|
-
*
|
|
24
|
-
* await restore.run({
|
|
25
|
-
* bundleId,
|
|
26
|
-
* filter, // optional file filter
|
|
27
|
-
* marker: { reason: "incident-2026-04-27" },
|
|
28
|
-
* });
|
|
29
|
-
* // → { bundleId, fileCount, totalBytes, rollbackPath, vaultKeyJson,
|
|
30
|
-
* // durationMs }
|
|
31
|
-
*
|
|
32
|
-
* await restore.rollback(); // → reverts the most recent restore
|
|
33
|
-
* await restore.listRollbacks(); // → [{ rollbackPath, swappedAt, marker }]
|
|
34
|
-
* await restore.purgeRollbacks({ keep });
|
|
35
|
-
*
|
|
36
|
-
* vaultKeyJson: the manifest's vaultKeyEnc decrypted via the passphrase,
|
|
37
|
-
* returned to the caller as a string. Returned but NOT auto-installed —
|
|
38
|
-
* the caller decides what to do with it (the swap may have already put
|
|
39
|
-
* the bundle's vault.key file into place if the bundle included one;
|
|
40
|
-
* operators with vault-passphrase-wrapped setups handle the placement
|
|
41
|
-
* themselves before re-starting the framework).
|
|
42
|
-
*
|
|
43
|
-
* Failure modes (each cleans up the tmp pull dir + staging dir):
|
|
44
|
-
* - bundle not in storage → restore/bundle-not-found
|
|
45
|
-
* - manifest absent / bad → restore/missing-manifest
|
|
46
|
-
* - wrong passphrase → restore/decrypt-failed
|
|
47
|
-
* - tampered blob → restore/decrypt-failed (AEAD tag check)
|
|
48
|
-
* - checksum mismatch → restore/checksum-mismatch
|
|
49
|
-
* - swap fails after extract → restore/swap-failed (staging is
|
|
50
|
-
* preserved at the path returned in error.stagingDir for operator
|
|
51
|
-
* manual recovery)
|
|
52
|
-
*/
|
|
53
|
-
|
|
54
|
-
var fs = require("fs");
|
|
55
|
-
var os = require("os");
|
|
56
|
-
var path = require("path");
|
|
57
|
-
var C = require("./constants");
|
|
58
|
-
var crypto = require("./crypto");
|
|
59
|
-
var numericChecks = require("./numeric-checks");
|
|
60
|
-
var restoreBundle = require("./restore-bundle");
|
|
61
|
-
var restoreRollback = require("./restore-rollback");
|
|
62
|
-
var lazyRequire = require("./lazy-require");
|
|
63
|
-
var validateOpts = require("./validate-opts");
|
|
64
|
-
var audit = lazyRequire(function () { return require("./audit"); });
|
|
65
|
-
var { FrameworkError } = require("./framework-error");
|
|
66
|
-
|
|
67
|
-
class RestoreError extends FrameworkError {
|
|
68
|
-
constructor(code, message, permanent) {
|
|
69
|
-
super(message, code);
|
|
70
|
-
this.name = "RestoreError";
|
|
71
|
-
this.permanent = !!permanent;
|
|
72
|
-
this.isRestoreError = true;
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function _validateStorage(storage) {
|
|
77
|
-
if (!storage || typeof storage !== "object") {
|
|
78
|
-
throw new RestoreError("restore/bad-storage",
|
|
79
|
-
"storage backend is required (use b.backup.localStorage or pass a custom one)");
|
|
80
|
-
}
|
|
81
|
-
var required = ["readBundle", "listBundles", "hasBundle"];
|
|
82
|
-
for (var i = 0; i < required.length; i++) {
|
|
83
|
-
if (typeof storage[required[i]] !== "function") {
|
|
84
|
-
throw new RestoreError("restore/bad-storage",
|
|
85
|
-
"storage backend missing method '" + required[i] + "'");
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
function create(opts) {
|
|
91
|
-
opts = opts || {};
|
|
92
|
-
validateOpts(opts, [
|
|
93
|
-
"dataDir", "storage", "passphrase", "rollbackRoot", "audit",
|
|
94
|
-
"maxPulledBytes", "maxPulledFiles",
|
|
95
|
-
], "restore");
|
|
96
|
-
validateOpts.requireNonEmptyString(opts.dataDir, "create: opts.dataDir", RestoreError, "restore/no-datadir");
|
|
97
|
-
_validateStorage(opts.storage);
|
|
98
|
-
if (!Buffer.isBuffer(opts.passphrase) && typeof opts.passphrase !== "string") {
|
|
99
|
-
throw new RestoreError("restore/no-passphrase",
|
|
100
|
-
"create: opts.passphrase is required (Buffer or string)");
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
var dataDir = opts.dataDir;
|
|
104
|
-
var storage = opts.storage;
|
|
105
|
-
var passphrase = opts.passphrase;
|
|
106
|
-
var rollbackRoot = opts.rollbackRoot || (dataDir + ".rollbacks");
|
|
107
|
-
var auditOn = opts.audit !== false;
|
|
108
|
-
|
|
109
|
-
// Preflight footprint caps. Defended against storage that returns a
|
|
110
|
-
// tampered or oversized bundle: we cap both the storage-reported size
|
|
111
|
-
// (cheap, before pull) AND the actually-pulled bytes/file-count
|
|
112
|
-
// (defense-in-depth in case the backend lied). Default 4 GiB / 100K
|
|
113
|
-
// files keeps the small-bundle path uncapped while bounding the
|
|
114
|
-
// pathological case.
|
|
115
|
-
// Default file-count cap = 0x186A0 (100,000). Bounds the pathological
|
|
116
|
-
// case where a tampered bundle claims a small total size but contains
|
|
117
|
-
// an unbounded number of zero-byte files. Operators with large bundles
|
|
118
|
-
// override.
|
|
119
|
-
var DEFAULT_MAX_PULLED_FILES = 0x186A0;
|
|
120
|
-
var maxPulledBytes = numericChecks.isPositiveFinite(opts.maxPulledBytes)
|
|
121
|
-
? opts.maxPulledBytes : C.BYTES.gib(4);
|
|
122
|
-
var maxPulledFiles = numericChecks.isPositiveInt(opts.maxPulledFiles)
|
|
123
|
-
? opts.maxPulledFiles : DEFAULT_MAX_PULLED_FILES;
|
|
124
|
-
|
|
125
|
-
function _walkPullDirFootprint(dir) {
|
|
126
|
-
var totalBytes = 0, fileCount = 0;
|
|
127
|
-
var stack = [dir];
|
|
128
|
-
while (stack.length > 0) {
|
|
129
|
-
var current = stack.pop();
|
|
130
|
-
var entries;
|
|
131
|
-
try { entries = fs.readdirSync(current, { withFileTypes: true }); }
|
|
132
|
-
catch (_e) { continue; }
|
|
133
|
-
for (var i = 0; i < entries.length; i++) {
|
|
134
|
-
var entry = entries[i];
|
|
135
|
-
var full = path.join(current, entry.name);
|
|
136
|
-
if (entry.isDirectory()) {
|
|
137
|
-
stack.push(full);
|
|
138
|
-
} else if (entry.isFile()) {
|
|
139
|
-
fileCount++;
|
|
140
|
-
if (fileCount > maxPulledFiles) {
|
|
141
|
-
return { tooManyFiles: true, fileCount: fileCount };
|
|
142
|
-
}
|
|
143
|
-
try {
|
|
144
|
-
totalBytes += fs.statSync(full).size;
|
|
145
|
-
if (totalBytes > maxPulledBytes) {
|
|
146
|
-
return { tooManyBytes: true, totalBytes: totalBytes };
|
|
147
|
-
}
|
|
148
|
-
} catch (_e) { /* file vanished mid-walk */ }
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
return { totalBytes: totalBytes, fileCount: fileCount };
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
function _emitAudit(action, info, outcome) {
|
|
156
|
-
if (!auditOn) return;
|
|
157
|
-
audit().safeEmit({
|
|
158
|
-
action: action,
|
|
159
|
-
outcome: outcome,
|
|
160
|
-
metadata: info || {},
|
|
161
|
-
reason: info && info.reason ? info.reason : null,
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async function list() { return await storage.listBundles(); }
|
|
166
|
-
|
|
167
|
-
// Find a bundle in storage.listBundles() output and check its
|
|
168
|
-
// reported size against maxPulledBytes BEFORE pulling. listBundles()
|
|
169
|
-
// returns the storage-reported size; cheap to scan and rejects an
|
|
170
|
-
// oversized object before any bytes hit local disk. Returns the
|
|
171
|
-
// bundle metadata when within bounds, throws when oversized, returns
|
|
172
|
-
// null when listBundles doesn't surface the bundle (e.g. listing is
|
|
173
|
-
// truncated by the backend).
|
|
174
|
-
async function _preflightBundleSize(bundleId) {
|
|
175
|
-
var listed;
|
|
176
|
-
try { listed = await storage.listBundles(); }
|
|
177
|
-
catch (_e) { return null; }
|
|
178
|
-
if (!Array.isArray(listed)) return null;
|
|
179
|
-
for (var i = 0; i < listed.length; i++) {
|
|
180
|
-
var entry = listed[i];
|
|
181
|
-
if (entry && entry.bundleId === bundleId) {
|
|
182
|
-
if (typeof entry.size === "number" && entry.size > maxPulledBytes) {
|
|
183
|
-
throw new RestoreError("restore/bundle-too-large",
|
|
184
|
-
"bundle '" + bundleId + "' reports size " + entry.size +
|
|
185
|
-
" bytes, exceeds maxPulledBytes " + maxPulledBytes);
|
|
186
|
-
}
|
|
187
|
-
return entry;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
return null;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
async function inspect(bundleId) {
|
|
194
|
-
if (typeof bundleId !== "string" || bundleId.length === 0) {
|
|
195
|
-
throw new RestoreError("restore/bad-bundle-id", "inspect: bundleId is required");
|
|
196
|
-
}
|
|
197
|
-
var has = await storage.hasBundle(bundleId);
|
|
198
|
-
if (!has) {
|
|
199
|
-
throw new RestoreError("restore/bundle-not-found",
|
|
200
|
-
"inspect: bundle '" + bundleId + "' not in storage");
|
|
201
|
-
}
|
|
202
|
-
await _preflightBundleSize(bundleId);
|
|
203
|
-
var pullDir = path.join(os.tmpdir(),
|
|
204
|
-
"blamejs-restore-inspect-" + crypto.generateToken(4));
|
|
205
|
-
try {
|
|
206
|
-
await storage.readBundle(bundleId, pullDir);
|
|
207
|
-
var pulled = _walkPullDirFootprint(pullDir);
|
|
208
|
-
if (pulled.tooManyBytes) {
|
|
209
|
-
throw new RestoreError("restore/pulled-too-large",
|
|
210
|
-
"bundle '" + bundleId + "' pulled " + pulled.totalBytes +
|
|
211
|
-
" bytes (caught mid-pull), exceeds maxPulledBytes " + maxPulledBytes);
|
|
212
|
-
}
|
|
213
|
-
if (pulled.tooManyFiles) {
|
|
214
|
-
throw new RestoreError("restore/pulled-too-many-files",
|
|
215
|
-
"bundle '" + bundleId + "' pulled " + pulled.fileCount +
|
|
216
|
-
" files, exceeds maxPulledFiles " + maxPulledFiles);
|
|
217
|
-
}
|
|
218
|
-
return restoreBundle.inspect({ bundleDir: pullDir });
|
|
219
|
-
} finally {
|
|
220
|
-
try { fs.rmSync(pullDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
async function run(runOpts) {
|
|
225
|
-
runOpts = runOpts || {};
|
|
226
|
-
var t0 = Date.now();
|
|
227
|
-
var bundleId = runOpts.bundleId;
|
|
228
|
-
if (typeof bundleId !== "string" || bundleId.length === 0) {
|
|
229
|
-
throw new RestoreError("restore/bad-bundle-id", "run: opts.bundleId is required");
|
|
230
|
-
}
|
|
231
|
-
var has = await storage.hasBundle(bundleId);
|
|
232
|
-
if (!has) {
|
|
233
|
-
throw new RestoreError("restore/bundle-not-found",
|
|
234
|
-
"run: bundle '" + bundleId + "' not in storage");
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
var pullId = crypto.generateToken(4);
|
|
238
|
-
var pullDir = path.join(os.tmpdir(), "blamejs-restore-pull-" + pullId);
|
|
239
|
-
var stagingDir = path.join(os.tmpdir(), "blamejs-restore-staging-" + pullId);
|
|
240
|
-
|
|
241
|
-
function _cleanupTmp() {
|
|
242
|
-
try { fs.rmSync(pullDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
243
|
-
try { fs.rmSync(stagingDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
// 1. Pull bundle out of storage
|
|
247
|
-
// Preflight: reject an oversized bundle BEFORE pulling bytes to
|
|
248
|
-
// disk. Cheap when the backend lists size; no-op when it doesn't.
|
|
249
|
-
try {
|
|
250
|
-
await _preflightBundleSize(bundleId);
|
|
251
|
-
} catch (e) {
|
|
252
|
-
_cleanupTmp();
|
|
253
|
-
_emitAudit("restore.failure",
|
|
254
|
-
{ bundleId: bundleId, reason: (e && e.message) || String(e) },
|
|
255
|
-
"failure");
|
|
256
|
-
throw e;
|
|
257
|
-
}
|
|
258
|
-
try {
|
|
259
|
-
await storage.readBundle(bundleId, pullDir);
|
|
260
|
-
} catch (e) {
|
|
261
|
-
_cleanupTmp();
|
|
262
|
-
_emitAudit("restore.failure",
|
|
263
|
-
{ bundleId: bundleId, reason: "storage.readBundle: " + ((e && e.message) || String(e)) },
|
|
264
|
-
"failure");
|
|
265
|
-
throw new RestoreError("restore/storage-read-failed",
|
|
266
|
-
"pulling bundle from storage failed: " + ((e && e.message) || String(e)));
|
|
267
|
-
}
|
|
268
|
-
// Defense-in-depth: walk the pulled bundle and re-check footprint.
|
|
269
|
-
// Catches a backend that under-reported size in listBundles or that
|
|
270
|
-
// doesn't surface size at all.
|
|
271
|
-
var pulled = _walkPullDirFootprint(pullDir);
|
|
272
|
-
if (pulled.tooManyBytes || pulled.tooManyFiles) {
|
|
273
|
-
_cleanupTmp();
|
|
274
|
-
var capCode = pulled.tooManyBytes ? "restore/pulled-too-large" : "restore/pulled-too-many-files";
|
|
275
|
-
var capMsg = pulled.tooManyBytes
|
|
276
|
-
? "bundle '" + bundleId + "' pulled " + pulled.totalBytes + " bytes, exceeds maxPulledBytes " + maxPulledBytes
|
|
277
|
-
: "bundle '" + bundleId + "' pulled " + pulled.fileCount + " files, exceeds maxPulledFiles " + maxPulledFiles;
|
|
278
|
-
_emitAudit("restore.failure", { bundleId: bundleId, reason: capMsg }, "failure");
|
|
279
|
-
throw new RestoreError(capCode, capMsg);
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
// 2. Decrypt + verify into stagingDir
|
|
283
|
-
var extracted;
|
|
284
|
-
try {
|
|
285
|
-
extracted = await restoreBundle.extract({
|
|
286
|
-
bundleDir: pullDir,
|
|
287
|
-
stagingDir: stagingDir,
|
|
288
|
-
passphrase: passphrase,
|
|
289
|
-
filter: runOpts.filter,
|
|
290
|
-
progressCallback: runOpts.progressCallback,
|
|
291
|
-
});
|
|
292
|
-
} catch (e) {
|
|
293
|
-
_cleanupTmp();
|
|
294
|
-
// Map restore-bundle error codes to restore/* domain so consumer
|
|
295
|
-
// code sees a single error namespace
|
|
296
|
-
var code = e && e.code;
|
|
297
|
-
var mappedCode = "restore/extract-failed";
|
|
298
|
-
if (code === "restore-bundle/decrypt-failed") mappedCode = "restore/decrypt-failed";
|
|
299
|
-
else if (code === "restore-bundle/checksum-mismatch") mappedCode = "restore/checksum-mismatch";
|
|
300
|
-
else if (code === "restore-bundle/missing-manifest") mappedCode = "restore/missing-manifest";
|
|
301
|
-
else if (code === "restore-bundle/missing-blob") mappedCode = "restore/missing-blob";
|
|
302
|
-
else if (code === "restore-bundle/size-mismatch") mappedCode = "restore/size-mismatch";
|
|
303
|
-
_emitAudit("restore.failure",
|
|
304
|
-
{ bundleId: bundleId, reason: (e && e.message) || String(e) }, "failure");
|
|
305
|
-
throw new RestoreError(mappedCode,
|
|
306
|
-
"extract failed: " + ((e && e.message) || String(e)));
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// 3. Atomic swap. On swap failure, the stagingDir is preserved so
|
|
310
|
-
// an operator can recover manually — we do NOT delete it here.
|
|
311
|
-
var swapResult;
|
|
312
|
-
try {
|
|
313
|
-
swapResult = restoreRollback.swap({
|
|
314
|
-
stagingDir: stagingDir,
|
|
315
|
-
dataDir: dataDir,
|
|
316
|
-
rollbackRoot: rollbackRoot,
|
|
317
|
-
marker: Object.assign({ bundleId: bundleId }, runOpts.marker || {}),
|
|
318
|
-
});
|
|
319
|
-
} catch (e) {
|
|
320
|
-
// Pull dir is safe to clean (the source bundle is in storage);
|
|
321
|
-
// staging stays for manual recovery.
|
|
322
|
-
try { fs.rmSync(pullDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
323
|
-
_emitAudit("restore.failure",
|
|
324
|
-
{ bundleId: bundleId, reason: "swap: " + ((e && e.message) || String(e)) },
|
|
325
|
-
"failure");
|
|
326
|
-
var err = new RestoreError("restore/swap-failed",
|
|
327
|
-
"atomic swap failed after successful extract — staging preserved at " +
|
|
328
|
-
stagingDir + ": " + ((e && e.message) || String(e)));
|
|
329
|
-
err.stagingDir = stagingDir;
|
|
330
|
-
throw err;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// 4. Clean up the pull dir (source bundle still in storage)
|
|
334
|
-
try { fs.rmSync(pullDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
335
|
-
|
|
336
|
-
var summary = {
|
|
337
|
-
bundleId: bundleId,
|
|
338
|
-
fileCount: extracted.fileCount,
|
|
339
|
-
totalBytes: extracted.totalBytes,
|
|
340
|
-
rollbackPath: swapResult.rollbackPath,
|
|
341
|
-
vaultKeyJson: extracted.vaultKeyJson,
|
|
342
|
-
durationMs: Date.now() - t0,
|
|
343
|
-
};
|
|
344
|
-
_emitAudit("restore.success", {
|
|
345
|
-
bundleId: bundleId,
|
|
346
|
-
fileCount: extracted.fileCount,
|
|
347
|
-
totalBytes: extracted.totalBytes,
|
|
348
|
-
rollbackPath: swapResult.rollbackPath,
|
|
349
|
-
durationMs: summary.durationMs,
|
|
350
|
-
});
|
|
351
|
-
return summary;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
async function rollback(rollbackOpts) {
|
|
355
|
-
rollbackOpts = rollbackOpts || {};
|
|
356
|
-
// Either an explicit rollbackPath OR pull the most-recent one
|
|
357
|
-
var target = rollbackOpts.rollbackPath;
|
|
358
|
-
if (!target) {
|
|
359
|
-
var bundles = restoreRollback.list({ rollbackRoot: rollbackRoot });
|
|
360
|
-
if (bundles.length === 0) {
|
|
361
|
-
throw new RestoreError("restore/no-rollbacks",
|
|
362
|
-
"rollback: no rollback points found at " + rollbackRoot);
|
|
363
|
-
}
|
|
364
|
-
target = bundles[0].rollbackPath;
|
|
365
|
-
}
|
|
366
|
-
var r;
|
|
367
|
-
try {
|
|
368
|
-
r = await restoreRollback.rollback({
|
|
369
|
-
dataDir: dataDir,
|
|
370
|
-
rollbackPath: target,
|
|
371
|
-
rollbackRoot: rollbackRoot,
|
|
372
|
-
});
|
|
373
|
-
} catch (e) {
|
|
374
|
-
_emitAudit("restore.rollback.failure",
|
|
375
|
-
{ rollbackPath: target, reason: (e && e.message) || String(e) }, "failure");
|
|
376
|
-
throw new RestoreError("restore/rollback-failed",
|
|
377
|
-
"rollback failed: " + ((e && e.message) || String(e)));
|
|
378
|
-
}
|
|
379
|
-
_emitAudit("restore.rollback.success",
|
|
380
|
-
{ rollbackPath: target, discardedAt: r.discardedAt });
|
|
381
|
-
return r;
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
function listRollbacks() {
|
|
385
|
-
return restoreRollback.list({ rollbackRoot: rollbackRoot });
|
|
386
|
-
}
|
|
387
|
-
function purgeRollbacks(purgeOpts) {
|
|
388
|
-
return restoreRollback.purge({
|
|
389
|
-
rollbackRoot: rollbackRoot,
|
|
390
|
-
keep: (purgeOpts && purgeOpts.keep) || 0,
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
return {
|
|
395
|
-
list: list,
|
|
396
|
-
inspect: inspect,
|
|
397
|
-
run: run,
|
|
398
|
-
rollback: rollback,
|
|
399
|
-
listRollbacks: listRollbacks,
|
|
400
|
-
purgeRollbacks: purgeRollbacks,
|
|
401
|
-
storage: storage,
|
|
402
|
-
rollbackRoot: rollbackRoot,
|
|
403
|
-
};
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
module.exports = {
|
|
407
|
-
create: create,
|
|
408
|
-
RestoreError: RestoreError,
|
|
409
|
-
};
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* restore — operator-facing restore from a backup bundle in storage.
|
|
4
|
+
*
|
|
5
|
+
* Mirror of lib/backup. Pulls a bundle from a storage backend,
|
|
6
|
+
* decrypts it via lib/restore-bundle into a staging directory, then
|
|
7
|
+
* swaps that staging into place as the new dataDir via
|
|
8
|
+
* lib/restore-rollback (saving the previous dataDir as a versioned
|
|
9
|
+
* rollback point). Operators stop the framework first, run restore,
|
|
10
|
+
* then start the framework — same workflow as a database restore.
|
|
11
|
+
*
|
|
12
|
+
* var restore = b.restore.create({
|
|
13
|
+
* dataDir: "./data",
|
|
14
|
+
* storage: b.backup.localStorage({ root: "./backups" }),
|
|
15
|
+
* passphrase: Buffer.from("operator backup passphrase"),
|
|
16
|
+
* rollbackRoot: "./data.rollbacks", // optional; default <dataDir>.rollbacks
|
|
17
|
+
* audit: true,
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* await restore.list(); // → [{ bundleId, createdAt, size }]
|
|
21
|
+
* await restore.inspect(bundleId); // → manifest (no decrypt; no passphrase
|
|
22
|
+
* // needed for inspect)
|
|
23
|
+
*
|
|
24
|
+
* await restore.run({
|
|
25
|
+
* bundleId,
|
|
26
|
+
* filter, // optional file filter
|
|
27
|
+
* marker: { reason: "incident-2026-04-27" },
|
|
28
|
+
* });
|
|
29
|
+
* // → { bundleId, fileCount, totalBytes, rollbackPath, vaultKeyJson,
|
|
30
|
+
* // durationMs }
|
|
31
|
+
*
|
|
32
|
+
* await restore.rollback(); // → reverts the most recent restore
|
|
33
|
+
* await restore.listRollbacks(); // → [{ rollbackPath, swappedAt, marker }]
|
|
34
|
+
* await restore.purgeRollbacks({ keep });
|
|
35
|
+
*
|
|
36
|
+
* vaultKeyJson: the manifest's vaultKeyEnc decrypted via the passphrase,
|
|
37
|
+
* returned to the caller as a string. Returned but NOT auto-installed —
|
|
38
|
+
* the caller decides what to do with it (the swap may have already put
|
|
39
|
+
* the bundle's vault.key file into place if the bundle included one;
|
|
40
|
+
* operators with vault-passphrase-wrapped setups handle the placement
|
|
41
|
+
* themselves before re-starting the framework).
|
|
42
|
+
*
|
|
43
|
+
* Failure modes (each cleans up the tmp pull dir + staging dir):
|
|
44
|
+
* - bundle not in storage → restore/bundle-not-found
|
|
45
|
+
* - manifest absent / bad → restore/missing-manifest
|
|
46
|
+
* - wrong passphrase → restore/decrypt-failed
|
|
47
|
+
* - tampered blob → restore/decrypt-failed (AEAD tag check)
|
|
48
|
+
* - checksum mismatch → restore/checksum-mismatch
|
|
49
|
+
* - swap fails after extract → restore/swap-failed (staging is
|
|
50
|
+
* preserved at the path returned in error.stagingDir for operator
|
|
51
|
+
* manual recovery)
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
var fs = require("fs");
|
|
55
|
+
var os = require("os");
|
|
56
|
+
var path = require("path");
|
|
57
|
+
var C = require("./constants");
|
|
58
|
+
var crypto = require("./crypto");
|
|
59
|
+
var numericChecks = require("./numeric-checks");
|
|
60
|
+
var restoreBundle = require("./restore-bundle");
|
|
61
|
+
var restoreRollback = require("./restore-rollback");
|
|
62
|
+
var lazyRequire = require("./lazy-require");
|
|
63
|
+
var validateOpts = require("./validate-opts");
|
|
64
|
+
var audit = lazyRequire(function () { return require("./audit"); });
|
|
65
|
+
var { FrameworkError } = require("./framework-error");
|
|
66
|
+
|
|
67
|
+
class RestoreError extends FrameworkError {
|
|
68
|
+
constructor(code, message, permanent) {
|
|
69
|
+
super(message, code);
|
|
70
|
+
this.name = "RestoreError";
|
|
71
|
+
this.permanent = !!permanent;
|
|
72
|
+
this.isRestoreError = true;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function _validateStorage(storage) {
|
|
77
|
+
if (!storage || typeof storage !== "object") {
|
|
78
|
+
throw new RestoreError("restore/bad-storage",
|
|
79
|
+
"storage backend is required (use b.backup.localStorage or pass a custom one)");
|
|
80
|
+
}
|
|
81
|
+
var required = ["readBundle", "listBundles", "hasBundle"];
|
|
82
|
+
for (var i = 0; i < required.length; i++) {
|
|
83
|
+
if (typeof storage[required[i]] !== "function") {
|
|
84
|
+
throw new RestoreError("restore/bad-storage",
|
|
85
|
+
"storage backend missing method '" + required[i] + "'");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function create(opts) {
|
|
91
|
+
opts = opts || {};
|
|
92
|
+
validateOpts(opts, [
|
|
93
|
+
"dataDir", "storage", "passphrase", "rollbackRoot", "audit",
|
|
94
|
+
"maxPulledBytes", "maxPulledFiles",
|
|
95
|
+
], "restore");
|
|
96
|
+
validateOpts.requireNonEmptyString(opts.dataDir, "create: opts.dataDir", RestoreError, "restore/no-datadir");
|
|
97
|
+
_validateStorage(opts.storage);
|
|
98
|
+
if (!Buffer.isBuffer(opts.passphrase) && typeof opts.passphrase !== "string") {
|
|
99
|
+
throw new RestoreError("restore/no-passphrase",
|
|
100
|
+
"create: opts.passphrase is required (Buffer or string)");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
var dataDir = opts.dataDir;
|
|
104
|
+
var storage = opts.storage;
|
|
105
|
+
var passphrase = opts.passphrase;
|
|
106
|
+
var rollbackRoot = opts.rollbackRoot || (dataDir + ".rollbacks");
|
|
107
|
+
var auditOn = opts.audit !== false;
|
|
108
|
+
|
|
109
|
+
// Preflight footprint caps. Defended against storage that returns a
|
|
110
|
+
// tampered or oversized bundle: we cap both the storage-reported size
|
|
111
|
+
// (cheap, before pull) AND the actually-pulled bytes/file-count
|
|
112
|
+
// (defense-in-depth in case the backend lied). Default 4 GiB / 100K
|
|
113
|
+
// files keeps the small-bundle path uncapped while bounding the
|
|
114
|
+
// pathological case.
|
|
115
|
+
// Default file-count cap = 0x186A0 (100,000). Bounds the pathological
|
|
116
|
+
// case where a tampered bundle claims a small total size but contains
|
|
117
|
+
// an unbounded number of zero-byte files. Operators with large bundles
|
|
118
|
+
// override.
|
|
119
|
+
var DEFAULT_MAX_PULLED_FILES = 0x186A0;
|
|
120
|
+
var maxPulledBytes = numericChecks.isPositiveFinite(opts.maxPulledBytes)
|
|
121
|
+
? opts.maxPulledBytes : C.BYTES.gib(4);
|
|
122
|
+
var maxPulledFiles = numericChecks.isPositiveInt(opts.maxPulledFiles)
|
|
123
|
+
? opts.maxPulledFiles : DEFAULT_MAX_PULLED_FILES;
|
|
124
|
+
|
|
125
|
+
function _walkPullDirFootprint(dir) {
|
|
126
|
+
var totalBytes = 0, fileCount = 0;
|
|
127
|
+
var stack = [dir];
|
|
128
|
+
while (stack.length > 0) {
|
|
129
|
+
var current = stack.pop();
|
|
130
|
+
var entries;
|
|
131
|
+
try { entries = fs.readdirSync(current, { withFileTypes: true }); }
|
|
132
|
+
catch (_e) { continue; }
|
|
133
|
+
for (var i = 0; i < entries.length; i++) {
|
|
134
|
+
var entry = entries[i];
|
|
135
|
+
var full = path.join(current, entry.name);
|
|
136
|
+
if (entry.isDirectory()) {
|
|
137
|
+
stack.push(full);
|
|
138
|
+
} else if (entry.isFile()) {
|
|
139
|
+
fileCount++;
|
|
140
|
+
if (fileCount > maxPulledFiles) {
|
|
141
|
+
return { tooManyFiles: true, fileCount: fileCount };
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
totalBytes += fs.statSync(full).size;
|
|
145
|
+
if (totalBytes > maxPulledBytes) {
|
|
146
|
+
return { tooManyBytes: true, totalBytes: totalBytes };
|
|
147
|
+
}
|
|
148
|
+
} catch (_e) { /* file vanished mid-walk */ }
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { totalBytes: totalBytes, fileCount: fileCount };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function _emitAudit(action, info, outcome) {
|
|
156
|
+
if (!auditOn) return;
|
|
157
|
+
audit().safeEmit({
|
|
158
|
+
action: action,
|
|
159
|
+
outcome: outcome,
|
|
160
|
+
metadata: info || {},
|
|
161
|
+
reason: info && info.reason ? info.reason : null,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function list() { return await storage.listBundles(); }
|
|
166
|
+
|
|
167
|
+
// Find a bundle in storage.listBundles() output and check its
|
|
168
|
+
// reported size against maxPulledBytes BEFORE pulling. listBundles()
|
|
169
|
+
// returns the storage-reported size; cheap to scan and rejects an
|
|
170
|
+
// oversized object before any bytes hit local disk. Returns the
|
|
171
|
+
// bundle metadata when within bounds, throws when oversized, returns
|
|
172
|
+
// null when listBundles doesn't surface the bundle (e.g. listing is
|
|
173
|
+
// truncated by the backend).
|
|
174
|
+
async function _preflightBundleSize(bundleId) {
|
|
175
|
+
var listed;
|
|
176
|
+
try { listed = await storage.listBundles(); }
|
|
177
|
+
catch (_e) { return null; }
|
|
178
|
+
if (!Array.isArray(listed)) return null;
|
|
179
|
+
for (var i = 0; i < listed.length; i++) {
|
|
180
|
+
var entry = listed[i];
|
|
181
|
+
if (entry && entry.bundleId === bundleId) {
|
|
182
|
+
if (typeof entry.size === "number" && entry.size > maxPulledBytes) {
|
|
183
|
+
throw new RestoreError("restore/bundle-too-large",
|
|
184
|
+
"bundle '" + bundleId + "' reports size " + entry.size +
|
|
185
|
+
" bytes, exceeds maxPulledBytes " + maxPulledBytes);
|
|
186
|
+
}
|
|
187
|
+
return entry;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function inspect(bundleId) {
|
|
194
|
+
if (typeof bundleId !== "string" || bundleId.length === 0) {
|
|
195
|
+
throw new RestoreError("restore/bad-bundle-id", "inspect: bundleId is required");
|
|
196
|
+
}
|
|
197
|
+
var has = await storage.hasBundle(bundleId);
|
|
198
|
+
if (!has) {
|
|
199
|
+
throw new RestoreError("restore/bundle-not-found",
|
|
200
|
+
"inspect: bundle '" + bundleId + "' not in storage");
|
|
201
|
+
}
|
|
202
|
+
await _preflightBundleSize(bundleId);
|
|
203
|
+
var pullDir = path.join(os.tmpdir(),
|
|
204
|
+
"blamejs-restore-inspect-" + crypto.generateToken(4));
|
|
205
|
+
try {
|
|
206
|
+
await storage.readBundle(bundleId, pullDir);
|
|
207
|
+
var pulled = _walkPullDirFootprint(pullDir);
|
|
208
|
+
if (pulled.tooManyBytes) {
|
|
209
|
+
throw new RestoreError("restore/pulled-too-large",
|
|
210
|
+
"bundle '" + bundleId + "' pulled " + pulled.totalBytes +
|
|
211
|
+
" bytes (caught mid-pull), exceeds maxPulledBytes " + maxPulledBytes);
|
|
212
|
+
}
|
|
213
|
+
if (pulled.tooManyFiles) {
|
|
214
|
+
throw new RestoreError("restore/pulled-too-many-files",
|
|
215
|
+
"bundle '" + bundleId + "' pulled " + pulled.fileCount +
|
|
216
|
+
" files, exceeds maxPulledFiles " + maxPulledFiles);
|
|
217
|
+
}
|
|
218
|
+
return restoreBundle.inspect({ bundleDir: pullDir });
|
|
219
|
+
} finally {
|
|
220
|
+
try { fs.rmSync(pullDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function run(runOpts) {
|
|
225
|
+
runOpts = runOpts || {};
|
|
226
|
+
var t0 = Date.now();
|
|
227
|
+
var bundleId = runOpts.bundleId;
|
|
228
|
+
if (typeof bundleId !== "string" || bundleId.length === 0) {
|
|
229
|
+
throw new RestoreError("restore/bad-bundle-id", "run: opts.bundleId is required");
|
|
230
|
+
}
|
|
231
|
+
var has = await storage.hasBundle(bundleId);
|
|
232
|
+
if (!has) {
|
|
233
|
+
throw new RestoreError("restore/bundle-not-found",
|
|
234
|
+
"run: bundle '" + bundleId + "' not in storage");
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
var pullId = crypto.generateToken(4);
|
|
238
|
+
var pullDir = path.join(os.tmpdir(), "blamejs-restore-pull-" + pullId);
|
|
239
|
+
var stagingDir = path.join(os.tmpdir(), "blamejs-restore-staging-" + pullId);
|
|
240
|
+
|
|
241
|
+
function _cleanupTmp() {
|
|
242
|
+
try { fs.rmSync(pullDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
243
|
+
try { fs.rmSync(stagingDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// 1. Pull bundle out of storage
|
|
247
|
+
// Preflight: reject an oversized bundle BEFORE pulling bytes to
|
|
248
|
+
// disk. Cheap when the backend lists size; no-op when it doesn't.
|
|
249
|
+
try {
|
|
250
|
+
await _preflightBundleSize(bundleId);
|
|
251
|
+
} catch (e) {
|
|
252
|
+
_cleanupTmp();
|
|
253
|
+
_emitAudit("restore.failure",
|
|
254
|
+
{ bundleId: bundleId, reason: (e && e.message) || String(e) },
|
|
255
|
+
"failure");
|
|
256
|
+
throw e;
|
|
257
|
+
}
|
|
258
|
+
try {
|
|
259
|
+
await storage.readBundle(bundleId, pullDir);
|
|
260
|
+
} catch (e) {
|
|
261
|
+
_cleanupTmp();
|
|
262
|
+
_emitAudit("restore.failure",
|
|
263
|
+
{ bundleId: bundleId, reason: "storage.readBundle: " + ((e && e.message) || String(e)) },
|
|
264
|
+
"failure");
|
|
265
|
+
throw new RestoreError("restore/storage-read-failed",
|
|
266
|
+
"pulling bundle from storage failed: " + ((e && e.message) || String(e)));
|
|
267
|
+
}
|
|
268
|
+
// Defense-in-depth: walk the pulled bundle and re-check footprint.
|
|
269
|
+
// Catches a backend that under-reported size in listBundles or that
|
|
270
|
+
// doesn't surface size at all.
|
|
271
|
+
var pulled = _walkPullDirFootprint(pullDir);
|
|
272
|
+
if (pulled.tooManyBytes || pulled.tooManyFiles) {
|
|
273
|
+
_cleanupTmp();
|
|
274
|
+
var capCode = pulled.tooManyBytes ? "restore/pulled-too-large" : "restore/pulled-too-many-files";
|
|
275
|
+
var capMsg = pulled.tooManyBytes
|
|
276
|
+
? "bundle '" + bundleId + "' pulled " + pulled.totalBytes + " bytes, exceeds maxPulledBytes " + maxPulledBytes
|
|
277
|
+
: "bundle '" + bundleId + "' pulled " + pulled.fileCount + " files, exceeds maxPulledFiles " + maxPulledFiles;
|
|
278
|
+
_emitAudit("restore.failure", { bundleId: bundleId, reason: capMsg }, "failure");
|
|
279
|
+
throw new RestoreError(capCode, capMsg);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// 2. Decrypt + verify into stagingDir
|
|
283
|
+
var extracted;
|
|
284
|
+
try {
|
|
285
|
+
extracted = await restoreBundle.extract({
|
|
286
|
+
bundleDir: pullDir,
|
|
287
|
+
stagingDir: stagingDir,
|
|
288
|
+
passphrase: passphrase,
|
|
289
|
+
filter: runOpts.filter,
|
|
290
|
+
progressCallback: runOpts.progressCallback,
|
|
291
|
+
});
|
|
292
|
+
} catch (e) {
|
|
293
|
+
_cleanupTmp();
|
|
294
|
+
// Map restore-bundle error codes to restore/* domain so consumer
|
|
295
|
+
// code sees a single error namespace
|
|
296
|
+
var code = e && e.code;
|
|
297
|
+
var mappedCode = "restore/extract-failed";
|
|
298
|
+
if (code === "restore-bundle/decrypt-failed") mappedCode = "restore/decrypt-failed";
|
|
299
|
+
else if (code === "restore-bundle/checksum-mismatch") mappedCode = "restore/checksum-mismatch";
|
|
300
|
+
else if (code === "restore-bundle/missing-manifest") mappedCode = "restore/missing-manifest";
|
|
301
|
+
else if (code === "restore-bundle/missing-blob") mappedCode = "restore/missing-blob";
|
|
302
|
+
else if (code === "restore-bundle/size-mismatch") mappedCode = "restore/size-mismatch";
|
|
303
|
+
_emitAudit("restore.failure",
|
|
304
|
+
{ bundleId: bundleId, reason: (e && e.message) || String(e) }, "failure");
|
|
305
|
+
throw new RestoreError(mappedCode,
|
|
306
|
+
"extract failed: " + ((e && e.message) || String(e)));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// 3. Atomic swap. On swap failure, the stagingDir is preserved so
|
|
310
|
+
// an operator can recover manually — we do NOT delete it here.
|
|
311
|
+
var swapResult;
|
|
312
|
+
try {
|
|
313
|
+
swapResult = restoreRollback.swap({
|
|
314
|
+
stagingDir: stagingDir,
|
|
315
|
+
dataDir: dataDir,
|
|
316
|
+
rollbackRoot: rollbackRoot,
|
|
317
|
+
marker: Object.assign({ bundleId: bundleId }, runOpts.marker || {}),
|
|
318
|
+
});
|
|
319
|
+
} catch (e) {
|
|
320
|
+
// Pull dir is safe to clean (the source bundle is in storage);
|
|
321
|
+
// staging stays for manual recovery.
|
|
322
|
+
try { fs.rmSync(pullDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
323
|
+
_emitAudit("restore.failure",
|
|
324
|
+
{ bundleId: bundleId, reason: "swap: " + ((e && e.message) || String(e)) },
|
|
325
|
+
"failure");
|
|
326
|
+
var err = new RestoreError("restore/swap-failed",
|
|
327
|
+
"atomic swap failed after successful extract — staging preserved at " +
|
|
328
|
+
stagingDir + ": " + ((e && e.message) || String(e)));
|
|
329
|
+
err.stagingDir = stagingDir;
|
|
330
|
+
throw err;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// 4. Clean up the pull dir (source bundle still in storage)
|
|
334
|
+
try { fs.rmSync(pullDir, { recursive: true, force: true }); } catch (_e) { /* best-effort tmpdir cleanup */ }
|
|
335
|
+
|
|
336
|
+
var summary = {
|
|
337
|
+
bundleId: bundleId,
|
|
338
|
+
fileCount: extracted.fileCount,
|
|
339
|
+
totalBytes: extracted.totalBytes,
|
|
340
|
+
rollbackPath: swapResult.rollbackPath,
|
|
341
|
+
vaultKeyJson: extracted.vaultKeyJson,
|
|
342
|
+
durationMs: Date.now() - t0,
|
|
343
|
+
};
|
|
344
|
+
_emitAudit("restore.success", {
|
|
345
|
+
bundleId: bundleId,
|
|
346
|
+
fileCount: extracted.fileCount,
|
|
347
|
+
totalBytes: extracted.totalBytes,
|
|
348
|
+
rollbackPath: swapResult.rollbackPath,
|
|
349
|
+
durationMs: summary.durationMs,
|
|
350
|
+
});
|
|
351
|
+
return summary;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async function rollback(rollbackOpts) {
|
|
355
|
+
rollbackOpts = rollbackOpts || {};
|
|
356
|
+
// Either an explicit rollbackPath OR pull the most-recent one
|
|
357
|
+
var target = rollbackOpts.rollbackPath;
|
|
358
|
+
if (!target) {
|
|
359
|
+
var bundles = restoreRollback.list({ rollbackRoot: rollbackRoot });
|
|
360
|
+
if (bundles.length === 0) {
|
|
361
|
+
throw new RestoreError("restore/no-rollbacks",
|
|
362
|
+
"rollback: no rollback points found at " + rollbackRoot);
|
|
363
|
+
}
|
|
364
|
+
target = bundles[0].rollbackPath;
|
|
365
|
+
}
|
|
366
|
+
var r;
|
|
367
|
+
try {
|
|
368
|
+
r = await restoreRollback.rollback({
|
|
369
|
+
dataDir: dataDir,
|
|
370
|
+
rollbackPath: target,
|
|
371
|
+
rollbackRoot: rollbackRoot,
|
|
372
|
+
});
|
|
373
|
+
} catch (e) {
|
|
374
|
+
_emitAudit("restore.rollback.failure",
|
|
375
|
+
{ rollbackPath: target, reason: (e && e.message) || String(e) }, "failure");
|
|
376
|
+
throw new RestoreError("restore/rollback-failed",
|
|
377
|
+
"rollback failed: " + ((e && e.message) || String(e)));
|
|
378
|
+
}
|
|
379
|
+
_emitAudit("restore.rollback.success",
|
|
380
|
+
{ rollbackPath: target, discardedAt: r.discardedAt });
|
|
381
|
+
return r;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function listRollbacks() {
|
|
385
|
+
return restoreRollback.list({ rollbackRoot: rollbackRoot });
|
|
386
|
+
}
|
|
387
|
+
function purgeRollbacks(purgeOpts) {
|
|
388
|
+
return restoreRollback.purge({
|
|
389
|
+
rollbackRoot: rollbackRoot,
|
|
390
|
+
keep: (purgeOpts && purgeOpts.keep) || 0,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return {
|
|
395
|
+
list: list,
|
|
396
|
+
inspect: inspect,
|
|
397
|
+
run: run,
|
|
398
|
+
rollback: rollback,
|
|
399
|
+
listRollbacks: listRollbacks,
|
|
400
|
+
purgeRollbacks: purgeRollbacks,
|
|
401
|
+
storage: storage,
|
|
402
|
+
rollbackRoot: rollbackRoot,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
module.exports = {
|
|
407
|
+
create: create,
|
|
408
|
+
RestoreError: RestoreError,
|
|
409
|
+
};
|