@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
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaanbiryol/crate-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.17.9",
|
|
4
|
+
"description": "Run Crate sync and its reminders PWA on your computer with automatic remote access.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Kaan Biryol",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/kaanbiryol/obsidian-crate.git"
|
|
11
|
+
},
|
|
12
|
+
"bin": {
|
|
13
|
+
"crate-server": "scripts/crate-server.mjs"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": "^26.8.2"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"scripts/",
|
|
20
|
+
"assets/",
|
|
21
|
+
"npm-shrinkwrap.json",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE",
|
|
24
|
+
"THIRD_PARTY_NOTICES.md",
|
|
25
|
+
"vendor/"
|
|
26
|
+
],
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"ws": "8.23.1",
|
|
32
|
+
"sharp": "0.35.5",
|
|
33
|
+
"youch": "4.1.0-beta.10",
|
|
34
|
+
"undici": "7.30.1",
|
|
35
|
+
"workerd": "1.20261123.1",
|
|
36
|
+
"@cspotcode/source-map-support": "0.8.1"
|
|
37
|
+
},
|
|
38
|
+
"crateServerRuntime": "5.20261123.1-beta",
|
|
39
|
+
"crateServerAssets": true
|
|
40
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
|
|
4
|
+
const packageRoot = resolve(import.meta.dirname, '..');
|
|
5
|
+
const metadata = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'utf8'));
|
|
6
|
+
// Only the packager sets this marker. Source modules use repository assets;
|
|
7
|
+
// installed modules must use the shipped assets and never fall back to a checkout.
|
|
8
|
+
export const packaged = metadata.crateServerAssets === true;
|
|
9
|
+
export const runtimeRoot = packaged ? packageRoot : resolve(packageRoot, '../..');
|
|
10
|
+
const runtimePackage = packaged ? metadata : JSON.parse(await readFile(join(runtimeRoot, 'package.json'), 'utf8'));
|
|
11
|
+
/** The installed package's version, or the repository's for a source checkout. */
|
|
12
|
+
export const packageVersion = /** @type {string} */ (runtimePackage.version);
|
|
13
|
+
/** @type {string} */
|
|
14
|
+
export const runtimeVersion = runtimePackage.crateServerRuntime ?? runtimePackage.devDependencies.miniflare;
|
|
15
|
+
/** @param {string} name */
|
|
16
|
+
export const serverAssetPath = name => join(runtimeRoot, packaged ? 'assets' : 'src/cloudflare', name);
|
|
17
|
+
/** The self-hosted Worker bundle, which a package ships as `assets/worker.mjs`. */
|
|
18
|
+
export const workerPath = packaged ? serverAssetPath('worker.mjs') : join(runtimeRoot, '.generated/cloudflare/worker-self-hosted.mjs');
|
|
19
|
+
// Source runs shared TypeScript modules through Node type stripping; the package ships them
|
|
20
|
+
// transpiled. scripts/package-server.mjs bundles each source into its asset.
|
|
21
|
+
export const sharedModules = /** @type {const} */ ({
|
|
22
|
+
upgradeRules: { source: 'src/cloudflare/deployment/database-upgrade-rules.ts', asset: 'database-upgrade-rules.mjs' },
|
|
23
|
+
revocation: { source: 'src/cloudflare/worker/auth/revocation.ts', asset: 'credential-revocation.mjs' },
|
|
24
|
+
coordinator: { source: 'src/cloudflare/worker/coordinator/coordinator.ts', asset: 'coordinator.mjs' },
|
|
25
|
+
// The plugin's QR encoder: a repository dependency for source, bundled into the package.
|
|
26
|
+
qrcode: { source: 'node_modules/qrcode-generator/dist/qrcode.mjs', asset: 'qrcode.mjs' },
|
|
27
|
+
});
|
|
28
|
+
/** @param {{ source: string, asset: string }} module */
|
|
29
|
+
const sharedModulePath = ({ source, asset }) => packaged ? serverAssetPath(asset) : join(runtimeRoot, source);
|
|
30
|
+
export const upgradeRulesPath = sharedModulePath(sharedModules.upgradeRules);
|
|
31
|
+
export const revocationPath = sharedModulePath(sharedModules.revocation);
|
|
32
|
+
export const coordinatorPath = sharedModulePath(sharedModules.coordinator);
|
|
33
|
+
export const qrcodeModule = sharedModulePath(sharedModules.qrcode);
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Data maintenance: backup (online or stopped), automatic backups, and the stopped-server
|
|
2
|
+
// restore, upgrade and upgrade check.
|
|
3
|
+
import { access } from 'node:fs/promises';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { backupLocalServer, checkLocalUpgrade, restoreLocalServer } from '../local-server-backup.mjs';
|
|
6
|
+
import { saveAutoBackup } from '../local-server-backup-schedule.mjs';
|
|
7
|
+
import { requestLocalControl } from '../local-server-control.mjs';
|
|
8
|
+
import { openLocalRuntime } from '../local-server-runtime.mjs';
|
|
9
|
+
import { describeAutoBackup } from './status.mjs';
|
|
10
|
+
|
|
11
|
+
/** @typedef {import('../local-server-options.mjs').Command} Command */
|
|
12
|
+
|
|
13
|
+
/** Backs up through the running server, pausing its writes briefly, or directly when it is stopped. @type {Command} */
|
|
14
|
+
export async function backup({ dataDir, values }) {
|
|
15
|
+
if (!values.output) throw new Error('Provide --output with a new backup directory.');
|
|
16
|
+
const output = resolve(values.output);
|
|
17
|
+
/** @type {{ output: string, pausedMs: number }} */
|
|
18
|
+
let online;
|
|
19
|
+
try { online = await requestLocalControl(dataDir, 'POST', '/backup', { output }, 60 * 60_000); }
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== 'ENOENT') throw new Error(`The running Crate server could not back up: ${error.message}`);
|
|
22
|
+
console.log(`Backup verified: ${await backupLocalServer(dataDir, output)}`);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
console.log(`Backup verified: ${online.output}\nSync paused for ${(online.pausedMs / 1000).toFixed(1)} s while the database was copied.`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Turns daily automatic backups on (`--output`, `--keep`) or off (`--off`). @type {Command} */
|
|
29
|
+
export async function autoBackup({ dataDir, values }) {
|
|
30
|
+
if (values.off === Boolean(values.output)) throw new Error('Provide --output with a backup directory, or --off.');
|
|
31
|
+
const keep = values.keep === undefined ? 7 : Number(values.keep);
|
|
32
|
+
const settings = await saveAutoBackup(dataDir, values.off ? null : { dir: /** @type {string} */ (values.output), keep });
|
|
33
|
+
console.log(describeAutoBackup(settings));
|
|
34
|
+
// A running server checks hourly; ask it to check now. A stopped one checks when it starts.
|
|
35
|
+
if (settings) await requestLocalControl(dataDir, 'POST', '/auto-backup').catch(() => {});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @type {Command} */
|
|
39
|
+
export async function upgrade({ dataDir, values }) {
|
|
40
|
+
if (Boolean(values.output) === Boolean(values.backup)) throw new Error('Stop the server and provide --output with a new backup directory, or --backup with the backup you just made of the stopped server.');
|
|
41
|
+
// --backup reuses that backup while it is the latest one, so an update does not copy the data twice.
|
|
42
|
+
const backup = /** @type {string} */ (values.output ?? values.backup);
|
|
43
|
+
// As for every other command, an interrupt waits for the upgrade to close the runtime
|
|
44
|
+
// and release the data directory instead of exiting mid-migration.
|
|
45
|
+
const upgraded = await openLocalRuntime({ dataDir, administrative: true, handleSignals: false, upgradeBackup: backup, reuseUpgradeBackup: Boolean(values.backup) });
|
|
46
|
+
await upgraded.close();
|
|
47
|
+
console.log('Server data upgraded. The verified backup is at ' + resolve(backup));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @type {Command} */
|
|
51
|
+
export async function restore({ dataDir, values }) {
|
|
52
|
+
if (!values.backup) throw new Error('Provide --backup with a verified backup directory. Restore into an empty data directory.');
|
|
53
|
+
await restoreLocalServer(dataDir, values.backup);
|
|
54
|
+
console.log(`Backup restored and database verified: ${dataDir}. Start Crate to resume.`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @type {Command} */
|
|
58
|
+
export async function checkUpgrade({ dataDir, values }) {
|
|
59
|
+
const checked = await checkLocalUpgrade(dataDir);
|
|
60
|
+
if (values.json) { console.log(JSON.stringify(checked)); return; }
|
|
61
|
+
console.log(`Compatible: server revision ${checked.from} → ${checked.to}, runtime ${checked.runtime}.${checked.requiresUpgrade ? ` ${checked.runtimeUpgrade ? 'The data needs the newer storage runtime' : 'The database needs a migration'}: run upgrade with a new --output backup directory before starting.` : ''} Back up before updating; no data was changed by this check.`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Before Docker serves a newer image, migrates data that needs it, after a verified backup
|
|
65
|
+
* into `backupRoot`. Incompatible data throws the check's reason; a fresh volume has nothing to check.
|
|
66
|
+
* @param {string} dataDir @param {string} backupRoot
|
|
67
|
+
* @returns {Promise<string | null>} The migration backup, or null when none was needed. */
|
|
68
|
+
export async function migrateBeforeStart(dataDir, backupRoot) {
|
|
69
|
+
if (!await access(join(dataDir, 'server.json')).then(() => true, () => false)) return null;
|
|
70
|
+
const checked = await checkLocalUpgrade(dataDir);
|
|
71
|
+
if (!checked.requiresUpgrade) return null;
|
|
72
|
+
// One backup per transition: Compose restarts a failing migration, which must not copy the data each time.
|
|
73
|
+
// A storage runtime update can keep the server revision, so its name includes the runtime.
|
|
74
|
+
const output = join(backupRoot, `before-migration-r${checked.from}-to-r${checked.to}${checked.runtimeUpgrade ? `-runtime-${checked.runtime}` : ''}`);
|
|
75
|
+
console.log(`This release needs a ${checked.runtimeUpgrade ? 'storage runtime update' : 'database migration'}. Backing up to ${output} first, unless an earlier attempt already did.`);
|
|
76
|
+
const upgraded = await openLocalRuntime({ dataDir, administrative: true, handleSignals: false, upgradeBackup: output, reuseUpgradeBackup: true });
|
|
77
|
+
await upgraded.close();
|
|
78
|
+
console.log('Server data migrated.');
|
|
79
|
+
return output;
|
|
80
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Device administration: pairing codes, offline tokens, listing and revocation.
|
|
2
|
+
import { access } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { resolveServerOrigin, resolveStartMode } from '../local-server-options.mjs';
|
|
5
|
+
import { requestLocalControl, requestLocalPairing } from '../local-server-control.mjs';
|
|
6
|
+
import { issueLocalDevice, listLocalDevices, revokeLocalDevice } from '../local-server-devices.mjs';
|
|
7
|
+
import { openLocalRuntime } from '../local-server-runtime.mjs';
|
|
8
|
+
import { pairingLink, terminalQr } from '../local-server-qr.mjs';
|
|
9
|
+
import { bold, cyan, dim } from '../local-server-style.mjs';
|
|
10
|
+
|
|
11
|
+
/** @typedef {import('../local-server-options.mjs').Command} Command */
|
|
12
|
+
|
|
13
|
+
/** The link, the code for pasting and a QR code that connect Obsidian, spaced apart so
|
|
14
|
+
* each can be found at a glance.
|
|
15
|
+
* @param {{ code: string }} pairing @param {string} origin */
|
|
16
|
+
export function formatPairing(pairing, origin) {
|
|
17
|
+
const link = pairingLink(origin, pairing.code);
|
|
18
|
+
// A loopback address means the phone itself, so a QR code could never reach this server.
|
|
19
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(new URL(origin).hostname);
|
|
20
|
+
const sections = [
|
|
21
|
+
`${bold('Connect Obsidian')}\n${dim('This code works once, for 10 minutes. Keep it private.')}`,
|
|
22
|
+
`${local ? 'This address only works on this computer. Open this link here:' : 'On a computer, open this link:'}\n ${cyan(link)}`,
|
|
23
|
+
`Or in Crate → ${bold('Connect to your server')}, paste:\n Address ${cyan(new URL(origin).origin)}\n Code ${cyan(pairing.code)}`,
|
|
24
|
+
...(local ? [] : [`On a phone or tablet, scan this with the camera:\n\n${terminalQr(link)}`]),
|
|
25
|
+
];
|
|
26
|
+
return `\n${sections.join('\n\n')}\n`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {{ code: string }} pairing @param {string} origin */
|
|
30
|
+
export function printPairing(pairing, origin) {
|
|
31
|
+
console.log(formatPairing(pairing, origin));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Uses the running server's control socket, or opens the stopped server's data.
|
|
35
|
+
* @template T
|
|
36
|
+
* @param {string} dataDir
|
|
37
|
+
* @param {string} method
|
|
38
|
+
* @param {string} path
|
|
39
|
+
* @param {unknown} body
|
|
40
|
+
* @param {(admin: import('../local-server-runtime.mjs').LocalRuntime) => Promise<T>} offline
|
|
41
|
+
* @returns {Promise<T>} */
|
|
42
|
+
async function administer(dataDir, method, path, body, offline) {
|
|
43
|
+
try { return await requestLocalControl(dataDir, method, path, body); }
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (error.code !== 'ENOENT') throw new Error(error.message || 'Could not reach the running server. Keep Crate running, check the data directory, then try again.');
|
|
46
|
+
}
|
|
47
|
+
// Never initialize an empty directory as a side effect of administration.
|
|
48
|
+
await access(join(dataDir, 'server.json')).catch(() => { throw new Error(`No Crate server data in ${dataDir}. Pass the server's --data-dir.`); });
|
|
49
|
+
const admin = await openLocalRuntime({ dataDir, administrative: true, handleSignals: false });
|
|
50
|
+
try { return await offline(admin); } finally { await admin.close(); }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @param {import('../local-server-devices.mjs').LocalDevice[]} devices */
|
|
54
|
+
function printDevices(devices) {
|
|
55
|
+
if (!devices.length) { console.log('No devices are connected.'); return; }
|
|
56
|
+
/** @type {Record<string, string>} */
|
|
57
|
+
const labels = { vault: 'Obsidian', reminders: 'Reminders web app', reading_capture: 'Reading shortcut' };
|
|
58
|
+
for (const device of devices) {
|
|
59
|
+
console.log(`${device.id} ${device.name || 'Unnamed'} · ${labels[device.scope] ?? device.scope}${device.platform ? ` (${device.platform})` : ''} · last seen ${device.lastSeenAt ? `${device.lastSeenAt} UTC` : 'never'}`);
|
|
60
|
+
}
|
|
61
|
+
console.log('Revoke one with the revoke command and --id TOKEN_ID.');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @param {string | undefined} name @param {{ id: string, token: string }} credential */
|
|
65
|
+
function printDevice(name, credential) {
|
|
66
|
+
console.log(`Device: ${name}\nToken ID: ${credential.id}\nAccess token (shown once): ${credential.token}\nPaste this token into Crate → Connect to your server. Keep it private.`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @type {Command} */
|
|
70
|
+
export async function listDevices({ dataDir }) {
|
|
71
|
+
printDevices((await administer(dataDir, 'GET', '/devices', undefined, async admin => ({ devices: await listLocalDevices(admin.db) }))).devices);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @type {Command} */
|
|
75
|
+
export async function revoke({ dataDir, values }) {
|
|
76
|
+
if (!values.id?.trim()) throw new Error('Provide --id with a token ID from the devices command.');
|
|
77
|
+
const id = values.id.trim();
|
|
78
|
+
const { revoked } = await administer(dataDir, 'POST', '/revoke', { id }, async admin => ({ revoked: await revokeLocalDevice(admin, id) }));
|
|
79
|
+
if (!revoked) throw new Error('No device has that token ID. Run the devices command to list current IDs.');
|
|
80
|
+
console.log('Device revoked. It can no longer sync; pair it again to reconnect.');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Asks the running server for a pairing code. @type {Command} */
|
|
84
|
+
export async function pair({ dataDir, values }) {
|
|
85
|
+
const pairing = await requestLocalPairing(dataDir, values.name);
|
|
86
|
+
console.log(`Server address to paste into Obsidian: ${bold(pairing.origin)}`);
|
|
87
|
+
printPairing(pairing, pairing.origin);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Issues a token offline, so the server must be stopped. It resolves the listener and
|
|
91
|
+
* origin like start does, so the same options are validated. @type {Command} */
|
|
92
|
+
export async function addDevice({ dataDir, values, signal }, resources) {
|
|
93
|
+
const { tailscale, port, host } = resolveStartMode('add-device', values, null);
|
|
94
|
+
signal.throwIfAborted();
|
|
95
|
+
const origin = resolveServerOrigin({ remote: null, tailscale, origin: values.origin, port, host });
|
|
96
|
+
const runtime = resources.runtime = await openLocalRuntime({ dataDir, origin, administrative: true, handleSignals: false });
|
|
97
|
+
signal.throwIfAborted();
|
|
98
|
+
// Without a reset generation, issueLocalDevice always returns a credential.
|
|
99
|
+
printDevice(values.name, /** @type {{ id: string, token: string }} */ (await issueLocalDevice(runtime.db, values.name)));
|
|
100
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// The doctor command: checks what keeps a self-hosted server working and prints one fix
|
|
2
|
+
// for each problem. It changes nothing.
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { access } from 'node:fs/promises';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { readLastBackup } from '../local-server-backup.mjs';
|
|
8
|
+
import { readAutoBackup } from '../local-server-backup-schedule.mjs';
|
|
9
|
+
import { LOW_DISK_BYTES } from '../local-server-alerts.mjs';
|
|
10
|
+
import { freeBytes } from '../local-server-host-status.mjs';
|
|
11
|
+
import { crateCommand, installKind } from '../local-server-install.mjs';
|
|
12
|
+
import { requestLocalControl } from '../local-server-control.mjs';
|
|
13
|
+
import { serviceState } from '../local-server-service.mjs';
|
|
14
|
+
import { findTailscale, tailscaleHostname } from '../local-server-tailscale.mjs';
|
|
15
|
+
import { readRemoteSettings } from '../local-server-tunnel.mjs';
|
|
16
|
+
|
|
17
|
+
/** @typedef {import('../local-server-options.mjs').Command} Command */
|
|
18
|
+
/** @typedef {{ status: 'pass' | 'warn' | 'fail', name: string, detail: string }} Check */
|
|
19
|
+
|
|
20
|
+
const execFileAsync = promisify(execFile);
|
|
21
|
+
const DAY = 24 * 60 * 60_000;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Everything doctor looks at; tests replace each probe.
|
|
25
|
+
* @typedef {object} DoctorProbes
|
|
26
|
+
* @property {string} node
|
|
27
|
+
* @property {boolean} hasData
|
|
28
|
+
* @property {() => Promise<{ origin: string, autoBackup: { settings: unknown, lastFailure: { at: string } | null } } | null>} running
|
|
29
|
+
* @property {() => Promise<{ mode?: string, hostname?: string } | null>} remote
|
|
30
|
+
* @property {(origin: string) => Promise<boolean>} reachable
|
|
31
|
+
* @property {() => Promise<string>} tailscale Rejects with the reason when Funnel cannot serve.
|
|
32
|
+
* @property {() => Promise<boolean>} cloudflared
|
|
33
|
+
* @property {() => Promise<{ supported: boolean, installed: boolean, running: boolean, keepAwake: boolean, dataDir: string | null }>} service
|
|
34
|
+
* @property {() => Promise<{ dir: string } | null>} autoBackup
|
|
35
|
+
* @property {() => Promise<{ createdAt: string } | null>} lastBackup
|
|
36
|
+
* @property {(path: string) => Promise<number | null>} free
|
|
37
|
+
* @property {() => Promise<number | null>} sleepMinutes System sleep in minutes on macOS; null elsewhere.
|
|
38
|
+
* @property {string} dataDir
|
|
39
|
+
* @property {(args: string) => string} command
|
|
40
|
+
* @property {() => number} now
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/** @param {DoctorProbes} probes @returns {Promise<Check[]>} */
|
|
44
|
+
export async function diagnose(probes) {
|
|
45
|
+
/** @type {Check[]} */
|
|
46
|
+
const checks = [];
|
|
47
|
+
const check = (/** @type {Check['status']} */ status, /** @type {string} */ name, /** @type {string} */ detail) => { checks.push({ status, name, detail }); };
|
|
48
|
+
const [major, minor] = probes.node.split('.').map(Number);
|
|
49
|
+
check(major === 26 && minor >= 8 ? 'pass' : 'fail', 'Node.js', major === 26 && minor >= 8 ? probes.node : `${probes.node}: install Node.js 26.8.2 or a later 26.x release.`);
|
|
50
|
+
if (!probes.hasData) {
|
|
51
|
+
check('fail', 'Server data', `No Crate server in ${probes.dataDir}. Run ${probes.command('setup')}, or pass the server's --data-dir.`);
|
|
52
|
+
return checks;
|
|
53
|
+
}
|
|
54
|
+
check('pass', 'Server data', probes.dataDir);
|
|
55
|
+
const running = await probes.running();
|
|
56
|
+
const service = await probes.service();
|
|
57
|
+
const managed = service.installed && service.dataDir === probes.dataDir;
|
|
58
|
+
check(running ? 'pass' : 'fail', 'Running', running ? `at ${running.origin}` : managed ? 'The service is installed but Crate is not running. Check its log.' : `Start it with ${probes.command('start')}.`);
|
|
59
|
+
if (!service.supported) check('warn', 'Start at login', 'Not available on this system; use Docker to keep Crate running.');
|
|
60
|
+
else if (!managed) check('warn', 'Start at login', `Crate stops when this terminal closes or the computer restarts. Run ${probes.command('service')}.`);
|
|
61
|
+
else check(service.running ? 'pass' : 'fail', 'Start at login', service.running ? 'Installed and running.' : `Installed but not running. Reinstall it with ${probes.command('service')}.`);
|
|
62
|
+
const remote = await probes.remote().catch(error => { check('fail', 'Remote access', error.message); return undefined; });
|
|
63
|
+
if (remote === null) check('warn', 'Remote access', `Only this computer can connect. For phones, run ${probes.command('setup --tailscale')}.`);
|
|
64
|
+
else if (remote?.mode === 'quick') check('warn', 'Remote access', 'A temporary address changes on every restart. Run setup --tailscale or setup --hostname for a permanent one.');
|
|
65
|
+
else if (remote?.mode === 'tailscale') {
|
|
66
|
+
await probes.tailscale().then(name => check(name === remote.hostname ? 'pass' : 'fail', 'Tailscale', name === remote.hostname ? `Funnel serves ${name}.`
|
|
67
|
+
: `This computer is now ${name} in Tailscale; rename it back to ${remote.hostname}.`), error => check('fail', 'Tailscale', error.message));
|
|
68
|
+
} else if (remote) {
|
|
69
|
+
const installed = await probes.cloudflared();
|
|
70
|
+
check(installed ? 'pass' : 'fail', 'Cloudflare Tunnel', installed ? `Serves ${remote.hostname}.` : 'cloudflared is missing. Install it: https://developers.cloudflare.com/tunnel/downloads/');
|
|
71
|
+
}
|
|
72
|
+
if (running?.origin.startsWith('https://')) {
|
|
73
|
+
const ok = await probes.reachable(running.origin);
|
|
74
|
+
check(ok ? 'pass' : 'fail', 'Public address', ok ? `${running.origin} reaches this server.` : `${running.origin} does not answer. Check the tunnel and this computer's internet connection; a new address can take 10 minutes.`);
|
|
75
|
+
}
|
|
76
|
+
const auto = await probes.autoBackup();
|
|
77
|
+
const last = await probes.lastBackup();
|
|
78
|
+
const failure = running?.autoBackup.lastFailure;
|
|
79
|
+
if (!auto) check('warn', 'Daily backups', `Off. Turn them on with ${probes.command('auto-backup --output PATH')}.`);
|
|
80
|
+
else if (failure) check('fail', 'Daily backups', `The last one failed at ${failure.at}. See the server log; Crate retries hourly.`);
|
|
81
|
+
else check('pass', 'Daily backups', `To ${auto.dir}.`);
|
|
82
|
+
if (last && probes.now() - Date.parse(last.createdAt) > 2 * DAY) check('warn', 'Last backup', `${last.createdAt}, more than two days ago.`);
|
|
83
|
+
else if (last) check('pass', 'Last backup', last.createdAt);
|
|
84
|
+
const free = (await Promise.all([probes.dataDir, ...(auto ? [auto.dir] : [])].map(probes.free))).filter(size => size !== null);
|
|
85
|
+
if (free.length) {
|
|
86
|
+
const least = Math.min(...free);
|
|
87
|
+
check(least < LOW_DISK_BYTES ? 'fail' : 'pass', 'Disk space', `${(least / 1024 ** 3).toFixed(1)} GB free${least < LOW_DISK_BYTES ? '. Free some space so sync and backups keep working.' : '.'}`);
|
|
88
|
+
}
|
|
89
|
+
const sleep = await probes.sleepMinutes();
|
|
90
|
+
if (sleep && !(managed && service.keepAwake)) check('warn', 'Sleep', `This Mac sleeps after ${sleep} minute${sleep === 1 ? '' : 's'} idle, which pauses sync. Run ${probes.command('service --keep-awake')}, or change it in System Settings → Energy.`);
|
|
91
|
+
return checks;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @type {Command} */
|
|
95
|
+
export async function doctor({ dataDir }) {
|
|
96
|
+
const kind = installKind();
|
|
97
|
+
const checks = await diagnose({
|
|
98
|
+
node: process.versions.node,
|
|
99
|
+
hasData: await access(join(dataDir, 'server.json')).then(() => true, () => false),
|
|
100
|
+
running: () => requestLocalControl(dataDir, 'GET', '/status').catch(() => null),
|
|
101
|
+
remote: () => readRemoteSettings(dataDir),
|
|
102
|
+
reachable: async origin => {
|
|
103
|
+
try {
|
|
104
|
+
const response = await fetch(`${origin}/.well-known/crate`, { redirect: 'error', signal: AbortSignal.timeout(10_000) });
|
|
105
|
+
return response.ok && /** @type {{ service?: unknown }} */ (await response.json()).service === 'crate';
|
|
106
|
+
} catch { return false; }
|
|
107
|
+
},
|
|
108
|
+
tailscale: async () => tailscaleHostname(await findTailscale()),
|
|
109
|
+
cloudflared: () => execFileAsync('cloudflared', ['--version']).then(() => true, () => false),
|
|
110
|
+
service: () => serviceState(),
|
|
111
|
+
autoBackup: () => readAutoBackup(dataDir),
|
|
112
|
+
lastBackup: () => readLastBackup(dataDir),
|
|
113
|
+
free: freeBytes,
|
|
114
|
+
sleepMinutes: async () => {
|
|
115
|
+
if (process.platform !== 'darwin') return null;
|
|
116
|
+
const match = (await execFileAsync('pmset', ['-g']).catch(() => ({ stdout: '' }))).stdout.match(/^\s*sleep\s+(\d+)/m);
|
|
117
|
+
return match ? Number(match[1]) : null;
|
|
118
|
+
},
|
|
119
|
+
dataDir,
|
|
120
|
+
command: args => crateCommand(kind, args),
|
|
121
|
+
now: Date.now,
|
|
122
|
+
});
|
|
123
|
+
const marks = { pass: '✓', warn: '!', fail: '✗' };
|
|
124
|
+
for (const { status, name, detail } of checks) console.log(`${marks[status]} ${name}: ${detail}`);
|
|
125
|
+
if (checks.some(item => item.status === 'fail')) process.exitCode = 1;
|
|
126
|
+
else console.log(checks.some(item => item.status === 'warn') ? '\nCrate works; the notes above make it more reliable.' : '\nEverything looks good.');
|
|
127
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// The service command: start Crate at login and keep it running, or stop doing so.
|
|
2
|
+
import { access } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { installKind } from '../local-server-install.mjs';
|
|
5
|
+
import { installService, uninstallService } from '../local-server-service.mjs';
|
|
6
|
+
|
|
7
|
+
/** @typedef {import('../local-server-options.mjs').Command} Command */
|
|
8
|
+
|
|
9
|
+
/** @type {Command} */
|
|
10
|
+
export async function service({ dataDir, values }) {
|
|
11
|
+
if (values.off) {
|
|
12
|
+
console.log(await uninstallService() ? 'Crate no longer starts automatically. It has been stopped.' : 'Crate was not set to start automatically.');
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
await access(join(dataDir, 'server.json')).catch(() => { throw new Error(`No Crate server data in ${dataDir}. Run setup first, then service.`); });
|
|
16
|
+
if (installKind() === 'npx') throw new Error('A service needs a lasting install. Run npm install -g @kaanbiryol/crate-server, then crate-server service.');
|
|
17
|
+
const { log } = await installService({ dataDir, keepAwake: Boolean(values['keep-awake']), maxFileSize: values['max-file-size'] });
|
|
18
|
+
console.log(`Crate now starts when you log in and restarts after a failure.\nLog: ${log}\nStop it with the service --off command.${process.platform === 'linux' ? '\nTo keep it running after you log out, run once: sudo loginctl enable-linger "$USER"' : ''}`);
|
|
19
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// Stable address setup: Tailscale Funnel or a named Cloudflare Tunnel. Each step locks
|
|
2
|
+
// storage before provisioning and returns the saved remote settings that start serves.
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { open, stat } from 'node:fs/promises';
|
|
5
|
+
import { hostname as computerName } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { createInterface } from 'node:readline/promises';
|
|
8
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
10
|
+
import { packageVersion, packaged, runtimeRoot } from '../assets.mjs';
|
|
11
|
+
import { saveAutoBackup } from '../local-server-backup-schedule.mjs';
|
|
12
|
+
import { PACKAGE_NAME, crateCommand, installKind } from '../local-server-install.mjs';
|
|
13
|
+
import { requestLocalControl, requestLocalPairing } from '../local-server-control.mjs';
|
|
14
|
+
import { runProcess } from '../local-server-process.mjs';
|
|
15
|
+
import { openLocalRuntime } from '../local-server-runtime.mjs';
|
|
16
|
+
import { installService, servicePaths } from '../local-server-service.mjs';
|
|
17
|
+
import { assertFunnelPortFree, currentTailscaleHostname, findTailscale, tailscaleSocket } from '../local-server-tailscale.mjs';
|
|
18
|
+
import { ensureCloudflared, normalizeTunnelHostname, saveTailscaleSettings, setupRemoteAccess } from '../local-server-tunnel.mjs';
|
|
19
|
+
import { runSetupWizard } from '../local-server-wizard.mjs';
|
|
20
|
+
import { printPairing } from './devices.mjs';
|
|
21
|
+
import { bold, cyan, dim, green, red } from '../local-server-style.mjs';
|
|
22
|
+
import { describeAutoBackup } from './status.mjs';
|
|
23
|
+
|
|
24
|
+
const execFileAsync = promisify(execFile);
|
|
25
|
+
|
|
26
|
+
/** @typedef {import('../local-server-options.mjs').CommandContext} CommandContext */
|
|
27
|
+
/** @typedef {import('../local-server-lifecycle.mjs').CommandResources} CommandResources */
|
|
28
|
+
/** @typedef {import('../local-server-tunnel.mjs').RemoteSettings} RemoteSettings */
|
|
29
|
+
|
|
30
|
+
/** A source checkout builds the Worker; an installed package ships it.
|
|
31
|
+
* @param {AbortSignal} signal */
|
|
32
|
+
export async function buildIfSource(signal) {
|
|
33
|
+
if (!packaged) await runProcess(process.execPath, [join(runtimeRoot, 'scripts/build-worker.mjs')], { signal });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Saves this computer's Tailscale Funnel address.
|
|
37
|
+
* @param {CommandContext} context
|
|
38
|
+
* @param {RemoteSettings | null} remote The directory's saved settings.
|
|
39
|
+
* @param {number} port
|
|
40
|
+
* @param {CommandResources} resources
|
|
41
|
+
* @returns {Promise<RemoteSettings>} */
|
|
42
|
+
export async function setupTailscale({ dataDir, signal }, remote, port, resources) {
|
|
43
|
+
console.log(dim('Setting up Tailscale Funnel. Files stay on this computer; public HTTPS traffic passes through Tailscale.'));
|
|
44
|
+
await buildIfSource(signal);
|
|
45
|
+
// Lock and validate storage before exposing anything.
|
|
46
|
+
const runtime = resources.runtime = await openLocalRuntime({ dataDir, administrative: true, handleSignals: false });
|
|
47
|
+
const hostname = await currentTailscaleHostname(signal);
|
|
48
|
+
if (!tailscaleSocket()) await assertFunnelPortFree(await findTailscale(), hostname, port);
|
|
49
|
+
if (remote && remote.hostname !== hostname) throw new Error(`This directory was set up for https://${remote.hostname}. Rename this computer back in Tailscale to keep connected devices and PWAs.`);
|
|
50
|
+
const saved = await saveTailscaleSettings(dataDir, hostname, port);
|
|
51
|
+
await runtime.close();
|
|
52
|
+
resources.runtime = null;
|
|
53
|
+
return saved;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Provisions a named Cloudflare Tunnel and its DNS route, asking for the hostname when
|
|
57
|
+
* none is saved or given.
|
|
58
|
+
* @param {CommandContext} context
|
|
59
|
+
* @param {RemoteSettings | null} remote The directory's saved settings.
|
|
60
|
+
* @param {number} port
|
|
61
|
+
* @param {CommandResources} resources
|
|
62
|
+
* @returns {Promise<RemoteSettings>} */
|
|
63
|
+
export async function setupNamedTunnel({ dataDir, values, signal }, remote, port, resources) {
|
|
64
|
+
let hostname = values.hostname ?? remote?.hostname;
|
|
65
|
+
if (!hostname) {
|
|
66
|
+
if (!process.stdin.isTTY) throw new Error('Provide --hostname crate.example.com when setup runs without an interactive terminal.');
|
|
67
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
68
|
+
try { hostname = await prompt.question('Public hostname on your Cloudflare domain (e.g. crate.example.com): ', { signal }); }
|
|
69
|
+
finally { prompt.close(); }
|
|
70
|
+
}
|
|
71
|
+
hostname = normalizeTunnelHostname(hostname);
|
|
72
|
+
if (remote && remote.hostname !== hostname) throw new Error('This directory already has a saved hostname. Reuse it to preserve installed PWA connections.');
|
|
73
|
+
console.log(dim(`Setting up https://${hostname}. Files stay on this computer; public HTTPS traffic passes through Cloudflare.`));
|
|
74
|
+
await buildIfSource(signal);
|
|
75
|
+
// Lock and validate storage before installing or provisioning anything.
|
|
76
|
+
const runtime = resources.runtime = await openLocalRuntime({ dataDir, administrative: true, handleSignals: false });
|
|
77
|
+
signal.throwIfAborted();
|
|
78
|
+
await ensureCloudflared({ signal });
|
|
79
|
+
const saved = await setupRemoteAccess({ dataDir, hostname, port, signal });
|
|
80
|
+
await runtime.close();
|
|
81
|
+
resources.runtime = null;
|
|
82
|
+
return saved;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Setup asks its questions only in a terminal, when no option or saved setup decides.
|
|
86
|
+
* @param {CommandContext} context @param {RemoteSettings | null} remote */
|
|
87
|
+
export function wizardApplies({ command, values, docker }, remote) {
|
|
88
|
+
return command === 'setup' && !remote && !docker && !values.hostname && !values.tailscale && !values.quick
|
|
89
|
+
&& Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Asks the setup questions, saves daily backups, and either installs the service (returning
|
|
93
|
+
* null) or returns the options a foreground start serves with.
|
|
94
|
+
* @param {CommandContext} context @param {CommandResources} resources
|
|
95
|
+
* @returns {Promise<import('../local-server-options.mjs').CommandOptions | null>} */
|
|
96
|
+
export async function runWizardSetup(context, resources) {
|
|
97
|
+
const { dataDir, signal } = context;
|
|
98
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
99
|
+
let choices;
|
|
100
|
+
try { choices = await runSetupWizard({ ask: question => prompt.question(question, { signal }), findTailscale }); }
|
|
101
|
+
finally { prompt.close(); }
|
|
102
|
+
const values = { ...context.values, 'keep-awake': choices.keepAwake,
|
|
103
|
+
...(choices.access === 'tailscale' ? { tailscale: true } : choices.access === 'quick' ? { quick: true } : { hostname: choices.hostname }) };
|
|
104
|
+
const port = values.port === undefined ? choices.access === 'quick' ? 0 : 8787 : Number(values.port);
|
|
105
|
+
const configured = { ...context, values };
|
|
106
|
+
if (choices.service) {
|
|
107
|
+
// Provisioning initializes storage and needs the interactive Tailscale or Cloudflare login.
|
|
108
|
+
const remote = choices.access === 'tailscale' ? await setupTailscale(configured, null, port, resources)
|
|
109
|
+
: await setupNamedTunnel(configured, null, port, resources);
|
|
110
|
+
const backups = choices.backupDir ? await saveAutoBackup(dataDir, { dir: choices.backupDir, keep: 7 }) : null;
|
|
111
|
+
const script = await lastingScript(signal);
|
|
112
|
+
const logPath = /** @type {{ log: string }} */ (servicePaths()).log;
|
|
113
|
+
// Only this run's log lines matter; earlier runs may have left codes and errors.
|
|
114
|
+
const offset = await stat(logPath).then(info => info.size, () => 0);
|
|
115
|
+
await installService({ dataDir, keepAwake: choices.keepAwake, script, maxFileSize: values['max-file-size'] });
|
|
116
|
+
const origin = `https://${remote.hostname}`;
|
|
117
|
+
console.log(`\n${green('✓')} ${choices.access === 'tailscale' ? 'Tailscale Funnel' : 'Cloudflare Tunnel'} address: ${cyan(origin)}`
|
|
118
|
+
+ `\n${green('✓')} Starts when you log in${choices.keepAwake ? ' and keeps this Mac awake' : ''}`
|
|
119
|
+
+ `\n${green('✓')} ${backups ? `Daily backups to ${backups.dir}` : 'Daily backups are off'}`);
|
|
120
|
+
await followService({ dataDir, origin, logPath, offset, signal });
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
if (choices.backupDir) {
|
|
124
|
+
// Saving settings creates the data directory, so initialize its storage first.
|
|
125
|
+
await buildIfSource(signal);
|
|
126
|
+
const runtime = resources.runtime = await openLocalRuntime({ dataDir, administrative: true, handleSignals: false });
|
|
127
|
+
await runtime.close();
|
|
128
|
+
resources.runtime = null;
|
|
129
|
+
console.log(describeAutoBackup(await saveAutoBackup(dataDir, { dir: choices.backupDir, keep: 7 })));
|
|
130
|
+
}
|
|
131
|
+
return values;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A service needs a script that outlives npx's temporary cache.
|
|
135
|
+
* @param {AbortSignal} signal @returns {Promise<string>} */
|
|
136
|
+
async function lastingScript(signal) {
|
|
137
|
+
if (installKind() !== 'npx') return process.argv[1];
|
|
138
|
+
console.log(dim(`Installing Crate so it can start at login: npm install -g ${PACKAGE_NAME}@${packageVersion}`));
|
|
139
|
+
await runProcess('npm', ['install', '-g', `${PACKAGE_NAME}@${packageVersion}`], { signal });
|
|
140
|
+
const root = (await execFileAsync('npm', ['root', '-g'])).stdout.trim();
|
|
141
|
+
return join(root, PACKAGE_NAME, 'scripts/crate-server.mjs');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The background server's log lines that need the person during setup: Tailscale's
|
|
145
|
+
* Funnel approval link and startup errors.
|
|
146
|
+
* @param {string} log @returns {string[]} */
|
|
147
|
+
export function serviceNotices(log) {
|
|
148
|
+
return [
|
|
149
|
+
...[...log.matchAll(/https:\/\/login\.tailscale\.com\/\S+/g)].map(([link]) => `Turn on Tailscale Funnel for your tailnet: ${cyan(link)}`),
|
|
150
|
+
...[...log.matchAll(/^Error: .+$/gm)].map(([error]) => error),
|
|
151
|
+
];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Waits for the background server to answer at its public address, then shows a code
|
|
155
|
+
* that connects Obsidian. The server's log stays in its file; this shows only what needs
|
|
156
|
+
* the person: Tailscale's approval link, startup errors, readiness and the code.
|
|
157
|
+
* Ctrl+C stops waiting; the service keeps running.
|
|
158
|
+
* @param {{ dataDir: string, origin: string, logPath: string, offset: number, signal: AbortSignal }} options */
|
|
159
|
+
async function followService({ dataDir, origin, logPath, offset, signal }) {
|
|
160
|
+
const doctor = crateCommand(installKind(), 'doctor');
|
|
161
|
+
console.log(dim(`\nChecking that ${origin} is reachable. This can take a few minutes the first time.\nPress Ctrl+C to stop waiting; Crate keeps running in the background.`));
|
|
162
|
+
const surfaced = new Set();
|
|
163
|
+
let shown = '', ready = false;
|
|
164
|
+
const deadline = Date.now() + 15 * 60_000;
|
|
165
|
+
while (!signal.aborted && Date.now() < deadline && !ready) {
|
|
166
|
+
const file = await open(logPath, 'r').catch(() => null);
|
|
167
|
+
if (file) {
|
|
168
|
+
try {
|
|
169
|
+
const { size } = await file.stat();
|
|
170
|
+
if (size > offset) {
|
|
171
|
+
const buffer = Buffer.alloc(size - offset);
|
|
172
|
+
await file.read(buffer, 0, buffer.length, offset);
|
|
173
|
+
offset = size;
|
|
174
|
+
shown += buffer.toString();
|
|
175
|
+
}
|
|
176
|
+
} finally { await file.close(); }
|
|
177
|
+
}
|
|
178
|
+
for (const notice of serviceNotices(shown)) {
|
|
179
|
+
if (!surfaced.has(notice)) { surfaced.add(notice); console.log(notice.startsWith('Error: ') ? red(notice) : notice); }
|
|
180
|
+
}
|
|
181
|
+
ready = /^Ready: /m.test(shown) && await requestLocalControl(dataDir, 'GET', '/status').then(() => true, () => false);
|
|
182
|
+
if (!ready) await delay(1000, undefined, { signal }).catch(() => {});
|
|
183
|
+
}
|
|
184
|
+
if (signal.aborted) return;
|
|
185
|
+
if (!ready) {
|
|
186
|
+
console.log(`\nCrate is still waiting for ${origin} to work. It keeps trying in the background; check with: ${cyan(doctor)}\n${dim(`Log: ${logPath}`)}`);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
console.log(`${green('✓')} ${origin} is reachable`);
|
|
190
|
+
// The server shows its first code in the log once ready; with devices connected, ask for one.
|
|
191
|
+
const code = /crate-pair-[a-f0-9]{64}/.exec(shown)?.[0];
|
|
192
|
+
printPairing(code ? { code } : await requestLocalPairing(dataDir, computerName().slice(0, 128)), origin);
|
|
193
|
+
console.log(`${bold('Crate keeps running in the background.')} Check on it with: ${cyan(doctor)}\n${dim(`Log: ${logPath}`)}`);
|
|
194
|
+
}
|