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
5 changes: 5 additions & 0 deletions .changeset/cli-password-protection.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/trust-proxy.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 7 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions SPECIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -396,6 +403,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
Expand Down
4 changes: 4 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
55 changes: 55 additions & 0 deletions packages/cli/src/encrypt.test.ts
Original file line number Diff line number Diff line change
@@ -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',
);
});
});
52 changes: 52 additions & 0 deletions packages/cli/src/encrypt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type { Client } from '@crypt.fyi/core';

type CreateInput = Parameters<Client['create']>[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}`;
}
35 changes: 22 additions & 13 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -30,13 +31,14 @@ program
.option('-f, --file <file>', 'Path to file to encrypt')
.option('-p, --password <password>', 'Password to encrypt with')
.option('-t, --ttl <duration>', '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 <ip>', 'Restrict access to specific IP address')
.option('-r, --reads <count>', 'Number of times the secret can be read', undefined)
.option('--wh-url <url>', 'Webhook URL for notifications')
.option('--wh-events <list>', 'Comma-separated events: read, burn, failed-key, failed-ip', 'read')
.option('--wh-name <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);
Expand Down Expand Up @@ -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:'));
Expand Down
1 change: 1 addition & 0 deletions packages/server/.env-example
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
PORT=4321
TRUST_PROXY=
SHUTDOWN_TIMEOUT_MS=30000
HEALTH_CHECK_ENDPOINT=/health
NODE_ENV=production
Expand Down
66 changes: 64 additions & 2 deletions packages/server/src/app.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -11,14 +11,15 @@ import { Redis } from 'ioredis';
import { Client } from 'undici';
import { machine, type CreateVaultRequest } from '@crypt.fyi/core';

const initAppTest = async () => {
const initAppTest = async (overrides: Partial<Config> = {}) => {
const config = {
...baseConfig,
healthCheckEndpoint: '/some-health-check-endpoint',
vaultEntryTTLMsDefault: 1000,
// 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({
Expand Down Expand Up @@ -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<CreateVaultRequest> = {}) => {
Expand Down
3 changes: 2 additions & 1 deletion packages/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
});
Expand Down
Loading
Loading