From d7e5caffa3b24d4e61e451992f21da803eebc036 Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:01:20 -0600 Subject: [PATCH 1/3] fix(cli): honour --password and make --reads usable The encrypt command never passed --password to the client, so links it printed as password-protected were encrypted with the URL key alone. Map the options in one tested function, add --no-burn, and let --reads turn off the default burn instead of sending a combination the server rejects. --- .changeset/cli-password-protection.md | 5 +++ packages/cli/README.md | 10 +++++ packages/cli/src/encrypt.test.ts | 55 +++++++++++++++++++++++++++ packages/cli/src/encrypt.ts | 52 +++++++++++++++++++++++++ packages/cli/src/index.ts | 35 ++++++++++------- 5 files changed, 144 insertions(+), 13 deletions(-) create mode 100644 .changeset/cli-password-protection.md create mode 100644 packages/cli/src/encrypt.test.ts create mode 100644 packages/cli/src/encrypt.ts diff --git a/.changeset/cli-password-protection.md b/.changeset/cli-password-protection.md new file mode 100644 index 00000000..c7d09bb3 --- /dev/null +++ b/.changeset/cli-password-protection.md @@ -0,0 +1,5 @@ +--- +'@crypt.fyi/cli': patch +--- + +Fix `cfyi encrypt --password`: the password was ignored, so links printed as password-protected could be read with the URL alone. Secrets created with `--password` by earlier versions were not password-protected. Also add `--no-burn`, and make `--reads` turn off the default burn-after-reading instead of failing with a 400. diff --git a/packages/cli/README.md b/packages/cli/README.md index 3bdbbf6d..17324211 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -32,6 +32,16 @@ cfyi --help cfyi encrypt --help ``` +### Password, burn and read count + +```bash +cfyi encrypt "your secret" --password "correct horse" # recipient needs the URL and the password +cfyi encrypt "your secret" --no-burn --ttl 1d # readable until it expires +cfyi encrypt "your secret" --reads 3 # readable 3 times +``` + +Secrets are burned after the first read by default. `--reads` turns that off, and can't be combined with an explicit `--burn`. + ### Encrypt with a webhook Use the same webhook options as the website's advanced settings. The server receives `POST` notifications at your URL when the configured events occur. diff --git a/packages/cli/src/encrypt.test.ts b/packages/cli/src/encrypt.test.ts new file mode 100644 index 00000000..4700bb81 --- /dev/null +++ b/packages/cli/src/encrypt.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect } from '@jest/globals'; +import { buildCreateInput, formatSecretUrl, type EncryptOptions } from './encrypt.js'; + +const baseOptions: EncryptOptions = { + ttl: 60_000, + burn: true, + burnExplicit: false, +}; + +describe('buildCreateInput', () => { + it('passes the password to the client', () => { + const input = buildCreateInput('secret', { ...baseOptions, password: 'pw' }); + expect(input.p).toBe('pw'); + }); + + it('burns after reading by default', () => { + const input = buildCreateInput('secret', baseOptions); + expect(input.b).toBe(true); + expect(input.rc).toBeUndefined(); + }); + + it('does not burn with --no-burn', () => { + const input = buildCreateInput('secret', { ...baseOptions, burn: false, burnExplicit: true }); + expect(input.b).toBe(false); + }); + + it('turns off the default burn when --reads is set', () => { + const input = buildCreateInput('secret', { ...baseOptions, reads: '3' }); + expect(input.b).toBe(false); + expect(input.rc).toBe(3); + }); + + it('rejects --reads together with an explicit --burn', () => { + expect(() => + buildCreateInput('secret', { ...baseOptions, burnExplicit: true, reads: '3' }), + ).toThrow('--reads cannot be combined with --burn'); + }); + + it('rejects a non-numeric --reads', () => { + expect(() => buildCreateInput('secret', { ...baseOptions, reads: 'three' })).toThrow( + '--reads must be a whole number', + ); + }); +}); + +describe('formatSecretUrl', () => { + it('marks password-protected links', () => { + expect(formatSecretUrl('https://crypt.fyi', 'id', 'key', true)).toBe( + 'https://crypt.fyi/id?p=true#key', + ); + expect(formatSecretUrl('https://crypt.fyi', 'id', 'key', false)).toBe( + 'https://crypt.fyi/id#key', + ); + }); +}); diff --git a/packages/cli/src/encrypt.ts b/packages/cli/src/encrypt.ts new file mode 100644 index 00000000..941fc92c --- /dev/null +++ b/packages/cli/src/encrypt.ts @@ -0,0 +1,52 @@ +import type { Client } from '@crypt.fyi/core'; + +type CreateInput = Parameters[0]; + +export type EncryptOptions = { + password?: string; + ttl: number; + burn: boolean; + /** True when `--burn` or `--no-burn` was given explicitly rather than defaulted. */ + burnExplicit: boolean; + ip?: string; + reads?: string; + wh?: CreateInput['wh']; +}; + +/** + * Maps parsed `cfyi encrypt` options to a `Client.create` input. + * + * Burn-after-reading is the default, but the server rejects it together with a + * read count, so `--reads` turns burning off unless `--burn` was asked for. + */ +export function buildCreateInput(content: string, options: EncryptOptions): CreateInput { + let rc: number | undefined; + if (options.reads !== undefined) { + rc = Number(options.reads); + if (!Number.isInteger(rc)) { + throw new Error('--reads must be a whole number'); + } + if (options.burn && options.burnExplicit) { + throw new Error('--reads cannot be combined with --burn'); + } + } + + return { + c: content, + p: options.password, + b: rc === undefined ? options.burn : false, + ttl: options.ttl, + ips: options.ip, + rc, + ...(options.wh ? { wh: options.wh } : {}), + }; +} + +export function formatSecretUrl( + webUrl: string, + id: string, + key: string, + hasPassword: boolean, +): string { + return `${webUrl}/${id}${hasPassword ? '?p=true' : ''}#${key}`; +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 38ed6785..46d7b157 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -6,6 +6,7 @@ import chalk from 'chalk'; import ora from 'ora'; import { config } from './config.js'; import { parseWhEvents, trimmedWhName } from './webhook.js'; +import { buildCreateInput, formatSecretUrl } from './encrypt.js'; const program = new Command(); @@ -30,13 +31,14 @@ program .option('-f, --file ', 'Path to file to encrypt') .option('-p, --password ', 'Password to encrypt with') .option('-t, --ttl ', 'Time to live (e.g., 1h, 1d)', '1h') - .option('-b, --burn', 'Burn after reading', true) + .option('-b, --burn', 'Burn after reading (default, unless --reads is set)', true) + .option('--no-burn', 'Keep the secret until it expires instead of burning it after reading') .option('--ip ', 'Restrict access to specific IP address') .option('-r, --reads ', 'Number of times the secret can be read', undefined) .option('--wh-url ', 'Webhook URL for notifications') .option('--wh-events ', 'Comma-separated events: read, burn, failed-key, failed-ip', 'read') .option('--wh-name ', 'Optional label for this secret in webhook payloads (max 50 chars)') - .action(async (content, options) => { + .action(async (content, options, command: Command) => { if (options.file && content) { console.error(chalk.red('Cannot provide both content and file')); process.exit(1); @@ -80,26 +82,33 @@ program process.exit(1); } + let input; + try { + input = buildCreateInput(content, { + password: options.password, + ttl: parseDuration(options.ttl), + burn: options.burn, + burnExplicit: command.getOptionValueSource('burn') === 'cli', + ip: options.ip, + reads: options.reads, + wh: whConfig, + }); + } catch (e) { + console.error(chalk.red(e instanceof Error ? e.message : 'Unknown error')); + process.exit(1); + } + const spinner = ora('Encrypting content...').start(); try { spinner.text = 'Creating vault...'; - const result = await client.create({ - c: content, - b: options.burn, - ttl: parseDuration(options.ttl), - ips: options.ip, - rc: options.reads ? parseInt(options.reads, 10) : undefined, - ...(whConfig ? { wh: whConfig } : {}), - }); + const result = await client.create(input); spinner.succeed('Secret encrypted and stored successfully!'); console.log('\nShare these details with the recipient:'); console.log(chalk.blue('\nSecret URL:')); - console.log( - `${config.webUrl}/${result.id}${options.password ? `?p=true` : ''}#${result.key}`, - ); + console.log(formatSecretUrl(config.webUrl, result.id, result.key, Boolean(options.password))); if (options.password) { console.log(chalk.yellow('\nPassword:')); From f3955f5ae2bfbff5f8b730bec8c8a76d325a7ee0 Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:01:37 -0600 Subject: [PATCH 2/3] fix(server): only trust X-Forwarded-For from configured proxies trustProxy: true took the client IP from the left-most X-Forwarded-For entry, which any client controls, so IP restrictions and the rate limit could be bypassed. Add TRUST_PROXY (proxy IPs, CIDRs or proxy-addr presets) and use the socket address when it is unset. --- .changeset/trust-proxy.md | 5 +++ README.md | 6 +++ SPECIFICATION.md | 4 ++ docker-compose.yaml | 4 ++ packages/server/.env-example | 1 + packages/server/src/app.test.ts | 66 ++++++++++++++++++++++++++++++++- packages/server/src/app.ts | 3 +- packages/server/src/config.ts | 43 +++++++++++++++++++++ 8 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 .changeset/trust-proxy.md diff --git a/.changeset/trust-proxy.md b/.changeset/trust-proxy.md new file mode 100644 index 00000000..750f4798 --- /dev/null +++ b/.changeset/trust-proxy.md @@ -0,0 +1,5 @@ +--- +'@crypt.fyi/server': minor +--- + +Stop trusting `X-Forwarded-For` from every client. The server now uses the connection's address for IP restrictions and rate limiting unless the new `TRUST_PROXY` setting lists the reverse proxies allowed to forward the client IP. Deployments behind a proxy, load balancer or CDN must set `TRUST_PROXY`, or all requests will share the proxy's address. diff --git a/README.md b/README.md index a8060a8c..618947b7 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,12 @@ The server holds a keyring: `ENCRYPTION_KEY` is the primary key, used for every If the old key leaked, you can shorten step 5, but removing it before `previousKeysNeededUntil` makes the remaining older secrets unreadable. Entries already re-encrypted in step 4 no longer expose their IP restrictions, webhook URLs or delete tokens to the old key. A non-zero `unreadable` count in the report means an entry was written with a key that is no longer configured; its secret can't be recovered unless you add that key back. +#### Running the API behind a reverse proxy + +The API uses the client's IP address for IP restrictions and rate limiting. By default it uses the address of the TCP connection and ignores `X-Forwarded-For`, which is correct for the compose file: it publishes the API port directly, and nginx only serves the web app. + +If a reverse proxy, load balancer or CDN sits in front of the API, every request arrives from the proxy's address. Set `TRUST_PROXY` to a comma-separated list of the proxy's IP addresses or CIDR blocks (or `loopback`, `linklocal`, `uniquelocal`), for example `TRUST_PROXY=10.0.0.0/8`. The server then takes the client IP from the right-most `X-Forwarded-For` entry that a trusted proxy did not add. Make sure the API is only reachable through that proxy. Never trust a range that clients can connect from, because anyone who can reach the API from it can choose their own IP. Hop counts and `true` are rejected for that reason. + `API_URL` is read when the web container starts, so changing it only needs a restart (`docker compose up -d`), not a rebuild. It must be a plain `http(s)://host[:port][/path]` URL; the container refuses to start otherwise. A prebuilt API server image (`linux/amd64`, `linux/arm64`) is published to GHCR on every release: diff --git a/SPECIFICATION.md b/SPECIFICATION.md index fb1358a1..f9bc3785 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -396,6 +396,10 @@ Abstract - `ENCRYPTION_PREVIOUS_KEYS`: Comma-separated previous keys, accepted for reads only while rotating `ENCRYPTION_KEY` - `RATE_LIMIT_MAX`: Maximum requests per time window + - `TRUST_PROXY`: Comma-separated addresses or CIDR blocks of reverse + proxies whose `X-Forwarded-For` is trusted. The client IP drives IP + restrictions and rate limiting, so servers MUST NOT trust forwarded + headers from any other peer; the default trusts none - `BODY_LIMIT_BYTES`: Maximum request body size - `CORS_ORIGIN`: Allowed CORS origins - `WEBHOOK_*`: Webhook configuration parameters diff --git a/docker-compose.yaml b/docker-compose.yaml index af4445f3..78905ece 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -41,6 +41,10 @@ services: - ENCRYPTION_KEY=${ENCRYPTION_KEY:?ENCRYPTION_KEY is required (e.g. openssl rand -base64 32)} # Comma-separated keys kept for reading existing entries while rotating ENCRYPTION_KEY (see README). - ENCRYPTION_PREVIOUS_KEYS=${ENCRYPTION_PREVIOUS_KEYS:-} + # The API port is published directly (nginx only serves the web app), so the + # socket address is the client IP and X-Forwarded-For is ignored. Set this to + # your proxy's addresses only if you put a reverse proxy in front of the API. + - TRUST_PROXY=${TRUST_PROXY:-} ports: - '${SERVER_PORT:-4321}:${SERVER_PORT:-4321}' depends_on: diff --git a/packages/server/.env-example b/packages/server/.env-example index c8868c86..ed14356d 100644 --- a/packages/server/.env-example +++ b/packages/server/.env-example @@ -1,4 +1,5 @@ PORT=4321 +TRUST_PROXY= SHUTDOWN_TIMEOUT_MS=30000 HEALTH_CHECK_ENDPOINT=/health NODE_ENV=production diff --git a/packages/server/src/app.test.ts b/packages/server/src/app.test.ts index 3158db40..7c83e081 100644 --- a/packages/server/src/app.test.ts +++ b/packages/server/src/app.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { initApp } from './app.js'; -import { config as baseConfig } from './config.js'; +import { config as baseConfig, trustProxySchema } from './config.js'; import type { Config } from './config.js'; import type { AddressInfo } from 'node:net'; import { pino } from 'pino'; @@ -11,7 +11,7 @@ import { Redis } from 'ioredis'; import { Client } from 'undici'; import { machine, type CreateVaultRequest } from '@crypt.fyi/core'; -const initAppTest = async () => { +const initAppTest = async (overrides: Partial = {}) => { const config = { ...baseConfig, healthCheckEndpoint: '/some-health-check-endpoint', @@ -19,6 +19,7 @@ const initAppTest = async () => { // Keep counters out of Redis so unit tests cannot poison e2e / local API limits. rateLimiter: 'memory', rateLimitMax: Number.MAX_SAFE_INTEGER, + ...overrides, } satisfies Config; const logger = pino({ enabled: false }); const tokenGenerator = createTokenGenerator({ @@ -408,6 +409,67 @@ describe('app', () => { expect(decryptedWhU).toBe('https://example.com/webhook'); }); + describe('client IP behind proxies', () => { + const createIpRestricted = async (client: Client) => { + const response = await client.request({ + method: 'POST', + path: '/vault', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + c: 'secret-content', + b: false, + h: 'abc123', + ttl: 5000, + ips: '10.1.2.3', + m: { encryption: { algorithm: 'aes-256-gcm' } }, + } satisfies CreateVaultRequest), + }); + expect(response.statusCode).toBe(201); + const { id } = (await response.body.json()) as { id: string }; + return id; + }; + + const read = async (client: Client, id: string, xff: string) => { + const response = await client.request({ + method: 'GET', + path: `/vault/${id}?h=abc123`, + headers: { 'X-Forwarded-For': xff }, + }); + await response.body.dump(); + return response.statusCode; + }; + + it('ignores X-Forwarded-For by default', async () => { + const id = await createIpRestricted(testContext.client); + expect(await read(testContext.client, id, '10.1.2.3')).toBe(404); + }); + + it('uses X-Forwarded-For only from configured proxies', async () => { + const proxied = await initAppTest({ trustProxy: ['loopback'] }); + try { + const id = await createIpRestricted(proxied.client); + // The proxy appends the address it saw; an earlier, client-supplied entry is not trusted. + expect(await read(proxied.client, id, '10.1.2.3, 198.51.100.7')).toBe(404); + expect(await read(proxied.client, id, '10.1.2.3')).toBe(200); + } finally { + await proxied.app.shutdown(); + await proxied.client.close(); + } + }); + + it('parses TRUST_PROXY into a list of addresses', () => { + expect(trustProxySchema.parse(undefined)).toEqual([]); + expect(trustProxySchema.parse('')).toEqual([]); + expect(trustProxySchema.parse('10.0.0.1, 172.16.0.0/12,loopback')).toEqual([ + '10.0.0.1', + '172.16.0.0/12', + 'loopback', + ]); + expect(() => trustProxySchema.parse('true')).toThrow(); + expect(() => trustProxySchema.parse('1')).toThrow(); + }); + }); + describe('verification hash and delete token at rest', () => { const m = { encryption: { algorithm: 'aes-256-gcm' as const } }; const createEntry = async (body: Partial = {}) => { diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts index ca48456d..d70114de 100644 --- a/packages/server/src/app.ts +++ b/packages/server/src/app.ts @@ -63,7 +63,8 @@ export const initApp = async (config: Config, deps: AppDeps) => { const app = Fastify({ loggerInstance: logger, - trustProxy: true, + // Only the configured proxies may set the client IP; see TRUST_PROXY. + trustProxy: config.trustProxy.length > 0 ? config.trustProxy : false, bodyLimit: config.bodyLimit, genReqId: () => randomUUID(), }); diff --git a/packages/server/src/config.ts b/packages/server/src/config.ts index 8483ce79..4914c5d2 100644 --- a/packages/server/src/config.ts +++ b/packages/server/src/config.ts @@ -33,12 +33,54 @@ const env = getEnv(); const logLevels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] as const; +// Named ranges understood by Fastify's proxy-addr. +const trustProxyPresets = ['loopback', 'linklocal', 'uniquelocal']; + +/** + * Addresses of the reverse proxies whose X-Forwarded-For entries are trusted + * (IPs, CIDR blocks or proxy-addr presets). `req.ip` drives the IP allow-list + * and the rate limiter, so trusting the header from anyone else would let + * clients choose their own IP. Empty (the default) means the socket address is + * used. Hop counts are not accepted: Fastify cannot validate the immediate peer + * with them and treats them as trusting nothing. + */ +export const trustProxySchema = z + .string() + .optional() + .transform((value) => + (value ?? '') + .split(',') + .map((entry) => entry.trim()) + .filter(Boolean), + ) + .pipe( + z.array( + z.union( + [ + z.ipv4(), + z.ipv6(), + z.cidrv4(), + z.cidrv6(), + z.enum(trustProxyPresets as [string, ...string[]]), + ], + { + error: (issue) => + `TRUST_PROXY entries must be proxy IP addresses, CIDR blocks or one of ${trustProxyPresets.join(', ')}; got '${String(issue.input)}'`, + }, + ), + ), + ); + const configSchema = z.object({ shutdownTimeoutMs: z.coerce .number() .default(1000 * 30) .describe('graceful shutdown timeout in milliseconds'), port: z.coerce.number().default(4321).describe('port to listen on for HTTP server'), + trustProxy: z + .array(z.string()) + .default([]) + .describe('reverse proxy addresses whose X-Forwarded-For is trusted (comma-separated)'), healthCheckEndpoint: z.string().default('/health').describe('endpoint for health check'), env: z.nativeEnum(Environment).default(Environment.Dev).describe('environment'), logLevel: z.enum(logLevels).default('info').describe('log level'), @@ -171,6 +213,7 @@ export const config = (() => { return configSchema.parse({ shutdownTimeoutMs: process.env.SHUTDOWN_TIMEOUT_MS, port: process.env.PORT, + trustProxy: trustProxySchema.parse(process.env.TRUST_PROXY), healthCheckEndpoint: process.env.HEALTH_CHECK_ENDPOINT, env, logLevel: process.env.LOG_LEVEL, From d7948cacdb9b403d375523b9b6b1d27f3f4fa14c Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:01:37 -0600 Subject: [PATCH 3/3] docs: state that browser E2EE depends on who serves the client code --- SECURITY.md | 7 +++++++ SPECIFICATION.md | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/SECURITY.md b/SECURITY.md index 9e52151c..bee2641e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -36,6 +36,13 @@ Please include the following information in your report: - No server-side logging of sensitive data - Zero-Trust architecture +### Threat Model and Limits + +- Encryption happens in the client, so the API server never sees plaintext, decryption keys or passwords. A compromised API or datastore can withhold, delete or replay ciphertext, but can't decrypt it. +- In the web app, the client code itself is served by whoever hosts it. Whoever controls that host, its deploy pipeline or the web image can serve modified JavaScript that reads secrets and keys as they are entered or displayed. End-to-end encryption in a browser can't protect against the party that serves the page; this applies equally to self-hosted instances. +- For the strongest guarantee, use a client that doesn't load code from a server at run time, such as the CLI (`@crypt.fyi/cli`) or the desktop app, and verify what you install. +- Anyone holding the full link (including the key in its fragment) can read the secret unless a password, IP restriction or read limit stops them. Send passwords over a different channel than the link. + ### Development Practices - Dependencies are regularly updated and monitored for vulnerabilities diff --git a/SPECIFICATION.md b/SPECIFICATION.md index f9bc3785..7a9b93a4 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -269,6 +269,13 @@ Abstract - Even with full API server compromise, encrypted data MUST remain secure + These guarantees cover the API server and its data store. They do not + cover whoever delivers the client code: a browser client runs whatever + JavaScript its web host serves, so a compromised web host, deploy + pipeline or web image can read plaintext and keys in the browser. + Clients that do not load code at run time (the CLI and desktop app) + are not exposed to this. + ### 6.2. Data Security - Data MUST have automatic expiration (TTL: 1 second to 7 days)