@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
@@ -38,13 +38,15 @@ import { SubscriptionBroker } from '@openreachtech/renchan'
38
38
  import { JobWorkersDaemon } from '@openreachtech/renchan-job-bullmq'
39
39
  import activate from '../sequelize/_.js'
40
40
  import ContentGenerationJobEngine from '../app/ContentGenerationJobEngine.js'
41
- import RedisConnection from '../app/queue/RedisConnection.js'
41
+ import ContentGenerationJobShare from '../app/contexts/ContentGenerationJobShare.js'
42
42
 
43
43
  await activate() // Sequelize (workers touch the DB)
44
44
 
45
45
  const subscriptionBroker = SubscriptionBroker.create({
46
46
  config: {
47
- redisOptions: RedisConnection.create().generatePubSubOptions(),
47
+ redisOptions: ContentGenerationJobShare
48
+ .createRedisConnection()
49
+ .generatePubSubOptions(),
48
50
  },
49
51
  })
50
52
 
@@ -15,9 +15,9 @@ export default class ContentGenerationJobEngine extends BaseJobEngine {
15
15
  return {
16
16
  workersPath: rootPath.to('app/jobs'), // Daemon scans here for BaseJobWorker subclasses
17
17
  schedulersPath: rootPath.to('app/jobs'), // scheduler registration scans here
18
- redisConfig: RedisConnection
19
- .create()
20
- .generateConnectionOptions(),
18
+ redisConfig: ContentGenerationJobShare
19
+ .createRedisConnection()
20
+ .generateConnectionOptions(),
21
21
  }
22
22
  }
23
23
 
@@ -53,6 +53,21 @@ Created once per process by the engine; holds `processClerk`, `env`, `timber`, a
53
53
  the `subscriptionBroker`. The getter just returns the stored instance — no side effects. Enqueue-only
54
54
  processes construct the Share with `subscriptionBroker: null`.
55
55
 
56
+ **The Share is the only class that imports `env`.** It hands the env to `RedisConnection` through
57
+ its factory, so no other class reads `REDIS_*` directly:
58
+
59
+ ```js
60
+ import RedisConnection from '../queue/RedisConnection.js'
61
+
62
+ export default class ContentGenerationJobShare extends BaseJobShare {
63
+ static createRedisConnection () {
64
+ return RedisConnection.create({
65
+ env: this.generateRenchanEnv(),
66
+ })
67
+ }
68
+ }
69
+ ```
70
+
56
71
  ## Context — per-job DI object
57
72
 
58
73
  `BaseJobContext` subclass. Created fresh for **each job execution** (`createAsync({ engine })`) and
@@ -61,8 +76,9 @@ the worker stays thin.
61
76
 
62
77
  ## RedisConnection — one Redis, two option shapes
63
78
 
64
- `app/queue/RedisConnection.js` reads `REDIS_HOST` /
65
- `REDIS_PORT` / `REDIS_PASSWORD` and produces:
79
+ `app/queue/RedisConnection.js` does not import `env`. The Share creates it with
80
+ `ContentGenerationJobShare.createRedisConnection()`, handing it the env, and it reads
81
+ `env.REDIS_HOST` / `env.REDIS_PORT` / `env.REDIS_PASSWORD` to produce:
66
82
 
67
83
  - **`generateConnectionOptions()`** — for BullMQ queues/workers. **Must include
68
84
  `maxRetriesPerRequest: null`** (BullMQ requirement).
@@ -71,6 +87,24 @@ the worker stays thin.
71
87
  The **GraphQL API process and the Job Daemon must point at the same Redis** — that shared instance is
72
88
  both the job queue and the progress-PubSub channel.
73
89
 
90
+ ## The queue's Redis runs with `noeviction`
91
+
92
+ BullMQ keeps each job's state in several Redis keys, and it breaks when Redis drops one of them. Run
93
+ the Redis that holds the queues with `maxmemory-policy noeviction`, the only policy that keeps the
94
+ queues correct:
95
+
96
+ ```
97
+ redis-server --maxmemory-policy noeviction
98
+ ```
99
+
100
+ - A policy such as `allkeys-lru` evicts keys once `maxmemory` is reached, which loses queued jobs and
101
+ corrupts the queue state, and BullMQ warns about it at startup.
102
+ - With `noeviction`, a full Redis rejects writes with an error instead. Size `maxmemory` for the
103
+ queues, and let completed and failed jobs go through `removeOnComplete` / `removeOnFail`.
104
+ - A managed Redis (a cloud cache service) sets the policy in its parameter group, not on the command
105
+ line.
106
+ - A separate Redis that serves only as a cache and holds no queue may keep an evicting policy.
107
+
74
108
  ## Connections are established once, never per job
75
109
 
76
110
  Both the subscription broker and each worker's Redis connection are established **once at Daemon
@@ -106,6 +106,33 @@ buildOptionHash () {
106
106
  publish progress to a subscription, override `onJobProgress` (see
107
107
  [subscriptions.md](./subscriptions.md)).
108
108
 
109
+ ### Detect a job's final failure
110
+
111
+ `onJobFailed({ jobModel, error, previousStatus })` fires on **every** failed attempt, retried or not,
112
+ so a hook that marks the work as failed (a database row, a progress event) has to tell the last
113
+ failure from the rest. BullMQ sets `job.finishedOn` only when it will not retry the job, so
114
+ `jobModel.job.finishedOn` being a number is the check:
115
+
116
+ ```js
117
+ /** @override */
118
+ onJobFailed ({
119
+ jobModel,
120
+ error,
121
+ }) {
122
+ const isFinalFailure = typeof jobModel.job.finishedOn === 'number'
123
+
124
+ if (!isFinalFailure) {
125
+ return null // BullMQ retries this job
126
+ }
127
+
128
+ // ... mark the work as failed, publish the error event ...
129
+ }
130
+ ```
131
+
132
+ Do not compare `attemptsMade >= attempts` instead. A job that throws `UnrecoverableError`, and a job
133
+ that fails because it stalled too many times, stop before `attempts` runs out, so that comparison
134
+ reports them as still retrying and the failure is never recorded.
135
+
109
136
  ## Dispatcher — enqueue + per-queue options
110
137
 
111
138
  `BaseJobDispatcher` subclass. It needs `EngineCtor` (which Engine/Redis to use) and `ManifestCtor`.
@@ -187,3 +214,33 @@ await dispatcher.teardown()
187
214
  **DispatcherResponse** (`hasError()` / `errorMessage` / `hasResponse()` / `createDispatchedAt()`).
188
215
  It auto-`teardown()`s the queue connection unless `keepsConnection: true` is passed (the provider
189
216
  passes `true` to reuse the connection).
217
+
218
+ ### Guard against duplicate jobs with `deduplication`
219
+
220
+ To keep two identical requests from enqueuing two jobs, pass the BullMQ `deduplication` job option
221
+ through `dispatchJob`'s `optionHash`. While the job with that `id` has not completed or failed, a
222
+ second `dispatchJob` with the same `id` adds nothing:
223
+
224
+ ```js
225
+ const response = await dispatcher.dispatchJob({
226
+ body: {
227
+ sessionToken,
228
+ },
229
+ optionHash: {
230
+ deduplication: {
231
+ id: `send-report-email-${sessionToken}`,
232
+ },
233
+ },
234
+ })
235
+ ```
236
+
237
+ - Add `ttl` (milliseconds) to ignore duplicates for a fixed window instead, whatever state the job is
238
+ in.
239
+ - Build the `id` from what makes two requests the same (the session token above), and keep it stable
240
+ across calls.
241
+ - The `deduplication` option is supported in the BullMQ 5 line that `@openreachtech/renchan-job-bullmq`
242
+ depends on (`^5.76.10`). The first 5.x release that carries it is unconfirmed.
243
+ - Prefer it over a custom `jobId`. BullMQ rejects a custom `jobId` that contains `:` or that is
244
+ integer-like (`'123'`), and a custom
245
+ `jobId` keeps blocking the same id for as long as the finished job stays in Redis (that is,
246
+ until `removeOnComplete` / `removeOnFail` removes it), so a retry of the work cannot be enqueued.
@@ -18,10 +18,9 @@ returns `false`, raises that entry's error. Per-value checks (presence / number
18
18
  positive-integer …) are delegated to **`@openreachtech/mentsu-value-inspector`**, imported directly
19
19
  (it is a published module — use it from the package, not a local wrapper).
20
20
 
21
- > Directory layout differs from the current repo on purpose — this is the target convention. The
22
- > support classes (`BaseInputValidator`, `NormalPaginationInputValidator`) come from the renchan
23
- > framework / shared layer; the inspectors come from the `@openreachtech/mentsu-value-inspector`
24
- > module.
21
+ > The support classes (`BaseInputValidator`, `NormalPaginationInputValidator`) ship with
22
+ > renchan-boilerplate under `app/validator/forResolver/`; the inspectors come from the
23
+ > `@openreachtech/mentsu-value-inspector` module.
25
24
 
26
25
  ## Grand principle: declare `[predicate, error]` entries, let the base run them
27
26
 
@@ -176,8 +175,8 @@ async resolve ({
176
175
  }
177
176
  ```
178
177
 
179
- `create({ input, errorHash })` and the run entrypoint (shown as `validate()`) are provided by
180
- `BaseInputValidator` — match the actual base API in your framework.
178
+ `create({ input, errorHash })` and `validate()` come from `BaseInputValidator`. A resolver that
179
+ decides itself when to throw calls `validateInput()`, which returns the error or `null`.
181
180
 
182
181
  ## Testing
183
182
 
@@ -155,9 +155,10 @@ only declare rules:
155
155
  constructors), supplied through the factory.
156
156
  - **`generateValidationEntries()`** — abstract; the subclass returns
157
157
  `Array<[() => boolean, RenchanGraphqlErrorCtor]>`.
158
- - **Run entrypoint** — iterates the entries and, for the first entry whose predicate returns
159
- `false`, raises that `ErrorCtor`. (Shown as `validate()` in the wiring below; use whatever the
160
- actual base names it.)
158
+ - **`validate()`** runs the entries in order and throws `ErrorCtor.create()` of the first one
159
+ whose predicate returns `false`.
160
+ - **`validateInput()`** runs the same entries and returns that error instead, or `null` when every
161
+ rule holds.
161
162
  - Generic JSDoc `@extends {BaseInputValidator<ErrorHash, InputType>}` documents the error hash and
162
163
  input shapes for that validator.
163
164
 
@@ -218,8 +219,7 @@ async resolve ({
218
219
 
219
220
  - The error names in the validator's `ErrorHash` typedef must match keys in the resolver's
220
221
  `errorCodeHash`.
221
- - `create({ input, errorHash })` and the run entrypoint come from `BaseInputValidator`; align with
222
- the actual base API.
222
+ - `create({ input, errorHash })` and `validate()` come from `BaseInputValidator`.
223
223
 
224
224
  ## Testing
225
225
 
@@ -2,10 +2,11 @@
2
2
  name: hor-restfulapi-architecture
3
3
  description: >
4
4
  Understand and build the RESTful API layer of a renchan-style backend: the renderer architecture
5
- under server/restfulapi/. Use this skill whenever the user asks how the REST API is structured,
6
- where a REST endpoint lives, or how to add or edit one — a GET / POST / PUT / PATCH / DELETE
7
- Renderer, its route and version, the render() entry point, the response and error hashes, the
8
- per-request context and share, the engine's auth filter, and response flushers.
5
+ under server/restfulapi/. Use whenever the user asks how the REST API is structured, where an
6
+ endpoint lives, or how to add or edit one: a Renderer per HTTP method, its route, version and
7
+ server directory, render(), the response and error hashes, the per-request context and share, the
8
+ auth filter, flushers, the credential a request carries (cookie, Bearer, IAP JWT, HMAC), and an
9
+ app behind IAP.
9
10
  ---
10
11
 
11
12
  # RESTful API Architecture
@@ -126,6 +127,23 @@ server/restfulapi/
126
127
  discovers every renderer under `renderersPath`, reads its `routePath` and `method`, and registers
127
128
  the express route — you never wire routes by hand.
128
129
 
130
+ - **Several RESTful API servers: one directory per server.** When a project runs more than one
131
+ server (for example one public and one reachable only inside a VPN), each server's routes live
132
+ under `renderers/<server>/v1/`, and each server's engine points `renderersPath` at its own
133
+ `renderers/<server>/v1/`. A single `renderers/v1/` shared by two engines would mount every route
134
+ on both servers, so the VPN-only routes would answer on the public one. A project with one
135
+ server keeps `renderers/v1/`.
136
+
137
+ ```
138
+ server/restfulapi/renderers/
139
+ public/
140
+ v1/
141
+ get/ <Name>Renderer.js
142
+ vpn/
143
+ v1/
144
+ get/ <Name>Renderer.js
145
+ ```
146
+
129
147
  Detail in [renderers.md](./references/renderers.md).
130
148
 
131
149
  ## 2. The renderer
@@ -213,9 +231,11 @@ These three set up the whole REST surface, mirroring the GraphQL engine/context/
213
231
  (`collectMiddleware()`), the **auth filter** (`generateFilterHandler()`), and the **visa issuers**
214
232
  (`visaIssuers`: `hasAuthenticated` / `hasAuthorized` / `hasPathPermission`).
215
233
  - **Context** (`AppRestfulApiContext extends BaseRestfulApiContext`) — built per request. Override
216
- `static async findUser()` to resolve the authenticated user from the access-token header. Exposes
217
- `now`, `userId`, `userEntity`, `share`, `env`, and the visa predicates
218
- (`hasAuthenticated()` / `hasAuthorized()` / `hasPathPermission()`).
234
+ `static async findUser()` to resolve the authenticated user from the access-token header, or
235
+ `static extractAccessToken()` as well to read the credential from another route (a cookie, a
236
+ Bearer token, an IAP JWT, an HMAC signature). Exposes `now`, `userId`, `userEntity`, `share`,
237
+ `env`, and the visa predicates (`hasAuthenticated()` / `hasAuthorized()` /
238
+ `hasPathPermission()`).
219
239
  - **Share** (`AppRestfulApiShare extends BaseRestfulApiShare`) — the per-process object (holds `env`;
220
240
  put shared clients/providers here). Often a `// noop` subclass.
221
241
 
@@ -267,6 +287,12 @@ The adapter, the validator contract, and the error mapping are in
267
287
  - [engine-and-context.md](./references/engine-and-context.md) — the engine (`config`,
268
288
  `renderersPath` / `pathPrefix`, `Share` / `Context`, `standardErrorEnvelopHash`, middleware,
269
289
  filter handler, visa issuers) and the per-request context / per-process share (§3)
290
+ - [credential-routes.md](./references/credential-routes.md) covers reading the credential from a cookie,
291
+ a Bearer token, an IAP JWT or an HMAC signature by overriding `extractAccessToken()` on the
292
+ context, with the CSRF and replay rules each route brings (§3)
293
+ - [behind-iap.md](./references/behind-iap.md) covers an application behind IAP with no sign-in of its
294
+ own: the IAP JWT and its claims, the verifier, a context that finds the actor by `sub`, and what
295
+ the filter skips (§3)
270
296
  - [response-and-flusher.md](./references/response-and-flusher.md) — `RestfulApiResponse`
271
297
  (success / `createAsError`), `errorStructureHash` → `errorResponseHash`, extending the response,
272
298
  and flushers (JSON / Html / Csv / custom, `FlusherCtor`, `contentType`) (§4)
@@ -0,0 +1,116 @@
1
+ # An application behind IAP
2
+
3
+ Identity-Aware Proxy (IAP) sits in front of the application and signs the user in before a request reaches it. The application then has **no sign-in of its own**: no password, no `signIn`, no `signUp`, no refresh token, no cookie, and no session table. Each request arrives with a JWT that IAP signed, and the context verifies it and finds the actor it names. Everything `/hor-cookie-authentication` and `/hor-oidc-sign-in` build is absent, and the access-token header is unused.
4
+
5
+ ## What IAP puts on the request
6
+
7
+ | Header | Use |
8
+ | --- | --- |
9
+ | `x-goog-iap-jwt-assertion` | The signed JWT. The only header the application trusts. |
10
+ | `x-goog-authenticated-user-email`, `x-goog-authenticated-user-id` | Plain headers anyone who reaches the application can set. The application never reads them. |
11
+
12
+ The JWT is signed with ES256 and carries the key id in its header. Its claims the application reads:
13
+
14
+ | Claim | Value | Check |
15
+ | --- | --- | --- |
16
+ | `iss` | `https://cloud.google.com/iap` | Equals this string exactly |
17
+ | `aud` | `/projects/<project-number>/global/backendServices/<backend-service-id>` for a backend service, or `/projects/<project-number>/apps/<project-id>` for App Engine | Equals the configured audience exactly |
18
+ | `exp` | Ten minutes after `iat` | In the future |
19
+ | `sub` | The stable account identifier, prefixed `accounts.google.com:` | Used as the lookup key |
20
+ | `email` | The signed-in address | Matched once, on first sight |
21
+
22
+ Copy the audience string from the protected resource's IAP settings, not from a composition of its parts: a digit transposed in the project number rejects every request, and the verification error does not say why.
23
+
24
+ ## The verifier
25
+
26
+ `IapAssertionVerifier` mirrors the OIDC verifier (`npm install jose`): `jose` fetches and caches Google's public keys for IAP (published as a JWK set), and `jwtVerify` checks the signature and the claims. It checks `exp` only when the token carries one, so `requiredClaims` rejects an assertion that lacks `exp`, `iat`, `sub` or `email`. The Share keeps it, because the key cache has to outlive a request, and creates it from two env values, `IAP_AUDIENCE` and `IAP_JWKS_URL`.
27
+
28
+ ```js
29
+ import {
30
+ createRemoteJWKSet,
31
+ jwtVerify,
32
+ } from 'jose'
33
+
34
+ const IAP_ISSUER = 'https://cloud.google.com/iap'
35
+
36
+ export default class IapAssertionVerifier {
37
+ constructor ({
38
+ audience,
39
+ jwks,
40
+ }) {
41
+ this.audience = audience
42
+ this.jwks = jwks
43
+ }
44
+
45
+ static create ({
46
+ audience,
47
+ jwksUrl,
48
+ }) {
49
+ return new this({
50
+ audience,
51
+ jwks: createRemoteJWKSet(new URL(jwksUrl)),
52
+ })
53
+ }
54
+
55
+ async verify ({
56
+ assertion,
57
+ }) {
58
+ const { payload } = await jwtVerify(assertion, this.jwks, {
59
+ issuer: IAP_ISSUER,
60
+ audience: this.audience,
61
+ algorithms: ['ES256'],
62
+ requiredClaims: ['exp', 'iat', 'sub', 'email'],
63
+ })
64
+
65
+ return payload
66
+ }
67
+ }
68
+ ```
69
+
70
+ Fix the issuer and the algorithm in code. Only the key location and the audience vary by environment, and the local stand-in signs with the real issuer (`/hor-build-e2e-test-environment`), so no check is relaxed to make a local run pass.
71
+
72
+ ## The context
73
+
74
+ `extractAccessToken()` returns the header ([credential-routes](./credential-routes.md)), and `findUser()` verifies it. A request with no assertion, or one that fails verification, resolves no user, and the filter answers `Unauthenticated`.
75
+
76
+ ```js
77
+ export default class AppRestfulApiContext extends BaseRestfulApiContext {
78
+ /** @override */
79
+ static extractAccessToken ({
80
+ expressRequest,
81
+ }) {
82
+ return AccessCredentialReader.readIapAssertion({
83
+ headers: expressRequest.headers,
84
+ })
85
+ }
86
+
87
+ /** @override */
88
+ static async findUser ({
89
+ engine,
90
+ accessToken,
91
+ }) {
92
+ if (accessToken === null) {
93
+ return null
94
+ }
95
+
96
+ const claimHash = await engine.share.iapAssertionVerifier
97
+ .verify({ assertion: accessToken })
98
+ .catch(rejection => {
99
+ console.error(`IAP assertion rejected: ${rejection.constructor.name}`)
100
+
101
+ return null
102
+ })
103
+
104
+ if (claimHash === null) {
105
+ return null
106
+ }
107
+
108
+ return Operator.findOrLinkByIapClaims({ claimHash })
109
+ }
110
+ }
111
+ ```
112
+
113
+ - **Verify on every request, and never fall through.** The application is reachable by something other than IAP (a neighbour in the network, a misconfigured firewall rule), and an unverified header there is a forged identity. A missing header is `Unauthenticated`, not a reason to try another route.
114
+ - **`findOrLinkByIapClaims()` finds the actor by `sub`.** On a miss it looks for a pre-registered actor with that `email` and records the `sub` against it in one guarded update, so every later request finds it by `sub`. A person IAP admits but the application does not know gets `null`. Create the actor on first sight only when the specification says anyone IAP admits may use the application.
115
+ - **The filter has almost nothing to skip.** `schemasToSkipFiltering` holds a health check at most, because there is no sign-in operation to be public. Authorization (`hasAuthorized`, `hasSchemaPermission`) still comes from the visa, from what the actor entity says it may do.
116
+ - **Sign-out is IAP's.** The application holds no session to revoke, so it ships no `signOut`. Ending the session means ending the Google session, which the frontend reaches through IAP's own sign-out path.
@@ -0,0 +1,173 @@
1
+ # Credential routes
2
+
3
+ A request carries its credential in one place, and the context decides which. By default the context reads the `x-renchan-access-token` header. Another route replaces that read by overriding one static method on the context class, and nothing else in the framework changes: `static extractAccessToken()` returns the credential as a string (or `null`), `static findUser()` turns it into an entity (or `null`), and the visa issuers and the filter handler work from there ([engine-and-context](./engine-and-context.md)).
4
+
5
+ ```js
6
+ // BaseRestfulApiContext, as shipped
7
+ static extractAccessToken ({
8
+ expressRequest,
9
+ }) {
10
+ return expressRequest.headers?.[this.ACCESS_TOKEN_HEADER_KEY]
11
+ ?? null
12
+ }
13
+ ```
14
+
15
+ Two rules hold for every route below.
16
+
17
+ - **`extractAccessToken()` only reads.** It is synchronous, so it does no I/O and verifies nothing: it returns the raw credential. Verification, key fetches and database lookups belong to `findUser()`, which is async and receives the credential as `accessToken`.
18
+ - **A context reads exactly one route, and a missing credential is `null`.** Do not write "try the cookie, then the header". A context that falls through lets a request that lost its intended credential authenticate by a weaker one, and the visa then says `hasAuthenticated` for the wrong reason. A different audience that authenticates differently gets its own engine and its own Context class.
19
+
20
+ The four readers sit in one app class, so a REST context and a GraphQL context that use the same route call the same code. Each takes the request's `headers`, which both contexts can supply.
21
+
22
+ ```js
23
+ import {
24
+ parse,
25
+ } from 'cookie'
26
+
27
+ export default class AccessCredentialReader {
28
+ static readCookie ({
29
+ headers,
30
+ cookieName,
31
+ }) {
32
+ if (!headers?.cookie) {
33
+ return null
34
+ }
35
+
36
+ return parse(headers.cookie)[cookieName]
37
+ ?? null
38
+ }
39
+
40
+ static readBearerToken ({
41
+ headers,
42
+ }) {
43
+ const matched = (headers?.authorization ?? '')
44
+ .match(/^Bearer\s+(\S+)$/iu)
45
+
46
+ return matched?.[1]
47
+ ?? null
48
+ }
49
+
50
+ static readIapAssertion ({
51
+ headers,
52
+ }) {
53
+ return headers?.['x-goog-iap-jwt-assertion']
54
+ ?? null
55
+ }
56
+
57
+ static readHmacSignature ({
58
+ headers,
59
+ }) {
60
+ return headers?.['x-signature']
61
+ ?? null
62
+ }
63
+ }
64
+ ```
65
+
66
+ Node lower-cases every header name, so the keys are lower case. The REST context calls a reader from its override:
67
+
68
+ ```js
69
+ export default class AppRestfulApiContext extends BaseRestfulApiContext {
70
+ /** @override */
71
+ static extractAccessToken ({
72
+ expressRequest,
73
+ }) {
74
+ return AccessCredentialReader.readBearerToken({
75
+ headers: expressRequest.headers,
76
+ })
77
+ }
78
+ }
79
+ ```
80
+
81
+ ## Cookie
82
+
83
+ The credential is a cookie of its own, never the refresh-token cookie of `/hor-cookie-authentication`, which only `renewAccessToken` and `signOut` may read. Read it with `readCookie({ headers, cookieName })`. No cookie-parsing middleware is mounted, so the `cookie` package parses the header (`npm install cookie`, which `/hor-cookie-authentication` already does for its own cookie).
84
+
85
+ A browser attaches a cookie to every request to its origin, so this route gives up the protection a custom header has. Set it `HttpOnly`, `Secure` and `SameSite=Lax` or `Strict`, and add a defence for state-changing requests: a custom header the page must set, or a check of `origin` against the allowed origins. `findUser()` looks the token up as it does for the header.
86
+
87
+ ## Bearer token
88
+
89
+ The credential is the `authorization` header with the `Bearer` scheme. `readBearerToken()` matches the scheme without regard to case and returns `null` for any other scheme or a missing token. `findUser()` is identical to the header route's: look the token up, return the entity or `null`.
90
+
91
+ ## IAP assertion
92
+
93
+ The credential is the JWT that IAP puts in `x-goog-iap-jwt-assertion`. `readIapAssertion()` returns it unverified. `findUser()` verifies the signature, issuer, audience and expiry before it trusts a claim, then finds the actor. The verifier, the claims and the lookup are in [behind-iap](./behind-iap.md). The `x-goog-authenticated-user-email` header that IAP also sets is not signed, so no code reads it.
94
+
95
+ ## HMAC signature
96
+
97
+ The credential is a signature that a caller computes over the request with a secret both sides hold, for a partner system that calls the API with no user. The header carries a timestamp and the digest, and a second header names the key:
98
+
99
+ ```
100
+ x-key-id: partner-0001
101
+ x-signature: t=1767225600,v1=<hex HMAC-SHA256 of "<t>.<METHOD>.<path>.<raw body>">
102
+ ```
103
+
104
+ `readHmacSignature()` returns the `x-signature` value, or `null` when the header is missing. `findUser()` returns `null` for that case before it parses anything, re-reads `x-key-id`, and checks four things in this order: the timestamp lies within a window of `requestedAt` (five minutes), a partner holds that key id, the digest matches, and the partner is active. The signed text binds the method and the path (with its query string), so a signature captured for one operation cannot authorize another.
105
+
106
+ ```js
107
+ static async findUser ({
108
+ expressRequest,
109
+ accessToken,
110
+ requestedAt = new Date(),
111
+ }) {
112
+ if (accessToken === null) {
113
+ return null
114
+ }
115
+
116
+ const signature = SignatureHeader.create({ headerValue: accessToken })
117
+
118
+ if (signature.isStale({ pointsAt: requestedAt })) {
119
+ return null
120
+ }
121
+
122
+ const partnerEntity = await Partner.findByKeyId({
123
+ keyId: expressRequest.headers['x-key-id'],
124
+ })
125
+
126
+ if (partnerEntity === null) {
127
+ return null
128
+ }
129
+
130
+ const hasMismatchedSignature = partnerEntity.hasMismatchedSignature({
131
+ signature,
132
+ method: expressRequest.method,
133
+ path: expressRequest.originalUrl,
134
+ rawBody: expressRequest.rawBody,
135
+ })
136
+
137
+ if (hasMismatchedSignature) {
138
+ return null
139
+ }
140
+
141
+ if (partnerEntity.isDeactivated()) {
142
+ return null
143
+ }
144
+
145
+ return partnerEntity
146
+ }
147
+ ```
148
+
149
+ `SignatureHeader` splits `t=<seconds>,v1=<hex>` into `timestamp` and `digestHex`, and `isStale()` is true when the timestamp lies outside the window around a moment.
150
+
151
+ ```js
152
+ // Partner
153
+ hasMismatchedSignature ({
154
+ signature,
155
+ method,
156
+ path,
157
+ rawBody,
158
+ }) {
159
+ const expected = createHmac('sha256', this.extractSigningSecret())
160
+ .update(`${signature.timestamp}.${method.toUpperCase()}.${path}.`)
161
+ .update(rawBody ?? '')
162
+ .digest()
163
+ const received = Buffer.from(signature.digestHex, 'hex')
164
+
165
+ return received.length !== expected.length
166
+ || !timingSafeEqual(received, expected)
167
+ }
168
+ ```
169
+
170
+ - **Compare in constant time, and compare lengths first.** `timingSafeEqual` throws on buffers of different length, and a `===` on hex strings leaks where they first differ.
171
+ - **The window blocks replay of an old request.** Inside the window a replay still verifies, so a state-changing operation that must run once carries an idempotency key of its own.
172
+ - **The signing secret must be recoverable**, because the server recomputes the digest. Store it encrypted, never hashed, and read it through the Share's env-held key, as every env value is read.
173
+ - **The signature covers the raw bytes.** The engine's body parser has to keep them: the `verify` callback of `express.json` stores `req.rawBody` as the `Buffer` it is given, under `// eslint-disable-next-line no-param-reassign`, the directive the lint config allows in the engine files. A GraphQL engine captures `rawBody` on `urlencoded` only, so its `express.json` needs the same `verify`. A body re-serialized from the parsed object is not the bytes the caller signed.
@@ -48,7 +48,9 @@ export default class AppRestfulApiServerEngine extends BaseRestfulApiServerEngin
48
48
 
49
49
  - **`static get config()`** — `pathPrefix` (route prefix, e.g. `/v1`), `renderersPath` (the **one**
50
50
  version directory whose renderers this engine serves), `staticPath` (static files root). To serve
51
- a second version, run an engine pointed at `renderers/v2/` with `pathPrefix: '/v2'`.
51
+ a second version, run an engine pointed at `renderers/v2/` with `pathPrefix: '/v2'`. With
52
+ several RESTful API servers, each server has its own engine whose `renderersPath` is
53
+ `renderers/<server>/v1/`, so one server never mounts another's routes.
52
54
  - **`static get Share()` / `static get Context()`** — the app Share / Context classes (below).
53
55
  - **`static get standardErrorEnvelopHash()`** — the **cross-cutting** error envelopes, keyed by
54
56
  name, each `{ statusCode, errorMessage }`. The framework requires at least `Unknown`,
@@ -132,8 +134,10 @@ A renderer with `get passesFilter () { return true }` skips this entirely (publi
132
134
  ## Context (per request)
133
135
 
134
136
  `AppRestfulApiContext extends BaseRestfulApiContext`. The framework builds it **per request**:
135
- it extracts the access token from the header (`x-renchan-access-token`), calls `findUser`, and
136
- builds the visa from the engine's `visaIssuers`.
137
+ it extracts the access token with `extractAccessToken()` (by default from the
138
+ `x-renchan-access-token` header), calls `findUser`, and builds the visa from the engine's
139
+ `visaIssuers`. A cookie, a Bearer token, an IAP JWT or an HMAC signature replaces the header by
140
+ overriding `extractAccessToken()` ([credential-routes.md](./credential-routes.md)).
137
141
 
138
142
  ```js
139
143
  import {
@@ -147,15 +151,17 @@ export default class AppRestfulApiContext extends BaseRestfulApiContext {
147
151
  * @override
148
152
  * @param {{
149
153
  * expressRequest: ExpressType.Request
154
+ * engine?: RestfulApiType.ServerEngine
150
155
  * accessToken: string | null
151
- * now?: Date
156
+ * requestedAt?: Date
152
157
  * }} params
153
158
  * @returns {Promise<renchan.UserEntity | null>}
154
159
  */
155
160
  static async findUser ({
156
161
  expressRequest,
162
+ engine,
157
163
  accessToken,
158
- now = new Date(),
164
+ requestedAt = new Date(),
159
165
  }) {
160
166
  // look up the token → return the user entity, or null
161
167
  }
@@ -38,6 +38,10 @@ server/restfulapi/renderers/<version>/<method>/<Name>Renderer.js
38
38
  than repeating it in the name.
39
39
  - A new API **version** is a new directory (`renderers/v2/`) served by an engine pointed at it with
40
40
  its own `pathPrefix` (`/v2`). See [engine-and-context.md](./engine-and-context.md).
41
+ - When a project runs **several RESTful API servers**, the server name becomes the first level:
42
+ `renderers/<server>/<version>/<method>/<Name>Renderer.js`, for example
43
+ `renderers/vpn/v1/get/HealthCheckRenderer.js`. Each server's engine serves only its own
44
+ `renderers/<server>/<version>/`, so a route placed under one server never mounts on another.
41
45
 
42
46
  ## The fixed surface
43
47