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/install-and-runtime-defaults.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@reelsaw/server": minor
---

Safer defaults for new installs and the runtime. The installers now write `SIGNUP_MODE=approval` (the first account is still the admin), publish the web port on `127.0.0.1` only (`BIND_ADDRESS`, `REELSAW_BIND` when installing; existing installs keep listening as before), leave `LLM_TRACE` off, and require the generated database password instead of falling back to `reelsaw`. The development compose file publishes MinIO on `127.0.0.1`. Postgres connections get a statement timeout (`DB_STATEMENT_TIMEOUT_SECONDS`, default 300 s) and boot migrations a 10 s lock timeout. Hosted models' answers are capped at `LLM_MAX_OUTPUT_TOKENS` (default 16384) tokens.
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,10 @@ APP_URL=http://localhost:3000
# UPDATE_CHECK_HOURS=6
# Postgres connection string. Compose sets it; set it yourself when running from source.
# DATABASE_URL=postgres://reelsaw:reelsaw@localhost:5432/reelsaw
# Connections in each process's Postgres pool (minimum 4). Unset: 10, and a worker process grows its pool to half its job slots plus 4 (logged at boot as "postgres pool sized to the job slots"). The app and every worker process hold their own, so keep the total under Postgres' max_connections. Set explicitly, the value is used as is, and the boot log warns when the job slots are more than twice it. Model-call slots use a separate small pool, and connections time out after 10 s to connect and 5 minutes idle inside a transaction.
# Connections in each process's Postgres pool (minimum 4). Unset: 10, and a worker process grows its pool to half its job slots plus 4 (logged at boot as "postgres pool sized to the job slots"). The app and every worker process hold their own, so keep the total under Postgres' max_connections. Set explicitly, the value is used as is, and the boot log warns when the job slots are more than twice it. Model-call slots use a separate small pool, and connections time out after 10 s to connect and 5 minutes idle inside a transaction (statements: DB_STATEMENT_TIMEOUT_SECONDS).
# DB_POOL_MAX=
# A query running longer than this is cancelled by Postgres, so a runaway one gives its pool connection back (0 = never). Migrations at boot are not bounded by it; they give up after waiting 10 s for a table lock instead, so a deploy never queues the app's queries behind one.
# DB_STATEMENT_TIMEOUT_SECONDS=300
# 32+ random characters (openssl rand -base64 32). Signs sessions and encrypts the provider keys admins enter in Settings; rotating it makes those keys unreadable.
BETTER_AUTH_SECRET=change-me-to-a-long-random-string
# Working directory for uploads, per-project scratch files, the local storage driver and caches.
Expand Down Expand Up @@ -174,6 +176,8 @@ TRANSCRIBE_CHUNK_SECONDS=600
# ANALYZE_CONCURRENCY=0
# Longest one model call may take (all its HTTP attempts together) before the step is stopped and retried. 0 = auto: 120 s for a hosted model, 600 s for a self-hosted one (Ollama, a compatible server), and for a self-hosted transcription at least twice the chunk's audio length. Time spent waiting for a provider slot (PROVIDER_CONCURRENCY) does not count. A slow CPU-only model may need more. Runtime setting: admins can change it under Settings → System without a restart.
# LLM_CALL_TIMEOUT_SECONDS=0
# Longest answer a hosted model may give, in tokens, sent as the call's output limit (0 = the provider's own maximum). Every step's answer is a short JSON object, far under the default; the limit stops a runaway answer from running to the provider's maximum and being billed for. Self-hosted servers (the compatible server, openai with OPENAI_BASE_URL) are not given one: some refuse a limit larger than the room left in their context.
# LLM_MAX_OUTPUT_TOKENS=16384
# A stage made of checkpointed steps (finding moments) is stopped when no step has finished for this long; Retry continues where it stopped. 0 = auto: 1.5 times the model call timeout. Runtime setting: admins can change it under Settings → System without a restart.
# STAGE_IDLE_TIMEOUT_MINUTES=0
# Model calls in flight per provider across every app and worker process, e.g. compat=2,openai=2 (compat = the compatible provider's name). Unset providers: 2 for a self-hosted compatible server, 1 for openai with OPENAI_BASE_URL (a local whisper uses every core per call), unlimited for cloud. Time a call waits here does not count against its time limit.
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,10 @@ providers (OpenAI, Anthropic, Google, Groq, Vercel AI Gateway) are a choice in t
key is asked for and never echoed, and Anthropic and Google pair with local Speaches for
speech-to-text. Without a terminal, or with `REELSAW_YES=1`, the proposed answers are taken;
`REELSAW_AI`, `REELSAW_LLM`, `REELSAW_PORT` and friends answer in advance and `REELSAW_DRY_RUN=1`
prints the plan and stops (every option is listed at the top of the script).
prints the plan and stops (every option is listed at the top of the script). The installed app
listens on 127.0.0.1 (`REELSAW_BIND`, or `BIND_ADDRESS` in its `.env`), sign-ups after the first
account wait for the admin's approval (`SIGNUP_MODE=approval`), and model-call logging
(`LLM_TRACE`) is off.
Manual setup: [deploy/README.md](deploy/README.md).
The scripts are [deploy/install.sh](deploy/install.sh) and [deploy/install.ps1](deploy/install.ps1);
they are served from `main` (see [docs/RELEASING.md](docs/RELEASING.md)).
Expand Down
3 changes: 2 additions & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ should follow the update check (Settings → System) or watch releases.

## Hardening an instance

- Set `SIGNUP_MODE=closed` or `approval` after creating the first account.
- Set `SIGNUP_MODE=closed` or `approval` after creating the first account (the installers write
`approval` and publish the port on `127.0.0.1` only).
- Keep `BETTER_AUTH_SECRET` long and private; rotating it invalidates sessions and the provider
keys stored in Settings.
- Leave `ALLOW_PRIVATE_SOURCE_URLS` off unless the instance must read from a NAS.
Expand Down
10 changes: 9 additions & 1 deletion apps/server/scripts/docs-meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,13 @@ export const DOCS: Record<string, [GroupId, string]> = {
PORT: ["core", "Port the HTTP server listens on."],
APP_URL: ["core", "Public URL people open in the browser; used for auth cookies, CORS, the OAuth issuer and links in emails."],
DATABASE_URL: ["core", "Postgres connection string. Compose sets it; set it yourself when running from source."],
DB_STATEMENT_TIMEOUT_SECONDS: [
"core",
"A query running longer than this is cancelled by Postgres, so a runaway one gives its pool connection back (0 = never). Migrations at boot are not bounded by it; they give up after waiting 10 s for a table lock instead, so a deploy never queues the app's queries behind one.",
],
DB_POOL_MAX: [
"core",
"Connections in each process's Postgres pool (minimum 4). Unset: 10, and a worker process grows its pool to half its job slots plus 4 (logged at boot as \"postgres pool sized to the job slots\"). The app and every worker process hold their own, so keep the total under Postgres' `max_connections`. Set explicitly, the value is used as is, and the boot log warns when the job slots are more than twice it. Model-call slots use a separate small pool, and connections time out after 10 s to connect and 5 minutes idle inside a transaction.",
"Connections in each process's Postgres pool (minimum 4). Unset: 10, and a worker process grows its pool to half its job slots plus 4 (logged at boot as \"postgres pool sized to the job slots\"). The app and every worker process hold their own, so keep the total under Postgres' `max_connections`. Set explicitly, the value is used as is, and the boot log warns when the job slots are more than twice it. Model-call slots use a separate small pool, and connections time out after 10 s to connect and 5 minutes idle inside a transaction (statements: `DB_STATEMENT_TIMEOUT_SECONDS`).",
],
BETTER_AUTH_SECRET: [
"core",
Expand Down Expand Up @@ -223,6 +227,10 @@ export const DOCS: Record<string, [GroupId, string]> = {
"Model calls in flight per provider across every app and worker process, e.g. `compat=2,openai=2` (`compat` = the compatible provider's name). Unset providers: 2 for a self-hosted compatible server, 1 for openai with OPENAI_BASE_URL (a local whisper uses every core per call), unlimited for cloud. Time a call waits here does not count against its time limit.",
],
ANALYZE_CONCURRENCY: ["pipeline", "Parallel LLM calls while finding and scoring moments. 0 = auto: 1 for a self-hosted model, 4 for cloud."],
LLM_MAX_OUTPUT_TOKENS: [
"pipeline",
"Longest answer a hosted model may give, in tokens, sent as the call's output limit (0 = the provider's own maximum). Every step's answer is a short JSON object, far under the default; the limit stops a runaway answer from running to the provider's maximum and being billed for. Self-hosted servers (the compatible server, `openai` with `OPENAI_BASE_URL`) are not given one: some refuse a limit larger than the room left in their context.",
],
LLM_CALL_TIMEOUT_SECONDS: [
"pipeline",
"Longest one model call may take (all its HTTP attempts together) before the step is stopped and retried. 0 = auto: 120 s for a hosted model, 600 s for a self-hosted one (Ollama, a compatible server), and for a self-hosted transcription at least twice the chunk's audio length. Time spent waiting for a provider slot (PROVIDER_CONCURRENCY) does not count. A slow CPU-only model may need more.",
Expand Down
1 change: 1 addition & 0 deletions apps/server/scripts/test-env.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export function testEnv(env: Record<string, string | undefined>): { env: Record<string, string | undefined>; removed: string[] };
16 changes: 16 additions & 0 deletions apps/server/scripts/test-env.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// The environment the stack-free tests run in: the host's without model-provider credentials. A developer's shell
// often exports ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN or a provider key for their own tools; the provider
// packages read those at call time, so a test that builds a real provider would send requests to that endpoint with
// that token, or fail on what it points at, instead of behaving the same as in CI.
const PROVIDER_VAR =
/^(ANTHROPIC|OPENAI|OPENAI_COMPATIBLE|GOOGLE_GENERATIVE_AI|GOOGLE_VERTEX|GROQ|DEEPGRAM|ASSEMBLYAI|AI_GATEWAY|OPENCODE|LANGFUSE)_|^VERCEL_OIDC_TOKEN$/;

/** @param {Record<string, string | undefined>} env @returns {{ env: Record<string, string | undefined>, removed: string[] }} */
export function testEnv(env) {
const removed = Object.keys(env)
.filter((k) => PROVIDER_VAR.test(k))
.sort();
const out = { ...env };
for (const k of removed) delete out[k];
return { env: out, removed };
}
6 changes: 5 additions & 1 deletion apps/server/scripts/unit-tests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { readdirSync, readFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { testEnv } from "./test-env.mjs";

const stack = process.argv.includes("--stack");
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
Expand All @@ -19,5 +20,8 @@ const files = readdirSync(dir)
console.log(`${files.length} ${stack ? "stack" : "stack-free"} test files`);
// the stack files share one app and one Postgres: same concurrency as `pnpm test`
const args = ["--import", "tsx", "--test", ...(stack ? ["--test-concurrency=2"] : []), ...files];
const r = spawnSync(process.execPath, args, { cwd: root, stdio: "inherit" });
// stack-free files never reach a model: the host's provider credentials stay out (test-env.mjs)
const { env, removed } = stack ? { env: process.env, removed: [] } : testEnv(process.env);
if (removed.length) console.log(`left out of the tests' environment: ${removed.join(", ")}`);
const r = spawnSync(process.execPath, args, { cwd: root, stdio: "inherit", env });
process.exit(r.status ?? 1);
25 changes: 24 additions & 1 deletion apps/server/src/ai/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,25 @@
}),
};

/**
* A ceiling on every answer's length (LLM_MAX_OUTPUT_TOKENS, OWASP LLM10). Without one a degenerate answer runs to the
* provider's own maximum (64k tokens and more for current models) or the call timeout, and is billed for. A call that
* asks for less (the model test asks for 8) keeps its own number.
*/
export function outputCap(max: number): LanguageModelMiddleware {
return { transformParams: async ({ params }) => ({ ...params, maxOutputTokens: Math.min(params.maxOutputTokens ?? max, max) }) };
}

/**
* Whether answers from this provider get `outputCap`: hosted providers only. A self-hosted server (the compatible
* server, or "openai" pointed at OPENAI_BASE_URL) costs nothing per token, and some (vLLM, llama.cpp) refuse a
* max_tokens larger than the room left in their context, which would fail every long prompt.
*/
export function capsOutput(provider: string, o: { compatName: string; baseUrl: string | undefined; max: number }): boolean {
if (o.max <= 0) return false;
return !(provider === o.compatName || (provider === "openai" && !!o.baseUrl));
}

export function createAi(
config: Config,
log: Logger,
Expand All @@ -153,7 +172,7 @@
/** word-timestamp verdicts (ai/word-timestamps.ts); shared through the database in the app, per process otherwise */
verdicts: VerdictStore = memoryVerdictStore(),
): AiService {
type Registry = ReturnType<typeof createProviderRegistry<Record<string, any>, ":">>;

Check warning on line 175 in apps/server/src/ai/registry.ts

View workflow job for this annotation

GitHub Actions / check

lint/suspicious/noExplicitAny

Unexpected any. Specify a different type.
let registry: { version: number; value: Promise<Registry> } | undefined;
const compat = config.OPENAI_COMPATIBLE_NAME;

Expand Down Expand Up @@ -197,7 +216,7 @@
: wordsFirst(openai.transcription(id)),
);
const groq = createGroq(key("groq"));
const providers: Record<string, any> = {

Check warning on line 219 in apps/server/src/ai/registry.ts

View workflow job for this annotation

GitHub Actions / check

lint/suspicious/noExplicitAny

Unexpected any. Specify a different type.
openai: openaiProvider,
anthropic: createAnthropic(key("anthropic")),
google: createGoogle(key("google")),
Expand Down Expand Up @@ -426,8 +445,12 @@
const model = (await resolve("language", id)) as Exclude<LanguageModel, string>;
// every model handed out: lenient OpenAI schemas, then LLM_TRACE capture (logs / Langfuse) when on
const chain = middleware ? [lenientJsonSchema, middleware] : [lenientJsonSchema];
// outside the trace, so the captured settings show the ceiling the provider was sent
const provider = providerOf(id);
const max = config.LLM_MAX_OUTPUT_TOKENS;
if (capsOutput(provider, { compatName: compat, baseUrl: credentials.get(provider).baseUrl, max })) chain.unshift(outputCap(max));
// the provider gate goes outermost, so a call's traced latency doesn't include its wait for a slot
if (gate) chain.unshift(gate.middleware(providerOf(id)));
if (gate) chain.unshift(gate.middleware(provider));
return wrapLanguageModel({ model: model as Parameters<typeof wrapLanguageModel>[0]["model"], middleware: chain }) as LanguageModel;
},
transcriptionModel: async (id = current().transcription) => (await resolve("transcription", id)) as TranscriptionModel,
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const envSchema = z.object({
* its job slots (workers.ts). Model-call slots (ai/gate.ts) use their own small pool.
*/
DB_POOL_MAX: z.coerce.number().int().min(4).optional(),
DB_STATEMENT_TIMEOUT_SECONDS: z.coerce.number().int().min(0).max(86_400).default(300),
BETTER_AUTH_SECRET: z.string().min(16),
DATA_DIR: z.string().default(path.resolve(process.cwd(), "data")),
WEB_DIST: z.string().optional(),
Expand Down Expand Up @@ -134,6 +135,8 @@ export const envSchema = z.object({
ANALYZE_CONCURRENCY: z.coerce.number().int().min(0).max(16).default(0),
// one model call (all its HTTP attempts) may take this long; 0 = auto: 120 s hosted, 600 s self-hosted
LLM_CALL_TIMEOUT_SECONDS: z.coerce.number().int().min(0).max(86_400).default(0),
/** Longest answer a hosted model may give, in tokens (0 = the provider's own maximum). Self-hosted servers keep theirs. */
LLM_MAX_OUTPUT_TOKENS: z.coerce.number().int().min(0).max(1_000_000).default(16_384),
// a checkpointed stage that finishes no unit of work for this long is stopped (it resumes on retry); 0 = auto: 1.5 x the call timeout
STAGE_IDLE_TIMEOUT_MINUTES: z.coerce.number().int().min(0).max(1440).default(0),
/** Model calls in flight per provider across every process ("ollama=2,openai=16"; 0 = unlimited). Unset: 2 for self-hosted (the compatible server, openai with a base URL), unlimited for cloud. See ai/gate.ts. */
Expand Down
Loading
Loading