fix(audit): comprehensive 2026-05-15 audit fix wave + Documenso v2 polish
Bundles the prior session's 50-task fix sweep (Documenso v2 + EOI/signing-
progress redesign + env-to-admin migration + dev-mode banner) with the
2026-05-18 audit fix wave (3 CRITICAL, 14 HIGH, 28 MEDIUM, 6 LOW).
CRITICAL (3):
- C-01 interest-berths INNER JOIN -> LEFT JOIN so hard-deleted berths
no longer silently drop interest links
- C-02 /setup added to PUBLIC_PATHS; fresh-deploy bootstrap loop fixed
- C-03 generic PATCH /interests/[id] no longer accepts pipelineStage —
callers must go through /stage with the override-guard chain
HIGH (14/15):
- H-01 explicit ON DELETE on previously-implicit NO ACTION FKs across
interests/documents/reservations/reminders/invoices (migration 0070)
- H-02 login page reads ?redirect= param with same-origin guard
- H-03 CRM invite token moves to URL fragment so it never lands in
nginx access logs / Referer headers
- H-04 Retry-After header on sign-in-by-identifier 429 (RFC 6585 §4)
- H-05 toggleAccount writes an audit row
- H-06 upsertSetting masks any value whose key ends with _encrypted
- H-07 archiveClient cascade fires per-interest audit rows
- H-08 createSalesTransporter applies SMTP_TIMEOUTS
- H-09 AppShell stable children — viewport flip across breakpoint no
longer destroys in-progress form drafts
- H-10 portal documents page swaps Unicode glyph status icons for
Lucide CheckCircle2/XCircle/Circle + aria-labels
- H-12 list components swap alert(...) for toast.warning(...)
- H-13 5 icon-only buttons gain aria-label
- H-14 parseBody treats empty bodies as {}
- H-15 admin layout renders a 403 panel instead of silent bounce
- H-11 not applicable — mobile-search-overlay IS a mobile bottom-sheet
MEDIUM (28+):
- M-MT01-05 defense-in-depth port_id/parent-id filters on UPDATE/DELETE
WHEREs across custom-fields, notes (all 6 entity types x update +
delete), client-contacts, yacht ownerClient lookup, webhook reads
- M-D01 documents-hub realtime event-name typo (file:created -> uploaded)
- M-EM01 portal-auth emails thread through portId
- M-EM02 sendEmail accepts cc/bcc params
- M-EM04 notification_digest catalog key
- M-IN01 portal presigned download URLs use 4h TTL
- M-IN02 OpenAI client lazy-instantiated
- M-IN04 stale pdfme refs updated to pdf-lib AcroForm
- M-IN05 umami.testConnection returns tagged union
- M-L01 reservations tenure_type unified with berths
- M-L02 report-generators canonicalize stage values
- M-AU01 audit log placeholder copy fixed
- M-AU04 outcome_set / outcome_cleared distinct audit verbs
- M-NEW-2 activity feed entity name+type separator
- M-R01 portal allowlist narrowed + portal_session backstop in proxy
- M-SC02 companies archived partial index
- M-SC04 audit_logs.searchText documented as DB-managed
- M-S01 storage_s3_access_key_encrypted admin field
- M-U01 audit log empty state uses <EmptyState>
- M-U09 invoice delete dialog -> <AlertDialog>
- M-U10 toast.success on ClientForm + InterestForm create/edit
- M-U11 settings-form-card logo preview alt text
- M-U14 mobile topbar title on clients/yachts/interests/berths
- M-U15 Invoices in mobile More-sheet
LOW (6/8):
- L-AU01 severity defaults for security-relevant verbs
- L-AU02 +13 missing actions in admin audit filter
- L-AU03 +7 missing entity types in admin audit filter
- L-AU04 dead listAuditLogs stubbed
- L-D02 CLAUDE.md Owner-wins chain tightened
Bonus — Document detail polish (#67 partial, 3/6 deliverables):
- state-aware action button per signer
- watcher Add UI with display-name resolution
- cleanSignerName cleanup
Prior session work bundled in:
- Documenso v2 webhook + envelope-ID normalization + sequential signing
- SigningProgress UI redesign (avatars, per-signer state, timestamps)
- env->admin settings registry + RegistryDrivenForm + encrypted creds
- Embedded-signing card + Test connection + setup help
- Dev-mode EMAIL_REDIRECT_TO banner
- Pipeline rules admin page
- Sales email config card
- Audit log details Sheet
- EOI tab: Finalising badge, absolute timestamps, sequential indicator
- Notes pipeline_stage_at_creation (migration 0069)
- Documenso numeric ID dual-key webhook (migration 0068)
- Dimensions criterion copy (migration 0067)
Tests: 1374/1374 vitest pass. tsc clean. lint clean.
See docs/AUDIT-FIX-WAVE-2026-05-18.md for the full progress report and
the user-input items still pending.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
517
src/lib/settings/registry.ts
Normal file
517
src/lib/settings/registry.ts
Normal file
@@ -0,0 +1,517 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { SettingEntry } from './types';
|
||||
|
||||
/**
|
||||
* Central registry of every tenant-configurable setting. One entry per setting,
|
||||
* consumed by the resolver, the admin form generator, the validator, and the
|
||||
* encryption helper. Adding a new integration is a registry entry — no new
|
||||
* schema, no new resolver, no new admin page wiring.
|
||||
*
|
||||
* Do NOT register boot-time / build-time secrets here (DATABASE_URL,
|
||||
* BETTER_AUTH_SECRET, NEXT_PUBLIC_*, etc.). Those stay in env.ts because
|
||||
* they're needed before the DB is reachable or get baked into the client
|
||||
* bundle at build time.
|
||||
*
|
||||
* Section naming convention: `<integration>.<group>` (e.g. `documenso.api`,
|
||||
* `documenso.signers`, `email.smtp`). The admin form generator filters by
|
||||
* section name, so keep them stable.
|
||||
*/
|
||||
export const REGISTRY: SettingEntry[] = [
|
||||
// ─── Documenso API ────────────────────────────────────────────────────────
|
||||
// Keys keep the existing `_override` suffix for the env-fallback fields so
|
||||
// existing data + per-domain readers (`getPortDocumensoConfig` etc.) don't
|
||||
// need a rename migration. Brand-new fields (webhook secret) use plain
|
||||
// suffix-free keys.
|
||||
{
|
||||
key: 'documenso_api_url_override',
|
||||
section: 'documenso.api',
|
||||
label: 'API URL',
|
||||
description:
|
||||
'Bare host only — never include /api/v1. The client appends versioned paths based on the API version below.',
|
||||
type: 'url',
|
||||
scope: 'port',
|
||||
envFallback: 'DOCUMENSO_API_URL',
|
||||
placeholder: 'https://documenso.example.com',
|
||||
},
|
||||
{
|
||||
key: 'documenso_api_key_override',
|
||||
section: 'documenso.api',
|
||||
label: 'API key',
|
||||
description: 'AES-encrypted at rest. Only stored when set explicitly.',
|
||||
type: 'password',
|
||||
scope: 'port',
|
||||
encrypted: true,
|
||||
sensitive: true,
|
||||
envFallback: 'DOCUMENSO_API_KEY',
|
||||
},
|
||||
{
|
||||
key: 'documenso_api_version_override',
|
||||
section: 'documenso.api',
|
||||
label: 'API version',
|
||||
description:
|
||||
'v1 = Documenso 1.13.x stable. v2 = Documenso 2.x with the envelope model. Test the connection after switching.',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ value: 'v1', label: 'v1 — Documenso 1.13.x (default, stable)' },
|
||||
{ value: 'v2', label: 'v2 — Documenso 2.x (envelope, recommended for new ports)' },
|
||||
],
|
||||
scope: 'port',
|
||||
envFallback: 'DOCUMENSO_API_VERSION',
|
||||
defaultValue: 'v1',
|
||||
},
|
||||
{
|
||||
key: 'documenso_webhook_secret',
|
||||
section: 'documenso.api',
|
||||
label: 'Webhook secret',
|
||||
description:
|
||||
'Verifies inbound webhook deliveries via the X-Documenso-Secret header (timing-safe compare). Generate with `openssl rand -hex 16`.',
|
||||
type: 'password',
|
||||
scope: 'port',
|
||||
encrypted: true,
|
||||
sensitive: true,
|
||||
envFallback: 'DOCUMENSO_WEBHOOK_SECRET',
|
||||
validator: z.string().min(16),
|
||||
},
|
||||
|
||||
// ─── Documenso signers ────────────────────────────────────────────────────
|
||||
{
|
||||
key: 'documenso_developer_name',
|
||||
section: 'documenso.signers',
|
||||
label: 'Developer signer — name',
|
||||
description:
|
||||
"Override the name on the developer recipient slot. Leave blank to use whatever's set on the Documenso template.",
|
||||
type: 'string',
|
||||
scope: 'port',
|
||||
},
|
||||
{
|
||||
key: 'documenso_developer_email',
|
||||
section: 'documenso.signers',
|
||||
label: 'Developer signer — email',
|
||||
description:
|
||||
"Override the email on the developer recipient slot. Leave blank to use whatever's set on the Documenso template.",
|
||||
type: 'email',
|
||||
scope: 'port',
|
||||
},
|
||||
{
|
||||
key: 'documenso_developer_label',
|
||||
section: 'documenso.signers',
|
||||
label: 'Developer signer — label',
|
||||
description: 'Display label shown on the signing screen (defaults to "Developer").',
|
||||
type: 'string',
|
||||
scope: 'port',
|
||||
placeholder: 'Developer',
|
||||
},
|
||||
{
|
||||
key: 'documenso_developer_recipient_id',
|
||||
section: 'documenso.signers',
|
||||
label: 'Developer Documenso recipient ID',
|
||||
description:
|
||||
'Numeric Documenso recipient slot ID for the developer signer. Set automatically by "Sync from Documenso" — you rarely set this by hand.',
|
||||
type: 'number',
|
||||
scope: 'port',
|
||||
envFallback: 'DOCUMENSO_DEVELOPER_RECIPIENT_ID',
|
||||
},
|
||||
{
|
||||
key: 'documenso_developer_user_id',
|
||||
section: 'documenso.signers',
|
||||
label: 'Developer signer — linked CRM user (optional)',
|
||||
description:
|
||||
"Project Director RBAC binding. When set, the webhook handler fires an in-CRM notification for this user when it's their turn to sign — alongside the branded email. Leave blank if the developer slot doesn't map to a CRM user (e.g. external developer).",
|
||||
type: 'user-select',
|
||||
scope: 'port',
|
||||
},
|
||||
{
|
||||
key: 'documenso_approver_name',
|
||||
section: 'documenso.signers',
|
||||
label: 'Approver signer — name',
|
||||
description:
|
||||
"Override the name on the approver recipient slot. Leave blank to use whatever's set on the Documenso template.",
|
||||
type: 'string',
|
||||
scope: 'port',
|
||||
},
|
||||
{
|
||||
key: 'documenso_approver_email',
|
||||
section: 'documenso.signers',
|
||||
label: 'Approver signer — email',
|
||||
description:
|
||||
"Override the email on the approver recipient slot. Leave blank to use whatever's set on the Documenso template.",
|
||||
type: 'email',
|
||||
scope: 'port',
|
||||
},
|
||||
{
|
||||
key: 'documenso_approver_label',
|
||||
section: 'documenso.signers',
|
||||
label: 'Approver signer — label',
|
||||
description: 'Display label shown on the signing screen (defaults to "Approver").',
|
||||
type: 'string',
|
||||
scope: 'port',
|
||||
placeholder: 'Approver',
|
||||
},
|
||||
{
|
||||
key: 'documenso_approval_recipient_id',
|
||||
section: 'documenso.signers',
|
||||
label: 'Approver Documenso recipient ID',
|
||||
description:
|
||||
'Numeric Documenso recipient slot ID for the approver. Set automatically by "Sync from Documenso" — you rarely set this by hand.',
|
||||
type: 'number',
|
||||
scope: 'port',
|
||||
envFallback: 'DOCUMENSO_APPROVAL_RECIPIENT_ID',
|
||||
},
|
||||
{
|
||||
key: 'documenso_approver_user_id',
|
||||
section: 'documenso.signers',
|
||||
label: 'Approver — linked CRM user (optional)',
|
||||
description:
|
||||
"Same as developer's linked user — when set, fires an in-CRM notification when it's the approver's turn to sign.",
|
||||
type: 'user-select',
|
||||
scope: 'port',
|
||||
},
|
||||
{
|
||||
key: 'documenso_client_recipient_id',
|
||||
section: 'documenso.signers',
|
||||
label: 'Client recipient ID',
|
||||
description:
|
||||
'Documenso recipient ID for the client slot. Maps to DOCUMENSO_CLIENT_RECIPIENT_ID in env.',
|
||||
type: 'number',
|
||||
scope: 'port',
|
||||
envFallback: 'DOCUMENSO_CLIENT_RECIPIENT_ID',
|
||||
},
|
||||
|
||||
// ─── Documenso templates ──────────────────────────────────────────────────
|
||||
{
|
||||
key: 'documenso_eoi_template_id',
|
||||
section: 'documenso.templates',
|
||||
label: 'EOI Documenso template ID',
|
||||
description:
|
||||
'Numeric template ID used by the Documenso EOI pathway. Populated automatically by "Sync from Documenso" below.',
|
||||
type: 'number',
|
||||
scope: 'port',
|
||||
envFallback: 'DOCUMENSO_TEMPLATE_ID_EOI',
|
||||
placeholder: '12345',
|
||||
},
|
||||
{
|
||||
key: 'eoi_default_pathway',
|
||||
section: 'documenso.templates',
|
||||
label: 'Default EOI pathway',
|
||||
description:
|
||||
'Which pathway is used when an EOI is generated without an explicit choice. Documenso = signed via Documenso, In-app = filled locally with pdf-lib.',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ value: 'documenso-template', label: 'Documenso template' },
|
||||
{ value: 'inapp', label: 'In-app (pdf-lib)' },
|
||||
],
|
||||
scope: 'port',
|
||||
defaultValue: 'documenso-template',
|
||||
},
|
||||
{
|
||||
key: 'eoi_send_mode',
|
||||
section: 'documenso.templates',
|
||||
label: 'Initial signing-invitation email behaviour',
|
||||
description:
|
||||
'Auto = the system sends the branded "please sign" email immediately when an EOI/contract/reservation is generated. Manual = the document is generated and the signing URL appears in the UI; a rep clicks "Send invitation" to dispatch. Applies to all document types, not just EOI.',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ value: 'manual', label: 'Manual (rep clicks Send after generation)' },
|
||||
{ value: 'auto', label: 'Auto (send branded email on generate)' },
|
||||
],
|
||||
scope: 'port',
|
||||
defaultValue: 'manual',
|
||||
},
|
||||
{
|
||||
key: 'documenso_reservation_template_id',
|
||||
section: 'documenso.templates',
|
||||
label: 'Reservation template ID',
|
||||
description: 'Template ID used for reservation agreements (optional).',
|
||||
type: 'number',
|
||||
scope: 'port',
|
||||
},
|
||||
{
|
||||
key: 'documenso_contract_template_id',
|
||||
section: 'documenso.templates',
|
||||
label: 'Contract template ID',
|
||||
description: 'Template ID used for the final purchase / lease contract (optional).',
|
||||
type: 'number',
|
||||
scope: 'port',
|
||||
},
|
||||
|
||||
// ─── Documenso behavior ───────────────────────────────────────────────────
|
||||
{
|
||||
key: 'documenso_signing_order',
|
||||
section: 'documenso.behavior',
|
||||
label: 'Signing order',
|
||||
description:
|
||||
'PARALLEL = all recipients can sign at once. SEQUENTIAL = each waits for the previous (v2 only — v1 always parallel).',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ value: 'PARALLEL', label: 'Parallel — all recipients sign concurrently' },
|
||||
{ value: 'SEQUENTIAL', label: 'Sequential — order matters (v2 only)' },
|
||||
],
|
||||
scope: 'port',
|
||||
defaultValue: 'PARALLEL',
|
||||
},
|
||||
{
|
||||
key: 'documenso_redirect_url',
|
||||
section: 'documenso.behavior',
|
||||
label: 'Post-sign redirect URL',
|
||||
description: 'Where signers land after completing their signature. Both v1 and v2 honour it.',
|
||||
type: 'url',
|
||||
scope: 'port',
|
||||
},
|
||||
|
||||
// ─── Pipeline auto-advance ───────────────────────────────────────────────
|
||||
// JSON map keyed by trigger name; value is one of 'auto' | 'suggest' |
|
||||
// 'off'. Read by `getStageAdvanceMode` in port-config.ts. The registry
|
||||
// entry uses the generic `string` type because the form generator's
|
||||
// schemas don't have a JSON variant — the admin UI is a dedicated page
|
||||
// (/admin/pipeline-rules) that renders 3-way toggles per trigger.
|
||||
{
|
||||
key: 'stage_advance_rules',
|
||||
section: 'pipeline.auto_advance',
|
||||
label: 'Pipeline auto-advance rules',
|
||||
description:
|
||||
'Per-trigger control for whether lifecycle events (EOI sent/signed, deposit received, etc.) auto-advance the deal stage, only suggest the move via a notification, or do nothing.',
|
||||
type: 'string',
|
||||
scope: 'port',
|
||||
validator: z.record(z.string(), z.enum(['auto', 'suggest', 'off'])),
|
||||
},
|
||||
|
||||
// ─── AI / OpenAI ──────────────────────────────────────────────────────────
|
||||
{
|
||||
key: 'ai_enabled',
|
||||
section: 'ai.master',
|
||||
label: 'AI features enabled',
|
||||
description:
|
||||
'Master switch. When OFF, every AI surface (receipt OCR, berth-PDF AI parse) is bypassed. Provider keys stay configured but unused.',
|
||||
type: 'boolean',
|
||||
scope: 'port',
|
||||
defaultValue: true,
|
||||
},
|
||||
{
|
||||
key: 'ai_monthly_token_cap',
|
||||
section: 'ai.master',
|
||||
label: 'Monthly token cap (this port)',
|
||||
description:
|
||||
'Soft cap on total AI tokens consumed per calendar month. When exceeded, AI features fall back to non-AI paths and surface a banner. Set 0 for no cap.',
|
||||
type: 'number',
|
||||
scope: 'port',
|
||||
defaultValue: 0,
|
||||
},
|
||||
{
|
||||
key: 'openai_api_key',
|
||||
section: 'ai.providers',
|
||||
label: 'OpenAI API key',
|
||||
description: 'Used by Receipt OCR fallback and berth-PDF AI parse. AES-encrypted at rest.',
|
||||
type: 'password',
|
||||
scope: 'port',
|
||||
encrypted: true,
|
||||
sensitive: true,
|
||||
envFallback: 'OPENAI_API_KEY',
|
||||
placeholder: 'sk-…',
|
||||
},
|
||||
{
|
||||
key: 'openai_default_model',
|
||||
section: 'ai.providers',
|
||||
label: 'Default OpenAI model',
|
||||
description: 'Used when a feature does not specify an explicit model.',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ value: 'gpt-4o-mini', label: 'gpt-4o-mini — cheap, fast, vision-capable' },
|
||||
{ value: 'gpt-4o', label: 'gpt-4o — full-strength multimodal' },
|
||||
{ value: 'gpt-4-turbo', label: 'gpt-4-turbo — legacy text reasoning' },
|
||||
],
|
||||
scope: 'port',
|
||||
defaultValue: 'gpt-4o-mini',
|
||||
},
|
||||
|
||||
// ─── Email — From / Reply-To ──────────────────────────────────────────────
|
||||
{
|
||||
key: 'email_from_name',
|
||||
section: 'email.from',
|
||||
label: 'From name',
|
||||
description: 'Display name shown in the From: header on outgoing email.',
|
||||
type: 'string',
|
||||
scope: 'port',
|
||||
placeholder: 'Port Nimara',
|
||||
},
|
||||
{
|
||||
key: 'email_from_address',
|
||||
section: 'email.from',
|
||||
label: 'From address',
|
||||
description: 'Sender email address. Falls back to SMTP_FROM env when blank.',
|
||||
type: 'email',
|
||||
scope: 'port',
|
||||
envFallback: 'SMTP_FROM',
|
||||
placeholder: 'noreply@example.com',
|
||||
},
|
||||
{
|
||||
key: 'email_reply_to',
|
||||
section: 'email.from',
|
||||
label: 'Reply-to address',
|
||||
description: 'Optional Reply-To: header for replies (e.g. sales@example.com).',
|
||||
type: 'email',
|
||||
scope: 'port',
|
||||
placeholder: 'sales@example.com',
|
||||
},
|
||||
|
||||
// ─── Email — SMTP overrides ───────────────────────────────────────────────
|
||||
{
|
||||
key: 'smtp_host_override',
|
||||
section: 'email.smtp',
|
||||
label: 'SMTP host override',
|
||||
description: 'Falls back to SMTP_HOST env when blank.',
|
||||
type: 'string',
|
||||
scope: 'port',
|
||||
envFallback: 'SMTP_HOST',
|
||||
placeholder: 'mail.example.com',
|
||||
},
|
||||
{
|
||||
key: 'smtp_port_override',
|
||||
section: 'email.smtp',
|
||||
label: 'SMTP port override',
|
||||
description: 'Falls back to SMTP_PORT env when blank.',
|
||||
type: 'number',
|
||||
scope: 'port',
|
||||
envFallback: 'SMTP_PORT',
|
||||
placeholder: '587',
|
||||
},
|
||||
{
|
||||
key: 'smtp_user_override',
|
||||
section: 'email.smtp',
|
||||
label: 'SMTP user override',
|
||||
description: 'Falls back to SMTP_USER env when blank.',
|
||||
type: 'string',
|
||||
scope: 'port',
|
||||
envFallback: 'SMTP_USER',
|
||||
},
|
||||
{
|
||||
key: 'smtp_pass_override',
|
||||
section: 'email.smtp',
|
||||
label: 'SMTP password override',
|
||||
description: 'AES-encrypted at rest. Falls back to SMTP_PASS env when blank.',
|
||||
type: 'password',
|
||||
scope: 'port',
|
||||
encrypted: true,
|
||||
sensitive: true,
|
||||
envFallback: 'SMTP_PASS',
|
||||
},
|
||||
|
||||
// ─── Storage — S3 / MinIO ─────────────────────────────────────────────────
|
||||
{
|
||||
key: 'storage_s3_endpoint',
|
||||
section: 'storage.s3',
|
||||
label: 'S3 endpoint URL',
|
||||
description:
|
||||
'Full URL including scheme and port (e.g. https://s3.amazonaws.com or http://localhost:9000 for MinIO).',
|
||||
type: 'url',
|
||||
scope: 'global',
|
||||
envFallback: 'MINIO_ENDPOINT',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_region',
|
||||
section: 'storage.s3',
|
||||
label: 'S3 region',
|
||||
description: 'AWS region or "auto" for many S3-compatible providers.',
|
||||
type: 'string',
|
||||
scope: 'global',
|
||||
defaultValue: 'us-east-1',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_bucket',
|
||||
section: 'storage.s3',
|
||||
label: 'S3 bucket name',
|
||||
description: 'The bucket to read/write file content.',
|
||||
type: 'string',
|
||||
scope: 'global',
|
||||
envFallback: 'MINIO_BUCKET',
|
||||
placeholder: 'crm-files',
|
||||
},
|
||||
{
|
||||
// Stored under the new `_encrypted` suffix to mirror the existing
|
||||
// `storage_s3_secret_key_encrypted` convention. The migration script
|
||||
// moves the legacy plaintext row at `storage_s3_access_key` into this
|
||||
// key (fixes audit finding S-23).
|
||||
key: 'storage_s3_access_key_encrypted',
|
||||
section: 'storage.s3',
|
||||
label: 'S3 access key',
|
||||
description:
|
||||
'IAM access key id. AES-encrypted at rest (was previously stored plaintext — fixed in this migration).',
|
||||
type: 'password',
|
||||
scope: 'global',
|
||||
encrypted: true,
|
||||
sensitive: true,
|
||||
envFallback: 'MINIO_ACCESS_KEY',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_secret_key_encrypted',
|
||||
section: 'storage.s3',
|
||||
label: 'S3 secret key',
|
||||
description: 'IAM secret access key. AES-encrypted at rest.',
|
||||
type: 'password',
|
||||
scope: 'global',
|
||||
encrypted: true,
|
||||
sensitive: true,
|
||||
envFallback: 'MINIO_SECRET_KEY',
|
||||
},
|
||||
{
|
||||
key: 'storage_s3_force_path_style',
|
||||
section: 'storage.s3',
|
||||
label: 'Force path-style URLs',
|
||||
description:
|
||||
'On for MinIO and most self-hosted S3-compatible servers. Off for AWS S3 (which uses virtual-hosted-style by default).',
|
||||
type: 'boolean',
|
||||
scope: 'global',
|
||||
defaultValue: false,
|
||||
},
|
||||
|
||||
// ─── Storage — Filesystem (single-node only) ──────────────────────────────
|
||||
{
|
||||
key: 'storage_filesystem_root',
|
||||
section: 'storage.filesystem',
|
||||
label: 'Filesystem root path',
|
||||
description:
|
||||
'Absolute directory where files land when the active backend is filesystem. Single-node deployments only — multi-node MUST use S3.',
|
||||
type: 'string',
|
||||
scope: 'global',
|
||||
placeholder: '/var/lib/pn-crm/files',
|
||||
},
|
||||
|
||||
// ─── App URLs ─────────────────────────────────────────────────────────────
|
||||
{
|
||||
key: 'app_url',
|
||||
section: 'app.urls',
|
||||
label: 'App URL (this CRM)',
|
||||
description:
|
||||
'Public URL of this CRM instance. Used in outbound emails and webhook URL construction.',
|
||||
type: 'url',
|
||||
scope: 'global',
|
||||
envFallback: 'APP_URL',
|
||||
placeholder: 'https://crm.example.com',
|
||||
},
|
||||
{
|
||||
key: 'public_site_url',
|
||||
section: 'app.urls',
|
||||
label: 'Marketing site URL',
|
||||
description: 'The public marketing website URL. Used by some templates and CTAs.',
|
||||
type: 'url',
|
||||
scope: 'global',
|
||||
envFallback: 'PUBLIC_SITE_URL',
|
||||
placeholder: 'https://example.com',
|
||||
},
|
||||
];
|
||||
|
||||
/** Quick lookup index keyed by setting key. */
|
||||
const REGISTRY_INDEX = new Map<string, SettingEntry>(REGISTRY.map((e) => [e.key, e]));
|
||||
|
||||
export function registryFor(key: string): SettingEntry | undefined {
|
||||
return REGISTRY_INDEX.get(key);
|
||||
}
|
||||
|
||||
export function entriesForSection(section: string): SettingEntry[] {
|
||||
return REGISTRY.filter((e) => e.section === section);
|
||||
}
|
||||
|
||||
export function entriesForSections(sections: string[]): SettingEntry[] {
|
||||
const set = new Set(sections);
|
||||
return REGISTRY.filter((e) => set.has(e.section));
|
||||
}
|
||||
362
src/lib/settings/resolver.ts
Normal file
362
src/lib/settings/resolver.ts
Normal file
@@ -0,0 +1,362 @@
|
||||
import { and, eq, isNull } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { createAuditLog, type AuditMeta } from '@/lib/audit';
|
||||
import { db } from '@/lib/db';
|
||||
import { systemSettings } from '@/lib/db/schema';
|
||||
import { NotFoundError, ValidationError } from '@/lib/errors';
|
||||
import { decrypt, encrypt } from '@/lib/utils/encryption';
|
||||
|
||||
import { registryFor } from './registry';
|
||||
import type { ResolvedSetting, SettingEntry, SettingSource } from './types';
|
||||
|
||||
/**
|
||||
* Stored shape for encrypted JSONB values. The encrypt() helper returns a
|
||||
* JSON string of this shape — we wrap it in the JSONB column verbatim.
|
||||
*/
|
||||
interface EncryptedEnvelope {
|
||||
iv: string;
|
||||
tag: string;
|
||||
data: string;
|
||||
}
|
||||
|
||||
function isEncryptedEnvelope(value: unknown): value is EncryptedEnvelope {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
typeof (value as { iv?: unknown }).iv === 'string' &&
|
||||
typeof (value as { tag?: unknown }).tag === 'string' &&
|
||||
typeof (value as { data?: unknown }).data === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validator inferred from the entry type when no explicit `validator` is set.
|
||||
* Keeps the registry concise — only override when standard rules don't fit.
|
||||
*/
|
||||
function defaultValidator(entry: SettingEntry): z.ZodTypeAny {
|
||||
if (entry.validator) return entry.validator;
|
||||
switch (entry.type) {
|
||||
case 'string':
|
||||
case 'password':
|
||||
case 'textarea':
|
||||
case 'user-select':
|
||||
return z.string();
|
||||
case 'url':
|
||||
return z.string().url();
|
||||
case 'email':
|
||||
return z.string().email();
|
||||
case 'number':
|
||||
return z.coerce.number();
|
||||
case 'boolean':
|
||||
return z.coerce.boolean();
|
||||
case 'select':
|
||||
if (entry.options) {
|
||||
return z.enum(entry.options.map((o) => o.value) as [string, ...string[]]);
|
||||
}
|
||||
return z.string();
|
||||
default:
|
||||
return z.unknown();
|
||||
}
|
||||
}
|
||||
|
||||
function coerceForType(entry: SettingEntry, raw: unknown): unknown {
|
||||
if (raw == null) return null;
|
||||
if (entry.transform) return entry.transform(raw);
|
||||
if (entry.type === 'number') {
|
||||
const n = typeof raw === 'number' ? raw : Number(raw);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
if (entry.type === 'boolean') {
|
||||
if (typeof raw === 'boolean') return raw;
|
||||
if (raw === 'true' || raw === '1') return true;
|
||||
if (raw === 'false' || raw === '0') return false;
|
||||
return Boolean(raw);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function readEnvValue(entry: SettingEntry): unknown | null {
|
||||
if (!entry.envFallback) return null;
|
||||
const v = process.env[entry.envFallback];
|
||||
if (v == null || v === '') return null;
|
||||
return coerceForType(entry, v);
|
||||
}
|
||||
|
||||
function unwrapStoredValue(entry: SettingEntry, stored: unknown): unknown {
|
||||
if (stored == null) return null;
|
||||
if (entry.encrypted && isEncryptedEnvelope(stored)) {
|
||||
return decrypt(JSON.stringify(stored));
|
||||
}
|
||||
// Settings written via the legacy upsertSetting helper wrap the value in
|
||||
// `{ value: ... }`. Unwrap that shape transparently for backward compat.
|
||||
if (
|
||||
typeof stored === 'object' &&
|
||||
stored !== null &&
|
||||
'value' in stored &&
|
||||
Object.keys(stored as object).length === 1
|
||||
) {
|
||||
return (stored as { value: unknown }).value;
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
interface ResolvedRaw {
|
||||
source: SettingSource;
|
||||
rawValue: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lower-level lookup that returns both the resolved value AND the source it
|
||||
* came from (port row, global row, env, or registry default). The admin API
|
||||
* uses this directly to drive the "Using env fallback" badge; service code
|
||||
* usually calls `getSetting()` which discards the source.
|
||||
*/
|
||||
export async function resolveSettingWithSource(
|
||||
key: string,
|
||||
portId: string | null,
|
||||
): Promise<ResolvedRaw> {
|
||||
const entry = registryFor(key);
|
||||
if (!entry) throw new Error(`Unknown setting key: ${key}`);
|
||||
|
||||
// 1. Port-specific row (only meaningful for port-scoped entries).
|
||||
if (portId && entry.scope === 'port') {
|
||||
const row = await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, portId)),
|
||||
});
|
||||
if (row?.value != null) {
|
||||
return { source: 'port', rawValue: unwrapStoredValue(entry, row.value) };
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Global row (port_id IS NULL).
|
||||
const globalRow = await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), isNull(systemSettings.portId)),
|
||||
});
|
||||
if (globalRow?.value != null) {
|
||||
return { source: 'global', rawValue: unwrapStoredValue(entry, globalRow.value) };
|
||||
}
|
||||
|
||||
// 3. Env fallback.
|
||||
const envValue = readEnvValue(entry);
|
||||
if (envValue != null) {
|
||||
return { source: 'env', rawValue: envValue };
|
||||
}
|
||||
|
||||
// 4. Registry default.
|
||||
return { source: 'default', rawValue: entry.defaultValue ?? null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a setting value through the precedence chain: port → global → env
|
||||
* → registry default. Encrypted values are decrypted on the way out.
|
||||
*
|
||||
* Use this from service code that needs the concrete cleartext value
|
||||
* (e.g. building an outbound Documenso request).
|
||||
*/
|
||||
export async function getSetting<T = unknown>(
|
||||
key: string,
|
||||
portId: string | null,
|
||||
): Promise<T | null> {
|
||||
const { rawValue } = await resolveSettingWithSource(key, portId);
|
||||
return rawValue as T | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch resolver — efficient for the admin form which needs every field in a
|
||||
* section. Returns a map keyed by setting key.
|
||||
*/
|
||||
export async function resolveSettings(
|
||||
keys: string[],
|
||||
portId: string | null,
|
||||
): Promise<Map<string, ResolvedRaw>> {
|
||||
const out = new Map<string, ResolvedRaw>();
|
||||
await Promise.all(
|
||||
keys.map(async (k) => {
|
||||
out.set(k, await resolveSettingWithSource(k, portId));
|
||||
}),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape returned to the admin API. Sensitive fields surface `isSet` only.
|
||||
*/
|
||||
export async function resolveForAdminAPI(
|
||||
keys: string[],
|
||||
portId: string | null,
|
||||
): Promise<Map<string, ResolvedSetting>> {
|
||||
const resolved = await resolveSettings(keys, portId);
|
||||
const out = new Map<string, ResolvedSetting>();
|
||||
for (const key of keys) {
|
||||
const entry = registryFor(key);
|
||||
if (!entry) continue;
|
||||
const r = resolved.get(key);
|
||||
if (!r) continue;
|
||||
const isSet = r.source !== 'default' && r.rawValue != null && r.rawValue !== '';
|
||||
const surfaceSensitive = entry.sensitive || entry.encrypted;
|
||||
out.set(key, {
|
||||
key,
|
||||
source: r.source,
|
||||
isSet,
|
||||
value: surfaceSensitive ? undefined : (r.rawValue ?? undefined),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and persist a setting. Encrypts if registered as encrypted. Always
|
||||
* writes to the row scope appropriate to the entry: port-scoped entries with
|
||||
* a non-null portId write the port row; global-scoped entries (or when called
|
||||
* with portId=null) write the global row.
|
||||
*/
|
||||
export async function writeSetting(
|
||||
key: string,
|
||||
rawValue: unknown,
|
||||
portId: string | null,
|
||||
meta: AuditMeta,
|
||||
): Promise<void> {
|
||||
const entry = registryFor(key);
|
||||
if (!entry) throw new ValidationError(`Unknown setting: ${key}`);
|
||||
|
||||
// Empty value on a settable field == delete the row (revert to fallback).
|
||||
// Sensitive/encrypted: empty input means "don't change" rather than
|
||||
// "revert" — UI shows ••• placeholder so an unchanged save shouldn't
|
||||
// wipe the stored ciphertext. The dedicated DELETE endpoint exists for
|
||||
// explicit reverts.
|
||||
if (rawValue === '' || rawValue == null) {
|
||||
if (entry.encrypted || entry.sensitive) {
|
||||
// No-op: leaving the existing row untouched.
|
||||
return;
|
||||
}
|
||||
await deleteSetting(key, portId, meta);
|
||||
return;
|
||||
}
|
||||
|
||||
const validator = defaultValidator(entry);
|
||||
const parsed = validator.safeParse(rawValue);
|
||||
if (!parsed.success) {
|
||||
throw new ValidationError(
|
||||
`Invalid value for "${key}": ${parsed.error.issues
|
||||
.map((i) => `${i.path.join('.')}: ${i.message}`)
|
||||
.join('; ')}`,
|
||||
);
|
||||
}
|
||||
const value = parsed.data;
|
||||
|
||||
const writePortId = entry.scope === 'global' ? null : portId;
|
||||
const storedValue = entry.encrypted
|
||||
? (JSON.parse(encrypt(String(value))) as EncryptedEnvelope)
|
||||
: value;
|
||||
|
||||
// Read existing for audit diff.
|
||||
const existing = writePortId
|
||||
? await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, writePortId)),
|
||||
})
|
||||
: await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), isNull(systemSettings.portId)),
|
||||
});
|
||||
|
||||
await db
|
||||
.insert(systemSettings)
|
||||
.values({
|
||||
key,
|
||||
value: storedValue as Record<string, unknown>,
|
||||
portId: writePortId,
|
||||
updatedBy: meta.userId,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [systemSettings.key, systemSettings.portId],
|
||||
set: {
|
||||
value: storedValue as Record<string, unknown>,
|
||||
updatedBy: meta.userId,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
// Audit-log with redaction for sensitive / encrypted fields — fixes AU-02
|
||||
// (encrypted ciphertext stored in audit_logs.new_value).
|
||||
const isSecret = entry.encrypted || entry.sensitive;
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
portId: meta.portId,
|
||||
action: existing ? 'update' : 'create',
|
||||
entityType: 'setting',
|
||||
entityId: key,
|
||||
oldValue: existing ? { value: isSecret ? '[redacted]' : existing.value } : undefined,
|
||||
newValue: { value: isSecret ? '[redacted]' : value },
|
||||
metadata: { settingKey: key, scope: entry.scope },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a setting row, reverting the resolver to global → env → default.
|
||||
* No-op (with NotFoundError) if no row exists at the target scope.
|
||||
*/
|
||||
export async function deleteSetting(
|
||||
key: string,
|
||||
portId: string | null,
|
||||
meta: AuditMeta,
|
||||
): Promise<void> {
|
||||
const entry = registryFor(key);
|
||||
if (!entry) throw new ValidationError(`Unknown setting: ${key}`);
|
||||
|
||||
const writePortId = entry.scope === 'global' ? null : portId;
|
||||
|
||||
const existing = writePortId
|
||||
? await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), eq(systemSettings.portId, writePortId)),
|
||||
})
|
||||
: await db.query.systemSettings.findFirst({
|
||||
where: and(eq(systemSettings.key, key), isNull(systemSettings.portId)),
|
||||
});
|
||||
|
||||
if (!existing) throw new NotFoundError('Setting');
|
||||
|
||||
await db
|
||||
.delete(systemSettings)
|
||||
.where(
|
||||
writePortId
|
||||
? and(eq(systemSettings.key, key), eq(systemSettings.portId, writePortId))
|
||||
: and(eq(systemSettings.key, key), isNull(systemSettings.portId)),
|
||||
);
|
||||
|
||||
const isSecret = entry.encrypted || entry.sensitive;
|
||||
void createAuditLog({
|
||||
userId: meta.userId,
|
||||
portId: meta.portId,
|
||||
action: 'delete',
|
||||
entityType: 'setting',
|
||||
entityId: key,
|
||||
oldValue: { value: isSecret ? '[redacted]' : existing.value },
|
||||
metadata: { settingKey: key, scope: entry.scope },
|
||||
ipAddress: meta.ipAddress,
|
||||
userAgent: meta.userAgent,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* One-click migration: read the env var named in `entry.envFallback`, write
|
||||
* it as the current scope's row. Used by the admin UI "Copy from env" button.
|
||||
*/
|
||||
export async function copyFromEnv(
|
||||
key: string,
|
||||
portId: string | null,
|
||||
meta: AuditMeta,
|
||||
): Promise<{ copied: boolean; envValue?: string }> {
|
||||
const entry = registryFor(key);
|
||||
if (!entry) throw new ValidationError(`Unknown setting: ${key}`);
|
||||
if (!entry.envFallback) {
|
||||
throw new ValidationError(`Setting "${key}" has no env fallback configured`);
|
||||
}
|
||||
const envValue = process.env[entry.envFallback];
|
||||
if (envValue == null || envValue === '') {
|
||||
return { copied: false };
|
||||
}
|
||||
await writeSetting(key, envValue, portId, meta);
|
||||
return { copied: true, envValue: entry.encrypted || entry.sensitive ? undefined : envValue };
|
||||
}
|
||||
77
src/lib/settings/types.ts
Normal file
77
src/lib/settings/types.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export type SettingType =
|
||||
| 'string'
|
||||
| 'password'
|
||||
| 'number'
|
||||
| 'boolean'
|
||||
| 'select'
|
||||
| 'url'
|
||||
| 'email'
|
||||
| 'textarea'
|
||||
/**
|
||||
* Renders a dropdown of the current port's CRM users (email + name).
|
||||
* Stored as the user's UUID. Used for fields that bind a CRM user to a
|
||||
* Documenso recipient slot for in-CRM notification routing.
|
||||
*/
|
||||
| 'user-select';
|
||||
|
||||
export type SettingScope = 'port' | 'global';
|
||||
|
||||
export type SettingSource = 'port' | 'global' | 'env' | 'default';
|
||||
|
||||
export interface SettingOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface SettingEntry {
|
||||
/** Stable key written to system_settings.key. Use snake_case. */
|
||||
key: string;
|
||||
/** Grouping name used by the admin form generator (e.g. "documenso.api"). */
|
||||
section: string;
|
||||
/** UI label. */
|
||||
label: string;
|
||||
/** UI description (plain text — can include backticks for inline code). */
|
||||
description: string;
|
||||
/** Drives both validation and form input rendering. */
|
||||
type: SettingType;
|
||||
/** select-only — list of option choices. */
|
||||
options?: SettingOption[];
|
||||
/** Optional Zod schema. When omitted, a type-appropriate default is used. */
|
||||
validator?: z.ZodTypeAny;
|
||||
/** Default applied when port + global + env all absent. */
|
||||
defaultValue?: string | number | boolean | null;
|
||||
/** Encrypt at rest with AES-256-GCM. Implies sensitive. */
|
||||
encrypted?: boolean;
|
||||
/** Per-port (with global + env fallback) or global-only (super-admin). */
|
||||
scope: SettingScope;
|
||||
/** Env var name consulted when port + global blank. */
|
||||
envFallback?: string;
|
||||
/** Value transformer applied after resolution (e.g. coerce string→number). */
|
||||
transform?: (raw: unknown) => unknown;
|
||||
/**
|
||||
* Sensitive: never surface cleartext via admin API. Encrypted fields are
|
||||
* sensitive by default; non-encrypted fields may still be marked sensitive
|
||||
* (e.g. an externally-shared secret) — the API emits `<key>IsSet: boolean`.
|
||||
*/
|
||||
sensitive?: boolean;
|
||||
/** Placeholder text shown in the input. */
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolved-value response shape returned to the admin UI.
|
||||
*
|
||||
* - `source` tells the UI whether the value came from the port row, the
|
||||
* global row, the env fallback, or the registry default — which drives
|
||||
* the "Using env fallback" badge.
|
||||
* - `value` carries the resolved cleartext for non-sensitive fields. For
|
||||
* sensitive / encrypted fields it is omitted and only `isSet` is exposed.
|
||||
*/
|
||||
export interface ResolvedSetting<T = unknown> {
|
||||
key: string;
|
||||
source: SettingSource;
|
||||
isSet: boolean;
|
||||
value?: T;
|
||||
}
|
||||
Reference in New Issue
Block a user