sipher/tests/docker/generate-keys.ts
Nixyan 660c17b319 feat: add client-side identity system, rate limiting, proxy hardening, and full test suite
### Major changes

- **Client-side identity** — New session key store (`sessionKey.ts`) backed by
  `sessionStorage` with a module-level caching, a `crypto.subtle` cache, a `useIdentityLock`
  hook for decrypt-once signing, `followSignature.ts` for signed follows, and
  two new UI modals (`IdentityBackup.tsx`, `UnlockIdentityModal.tsx`).
  `CreateIdentity.tsx` is rewritten to generate BIP-39 mnemonics and encrypt the
  Ed25519 keypair with AES-256-GCM via PBKDF2 (600k iterations) before storing
  in IndexedDB.

- **Rate limiting** — New `rate-limit-config.ts` and `rate-limit.ts` provide a
  per-IP sliding-window rate limiter backed by Redis. All external-facing routes
  (`/discover`, `/discover/rotate/*`, `/proxy`, social API endpoints) now have
  conservative defaults wired into the custom HTTP server before requests reach
  Next.js handlers.

- **Proxy route hardening** — The `/proxy` route now enforces a 256 KB payload
  limit (HTTP 413), validates JSON before parsing, applies a per-origin rate
  limit (100 req/min), and imports the `blocks` table to reject requests from
  blocked servers.

- **Docker integration-test cluster** — New `Dockerfile`, `.dockerignore`, and
  `tests/docker-compose.yml` orchestrate three SiPher instances (A, B, C) plus
  shared PostgreSQL and Redis. Key generation (`generate-keys.ts`) and discovery
  setup (`setup-discovery.ts`) scripts automate cluster bootstrap. Three example
  env files document required per-instance configuration.

- **Full test suite overhaul** — Replaces the old attack/auth/discover/key/proxy
  tests with a structured suite:
  * `tests/federation/` — Keytools unit tests + key-rotation e2e test
  * `tests/proxy/` — Proxy relay e2e tests (single-server validation)
  * `tests/integration/` — Multi-instance integration tests for discover,
    proxy-chain relay, and federated post delivery via BullMQ
  * `tests/helpers/` — Reusable DB, identity, and auth-user utilities
  * Playwright config updated to match new file conventions
  * Unused helpers (`tests/helpers/queue.ts`) removed

- **Social plugin endpoints** — Rewritten `follows.ts`, `blocks.ts`, `mutes.ts`,
  and `posts.ts` with proper federation integration. `social.ts` gains helpers
  for looking up posts by federation URL.

### Minor changes

- **README** — Expanded from a 42-line stub to a full architecture guide with
  tables for every layer (auth, DB, queues, storage, real-time), API route
  documentation, setup instructions, environment variables, test coverage, and
  the updated roadmap.

- **Federation helpers** — `keytools.ts` refactors imports and cleans up the public surface.
  `fetch.ts`, `registry.ts`, and `proxy-helpers/federated-post.ts` pick up small
  improvements. `PostFederationSchema` simplifies its encryption type assertion.

- **Plugin infrastructure** — Oven plugin schema and server index gain minor
  refactors. Social client adds a `muteUser` method.

- **UI components** — `switch.tsx` and `tooltip.tsx` rewritten for Radix v2 /
  Tailwind 4; `accordion.tsx`, `dropdown-menu.tsx`, `form`, `button`, `card` get
  minor consistency fixes. `dialog.tsx` removes unused `DialogHeader`.

- **Server bootstrap** — `server.ts` imports DB schema before `instrumentation`
  for correct Drizzle initialization, rate-limiting routes are wired, and CORS
  allows federation origins. `auth.ts` regenerates Oven and social plugin schemas.

- **Dependencies** — Added `@noble/ciphers` and `@noble/hashes` (crypto
  primitives). Removed `@signalapp/libsignal-client`, `base58-js`, `nanostores`,
  `tweetnacl-util`, `dexie-react-hooks`, `socket.io-client`. Updated all Better
  Auth packages to 1.6.11, BullMQ to 5.76.10, and various dev deps across the
  board.

- **.gitignore** — Added `/audits` and `tests/docker/*.env` to prevent secret
  leakage.

- **DB schema** — `blocks` table imported in `src/lib/db/schema/index.ts`.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-18 09:48:42 -03:00

80 lines
3.1 KiB
TypeScript

/**
* Generates unique Ed25519 + X25519 federation keypairs AND a random
* BETTER_AUTH_SECRET for each Sipher instance, writing everything into
* tests/docker/sipher-{a,b,c}.env (created from *.env.example if not yet present).
*
* Usage:
* bun run docker:generate-keys
*
* Run this once before the first `docker compose up`. Re-running rotates all
* secrets — wipe the databases afterwards if you do that intentionally.
*/
import { readFileSync, writeFileSync, existsSync } from "node:fs";
import { randomBytes } from "node:crypto";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import nacl from "tweetnacl";
const DOCKER_DIR = dirname(fileURLToPath(import.meta.url));
function generateSecrets() {
const signing = nacl.sign.keyPair();
const encryption = nacl.box.keyPair();
return {
BETTER_AUTH_SECRET: randomBytes(32).toString("hex"),
FEDERATION_PUBLIC_KEY: Buffer.from(signing.publicKey).toString("base64"),
FEDERATION_PRIVATE_KEY: Buffer.from(signing.secretKey).toString("base64"),
FEDERATION_ENCRYPTION_PUBLIC_KEY: Buffer.from(encryption.publicKey).toString("base64"),
FEDERATION_ENCRYPTION_PRIVATE_KEY: Buffer.from(encryption.secretKey).toString("base64"),
};
}
/**
* Replace `KEY=<placeholder>` or `KEY=` lines in an env-file string.
* Matches both empty values and the CHANGE_ME_* placeholder values used in the
* example files so the script is idempotent on first run.
*/
function injectSecrets(content: string, secrets: ReturnType<typeof generateSecrets>): string {
let out = content;
for (const [k, v] of Object.entries(secrets)) {
out = out.replace(
new RegExp(`^(${k})=.*$`, "m"),
`$1=${v}`,
);
}
return out;
}
const instances = ["a", "b", "c"] as const;
for (const id of instances) {
const examplePath = join(DOCKER_DIR, `sipher-${id}.env.example`);
const outPath = join(DOCKER_DIR, `sipher-${id}.env`);
const template = readFileSync(examplePath, "utf8");
// If the env file already exists, start from it so any other custom edits
// (e.g. EMAIL_*, MINIO_*) are preserved; otherwise seed from the template.
const base = existsSync(outPath) ? readFileSync(outPath, "utf8") : template;
const secrets = generateSecrets();
const content = injectSecrets(base, secrets);
writeFileSync(outPath, content, "utf8");
console.log(`✔ tests/docker/sipher-${id}.env`);
console.log(` BETTER_AUTH_SECRET: ${secrets.BETTER_AUTH_SECRET.slice(0, 8)}`);
console.log(` signing key: ${secrets.FEDERATION_PUBLIC_KEY.slice(0, 12)}`);
console.log(` encryption key: ${secrets.FEDERATION_ENCRYPTION_PUBLIC_KEY.slice(0, 12)}`);
}
console.log(`
Done. Next steps:
1. docker compose -f tests/docker-compose.yml --profile init up # push DB schema
2. docker compose -f tests/docker-compose.yml up -d # start cluster
3. docker compose -f tests/docker-compose.yml --profile setup up # mutual discovery
4. Run integration tests inside Docker:
docker compose -f tests/docker-compose.yml run --rm test-runner \\
tests/integration/proxy-chain.ts \\
--proxy http://sipher-b:3001 --target http://sipher-c:3002
`);