@openreachtech/hora-skills-ort-renchan 0.3.0 → 0.5.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 (50) 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 +17 -8
  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 +544 -45
  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 +6 -2
  18. package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +10 -6
  19. package/dist/skills/hor-oidc-sign-in/SKILL.md +61 -0
  20. package/dist/skills/hor-oidc-sign-in/references/environment.md +94 -0
  21. package/dist/skills/hor-oidc-sign-in/references/id-token-verification.md +98 -0
  22. package/dist/skills/hor-oidc-sign-in/references/resolvers.md +134 -0
  23. package/dist/skills/hor-oidc-sign-in/references/storage.md +118 -0
  24. package/dist/skills/hor-query-resolver/SKILL.md +2 -0
  25. package/dist/skills/hor-query-resolver/references/anatomy.md +7 -7
  26. package/dist/skills/hor-query-resolver/references/data-access.md +17 -0
  27. package/dist/skills/hor-renchan-job-bullmq/SKILL.md +15 -6
  28. package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +4 -2
  29. package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +39 -5
  30. package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +57 -0
  31. package/dist/skills/hor-resolver-validator/SKILL.md +5 -6
  32. package/dist/skills/hor-resolver-validator/references/validator-pattern.md +5 -5
  33. package/dist/skills/hor-restfulapi-architecture/SKILL.md +33 -7
  34. package/dist/skills/hor-restfulapi-architecture/references/behind-iap.md +116 -0
  35. package/dist/skills/hor-restfulapi-architecture/references/credential-routes.md +173 -0
  36. package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +11 -5
  37. package/dist/skills/hor-restfulapi-architecture/references/renderers.md +4 -0
  38. package/dist/skills/hor-sequelize-migration/SKILL.md +30 -15
  39. package/dist/skills/hor-sequelize-migration/references/alter-table.md +26 -13
  40. package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +5 -2
  41. package/dist/skills/hor-sequelize-migration/references/indexes.md +41 -2
  42. package/dist/skills/hor-sequelize-migration/references/notation.md +1 -1
  43. package/dist/skills/hor-sequelize-model/references/associations.md +2 -1
  44. package/dist/skills/hor-sequelize-model/references/notation.md +1 -1
  45. package/dist/skills/hor-sequelize-seeder/SKILL.md +9 -4
  46. package/dist/skills/hor-sequelize-seeder/references/notation.md +59 -0
  47. package/dist/skills/hor-type-interface/SKILL.md +48 -32
  48. package/docs/skills.ja.md +6 -5
  49. package/docs/skills.md +6 -5
  50. package/package.json +1 -1
@@ -1,12 +1,11 @@
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, error codes and WebSocket server, and decide what the engine and its Share
7
+ may hold and who reads env. Use whenever the user adds a GraphQL endpoint, pairs a stub engine,
8
+ changes its auth policy or credential route, enables Redis PubSub, or limits its WebSocket server.
10
9
  ---
11
10
 
12
11
  # GraphQL Server Engine
@@ -14,7 +13,8 @@ description: >
14
13
  A skill for the **`*GraphqlServerEngine` classes under `server/graphql/`**. An engine is the one
15
14
  object that **wires a single GraphQL endpoint**: its URL and port, which schema and resolver
16
15
  directories to load, the Share / Context dependency-injection classes, the authentication filter,
17
- the Express middleware, the custom scalars, and the error-code hash. `server/index.js` then boots
16
+ the Express middleware, the custom scalars, the error-code hash, and the WebSocket server's hooks and
17
+ switches. `server/index.js` then boots
18
18
  **one HTTP server per engine** through `GraphqlServerBuilder`.
19
19
 
20
20
  The engine sits *above* the pieces other skills build: resolvers (`hor-resolver-validator`
@@ -34,11 +34,12 @@ 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) |
41
41
  | Shared error codes | `standardErrorCodeHash` | [§6](#6-middleware-scalars-error-codes) |
42
+ | WebSocket server (`graphql-ws` hooks, skip switch, `ConnectionInit` timeout) | `composeServerHookHash()` + `config.graphqlServer` | [§9](#9-the-websocket-server-composeserverhookhash--graphqlserver) |
42
43
 
43
44
  **App-common settings are not repeated per engine** — they are lifted into an **app base class**
44
45
  (`BaseAppGraphqlServerEngine`) that every engine extends ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)).
@@ -58,9 +59,9 @@ the resolvers and the context; the engine just points at them.
58
59
  request. Anything stateful or per-request belongs in `Context` (per request) or `Share` (per
59
60
  process); anything domain-specific belongs in a resolver. An engine that starts doing work becomes
60
61
  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
62
+ - **Extend the app base, override only what differs.** The shared middleware classes and error codes live in
62
63
  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.
64
+ mostly `config` + `Share` + `Context` + the public schemas and visa issuers.
64
65
 
65
66
  **Comment language**: the `js` examples in this SKILL.md use English comments (matching the framework
66
67
  files). In the **engine files you generate** (`*GraphqlServerEngine.js`), keep structural comments in
@@ -75,16 +76,25 @@ and overrides only what is endpoint-specific.**
75
76
  | Base | Where | Role |
76
77
  | --- | --- | --- |
77
78
  | `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"
79
+ | `BaseAppGraphqlServerEngine` | `server/graphql/BaseAppGraphqlServerEngine.js` | **This app's shared settings** — factor here anything common to every endpoint, such as `standardErrorCodeHash`. |
80
+
81
+ - **Lift a member into the app base only when its logic is the same for every endpoint, always.**
82
+ Similar is not the same. Admin and customer declare different schemas, so
83
+ `schemasToSkipFiltering` stays in each engine, and `visaIssuers` stays because one role may
84
+ tighten its login checks later. `ExpressMiddleware` stays because each endpoint lists its own
85
+ CORS class. The error-code hash is the shared one.
86
+ `generateFilterHandler()` and `collectScalars()` read the same in every engine today, but
87
+ lifting them is a refactor of its own: a change that moves them goes in its own pull request,
88
+ never inside one with another purpose. Each concrete engine then extends
89
+ `BaseAppGraphqlServerEngine` and declares the rest — `config`, `Share`, `Context`, `ExpressMiddleware`,
90
+ `schemasToSkipFiltering`, `visaIssuers`, `generateFilterHandler()`, `collectScalars()` and
91
+ `collectMiddleware()`. This keeps one source of truth for the shared config (Open Reach Tech's DRY / "carve once"
84
92
  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
93
+ - **`collectMiddleware()` stays in each engine**, though it reads the same everywhere. Its
94
+ `express.urlencoded` `verify` callback writes `req['rawBody']` under
95
+ `// eslint-disable-next-line no-param-reassign`, and the lint config allows that directive only in
96
+ the engine files ([§6](#6-middleware-scalars-error-codes)).
97
+ - Prefer having the app base hold the shared middleware classes + error codes and every engine — **stub** and
88
98
  **actual** — extend it. If some engines still extend the framework base directly and repeat those
89
99
  members, migrate them to the app base when you next touch an engine so the shared settings live in
90
100
  one place.
@@ -94,15 +104,19 @@ and overrides only what is endpoint-specific.**
94
104
  import BaseAppGraphqlServerEngine from './BaseAppGraphqlServerEngine.js'
95
105
  import PartnerGraphqlShare from './contexts/PartnerGraphqlShare.js'
96
106
  import PartnerGraphqlContext from './contexts/PartnerGraphqlContext.js'
107
+ import PartnerCorsExpressMiddleware from '../middleware/PartnerCorsExpressMiddleware.js'
97
108
 
98
109
  export default class PartnerGraphqlServerEngine extends BaseAppGraphqlServerEngine {
99
110
  /** @override */ static get config () { /* ... §2 ... */ }
111
+ /** @override */ static get ExpressMiddleware () { return [PartnerCorsExpressMiddleware] }
100
112
  /** @override */ get schemasToSkipFiltering () { /* ... §4 ... */ }
101
113
  /** @override */ generateFilterHandler () { /* ... §4 ... */ }
114
+ /** @override */ get visaIssuers () { /* ... §4 ... */ }
102
115
  /** @override */ static get Share () { return PartnerGraphqlShare }
103
116
  /** @override */ static get Context () { return PartnerGraphqlContext }
104
117
  /** @override */ async collectScalars () { /* ... §6 ... */ }
105
- // collectMiddleware() / standardErrorCodeHash inherited from the app base
118
+ /** @override */ collectMiddleware () { /* ... §6 ... */ }
119
+ // standardErrorCodeHash inherited from the app base
106
120
  }
107
121
  ```
108
122
 
@@ -119,11 +133,12 @@ export default class PartnerGraphqlServerEngine extends BaseAppGraphqlServerEngi
119
133
  | `actualResolversPath` | Directory of the real resolvers (`.../resolvers/<role>/actual/`), or `null`. |
120
134
  | `stubResolversPath` | Directory of stub resolvers (`.../resolvers/<role>/stub/`), or `null`. |
121
135
  | `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)). |
136
+ | `graphqlServer?` | Settings of the WebSocket server mounted on the endpoint: `skipsWebSocket` and `connectionInitWaitTimeout` ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)). |
137
+ | `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
138
 
124
139
  ```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'
140
+ // Good: config is a pure routing declaration with paths via rootPath.to(), and no env import
141
+ import { rootPath } from '../../app/globals/_.js'
127
142
 
128
143
  /** @override */
129
144
  static get config () {
@@ -134,10 +149,20 @@ static get config () {
134
149
  actualResolversPath: rootPath.to('server/graphql/resolvers/customer/actual/'),
135
150
  stubResolversPath: rootPath.to('server/graphql/resolvers/customer/stub/'),
136
151
  postWorkersPath: rootPath.to('server/graphql/post-workers/customer/'),
137
- redisOptions: {
138
- host: env.REDIS_HOST,
139
- port: env.REDIS_PORT,
140
- },
152
+ }
153
+ }
154
+ ```
155
+
156
+ ```js
157
+ // Bad: the engine imports env to fill redisOptions
158
+ import { rootPath, env } from '../../app/globals/_.js'
159
+
160
+ /** @override */
161
+ static get config () {
162
+ return {
163
+ graphqlEndpoint: '/graphql-customer',
164
+ // ...
165
+ redisOptions: env.redisOptions,
141
166
  }
142
167
  }
143
168
  ```
@@ -146,11 +171,13 @@ static get config () {
146
171
  never hand-built relative strings.
147
172
  - **`graphqlEndpoint` must be unique** across all engines (each maps to its own path + port in
148
173
  `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.
174
+ - **Keep `config` a pure declaration, and keep `env` out of the engine file.** Resolve the redis
175
+ connection in the **`env` layer**: `env.redisOptions` returns `{ host, port }` on staging / live
176
+ and `null` in dev (no Redis). The Share reads it and hands it to the broker
177
+ ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)), because the Share is the
178
+ only class that imports `env`. Dev then falls back to `LocalPubSub`; staging / live opt in via
179
+ environment. Do **not** branch on env inside `config` (`env.REDIS_HOST ? { ... } : null`): a
180
+ config holds no logic, because no test can reach logic there.
154
181
 
155
182
  ## 3. `Share` and `Context` — the DI the engine hands to every resolver
156
183
 
@@ -174,10 +201,293 @@ threads them into every resolver call.
174
201
  - **Each endpoint pairs its own Share + Context** (`Admin*` with `Admin*`); do not share one role's
175
202
  Context with another endpoint — the principal and permissions differ.
176
203
  - 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` /
204
+ concern; this skill only wires them onto the engine, and says below where the Context reads the
205
+ credential. (See the `contexts/` classes such as `AdminGraphqlContext.js` /
179
206
  `AdminGraphqlShare.js`.)
180
207
 
208
+ ### The Context reads the credential from one route
209
+
210
+ The Context reads the `x-renchan-access-token` header unless a derived class says otherwise. A cookie,
211
+ a Bearer token, an IAP JWT or an HMAC signature replaces it by overriding
212
+ `static extractAccessToken()`. The engine, the filter and the visa stay as they are, because the
213
+ filter reads what `findUser()` resolved and never where the credential came from.
214
+
215
+ ```js
216
+ // Good: the GraphQL signature takes requestParams as well as expressRequest
217
+ /** @override */
218
+ static extractAccessToken ({
219
+ expressRequest,
220
+ requestParams,
221
+ }) {
222
+ const headers = expressRequest.headers
223
+ ?? this.extractHeadersFromRequestParams({
224
+ requestParams,
225
+ })
226
+
227
+ return AccessCredentialReader.readBearerToken({
228
+ headers,
229
+ })
230
+ }
231
+ ```
232
+
233
+ - **Keep the base's fallback.** The base reads `expressRequest.headers` and falls back to the headers in
234
+ the connection payload (`extractHeadersFromRequestParams()`) when the request has none. An override
235
+ that reads `expressRequest.headers` alone drops that fallback, and a request that relies on it
236
+ arrives with no credential.
237
+ - **One override serves every read.** `context.accessToken` calls `extractAccessToken()` again, so no
238
+ second place needs the change.
239
+ - **A context reads exactly one route.** The readers, `findUser()` for each route, and the CSRF and
240
+ replay rules are in `/hor-restfulapi-architecture` (its `credential-routes` reference), which
241
+ describes the REST context; the GraphQL context differs only in the signature above. An HMAC route
242
+ needs the raw bytes, and `collectMiddleware()` captures `rawBody` on `express.urlencoded` only, so
243
+ the engine's `express.json` takes the same `verify` callback ([§6](#6-middleware-scalars-error-codes)).
244
+
245
+ ### The Share hands the broker its Redis options
246
+
247
+ The subscription broker reads `redisOptions` from the config it is created with. The Share reads
248
+ `env` once in `.createAsync()` and overrides `.createBroker()` to pass that value along, so the
249
+ engine's `config` never touches `env`. A job daemon follows the same rule by another route: its
250
+ Share creates a `RedisConnection` (see `/hor-renchan-job-bullmq`).
251
+
252
+ ```js
253
+ // Good: the Share reads env once and hands the broker its Redis options
254
+ /** @override */
255
+ static async createAsync ({
256
+ config,
257
+ }) {
258
+ const env = this.generateEnv()
259
+ const broker = this.createBroker({
260
+ config,
261
+ env,
262
+ })
263
+
264
+ return this.create({
265
+ env,
266
+ broker,
267
+ })
268
+ }
269
+
270
+ /** @override */
271
+ static createBroker ({
272
+ config,
273
+ env,
274
+ }) {
275
+ return this.Broker.create({
276
+ config: {
277
+ ...config,
278
+ redisOptions: env.redisOptions,
279
+ },
280
+ })
281
+ }
282
+ ```
283
+
284
+ ### What the engine, the Share and `env` may each hold
285
+
286
+ - **The engine is a source of configuration and handlers; it generates nothing itself.** It keeps
287
+ `#share`, and other classes read what they need from the engine and generate their own values.
288
+ The engine has no logic method of its own for producing a value: no `.get:allowedOrigins` that
289
+ parses a string.
290
+ - **A getter calls no method**: no `.create()` and no parse call inside a getter.
291
+ `.get:config` keeps its `rootPath.to()` paths as [§2](#2-static-get-config--the-endpoints-routing-declaration)
292
+ shows them.
293
+ - **`Share` is the only class that imports `env`.** Every other class reads env through the Share
294
+ (`this.share.env`, or the engine's `#get:env`), or reads a value the Share built from it.
295
+ *Reason*: a test replaces env in one place, by handing the Share a mock env.
296
+ - **`Share` is a ValueObject**: it shares created instances and holds no logic. Its static
297
+ factories (`.create()`, `.createAsync()`) only create instances through other classes' factory
298
+ methods, where a factory method wraps `new` for its own class (`AllowedCorsOriginCollection.create()`).
299
+ *Reason*: `Share` means "sharing created instances", so it does nothing by itself. The rest of the Share's shape belongs to `hor-resolver-share`.
300
+ - **`Share` keeps no instance that needs only `env`.** It already keeps `env`, so the class that
301
+ uses such an instance creates it from `share.env` in its own body.
302
+ - **A method name states what it returns, and a value class is a singular noun.** A `create~`
303
+ method returns an instance of a class and reads "create + singular noun":
304
+ `#createAllowedCorsOriginCollection()`. The class is `AllowedCorsOriginCollection`, never
305
+ `AllowedOrigins`. The verbs follow the method-name verbs of `hoc-naming`.
306
+
307
+ | Verb | Returns | Example |
308
+ | --- | --- | --- |
309
+ | `create~` | an instance of a class | `#createAllowedCorsOriginCollection()` |
310
+ | `generate~` | a primitive value it makes | `#generateCacheKey()` |
311
+ | `build~` | a temporary object | `#buildOptionHash()` |
312
+ | `extract~` | data pulled from a property | `#extractOrigins()` |
313
+
314
+ The table governs the names the app writes. Names the framework defines and the app inherits,
315
+ such as `.generateEnv()` and `#generateFilterHandler()`, stay as they are.
316
+
317
+ #### Example: the allowed CORS origins
318
+
319
+ ```js
320
+ // Good: a value class owns the parse
321
+ // server/tools/AllowedCorsOriginCollection.js
322
+ export default class AllowedCorsOriginCollection {
323
+ constructor ({
324
+ originsString,
325
+ }) {
326
+ this.originsString = originsString
327
+ }
328
+
329
+ static create ({
330
+ originsString,
331
+ }) {
332
+ return new this({
333
+ originsString,
334
+ })
335
+ }
336
+
337
+ extractOrigins () {
338
+ if (!this.originsString) {
339
+ return []
340
+ }
341
+
342
+ return this.originsString
343
+ .split(',')
344
+ .map(it => it.trim())
345
+ .filter(it => it.length > 0)
346
+ }
347
+ }
348
+ ```
349
+
350
+ The Share does not keep the collection. It already keeps `env`, and the collection needs nothing
351
+ else, so the class that uses the collection creates it from `share.env` in its own body. That
352
+ class is an `ExpressMiddleware`: it reads through one getter per hop, so no line reaches past
353
+ its neighbour (the Law of Demeter). `BaseExpressMiddleware` holds the engine and gives
354
+ `#get:share`; it ships in `@openreachtech/renchan` from `2.11.0`.
355
+
356
+ ```js
357
+ // Good: the middleware creates the collection; a derived class names the env key
358
+ // server/middleware/CorsExpressMiddleware.js
359
+ import cors from 'cors'
360
+
361
+ import {
362
+ BaseExpressMiddleware,
363
+ } from '@openreachtech/renchan'
364
+
365
+ import AllowedCorsOriginCollection from '../tools/AllowedCorsOriginCollection.js'
366
+
367
+ export default class CorsExpressMiddleware extends BaseExpressMiddleware {
368
+ static get corsClient () {
369
+ return cors
370
+ }
371
+
372
+ get env () {
373
+ return this.share.env
374
+ }
375
+
376
+ /** @abstract */
377
+ get originsString () {
378
+ throw new Error(`101.X000.001 {"memberName":"${this.constructor.name}#get:originsString"}`)
379
+ }
380
+
381
+ /** @override */
382
+ composeMiddleware () {
383
+ return this.Ctor.corsClient(
384
+ this.buildOptionHash()
385
+ )
386
+ }
387
+
388
+ createAllowedCorsOriginCollection () {
389
+ return AllowedCorsOriginCollection.create({
390
+ originsString: this.originsString,
391
+ })
392
+ }
393
+
394
+ buildOptionHash () {
395
+ return {
396
+ origin: this.createAllowedCorsOriginCollection()
397
+ .extractOrigins(),
398
+ }
399
+ }
400
+ }
401
+ ```
402
+
403
+ Each endpoint reads its own key (`CORS_ADMIN_ORIGINS`, `CORS_CUSTOMER_ORIGINS`), and renchan
404
+ offers no structure yet that picks a key by endpoint. So each endpoint takes a derived class
405
+ that names its key and nothing else, and the engine lists that class.
406
+
407
+ ```js
408
+ // Good: one derived class per endpoint, holding only its env key
409
+ // server/middleware/AdminCorsExpressMiddleware.js
410
+ export default class AdminCorsExpressMiddleware extends CorsExpressMiddleware {
411
+ /** @override */
412
+ get originsString () {
413
+ return this.env.CORS_ADMIN_ORIGINS
414
+ }
415
+ }
416
+ ```
417
+
418
+ ```js
419
+ // Good: each engine lists its own class; see §6 for how it is composed
420
+ static get ExpressMiddleware () {
421
+ return [
422
+ AdminCorsExpressMiddleware,
423
+ ]
424
+ }
425
+ ```
426
+
427
+ ```js
428
+ // Bad: the Share keeps an instance it could leave to the class that uses it
429
+ static createAllowedCorsOriginCollection ({
430
+ env,
431
+ }) {
432
+ return AllowedCorsOriginCollection.create({
433
+ originsString: env.CORS_ADMIN_ORIGINS,
434
+ })
435
+ }
436
+ ```
437
+
438
+ ```js
439
+ // Bad: the engine reaches through its Share into the collection
440
+ collectMiddleware () {
441
+ return [
442
+ cors({
443
+ origin: this.share.allowedCorsOriginCollection.extractOrigins(),
444
+ }),
445
+ ]
446
+ }
447
+ ```
448
+
449
+ ```js
450
+ // Bad: the engine names the env key of a middleware it does not own
451
+ static get corsOriginsEnvKey () {
452
+ return 'CORS_ADMIN_ORIGINS'
453
+ }
454
+ ```
455
+
456
+ ```js
457
+ // Bad: the engine imports env and parses it inside a static getter
458
+ import { env } from '../../app/globals/_.js'
459
+ import AllowedOriginsParser from '../tools/AllowedOriginsParser.js'
460
+
461
+ static get allowedOrigins () {
462
+ return AllowedOriginsParser.create({
463
+ originsString: env.CORS_CUSTOMER_ORIGINS,
464
+ })
465
+ .parseOrigins()
466
+ }
467
+ ```
468
+
469
+ ```js
470
+ // Bad: the Share runs the parse, and a create~ method returns an array
471
+ static createAllowedOrigins ({
472
+ env,
473
+ }) {
474
+ return AllowedOriginsParser.create({
475
+ originsString: env.CORS_CUSTOMER_ORIGINS,
476
+ })
477
+ .parseOrigins()
478
+ }
479
+ ```
480
+
481
+ Do not guard the parse with `originsString instanceof String`. A string read from env is a
482
+ primitive and never an instance of `String`, so that guard drops every origin.
483
+
484
+ ```js
485
+ // Bad: always true for a string primitive, so extractOrigins() returns [] for every value
486
+ if (!(this.originsString instanceof String)) {
487
+ return []
488
+ }
489
+ ```
490
+
181
491
  ## 4. Authentication: `schemasToSkipFiltering` + `generateFilterHandler`
182
492
 
183
493
  Every operation on the endpoint runs through the engine's **filter handler** before its resolver —
@@ -260,7 +570,7 @@ Each role is served by **two** engines on **two ports**:
260
570
  (`return async () => {}`, `schemasToSkipFiltering: []`). It exists so the frontend can develop
261
571
  against canned data. **Auth-off is acceptable only because a stub serves fake data on a separate
262
572
  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
573
+ - **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
574
  **Redis PubSub** (required when a separate process — e.g. the job daemon — publishes to
265
575
  subscribers, see `hor-renchan-job-bullmq` §4). When it is `null`, the
266
576
  engine uses an in-process `LocalPubSub` — fine for dev and single-process endpoints. Enable Redis on
@@ -270,10 +580,15 @@ Each role is served by **two** engines on **two ports**:
270
580
 
271
581
  The remaining overrides are cross-cutting endpoint policy:
272
582
 
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).
583
+ - **`static get ExpressMiddleware`** → the `BaseExpressMiddleware` classes this endpoint mounts
584
+ (its own `CorsExpressMiddleware` derived class, [§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)).
585
+ `#composeExpressMiddleware()` creates each one with the engine and returns what its
586
+ `#composeMiddleware()` builds.
587
+ - **`collectMiddleware()`** → the Express middleware array: what `#composeExpressMiddleware()`
588
+ returns, then `express.json({ limit })`, `express.static`, the upload middleware and
589
+ `express.urlencoded` capturing `rawBody`. Each engine declares it, since the lint exception its
590
+ `verify` callback needs covers only the engine files
591
+ ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)).
277
592
  - **`async collectScalars()`** → the custom GraphQL scalars this endpoint exposes
278
593
  (`DateTimeScalar`, `BigNumberScalar`). Return only what the schema uses.
279
594
  - **`static get standardErrorCodeHash`** → maps the framework error names (`Unauthenticated`,
@@ -284,19 +599,35 @@ The remaining overrides are cross-cutting endpoint policy:
284
599
  production and maps them to `errorHash` codes in production — do not disable error mapping in prod.
285
600
 
286
601
  ```js
287
- // Good: only override middleware to change a limit; otherwise inherit from the app base
602
+ // Good: each engine declares its middleware, CORS first through ExpressMiddleware
288
603
  /** @override */
289
604
  collectMiddleware () {
605
+ const composedExpressMiddleware = this.composeExpressMiddleware()
606
+
290
607
  return [
291
- cors({ origin: '*' }),
292
- express.json({ limit: '30mb' }), // this endpoint accepts large uploads
608
+ ...composedExpressMiddleware,
609
+ express.json({
610
+ limit: '10mb',
611
+ verify: (req, res, body) => {
612
+ // eslint-disable-next-line no-param-reassign
613
+ req['rawBody'] = body
614
+ },
615
+ }),
293
616
  express.static(this.config.staticPath),
294
617
  graphqlUploadExpressWithResolvingContentType({ maxFileSize: 10000000, maxFiles: 10 }),
295
- express.urlencoded({ extended: true, verify: (req, res, body) => { req['rawBody'] = body.toString() } }),
618
+ express.urlencoded({
619
+ extended: true,
620
+ verify: (req, res, body) => {
621
+ // eslint-disable-next-line no-param-reassign
622
+ req['rawBody'] = body
623
+ },
624
+ }),
296
625
  ]
297
626
  }
298
627
  ```
299
628
 
629
+ 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.
630
+
300
631
  ## 7. Post-resolve hooks: `defineOnResolved` + `postWorkersPath`
301
632
 
302
633
  Two ways to run something *after* a resolver returns, both wired on the engine:
@@ -343,14 +674,182 @@ An endpoint → port layout looks like this (roles, paths, and ports are illustr
343
674
  as a REST server).
344
675
  - Pair the actual engine with its stub engine here too (both get their own `createAsync` + `listen`).
345
676
 
677
+ ## 9. The WebSocket server: `composeServerHookHash()` + `graphqlServer`
678
+
679
+ `GraphqlServerBuilder` mounts a `graphql-ws` server on the endpoint's `graphqlEndpoint` path, next to
680
+ the HTTP handler. The engine shapes it through two members, from `@openreachtech/renchan` `2.12.0`.
681
+ A WebSocket connection never passes through the Express middleware of
682
+ [§6](#6-middleware-scalars-error-codes), so a rule that lives there (a sign-in rate limit, a CORS
683
+ check) does not see an operation that arrives over the socket.
684
+
685
+ | Member | Kind | What it decides |
686
+ | --- | --- | --- |
687
+ | `composeServerHookHash()` | instance method | The `graphql-ws` server hooks (`onConnect`, `onSubscribe`, `onClose`, ...). Default `{}`. Type `GraphqlType.WebSocketServerHookHash`. |
688
+ | `config.graphqlServer.skipsWebSocket` | boolean | `true` leaves the WebSocket server unmounted. Default `false`. |
689
+ | `config.graphqlServer.connectionInitWaitTimeout` | number (ms) | How long the server waits for `ConnectionInit` after a connection opens. A positive finite number only; anything else (omitted, `null`, `0`, `Infinity`, `NaN`, a string) leaves the `graphql-ws` default of 3000. |
690
+
691
+ - **A switch goes in `config`, and a hook never overrides what the builder wires.** The builder drops
692
+ these keys from whatever `composeServerHookHash()` returns: `execute`, `subscribe`, `context`,
693
+ `schema`, `roots`, `validate`, `connectionInitWaitTimeout`, `jsonMessageReviver` and
694
+ `jsonMessageReplacer`. The type omits the same keys, and the builder ignores one that slips
695
+ through. Set the wait through `config`, never through the hash.
696
+ - **`0` and `Infinity` do not turn the wait off.** `graphql-ws` itself treats them as "do not wait",
697
+ but the builder resolves them to its default, so an endpoint always waits for `ConnectionInit`.
698
+ - **Skip the server on an endpoint that serves no subscription.** An endpoint whose schema has no
699
+ `Subscription` type, such as a role that only queries and mutates, mounts a WebSocket server
700
+ nobody needs, and an open door is attack surface. `skipsWebSocket: true` is the switch; do not
701
+ emulate it with a hook that refuses everything.
702
+ - **`composeServerHookHash()` is a method, so it may build the hash.** The getter rule of
703
+ [§3](#what-the-engine-the-share-and-env-may-each-hold) holds: a getter calls no method. The method
704
+ returns hook functions that decide allow or deny and nothing else, like `generateFilterHandler()`
705
+ ([§4](#4-authentication-schemastoskipfiltering--generatefilterhandler)). Anything that needs `env`
706
+ reads it through `this.share.env`, because only the Share imports `env`.
707
+ - **Refuse an operation by returning `GraphQLError`s from `onSubscribe`.** Return `void` to let the
708
+ operation go on. Return an array of at least one `GraphQLError` (from `graphql`) to refuse it:
709
+ `graphql-ws` sends the client an error message for that operation and the socket stays open.
710
+ An error from `this.errorHash` does not qualify, because it extends `Error` and is not a
711
+ `GraphQLError`.
712
+ - **Never return `ExecutionArgs` from `onSubscribe`.** It skips the builder's validation, so the
713
+ endpoint's own validation rules stop applying to that operation.
714
+ - **Throwing from `onSubscribe` closes the whole socket.** `parse()` throws on a syntax error, so the
715
+ example below ends the connection on a malformed query, as `graphql-ws` does when no hook is set.
716
+
717
+ ```js
718
+ // Good: a WebSocket carries subscriptions only; a query or a mutation must go through HTTP
719
+ import {
720
+ GraphQLError,
721
+ getOperationAST,
722
+ parse,
723
+ } from 'graphql'
724
+
725
+ /** @override */
726
+ composeServerHookHash () {
727
+ return {
728
+ onSubscribe: (context, message) => {
729
+ const operationAst = getOperationAST(
730
+ parse(message.payload.query),
731
+ message.payload.operationName
732
+ )
733
+
734
+ if (operationAst?.operation === 'subscription') {
735
+ return undefined
736
+ }
737
+
738
+ return [
739
+ new GraphQLError('Only a subscription is accepted over WebSocket.'),
740
+ ]
741
+ },
742
+ }
743
+ }
744
+ ```
745
+
746
+ An operation the hook refuses never reaches a resolver, so a sign-in mutation sent over the socket
747
+ cannot dodge the sign-in rate limit that the Express middleware applies over HTTP. The check fails
748
+ closed: anything other than a subscription, including an operation the AST cannot identify
749
+ (`operationAst` is `null`), is refused.
750
+
751
+ ### Check the `Origin` of a WebSocket connection in `onConnect`
752
+
753
+ The CORS middleware of [§3](#what-the-engine-the-share-and-env-may-each-hold) never sees the
754
+ WebSocket handshake either, so a page on any origin can open a socket to the endpoint. `onConnect`
755
+ runs when the client sends `ConnectionInit`: `graphql-ws` allows the connection when it returns
756
+ `true` (or nothing), and closes the socket with `4403: Forbidden` when it returns `false`. With the
757
+ `ws` server, `context.extra.request` is the handshake `IncomingMessage`, so the origin is
758
+ `context.extra.request.headers.origin`.
759
+
760
+ The allowed origins already live in the endpoint's `CorsExpressMiddleware` derived class, which
761
+ reads its env key through `this.share.env`. Give that class the one predicate the hook needs, and
762
+ create the class in the engine with `Ctor.create({ engine: this })`, as
763
+ `composeExpressMiddleware()` does. The engine then imports no `env`, parses nothing and keeps one
764
+ list of origins for HTTP and WebSocket.
765
+
766
+ ```js
767
+ // Good: the middleware class owns the origin list, so the hook only asks it
768
+ // server/middleware/CorsExpressMiddleware.js
769
+ allowsOrigin ({
770
+ origin,
771
+ }) {
772
+ return this.createAllowedCorsOriginCollection()
773
+ .extractOrigins()
774
+ .includes(origin)
775
+ }
776
+ ```
777
+
778
+ ```js
779
+ // Good: the engine composes the hook; a missing or foreign Origin is refused with 4403
780
+ import AdminCorsExpressMiddleware from '../middleware/AdminCorsExpressMiddleware.js'
781
+
782
+ /** @override */
783
+ composeServerHookHash () {
784
+ const corsExpressMiddleware = AdminCorsExpressMiddleware.create({
785
+ engine: this,
786
+ })
787
+
788
+ return {
789
+ onConnect: context => corsExpressMiddleware.allowsOrigin({
790
+ origin: context.extra.request.headers.origin,
791
+ }),
792
+ }
793
+ }
794
+ ```
795
+
796
+ - **A browser always sends `Origin` on a WebSocket handshake; a script or a server client sends none.**
797
+ The hook above refuses a connection with no `Origin`. An endpoint that serves such a client
798
+ decides that case on purpose, never by loosening the list.
799
+ - **`onConnect` and `onSubscribe` live in the same hash.** Return both from one
800
+ `composeServerHookHash()`.
801
+
802
+ ```js
803
+ // Good: a switch is a config value
804
+ /** @override */
805
+ static get config () {
806
+ return {
807
+ graphqlEndpoint: '/graphql-admin',
808
+ // ...
809
+ graphqlServer: {
810
+ skipsWebSocket: false,
811
+ connectionInitWaitTimeout: 5000,
812
+ },
813
+ }
814
+ }
815
+ ```
816
+
817
+ ```js
818
+ // Bad: the wait is a config value, so the builder drops it from the hash
819
+ /** @override */
820
+ composeServerHookHash () {
821
+ return {
822
+ connectionInitWaitTimeout: 5000,
823
+ }
824
+ }
825
+ ```
826
+
827
+ ```js
828
+ // Bad: ExecutionArgs from onSubscribe skips the builder's validation
829
+ /** @override */
830
+ composeServerHookHash () {
831
+ return {
832
+ onSubscribe: (context, message) => ({
833
+ schema,
834
+ document: parse(message.payload.query),
835
+ }),
836
+ }
837
+ }
838
+ ```
839
+
346
840
  ## Finishing checklist
347
841
 
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.
842
+ - [ ] 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
843
  - [ ] 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)).
844
+ - [ ] `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
845
  - [ ] `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)).
846
+ - [ ] 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)).
847
+ - [ ] 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)).
848
+ - [ ] 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
849
  - [ ] `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
850
  - [ ] 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
851
  - [ ] Redis PubSub enabled on endpoints whose subscriptions are published by **another process** ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)).
355
852
  - [ ] `postWorkersPath` set when the endpoint needs post-workers (`null` disables them) ([§7](#7-post-resolve-hooks-defineonresolved--postworkerspath)).
356
853
  - [ ] Engine **registered in `server/index.js`** with a unique port ([§8](#8-wiring-into-serverindexjs)).
854
+ - [ ] An endpoint's `onConnect` refuses an `Origin` outside the list its `CorsExpressMiddleware` derived class reads, and the engine imports no `env` for it ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)).
855
+ - [ ] An endpoint that serves no subscription sets `config.graphqlServer.skipsWebSocket: true`; one that does refuses every non-subscription operation in `composeServerHookHash()`'s `onSubscribe`, returns `GraphQLError`s (never `ExecutionArgs`), and keeps `connectionInitWaitTimeout` in `config` ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)).