The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
Fewer ops mails: daily guard digest, one failure mail a day, no alert about your own change (PR 2061)
Janik72fb8e1fd03a
diff --git a/.gitignore b/.gitignoreindex bc584069..d12375e7 100644--- a/.gitignore+++ b/.gitignore@@ -16,3 +16,4 @@ backups/*.dumpemail-previews/apps/agent/llm-test-results/+__pycache__/diff --git a/apps/api/src/admin-alert-actor.test.ts b/apps/api/src/admin-alert-actor.test.tsnew file mode 100644index 00000000..ed682ad3--- /dev/null+++ b/apps/api/src/admin-alert-actor.test.ts@@ -0,0 +1,32 @@+// LIN-900: no alert email about your own change while another admin hears of it; keys and impersonation always tell.+import { describe, expect, it } from 'vitest'+import { ownChange, withoutActor } from './admin-alert-actor.ts'++describe('withoutActor', () => {+ const admins = ['[email protected]', '[email protected]']+ it('leaves out the admin who made the change', () => {+ expect(withoutActor(admins, { email: '[email protected]' })).toEqual(['[email protected]'])+ })+ it('keeps everyone for the operator, an unknown actor or none', () => {+ expect(withoutActor(admins, { operator: true })).toEqual(admins)+ expect(withoutActor(admins, { email: null })).toEqual(admins)+ expect(withoutActor(admins, undefined)).toEqual(admins)+ })+ it('keeps the only admin: nobody else would hear of it', () => {+ expect(withoutActor(['[email protected]'], { email: '[email protected]' })).toEqual(['[email protected]'])+ })+})++describe('ownChange', () => {+ const who = { email: '[email protected]' }+ it('is the person in their own session', () => {+ expect(ownChange({ sessionId: 's' }, who)).toBe(who)+ })+ it('is nobody without a session, for a key or an impersonation', () => {+ expect(ownChange({}, who)).toBeUndefined()+ expect(ownChange({ sessionId: 's', setupKeyId: 'k' }, who)).toBeUndefined()+ expect(ownChange({ sessionId: 's', apiKeyId: 'k' }, who)).toBeUndefined()+ expect(ownChange({ sessionId: 's', personalKeyId: 'k' }, who)).toBeUndefined()+ expect(ownChange({ sessionId: 's', impersonation: { by: 'x' } }, who)).toBeUndefined()+ })+})diff --git a/apps/api/src/admin-alert-actor.ts b/apps/api/src/admin-alert-actor.tsnew file mode 100644index 00000000..407a4b6d--- /dev/null+++ b/apps/api/src/admin-alert-actor.ts@@ -0,0 +1,30 @@+// Who hears of a change (LIN-900): not the admin who made it in their own session, as long as another admin does.+// Its own file without the database, so the rule is tested on its own (admin-alert-actor.test.ts).+import type { AlertActor } from './emails/alerts.ts'++/** The admins to tell, without the one who made the change, unless nobody else would hear of it (alertInstanceAdmins). */+export function withoutActor(admins: string[], actor: AlertActor | undefined): string[] {+ const own = actor && !actor.operator ? actor.email?.toLowerCase() : undefined+ if (!own) return admins+ const others = admins.filter(a => a.toLowerCase() !== own)+ return others.length ? others : admins+}++/**+ * The actor to leave out of an alert (alertInstanceAdmins `actor`): only a person signed in to their own session, with+ * no key involved (an allowlist: a new kind of actor alerts everyone until it is added here). A key (API, personal, an+ * agent's setup key) or an impersonation acts in their name without being them, so they hear of it too.+ */+export function ownChange(+ actor: {+ sessionId?: string+ setupKeyId?: string+ apiKeyId?: string+ personalKeyId?: string+ impersonation?: unknown+ },+ who: AlertActor,+): AlertActor | undefined {+ const ownSession = Boolean(actor.sessionId) && !actor.setupKeyId && !actor.apiKeyId && !actor.personalKeyId+ return ownSession && !actor.impersonation ? who : undefined+}diff --git a/apps/api/src/admin-alerts.ts b/apps/api/src/admin-alerts.tsindex 1584fbc5..f67cacaa 100644--- a/apps/api/src/admin-alerts.ts+++ b/apps/api/src/admin-alerts.ts@@ -12,8 +12,15 @@ import { db } from './db.ts'import { type EmailSender, emailSender, sendNotice } from './email.ts'import { withoutEmailBrand } from './email-brand.ts'import { localeForEmail } from './email-locale.ts'-import { type AdminAlertText, adminAlertEmail, adminSignInAlert, type BrowserGuess } from './emails/alerts.ts'+import {+ type AdminAlertText,+ type AlertActor,+ adminAlertEmail,+ adminSignInAlert,+ type BrowserGuess,+} from './emails/alerts.ts'import { instanceAdminEmails, isInstanceAdmin } from './instance-admin.ts'+import { withoutActor } from './admin-alert-actor.ts'import { takeSetupSignIn } from './setup.ts'/**@@ -21,22 +28,32 @@ import { takeSetupSignIn } from './setup.ts'* (emails/alerts.ts). Resolves once the list and their languages are read; the sends run on their own, unless `wait`* (a job, so its retries can help): then it resolves once every email went out and throws when one did not. Without* email set up: skipped with one log line (no stack, nothing to retry).+ *+ * `actor`: the admin who made the change this alert is about. They are left out when another admin gets it (LIN-900:+ * no email about your own change; it stays in the audit log). With no other admin, they get it too: then it is the+ * only sign of a change made with their account by someone else.*/+export { ownChange } from './admin-alert-actor.ts'+export function alertInstanceAdmins(alert: AdminAlertText,sender: EmailSender = emailSender,- options: { wait?: boolean } = {},+ options: { wait?: boolean; actor?: AlertActor } = {},): Promise<void> {// The install's alert to its own admins: never in a partner's brand, wherever it was started (email-brand.ts).return withoutEmailBrand(() => sendAlert(alert, sender, options))}-async function sendAlert(alert: AdminAlertText, sender: EmailSender, { wait = false }: { wait?: boolean }) {+async function sendAlert(+ alert: AdminAlertText,+ sender: EmailSender,+ { wait = false, actor }: { wait?: boolean; actor?: AlertActor },+) {if (sender.kind === 'none') {console.log(`Admin alert not sent (email is not set up): ${alert(SOURCE).subject}`)return}- const admins = await instanceAdminEmails()+ const admins = withoutActor(await instanceAdminEmails(), actor)const locales = await Promise.all(admins.map(to => localeForEmail(db, to).catch(() => SOURCE)))const emails = admins.map((to, i) => ({ to, ...adminAlertEmail(alert(locales[i]), undefined, locales[i]) }))if (!wait) {diff --git a/apps/api/src/admin-handlers.ts b/apps/api/src/admin-handlers.tsindex c74d301c..7e7019a5 100644--- a/apps/api/src/admin-handlers.ts+++ b/apps/api/src/admin-handlers.ts@@ -237,13 +237,16 @@ const keysChange = (provider: ProviderName, what: 'changed' | 'removed', actor:/** Every instance admin hears about a change of email or sign-in (admin-alerts.ts), through `senders`. */async function alertChange({ change, provider, actor, money }: Change, senders: EmailSender[] = [emailSender]) {+ const who = await actorOf(actor)const alert = settingsChangedAlert({change,provider,- actor: await actorOf(actor),+ actor: who,agent: await agentOf(actor),...(money ? { money } : {}),})+ // Email, sign-in and money providers alert the admin who changed them too: with a stolen session, they are the one+ // person who knows it was not them (security review of LIN-900).for (const sender of senders) await alertInstanceAdmins(alert, sender)}diff --git a/apps/api/src/billing-admin.ts b/apps/api/src/billing-admin.tsindex e868ee98..e40a33c5 100644--- a/apps/api/src/billing-admin.ts+++ b/apps/api/src/billing-admin.ts@@ -52,7 +52,7 @@ import {user,} from '@linedesk/db'import { and, desc, eq, inArray, isNull, like, lt, ne, sql } from 'drizzle-orm'-import { alertInstanceAdmins } from './admin-alerts.ts'+import { alertInstanceAdmins, ownChange } from './admin-alerts.ts'import {BILLING_RULES_KEY,billingRules,@@ -1191,9 +1191,12 @@ export const billingAdminHandlers: Record<string, Handler> = {const keys = [...new Set([...Object.keys(before), ...Object.keys(next)])].sort()const changed = keys.filter(k => JSON.stringify(before[k]) !== JSON.stringify(next[k]))const fields = Object.keys(next).length ? changed : []- onCommit?.(async () =>- alertInstanceAdmins(billingRulesAlert({ actor: await alertActor(actor), fields, reason: input.reason })),- )+ onCommit?.(async () => {+ const who = await alertActor(actor)+ await alertInstanceAdmins(billingRulesAlert({ actor: who, fields, reason: input.reason }), undefined, {+ actor: ownChange(actor, who),+ })+ })// Changed plan prices reach Stripe now, not at a customer's Checkout (security review of #1040, M-1).if (changed.some(k => PLAN_RULE_FIELDS.has(k))) syncCatalogAfterCommit(onCommit)// The Stripe Tax switch reaches running subscriptions too, not only new Checkouts (security review of #1105, M-1).@@ -1212,7 +1215,12 @@ export const billingAdminHandlers: Record<string, Handler> = {throw Reject.t('server.api.signup.termsMissing', { vars: before.termsMissing.join(', ') })await writeSetting(tx, SELF_SERVE_KEY, input.on ? 'on' : 'off', actor, now)if (before.on !== input.on)- onCommit?.(async () => alertInstanceAdmins(selfServeAlert({ actor: await alertActor(actor), on: input.on })))+ onCommit?.(async () => {+ const who = await alertActor(actor)+ await alertInstanceAdmins(selfServeAlert({ actor: who, on: input.on }), undefined, {+ actor: ownChange(actor, who),+ })+ })return { rows: {}, data: await selfServe(tx) }},@@ -1240,11 +1248,14 @@ export const billingAdminHandlers: Record<string, Handler> = {const ruleChanges = signupRuleChanges(stateBefore.rules, stateAfter.rules)const opened = !stateBefore.open && stateAfter.openif (ruleChanges.length || opened)- onCommit?.(async () =>- alertInstanceAdmins(- signupRulesAlert({ actor: await alertActor(actor), changes: ruleChanges, opened, reason: input.reason }),- ),- )+ onCommit?.(async () => {+ const who = await alertActor(actor)+ await alertInstanceAdmins(+ signupRulesAlert({ actor: who, changes: ruleChanges, opened, reason: input.reason }),+ undefined,+ { actor: ownChange(actor, who) },+ )+ })return { rows: {}, data: { ...(await selfServe(tx)), changed, ruleChanges } }},}diff --git a/docs/architecture.md b/docs/architecture.mdindex 04abe58b..9ff32712 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -370,7 +370,7 @@ Better Auth's admin plugin was not used: it adds impersonation, user creation, p**What stays in env.** Only what the install needs before it can read its database: the secrets its containers share (`POSTGRES_PASSWORD`, `ELECTRIC_SECRET`, `BETTER_AUTH_SECRET`, `SECRETS_KEY`, `AGENT_API_TOKEN`, LiveKit's key and secret, which LiveKit, SIP and egress read from their own config), addresses (`PUBLIC_URL`) and limits. `scripts/setup.sh` writes them with random values, so a new install needs no hand-made `.env`. Every provider field keeps its variable as a fallback for scripted installs; `apps/api/src/providers-import.ts` moves set variables into the app.-**Sign-in is read at start, email applies at once** (`apps/api/src/instance-env.ts`): Better Auth is built with its sign-in providers once. `server.ts` copies the stored values of the email and sign-in categories into `process.env` (the stored value wins; `serverEnv` keeps the server's own variables, the fallback the admin area shows) and only then imports the app. A change of either (`provider.setKeys`/`clearKeys`, the email pick) needs Server admin, so the passkey check (an SMTP server or sign-in provider of one's own would hand over sign-in codes or any account), and emails every instance admin (`signInCategories`). Email then applies without a restart: once the action committed and before it answers (`onCommit`, run-action.ts), the stored email settings are copied into `process.env` again (`followEmailSettings`; a read that started earlier is never applied over a later one) and the sender (`email.ts`) follows `process.env`. Codes still waiting to be used (sign-in, confirmation, password reset, email change) are deleted, and the alert goes through the sender in effect before the change, and through the new one too when it differs (the first setup has none before), so a mail server of an attacker's own cannot swallow the alert about itself. Picking which email provider sends (`provider.setActive`) alerts the same way; the email code endpoints of Better Auth are always loaded and answered only while email can go out. A sign-in change restarts the API once it has committed where something starts it again (`LINEDESK_SELF_RESTART=1`, set by `docker/api-entrypoint.sh`: Docker's restart policy, dev mode's runner); in `pnpm dev` it logs that a restart is needed, and Server admin › Providers shows sign-in as "saved, takes effect after the API restarts" until then. Every API process also compares the stored rows every 15 s: it follows changed email settings and restarts for changed sign-in settings, so a second process follows. Sign-in (`sign_in`) is the one category where every provider that is set up is in use at once (`multiCategories`); the dialog shows the redirect URIs to add to the provider's app. "Test connection" for an OAuth app exchanges a made-up code: the provider checks the client first (`invalid_client`) and the code second (`invalid_grant`), so a rejected code means the app is right. SMTP is tested by connecting and logging in.+**Sign-in is read at start, email applies at once** (`apps/api/src/instance-env.ts`): Better Auth is built with its sign-in providers once. `server.ts` copies the stored values of the email and sign-in categories into `process.env` (the stored value wins; `serverEnv` keeps the server's own variables, the fallback the admin area shows) and only then imports the app. A change of either (`provider.setKeys`/`clearKeys`, the email pick) needs Server admin, so the passkey check (an SMTP server or sign-in provider of one's own would hand over sign-in codes or any account), and emails every instance admin (`signInCategories`), the one who made it included. Email then applies without a restart: once the action committed and before it answers (`onCommit`, run-action.ts), the stored email settings are copied into `process.env` again (`followEmailSettings`; a read that started earlier is never applied over a later one) and the sender (`email.ts`) follows `process.env`. Codes still waiting to be used (sign-in, confirmation, password reset, email change) are deleted, and the alert goes through the sender in effect before the change, and through the new one too when it differs (the first setup has none before), so a mail server of an attacker's own cannot swallow the alert about itself. Picking which email provider sends (`provider.setActive`) alerts the same way; the email code endpoints of Better Auth are always loaded and answered only while email can go out. A sign-in change restarts the API once it has committed where something starts it again (`LINEDESK_SELF_RESTART=1`, set by `docker/api-entrypoint.sh`: Docker's restart policy, dev mode's runner); in `pnpm dev` it logs that a restart is needed, and Server admin › Providers shows sign-in as "saved, takes effect after the API restarts" until then. Every API process also compares the stored rows every 15 s: it follows changed email settings and restarts for changed sign-in settings, so a second process follows. Sign-in (`sign_in`) is the one category where every provider that is set up is in use at once (`multiCategories`); the dialog shows the redirect URIs to add to the provider's app. "Test connection" for an OAuth app exchanges a made-up code: the provider checks the client first (`invalid_client`) and the code second (`invalid_grant`), so a rejected code means the app is right. SMTP is tested by connecting and logging in.**Branding** (Server admin › Branding, `branding.set`, `apps/api/src/branding.ts`): an install that runs under its own name sets the product name (shown wherever the app says Linedesk: menu, sign-in, tab title, emails, passkey prompts), a logo, the primary color (`--action`, text on it light or dark by contrast) and whether the GitHub star prompt shows (the one-time card, Star on GitHub in the sidebar and the line at the end of onboarding; the API reads the repository's star count from GitHub about once an hour, `apps/api/src/github-stars.ts`, and returns it as `starCount`, so browsers never call GitHub). Stored in `instance_settings` (`branding` as JSON, the logo under `branding.logo`). The browser turns any uploaded image into a PNG of at most 512×512 before it is sent; the server checks the PNG header and size and serves only that PNG (`GET /v1/branding/logo.png?v=<version>`, cached for good), so no uploaded SVG ever reaches a page. Public: `GET /v1/branding` (the web app reads it before sign-in and keeps it in localStorage for the next load) and `GET /v1/branding/manifest.webmanifest` (name and icons for the installed app). Each API process keeps the branding in memory for emails and messages (loaded at start, after its own change, every 30 s). Messages about the install itself say "this server" instead of a product name; developer-facing names (webhook headers, the API title, logs) stay Linedesk.diff --git a/ops/server/README.md b/ops/server/README.mdindex 80090e7f..65f63fdc 100644--- a/ops/server/README.md+++ b/ops/server/README.md@@ -32,7 +32,7 @@ sudo ops/server/setup.sh --dry-run # shows every file it would change, touche| `--harden-ssh`: keys only, no root login, 3 tries (refuses unless a sudo user with a full SSH key exists; checks `sshd -t` first and `sshd -T` after) | `etc/sshd-hardening.conf` | || `--ufw`: only SSH reaches the host's own services (Docker's published ports go past ufw; the firewalls above cover them) | | |-Both firewalls fail closed: every entry is checked before anything changes, and each chain is replaced in one step, so it never exists without its final DROP. A firewall, check or backup that fails sends an alert, at most one per unit every 6 hours. Alert emails carry a unit's last log lines without row data, and the SMTP password never shows on a command line.+Both firewalls fail closed: every entry is checked before anything changes, and each chain is replaced in one step, so it never exists without its final DROP. A firewall, check or backup that fails sends an alert, at most one per unit a day, naming how often it failed since the last one. Alert emails carry a unit's last log lines without row data, and the SMTP password never shows on a command line.Settings live in `/etc/linedesk/ops.env` (no secrets). Test the email: `/usr/local/sbin/linedesk-alert-text Test "Alerts work."`.diff --git a/ops/server/bin/linedesk-alert b/ops/server/bin/linedesk-alertindex 0d20df18..0e0a6e17 100755--- a/ops/server/bin/linedesk-alert+++ b/ops/server/bin/linedesk-alert@@ -2,21 +2,33 @@# Emails an alert about a failed systemd unit (OnFailure=linedesk-alert@%n.service) with the unit's last log lines.set -euunit=${1:?unit}-# At most one email per unit every 6 hours: a unit that runs every minute (WAL archiving) and keeps failing would-# otherwise send one a minute. The state is in StateDirectory=linedesk-alert (the unit).+# At most one email per unit a day (LIN-900; was every 6 hours, still so for the guard): a unit that runs every few minutes and keeps failing+# (WAL archiving, the autopilot every 30 minutes) would otherwise fill the inbox, and the one email that matters gets+# lost. The failures in between are counted and named in the next email. The state is in+# StateDirectory=linedesk-alert (the unit): its time is the last email, its text the failures since.state=${STATE_DIRECTORY:-/var/lib/linedesk-alert}/$(printf '%s' "$unit" | tr -c 'A-Za-z0-9@._-' _)-if [ -n "$(find "$state" -mmin -360 2>/dev/null)" ]; then- echo "linedesk-alert: $unit alerted less than 6 hours ago; not again"+# The guard's own units (they end shell windows and write the SSH keys) keep the 6 hours: one of them broken for a+# day is a risk, not noise.+quiet=1440+case $unit in linedesk-guard*) quiet=360 ;; esac+if [ -n "$(find "$state" -mmin -"$quiet" 2>/dev/null)" ]; then+ count=$(( $(head -c 12 "$state" | tr -cd 0-9 | sed 's/^$/0/') + 1 ))+ printf '%s\n' "$count" > "$state.tmp" && touch -r "$state" "$state.tmp" && mv "$state.tmp" "$state"+ echo "linedesk-alert: $unit mailed less than $((quiet / 60)) hours ago; failure $count since then, not mailed"exit 0fi+again=''+[ -f "$state" ] && again=$(head -c 12 "$state" | tr -cd 0-9)# The unit's last lines, shortened, without what a failed database step can print about rows (DETAIL, Failing row,# COPY data): enough to see what broke, the rest is on the server (journalctl -u <unit>).log=$(journalctl -u "$unit" -n 40 --no-pager -o short-iso 2>/dev/null |grep -viE 'DETAIL:|Failing row|COPY |INSERT INTO|VALUES ?\(' | tail -15 | cut -c1-240 || true)-/usr/local/sbin/linedesk-alert-text "$unit failed on $(hostname)" "$unit failed at $(date -u '+%F %T UTC').+more=''+[ "${again:-0}" -gt 0 ] && more=" It also failed $again more times since the last email about it."+/usr/local/sbin/linedesk-alert-text "$unit failed on $(hostname)" "$unit failed at $(date -u '+%F %T UTC').$moreLast log lines:$log"# Only a sent email counts: a failed send is tried again on the next failure.-touch "$state"+printf '0\n' > "$state"