@openreachtech/hora-skills-ort-renchan 0.2.2 → 0.4.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 (54) hide show
  1. package/dist/skills/hor-backend-testing/SKILL.md +4 -3
  2. package/dist/skills/hor-backend-testing/references/running-tests.md +9 -1
  3. package/dist/skills/hor-build-e2e-test-environment/SKILL.md +24 -9
  4. package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +11 -7
  5. package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +1 -1
  6. package/dist/skills/hor-cookie-authentication/SKILL.md +4 -2
  7. package/dist/skills/hor-cookie-authentication/references/environment.md +4 -2
  8. package/dist/skills/hor-database-design/references/column-types.md +25 -9
  9. package/dist/skills/hor-database-design/references/datetimes.md +7 -3
  10. package/dist/skills/hor-graphql-schema/SKILL.md +10 -8
  11. package/dist/skills/hor-graphql-server-engine/SKILL.md +376 -44
  12. package/dist/skills/hor-light-rag/SKILL.md +6 -1
  13. package/dist/skills/hor-light-rag/references/retrieval-internals.md +3 -1
  14. package/dist/skills/hor-multi-llm-provider/SKILL.md +158 -20
  15. package/dist/skills/hor-multi-llm-provider/references/access-routes.md +230 -0
  16. package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +9 -3
  17. package/dist/skills/hor-mutation-resolver/SKILL.md +13 -9
  18. package/dist/skills/hor-mutation-resolver/references/errors.md +15 -18
  19. package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +10 -6
  20. package/dist/skills/hor-oidc-sign-in/SKILL.md +61 -0
  21. package/dist/skills/hor-oidc-sign-in/references/environment.md +94 -0
  22. package/dist/skills/hor-oidc-sign-in/references/id-token-verification.md +98 -0
  23. package/dist/skills/hor-oidc-sign-in/references/resolvers.md +134 -0
  24. package/dist/skills/hor-oidc-sign-in/references/storage.md +118 -0
  25. package/dist/skills/hor-query-resolver/SKILL.md +6 -5
  26. package/dist/skills/hor-query-resolver/references/anatomy.md +7 -7
  27. package/dist/skills/hor-query-resolver/references/data-access.md +17 -0
  28. package/dist/skills/hor-query-resolver/references/errors-and-context.md +12 -16
  29. package/dist/skills/hor-renchan-job-bullmq/SKILL.md +15 -6
  30. package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +4 -2
  31. package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +39 -5
  32. package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +57 -0
  33. package/dist/skills/hor-resolver-validator/SKILL.md +5 -6
  34. package/dist/skills/hor-resolver-validator/references/validator-pattern.md +5 -5
  35. package/dist/skills/hor-restfulapi-architecture/SKILL.md +33 -7
  36. package/dist/skills/hor-restfulapi-architecture/references/behind-iap.md +116 -0
  37. package/dist/skills/hor-restfulapi-architecture/references/credential-routes.md +173 -0
  38. package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +11 -5
  39. package/dist/skills/hor-restfulapi-architecture/references/renderers.md +4 -0
  40. package/dist/skills/hor-security-audit/SKILL.md +2 -2
  41. package/dist/skills/hor-security-audit/references/secrets.md +62 -36
  42. package/dist/skills/hor-sequelize-migration/SKILL.md +30 -15
  43. package/dist/skills/hor-sequelize-migration/references/alter-table.md +26 -13
  44. package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +5 -2
  45. package/dist/skills/hor-sequelize-migration/references/indexes.md +41 -2
  46. package/dist/skills/hor-sequelize-migration/references/notation.md +1 -1
  47. package/dist/skills/hor-sequelize-model/references/associations.md +2 -1
  48. package/dist/skills/hor-sequelize-model/references/notation.md +1 -1
  49. package/dist/skills/hor-sequelize-seeder/SKILL.md +9 -4
  50. package/dist/skills/hor-sequelize-seeder/references/notation.md +59 -0
  51. package/dist/skills/hor-type-interface/SKILL.md +48 -32
  52. package/docs/skills.ja.md +5 -4
  53. package/docs/skills.md +5 -4
  54. package/package.json +4 -1
@@ -1,12 +1,12 @@
1
1
  ---
2
2
  name: hor-graphql-server-engine
3
3
  description: >
4
- Implement and wire a GraphQL server engine — a per-endpoint *GraphqlServerEngine class under
5
- server/graphql/ that declares one endpoint's URL, schema path, resolver directories, Share and
6
- Context DI, auth filter, middleware, scalars and error codes, then is booted in server/index.js.
7
- Use whenever the user asks to add a GraphQL endpoint (a new role such as user / admin / portal),
8
- pair a stub engine with an actual one, change its auth policy or public-operation allowlist, or
9
- enable Redis PubSub.
4
+ Implement and wire a GraphQL server engine, the per-endpoint *GraphqlServerEngine class under
5
+ server/graphql/ that declares one endpoint's routing, Share and Context DI, auth filter,
6
+ middleware, scalars and error codes, and decide what the engine and its Share may hold and who
7
+ reads env. Use whenever the user asks to add a GraphQL endpoint (a role such as user / admin),
8
+ pair a stub engine with an actual one, change its auth policy or credential route, or enable Redis
9
+ PubSub.
10
10
  ---
11
11
 
12
12
  # GraphQL Server Engine
@@ -34,7 +34,7 @@ one of these settings — nothing more:
34
34
  | Setting | Member | Section |
35
35
  | --- | --- | --- |
36
36
  | Endpoint routing (URL, schema / resolver dirs, redis) | `static get config` | [§2](#2-static-get-config--the-endpoints-routing-declaration) |
37
- | Middleware (cors / json / static / upload / urlencoded) | `collectMiddleware()` | [§6](#6-middleware-scalars-error-codes) |
37
+ | Middleware (cors through `ExpressMiddleware`, then json / static / upload / urlencoded) | `static get ExpressMiddleware` + `collectMiddleware()` | [§6](#6-middleware-scalars-error-codes) |
38
38
  | Share / Context DI classes | `static get Share` / `static get Context` | [§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver) |
39
39
  | Custom scalars | `collectScalars()` | [§6](#6-middleware-scalars-error-codes) |
40
40
  | Auth policy — the **no-auth (public) operations** + the filter | `schemasToSkipFiltering` + `generateFilterHandler()` | [§4](#4-authentication-schemastoskipfiltering--generatefilterhandler) |
@@ -58,9 +58,9 @@ the resolvers and the context; the engine just points at them.
58
58
  request. Anything stateful or per-request belongs in `Context` (per request) or `Share` (per
59
59
  process); anything domain-specific belongs in a resolver. An engine that starts doing work becomes
60
60
  a god object that every endpoint's behavior routes through.
61
- - **Extend the app base, override only what differs.** The shared middleware and error codes live in
61
+ - **Extend the app base, override only what differs.** The shared middleware classes and error codes live in
62
62
  the app base ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)); a concrete engine should be
63
- mostly `config` + `Share` + `Context` + auth policy.
63
+ mostly `config` + `Share` + `Context` + the public schemas and visa issuers.
64
64
 
65
65
  **Comment language**: the `js` examples in this SKILL.md use English comments (matching the framework
66
66
  files). In the **engine files you generate** (`*GraphqlServerEngine.js`), keep structural comments in
@@ -75,16 +75,25 @@ and overrides only what is endpoint-specific.**
75
75
  | Base | Where | Role |
76
76
  | --- | --- | --- |
77
77
  | `BaseGraphqlServerEngine` | `@openreachtech/renchan` | The **framework contract**: factory (`create` / `createAsync`), `buildErrorHash`, and the abstract members every engine fills in (`config`, `Share`, `Context`, `collectMiddleware`, `generateFilterHandler`, …). |
78
- | `BaseAppGraphqlServerEngine` | `server/graphql/BaseAppGraphqlServerEngine.js` | **This app's shared settings** — factor here anything common to every endpoint: the shared `collectMiddleware()` (cors / json / static / upload / urlencoded) and `standardErrorCodeHash`. |
79
-
80
- - **When a setting is the same for every endpoint, lift it into the app base.** Middleware and the
81
- error-code hash are the usual ones. Each concrete engine then extends `BaseAppGraphqlServerEngine`
82
- and declares only the parts that differ per endpoint — `config`, `Share`, `Context`, and the auth
83
- policy. This keeps one source of truth for the shared config (Open Reach Tech's DRY / "carve once"
78
+ | `BaseAppGraphqlServerEngine` | `server/graphql/BaseAppGraphqlServerEngine.js` | **This app's shared settings** — factor here anything common to every endpoint, such as `standardErrorCodeHash`. |
79
+
80
+ - **Lift a member into the app base only when its logic is the same for every endpoint, always.**
81
+ Similar is not the same. Admin and customer declare different schemas, so
82
+ `schemasToSkipFiltering` stays in each engine, and `visaIssuers` stays because one role may
83
+ tighten its login checks later. `ExpressMiddleware` stays because each endpoint lists its own
84
+ CORS class. The error-code hash is the shared one.
85
+ `generateFilterHandler()` and `collectScalars()` read the same in every engine today, but
86
+ lifting them is a refactor of its own: a change that moves them goes in its own pull request,
87
+ never inside one with another purpose. Each concrete engine then extends
88
+ `BaseAppGraphqlServerEngine` and declares the rest — `config`, `Share`, `Context`, `ExpressMiddleware`,
89
+ `schemasToSkipFiltering`, `visaIssuers`, `generateFilterHandler()`, `collectScalars()` and
90
+ `collectMiddleware()`. This keeps one source of truth for the shared config (Open Reach Tech's DRY / "carve once"
84
91
  stance) and makes a new endpoint a short file.
85
- - **Only override a shared member to change it** for one endpoint — e.g. the user endpoint overrides
86
- `collectMiddleware()` just to raise the body limit to `30mb` ([§6](#6-middleware-scalars-error-codes)).
87
- - Prefer having the app base hold the shared middleware + error codes and every engine — **stub** and
92
+ - **`collectMiddleware()` stays in each engine**, though it reads the same everywhere. Its
93
+ `express.urlencoded` `verify` callback writes `req['rawBody']` under
94
+ `// eslint-disable-next-line no-param-reassign`, and the lint config allows that directive only in
95
+ the engine files ([§6](#6-middleware-scalars-error-codes)).
96
+ - Prefer having the app base hold the shared middleware classes + error codes and every engine — **stub** and
88
97
  **actual** — extend it. If some engines still extend the framework base directly and repeat those
89
98
  members, migrate them to the app base when you next touch an engine so the shared settings live in
90
99
  one place.
@@ -94,15 +103,19 @@ and overrides only what is endpoint-specific.**
94
103
  import BaseAppGraphqlServerEngine from './BaseAppGraphqlServerEngine.js'
95
104
  import PartnerGraphqlShare from './contexts/PartnerGraphqlShare.js'
96
105
  import PartnerGraphqlContext from './contexts/PartnerGraphqlContext.js'
106
+ import PartnerCorsExpressMiddleware from '../middleware/PartnerCorsExpressMiddleware.js'
97
107
 
98
108
  export default class PartnerGraphqlServerEngine extends BaseAppGraphqlServerEngine {
99
109
  /** @override */ static get config () { /* ... §2 ... */ }
110
+ /** @override */ static get ExpressMiddleware () { return [PartnerCorsExpressMiddleware] }
100
111
  /** @override */ get schemasToSkipFiltering () { /* ... §4 ... */ }
101
112
  /** @override */ generateFilterHandler () { /* ... §4 ... */ }
113
+ /** @override */ get visaIssuers () { /* ... §4 ... */ }
102
114
  /** @override */ static get Share () { return PartnerGraphqlShare }
103
115
  /** @override */ static get Context () { return PartnerGraphqlContext }
104
116
  /** @override */ async collectScalars () { /* ... §6 ... */ }
105
- // collectMiddleware() / standardErrorCodeHash inherited from the app base
117
+ /** @override */ collectMiddleware () { /* ... §6 ... */ }
118
+ // standardErrorCodeHash inherited from the app base
106
119
  }
107
120
  ```
108
121
 
@@ -119,11 +132,11 @@ export default class PartnerGraphqlServerEngine extends BaseAppGraphqlServerEngi
119
132
  | `actualResolversPath` | Directory of the real resolvers (`.../resolvers/<role>/actual/`), or `null`. |
120
133
  | `stubResolversPath` | Directory of stub resolvers (`.../resolvers/<role>/stub/`), or `null`. |
121
134
  | `postWorkersPath` | Directory of post-workers, or `null` when unused ([§7](#7-post-resolve-hooks-defineonresolved--postworkerspath)). |
122
- | `redisOptions?` | Redis connection for subscription PubSub; omit / `null` → in-process `LocalPubSub` ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)). |
135
+ | `redisOptions?` | Redis connection for subscription PubSub, read by the subscription broker. The engine leaves it out; the Share adds it from `env` when it creates the broker ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)). `null` → in-process `LocalPubSub` ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)). |
123
136
 
124
137
  ```js
125
- // Good: config is a pure routing declaration; paths via rootPath.to(), redis resolved in env
126
- import { rootPath, env } from '../../app/globals/_.js'
138
+ // Good: config is a pure routing declaration with paths via rootPath.to(), and no env import
139
+ import { rootPath } from '../../app/globals/_.js'
127
140
 
128
141
  /** @override */
129
142
  static get config () {
@@ -134,10 +147,20 @@ static get config () {
134
147
  actualResolversPath: rootPath.to('server/graphql/resolvers/customer/actual/'),
135
148
  stubResolversPath: rootPath.to('server/graphql/resolvers/customer/stub/'),
136
149
  postWorkersPath: rootPath.to('server/graphql/post-workers/customer/'),
137
- redisOptions: {
138
- host: env.REDIS_HOST,
139
- port: env.REDIS_PORT,
140
- },
150
+ }
151
+ }
152
+ ```
153
+
154
+ ```js
155
+ // Bad: the engine imports env to fill redisOptions
156
+ import { rootPath, env } from '../../app/globals/_.js'
157
+
158
+ /** @override */
159
+ static get config () {
160
+ return {
161
+ graphqlEndpoint: '/graphql-customer',
162
+ // ...
163
+ redisOptions: env.redisOptions,
141
164
  }
142
165
  }
143
166
  ```
@@ -146,11 +169,13 @@ static get config () {
146
169
  never hand-built relative strings.
147
170
  - **`graphqlEndpoint` must be unique** across all engines (each maps to its own path + port in
148
171
  `server/index.js`, [§8](#8-wiring-into-serverindexjs)).
149
- - **Keep `config` a pure declaration — never put logic in the getter.** Resolve the redis connection
150
- in the **`env` layer**: `env.redisOptions` returns `{ host, port }` on staging / live and `null` in
151
- dev (no Redis), so the getter just references it. Dev then falls back to `LocalPubSub`; staging /
152
- live opt in via environment. Do **not** branch inside `config` (`env.REDIS_HOST ? { … } : null`) —
153
- a getter must return a value, not compute one.
172
+ - **Keep `config` a pure declaration, and keep `env` out of the engine file.** Resolve the redis
173
+ connection in the **`env` layer**: `env.redisOptions` returns `{ host, port }` on staging / live
174
+ and `null` in dev (no Redis). The Share reads it and hands it to the broker
175
+ ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)), because the Share is the
176
+ only class that imports `env`. Dev then falls back to `LocalPubSub`; staging / live opt in via
177
+ environment. Do **not** branch on env inside `config` (`env.REDIS_HOST ? { ... } : null`): a
178
+ config holds no logic, because no test can reach logic there.
154
179
 
155
180
  ## 3. `Share` and `Context` — the DI the engine hands to every resolver
156
181
 
@@ -174,10 +199,293 @@ threads them into every resolver call.
174
199
  - **Each endpoint pairs its own Share + Context** (`Admin*` with `Admin*`); do not share one role's
175
200
  Context with another endpoint — the principal and permissions differ.
176
201
  - The Share / Context implementations themselves (findUser, visa issuing, extra clients) are their own
177
- concern; this skill only wires them onto the engine. (See the `contexts/` classes such as
178
- `AdminGraphqlContext.js` /
202
+ concern; this skill only wires them onto the engine, and says below where the Context reads the
203
+ credential. (See the `contexts/` classes such as `AdminGraphqlContext.js` /
179
204
  `AdminGraphqlShare.js`.)
180
205
 
206
+ ### The Context reads the credential from one route
207
+
208
+ The Context reads the `x-renchan-access-token` header unless a derived class says otherwise. A cookie,
209
+ a Bearer token, an IAP JWT or an HMAC signature replaces it by overriding
210
+ `static extractAccessToken()`. The engine, the filter and the visa stay as they are, because the
211
+ filter reads what `findUser()` resolved and never where the credential came from.
212
+
213
+ ```js
214
+ // Good: the GraphQL signature takes requestParams as well as expressRequest
215
+ /** @override */
216
+ static extractAccessToken ({
217
+ expressRequest,
218
+ requestParams,
219
+ }) {
220
+ const headers = expressRequest.headers
221
+ ?? this.extractHeadersFromRequestParams({
222
+ requestParams,
223
+ })
224
+
225
+ return AccessCredentialReader.readBearerToken({
226
+ headers,
227
+ })
228
+ }
229
+ ```
230
+
231
+ - **Keep the base's fallback.** The base reads `expressRequest.headers` and falls back to the headers in
232
+ the connection payload (`extractHeadersFromRequestParams()`) when the request has none. An override
233
+ that reads `expressRequest.headers` alone drops that fallback, and a request that relies on it
234
+ arrives with no credential.
235
+ - **One override serves every read.** `context.accessToken` calls `extractAccessToken()` again, so no
236
+ second place needs the change.
237
+ - **A context reads exactly one route.** The readers, `findUser()` for each route, and the CSRF and
238
+ replay rules are in `/hor-restfulapi-architecture` (its `credential-routes` reference), which
239
+ describes the REST context; the GraphQL context differs only in the signature above. An HMAC route
240
+ needs the raw bytes, and `collectMiddleware()` captures `rawBody` on `express.urlencoded` only, so
241
+ the engine's `express.json` takes the same `verify` callback ([§6](#6-middleware-scalars-error-codes)).
242
+
243
+ ### The Share hands the broker its Redis options
244
+
245
+ The subscription broker reads `redisOptions` from the config it is created with. The Share reads
246
+ `env` once in `.createAsync()` and overrides `.createBroker()` to pass that value along, so the
247
+ engine's `config` never touches `env`. A job daemon follows the same rule by another route: its
248
+ Share creates a `RedisConnection` (see `/hor-renchan-job-bullmq`).
249
+
250
+ ```js
251
+ // Good: the Share reads env once and hands the broker its Redis options
252
+ /** @override */
253
+ static async createAsync ({
254
+ config,
255
+ }) {
256
+ const env = this.generateEnv()
257
+ const broker = this.createBroker({
258
+ config,
259
+ env,
260
+ })
261
+
262
+ return this.create({
263
+ env,
264
+ broker,
265
+ })
266
+ }
267
+
268
+ /** @override */
269
+ static createBroker ({
270
+ config,
271
+ env,
272
+ }) {
273
+ return this.Broker.create({
274
+ config: {
275
+ ...config,
276
+ redisOptions: env.redisOptions,
277
+ },
278
+ })
279
+ }
280
+ ```
281
+
282
+ ### What the engine, the Share and `env` may each hold
283
+
284
+ - **The engine is a source of configuration and handlers; it generates nothing itself.** It keeps
285
+ `#share`, and other classes read what they need from the engine and generate their own values.
286
+ The engine has no logic method of its own for producing a value: no `.get:allowedOrigins` that
287
+ parses a string.
288
+ - **A getter calls no method**: no `.create()` and no parse call inside a getter.
289
+ `.get:config` keeps its `rootPath.to()` paths as [§2](#2-static-get-config--the-endpoints-routing-declaration)
290
+ shows them.
291
+ - **`Share` is the only class that imports `env`.** Every other class reads env through the Share
292
+ (`this.share.env`, or the engine's `#get:env`), or reads a value the Share built from it.
293
+ *Reason*: a test replaces env in one place, by handing the Share a mock env.
294
+ - **`Share` is a ValueObject**: it shares created instances and holds no logic. Its static
295
+ factories (`.create()`, `.createAsync()`) only create instances through other classes' factory
296
+ methods, where a factory method wraps `new` for its own class (`AllowedCorsOriginCollection.create()`).
297
+ *Reason*: `Share` means "sharing created instances", so it does nothing by itself. The rest of the Share's shape belongs to `hor-resolver-share`.
298
+ - **`Share` keeps no instance that needs only `env`.** It already keeps `env`, so the class that
299
+ uses such an instance creates it from `share.env` in its own body.
300
+ - **A method name states what it returns, and a value class is a singular noun.** A `create~`
301
+ method returns an instance of a class and reads "create + singular noun":
302
+ `#createAllowedCorsOriginCollection()`. The class is `AllowedCorsOriginCollection`, never
303
+ `AllowedOrigins`. The verbs follow the method-name verbs of `hoc-naming`.
304
+
305
+ | Verb | Returns | Example |
306
+ | --- | --- | --- |
307
+ | `create~` | an instance of a class | `#createAllowedCorsOriginCollection()` |
308
+ | `generate~` | a primitive value it makes | `#generateCacheKey()` |
309
+ | `build~` | a temporary object | `#buildOptionHash()` |
310
+ | `extract~` | data pulled from a property | `#extractOrigins()` |
311
+
312
+ The table governs the names the app writes. Names the framework defines and the app inherits,
313
+ such as `.generateEnv()` and `#generateFilterHandler()`, stay as they are.
314
+
315
+ #### Example: the allowed CORS origins
316
+
317
+ ```js
318
+ // Good: a value class owns the parse
319
+ // server/tools/AllowedCorsOriginCollection.js
320
+ export default class AllowedCorsOriginCollection {
321
+ constructor ({
322
+ originsString,
323
+ }) {
324
+ this.originsString = originsString
325
+ }
326
+
327
+ static create ({
328
+ originsString,
329
+ }) {
330
+ return new this({
331
+ originsString,
332
+ })
333
+ }
334
+
335
+ extractOrigins () {
336
+ if (!this.originsString) {
337
+ return []
338
+ }
339
+
340
+ return this.originsString
341
+ .split(',')
342
+ .map(it => it.trim())
343
+ .filter(it => it.length > 0)
344
+ }
345
+ }
346
+ ```
347
+
348
+ The Share does not keep the collection. It already keeps `env`, and the collection needs nothing
349
+ else, so the class that uses the collection creates it from `share.env` in its own body. That
350
+ class is an `ExpressMiddleware`: it reads through one getter per hop, so no line reaches past
351
+ its neighbour (the Law of Demeter). `BaseExpressMiddleware` holds the engine and gives
352
+ `#get:share`; it ships in `@openreachtech/renchan` from `2.11.0`.
353
+
354
+ ```js
355
+ // Good: the middleware creates the collection; a derived class names the env key
356
+ // server/middleware/CorsExpressMiddleware.js
357
+ import cors from 'cors'
358
+
359
+ import {
360
+ BaseExpressMiddleware,
361
+ } from '@openreachtech/renchan'
362
+
363
+ import AllowedCorsOriginCollection from '../tools/AllowedCorsOriginCollection.js'
364
+
365
+ export default class CorsExpressMiddleware extends BaseExpressMiddleware {
366
+ static get corsClient () {
367
+ return cors
368
+ }
369
+
370
+ get env () {
371
+ return this.share.env
372
+ }
373
+
374
+ /** @abstract */
375
+ get originsString () {
376
+ throw new Error(`101.X000.001 {"memberName":"${this.constructor.name}#get:originsString"}`)
377
+ }
378
+
379
+ /** @override */
380
+ composeMiddleware () {
381
+ return this.Ctor.corsClient(
382
+ this.buildOptionHash()
383
+ )
384
+ }
385
+
386
+ createAllowedCorsOriginCollection () {
387
+ return AllowedCorsOriginCollection.create({
388
+ originsString: this.originsString,
389
+ })
390
+ }
391
+
392
+ buildOptionHash () {
393
+ return {
394
+ origin: this.createAllowedCorsOriginCollection()
395
+ .extractOrigins(),
396
+ }
397
+ }
398
+ }
399
+ ```
400
+
401
+ Each endpoint reads its own key (`CORS_ADMIN_ORIGINS`, `CORS_CUSTOMER_ORIGINS`), and renchan
402
+ offers no structure yet that picks a key by endpoint. So each endpoint takes a derived class
403
+ that names its key and nothing else, and the engine lists that class.
404
+
405
+ ```js
406
+ // Good: one derived class per endpoint, holding only its env key
407
+ // server/middleware/AdminCorsExpressMiddleware.js
408
+ export default class AdminCorsExpressMiddleware extends CorsExpressMiddleware {
409
+ /** @override */
410
+ get originsString () {
411
+ return this.env.CORS_ADMIN_ORIGINS
412
+ }
413
+ }
414
+ ```
415
+
416
+ ```js
417
+ // Good: each engine lists its own class; see §6 for how it is composed
418
+ static get ExpressMiddleware () {
419
+ return [
420
+ AdminCorsExpressMiddleware,
421
+ ]
422
+ }
423
+ ```
424
+
425
+ ```js
426
+ // Bad: the Share keeps an instance it could leave to the class that uses it
427
+ static createAllowedCorsOriginCollection ({
428
+ env,
429
+ }) {
430
+ return AllowedCorsOriginCollection.create({
431
+ originsString: env.CORS_ADMIN_ORIGINS,
432
+ })
433
+ }
434
+ ```
435
+
436
+ ```js
437
+ // Bad: the engine reaches through its Share into the collection
438
+ collectMiddleware () {
439
+ return [
440
+ cors({
441
+ origin: this.share.allowedCorsOriginCollection.extractOrigins(),
442
+ }),
443
+ ]
444
+ }
445
+ ```
446
+
447
+ ```js
448
+ // Bad: the engine names the env key of a middleware it does not own
449
+ static get corsOriginsEnvKey () {
450
+ return 'CORS_ADMIN_ORIGINS'
451
+ }
452
+ ```
453
+
454
+ ```js
455
+ // Bad: the engine imports env and parses it inside a static getter
456
+ import { env } from '../../app/globals/_.js'
457
+ import AllowedOriginsParser from '../tools/AllowedOriginsParser.js'
458
+
459
+ static get allowedOrigins () {
460
+ return AllowedOriginsParser.create({
461
+ originsString: env.CORS_CUSTOMER_ORIGINS,
462
+ })
463
+ .parseOrigins()
464
+ }
465
+ ```
466
+
467
+ ```js
468
+ // Bad: the Share runs the parse, and a create~ method returns an array
469
+ static createAllowedOrigins ({
470
+ env,
471
+ }) {
472
+ return AllowedOriginsParser.create({
473
+ originsString: env.CORS_CUSTOMER_ORIGINS,
474
+ })
475
+ .parseOrigins()
476
+ }
477
+ ```
478
+
479
+ Do not guard the parse with `originsString instanceof String`. A string read from env is a
480
+ primitive and never an instance of `String`, so that guard drops every origin.
481
+
482
+ ```js
483
+ // Bad: always true for a string primitive, so extractOrigins() returns [] for every value
484
+ if (!(this.originsString instanceof String)) {
485
+ return []
486
+ }
487
+ ```
488
+
181
489
  ## 4. Authentication: `schemasToSkipFiltering` + `generateFilterHandler`
182
490
 
183
491
  Every operation on the endpoint runs through the engine's **filter handler** before its resolver —
@@ -260,7 +568,7 @@ Each role is served by **two** engines on **two ports**:
260
568
  (`return async () => {}`, `schemasToSkipFiltering: []`). It exists so the frontend can develop
261
569
  against canned data. **Auth-off is acceptable only because a stub serves fake data on a separate
262
570
  port** — never ship a stub engine's config on a real endpoint.
263
- - **Subscriptions PubSub**: when `config.redisOptions` is set, progress/subscription events go through
571
+ - **Subscriptions PubSub**: when the Share hands the broker `redisOptions` ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)), progress/subscription events go through
264
572
  **Redis PubSub** (required when a separate process — e.g. the job daemon — publishes to
265
573
  subscribers, see `hor-renchan-job-bullmq` §4). When it is `null`, the
266
574
  engine uses an in-process `LocalPubSub` — fine for dev and single-process endpoints. Enable Redis on
@@ -270,10 +578,15 @@ Each role is served by **two** engines on **two ports**:
270
578
 
271
579
  The remaining overrides are cross-cutting endpoint policy:
272
580
 
273
- - **`collectMiddleware()`** → the Express middleware array (cors, `express.json({ limit })`,
274
- `express.static`, the upload middleware, `express.urlencoded` capturing `rawBody`). Inherit it from
275
- the app base; only override to change a limit (e.g. the user endpoint raises the body limit to
276
- `30mb` for uploads).
581
+ - **`static get ExpressMiddleware`** → the `BaseExpressMiddleware` classes this endpoint mounts
582
+ (its own `CorsExpressMiddleware` derived class, [§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)).
583
+ `#composeExpressMiddleware()` creates each one with the engine and returns what its
584
+ `#composeMiddleware()` builds.
585
+ - **`collectMiddleware()`** → the Express middleware array: what `#composeExpressMiddleware()`
586
+ returns, then `express.json({ limit })`, `express.static`, the upload middleware and
587
+ `express.urlencoded` capturing `rawBody`. Each engine declares it, since the lint exception its
588
+ `verify` callback needs covers only the engine files
589
+ ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)).
277
590
  - **`async collectScalars()`** → the custom GraphQL scalars this endpoint exposes
278
591
  (`DateTimeScalar`, `BigNumberScalar`). Return only what the schema uses.
279
592
  - **`static get standardErrorCodeHash`** → maps the framework error names (`Unauthenticated`,
@@ -284,19 +597,35 @@ The remaining overrides are cross-cutting endpoint policy:
284
597
  production and maps them to `errorHash` codes in production — do not disable error mapping in prod.
285
598
 
286
599
  ```js
287
- // Good: only override middleware to change a limit; otherwise inherit from the app base
600
+ // Good: each engine declares its middleware, CORS first through ExpressMiddleware
288
601
  /** @override */
289
602
  collectMiddleware () {
603
+ const composedExpressMiddleware = this.composeExpressMiddleware()
604
+
290
605
  return [
291
- cors({ origin: '*' }),
292
- express.json({ limit: '30mb' }), // this endpoint accepts large uploads
606
+ ...composedExpressMiddleware,
607
+ express.json({
608
+ limit: '10mb',
609
+ verify: (req, res, body) => {
610
+ // eslint-disable-next-line no-param-reassign
611
+ req['rawBody'] = body
612
+ },
613
+ }),
293
614
  express.static(this.config.staticPath),
294
615
  graphqlUploadExpressWithResolvingContentType({ maxFileSize: 10000000, maxFiles: 10 }),
295
- express.urlencoded({ extended: true, verify: (req, res, body) => { req['rawBody'] = body.toString() } }),
616
+ express.urlencoded({
617
+ extended: true,
618
+ verify: (req, res, body) => {
619
+ // eslint-disable-next-line no-param-reassign
620
+ req['rawBody'] = body
621
+ },
622
+ }),
296
623
  ]
297
624
  }
298
625
  ```
299
626
 
627
+ Both `verify` callbacks keep `rawBody` as the `Buffer` they receive, because an HMAC check has to run over the exact bytes the caller signed and `toString()` can alter them.
628
+
300
629
  ## 7. Post-resolve hooks: `defineOnResolved` + `postWorkersPath`
301
630
 
302
631
  Two ways to run something *after* a resolver returns, both wired on the engine:
@@ -345,10 +674,13 @@ An endpoint → port layout looks like this (roles, paths, and ports are illustr
345
674
 
346
675
  ## Finishing checklist
347
676
 
348
- - [ ] One engine per endpoint, extending the **app base** ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)); no duplicated middleware / error hash unless the endpoint truly differs.
677
+ - [ ] One engine per endpoint, extending the **app base** ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)); a member moves to the app base only when it is always the same for every endpoint, and `collectMiddleware()` stays in each engine.
349
678
  - [ ] The engine is **declaration + wiring only** — no DB queries, no response building, no per-request state in the engine.
350
- - [ ] `config` has a **unique `graphqlEndpoint`**, `rootPath.to(...)` paths for schema / resolvers, and `redisOptions` from `env` (or `null`) ([§2](#2-static-get-config--the-endpoints-routing-declaration)).
679
+ - [ ] `config` has a **unique `graphqlEndpoint`**, `rootPath.to(...)` paths for schema / resolvers, and no `env` import; the Share supplies `redisOptions` from `env` (or `null`) ([§2](#2-static-get-config--the-endpoints-routing-declaration)).
351
680
  - [ ] `static get Share` / `static get Context` name **this role's own** Share + Context ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)).
681
+ - [ ] The engine generates no value of its own, and no getter calls a method; values come from classes the Share creates ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)).
682
+ - [ ] CORS mounts through the endpoint's own `CorsExpressMiddleware` derived class, the Share keeps no CORS collection, and `collectMiddleware()` never reaches through the Share ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)).
683
+ - [ ] Only the Share imports `env`; the Share holds created instances and runs no logic, and each `create~` method returns an instance of a singular-noun class ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)).
352
684
  - [ ] `schemasToSkipFiltering` lists **only genuinely public** operations; the filter runs the four-step visa gate; **no real work** in the filter ([§4](#4-authentication-schemastoskipfiltering--generatefilterhandler)).
353
685
  - [ ] A **stub** engine (if added) points `actualResolversPath` at the stub dir and uses a **noop** filter — and never leaks that config onto a real endpoint ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)).
354
686
  - [ ] Redis PubSub enabled on endpoints whose subscriptions are published by **another process** ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)).
@@ -41,7 +41,7 @@ to pick document ids from a metadata catalog.
41
41
  | Family | What it retrieves | Where |
42
42
  | --- | --- | --- |
43
43
  | **Document RAG** (this skill's core) | agent documents (`Document` bodies) for background knowledge | `DynamicDocumentVectorSelector` + `DynamicDocumentsBackgroundKnowledgeFetcher`, meeting at `AiAgentBaseKnowledgeAssembler` |
44
- | **N-gram fulltext** | generic keyword rows via `MATCH ... AGAINST` | `NgramSearchWordGenerator` + `FullTextSearchConditionGenerator` |
44
+ | **N-gram fulltext** | generic keyword rows via `MATCH ... AGAINST` (MySQL / MariaDB only) | `NgramSearchWordGenerator` + `FullTextSearchConditionGenerator` |
45
45
 
46
46
  > Record search over CRM data (not documents) goes through Elasticsearch
47
47
  > (`app/ReplicaFragments/OriginObjectReplicaFragmentClient.js`) and is a **separate subsystem** — see the
@@ -206,6 +206,11 @@ return this.logicalOperator === 'or'
206
206
  AND → `+apple +banana`; OR → `apple banana`. Use this for generic fulltext filtering, not for agent
207
207
  document RAG.
208
208
 
209
+ This builder assumes **MySQL / MariaDB**. PostgreSQL has no `MATCH ... AGAINST` and no BOOLEAN
210
+ mode, so the emitted clause is a syntax error there; its equivalent is a `tsvector` column matched
211
+ by a `tsquery` with `@@` (or the `pg_trgm` extension for trigram matching). A PostgreSQL project
212
+ writes its own condition generator and keeps the n-gram tokenizer, which is database-independent.
213
+
209
214
  ## Models
210
215
 
211
216
  | Model (table) | Key columns | Role |
@@ -140,4 +140,6 @@ from the filename):
140
140
  empty; `#formatAgainstText()` delegates to `NgramSearchWordGenerator`.
141
141
 
142
142
  This n-gram/fulltext infra is generic MySQL/MariaDB fulltext and is **not** wired into the document-RAG
143
- selectors.
143
+ selectors. `NgramTextTokenizer` is database-independent, but `NgramSearchWordGenerator` and
144
+ `FullTextSearchConditionGenerator` emit MySQL `MATCH ... AGAINST ... IN BOOLEAN MODE` and do not run
145
+ on PostgreSQL (see `SKILL.md`).