Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
34 changes: 34 additions & 0 deletions apps/docs/src/content/docs/self-host.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,40 @@ Then open `<origin>/app`, sign in, and create an organization and a server.
</Step>
</Steps>

## Run it on celld instead

**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.
- **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/<name>-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/<name>-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/<name>-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:

```sh
export TALKTO_AUTH_PROVIDER=better-auth TALKTO_SERVICE_ORIGIN=<origin> TALKTO_OWNER_EMAILS=<owners>
export CELLD_BUCKET=s3://<bucket> S3_ENDPOINT=<S3 endpoint> AWS_ACCESS_KEY_ID=<key> AWS_SECRET_ACCESS_KEY=<secret>
export BETTER_AUTH_SECRET=<from openssl rand -base64 48> TALKTO_SIGNAL_KEY=<from openssl rand -base64 32>
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:
Expand Down
41 changes: 35 additions & 6 deletions apps/server/src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,41 @@ 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;
}
/** An https address with no trailing slash, query or fragment, so `<base>/<key>?…` 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. A malformed value turns
* transfers off and is logged once per isolate, by name only.
*/
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) {
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;
};
/**
* 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
Expand All @@ -77,13 +107,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(
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/files/r2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: () =>
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/files/transfers-binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
2 changes: 2 additions & 0 deletions apps/server/test/platform-harness.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
39 changes: 39 additions & 0 deletions apps/server/test/transfers.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -134,6 +135,44 @@ 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("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();
Expand Down
129 changes: 129 additions & 0 deletions apps/server/tools/celld.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// 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, 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 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(
"Set TALKTO_AUTH_PROVIDER=better-auth: on celld, TalkTo supports Better Auth sign-in.",
);
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.
// 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,
CLOUDFLARE_ACCOUNT_ID: "0".repeat(32),
TALKTO_D1_DATABASE_ID: "00000000-0000-4000-8000-000000000000",
},
});
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.
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/<bucket_name>/. 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;
}

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];
// 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);
7 changes: 5 additions & 2 deletions apps/server/tools/selfhost-config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <file>` 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) => {
Expand Down Expand Up @@ -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(
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down