ddd-ts-kit 0.7.0 → 0.9.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.
Files changed (196) hide show
  1. package/README.md +9 -4
  2. package/dist/check/catalogue/architecture-rules.d.ts.map +1 -1
  3. package/dist/check/catalogue/architecture-rules.js +6 -0
  4. package/dist/check/catalogue/architecture-rules.js.map +1 -1
  5. package/dist/check/errors/kit-error-codes.d.ts.map +1 -1
  6. package/dist/check/errors/kit-error-codes.js +5 -0
  7. package/dist/check/errors/kit-error-codes.js.map +1 -1
  8. package/dist/check/explain/errors-docs.js +1 -1
  9. package/dist/check/explain/errors-docs.js.map +1 -1
  10. package/dist/check/explain/persistence-docs.d.ts.map +1 -1
  11. package/dist/check/explain/persistence-docs.js +26 -0
  12. package/dist/check/explain/persistence-docs.js.map +1 -1
  13. package/dist/check/explain/rule-docs.d.ts.map +1 -1
  14. package/dist/check/explain/rule-docs.js +2 -0
  15. package/dist/check/explain/rule-docs.js.map +1 -1
  16. package/dist/check/explain/tenancy-docs.d.ts +3 -0
  17. package/dist/check/explain/tenancy-docs.d.ts.map +1 -0
  18. package/dist/check/explain/tenancy-docs.js +15 -0
  19. package/dist/check/explain/tenancy-docs.js.map +1 -0
  20. package/dist/check/files/file-content-findings.d.ts +4 -0
  21. package/dist/check/files/file-content-findings.d.ts.map +1 -0
  22. package/dist/check/files/file-content-findings.js +29 -0
  23. package/dist/check/files/file-content-findings.js.map +1 -0
  24. package/dist/check/files/file-content-pattern.d.ts +7 -0
  25. package/dist/check/files/file-content-pattern.d.ts.map +1 -0
  26. package/dist/check/files/file-content-pattern.js +17 -0
  27. package/dist/check/files/file-content-pattern.js.map +1 -0
  28. package/dist/check/files/schema-sources.d.ts +13 -0
  29. package/dist/check/files/schema-sources.d.ts.map +1 -0
  30. package/dist/check/files/schema-sources.js +37 -0
  31. package/dist/check/files/schema-sources.js.map +1 -0
  32. package/dist/check/fixtures/files-fixtures.d.ts +3 -0
  33. package/dist/check/fixtures/files-fixtures.d.ts.map +1 -0
  34. package/dist/check/fixtures/files-fixtures.js +92 -0
  35. package/dist/check/fixtures/files-fixtures.js.map +1 -0
  36. package/dist/check/fixtures/fixtures.d.ts.map +1 -1
  37. package/dist/check/fixtures/fixtures.js +4 -0
  38. package/dist/check/fixtures/fixtures.js.map +1 -1
  39. package/dist/check/fixtures/tenancy-fixtures.d.ts +3 -0
  40. package/dist/check/fixtures/tenancy-fixtures.d.ts.map +1 -0
  41. package/dist/check/fixtures/tenancy-fixtures.js +136 -0
  42. package/dist/check/fixtures/tenancy-fixtures.js.map +1 -0
  43. package/dist/check/layers/outside-concern.d.ts.map +1 -1
  44. package/dist/check/layers/outside-concern.js +4 -0
  45. package/dist/check/layers/outside-concern.js.map +1 -1
  46. package/dist/check/rules/files-port-not-connector.d.ts +3 -0
  47. package/dist/check/rules/files-port-not-connector.d.ts.map +1 -0
  48. package/dist/check/rules/files-port-not-connector.js +28 -0
  49. package/dist/check/rules/files-port-not-connector.js.map +1 -0
  50. package/dist/check/rules/persistence-no-file-content.d.ts +3 -0
  51. package/dist/check/rules/persistence-no-file-content.d.ts.map +1 -0
  52. package/dist/check/rules/persistence-no-file-content.js +14 -0
  53. package/dist/check/rules/persistence-no-file-content.js.map +1 -0
  54. package/dist/check/rules/tenancy-scoped-statement.d.ts +3 -0
  55. package/dist/check/rules/tenancy-scoped-statement.d.ts.map +1 -0
  56. package/dist/check/rules/tenancy-scoped-statement.js +37 -0
  57. package/dist/check/rules/tenancy-scoped-statement.js.map +1 -0
  58. package/dist/check/tenancy/balanced-arguments.d.ts +3 -0
  59. package/dist/check/tenancy/balanced-arguments.d.ts.map +1 -0
  60. package/dist/check/tenancy/balanced-arguments.js +13 -0
  61. package/dist/check/tenancy/balanced-arguments.js.map +1 -0
  62. package/dist/check/tenancy/declared-with.d.ts +11 -0
  63. package/dist/check/tenancy/declared-with.d.ts.map +1 -0
  64. package/dist/check/tenancy/declared-with.js +13 -0
  65. package/dist/check/tenancy/declared-with.js.map +1 -0
  66. package/dist/check/tenancy/drizzle-unscoped.d.ts +7 -0
  67. package/dist/check/tenancy/drizzle-unscoped.d.ts.map +1 -0
  68. package/dist/check/tenancy/drizzle-unscoped.js +35 -0
  69. package/dist/check/tenancy/drizzle-unscoped.js.map +1 -0
  70. package/dist/check/tenancy/executor-uses.d.ts +11 -0
  71. package/dist/check/tenancy/executor-uses.d.ts.map +1 -0
  72. package/dist/check/tenancy/executor-uses.js +14 -0
  73. package/dist/check/tenancy/executor-uses.js.map +1 -0
  74. package/dist/check/tenancy/knex-unscoped.d.ts +7 -0
  75. package/dist/check/tenancy/knex-unscoped.d.ts.map +1 -0
  76. package/dist/check/tenancy/knex-unscoped.js +19 -0
  77. package/dist/check/tenancy/knex-unscoped.js.map +1 -0
  78. package/dist/check/tenancy/unscoped-read-models.d.ts +4 -0
  79. package/dist/check/tenancy/unscoped-read-models.d.ts.map +1 -0
  80. package/dist/check/tenancy/unscoped-read-models.js +15 -0
  81. package/dist/check/tenancy/unscoped-read-models.js.map +1 -0
  82. package/dist/commands/init.d.ts.map +1 -1
  83. package/dist/commands/init.js +2 -0
  84. package/dist/commands/init.js.map +1 -1
  85. package/dist/config/index.d.ts +1 -1
  86. package/dist/config/index.d.ts.map +1 -1
  87. package/dist/config/index.js +1 -1
  88. package/dist/config/index.js.map +1 -1
  89. package/dist/config/parse-stack.d.ts.map +1 -1
  90. package/dist/config/parse-stack.js +3 -1
  91. package/dist/config/parse-stack.js.map +1 -1
  92. package/dist/config/stack.d.ts +18 -0
  93. package/dist/config/stack.d.ts.map +1 -1
  94. package/dist/config/stack.js +8 -0
  95. package/dist/config/stack.js.map +1 -1
  96. package/dist/config/written-stack.d.ts.map +1 -1
  97. package/dist/config/written-stack.js +6 -2
  98. package/dist/config/written-stack.js.map +1 -1
  99. package/dist/generate/kinds/file-upload/write-upload-controller.d.ts +5 -0
  100. package/dist/generate/kinds/file-upload/write-upload-controller.d.ts.map +1 -0
  101. package/dist/generate/kinds/file-upload/write-upload-controller.js +42 -0
  102. package/dist/generate/kinds/file-upload/write-upload-controller.js.map +1 -0
  103. package/dist/generate/kinds/file-upload-kind.d.ts +3 -0
  104. package/dist/generate/kinds/file-upload-kind.d.ts.map +1 -0
  105. package/dist/generate/kinds/file-upload-kind.js +55 -0
  106. package/dist/generate/kinds/file-upload-kind.js.map +1 -0
  107. package/dist/generate/kinds/generate-repository.js +5 -4
  108. package/dist/generate/kinds/generate-repository.js.map +1 -1
  109. package/dist/generate/kinds.d.ts.map +1 -1
  110. package/dist/generate/kinds.js +2 -0
  111. package/dist/generate/kinds.js.map +1 -1
  112. package/dist/help/usage.d.ts +1 -1
  113. package/dist/help/usage.d.ts.map +1 -1
  114. package/dist/help/usage.js +3 -2
  115. package/dist/help/usage.js.map +1 -1
  116. package/dist/init/files/platform-files.d.ts.map +1 -1
  117. package/dist/init/files/platform-files.js +22 -0
  118. package/dist/init/files/platform-files.js.map +1 -1
  119. package/dist/init/manifest/dependencies-for.d.ts.map +1 -1
  120. package/dist/init/manifest/dependencies-for.js +7 -1
  121. package/dist/init/manifest/dependencies-for.js.map +1 -1
  122. package/dist/init/manifest/versions.d.ts.map +1 -1
  123. package/dist/init/manifest/versions.js +28 -23
  124. package/dist/init/manifest/versions.js.map +1 -1
  125. package/dist/init/stack/resolve-stack.d.ts.map +1 -1
  126. package/dist/init/stack/resolve-stack.js +13 -2
  127. package/dist/init/stack/resolve-stack.js.map +1 -1
  128. package/dist/init/stack/resolve-tenancy.d.ts +8 -0
  129. package/dist/init/stack/resolve-tenancy.d.ts.map +1 -0
  130. package/dist/init/stack/resolve-tenancy.js +31 -0
  131. package/dist/init/stack/resolve-tenancy.js.map +1 -0
  132. package/dist/init/stack/stack-options.d.ts +2 -0
  133. package/dist/init/stack/stack-options.d.ts.map +1 -1
  134. package/dist/init/template-vars.d.ts.map +1 -1
  135. package/dist/init/template-vars.js +3 -2
  136. package/dist/init/template-vars.js.map +1 -1
  137. package/dist/stack/files-vars.d.ts +5 -0
  138. package/dist/stack/files-vars.d.ts.map +1 -0
  139. package/dist/stack/files-vars.js +11 -0
  140. package/dist/stack/files-vars.js.map +1 -0
  141. package/dist/stack/stack-vars.d.ts.map +1 -1
  142. package/dist/stack/stack-vars.js +14 -4
  143. package/dist/stack/stack-vars.js.map +1 -1
  144. package/dist/version.d.ts +1 -1
  145. package/dist/version.js +1 -1
  146. package/package.json +3 -3
  147. package/templates/file-upload/command.ts.tpl +41 -0
  148. package/templates/file-upload/controller.spec.ts.tpl +46 -0
  149. package/templates/file-upload/controller.ts.tpl +23 -0
  150. package/templates/file-upload/handler.declared.ts.tpl +18 -0
  151. package/templates/file-upload/handler.spec.ts.tpl +79 -0
  152. package/templates/file-upload/handler.ts.tpl +16 -0
  153. package/templates/file-upload/wiring.manual.tpl +9 -0
  154. package/templates/file-upload/wiring.tsyringe.tpl +7 -0
  155. package/templates/init/README.md.tpl +22 -0
  156. package/templates/init/docker/docker-compose.yml.tpl +25 -0
  157. package/templates/init/docker/env.example.tpl +21 -0
  158. package/templates/init/gitignore.tpl +3 -0
  159. package/templates/init/main.ts.tpl +6 -0
  160. package/templates/init/platform/audit/audit.module.manual.ts.tpl +5 -0
  161. package/templates/init/platform/audit/audit.module.tsyringe.ts.tpl +5 -0
  162. package/templates/init/platform/audit/create-audit.ts.tpl +24 -0
  163. package/templates/init/platform/audit/search-audit-entries.handler.ts.tpl +13 -0
  164. package/templates/init/platform/audit/search-audit-entries.query.ts.tpl +5 -0
  165. package/templates/init/platform/auth/http-boundary.ts.tpl +62 -1
  166. package/templates/init/platform/buses/create-command-bus.ts.tpl +7 -1
  167. package/templates/init/platform/compose-application.manual.ts.tpl +28 -0
  168. package/templates/init/platform/compose-application.tsyringe.ts.tpl +45 -0
  169. package/templates/init/platform/config/app-config.ts.tpl +7 -0
  170. package/templates/init/platform/config/load-config.ts.tpl +9 -0
  171. package/templates/init/platform/config/read-files.local.ts.tpl +39 -0
  172. package/templates/init/platform/config/read-files.s3.ts.tpl +42 -0
  173. package/templates/init/platform/create-platform.manual.ts.tpl +38 -1
  174. package/templates/init/platform/database/persistence-over.knex.ts.tpl +5 -0
  175. package/templates/init/platform/database/schema.drizzle.ts.tpl +8 -0
  176. package/templates/init/platform/database/schema.knex.ts.tpl +6 -0
  177. package/templates/init/platform/files/bind-files.tsyringe.ts.tpl +32 -0
  178. package/templates/init/platform/files/create-files.ts.tpl +34 -0
  179. package/templates/init/platform/files/file-routes.ts.tpl +10 -0
  180. package/templates/init/platform/files/files.module.tsyringe.ts.tpl +18 -0
  181. package/templates/init/platform/files/open-files.local.ts.tpl +13 -0
  182. package/templates/init/platform/files/open-files.s3.ts.tpl +10 -0
  183. package/templates/init/platform/files/staging-uploads.tsyringe.ts.tpl +11 -0
  184. package/templates/init/platform/http/start-http-server.express.ts.tpl +5 -1
  185. package/templates/init/platform/http/start-http-server.fastify.ts.tpl +4 -1
  186. package/templates/init/platform/http/start-http-server.nest.ts.tpl +12 -1
  187. package/templates/init/platform/platform-test.module.tsyringe.ts.tpl +11 -0
  188. package/templates/init/platform/platform.manual.ts.tpl +7 -0
  189. package/templates/init/rules/application.md.tpl +3 -0
  190. package/templates/init/rules/infrastructure.md.tpl +4 -0
  191. package/templates/init/rules/platform.md.tpl +3 -0
  192. package/templates/pipeline/package-scripts.json +1 -1
  193. package/templates/repository/drizzle/repository.ts.tpl +7 -8
  194. package/templates/repository/knex/repository.ts.tpl +32 -12
  195. package/templates/service/main.ts.tpl +6 -0
  196. package/templates/worker/main.ts.tpl +6 -0
@@ -163,6 +163,28 @@ and `execution.scheduledAt` says which period the work is for.
163
163
  on the API), or initialise the project with `--cache redis`, which binds `RedisLock`, or bind a
164
164
  lock between processes of your own to `Lock` in the platform.
165
165
  {{/unless}}
166
+ {{#if files.any}}
167
+
168
+ ## Files
169
+
170
+ The content of a file lives in a file storage, never in the database: {{#if files.local}}a directory
171
+ (`FILES_DIRECTORY`, `.data/files` by default, kept out of version control) whose signed links the
172
+ application answers under `/files`; before running several instances, move to an object store
173
+ with `npx ddd-ts-kit init --force --storage s3`{{/if}}{{#if files.s3}}a bucket of the S3 protocol (`S3_*` variables), MinIO
174
+ in `docker-compose.yml` while developing, which creates the bucket at its first start{{/if}}. The tests keep files in memory. An
175
+ aggregate keeps the `StoredFile` reference (key, size, media type, checksum). The command bus
176
+ stages a file a command carries before the transaction opens, `FileStaging` moves it to its key
177
+ with the commit and, every hour, purges what refused or rolled-back commands left in `staging/`. `npx ddd-ts-kit generate file-upload <context> <UseCase>` writes an
178
+ upload; see https://github.com/gbourgeat/ddd-ts-kit/blob/main/docs/concepts/file-storage.md.
179
+ {{#if files.local}}
180
+
181
+ | Variable | Says |
182
+ |---|---|
183
+ | `FILES_DIRECTORY` | the directory of the files, `.data/files` by default |
184
+ | `FILES_PUBLIC_URL` | where clients reach `/files`, which signed links point to: required in production, `http://localhost:<PORT>/files` elsewhere |
185
+ | `FILES_SIGNING_SECRET` | signs the links, 32 characters at least: required in production, even before the first file arrives; drawn at each start elsewhere |
186
+ {{/if}}
187
+ {{/if}}
166
188
  {{#if errors.sentry}}
167
189
 
168
190
  ## Error reporting
@@ -118,6 +118,28 @@ services:
118
118
  timeout: 3s
119
119
  retries: 30
120
120
 
121
+ {{/if}}
122
+ {{#if files.s3}}
123
+ # MinIO, an S3 server for local use (pgsty/minio builds it from the upstream sources, which no longer publish images).
124
+ # The bucket of S3_BUCKET is created at the first start; its root account is for local development ONLY.
125
+ minio:
126
+ image: pgsty/minio:RELEASE.2026-08-04T00-00-00Z@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372
127
+ entrypoint: ["sh", "-c"]
128
+ command: ["mkdir -p /data/$${S3_BUCKET} && exec minio server /data"]
129
+ environment:
130
+ MINIO_ROOT_USER: ${S3_ACCESS_KEY_ID:-minio-app}
131
+ MINIO_ROOT_PASSWORD: ${S3_SECRET_ACCESS_KEY:-minio-app-secret}
132
+ S3_BUCKET: ${S3_BUCKET:-{{project.name}}-files}
133
+ ports:
134
+ - "127.0.0.1:${MINIO_PORT:-9000}:9000"
135
+ volumes:
136
+ - minio-data:/data
137
+ healthcheck:
138
+ test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "http://127.0.0.1:9000/minio/health/ready"]
139
+ interval: 2s
140
+ timeout: 3s
141
+ retries: 30
142
+
121
143
  {{/if}}
122
144
  {{#if authn.keycloak}}
123
145
  # Keycloak {{keycloak.version}} in development mode, for local use only: it imports docker/keycloak/{{project.name}}-realm.json
@@ -232,3 +254,6 @@ volumes:
232
254
  {{#if errors.sentry}}
233
255
  glitchtip-postgres:
234
256
  {{/if}}
257
+ {{#if files.s3}}
258
+ minio-data:
259
+ {{/if}}
@@ -126,6 +126,27 @@ KEYCLOAK_AUDIENCE={{project.name}}-api
126
126
  # SENTRY_SCRUB_MESSAGES=false
127
127
  GLITCHTIP_PORT=8000
128
128
  {{/if}}
129
+ {{#if files.local}}
130
+
131
+ # Files live in a directory, never in the database; the application answers their signed links under /files.
132
+ # FILES_DIRECTORY=.data/files
133
+ # Where clients reach /files: required in production, this value by default elsewhere.
134
+ # FILES_PUBLIC_URL=http://localhost:3000/files
135
+ # Signs the links, 32 characters at least: required in production (openssl rand -hex 32), drawn at each start elsewhere.
136
+ # FILES_SIGNING_SECRET=
137
+ {{/if}}
138
+ {{#if files.s3}}
139
+
140
+ # Files live in a bucket of the S3 protocol (MinIO in docker-compose.yml), never in the database.
141
+ # For AWS leave S3_ENDPOINT out; OVHcloud, Scaleway and Cloudflare R2 give their own endpoint (S3_REGION=auto for R2).
142
+ S3_ENDPOINT=http://localhost:9000
143
+ S3_REGION=us-east-1
144
+ S3_BUCKET={{project.name}}-files
145
+ # The root account of the local MinIO, for local development ONLY: in a deployment, an access key allowed on this bucket only.
146
+ S3_ACCESS_KEY_ID=minio-app
147
+ S3_SECRET_ACCESS_KEY=minio-app-secret
148
+ MINIO_PORT=9000
149
+ {{/if}}
129
150
 
130
151
  # Traces: start Jaeger with `docker compose --profile observability up -d jaeger`, then open http://127.0.0.1:16686
131
152
  # Without an endpoint no span leaves the process.
@@ -7,3 +7,6 @@ dist
7
7
  {{#if orm.prisma}}
8
8
  generated
9
9
  {{/if}}
10
+ {{#if files.local}}
11
+ .data/
12
+ {{/if}}
@@ -14,6 +14,9 @@ import { {{events.providerName}} } from '{{alias.platform}}/events/{{events.prov
14
14
  {{#if events.outbox}}
15
15
  import { startOutboxRelay } from '{{alias.platform}}/events/start-outbox-relay{{alias.ext}}';
16
16
  {{/if}}
17
+ {{#if files.any}}
18
+ import { openFiles } from '{{alias.platform}}/files/open-files{{alias.ext}}';
19
+ {{/if}}
17
20
  {{#if http.any}}
18
21
  import { startHttpServer } from '{{alias.platform}}/http/start-http-server{{alias.ext}}';
19
22
  {{/if}}
@@ -48,6 +51,9 @@ const application = composeApplication(persistence, {
48
51
  {{#if cache.redis}}
49
52
  redis,
50
53
  {{/if}}
54
+ {{#if files.any}}
55
+ files: openFiles(config.files),
56
+ {{/if}}
51
57
  });
52
58
 
53
59
  await application.start();
@@ -29,7 +29,12 @@ interface AuditWiring {
29
29
  * use case so that reading the trail is authorized and recorded.
30
30
  */
31
31
  export function auditModule(platform: Platform): AuditWiring {
32
+ {{#if tenancy.any}}
33
+ platform.queries.register(SearchAuditEntriesQuery, new SearchAuditEntriesHandler(platform.audit.reader), {
34
+ {{/if}}
35
+ {{#unless tenancy.any}}
32
36
  platform.queries.register(SearchAuditEntriesQuery, new SearchAuditEntriesHandler(platform.audit.trail), {
37
+ {{/unless}}
33
38
  context: 'audit',
34
39
  });
35
40
 
@@ -22,7 +22,12 @@ export function auditModule(audit: Audit): ContextModule {
22
22
  name: 'audit',
23
23
  register(builder) {
24
24
  builder.bind(AuditTrail).toValue(audit.trail);
25
+ {{#if tenancy.any}}
26
+ builder.bind(AuditReader).toValue(audit.reader);
27
+ {{/if}}
28
+ {{#unless tenancy.any}}
25
29
  builder.bind(AuditReader).toValue(audit.trail);
30
+ {{/unless}}
26
31
  {{#if audit.route}}
27
32
  {{#if authz.rebac}}
28
33
 
@@ -1,22 +1,32 @@
1
1
  {{#if audit.sql}}
2
2
  import {
3
+ {{#if tenancy.any}}
4
+ TenantAuditReader,
5
+ {{/if}}
3
6
  auditDecisions,
7
+ auditGuardRefusals,
4
8
  auditIntegrationEvents,
5
9
  auditMiddleware,
6
10
  type AuditReader,
7
11
  type AuditSource,
8
12
  type AuditTrail,
13
+ type GuardRefusalOfARoute,
9
14
  } from '@ddd-ts-kit/audit';
10
15
  {{/if}}
11
16
  {{#if audit.memory}}
12
17
  import {
13
18
  InMemoryAuditTrail,
19
+ {{#if tenancy.any}}
20
+ TenantAuditReader,
21
+ {{/if}}
14
22
  auditDecisions,
23
+ auditGuardRefusals,
15
24
  auditIntegrationEvents,
16
25
  auditMiddleware,
17
26
  type AuditReader,
18
27
  type AuditSource,
19
28
  type AuditTrail,
29
+ type GuardRefusalOfARoute,
20
30
  } from '@ddd-ts-kit/audit';
21
31
  {{/if}}
22
32
  {{#if audit.knex}}
@@ -50,8 +60,18 @@ const consumer = 'audit';
50
60
  */
51
61
  export interface Audit {
52
62
  readonly trail: AuditTrail & AuditReader;
63
+ {{#if tenancy.any}}
64
+ /**
65
+ * The trail as the read side searches it: confined to the tenant of the work in progress,
66
+ * whatever the filter or the actor says. Platform staff read across tenants only inside
67
+ * `acrossTenants`, which records the elevation first; work in no tenant is refused.
68
+ */
69
+ readonly reader: AuditReader;
70
+ {{/if}}
53
71
  /** The `onDecision` hook of the authorization: who was allowed or refused what. */
54
72
  readonly decisions: OnDecision;
73
+ /** The `onGuardRefusal` hook of the HTTP pipeline: who a guard refused at the edge, before any use case. */
74
+ readonly refusals: (refusal: GuardRefusalOfARoute) => Promise<void>;
55
75
  /** On the command bus, before the unit of work: which command ran and how it ended. */
56
76
  readonly commands: BusMiddleware;
57
77
  /** On the query bus: whoever reads the trail leaves an entry in it. */
@@ -68,6 +88,10 @@ export function createAudit(persistence: Persistence, source: AuditSource): Audi
68
88
 
69
89
  return {
70
90
  trail,
91
+ {{#if tenancy.any}}
92
+ reader: new TenantAuditReader(trail, source.scope),
93
+ {{/if}}
94
+ refusals: auditGuardRefusals(trail, source),
71
95
  {{#if audit.route}}
72
96
  decisions: auditDecisions(trail, { ...source, sensitivePermissions: [auditPermissions['trail.read'].id] }),
73
97
  // TODO(platform): declare what may go into `changes` with `fields: [auditedFields(SomeCommand, ['status'])]`; by default an entry carries identifiers and codes only.
@@ -5,6 +5,18 @@ import type { SearchAuditEntriesQuery } from '{{alias.platform}}/audit/search-au
5
5
  export class SearchAuditEntriesHandler implements QueryHandler<SearchAuditEntriesQuery> {
6
6
  constructor(private readonly reader: AuditReader) {}
7
7
 
8
+ {{#if tenancy.any}}
9
+ /**
10
+ * The permission was decided by the guard of the bus. The reader is the tenant audit reader
11
+ * of the platform: it bounds the read to the tenant of the work in progress, in the statement
12
+ * and never in memory, whatever the filter says. Platform staff read across tenants only
13
+ * through `acrossTenants`, never because their actor names no tenant.
14
+ */
15
+ async execute(query: SearchAuditEntriesQuery): Promise<Page<AuditEntry>> {
16
+ return this.reader.search(query.filter, query.page);
17
+ }
18
+ {{/if}}
19
+ {{#unless tenancy.any}}
8
20
  /**
9
21
  * The permission was decided by the guard of the bus. The tenant of the actor then bounds the
10
22
  * read itself, in the statement and never in memory: a tenant lists its own chain, and only an
@@ -15,4 +27,5 @@ export class SearchAuditEntriesHandler implements QueryHandler<SearchAuditEntrie
15
27
 
16
28
  return this.reader.search({ ...query.filter, ...(tenantId === undefined ? {} : { tenantId }) }, query.page);
17
29
  }
30
+ {{/unless}}
18
31
  }
@@ -1,7 +1,12 @@
1
1
  import type { AuditEntry, AuditFilter, AuditSortField } from '@ddd-ts-kit/audit';
2
2
  import { AuthorizedQuery, type Actor, type Page, type PageRequest } from '@ddd-ts-kit/kernel';
3
3
 
4
+ {{#if tenancy.any}}
5
+ /** What a reader of the trail may narrow the search by. The tenant is the one of the work, never a filter. */
6
+ {{/if}}
7
+ {{#unless tenancy.any}}
4
8
  /** What a reader of the trail may narrow the search by. The tenant is not among them: it is the one of the actor. */
9
+ {{/unless}}
5
10
  export type AuditEntriesFilter = Pick<AuditFilter, 'actorId' | 'action' | 'outcome' | 'correlationId'>;
6
11
 
7
12
  /** A page of the audit trail, for whoever holds `audit:trail.read`. */
@@ -1,12 +1,40 @@
1
1
  import type { Authenticator } from '@ddd-ts-kit/auth';
2
2
  {{#if errors.none}}
3
- import type { ErrorContext, ErrorMapper, RouteAround } from '@ddd-ts-kit/http';
3
+ import type { ErrorContext, ErrorMapper, {{#if audit.on}}GuardRefusal, {{/if}}RouteAround{{#if files.http}}, UploadReader{{/if}} } from '@ddd-ts-kit/http';
4
4
  import type { Clock, ExecutionScope, Logger, Session } from '@ddd-ts-kit/kernel';
5
5
  {{/if}}
6
6
  {{#if errors.sentry}}
7
+ {{#unless audit.on}}
8
+ {{#unless files.http}}
7
9
  import { reportHttpErrors, type ErrorContext, type ErrorMapper, type RouteAround } from '@ddd-ts-kit/http';
10
+ {{/unless}}
11
+ {{#if files.http}}
12
+ import {
13
+ reportHttpErrors,
14
+ type ErrorContext,
15
+ type ErrorMapper,
16
+ type RouteAround,
17
+ type UploadReader,
18
+ } from '@ddd-ts-kit/http';
19
+ {{/if}}
20
+ {{/unless}}
21
+ {{#if audit.on}}
22
+ import {
23
+ reportHttpErrors,
24
+ type ErrorContext,
25
+ type ErrorMapper,
26
+ type GuardRefusal,
27
+ type RouteAround,
28
+ {{#if files.http}}
29
+ type UploadReader,
30
+ {{/if}}
31
+ } from '@ddd-ts-kit/http';
32
+ {{/if}}
8
33
  import type { Clock, ErrorReporter, ExecutionScope, Logger, Session } from '@ddd-ts-kit/kernel';
9
34
  {{/if}}
35
+ {{#if files.http}}
36
+ import { multipartUploads } from '@ddd-ts-kit/http/uploads';
37
+ {{/if}}
10
38
  import { tracedRoutes } from '@ddd-ts-kit/tracing';
11
39
  import { principalOf } from '{{alias.platform}}/auth/principal-of{{alias.ext}}';
12
40
 
@@ -21,6 +49,14 @@ export interface HttpBoundary {
21
49
  readonly onError: (error: unknown, context: ErrorContext) => void;
22
50
  /** The span of a request, named by its route template; probes and documentation routes make none. */
23
51
  readonly around: RouteAround;
52
+ {{#if files.http}}
53
+ /** Reads the file of a controller that declares an upload, as it streams: its size and media types are checked on the way. */
54
+ readonly uploads: UploadReader;
55
+ {{/if}}
56
+ {{#if audit.on}}
57
+ /** A request a guard refused at the edge, written to the audit trail as a denied decision. */
58
+ readonly onGuardRefusal: (refusal: GuardRefusal) => Promise<void>;
59
+ {{/if}}
24
60
  }
25
61
 
26
62
  interface Edge {
@@ -29,6 +65,10 @@ interface Edge {
29
65
  readonly errorMapper: ErrorMapper;
30
66
  readonly clock: Clock;
31
67
  readonly logger: Logger;
68
+ {{#if audit.on}}
69
+ /** Where a refusal at the edge is recorded: the audit trail. */
70
+ readonly refusals: (refusal: GuardRefusal) => Promise<void>;
71
+ {{/if}}
32
72
  {{#if errors.sentry}}
33
73
  /** Where a request answered 5xx is reported, unless a bus already reported its failure. */
34
74
  readonly errors: ErrorReporter;
@@ -37,7 +77,19 @@ interface Edge {
37
77
 
38
78
  /** A request is authenticated once, then handled inside the execution scope, so infrastructure sees who acts and under which correlation. */
39
79
  {{#if errors.none}}
80
+ {{#unless audit.on}}
40
81
  export function httpBoundary({ authenticator, executionScope, errorMapper, clock, logger }: Edge): HttpBoundary {
82
+ {{/unless}}
83
+ {{#if audit.on}}
84
+ export function httpBoundary({
85
+ authenticator,
86
+ executionScope,
87
+ errorMapper,
88
+ clock,
89
+ logger,
90
+ refusals,
91
+ }: Edge): HttpBoundary {
92
+ {{/if}}
41
93
  {{/if}}
42
94
  {{#if errors.sentry}}
43
95
  export function httpBoundary({
@@ -46,6 +98,9 @@ export function httpBoundary({
46
98
  errorMapper,
47
99
  clock,
48
100
  logger,
101
+ {{#if audit.on}}
102
+ refusals,
103
+ {{/if}}
49
104
  errors,
50
105
  }: Edge): HttpBoundary {
51
106
  const report = reportHttpErrors(errors);
@@ -57,6 +112,12 @@ export function httpBoundary({
57
112
  errorMapper,
58
113
  clock,
59
114
  around: tracedRoutes(),
115
+ {{#if files.http}}
116
+ uploads: multipartUploads(),
117
+ {{/if}}
118
+ {{#if audit.on}}
119
+ onGuardRefusal: refusals,
120
+ {{/if}}
60
121
  // The message of the error may quote data: only the code and the route are logged.
61
122
  {{#if errors.none}}
62
123
  onError: (_error, context) => {
@@ -31,6 +31,9 @@ import {
31
31
  } from '@ddd-ts-kit/kernel';
32
32
  {{/unless}}
33
33
  {{/if}}
34
+ {{#if files.any}}
35
+ import { stagingUploads } from '{{alias.platform}}/files/staging-uploads{{alias.ext}}';
36
+ {{/if}}
34
37
  import type { Foundations } from '{{alias.platform}}/lay-foundations{{alias.ext}}';
35
38
  {{#if cache.relaySignal}}
36
39
  import type { RedisServices } from '{{alias.platform}}/redis/open-redis{{alias.ext}}';
@@ -48,7 +51,7 @@ interface Signalled {
48
51
  * Around every command, outermost first: the report of an unexpected failure (a failed commit
49
52
  * included), the log entry and the measure of the use case, the
50
53
  {{/if}}
51
- * permission, the span of the use case (a refused command never started){{#if cache.relaySignal}}, the wake-up of the outbox relay{{/if}}{{#if audit.on}}, the audit entry{{/if}}, then the unit of work. The guard and the unit of
54
+ * permission, the span of the use case (a refused command never started){{#if files.any}}, the staging of the file it carries{{/if}}{{#if cache.relaySignal}}, the wake-up of the outbox relay{{/if}}{{#if audit.on}}, the audit entry{{/if}}, then the unit of work. The guard and the unit of
52
55
  * work are resolved at each command: building the bus must not open anything.{{#if audit.on}} The audit entry
53
56
  * opens the transaction itself, so that the entry of a success commits with the state change
54
57
  * and the entry of a failure survives the rollback.{{/if}}
@@ -69,6 +72,9 @@ export function createCommandBus(resolve: Resolve, foundations: Foundations): In
69
72
  .use(metricsMiddleware(foundations.metrics))
70
73
  .use((message, next, info) => resolve(UseCaseGuard).check(message, next, info))
71
74
  .use(foundations.traced.useCase)
75
+ {{#if files.any}}
76
+ .use(stagingUploads(resolve))
77
+ {{/if}}
72
78
  {{#if cache.relaySignal}}
73
79
  .use(wakingTheRelay(options.redis))
74
80
  {{/if}}
@@ -11,6 +11,9 @@ import { subscribeAll } from '@ddd-ts-kit/events';
11
11
  {{#if http.any}}
12
12
  import { createErrorMapper, defineRoutes, type Route } from '@ddd-ts-kit/http';
13
13
  {{/if}}
14
+ {{#if files.any}}
15
+ import { PurgeStagedFiles } from '@ddd-ts-kit/kernel';
16
+ {{/if}}
14
17
  {{#if cache.rateLimit}}
15
18
  import type { IntegrationEventPublisher, IntegrationEventSubscriber, Logger, RateLimiter } from '@ddd-ts-kit/kernel';
16
19
  {{/if}}
@@ -28,6 +31,9 @@ import { relateSystemActors } from '{{alias.platform}}/auth/relate-system-actors
28
31
  {{/if}}
29
32
  import { createPlatform, type PlatformOptions } from '{{alias.platform}}/create-platform{{alias.ext}}';
30
33
  import type { Persistence } from '{{alias.platform}}/database/persistence{{alias.ext}}';
34
+ {{#if files.http}}
35
+ import { fileRoutes } from '{{alias.platform}}/files/file-routes{{alias.ext}}';
36
+ {{/if}}
31
37
  import type { Platform } from '{{alias.platform}}/platform{{alias.ext}}';
32
38
  // ddd-ts-kit:imports
33
39
  // /ddd-ts-kit:imports
@@ -65,6 +71,10 @@ export interface Application {
65
71
  /** Authenticates every request and runs it inside the execution scope. */
66
72
  readonly boundary: HttpBoundary;
67
73
  {{/if}}
74
+ {{#if files.http}}
75
+ /** The routes that answer the signed links of a storage the application serves itself; mounted before any body parser. */
76
+ readonly fileRoutes: readonly Route[];
77
+ {{/if}}
68
78
  {{#unless http.any}}
69
79
  readonly routes: readonly never[];
70
80
  readonly contexts: readonly ContextWiring[];
@@ -101,6 +111,9 @@ export function composeApplication(
101
111
  const { logger, metrics, cache, clock } = platform;
102
112
 
103
113
  installAspectRuntime({ logger, metrics, cache, clock });
114
+ {{#if files.any}}
115
+ purgeStagedFiles(platform);
116
+ {{/if}}
104
117
 
105
118
  {{#if audit.route}}
106
119
  const contexts = [...selection, auditModule].map((module) => module(platform));
@@ -120,6 +133,9 @@ export function composeApplication(
120
133
  errorMapper: createErrorMapper(),
121
134
  clock,
122
135
  logger,
136
+ {{#if audit.on}}
137
+ refusals: platform.audit.refusals,
138
+ {{/if}}
123
139
  {{#if errors.sentry}}
124
140
  errors: platform.errors,
125
141
  {{/if}}
@@ -129,6 +145,9 @@ export function composeApplication(
129
145
  routes: [],
130
146
  contexts,
131
147
  {{/unless}}
148
+ {{#if files.http}}
149
+ fileRoutes: fileRoutes(platform.files.storage),
150
+ {{/if}}
132
151
  eventBus: platform.eventBus,
133
152
  {{#if broker.external}}
134
153
  // Behind a broker a listener has queues of its own, under its own name.
@@ -185,3 +204,12 @@ async function stop(platform: Platform, options: ApplicationOptions): Promise<vo
185
204
  {{/if}}
186
205
  await platform.logger.flush();
187
206
  }
207
+ {{#if files.any}}
208
+
209
+ /** What rolled-back commands left in `staging/`, removed every hour by the process that runs the jobs. */
210
+ function purgeStagedFiles(platform: Platform): void {
211
+ const purge = new PurgeStagedFiles(platform.files.staging, platform.clock);
212
+
213
+ platform.jobs.register({ name: 'files.purge-staged', schedule: { every: '1h' }, run: () => purge.run() });
214
+ }
215
+ {{/if}}
@@ -38,6 +38,17 @@ import {
38
38
  {{#if http.any}}
39
39
  ExecutionScope,
40
40
  {{/if}}
41
+ {{#if files.http}}
42
+ FileStorage,
43
+ {{/if}}
44
+ {{#if audit.on}}
45
+ {{#if http.any}}
46
+ IdGenerator,
47
+ {{/if}}
48
+ {{/if}}
49
+ {{#if files.any}}
50
+ InMemoryFileStorage,
51
+ {{/if}}
41
52
  {{#unless broker.external}}
42
53
  IntegrationEventSubscriber,
43
54
  {{/unless}}
@@ -50,6 +61,11 @@ import {
50
61
  RateLimiter,
51
62
  {{/if}}
52
63
  scopedPublisher,
64
+ {{#if files.any}}
65
+ {{#unless files.http}}
66
+ type FileStorage,
67
+ {{/unless}}
68
+ {{/if}}
53
69
  type IntegrationEventPublisher,
54
70
  {{#if broker.external}}
55
71
  type IntegrationEventSubscriber,
@@ -57,6 +73,9 @@ import {
57
73
  } from '@ddd-ts-kit/kernel';
58
74
  import { tracedPublisher } from '@ddd-ts-kit/tracing';
59
75
  {{#if audit.on}}
76
+ {{#if http.any}}
77
+ import { AuditTrail, auditGuardRefusals } from '@ddd-ts-kit/audit';
78
+ {{/if}}
60
79
  import { auditModule } from '{{alias.platform}}/audit/audit.module{{alias.ext}}';
61
80
  {{/if}}
62
81
  {{#if audit.functionRoute}}
@@ -78,6 +97,12 @@ import { relateSystemActors } from '{{alias.platform}}/auth/relate-system-actors
78
97
  import { createCommandBus } from '{{alias.platform}}/buses/create-command-bus{{alias.ext}}';
79
98
  import { createQueryBus } from '{{alias.platform}}/buses/create-query-bus{{alias.ext}}';
80
99
  import type { Persistence } from '{{alias.platform}}/database/persistence{{alias.ext}}';
100
+ {{#if files.http}}
101
+ import { fileRoutes } from '{{alias.platform}}/files/file-routes{{alias.ext}}';
102
+ {{/if}}
103
+ {{#if files.any}}
104
+ import { filesModule } from '{{alias.platform}}/files/files.module{{alias.ext}}';
105
+ {{/if}}
81
106
  import { layFoundations, type Foundations } from '{{alias.platform}}/lay-foundations{{alias.ext}}';
82
107
  import { platformModule, type PlatformOptions } from '{{alias.platform}}/platform.module{{alias.ext}}';
83
108
  // ddd-ts-kit:imports
@@ -86,6 +111,10 @@ import { platformModule, type PlatformOptions } from '{{alias.platform}}/platfor
86
111
  export interface ApplicationOptions extends PlatformOptions {
87
112
  /** Whether this process runs the scheduled jobs, and their settings; left out (the tools, the tests), no job runs by time. */
88
113
  readonly jobs?: JobsOptions;
114
+ {{#if files.any}}
115
+ /** Where the content of files lives: the storage of `main.ts`; left out (the tools, the tests), the memory of the process. */
116
+ readonly files?: FileStorage;
117
+ {{/if}}
89
118
  }
90
119
 
91
120
  export interface Application {
@@ -94,6 +123,10 @@ export interface Application {
94
123
  /** Authenticates every request and runs it inside the execution scope. */
95
124
  readonly boundary: HttpBoundary;
96
125
  {{/if}}
126
+ {{#if files.http}}
127
+ /** The routes that answer the signed links of a storage the application serves itself; mounted before any body parser. */
128
+ readonly fileRoutes: readonly Route[];
129
+ {{/if}}
97
130
  {{#unless http.any}}
98
131
  readonly routes: readonly never[];
99
132
  {{/unless}}
@@ -162,6 +195,9 @@ export function composeApplication(
162
195
  guard,
163
196
  {{#if audit.on}}
164
197
  auditModule(foundations.audit),
198
+ {{/if}}
199
+ {{#if files.any}}
200
+ filesModule(options.files ?? new InMemoryFileStorage()),
165
201
  {{/if}}
166
202
  ...contexts.modules,
167
203
  ],
@@ -232,6 +268,12 @@ function running(container: Container, options: ApplicationOptions, contexts: Co
232
268
  errorMapper: container.resolve(ErrorMapper),
233
269
  clock: container.resolve(Clock),
234
270
  logger,
271
+ {{#if audit.on}}
272
+ refusals: auditGuardRefusals(container.resolve(AuditTrail), {
273
+ clock: container.resolve(Clock),
274
+ ids: container.resolve(IdGenerator),
275
+ }),
276
+ {{/if}}
235
277
  {{#if errors.sentry}}
236
278
  errors: container.resolve(ErrorReporter),
237
279
  {{/if}}
@@ -240,6 +282,9 @@ function running(container: Container, options: ApplicationOptions, contexts: Co
240
282
  {{#unless http.any}}
241
283
  routes: [],
242
284
  {{/unless}}
285
+ {{#if files.http}}
286
+ fileRoutes: fileRoutes(container.resolve(FileStorage)),
287
+ {{/if}}
243
288
  // What the outbox relay delivers with: each publication continues the trace stored with its event.
244
289
  eventBus: tracedPublisher(container.resolve(EventBus)),
245
290
  {{#if broker.external}}
@@ -5,6 +5,9 @@ import type { LogLevel, RateLimit } from '@ddd-ts-kit/kernel';
5
5
  import type { LogLevel } from '@ddd-ts-kit/kernel';
6
6
  {{/unless}}
7
7
  import type { ResilienceSettings } from '{{alias.platform}}/resilience/resilience-settings{{alias.ext}}';
8
+ {{#if files.any}}
9
+ import type { FilesConfig } from '{{alias.platform}}/config/read-files{{alias.ext}}';
10
+ {{/if}}
8
11
  import type { TracingConfig } from '{{alias.platform}}/config/read-tracing{{alias.ext}}';
9
12
 
10
13
  /** The validated configuration of the process: `loadConfig` is the only reader of the environment. */
@@ -49,6 +52,10 @@ export interface AppConfig {
49
52
  /** Where unexpected failures are reported: a Sentry or a GlitchTip project. Without a DSN nothing is reported. */
50
53
  readonly errorReporting: ErrorReportingConfig;
51
54
  {{/if}}
55
+ {{#if files.any}}
56
+ /** Where the content of files lives (`files/open-files.ts`), never in the database. */
57
+ readonly files: FilesConfig;
58
+ {{/if}}
52
59
  }
53
60
 
54
61
  /** `LOG_LEVEL`, `LOG_FORMAT` and `LOG_SCRUB_MESSAGES`. */
@@ -1,6 +1,9 @@
1
1
  import { LOG_LEVELS, type LogLevel } from '@ddd-ts-kit/kernel';
2
2
  import type { AppConfig } from '{{alias.platform}}/config/app-config{{alias.ext}}';
3
3
  import { ConfigError } from '{{alias.platform}}/config/config-error{{alias.ext}}';
4
+ {{#if files.any}}
5
+ import { readFiles } from '{{alias.platform}}/config/read-files{{alias.ext}}';
6
+ {{/if}}
4
7
  import { readTracing } from '{{alias.platform}}/config/read-tracing{{alias.ext}}';
5
8
 
6
9
  const environments = ['development', 'test', 'production'] as const;
@@ -65,6 +68,12 @@ export function loadConfig(env: Variables): AppConfig {
65
68
  {{#if errors.sentry}}
66
69
  errorReporting: readErrorReporting(env, environment, problems),
67
70
  {{/if}}
71
+ {{#if files.local}}
72
+ files: readFiles(env, environment, problems),
73
+ {{/if}}
74
+ {{#if files.s3}}
75
+ files: readFiles(env, problems),
76
+ {{/if}}
68
77
  };
69
78
 
70
79
  if (problems.length > 0) {
@@ -0,0 +1,39 @@
1
+ type Variables = Readonly<Record<string, string | undefined>>;
2
+
3
+ /** Where the local storage keeps the content of files, and how a client reaches its signed links. */
4
+ export interface FilesConfig {
5
+ /** `FILES_DIRECTORY`: a directory out of version control. Default `.data/files`. */
6
+ readonly directory: string;
7
+ /** `FILES_PUBLIC_URL`: where the routes that answer the signed links are reached. Required in production; elsewhere `http://localhost:<PORT>/files` by default. */
8
+ readonly publicUrl: string;
9
+ /** `FILES_SIGNING_SECRET`: signs the links, 32 characters at least. Required in production; left out elsewhere, one is drawn at each start. */
10
+ readonly signingSecret?: string;
11
+ }
12
+
13
+ /** The settings of the local file storage; a problem is reported by variable name only, never by value. */
14
+ export function readFiles(env: Variables, environment: string, problems: string[]): FilesConfig {
15
+ const production = environment === 'production';
16
+ const signingSecret = (env['FILES_SIGNING_SECRET'] ?? '').trim();
17
+
18
+ if (signingSecret.length < 32 && (signingSecret !== '' || production)) {
19
+ problems.push('FILES_SIGNING_SECRET must hold 32 characters at least, and is required in production');
20
+ }
21
+
22
+ return {
23
+ directory: env['FILES_DIRECTORY'] ?? '.data/files',
24
+ publicUrl: publicUrlOf(env, production, problems),
25
+ ...(signingSecret === '' ? {} : { signingSecret }),
26
+ };
27
+ }
28
+
29
+ /** Left to its default in production, every signed link would point at localhost. */
30
+ function publicUrlOf(env: Variables, production: boolean, problems: string[]): string {
31
+ const given = env['FILES_PUBLIC_URL'];
32
+ const publicUrl = given ?? `http://localhost:${env['PORT'] ?? '3000'}/files`;
33
+
34
+ if (!URL.canParse(publicUrl) || (production && given === undefined)) {
35
+ problems.push('FILES_PUBLIC_URL must be a URL, and is required in production');
36
+ }
37
+
38
+ return publicUrl;
39
+ }