@openreachtech/hora-skills-ort-renchan 0.3.0 → 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 (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 +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 +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 +5 -4
  49. package/docs/skills.md +5 -4
  50. package/package.json +1 -1
@@ -0,0 +1,61 @@
1
+ ---
2
+ name: hor-oidc-sign-in
3
+ description: "Sign an actor in through an external OpenID Connect identity provider on a renchan backend: the authorization code flow with PKCE, where state, nonce and the code verifier live, how the ID token is verified, and how the provider's subject links to an actor. Use when adding a 'sign in with' provider. Boundary: tokens, sessions and the refresh cookie follow the cookie authentication convention; a proxy that signs users in before the app, such as IAP, is not this flow."
4
+ metadata:
5
+ author: OpenReachTech
6
+ version: "2026.10.16"
7
+ ---
8
+
9
+ # OIDC Sign-in (Backend)
10
+
11
+ Use this skill when an actor signs in at an external OpenID Connect identity provider (IdP) instead of with a password held by the app. The app is a **confidential client**: it holds the client secret, starts the flow, receives the authorization code, exchanges it, verifies the ID token, and links the provider's account to one of its own actors.
12
+
13
+ This skill ends at an **actor entity**. Opening the session from there is `/hor-cookie-authentication`, unchanged: `SessionClerk.saveSession`, the refresh-token cookie, and the access token in the response body. After sign-in, every request still authenticates by the access-token header, `renewAccessToken` still renews, and `signOut` still revokes. Nothing in this skill touches those. A proxy that signs the user in before the request reaches the app (IAP) has no code exchange and no session: see `/hor-restfulapi-architecture`, its `behind-iap` reference.
14
+
15
+ > Snippets use `<Actor>` for the role being signed in, as `/hor-cookie-authentication` does.
16
+
17
+ ## The flow
18
+
19
+ Two public mutations bracket a trip to the IdP. The browser never sees the client secret, the code verifier or the nonce.
20
+
21
+ ```
22
+ frontend backend identity provider
23
+ | startOidcSignIn |
24
+ |-------------------->| create state, nonce, code verifier
25
+ | | save the authorization row, set the state cookie
26
+ |<--------------------| authorizationUrl
27
+ | navigate ---------------------------------------------->| user signs in
28
+ |<---------------------------------------- redirect to redirect_uri?code&state
29
+ | signInWithOidc |
30
+ | { code, state } | state == cookie == row, row unused and unexpired
31
+ |-------------------->| exchange code + code verifier + client secret ---->|
32
+ | |<--------------------------------------- ID token --|
33
+ | | verify the ID token, find or link the actor
34
+ | | saveSession, refresh cookie, clear the state cookie
35
+ |<--------------------| accessToken
36
+ ```
37
+
38
+ A public mutation pair follows the precedent `/hor-graphql-server-engine` sets with its public operations. The alternative is a REST `GET` callback on the backend that answers with a redirect. Choose it only when no frontend page can receive the IdP's redirect. The renderer then answers with a redirect flusher and sets the cookies through the response `headers` (`/hor-restfulapi-architecture`), and the rules below hold unchanged.
39
+
40
+ ## Rules that keep the flow safe
41
+
42
+ - **PKCE with `S256` on every authorization**, even though the app holds a secret. The `code_challenge` is the SHA-256 digest of the verifier, base64url-encoded without padding. The verifier is 32 random bytes from `crypto.randomBytes`, base64url-encoded.
43
+ - **`state` ties the callback to the browser that started it.** The backend writes it to a short-lived `HttpOnly` cookie and to the authorization row. `signInWithOidc` accepts the call only when the `state` argument, the cookie and a row all agree. Without the cookie, an attacker could hand a victim a callback link that signs the victim in as the attacker.
44
+ - **The authorization row is single use and expires in about ten minutes.** Spend it with one update guarded on `usedAt: null` and on `expiredAt` still ahead, as the refresh-token rotation guards its own, so a replayed or late callback updates nothing. Missing, used and expired rows all raise one error, so the response does not say which.
45
+ - **`nonce` travels inside the ID token.** Compare the token's `nonce` claim to the one stored in the row.
46
+ - **Verify the ID token before reading any claim from it** ([id-token-verification](./references/id-token-verification.md)). The code exchange happens over TLS straight from the IdP, but the signature check is still required, because the claims are what the app is about to trust.
47
+ - **`redirect_uri` is a configured value, never taken from the request**, and it matches the IdP's registration exactly. The same string goes into the authorization URL and into the token request.
48
+ - **Link an actor by `(issuer, subject)`, never by email alone.** `sub` is stable and an email address can change hands. A first sign-in may attach to a pre-registered actor by email only when the token carries `email_verified: true`, and only once: the identity row it writes is what every later sign-in finds.
49
+ - **Keep the IdP's tokens out of storage** unless the app calls the IdP's APIs on the actor's behalf. Signing in needs the ID token once, during the callback.
50
+ - **The client secret is read through the Share** (`share.env`), like every other env value ([environment](./references/environment.md)). Log neither the code, the verifier nor any token.
51
+
52
+ ## Core
53
+
54
+ | Topic | Description | Reference |
55
+ | --- | --- | --- |
56
+ | Environment & config | The `OIDC_*` env vars, the discovery document, the state-cookie constant and the engine's public operations | [environment](./references/environment.md) |
57
+ | Authorization & identity storage | The two tables and their models: the single-use authorization row and the `(issuer, subject)` identity link | [storage](./references/storage.md) |
58
+ | ID token verification | `OidcIdTokenVerifier`: signature by `kid`, `iss`, `aud`, `exp`, `nonce`, and why the Share keeps it | [id-token-verification](./references/id-token-verification.md) |
59
+ | Resolvers | `startOidcSignIn` and `signInWithOidc`, wired to the session clerk and the cookie clerk | [resolvers](./references/resolvers.md) |
60
+
61
+ The token-endpoint call and the discovery and key fetches are an external API client (`/hor-external-api-client`). The IdP stand-in for local runs belongs to `/hor-build-e2e-test-environment`.
@@ -0,0 +1,94 @@
1
+ # Environment & config
2
+
3
+ Set these up once per project, before the resolvers. Steps:
4
+
5
+ ## 1. Dependency
6
+
7
+ The ID token is verified with `jose` ([id-token-verification](./id-token-verification.md)), and the state cookie is written with the `cookie` package that `/hor-cookie-authentication` already installs. Add the first:
8
+
9
+ ```
10
+ npm install jose
11
+ ```
12
+
13
+ ## 2. Env vars
14
+
15
+ The provider's identity and the app's registration with it are environment-driven, so they change per deploy with no code change. Add to each `.env.*`:
16
+
17
+ ```
18
+ OIDC_ISSUER=
19
+ OIDC_CLIENT_ID=
20
+ OIDC_CLIENT_SECRET=
21
+ OIDC_REDIRECT_URI=
22
+ OIDC_SCOPE=
23
+ ```
24
+
25
+ Declare them on the env-facade typedef and read them **through the facade**, never `process.env` directly. Only the Share imports `env`, so every other class receives the values from `share.env` (`/hor-resolver-share`).
26
+
27
+ - `OIDC_ISSUER` is the issuer identifier exactly as the provider publishes it, including any trailing slash. It is compared to the `iss` claim as a string, so a slash that differs rejects every token.
28
+ - `OIDC_REDIRECT_URI` is one of the redirect URIs registered at the provider, character for character.
29
+ - `OIDC_SCOPE` starts with `openid`. Add `email` when the first-link step matches a pre-registered actor by email ([storage](./storage.md)).
30
+ - `OIDC_CLIENT_SECRET` is a secret: keep it out of committed env files. A local env file holds only the stand-in's placeholder (`/hor-build-e2e-test-environment`).
31
+
32
+ ## 3. The discovery document
33
+
34
+ The provider publishes its endpoints at a well-known path under the issuer. `OidcProviderConfiguration` fetches that document **once, when the Share is created**, through an external API client (`/hor-external-api-client`), and exposes `issuer`, `authorizationEndpoint`, `tokenEndpoint` and `jwksUri`. It checks that the document's `issuer` equals `OIDC_ISSUER` and throws otherwise: a mismatch means the app is pointed at the wrong provider, and booting is better than signing anyone in against it.
35
+
36
+ The Share only creates what it keeps, through the other classes' factory methods:
37
+
38
+ ```js
39
+ /** @override */
40
+ static async createAsync ({
41
+ config,
42
+ }) {
43
+ const env = this.generateEnv()
44
+ const oidcProviderConfiguration = await OidcProviderConfiguration.createAsync({
45
+ issuer: env.OIDC_ISSUER,
46
+ })
47
+
48
+ return this.create({
49
+ env,
50
+ oidcProviderConfiguration,
51
+ oidcIdTokenVerifier: OidcIdTokenVerifier.create({
52
+ clientId: env.OIDC_CLIENT_ID,
53
+ providerConfiguration: oidcProviderConfiguration,
54
+ }),
55
+ // ...
56
+ })
57
+ }
58
+ ```
59
+
60
+ The Share keeps both instances because each outlives a request: the configuration is fetched once, and the verifier holds the key cache ([id-token-verification](./id-token-verification.md)). A resolver reads `tokenEndpoint` from `context.share.oidcProviderConfiguration`.
61
+
62
+ ## 4. State-cookie constant
63
+
64
+ The state cookie has its own name, so it never collides with the refresh-token cookie of the same actor. Define it next to that one (`/hor-constant-definition`):
65
+
66
+ ```js
67
+ // constants/authConstants.cjs
68
+ OIDC_STATE_COOKIE: {
69
+ <ACTOR>: {
70
+ NAME: '<actor>_oidc_state',
71
+ MAX_AGE_SECONDS: 600,
72
+ },
73
+ }
74
+ ```
75
+
76
+ The cookie is written and cleared by a clerk shaped like the refresh-token cookie clerk (`/hor-cookie-authentication`): `HttpOnly`, the same `secure` and `sameSite` as that cookie, the same `path`, and a lifetime equal to the authorization row's. Clearing presents the same attributes as the write, minus the lifetime.
77
+
78
+ ## 5. Public operations
79
+
80
+ Both mutations run before the actor has a credential, so list them in the engine's `schemasToSkipFiltering` next to the password operations (`/hor-graphql-server-engine`):
81
+
82
+ ```js
83
+ get schemasToSkipFiltering () {
84
+ return [
85
+ 'startOidcSignIn',
86
+ 'signInWithOidc',
87
+ // ... the other public operations
88
+ ]
89
+ }
90
+ ```
91
+
92
+ ## 6. TLS
93
+
94
+ The state cookie and the refresh cookie are `Secure` in production, so the redirect URI is an HTTPS address there. A local run against the provider stand-in uses plain HTTP and turns `AUTH_COOKIE_SECURE` off, as the cookie skill's environment step describes.
@@ -0,0 +1,98 @@
1
+ # ID token verification
2
+
3
+ The ID token is a signed JWT, and the app must verify it before reading one claim from it. `OidcIdTokenVerifier` (`app/oidc/`) does this with `jose`: `createRemoteJWKSet` fetches and caches the provider's public keys, and `jwtVerify` checks the signature and the claims in one call.
4
+
5
+ ```js
6
+ import {
7
+ createRemoteJWKSet,
8
+ jwtVerify,
9
+ } from 'jose'
10
+
11
+ export default class OidcIdTokenVerifier {
12
+ constructor ({
13
+ clientId,
14
+ issuer,
15
+ jwks,
16
+ }) {
17
+ this.clientId = clientId
18
+ this.issuer = issuer
19
+ this.jwks = jwks
20
+ }
21
+
22
+ static create ({
23
+ clientId,
24
+ providerConfiguration,
25
+ }) {
26
+ return new this({
27
+ clientId,
28
+ issuer: providerConfiguration.issuer,
29
+ jwks: createRemoteJWKSet(new URL(providerConfiguration.jwksUri)),
30
+ })
31
+ }
32
+
33
+ /**
34
+ * Verify the ID token and return its claims.
35
+ *
36
+ * @param {{
37
+ * idToken: string
38
+ * nonce: string
39
+ * }} params
40
+ * @returns {Promise<import('jose').JWTPayload>}
41
+ */
42
+ async verify ({
43
+ idToken,
44
+ nonce,
45
+ }) {
46
+ const { payload } = await jwtVerify(idToken, this.jwks, {
47
+ issuer: this.issuer,
48
+ audience: this.clientId,
49
+ algorithms: ['RS256'],
50
+ requiredClaims: ['exp', 'iat', 'sub'],
51
+ clockTolerance: 30,
52
+ })
53
+
54
+ if (payload.nonce !== nonce) {
55
+ throw new Error('The nonce claim differs from the stored nonce')
56
+ }
57
+
58
+ if (this.hasUnrelatedAuthorizedParty({ payload })) {
59
+ throw new Error('The azp claim names another client')
60
+ }
61
+
62
+ return payload
63
+ }
64
+
65
+ hasUnrelatedAuthorizedParty ({
66
+ payload,
67
+ }) {
68
+ const hasSeveralAudiences = Array.isArray(payload.aud)
69
+ && payload.aud.length > 1
70
+
71
+ return hasSeveralAudiences
72
+ && payload.azp !== this.clientId
73
+ }
74
+ }
75
+ ```
76
+
77
+ ## What each check rules out
78
+
79
+ | Check | Rules out |
80
+ | --- | --- |
81
+ | Signature, with the key picked by the header's `kid` | A token the provider never signed |
82
+ | `algorithms` pinned to the one the provider uses | A token that names `none`, or a symmetric algorithm keyed with a public key |
83
+ | `iss` equals the configured issuer, as a string | A token from another provider, or another tenant of the same one |
84
+ | `aud` contains `OIDC_CLIENT_ID` | A token issued to a different application |
85
+ | `azp` equals the client id, when `aud` holds several values | A token another client of the provider could replay here |
86
+ | `exp` present and in the future, with a small tolerance | An old token, or a token that never expires |
87
+ | `iat` and `sub` present | A token that names no moment of issue or no subject |
88
+ | `nonce` equals the stored nonce | A token minted for another authorization, which replays an earlier one |
89
+
90
+ `jwtVerify` enforces the signature, `algorithms`, `iss` and `aud`, and checks `exp` only when the token carries one, so `requiredClaims` makes a token without `exp`, `iat` or `sub` fail. The `azp` and `nonce` lines are the app's own, so `verify()` compares them whatever the library version does.
91
+
92
+ - **Pin `algorithms` to what the provider lists as `id_token_signing_alg_values_supported`.** `RS256` is the default the specification sets for ID tokens, so it is the default here. A provider that signs with `ES256` or `PS256` takes that value instead, never a list that widens past the provider's own.
93
+ - **Unknown `kid`.** `createRemoteJWKSet` refetches the key set when a token names a key it does not hold, and not more often than its cooldown allows. The provider rotates keys on its own schedule, and the app does nothing about it.
94
+ - **Every failure is one error to the client.** `jwtVerify` throws a distinct error for an expired token, a failed signature and a wrong claim. The resolver catches all of them, logs the class name, and raises one `OidcIdTokenInvalid`, so the response teaches an attacker nothing.
95
+
96
+ ## Why the Share keeps the verifier
97
+
98
+ `/hor-graphql-server-engine` says the Share keeps no instance that needs only `env`, and the verifier looks like one. It stays in the Share because it holds state that has to outlive a request: the key cache. A verifier created per request fetches the key set from the provider on every sign-in, which is slow and can trip the provider's rate limit. The configuration object is kept for the same reason, since it is a fetched document.
@@ -0,0 +1,134 @@
1
+ # Resolvers
2
+
3
+ Two mutations, both public ([environment](./environment.md)), both thin. Write them with `/hor-mutation-resolver` and declare them with `/hor-graphql-schema`; this reference is only the OIDC wiring. The session half reuses `SessionClerk` and the refresh-token cookie clerk from `/hor-cookie-authentication` through the same getter seams.
4
+
5
+ The authorization row goes through a small `OidcAuthorizationClerk` shaped like `SessionClerk`: each write self-resolves a transaction and returns a result object, so a failed save is `result.hasError()` and never a throw.
6
+
7
+ ```graphql
8
+ type Mutation {
9
+ startOidcSignIn: StartOidcSignInResult!
10
+ signInWithOidc(input: SignInWithOidcInput!): SignInWithOidcResult!
11
+ }
12
+ ```
13
+
14
+ ## startOidcSignIn
15
+
16
+ Create the authorization, set the state cookie **after** the row commits, and return the URL the browser navigates to.
17
+
18
+ ```js
19
+ const result = await this.createOidcAuthorizationClerk()
20
+ .saveAuthorization({
21
+ now: context.now,
22
+ })
23
+
24
+ if (result.hasError()) {
25
+ throw new Error(result.extractErrorMessage())
26
+ }
27
+
28
+ const { authorizationEntity } = result
29
+
30
+ this.createStateCookieClerk({ context })
31
+ .saveStateCookie({ state: authorizationEntity.state })
32
+
33
+ return {
34
+ authorizationUrl: this.createAuthorizationUrlBuilder({ context })
35
+ .build({ authorizationEntity }),
36
+ }
37
+ ```
38
+
39
+ The URL is the provider's `authorization_endpoint` plus these query parameters, built with `URLSearchParams` so every value is encoded:
40
+
41
+ | Parameter | Value |
42
+ | --- | --- |
43
+ | `response_type` | `code` |
44
+ | `client_id` | `OIDC_CLIENT_ID` |
45
+ | `redirect_uri` | `OIDC_REDIRECT_URI` |
46
+ | `scope` | `OIDC_SCOPE`, starting with `openid` |
47
+ | `state` | the row's `state` |
48
+ | `nonce` | the row's `nonce` |
49
+ | `code_challenge` | base64url of the SHA-256 digest of the row's `codeVerifier` |
50
+ | `code_challenge_method` | `S256` |
51
+
52
+ The mutation takes no argument from the client, so it has nothing to validate and nothing a caller can steer.
53
+
54
+ ## signInWithOidc
55
+
56
+ The order of the checks matters: a cheap rejection comes before the network call, and the ID token is verified before any claim is read.
57
+
58
+ ```js
59
+ const stateCookieClerk = this.createStateCookieClerk({ context })
60
+
61
+ if (stateCookieClerk.extractState() !== input.state) {
62
+ stateCookieClerk.clearStateCookie()
63
+
64
+ throw this.errorHash.OidcAuthorizationUnusable.create()
65
+ }
66
+
67
+ const spendResult = await this.createOidcAuthorizationClerk()
68
+ .spendAuthorization({ state: input.state, now: context.now })
69
+
70
+ if (spendResult.hasError()) {
71
+ throw new Error(spendResult.extractErrorMessage())
72
+ }
73
+
74
+ if (spendResult.isUnspent()) {
75
+ stateCookieClerk.clearStateCookie()
76
+
77
+ throw this.errorHash.OidcAuthorizationUnusable.create()
78
+ }
79
+
80
+ const claimHash = await this.verifyIdToken({
81
+ context,
82
+ code: input.code,
83
+ authorizationEntity: spendResult.authorizationEntity,
84
+ })
85
+
86
+ const actorEntity = await this.findOrLinkActor({ claimHash, now: context.now })
87
+
88
+ const sessionResult = await this.createSessionClerk()
89
+ .saveSession({
90
+ userId: actorEntity.id,
91
+ now: context.now,
92
+ })
93
+
94
+ if (sessionResult.hasError()) {
95
+ throw new Error(sessionResult.extractErrorMessage())
96
+ }
97
+
98
+ stateCookieClerk.clearStateCookie()
99
+
100
+ this.createCookieClerk({ context })
101
+ .saveRefreshTokenCookie({ refreshToken: sessionResult.credentialPair.refreshToken })
102
+
103
+ return {
104
+ accessToken: sessionResult.credentialPair.accessTokenEntity.accessToken,
105
+ }
106
+ ```
107
+
108
+ - **`isUnspent()` names the purpose.** The result reads true when the guarded update touched no row, so the caller never negates a predicate.
109
+ - **The row is spent before the exchange.** An authorization code works once at the provider, and a row that stays spendable after a failed exchange would let the same state be tried again. A failed callback means the person starts over.
110
+ - **`verifyIdToken()`** exchanges the code at the provider's `token_endpoint`, then hands the returned `id_token` to `context.share.oidcIdTokenVerifier.verify({ idToken, nonce })`. The exchange is a form-encoded `POST` (`application/x-www-form-urlencoded`) carrying `grant_type=authorization_code`, `code`, `redirect_uri`, `client_id`, `client_secret` and the row's `code_verifier`. It goes through an external API client (`/hor-external-api-client`), so the provider's key names stay in its Payload and Capsule. Any verifier error becomes `OidcIdTokenInvalid`.
111
+ - **`findOrLinkActor()`** looks up the identity by `(issuer, subject)`, and on a miss takes the first-link path the actor allows ([storage](./storage.md)). The write and the actor lookup for a first link share one transaction.
112
+ - **The cookies change after the writes commit**, as in `signIn`: a refresh cookie for a rolled-back session would leave the client holding a token no row backs.
113
+
114
+ ## Error codes
115
+
116
+ Three codes, spread over `super.errorCodeHash` in the resolver as the cookie skill does. The numbers are examples: take the next free ones in the app's hash.
117
+
118
+ ```js
119
+ static get errorCodeHash () {
120
+ return {
121
+ ...super.errorCodeHash,
122
+
123
+ OidcAuthorizationUnusable: '205.M004.001',
124
+ OidcIdTokenInvalid: '205.M004.002',
125
+ OidcAccountNotLinked: '205.M004.003',
126
+ }
127
+ }
128
+ ```
129
+
130
+ - **`OidcAuthorizationUnusable`** covers a state that disagrees with the cookie, a row that does not exist, a row already spent and a row that expired. One code, so the response never says which.
131
+ - **`OidcIdTokenInvalid`** covers a failed exchange and every verification failure, for the same reason. Log the underlying class name on the server.
132
+ - **`OidcAccountNotLinked`** is the one the frontend can act on: the provider vouched for the person, and the app has no actor for them. It shows a message, not a retry.
133
+
134
+ `Unauthenticated` stays reserved for the header filter and `renewAccessToken`.
@@ -0,0 +1,118 @@
1
+ # Authorization & identity storage
2
+
3
+ Two tables hold what an OIDC sign-in adds to the cluster `/hor-cookie-authentication` builds. For an actor `<Actor>`:
4
+
5
+ - `<Actor>OidcAuthorization` (`<actor>_oidc_authorizations`) is one pending sign-in: the values the callback needs and the browser never holds.
6
+ - `<Actor>OidcIdentity` (`<actor>_oidc_identities`) is the permanent link from a provider's account to the actor.
7
+
8
+ Each is a normal renchan model (`/hor-sequelize-model`) with a create-table migration (`/hor-sequelize-migration`). This reference is only the OIDC-specific shape. Neither table takes the backup mixin: an authorization is deleted after use, and an identity is added or removed, never rewritten.
9
+
10
+ ## The authorization row
11
+
12
+ ```js
13
+ // <Actor>OidcAuthorization.createAttributes
14
+ state: {
15
+ type: DataTypes.STRING(191),
16
+ allowNull: false,
17
+ unique: true,
18
+ },
19
+ nonce: {
20
+ type: DataTypes.STRING(191),
21
+ allowNull: false,
22
+ },
23
+ codeVerifier: {
24
+ type: DataTypes.STRING(191),
25
+ allowNull: false,
26
+ },
27
+ usedAt: {
28
+ type: DataTypes.DATE,
29
+ allowNull: true,
30
+ },
31
+ generatedAt: {
32
+ type: DataTypes.DATE,
33
+ allowNull: false,
34
+ },
35
+ expiredAt: {
36
+ type: DataTypes.DATE,
37
+ allowNull: false,
38
+ },
39
+ ```
40
+
41
+ - `state` is the lookup key, so it carries the unique index. All three random values come from `crypto.randomBytes(32)` encoded as base64url, which is 43 characters.
42
+ - `codeVerifier` is a secret that is useless without the matching code and expires with the row. Store it as it is, and prune spent and expired rows on a schedule (`/hor-renchan-job-bullmq`).
43
+ - The row takes no `redirect_uri` column: the redirect URI is configuration, the same for every authorization.
44
+
45
+ State reads live on the model, as they do on the refresh token, so a resolver never re-implements the rules:
46
+
47
+ ```js
48
+ isAvailable ({ pointsAt }) {
49
+ return this.get('usedAt') === null
50
+ && this.isUnexpired({ pointsAt })
51
+ }
52
+ ```
53
+
54
+ `isUnexpired()` reads true while `expiredAt` is still ahead of `pointsAt`, so the caller never negates a predicate.
55
+
56
+ Spending the row is one update guarded on `usedAt: null` and on `expiredAt` still ahead. Zero rows updated means the row is missing, spent or expired, and the callback fails as an unusable authorization:
57
+
58
+ ```js
59
+ static async spend ({
60
+ state,
61
+ now,
62
+ transaction,
63
+ }) {
64
+ const [spentCount] = await this.update({
65
+ usedAt: now,
66
+ }, {
67
+ where: {
68
+ state,
69
+ usedAt: null,
70
+ expiredAt: {
71
+ [Op.gt]: now,
72
+ },
73
+ },
74
+ transaction,
75
+ })
76
+
77
+ return spentCount === 1
78
+ }
79
+ ```
80
+
81
+ ## The identity row
82
+
83
+ ```js
84
+ // <Actor>OidcIdentity.createAttributes
85
+ <Actor>Id: {
86
+ type: DataTypes.BIGINT,
87
+ allowNull: false,
88
+ },
89
+ issuer: {
90
+ type: DataTypes.STRING(191),
91
+ allowNull: false,
92
+ },
93
+ subject: {
94
+ type: DataTypes.STRING(255),
95
+ allowNull: false,
96
+ },
97
+ email: {
98
+ type: DataTypes.STRING(191),
99
+ allowNull: true,
100
+ },
101
+ linkedAt: {
102
+ type: DataTypes.DATE,
103
+ allowNull: false,
104
+ },
105
+ ```
106
+
107
+ - **A unique index on (`issuer`, `subject`)** makes the pair the lookup key and makes a second link for one provider account impossible. Index `<actor>_id` as well. As elsewhere, the foreign key is a plain `BIGINT` with no DB-level `references`.
108
+ - `subject` takes 255 characters because that is the ceiling the OpenID Connect specification sets for `sub`. The issuer and subject columns stay under the key length your database allows for the composite index.
109
+ - `email` is what the provider reported at link time, kept for display and for the first-link match. It is never a lookup key afterwards.
110
+
111
+ ## First link
112
+
113
+ A sign-in whose `(issuer, subject)` has no identity row takes one of two paths, and the app picks one per actor:
114
+
115
+ - **Provision.** Create the actor and its identity in one transaction. This is "sign up with the provider", and the profile fields come from the token's claims.
116
+ - **Match a pre-registered actor.** Find the actor by the token's `email`, and only when `email_verified` is `true`. Write the identity row in the same transaction. Every later sign-in finds the identity and never reads the email again.
117
+
118
+ A token with no matching identity and no permitted path raises `OidcAccountNotLinked`. The cookie skill's `signUp` has no role here: the provider is the only place an account is created.
@@ -220,6 +220,8 @@ entities to the schema's field names — never returns raw model instances.
220
220
 
221
221
  - Rename model columns to schema fields (`user.id` → `userId`), map arrays to their output shape, and
222
222
  **echo pagination** (`limit` / `offset` / `sort` / `totalRecords`) for lists.
223
+ - On PostgreSQL, `BIGINT` ids arrive as strings, so wrap each one in `Number()` before it fills an
224
+ SDL `Int` field (a nullable one is branched first, because `Number(null)` is `0`).
223
225
  - Read deep association values with `FieldPathValueExtractor`; guard optional relations and default
224
226
  missing scalars (`?? ''` / `?? null`) rather than leaking `undefined`
225
227
  ([data-access.md](./references/data-access.md)).
@@ -62,10 +62,10 @@ export default class UsersQueryResolver extends BaseQueryResolver {
62
62
  * @override
63
63
  * @param {{
64
64
  * variables: {
65
- * input: server.graphql.admin.UsersInput
65
+ * input: graphql.admin.UsersInput
66
66
  * }
67
67
  * }} params
68
- * @returns {Promise<server.graphql.admin.UsersResult>}
68
+ * @returns {Promise<graphql.admin.UsersResult>}
69
69
  */
70
70
  async resolve ({
71
71
  variables: {
@@ -111,7 +111,7 @@ export default class UsersQueryResolver extends BaseQueryResolver {
111
111
  * Validate the input of the users query.
112
112
  *
113
113
  * @param {{
114
- * input: server.graphql.admin.UsersInput
114
+ * input: graphql.admin.UsersInput
115
115
  * }} params
116
116
  * @returns {InstanceType<RenchanGraphqlErrorCtor> | null}
117
117
  */
@@ -129,7 +129,7 @@ export default class UsersQueryResolver extends BaseQueryResolver {
129
129
  * Create a UsersInputValidator instance.
130
130
  *
131
131
  * @param {{
132
- * input: server.graphql.admin.UsersInput
132
+ * input: graphql.admin.UsersInput
133
133
  * errorHash?: ErrorHash
134
134
  * }} params
135
135
  * @returns {UsersInputValidator}
@@ -241,7 +241,7 @@ export default class UsersQueryResolver extends BaseQueryResolver {
241
241
  * pagination: graphql.NormalPaginationInput
242
242
  * totalRecords: number
243
243
  * }} params
244
- * @returns {server.graphql.admin.UsersResult}
244
+ * @returns {graphql.admin.UsersResult}
245
245
  */
246
246
  formatResponse ({
247
247
  users,
@@ -354,12 +354,12 @@ export default class DepartmentsQueryResolver extends BaseQueryResolver {
354
354
 
355
355
  ## The trailing typedef block
356
356
 
357
- Types tied to the DB and the GraphQL schema live in `/types` (`model.*`, `server.graphql.*`); the
357
+ Types tied to the DB and the GraphQL schema live in `/types` (`model.*`, `graphql.*`); the
358
358
  resolver file only **aliases** them and declares its own local shapes. Keep the block at the bottom,
359
359
  after the class. A resolver with associations typically declares:
360
360
 
361
361
  - `ErrorCodeHash` — the keys of `errorCodeHash` (values `string`).
362
- - `Input` / `Result` aliases — `@typedef {server.graphql.<endpoint>.XxxInput} XxxInput`.
362
+ - `Input` / `Result` aliases — `@typedef {graphql.<endpoint>.XxxInput} XxxInput`.
363
363
  - `ErrorHash` — `Record<string, RenchanGraphqlErrorCtor>`.
364
364
  - `RenchanGraphqlErrorCtor` — `typeof import('@openreachtech/renchan').RenchanGraphqlError`.
365
365
  - An **associated-entity** typedef describing the `include` tree, when a finder returns a record with
@@ -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
@@ -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.