create-ailk 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -8
- package/component-catalog.json +336 -27
- package/component-catalog.md +25 -12
- package/dist/cli.js +54 -5
- package/dist/copy.d.ts +14 -0
- package/dist/copy.js +38 -1
- package/dist/lib/api-boot-assertion.d.ts +46 -0
- package/dist/lib/api-boot-assertion.js +70 -0
- package/dist/lib/extract-module-bundle.d.ts +20 -1
- package/dist/lib/extract-module-bundle.js +64 -5
- package/dist/lib/import-graph.d.ts +29 -0
- package/dist/lib/import-graph.js +140 -0
- package/dist/lib/module-license-gate.d.ts +6 -1
- package/dist/lib/module-license-gate.js +6 -1
- package/dist/lib/pro-callout.js +1 -1
- package/dist/module-architecture.d.ts +1 -0
- package/dist/module-architecture.js +253 -127
- package/dist/modules/commerce/0.6.0.tar.gz +0 -0
- package/dist/modules/docs-blog/0.6.0.tar.gz +0 -0
- package/dist/modules/multi-tenant/0.6.0.tar.gz +0 -0
- package/dist/modules/scheduling/0.6.0.tar.gz +0 -0
- package/dist/modules/signal-collectors/0.6.0.tar.gz +0 -0
- package/dist/modules/workspace/0.6.0.tar.gz +0 -0
- package/dist/programmatic.js +14 -10
- package/dist/surfaces.js +105 -7
- package/dist/template-manifest.d.ts +33 -0
- package/dist/template-manifest.js +99 -16
- package/dist/template-names.d.ts +1 -1
- package/dist/template-names.js +1 -0
- package/package.json +3 -2
- package/site-templates/marketing-site/DESIGN.md +148 -0
- package/site-templates/marketing-site/TEMPLATE-MANIFEST.json +22 -2
- package/site-templates/marketing-site/TEMPLATE-MANIFEST.md +9 -2
- package/site-templates/marketing-site/ailk-template.json +1 -1
- package/site-templates/marketing-site-free/DESIGN.md +148 -0
- package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.json +2 -2
- package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.md +1 -0
- package/site-templates/minimalism-site/DESIGN.md +148 -0
- package/site-templates/minimalism-site/TEMPLATE-MANIFEST.json +10 -2
- package/site-templates/minimalism-site/TEMPLATE-MANIFEST.md +47 -35
- package/site-templates/minimalism-site/ailk-template.json +2 -1
- package/site-templates/minimalism-site/assets/wordmark-placeholder.svg +28 -0
- package/site-templates/minimalism-site/content/en/HomePage/home.mdx +49 -19
- package/site-templates/saas-product/DESIGN.md +148 -0
- package/site-templates/simple-service/DESIGN.md +148 -0
- package/site-templates/simple-service/TEMPLATE-MANIFEST.json +240 -0
- package/site-templates/simple-service/TEMPLATE-MANIFEST.md +278 -0
- package/site-templates/simple-service/ailk-template.json +10 -0
- package/site-templates/simple-service/content/en/AboutPage/about.mdx +38 -0
- package/site-templates/simple-service/content/en/ContactPage/contact.mdx +67 -0
- package/site-templates/simple-service/content/en/FAQPage/faq.mdx +56 -0
- package/site-templates/simple-service/content/en/HomePage/home.mdx +85 -0
- package/site-templates/simple-service/content/en/Service/landscape-design.mdx +40 -0
- package/site-templates/simple-service/content/en/Service/lawn-maintenance.mdx +40 -0
- package/site-templates/simple-service/content/en/Service/seasonal-cleanup.mdx +40 -0
- package/site-templates/simple-service/content/en/ServicesList/services.mdx +72 -0
- package/site-templates/simple-service/provenance.json +4 -0
- package/templates/.env.example +72 -7
- package/templates/CLAUDE.md +2 -3
- package/templates/DESIGN.md +155 -0
- package/templates/README.md +42 -8
- package/templates/apps/api/.ailk/inbox/2026-09-20T14-57-31.552Z-fallback-1789916251590-037e9005.json +8 -0
- package/templates/apps/api/.ailk/inbox/2026-09-20T14-57-33.840Z-fallback-1789916253842-b52659e9.json +12 -0
- package/templates/apps/api/.ailk/inbox/2026-09-20T14-57-33.844Z-fallback-1789916253845-6b266f8c.json +12 -0
- package/templates/apps/api/.env.example +13 -0
- package/templates/apps/api/CLAUDE.md +26 -2
- package/templates/apps/api/jest.config.cjs +3 -0
- package/templates/apps/api/package.json +1 -0
- package/templates/apps/api/src/__tests__/commerce-claim-registration.test.ts +407 -0
- package/templates/apps/api/src/__tests__/module-exclusion.test.ts +83 -7
- package/templates/apps/api/src/__tests__/server.test.ts +471 -0
- package/templates/apps/api/src/__tests__/vercel-handler.test.ts +45 -0
- package/templates/apps/api/src/__tests__/workspace-module-registration.test.ts +2 -0
- package/templates/apps/api/src/config/index.ts +62 -0
- package/templates/apps/api/src/config/modules.ts +7 -3
- package/templates/apps/api/src/lib/__mocks__/prisma.ts +238 -2
- package/templates/apps/api/src/lib/__tests__/auth-email-budget.test.ts +143 -0
- package/templates/apps/api/src/lib/__tests__/content-adapter.test.ts +23 -0
- package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +125 -0
- package/templates/apps/api/src/lib/__tests__/error-serializer.test.ts +20 -0
- package/templates/apps/api/src/lib/__tests__/require-commerce-claim.test.ts +317 -0
- package/templates/apps/api/src/lib/__tests__/site.test.ts +238 -0
- package/templates/apps/api/src/lib/__tests__/stripe.test.ts +75 -0
- package/templates/apps/api/src/lib/auth-email-budget.ts +160 -0
- package/templates/apps/api/src/lib/content-adapter.ts +57 -31
- package/templates/apps/api/src/lib/deliverable-asset-store.ts +76 -0
- package/templates/apps/api/src/lib/error-serializer.ts +23 -3
- package/templates/apps/api/src/lib/outbound-http.ts +7 -2
- package/templates/apps/api/src/lib/require-commerce-claim.ts +250 -0
- package/templates/apps/api/src/lib/site.ts +208 -9
- package/templates/apps/api/src/lib/stripe.ts +66 -0
- package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +182 -0
- package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +42 -0
- package/templates/apps/api/src/middleware/rate-limit.ts +7 -1
- package/templates/apps/api/src/openapi/spec.ts +543 -2
- package/templates/apps/api/src/routes/auth/__tests__/auth-user.functional.test.ts +48 -0
- package/templates/apps/api/src/routes/auth/__tests__/transactional-email.test.ts +309 -0
- package/templates/apps/api/src/routes/auth/__tests__/user.test.ts +123 -0
- package/templates/apps/api/src/routes/auth/transactional-email.ts +273 -0
- package/templates/apps/api/src/routes/auth/user.ts +61 -0
- package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +434 -0
- package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +888 -0
- package/templates/apps/api/src/routes/checkout/index.ts +34 -0
- package/templates/apps/api/src/routes/checkout/session.ts +139 -0
- package/templates/apps/api/src/routes/checkout/sessions.ts +197 -0
- package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +554 -0
- package/templates/apps/api/src/routes/content/__tests__/list-pages.test.ts +108 -0
- package/templates/apps/api/src/routes/content/__tests__/search.test.ts +450 -0
- package/templates/apps/api/src/routes/content/get-page.ts +94 -12
- package/templates/apps/api/src/routes/content/index.ts +13 -73
- package/templates/apps/api/src/routes/content/list-pages.ts +15 -3
- package/templates/apps/api/src/routes/content/rate-limit.ts +15 -6
- package/templates/apps/api/src/routes/content/search.ts +129 -0
- package/templates/apps/api/src/routes/leads/__tests__/index.test.ts +447 -31
- package/templates/apps/api/src/routes/leads/index.ts +100 -13
- package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +51 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +351 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +51 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +5 -2
- package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +4 -1
- package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +58 -0
- package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +107 -6
- package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +87 -2
- package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +51 -0
- package/templates/apps/api/src/routes/project-listings/start.ts +5 -1
- package/templates/apps/api/src/routes/requests/__tests__/confirm.test.ts +686 -0
- package/templates/apps/api/src/routes/requests/confirm.ts +601 -0
- package/templates/apps/api/src/routes/requests/index.ts +54 -0
- package/templates/apps/api/src/routes/webhooks/README.md +265 -0
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-dunning.test.ts +749 -0
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +330 -0
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +262 -0
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +285 -0
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +213 -0
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe-request-paid.test.ts +301 -0
- package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +648 -0
- package/templates/apps/api/src/routes/webhooks/index.ts +89 -0
- package/templates/apps/api/src/routes/webhooks/stripe.ts +1399 -0
- package/templates/apps/api/src/server.ts +439 -49
- package/templates/apps/api/src/services/__tests__/abandon-email.test.ts +39 -0
- package/templates/apps/api/src/services/__tests__/aeo-score.test.ts +217 -40
- package/templates/apps/api/src/services/__tests__/audit-log.test.ts +620 -0
- package/templates/apps/api/src/services/__tests__/consent.test.ts +2 -0
- package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +300 -5
- package/templates/apps/api/src/services/__tests__/deliverable-resend.test.ts +20 -0
- package/templates/apps/api/src/services/__tests__/dunning-policy.test.ts +368 -0
- package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +160 -0
- package/templates/apps/api/src/services/__tests__/listing-config.test.ts +166 -0
- package/templates/apps/api/src/services/__tests__/project-listings.fence.test.ts +154 -0
- package/templates/apps/api/src/services/__tests__/public-site-resolver.test.ts +137 -0
- package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +444 -0
- package/templates/apps/api/src/services/__tests__/revalidation.test.ts +238 -0
- package/templates/apps/api/src/services/__tests__/verified-email.test.ts +78 -0
- package/templates/apps/api/src/services/abandon-email.ts +8 -2
- package/templates/apps/api/src/services/aeo-score.ts +49 -12
- package/templates/apps/api/src/services/audit-log.ts +668 -0
- package/templates/apps/api/src/services/consent.ts +18 -0
- package/templates/apps/api/src/services/default-tenant.ts +70 -31
- package/templates/apps/api/src/services/deliverable-fulfillment.ts +141 -13
- package/templates/apps/api/src/services/dunning-policy.ts +294 -0
- package/templates/apps/api/src/services/entitlements.ts +80 -0
- package/templates/apps/api/src/services/lead-promotion.ts +13 -14
- package/templates/apps/api/src/services/lead-routing.ts +161 -2
- package/templates/apps/api/src/services/leads-inbox.ts +23 -2
- package/templates/apps/api/src/services/listing-config.ts +27 -9
- package/templates/apps/api/src/services/project-listings.ts +201 -6
- package/templates/apps/api/src/services/public-site-resolver.ts +106 -0
- package/templates/apps/api/src/services/request-confirm.ts +646 -0
- package/templates/apps/api/src/services/revalidation.ts +173 -0
- package/templates/apps/api/src/services/verified-email.ts +71 -0
- package/templates/apps/api/src/vercel-handler.ts +75 -35
- package/templates/apps/mcp/.env.example +17 -0
- package/templates/apps/mcp/CLAUDE.md +57 -24
- package/templates/apps/mcp/__tests__/aeo-cli-parity.test.ts +6 -0
- package/templates/apps/mcp/__tests__/audit.test.ts +137 -8
- package/templates/apps/mcp/__tests__/catalog-drift.test.ts +79 -36
- package/templates/apps/mcp/__tests__/get_offerings.test.ts +111 -2
- package/templates/apps/mcp/__tests__/get_pricing.test.ts +82 -2
- package/templates/apps/mcp/__tests__/http-transport.test.ts +541 -2
- package/templates/apps/mcp/__tests__/index.test.ts +39 -0
- package/templates/apps/mcp/__tests__/lib/audit-single-page-readiness-scan.test.ts +143 -0
- package/templates/apps/mcp/__tests__/lib/commerce-claim.test.ts +111 -0
- package/templates/apps/mcp/__tests__/lib/content-adapter-parity.test.ts +65 -0
- package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +188 -0
- package/templates/apps/mcp/__tests__/lib/fail-closed-tools.test.ts +165 -0
- package/templates/apps/mcp/__tests__/lib/public-workspace.test.ts +124 -0
- package/templates/apps/mcp/__tests__/list_pages.test.ts +116 -0
- package/templates/apps/mcp/__tests__/module-exclusion.test.ts +7 -1
- package/templates/apps/mcp/__tests__/parity.test.ts +10 -7
- package/templates/apps/mcp/__tests__/purchase-disabled.test.ts +89 -22
- package/templates/apps/mcp/__tests__/read_content.test.ts +322 -1
- package/templates/apps/mcp/__tests__/search_content.test.ts +105 -2
- package/templates/apps/mcp/__tests__/server.test.ts +67 -14
- package/templates/apps/mcp/__tests__/start_purchase.test.ts +252 -0
- package/templates/apps/mcp/__tests__/tools/purchase.test.ts +300 -123
- package/templates/apps/mcp/jest.config.cjs +13 -0
- package/templates/apps/mcp/package.json +2 -0
- package/templates/apps/mcp/src/abuse/index.ts +159 -24
- package/templates/apps/mcp/src/config/modules.ts +10 -5
- package/templates/apps/mcp/src/http-transport.ts +102 -29
- package/templates/apps/mcp/src/index.ts +73 -11
- package/templates/apps/mcp/src/lib/audit-single-page.ts +90 -3
- package/templates/apps/mcp/src/lib/commerce-claim.ts +94 -0
- package/templates/apps/mcp/src/lib/content-adapter.ts +113 -0
- package/templates/apps/mcp/src/lib/empty-content-adapter.ts +139 -0
- package/templates/apps/mcp/src/lib/prisma.ts +39 -0
- package/templates/apps/mcp/src/lib/public-workspace.ts +133 -0
- package/templates/apps/mcp/src/lib/stripe-tax-signal.ts +59 -0
- package/templates/apps/mcp/src/server.ts +59 -35
- package/templates/apps/mcp/src/tools/audit.ts +26 -2
- package/templates/apps/mcp/src/tools/get_business_hours.ts +4 -3
- package/templates/apps/mcp/src/tools/get_faq.ts +4 -3
- package/templates/apps/mcp/src/tools/get_locations.ts +5 -3
- package/templates/apps/mcp/src/tools/get_offerings.ts +16 -4
- package/templates/apps/mcp/src/tools/get_pricing.ts +25 -6
- package/templates/apps/mcp/src/tools/get_site_info.ts +4 -3
- package/templates/apps/mcp/src/tools/index.ts +6 -4
- package/templates/apps/mcp/src/tools/list_pages.ts +4 -3
- package/templates/apps/mcp/src/tools/purchase.ts +128 -45
- package/templates/apps/mcp/src/tools/read_content.ts +20 -6
- package/templates/apps/mcp/src/tools/search_content.ts +11 -4
- package/templates/apps/web/.env.example +71 -5
- package/templates/apps/web/CLAUDE.md +44 -0
- package/templates/apps/web/PRODUCT.md +86 -0
- package/templates/apps/web/app/.well-known/mcp.json/build-manifest.ts +18 -2
- package/templates/apps/web/app/.well-known/mcp.json/route.ts +11 -3
- package/templates/apps/web/app/[locale]/(auth)/__tests__/auth-pages.test.tsx +282 -0
- package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +515 -0
- package/templates/apps/web/app/[locale]/(auth)/forgot-password/forgot-password-card.tsx +89 -0
- package/templates/apps/web/app/[locale]/(auth)/forgot-password/page.tsx +109 -0
- package/templates/apps/web/app/[locale]/(auth)/layout.tsx +92 -0
- package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +135 -0
- package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +109 -0
- package/templates/apps/web/app/[locale]/{sign-in → (auth)/sign-in}/__tests__/page.test.tsx +48 -2
- package/templates/apps/web/app/[locale]/{sign-in → (auth)/sign-in}/page.tsx +20 -6
- package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +125 -0
- package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +96 -0
- package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +101 -0
- package/templates/apps/web/app/[locale]/(auth)/use-auth-card-flow.ts +102 -0
- package/templates/apps/web/app/[locale]/(auth)/verify-email/page.tsx +87 -0
- package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +20 -10
- package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +84 -0
- package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +58 -0
- package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +63 -8
- package/templates/apps/web/app/[locale]/(authed)/layout.tsx +18 -1
- package/templates/apps/web/app/[locale]/cancellation/page.tsx +44 -0
- package/templates/apps/web/app/[locale]/layout.tsx +133 -87
- package/templates/apps/web/app/[locale]/purchase/__tests__/cancel.test.tsx +162 -0
- package/templates/apps/web/app/[locale]/purchase/__tests__/module-scope.test.ts +68 -0
- package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +361 -0
- package/templates/apps/web/app/[locale]/purchase/cancel/page.tsx +115 -0
- package/templates/apps/web/app/[locale]/purchase/success/page.tsx +307 -0
- package/templates/apps/web/app/[locale]/returns/page.tsx +44 -0
- package/templates/apps/web/app/[locale]/shipping/page.tsx +44 -0
- package/templates/apps/web/app/api/revalidate/__tests__/route.test.ts +670 -0
- package/templates/apps/web/app/api/revalidate/route.ts +194 -0
- package/templates/apps/web/auth.ts +407 -8
- package/templates/apps/web/jest.config.cjs +8 -4
- package/templates/apps/web/lib/__tests__/auth-email.test.ts +214 -0
- package/templates/apps/web/lib/__tests__/auth-routes.test.ts +74 -0
- package/templates/apps/web/lib/__tests__/meeting-slugs.test.ts +72 -0
- package/templates/apps/web/lib/__tests__/site-theme.test.ts +135 -20
- package/templates/apps/web/lib/__tests__/structured-data.test.tsx +18 -1
- package/templates/apps/web/lib/auth-email.ts +318 -0
- package/templates/apps/web/lib/auth-env.ts +85 -0
- package/templates/apps/web/lib/auth-routes.ts +55 -0
- package/templates/apps/web/lib/meeting-slugs.ts +53 -0
- package/templates/apps/web/lib/site-brand.tsx +4 -8
- package/templates/apps/web/lib/telemetry-scrub.ts +5 -1
- package/templates/apps/web/messages/en.json +187 -0
- package/templates/apps/web/middleware.ts +1 -1
- package/templates/apps/web/package.json +2 -1
- package/templates/apps/web/src/lib/commerce-claim.ts +33 -0
- package/templates/apps/web/src/lib/commerce-sections.ts +93 -0
- package/templates/content/_site.mdx +18 -3
- package/templates/content/en/CancellationPolicyPage/cancellation.mdx +108 -0
- package/templates/content/en/ReturnsPolicyPage/returns.mdx +108 -0
- package/templates/content/en/ShippingPolicyPage/shipping.mdx +108 -0
- package/templates/database/CHANGELOG.md +149 -0
- package/templates/database/README.md +10 -3
- package/templates/database/__tests__/appointment.db.test.ts +106 -0
- package/templates/database/__tests__/artifact-content-store.db.test.ts +316 -0
- package/templates/database/__tests__/composite-fence.db.test.ts +206 -0
- package/templates/database/__tests__/fence-fan-out.db.test.ts +711 -0
- package/templates/database/__tests__/fixtures/appointment-create-probe.ts +79 -0
- package/templates/database/__tests__/fixtures/project-listing-consent-probe.ts +100 -0
- package/templates/database/__tests__/flow-workspace-key.db.test.ts +263 -0
- package/templates/database/__tests__/prefixed-ids.db.test.ts +85 -9
- package/templates/database/__tests__/project-listing-consent-at.db.test.ts +111 -0
- package/templates/database/__tests__/tenancy.test.ts +141 -0
- package/templates/database/config/schema.prisma +79 -2
- package/templates/database/content/schema.prisma +87 -11
- package/templates/database/inbox/schema.prisma +452 -9
- package/templates/database/jest.config.cjs +5 -3
- package/templates/database/migrations/20260915120000_project_listing_solution/migration.sql +15 -0
- package/templates/database/migrations/20260916120000_artifact_content_store/migration.sql +158 -0
- package/templates/database/migrations/20260917120000_callback_request_confirm/migration.sql +40 -0
- package/templates/database/migrations/20260918120000_add_appointment/migration.sql +67 -0
- package/templates/database/migrations/20260918120000_asset_metadata_columns/migration.sql +70 -0
- package/templates/database/migrations/20260919120000_flow_workspace_key/migration.sql +181 -0
- package/templates/database/migrations/20260919130000_flow_definition_admin_columns/migration.sql +172 -0
- package/templates/database/migrations/20260919130000_workspace_meetings/migration.sql +41 -0
- package/templates/database/migrations/20260919140000_inbox_workspace_key/migration.sql +185 -0
- package/templates/database/migrations/20260920120000_lead_handled_at/migration.sql +70 -0
- package/templates/database/migrations/20260920130000_lead_workspace_source_index/migration.sql +57 -0
- package/templates/database/migrations/20260921120000_deliverable_grant_workspace_key/migration.sql +68 -0
- package/templates/database/migrations/20260922120000_tenancy_fence/migration.sql +1067 -0
- package/templates/database/migrations/20260923120000_listing_capturing_magnet/migration.sql +210 -0
- package/templates/database/package.json +3 -2
- package/templates/database/tenancy.ts +86 -1
- package/templates/database/tsconfig.json +1 -0
- package/versions.json +34 -34
- package/templates/apps/api/src/routes/content/__tests__/create.test.ts +0 -253
- package/templates/apps/api/src/routes/content/__tests__/delete.test.ts +0 -215
- package/templates/apps/api/src/routes/content/__tests__/update.test.ts +0 -266
- package/templates/apps/api/src/routes/content/create.ts +0 -115
- package/templates/apps/api/src/routes/content/delete.ts +0 -82
- package/templates/apps/api/src/routes/content/update.ts +0 -112
- package/templates/apps/mcp/__tests__/create_page.test.ts +0 -202
- package/templates/apps/mcp/__tests__/delete_page.test.ts +0 -177
- package/templates/apps/mcp/__tests__/update_page.test.ts +0 -196
- package/templates/apps/mcp/src/tools/create_page.ts +0 -96
- package/templates/apps/mcp/src/tools/delete_page.ts +0 -74
- package/templates/apps/mcp/src/tools/update_page.ts +0 -92
- package/templates/apps/web/app/[locale]/sign-in/sign-in-card.tsx +0 -123
- package/templates/apps/web/public/logo-dark.svg +0 -21
- package/templates/apps/web/public/logo-light.svg +0 -21
- /package/templates/apps/web/app/[locale]/{sign-in → (auth)/sign-in}/__tests__/next-path.test.ts +0 -0
- /package/templates/apps/web/app/[locale]/{sign-in → (auth)/sign-in}/next-path.ts +0 -0
|
@@ -0,0 +1,668 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file audit-log.ts
|
|
3
|
+
* @description The agent-action audit writer (#6040, REL-017 row 5 / FEAT-084
|
|
4
|
+
* SUB-096) — `recordAgentAction`, the first production write site for
|
|
5
|
+
* `ops.AuditLog`. Writes exactly one row per agent action: tenant, actor,
|
|
6
|
+
* tool, and outcome, with personal data redacted before it can reach the
|
|
7
|
+
* stored row.
|
|
8
|
+
*
|
|
9
|
+
* ## AUDIT FAILURE DOES NOT BLOCK THE AUDITED ACTION
|
|
10
|
+
*
|
|
11
|
+
* A failed write is reported to the caller and logged at `error`; it never
|
|
12
|
+
* throws and never aborts the caller's action. At MVP the audited action is
|
|
13
|
+
* frequently already irreversible by the time this writer runs — a Stripe
|
|
14
|
+
* refund has been issued, a price has changed — so aborting the caller's
|
|
15
|
+
* request after the money moved would make the site lie to its operator
|
|
16
|
+
* about what happened. The compensating control is that the failure is
|
|
17
|
+
* loud: a typed `{ ok: false }` the caller can branch on, plus a
|
|
18
|
+
* `logger.error` line. Nothing in TypeScript FORCES a caller to read the
|
|
19
|
+
* result — `await recordAgentAction(input)` as a bare statement compiles
|
|
20
|
+
* and lints clean — so the caller issue (#6041 or SUB-097) owns branching on
|
|
21
|
+
* `ok` and raising its own alert; a lint/metric enforcing that belongs to
|
|
22
|
+
* whichever issue adds the first caller.
|
|
23
|
+
*
|
|
24
|
+
* ## WHY THIS FILE CARRIES NO `architecture.yaml` EXCEPTION
|
|
25
|
+
*
|
|
26
|
+
* `architecture.yaml`'s tenant-scope `forbidden_pattern` protects against ONE
|
|
27
|
+
* failure mode: an UN-SCOPED read of a listed tenancy/domain model — this
|
|
28
|
+
* one included — that could enumerate or leak another tenant's rows. This
|
|
29
|
+
* file does not have that failure mode, by construction rather than by
|
|
30
|
+
* convention: its write delegate (`AuditWriteClient`, below) declares only
|
|
31
|
+
* `create` — no `find*`/`update`/`delete`/`count` — so a read of this model
|
|
32
|
+
* is a COMPILE ERROR here, not a review catch. Every write goes through that
|
|
33
|
+
* delegate (`db.auditLog.create`), never the raw singleton directly, which
|
|
34
|
+
* is WHY it also satisfies the rule MECHANICALLY (the pattern is a raw-text
|
|
35
|
+
* scan over the whole file, comments included — so this paragraph is
|
|
36
|
+
* deliberately worded to describe the shape without ever writing the literal
|
|
37
|
+
* banned call adjacency itself) — the mechanical pass is a consequence of
|
|
38
|
+
* meeting the rule's intent, not a way around it. No `paths_excluded` entry
|
|
39
|
+
* was added for it (a draft of this design proposed one; it was withdrawn):
|
|
40
|
+
* that list is a capability allow-list under the `security_settings` hard
|
|
41
|
+
* floor, and this file does not need to widen it. If a later change ever
|
|
42
|
+
* inlines a direct singleton call for this model, the lint goes red on this
|
|
43
|
+
* file and a human looks — which is the intended outcome, since that change
|
|
44
|
+
* would be the first one actually capable of the failure mode the rule
|
|
45
|
+
* guards against.
|
|
46
|
+
*
|
|
47
|
+
* ## THE WRITER CANNOT VERIFY TENANT OWNERSHIP
|
|
48
|
+
*
|
|
49
|
+
* `tenant` is the full `TenantContext` (never a `Pick`) so a caller must at
|
|
50
|
+
* least have *constructed* a resolved-context-shaped value, and
|
|
51
|
+
* `workspaceId` is format-validated against `zWorkspaceId` at runtime. But
|
|
52
|
+
* an `Id<E>`'s brand is compile-time only — at runtime an id is a plain
|
|
53
|
+
* string — so this writer cannot and does not verify that the actor
|
|
54
|
+
* genuinely belongs to the workspace it is told. `tenant` MUST come from
|
|
55
|
+
* `resolveActiveTenant` (multi-tenant) or `resolveDefaultTenant` /
|
|
56
|
+
* `resolveDefaultTenantForOperator` (base) — never assembled from request
|
|
57
|
+
* input. That is a caller obligation this file cannot enforce.
|
|
58
|
+
*
|
|
59
|
+
* ## NOT GATED ON THE `commerce` LICENSE CLAIM
|
|
60
|
+
*
|
|
61
|
+
* An audit writer a license read can switch off is not an audit writer:
|
|
62
|
+
* there is no state in which the right answer to "should this write
|
|
63
|
+
* happen?" is "no." Gating stays upstream, at the caller's own
|
|
64
|
+
* `require-commerce-claim.ts` check.
|
|
65
|
+
*
|
|
66
|
+
* External dependency boundaries: `@working-theory/observability` (logger +
|
|
67
|
+
* `redactHighEntropy`); `@working-theory/ids` (id format validation +
|
|
68
|
+
* the entity registry); `node:crypto` (the id digest); `../lib/prisma.js`
|
|
69
|
+
* (the default write delegate, structurally satisfied via `AuditWriteClient`
|
|
70
|
+
* — a caller may inject its own, e.g. an interactive `$transaction` client).
|
|
71
|
+
*/
|
|
72
|
+
|
|
73
|
+
import { createHash } from "node:crypto";
|
|
74
|
+
|
|
75
|
+
import type { Prisma } from "@working-theory/database";
|
|
76
|
+
import {
|
|
77
|
+
ENTITIES,
|
|
78
|
+
idRegex,
|
|
79
|
+
zAuditLogId,
|
|
80
|
+
zWorkspaceId,
|
|
81
|
+
type Entity,
|
|
82
|
+
type Id,
|
|
83
|
+
} from "@working-theory/ids";
|
|
84
|
+
import { logger, redactHighEntropy } from "@working-theory/observability";
|
|
85
|
+
|
|
86
|
+
import { prisma } from "../lib/prisma.js";
|
|
87
|
+
|
|
88
|
+
import { isUniqueViolation, type TenantContext } from "./default-tenant.js";
|
|
89
|
+
|
|
90
|
+
// ─── Types ──────────────────────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
/** The full actor-kind vocabulary the model comments (not a DB CHECK). Only
|
|
93
|
+
* `"agent"` is ever written by this file — `"user"`/`"system"` are exported
|
|
94
|
+
* so a future writer for those actors (#3591) shares one union. */
|
|
95
|
+
export type AuditActorType = "user" | "agent" | "system";
|
|
96
|
+
|
|
97
|
+
export type AgentActionOutcome =
|
|
98
|
+
"succeeded" | "failed" | "refused" | "awaiting_approval";
|
|
99
|
+
|
|
100
|
+
/** One row as this writer assembles it — never re-exported; a caller sees
|
|
101
|
+
* only the input/output shapes below. */
|
|
102
|
+
/** `metadata`'s closed, versioned shape (D9) — declared with concrete scalar
|
|
103
|
+
* value types (never `Record<string, unknown>`) so it structurally satisfies
|
|
104
|
+
* Prisma's `InputJsonValue` under `exactOptionalPropertyTypes` — an
|
|
105
|
+
* `unknown`-valued record does not. */
|
|
106
|
+
interface AuditLogMetadata {
|
|
107
|
+
v: 1;
|
|
108
|
+
outcome: AgentActionOutcome;
|
|
109
|
+
tool: string;
|
|
110
|
+
idempotencyKey: string;
|
|
111
|
+
summary?: string;
|
|
112
|
+
failureReason?: string;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
interface AuditLogRow {
|
|
116
|
+
id: string;
|
|
117
|
+
workspaceId: string;
|
|
118
|
+
actorId: string;
|
|
119
|
+
actorType: AuditActorType;
|
|
120
|
+
action: string;
|
|
121
|
+
targetType?: string;
|
|
122
|
+
targetId?: string;
|
|
123
|
+
/** `AuditLogMetadata`'s shape, cast at the call site — Prisma's generated
|
|
124
|
+
* `InputJsonObject` requires a `[key: string]: InputJsonValue` index
|
|
125
|
+
* signature a named interface does not structurally carry. */
|
|
126
|
+
metadata: Prisma.InputJsonValue;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The one delegate this module writes through — deliberately narrower than
|
|
131
|
+
* `PrismaClient["auditLog"]`: it declares ONLY `create`, so a read (which
|
|
132
|
+
* would defeat the "cannot leak one tenant's rows to another" property) is a
|
|
133
|
+
* compile error, not a review catch. The real `prisma` singleton satisfies
|
|
134
|
+
* this structurally (checked by `pnpm type-check`); a caller running inside
|
|
135
|
+
* an interactive `$transaction` may pass its `tx` client instead, so the
|
|
136
|
+
* audit row can land in the SAME transaction as the action it records.
|
|
137
|
+
*/
|
|
138
|
+
export interface AuditWriteClient {
|
|
139
|
+
auditLog: {
|
|
140
|
+
create(args: { data: AuditLogRow }): Promise<{ id: string }>;
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Every string member is charset- and length-constrained. A value outside
|
|
146
|
+
* its constraint is an `invalid_input` refusal, never a truncation or a
|
|
147
|
+
* silent coercion — a coerced audit row is a wrong audit row.
|
|
148
|
+
*/
|
|
149
|
+
export interface RecordAgentActionInput {
|
|
150
|
+
/** MUST come from `resolveActiveTenant` / `resolveDefaultTenant` — never
|
|
151
|
+
* assembled from request input. See the file docblock. */
|
|
152
|
+
tenant: TenantContext;
|
|
153
|
+
/** <=128 chars, `/^[A-Za-z0-9_:.-]+$/`, then personal-data-scanned. */
|
|
154
|
+
actorId: string;
|
|
155
|
+
/** <=64 chars, `/^[a-z0-9_.-]+$/` — an identifier, so `action` cannot
|
|
156
|
+
* carry prose. */
|
|
157
|
+
tool: string;
|
|
158
|
+
outcome: AgentActionOutcome;
|
|
159
|
+
/** <=256 chars, `/^[A-Za-z0-9_:.-]+$/`, then personal-data-scanned.
|
|
160
|
+
* REQUIRED — an optional key would silently degrade to "no dedup" for a
|
|
161
|
+
* caller who forgets it. Stable across a replay of the same logical
|
|
162
|
+
* action (the MCP request/tool-call id, or the provider event id).
|
|
163
|
+
*
|
|
164
|
+
* MUST be process-INDEPENDENT (#6231): a value unique to one logical
|
|
165
|
+
* action across every instance, such as a client-supplied idempotency
|
|
166
|
+
* header, a provider event id, or a fresh `crypto.randomUUID()`. Never
|
|
167
|
+
* Fastify's default `request.id` — `req-<base36>` is a per-process
|
|
168
|
+
* counter that restarts at `req-1` on every fresh serverless instance,
|
|
169
|
+
* so two genuine actions on two instances can share a key. Since
|
|
170
|
+
* `deriveAuditRowId` digests every field the row carries and a caller's
|
|
171
|
+
* other digest inputs are typically constant, a shared key makes the
|
|
172
|
+
* SECOND genuine action collide on the primary key and be reported
|
|
173
|
+
* `duplicate` — a real action left unaudited. */
|
|
174
|
+
idempotencyKey: string;
|
|
175
|
+
/** <=2000 chars, NFKC-normalised, entropy- and personal-data-scanned. */
|
|
176
|
+
summary?: string;
|
|
177
|
+
/** <=2000 chars, same treatment. Provider error text lands here — hence
|
|
178
|
+
* the entropy scan (a live secret is more likely to arrive here than in
|
|
179
|
+
* `summary`). */
|
|
180
|
+
failureReason?: string;
|
|
181
|
+
/** <=32 chars, `/^[a-z][a-z0-9_]*$/`. */
|
|
182
|
+
targetType?: string;
|
|
183
|
+
/** <=128 chars; `zId`-validated against the entity registry when
|
|
184
|
+
* `targetType` names a known entity, else a generic identifier charset. */
|
|
185
|
+
targetId?: string;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export type RecordAgentActionResult =
|
|
189
|
+
| { ok: true; outcome: "recorded" | "duplicate"; id: Id<"auditLog"> }
|
|
190
|
+
| {
|
|
191
|
+
ok: false;
|
|
192
|
+
error: {
|
|
193
|
+
kind: "invalid_input" | "write_failed";
|
|
194
|
+
message: string;
|
|
195
|
+
/** ALWAYS false — one insert, no transaction, nothing partial to
|
|
196
|
+
* leave behind. */
|
|
197
|
+
persisted: false;
|
|
198
|
+
};
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The fields `deriveAuditRowId` digests, in the ONE fixed order used by
|
|
203
|
+
* every caller — every field the row will carry, so pre-empting a row
|
|
204
|
+
* requires writing a byte-identical one (D8). `summary` / `failureReason`
|
|
205
|
+
* here are the POST-REDACTION values (what will actually be stored);
|
|
206
|
+
* `idempotencyKey` is the RAW caller-supplied value, so a replay under the
|
|
207
|
+
* same key always digests identically regardless of any future redaction
|
|
208
|
+
* change.
|
|
209
|
+
*/
|
|
210
|
+
export interface AuditRowDigestInput {
|
|
211
|
+
workspaceId: string;
|
|
212
|
+
actorId: string;
|
|
213
|
+
actorType: AuditActorType;
|
|
214
|
+
action: string;
|
|
215
|
+
targetType: string | undefined;
|
|
216
|
+
targetId: string | undefined;
|
|
217
|
+
outcome: AgentActionOutcome;
|
|
218
|
+
summary: string | undefined;
|
|
219
|
+
failureReason: string | undefined;
|
|
220
|
+
idempotencyKey: string;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ─── Constants ──────────────────────────────────────────────────────────────
|
|
224
|
+
|
|
225
|
+
/** The free-text cap (`summary` / `failureReason`) — bounds both the stored
|
|
226
|
+
* row and the redaction scan's regex work. Rejected above it, not
|
|
227
|
+
* truncated. */
|
|
228
|
+
const MAX_TEXT = 2_000;
|
|
229
|
+
|
|
230
|
+
/** An MCP tool name is an identifier — this charset cannot express an `@`,
|
|
231
|
+
* and it bounds the `action` column (`"agent.commerce." + tool`). */
|
|
232
|
+
const TOOL_RE = /^[a-z0-9_.-]{1,64}$/;
|
|
233
|
+
|
|
234
|
+
/** The schema's own examples are `"workspace"`, `"lead"`, `"user"`. */
|
|
235
|
+
const TARGET_TYPE_RE = /^[a-z][a-z0-9_]{0,31}$/;
|
|
236
|
+
|
|
237
|
+
/** `actorId`'s shape is open (Q2) — an opaque, non-registry identifier. */
|
|
238
|
+
const ACTOR_ID_RE = /^[A-Za-z0-9_:.-]{1,128}$/;
|
|
239
|
+
|
|
240
|
+
/** `targetId` when `targetType` does not name a known registry entity. */
|
|
241
|
+
const TARGET_ID_FALLBACK_RE = /^[A-Za-z0-9_:-]{1,128}$/;
|
|
242
|
+
|
|
243
|
+
/** The MCP request/tool-call id or provider event id — an identifier, not
|
|
244
|
+
* prose. */
|
|
245
|
+
const IDEMPOTENCY_KEY_RE = /^[A-Za-z0-9_:.-]{1,256}$/;
|
|
246
|
+
|
|
247
|
+
/** NUL and the rest of the C0 control range. Postgres `text` cannot store
|
|
248
|
+
* U+0000 — an unvalidated NUL anywhere in a free-text member is a
|
|
249
|
+
* repeatable audit-disable switch under the fail-open policy above. */
|
|
250
|
+
// eslint-disable-next-line no-control-regex -- the control-character range is exactly what F9 must detect and refuse (a NUL in `text` fails every Postgres insert).
|
|
251
|
+
const C0_CONTROL_RE = /[\x00-\x1f]/;
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Email — RFC-ish local + domain, no nested quantifier. The domain segment
|
|
255
|
+
* is a negated class (`[^\s@]`, not `[A-Za-z0-9.-]`) so an
|
|
256
|
+
* internationalised/homoglyph domain is still bounded and redacted rather
|
|
257
|
+
* than silently admitted past the pattern.
|
|
258
|
+
*/
|
|
259
|
+
const EMAIL_RE = /[^\s@]{1,64}@[^\s@]{1,255}\.[A-Za-z]{2,24}/g;
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* International phone — an optional leading `+`, then 7-15 digits with
|
|
263
|
+
* optional space/dot/dash separators between them. No separator is also
|
|
264
|
+
* accepted (a bare digit run), which is deliberate belt-and-braces: it also
|
|
265
|
+
* catches a phone number typed with no separators at all.
|
|
266
|
+
*/
|
|
267
|
+
const PHONE_RE = /\+?\d(?:[ .-]?\d){6,14}/g;
|
|
268
|
+
|
|
269
|
+
/** Long digit runs (9+) — account- and card-shaped numbers not already
|
|
270
|
+
* caught by the phone pattern (its separators are optional, so most digit
|
|
271
|
+
* runs are already consumed above; this is the residual). */
|
|
272
|
+
const LONG_DIGIT_RUN_RE = /\d{9,}/g;
|
|
273
|
+
|
|
274
|
+
const EMAIL_MARKER = "[REDACTED:email]";
|
|
275
|
+
const PHONE_MARKER = "[REDACTED:phone]";
|
|
276
|
+
const NUMBER_MARKER = "[REDACTED:number]";
|
|
277
|
+
|
|
278
|
+
// ─── Pure helpers (D1 — directly unit-testable, no database) ───────────────
|
|
279
|
+
|
|
280
|
+
/** True when `value` names a registered `packages/ids` entity — the branch
|
|
281
|
+
* that lets `targetId` be validated against the entity's own id grammar
|
|
282
|
+
* rather than the generic fallback. */
|
|
283
|
+
function isKnownEntity(value: string): value is Entity {
|
|
284
|
+
return (ENTITIES as readonly string[]).includes(value);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Redacts personal data from a free-text value: caps (the CALLER enforces
|
|
289
|
+
* the cap as a rejection — this function assumes an already-capped input),
|
|
290
|
+
* NFKC-normalises (so a full-width or other compatibility form does not
|
|
291
|
+
* walk past a pattern that would catch its canonical twin), runs
|
|
292
|
+
* `redactHighEntropy` first (catches a live secret pasted into
|
|
293
|
+
* `failureReason` — the natural home for provider error text), then applies
|
|
294
|
+
* the three anchored, bounded personal-data patterns. Exported — directly
|
|
295
|
+
* unit-testable, and reused (as a detection predicate) for `actorId` and
|
|
296
|
+
* `idempotencyKey` below.
|
|
297
|
+
*
|
|
298
|
+
* What this does NOT catch, stated rather than implied: a postal address or
|
|
299
|
+
* a personal name in free text (no achievable regex exists across locales),
|
|
300
|
+
* an obfuscated address ("jane dot doe at example dot com"), a date of
|
|
301
|
+
* birth, or a national identifier. The allow-list (this file's input type
|
|
302
|
+
* has no member whose purpose is a buyer's identity) and the charset
|
|
303
|
+
* constraints below are the guarantee; this scan is defence-in-depth over
|
|
304
|
+
* the two members that must stay free text.
|
|
305
|
+
*/
|
|
306
|
+
export function redactPersonalData(text: string): string {
|
|
307
|
+
let out = text.normalize("NFKC");
|
|
308
|
+
out = redactHighEntropy(out);
|
|
309
|
+
out = out.replace(EMAIL_RE, EMAIL_MARKER);
|
|
310
|
+
// Long-digit-run BEFORE phone, deliberately: its unbounded `{9,}` consumes
|
|
311
|
+
// an arbitrarily-long unseparated digit run (a card/account number) in ONE
|
|
312
|
+
// match, whereas the phone pattern's bounded `{6,14}` would otherwise eat
|
|
313
|
+
// only the first 15 digits of a longer run and leave a ragged remainder.
|
|
314
|
+
// A phone number written WITH separators (spaces/dots/dashes) has no
|
|
315
|
+
// contiguous 9+ digit substring, so this pass never touches it.
|
|
316
|
+
out = out.replace(LONG_DIGIT_RUN_RE, NUMBER_MARKER);
|
|
317
|
+
out = out.replace(PHONE_RE, PHONE_MARKER);
|
|
318
|
+
return out;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** True when `redactPersonalData` would change `text` — used to REFUSE
|
|
322
|
+
* (never silently rewrite) an identifier-shaped field that happens to
|
|
323
|
+
* contain a personal-data-shaped substring (`actorId`, `idempotencyKey`). */
|
|
324
|
+
function personalDataDetected(text: string): boolean {
|
|
325
|
+
// Checked by MARKER PRESENCE, not by inequality against the input — an
|
|
326
|
+
// inequality check is a call-order-dependent accident: NFKC alone can
|
|
327
|
+
// change a string with no personal data present (a full-width form
|
|
328
|
+
// folding to its ASCII twin) with nothing to redact, and that must never
|
|
329
|
+
// read as "detected" regardless of what charset check a future caller
|
|
330
|
+
// does or doesn't run first (code review, #6040).
|
|
331
|
+
const redacted = redactPersonalData(text);
|
|
332
|
+
return (
|
|
333
|
+
redacted.includes(EMAIL_MARKER) ||
|
|
334
|
+
redacted.includes(PHONE_MARKER) ||
|
|
335
|
+
redacted.includes(NUMBER_MARKER)
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Derives the row's primary key deterministically from every field the row
|
|
341
|
+
* will carry (D8) — the mechanism that makes AC-4 (replay produces no
|
|
342
|
+
* duplicate) hold on a table whose only unique constraint is its primary
|
|
343
|
+
* key. Each field is encoded as a 1-byte presence flag, then (when present)
|
|
344
|
+
* a 4-byte big-endian UTF-8 byte length, then the UTF-8 bytes themselves —
|
|
345
|
+
* length-PREFIXED, not separator-delimited, so no component boundary is
|
|
346
|
+
* expressible inside a component (a `tool`/`idempotencyKey` pair that
|
|
347
|
+
* shifts content across the two fields' boundary digests differently,
|
|
348
|
+
* because the length prefixes differ).
|
|
349
|
+
*
|
|
350
|
+
* The sha256 digest's first 16 bytes become a uuid with the version nibble
|
|
351
|
+
* forced to `7` and the variant nibble forced to `8`, satisfying the
|
|
352
|
+
* `audit_logs_id_format` DB CHECK constraint
|
|
353
|
+
* (`database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql:158`)
|
|
354
|
+
* and `zAuditLogId`. `createdAt` is deliberately NOT a digest input (nor an
|
|
355
|
+
* insert column — the database clock supplies it) — including it would make
|
|
356
|
+
* every call mint a fresh id and destroy replay detection entirely.
|
|
357
|
+
*
|
|
358
|
+
* Widening the digest to the WHOLE row (rather than a caller-controlled
|
|
359
|
+
* subset) is what defeats an agent pre-writing a harmless decoy to suppress
|
|
360
|
+
* its real action's record: pre-empting a row now requires writing one with
|
|
361
|
+
* byte-identical content, which means the correct record already exists.
|
|
362
|
+
*/
|
|
363
|
+
export function deriveAuditRowId(input: AuditRowDigestInput): string {
|
|
364
|
+
const parts: Array<string | undefined> = [
|
|
365
|
+
input.workspaceId,
|
|
366
|
+
input.actorId,
|
|
367
|
+
input.actorType,
|
|
368
|
+
input.action,
|
|
369
|
+
input.targetType,
|
|
370
|
+
input.targetId,
|
|
371
|
+
input.outcome,
|
|
372
|
+
input.summary,
|
|
373
|
+
input.failureReason,
|
|
374
|
+
input.idempotencyKey,
|
|
375
|
+
];
|
|
376
|
+
const encoded = Buffer.concat(parts.map(encodeDigestField));
|
|
377
|
+
const digest = createHash("sha256").update(encoded).digest();
|
|
378
|
+
const bytes = Buffer.from(digest.subarray(0, 16));
|
|
379
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70; // version 7
|
|
380
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x0f) | 0x80; // variant 8 (satisfies the [89ab] CHECK)
|
|
381
|
+
const hex = bytes.toString("hex");
|
|
382
|
+
const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
383
|
+
return `audit_${uuid}`;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** One digest component: a 1-byte presence flag, then (when present) a
|
|
387
|
+
* fixed-width 4-byte length prefix plus the UTF-8 bytes. `undefined` is
|
|
388
|
+
* encoded distinctly from an empty string. */
|
|
389
|
+
function encodeDigestField(value: string | undefined): Buffer {
|
|
390
|
+
if (value === undefined) {
|
|
391
|
+
return Buffer.from([0]);
|
|
392
|
+
}
|
|
393
|
+
const bytes = Buffer.from(value, "utf8");
|
|
394
|
+
const length = Buffer.alloc(4);
|
|
395
|
+
length.writeUInt32BE(bytes.length, 0);
|
|
396
|
+
return Buffer.concat([Buffer.from([1]), length, bytes]);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** `error.code` / `error.constructor.name` only — never the message, which
|
|
400
|
+
* on this writer embeds the audit row itself (`summary`, `actorId`,
|
|
401
|
+
* `targetId`, `idempotencyKey`) via Prisma's validation-error `data`
|
|
402
|
+
* argument (N7, D10). */
|
|
403
|
+
function classifyError(error: unknown): { code: string; name: string } {
|
|
404
|
+
const code =
|
|
405
|
+
typeof error === "object" &&
|
|
406
|
+
error !== null &&
|
|
407
|
+
"code" in error &&
|
|
408
|
+
typeof (error as { code?: unknown }).code === "string"
|
|
409
|
+
? (error as { code: string }).code
|
|
410
|
+
: "unknown";
|
|
411
|
+
const name = error instanceof Error ? error.constructor.name : typeof error;
|
|
412
|
+
return { code, name };
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ─── Input validation ───────────────────────────────────────────────────────
|
|
416
|
+
|
|
417
|
+
interface ValidatedFields {
|
|
418
|
+
workspaceId: string;
|
|
419
|
+
actorId: string;
|
|
420
|
+
tool: string;
|
|
421
|
+
targetType: string | undefined;
|
|
422
|
+
targetId: string | undefined;
|
|
423
|
+
redactedSummary: string | undefined;
|
|
424
|
+
redactedFailureReason: string | undefined;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
type ValidationResult =
|
|
428
|
+
{ ok: true; value: ValidatedFields } | { ok: false; message: string };
|
|
429
|
+
|
|
430
|
+
/** Caps first (rejected, not truncated), then rejects a NUL or other C0
|
|
431
|
+
* control character (F9 — Postgres `text` cannot store U+0000), then
|
|
432
|
+
* redacts. Absent input passes through as `undefined`. */
|
|
433
|
+
function validateFreeText(
|
|
434
|
+
text: string | undefined,
|
|
435
|
+
): { ok: true; value: string | undefined } | { ok: false; message: string } {
|
|
436
|
+
if (text === undefined) {
|
|
437
|
+
return { ok: true, value: undefined };
|
|
438
|
+
}
|
|
439
|
+
if (text.length > MAX_TEXT) {
|
|
440
|
+
return { ok: false, message: `exceeds the ${MAX_TEXT}-character cap` };
|
|
441
|
+
}
|
|
442
|
+
if (C0_CONTROL_RE.test(text)) {
|
|
443
|
+
return {
|
|
444
|
+
ok: false,
|
|
445
|
+
message: "contains a NUL or other C0 control character",
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
return { ok: true, value: redactPersonalData(text) };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Validates every string member before it is digested or written (F9).
|
|
453
|
+
* Identifier-shaped members are REFUSED on a constraint violation, never
|
|
454
|
+
* coerced — a coerced audit row is a wrong audit row (D5). `actorId` and
|
|
455
|
+
* `idempotencyKey` additionally fail the personal-data scan as a REFUSAL
|
|
456
|
+
* (never a silent rewrite of an identifier field) rather than as a
|
|
457
|
+
* redaction, unlike `summary` / `failureReason`.
|
|
458
|
+
*/
|
|
459
|
+
function validateInput(input: RecordAgentActionInput): ValidationResult {
|
|
460
|
+
if (!zWorkspaceId.safeParse(input.tenant.workspaceId).success) {
|
|
461
|
+
return {
|
|
462
|
+
ok: false,
|
|
463
|
+
message: "tenant.workspaceId is not a valid workspace id",
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
if (!ACTOR_ID_RE.test(input.actorId)) {
|
|
467
|
+
return {
|
|
468
|
+
ok: false,
|
|
469
|
+
message: "actorId does not match the required identifier grammar",
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
if (personalDataDetected(input.actorId)) {
|
|
473
|
+
return {
|
|
474
|
+
ok: false,
|
|
475
|
+
message: "actorId appears to carry personal data",
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
if (!TOOL_RE.test(input.tool)) {
|
|
479
|
+
return {
|
|
480
|
+
ok: false,
|
|
481
|
+
message: "tool does not match the required identifier grammar",
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
if (!IDEMPOTENCY_KEY_RE.test(input.idempotencyKey)) {
|
|
485
|
+
return {
|
|
486
|
+
ok: false,
|
|
487
|
+
message: "idempotencyKey does not match the required identifier grammar",
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
if (personalDataDetected(input.idempotencyKey)) {
|
|
491
|
+
return {
|
|
492
|
+
ok: false,
|
|
493
|
+
message: "idempotencyKey appears to carry personal data",
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
if (
|
|
497
|
+
input.targetType !== undefined &&
|
|
498
|
+
!TARGET_TYPE_RE.test(input.targetType)
|
|
499
|
+
) {
|
|
500
|
+
return {
|
|
501
|
+
ok: false,
|
|
502
|
+
message: "targetType does not match the required identifier grammar",
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
if (input.targetId !== undefined) {
|
|
506
|
+
const targetIdRe =
|
|
507
|
+
input.targetType !== undefined && isKnownEntity(input.targetType)
|
|
508
|
+
? idRegex(input.targetType)
|
|
509
|
+
: TARGET_ID_FALLBACK_RE;
|
|
510
|
+
if (!targetIdRe.test(input.targetId)) {
|
|
511
|
+
return {
|
|
512
|
+
ok: false,
|
|
513
|
+
message:
|
|
514
|
+
"targetId does not match the required grammar for its targetType",
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const summaryCheck = validateFreeText(input.summary);
|
|
519
|
+
if (!summaryCheck.ok) {
|
|
520
|
+
return { ok: false, message: `summary ${summaryCheck.message}` };
|
|
521
|
+
}
|
|
522
|
+
const failureReasonCheck = validateFreeText(input.failureReason);
|
|
523
|
+
if (!failureReasonCheck.ok) {
|
|
524
|
+
return {
|
|
525
|
+
ok: false,
|
|
526
|
+
message: `failureReason ${failureReasonCheck.message}`,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
return {
|
|
531
|
+
ok: true,
|
|
532
|
+
value: {
|
|
533
|
+
workspaceId: input.tenant.workspaceId,
|
|
534
|
+
actorId: input.actorId,
|
|
535
|
+
tool: input.tool,
|
|
536
|
+
targetType: input.targetType,
|
|
537
|
+
targetId: input.targetId,
|
|
538
|
+
redactedSummary: summaryCheck.value,
|
|
539
|
+
redactedFailureReason: failureReasonCheck.value,
|
|
540
|
+
},
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// ─── The writer ─────────────────────────────────────────────────────────────
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Writes exactly one `audit_logs` row for one agent action. Never throws;
|
|
548
|
+
* never blocks the caller's action (see the file docblock heading). Not
|
|
549
|
+
* gated on the `commerce` license claim (see the file docblock) — gating
|
|
550
|
+
* stays upstream, at the caller's own claim check.
|
|
551
|
+
*/
|
|
552
|
+
export async function recordAgentAction(
|
|
553
|
+
input: RecordAgentActionInput,
|
|
554
|
+
db: AuditWriteClient = prisma,
|
|
555
|
+
): Promise<RecordAgentActionResult> {
|
|
556
|
+
const validated = validateInput(input);
|
|
557
|
+
if (!validated.ok) {
|
|
558
|
+
return {
|
|
559
|
+
ok: false,
|
|
560
|
+
error: {
|
|
561
|
+
kind: "invalid_input",
|
|
562
|
+
message: validated.message,
|
|
563
|
+
persisted: false,
|
|
564
|
+
},
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const {
|
|
569
|
+
workspaceId,
|
|
570
|
+
actorId,
|
|
571
|
+
tool,
|
|
572
|
+
targetType,
|
|
573
|
+
targetId,
|
|
574
|
+
redactedSummary,
|
|
575
|
+
redactedFailureReason,
|
|
576
|
+
} = validated.value;
|
|
577
|
+
const actorType: AuditActorType = "agent";
|
|
578
|
+
const action = `agent.commerce.${tool}`;
|
|
579
|
+
|
|
580
|
+
const id = deriveAuditRowId({
|
|
581
|
+
workspaceId,
|
|
582
|
+
actorId,
|
|
583
|
+
actorType,
|
|
584
|
+
action,
|
|
585
|
+
targetType,
|
|
586
|
+
targetId,
|
|
587
|
+
outcome: input.outcome,
|
|
588
|
+
summary: redactedSummary,
|
|
589
|
+
failureReason: redactedFailureReason,
|
|
590
|
+
idempotencyKey: input.idempotencyKey,
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
if (!zAuditLogId.safeParse(id).success) {
|
|
594
|
+
// Structurally unreachable given the derivation above (sha256 digest,
|
|
595
|
+
// version/variant nibbles forced) — a defensive guard, never observed
|
|
596
|
+
// to fire, kept because the format authority stays in `packages/ids`
|
|
597
|
+
// even though the derivation lives here (D8).
|
|
598
|
+
logger.error(
|
|
599
|
+
{ workspaceId, action, actorType },
|
|
600
|
+
"[audit-log] derived id failed format validation",
|
|
601
|
+
);
|
|
602
|
+
return {
|
|
603
|
+
ok: false,
|
|
604
|
+
error: {
|
|
605
|
+
kind: "write_failed",
|
|
606
|
+
message: "agent action row write failed",
|
|
607
|
+
persisted: false,
|
|
608
|
+
},
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const metadata: AuditLogMetadata = {
|
|
613
|
+
v: 1,
|
|
614
|
+
outcome: input.outcome,
|
|
615
|
+
tool,
|
|
616
|
+
idempotencyKey: input.idempotencyKey,
|
|
617
|
+
...(redactedSummary !== undefined && { summary: redactedSummary }),
|
|
618
|
+
...(redactedFailureReason !== undefined && {
|
|
619
|
+
failureReason: redactedFailureReason,
|
|
620
|
+
}),
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
const row: AuditLogRow = {
|
|
624
|
+
id,
|
|
625
|
+
workspaceId,
|
|
626
|
+
actorId,
|
|
627
|
+
actorType,
|
|
628
|
+
action,
|
|
629
|
+
...(targetType !== undefined && { targetType }),
|
|
630
|
+
...(targetId !== undefined && { targetId }),
|
|
631
|
+
|
|
632
|
+
metadata: metadata as unknown as Prisma.InputJsonValue,
|
|
633
|
+
};
|
|
634
|
+
|
|
635
|
+
try {
|
|
636
|
+
// The delegate's resolved `{ id }` is discarded deliberately — the row's
|
|
637
|
+
// id is `id` above (the digest this writer derived), never a value the
|
|
638
|
+
// database could have generated differently (code review, #6040).
|
|
639
|
+
await db.auditLog.create({ data: row });
|
|
640
|
+
return { ok: true, outcome: "recorded", id: id as Id<"auditLog"> };
|
|
641
|
+
} catch (error) {
|
|
642
|
+
if (isUniqueViolation(error)) {
|
|
643
|
+
// F10 — a replay is reported, not silent. The colliding id IS the
|
|
644
|
+
// stored row's id (that is the whole point of a deterministic PK), so
|
|
645
|
+
// no read is needed to report it.
|
|
646
|
+
logger.warn(
|
|
647
|
+
{ workspaceId, action, actorType, auditLogId: id },
|
|
648
|
+
"[audit-log] duplicate agent action row suppressed by primary key",
|
|
649
|
+
);
|
|
650
|
+
return { ok: true, outcome: "duplicate", id: id as Id<"auditLog"> };
|
|
651
|
+
}
|
|
652
|
+
const { code, name } = classifyError(error);
|
|
653
|
+
// Never `error.message` — on this writer the Prisma validation `data`
|
|
654
|
+
// argument IS the audit row (N7, D10).
|
|
655
|
+
logger.error(
|
|
656
|
+
{ workspaceId, action, actorType, errorCode: code, errorName: name },
|
|
657
|
+
"[audit-log] agent action row write failed",
|
|
658
|
+
);
|
|
659
|
+
return {
|
|
660
|
+
ok: false,
|
|
661
|
+
error: {
|
|
662
|
+
kind: "write_failed",
|
|
663
|
+
message: "agent action row write failed",
|
|
664
|
+
persisted: false,
|
|
665
|
+
},
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
}
|