.github/9
ISSUE_TEMPLATE/3bug_report.md config.yml feature_request.md
workflows/3ci.yml clean-clone.yml release.yml
CODEOWNERS dependabot.yml pull_request_template.md
apps/630
api/250
src/243
common/30
__tests__/3authorize.test.ts bigint-serialization.interceptor.test.ts files-limits.test.ts
filters/1all-exceptions.filter.ts
guards/3auth.guard.ts internal-service.guard.ts rate-limit.guard.ts
interceptors/2actor-context.interceptor.ts bigint-serialization.interceptor.ts
middleware/2idempotency.test.ts idempotency.ts
pipes/1zod-validation.pipe.ts
actor-context.ts audit.service.ts cache.test.ts cache.ts cookies.ts core.module.ts deprecation.ts email.service.ts errors.ts event-bus.ts log-scrubber.test.ts log-scrubber.ts logger.ts permission-cache-bridge.ts prisma.service.ts redis.service.ts trace-metadata.ts types.ts
config/1env.ts
lib/11
__tests__/5crypto.test.ts filter-builder.test.ts jwt.test.ts pagination.test.ts positions.test.ts
authorize.ts crypto.ts filter-builder.ts jwt.ts pagination.ts positions.ts
modules/197
ai/28
__tests__/4ai-writing.test.ts database-ai.test.ts generate-executor.test.ts prompts.test.ts
generator/4executor.ts generate.controller.ts generate.dto.ts generate.service.ts
ai-chat.service.ts ai-rate-limit.ts ai-writing.controller.ts ai-writing.dto.ts ai-writing.service.ts ai.controller.ts ai.module.ts ai.service.ts budget-guard.service.ts database-ai.controller.ts database-ai.dto.ts database-ai.service.ts db-prompts.ts dto.ts gateway-provider.ts ledger.service.ts prompts.ts rag.controller.ts rag.dto.ts rag.service.ts
api-keys/3api-keys.controller.ts api-keys.module.ts api-keys.service.ts
audit/2audit-log.controller.ts audit.module.ts
auth/4auth.controller.ts auth.module.ts auth.service.ts dto.ts
automations/5automations.controller.ts automations.module.ts automations.service.ts dto.ts webhook-incoming.controller.ts
blocks/5
__tests__/1batch-version-cas.test.ts
block.service.ts blocks.controller.ts blocks.module.ts dto.ts
comments/4comments.controller.ts comments.module.ts comments.service.ts dto.ts
databases/9
__tests__/3normalize-select-options.test.ts option-id-canonicalization.test.ts record-open-query-shape.test.ts
database.service.ts databases.controller.ts databases.module.ts dto.ts property-cache-schema.ts query.service.ts
docs/2docs.controller.ts docs.module.ts
files/10
__tests__/1quota.test.ts
dto.ts files.controller.ts files.module.ts files.service.ts quota.ts record.ts s3.ts uploads.controller.ts uploads.service.ts
forms/18debug.controller.ts form.dto.ts forms.controller.ts forms.module.ts forms.service.ts markdown.test.ts markdown.ts optional-auth.guard.ts public-forms.controller.ts public-forms.service.ts question.dto.ts questions.service.ts rate-limit.ts recaptcha.ts slug.ts submissions.controller.ts submissions.service.ts submit-schema.ts
health/3health.controller.ts health.module.ts health.service.ts
integrations/3integrations.controller.ts integrations.module.ts integrations.service.ts
internal/12
__tests__/2flush-query-shape.test.ts internal.endpoints.test.ts
ai-test-seam.controller.ts ai-test-seam.dto.ts ai-test-seam.service.ts internal.controller.ts internal.dto.ts internal.module.ts internal.service.ts test-seam.controller.ts test-seam.dto.ts test-seam.service.ts
notifications/3notifications.controller.ts notifications.module.ts notifications.service.ts
oauth/6
__tests__/1oauth.scopes.test.ts
oauth.controller.ts oauth.module.ts oauth.service.ts scopes.ts token-keys.ts
org/15audit.service.ts embed-preview.controller.ts guards.ts members.service.ts org-admin.controller.ts org-policy.service.ts org.module.ts overview.service.ts policy-effective.controller.ts policy.schema.ts policy.test.ts retention.service.ts totp.test.ts totp.ts two-factor.service.ts
orgs/5dto.ts orgs.controller.ts orgs.module.ts orgs.service.ts util.ts
pages/4dto.ts page.service.ts pages.controller.ts pages.module.ts
scim/15
__tests__/3email-mapping.test.ts etag.test.ts filters.test.ts
etag.ts filters.ts groups.service.ts schemas.ts scim-admin.controller.ts scim-admin.service.ts scim-auth.guard.ts scim-auth.service.ts scim-errors.ts scim.controller.ts scim.module.ts users.service.ts
search/4
__tests__/1search.service.test.ts
search.controller.ts search.module.ts search.service.ts
sessions/3sessions.controller.ts sessions.module.ts sessions.service.ts
share/3share.controller.ts share.module.ts share.service.ts
sso/16
__tests__/4enforcement.test.ts oidc.verify.test.ts provisioning.test.ts saml.validate.test.ts
enforcement.ts oidc.controller.ts oidc.service.ts oidc.ts provisioning.service.ts saml.controller.ts saml.ts schemas.ts sso-admin.controller.ts sso-admin.service.ts sso-secrets.ts sso.module.ts
teams/4dto.ts teams.controller.ts teams.module.ts teams.service.ts
users/4dto.ts users.controller.ts users.module.ts users.service.ts
webhooks/3webhooks.controller.ts webhooks.module.ts webhooks.service.ts
workspaces/4dto.ts workspaces.controller.ts workspaces.module.ts workspaces.service.ts
types/1xmldom.d.ts
app.module.ts constants.ts main.ts
_probe_rawbody.cjs .env.example Dockerfile package.json README.md tsconfig.json vitest.config.ts
realtime/33
src/17auth.ts comments.ts config.ts event-source.ts http-store.ts index.ts metrics.ts notifications.ts page-updated-source.ts presence.ts prisma-store.ts protocol.ts rate-limit.ts room-key.ts rooms.ts server.ts update-log.ts
test/11auth.test.ts config.test.ts event-source.test.ts http-store.test.ts metrics-merge.test.ts page-updated-source.test.ts presence.test.ts protocol.test.ts rate-limit.test.ts rooms.test.ts task-0094-builders.test.ts
.env.example Dockerfile package.json README.md tsconfig.json
web/255
src/244
app/45
__tests__/1theme-tokens.test.ts
(app)/26
w/25
[workspace]/25
ask/1page.tsx
databases/1
[id]/1page.tsx
favorites/1page.tsx
files/1page.tsx
notifications/1page.tsx
page/4
[id]/4
[block]/1page.tsx
share/1page.tsx
layout.tsx page.tsx
search/1page.tsx
settings/10
appearance/1page.tsx
automations/3
[id]/1page.tsx
new/1page.tsx
page.tsx
billing/1page.tsx
developers/1page.tsx
members/1page.tsx
permissions/1page.tsx
teams/1page.tsx
page.tsx
shared/1page.tsx
templates/1page.tsx
trash/1page.tsx
layout.tsx page.tsx
layout.tsx
(auth)/4
login/1page.tsx
register/1page.tsx
reset-password/1page.tsx
layout.tsx
api/2
metrics/1route.ts
v1/1
health/1route.ts
f/1
[slug]/1page.tsx
health/1
ready/1route.ts
org/2
[orgId]/2
admin/2
integrations/1page.tsx
page.tsx
share/1
[id]/1page.tsx
error.tsx global-error.tsx globals.css layout.tsx not-found.tsx page.tsx providers.tsx
components/118
admin/10
org-admin/8ApiKeysTab.tsx AuditTab.tsx MembersTab.tsx OverviewTab.tsx PoliciesTab.tsx RetentionTab.tsx WebhooksTab.tsx WorkspacePicker.tsx
ScimCard.tsx SsoTabs.tsx
ai/6ai-panel.tsx ask-ai-submenu.tsx db-ai-dialog.tsx generate-page-dialog.tsx writing-actions-menu.tsx writing-diff.tsx
automations/5action-editor.tsx condition-editor.tsx lib.ts run-history.tsx trigger-editor.tsx
collaboration/6CursorLayer.tsx OfflineBanner.tsx PresenceBar.tsx README.md ReviewFailedDialog.tsx StatusChip.tsx
comments/3comment-panel.tsx comment-thread.tsx mention-input.tsx
database/27
__tests__/2cell-editor.test.tsx cell-renderer.test.tsx
AiExtractDialog.tsx AiFormulaDialog.tsx AiGenerateDialog.tsx board-view.tsx buttons-panel.tsx calendar-view.tsx cell-editor.tsx cell-renderer.tsx chart-view.tsx database-page-view.tsx database-toolbar.tsx database-view-renderer.tsx db-embedded.tsx filter-builder.tsx form-builder-view.tsx formula-editor.tsx gallery-view.tsx group-builder.tsx list-view.tsx property-editor.tsx record-header.tsx record-panel.tsx sort-builder.tsx table-view.tsx timeline-view.tsx
dialogs/7
__tests__/1move-to-dialog.test.tsx
create-dialog.tsx dialog.tsx file-permissions-dialog.tsx invite-dialog.tsx move-to-dialog.tsx share-dialog.tsx
editor/19
__tests__/3code-block-text.test.ts code-block.test.tsx expandable.test.tsx
block-card.tsx block-renderer.tsx block-save-queue.ts block-toolbar.tsx context-menu.tsx expandable.tsx history-popover.tsx inline-editor.tsx insert-dialog.tsx page-canvas.tsx page-spinner.tsx page-view.tsx selection-toolbar.tsx slash-menu.tsx template-dialog.tsx type-menu.tsx
files/4FileBlock.tsx FileBrowser.tsx FilePicker.tsx PreviewModal.tsx
form/4form-field.tsx form-renderer.tsx form-responses-view.tsx form-view.tsx
layout/8
__tests__/1page-tree-icon.test.tsx
command-palette.tsx factory-logo.tsx page-tree-node.tsx sidebar.tsx theme-provider.tsx topbar.tsx workspace-shell.tsx
mentions/3
__tests__/1mention-model.test.ts
mention-model.ts MentionPopup.tsx
search/3ask-ai-search.tsx results-list.tsx search-dialog.tsx
settings/10
api-keys/4ApiKeyCreateDialog.tsx ApiKeyRevealDialog.tsx ApiKeyTable.tsx ScopesBadge.tsx
webhooks/5CurlExamples.tsx DeliveryInspector.tsx EventExplorer.tsx OverviewTab.tsx WebhooksTab.tsx
settings-shell.tsx
ui/3confirm-dialog.tsx form.tsx toaster.tsx
hooks/21
__tests__/4realtime-frame-handler.test.ts use-blocks.test.ts use-database-options.test.ts use-workspace.test.tsx
realtime-frame-handler.ts use-ai-stream.ts use-auth.ts use-blocks.ts use-database.ts use-db-ai-stream.ts use-forms.ts use-members.ts use-mention-sources.ts use-notifications.ts use-offline-status.ts use-pages.ts use-presence-announcer.ts use-presence-toasts.ts use-presence.ts use-realtime.ts use-workspace.ts
lib/50
__tests__/21ai-database.test.ts ai-generate.test.ts ai-sse.test.ts ai-writing.test.ts api-keys.test.ts api-members.test.ts auth-refresh.test.ts auth-store.test.ts batch-queue-drop.test.ts block-content.test.ts clipboard-import.test.ts code-highlight.test.ts offline-status.test.ts presence-announcer.test.ts presence-color.test.ts presence-cursor.test.ts presence-emitter.test.ts realtime-url.test.ts search.test.ts utils.test.ts writing-diff.test.ts
files/7
__tests__/2picker.test.ts upload.test.ts
api.ts picker.ts upload-store.ts upload.ts use-file-uploads.ts
ai-database.ts ai.ts api-keys.ts api.ts auth-store.ts batch-queue.ts block-content.ts clipboard-import.ts code-highlight.ts constants.ts offline-status.ts org-admin.ts presence-announcer.ts presence-color.ts presence-cursor.ts presence-editor-views.ts presence-emitter.ts query-client.ts realtime.ts search.ts types.ts utils.ts
stores/8
__tests__/1block-patch-store.test.ts
block-patch-store.ts comment-pill-store.ts database-store.ts editor-store.ts offlineQueue.ts presence-store.ts ui-store.ts
instrumentation.ts middleware.ts
.env.example Dockerfile next-env.d.ts next.config.mjs package.json postcss.config.mjs README.md tailwind.config.ts tsconfig.json tsconfig.tsbuildinfo vitest.config.ts
worker/92
src/87
__tests__/13ai-embedding.test.ts ai-request.test.ts ai-usage-budget.test.ts audit-export.test.ts email-decision.test.ts encrypt.test.ts health-search-index-lag.test.ts mime.test.ts retention.test.ts s3-sign.test.ts search-index.test.ts smtp.test.ts webhook-sign.test.ts
health/1server.ts
lib/12
__tests__/1clamav.test.ts
clamav.ts encrypt.ts job-otel.ts mime.ts notify.ts prisma.ts redis-stream.ts redis.ts s3.ts sharp.ts smtp.ts
processors/56
automations/28
__tests__/3condition-evaluator.spec.ts executors.spec.ts run-pipeline.spec.ts
executors/17assign-user.ts call-integration.ts change-status.ts classify.ts create-notification.ts create-page.ts email-cap.ts helpers.ts integration-registry.ts permission.ts record-write.ts registry.ts run-ai-action.ts send-email.ts send-webhook.ts types.ts update-record.ts
condition-evaluator.ts dead-letter.ts log.ts matcher.ts pipeline.ts run-state.ts schedule.ts watchdog.ts
files/15
__tests__/4errors.test.ts scan-gate.test.ts status.test.ts temp.test.ts
steps/4finalize.ts metadata.ts scan.ts thumbnails.ts
cleanup.ts errors.ts generateThumbs.ts processor.ts status.ts temp.ts types.ts
search-index/4builders.ts grants.ts index.ts processor.ts
ai-embedding.ts ai.processor.ts audit-export.ts automations.processor.ts email-decision.processor.ts email.processor.ts maintenance.processor.ts retention.ts webhooks.processor.ts
config.ts events.ts index.ts logger.ts queues.ts
.env.example Dockerfile package.json README.md tsconfig.json
docs/73
api/17ai.md authentication.md automations.md blocks.md comments.md databases.md files.md forms.md openapi.yaml org-admin.md pages.md scim.md search.md sso.md versioning.md webhooks.md workspaces.md
architecture/10ai-architecture.md automation.md backend-architecture.md database-architecture.md frontend-architecture.md realtime-architecture.md search-architecture.md security-architecture.md storage.md system-architecture.md
database/2database-architecture.md redis-keys.md
development/8admin-guide.md coding-standards.md deployment.md development-guide.md files-pipeline.md perf-report.md performance.md testing.md
product/4functional-requirements.md non-functional-requirements.md product-requirements.md ux-requirements.md
requirements/1requirements-matrix.md
security/5audit-report.md files.md forms.md license-allowlist.md security-architecture.md
tasks/16phase-00-foundation.md phase-01-authentication.md phase-02-workspace.md phase-03-pages.md phase-04-editor.md phase-05-databases.md phase-06-relations.md phase-07-collaboration.md phase-08-search.md phase-09-files.md phase-10-forms.md phase-11-automation.md phase-12-ai.md phase-13-api.md phase-14-enterprise.md phase-15-production.md
ui/9ai.md automations.md design-system.md developers.md files.md forms.md org-admin.md scim.md sso.md
support-matrix.md
infrastructure/71
caddy/1Caddyfile
docker/6
init/101-extensions.sql
opensearch/1init-indices.json
.env.docker docker-compose.yml opensearch-init.sh README.md
kubernetes/40
observability/20
alertmanager/1alertmanager.yaml
grafana/8
dashboards/6ai.json api-overview.json infra.json realtime.json search.json workers-queues.json
provisioning/2
dashboards/1dashboards.yaml
datasources/1datasource.yaml
prometheus/3alerts.yaml recording-rules.yaml scrape.yaml
scripts/1sync-sources.mjs
alertmanager.yaml grafana.yaml kustomization.yaml namespace.yaml node-exporter.yaml otel-collector.yaml prometheus.yaml
postgres/7configmap.yaml cronjob-backup.yaml cronjob-opensearch-snapshot.yaml pgbouncer.yaml replica.yaml statefulset.yaml walg-iam-policy.yaml
api.yaml configmap.yaml ingress.yaml kustomization.yaml namespace.yaml networkpolicy.yaml pdb.yaml README.md realtime.yaml redis.yaml secret.example.yaml web.yaml worker.yaml
nginx/2nginx.conf README.md
observability/14
alertmanager/1alertmanager.yaml
grafana/8
dashboards/6ai.json api-overview.json infra.json realtime.json search.json workers-queues.json
provisioning/2
dashboards/1dashboards.yaml
datasources/1datasource.yaml
prometheus/3alerts.yaml recording-rules.yaml scrape.yaml
scripts/1dashboard-completeness.mjs
README.md
terraform/8compute.tf data.tf main.tf network.tf outputs.tf README.md security.tf variables.tf
packages/289
ai/24
src/20
providers/7anthropic.ts google.ts http.ts index.ts openai-compatible.ts rag.test.ts writing.test.ts
schemas/2database.ts generate.ts
adapters.test.ts config.test.ts config.ts gateway.test.ts gateway.ts index.ts tools.test.ts tools.ts types.ts usage.test.ts usage.ts
package.json README.md tsconfig.json vitest.config.ts
auth/11
src/7index.ts passwords.test.ts passwords.ts sessions.test.ts sessions.ts tokens.test.ts tokens.ts
package.json README.md tsconfig.json vitest.config.ts
collaboration/17
src/13awareness.ts codec.test.ts codec.ts index.ts lww.test.ts lww.ts mapping.ts offline.ts outbox.test.ts outbox.ts provider.test.ts provider.ts types.ts
package.json README.md tsconfig.json vitest.config.ts
config/7
src/4eslint.base.js index.ts prettier.base.json tsconfig.base.json
package.json README.md tsconfig.json
database-client/5
src/2index.test.ts index.ts
package.json README.md tsconfig.json
database-engine/33
src/29
filter/2filter.test.ts index.ts
formula/8evaluator.ts formula.test.ts functions.ts index.ts lexer.ts parser.ts types.ts validate.ts
query/6group.ts index.ts paginate.ts pivot.ts query.test.ts sort.ts
relations/2index.ts relations.test.ts
rollups/2index.ts rollups.test.ts
values/5dates.ts index.ts registry.ts types.ts values.test.ts
views/3buttons.ts index.ts views.test.ts
index.ts
package.json README.md tsconfig.json vitest.config.ts
editor/25
src/21
marks/1highlight.ts
nodes/2equation.ts mention.ts
autosave.test.ts autosave.ts clipboard.test.ts clipboard.ts codec.test.ts codec.ts context-menu.test.ts context-menu.ts diff.test.ts diff.ts factory.ts history.test.ts history.ts index.ts positions.ts slash.test.ts slash.ts types.ts
package.json README.md tsconfig.json vitest.config.ts
observability/20
src/16
__tests__/8db-redis-metrics.test.ts metrics.test.ts otel.test.ts pino-otel.test.ts prometheus.test.ts resource.test.ts scrubber.test.ts traceparent.test.ts
index.ts metrics.ts otel.ts pino-otel.ts prometheus.ts resource.ts scrubber.ts traceparent.ts
package.json README.md tsconfig.json vitest.config.ts
permissions/11
src/7index.ts levels.test.ts levels.ts resolve.test.ts resolve.ts rules.test.ts rules.ts
package.json README.md tsconfig.json vitest.config.ts
search/22
src/18chunking.test.ts chunking.ts client.test.ts client.ts embeddings.test.ts embeddings.ts hybrid.test.ts hybrid.ts index.ts indexer.test.ts indexer.ts mapping.test.ts mapping.ts queries.test.ts queries.ts rrf.test.ts rrf.ts types.ts
package.json README.md tsconfig.json vitest.config.ts
shared/61
src/57
dto/17ai.dto.ts auth.dto.test.ts auth.dto.ts block.dto.ts browser-safety.test.ts comment.dto.ts database.dto.test.ts database.dto.ts file.dto.ts formula-ast.ts index.ts notification.dto.ts page.dto.ts search.dto.ts share.dto.ts webhook.dto.ts workspace.dto.ts
events/8audit-catalog.test.ts audit-catalog.ts audit-csv.test.ts audit-csv.ts audit-scope.test.ts audit-scope.ts catalog.test.ts catalog.ts
realtime/6comment-events.ts frames.test.ts frames.ts notification-policy.ts notification-prefs.ts task-0094.test.ts
automation.test.ts automation.ts constants.ts crypto.test.ts crypto.ts env.ts errors.ts events.test.ts events.ts forms.test.ts forms.ts index.ts markdown.test.ts markdown.ts mentions.test.ts mentions.ts net.test.ts net.ts positions.test.ts positions.ts presence.test.ts presence.ts security-headers.ts webhook-delivery.test.ts webhook-delivery.ts webhook-events.ts
package.json README.md tsconfig.json vitest.config.ts
storage/16
src/12client.test.ts client.ts index.ts keys.test.ts keys.ts mime.test.ts mime.ts presign.test.ts presign.ts thumbnails.test.ts thumbnails.ts types.ts
package.json README.md tsconfig.json vitest.config.ts
ui/37
src/33
components/19avatar.tsx badge.tsx button.tsx checkbox.tsx command.tsx context-menu.tsx dialog.tsx dropdown-menu.tsx empty-state.tsx index.ts popover.tsx separator.tsx skeleton.tsx slider.tsx spinner.tsx switch.tsx tabs.tsx toast.tsx tooltip.tsx
color.ts command-filter.test.ts command-filter.ts focus.test.ts focus.ts formatters.test.ts formatters.ts index.ts theme.test.ts theme.ts toast-store.test.ts toast-store.ts tokens.test.ts tokens.ts
package.json README.md tsconfig.json vitest.config.ts
prisma/16
migrations/13
20260927000000_init/1migration.sql
20260928000000_search_documents_content_hash/1migration.sql
20260929000000_workspace_usage_storage_bytes/1migration.sql
20260930000000_form_submitted_notification_type/1migration.sql
20261001000000_ai_phase12/1migration.sql
20261002000000_webhooks_secret_encrypted_dlq/1migration.sql
20261002111436_webhook_delivery_latency/1migration.sql
20261002120000_org_admin_2fa_retention_unique/1migration.sql
20261002215124_audit_export/1migration.sql
20261003210000_perf_indexes_hot_paths/1migration.sql
20261004004500_perf_indexes_hot_paths_2/1migration.sql
migration_lock.toml README.md
schema.prisma seed.ts verify.ts
scripts/7backup-health.ts docs-completeness.mjs generate-openapi.mjs minio-init.ts opensearch-reindex.ts storage-orphans.ts verify-clean-clone.sh
tests/169
e2e/63
.auth/1user.json
fixtures/7
files/6clip.mp4 clip.wav clip.webm hero-1400.png note.docx note.txt
realtime.ts
mocks/2oidc-issuer.ts saml-idp.ts
playwright-report/3
data/2a6557bae9c2714a658968d4eb8534195c08ebda8.png e3092d07d00a16063e46385c02a559a9054fa847.webm
index.html
reports/1files-security.json
specs/34ai-database.spec.ts ai-generate.spec.ts ai-rag.spec.ts ai-security.spec.ts ai-writing.spec.ts ai.spec.ts api-keys.spec.ts appearance-theme.spec.ts auth.spec.ts automation.spec.ts collab-two-tab.spec.ts comments.spec.ts databases.spec.ts default-workspace-alias.spec.ts developers.spec.ts editor.spec.ts files.spec.ts final-flow.spec.ts forms.spec.ts oauth.spec.ts org-admin.spec.ts pages.spec.ts performance.spec.ts presence-cursors.spec.ts qa-paste-toggle.spec.ts realtime.spec.ts scim.spec.ts search-index-lag.spec.ts search.spec.ts sharing.spec.ts sso.spec.ts task-0094-comments-notifications.spec.ts webhooks.spec.ts workspace.spec.ts
test-results-final-flow/3
final-flow-Release-v1-0-fi-6c06b-w-state-carries-sequential--chromium-desktop/2test-failed-1.png trace.zip
.last-run.json
utils/4api.ts dnd.ts search-lag.ts wait.ts
.gitignore fixtures.ts global-setup.ts package.json playwright.config.ts playwright.final-flow.config.ts README.md tsconfig.json
fixtures/1
files/1make-sparse.ts
integration/60
ai-capability/2ai-app.capability.test.ts gateway.capability.test.ts
drill/2seed-drill.mjs verify-restore.mjs
fixtures/5
files/5clip.mp4 clip.wav doc.pdf hero-1400.png note.txt
helpers/3api.ts containers.ts seed.ts
realtime/11control-channel.test.ts convergence.test.ts flush-rebase-http.test.ts handshake.test.ts heartbeat-limits.test.ts lifecycle.test.ts presence.test.ts rebase.test.ts resume.test.ts rt-helpers.ts task-0094-fanout.test.ts
ai-chat.integration.test.ts ai-database.integration.test.ts ai-generate.integration.test.ts ai-rag.integration.test.ts ai-writing.integration.test.ts api-keys.integration.test.ts audit-completeness.integration.test.ts audit-export-s3.integration.test.ts auth.integration.test.ts automation-pipeline.integration.test.ts automations.integration.test.ts blocks.integration.test.ts cache-invalidation.integration.test.ts comments.integration.test.ts databases.integration.test.ts files-lifecycle.integration.test.ts files-pipeline.integration.test.ts files-security.integration.test.ts files.integration.test.ts forms-responses.integration.test.ts forms.integration.test.ts oauth.integration.test.ts openapi.contract.test.ts org-admin.integration.test.ts package.json pages.integration.test.ts permissions.integration.test.ts README.md replica-routing.integration.test.ts retention-engine.integration.test.ts scim.integration.test.ts search.integration.test.ts sso.integration.test.ts tsconfig.json vitest.config.ts webhooks.integration.test.ts workspace.integration.test.ts
performance/28
fixtures/1search-100k.ts
helpers/2seed-100k.mjs seed-1k-load.mjs
reports/7api-load-smoke.json database-load-smoke.json editor-local.json realtime-load.json search-full.json search-last.json search-reduced.json
api-load.js api.js archive.tar database-load.js database.js editor-local.mjs extract-100k-env.mjs package.json README.md realtime-1k.js realtime-load.js realtime.js run-realtime-load.sh search-search.k6.js search-summary.json seed-100k.mjs threshold-breach-demo.js verify-zero-op-loss.mjs
security/16
helpers/1app.ts
audit-report.test.ts auth-paths.test.ts deps.test.ts formula-fuzz.test.ts gitleaks-config.test.ts headers.test.ts images.test.ts oracle.ts package.json permission-fuzz.test.ts rate-limits.test.ts README.md tsconfig.json upload-abuse.test.ts vitest.config.ts
README.md
.dockerignore .env .env.bak-task0125 .env.example .eslintrc.json .gitignore .npmrc .prettierignore .prettierrc.json AGENTS.md ARCHITECTURE.md CHANGELOG.md CONTRIBUTING.md gitleaks.toml LICENSE package.json pnpm-lock.yaml pnpm-workspace.yaml PRODUCT-SPEC.md README.md ROADMAP.md SECURITY.md tsconfig.json turbo.json
public-forms.service.tsapps/api/src/modules/forms/public-forms.service.tsraw← forms32,097 B← Back to the app
1/**
2 * TASK-0107/0108 — the PUBLIC form surface (no auth).
3 *
4 * `GET /public/forms/:slug` (TASK-0107 §1)
5 *   - PUBLISHED → the spec's EXACT whitelist: form { slug, name, description,
6 *     status: "published"|"closed", config { iconUrl, intro (sanitized
7 *     markdown), accent, successMessage, closedMessage } } + questions
8 *     [{ id, label, description, type, required, placeholder, validation:
9 *     public-safe subset }]. NEVER: workspace/database/property ids or
10 *     names, question propertyId, other forms, user data, submissions.
11 *   - DRAFT / unknown slug → 404 (no existence leak).
12 *   - CLOSED → 200 + status "closed" + closedMessage (intentionally visible).
13 *
14 * `POST /public/forms/:slug/submit` (TASK-0108 pipeline):
15 *   1. load form + questions (DRAFT/unknown → 404; CLOSED → 403 FORM_CLOSED);
16 *   2. content-type + 64 KB payload guard (415 / 413);
17 *   3. honeypot → 400 generic (NOT revealed; logged `form.honeypot_triggered`);
18 *   4. reCAPTCHA stub (skips while unconfigured — WARN-logged);
19 *   5. rate limit 5/min per IP per form → 429 + Retry-After;
20 *   6. optional session (valid JWT for this workspace → attributed; invalid
21 *      or absent → anonymous — never a 401 on the public path);
22 *   7. dynamic validation from the STORED questions (server is authoritative;
23 *      ALL violations in one 422, unknown questionIds ignored);
24 *   8. FILE answers verified: same workspace + status READY + linked to THIS
25 *      form (metadata.formId) → 422 FILE_NOT_OWNED / FILE_NOT_READY (fail
26 *      fast, BEFORE the transaction — a failed submit must not half-write);
27 *   9. ONE Prisma transaction: the DatabaseRecord (+ its backing Page with
28 *      the title) + RecordProperty rows (Phase-5 coercion shapes) + the
29 *      FormSubmission (RAW answers — the audit trail) + File.pageId links;
30 *   10. after commit: `form.submitted` event (the Phase-11 trigger; IP
31 *      redacted to /24 in the payload — full IP only in the DB) + owner
32 *      Notification (best-effort) + `form.submitted` audit (mandatory).
33 *
34 * `POST /public/forms/:slug/files` + `PUT .../files/:fileId/complete`
35 * (TASK-0108 file decision, recorded): public upload sessions attributed to
36 * the FORM (workspace = the form's, `metadata.formId` set at creation — the
37 * submit then accepts only files that both belong to the workspace AND were
38 * opened for this form). Reuses the Phase-9 primitives (MIME allow-list,
39 * quota, magic-byte sniff, worker pipeline) — no duplication of the state
40 * machine; the difference from the authenticated session is only the auth
41 * context (anonymous, form-scoped) and the formId attribution.
42 *
43 * Zero workspace data leaves this surface: every payload is hand-picked,
44 * the config is re-parsed through the shared strict schema, the intro is
45 * sanitized, and signed URLs point at object storage only.
46 */
47import { Inject, Injectable } from "@nestjs/common";
48import type { Request } from "express";
49import { randomBytes } from "node:crypto";
50import {
51  FORM_CONFIG_SCHEMA,
52  FORM_ACCENTS,
53  FORM_ERROR_CODES,
54  toPublicSafeValidation,
55  type FormQuestionType,
56  type FormStatus
57} from "@factory/shared";
58import { Prisma } from "@prisma/client";
59import { buildFileKey, isAllowedMime, presignGet, presignPut, sanitizeFilename, sniffVerdict } from "@factory/storage";
60import { jobTraceMetadata } from "../../common/trace-metadata.js";
61import { PrismaService } from "../../common/prisma.service.js";
62import { AuditService } from "../../common/audit.service.js";
63import { EventBus } from "../../common/event-bus.js";
64import { RedisService } from "../../common/redis.service.js";
65import { logger } from "../../common/logger.js";
66import { ApiError, type ErrorDetail } from "../../common/errors.js";
67import { EVENTS } from "../../constants.js";
68import { between } from "../../lib/positions.js";
69import { loadEnv } from "../../config/env.js";
70import { effectiveStorageQuota } from "../files/quota.js";
71import { effectiveMaxFileSize } from "../files/uploads.service.js";
72import { filesBucketConfig, makeFilesClient, signExpirySeconds } from "../files/s3.js";
73import { renderIntroMarkdown } from "./markdown.js";
74import { FormRateLimiter } from "./rate-limit.js";
75import { verifyRecaptcha } from "./recaptcha.js";
76import { buildAnswerResult, configIntegrityIssue, type StoredQuestion } from "./submit-schema.js";
77import { NotificationsService } from "../notifications/notifications.service.js";
78 
79/** The honeypot field names the public page renders (both checked). */
80const HONEYPOT_FIELDS = ["website", "hp"] as const;
81 
82/** The answers payload cap (spec §7: ≤ 64 KB → 413 PAYLOAD_TOO_LARGE). */
83const MAX_ANSWERS_BYTES = 64 * 1024;
84 
85/** A public file session's declared shape (same as Phase 9's, minus anchors). */
86interface PublicUploadInput {
87  name: string;
88  size: number;
89  mimeType: string;
90}
91 
92@Injectable()
93export class PublicFormsService {
94  constructor(
95    @Inject(PrismaService) private readonly prisma: PrismaService,
96    @Inject(AuditService) private readonly audit: AuditService,
97    @Inject(EventBus) private readonly events: EventBus,
98    @Inject(NotificationsService) private readonly notifications: NotificationsService,
99    @Inject(FormRateLimiter) private readonly rateLimiter: FormRateLimiter,
100    @Inject(RedisService) private readonly redis: RedisService
101  ) {}
102 
103  // ------------------------------------------------------------------ GET
104 
105  /** `GET /public/forms/:slug` — the spec's exact whitelist. */
106  async getPublic(slug: string) {
107    const form = await this.prisma.form.findUnique({
108      where: { slug },
109      include: { questions: { orderBy: { position: "asc" } } }
110    });
111    // DRAFT + unknown slug → 404 (the spec's explicit choice: drafts are not
112    // discoverable; a soft-deleted form's released slug 404s the same way).
113    if (!form || form.status === "DRAFT") throw ApiError.notFound("Form not found.");
114 
115    const config = this.safeConfig(form.config);
116    const status = form.status as FormStatus;
117    const published = status === "PUBLISHED";
118 
119    // Deviation from the §1 whitelist, recorded (same spec section requires
120    // the keys to function — §4 footer, §6c recaptcha slot): `poweredBy` +
121    // `recaptcha.enabled` are added; NOTHING else beyond the whitelist.
122    return {
123      form: {
124        slug: form.slug,
125        name: form.name,
126        description: form.description,
127        status: published ? "published" : "closed",
128        config: {
129          iconUrl: published ? await this.signedIconUrl(form, config.icon) : null,
130          intro: renderIntroMarkdown(typeof config.intro === "string" ? config.intro : ""),
131          accent: config.accent ?? FORM_ACCENTS[0],
132          successMessage: config.successMessage ?? null,
133          closedMessage: config.closedMessage ?? null,
134          poweredBy: config.poweredBy ?? true,
135          recaptcha: { enabled: Boolean((config.recaptcha as { enabled?: boolean } | undefined)?.enabled) }
136        }
137      },
138      questions: form.questions.map((q) => this.publicQuestion(q, published))
139    };
140  }
141 
142  /** A question's PUBLIC shape: no propertyId, safe validation only. A
143   *  closed form exposes no validation at all (no inputs are rendered). */
144  private publicQuestion(
145    q: {
146      id: string;
147      label: string;
148      description: string | null;
149      type: string;
150      required: boolean;
151      validation: unknown;
152      placeholder: string | null;
153    },
154    published: boolean
155  ) {
156    return {
157      id: q.id,
158      type: q.type as FormQuestionType,
159      label: q.label,
160      description: q.description,
161      required: q.required,
162      placeholder: q.placeholder,
163      validation: published ? toPublicSafeValidation(q.validation) : {}
164    };
165  }
166 
167  /** Re-parse the stored config through the shared strict schema (fail
168   *  closed to the empty config — corrupt Json is never echoed raw). */
169  private safeConfig(config: unknown): Record<string, unknown> {
170    const parsed = FORM_CONFIG_SCHEMA.safeParse(config ?? {});
171    return parsed.success ? (parsed.data as Record<string, unknown>) : {};
172  }
173 
174  /** Sign a 15-min GET for the icon file (workspace + READY + image only). */
175  private async signedIconUrl(
176    form: { workspaceId: string },
177    icon: unknown
178  ): Promise<string | null> {
179    if (typeof icon !== "string" || icon.length === 0) return null;
180    const file = await this.prisma.file.findFirst({
181      where: { id: icon, workspaceId: form.workspaceId, deletedAt: null },
182      select: { id: true, status: true, key: true, mimeType: true }
183    });
184    if (!file || file.status !== "READY" || !file.mimeType.startsWith("image/")) return null;
185    try {
186      const env = loadEnv();
187      const { url } = presignGet({
188        config: filesBucketConfig(env),
189        key: file.key,
190        expiresSec: 900,
191        now: new Date()
192      });
193      return url;
194    } catch {
195      return null;
196    }
197  }
198 
199  // ---------------------------------------------------------------- SUBMIT
200 
201  /**
202   * `POST /public/forms/:slug/submit`. 201 `{ success, submissionId,
203   * message }` + `X-Submission-Id` header (the controller sets it).
204   */
205  async submitPublic(
206    slug: string,
207    body: { answers?: unknown; website?: string; hp?: string; recaptchaToken?: string },
208    req: Request
209  ): Promise<{ success: true; submissionId: string; message: string | null }> {
210    // Content-type guard (CSRF mitigation per TASK-0107: a cross-origin form
211    // post can't send application/json without a preflight).
212    const contentType = String(req.headers["content-type"] ?? "");
213    if (!contentType.includes("application/json")) {
214      throw new ApiError("UNSUPPORTED_MEDIA_TYPE", 415, "Content-Type must be application/json.", [
215        { issue: "json_required" }
216      ]);
217    }
218 
219    const form = await this.prisma.form.findUnique({
220      where: { slug },
221      include: { questions: { orderBy: { position: "asc" } } }
222    });
223    // DRAFT + unknown slug → 404 (same shape as the GET path).
224    if (!form || form.status === "DRAFT") throw ApiError.notFound("Form not found.");
225    if (form.status === "CLOSED") {
226      throw new ApiError("FORBIDDEN", 403, "This form is closed.", [
227        { reason: FORM_ERROR_CODES.FORM_CLOSED }
228      ]);
229    }
230 
231    // 64 KB answers guard (spec §7).
232    const answersJson = JSON.stringify(body.answers ?? {});
233    if (answersJson.length > MAX_ANSWERS_BYTES) {
234      throw new ApiError("PAYLOAD_TOO_LARGE", 413, "The answers payload is too large.", [
235        { issue: FORM_ERROR_CODES.PAYLOAD_TOO_LARGE, maxBytes: MAX_ANSWERS_BYTES }
236      ]);
237    }
238 
239    // 1. honeypot → 400 generic (the spec's TASK-0107 §6a: NOT a fake
240    //    success; the reason is never revealed — only the internal log).
241    if (HONEYPOT_FIELDS.some((f) => body[f] && String(body[f]).trim() !== "")) {
242      logger.warn(`form.honeypot_triggered slug=${slug} ip=${req.ip ?? "unknown"}`);
243      throw new ApiError("VALIDATION_ERROR", 400, "Submission failed. Please try again.");
244    }
245 
246    const ip = req.ip ?? "unknown";
247 
248    // 2. reCAPTCHA stub (skips while unconfigured — WARN-logged).
249    await verifyRecaptcha(body.recaptchaToken, ip);
250 
251    // 3. rate limit (after the honeypot — bots do not eat real slots).
252    const rl = await this.rateLimiter.check(slug, ip);
253    if (!rl.allowed) {
254      // The Retry-After header must ride the 429 (spec §6): set it on the
255      // response BEFORE throwing — the exception filter writes the body and
256      // the header flushes with it.
257      req.res?.setHeader("Retry-After", String(rl.retryAfterSeconds));
258      throw new ApiError("RATE_LIMITED", 429, "Too many submissions. Try again shortly.", [
259        { retryAfterSeconds: rl.retryAfterSeconds }
260      ]);
261    }
262 
263    // 4. optional session (invalid/absent → anonymous; never 401 here — the
264    //    OptionalAuthGuard already decoded a valid user JWT into req.auth).
265    const submittedBy = await this.optionalSession(req, form.workspaceId);
266    const anonymous = submittedBy === null;
267 
268    // 5. dynamic validation (the stored questions ARE the schema source).
269    const stored: StoredQuestion[] = form.questions.map((q) => ({
270      id: q.id,
271      label: q.label,
272      type: q.type,
273      required: q.required,
274      validation: q.validation
275    }));
276    const configIssue = configIntegrityIssue(stored);
277    if (configIssue) {
278      throw new ApiError("INTERNAL_ERROR", 500, "Form configuration is corrupt.", [
279        { reason: FORM_ERROR_CODES.FORM_CONFIG_INVALID, detail: configIssue }
280      ]);
281    }
282    const { answers, violations } = buildAnswerResult(
283      stored,
284      (body.answers ?? {}) as Record<string, unknown>
285    );
286    if (violations.length > 0) {
287      const details: ErrorDetail[] = violations.map((v) => ({
288        questionId: v.questionId,
289        code: v.code,
290        message: v.message
291      }));
292      throw new ApiError("UNPROCESSABLE_ENTITY", 422, "Submission failed validation.", details);
293    }
294 
295    // 6. FILE answers: same workspace + READY + linked to THIS form
296    //    (metadata.formId — the public session sets it; a forged id from
297    //    another workspace/form is rejected + audited below via the 422
298    //    details, and the honeypot-independent log line).
299    const fileIds = collectFileIds(answers);
300    const fileRows = new Map<string, { status: string; metadata: unknown }>();
301    if (fileIds.length > 0) {
302      const files = await this.prisma.file.findMany({
303        where: { id: { in: fileIds }, workspaceId: form.workspaceId, deletedAt: null },
304        select: { id: true, status: true, metadata: true }
305      });
306      for (const f of files) fileRows.set(f.id, { status: f.status, metadata: f.metadata });
307      for (const id of fileIds) {
308        const f = fileRows.get(id);
309        const meta = (f?.metadata ?? {}) as Record<string, unknown>;
310        if (!f || meta.formId !== form.id) {
311          logger.warn(`form.file_not_owned slug=${slug} fileId=${id} workspaceId=${form.workspaceId}`);
312          throw new ApiError("UNPROCESSABLE_ENTITY", 422, "A submitted file is not available in this form.", [
313            { fileId: id, reason: FORM_ERROR_CODES.FILE_NOT_OWNED }
314          ]);
315        }
316        if (f.status !== "READY") {
317          throw new ApiError("UNPROCESSABLE_ENTITY", 422, "A submitted file is still processing — try again in a moment.", [
318            { fileId: id, reason: FORM_ERROR_CODES.FILE_NOT_READY }
319          ]);
320        }
321      }
322    }
323 
324    // 7. map answers → record property values. Mappings were validated at
325    //    question-write time; re-verify here because a property can be
326    //    deleted AFTER the form was saved — a dead mapping is SKIPPED (the
327    //    answer is retained in FormSubmission.answers; the record still
328    //    gets everything that still maps). Coercion mirrors Phase 5's
329    //    RecordService.coerceValue shapes (documented reuse decision).
330    const properties = await this.prisma.databaseProperty.findMany({
331      where: { databaseId: form.databaseId, deletedAt: null },
332      select: { id: true, type: true, isTitle: true }
333    });
334    const propById = new Map(properties.map((p) => [p.id, p]));
335    const recordValues = new Map<string, unknown>();
336    let titlePropertyId: string | null = null;
337    let mappedCount = 0;
338    for (const q of form.questions) {
339      const prop = q.propertyId ? propById.get(q.propertyId) : undefined;
340      if (!prop) continue; // dead mapping (property deleted after save) — skipped
341      mappedCount += 1;
342      if (prop.isTitle || prop.type === "TITLE") titlePropertyId = prop.id;
343      if (!(q.id in answers)) continue;
344      recordValues.set(prop.id, coerceForProperty(answers[q.id], prop.type));
345    }
346    const mapped = { length: mappedCount };
347    // Record title (spec §3a): the TITLE-mapped question's value, else the
348    // deterministic fallback `"<form name> — <first 8 chars of the first
349    // text answer>"`.
350    const titleAnswer =
351      titlePropertyId !== null
352        ? (answers[form.questions.find((q) => q.propertyId === titlePropertyId)?.id ?? ""] ?? undefined)
353        : undefined;
354    const title =
355      typeof titleAnswer === "string" && titleAnswer.trim() !== ""
356        ? titleAnswer.trim().slice(0, 300)
357        : fallbackTitle(form.name, answers);
358 
359    // 8. ONE transaction: record + page + properties + submission + file
360    //    links (atomicity — a failure leaves NOTHING, spec §3).
361    const createdBy = submittedBy ?? form.createdById;
362    const { submission, recordId, pageId } = await this.prisma.$transaction(async (tx) => {
363      let recordIdOut: string | null = null;
364      let pageIdOut: string | null = null;
365      if (mapped.length > 0) {
366        const last = await tx.databaseRecord.findFirst({
367          where: { databaseId: form.databaseId },
368          orderBy: { position: "desc" },
369          select: { position: true }
370        });
371        const position = between(last?.position, undefined);
372        const page = await tx.page.create({
373          data: {
374            workspaceId: form.workspaceId,
375            title,
376            position,
377            createdBy,
378            updatedBy: createdBy
379          }
380        });
381        const record = await tx.databaseRecord.create({
382          data: {
383            workspaceId: form.workspaceId,
384            databaseId: form.databaseId,
385            pageId: page.id,
386            position,
387            createdBy,
388            lastEditedBy: createdBy
389          }
390        });
391        recordIdOut = record.id;
392        pageIdOut = page.id;
393        for (const [propertyId, value] of recordValues) {
394          const json = value === null ? Prisma.JsonNull : (value as Prisma.InputJsonValue);
395          await tx.recordProperty.upsert({
396            where: { recordId_propertyId: { recordId: record.id, propertyId } },
397            update: { value: json },
398            create: { recordId: record.id, propertyId, value: json }
399          });
400        }
401      }
402 
403      const sub = await tx.formSubmission.create({
404        data: {
405          workspaceId: form.workspaceId,
406          formId: form.id,
407          recordId: recordIdOut,
408          answers: answers as object,
409          submittedBy: submittedBy ?? null,
410          ipAddress: ip
411        }
412      });
413 
414      // Link the submitted files (spec §3c): File.pageId → the record's
415      // page (+ blockId null), metadata.formId/submissionId stamped (the
416      // TASK-0109 cascade finds them by these). Runs even when NO record
417      // was created (all questions unmapped) — the submissionId stamp is
418      // what makes the files deletable-with-their-submission.
419      if (fileIds.length > 0) {
420        for (const id of fileIds) {
421          const meta = (fileRows.get(id)?.metadata ?? {}) as Record<string, unknown>;
422          await tx.file.update({
423            where: { id },
424            data: {
425              pageId: pageIdOut,
426              blockId: null,
427              metadata: { ...meta, formId: form.id, submissionId: sub.id }
428            }
429          });
430        }
431      }
432 
433      return { submission: sub, recordId: recordIdOut, pageId: pageIdOut };
434    });
435 
436    // 9. Side effects (after commit — best-effort, their own error
437    //    handling per spec §4; a failure never undoes the submission).
438    const redactedIp = redactIp24(ip);
439    await this.events.publish(EVENTS.FORM_SUBMITTED, {
440      workspaceId: form.workspaceId,
441      formId: form.id,
442      slug: form.slug,
443      submissionId: submission.id,
444      recordId,
445      databaseId: form.databaseId,
446      questionCount: form.questions.length,
447      anonymous,
448      ip: redactedIp
449    });
450 
451    try {
452      const owner = await this.prisma.user.findUnique({
453        where: { id: form.createdById },
454        select: { displayName: true, name: true }
455      });
456      await this.notifications.notify({
457        workspaceId: form.workspaceId,
458        userId: form.createdById,
459        type: "FORM_SUBMITTED",
460        title: `${form.name} received a new response`,
461        body: submittedBy ? `From ${submittedBy === form.createdById ? "you" : (owner?.displayName ?? owner?.name ?? "a member")}.` : "Anonymous public submission.",
462        link: { type: "form", id: form.id },
463        actorId: submittedBy ?? null
464      });
465    } catch (err) {
466      // A notification failure never fails the submit (spec §4).
467      logger.warn(`form owner notification failed (${form.id}): ${(err as Error).message}`);
468    }
469 
470    await this.audit.audit(req, undefined, {
471      action: "form.submitted",
472      resourceType: "form_submission",
473      resourceId: submission.id,
474      workspaceId: form.workspaceId,
475      actorId: submittedBy ?? "anonymous",
476      metadata: {
477        formId: form.id,
478        slug: form.slug,
479        recordId,
480        ip,
481        anonymous,
482        questionCount: form.questions.length
483      }
484    });
485 
486    // X-Submission-Id: client dedupe logging (spec §6) — set on the response
487    // before the JSON body is written.
488    req.res?.setHeader("X-Submission-Id", submission.id);
489    return {
490      success: true,
491      submissionId: submission.id,
492      message: (this.safeConfig(form.config).successMessage as string | undefined) ?? null
493    };
494  }
495 
496  /** The guard-decoded user session, when it belongs to THIS workspace. */
497  /**
498   * Resolve the attributing user for a public submit. A valid user JWT
499   * (decoded by the controller's OptionalAuthGuard into req.auth) is the
500   * candidate; the WORKSPACE MEMBERSHIP is verified against the DB (the
501   * `workspaceMember` table — the source of truth for roles, exactly as
502   * `effectiveLevel` resolves them), NOT against the JWT's `workspaces`
503   * snapshot. That claim is frozen at mint time, so a membership granted
504   * after the token was issued would otherwise go unattributed (the user
505   * IS a member, but the stale claim says otherwise). A non-member or a
506   * forged/invalid token → anonymous (never an error — the public surface
507   * must stay open; attribution is a best-effort, server-side decision).
508   */
509  private async optionalSession(req: Request, workspaceId: string): Promise<string | null> {
510    const auth = (req as Request & { auth?: import("../../common/types.js").AuthContext }).auth;
511    if (!auth || auth.kind !== "user" || !auth.userId) return null;
512    const membership = await this.prisma.workspaceMember.findUnique({
513      where: { workspaceId_userId: { workspaceId, userId: auth.userId } }
514    });
515    return membership ? auth.userId : null;
516  }
517 
518  // ---------------------------------------------- public FILE sessions
519 
520  /**
521   * `POST /public/forms/:slug/files` — open a form-attributed upload session
522   * (anonymous). Same Phase-9 gates as the authenticated session: workspace
523   * plan size limit, storage quota, closed MIME allow-list. The File row
524   * carries `metadata.formId` — the submit endpoint later accepts ONLY
525   * files with this exact attribution (forged ids → FILE_NOT_OWNED).
526   */
527  async openPublicUpload(slug: string, input: PublicUploadInput, req: Request) {
528    const form = await this.loadPublicForm(slug);
529    const ws = await this.prisma.workspace.findUnique({ where: { id: form.workspaceId } });
530    if (!ws || ws.deletedAt) throw ApiError.notFound("Form not found.");
531 
532    if (!isAllowedMime(input.mimeType)) {
533      throw ApiError.validation("File type is not allowed.", [
534        { field: "mimeType", issue: "mime_not_allowed", received: input.mimeType }
535      ]);
536    }
537    const limits = (ws.usageLimits ?? {}) as { maxFileSize?: number; storageQuota?: number };
538    const maxFileSize = effectiveMaxFileSize(ws.billingPlan, limits);
539    if (input.size > maxFileSize) {
540      throw new ApiError("FILE_TOO_LARGE", 413, "File size exceeds the workspace plan limit.", [
541        { maxBytes: maxFileSize, plan: ws.billingPlan }
542      ]);
543    }
544    const quota = effectiveStorageQuota(ws.billingPlan, limits);
545    const used = Number(ws.usageStorageBytes ?? 0n);
546    if (input.size > quota - used) {
547      throw new ApiError("QUOTA_EXCEEDED", 413, "The workspace storage quota is full.", [
548        { maxBytes: quota, usedBytes: used }
549      ]);
550    }
551 
552    const env = loadEnv();
553    const fileId = `file_${randomBytes(12).toString("base64url")}`;
554    const key = buildFileKey({
555      workspaceId: form.workspaceId,
556      fileId,
557      version: 1,
558      name: sanitizeFilename(input.name)
559    });
560    const now = new Date();
561    const expiresSec = signExpirySeconds(env);
562 
563    const file = await this.prisma.file.create({
564      data: {
565        id: fileId,
566        workspaceId: form.workspaceId,
567        pageId: null,
568        blockId: null,
569        name: sanitizeFilename(input.name),
570        key,
571        size: input.size,
572        mimeType: input.mimeType,
573        status: "UPLOADING",
574        metadata: { formId: form.id, public: true } as object,
575        uploadedBy: "anonymous"
576      }
577    });
578 
579    const put = presignPut({
580      config: filesBucketConfig(env),
581      key,
582      contentType: input.mimeType,
583      expiresSec,
584      now
585    });
586 
587    await this.audit.audit(req, undefined, {
588      action: "form.public_upload_created",
589      resourceType: "file",
590      resourceId: file.id,
591      workspaceId: form.workspaceId,
592      actorId: "anonymous",
593      metadata: { formId: form.id, name: input.name, size: input.size, mimeType: input.mimeType }
594    });
595 
596    return {
597      upload: {
598        fileId: file.id,
599        uploadUrl: put.url,
600        method: "PUT" as const,
601        headers: { "Content-Type": input.mimeType },
602        expiresAt: new Date(now.getTime() + expiresSec * 1000).toISOString()
603      }
604    };
605  }
606 
607  /**
608   * `PUT /public/forms/:slug/files/:fileId/complete` — the public half of
609   * Phase 9's two-phase completion (HEAD size check + magic-byte sniff +
610   * SCANNING + worker enqueue). The file must belong to this form's
611   * session (metadata.formId + workspace) or the request 404s.
612   */
613  async completePublicUpload(slug: string, fileId: string, req: Request) {
614    const form = await this.loadPublicForm(slug);
615    const file = await this.prisma.file.findFirst({
616      where: { id: fileId, workspaceId: form.workspaceId, deletedAt: null }
617    });
618    const meta = (file?.metadata ?? {}) as Record<string, unknown>;
619    if (!file || meta.formId !== form.id) throw ApiError.notFound("Upload session not found.");
620    if (file.status !== "UPLOADING") {
621      throw new ApiError("CONFLICT", 409, "This upload session has already been completed.", [
622        { reason: "upload_already_completed" }
623      ]);
624    }
625 
626    const s3 = makeFilesClient();
627    let head: { size: number };
628    try {
629      head = await s3.headObject(file.key);
630    } catch (err) {
631      const status = (err as { status?: number })?.status;
632      if (status === 404) {
633        throw new ApiError("UPLOAD_EXPIRED", 410, "The upload object is not present.", [
634          { reason: "upload_expired" }
635        ]);
636      }
637      throw err;
638    }
639    if (head.size !== file.size) {
640      throw new ApiError("UPLOAD_INCOMPLETE", 422, "Uploaded object size does not match the declared size.", [
641        { received: head.size, expected: file.size }
642      ]);
643    }
644 
645    const { prefix } = await s3.readPrefix(file.key, 8 * 1024);
646    const verdict = sniffVerdict(prefix, file.mimeType);
647    if (verdict === "mismatch") {
648      await s3.deleteObject(file.key).catch(() => undefined);
649      await this.prisma.file.update({
650        where: { id: file.id },
651        data: {
652          status: "FAILED",
653          metadata: { ...meta, pipeline: { error: "mime_mismatch" } },
654          scanReport: { engine: "magic-bytes", result: "mismatch", claimed: file.mimeType } as object
655        }
656      });
657      throw new ApiError("MIME_MISMATCH", 415, "The uploaded bytes do not match the declared MIME type.", [
658        { claimed: file.mimeType, issue: "mime_mismatch" }
659      ]);
660    }
661 
662    await this.prisma.file.update({
663      where: { id: file.id },
664      data: { status: "SCANNING", size: head.size }
665    });
666    await this.enqueueProcessFile(file.id, file.workspaceId);
667 
668    await this.audit.audit(req, undefined, {
669      action: "form.public_upload_completed",
670      resourceType: "file",
671      resourceId: file.id,
672      workspaceId: file.workspaceId,
673      actorId: "anonymous",
674      metadata: { formId: form.id, name: file.name, size: head.size }
675    });
676 
677    return { id: file.id, status: "SCANNING", verifiedBy: "worker" };
678  }
679 
680  /** The PUBLISHED form row for public surface ops (DRAFT/unknown → 404). */
681  private async loadPublicForm(slug: string) {
682    const form = await this.prisma.form.findUnique({ where: { slug } });
683    if (!form || form.status === "DRAFT") throw ApiError.notFound("Form not found.");
684    return form;
685  }
686 
687  /** Enqueue the Phase-9 pipeline job (worker does scan/metadata/thumbs). */
688  private async enqueueProcessFile(fileId: string, workspaceId: string): Promise<void> {
689    try {
690      const { Queue } = await import("bullmq");
691      const q = new Queue("files", {
692        connection: this.redis.getRedis().options as never,
693        defaultJobOptions: {
694          attempts: 3,
695          backoff: { type: "exponential", delay: 2_000 },
696          removeOnComplete: 500,
697          removeOnFail: 200
698        }
699      });
700      // TASK-0135: continue the enqueueing request's trace into the job.
701      await q.add("process-file", { fileId, version: 1, workspaceId }, { ...jobTraceMetadata() });
702      await q.close();
703    } catch (err) {
704      logger.warn(`files queue enqueue failed for ${fileId}: ${(err as Error).message}`);
705    }
706  }
707}
708 
709/** Redact an IPv4 to /24 (`1.2.3.***`) — the event payload's IP form. */
710function redactIp24(ip: string): string {
711  if (!ip) return "unknown";
712  const v4 = ip.replace(/^::ffff:/, "");
713  const parts = v4.split(".");
714  if (parts.length === 4) return `${parts[0]}.${parts[1]}.${parts[2]}.***`;
715  return "***";
716}
717 
718/** Deterministic fallback title (spec §3a): name + first 8 chars of the
719 *  first text-ish answer in question order. */
720function fallbackTitle(formName: string, answers: Record<string, unknown>): string {
721  for (const v of Object.values(answers)) {
722    if (typeof v === "string" && v.trim() !== "") {
723      const head = v.trim().slice(0, 8);
724      return `${formName} — ${head}`.slice(0, 300);
725    }
726  }
727  return formName.slice(0, 300);
728}
729 
730/** Every FILE answer's file ids (flat, deduped). */
731function collectFileIds(answers: Record<string, unknown>): string[] {
732  const out: string[] = [];
733  for (const v of Object.values(answers)) {
734    if (Array.isArray(v)) {
735      for (const item of v) if (typeof item === "string") out.push(item);
736    }
737  }
738  return [...new Set(out)];
739}
740 
741/**
742 * Coerce a validated answer to the database property's storage shape —
743 * the SAME shapes Phase 5's RecordService.coerceValue writes (documented
744 * reuse: the anonymous submit cannot call that service — it asserts an
745 * authenticated EDIT — so the shapes are mirrored here and kept in lockstep
746 * by the TASK-0108 integration assertions on stored values).
747 */
748function coerceForProperty(value: unknown, propType: string): unknown {
749  if (value === undefined || value === null) return null;
750  switch (propType) {
751    case "TITLE":
752    case "TEXT":
753    case "RICH_TEXT":
754      return { text: String(value), marks: [] };
755    case "NUMBER":
756      return { value: Number(value) };
757    case "SELECT":
758    case "STATUS":
759      return { optionId: String(value) };
760    case "MULTI_SELECT":
761      return { optionIds: Array.isArray(value) ? value.map(String) : [String(value)] };
762    case "DATE":
763    case "DATE_RANGE":
764      return { start: String(value), end: null };
765    case "EMAIL":
766    case "PHONE":
767      return { value: String(value) };
768    case "URL":
769      return { value: String(value), title: null };
770    case "CHECKBOX":
771      return { value: Boolean(value) };
772    case "FILES":
773      return { fileIds: Array.isArray(value) ? value : [value] };
774    default:
775      // A matrix-allowed mapping with no direct storage shape — store the
776      // raw answer (recorded: the matrix is the contract; raw is the
777      // lossless default).
778      return value;
779  }
780}
781