@kaanbiryol/crate-server 0.0.0-stage → 0.17.9
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/LICENSE +21 -0
- package/README.md +73 -2
- package/THIRD_PARTY_NOTICES.md +3664 -0
- package/assets/coordinator.mjs +116 -0
- package/assets/credential-revocation.mjs +18 -0
- package/assets/database-upgrade-rules.mjs +42 -0
- package/assets/migrations/README.md +19 -0
- package/assets/qrcode.mjs +1638 -0
- package/assets/schema.sql +368 -0
- package/assets/server-release.json +6 -0
- package/assets/worker-runtime.json +12 -0
- package/assets/worker.mjs +1458 -0
- package/npm-shrinkwrap.json +939 -0
- package/package.json +38 -4
- package/scripts/assets.mjs +33 -0
- package/scripts/commands/data.mjs +80 -0
- package/scripts/commands/devices.mjs +100 -0
- package/scripts/commands/doctor.mjs +127 -0
- package/scripts/commands/service.mjs +19 -0
- package/scripts/commands/setup.mjs +194 -0
- package/scripts/commands/start.mjs +171 -0
- package/scripts/commands/status.mjs +49 -0
- package/scripts/commands/update.mjs +138 -0
- package/scripts/crate-server.mjs +11 -0
- package/scripts/deployment-fingerprint.mjs +13 -0
- package/scripts/local-server-alerts.mjs +53 -0
- package/scripts/local-server-backup-schedule.mjs +153 -0
- package/scripts/local-server-backup.mjs +275 -0
- package/scripts/local-server-cloudflared.mjs +93 -0
- package/scripts/local-server-control.mjs +150 -0
- package/scripts/local-server-devices.mjs +71 -0
- package/scripts/local-server-host-status.mjs +72 -0
- package/scripts/local-server-http.mjs +120 -0
- package/scripts/local-server-install.mjs +22 -0
- package/scripts/local-server-lifecycle.mjs +54 -0
- package/scripts/local-server-lock.mjs +217 -0
- package/scripts/local-server-migrations.mjs +43 -0
- package/scripts/local-server-options.mjs +134 -0
- package/scripts/local-server-pairing.mjs +47 -0
- package/scripts/local-server-process.mjs +77 -0
- package/scripts/local-server-qr.mjs +34 -0
- package/scripts/local-server-quick.mjs +116 -0
- package/scripts/local-server-readiness.mjs +48 -0
- package/scripts/local-server-runtime.mjs +460 -0
- package/scripts/local-server-service.mjs +209 -0
- package/scripts/local-server-style.mjs +12 -0
- package/scripts/local-server-tailscale.mjs +122 -0
- package/scripts/local-server-tunnel.mjs +212 -0
- package/scripts/local-server-watchdog.mjs +37 -0
- package/scripts/local-server-wizard.mjs +100 -0
- package/scripts/local-server.mjs +100 -0
- package/vendor/miniflare/LICENSE +25 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/ArrowClockwise.es-Cs0EHtoR.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Breadcrumbs-BlzUUgNz.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CaretDown.es-r8EMGhHM.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CaretLeft.es-CCxvlwgr.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CaretRight.es-CWeeOO8C.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CaretUpDown.es-Bp73BWZN.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Check.es-B3dV_aVM.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Copy.es-DUyM7PbX.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CopyButton-DdMFsAgv.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CronTriggersContext-CtoQyHCH.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CronTriggersPage-BC2FvZf5.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/DotsThree.es-B9u_qIrH.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Download.es-v8YTKdZh.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/List.es-GlowdvL8.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/ListBullets.es-DrJsrtCL.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/MagnifyingGlass.es-BzOo3pru.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/PaperPlaneTilt.es-DTLdWOnM.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Paperclip.es-6Ysj3lly.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Pencil.es-CDpuGAys.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Plus.es-xOjOjCs5.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/ResourceError-DNadec0F.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Spinner.es-oqUPe-aY.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/TableSelect-DgjN53ZF.js +25 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Trash.es-DTqwcb2_.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Warning.es-CLa-n7LD.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/X.es-BiJFnG31.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_appId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_appId-TnuOHwOA.js +5 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-DMGTgdaZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-DqCj-aYZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-uYCS7veQ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Cb6ggQGG.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-BW1__nAw.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-DCj9M_Uf.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-DMGTgdaZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-uYCS7veQ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_databaseId-BEh2sOY5.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_databaseId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-CxJm9jpK.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_namespaceId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_namespaceId-HT9g0tMq.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-DdmD-NV1.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-DMGTgdaZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-WgIBBs_w.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-uYCS7veQ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/ad-hoc-B9HL0oNk.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/async-t2_zA-v_.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/button-cdxnqcgzwko8ooha-CjoTKpgy.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/checkbox-kt1uojk2f9e0d0h1-D923QL-G.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/clipboard-text-vcbvmtne4zjk4b18-CEoJIuMe.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/configured-BGeRrlYf.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/cron-triggers-ZP5ClwAa.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/dialog-oqh8l3l3zutpibxx-nho54TMC.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/dropdown-ncwhcd912vmone8k-BAT0p_ep.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/email-B-IveBKB.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/events-ClnoiyGH.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/events-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/field-krp6z6vfbkrvufz2-DsLUBjzS.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/format-CjQ0gyEW.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/helpers-Bz2sloWm.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/index-BHW_FKpE.js +30 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/index-CiXL10aq.css +2 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/input-area-no30c09udyjxshu5-T786oEMj.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/input-group-lxdd09p60cf27pe1-BqVz8A4J.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/input-h48k3uagzrgb98au-BF-hE08e.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/label-latndvb1ngem7we8-mWoel0Kk.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/link-DadJAPnd.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/link-provider-mn2voeohon7cj9o4-CNosc_Ni.js +13 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/matchContext-C1eKDtty.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/object._-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/object._-DDwO6NT7.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/object._-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/observability-CC1mP6Xo.js +15 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/observability-CX-6-j6d.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/observability-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/react-BZY8YNV6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/redirect-CckYXsV1.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routes-BlOyav-b.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routing-CVthjHxr.js +2 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routing-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routing-DMGTgdaZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routing-uYCS7veQ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/select-kva5ru5f673kah1m-DQuxH2_G.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/sending-BPjb3S3Y.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/sending-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/switch-ihaydbzem62bey4p-C9M-MPNS.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/table-inweecadl3her7pd-UWLv9e8D.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/text-nmyi1rkwdj37f30f-BLzIhmEO.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/types-DTx0hLYz.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/useCursorPaginatedList-BGUINn38.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/useRouterState-BLq6Ai_6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/favicon.svg +3 -0
- package/vendor/miniflare/dist/local-explorer-ui/index.html +27 -0
- package/vendor/miniflare/dist/src/index.d.ts +14183 -0
- package/vendor/miniflare/dist/src/index.js +123738 -0
- package/vendor/miniflare/dist/src/mdream_edge_bg.wasm +0 -0
- package/vendor/miniflare/dist/src/plugins/artifacts/git-sidecar.js +21071 -0
- package/vendor/miniflare/dist/src/workers/access/access-identity.worker.js +10 -0
- package/vendor/miniflare/dist/src/workers/analytics-engine/analytics-engine.worker.js +21 -0
- package/vendor/miniflare/dist/src/workers/analytics-engine/remote.worker.js +2578 -0
- package/vendor/miniflare/dist/src/workers/artifacts/binding.worker.js +903 -0
- package/vendor/miniflare/dist/src/workers/artifacts/wrapped-binding.worker.js +52 -0
- package/vendor/miniflare/dist/src/workers/assets/assets-kv.worker.js +27 -0
- package/vendor/miniflare/dist/src/workers/assets/assets.worker.js +1525 -0
- package/vendor/miniflare/dist/src/workers/assets/router.worker.js +1883 -0
- package/vendor/miniflare/dist/src/workers/assets/rpc-proxy.worker.js +55 -0
- package/vendor/miniflare/dist/src/workers/browser-rendering/binding.worker.js +453 -0
- package/vendor/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js +18 -0
- package/vendor/miniflare/dist/src/workers/cache/cache-entry.worker.js +24 -0
- package/vendor/miniflare/dist/src/workers/cache/cache.worker.js +652 -0
- package/vendor/miniflare/dist/src/workers/core/dev-control.worker.js +52 -0
- package/vendor/miniflare/dist/src/workers/core/dev-registry-proxy.worker.js +371 -0
- package/vendor/miniflare/dist/src/workers/core/do-wrapper.worker.js +67 -0
- package/vendor/miniflare/dist/src/workers/core/entry.worker.js +5516 -0
- package/vendor/miniflare/dist/src/workers/core/outbound.worker.js +147 -0
- package/vendor/miniflare/dist/src/workers/d1/database.worker.js +298 -0
- package/vendor/miniflare/dist/src/workers/d1/entry.worker.js +143 -0
- package/vendor/miniflare/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js +2574 -0
- package/vendor/miniflare/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js +11 -0
- package/vendor/miniflare/dist/src/workers/email/email-store.worker.js +606 -0
- package/vendor/miniflare/dist/src/workers/email/email.worker.js +26 -0
- package/vendor/miniflare/dist/src/workers/email/send_email.worker.js +3703 -0
- package/vendor/miniflare/dist/src/workers/flagship/binding.worker.js +394 -0
- package/vendor/miniflare/dist/src/workers/flagship/object.worker.js +349 -0
- package/vendor/miniflare/dist/src/workers/hello-world/binding.worker.js +18 -0
- package/vendor/miniflare/dist/src/workers/hello-world/object.worker.js +13 -0
- package/vendor/miniflare/dist/src/workers/images/images.worker.js +450 -0
- package/vendor/miniflare/dist/src/workers/k2/binding.worker.js +2583 -0
- package/vendor/miniflare/dist/src/workers/kv/namespace.worker.js +323 -0
- package/vendor/miniflare/dist/src/workers/kv/sites.worker.js +148 -0
- package/vendor/miniflare/dist/src/workers/local-explorer/explorer.worker.js +17275 -0
- package/vendor/miniflare/dist/src/workers/observability/collector.worker.js +725 -0
- package/vendor/miniflare/dist/src/workers/pipelines/pipeline.worker.js +9 -0
- package/vendor/miniflare/dist/src/workers/queues/broker.worker.js +391 -0
- package/vendor/miniflare/dist/src/workers/r2/bucket.worker.js +1171 -0
- package/vendor/miniflare/dist/src/workers/r2/public.worker.js +1319 -0
- package/vendor/miniflare/dist/src/workers/r2/s3/index.worker.js +11128 -0
- package/vendor/miniflare/dist/src/workers/ratelimit/ratelimit-object.worker.js +55 -0
- package/vendor/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js +69 -0
- package/vendor/miniflare/dist/src/workers/secrets-store/secret.worker.js +64 -0
- package/vendor/miniflare/dist/src/workers/shared/index.worker.js +730 -0
- package/vendor/miniflare/dist/src/workers/shared/object-entry.worker.js +33 -0
- package/vendor/miniflare/dist/src/workers/shared/remote-proxy-client.worker.js +2698 -0
- package/vendor/miniflare/dist/src/workers/shared/zod.worker.js +15459 -0
- package/vendor/miniflare/dist/src/workers/stream/binding.worker.js +282 -0
- package/vendor/miniflare/dist/src/workers/stream/object.worker.js +479 -0
- package/vendor/miniflare/dist/src/workers/workflows/binding.worker.js +5137 -0
- package/vendor/miniflare/dist/src/workers/workflows/wrapped-binding.worker.js +111 -0
- package/vendor/miniflare/package.json +135 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { createReadStream, createWriteStream } from 'node:fs';
|
|
3
|
+
import { copyFile, link, lstat, mkdir, readFile, readdir, realpath, rename, rm, statfs, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
6
|
+
import { assertLocalMigrationPath } from './local-server-migrations.mjs';
|
|
7
|
+
import { lockLocalData } from './local-server-lock.mjs';
|
|
8
|
+
import { assertCompatibleLocalMetadata, localBuildInfo, openLocalRuntime, runtimeAdvances } from './local-server-runtime.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* One backed-up file, relative to its directory.
|
|
12
|
+
* @typedef {{ path: string, size: number, sha256: string }} BackupFile
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A verified backup's inventory (`backup.json`).
|
|
17
|
+
* @typedef {object} BackupManifest
|
|
18
|
+
* @property {number} format
|
|
19
|
+
* @property {string} createdAt
|
|
20
|
+
* @property {import('./local-server-runtime.mjs').ServerMetadata} metadata
|
|
21
|
+
* @property {BackupFile[]} data
|
|
22
|
+
* @property {BackupFile[]} remote
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
// A backup describes its own source, so the record of the last backup stays out of it, and so
|
|
26
|
+
// do automatic backup settings: a restored copy must not prune the original server's backups.
|
|
27
|
+
const ephemeral = new Set(['server.lock', 'workerd.json', 'control.json', 'control.sock', 'status.json', 'last-backup.json', 'auto-backup.json', 'alerts.json', '.DS_Store']);
|
|
28
|
+
const inside = (/** @type {string} */ parent, /** @type {string} */ child) => { const path = relative(parent, child); return path === '' || (!path.startsWith('..') && !isAbsolute(path)); };
|
|
29
|
+
/** @param {string} path */
|
|
30
|
+
async function digest(path) {
|
|
31
|
+
const hash = createHash('sha256');
|
|
32
|
+
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
|
33
|
+
return hash.digest('hex');
|
|
34
|
+
}
|
|
35
|
+
/** @param {string} directory @param {string} [prefix] @returns {Promise<BackupFile[]>} */
|
|
36
|
+
async function inventory(directory, prefix = '') {
|
|
37
|
+
/** @type {BackupFile[]} */
|
|
38
|
+
const files = [];
|
|
39
|
+
for (const name of (await readdir(join(directory, prefix))).sort()) {
|
|
40
|
+
const path = prefix ? `${prefix}/${name}` : name;
|
|
41
|
+
if (!prefix && ephemeral.has(name)) continue;
|
|
42
|
+
const stat = await lstat(join(directory, path));
|
|
43
|
+
if (stat.isDirectory()) files.push(...await inventory(directory, path));
|
|
44
|
+
else if (stat.isFile()) files.push({ path, size: stat.size, sha256: await digest(join(directory, path)) });
|
|
45
|
+
else throw new Error('Backups cannot contain symlinks or special files.');
|
|
46
|
+
}
|
|
47
|
+
return files;
|
|
48
|
+
}
|
|
49
|
+
/** @param {string} source @param {string} target @param {BackupFile[]} files */
|
|
50
|
+
async function copyInventory(source, target, files) {
|
|
51
|
+
for (const file of files) {
|
|
52
|
+
await mkdir(dirname(join(target, file.path)), { recursive: true, mode: 0o700 });
|
|
53
|
+
await copyFile(join(source, file.path), join(target, file.path));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @param {string} dataDir */
|
|
58
|
+
export async function checkLocalUpgrade(dataDir) {
|
|
59
|
+
/** @type {import('./local-server-runtime.mjs').ServerMetadata} */
|
|
60
|
+
const current = JSON.parse(await readFile(join(dataDir, 'server.json'), 'utf8'));
|
|
61
|
+
const next = await localBuildInfo();
|
|
62
|
+
const migration = current?.schemaHash !== next.schemaHash;
|
|
63
|
+
if (migration) assertLocalMigrationPath(current?.schemaVersion, next.release);
|
|
64
|
+
// A newer Miniflare opens the data only through upgrade, which backs up and verifies first.
|
|
65
|
+
const runtimeUpgrade = runtimeAdvances(current?.runtimeVersion, next.runtimeVersion);
|
|
66
|
+
assertCompatibleLocalMetadata({ ...current, ...(migration ? { schemaHash: next.schemaHash } : {}),
|
|
67
|
+
...(runtimeUpgrade ? { runtimeVersion: next.runtimeVersion } : {}) }, next, dataDir);
|
|
68
|
+
return { from: current.serverRevision, to: next.serverRevision, runtime: next.runtimeVersion, requiresUpgrade: migration || runtimeUpgrade, migration, runtimeUpgrade };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Miniflare stores R2 object bytes in write-once files with unguessable names: a blob is
|
|
72
|
+
// only ever created or deleted, never changed (BlobStore in miniflare's shared worker).
|
|
73
|
+
const isBlob = (/** @type {string} */ path) => /(?:^|\/)blobs\/[^/]+$/.test(path);
|
|
74
|
+
const GiB = 1024 ** 3;
|
|
75
|
+
|
|
76
|
+
/** @param {string} directory @param {string} [prefix]
|
|
77
|
+
* @returns {Promise<{ path: string, size: number, mtimeMs: number }[]>} Files in `inventory` order. */
|
|
78
|
+
async function listFiles(directory, prefix = '') {
|
|
79
|
+
/** @type {{ path: string, size: number, mtimeMs: number }[]} */
|
|
80
|
+
const files = [];
|
|
81
|
+
for (const name of (await readdir(join(directory, prefix))).sort()) {
|
|
82
|
+
const path = prefix ? `${prefix}/${name}` : name;
|
|
83
|
+
if (!prefix && ephemeral.has(name)) continue;
|
|
84
|
+
const stat = await lstat(join(directory, path));
|
|
85
|
+
if (stat.isDirectory()) files.push(...await listFiles(directory, path));
|
|
86
|
+
else if (stat.isFile()) files.push({ path, size: stat.size, mtimeMs: stat.mtimeMs });
|
|
87
|
+
else throw new Error('Backups cannot contain symlinks or special files.');
|
|
88
|
+
}
|
|
89
|
+
return files;
|
|
90
|
+
}
|
|
91
|
+
/** @param {string} directory */
|
|
92
|
+
const listOptional = directory => listFiles(directory).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
|
|
93
|
+
|
|
94
|
+
/** Copies a file, hashing the bytes read from the source. Never writes through an existing
|
|
95
|
+
* target: it may be a hard link into an earlier backup. @param {string} source @param {string} target @param {AbortSignal} [signal] */
|
|
96
|
+
async function copyHashed(source, target, signal) {
|
|
97
|
+
signal?.throwIfAborted();
|
|
98
|
+
await rm(target, { force: true });
|
|
99
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
100
|
+
const hash = createHash('sha256');
|
|
101
|
+
await pipeline(createReadStream(source), async function* (chunks) { for await (const chunk of chunks) { hash.update(chunk); yield chunk; } }, createWriteStream(target, { flags: 'wx', mode: 0o600 }), ...(signal ? [{ signal }] : []));
|
|
102
|
+
return hash.digest('hex');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** @param {string} source @param {string} target @returns {Promise<boolean>} False when the filesystem cannot link them. */
|
|
106
|
+
async function tryLink(source, target) {
|
|
107
|
+
await rm(target, { force: true });
|
|
108
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
109
|
+
try { await link(source, target); return true; }
|
|
110
|
+
catch (error) { if (['EXDEV', 'EPERM', 'ENOTSUP', 'EMLINK', 'ENOENT'].includes(error.code)) return false; throw error; }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** @param {string} directory */
|
|
114
|
+
async function freeBytes(directory) {
|
|
115
|
+
const stats = await statfs(directory);
|
|
116
|
+
return stats.bavail * stats.bsize;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Creates a verified backup. A running server passes `pause`: write-once blobs are copied
|
|
121
|
+
* while it serves, and only the rest is copied while its runtime is stopped.
|
|
122
|
+
* @param {string} dataDir
|
|
123
|
+
* @param {string} output A new directory.
|
|
124
|
+
* @param {object} [options]
|
|
125
|
+
* @param {boolean} [options.alreadyLocked] The caller holds the data directory lock.
|
|
126
|
+
* @param {() => Promise<() => Promise<void>>} [options.pause] Stops writes; returns a resume.
|
|
127
|
+
* @param {string} [options.linkFrom] An earlier backup whose unchanged blobs are hard-linked, not copied.
|
|
128
|
+
* @param {AbortSignal} [options.signal] Stops the backup between and during copies; nothing is published.
|
|
129
|
+
* @param {(directory: string) => Promise<number>} [options.available] Free bytes where the backup goes.
|
|
130
|
+
* @returns {Promise<string>} The backup directory.
|
|
131
|
+
*/
|
|
132
|
+
export async function backupLocalServer(dataDir, output, { alreadyLocked = false, pause, linkFrom, signal, available = freeBytes } = {}) {
|
|
133
|
+
dataDir = await realpath(dataDir);
|
|
134
|
+
output = resolve(output);
|
|
135
|
+
await mkdir(dirname(output), { recursive: true, mode: 0o700 });
|
|
136
|
+
output = join(await realpath(dirname(output)), basename(output));
|
|
137
|
+
if (inside(dataDir, output) || inside(`${dataDir}.remote`, output)) throw new Error('Choose a backup location outside the server data and remote directories.');
|
|
138
|
+
if (await lstat(output).catch(error => { if (error.code === 'ENOENT') return null; throw error; })) throw new Error('The backup destination already exists. Choose a new directory.');
|
|
139
|
+
const unlock = alreadyLocked ? async () => {} : await lockLocalData(dataDir);
|
|
140
|
+
const staging = `${output}.tmp-${randomUUID()}`;
|
|
141
|
+
try {
|
|
142
|
+
/** @type {Map<string, BackupFile>} Blobs an earlier backup holds, by path. */
|
|
143
|
+
const linkable = new Map();
|
|
144
|
+
if (linkFrom) {
|
|
145
|
+
const previous = await readBackupManifest(linkFrom).catch(() => null);
|
|
146
|
+
for (const file of previous?.data ?? []) if (isBlob(file.path)) linkable.set(file.path, file);
|
|
147
|
+
}
|
|
148
|
+
/** @param {{ path: string, size: number }} file @returns {Promise<string>} Its SHA-256. */
|
|
149
|
+
const place = async file => {
|
|
150
|
+
const target = join(staging, 'data', file.path);
|
|
151
|
+
const earlier = linkable.get(file.path);
|
|
152
|
+
if (linkFrom && earlier?.size === file.size && await tryLink(join(linkFrom, 'data', file.path), target)) return earlier.sha256;
|
|
153
|
+
return copyHashed(join(dataDir, file.path), target, signal);
|
|
154
|
+
};
|
|
155
|
+
const before = await listFiles(dataDir);
|
|
156
|
+
const needed = [...before, ...await listOptional(`${dataDir}.remote`)]
|
|
157
|
+
.reduce((sum, file) => sum + (linkable.get(file.path)?.size === file.size ? 0 : file.size), 0);
|
|
158
|
+
const free = await available(dirname(output));
|
|
159
|
+
if (free < needed + GiB) throw new Error(`Not enough free space for a backup at ${dirname(output)}: it needs about ${Math.ceil(needed / 1024 ** 2)} MB plus 1 GB to spare, and ${Math.floor(free / 1024 ** 2)} MB is free.`);
|
|
160
|
+
await mkdir(staging, { mode: 0o700 });
|
|
161
|
+
await mkdir(join(staging, 'data'), { mode: 0o700 });
|
|
162
|
+
await mkdir(join(staging, 'remote'), { mode: 0o700 });
|
|
163
|
+
/** @type {Map<string, { size: number, mtimeMs: number, sha256: string }>} */
|
|
164
|
+
const early = new Map();
|
|
165
|
+
if (pause) for (const file of before.filter(file => isBlob(file.path))) {
|
|
166
|
+
// Maintenance may delete an expired blob meanwhile; the listing taken while paused decides what the backup holds.
|
|
167
|
+
try { early.set(file.path, { ...file, sha256: await place(file) }); }
|
|
168
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; await rm(join(staging, 'data', file.path), { force: true }); }
|
|
169
|
+
}
|
|
170
|
+
const resume = pause ? await pause() : null;
|
|
171
|
+
/** @type {import('./local-server-runtime.mjs').ServerMetadata} */
|
|
172
|
+
let metadata;
|
|
173
|
+
/** @type {BackupFile[]} */
|
|
174
|
+
const data = [];
|
|
175
|
+
/** @type {BackupFile[]} */
|
|
176
|
+
const remote = [];
|
|
177
|
+
try {
|
|
178
|
+
metadata = JSON.parse(await readFile(join(dataDir, 'server.json'), 'utf8'));
|
|
179
|
+
for (const file of await listFiles(dataDir)) {
|
|
180
|
+
const copied = early.get(file.path);
|
|
181
|
+
early.delete(file.path);
|
|
182
|
+
const unchanged = copied && copied.size === file.size && copied.mtimeMs === file.mtimeMs;
|
|
183
|
+
data.push({ path: file.path, size: file.size, sha256: unchanged ? copied.sha256 : await place(file) });
|
|
184
|
+
}
|
|
185
|
+
for (const file of await listOptional(`${dataDir}.remote`)) {
|
|
186
|
+
remote.push({ path: file.path, size: file.size, sha256: await copyHashed(join(`${dataDir}.remote`, file.path), join(staging, 'remote', file.path), signal) });
|
|
187
|
+
}
|
|
188
|
+
} finally { await resume?.(); }
|
|
189
|
+
// Blobs deleted after they were copied.
|
|
190
|
+
for (const path of early.keys()) await rm(join(staging, 'data', path), { force: true });
|
|
191
|
+
// Re-read copied bytes before publishing a completed backup.
|
|
192
|
+
if (JSON.stringify(await inventory(join(staging, 'data'))) !== JSON.stringify(data)
|
|
193
|
+
|| JSON.stringify(await inventory(join(staging, 'remote'))) !== JSON.stringify(remote)) throw new Error('Backup verification failed. No completed backup was created.');
|
|
194
|
+
signal?.throwIfAborted();
|
|
195
|
+
const createdAt = new Date().toISOString();
|
|
196
|
+
await writeFile(join(staging, 'backup.json'), JSON.stringify({ format: 1, createdAt, metadata, data, remote }), { mode: 0o600 });
|
|
197
|
+
await rename(staging, output);
|
|
198
|
+
// Only a status report reads this; the completed backup stands even if recording it fails.
|
|
199
|
+
await writeFile(join(dataDir, 'last-backup.json'), `${JSON.stringify({ createdAt, output })}\n`, { mode: 0o600 })
|
|
200
|
+
.catch(error => console.warn(`Backup completed, but its time could not be recorded: ${error.message}`));
|
|
201
|
+
return output;
|
|
202
|
+
} finally { await rm(staging, { recursive: true, force: true }); await unlock(); }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Backs up stopped data before a migration into `output`, or reuses the backup already
|
|
206
|
+
* there while it is this data directory's latest backup: Compose restarts a failing
|
|
207
|
+
* migration, which must not copy the data each time. A backup that is no longer the latest
|
|
208
|
+
* (a restore, a later backup, or a lost record) is kept, and a new one is made beside it.
|
|
209
|
+
* @param {string} dataDir @param {string} output @returns {Promise<string>} The backup used. */
|
|
210
|
+
export async function prepareMigrationBackup(dataDir, output) {
|
|
211
|
+
const latest = await readLastBackup(dataDir);
|
|
212
|
+
const existing = await realpath(output).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
213
|
+
if (existing && latest?.output === existing && await readBackupManifest(existing).then(() => true, () => false)) return existing;
|
|
214
|
+
const target = existing ? `${output}-${new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')}` : output;
|
|
215
|
+
return backupLocalServer(dataDir, target, { alreadyLocked: true });
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** @param {string} backup @returns {Promise<BackupManifest>} */
|
|
219
|
+
export async function readBackupManifest(backup) {
|
|
220
|
+
const manifest = JSON.parse(await readFile(join(backup, 'backup.json'), 'utf8'));
|
|
221
|
+
if (manifest?.format !== 1 || !Array.isArray(manifest.data) || !Array.isArray(manifest.remote) || typeof manifest.createdAt !== 'string') throw new Error('Unsupported backup format.');
|
|
222
|
+
return manifest;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** The most recent verified backup of this data directory, or null if none was recorded.
|
|
226
|
+
* @param {string} dataDir @returns {Promise<{ createdAt: string, output: string } | null>} */
|
|
227
|
+
export async function readLastBackup(dataDir) {
|
|
228
|
+
try {
|
|
229
|
+
const record = JSON.parse(await readFile(join(dataDir, 'last-backup.json'), 'utf8'));
|
|
230
|
+
return typeof record?.createdAt === 'string' && typeof record.output === 'string' ? { createdAt: record.createdAt, output: record.output } : null;
|
|
231
|
+
} catch { return null; }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** @param {string} dataDir @param {string} backup */
|
|
235
|
+
export async function restoreLocalServer(dataDir, backup) {
|
|
236
|
+
dataDir = resolve(dataDir);
|
|
237
|
+
backup = await realpath(backup);
|
|
238
|
+
if (inside(dataDir, backup) || inside(backup, dataDir)) throw new Error('Choose a restore directory separate from the backup.');
|
|
239
|
+
/** @type {BackupManifest} */
|
|
240
|
+
const manifest = JSON.parse(await readFile(join(backup, 'backup.json'), 'utf8'));
|
|
241
|
+
if (manifest.format !== 1 || !Array.isArray(manifest.data) || !Array.isArray(manifest.remote)) throw new Error('Unsupported backup format.');
|
|
242
|
+
assertCompatibleLocalMetadata(manifest.metadata, await localBuildInfo());
|
|
243
|
+
for (const key of /** @type {const} */ (['data', 'remote'])) {
|
|
244
|
+
for (const file of manifest[key]) {
|
|
245
|
+
if (typeof file.path !== 'string' || !file.path || file.path.includes('\\')
|
|
246
|
+
|| file.path.split('/').some(part => !part || part === '.' || part === '..')) throw new Error('Invalid backup file path.');
|
|
247
|
+
}
|
|
248
|
+
if (JSON.stringify(await inventory(join(backup, key))) !== JSON.stringify(manifest[key])) throw new Error('Backup files are missing, changed, or damaged. Restore was not started.');
|
|
249
|
+
}
|
|
250
|
+
const metadata = JSON.parse(await readFile(join(backup, 'data/server.json'), 'utf8'));
|
|
251
|
+
if (JSON.stringify(metadata) !== JSON.stringify(manifest.metadata)) throw new Error('Backup metadata does not match its inventory.');
|
|
252
|
+
const unlock = await lockLocalData(dataDir);
|
|
253
|
+
const staging = `${dataDir}.restore-${randomUUID()}`;
|
|
254
|
+
try {
|
|
255
|
+
if ((await readdir(dataDir)).some(name => name !== 'server.lock')) throw new Error('Restore requires an empty data directory. Existing data was not changed.');
|
|
256
|
+
if (await lstat(`${dataDir}.remote`).catch(error => { if (error.code === 'ENOENT') return null; throw error; })) throw new Error('Restore requires an unused remote settings directory.');
|
|
257
|
+
await mkdir(staging, { mode: 0o700 });
|
|
258
|
+
await copyInventory(join(backup, 'data'), staging, manifest.data);
|
|
259
|
+
// Validate the restored database with alarms disabled before exposing it.
|
|
260
|
+
const verified = await openLocalRuntime({ dataDir: staging, administrative: true, handleSignals: false });
|
|
261
|
+
// A restored server is another server to its devices, even once its changelog catches
|
|
262
|
+
// up with their cursors. The next sync read creates a new storage identity
|
|
263
|
+
// (STORAGE_ID_SQL in src/cloudflare/worker/sync/storage.ts).
|
|
264
|
+
try { await verified.db.prepare("DELETE FROM maintenance_state WHERE key = 'storage_id'").run(); }
|
|
265
|
+
finally { await verified.close(); }
|
|
266
|
+
const files = await inventory(staging);
|
|
267
|
+
await copyInventory(staging, dataDir, files.filter(file => file.path !== 'server.json'));
|
|
268
|
+
if (manifest.remote.length) {
|
|
269
|
+
await mkdir(`${dataDir}.remote`, { mode: 0o700 });
|
|
270
|
+
await copyInventory(join(backup, 'remote'), `${dataDir}.remote`, manifest.remote);
|
|
271
|
+
}
|
|
272
|
+
// Metadata is the final publication marker; interrupted copies fail closed.
|
|
273
|
+
await copyFile(join(staging, 'server.json'), join(dataDir, 'server.json'));
|
|
274
|
+
} finally { await rm(staging, { recursive: true, force: true }); await unlock(); }
|
|
275
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { chmod, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { gunzipSync } from 'node:zlib';
|
|
7
|
+
import { runProcess } from './local-server-process.mjs';
|
|
8
|
+
|
|
9
|
+
// Official release assets. Pin both version and SHA-256; never execute a
|
|
10
|
+
// download based only on a mutable "latest" URL or an unverified API response.
|
|
11
|
+
export const cloudflaredVersion = '2026.10.3';
|
|
12
|
+
/** @type {Record<string, [filename: string, sha256: string]>} */
|
|
13
|
+
const assets = {
|
|
14
|
+
'darwin-arm64': ['cloudflared-darwin-arm64.tgz', '1165d14b6f6360a3b8c283d7d1100024d6ec7cd9bc9e32519e96150645f3ec55'],
|
|
15
|
+
'darwin-x64': ['cloudflared-darwin-amd64.tgz', '81b7b85f2376815c4f59b1aa323887b62e16ce8b67555c2e1577dc23f2a82000'],
|
|
16
|
+
'linux-x64': ['cloudflared-linux-amd64', '053b80b0a23031a038fdbf3c073f59f82b8f1f152aa67971d7383ffafc0dbab0'],
|
|
17
|
+
'linux-arm64': ['cloudflared-linux-arm64', '89297ebfb9e8c99c0dc013a1140601453cf3798d8306c5591651f4a3f5210be8'],
|
|
18
|
+
'win32-x64': ['cloudflared-windows-amd64.exe', '76b2805253d0d6ffacb092a7acfbee99e7af6917835c0c5410e23f3ef5052da2'],
|
|
19
|
+
};
|
|
20
|
+
const hash = (/** @type {Buffer} */ data) => createHash('sha256').update(data).digest('hex');
|
|
21
|
+
|
|
22
|
+
// Up to three attempts with a short growing backoff, each with its own timeout.
|
|
23
|
+
// Only network errors, timeouts and server errors are retried; an abort stops at once.
|
|
24
|
+
/** @param {string} url @param {AbortSignal | undefined} signal @param {typeof fetch} fetchAsset @returns {Promise<Buffer>} */
|
|
25
|
+
async function download(url, signal, fetchAsset) {
|
|
26
|
+
for (let attempt = 1; ; attempt++) {
|
|
27
|
+
/** @type {number | undefined} */
|
|
28
|
+
let status;
|
|
29
|
+
try {
|
|
30
|
+
const response = await fetchAsset(url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(120_000)]) : AbortSignal.timeout(120_000) });
|
|
31
|
+
if (response.ok) return Buffer.from(await response.arrayBuffer());
|
|
32
|
+
status = response.status;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (signal?.aborted || !['TypeError', 'TimeoutError'].includes(error?.name) || attempt === 3) throw error;
|
|
35
|
+
}
|
|
36
|
+
if (status !== undefined && (status < 500 || attempt === 3)) throw new Error(`Could not download cloudflared (HTTP ${status}). Retry when internet access is available.`);
|
|
37
|
+
await delay(1000 * attempt, undefined, { signal });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {Buffer} archive */
|
|
42
|
+
function extractCloudflared(archive) {
|
|
43
|
+
const tar = gunzipSync(archive, { maxOutputLength: 100 * 1024 * 1024 });
|
|
44
|
+
for (let offset = 0; offset + 512 <= tar.length;) {
|
|
45
|
+
const name = tar.subarray(offset, offset + 100).toString().replace(/\0.*$/s, '');
|
|
46
|
+
const sizeText = tar.subarray(offset + 124, offset + 136).toString().replace(/\0.*$/s, '').trim();
|
|
47
|
+
if (!name) break;
|
|
48
|
+
if (!/^[0-7]+$/.test(sizeText)) throw new Error('Invalid cloudflared archive size.');
|
|
49
|
+
const size = parseInt(sizeText, 8);
|
|
50
|
+
if (offset + 512 + size > tar.length) throw new Error('Truncated cloudflared archive.');
|
|
51
|
+
if (['cloudflared', './cloudflared'].includes(name) && [0, 48].includes(tar[offset + 156])) {
|
|
52
|
+
return tar.subarray(offset + 512, offset + 512 + size);
|
|
53
|
+
}
|
|
54
|
+
offset += 512 + Math.ceil(size / 512) * 512;
|
|
55
|
+
}
|
|
56
|
+
throw new Error('Cloudflared executable is missing from its release archive.');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {{ signal?: AbortSignal, platform?: NodeJS.Platform, arch?: NodeJS.Architecture, cacheDir?: string,
|
|
61
|
+
* fetchAsset?: typeof fetch, run?: typeof runProcess }} [options]
|
|
62
|
+
* @returns {Promise<string>} The command that runs cloudflared.
|
|
63
|
+
*/
|
|
64
|
+
export async function installCloudflared({ signal, platform = process.platform, arch = process.arch,
|
|
65
|
+
cacheDir = join(homedir(), '.crate', 'bin'), fetchAsset = fetch, run = runProcess } = {}) {
|
|
66
|
+
try { await run('cloudflared', ['--version'], { signal, stdio: 'ignore' }); return 'cloudflared'; }
|
|
67
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
68
|
+
const asset = assets[`${platform}-${arch}`];
|
|
69
|
+
if (!asset) throw new Error(`Automatic cloudflared installation is unavailable for ${platform}/${arch}. Install cloudflared yourself and retry.`);
|
|
70
|
+
const [filename, sha256] = asset;
|
|
71
|
+
const directory = join(cacheDir, cloudflaredVersion, `${platform}-${arch}`);
|
|
72
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
73
|
+
const archivePath = join(directory, filename + '.download');
|
|
74
|
+
/** @type {Buffer | null} */
|
|
75
|
+
let archive = await readFile(archivePath).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
76
|
+
if (!archive || hash(archive) !== sha256) {
|
|
77
|
+
console.log(`Downloading cloudflared ${cloudflaredVersion} from Cloudflare's GitHub release...`);
|
|
78
|
+
archive = await download(`https://github.com/cloudflare/cloudflared/releases/download/${cloudflaredVersion}/${filename}`, signal, fetchAsset);
|
|
79
|
+
if (hash(archive) !== sha256) throw new Error('Cloudflared checksum mismatch. The download was not installed or executed.');
|
|
80
|
+
await writeFile(archivePath, archive, { mode: 0o600 });
|
|
81
|
+
}
|
|
82
|
+
signal?.throwIfAborted();
|
|
83
|
+
const binary = filename.endsWith('.tgz') ? extractCloudflared(archive) : archive;
|
|
84
|
+
const command = join(directory, platform === 'win32' ? 'cloudflared.exe' : 'cloudflared');
|
|
85
|
+
const existing = await readFile(command).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
86
|
+
if (!existing || hash(existing) !== hash(binary)) {
|
|
87
|
+
const temporary = `${command}.${randomUUID()}.tmp`;
|
|
88
|
+
try { await writeFile(temporary, binary, { flag: 'wx', mode: 0o700 }); await rename(temporary, command); }
|
|
89
|
+
finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
|
90
|
+
}
|
|
91
|
+
await chmod(command, 0o700);
|
|
92
|
+
return command;
|
|
93
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { createServer, request as httpRequest } from 'node:http';
|
|
3
|
+
import { chmod, readFile, unlink, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { isAbsolute, join } from 'node:path';
|
|
6
|
+
import { readLastBackup } from './local-server-backup.mjs';
|
|
7
|
+
import { startBackups } from './local-server-backup-schedule.mjs';
|
|
8
|
+
import { createAlerts } from './local-server-alerts.mjs';
|
|
9
|
+
import { createHostStatus } from './local-server-host-status.mjs';
|
|
10
|
+
import { installKind } from './local-server-install.mjs';
|
|
11
|
+
import { listLocalDevices, revokeLocalDevice } from './local-server-devices.mjs';
|
|
12
|
+
import { readSmallJson, sendJson } from './local-server-http.mjs';
|
|
13
|
+
|
|
14
|
+
// sun_path holds 104 bytes on macOS (108 on Linux), including the terminating NUL.
|
|
15
|
+
const socketPathLimit = 103;
|
|
16
|
+
|
|
17
|
+
/** Administration stays on a private local socket and additionally requires a
|
|
18
|
+
* random secret stored in the owner's private data directory. Never proxied.
|
|
19
|
+
* @param {object} options
|
|
20
|
+
* @param {string} options.dataDir
|
|
21
|
+
* @param {Pick<import('./local-server-pairing.mjs').LocalPairing, 'issue'>} options.pairing
|
|
22
|
+
* @param {string} options.origin
|
|
23
|
+
* @param {import('./local-server-runtime.mjs').LocalRuntime} options.runtime */
|
|
24
|
+
export async function startLocalControl({ dataDir, pairing, origin, runtime }) {
|
|
25
|
+
const file = join(dataDir, 'control.json');
|
|
26
|
+
const id = randomBytes(16).toString('hex');
|
|
27
|
+
// Scheduled temp cleanup can delete a long-running server's socket, so prefer the
|
|
28
|
+
// data directory and use the temp directory only when that path is too long.
|
|
29
|
+
const inData = join(dataDir, 'control.sock');
|
|
30
|
+
const socket = process.platform === 'win32' ? `\\\\.\\pipe\\crate-${id}`
|
|
31
|
+
: Buffer.byteLength(inData) <= socketPathLimit ? inData : join(tmpdir(), `crate-${id}.sock`);
|
|
32
|
+
// The caller holds the data directory lock, so a socket already there was left by a crash.
|
|
33
|
+
if (socket === inData) await unlink(socket).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
34
|
+
const secret = randomBytes(32).toString('hex');
|
|
35
|
+
const alerts = createAlerts({ dataDir, send: kind => runtime.alert(kind) });
|
|
36
|
+
/** @type {ReturnType<typeof createHostStatus>} */
|
|
37
|
+
let host;
|
|
38
|
+
const backups = startBackups({ dataDir, runtime, onChange: automaticFailure => {
|
|
39
|
+
void host.refresh();
|
|
40
|
+
if (automaticFailure) void alerts.notify('backup-failed');
|
|
41
|
+
} });
|
|
42
|
+
host = createHostStatus({ runtime, dataDir, install: installKind(), public: origin.startsWith('https://'),
|
|
43
|
+
autoBackup: () => backups.status(), onDisk: bytes => alerts.disk(bytes) });
|
|
44
|
+
void host.refresh();
|
|
45
|
+
// Hourly, so devices see current disk space and a low disk raises its alert.
|
|
46
|
+
const heartbeat = setInterval(() => { void host.refresh(); }, 60 * 60_000);
|
|
47
|
+
heartbeat.unref();
|
|
48
|
+
/** @template T @param {() => Promise<T>} task @returns {Promise<T>} */
|
|
49
|
+
const withRuntime = async task => {
|
|
50
|
+
const release = await runtime.request();
|
|
51
|
+
if (!release) throw new Error('Crate is finishing a backup. Try again shortly.');
|
|
52
|
+
try { return await task(); } finally { release(); }
|
|
53
|
+
};
|
|
54
|
+
const server = createServer(async (request, response) => {
|
|
55
|
+
if (request.headers.authorization !== `Bearer ${secret}`) { sendJson(response, 403, { error: 'Not authorized' }); return; }
|
|
56
|
+
if (request.method === 'GET' && request.url === '/devices') {
|
|
57
|
+
try { sendJson(response, 200, { devices: await withRuntime(() => listLocalDevices(runtime.db)) }); }
|
|
58
|
+
catch { sendJson(response, 500, { error: 'Could not list devices.' }); }
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (request.method === 'GET' && request.url === '/status') {
|
|
62
|
+
sendJson(response, 200, { origin, uptimeSeconds: Math.round(process.uptime()), crashes: runtime.crashes,
|
|
63
|
+
lastBackup: await readLastBackup(dataDir), autoBackup: await backups.status() });
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (request.method === 'POST' && request.url === '/revoke') {
|
|
67
|
+
try {
|
|
68
|
+
const { id } = await readSmallJson(request);
|
|
69
|
+
sendJson(response, 200, { revoked: await withRuntime(() => revokeLocalDevice(runtime, id)) });
|
|
70
|
+
} catch (error) { sendJson(response, 400, { error: error.message }); }
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (request.method === 'POST' && request.url === '/backup') {
|
|
74
|
+
try {
|
|
75
|
+
const { output } = await readSmallJson(request, 8192);
|
|
76
|
+
if (typeof output !== 'string' || !isAbsolute(output)) throw new Error('Provide an absolute backup path.');
|
|
77
|
+
sendJson(response, 200, await backups.run(output));
|
|
78
|
+
} catch (error) { sendJson(response, error.code === 'EBUSY' ? 409 : 400, { error: error.message }); }
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (request.method === 'POST' && request.url === '/auto-backup') {
|
|
82
|
+
void backups.check();
|
|
83
|
+
sendJson(response, 200, { checking: true });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (request.method !== 'POST' || request.url !== '/pair') { sendJson(response, 404, { error: 'Not found' }); return; }
|
|
87
|
+
try {
|
|
88
|
+
const { name } = await readSmallJson(request);
|
|
89
|
+
sendJson(response, 200, { ...pairing.issue(name), origin });
|
|
90
|
+
} catch { sendJson(response, 400, { error: 'Could not create a pairing code. Check the device name or wait for pending codes to expire.' }); }
|
|
91
|
+
});
|
|
92
|
+
server.requestTimeout = 5000;
|
|
93
|
+
await /** @type {Promise<void>} */ (new Promise((resolve, reject) => { server.once('error', reject); server.listen(socket, resolve); }));
|
|
94
|
+
try {
|
|
95
|
+
if (process.platform !== 'win32') await chmod(socket, 0o600);
|
|
96
|
+
await writeFile(file, JSON.stringify({ socket, secret }), { mode: 0o600 });
|
|
97
|
+
await chmod(file, 0o600);
|
|
98
|
+
} catch (error) { server.close(); clearInterval(heartbeat); await alerts.close(); await backups.close(); throw error; }
|
|
99
|
+
return {
|
|
100
|
+
/** The public address became reachable, or stopped being reachable. @param {boolean} ready */
|
|
101
|
+
onReadiness(ready) {
|
|
102
|
+
void host.refresh({ publicAccess: ready ? 'ready' : 'waiting' });
|
|
103
|
+
alerts.publicAccess(ready);
|
|
104
|
+
},
|
|
105
|
+
async close() {
|
|
106
|
+
clearInterval(heartbeat);
|
|
107
|
+
await alerts.close();
|
|
108
|
+
// A running backup holds the runtime paused; it finishes before storage closes.
|
|
109
|
+
await backups.close();
|
|
110
|
+
await host.settled();
|
|
111
|
+
server.closeAllConnections();
|
|
112
|
+
await new Promise(resolve => server.close(resolve));
|
|
113
|
+
await unlink(file).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The running server's control socket and secret (`control.json`).
|
|
119
|
+
* @typedef {{ socket: string, secret: string }} LocalControlFile */
|
|
120
|
+
|
|
121
|
+
/** Sends one request to the running server's private control socket. Rejects with
|
|
122
|
+
* code ENOENT when no server is running for this data directory.
|
|
123
|
+
* @param {string} dataDir @param {string} method @param {string} path @param {unknown} [body]
|
|
124
|
+
* @param {number} [timeout] Milliseconds to wait for the server.
|
|
125
|
+
* @returns {Promise<any>} The parsed JSON response. */
|
|
126
|
+
export async function requestLocalControl(dataDir, method, path, body, timeout = 5000) {
|
|
127
|
+
/** @type {LocalControlFile} */
|
|
128
|
+
const { socket, secret } = JSON.parse(await readFile(join(dataDir, 'control.json'), 'utf8'));
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
const request = httpRequest({ socketPath: socket, path, method,
|
|
131
|
+
headers: { Authorization: `Bearer ${secret}`, 'Content-Type': 'application/json' }, timeout,
|
|
132
|
+
}, async response => {
|
|
133
|
+
try {
|
|
134
|
+
const result = await readSmallJson(response, 1024 * 1024);
|
|
135
|
+
if (response.statusCode !== 200) throw new Error(result.error);
|
|
136
|
+
resolve(result);
|
|
137
|
+
} catch (error) { reject(error); }
|
|
138
|
+
});
|
|
139
|
+
request.on('error', reject);
|
|
140
|
+
request.on('timeout', () => request.destroy(new Error('Local administration timed out.')));
|
|
141
|
+
request.end(body === undefined ? undefined : JSON.stringify(body));
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** @param {string} dataDir @param {string | undefined} name
|
|
146
|
+
* @returns {Promise<{ code: string, expiresAt: number, origin: string }>} */
|
|
147
|
+
export async function requestLocalPairing(dataDir, name) {
|
|
148
|
+
try { return await requestLocalControl(dataDir, 'POST', '/pair', { name }); }
|
|
149
|
+
catch { throw new Error('Could not create a pairing code. Keep Crate running, check the data directory and device name, then try again.'); }
|
|
150
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { revocationPath } from './assets.mjs';
|
|
2
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
/** @type {typeof import('../../../src/cloudflare/worker/auth/revocation.ts')} */
|
|
5
|
+
const { RESET_GENERATION_SQL } = await import(pathToFileURL(revocationPath).href);
|
|
6
|
+
|
|
7
|
+
/** @typedef {import('./local-server-runtime.mjs').LocalD1Database} LocalD1Database */
|
|
8
|
+
/** @typedef {import('./local-server-runtime.mjs').LocalRuntime} LocalRuntime */
|
|
9
|
+
|
|
10
|
+
/** @param {string} value */
|
|
11
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
12
|
+
|
|
13
|
+
/** @param {LocalD1Database} db @returns {Promise<string>} */
|
|
14
|
+
export async function readResetGeneration(db) {
|
|
15
|
+
const row = await db.prepare('SELECT reset_generation AS generation FROM server_state WHERE id = 1').first();
|
|
16
|
+
return row?.generation ?? '';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** With `resetGeneration`, the device is added only while no encryption reset has
|
|
20
|
+
* happened since it was read, as the Worker's pairing does. Returns null otherwise.
|
|
21
|
+
* @param {LocalD1Database} db
|
|
22
|
+
* @param {string | undefined} name
|
|
23
|
+
* @param {string} [resetGeneration]
|
|
24
|
+
* @returns {Promise<{ id: string, token: string } | null>} */
|
|
25
|
+
export async function issueLocalDevice(db, name, resetGeneration) {
|
|
26
|
+
name = name?.trim();
|
|
27
|
+
if (!name || name.length > 128) throw new Error('Provide a device name between 1 and 128 characters.');
|
|
28
|
+
const token = randomBytes(32).toString('hex');
|
|
29
|
+
const id = randomUUID();
|
|
30
|
+
if (resetGeneration === undefined) {
|
|
31
|
+
await db.prepare("INSERT INTO auth_tokens (id, token_hash, device_name, platform, scope) VALUES (?, ?, ?, 'self-hosted', 'vault')")
|
|
32
|
+
.bind(id, digest(token), name).run();
|
|
33
|
+
return { id, token };
|
|
34
|
+
}
|
|
35
|
+
const result = await db.prepare(`INSERT INTO auth_tokens (id, token_hash, device_name, platform, scope)
|
|
36
|
+
SELECT ?, ?, ?, 'self-hosted', 'vault' WHERE ${RESET_GENERATION_SQL} = ?`)
|
|
37
|
+
.bind(id, digest(token), name, resetGeneration).run();
|
|
38
|
+
return result.meta.changes === 1 ? { id, token } : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A credential row as the devices command and control socket report it.
|
|
43
|
+
* @typedef {object} LocalDevice
|
|
44
|
+
* @property {string} id
|
|
45
|
+
* @property {string | null} name
|
|
46
|
+
* @property {string | null} platform
|
|
47
|
+
* @property {string} scope
|
|
48
|
+
* @property {string} createdAt
|
|
49
|
+
* @property {string | null} lastSeenAt
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/** Every credential the server holds, newest activity first. Shortcut capture
|
|
53
|
+
* credentials are listed too; revoking their issuing device removes them.
|
|
54
|
+
* @param {LocalD1Database} db
|
|
55
|
+
* @returns {Promise<LocalDevice[]>} */
|
|
56
|
+
export async function listLocalDevices(db) {
|
|
57
|
+
const { results } = await db.prepare(`SELECT id, device_name AS name, platform, scope, created_at AS createdAt, last_seen_at AS lastSeenAt
|
|
58
|
+
FROM auth_tokens ORDER BY COALESCE(last_seen_at, created_at) DESC, created_at DESC`).all();
|
|
59
|
+
return results;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The Worker's device revocation: the credential, its push subscriptions and the
|
|
63
|
+
* shortcut capture credentials it issued go together. A running server revokes under
|
|
64
|
+
* the coordinator lock, like the Worker, so no request the credential authenticated
|
|
65
|
+
* there commits after this returns.
|
|
66
|
+
* @param {Pick<LocalRuntime, 'revoke'>} runtime
|
|
67
|
+
* @param {unknown} id */
|
|
68
|
+
export async function revokeLocalDevice(runtime, id) {
|
|
69
|
+
if (typeof id !== 'string' || !id.trim() || id.length > 128) throw new Error('Provide --id with a token ID from the devices command.');
|
|
70
|
+
return runtime.revoke(id);
|
|
71
|
+
}
|