From ad3c9a233627a0332374b4cb055a7829272dd255 Mon Sep 17 00:00:00 2001 From: Will Hampson Date: Sat, 21 Nov 2026 06:04:31 -0800 Subject: [PATCH 1/2] Support self-hosting on celld celld, Deno's self-hosted Workers runtime, runs TalkTo's Worker, Durable Objects, D1, R2, cron and assets from an S3-compatible bucket. - TALKTO_R2_OBJECT_BASE sets the https address before each object key in signed transfer links, for a store other than R2. celld keeps the binding's objects under r2// in its own bucket. Unset, links use R2 as before. - `pnpm celld deploy | migrate` builds a celld config from the self-host template, drops the keys celld rejects, copies the dashboard into the project, runs celld and deletes the config, which holds secrets. - The self-hosting guide gains a "Run it on celld instead" section. Co-Authored-By: Claude --- .gitignore | 3 + apps/docs/src/content/docs/self-host.mdx | 29 +++++ apps/server/src/configuration.ts | 27 ++++- apps/server/src/files/r2.ts | 4 +- apps/server/src/files/transfers-binding.d.ts | 2 + apps/server/test/platform-harness.mjs | 2 + apps/server/test/transfers.test.mjs | 13 +++ apps/server/tools/celld.mjs | 116 +++++++++++++++++++ package.json | 1 + 9 files changed, 189 insertions(+), 8 deletions(-) create mode 100644 apps/server/tools/celld.mjs diff --git a/.gitignore b/.gitignore index 0362767..c387a22 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ apps/docs/src/content/partials/generated/ /PRODUCT_SPEC.md *.tar.gz *.zip +apps/server/wrangler.celld.json +apps/server/celld-assets/ +apps/server/.celld/ diff --git a/apps/docs/src/content/docs/self-host.mdx b/apps/docs/src/content/docs/self-host.mdx index fae37da..9468c17 100644 --- a/apps/docs/src/content/docs/self-host.mdx +++ b/apps/docs/src/content/docs/self-host.mdx @@ -264,6 +264,35 @@ Then open `/app`, sign in, and create an organization and a server. +## Run it on celld instead + +[celld](https://github.com/denoland/celld) is Deno's self-hosted Workers runtime. It runs the same Worker, Durable Objects, D1, R2, cron and static assets on your own machines, and keeps their data in an S3-compatible bucket. A copy on celld signs people in with Better Auth: Cloudflare Access and WorkOS need Cloudflare. + +What is different: + +- celld has no rate-limit bindings and no version metadata. TalkTo runs without both. +- celld has no TLS and no secret store. Put an https proxy in front of it. `pnpm celld deploy` stores the secrets as Worker variables in the bucket, so protect the bucket like the secrets. +- Behind a proxy there is no `cf-connecting-ip` header, so everyone shares Better Auth's sign-in rate limits. +- File transfers: celld keeps the transfer bucket's objects under `r2/-transfers/` in its own bucket. Set `TALKTO_R2_OBJECT_BASE` to the https address where agents reach that folder, for example `https://files.example.com/talkto/r2/talkto-transfers`, and `TALKTO_R2_ACCESS_KEY_ID` and `TALKTO_R2_SECRET_ACCESS_KEY` to a key that can read and write only that folder. Without them, transfers are off. Delete transfers older than 30 days in your store yourself. + +To deploy, set the Better Auth variables from the steps above, then: + +```sh +export TALKTO_AUTH_PROVIDER=better-auth TALKTO_SERVICE_ORIGIN= TALKTO_OWNER_EMAILS= +export CELLD_BUCKET=s3:// S3_ENDPOINT= AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= +export BETTER_AUTH_SECRET= TALKTO_SIGNAL_KEY= +pnpm build:selfhost +pnpm celld deploy +``` + +Start a node on the same bucket, with your proxy sending https to its listener. Add `--trust-forwarded-headers` only when the proxy replaces `X-Forwarded-Host` and `X-Forwarded-Proto`: + +```sh +celld --bucket "$CELLD_BUCKET" --endpoint "$S3_ENDPOINT" --listen 127.0.0.1:8080 --trust-forwarded-headers +``` + +A node takes part in the fleet only after the first deploy, so apply the migrations after it starts: `pnpm celld migrate`. Then make your account link with `pnpm selfhost:link` as above. To update, run `pnpm build:selfhost`, `pnpm celld migrate` and `pnpm celld deploy`: nodes adopt the new version without a restart. + ## Update to a new version Read the release notes first: they say when a release adds a setting or a secret. Then: diff --git a/apps/server/src/configuration.ts b/apps/server/src/configuration.ts index 18c99f3..79e2469 100644 --- a/apps/server/src/configuration.ts +++ b/apps/server/src/configuration.ts @@ -64,11 +64,27 @@ export const readFilesRemote = Effect.fn("Configuration.readFilesRemote")(functi /** What signing an R2 link and reading its objects need. */ export interface R2Settings { readonly bucket: R2Bucket; - readonly accountId: string; - readonly bucketName: string; + /** The https address before each object key in a signed link, with no trailing slash. */ + readonly objectBase: string; readonly accessKeyId: string; readonly secretAccessKey: string; } +/** + * R2's own S3 address, unless `TALKTO_R2_OBJECT_BASE` names another S3-compatible store that + * holds the binding's objects, as a self-hosted Workers runtime does. + */ +const objectBase = (env: Env): string | undefined => { + const { + TALKTO_R2_OBJECT_BASE: base, + TALKTO_R2_ACCOUNT_ID: accountId, + TALKTO_R2_BUCKET: name, + } = env; + if (base !== undefined) + return URL.canParse(base) && base.startsWith("https://") && !base.endsWith("/") + ? base + : undefined; + return accountId && name ? `https://${accountId}.r2.cloudflarestorage.com/${name}` : undefined; +}; /** * The R2 store's settings, or null until the binding and every value are present. Capability * reporting and store composition share this one predicate, so a half-configured deployment @@ -77,13 +93,12 @@ export interface R2Settings { export const r2Settings = (env: Env): R2Settings | null => { const { TRANSFERS: bucket, - TALKTO_R2_ACCOUNT_ID: accountId, - TALKTO_R2_BUCKET: bucketName, TALKTO_R2_ACCESS_KEY_ID: accessKeyId, TALKTO_R2_SECRET_ACCESS_KEY: secretAccessKey, } = env; - return bucket && accountId && bucketName && accessKeyId && secretAccessKey - ? { bucket, accountId, bucketName, accessKeyId, secretAccessKey } + const base = objectBase(env); + return bucket && base && accessKeyId && secretAccessKey + ? { bucket, objectBase: base, accessKeyId, secretAccessKey } : null; }; const ArtifactsRemoteBase = Schema.String.check( diff --git a/apps/server/src/files/r2.ts b/apps/server/src/files/r2.ts index 4669cec..acd7a31 100644 --- a/apps/server/src/files/r2.ts +++ b/apps/server/src/files/r2.ts @@ -20,10 +20,10 @@ const failure = (operation: string) => () => * only the declared size, and only once. */ export const make = (settings: R2Settings) => { - const { bucket, accountId, bucketName, accessKeyId, secretAccessKey } = settings; + const { bucket, objectBase, accessKeyId, secretAccessKey } = settings; const client = new AwsClient({ service: "s3", region: "auto", accessKeyId, secretAccessKey }); const link = (key: string, query: string, seconds: number = Transfers.linkSeconds) => - `https://${accountId}.r2.cloudflarestorage.com/${bucketName}/${key}?X-Amz-Expires=${seconds}${query}`; + `${objectBase}/${key}?X-Amz-Expires=${seconds}${query}`; const sign = (operation: string, url: string, init: RequestInit) => Effect.tryPromise({ try: () => diff --git a/apps/server/src/files/transfers-binding.d.ts b/apps/server/src/files/transfers-binding.d.ts index 4c9a7f1..cdbd832 100644 --- a/apps/server/src/files/transfers-binding.d.ts +++ b/apps/server/src/files/transfers-binding.d.ts @@ -5,6 +5,8 @@ interface Env { readonly TRANSFERS?: R2Bucket; readonly TALKTO_R2_ACCOUNT_ID?: string; readonly TALKTO_R2_BUCKET?: string; + /** Overrides the R2 address in signed links, for another S3-compatible store. */ + readonly TALKTO_R2_OBJECT_BASE?: string; readonly TALKTO_R2_ACCESS_KEY_ID?: string; readonly TALKTO_R2_SECRET_ACCESS_KEY?: string; } diff --git a/apps/server/test/platform-harness.mjs b/apps/server/test/platform-harness.mjs index 1f7a97f..9a5139c 100644 --- a/apps/server/test/platform-harness.mjs +++ b/apps/server/test/platform-harness.mjs @@ -112,6 +112,8 @@ export async function start(t, options = {}) { transferStore.TALKTO_R2_BUCKET = "talkto-test-transfers"; transferStore.TALKTO_R2_ACCESS_KEY_ID = "test-access-key"; transferStore.TALKTO_R2_SECRET_ACCESS_KEY = "test-secret-key"; + if (options.transferObjectBase) + transferStore.TALKTO_R2_OBJECT_BASE = options.transferObjectBase; transferBucket.r2Buckets = { TRANSFERS: "talkto-test-transfers" }; } // A throwaway key per run; hosts are answered by the test's handler, never the real services. diff --git a/apps/server/test/transfers.test.mjs b/apps/server/test/transfers.test.mjs index 6423337..13091d4 100644 --- a/apps/server/test/transfers.test.mjs +++ b/apps/server/test/transfers.test.mjs @@ -134,6 +134,19 @@ test("an upload link opens one object, for minutes, at the declared size, once", assert.ok(data.expiresAt > data.uploadExpiresAt); }); +test("another S3-compatible store signs links at its own address", async (t) => { + const base = "https://files.example.test:8443/fleet/r2/talkto-test-transfers"; + const s = await setup(t, { transferObjectBase: base }); + const { data } = await s.prepare(); + const url = new URL(data.uploadUrl); + assert.equal(url.origin, "https://files.example.test:8443"); + assert.equal( + url.pathname, + `/fleet/r2/talkto-test-transfers/r30/${s.server.id}/${data.transferId}/payload`, + ); + assert.ok(url.searchParams.get("X-Amz-Signature")); +}); + test("nothing is offered until the upload arrives at its declared size", async (t) => { const s = await setup(t); const { data } = await s.prepare(); diff --git a/apps/server/tools/celld.mjs b/apps/server/tools/celld.mjs new file mode 100644 index 0000000..a0f77ac --- /dev/null +++ b/apps/server/tools/celld.mjs @@ -0,0 +1,116 @@ +// Deploy a self-hosted TalkTo to celld, Deno's self-hosted Workers runtime, or apply its D1 +// migrations. Run from the repository root after `pnpm build:selfhost`: +// +// pnpm celld deploy # build the celld config, `celld deploy`, then delete the config +// pnpm celld migrate # build the celld config, `celld d1 migrations apply`, then delete it +// +// It reads the same environment variables as `pnpm selfhost:config` (with Better Auth), plus the +// fleet bucket (CELLD_BUCKET, S3_ENDPOINT, AWS_REGION and the AWS credentials, as celld reads +// them) and the values Cloudflare keeps as Worker secrets. celld has no secret store: those values +// become Worker variables inside the fleet bucket, so protect the bucket like the secrets. +import { spawnSync } from "node:child_process"; +import { cpSync, existsSync, rmSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { delimiter, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { experimental_readRawConfig } from "wrangler"; + +const here = (path) => fileURLToPath(new URL(path, import.meta.url)); +const server = here(".."); +const selfhost = join(server, "wrangler.selfhost.jsonc"); +const output = join(server, "wrangler.celld.json"); +const assets = join(server, "celld-assets"); + +const command = process.argv[2]; +if (command !== "deploy" && command !== "migrate") { + console.error("Usage: pnpm celld deploy | pnpm celld migrate"); + process.exit(2); +} +if (process.env.TALKTO_AUTH_PROVIDER?.trim() !== "better-auth") { + console.error( + "celld needs TALKTO_AUTH_PROVIDER=better-auth: Cloudflare Access and WorkOS need Cloudflare.", + ); + process.exit(1); +} +const missing = ["BETTER_AUTH_SECRET", "CELLD_BUCKET"].filter((name) => !process.env[name]?.trim()); +if (missing.length > 0) { + console.error(`Not set: ${missing.join(", ")}.`); + process.exit(1); +} + +// The Cloudflare account and D1 database IDs mean nothing to celld; the template still wants them. +const generated = spawnSync(process.execPath, [here("selfhost-config.mjs")], { + stdio: ["ignore", "ignore", "inherit"], + env: { + ...process.env, + CLOUDFLARE_ACCOUNT_ID: "0".repeat(32), + TALKTO_D1_DATABASE_ID: "00000000-0000-4000-8000-000000000000", + }, +}); +if (generated.status !== 0) process.exit(generated.status ?? 1); + +const { rawConfig: config } = experimental_readRawConfig({ config: selfhost }); +rmSync(selfhost); + +// Keys celld rejects. Each is optional to TalkTo: no rate-limit bindings, no version metadata, +// and the address comes from the proxy in front of celld instead of a Cloudflare route. +for (const key of [ + "account_id", + "ratelimits", + "version_metadata", + "workers_dev", + "preview_urls", + "observability", + "routes", +]) + delete config[key]; +for (const rule of config.rules ?? []) delete rule.fallthrough; +// Without a database_id celld names the database by database_name, which stays stable. +for (const database of config.d1_databases ?? []) delete database.database_id; + +// celld serves assets only from inside the project, and has no `.assetsignore`. +const built = join(server, "../web/dist"); +if (command === "deploy") { + if (!existsSync(built)) { + console.error("Build the dashboard first: pnpm build:selfhost"); + process.exit(1); + } + rmSync(assets, { recursive: true, force: true }); + cpSync(built, assets, { + recursive: true, + filter: (path) => !path.endsWith(".map") && !path.endsWith(".assetsignore"), + }); +} +config.assets.directory = "celld-assets"; + +// Signed transfer links reach the binding's objects in the fleet bucket, where celld keeps them +// under r2//. Transfers stay off until the store's address and keys are all set. +delete config.vars.TALKTO_R2_ACCOUNT_ID; +for (const name of [ + "BETTER_AUTH_SECRET", + "TALKTO_SIGNAL_KEY", + "TALKTO_R2_OBJECT_BASE", + "TALKTO_R2_ACCESS_KEY_ID", + "TALKTO_R2_SECRET_ACCESS_KEY", +]) { + const value = process.env[name]?.trim(); + if (value) config.vars[name] = value; +} + +writeFileSync(output, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); +const celld = process.env.CELLD ?? "celld"; +// celld bundles the Worker with the esbuild on PATH; use the one Wrangler already installed. +const esbuild = dirname( + createRequire(createRequire(import.meta.url).resolve("wrangler")).resolve("esbuild/bin/esbuild"), +); +const args = + command === "deploy" + ? ["deploy", output] + : ["d1", "migrations", "apply", config.d1_databases[0].database_name, output]; +const result = spawnSync(celld, [...args, "--bucket", process.env.CELLD_BUCKET], { + cwd: server, + stdio: "inherit", + env: { ...process.env, PATH: `${esbuild}${delimiter}${process.env.PATH}` }, +}); +rmSync(output); +process.exit(result.status ?? 1); diff --git a/package.json b/package.json index f04c1af..fe02a6d 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,7 @@ "selfhost:link": "pnpm --filter @talkto/server exec node tools/better-auth-link.mjs", "selfhost:migrate": "pnpm --filter @talkto/server exec wrangler d1 migrations apply PLATFORM --remote --config wrangler.selfhost.jsonc", "selfhost:deploy": "pnpm build:selfhost && pnpm --filter @talkto/server exec wrangler deploy --config wrangler.selfhost.jsonc", + "celld": "pnpm --filter @talkto/server exec node tools/celld.mjs", "email:announce": "pnpm --filter @talkto/server exec node tools/email-announce.mjs" }, "devDependencies": { From 3b19a88d68a7097a574767050a4e2cf3a2ff62d6 Mon Sep 17 00:00:00 2001 From: Michael Ramos <7244317+backnotprop@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:18:29 -0500 Subject: [PATCH 2/2] Harden the celld self-host path - Self-host guide: celld is community-supported and untested by TalkTo. The proxy must replace cf-connecting-ip with the real client address, or password-guess limits can be bypassed. Transfers are optional, need a key limited to the transfers folder, need your own 30-day cleanup, and are signed for region auto. - TALKTO_R2_OBJECT_BASE: reject a query or fragment, and log one warning by name when the value is malformed. - pnpm celld: generate the config in a temporary directory, so your own wrangler.selfhost.jsonc stays, and always delete the secrets file. --- apps/docs/src/content/docs/self-host.mdx | 11 ++++-- apps/server/src/configuration.ts | 24 ++++++++++--- apps/server/test/transfers.test.mjs | 26 ++++++++++++++ apps/server/tools/celld.mjs | 45 +++++++++++++++--------- apps/server/tools/selfhost-config.mjs | 7 ++-- 5 files changed, 87 insertions(+), 26 deletions(-) diff --git a/apps/docs/src/content/docs/self-host.mdx b/apps/docs/src/content/docs/self-host.mdx index 9468c17..10bfada 100644 --- a/apps/docs/src/content/docs/self-host.mdx +++ b/apps/docs/src/content/docs/self-host.mdx @@ -266,14 +266,19 @@ Then open `/app`, sign in, and create an organization and a server. ## Run it on celld instead -[celld](https://github.com/denoland/celld) is Deno's self-hosted Workers runtime. It runs the same Worker, Durable Objects, D1, R2, cron and static assets on your own machines, and keeps their data in an S3-compatible bucket. A copy on celld signs people in with Better Auth: Cloudflare Access and WorkOS need Cloudflare. +**Community-supported, untested by TalkTo.** celld is not yet at version 1.0, so check each new celld release with your own copy before you rely on it. + +[celld](https://github.com/denoland/celld) is Deno's self-hosted Workers runtime. It runs the same Worker, Durable Objects, D1, R2, cron and static assets on your own machines, and keeps their data in an S3-compatible bucket. On celld, TalkTo supports Better Auth sign-in. What is different: - celld has no rate-limit bindings and no version metadata. TalkTo runs without both. - celld has no TLS and no secret store. Put an https proxy in front of it. `pnpm celld deploy` stores the secrets as Worker variables in the bucket, so protect the bucket like the secrets. -- Behind a proxy there is no `cf-connecting-ip` header, so everyone shares Better Auth's sign-in rate limits. -- File transfers: celld keeps the transfer bucket's objects under `r2/-transfers/` in its own bucket. Set `TALKTO_R2_OBJECT_BASE` to the https address where agents reach that folder, for example `https://files.example.com/talkto/r2/talkto-transfers`, and `TALKTO_R2_ACCESS_KEY_ID` and `TALKTO_R2_SECRET_ACCESS_KEY` to a key that can read and write only that folder. Without them, transfers are off. Delete transfers older than 30 days in your store yourself. +- **Your proxy must set `cf-connecting-ip`.** TalkTo limits password guesses per client address, and it reads that address from the `cf-connecting-ip` header. Cloudflare always sets this header; celld does not. Set your proxy to replace `cf-connecting-ip` with the real client address on every request, for example `proxy_set_header cf-connecting-ip $remote_addr;` in nginx. If the proxy passes on what the client sent, anyone can send a new made-up address with each request and guess passwords with no limit. If the header is missing, all sign-ins share one limit, so one person can lock everyone out. +- **File transfers are optional and stay off unless you set them.** celld keeps the transfer bucket's objects under `r2/-transfers/` in its fleet bucket. To turn transfers on, set `TALKTO_R2_OBJECT_BASE` to the https address where agents reach that folder, for example `https://files.example.com/talkto/r2/talkto-transfers`, and set `TALKTO_R2_ACCESS_KEY_ID` and `TALKTO_R2_SECRET_ACCESS_KEY`. Before you do: + - Make a key that can read and write only `r2/-transfers/`. Never use the fleet bucket's keys: they control the whole fleet, and TalkTo keeps this key as a Worker variable. + - Nothing deletes old transfers for you. Add a rule in your store that deletes objects under `r2/-transfers/r30/` after 30 days. + - TalkTo signs links for the region `auto`. A store that checks the region, such as AWS S3, may reject them. To deploy, set the Better Auth variables from the steps above, then: diff --git a/apps/server/src/configuration.ts b/apps/server/src/configuration.ts index 79e2469..232ab6c 100644 --- a/apps/server/src/configuration.ts +++ b/apps/server/src/configuration.ts @@ -69,9 +69,18 @@ export interface R2Settings { readonly accessKeyId: string; readonly secretAccessKey: string; } +/** An https address with no trailing slash, query or fragment, so `/?…` stays one URL. */ +const validObjectBase = (base: string) => + URL.canParse(base) && + new URL(base).protocol === "https:" && + !base.endsWith("/") && + !base.includes("?") && + !base.includes("#"); +let objectBaseWarned = false; /** * R2's own S3 address, unless `TALKTO_R2_OBJECT_BASE` names another S3-compatible store that - * holds the binding's objects, as a self-hosted Workers runtime does. + * holds the binding's objects, as a self-hosted Workers runtime does. A malformed value turns + * transfers off and is logged once per isolate, by name only. */ const objectBase = (env: Env): string | undefined => { const { @@ -79,10 +88,15 @@ const objectBase = (env: Env): string | undefined => { TALKTO_R2_ACCOUNT_ID: accountId, TALKTO_R2_BUCKET: name, } = env; - if (base !== undefined) - return URL.canParse(base) && base.startsWith("https://") && !base.endsWith("/") - ? base - : undefined; + if (base !== undefined) { + if (validObjectBase(base)) return base; + if (!objectBaseWarned) + console.warn( + "TalkTo file transfers are off: TALKTO_R2_OBJECT_BASE must be an https:// address with no trailing slash, query or fragment.", + ); + objectBaseWarned = true; + return undefined; + } return accountId && name ? `https://${accountId}.r2.cloudflarestorage.com/${name}` : undefined; }; /** diff --git a/apps/server/test/transfers.test.mjs b/apps/server/test/transfers.test.mjs index 13091d4..12d9bff 100644 --- a/apps/server/test/transfers.test.mjs +++ b/apps/server/test/transfers.test.mjs @@ -15,6 +15,7 @@ import { join } from "node:path"; import { test } from "node:test"; import { rpc } from "./mcp-wire.mjs"; import { start } from "./platform-harness.mjs"; +import { load } from "./sources.mjs"; import { storageGigabytes } from "@talkto/api/pricing"; const sha = "a".repeat(64); @@ -147,6 +148,31 @@ test("another S3-compatible store signs links at its own address", async (t) => assert.ok(url.searchParams.get("X-Amz-Signature")); }); +test("a malformed store address turns transfers off and is logged once, by name only", async (t) => { + const Configuration = await load("../src/configuration.ts"); + const warn = t.mock.method(console, "warn", () => undefined); + const env = (base) => ({ + TRANSFERS: {}, + TALKTO_R2_OBJECT_BASE: base, + TALKTO_R2_ACCESS_KEY_ID: "test-access-key", + TALKTO_R2_SECRET_ACCESS_KEY: "test-secret-key", + }); + for (const base of [ + "http://files.example.test/fleet", + "https://files.example.test/fleet/", + "https://files.example.test/fleet?secret=1", + "https://files.example.test/fleet#secret", + "files.example.test/fleet", + ]) + assert.equal(Configuration.r2Settings(env(base)), null, base); + assert.equal(warn.mock.callCount(), 1); + const [message] = warn.mock.calls[0].arguments; + assert.match(message, /TALKTO_R2_OBJECT_BASE/); + assert.doesNotMatch(message, /files\.example\.test|secret/); + const base = "https://files.example.test:8443/fleet/r2/talkto-test-transfers"; + assert.equal(Configuration.r2Settings(env(base))?.objectBase, base); +}); + test("nothing is offered until the upload arrives at its declared size", async (t) => { const s = await setup(t); const { data } = await s.prepare(); diff --git a/apps/server/tools/celld.mjs b/apps/server/tools/celld.mjs index a0f77ac..5b454b6 100644 --- a/apps/server/tools/celld.mjs +++ b/apps/server/tools/celld.mjs @@ -9,15 +9,15 @@ // them) and the values Cloudflare keeps as Worker secrets. celld has no secret store: those values // become Worker variables inside the fleet bucket, so protect the bucket like the secrets. import { spawnSync } from "node:child_process"; -import { cpSync, existsSync, rmSync, writeFileSync } from "node:fs"; +import { cpSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; import { delimiter, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { experimental_readRawConfig } from "wrangler"; const here = (path) => fileURLToPath(new URL(path, import.meta.url)); const server = here(".."); -const selfhost = join(server, "wrangler.selfhost.jsonc"); const output = join(server, "wrangler.celld.json"); const assets = join(server, "celld-assets"); @@ -28,7 +28,7 @@ if (command !== "deploy" && command !== "migrate") { } if (process.env.TALKTO_AUTH_PROVIDER?.trim() !== "better-auth") { console.error( - "celld needs TALKTO_AUTH_PROVIDER=better-auth: Cloudflare Access and WorkOS need Cloudflare.", + "Set TALKTO_AUTH_PROVIDER=better-auth: on celld, TalkTo supports Better Auth sign-in.", ); process.exit(1); } @@ -39,7 +39,10 @@ if (missing.length > 0) { } // The Cloudflare account and D1 database IDs mean nothing to celld; the template still wants them. -const generated = spawnSync(process.execPath, [here("selfhost-config.mjs")], { +// The generated config goes to a temporary directory, so your own wrangler.selfhost.jsonc stays. +const scratch = mkdtempSync(join(tmpdir(), "talkto-celld-")); +const selfhost = join(scratch, "wrangler.selfhost.jsonc"); +const generated = spawnSync(process.execPath, [here("selfhost-config.mjs"), "--out", selfhost], { stdio: ["ignore", "ignore", "inherit"], env: { ...process.env, @@ -47,10 +50,10 @@ const generated = spawnSync(process.execPath, [here("selfhost-config.mjs")], { TALKTO_D1_DATABASE_ID: "00000000-0000-4000-8000-000000000000", }, }); -if (generated.status !== 0) process.exit(generated.status ?? 1); - -const { rawConfig: config } = experimental_readRawConfig({ config: selfhost }); -rmSync(selfhost); +const config = + generated.status === 0 ? experimental_readRawConfig({ config: selfhost }).rawConfig : null; +rmSync(scratch, { recursive: true, force: true }); +if (config === null) process.exit(generated.status ?? 1); // Keys celld rejects. Each is optional to TalkTo: no rate-limit bindings, no version metadata, // and the address comes from the proxy in front of celld instead of a Cloudflare route. @@ -97,7 +100,6 @@ for (const name of [ if (value) config.vars[name] = value; } -writeFileSync(output, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); const celld = process.env.CELLD ?? "celld"; // celld bundles the Worker with the esbuild on PATH; use the one Wrangler already installed. const esbuild = dirname( @@ -107,10 +109,21 @@ const args = command === "deploy" ? ["deploy", output] : ["d1", "migrations", "apply", config.d1_databases[0].database_name, output]; -const result = spawnSync(celld, [...args, "--bucket", process.env.CELLD_BUCKET], { - cwd: server, - stdio: "inherit", - env: { ...process.env, PATH: `${esbuild}${delimiter}${process.env.PATH}` }, -}); -rmSync(output); -process.exit(result.status ?? 1); +// The config holds the secrets. Ctrl-C reaches celld as well; this process waits for celld to +// stop, so the `finally` below always deletes the config. +for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(signal, () => {}); +let status = 1; +try { + rmSync(output, { force: true }); + writeFileSync(output, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); + const result = spawnSync(celld, [...args, "--bucket", process.env.CELLD_BUCKET], { + cwd: server, + stdio: "inherit", + env: { ...process.env, PATH: `${esbuild}${delimiter}${process.env.PATH}` }, + }); + if (result.error) console.error(`Could not run ${celld}: ${result.error.message}`); + status = result.status ?? 1; +} finally { + rmSync(output, { force: true }); +} +process.exit(status); diff --git a/apps/server/tools/selfhost-config.mjs b/apps/server/tools/selfhost-config.mjs index eb3b3f1..72693c8 100644 --- a/apps/server/tools/selfhost-config.mjs +++ b/apps/server/tools/selfhost-config.mjs @@ -4,11 +4,14 @@ // Auth's secret is a Worker secret (`wrangler secret put BETTER_AUTH_SECRET`), never in this file. import { writeFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; import { experimental_readRawConfig } from "wrangler"; const here = (path) => fileURLToPath(new URL(path, import.meta.url)); const template = here("../wrangler.selfhost.example.jsonc"); -const output = here("../wrangler.selfhost.jsonc"); +// `--out ` writes somewhere else; `pnpm celld` uses it to leave your own config alone. +const { values: args } = parseArgs({ options: { out: { type: "string" } } }); +const output = args.out ?? here("../wrangler.selfhost.jsonc"); const problems = []; const setting = (name, pattern, hint, fallback) => { @@ -154,7 +157,7 @@ writeFileSync( output, `// Written by pnpm selfhost:config from wrangler.selfhost.example.jsonc. Holds no secrets.\n${text}\n`, ); -console.log(`Wrote apps/server/wrangler.selfhost.jsonc for ${origin}:`); +console.log(`Wrote ${args.out ?? "apps/server/wrangler.selfhost.jsonc"} for ${origin}:`); console.log(` Worker ${name}, D1 ${name}-platform, R2 ${name}-transfers`); console.log(` ${config.workers_dev ? "workers.dev address" : `Custom Domain ${host}`}`); console.log(