@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.
- package/dist/skills/hor-backend-testing/SKILL.md +4 -3
- package/dist/skills/hor-backend-testing/references/running-tests.md +9 -1
- package/dist/skills/hor-build-e2e-test-environment/SKILL.md +24 -9
- package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +11 -7
- package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +1 -1
- package/dist/skills/hor-cookie-authentication/SKILL.md +4 -2
- package/dist/skills/hor-cookie-authentication/references/environment.md +4 -2
- package/dist/skills/hor-database-design/references/column-types.md +25 -9
- package/dist/skills/hor-database-design/references/datetimes.md +7 -3
- package/dist/skills/hor-graphql-schema/SKILL.md +10 -8
- package/dist/skills/hor-graphql-server-engine/SKILL.md +376 -44
- package/dist/skills/hor-light-rag/SKILL.md +6 -1
- package/dist/skills/hor-light-rag/references/retrieval-internals.md +3 -1
- package/dist/skills/hor-multi-llm-provider/SKILL.md +158 -20
- package/dist/skills/hor-multi-llm-provider/references/access-routes.md +230 -0
- package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +9 -3
- package/dist/skills/hor-mutation-resolver/SKILL.md +13 -9
- package/dist/skills/hor-mutation-resolver/references/errors.md +15 -18
- package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +10 -6
- package/dist/skills/hor-oidc-sign-in/SKILL.md +61 -0
- package/dist/skills/hor-oidc-sign-in/references/environment.md +94 -0
- package/dist/skills/hor-oidc-sign-in/references/id-token-verification.md +98 -0
- package/dist/skills/hor-oidc-sign-in/references/resolvers.md +134 -0
- package/dist/skills/hor-oidc-sign-in/references/storage.md +118 -0
- package/dist/skills/hor-query-resolver/SKILL.md +6 -5
- package/dist/skills/hor-query-resolver/references/anatomy.md +7 -7
- package/dist/skills/hor-query-resolver/references/data-access.md +17 -0
- package/dist/skills/hor-query-resolver/references/errors-and-context.md +12 -16
- package/dist/skills/hor-renchan-job-bullmq/SKILL.md +15 -6
- package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +4 -2
- package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +39 -5
- package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +57 -0
- package/dist/skills/hor-resolver-validator/SKILL.md +5 -6
- package/dist/skills/hor-resolver-validator/references/validator-pattern.md +5 -5
- package/dist/skills/hor-restfulapi-architecture/SKILL.md +33 -7
- package/dist/skills/hor-restfulapi-architecture/references/behind-iap.md +116 -0
- package/dist/skills/hor-restfulapi-architecture/references/credential-routes.md +173 -0
- package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +11 -5
- package/dist/skills/hor-restfulapi-architecture/references/renderers.md +4 -0
- package/dist/skills/hor-security-audit/SKILL.md +2 -2
- package/dist/skills/hor-security-audit/references/secrets.md +62 -36
- package/dist/skills/hor-sequelize-migration/SKILL.md +30 -15
- package/dist/skills/hor-sequelize-migration/references/alter-table.md +26 -13
- package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +5 -2
- package/dist/skills/hor-sequelize-migration/references/indexes.md +41 -2
- package/dist/skills/hor-sequelize-migration/references/notation.md +1 -1
- package/dist/skills/hor-sequelize-model/references/associations.md +2 -1
- package/dist/skills/hor-sequelize-model/references/notation.md +1 -1
- package/dist/skills/hor-sequelize-seeder/SKILL.md +9 -4
- package/dist/skills/hor-sequelize-seeder/references/notation.md +59 -0
- package/dist/skills/hor-type-interface/SKILL.md +48 -32
- package/docs/skills.ja.md +5 -4
- package/docs/skills.md +5 -4
- package/package.json +4 -1
|
@@ -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
|
|
136
|
-
builds the visa from the engine's
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
|
|
@@ -76,8 +76,8 @@ type). **LOW** = hardening gap. **INFO** = worth noting, not a vulnerability.
|
|
|
76
76
|
| 9 | Introspection / playground / debug endpoints disabled in prod | [auth-and-transport.md](./references/auth-and-transport.md) |
|
|
77
77
|
| 10 | CORS scoped (not wildcard in production) | [auth-and-transport.md](./references/auth-and-transport.md) |
|
|
78
78
|
| 11 | Rate limiting on public endpoints (and not bypassable) | [auth-and-transport.md](./references/auth-and-transport.md) |
|
|
79
|
-
| 12 |
|
|
80
|
-
| 13 |
|
|
79
|
+
| 12 | Production-facing env files covered by `.gitignore` | [secrets.md](./references/secrets.md) |
|
|
80
|
+
| 13 | Committed env files hold only values that reach the local machine | [secrets.md](./references/secrets.md) |
|
|
81
81
|
| 14 | No hardcoded secrets in code / config | [secrets.md](./references/secrets.md) |
|
|
82
82
|
| 15 | No plaintext passwords / secrets in seed / fixture data | [secrets.md](./references/secrets.md) |
|
|
83
83
|
| 16 | No vulnerable dependencies (advisory audit) | [dependencies.md](./references/dependencies.md) |
|
|
@@ -4,50 +4,65 @@
|
|
|
4
4
|
plaintext passwords in seed / fixture data. Referenced from [SKILL.md](../SKILL.md). **Mask every
|
|
5
5
|
secret value in the report.**
|
|
6
6
|
|
|
7
|
-
## 12.
|
|
7
|
+
## 12. Production-facing env files covered by `.gitignore`
|
|
8
|
+
|
|
9
|
+
Env files fall on two sides of one line, and the check differs by side.
|
|
10
|
+
|
|
11
|
+
| Side | Files | May be tracked |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| **production-facing** | `.env`, `.env.production`, `.env.prod`, `.env.staging` | never. `.env.staging` is shared with a client at times, so it is held as production |
|
|
14
|
+
| **local** | every other per-environment file — `.env.development`, `.env.live`, `.env.live-local`, `.env.test` and their like | yes, holding only values that reach the local machine (check 13) |
|
|
8
15
|
|
|
9
16
|
A `.gitignore` with a bare `.env` line matches **only** a file named exactly `.env` — it does **not**
|
|
10
|
-
match `.env.
|
|
11
|
-
|
|
17
|
+
match `.env.production`, `.env.staging` or `.env.prod`. Those stay trackable and are easily committed
|
|
18
|
+
with real secrets.
|
|
12
19
|
|
|
13
20
|
```bash
|
|
14
21
|
ls -a | grep -E '^\.env' # which env files exist on disk
|
|
15
22
|
git check-ignore -v .env .env.* 2>/dev/null # prints the matching rule for each IGNORED file
|
|
16
|
-
git ls-files | grep -E '(^|/)\.env' # env files TRACKED in git
|
|
23
|
+
git ls-files | grep -E '(^|/)\.env' # env files TRACKED in git — sort each onto its side
|
|
17
24
|
```
|
|
18
25
|
|
|
19
26
|
- **Important:** adding a pattern to `.gitignore` does **not** untrack a file that is already
|
|
20
|
-
committed — `.gitignore` only affects untracked files. If
|
|
21
|
-
removed from the index with `git rm --cached <file>` (and the secret rotated).
|
|
22
|
-
`git ls-files`, not just by reading `.gitignore`.
|
|
23
|
-
- **FINDING (HIGH if the tracked file holds real secrets, else MEDIUM):**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
27
|
+
committed — `.gitignore` only affects untracked files. If a production-facing env file is already
|
|
28
|
+
tracked, it must be removed from the index with `git rm --cached <file>` (and the secret rotated).
|
|
29
|
+
Verify with `git ls-files`, not just by reading `.gitignore`.
|
|
30
|
+
- **FINDING (HIGH if the tracked file holds real secrets, else MEDIUM):** a production-facing env file
|
|
31
|
+
is **tracked** or **not ignored**. Recommend ignoring each by name, `git rm --cached` for anything
|
|
32
|
+
already tracked, and — if a secret was ever committed — rotating it and purging history.
|
|
33
|
+
- **A local env file that is tracked is not a finding here.** Tracking it is allowed; what it holds
|
|
34
|
+
is judged in check 13.
|
|
35
|
+
- **PASS:** every production-facing env file is ignored and untracked.
|
|
36
|
+
|
|
37
|
+
## 13. Committed env files hold only values that reach the local machine
|
|
38
|
+
|
|
39
|
+
A tracked local env file (check 12) is allowed on a condition, so **every one is read, every time** —
|
|
40
|
+
this check is never skipped, and never answered from the file's name. Read each file, and report
|
|
41
|
+
values **masked**: whether a value is local is judged on its shape, and the report never echoes it.
|
|
42
|
+
|
|
43
|
+
| Allowed in a local env file | A finding wherever it sits |
|
|
44
|
+
|---|---|
|
|
45
|
+
| an endpoint on `127.0.0.1` or `localhost` — `http://localhost:3000` included | an external host |
|
|
46
|
+
| a placeholder credential — `user` / `password` and their like | a real staging or production endpoint |
|
|
47
|
+
| the connection of a CI or test database (`live`) | a key-shaped value — an API key, a token, a private key |
|
|
34
48
|
|
|
35
49
|
```bash
|
|
36
|
-
# For each TRACKED env file (from check 12), list
|
|
50
|
+
# For each TRACKED local env file (from check 12), list every key, whether it holds a value MASKED:
|
|
37
51
|
git ls-files | grep -E '(^|/)\.env' | while read f; do echo "== $f =="; \
|
|
38
|
-
|
|
39
|
-
#
|
|
40
|
-
#
|
|
52
|
+
sed -E 's/=.+$/=****(masked)/' "$f"; done
|
|
53
|
+
# Hosts are the one value read in full, since locality is the point: any that is not local is a
|
|
54
|
+
# finding. Credentials inside a URL are masked first:
|
|
55
|
+
git ls-files | grep -E '(^|/)\.env' | xargs grep -nE '(HOST|URL|ENDPOINT|DSN)[A-Z_]*=' \
|
|
56
|
+
| sed -E 's#://[^@/]*@#://****@#' \
|
|
57
|
+
| grep -vE '=([a-z+]+://)?(\*\*\*\*@)?(127\.0\.0\.1|localhost)([:/]|$)'
|
|
41
58
|
```
|
|
42
59
|
|
|
43
|
-
- **
|
|
44
|
-
|
|
45
|
-
- **
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
- **PASS:** values are empty / obvious placeholders (`your-key-here`, `changeme`, `xxxx`), and a
|
|
50
|
-
secret-free template exists.
|
|
60
|
+
- **An auditor told not to read env files reports this check as BLOCKED, never as passed.** The
|
|
61
|
+
allowance in check 12 rests on this reading; without it, nothing says the file stayed local.
|
|
62
|
+
- **FINDING (HIGH):** a tracked local env file holds a value outside the allowed column — an external
|
|
63
|
+
host, a real staging or production endpoint, a key-shaped value. Recommend moving the value to a
|
|
64
|
+
production-facing file or a secret manager, and rotating it if it was real.
|
|
65
|
+
- **PASS:** every tracked local env file holds only allowed values.
|
|
51
66
|
|
|
52
67
|
## 14. No hardcoded secrets in code / config
|
|
53
68
|
|
|
@@ -62,12 +77,23 @@ git grep -nE "AIza[0-9A-Za-z_-]{20,}|sk-[A-Za-z0-9]{20,}|ghp_[A-Za-z0-9]{20,}|AK
|
|
|
62
77
|
```
|
|
63
78
|
|
|
64
79
|
- **Pay special attention to connection / datastore config files** — per-environment blocks commonly
|
|
65
|
-
carry hardcoded `username` / `password`.
|
|
66
|
-
finding
|
|
67
|
-
|
|
68
|
-
- **
|
|
69
|
-
|
|
70
|
-
|
|
80
|
+
carry hardcoded `username` / `password`. **A production or staging block takes its credentials from
|
|
81
|
+
the environment**, and a literal there is a finding even if it looks like a placeholder, because
|
|
82
|
+
it normalizes the pattern where it does harm.
|
|
83
|
+
- **The same line as check 13 holds outside env files.** A placeholder credential is not a finding
|
|
84
|
+
where only the local machine is reached by it:
|
|
85
|
+
|
|
86
|
+
| Not a finding | Why |
|
|
87
|
+
|---|---|
|
|
88
|
+
| the compose of local middleware whose ports are published on `127.0.0.1` only | nothing off the machine reaches it |
|
|
89
|
+
| the config of a CI or test database | it holds test data, and is rebuilt from nothing |
|
|
90
|
+
|
|
91
|
+
A port published on every interface (`3306:3306`, `0.0.0.0:…`) takes the compose out of the first
|
|
92
|
+
row, and its credentials are a finding again.
|
|
93
|
+
- **FINDING (HIGH real / MEDIUM placeholder):** a literal credential in tracked code / config, outside
|
|
94
|
+
the two rows above. Recommend sourcing from env / a secret manager; rotate if real.
|
|
95
|
+
- **PASS:** credentials come from `process.env` / a config facade, or are placeholders where only the
|
|
96
|
+
local machine reaches them.
|
|
71
97
|
|
|
72
98
|
## 15. No plaintext passwords / secrets in seed / fixture data
|
|
73
99
|
|
|
@@ -15,9 +15,11 @@ A skill for writing the `sequelize/migrations/*.cjs` files. It defines the **phy
|
|
|
15
15
|
when you add a column in the migration, add the matching attribute in the model (and vice versa).
|
|
16
16
|
The conventions are split across the detail files below.
|
|
17
17
|
|
|
18
|
-
This repo does **not** `sync`. The schema is **built entirely by migrations
|
|
19
|
-
staging = MySQL / live = MariaDB
|
|
20
|
-
|
|
18
|
+
This repo does **not** `sync`. The schema is **built entirely by migrations**. The databases these
|
|
19
|
+
skills assume are dev = SQLite / staging = MySQL / live = MariaDB, and the dialects differ; a
|
|
20
|
+
PostgreSQL project substitutes its own databases, and each rule below names PostgreSQL where it
|
|
21
|
+
differs. A model's `unique: true` and the like are only declarations; **the real object is always
|
|
22
|
+
created by the migration**.
|
|
21
23
|
|
|
22
24
|
## Grand principle: a migration is a filled-in template
|
|
23
25
|
|
|
@@ -132,8 +134,8 @@ module.exports = {
|
|
|
132
134
|
- **Each column** is declared with a camelCase key + `field: COLUMN_NAME.X` (the snake physical
|
|
133
135
|
name). **Always** declare `allowNull`, and add `defaultValue` when the column has a default. The
|
|
134
136
|
type is `Sequelize.X` (`BIGINT` / `INTEGER` / `STRING(n)` / `TEXT` (long items: `TEXT('medium')`) /
|
|
135
|
-
`DATE(3)` / `BOOLEAN` / `JSON` / `DECIMAL(p,s)` / `BLOB('long')`). Avoid
|
|
136
|
-
constant + `STRING(n)`.
|
|
137
|
+
`DATE(3)` / `BOOLEAN` / `JSON` (`JSONB` on PostgreSQL) / `DECIMAL(p,s)` / `BLOB('long')`). Avoid
|
|
138
|
+
`ENUM`; use a domain constant + `STRING(n)`.
|
|
137
139
|
Datetimes default to `DATE(3)`. Keep `allowNull` / `defaultValue` in sync with the same-named
|
|
138
140
|
column on the model side.
|
|
139
141
|
|
|
@@ -210,7 +212,8 @@ migrations).
|
|
|
210
212
|
|
|
211
213
|
- **Why**: dev = SQLite / staging = MySQL / live = MariaDB differ, and there is no `sync`. A DB FK
|
|
212
214
|
constraint pins insert order and makes cloning into backup (`*_bk`) tables and handling circular
|
|
213
|
-
references awkward.
|
|
215
|
+
references awkward. Those costs come from the constraint, not from a dialect, so the rule holds on
|
|
216
|
+
PostgreSQL unchanged. Referential integrity is enforced in the **app layer** (associations,
|
|
214
217
|
transactions, existence checks). See [foreign-keys.md](./references/foreign-keys.md); for the
|
|
215
218
|
column notation see [notation.md](./references/notation.md).
|
|
216
219
|
|
|
@@ -246,9 +249,10 @@ await Promise.all([
|
|
|
246
249
|
|
|
247
250
|
### Shortening a long index name (over ~50 chars)
|
|
248
251
|
|
|
249
|
-
The
|
|
250
|
-
|
|
251
|
-
|
|
252
|
+
The identifier limit is 64 characters on MariaDB and MySQL and 63 bytes on PostgreSQL (SQLite sets
|
|
253
|
+
none). As a safety margin, shorten once a name would run past **~50 characters**; the names are
|
|
254
|
+
ASCII snake_case, so a byte is a character. Shorten in the **following priority order**, taking the
|
|
255
|
+
**initial of each word**:
|
|
252
256
|
|
|
253
257
|
1. **First shorten the column name(s)** (`SHORT_COLUMN_NAME`), keeping the table name in full.
|
|
254
258
|
e.g. `content_generations` + `cgji` (= content_generation_job_id) + `unique`
|
|
@@ -257,6 +261,12 @@ word**:
|
|
|
257
261
|
e.g. `cgrf` (= content_generation_requirement_files) + `cgji` + `index`
|
|
258
262
|
→ `cgrf_cgji_index`
|
|
259
263
|
|
|
264
|
+
Index names are unique per table on MariaDB and MySQL, but per schema on PostgreSQL and per
|
|
265
|
+
database on SQLite, so the same name on two tables is an error there. PostgreSQL also truncates a
|
|
266
|
+
name past 63 bytes instead of rejecting it, so two long names that differ only at the end collide.
|
|
267
|
+
Keep the `<table>_` part (or a `SHORT_TABLE_NAME` unique across the schema). See
|
|
268
|
+
[indexes.md](./references/indexes.md).
|
|
269
|
+
|
|
260
270
|
Initialism examples: `content_generation_job_id`→`cgji`, `chat_room_id`→`cri`,
|
|
261
271
|
`customer_id`→`ci`, `content_generation_requirement_files`→`cgrf`, `content_plan_rates`→`err`.
|
|
262
272
|
Put the abbreviations in `SHORT_COLUMN_NAME` / `SHORT_TABLE_NAME` constants and reference them from
|
|
@@ -268,9 +278,13 @@ the `addIndex` `name`. Details and a table of real abbreviations are in
|
|
|
268
278
|
Add a column to an existing table with `addColumn`, and drop the same column symmetrically in
|
|
269
279
|
`down`. The filename is `{timestamp}-{seq}-alter_table-<table>-<column>.cjs`.
|
|
270
280
|
|
|
271
|
-
- **
|
|
272
|
-
MariaDB
|
|
273
|
-
(in `up` or `down
|
|
281
|
+
- **On MariaDB, do not use `removeColumn` to drop a column.** Sequelize's `removeColumn` does not
|
|
282
|
+
work on MariaDB, so when MariaDB is the live database run raw SQL `ALTER TABLE ... DROP COLUMN`
|
|
283
|
+
via `queryInterface.sequelize.query` (in `up` or `down`). Quote each identifier with
|
|
284
|
+
`queryInterface.quoteIdentifier()`, which writes backticks on MariaDB, MySQL and SQLite and
|
|
285
|
+
double quotes on PostgreSQL; a hand-written backtick is a syntax error on PostgreSQL.
|
|
286
|
+
- **On PostgreSQL (and SQLite), `queryInterface.removeColumn` works.** A project whose databases
|
|
287
|
+
are only those two drops a column with `removeColumn` and writes no raw SQL.
|
|
274
288
|
- `up` / `down` are **symmetric** (drop in `down` what `up` added). Column adds can be grouped with
|
|
275
289
|
`Promise.all`, but drops are run as one raw statement per column, sequentially.
|
|
276
290
|
- Put a `/* ... */` block at the top of the file describing the **intent** (ticket number, spec
|
|
@@ -305,8 +319,8 @@ module.exports = {
|
|
|
305
319
|
) {
|
|
306
320
|
// removeColumn does not work on MariaDB, so drop via raw SQL DROP COLUMN.
|
|
307
321
|
await queryInterface.sequelize.query(`
|
|
308
|
-
ALTER TABLE
|
|
309
|
-
DROP COLUMN
|
|
322
|
+
ALTER TABLE ${queryInterface.quoteIdentifier(TABLE_NAME)}
|
|
323
|
+
DROP COLUMN ${queryInterface.quoteIdentifier(COLUMN_NAME)}
|
|
310
324
|
`)
|
|
311
325
|
},
|
|
312
326
|
}
|
|
@@ -333,4 +347,5 @@ scripts:
|
|
|
333
347
|
- [indexes.md](./references/indexes.md) — index naming, UNIQUE, `Promise.all`, composite indexes,
|
|
334
348
|
the shortening algorithm for long names with a table of real examples (§4)
|
|
335
349
|
- [alter-table.md](./references/alter-table.md) — `addColumn`, dropping a column with raw
|
|
336
|
-
`DROP COLUMN` (because `removeColumn` fails
|
|
350
|
+
`DROP COLUMN` on MariaDB (because `removeColumn` fails there) and with `removeColumn` on
|
|
351
|
+
PostgreSQL, identifier quoting, symmetric up/down, intent comment (§5)
|
|
@@ -4,15 +4,21 @@ How to write migrations that add or remove columns on an existing table. Referen
|
|
|
4
4
|
`SKILL.md`. The column type / `field` / `allowNull` notation is shared with
|
|
5
5
|
[notation.md](./notation.md).
|
|
6
6
|
|
|
7
|
-
## Add with addColumn, drop with raw SQL DROP COLUMN (symmetric up/down)
|
|
7
|
+
## Add with addColumn, drop with raw SQL DROP COLUMN on MariaDB (symmetric up/down)
|
|
8
8
|
|
|
9
9
|
`addColumn` in `up`, and drop the same column in `down` to keep them symmetric. The filename is
|
|
10
10
|
`{timestamp}-{seq}-alter_table-<table>-<column>.cjs`.
|
|
11
11
|
|
|
12
|
-
**
|
|
13
|
-
on MariaDB
|
|
14
|
-
`ALTER TABLE ... DROP COLUMN` via `queryInterface.sequelize.query`. Quote
|
|
15
|
-
(
|
|
12
|
+
**On MariaDB, do not use `removeColumn` to drop a column.** Sequelize's `removeColumn` does not work
|
|
13
|
+
correctly on MariaDB, so when MariaDB is the live database, drop a column (in `up` or `down`) with
|
|
14
|
+
raw SQL `ALTER TABLE ... DROP COLUMN` via `queryInterface.sequelize.query`. Quote every identifier
|
|
15
|
+
with `queryInterface.quoteIdentifier()`, never with a hand-written backtick (see
|
|
16
|
+
[Quoting identifiers](#quoting-identifiers-in-raw-sql)).
|
|
17
|
+
|
|
18
|
+
**On PostgreSQL (and SQLite), `queryInterface.removeColumn` works.** A project whose databases are
|
|
19
|
+
only those two drops a column with `removeColumn(TABLE_NAME, COLUMN_NAME)` in `up` or `down` and
|
|
20
|
+
writes no raw SQL. The raw form below stays the one to write whenever MariaDB is among the
|
|
21
|
+
databases, because it runs unchanged on all of them.
|
|
16
22
|
|
|
17
23
|
```js
|
|
18
24
|
'use strict'
|
|
@@ -43,8 +49,8 @@ module.exports = {
|
|
|
43
49
|
) {
|
|
44
50
|
// removeColumn does not work on MariaDB, so drop via raw SQL DROP COLUMN.
|
|
45
51
|
await queryInterface.sequelize.query(`
|
|
46
|
-
ALTER TABLE
|
|
47
|
-
DROP COLUMN
|
|
52
|
+
ALTER TABLE ${queryInterface.quoteIdentifier(TABLE_NAME)}
|
|
53
|
+
DROP COLUMN ${queryInterface.quoteIdentifier(COLUMN_NAME)}
|
|
48
54
|
`)
|
|
49
55
|
},
|
|
50
56
|
}
|
|
@@ -57,6 +63,13 @@ module.exports = {
|
|
|
57
63
|
dialect-independent, run `ALTER TABLE ... DROP COLUMN` directly. The add side (`addColumn`) is
|
|
58
64
|
fine, so keep using it.
|
|
59
65
|
|
|
66
|
+
### Quoting identifiers in raw SQL
|
|
67
|
+
|
|
68
|
+
`queryInterface.quoteIdentifier(name)` returns the name quoted the way the connected dialect
|
|
69
|
+
expects: backticks on MariaDB, MySQL and SQLite, double quotes on PostgreSQL. A hand-written
|
|
70
|
+
backtick runs on the first three and is a syntax error on PostgreSQL, so a migration that has a
|
|
71
|
+
backtick in it cannot be moved to PostgreSQL without being rewritten.
|
|
72
|
+
|
|
60
73
|
## Write an intent comment (`/* ... */`) at the top
|
|
61
74
|
|
|
62
75
|
A column-adding migration is really about "why is this column being added", so put a `/* ... */`
|
|
@@ -111,16 +124,16 @@ module.exports = {
|
|
|
111
124
|
) {
|
|
112
125
|
// removeColumn does not work on MariaDB, so drop per column with raw SQL DROP COLUMN.
|
|
113
126
|
await queryInterface.sequelize.query(`
|
|
114
|
-
ALTER TABLE
|
|
115
|
-
DROP COLUMN
|
|
127
|
+
ALTER TABLE ${queryInterface.quoteIdentifier(TABLE_NAME)}
|
|
128
|
+
DROP COLUMN ${queryInterface.quoteIdentifier(COLUMN_NAME.WIZARD_ANSWERS_JSON)}
|
|
116
129
|
`)
|
|
117
130
|
await queryInterface.sequelize.query(`
|
|
118
|
-
ALTER TABLE
|
|
119
|
-
DROP COLUMN
|
|
131
|
+
ALTER TABLE ${queryInterface.quoteIdentifier(TABLE_NAME)}
|
|
132
|
+
DROP COLUMN ${queryInterface.quoteIdentifier(COLUMN_NAME.WIZARD_TEMPLATE_ID)}
|
|
120
133
|
`)
|
|
121
134
|
await queryInterface.sequelize.query(`
|
|
122
|
-
ALTER TABLE
|
|
123
|
-
DROP COLUMN
|
|
135
|
+
ALTER TABLE ${queryInterface.quoteIdentifier(TABLE_NAME)}
|
|
136
|
+
DROP COLUMN ${queryInterface.quoteIdentifier(COLUMN_NAME.WIZARD_TEMPLATE_VERSION)}
|
|
124
137
|
`)
|
|
125
138
|
|
|
126
139
|
return Promise.resolve()
|
|
@@ -42,6 +42,9 @@ CustomerId: {
|
|
|
42
42
|
DB FK constraint (1) pins insert / delete order, (2) makes cloning into backup (`*_bk`) tables
|
|
43
43
|
hard, and (3) cannot express circular references. Referential integrity is enforced in the **app
|
|
44
44
|
layer** (model associations and domain logic).
|
|
45
|
+
- **PostgreSQL gets the same rule.** The three costs belong to the constraint itself, and PostgreSQL
|
|
46
|
+
enforces a constraint as strictly as MariaDB and MySQL do, so a project on PostgreSQL writes no
|
|
47
|
+
`references` either.
|
|
45
48
|
|
|
46
49
|
## Create the FK *column*; express the relation on the model side
|
|
47
50
|
|
|
@@ -88,8 +91,8 @@ ContentGenerationJobId: {
|
|
|
88
91
|
## A set of ids you don't want as FKs → a JSON array
|
|
89
92
|
|
|
90
93
|
When you want to hold a set of ids but not enough to warrant individual FK columns or a join table,
|
|
91
|
-
hold them in a `JSON`-typed array column. Same idea as having no FK
|
|
92
|
-
integrity in the app layer.
|
|
94
|
+
hold them in a `JSON`-typed array column (`JSONB` on PostgreSQL). Same idea as having no FK
|
|
95
|
+
constraint: check referential integrity in the app layer.
|
|
93
96
|
|
|
94
97
|
```js
|
|
95
98
|
// An array of ids without an FK.
|
|
@@ -70,8 +70,10 @@ name: [SHORT_TABLE_NAME, 'job_package', 'unique'].join('_')
|
|
|
70
70
|
|
|
71
71
|
## Shortening a long index name (over ~50 chars)
|
|
72
72
|
|
|
73
|
-
The
|
|
74
|
-
|
|
73
|
+
The identifier limit is 64 characters on MariaDB and MySQL and 63 bytes on PostgreSQL, so write
|
|
74
|
+
for the stricter 63. SQLite sets none. As a **safety margin, shorten once a name would run past
|
|
75
|
+
~50 characters**. Index names are ASCII snake_case, so a byte is a character. Shorten in stages, in
|
|
76
|
+
the **following priority order**.
|
|
75
77
|
|
|
76
78
|
### Priority 1: shorten the column name(s) first (keep the table name in full)
|
|
77
79
|
|
|
@@ -134,12 +136,49 @@ character** of each word.
|
|
|
134
136
|
from the `addIndex` `name` (do not inline). If abbreviations collide within a table, add a second
|
|
135
137
|
letter (etc.) to keep them unique while staying meaningful.
|
|
136
138
|
|
|
139
|
+
### What the database does with a name that is too long or taken
|
|
140
|
+
|
|
141
|
+
| Database | Over-long name | Same name on two tables |
|
|
142
|
+
| --- | --- | --- |
|
|
143
|
+
| MariaDB / MySQL | error past 64 characters | allowed, names are unique per table |
|
|
144
|
+
| PostgreSQL | cut to 63 bytes with a NOTICE, no error | error `relation ... already exists`, names are unique per schema |
|
|
145
|
+
| SQLite | no limit | error, names are unique per database |
|
|
146
|
+
|
|
147
|
+
- **PostgreSQL's silent cut is the trap.** Two names that differ only after byte 63 become the same
|
|
148
|
+
name, and the second `addIndex` fails with `already exists` although both names looked distinct in
|
|
149
|
+
the file. Shortening to ~50 characters keeps that from happening.
|
|
150
|
+
- **The `<table>_` part is what keeps names unique across tables** on PostgreSQL and SQLite. Keep
|
|
151
|
+
it in full (Priority 1 above), and when `SHORT_TABLE_NAME` is needed, check that the abbreviation
|
|
152
|
+
is unique across the whole schema, not only within the file. If abbreviations collide, add a
|
|
153
|
+
second letter.
|
|
154
|
+
|
|
137
155
|
### Shorten only when needed
|
|
138
156
|
|
|
139
157
|
If it fits within ~50 characters, do not shorten. `.join('_')` the full `TABLE_NAME` / `COLUMN_NAME`
|
|
140
158
|
as in `customers_registered_at_index`. **Do not mechanically initialize just because you can** (it
|
|
141
159
|
hurts readability).
|
|
142
160
|
|
|
161
|
+
## A UNIQUE index compares with the column's collation
|
|
162
|
+
|
|
163
|
+
A UNIQUE index rejects what the column's collation calls equal. On MariaDB and MySQL with a `_ci`
|
|
164
|
+
collation, `Taro` and `taro` are duplicates, and the second insert fails. PostgreSQL compares
|
|
165
|
+
case-sensitively by default, so both rows fit and a case-insensitive natural key (an email, a login
|
|
166
|
+
name) is not enforced. On PostgreSQL, normalize the value to lower case before it is saved, or
|
|
167
|
+
index `lower(<column>)`, instead of relying on the collation. `addIndex` may not accept an
|
|
168
|
+
expression, so write the index as raw SQL, guarded for PostgreSQL:
|
|
169
|
+
|
|
170
|
+
```js
|
|
171
|
+
const INDEX_NAME = 'customers_email_lower_unique'
|
|
172
|
+
|
|
173
|
+
if (queryInterface.sequelize.getDialect() === 'postgres') {
|
|
174
|
+
await queryInterface.sequelize.query(
|
|
175
|
+
`CREATE UNIQUE INDEX ${INDEX_NAME} ON ${queryInterface.quoteIdentifier(TABLE_NAME)} (lower(email))`
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`down` runs `DROP INDEX IF EXISTS ${INDEX_NAME}` under the same guard.
|
|
181
|
+
|
|
143
182
|
## A UNIQUE named index is "the real constraint"
|
|
144
183
|
|
|
145
184
|
The uniqueness of a 1:1 relation's FK or a natural key is **actually enforced by this UNIQUE named
|