@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
@@ -141,6 +141,12 @@ buildWhereClause ({
141
141
 
142
142
  - Import `Op` from `sequelize`. Use `[Op.like]` for prefix search (`` `${keyword}%` ``), `[Op.or]`
143
143
  for multi-column keyword match, `[Op.in]` with a subquery for a related-table filter.
144
+ - **`[Op.like]` is as case-sensitive as the database's collation.** On MariaDB and MySQL the usual
145
+ `_ci` collations make it case-insensitive (and accent-insensitive), and SQLite matches ASCII
146
+ letters without regard to case. PostgreSQL is case-sensitive, so `name LIKE 'tar%'` misses `Taro`
147
+ there. On PostgreSQL write `[Op.iLike]` for a case-insensitive prefix match; it emits `ILIKE`,
148
+ which MariaDB, MySQL and SQLite do not have, so a project that runs on both picks the operator by
149
+ `sequelize.getDialect()`.
144
150
  - Import `ValueInspector` from `@openreachtech/mentsu-value-inspector`;
145
151
  `ValueInspector.create({ value: keyword }).isPresent()` guards `null` / `undefined` before
146
152
  `keyword.trim()`. The package has no string/blank inspector (presence + number / integer / date
@@ -201,6 +207,17 @@ builds the output object. Never return a raw model instance.
201
207
  - **Money / decimal fields → strings.** Emit a decimal (money, rate) via `BigNumber(value).toFixed(2)`
202
208
  (compute into a named `const` first), matching the `String!` SDL money type (`hor-graphql-schema`) —
203
209
  never a raw JS number.
210
+ - **PostgreSQL `BIGINT` ids → `Number()`.** node-postgres returns a `BIGINT` (int8) column as a
211
+ string (`'100001'`), where MariaDB, MySQL and SQLite return a number. Convert each such value in
212
+ `formatResponse()` before it goes into an SDL `Int` field (`userId: Number(user.id)`), so the
213
+ response carries a number and a later `===` against an `Int` input holds (`'100001' === 100001`
214
+ is `false`). `Number()` changes nothing on the other databases, so write it unconditionally.
215
+ - **Never wrap a nullable value directly**, because `Number(null)` is `0`:
216
+ `customerId: order.CustomerId === null ? null : Number(order.CustomerId)`.
217
+ - `Number()` loses precision above `Number.MAX_SAFE_INTEGER` (2^53 - 1), so an id that can exceed
218
+ it stays a string (GraphQL `ID`).
219
+ - A GraphQL `Int` is 32 bits. A column whose values can pass 2147483647 takes the `BigNumber`
220
+ scalar (`/hor-graphql-schema`), not `Number()`.
204
221
  - Echo pagination for lists.
205
222
 
206
223
  ### Deep values via FieldPathValueExtractor
@@ -1,13 +1,13 @@
1
1
  # Errors, context, and actual-vs-stub
2
2
 
3
- The errorCodeHash prefix families, the validator↔errorHash contract, domain-error creators, reading
4
- auth and injected providers off `context`, and the actual-vs-stub split. Referenced from §1 and §4 of
5
- [SKILL.md](../SKILL.md).
3
+ The categories a query resolver's codes take, the validator↔errorHash contract, domain-error
4
+ creators, reading auth and injected providers off `context`, and the actual-vs-stub split.
5
+ Referenced from §1 and §4 of [SKILL.md](../SKILL.md).
6
6
 
7
7
  > The `users` / `User` / `Department` names and the `Q001` / `Q002` identifiers are placeholders —
8
8
  > swap in your resource and this resolver's own identifier.
9
9
 
10
- ## errorCodeHash: families and identifiers
10
+ ## errorCodeHash: which category each error takes
11
11
 
12
12
  `errorCodeHash` maps each error **name** to a **string code**; the framework's `create()` turns those
13
13
  into the `this.errorHash.<Name>` constructors the resolver and its validator throw. Always spread
@@ -30,18 +30,14 @@ static get errorCodeHash () {
30
30
  }
31
31
  ```
32
32
 
33
- Code format is `<family>.<identifier>.<seq>`:
34
-
35
- - **`<family>`** — the leading number classifies the error:
36
- - `203` — invalid input (raised by the `*InputValidator`).
37
- - `204` — database / not-found (thrown from `resolve()`).
38
- - `205` — business logic / external API.
39
- - Framework standards sit above these and are already defined by the engine — do **not** redeclare
40
- them: `102` unauthenticated / unauthorized / denied-permission, `104` database, `100` unknown,
41
- `101` concrete-member-not-found.
42
- - **`<identifier>`** (`Q002`, …) is a **stable per-query id**. Keep one resolver on one identifier;
43
- the letter tracks the endpoint family (`Q` for the query endpoints).
44
- - **`<seq>`** (`001`, `002`, …) numbers the errors within this resolver, per family.
33
+ The code's shape, and the categories its leading digits sort a failure into, are settled by
34
+ `hoc-error-codes`. What a query resolver decides is which category each of its own errors takes:
35
+
36
+ - `203` — validational, raised by the `*InputValidator`.
37
+ - `204` — database record, thrown from `resolve()`.
38
+
39
+ The framework's own codes are already declared by the engine — `102` access right, `104` database
40
+ record, `100` unknown, `101` implementational — and a resolver never redeclares one.
45
41
 
46
42
  ## The validator ↔ errorHash contract
47
43
 
@@ -5,7 +5,7 @@ description: >
5
5
  this skill whenever the user asks to add or edit a job under app/jobs/** — a Manifest / Worker /
6
6
  Dispatcher triple, a cron or interval (repeatable) job, enqueuing from a GraphQL/REST resolver,
7
7
  publishing progress to a GraphQL subscription, the worker daemon entry point, splitting work
8
- across queues, or tuning concurrency / retries / rate limits.
8
+ across queues, tuning concurrency / retries / rate limits, the queue's Redis policy, or duplicate guards.
9
9
  ---
10
10
 
11
11
  # renchan-job-bullmq
@@ -88,11 +88,14 @@ Full classes, hooks, the base-app-dispatcher pattern, and the enqueue paths are
88
88
  the one config object: `config` = `{ workersPath, schedulersPath, redisConfig }` (both paths point
89
89
  at `app/jobs`), plus `ShareCtor` / `ContextCtor`, error codes, log path. `createAsync({ subscriptionBroker })`
90
90
  injects the progress broker (§4).
91
- - **Share** — per-**process** DI (holds `subscriptionBroker` or `null`, `env`, `timber`, …).
91
+ - **Share** is the per-**process** DI (holds `subscriptionBroker` or `null`, `env`, `timber`, …). It is the
92
+ only class that imports `env`.
92
93
  - **Context** — per-**job** DI, created for each run and passed to `executeJob`.
93
- - **RedisConnection** (`app/queue/RedisConnection.js`) —
94
+ - **RedisConnection** (`app/queue/RedisConnection.js`) is created by the Share with the env
95
+ (`ContentGenerationJobShare.createRedisConnection()`), and gives
94
96
  `generateConnectionOptions()` for BullMQ (**`maxRetriesPerRequest: null` required**) and
95
97
  `generatePubSubOptions()` for the broker. **API and Daemon must share one Redis.**
98
+ That Redis must run with `maxmemory-policy noeviction`; an evicting policy corrupts the queues.
96
99
 
97
100
  Details and the package-exports table are in [engine-and-infra.md](./references/engine-and-infra.md).
98
101
 
@@ -154,12 +157,18 @@ Details and the directory diagram are in [queues.md](./references/queues.md).
154
157
  (`{ millisecond, isImmediately }`), listed in `SchedulerService.collectScheduleInputs()` with a
155
158
  `schedulerId` matching the scheduler class. See [daemon-and-scheduler.md](./references/daemon-and-scheduler.md).
156
159
  - **Connection reuse** — `JobDispatcherProvider`
157
- (`app/tools/JobDispatcherProvider.js`) caches one
158
- Dispatcher per `DispatcherCtor` and dispatches with `keepsConnection: true`; the request Share
159
- holds one, torn down on process exit. Prefer it over `Dispatcher.createAsync()` per request.
160
+ (`app/tools/JobDispatcherProvider.js`) caches one Dispatcher per `DispatcherCtor` and dispatches
161
+ with `keepsConnection: true`; the request Share holds one, torn down on process exit. Prefer it
162
+ over `Dispatcher.createAsync()` per request.
160
163
  - **Retries & idempotency** — set `attempts` in `optionHash`; make `executeJob` idempotent (BullMQ may
161
164
  re-run). Expensive AI jobs checkpoint to `content_generations.intermediate_steps_json` and
162
165
  resume on retry.
166
+ `onJobFailed` fires on every failed attempt, so treat a job as finally failed only when
167
+ `jobModel.job.finishedOn` is a number, never by comparing `attemptsMade` with `attempts`
168
+ ([job-triple.md](./references/job-triple.md)).
169
+ - **Duplicate guard**: to keep identical requests from enqueuing twice, pass
170
+ `optionHash: { deduplication: { id } }` to `dispatchJob` rather than a custom `jobId`
171
+ ([job-triple.md](./references/job-triple.md)).
163
172
  - **Concurrency & rate limiting** — `buildOptionHash()` forwards `concurrency` + `limiter`
164
173
  (`app/tools/ContentGenerationRateLimiter.js`).
165
174
  - **Testing** — unit-test workers/dispatchers with the `hoc-jest` skill.
@@ -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.