@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.
Files changed (213) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +73 -2
  3. package/THIRD_PARTY_NOTICES.md +3664 -0
  4. package/assets/coordinator.mjs +116 -0
  5. package/assets/credential-revocation.mjs +18 -0
  6. package/assets/database-upgrade-rules.mjs +42 -0
  7. package/assets/migrations/README.md +19 -0
  8. package/assets/qrcode.mjs +1638 -0
  9. package/assets/schema.sql +368 -0
  10. package/assets/server-release.json +6 -0
  11. package/assets/worker-runtime.json +12 -0
  12. package/assets/worker.mjs +1458 -0
  13. package/npm-shrinkwrap.json +939 -0
  14. package/package.json +38 -4
  15. package/scripts/assets.mjs +33 -0
  16. package/scripts/commands/data.mjs +80 -0
  17. package/scripts/commands/devices.mjs +100 -0
  18. package/scripts/commands/doctor.mjs +127 -0
  19. package/scripts/commands/service.mjs +19 -0
  20. package/scripts/commands/setup.mjs +194 -0
  21. package/scripts/commands/start.mjs +171 -0
  22. package/scripts/commands/status.mjs +49 -0
  23. package/scripts/commands/update.mjs +138 -0
  24. package/scripts/crate-server.mjs +11 -0
  25. package/scripts/deployment-fingerprint.mjs +13 -0
  26. package/scripts/local-server-alerts.mjs +53 -0
  27. package/scripts/local-server-backup-schedule.mjs +153 -0
  28. package/scripts/local-server-backup.mjs +275 -0
  29. package/scripts/local-server-cloudflared.mjs +93 -0
  30. package/scripts/local-server-control.mjs +150 -0
  31. package/scripts/local-server-devices.mjs +71 -0
  32. package/scripts/local-server-host-status.mjs +72 -0
  33. package/scripts/local-server-http.mjs +120 -0
  34. package/scripts/local-server-install.mjs +22 -0
  35. package/scripts/local-server-lifecycle.mjs +54 -0
  36. package/scripts/local-server-lock.mjs +217 -0
  37. package/scripts/local-server-migrations.mjs +43 -0
  38. package/scripts/local-server-options.mjs +134 -0
  39. package/scripts/local-server-pairing.mjs +47 -0
  40. package/scripts/local-server-process.mjs +77 -0
  41. package/scripts/local-server-qr.mjs +34 -0
  42. package/scripts/local-server-quick.mjs +116 -0
  43. package/scripts/local-server-readiness.mjs +48 -0
  44. package/scripts/local-server-runtime.mjs +460 -0
  45. package/scripts/local-server-service.mjs +209 -0
  46. package/scripts/local-server-style.mjs +12 -0
  47. package/scripts/local-server-tailscale.mjs +122 -0
  48. package/scripts/local-server-tunnel.mjs +212 -0
  49. package/scripts/local-server-watchdog.mjs +37 -0
  50. package/scripts/local-server-wizard.mjs +100 -0
  51. package/scripts/local-server.mjs +100 -0
  52. package/vendor/miniflare/LICENSE +25 -0
  53. package/vendor/miniflare/dist/local-explorer-ui/assets/ArrowClockwise.es-Cs0EHtoR.js +1 -0
  54. package/vendor/miniflare/dist/local-explorer-ui/assets/Breadcrumbs-BlzUUgNz.js +1 -0
  55. package/vendor/miniflare/dist/local-explorer-ui/assets/CaretDown.es-r8EMGhHM.js +1 -0
  56. package/vendor/miniflare/dist/local-explorer-ui/assets/CaretLeft.es-CCxvlwgr.js +1 -0
  57. package/vendor/miniflare/dist/local-explorer-ui/assets/CaretRight.es-CWeeOO8C.js +1 -0
  58. package/vendor/miniflare/dist/local-explorer-ui/assets/CaretUpDown.es-Bp73BWZN.js +1 -0
  59. package/vendor/miniflare/dist/local-explorer-ui/assets/Check.es-B3dV_aVM.js +1 -0
  60. package/vendor/miniflare/dist/local-explorer-ui/assets/Copy.es-DUyM7PbX.js +1 -0
  61. package/vendor/miniflare/dist/local-explorer-ui/assets/CopyButton-DdMFsAgv.js +1 -0
  62. package/vendor/miniflare/dist/local-explorer-ui/assets/CronTriggersContext-CtoQyHCH.js +1 -0
  63. package/vendor/miniflare/dist/local-explorer-ui/assets/CronTriggersPage-BC2FvZf5.js +1 -0
  64. package/vendor/miniflare/dist/local-explorer-ui/assets/DotsThree.es-B9u_qIrH.js +1 -0
  65. package/vendor/miniflare/dist/local-explorer-ui/assets/Download.es-v8YTKdZh.js +1 -0
  66. package/vendor/miniflare/dist/local-explorer-ui/assets/List.es-GlowdvL8.js +1 -0
  67. package/vendor/miniflare/dist/local-explorer-ui/assets/ListBullets.es-DrJsrtCL.js +1 -0
  68. package/vendor/miniflare/dist/local-explorer-ui/assets/MagnifyingGlass.es-BzOo3pru.js +1 -0
  69. package/vendor/miniflare/dist/local-explorer-ui/assets/PaperPlaneTilt.es-DTLdWOnM.js +1 -0
  70. package/vendor/miniflare/dist/local-explorer-ui/assets/Paperclip.es-6Ysj3lly.js +1 -0
  71. package/vendor/miniflare/dist/local-explorer-ui/assets/Pencil.es-CDpuGAys.js +1 -0
  72. package/vendor/miniflare/dist/local-explorer-ui/assets/Plus.es-xOjOjCs5.js +1 -0
  73. package/vendor/miniflare/dist/local-explorer-ui/assets/ResourceError-DNadec0F.js +1 -0
  74. package/vendor/miniflare/dist/local-explorer-ui/assets/Spinner.es-oqUPe-aY.js +1 -0
  75. package/vendor/miniflare/dist/local-explorer-ui/assets/TableSelect-DgjN53ZF.js +25 -0
  76. package/vendor/miniflare/dist/local-explorer-ui/assets/Trash.es-DTqwcb2_.js +1 -0
  77. package/vendor/miniflare/dist/local-explorer-ui/assets/Warning.es-CLa-n7LD.js +1 -0
  78. package/vendor/miniflare/dist/local-explorer-ui/assets/X.es-BiJFnG31.js +1 -0
  79. package/vendor/miniflare/dist/local-explorer-ui/assets/_appId-Cow8QNw6.js +1 -0
  80. package/vendor/miniflare/dist/local-explorer-ui/assets/_appId-TnuOHwOA.js +5 -0
  81. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-Cow8QNw6.js +1 -0
  82. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-DMGTgdaZ.js +1 -0
  83. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-Daanvg3W.js +1 -0
  84. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-DqCj-aYZ.js +1 -0
  85. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-uYCS7veQ.js +1 -0
  86. package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Cb6ggQGG.js +1 -0
  87. package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Cow8QNw6.js +1 -0
  88. package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Daanvg3W.js +1 -0
  89. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-BW1__nAw.js +1 -0
  90. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-Cow8QNw6.js +1 -0
  91. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-DCj9M_Uf.js +1 -0
  92. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-DMGTgdaZ.js +1 -0
  93. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-Daanvg3W.js +1 -0
  94. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-uYCS7veQ.js +1 -0
  95. package/vendor/miniflare/dist/local-explorer-ui/assets/_databaseId-BEh2sOY5.js +1 -0
  96. package/vendor/miniflare/dist/local-explorer-ui/assets/_databaseId-Cow8QNw6.js +1 -0
  97. package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-Cow8QNw6.js +1 -0
  98. package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-CxJm9jpK.js +1 -0
  99. package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-Daanvg3W.js +1 -0
  100. package/vendor/miniflare/dist/local-explorer-ui/assets/_namespaceId-Cow8QNw6.js +1 -0
  101. package/vendor/miniflare/dist/local-explorer-ui/assets/_namespaceId-HT9g0tMq.js +1 -0
  102. package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-Cow8QNw6.js +1 -0
  103. package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-Daanvg3W.js +1 -0
  104. package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-DdmD-NV1.js +1 -0
  105. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-Cow8QNw6.js +1 -0
  106. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-DMGTgdaZ.js +1 -0
  107. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-Daanvg3W.js +1 -0
  108. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-WgIBBs_w.js +1 -0
  109. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-uYCS7veQ.js +1 -0
  110. package/vendor/miniflare/dist/local-explorer-ui/assets/ad-hoc-B9HL0oNk.js +1 -0
  111. package/vendor/miniflare/dist/local-explorer-ui/assets/async-t2_zA-v_.js +1 -0
  112. package/vendor/miniflare/dist/local-explorer-ui/assets/button-cdxnqcgzwko8ooha-CjoTKpgy.js +1 -0
  113. package/vendor/miniflare/dist/local-explorer-ui/assets/checkbox-kt1uojk2f9e0d0h1-D923QL-G.js +1 -0
  114. package/vendor/miniflare/dist/local-explorer-ui/assets/clipboard-text-vcbvmtne4zjk4b18-CEoJIuMe.js +1 -0
  115. package/vendor/miniflare/dist/local-explorer-ui/assets/configured-BGeRrlYf.js +1 -0
  116. package/vendor/miniflare/dist/local-explorer-ui/assets/cron-triggers-ZP5ClwAa.js +1 -0
  117. package/vendor/miniflare/dist/local-explorer-ui/assets/dialog-oqh8l3l3zutpibxx-nho54TMC.js +1 -0
  118. package/vendor/miniflare/dist/local-explorer-ui/assets/dropdown-ncwhcd912vmone8k-BAT0p_ep.js +1 -0
  119. package/vendor/miniflare/dist/local-explorer-ui/assets/email-B-IveBKB.js +1 -0
  120. package/vendor/miniflare/dist/local-explorer-ui/assets/events-ClnoiyGH.js +1 -0
  121. package/vendor/miniflare/dist/local-explorer-ui/assets/events-Cow8QNw6.js +1 -0
  122. package/vendor/miniflare/dist/local-explorer-ui/assets/field-krp6z6vfbkrvufz2-DsLUBjzS.js +1 -0
  123. package/vendor/miniflare/dist/local-explorer-ui/assets/format-CjQ0gyEW.js +1 -0
  124. package/vendor/miniflare/dist/local-explorer-ui/assets/helpers-Bz2sloWm.js +1 -0
  125. package/vendor/miniflare/dist/local-explorer-ui/assets/index-BHW_FKpE.js +30 -0
  126. package/vendor/miniflare/dist/local-explorer-ui/assets/index-CiXL10aq.css +2 -0
  127. package/vendor/miniflare/dist/local-explorer-ui/assets/input-area-no30c09udyjxshu5-T786oEMj.js +1 -0
  128. package/vendor/miniflare/dist/local-explorer-ui/assets/input-group-lxdd09p60cf27pe1-BqVz8A4J.js +1 -0
  129. package/vendor/miniflare/dist/local-explorer-ui/assets/input-h48k3uagzrgb98au-BF-hE08e.js +1 -0
  130. package/vendor/miniflare/dist/local-explorer-ui/assets/label-latndvb1ngem7we8-mWoel0Kk.js +1 -0
  131. package/vendor/miniflare/dist/local-explorer-ui/assets/link-DadJAPnd.js +1 -0
  132. package/vendor/miniflare/dist/local-explorer-ui/assets/link-provider-mn2voeohon7cj9o4-CNosc_Ni.js +13 -0
  133. package/vendor/miniflare/dist/local-explorer-ui/assets/matchContext-C1eKDtty.js +1 -0
  134. package/vendor/miniflare/dist/local-explorer-ui/assets/object._-Cow8QNw6.js +1 -0
  135. package/vendor/miniflare/dist/local-explorer-ui/assets/object._-DDwO6NT7.js +1 -0
  136. package/vendor/miniflare/dist/local-explorer-ui/assets/object._-Daanvg3W.js +1 -0
  137. package/vendor/miniflare/dist/local-explorer-ui/assets/observability-CC1mP6Xo.js +15 -0
  138. package/vendor/miniflare/dist/local-explorer-ui/assets/observability-CX-6-j6d.js +1 -0
  139. package/vendor/miniflare/dist/local-explorer-ui/assets/observability-Cow8QNw6.js +1 -0
  140. package/vendor/miniflare/dist/local-explorer-ui/assets/react-BZY8YNV6.js +1 -0
  141. package/vendor/miniflare/dist/local-explorer-ui/assets/redirect-CckYXsV1.js +1 -0
  142. package/vendor/miniflare/dist/local-explorer-ui/assets/routes-BlOyav-b.js +1 -0
  143. package/vendor/miniflare/dist/local-explorer-ui/assets/routing-CVthjHxr.js +2 -0
  144. package/vendor/miniflare/dist/local-explorer-ui/assets/routing-Cow8QNw6.js +1 -0
  145. package/vendor/miniflare/dist/local-explorer-ui/assets/routing-DMGTgdaZ.js +1 -0
  146. package/vendor/miniflare/dist/local-explorer-ui/assets/routing-uYCS7veQ.js +1 -0
  147. package/vendor/miniflare/dist/local-explorer-ui/assets/select-kva5ru5f673kah1m-DQuxH2_G.js +1 -0
  148. package/vendor/miniflare/dist/local-explorer-ui/assets/sending-BPjb3S3Y.js +1 -0
  149. package/vendor/miniflare/dist/local-explorer-ui/assets/sending-Cow8QNw6.js +1 -0
  150. package/vendor/miniflare/dist/local-explorer-ui/assets/switch-ihaydbzem62bey4p-C9M-MPNS.js +1 -0
  151. package/vendor/miniflare/dist/local-explorer-ui/assets/table-inweecadl3her7pd-UWLv9e8D.js +1 -0
  152. package/vendor/miniflare/dist/local-explorer-ui/assets/text-nmyi1rkwdj37f30f-BLzIhmEO.js +1 -0
  153. package/vendor/miniflare/dist/local-explorer-ui/assets/types-DTx0hLYz.js +1 -0
  154. package/vendor/miniflare/dist/local-explorer-ui/assets/useCursorPaginatedList-BGUINn38.js +1 -0
  155. package/vendor/miniflare/dist/local-explorer-ui/assets/useRouterState-BLq6Ai_6.js +1 -0
  156. package/vendor/miniflare/dist/local-explorer-ui/favicon.svg +3 -0
  157. package/vendor/miniflare/dist/local-explorer-ui/index.html +27 -0
  158. package/vendor/miniflare/dist/src/index.d.ts +14183 -0
  159. package/vendor/miniflare/dist/src/index.js +123738 -0
  160. package/vendor/miniflare/dist/src/mdream_edge_bg.wasm +0 -0
  161. package/vendor/miniflare/dist/src/plugins/artifacts/git-sidecar.js +21071 -0
  162. package/vendor/miniflare/dist/src/workers/access/access-identity.worker.js +10 -0
  163. package/vendor/miniflare/dist/src/workers/analytics-engine/analytics-engine.worker.js +21 -0
  164. package/vendor/miniflare/dist/src/workers/analytics-engine/remote.worker.js +2578 -0
  165. package/vendor/miniflare/dist/src/workers/artifacts/binding.worker.js +903 -0
  166. package/vendor/miniflare/dist/src/workers/artifacts/wrapped-binding.worker.js +52 -0
  167. package/vendor/miniflare/dist/src/workers/assets/assets-kv.worker.js +27 -0
  168. package/vendor/miniflare/dist/src/workers/assets/assets.worker.js +1525 -0
  169. package/vendor/miniflare/dist/src/workers/assets/router.worker.js +1883 -0
  170. package/vendor/miniflare/dist/src/workers/assets/rpc-proxy.worker.js +55 -0
  171. package/vendor/miniflare/dist/src/workers/browser-rendering/binding.worker.js +453 -0
  172. package/vendor/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js +18 -0
  173. package/vendor/miniflare/dist/src/workers/cache/cache-entry.worker.js +24 -0
  174. package/vendor/miniflare/dist/src/workers/cache/cache.worker.js +652 -0
  175. package/vendor/miniflare/dist/src/workers/core/dev-control.worker.js +52 -0
  176. package/vendor/miniflare/dist/src/workers/core/dev-registry-proxy.worker.js +371 -0
  177. package/vendor/miniflare/dist/src/workers/core/do-wrapper.worker.js +67 -0
  178. package/vendor/miniflare/dist/src/workers/core/entry.worker.js +5516 -0
  179. package/vendor/miniflare/dist/src/workers/core/outbound.worker.js +147 -0
  180. package/vendor/miniflare/dist/src/workers/d1/database.worker.js +298 -0
  181. package/vendor/miniflare/dist/src/workers/d1/entry.worker.js +143 -0
  182. package/vendor/miniflare/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js +2574 -0
  183. package/vendor/miniflare/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js +11 -0
  184. package/vendor/miniflare/dist/src/workers/email/email-store.worker.js +606 -0
  185. package/vendor/miniflare/dist/src/workers/email/email.worker.js +26 -0
  186. package/vendor/miniflare/dist/src/workers/email/send_email.worker.js +3703 -0
  187. package/vendor/miniflare/dist/src/workers/flagship/binding.worker.js +394 -0
  188. package/vendor/miniflare/dist/src/workers/flagship/object.worker.js +349 -0
  189. package/vendor/miniflare/dist/src/workers/hello-world/binding.worker.js +18 -0
  190. package/vendor/miniflare/dist/src/workers/hello-world/object.worker.js +13 -0
  191. package/vendor/miniflare/dist/src/workers/images/images.worker.js +450 -0
  192. package/vendor/miniflare/dist/src/workers/k2/binding.worker.js +2583 -0
  193. package/vendor/miniflare/dist/src/workers/kv/namespace.worker.js +323 -0
  194. package/vendor/miniflare/dist/src/workers/kv/sites.worker.js +148 -0
  195. package/vendor/miniflare/dist/src/workers/local-explorer/explorer.worker.js +17275 -0
  196. package/vendor/miniflare/dist/src/workers/observability/collector.worker.js +725 -0
  197. package/vendor/miniflare/dist/src/workers/pipelines/pipeline.worker.js +9 -0
  198. package/vendor/miniflare/dist/src/workers/queues/broker.worker.js +391 -0
  199. package/vendor/miniflare/dist/src/workers/r2/bucket.worker.js +1171 -0
  200. package/vendor/miniflare/dist/src/workers/r2/public.worker.js +1319 -0
  201. package/vendor/miniflare/dist/src/workers/r2/s3/index.worker.js +11128 -0
  202. package/vendor/miniflare/dist/src/workers/ratelimit/ratelimit-object.worker.js +55 -0
  203. package/vendor/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js +69 -0
  204. package/vendor/miniflare/dist/src/workers/secrets-store/secret.worker.js +64 -0
  205. package/vendor/miniflare/dist/src/workers/shared/index.worker.js +730 -0
  206. package/vendor/miniflare/dist/src/workers/shared/object-entry.worker.js +33 -0
  207. package/vendor/miniflare/dist/src/workers/shared/remote-proxy-client.worker.js +2698 -0
  208. package/vendor/miniflare/dist/src/workers/shared/zod.worker.js +15459 -0
  209. package/vendor/miniflare/dist/src/workers/stream/binding.worker.js +282 -0
  210. package/vendor/miniflare/dist/src/workers/stream/object.worker.js +479 -0
  211. package/vendor/miniflare/dist/src/workers/workflows/binding.worker.js +5137 -0
  212. package/vendor/miniflare/dist/src/workers/workflows/wrapped-binding.worker.js +111 -0
  213. package/vendor/miniflare/package.json +135 -0
@@ -0,0 +1,12 @@
1
+ // Terminal emphasis for interactive output. Logs, pipes and NO_COLOR stay plain text,
2
+ // so log followers and tests match the same words.
3
+ const styled = Boolean(process.stdout.isTTY) && !('NO_COLOR' in process.env);
4
+
5
+ /** @param {number} open @param {number} close */
6
+ const style = (open, close) => (/** @type {string} */ text) => styled ? `\x1b[${open}m${text}\x1b[${close}m` : text;
7
+
8
+ export const bold = style(1, 22);
9
+ export const dim = style(2, 22);
10
+ export const green = style(32, 39);
11
+ export const red = style(31, 39);
12
+ export const cyan = style(36, 39);
@@ -0,0 +1,122 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { request } from 'node:http';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { promisify } from 'node:util';
5
+ import { startProcess } from './local-server-process.mjs';
6
+ import { normalizeTunnelHostname } from './local-server-tunnel.mjs';
7
+
8
+ const execFileAsync = promisify(execFile);
9
+ // The Mac app ships its CLI inside the bundle and does not always add it to PATH.
10
+ const MAC_APP_CLI = '/Applications/Tailscale.app/Contents/MacOS/Tailscale';
11
+
12
+ /** @param {{ platform?: NodeJS.Platform, run?: (command: string, args: string[]) => Promise<{ stdout: string }> }} [options] */
13
+ export async function findTailscale({ platform = process.platform, run = execFileAsync } = {}) {
14
+ for (const command of ['tailscale', ...(platform === 'darwin' ? [MAC_APP_CLI] : [])]) {
15
+ try { await run(command, ['version']); return command; }
16
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
17
+ }
18
+ throw new Error('Install Tailscale and sign in, then rerun setup: https://tailscale.com/download');
19
+ }
20
+
21
+ /**
22
+ * The `tailscale status --json` fields Crate reads.
23
+ * @typedef {{ BackendState?: string, AuthURL?: string, Self?: { DNSName?: unknown } }} TailscaleStatus
24
+ */
25
+
26
+ /** @param {string} text @returns {TailscaleStatus} */
27
+ function parseStatus(text) {
28
+ try { return JSON.parse(text); }
29
+ catch { throw new Error('Could not read Tailscale status. Update Tailscale, then retry.'); }
30
+ }
31
+
32
+ /** @param {TailscaleStatus | null} status */
33
+ function hostnameFromStatus(status) {
34
+ if (status?.BackendState !== 'Running') throw new Error('Tailscale is not connected. Open Tailscale or run tailscale up, sign in, then retry.');
35
+ const name = typeof status.Self?.DNSName === 'string' ? status.Self.DNSName.replace(/\.$/, '') : '';
36
+ if (!name.endsWith('.ts.net')) throw new Error('Turn on MagicDNS and HTTPS certificates for your tailnet, then retry: https://login.tailscale.com/admin/dns');
37
+ return normalizeTunnelHostname(name);
38
+ }
39
+
40
+ /** This machine's stable public name, from the signed-in Tailscale client.
41
+ * @param {string} command
42
+ * @param {{ run?: (command: string, args: string[]) => Promise<{ stdout: string }> }} [options] */
43
+ export async function tailscaleHostname(command, { run = execFileAsync } = {}) {
44
+ return hostnameFromStatus(parseStatus((await run(command, ['status', '--json'])).stdout));
45
+ }
46
+
47
+ /** In Docker, a Tailscale container next to Crate serves Funnel. Crate reads its
48
+ * name over the LocalAPI socket the two containers share. */
49
+ export const tailscaleSocket = () => process.env.CRATE_TAILSCALE_SOCKET || null;
50
+
51
+ /** @param {string} socketPath @returns {Promise<string>} */
52
+ function localApiStatus(socketPath) {
53
+ return new Promise((resolve, reject) => {
54
+ const call = request({ socketPath, path: '/localapi/v0/status', headers: { Host: 'local-tailscaled.sock' }, timeout: 5000 }, response => {
55
+ let body = '';
56
+ response.on('data', chunk => { body += chunk; if (body.length > 4 * 1024 * 1024) call.destroy(new Error('Tailscale status is too large.')); });
57
+ response.on('end', () => response.statusCode === 200 ? resolve(body) : reject(new Error(`Tailscale status failed (${response.statusCode}).`)));
58
+ });
59
+ call.on('error', reject);
60
+ call.on('timeout', () => call.destroy(new Error('Tailscale status timed out.')));
61
+ call.end();
62
+ });
63
+ }
64
+
65
+ /** Waits while the Tailscale container starts or waits for sign-in, showing its login link once.
66
+ * @param {string} socketPath
67
+ * @param {{ signal?: AbortSignal, interval?: number, log?: (message: string) => void, status?: (socketPath: string) => Promise<string> }} [options] */
68
+ export async function socketTailscaleHostname(socketPath, { signal, interval = 2000, log = console.log, status = localApiStatus } = {}) {
69
+ let announced = '';
70
+ for (;;) {
71
+ signal?.throwIfAborted();
72
+ let current = null;
73
+ try { current = parseStatus(await status(socketPath)); }
74
+ catch (error) { if (!['ENOENT', 'ECONNREFUSED'].includes(error.code)) throw error; }
75
+ if (current?.BackendState === 'Running') return hostnameFromStatus(current);
76
+ const message = current?.AuthURL ? `Sign in to Tailscale to finish setup: ${current.AuthURL}` : 'Waiting for the Tailscale container to start and sign in.';
77
+ if (message !== announced) { log(message); announced = message; }
78
+ await delay(interval, undefined, { signal });
79
+ }
80
+ }
81
+
82
+ /** The saved name, read from the CLI or, in Docker, the shared socket.
83
+ * @param {AbortSignal} [signal] */
84
+ export async function currentTailscaleHostname(signal) {
85
+ const socket = tailscaleSocket();
86
+ return socket ? socketTailscaleHostname(socket, { signal }) : tailscaleHostname(await findTailscale());
87
+ }
88
+
89
+ /** Funnel serves Crate on port 443, which `tailscale serve` can already give to another app
90
+ * on this computer. Tailscale then refuses with "listener already exists", so say which.
91
+ * @param {string} command @param {string} hostname @param {number} port
92
+ * @param {{ run?: (command: string, args: string[]) => Promise<{ stdout: string }> }} [options] */
93
+ export async function assertFunnelPortFree(command, hostname, port, { run = execFileAsync } = {}) {
94
+ /** @type {{ TCP?: Record<string, unknown>, Web?: Record<string, { Handlers?: Record<string, { Proxy?: string }> }> }} */
95
+ let config;
96
+ try { config = JSON.parse((await run(command, ['serve', 'status', '--json'])).stdout || '{}'); }
97
+ catch { return; }
98
+ if (!config?.TCP?.['443']) return;
99
+ const handlers = Object.values(config.Web?.[`${hostname}:443`]?.Handlers ?? {});
100
+ if (handlers.length && handlers.every(handler => handler.Proxy === `http://127.0.0.1:${port}`)) return;
101
+ const other = handlers.map(handler => handler.Proxy).filter(Boolean).join(', ');
102
+ throw new Error(`Tailscale already serves ${other || 'another app'} at https://${hostname}, and Funnel needs that address for Crate. Turn it off with: tailscale serve --https=443 off, then run setup again. To keep it, choose your own domain on Cloudflare instead.`);
103
+ }
104
+
105
+ /** Runs Funnel in the foreground, so stopping Crate also takes its public address offline.
106
+ * The first run prints a Tailscale link to approve Funnel for this tailnet.
107
+ * @param {import('./local-server-tunnel.mjs').RemoteSettings} settings
108
+ * @param {AbortSignal} [signal]
109
+ * @param {{ run?: (command: string, args: string[]) => Promise<{ stdout: string }>, platform?: NodeJS.Platform,
110
+ * start?: typeof startProcess, socket?: string | null }} [options]
111
+ * @returns {Promise<import('./local-server-process.mjs').StartedProcess>} */
112
+ export async function startTailscaleFunnel(settings, signal, { run = execFileAsync, platform = process.platform, start = startProcess, socket = tailscaleSocket() } = {}) {
113
+ const command = socket ? null : await findTailscale({ platform, run });
114
+ const hostname = socket ? await socketTailscaleHostname(socket, { signal }) : await tailscaleHostname(/** @type {string} */ (command), { run });
115
+ if (hostname !== settings.hostname) {
116
+ throw new Error(`This server was set up for https://${settings.hostname}, but Tailscale now names this computer ${hostname}. Rename the computer back in Tailscale; a new address requires reconnecting every device and PWA.`);
117
+ }
118
+ // The Tailscale container's serve configuration publishes Funnel; it outlives Crate restarts.
119
+ if (socket) return { exited: new Promise(() => {}), async stop() {} };
120
+ await assertFunnelPortFree(/** @type {string} */ (command), hostname, settings.port, { run });
121
+ return start(/** @type {string} */ (command), ['funnel', '--https=443', `http://127.0.0.1:${settings.port}`], { signal });
122
+ }
@@ -0,0 +1,212 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, mkdir, open, readFile, readdir, rename, stat, unlink } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { isIP } from 'node:net';
5
+ import { join, resolve } from 'node:path';
6
+ import { runProcess, startProcess, tunnelEnvironment } from './local-server-process.mjs';
7
+
8
+ /**
9
+ * Saved remote access settings (`remote.json` beside the data directory). `mode` is
10
+ * absent for a named Cloudflare Tunnel, which alone has `name`, `ready` and
11
+ * `tunnelId`; a Quick Tunnel has no `hostname`.
12
+ * @typedef {object} RemoteSettings
13
+ * @property {1} format
14
+ * @property {'quick' | 'tailscale'} [mode]
15
+ * @property {number} port
16
+ * @property {string} [hostname]
17
+ * @property {string} [name]
18
+ * @property {boolean} [ready]
19
+ * @property {string} [tunnelId]
20
+ */
21
+
22
+ /**
23
+ * The credentials file `cloudflared tunnel create` writes (`tunnel.json`).
24
+ * @typedef {{ TunnelID: string, AccountTag: string, TunnelSecret: string }} TunnelCredentials
25
+ */
26
+
27
+ /** @param {string | undefined} value @returns {string} */
28
+ export function normalizeTunnelHostname(value) {
29
+ const hostname = value?.trim().toLowerCase();
30
+ if (!hostname || hostname.length > 253 || !hostname.includes('.') || isIP(hostname)
31
+ || hostname.endsWith('.localhost') || hostname.endsWith('.local')
32
+ || hostname.split('.').some(label => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))) {
33
+ throw new Error('Provide a public DNS hostname such as crate.example.com, without https://, a port, or a path.');
34
+ }
35
+ return hostname;
36
+ }
37
+
38
+ /** @param {string} dataDir */
39
+ export function remotePaths(dataDir) {
40
+ const directory = `${resolve(dataDir)}.remote`;
41
+ return { directory, settings: join(directory, 'remote.json'), credentials: join(directory, 'tunnel.json'), config: join(directory, 'config.yml') };
42
+ }
43
+
44
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
45
+
46
+ /** @param {string} path @returns {Promise<any>} The parsed file, or undefined when it is missing. */
47
+ async function readJson(path) {
48
+ let text;
49
+ try { text = await readFile(path, 'utf8'); }
50
+ catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
51
+ try { return JSON.parse(text); }
52
+ catch { throw new Error(`Invalid JSON in ${path}. Restore this file before continuing.`); }
53
+ }
54
+
55
+ /** @param {string} dataDir @returns {Promise<RemoteSettings | null>} */
56
+ export async function readRemoteSettings(dataDir) {
57
+ const paths = remotePaths(dataDir);
58
+ /** @type {RemoteSettings | undefined} */
59
+ const settings = await readJson(paths.settings);
60
+ if (settings === undefined) {
61
+ const contents = await readdir(paths.directory).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
62
+ if (contents.some(name => name !== '.DS_Store')) throw new Error('Remote configuration files exist without remote.json. Restore the complete remote directory before continuing.');
63
+ return null;
64
+ }
65
+ if (settings?.mode === 'tailscale') {
66
+ if (settings.format !== 1 || typeof settings.hostname !== 'string' || !settings.hostname.endsWith('.ts.net')
67
+ || normalizeTunnelHostname(settings.hostname) !== settings.hostname
68
+ || !Number.isInteger(settings.port) || settings.port < 1 || settings.port > 65535) throw new Error('Invalid saved Tailscale Funnel settings. Restore them before continuing.');
69
+ return settings;
70
+ }
71
+ if (settings?.mode === 'quick') {
72
+ if (settings.format !== 1 || !Number.isInteger(settings.port) || settings.port < 0 || settings.port > 65535) throw new Error('Invalid saved Quick Tunnel settings.');
73
+ return settings;
74
+ }
75
+ if (!settings || settings.format !== 1 || typeof settings.hostname !== 'string'
76
+ || normalizeTunnelHostname(settings.hostname) !== settings.hostname
77
+ || !Number.isInteger(settings.port) || settings.port < 1 || settings.port > 65535
78
+ || typeof settings.ready !== 'boolean' || typeof settings.name !== 'string' || !settings.name.startsWith('crate-') || !uuid.test(settings.name.slice(6))
79
+ || (settings.tunnelId !== undefined && !uuid.test(settings.tunnelId)) || (settings.ready && !settings.tunnelId)) {
80
+ throw new Error('Invalid saved remote configuration. Restore it before continuing.');
81
+ }
82
+ return settings;
83
+ }
84
+
85
+ /** @param {string} dataDir @param {number} port */
86
+ export async function saveQuickSettings(dataDir, port) {
87
+ const existing = await readRemoteSettings(dataDir);
88
+ if (existing && existing.mode !== 'quick') throw new Error('This directory uses a saved stable address. Keep that setup or choose another data directory.');
89
+ const paths = remotePaths(dataDir);
90
+ await mkdir(paths.directory, { recursive: true, mode: 0o700 });
91
+ await writePrivate(paths.settings, { format: 1, mode: 'quick', port });
92
+ }
93
+
94
+ /** A Funnel address belongs to this computer's Tailscale name, so it is saved once and then reused.
95
+ * @param {string} dataDir @param {string} hostname @param {number} port */
96
+ export async function saveTailscaleSettings(dataDir, hostname, port) {
97
+ // Saved Quick Tunnel settings hold no address devices keep, so a Funnel replaces them.
98
+ const existing = await readRemoteSettings(dataDir).then(saved => saved?.mode === 'quick' ? null : saved);
99
+ if (existing && existing.mode !== 'tailscale') throw new Error('This directory already uses another remote access setup. Keep it or choose another data directory.');
100
+ if (existing && (existing.hostname !== hostname || existing.port !== port)) {
101
+ throw new Error('This data directory already has a saved address and port. Reuse them; changing the PWA origin requires a deliberate migration.');
102
+ }
103
+ const paths = remotePaths(dataDir);
104
+ await mkdir(paths.directory, { recursive: true, mode: 0o700 });
105
+ await chmod(paths.directory, 0o700);
106
+ /** @type {RemoteSettings} */
107
+ const settings = { format: 1, mode: 'tailscale', hostname, port };
108
+ await writePrivate(paths.settings, settings);
109
+ return settings;
110
+ }
111
+
112
+ /** @param {string} path @param {unknown} value */
113
+ async function writePrivate(path, value) {
114
+ const temporary = `${path}.${randomUUID()}.tmp`;
115
+ try {
116
+ const file = await open(temporary, 'wx', 0o600);
117
+ try { await file.writeFile(`${JSON.stringify(value, null, 2)}\n`); await file.sync(); }
118
+ finally { await file.close(); }
119
+ await rename(temporary, path);
120
+ } finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
121
+ }
122
+ /** @param {string} path @param {RemoteSettings} settings @returns {Promise<TunnelCredentials>} */
123
+ async function readCredentials(path, settings) {
124
+ /** @type {TunnelCredentials | undefined} */
125
+ const credentials = await readJson(path);
126
+ if (!credentials || !uuid.test(credentials.TunnelID) || typeof credentials.AccountTag !== 'string'
127
+ || !credentials.AccountTag || typeof credentials.TunnelSecret !== 'string'
128
+ || Buffer.from(credentials.TunnelSecret, 'base64').length !== 32
129
+ || (settings.tunnelId && credentials.TunnelID !== settings.tunnelId)) {
130
+ throw new Error('Tunnel credentials are missing or invalid. Restore the remote configuration directory; do not create a replacement tunnel for an existing address.');
131
+ }
132
+ await chmod(path, 0o600);
133
+ return credentials;
134
+ }
135
+
136
+ /** @param {{ signal?: AbortSignal, run?: typeof runProcess, platform?: NodeJS.Platform }} [options] */
137
+ export async function ensureCloudflared({ signal, run = runProcess, platform = process.platform } = {}) {
138
+ try { await run('cloudflared', ['--version'], { signal, stdio: 'ignore' }); }
139
+ catch (error) {
140
+ if (error.code !== 'ENOENT') throw error;
141
+ if (platform !== 'darwin') throw new Error('Install cloudflared, then rerun setup: https://developers.cloudflare.com/tunnel/downloads/');
142
+ try { await run('brew', ['--version'], { signal, stdio: 'ignore' }); }
143
+ catch { signal?.throwIfAborted(); throw new Error('Install cloudflared (brew install cloudflared), then rerun setup. Homebrew was not available.'); }
144
+ console.log('Installing cloudflared with Homebrew...');
145
+ await run('brew', ['install', 'cloudflared'], { signal });
146
+ await run('cloudflared', ['--version'], { signal, stdio: 'ignore' });
147
+ }
148
+ }
149
+
150
+ // Caller holds the server data lock throughout setup. Persist each completed
151
+ // step so a failed DNS request can resume without creating another tunnel.
152
+ /** @param {{ dataDir: string, hostname?: string, port?: number, signal?: AbortSignal, run?: typeof runProcess }} options */
153
+ export async function setupRemoteAccess({ dataDir, hostname, port, signal, run = runProcess }) {
154
+ const paths = remotePaths(dataDir);
155
+ // Saved Quick Tunnel settings hold no address devices keep, so a named tunnel replaces them.
156
+ let settings = await readRemoteSettings(dataDir).then(saved => saved?.mode === 'quick' ? null : saved);
157
+ hostname = normalizeTunnelHostname(hostname ?? settings?.hostname);
158
+ port ??= settings?.port ?? 8787;
159
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Port must be between 1 and 65535.');
160
+ if (settings && (settings.hostname !== hostname || settings.port !== port)) {
161
+ throw new Error('This data directory already has a saved hostname and port. Reuse them; changing the PWA origin requires a deliberate migration.');
162
+ }
163
+ await mkdir(paths.directory, { recursive: true, mode: 0o700 });
164
+ await chmod(paths.directory, 0o700);
165
+ if (!settings) {
166
+ settings = { format: 1, hostname, port, name: `crate-${randomUUID()}`, ready: false };
167
+ await writePrivate(paths.settings, settings);
168
+ }
169
+ const cf = (/** @type {string[]} */ args) => run('cloudflared', ['tunnel', '--config', paths.config, ...args], { signal, env: tunnelEnvironment() });
170
+ // An explicit config prevents an unrelated ~/.cloudflared/config.yml from
171
+ // changing provisioning behavior. JSON is valid YAML for cloudflared.
172
+ if (!settings.ready) {
173
+ await writePrivate(paths.config, {});
174
+ const certificate = join(homedir(), '.cloudflared', 'cert.pem');
175
+ if (!(await stat(certificate).catch(error => { if (error.code === 'ENOENT') return null; throw error; }))?.size) {
176
+ console.log('Authorize your domain in the Cloudflare browser login. On a headless host, open the printed URL on another device.');
177
+ await cf(['login']);
178
+ }
179
+ if (!(await stat(paths.credentials).catch(error => { if (error.code === 'ENOENT') return null; throw error; }))) {
180
+ if (settings.tunnelId) throw new Error('Saved tunnel credentials are missing. Restore the remote configuration directory.');
181
+ await cf(['create', '--credentials-file', paths.credentials, /** @type {string} */ (settings.name)]);
182
+ }
183
+ const credentials = await readCredentials(paths.credentials, settings);
184
+ settings.tunnelId = credentials.TunnelID;
185
+ await writePrivate(paths.settings, settings);
186
+ console.log(`Connecting ${hostname} to this tunnel. Existing DNS records will not be overwritten.`);
187
+ await cf(['route', 'dns', settings.tunnelId, hostname]);
188
+ }
189
+ await readCredentials(paths.credentials, settings);
190
+ await writeTunnelConfig(paths, settings);
191
+ await cf(['ingress', 'validate']);
192
+ signal?.throwIfAborted();
193
+ settings.ready = true;
194
+ await writePrivate(paths.settings, settings);
195
+ return settings;
196
+ }
197
+
198
+ /** @param {ReturnType<typeof remotePaths>} paths @param {RemoteSettings} settings */
199
+ async function writeTunnelConfig(paths, settings) {
200
+ await writePrivate(paths.config, { tunnel: settings.tunnelId, 'credentials-file': paths.credentials,
201
+ ingress: [{ hostname: settings.hostname, service: `http://127.0.0.1:${settings.port}` }, { service: 'http_status:404' }] });
202
+ }
203
+
204
+ /** @param {string} dataDir @param {RemoteSettings} settings @param {AbortSignal} [signal] */
205
+ export async function startTunnel(dataDir, settings, signal) {
206
+ if (!settings.ready || !settings.tunnelId) throw new Error('Remote setup is incomplete. Run npm run server -- setup again.');
207
+ const paths = remotePaths(dataDir);
208
+ await readCredentials(paths.credentials, settings);
209
+ await writeTunnelConfig(paths, settings);
210
+ return startProcess('cloudflared', ['tunnel', '--config', paths.config, '--no-autoupdate', '--loglevel', 'info',
211
+ '--metrics', '127.0.0.1:0', 'run', settings.tunnelId], { signal, env: tunnelEnvironment() });
212
+ }
@@ -0,0 +1,37 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+
3
+ /** Watches a running Workers runtime. Miniflare restarts a crashed workerd on its own;
4
+ * if that restart fails, every request fails while the process stays up. After `limit`
5
+ * missed probes in a row, `failed` rejects so serving stops and the process exits,
6
+ * letting its service manager (Docker, launchd, systemd) start a fresh one.
7
+ * @param {object} options
8
+ * @param {(signal: AbortSignal) => Promise<void>} options.probe Rejects when the runtime cannot answer.
9
+ * @param {number} [options.interval]
10
+ * @param {number} [options.timeout] Milliseconds one probe may take.
11
+ * @param {number} [options.limit] */
12
+ export function watchRuntime({ probe, interval = 15_000, timeout = 10_000, limit = 3 }) {
13
+ const controller = new AbortController();
14
+ const { signal } = controller;
15
+ /** @type {Promise<never>} */
16
+ const failed = new Promise((_, reject) => {
17
+ void (async () => {
18
+ let misses = 0;
19
+ while (!signal.aborted) {
20
+ try { await delay(interval, undefined, { signal }); } catch { return; }
21
+ try {
22
+ await probe(AbortSignal.any([signal, AbortSignal.timeout(timeout)]));
23
+ misses = 0;
24
+ } catch (error) {
25
+ if (signal.aborted) return;
26
+ if (++misses >= limit) {
27
+ reject(new Error(`The Workers runtime stopped responding (${error instanceof Error ? error.message : String(error)}). Crate is stopping so its service manager can restart it.`, { cause: error }));
28
+ return;
29
+ }
30
+ }
31
+ }
32
+ })();
33
+ });
34
+ // Callers race on `failed`; a rejection before they do must not crash the process.
35
+ failed.catch(() => {});
36
+ return { failed, close() { controller.abort(); } };
37
+ }
@@ -0,0 +1,100 @@
1
+ // The questions setup asks in a terminal when no options choose for it: how devices
2
+ // reach this computer, whether Crate starts at login and stays awake, and where daily
3
+ // backups go. It only decides; commands/start.mjs carries the choices out.
4
+ import { access } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import { join } from 'node:path';
7
+
8
+ /**
9
+ * @typedef {object} WizardChoices
10
+ * @property {'tailscale' | 'domain' | 'quick'} access
11
+ * @property {string} [hostname] The named tunnel's hostname, for `domain`.
12
+ * @property {boolean} service Start at login and keep running.
13
+ * @property {boolean} keepAwake
14
+ * @property {string | null} backupDir
15
+ */
16
+
17
+ /**
18
+ * @typedef {object} WizardEnvironment
19
+ * @property {(question: string) => Promise<string>} ask
20
+ * @property {(message: string) => void} [log]
21
+ * @property {NodeJS.Platform} [platform]
22
+ * @property {string} [home]
23
+ * @property {() => Promise<unknown>} findTailscale Rejects with install guidance.
24
+ */
25
+
26
+ /** A folder on this computer. Backups hold vault contents and server credentials, so they
27
+ * leave it only when the person chooses a synced folder such as iCloud Drive.
28
+ * @param {{ home?: string }} [options] */
29
+ export function defaultBackupDir({ home = homedir() } = {}) {
30
+ return join(home, 'crate_backups');
31
+ }
32
+
33
+ /** The iCloud Drive backup folder, when this Mac has iCloud Drive.
34
+ * @param {{ platform?: NodeJS.Platform, home?: string }} [options] @returns {Promise<string | null>} */
35
+ export async function icloudBackupDir({ platform = process.platform, home = homedir() } = {}) {
36
+ const icloud = join(home, 'Library/Mobile Documents/com~apple~CloudDocs');
37
+ return platform === 'darwin' && await access(icloud).then(() => true, () => false) ? join(icloud, 'crate_backups') : null;
38
+ }
39
+
40
+ /** @param {WizardEnvironment['ask']} ask @param {string} question @param {string[]} options @returns {Promise<number>} */
41
+ async function choose(ask, question, options) {
42
+ const list = options.map((option, index) => ` ${index + 1}. ${option}`).join('\n');
43
+ for (;;) {
44
+ const answer = (await ask(`${question}\n${list}\nChoose 1-${options.length} [1]: `)).trim();
45
+ if (!answer) return 0;
46
+ const index = Number(answer) - 1;
47
+ if (Number.isInteger(index) && index >= 0 && index < options.length) return index;
48
+ }
49
+ }
50
+
51
+ /** @param {WizardEnvironment['ask']} ask @param {string} question @param {boolean} fallback */
52
+ async function confirm(ask, question, fallback) {
53
+ for (;;) {
54
+ const answer = (await ask(`${question} [${fallback ? 'Y/n' : 'y/N'}]: `)).trim().toLowerCase();
55
+ if (!answer) return fallback;
56
+ if (['y', 'yes'].includes(answer)) return true;
57
+ if (['n', 'no'].includes(answer)) return false;
58
+ }
59
+ }
60
+
61
+ /** @param {WizardEnvironment} environment @returns {Promise<WizardChoices>} */
62
+ export async function runSetupWizard({ ask, log = console.log, platform = process.platform, home = homedir(), findTailscale }) {
63
+ log('Set up Crate on this computer. Press Enter to accept the suggestion in [brackets].\n');
64
+ /** @type {WizardChoices['access']} */
65
+ let access;
66
+ /** @type {string | undefined} */
67
+ let hostname;
68
+ for (;;) {
69
+ const index = await choose(ask, 'How will your phone and other devices reach this computer?', [
70
+ 'Tailscale Funnel: a permanent address, free, no domain needed (recommended)',
71
+ 'My own domain on Cloudflare, such as crate.example.com',
72
+ 'A temporary address to try Crate out (changes every restart)',
73
+ ]);
74
+ access = /** @type {const} */ (['tailscale', 'domain', 'quick'])[index];
75
+ if (access !== 'tailscale') break;
76
+ try { await findTailscale(); break; }
77
+ catch (error) { log(`${error.message}\nInstall Tailscale, sign in, and choose it again, or pick another option.\n`); }
78
+ }
79
+ if (access === 'domain') {
80
+ while (!hostname) hostname = (await ask('Public hostname on your Cloudflare domain (e.g. crate.example.com): ')).trim() || undefined;
81
+ }
82
+ const supported = platform === 'darwin' || platform === 'linux';
83
+ const service = supported && access !== 'quick'
84
+ && await confirm(ask, 'Start Crate when you log in, and restart it if it stops?', true);
85
+ const keepAwake = platform === 'darwin' && await confirm(ask, 'Keep this Mac awake while Crate runs, so devices can always sync?', true);
86
+ const suggested = defaultBackupDir({ home });
87
+ const icloud = await icloudBackupDir({ platform, home });
88
+ const shown = (/** @type {string} */ path) => path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
89
+ const folders = [suggested, ...(icloud ? [icloud] : [])];
90
+ const index = await choose(ask, 'Where should Crate save daily backups?', [
91
+ `${shown(suggested)} on this computer`,
92
+ ...(icloud ? [`iCloud Drive (${shown(icloud)}), so a copy is also off this computer. Backups include your vault and server credentials.`] : []),
93
+ 'Another folder',
94
+ "Don't back up",
95
+ ]);
96
+ /** @type {string | null} */
97
+ let backupDir = folders[index] ?? null;
98
+ if (index === folders.length) while (!backupDir) backupDir = (await ask('Backup folder: ')).trim() || null;
99
+ return { access, ...(hostname ? { hostname } : {}), service, keepAwake, backupDir };
100
+ }
@@ -0,0 +1,100 @@
1
+ // The CLI entry: parses arguments, turns signals into an abort, runs one command and
2
+ // closes what it opened, in order, even after a failure. Commands live in commands/.
3
+ import { homedir } from 'node:os';
4
+ import { resolve, join } from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+ import { tailscaleSocket } from './local-server-tailscale.mjs';
7
+ import { closeLocalServerResources } from './local-server-lifecycle.mjs';
8
+ import { validateCommandOptions } from './local-server-options.mjs';
9
+ import { autoBackup, backup, checkUpgrade, restore, upgrade } from './commands/data.mjs';
10
+ import { addDevice, listDevices, pair, revoke } from './commands/devices.mjs';
11
+ import { start } from './commands/start.mjs';
12
+ import { status } from './commands/status.mjs';
13
+ import { service } from './commands/service.mjs';
14
+ import { update } from './commands/update.mjs';
15
+ import { doctor } from './commands/doctor.mjs';
16
+
17
+ const help = `Crate local server
18
+
19
+ npm run server -- setup [--data-dir PATH] [--name "My Mac"]
20
+ npm run server -- setup --hostname crate.example.com [--data-dir PATH] [--port 8787]
21
+ npm run server -- setup --tailscale [--data-dir PATH] [--port 8787]
22
+ npm run server -- start [--data-dir PATH]
23
+ npm run server -- start --local [--port 8787] [--host 127.0.0.1] [--origin https://crate.example.com]
24
+ npm run server -- add-device --name "My Mac" [--data-dir PATH]
25
+ npm run server -- pair --name "My phone" [--data-dir PATH]
26
+ npm run server -- devices [--data-dir PATH]
27
+ npm run server -- revoke --id TOKEN_ID [--data-dir PATH]
28
+ npm run server -- status [--data-dir PATH]
29
+ npm run server -- backup --output PATH [--data-dir PATH]
30
+ npm run server -- auto-backup --output DIR [--keep 7] [--data-dir PATH]
31
+ npm run server -- auto-backup --off [--data-dir PATH]
32
+ npm run server -- upgrade --output NEW_BACKUP_PATH [--data-dir PATH]
33
+ npm run server -- upgrade --backup LATEST_BACKUP_PATH [--data-dir PATH]
34
+ npm run server -- restore --backup PATH --data-dir EMPTY_PATH
35
+ npm run server -- check-upgrade [--data-dir PATH]
36
+ npm run server -- service [--keep-awake] [--max-file-size MB] [--data-dir PATH]
37
+ npm run server -- service --off
38
+ npm run server -- update [--data-dir PATH]
39
+ npm run server -- doctor [--data-dir PATH]
40
+
41
+ Setup defaults to a Quick Tunnel: no account or domain. It initializes storage,
42
+ installs cloudflared if missing, and prints your address and first pairing code.
43
+ Quick Tunnel addresses change on restart; reconnect devices and re-enroll PWAs.
44
+ --hostname selects a permanent named tunnel and requires a Cloudflare domain.
45
+ --tailscale uses Tailscale Funnel for a permanent address without a domain.
46
+ Start reuses saved remote settings; --local skips the managed tunnel.
47
+ Without remote setup, start uses localhost (build first: npm run build:worker).
48
+ Use pair while the server is running to connect another device without downtime.
49
+ devices, revoke, status, backup and auto-backup work while the server runs or while it
50
+ is stopped. A running server pauses sync for a moment while backup copies its database.
51
+ auto-backup makes a verified backup every day while the server runs and keeps the newest.
52
+ service starts Crate at login (launchd on macOS, systemd on Linux) and restarts it after a failure.
53
+ --keep-awake keeps a Mac from idle sleep while Crate runs.
54
+ --max-file-size MB (start, setup, service; CRATE_MAX_FILE_SIZE_MB in Docker) syncs files up to
55
+ that size, from 25 (the default) to 1024. Above 25, every device needs the current Crate plugin
56
+ and mobile devices still skip files over 25 MB. Encrypted vaults and Markdown notes stay at 128 MB.
57
+ update installs the newest release after a verified backup and rolls back if it fails;
58
+ other installs print their own update steps. doctor checks the server and prints a fix for each problem.
59
+ Stop the server before offline add-device administration.
60
+ Default data directory: ~/.crate/server (one vault per directory).
61
+ See docs/self-hosting.md for backups, updates, and other HTTPS proxies.`;
62
+
63
+ /** @type {Record<string, import('./local-server-options.mjs').Command>} */
64
+ const commands = {
65
+ setup: start, start, 'add-device': addDevice, pair, devices: listDevices, revoke, status,
66
+ backup, 'auto-backup': autoBackup, upgrade, restore, 'check-upgrade': checkUpgrade, service, update, doctor,
67
+ };
68
+
69
+ const shutdown = new AbortController();
70
+ const stopped = new Promise(resolve => shutdown.signal.addEventListener('abort', resolve, { once: true }));
71
+ const onSignal = () => shutdown.abort();
72
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
73
+ for (const signal of signals) process.on(signal, onSignal);
74
+ const docker = process.env.CRATE_DOCKER === '1';
75
+ /** @type {import('./local-server-lifecycle.mjs').CommandResources} */
76
+ const resources = {};
77
+
78
+ try {
79
+ const { values, positionals } = parseArgs({ allowPositionals: true, options: {
80
+ 'data-dir': { type: 'string' }, port: { type: 'string' }, host: { type: 'string' }, origin: { type: 'string' },
81
+ output: { type: 'string' }, backup: { type: 'string' }, keep: { type: 'string' }, off: { type: 'boolean' },
82
+ hostname: { type: 'string' }, name: { type: 'string' }, id: { type: 'string' }, local: { type: 'boolean' }, 'keep-awake': { type: 'boolean' }, 'max-file-size': { type: 'string' }, quick: { type: 'boolean' }, tailscale: { type: 'boolean' }, help: { type: 'boolean' }, json: { type: 'boolean' },
83
+ } });
84
+ const command = positionals[0];
85
+ if (values.help || !command) console.log(help);
86
+ else {
87
+ validateCommandOptions(positionals, values, { dockerWithoutTailscale: () => docker && !tailscaleSocket() });
88
+ process.umask(0o077);
89
+ const dataDir = resolve(values['data-dir'] ?? join(homedir(), '.crate', 'server'));
90
+ await commands[command]({ command, values, dataDir, docker, signal: shutdown.signal, stopped }, resources);
91
+ }
92
+ } catch (error) {
93
+ if (!shutdown.signal.aborted) { console.error(`\nError: ${error.message}`); process.exitCode = 1; }
94
+ } finally {
95
+ try {
96
+ if (resources.quickServer) await resources.quickServer.close();
97
+ else await closeLocalServerResources(resources);
98
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
99
+ for (const signal of signals) process.removeListener(signal, onSignal);
100
+ }
@@ -0,0 +1,25 @@
1
+ Copyright (c) 2020 Cloudflare, Inc. <wrangler@cloudflare.com>
2
+
3
+ Permission is hereby granted, free of charge, to any
4
+ person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the
6
+ Software without restriction, including without
7
+ limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software
10
+ is furnished to do so, subject to the following
11
+ conditions:
12
+
13
+ The above copyright notice and this permission notice
14
+ shall be included in all copies or substantial portions
15
+ of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ import{a as e,t}from"./react-BZY8YNV6.js";import{Bt as n}from"./link-provider-mn2voeohon7cj9o4-CNosc_Ni.js";var r=e(t(),1),i=new Map([[`bold`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M244,56v48a12,12,0,0,1-12,12H184a12,12,0,1,1,0-24H201.1l-19-17.38c-.13-.12-.26-.24-.38-.37A76,76,0,1,0,127,204h1a75.53,75.53,0,0,0,52.15-20.72,12,12,0,0,1,16.49,17.45A99.45,99.45,0,0,1,128,228h-1.37A100,100,0,1,1,198.51,57.06L220,76.72V56a12,12,0,0,1,24,0Z`}))],[`duotone`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),r.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z`}))],[`fill`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1-5.66-13.66l17-17-10.55-9.65-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,1,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60l10.93,10L226.34,50.3A8,8,0,0,1,240,56Z`}))],[`light`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M238,56v48a6,6,0,0,1-6,6H184a6,6,0,0,1,0-12h32.55l-30.38-27.8c-.06-.06-.12-.13-.19-.19a82,82,0,1,0-1.7,117.65,6,6,0,0,1,8.24,8.73A93.46,93.46,0,0,1,128,222h-1.28A94,94,0,1,1,194.37,61.4L226,90.35V56a6,6,0,1,1,12,0Z`}))],[`regular`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z`}))],[`thin`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M236,56v48a4,4,0,0,1-4,4H184a4,4,0,0,1,0-8h37.7L187.53,68.69l-.13-.12a84,84,0,1,0-1.75,120.51,4,4,0,0,1,5.5,5.82A91.43,91.43,0,0,1,128,220h-1.26A92,92,0,1,1,193,62.84l35,32.05V56a4,4,0,1,1,8,0Z`}))]]),a=r.forwardRef((e,t)=>r.createElement(n,{ref:t,...e,weights:i}));a.displayName=`ArrowClockwiseIcon`;export{a as t};
@@ -0,0 +1 @@
1
+ import{a as e,n as t,t as n}from"./react-BZY8YNV6.js";import{Vt as r,t as i}from"./link-provider-mn2voeohon7cj9o4-CNosc_Ni.js";import{r as a}from"./button-cdxnqcgzwko8ooha-CjoTKpgy.js";import{t as o}from"./Check.es-B3dV_aVM.js";import{t as s}from"./Copy.es-DUyM7PbX.js";import{nn as c}from"./index-BHW_FKpE.js";var l=t(),u=e(n(),1),d={size:{sm:{classes:`text-sm h-10 gap-0.5`,description:`Compact breadcrumbs for dense UIs`},base:{classes:`text-base h-12 gap-1`,description:`Default breadcrumbs size`}}},f={size:`base`};function p({size:e=f.size}={}){return r(`group mr-4 flex min-w-0 grow items-center overflow-hidden whitespace-nowrap`,d.size[e].classes)}var m=({href:e,icon:t,children:n})=>{let r=i();return(0,l.jsxs)(r,{to:e,className:`flex min-w-0 max-w-full items-center gap-1 text-kumo-subtle no-underline`,children:[!!t&&(0,l.jsx)(`span`,{className:`flex shrink-0 items-center`,children:t}),(0,l.jsx)(`span`,{className:`truncate`,children:n})]})};function h({children:e,icon:t,loading:n}){return n?(0,l.jsxs)(`div`,{className:`flex w-[125px] min-w-0 items-center gap-1`,children:[t&&(0,l.jsx)(`span`,{className:`flex shrink-0 items-center`,children:t}),(0,l.jsx)(c,{})]}):(0,l.jsxs)(`div`,{className:`flex min-w-0 max-w-full items-center gap-1 font-medium`,"aria-current":`page`,children:[t&&(0,l.jsx)(`span`,{className:`flex shrink-0 items-center`,children:t}),(0,l.jsx)(`span`,{className:`truncate`,children:e})]})}function g(){return(0,l.jsx)(`span`,{className:`flex shrink-0 items-center text-kumo-inactive`,"aria-hidden":`true`,children:(0,l.jsx)(`svg`,{width:`24`,height:`24`,fill:`none`,viewBox:`0 0 24 24`,children:(0,l.jsx)(`path`,{stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,d:`M10.75 8.75L14.25 12L10.75 15.25`})})})}function _(){return(0,l.jsx)(`span`,{className:`flex shrink-0 items-center text-kumo-subtle`,"aria-hidden":!0,children:`...`})}function v({text:e}){let[t,n]=(0,u.useState)(!1);return(0,u.useEffect)(()=>{if(!t)return;let e=setTimeout(()=>n(!1),2e3);return()=>clearTimeout(e)},[t]),(0,l.jsx)(a,{variant:`ghost`,shape:`square`,size:`sm`,className:`opacity-0 transition-[opacity] group-hover:opacity-100`,onClick:async()=>{if(e)try{await navigator.clipboard.writeText(e),n(!0)}catch(e){console.error(`Failed to copy deeplink:`,e)}},title:`Click to copy`,"aria-label":`Copy`,children:t?(0,l.jsx)(o,{weight:`bold`,className:`text-kumo-success`}):(0,l.jsx)(s,{weight:`regular`})})}function y({children:e,size:t=`base`,className:n}){let i=u.Children.toArray(e),a=x(i);return(0,l.jsxs)(`nav`,{className:r(p({size:t}),n),"aria-label":`breadcrumb`,children:[(0,l.jsx)(`div`,{className:`contents sm:hidden`,children:a}),(0,l.jsx)(`div`,{className:`hidden sm:contents`,children:i})]})}function b(e,t){return(0,u.isValidElement)(e)&&e.type===t}function x(e){let t=e.filter(e=>b(e,m)||b(e,h));if(t.length<=2)return e;let[n,r]=t.slice(-2),i=[(0,l.jsx)(_,{},`kumo-breadcrumb-mobile-ellipsis`),(0,l.jsx)(g,{},`kumo-breadcrumb-mobile-separator-leading`),(0,u.cloneElement)(n,{key:`kumo-breadcrumb-mobile-parent`}),(0,l.jsx)(g,{},`kumo-breadcrumb-mobile-separator-trailing`),(0,u.cloneElement)(r,{key:`kumo-breadcrumb-mobile-current`})],a=e.filter(e=>!b(e,m)&&!b(e,h)&&!b(e,g));return[...i,...a]}y.Link=m,y.Current=h,y.Separator=g,y.Clipboard=v;function S({children:e,icon:t,items:n,title:r}){return(0,l.jsxs)(`div`,{className:`box-border flex min-h-14.5 shrink-0 items-center gap-2 border-b border-kumo-fill bg-kumo-elevated px-6 text-sm`,children:[(0,l.jsxs)(y,{children:[(0,l.jsx)(y.Current,{icon:(0,l.jsx)(t,{className:`h-4 w-4`}),children:r}),n.map((e,t)=>(0,l.jsxs)(u.Fragment,{children:[(0,l.jsx)(y.Separator,{}),e]},t))]}),e]})}export{y as n,S as t};
@@ -0,0 +1 @@
1
+ import{a as e,t}from"./react-BZY8YNV6.js";import{Bt as n}from"./link-provider-mn2voeohon7cj9o4-CNosc_Ni.js";var r=e(t(),1),i=new Map([[`bold`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M216.49,104.49l-80,80a12,12,0,0,1-17,0l-80-80a12,12,0,0,1,17-17L128,159l71.51-71.52a12,12,0,0,1,17,17Z`}))],[`duotone`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M208,96l-80,80L48,96Z`,opacity:`0.2`}),r.createElement(`path`,{d:`M215.39,92.94A8,8,0,0,0,208,88H48a8,8,0,0,0-5.66,13.66l80,80a8,8,0,0,0,11.32,0l80-80A8,8,0,0,0,215.39,92.94ZM128,164.69,67.31,104H188.69Z`}))],[`fill`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,48,88H208a8,8,0,0,1,5.66,13.66Z`}))],[`light`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M212.24,100.24l-80,80a6,6,0,0,1-8.48,0l-80-80a6,6,0,0,1,8.48-8.48L128,167.51l75.76-75.75a6,6,0,0,1,8.48,8.48Z`}))],[`regular`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,53.66,90.34L128,164.69l74.34-74.35a8,8,0,0,1,11.32,11.32Z`}))],[`thin`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M210.83,98.83l-80,80a4,4,0,0,1-5.66,0l-80-80a4,4,0,0,1,5.66-5.66L128,170.34l77.17-77.17a4,4,0,1,1,5.66,5.66Z`}))]]),a=r.forwardRef((e,t)=>r.createElement(n,{ref:t,...e,weights:i}));a.displayName=`CaretDownIcon`;export{a as t};
@@ -0,0 +1 @@
1
+ import{a as e,t}from"./react-BZY8YNV6.js";import{Bt as n}from"./link-provider-mn2voeohon7cj9o4-CNosc_Ni.js";var r=e(t(),1),i=new Map([[`bold`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M168.49,199.51a12,12,0,0,1-17,17l-80-80a12,12,0,0,1,0-17l80-80a12,12,0,0,1,17,17L97,128Z`}))],[`duotone`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M160,48V208L80,128Z`,opacity:`0.2`}),r.createElement(`path`,{d:`M163.06,40.61a8,8,0,0,0-8.72,1.73l-80,80a8,8,0,0,0,0,11.32l80,80A8,8,0,0,0,168,208V48A8,8,0,0,0,163.06,40.61ZM152,188.69,91.31,128,152,67.31Z`}))],[`fill`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M168,48V208a8,8,0,0,1-13.66,5.66l-80-80a8,8,0,0,1,0-11.32l80-80A8,8,0,0,1,168,48Z`}))],[`light`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M164.24,203.76a6,6,0,1,1-8.48,8.48l-80-80a6,6,0,0,1,0-8.48l80-80a6,6,0,0,1,8.48,8.48L88.49,128Z`}))],[`regular`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M165.66,202.34a8,8,0,0,1-11.32,11.32l-80-80a8,8,0,0,1,0-11.32l80-80a8,8,0,0,1,11.32,11.32L91.31,128Z`}))],[`thin`,r.createElement(r.Fragment,null,r.createElement(`path`,{d:`M162.83,205.17a4,4,0,0,1-5.66,5.66l-80-80a4,4,0,0,1,0-5.66l80-80a4,4,0,1,1,5.66,5.66L85.66,128Z`}))]]),a=r.forwardRef((e,t)=>r.createElement(n,{ref:t,...e,weights:i}));a.displayName=`CaretLeftIcon`;export{a as t};