@cosmicdrift/kumiko-framework 0.413.1 → 0.414.0
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/AGENTS.md +5 -2
- package/agents/api/framework-db.md +14 -3
- package/agents/api/framework-engine.md +63 -13
- package/agents/api/framework-event-store.md +14 -0
- package/agents/api/framework-ui-types.md +149 -21
- package/agents/api/renderer-web.md +93 -9
- package/agents/api/testing-helpers.md +3 -2
- package/agents/api/testing-stack.md +3 -0
- package/agents/api/types.md +205 -14
- package/agents/api.md +7 -7
- package/agents/boot-rules.md +63 -9
- package/agents/examples/api-docs.md +2 -6
- package/agents/examples/auth-mfa.md +57 -10
- package/agents/examples/chat-channels.md +2 -0
- package/agents/examples/currencies-global.md +1 -0
- package/agents/examples/env-composition.md +7 -11
- package/agents/examples/managed-pages.md +90 -1
- package/agents/examples/pwa-shell.md +210 -0
- package/agents/examples/rate-limiting.md +3 -3
- package/agents/examples/record-detail-layout.md +1537 -67
- package/agents/examples/workflow-engine.md +16 -12
- package/agents/examples.md +1 -0
- package/agents/features-index.md +4 -2
- package/agents/features.md +22 -7
- package/agents/widgets.md +19 -1
- package/dist/api/api-constants.d.ts +1 -0
- package/dist/api/api-constants.js +4 -0
- package/dist/api/auth-middleware.js +4 -3
- package/dist/api/auth-routes-shared.js +2 -1
- package/dist/api/entity-read-access.d.ts +1 -0
- package/dist/api/entity-read-access.js +18 -0
- package/dist/api/export/export-route.d.ts +6 -1
- package/dist/api/export/export-route.js +27 -1
- package/dist/api/export/export-rows.js +19 -3
- package/dist/api/routes.d.ts +2 -0
- package/dist/api/routes.js +9 -1
- package/dist/api/server-extra-routes.js +2 -1
- package/dist/api/server-feature-http-routes.d.ts +9 -0
- package/dist/api/server-feature-http-routes.js +109 -0
- package/dist/api/server-middleware.js +2 -19
- package/dist/api/server-pat-rate-limit-guard.d.ts +3 -0
- package/dist/api/server-pat-rate-limit-guard.js +19 -0
- package/dist/api/server-rate-limit-wiring.d.ts +10 -0
- package/dist/api/server-rate-limit-wiring.js +37 -0
- package/dist/api/server-routes.d.ts +4 -12
- package/dist/api/server-routes.js +12 -171
- package/dist/api/server-schema-route.d.ts +3 -0
- package/dist/api/server-schema-route.js +58 -0
- package/dist/api/server-wiring.js +2 -37
- package/dist/api/server.js +3 -1
- package/dist/compliance/override-schema.js +5 -5
- package/dist/compliance/sub-processors.js +10 -1
- package/dist/crypto/index.d.ts +1 -1
- package/dist/crypto/index.js +1 -1
- package/dist/crypto/pii-field-encryption.d.ts +2 -0
- package/dist/crypto/pii-field-encryption.js +16 -1
- package/dist/db/apply-entity-event.js +4 -0
- package/dist/db/bun-sql-connection-codes.d.ts +1 -0
- package/dist/db/bun-sql-connection-codes.js +7 -0
- package/dist/db/collect-table-metas.js +4 -1
- package/dist/db/config-seed.js +1 -1
- package/dist/db/derived-field-sql.js +15 -13
- package/dist/db/derived-related-sql.d.ts +2 -2
- package/dist/db/derived-related-sql.js +4 -2
- package/dist/db/dialect.d.ts +3 -0
- package/dist/db/dialect.js +1 -3
- package/dist/db/driver-row-coercion.js +2 -2
- package/dist/db/driver-value-preparation.js +1 -1
- package/dist/db/eagerload.js +15 -12
- package/dist/db/entity-table-meta.d.ts +2 -0
- package/dist/db/entity-table-meta.js +7 -0
- package/dist/db/event-store-executor-context.js +13 -8
- package/dist/db/event-store-executor-read-aggregate-currencies.js +2 -2
- package/dist/db/event-store-executor-read-aggregate.js +2 -2
- package/dist/db/event-store-executor-read-filter.d.ts +4 -0
- package/dist/db/event-store-executor-read-filter.js +28 -11
- package/dist/db/event-store-executor-read-search.d.ts +1 -0
- package/dist/db/event-store-executor-read-search.js +6 -6
- package/dist/db/event-store-executor-read-sort.js +3 -3
- package/dist/db/event-store-executor-read-where.js +14 -5
- package/dist/db/event-store-executor-read.js +7 -7
- package/dist/db/event-store-executor-write.js +50 -95
- package/dist/db/executor-managed-tables.js +4 -1
- package/dist/db/index.d.ts +4 -2
- package/dist/db/index.js +4 -2
- package/dist/db/known-table-names.d.ts +1 -0
- package/dist/db/known-table-names.js +7 -5
- package/dist/db/list-aggregate-labels.d.ts +1 -0
- package/dist/db/list-aggregate-labels.js +9 -1
- package/dist/db/migrate-generator.js +23 -4
- package/dist/db/migrate-rls-diff.d.ts +1 -0
- package/dist/db/migrate-rls-diff.js +15 -1
- package/dist/db/migrate-runner.js +2 -2
- package/dist/db/money.d.ts +1 -1
- package/dist/db/money.js +1 -4
- package/dist/db/parent-ref-clause.d.ts +6 -2
- package/dist/db/parent-ref-clause.js +76 -23
- package/dist/db/parent-ref-global-hosts.d.ts +20 -0
- package/dist/db/parent-ref-global-hosts.js +47 -0
- package/dist/db/production-schema-command-hint.d.ts +1 -0
- package/dist/db/production-schema-command-hint.js +3 -0
- package/dist/db/queries/backfill-pii.js +55 -29
- package/dist/db/queries/ddl.js +13 -2
- package/dist/db/queries/event-store-open-streams.d.ts +15 -0
- package/dist/db/queries/event-store-open-streams.js +33 -0
- package/dist/db/queries/event-store-payload-scrub.d.ts +5 -0
- package/dist/db/queries/event-store-payload-scrub.js +11 -0
- package/dist/db/queries/event-store.js +0 -1
- package/dist/db/queries/raw-sql.js +0 -1
- package/dist/db/queries/rebuild-rls-guard.d.ts +2 -1
- package/dist/db/queries/rebuild-rls-guard.js +24 -11
- package/dist/db/queries/rls-boot-catalog.d.ts +1 -0
- package/dist/db/queries/rls-boot-catalog.js +13 -8
- package/dist/db/queries/rls-shape.d.ts +2 -1
- package/dist/db/queries/rls-shape.js +10 -0
- package/dist/db/queries/session-advisory-lock.js +2 -1
- package/dist/db/queries/test-stack.js +7 -7
- package/dist/db/query.js +16 -11
- package/dist/db/rebuild-marker.js +11 -2
- package/dist/db/render-rls-ddl.d.ts +2 -0
- package/dist/db/render-rls-ddl.js +16 -11
- package/dist/db/replay-migration-sql.js +1 -1
- package/dist/db/row-level-security-boot-check.js +18 -5
- package/dist/db/row-level-security-connection.js +25 -12
- package/dist/db/row-level-security-scope.d.ts +2 -1
- package/dist/db/row-level-security-scope.js +9 -5
- package/dist/db/sql-identifier.d.ts +1 -0
- package/dist/db/sql-identifier.js +3 -0
- package/dist/db/system-tenant-read-db.d.ts +5 -0
- package/dist/db/system-tenant-read-db.js +28 -0
- package/dist/db/table-builder.d.ts +3 -1
- package/dist/db/table-builder.js +18 -8
- package/dist/db/table-info.d.ts +1 -2
- package/dist/db/table-introspection.d.ts +3 -0
- package/dist/db/table-introspection.js +6 -0
- package/dist/db/table-push.d.ts +1 -0
- package/dist/db/table-push.js +7 -1
- package/dist/db/tenant-db-runner.d.ts +3 -0
- package/dist/db/tenant-db-runner.js +19 -1
- package/dist/db/transaction-serialization.d.ts +1 -0
- package/dist/db/transaction-serialization.js +20 -3
- package/dist/db/where-clause.js +11 -2
- package/dist/db/write-ownership-failures.d.ts +25 -0
- package/dist/db/write-ownership-failures.js +82 -0
- package/dist/engine/boot-validator/boot-check.js +7 -1
- package/dist/engine/boot-validator/boot-phases-app.js +5 -5
- package/dist/engine/boot-validator/boot-phases.js +3 -2
- package/dist/engine/boot-validator/boot-rules.d.ts +293 -26
- package/dist/engine/boot-validator/boot-rules.js +4 -0
- package/dist/engine/boot-validator/bundled-lists-table.js +2 -2
- package/dist/engine/boot-validator/card-meta-overflow.js +1 -0
- package/dist/engine/boot-validator/config-deps.d.ts +0 -1
- package/dist/engine/boot-validator/config-deps.js +0 -28
- package/dist/engine/boot-validator/config-key-rules.d.ts +0 -15
- package/dist/engine/boot-validator/config-key-rules.js +0 -15
- package/dist/engine/boot-validator/dashboard-screen-target.d.ts +22 -0
- package/dist/engine/boot-validator/dashboard-screen-target.js +20 -0
- package/dist/engine/boot-validator/dashboard-stat-navigate.d.ts +1 -0
- package/dist/engine/boot-validator/dashboard-stat-navigate.js +25 -17
- package/dist/engine/boot-validator/definition-webhook-events-rules.d.ts +5 -0
- package/dist/engine/boot-validator/definition-webhook-events-rules.js +5 -0
- package/dist/engine/boot-validator/derived-sql-fields.js +1 -2
- package/dist/engine/boot-validator/entity-declaration-rules.d.ts +5 -0
- package/dist/engine/boot-validator/entity-declaration-rules.js +5 -0
- package/dist/engine/boot-validator/entity-list-screens.d.ts +1 -0
- package/dist/engine/boot-validator/entity-list-screens.js +33 -6
- package/dist/engine/boot-validator/entity-structure-rules.d.ts +5 -0
- package/dist/engine/boot-validator/entity-structure-rules.js +5 -0
- package/dist/engine/boot-validator/list-column-layout.js +10 -6
- package/dist/engine/boot-validator/list-row-guidance-rules.d.ts +67 -0
- package/dist/engine/boot-validator/list-row-guidance-rules.js +67 -0
- package/dist/engine/boot-validator/list-row-guidance.d.ts +20 -0
- package/dist/engine/boot-validator/list-row-guidance.js +129 -0
- package/dist/engine/boot-validator/list-sort-summary-rules.d.ts +42 -0
- package/dist/engine/boot-validator/list-sort-summary-rules.js +42 -0
- package/dist/engine/boot-validator/list-sort-summary.d.ts +5 -0
- package/dist/engine/boot-validator/list-sort-summary.js +149 -0
- package/dist/engine/boot-validator/list-table-options.js +15 -1
- package/dist/engine/boot-validator/list-table-rules.d.ts +10 -5
- package/dist/engine/boot-validator/list-table-rules.js +10 -5
- package/dist/engine/boot-validator/list-toolbar-options.d.ts +10 -0
- package/dist/engine/boot-validator/list-toolbar-options.js +31 -0
- package/dist/engine/boot-validator/named-filter-rules.d.ts +32 -2
- package/dist/engine/boot-validator/named-filter-rules.js +32 -2
- package/dist/engine/boot-validator/ownership.js +10 -1
- package/dist/engine/boot-validator/parent-ref.js +87 -50
- package/dist/engine/boot-validator/projection-list-screens.d.ts +1 -0
- package/dist/engine/boot-validator/projection-list-screens.js +31 -1
- package/dist/engine/boot-validator/query-output-columns.js +62 -9
- package/dist/engine/boot-validator/query-output-guidance.d.ts +7 -0
- package/dist/engine/boot-validator/query-output-guidance.js +39 -0
- package/dist/engine/boot-validator/query-refs.js +24 -1
- package/dist/engine/boot-validator/row-decoration.d.ts +11 -0
- package/dist/engine/boot-validator/row-decoration.js +16 -0
- package/dist/engine/boot-validator/screens-dashboard-links.d.ts +10 -0
- package/dist/engine/boot-validator/screens-dashboard-links.js +36 -0
- package/dist/engine/boot-validator/screens-dashboard-narrow.d.ts +4 -0
- package/dist/engine/boot-validator/screens-dashboard-narrow.js +211 -0
- package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +84 -4
- package/dist/engine/boot-validator/screens-dashboard-rules.js +84 -4
- package/dist/engine/boot-validator/screens-dashboard.js +29 -7
- package/dist/engine/boot-validator/screens-kind-entity-list.js +32 -27
- package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.d.ts +3 -0
- package/dist/engine/boot-validator/screens-kind-projection-detail-guidance.js +46 -0
- package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +20 -0
- package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +20 -0
- package/dist/engine/boot-validator/screens-kind-projection-detail.js +2 -0
- package/dist/engine/boot-validator/screens-kind-projection-list.js +4 -0
- package/dist/engine/boot-validator/screens-kind-rules.d.ts +25 -0
- package/dist/engine/boot-validator/screens-kind-rules.js +25 -0
- package/dist/engine/boot-validator/screens-lists.d.ts +8 -2
- package/dist/engine/boot-validator/screens-lists.js +19 -3
- package/dist/engine/boot-validator/screens.js +1 -1
- package/dist/engine/boot-validator/sort-nulls.d.ts +2 -0
- package/dist/engine/boot-validator/sort-nulls.js +15 -0
- package/dist/engine/boot-validator/zod-shape.d.ts +2 -1
- package/dist/engine/boot-validator/zod-shape.js +19 -1
- package/dist/engine/build-app-schema.js +4 -0
- package/dist/engine/config-helpers.d.ts +1 -2
- package/dist/engine/config-helpers.js +6 -7
- package/dist/engine/define-feature.js +1 -0
- package/dist/engine/define-handler.d.ts +1 -0
- package/dist/engine/define-handler.js +4 -2
- package/dist/engine/definition-violations.js +2 -2
- package/dist/engine/entity-handlers.js +3 -8
- package/dist/engine/entity-list-runtime-options.js +9 -8
- package/dist/engine/factories.d.ts +2 -0
- package/dist/engine/feature-config-events-jobs.js +1 -0
- package/dist/engine/feature-entity-handlers.js +5 -2
- package/dist/engine/field-access.d.ts +1 -1
- package/dist/engine/field-access.js +7 -10
- package/dist/engine/find-entity.js +3 -3
- package/dist/engine/form-derivations.js +3 -3
- package/dist/engine/index.d.ts +3 -3
- package/dist/engine/index.js +2 -2
- package/dist/engine/named-filter-roles.d.ts +3 -0
- package/dist/engine/named-filter-roles.js +23 -0
- package/dist/engine/pipeline.js +0 -1
- package/dist/engine/project-app-schema-for-roles.js +17 -2
- package/dist/engine/qualified-name.js +0 -1
- package/dist/engine/registry-facade.js +1 -2
- package/dist/engine/registry-state.d.ts +1 -1
- package/dist/engine/registry-state.js +5 -2
- package/dist/engine/registry-validate.js +2 -1
- package/dist/engine/resolve-named-list-filters.js +5 -2
- package/dist/engine/schema-builder.js +6 -10
- package/dist/engine/screen-helpers.d.ts +12 -0
- package/dist/engine/screen-helpers.js +17 -1
- package/dist/engine/soft-delete-cleanup.js +1 -5
- package/dist/engine/state-machine.js +0 -1
- package/dist/engine/steps/_database-clock.d.ts +2 -0
- package/dist/engine/steps/_database-clock.js +6 -0
- package/dist/engine/steps/compute.js +1 -1
- package/dist/engine/steps/retry.js +5 -1
- package/dist/engine/steps/return.js +0 -1
- package/dist/engine/steps/wait-for-event.js +2 -1
- package/dist/engine/steps/wait.js +2 -1
- package/dist/engine/system-user.d.ts +2 -2
- package/dist/engine/system-user.js +2 -2
- package/dist/engine/types/handlers.d.ts +1 -1
- package/dist/engine/types/handlers.js +1 -1
- package/dist/engine/types/screen.d.ts +1 -1
- package/dist/engine/types/screen.js +1 -1
- package/dist/engine/webhook-contracts.d.ts +2 -3
- package/dist/engine/webhook-contracts.js +2 -25
- package/dist/engine/webhook-events.js +48 -29
- package/dist/engine/webhook-payload-strictness.d.ts +7 -0
- package/dist/engine/webhook-payload-strictness.js +53 -0
- package/dist/env/_zod-introspect.d.ts +1 -0
- package/dist/env/dry-run.d.ts +1 -1
- package/dist/env/dry-run.js +1 -1
- package/dist/env/field-meta.d.ts +4 -0
- package/dist/env/field-meta.js +67 -0
- package/dist/env/field-rules.d.ts +9 -0
- package/dist/env/field-rules.js +46 -0
- package/dist/env/index.d.ts +3 -3
- package/dist/env/index.js +16 -71
- package/dist/env/internals.d.ts +3 -0
- package/dist/env/internals.js +1 -2
- package/dist/env/required-env.d.ts +3 -1
- package/dist/env/required-env.js +5 -2
- package/dist/errors/serialize.js +2 -2
- package/dist/errors/write-error-info.js +0 -2
- package/dist/es-ops/operations-schema.js +18 -7
- package/dist/event-store/admin-api.js +3 -3
- package/dist/event-store/event-store.js +0 -3
- package/dist/event-store/index.d.ts +1 -0
- package/dist/event-store/index.js +1 -0
- package/dist/event-store/transfer.js +1 -1
- package/dist/files/assert-file-refs-belong-to-tenant.d.ts +2 -1
- package/dist/files/assert-file-refs-belong-to-tenant.js +15 -13
- package/dist/files/bind-pending-file-refs.d.ts +3 -1
- package/dist/files/bind-pending-file-refs.js +54 -27
- package/dist/files/copy-pending-file-refs-to-tenant.js +7 -3
- package/dist/files/create-file-ref.d.ts +4 -1
- package/dist/files/create-file-ref.js +14 -3
- package/dist/files/default-file-guard.js +4 -1
- package/dist/files/file-claim.d.ts +6 -0
- package/dist/files/file-claim.js +17 -0
- package/dist/files/file-field-slots.d.ts +2 -0
- package/dist/files/file-field-slots.js +28 -0
- package/dist/files/file-ref-entity.d.ts +3 -0
- package/dist/files/file-ref-entity.js +2 -0
- package/dist/files/file-ref-table.d.ts +3 -0
- package/dist/files/file-routes.d.ts +4 -1
- package/dist/files/file-routes.js +80 -16
- package/dist/files/in-memory-provider.d.ts +1 -1
- package/dist/files/in-memory-provider.js +2 -1
- package/dist/files/index.d.ts +1 -1
- package/dist/files/index.js +1 -1
- package/dist/files/invalid-file-ref-error.d.ts +2 -0
- package/dist/files/invalid-file-ref-error.js +15 -0
- package/dist/files/local-provider.js +9 -2
- package/dist/files/provider-resolver.js +1 -1
- package/dist/files/rebind-file-ref.d.ts +3 -2
- package/dist/files/rebind-file-ref.js +24 -18
- package/dist/files/resolve-file-handles.d.ts +13 -0
- package/dist/files/resolve-file-handles.js +57 -0
- package/dist/files/storage-tracking.d.ts +1 -1
- package/dist/files/storage-tracking.js +5 -2
- package/dist/files/sweep-stale-pending-file-refs.js +10 -4
- package/dist/files/types.d.ts +4 -0
- package/dist/files/types.js +10 -0
- package/dist/files/upload-field-resolution.d.ts +1 -0
- package/dist/files/upload-field-resolution.js +16 -2
- package/dist/files/upload-ledger.js +1 -1
- package/dist/i18n/required-surface-guidance-keys.d.ts +3 -0
- package/dist/i18n/required-surface-guidance-keys.js +9 -0
- package/dist/i18n/required-surface-keys.js +19 -4
- package/dist/internal/boot-rule-table-expectations.d.ts +2 -0
- package/dist/internal/boot-rule-table-expectations.js +29 -0
- package/dist/internal/row-level-security.d.ts +1 -0
- package/dist/internal/row-level-security.js +1 -0
- package/dist/internal/testing.d.ts +1 -0
- package/dist/internal/testing.js +1 -0
- package/dist/jobs/index.d.ts +1 -0
- package/dist/jobs/index.js +1 -0
- package/dist/jobs/job-load-events.d.ts +10 -0
- package/dist/jobs/job-load-events.js +12 -0
- package/dist/jobs/job-runner-context.js +6 -158
- package/dist/jobs/job-runner-dispatch.d.ts +7 -0
- package/dist/jobs/job-runner-dispatch.js +57 -0
- package/dist/jobs/job-runner-event-triggers.js +18 -9
- package/dist/jobs/job-runner-execution.js +2 -2
- package/dist/jobs/job-runner-facets.d.ts +48 -0
- package/dist/jobs/job-runner-facets.js +156 -0
- package/dist/jobs/job-runner-gates.js +19 -11
- package/dist/jobs/job-runner-helpers.d.ts +5 -1
- package/dist/jobs/job-runner-helpers.js +18 -3
- package/dist/jobs/job-runner-scope.d.ts +1 -0
- package/dist/jobs/job-runner-scope.js +2 -0
- package/dist/jobs/job-runner-tenant-cap-lock.d.ts +2 -0
- package/dist/jobs/job-runner-tenant-cap-lock.js +30 -0
- package/dist/jobs/job-runner.js +31 -70
- package/dist/jobs/obliterate-job-queues.d.ts +6 -0
- package/dist/jobs/obliterate-job-queues.js +23 -0
- package/dist/lifecycle/lifecycle.js +1 -1
- package/dist/migrations/event-header-scrub.d.ts +11 -0
- package/dist/migrations/event-header-scrub.js +33 -0
- package/dist/migrations/event-payload-scrub.d.ts +1 -1
- package/dist/migrations/event-payload-scrub.js +36 -4
- package/dist/migrations/index.d.ts +1 -0
- package/dist/migrations/index.js +2 -0
- package/dist/migrations/kumiko-drift.d.ts +5 -2
- package/dist/migrations/kumiko-drift.js +51 -14
- package/dist/migrations/pending-rebuilds.js +4 -5
- package/dist/observability/sensitive-filter.js +0 -12
- package/dist/pipeline/aggregate-type-removal.js +17 -4
- package/dist/pipeline/context-services.d.ts +2 -0
- package/dist/pipeline/context-services.js +5 -2
- package/dist/pipeline/dispatch-batch.js +4 -3
- package/dist/pipeline/dispatch-context-helpers.d.ts +11 -0
- package/dist/pipeline/dispatch-context-helpers.js +58 -0
- package/dist/pipeline/dispatch-nested-write.d.ts +7 -0
- package/dist/pipeline/dispatch-nested-write.js +119 -0
- package/dist/pipeline/dispatch-query.js +10 -3
- package/dist/pipeline/dispatch-scope.js +4 -3
- package/dist/pipeline/dispatch-shared.d.ts +2 -6
- package/dist/pipeline/dispatch-shared.js +6 -38
- package/dist/pipeline/dispatch-write.d.ts +0 -1
- package/dist/pipeline/dispatch-write.js +3 -302
- package/dist/pipeline/dispatcher-utils.js +6 -0
- package/dist/pipeline/effective-system-scope.d.ts +3 -0
- package/dist/pipeline/effective-system-scope.js +22 -0
- package/dist/pipeline/event-dispatcher-delivery.d.ts +1 -0
- package/dist/pipeline/event-dispatcher-delivery.js +17 -9
- package/dist/pipeline/event-dispatcher.d.ts +4 -1
- package/dist/pipeline/event-dispatcher.js +6 -7
- package/dist/pipeline/handler-context-auth.d.ts +3 -2
- package/dist/pipeline/handler-context-auth.js +3 -4
- package/dist/pipeline/handler-context-db.js +11 -4
- package/dist/pipeline/handler-context-dispatch.js +2 -2
- package/dist/pipeline/handler-context-events.d.ts +8 -3
- package/dist/pipeline/handler-context-events.js +20 -65
- package/dist/pipeline/handler-context-member-resolution.js +16 -8
- package/dist/pipeline/handler-context-notify.d.ts +1 -0
- package/dist/pipeline/handler-context-notify.js +2 -0
- package/dist/pipeline/handler-context-phase-denials.js +3 -2
- package/dist/pipeline/handler-context-projection.d.ts +3 -0
- package/dist/pipeline/handler-context-projection.js +39 -0
- package/dist/pipeline/handler-context-scope.d.ts +1 -1
- package/dist/pipeline/handler-context-scope.js +14 -2
- package/dist/pipeline/index.d.ts +1 -1
- package/dist/pipeline/index.js +1 -1
- package/dist/pipeline/lifecycle-pipeline.d.ts +1 -0
- package/dist/pipeline/lifecycle-pipeline.js +7 -4
- package/dist/pipeline/member-reader.js +4 -2
- package/dist/pipeline/msp-rebuild.js +1 -1
- package/dist/pipeline/nested-write-parent-guard.d.ts +5 -0
- package/dist/pipeline/nested-write-parent-guard.js +81 -0
- package/dist/pipeline/projection-rebuild.d.ts +2 -0
- package/dist/pipeline/projection-rebuild.js +16 -7
- package/dist/pipeline/projection-state.js +4 -6
- package/dist/pipeline/system-hooks.js +36 -6
- package/dist/pipeline/write-result-masking.js +31 -3
- package/dist/pipeline/write-transition-guard.d.ts +7 -0
- package/dist/pipeline/write-transition-guard.js +95 -0
- package/dist/schema-cli/shared.d.ts +2 -0
- package/dist/schema-cli/shared.js +4 -2
- package/dist/schema-cli/validate-command.js +43 -28
- package/dist/search/meilisearch-adapter.js +14 -9
- package/dist/search/reindex-entity.d.ts +2 -0
- package/dist/search/reindex-entity.js +32 -4
- package/dist/search/reindex-tenants-search.js +20 -4
- package/dist/time/tz-context.js +1 -1
- package/dist/ui-types/card-column-roles.d.ts +4 -0
- package/dist/ui-types/card-column-roles.js +6 -3
- package/dist/ui-types/index.d.ts +2 -2
- package/dist/ui-types/index.js +1 -1
- package/dist/utils/ids.js +0 -1
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js +1 -0
- package/dist/utils/return-path-limit.d.ts +1 -0
- package/dist/utils/return-path-limit.js +1 -0
- package/package.json +5 -3
- package/presets/biome-app.json +39 -21
- package/presets/biome-plugins/admin-api.grit +10 -0
- package/presets/biome-plugins/error-reasons.grit +53 -0
- package/presets/biome-plugins/es-literal-writes-tests.grit +18 -0
- package/presets/biome-plugins/es-literal-writes.grit +22 -0
- package/presets/biome-plugins/i18n-locale-terminology-de.grit +15 -0
- package/presets/biome-plugins/i18n-locale-terminology-romance.grit +10 -0
- package/presets/biome-plugins/no-create-test-dispatcher.grit +5 -0
- package/presets/biome-plugins/no-css-properties-type.grit +7 -0
- package/presets/biome-plugins/no-date-api.grit +9 -0
- package/presets/biome-plugins/no-direct-fetch.grit +16 -0
- package/presets/biome-plugins/no-direct-fs.grit +16 -0
- package/presets/biome-plugins/no-external-font-cdn-css.grit +9 -0
- package/presets/biome-plugins/no-external-font-cdn.grit +12 -0
- package/presets/biome-plugins/no-raw-hooks.grit +10 -0
- package/presets/biome-plugins/no-same-folder-barrel-import.grit +11 -0
- package/presets/biome-plugins/no-screen-container-classes.grit +7 -0
- package/presets/biome-plugins/no-skipped-or-retried-tests.grit +34 -0
- package/presets/biome-plugins/no-temporal-polyfill-require.grit +10 -0
- package/presets/biome-plugins/raw-html-in-web.grit +40 -0
- package/presets/biome-plugins/raw-ui-in-app.grit +142 -0
- package/presets/biome-plugins/restricted-event-store-symbols.grit +18 -0
- package/presets/biome-plugins/test-title.grit +20 -0
- package/presets/biome-plugins/unsafe-json-parse.grit +6 -0
- package/presets/biome-rules.json +465 -0
- package/src/changes.json +309 -0
- package/dist/engine/minor-units.d.ts +0 -2
- package/dist/engine/minor-units.js +0 -8
|
@@ -287,6 +287,14 @@ import { createInMemorySuspendedRunFetcher } from "../postgres-resume-loop";
|
|
|
287
287
|
import { runResumeLoop, type SuspendableRun } from "../resume-loop";
|
|
288
288
|
import { startAndRunWorkflow } from "../workflow-runner";
|
|
289
289
|
|
|
290
|
+
// No Postgres in-memory: wait steps read their wake time from this stand-in for the database clock.
|
|
291
|
+
function makeAppendOnlyCtx() {
|
|
292
|
+
return {
|
|
293
|
+
events: { unsafeAppend: mock().mockResolvedValue(undefined) },
|
|
294
|
+
db: { databaseNow: async () => new Date("2031-03-04T05:06:07.000Z") },
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
290
298
|
function makeWaitWorkflow(name: string) {
|
|
291
299
|
return defineWorkflow({
|
|
292
300
|
name,
|
|
@@ -325,7 +333,7 @@ describe("workflow-engine", () => {
|
|
|
325
333
|
});
|
|
326
334
|
|
|
327
335
|
it("webhook-delivery completes with exactly one dispatch request", async () => {
|
|
328
|
-
const ctx =
|
|
336
|
+
const ctx = makeAppendOnlyCtx();
|
|
329
337
|
|
|
330
338
|
const result = await startAndRunWorkflow({
|
|
331
339
|
runId: "wf-webhook-delivery-1",
|
|
@@ -366,10 +374,6 @@ describe("workflow-engine", () => {
|
|
|
366
374
|
});
|
|
367
375
|
|
|
368
376
|
describe("workflow-runner", () => {
|
|
369
|
-
function makeAppendOnlyCtx() {
|
|
370
|
-
return { events: { unsafeAppend: mock().mockResolvedValue(undefined) } };
|
|
371
|
-
}
|
|
372
|
-
|
|
373
377
|
it("startAndRunWorkflow writes run.started with Q7 snapshot fingerprint, then runs the pipeline to completion when no suspension", async () => {
|
|
374
378
|
const workflow = defineWorkflow({
|
|
375
379
|
name: "demo-sync",
|
|
@@ -453,7 +457,7 @@ describe("workflow-runner", () => {
|
|
|
453
457
|
|
|
454
458
|
describe("userOnboardingWorkflow (end-to-end, in-memory)", () => {
|
|
455
459
|
it("suspends on the first wait, then resume-loop runs it through to completion", async () => {
|
|
456
|
-
const ctx =
|
|
460
|
+
const ctx = makeAppendOnlyCtx();
|
|
457
461
|
const trigger = {
|
|
458
462
|
aggregateId: "agg_user_42",
|
|
459
463
|
type: "user.signed-up",
|
|
@@ -516,7 +520,7 @@ describe("userOnboardingWorkflow (end-to-end, in-memory)", () => {
|
|
|
516
520
|
definitionFingerprint: waitingCall.payload["definitionFingerprint"] as string,
|
|
517
521
|
};
|
|
518
522
|
|
|
519
|
-
const resumeCtx =
|
|
523
|
+
const resumeCtx = makeAppendOnlyCtx();
|
|
520
524
|
const count = await runResumeLoop(
|
|
521
525
|
createInMemorySuspendedRunFetcher([suspendedRun]),
|
|
522
526
|
resumeCtx as never,
|
|
@@ -542,7 +546,7 @@ describe("userOnboardingWorkflow (end-to-end, in-memory)", () => {
|
|
|
542
546
|
});
|
|
543
547
|
|
|
544
548
|
it("not-engaged path picks the reminder branch", async () => {
|
|
545
|
-
const ctx =
|
|
549
|
+
const ctx = makeAppendOnlyCtx();
|
|
546
550
|
const trigger = {
|
|
547
551
|
aggregateId: "agg_user_cold",
|
|
548
552
|
type: "user.signed-up",
|
|
@@ -568,7 +572,7 @@ describe("userOnboardingWorkflow (end-to-end, in-memory)", () => {
|
|
|
568
572
|
triggerEvent: trigger as never,
|
|
569
573
|
definitionFingerprint: waiting.payload["definitionFingerprint"] as string,
|
|
570
574
|
};
|
|
571
|
-
const resumeCtx =
|
|
575
|
+
const resumeCtx = makeAppendOnlyCtx();
|
|
572
576
|
await runResumeLoop(createInMemorySuspendedRunFetcher([suspendedRun]), resumeCtx as never);
|
|
573
577
|
|
|
574
578
|
const reminderMail = resumeCtx.events.unsafeAppend.mock.calls[1]![0] as {
|
|
@@ -722,7 +726,7 @@ describe("cron-scheduler", () => {
|
|
|
722
726
|
steps: stepsPipeline(({ r }) => [r.step.return({ isSuccess: true, data: undefined })]),
|
|
723
727
|
});
|
|
724
728
|
|
|
725
|
-
const handlerCtx =
|
|
729
|
+
const handlerCtx = makeAppendOnlyCtx();
|
|
726
730
|
const lastRuns = new Map<string, Temporal.Instant>();
|
|
727
731
|
const lastRun = Temporal.Instant.from("2025-05-31T08:00:00Z");
|
|
728
732
|
lastRuns.set("test-daily", lastRun);
|
|
@@ -770,7 +774,7 @@ describe("resume-loop", () => {
|
|
|
770
774
|
};
|
|
771
775
|
|
|
772
776
|
const fetchRuns = createInMemorySuspendedRunFetcher([suspendedRun]);
|
|
773
|
-
const handlerCtx =
|
|
777
|
+
const handlerCtx = makeAppendOnlyCtx();
|
|
774
778
|
|
|
775
779
|
const count = await runResumeLoop(fetchRuns, handlerCtx as never);
|
|
776
780
|
|
|
@@ -804,7 +808,7 @@ describe("resume-loop", () => {
|
|
|
804
808
|
};
|
|
805
809
|
|
|
806
810
|
const fetchRuns = createInMemorySuspendedRunFetcher([suspendedRun]);
|
|
807
|
-
const handlerCtx =
|
|
811
|
+
const handlerCtx = makeAppendOnlyCtx();
|
|
808
812
|
|
|
809
813
|
const count = await runResumeLoop(fetchRuns, handlerCtx as never);
|
|
810
814
|
|
package/agents/examples.md
CHANGED
|
@@ -62,6 +62,7 @@
|
|
|
62
62
|
| `pipeline-basics` | M.1 Tier-1 step-vocabulary showcase: every step in one inventory-management feature (aggregate.{create,update,appendEvent}, read.{findOne,findMany}, branch, forEach, compute, return, unsafeProjection{Upsert,Delete}). | `examples/pipeline-basics.md` |
|
|
63
63
|
| `prod-boot-options` | runProdApp boot options: mail, kmsMode, fileStorage, demoMode and signal handling declared as options instead of hand-wired in bin/main.ts. | `examples/prod-boot-options.md` |
|
|
64
64
|
| `public-share-token` | Generic share-token entity: mint hash-stored token, anonymous read-by-token with IP rate-limit. | `examples/public-share-token.md` |
|
|
65
|
+
| `pwa-shell` | pwa option on runProdApp and the dev server: web manifest, generated service worker with an offline app shell and a one-time install hint. | `examples/pwa-shell.md` |
|
|
65
66
|
| `rate-limiting` | End-to-end rate limiting: L1 global-IP + L2 auth-endpoints + L3 handler opt-in. | `examples/rate-limiting.md` |
|
|
66
67
|
| `realtime-sse` | Server-sent events demo. Goodbye F5. | `examples/realtime-sse.md` |
|
|
67
68
|
| `record-detail-layout` | projectionDetail record header, metrics band, and layout.mode: "tabs" — an order screen with two relatedList tabs and a fields tab. | `examples/record-detail-layout.md` |
|
package/agents/features-index.md
CHANGED
|
@@ -42,6 +42,8 @@ One entry per feature a package ships: purpose, import of its factory, required
|
|
|
42
42
|
`import { createChannelTeamsFeature } from "@cosmicdrift/kumiko-bundled-features/channel-teams"`; requires `delivery`, `secrets`
|
|
43
43
|
- `channel-telegram`: Sends delivery notifications through the Telegram Bot API (`sendMessage`, plain text), registered as the `telegram` channel in the delivery system.
|
|
44
44
|
`import { createChannelTelegramFeature } from "@cosmicdrift/kumiko-bundled-features/channel-telegram"`; requires `delivery`, `secrets`; secrets `channel-telegram:secret:bot-token`
|
|
45
|
+
- `channel-whatsapp`: WhatsApp Business (Meta Cloud API) as a two-way channel, not a delivery channel.
|
|
46
|
+
`import { createChannelWhatsappFeature } from "@cosmicdrift/kumiko-bundled-features/channel-whatsapp"`; requires `secrets`; secrets `channel-whatsapp:secret:access-token`, `channel-whatsapp:secret:app-secret`, `channel-whatsapp:secret:verify-token`
|
|
45
47
|
- `compliance-profiles`: Lets each tenant select a compliance regime (e.g. `eu-dsgvo`, `swiss-dsg`, `de-hr-dsgvo-hgb`) that bundles user-rights grace periods, breach-disclosure deadlines, sub-processor requirements, and audit-retention rules into a single named profile.
|
|
46
48
|
`import { createComplianceProfilesFeature } from "@cosmicdrift/kumiko-bundled-features/compliance-profiles"`
|
|
47
49
|
- `compliance-profiles-ops`: Platform-wide SystemAdmin counterpart to `compliance-profiles`' `needs-profile` query (#2089): `tenants-missing-profile` lists every enabled tenant with no row in `tenantComplianceProfile` at all, tenant-wide instead of scoped to the caller's own tenant.
|
|
@@ -95,7 +97,7 @@ One entry per feature a package ships: purpose, import of its factory, required
|
|
|
95
97
|
- `inbound-mail-foundation`: Plugin host for inbound e-mail (inbox federation) — provider plugins (inbound-provider-imap, later M365 Graph / Gmail REST) register at the `inboundMailProvider` extension point with verify/fetch and optional oauth/watch (live push) and send.
|
|
96
98
|
`import { createInboundMailFoundationFeature } from "@cosmicdrift/kumiko-bundled-features/inbound-mail-foundation"`; requires `tenant-lifecycle`
|
|
97
99
|
- `inbound-provider-imap`: Registers the `"imap"` provider for `inbound-mail-foundation` using imapflow — password/app-password auth covers classic IMAP hosts without any OAuth (plus an XOAUTH2 fallback consuming an access token from the secret slot).
|
|
98
|
-
`import { createInboundProviderImapFeature } from "@cosmicdrift/kumiko-bundled-features/inbound-provider-imap"`; requires `inbound-mail-foundation`, `secrets`
|
|
100
|
+
`import { createInboundProviderImapFeature } from "@cosmicdrift/kumiko-bundled-features/inbound-provider-imap"`; requires `inbound-mail-foundation`, `secrets`, `user`
|
|
99
101
|
- `inbound-provider-inmemory`: Registers a scriptable in-process `"inmemory"` provider for `inbound-mail-foundation`.
|
|
100
102
|
`import { createInboundProviderInMemoryFeature } from "@cosmicdrift/kumiko-bundled-features/inbound-provider-inmemory"`; requires `inbound-mail-foundation`
|
|
101
103
|
- `jobs`: Persistence and operator tooling for background jobs registered via `r.job(...)`.
|
|
@@ -147,7 +149,7 @@ One entry per feature a package ships: purpose, import of its factory, required
|
|
|
147
149
|
- `subscription-mollie`: Mollie payment provider plugin for `billing-foundation`, covering the DACH/EU mid-market use case.
|
|
148
150
|
`import { createSubscriptionMollieFeature } from "@cosmicdrift/kumiko-bundled-features/subscription-mollie"`; requires `billing-foundation`
|
|
149
151
|
- `subscription-paddle`: Paddle Billing provider plugin for `billing-foundation`.
|
|
150
|
-
`import { createSubscriptionPaddleFeature } from "@cosmicdrift/kumiko-bundled-features/subscription-paddle"`; requires `billing-foundation`, `config`, `secrets`; config without default `api-key`, `client-token`, `
|
|
152
|
+
`import { createSubscriptionPaddleFeature } from "@cosmicdrift/kumiko-bundled-features/subscription-paddle"`; requires `billing-foundation`, `config`, `secrets`; config without default `api-key`, `client-token`, `webhook-secret`
|
|
151
153
|
- `subscription-stripe`: Stripe payment provider plugin for `billing-foundation`.
|
|
152
154
|
`import { createSubscriptionStripeFeature } from "@cosmicdrift/kumiko-bundled-features/subscription-stripe"`; requires `billing-foundation`, `config`, `secrets`; config without default `api-key`, `webhook-secret`
|
|
153
155
|
- `tags`: Generic, host-agnostic tagging for any entity.
|
package/agents/features.md
CHANGED
|
@@ -168,6 +168,22 @@ Secrets:
|
|
|
168
168
|
| --- | --- | --- |
|
|
169
169
|
| `channel-telegram:secret:bot-token` | tenant | Telegram bot token |
|
|
170
170
|
|
|
171
|
+
## channel-whatsapp
|
|
172
|
+
|
|
173
|
+
WhatsApp Business (Meta Cloud API) as a two-way channel, not a delivery channel. Inbound: mount `createWhatsappWebhookRoutes()` via `extraRoutes` (default path `/api/channel-whatsapp/webhook/:tenantId`, the tenant id is part of the URL because the secrets are tenant-scoped); GET answers Meta's `hub.challenge` handshake, POST checks `X-Hub-Signature-256` over the raw body and normalizes each message and status. Events: `channel-whatsapp:event:message-received` (sender, wamid, type text|audio|image|interactive_button|other, text, button payload, `contextWamid`, media id and mime type, `phoneNumberId`), `status-updated` (sent|delivered|read|failed|other) and `throttled` (sender over the per-number limit). Sender number, text, button payload and status recipient are PII, stored as tenant-key ciphertext; read them with `readWhatsappMessagePii`. A redelivered wamid is stored once and answered 200; a failed dispatch answers 500 so Meta redelivers. Outbound: `createWhatsappClient(opts)` gives `sendText`, `sendTemplate`, `sendButtons`, `sendMedia` (each takes the sending `phoneNumberId` and answers `{ ok: true, wamid }` or a typed failure) and `fetchMedia` (media id to bytes and mime type; the URL from the Graph answer is checked against `allowedHosts` before the token is sent). Tenant secrets `channel-whatsapp:secret:access-token`, `app-secret` and `verify-token`. App options of `createChannelWhatsappFeature(opts)`: `apiBaseUrl`, `apiVersion` (default v21.0), `allowedHosts` (default graph.facebook.com and lookaside.fbsbx.com), `requireHttps` (default true; boot fails on a mismatch), `timeoutMs`, `mediaMaxBytes`, `transport` (in-memory Meta for tests), `senderRateLimits` (default 30 per hour and 200 per day per sender and tenant) and `rateLimit` (flood guard of the inbound handlers; cannot be disabled while a sender limit is set). Requires `secrets`. A worker-run job triggered by `message-received` attaches the business process.
|
|
174
|
+
|
|
175
|
+
Category: notifications
|
|
176
|
+
|
|
177
|
+
Requires: `secrets`
|
|
178
|
+
|
|
179
|
+
Secrets:
|
|
180
|
+
|
|
181
|
+
| Secret | Scope | Label |
|
|
182
|
+
| --- | --- | --- |
|
|
183
|
+
| `channel-whatsapp:secret:access-token` | tenant | WhatsApp access token |
|
|
184
|
+
| `channel-whatsapp:secret:app-secret` | tenant | WhatsApp app secret |
|
|
185
|
+
| `channel-whatsapp:secret:verify-token` | tenant | WhatsApp verify token |
|
|
186
|
+
|
|
171
187
|
## collection-labels
|
|
172
188
|
|
|
173
189
|
Nav labels for the content collections mounted by this sample app.
|
|
@@ -216,7 +232,7 @@ Exposes APIs: `retention.policyFor`
|
|
|
216
232
|
|
|
217
233
|
## delivery
|
|
218
234
|
|
|
219
|
-
The notification dispatch core: call `ctx.notify(notificationType, { to, route, data, priority, idempotencyKey })` from any handler to fan out a notification across all registered channels (email, in-app, push). Inside a write handler the delivery runs after the write has committed (the call returns `{ kind: "deferred" }`, a rolled-back write sends nothing); `immediate: true` delivers synchronously and returns `{ kind: "dispatched", deliveries }`. It stores per-user channel preferences in the `notification-preference` entity, opt-outs for no-account recipient addresses in `notification-address-opt-out` (keyed by a blind-index hash, never the plaintext address), logs every attempt to `store_delivery_attempts`, and enforces idempotency and rate-limiting — add `channel-email`, `channel-in-app`, or `channel-push` on top to actually send anything. Unsubscribe/resubscribe links are served by `createUnsubscribeRoutes({ secret })` mounted via the app's `extraRoutes` at `/api/delivery/unsubscribe` and `/api/delivery/resubscribe`: `GET /unsubscribe?token=` renders a confirmation page (no write), `POST /unsubscribe` performs the opt-out (RFC 8058 one-click, token from the form body or query), `POST /resubscribe` undoes it (JSON `{token}` or form body only, never the query — reachable by a mail-client link prefetcher) — sign links with `signUnsubscribeToken` / `signAddressUnsubscribeToken` using the same secret. `channel-email` sets `List-Unsubscribe` / `List-Unsubscribe-Post` automatically when a message's `data.unsubscribeUrl` points at the unsubscribe route. A notification declared with `unsubscribe: true` gets that link from delivery itself when the service has `unsubscribeLinks` (the `runProdApp` and `runDevApp` option `unsubscribe: { secret }` mounts the routes and wires it; base URL from `auth.publicOrigin`, `auth.mail.baseUrl` or `APP_BASE_URL`): user recipients get a user token, `route` recipients an address token (needs a blind-index key, otherwise no link); a `data.unsubscribeUrl` from the caller wins. `unsubscribe.tenantOrigin: (ctx) => origin | null` points the link at the tenant's own host (subdomain or custom domain, must serve this app's `/api`); null, a throw or a non-https value fall back to the app origin. The token carries the mail's locale, so the confirmation and result pages render in the mail's language. An app serving its own (e.g. legacy) unsubscribe links renders the same result page with `renderUnsubscribeResultPage({ kind, locale })`. To react to a no-account opt-out (e.g. remove the app's own subscriber row), declare `r.job(name, { trigger: { on: DeliveryHandlers.unsubscribeAddress } }, handler)` on a lane the app consumes: it runs after each committed opt-out, also an idempotent repeat, with `unsubscribeAddressPayloadSchema` (`addressHash`, `notificationType`, `channel`) as payload and the tenant in `ctx.triggeredBy.tenantId`; match the subscriber via `hashUnsubscribeAddress(email)`. Declare `unsubscribeUrl` as an optional template variable if the mail body shows it.
|
|
235
|
+
The notification dispatch core: call `ctx.notify(notificationType, { to, route, data, priority, idempotencyKey })` from any handler to fan out a notification across all registered channels (email, in-app, push). Inside a write handler the delivery runs after the write has committed (the call returns `{ kind: "deferred" }`, a rolled-back write sends nothing); `immediate: true` delivers synchronously and returns `{ kind: "dispatched", deliveries }`. It stores per-user channel preferences in the `notification-preference` entity, opt-outs for no-account recipient addresses in `notification-address-opt-out` (keyed by a blind-index hash, never the plaintext address), logs every attempt to `store_delivery_attempts`, and enforces idempotency and rate-limiting — add `channel-email`, `channel-in-app`, or `channel-push` on top to actually send anything. Unsubscribe/resubscribe links are served by `createUnsubscribeRoutes({ secret })` mounted via the app's `extraRoutes` at `/api/delivery/unsubscribe` and `/api/delivery/resubscribe`: `GET /unsubscribe?token=` renders a confirmation page (no write), `POST /unsubscribe` performs the opt-out (RFC 8058 one-click, token from the form body or query), `POST /resubscribe` undoes it (JSON `{token}` or form body only, never the query — reachable by a mail-client link prefetcher) — sign links with `signUnsubscribeToken` / `signAddressUnsubscribeToken` using the same secret. `channel-email` sets `List-Unsubscribe` / `List-Unsubscribe-Post` automatically when a message's `data.unsubscribeUrl` points at the unsubscribe route. A notification declared with `unsubscribe: true` gets that link from delivery itself when the service has `unsubscribeLinks` (the `runProdApp` and `runDevApp` option `unsubscribe: { secret }` mounts the routes and wires it; base URL from `auth.publicOrigin`, `auth.mail.baseUrl` or `APP_BASE_URL`): user recipients get a user token, `route` recipients an address token (needs a blind-index key, otherwise no link); a `data.unsubscribeUrl` from the caller wins. `unsubscribe.tenantOrigin: (ctx) => origin | null` points the link at the tenant's own host (subdomain or custom domain, must serve this app's `/api`); null, a throw or a non-https value fall back to the app origin. The token carries the mail's locale, so the confirmation and result pages render in the mail's language. An app serving its own (e.g. legacy) unsubscribe links renders the same result page with `renderUnsubscribeResultPage({ kind, locale })`. To react to a no-account opt-out (e.g. remove the app's own subscriber row), declare `r.job(name, { trigger: { on: DeliveryHandlers.unsubscribeAddress } }, handler)` on a lane the app consumes: it runs after each committed opt-out, also an idempotent repeat, with `unsubscribeAddressPayloadSchema` (`addressHash`, `notificationType`, `channel`) as payload and the tenant in `ctx.triggeredBy.tenantId`; match the subscriber via `hashUnsubscribeAddress(email)`. Declare `unsubscribeUrl` as an optional template variable if the mail body shows it. A job that sends an opt-in notification (e.g. a daily digest) reads the members who switched it on from the job-only query `delivery:query:opted-in-user-ids` (`{ notificationType, channel }` answers `{ userIds }`).
|
|
220
236
|
|
|
221
237
|
Category: notifications
|
|
222
238
|
|
|
@@ -405,7 +421,7 @@ Requires: `auth-foundation`, `tenant`
|
|
|
405
421
|
|
|
406
422
|
## inbound-mail-foundation
|
|
407
423
|
|
|
408
|
-
Plugin host for inbound e-mail (inbox federation) — provider plugins (inbound-provider-imap, later M365 Graph / Gmail REST) register at the `inboundMailProvider` extension point with verify/fetch and optional oauth/watch (live push) and send. `sendMailFromAccount(ctx, { accountId, message })` sends from a connected mailbox through its provider (From = the mailbox address, no fallback to the app sender) and answers typed failures (not configured, login rejected, server unreachable, rejected, invalid message); app write handlers call it, it is no endpoint of its own. The foundation owns three event-sourced streams (mail-account lifecycle, inbound-message with exactly-once ingest via deterministic aggregate ids, mail-thread rollup) and their projections `read_mail_accounts`/`read_inbound_messages`/`read_mail_threads`; PII fields are envelope-encrypted per tenant subject key before every append (crypto-shredding on tenant destroy). Wire `createInboundMailConnectRoutes` (OAuth connect + anonymous callback outside /api) and `createInboundMailSupervisor` (IDLE watch with backoff + reconciliation poll) in bin/server.ts. Consume `inbound-mail-foundation:event:inbound-message-received` from app features to attach business processes.
|
|
424
|
+
Plugin host for inbound e-mail (inbox federation) — provider plugins (inbound-provider-imap, later M365 Graph / Gmail REST) register at the `inboundMailProvider` extension point with verify/fetch and optional oauth/watch (live push) and send. `sendMailFromAccount(ctx, { accountId, message })` sends from a connected mailbox through its provider (From = the mailbox address, no fallback to the app sender) and answers typed failures (not configured, login rejected, server unreachable, rejected, invalid message); app write handlers call it from `beforeTransaction` (it sends at once and a rollback cannot recall the mail), it is no endpoint of its own. The foundation owns three event-sourced streams (mail-account lifecycle, inbound-message with exactly-once ingest via deterministic aggregate ids, mail-thread rollup) and their projections `read_mail_accounts`/`read_inbound_messages`/`read_mail_threads`; PII fields are envelope-encrypted per tenant subject key before every append (crypto-shredding on tenant destroy). Wire `createInboundMailConnectRoutes` (OAuth connect + anonymous callback outside /api) and `createInboundMailSupervisor` (IDLE watch with backoff + reconciliation poll) in bin/server.ts. Consume `inbound-mail-foundation:event:inbound-message-received` from app features to attach business processes.
|
|
409
425
|
|
|
410
426
|
Category: notifications
|
|
411
427
|
|
|
@@ -413,11 +429,11 @@ Requires: `tenant-lifecycle`
|
|
|
413
429
|
|
|
414
430
|
## inbound-provider-imap
|
|
415
431
|
|
|
416
|
-
Registers the `"imap"` provider for `inbound-mail-foundation` using imapflow — password/app-password auth covers classic IMAP hosts without any OAuth (plus an XOAUTH2 fallback consuming an access token from the secret slot). Incremental sync via a UIDVALIDITY:lastUid cursor (UIDVALIDITY change triggers a cursor-invalid full resync), initial backfill bounded by the foundation backfill window, and live push via IMAP IDLE for the watch supervisor. Tenant admins connect a shared mailbox through the "Connect mailbox" form on the mail accounts list and members a personal one through the same form on "My mail accounts" (`connect-mailbox` and `connect-my-mailbox` check the IMAP login and the SMTP login of the outgoing server first, then creates the account and its credential secret in one transaction; `reconnect-mailbox` does the same check for an existing mailbox with a sign-in error and overwrites its credential secret); programmatic setups store the per-account connection JSON (host/port/secure/user/password, plus smtpHost/smtpPort for sending) in the account credential secret slot before the first sync. Implements the provider `send`: `sendMailFromAccount` sends over the SMTP server of the mailbox itself (implicit
|
|
432
|
+
Registers the `"imap"` provider for `inbound-mail-foundation` using imapflow — password/app-password auth covers classic IMAP hosts without any OAuth (plus an XOAUTH2 fallback consuming an access token from the secret slot). Incremental sync via a UIDVALIDITY:lastUid cursor (UIDVALIDITY change triggers a cursor-invalid full resync), initial backfill bounded by the foundation backfill window, and live push via IMAP IDLE for the watch supervisor. Tenant admins connect a shared mailbox through the "Connect mailbox" form on the mail accounts list and members a personal one through the same form on "My mail accounts" (`connect-mailbox` and `connect-my-mailbox` check the IMAP login and the SMTP login of the outgoing server first, then creates the account and its credential secret in one transaction; `reconnect-mailbox` does the same check for an existing mailbox with a sign-in error and overwrites its credential secret); programmatic setups store the per-account connection JSON (host/port/secure/user/password, plus smtpHost/smtpPort for sending) in the account credential secret slot before the first sync. Implements the provider `send`: `sendMailFromAccount` sends over the SMTP server of the mailbox itself (TLS enforced: implicit on port 465, STARTTLS with requireTLS on every other port, port from the credential document, connect form default 587; same login) with the mailbox address as From and stores a copy in its sent folder.
|
|
417
433
|
|
|
418
434
|
Category: notifications
|
|
419
435
|
|
|
420
|
-
Requires: `inbound-mail-foundation`, `secrets`
|
|
436
|
+
Requires: `inbound-mail-foundation`, `secrets`, `user`
|
|
421
437
|
|
|
422
438
|
## inbound-provider-inmemory
|
|
423
439
|
|
|
@@ -646,7 +662,7 @@ Exposes APIs: `sessions.revokeAllForUser`
|
|
|
646
662
|
|
|
647
663
|
## step-dispatcher
|
|
648
664
|
|
|
649
|
-
Internal system feature that drains deferred Tier-2 side-effects (currently `webhook.send` and `mail.send`) after their originating transaction commits. An `r.multiStreamProjection` on the `kumiko:system:step.dispatch-requested` system event enqueues one `step-dispatcher:job:deliver` BullMQ job per dispatch (Redis carries only the stream id and tenant, never the request payload). The job performs the actual HTTP or mail delivery and appends `kumiko:system:step.dispatched` or `kumiko:system:step.dispatch-failed` back onto the same stream, so the outcome is recorded in the event log without a separate status table. Transient failures (network error, timeout, 5xx, 408, 429, any mail adapter failure) are retried 3 times with exponential backoff; the outcome is recorded after the final attempt and the payload key is erased only then. Permanent failures (invalid url, blocked host, other 4xx, unavailable auth secret) are recorded immediately. At most 2 deliveries per tenant run at once (`maxPerTenant` with `onLimit: "defer"`), so a slow receiver of one tenant does not delay other tenants. Requires a job runner (Redis) and a worker consuming the job's default `worker` lane; without a job runner the projection fails loudly. Mount this feature explicitly via `createStepDispatcherFeature()` in your app's feature list alongside any features that use `r.step.webhook.send` or `r.step.mail.send`. Requires the `secrets` feature (`createSecretsFeature()`) to be mounted — `webhook.send` auth resolves per-tenant through it, under `step-dispatcher:webhook-auth.<name>`. Every `webhook.send` request carries `Idempotency-Key: <dispatch stream id>`, stable across retries and redeliveries of the same dispatch request; an explicit `Idempotency-Key` in `headers` takes precedence.
|
|
665
|
+
Internal system feature that drains deferred Tier-2 side-effects (currently `webhook.send` and `mail.send`) after their originating transaction commits. An `r.multiStreamProjection` on the `kumiko:system:step.dispatch-requested` system event enqueues one `step-dispatcher:job:deliver` BullMQ job per dispatch (Redis carries only the stream id and tenant, never the request payload). The job performs the actual HTTP or mail delivery and appends `kumiko:system:step.dispatched` or `kumiko:system:step.dispatch-failed` back onto the same stream, so the outcome is recorded in the event log without a separate status table. Transient failures (network error, timeout, 5xx, 408, 429, any mail adapter failure) are retried 3 times with exponential backoff; the outcome is recorded after the final attempt and the payload key is erased only then. A request that still has no outcome after 24 hours (job stalled or lost, or its final attempt could not record one) is closed by the daily `step-dispatcher:job:sweep-abandoned` cron (it pages through all such requests; requests that already have an outcome are not swept) with a generic `dispatch-failed` event and its payload key is erased. Permanent failures (invalid url, blocked host, other 4xx, unavailable auth secret) are recorded immediately. At most 2 deliveries per tenant run at once (`maxPerTenant` with `onLimit: "defer"`), so a slow receiver of one tenant does not delay other tenants. Requires a job runner (Redis) and a worker consuming the job's default `worker` lane; without a job runner the projection fails loudly. Mount this feature explicitly via `createStepDispatcherFeature()` in your app's feature list alongside any features that use `r.step.webhook.send` or `r.step.mail.send`. Requires the `secrets` feature (`createSecretsFeature()`) to be mounted — `webhook.send` auth resolves per-tenant through it, under `step-dispatcher:webhook-auth.<name>`. Every `webhook.send` request carries `Idempotency-Key: <dispatch stream id>`, stable across retries and redeliveries of the same dispatch request; an explicit `Idempotency-Key` in `headers` takes precedence.
|
|
650
666
|
|
|
651
667
|
Category: infrastructure
|
|
652
668
|
|
|
@@ -662,7 +678,7 @@ Requires: `billing-foundation`
|
|
|
662
678
|
|
|
663
679
|
## subscription-paddle
|
|
664
680
|
|
|
665
|
-
Paddle Billing provider plugin for `billing-foundation`. Paddle acts as merchant of record: it sells to the customer and issues invoice and VAT, so the consumer-protection texts for this provider come from `consumerProtection.providerTexts`. Reads its API key
|
|
681
|
+
Paddle Billing provider plugin for `billing-foundation`. Paddle acts as merchant of record: it sells to the customer and issues invoice and VAT, so the consumer-protection texts for this provider come from `consumerProtection.providerTexts`. Reads its API key and webhook secret from system config keys with `backing:"secrets"` (envelope-encrypted in the secrets store under the system tenant), the public Paddle.js `client-token`, a `billingLive` master switch and an `environment` key (sandbox | live). `environment` is its own key because Paddle serves sandbox and live from different API hosts and a live key must never hit the sandbox host or the other way round; `billingLive` only decides whether checkouts are offered at all. All of them are runtime config, so keys rotate and prod goes live without a redeploy, and the `mask` on each derives the sysadmin settings screen and nav. Mount via `createSubscriptionPaddleFeature({ priceToTier })`; the optional `apiKey`/`webhookSecret`/`clientToken` options are env to config bridge fallbacks (`PADDLE_API_KEY`, `PADDLE_WEBHOOK_SECRET`, `PADDLE_CLIENT_TOKEN`). The plugin always mounts; `createCheckoutSession` throws `feature_disabled` unless `billingLive` is true, and billing counts as enabled only with the API key present. Webhooks arrive at `/webhooks/subscription/paddle` when mounted through the server-runtime `billing.paddle` boot option, or at `/api/subscription/webhook/paddle` when `createSubscriptionWebhookRoute` is mounted by hand and are verified with the `Paddle-Signature` header (HMAC-SHA256 over `ts:rawBody` keyed with the raw secret, any `h1` may match, 5 minute tolerance). Paddle.js can open checkouts with arbitrary `customData` from the browser, so `custom_data.tenantId` only locates the tenant stream: billing-foundation keeps a checkout ledger and accepts a webhook only for a transaction the server opened itself (a `subscription.created` must name it in `transaction_id`), so events for prices outside `priceToTier`, without a tenant or for foreign transactions are dropped. The `backfill-checkout-ledger` job ledgers Paddle checkouts that were open when the ledger was introduced, then goes quiet. Paddle has no hosted checkout page, so the feature serves the Default Payment Link itself at `/billing/paddle-checkout` (the Default Payment Link in the Paddle dashboard must point to `<APP_BASE_URL>/billing/paddle-checkout`; it is the only source, because checkouts are created without a `checkout.url`). Create subscription prices in the Paddle catalog with quantity minimum and maximum 1; for one-off packs set the quantity limits on purpose, because the payment event carries `quantity` and the app has to multiply its credits by it: an anonymous page with its own CSP that loads Paddle.js from cdn.paddle.com, the one external script this framework allows, and opens the overlay for the transaction. Implements checkout, customer portal, cancel and resume, `retrievePrices` (batched, 10-minute TTL cache), `retrieveSubscription` for the sync job, and an in-app plan switch: `previewPlanSwitch` shows the proration before the customer confirms, `applyPlanSwitch` changes the plan without a hosted page and waits for the `subscription.updated` webhook to move the tier.
|
|
666
682
|
|
|
667
683
|
Category: billing
|
|
668
684
|
|
|
@@ -676,7 +692,6 @@ Config keys:
|
|
|
676
692
|
| `billing-live` | boolean | system | `false` |
|
|
677
693
|
| `client-token` | text | system | |
|
|
678
694
|
| `environment` | select | system | `sandbox` |
|
|
679
|
-
| `tenant-binding-key` | text | system | |
|
|
680
695
|
| `webhook-secret` | text | system | |
|
|
681
696
|
|
|
682
697
|
## subscription-stripe
|
package/agents/widgets.md
CHANGED
|
@@ -37,14 +37,25 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
|
|
|
37
37
|
| `DropdownMenuPortal` | |
|
|
38
38
|
| `DropdownMenuSeparator` | |
|
|
39
39
|
| `DropdownMenuTrigger` | |
|
|
40
|
+
| `EditorBody` | |
|
|
41
|
+
| `EditorFooter` | |
|
|
42
|
+
| `EditorFrame` | |
|
|
43
|
+
| `EditorHeader` | |
|
|
44
|
+
| `EditorInfoBar` | |
|
|
45
|
+
| `EditorLocaleSwitch` | |
|
|
46
|
+
| `EditorModeSwitch` | |
|
|
40
47
|
| `EditorPanel` | |
|
|
48
|
+
| `EditorWorkbench` | |
|
|
41
49
|
| `EmptyState` | Empty state with an optional icon and CTA, using the dashed-box style of entityList empty states as a standalone widget for custom screens. |
|
|
42
50
|
| `ErrorState` | Error state based on the Banner primitive, with a retry button. |
|
|
43
51
|
| `FeedList` | Non-tabular compact list (e.g. "upcoming appointments") — primary text plus an optional right-aligned trailing value for each row. |
|
|
44
52
|
| `FileField` | File upload = Field + Input(kind:"file"\|"image"), based on FileRef. |
|
|
53
|
+
| `FileViewAction` | "View" action for a stored file: renders only for PDFs and opens the viewer in a drawer. |
|
|
45
54
|
| `FloatingPanel` | Non-modal panel floating above the page: draggable by its header, resizable from all edges and corners, clamped to the viewport, geometry optionally remembered. |
|
|
46
55
|
| `FormScreenShell` | |
|
|
47
56
|
| `HeaderActionGroup` | |
|
|
57
|
+
| `HeaderActionPinned` | Marks an app header action (e.g. the assistant trigger) that stays in the bar on a phone, next to the bell; the rest of `headerActions` folds into the "…" menu. |
|
|
58
|
+
| `HtmlMailFrame` | Renders server-sanitized mail HTML in a script-free sandboxed iframe that grows to its content. |
|
|
48
59
|
| `Icon` | |
|
|
49
60
|
| `InfinityList` | Cursor-paginated scroll list (mail inbox, activity feeds) — loads the next page when the end sentinel becomes visible (IntersectionObserver), instead of a pager bar like QueryTable/entityList. |
|
|
50
61
|
| `KumikoLink` | |
|
|
@@ -72,12 +83,17 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
|
|
|
72
83
|
| `PlanGrid` | |
|
|
73
84
|
| `PresenceAvatars` | Small round avatars of the people on a row, with "+n" for the rest; for list rows. |
|
|
74
85
|
| `PresenceNotice` | One quiet line above a record: who else is on it and for how long. |
|
|
86
|
+
| `PreviewWidthFrame` | |
|
|
75
87
|
| `PrimitivesProvider` | |
|
|
76
88
|
| `ProfileMenu` | |
|
|
77
89
|
| `ProgressBar` | Progress bar, `value` 0..1 (clamped). |
|
|
78
90
|
| `ProgressList` | Label/value header and progress bar for each entry (for example, loan repayment progress). |
|
|
79
91
|
| `PublicShell` | One header and footer for anonymous pages; `focus` narrows to a task column, `card` centers a single card (sign-in). |
|
|
80
92
|
| `QueryTable` | |
|
|
93
|
+
| `RailField` | |
|
|
94
|
+
| `RailHint` | |
|
|
95
|
+
| `RailRow` | |
|
|
96
|
+
| `RailSection` | |
|
|
81
97
|
| `RangeField` | Slider = Field + Input(kind:"range"). |
|
|
82
98
|
| `RenderEdit` | |
|
|
83
99
|
| `RenderField` | |
|
|
@@ -132,6 +148,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
|
|
|
132
148
|
| `useDispatcher` | |
|
|
133
149
|
| `useDispatcherStatus` | |
|
|
134
150
|
| `useDraft` | Form state for calculator screens: a draft object plus `patch` for partial updates, and `field(name)` that provides `{ id, name, value, onChange }` props ready for field widgets (NumberField/MoneyField/PercentField). |
|
|
151
|
+
| `useFileMeta` | |
|
|
135
152
|
| `useForm` | |
|
|
136
153
|
| `useIsNarrowViewport` | |
|
|
137
154
|
| `useIsViewportBelow` | |
|
|
@@ -175,6 +192,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
|
|
|
175
192
|
| `filterByAccess` | |
|
|
176
193
|
| `formatMoney` | |
|
|
177
194
|
| `formatPath` | |
|
|
195
|
+
| `formatRelativeWhen` | |
|
|
178
196
|
| `parsePath` | |
|
|
179
197
|
| `parseTargetFromSearchParams` | Parses the current search parameters back into a TargetRef. |
|
|
180
198
|
| `postWithDownload` | |
|
|
@@ -186,7 +204,7 @@ Value exports of `@cosmicdrift/kumiko-renderer/web`.
|
|
|
186
204
|
| `smoothPath` | Quadratic midpoint technique: smooths the zigzag line without overshoot (~5 lines instead of a Catmull-Rom/Bezier fit). |
|
|
187
205
|
| `synthesizeActionFormEntity` | Builds a minimal EntityDefinition from the inline fields of an ActionForm or SecretMint screen. |
|
|
188
206
|
| `synthesizeActionFormScreen` | Converts an ActionFormScreenDefinition or SecretMintScreenDefinition to the EntityEditScreen shape expected by RenderEdit. |
|
|
189
|
-
| `uploadFileRef` | Posts one file to the stack's file endpoint (double-submit CSRF) and returns the new FileRef id. |
|
|
207
|
+
| `uploadFileRef` | Posts one file to the stack's file endpoint (double-submit CSRF) and returns the new FileRef id, or the claim handle when the server issued one (anonymous uploads), which a save must submit. |
|
|
190
208
|
|
|
191
209
|
## Constants
|
|
192
210
|
|
|
@@ -46,4 +46,5 @@ export declare const STATE_CHANGING_METHODS: ReadonlySet<string>;
|
|
|
46
46
|
export declare const TENANT_HEADER_NAME = "X-Tenant";
|
|
47
47
|
export declare const LOCALE_HEADER_NAME = "X-Locale";
|
|
48
48
|
export declare const NO_ROUTE_MATCH_HEADER_NAME = "X-Kumiko-No-Route-Match";
|
|
49
|
+
export declare const APP_NOW_HEADER_NAME = "X-Kumiko-Now";
|
|
49
50
|
export type Route = (typeof Routes)[keyof typeof Routes];
|
|
@@ -146,3 +146,7 @@ export const LOCALE_HEADER_NAME = "X-Locale";
|
|
|
146
146
|
// "unregistered path" from "registered path, access denied" — a leak the
|
|
147
147
|
// denying routes deliberately collapse into one status code.
|
|
148
148
|
export const NO_ROUTE_MATCH_HEADER_NAME = "X-Kumiko-No-Route-Match";
|
|
149
|
+
// Every query answer carries the app clock (`ctx.clock`, a fixed clock in tests and screenshot
|
|
150
|
+
// runs) as an ISO instant, so the UI's "As of" and relative times follow the app, not the device.
|
|
151
|
+
// The renderer reads it by the same name (renderer/src/server-clock.ts).
|
|
152
|
+
export const APP_NOW_HEADER_NAME = "X-Kumiko-Now";
|
|
@@ -20,7 +20,6 @@ export const PAT_TOKEN_PREFIX = "kpat_";
|
|
|
20
20
|
export function sessionCheckStatus(result) {
|
|
21
21
|
return typeof result === "string" ? result : result.status;
|
|
22
22
|
}
|
|
23
|
-
// @wrapper-known error-helper
|
|
24
23
|
function middlewareReject(c, opts) {
|
|
25
24
|
return c.json({
|
|
26
25
|
error: {
|
|
@@ -455,12 +454,14 @@ function resolveAgainstDefault(defaultTenantId, clientTenant) {
|
|
|
455
454
|
async function resolveWithAuthoritativeResolver(c, tenantResolver, clientTenant) {
|
|
456
455
|
const resolved = await tenantResolver(c);
|
|
457
456
|
if (resolved !== null && resolved !== undefined) {
|
|
458
|
-
|
|
457
|
+
// A cookie is ambient state (possibly apex-scoped, left over from another
|
|
458
|
+
// tenant's subdomain); only an explicit header counts as a conflicting claim.
|
|
459
|
+
if (clientTenant && clientTenant.source === "header" && clientTenant.id !== resolved) {
|
|
459
460
|
return {
|
|
460
461
|
error: {
|
|
461
462
|
code: "tenant_mismatch",
|
|
462
463
|
status: 400,
|
|
463
|
-
message:
|
|
464
|
+
message: "header tenant disagrees with resolved tenant",
|
|
464
465
|
i18nKey: "auth.errors.tenantMismatch",
|
|
465
466
|
details: { clientTenantId: clientTenant.id, resolvedTenantId: resolved },
|
|
466
467
|
},
|
|
@@ -3,10 +3,11 @@ import { createAnonymousUser } from "../engine/system-user.js";
|
|
|
3
3
|
import { SYSTEM_TENANT_ID } from "../engine/types/index.js";
|
|
4
4
|
import { NotFoundError } from "../errors/index.js";
|
|
5
5
|
import { createFallbackLogger } from "../logging/utils.js";
|
|
6
|
+
import { MAX_RETURN_PATH_LENGTH } from "../utils/return-path-limit.js";
|
|
6
7
|
const log = createFallbackLogger("kumiko");
|
|
7
8
|
// Content is checked where the mail link is built (bundled-features knows the path rules); a bad
|
|
8
9
|
// value must never void the whole body, or the request would silently send no mail.
|
|
9
|
-
const returnToField = z.string().max(
|
|
10
|
+
const returnToField = z.string().max(MAX_RETURN_PATH_LENGTH).optional().catch(undefined);
|
|
10
11
|
// Cross-device try-first handover: an optional tenant-handover grant the signup-request
|
|
11
12
|
// route forwards to the handler for server-side verification and binding —
|
|
12
13
|
// the grant itself never appears anywhere else (URL, mail, log, response).
|
|
@@ -5,4 +5,5 @@ export declare function assertNoAggregateTypeKeyCollisions(registry: Registry):
|
|
|
5
5
|
export declare function collectEntityDetailQueries(registry: Registry): ReadonlyMap<string, string>;
|
|
6
6
|
export declare function collectEntityDetailAccess(registry: Registry): ReadonlyMap<string, AccessRule>;
|
|
7
7
|
export declare function collectEntityReadAccess(registry: Registry): ReadonlyMap<string, readonly AccessRule[]>;
|
|
8
|
+
export declare function collectEntityQueryAccess(registry: Registry): ReadonlyMap<string, readonly AccessRule[]>;
|
|
8
9
|
export declare function collectEntityRowReadMaps(registry: Registry): ReadonlyMap<string, OwnershipMap>;
|
|
@@ -80,6 +80,24 @@ export function collectEntityReadAccess(registry) {
|
|
|
80
80
|
}
|
|
81
81
|
return rulesByEntity;
|
|
82
82
|
}
|
|
83
|
+
// Access rules of the query handlers that belong to an entity. Unlike collectEntityReadAccess,
|
|
84
|
+
// a handler that merely names the entity in liveEntities does not count: it returns signals,
|
|
85
|
+
// not the entity's rows, so it must not open derived values over the entity.
|
|
86
|
+
export function collectEntityQueryAccess(registry) {
|
|
87
|
+
assertNoAggregateTypeKeyCollisions(registry);
|
|
88
|
+
const rulesByEntity = new Map();
|
|
89
|
+
for (const [handlerName, handler] of registry.getAllQueryHandlers()) {
|
|
90
|
+
const entityName = registry.getHandlerEntity(handlerName);
|
|
91
|
+
if (entityName === undefined)
|
|
92
|
+
continue;
|
|
93
|
+
for (const key of new Set([entityName, toKebab(entityName)])) {
|
|
94
|
+
const rules = rulesByEntity.get(key) ?? [];
|
|
95
|
+
rules.push(handler.access);
|
|
96
|
+
rulesByEntity.set(key, rules);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return rulesByEntity;
|
|
100
|
+
}
|
|
83
101
|
// Entities whose own access.read narrows rows per role (e.g. Driver sees only assigned rows).
|
|
84
102
|
// A signal for such an entity must not name ids to a role that does not read every row.
|
|
85
103
|
export function collectEntityRowReadMaps(registry) {
|
|
@@ -1,4 +1,9 @@
|
|
|
1
|
+
import type { RateLimitResolver } from "@cosmicdrift/kumiko-types/rate-limit-types";
|
|
1
2
|
import { Hono } from "hono";
|
|
2
3
|
import type { Registry } from "../../engine/types/index.ts";
|
|
3
4
|
import type { Dispatcher } from "../../pipeline/dispatcher.ts";
|
|
4
|
-
export declare
|
|
5
|
+
export declare const EXPORT_RATE_LIMIT: {
|
|
6
|
+
readonly limit: 60;
|
|
7
|
+
readonly windowSeconds: 60;
|
|
8
|
+
};
|
|
9
|
+
export declare function createExportRoutes(dispatcher: Dispatcher, registry: Registry, rateLimitResolver?: RateLimitResolver): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Hono } from "hono";
|
|
2
2
|
import * as z from "zod";
|
|
3
|
+
import { RateLimitError } from "../../errors/classes.js";
|
|
3
4
|
import { toKumikoError } from "../../errors/to-kumiko-error.js";
|
|
4
5
|
import { createI18n } from "../../i18n/index.js";
|
|
5
6
|
import { DEFAULT_LOCALE } from "../../i18n/request-locale.js";
|
|
@@ -14,6 +15,10 @@ import { resolveExportPlan } from "./export-screen.js";
|
|
|
14
15
|
import { writeExportWorkbook } from "./export-xlsx-writer.js";
|
|
15
16
|
const XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
16
17
|
const MAX_ID_LENGTH = 200;
|
|
18
|
+
// One export fans out into up to maxRows / MAX_LIST_LIMIT queries and buffers the whole
|
|
19
|
+
// workbook; the per-request IP limiter counts it as a single request.
|
|
20
|
+
const EXPORT_BUCKET = "export-xlsx-in-flight";
|
|
21
|
+
const EXPORT_RETRY_AFTER_SECONDS = 5;
|
|
17
22
|
const exportBodySchema = z.object({
|
|
18
23
|
screen: z.string().max(MAX_ID_LENGTH),
|
|
19
24
|
payload: z.record(z.string(), z.unknown()).default({}),
|
|
@@ -32,12 +37,30 @@ function downloadFileName(screenShortId, now) {
|
|
|
32
37
|
const safeId = screenShortId.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
33
38
|
return `${safeId}-${now.toISOString().slice(0, 10)}.xlsx`;
|
|
34
39
|
}
|
|
35
|
-
|
|
40
|
+
function exportAlreadyRunning() {
|
|
41
|
+
return new RateLimitError({
|
|
42
|
+
bucket: EXPORT_BUCKET,
|
|
43
|
+
limit: 1,
|
|
44
|
+
windowSeconds: EXPORT_RETRY_AFTER_SECONDS,
|
|
45
|
+
remaining: 0,
|
|
46
|
+
retryAfterSeconds: EXPORT_RETRY_AFTER_SECONDS,
|
|
47
|
+
resetAt: new Date(Date.now() + EXPORT_RETRY_AFTER_SECONDS * 1000).toISOString(),
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
export const EXPORT_RATE_LIMIT = { limit: 60, windowSeconds: 60 };
|
|
51
|
+
export function createExportRoutes(dispatcher, registry, rateLimitResolver) {
|
|
36
52
|
const api = new Hono();
|
|
37
53
|
const i18n = createI18n(registry, { defaultLocale: DEFAULT_LOCALE });
|
|
54
|
+
const exportsInFlight = new Set();
|
|
38
55
|
api.post(Routes.exportXlsx, async (c) => {
|
|
39
56
|
const user = getUser(c);
|
|
57
|
+
const inFlightKey = `${user.tenantId}:${user.id}`;
|
|
58
|
+
if (exportsInFlight.has(inFlightKey)) {
|
|
59
|
+
return queryErrorResponse(c, exportAlreadyRunning(), Routes.exportXlsx);
|
|
60
|
+
}
|
|
61
|
+
exportsInFlight.add(inFlightKey);
|
|
40
62
|
try {
|
|
63
|
+
await rateLimitResolver?.enforce(`export-xlsx:${inFlightKey}`, EXPORT_RATE_LIMIT);
|
|
41
64
|
const parsed = exportBodySchema.safeParse(await c.req.json().catch(() => undefined));
|
|
42
65
|
if (!parsed.success)
|
|
43
66
|
throw exportRejection("export_invalid_request", "body");
|
|
@@ -70,6 +93,9 @@ export function createExportRoutes(dispatcher, registry) {
|
|
|
70
93
|
catch (e) {
|
|
71
94
|
return queryErrorResponse(c, toKumikoError(e), Routes.exportXlsx);
|
|
72
95
|
}
|
|
96
|
+
finally {
|
|
97
|
+
exportsInFlight.delete(inFlightKey);
|
|
98
|
+
}
|
|
73
99
|
});
|
|
74
100
|
return api;
|
|
75
101
|
}
|
|
@@ -33,11 +33,22 @@ function parsePage(result, queryType) {
|
|
|
33
33
|
nextCursor: typeof nextCursor === "string" && nextCursor !== "" ? nextCursor : undefined,
|
|
34
34
|
};
|
|
35
35
|
}
|
|
36
|
+
// Rows without a string id cannot be told apart, so they always count as unseen.
|
|
37
|
+
function claimRowId(row, seenRowIds) {
|
|
38
|
+
const id = row["id"];
|
|
39
|
+
if (typeof id !== "string")
|
|
40
|
+
return true;
|
|
41
|
+
if (seenRowIds.has(id))
|
|
42
|
+
return false;
|
|
43
|
+
seenRowIds.add(id);
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
36
46
|
/** Reads the whole filtered list page by page; gives up as soon as more than `maxRows` exist. */
|
|
37
47
|
export async function readExportRows(dispatcher, plan, clientPayload, user) {
|
|
38
48
|
const base = sanitizeExportPayload(clientPayload, plan);
|
|
39
49
|
const rows = [];
|
|
40
50
|
const seenCursors = new Set();
|
|
51
|
+
const seenRowIds = new Set();
|
|
41
52
|
let cursor;
|
|
42
53
|
for (;;) {
|
|
43
54
|
const limit = Math.min(MAX_LIST_LIMIT, plan.maxRows + 1 - rows.length);
|
|
@@ -47,11 +58,16 @@ export async function readExportRows(dispatcher, plan, clientPayload, user) {
|
|
|
47
58
|
? { ...base, limit, offset: rows.length }
|
|
48
59
|
: { ...base, limit };
|
|
49
60
|
const page = parsePage(await dispatcher.query(plan.queryType, pagingPayload, user), plan.queryType);
|
|
50
|
-
rows.
|
|
61
|
+
const freshRows = page.rows.filter((row) => claimRowId(row, seenRowIds));
|
|
62
|
+
rows.push(...freshRows);
|
|
51
63
|
if (rows.length > plan.maxRows)
|
|
52
64
|
return { tooMany: true };
|
|
53
|
-
// A short
|
|
54
|
-
|
|
65
|
+
// A short page proves nothing (a query may cap `limit` itself), so only an empty page ends the
|
|
66
|
+
// list. A page without any unseen row means the query ignores offset/cursor and would repeat
|
|
67
|
+
// itself until maxRows. A repeated cursor would loop forever.
|
|
68
|
+
if (page.rows.length === 0 || freshRows.length === 0)
|
|
69
|
+
return { tooMany: false, rows };
|
|
70
|
+
if (cursor !== undefined && page.nextCursor === undefined)
|
|
55
71
|
return { tooMany: false, rows };
|
|
56
72
|
if (page.nextCursor !== undefined) {
|
|
57
73
|
if (seenCursors.has(page.nextCursor))
|
package/dist/api/routes.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Clock } from "@cosmicdrift/kumiko-types/tz-context";
|
|
1
2
|
import { type Context, Hono } from "hono";
|
|
2
3
|
import { type KumikoError } from "../errors/index.ts";
|
|
3
4
|
import type { Dispatcher } from "../pipeline/dispatcher.ts";
|
|
@@ -9,6 +10,7 @@ export declare const StreamFrame: {
|
|
|
9
10
|
};
|
|
10
11
|
export type ApiRoutesOptions = {
|
|
11
12
|
readonly sseHeartbeatMs?: number;
|
|
13
|
+
readonly clock?: Clock;
|
|
12
14
|
};
|
|
13
15
|
export declare function createApiRoutes(dispatcher: Dispatcher, options?: ApiRoutesOptions): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
|
|
14
16
|
export type SseWriter = {
|
package/dist/api/routes.js
CHANGED
|
@@ -8,7 +8,7 @@ import { scrubLogValue } from "../logging/scrub.js";
|
|
|
8
8
|
import { wrapToKumiko } from "../pipeline/dispatcher-utils.js";
|
|
9
9
|
import { isPlainObject } from "../utils/is-plain-object.js";
|
|
10
10
|
import { stringifyJson } from "../utils/safe-json.js";
|
|
11
|
-
import { Routes } from "./api-constants.js";
|
|
11
|
+
import { APP_NOW_HEADER_NAME, Routes } from "./api-constants.js";
|
|
12
12
|
import { getAuthTokenExpiry, getUser } from "./auth-middleware.js";
|
|
13
13
|
import { patAllows } from "./pat-scope.js";
|
|
14
14
|
import { requestContext } from "./request-context.js";
|
|
@@ -28,6 +28,14 @@ const CLIENT_CLOSED_REQUEST_STATUS = 499;
|
|
|
28
28
|
export function createApiRoutes(dispatcher, options = {}) {
|
|
29
29
|
const heartbeatMs = options.sseHeartbeatMs ?? SSE_HEARTBEAT_INTERVAL_MS;
|
|
30
30
|
const api = new Hono();
|
|
31
|
+
// Before any body is read, so even an answer to a broken body carries the app clock. Whole
|
|
32
|
+
// milliseconds in ISO form: Temporal's toString() can run to nanoseconds, which Date.parse on
|
|
33
|
+
// Hermes/JSC does not define.
|
|
34
|
+
api.use("*", async (c, next) => {
|
|
35
|
+
const nowMs = options.clock?.now().epochMilliseconds ?? Date.now();
|
|
36
|
+
c.header(APP_NOW_HEADER_NAME, new Date(nowMs).toISOString());
|
|
37
|
+
await next();
|
|
38
|
+
});
|
|
31
39
|
api.post(Routes.write, async (c) => {
|
|
32
40
|
const user = getUser(c);
|
|
33
41
|
const body = await readDispatchBody(c);
|
|
@@ -7,7 +7,8 @@ import { getUser } from "./auth-middleware.js";
|
|
|
7
7
|
import { clientIpSourceFromHonoContext } from "./client-ip.js";
|
|
8
8
|
import { ExtraRouteEntries, ExtraRouteRejection, } from "./extra-route.js";
|
|
9
9
|
import { bodyLimitForRoutePath, DEFAULT_MAX_REQUEST_BYTES } from "./route-registrars.js";
|
|
10
|
-
import {
|
|
10
|
+
import { makeSystemQuery, mountHonoRoute } from "./server-feature-http-routes.js";
|
|
11
|
+
import { isMissingOrAnonymousUser, unauthenticatedResponse } from "./server-routes.js";
|
|
11
12
|
import { tenantScopedSecrets } from "./tenant-scoped-secrets.js";
|
|
12
13
|
// Only entry:"signature" bypasses jwtGuard (verify() authenticates
|
|
13
14
|
// itself); entry:"anonymous" still needs the anonymousAccess fallthrough
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { HttpRouteMethod } from "@cosmicdrift/kumiko-types/http-route";
|
|
2
|
+
import type { Hono, MiddlewareHandler } from "hono";
|
|
3
|
+
import type { TenantId } from "../engine/types/index.ts";
|
|
4
|
+
import type { Dispatcher } from "../pipeline/dispatcher.ts";
|
|
5
|
+
import { type ClientIpResolver } from "./client-ip.ts";
|
|
6
|
+
import type { ServerWiring } from "./server-wiring.ts";
|
|
7
|
+
export declare function mountFeatureHttpRoutes(app: Hono, wiring: Pick<ServerWiring, "options" | "dispatcher" | "clientIpResolver" | "rateLimitResolver" | "observability">, sessionOnlyHttpRouteGuards: readonly MiddlewareHandler[]): void;
|
|
8
|
+
export declare function mountHonoRoute(app: Hono, method: HttpRouteMethod, path: string, handler: (c: import("hono").Context<any, any>) => Response | Promise<Response>, middlewares?: readonly MiddlewareHandler[]): void;
|
|
9
|
+
export declare function makeSystemQuery(c: import("hono").Context<any, any>, dispatcher: Dispatcher, clientIpResolver?: ClientIpResolver): (type: string, payload: unknown, tenantId: TenantId) => Promise<unknown>;
|