@starci/hfs 4.11.18 → 4.11.20
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/CHANGELOG.md +12 -0
- package/package.json +1 -1
- package/runtime/knowledge/hfs/canon-pins.yaml +7 -7
- package/runtime/knowledge/hfs/rules.yaml +3 -3
- package/runtime/knowledge/hfs/slots.yaml +11 -6
- package/runtime/scripts/hfs/allows.mjs +25 -4
- package/runtime/scripts/hfs/architecture/identity.mjs +6 -2
- package/runtime/scripts/hfs/architecture/jwt-ast.mjs +1 -1
- package/runtime/scripts/hfs/coverage-scope.mjs +31 -18
- package/runtime/scripts/hfs/manifest-shape.mjs +37 -2
- package/runtime/scripts/hfs/rules/coverage-below.mjs +3 -10
- package/runtime/scripts/hfs/rules/stacks-release.mjs +44 -8
- package/runtime/scripts/hfs/slot-manifest-shape.mjs +2 -1
- package/sync/index.mjs +2 -2
- package/templates/be/skeleton-lite/src/modules/integrations/passport/passport.cookie.spec.ts +57 -0
- package/templates/be/skeleton-lite/src/modules/integrations/passport/passport.password.spec.ts +28 -0
- package/templates/be/skeleton-lite/src/modules/integrations/passport/passport.tokens.spec.ts +74 -18
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.11.20 - 2026-10-30
|
|
4
|
+
|
|
5
|
+
- Added: a slot may declare the files of its own that carry logic: `logic: [file, ...]` (owner ruling slot-declared-logic, contexts/decisions/rulings.yaml), valid only on a tracked be directory slot with `coverage: required` and `tests: unit-beside`, each a `<name>.<part>.ts` the slot requires or allows and not already a logic-role file (`manifest-shape.mjs` `slotLogicProblems`, `declaredLogicOf`). A declared file is measured at 100 per file like a logic role (`coverage-scope.mjs` `files` and `measuredBy`, `rules/coverage-below.mjs`, `sync/index.mjs` renders `files` into be/jest.config.js, Sonar no longer excludes it), and its colocated `.spec.ts` is admitted unlisted (`allows.mjs`). `be.integrations.passport` declares `passport.tokens.ts`, `passport.password.ts` and `passport.cookie.ts`; the lite skeleton ships their specs in the testing-module form (`passport.password.spec.ts` and `passport.cookie.spec.ts` are new), each file at 100. Specs: `src/slot-declared-logic.spec.mjs`; `codecov-scope` and `scaffold-template-canon-be` follow.
|
|
6
|
+
- Fixed: the object-storage slot requires and allows the skeleton's names, `object-storage.{config,options,decorators,client}.ts` (it named `storage.*`, so the scaffold failed HFS_SLOT_REQUIRED_MISSING and a renamed app's module was judged a sub-module), and allows `object-storage.module.ts` and `object-storage.module-definition.ts`.
|
|
7
|
+
- Fixed: `BE_AUTH_JWT_OWN_JWKS` takes an audience of typed configuration as pinned, as R260 already did (`identity.mjs` with `fromConfig` of `jwt-ast.mjs`), so the skeleton's `audience: options.audience` passes; an audience that is neither a literal nor typed configuration is still refused. Spec: `src/be-auth-jwt-own-jwks.spec.mjs`.
|
|
8
|
+
- Changed: the bundled canon pins name jest-preset 2.5.2, eslint-canon-be 3.8.19, eslint-canon-fe 9.5.21 and the Grammar family 0.15.32.
|
|
9
|
+
|
|
10
|
+
## 4.11.19 - 2026-10-30
|
|
11
|
+
|
|
12
|
+
- Fixed: `HFS_SCHEDULE_UNDECLARED` (R268) reads an application SQL template whose `${}` sits where Postgres wants an identifier (`LISTEN ${channel}`, `SET x = ${n}`): the template is read with each `${}` as NULL, and when that does not parse, again with each as an identifier (`stacks-release.mjs` `templateObservations`). Such a statement was taken for an undeclared pg_cron job. A bare interpolated function name (`FROM ${fn}(...)`) still fails closed, since it may be `cron.schedule`; the skeleton's `callDbFunction` quotes `"${schema}"."${name}"` and parses as it is.
|
|
13
|
+
- Fixed: SQL named in a same-file `const` before its `query`/`execute` call is judged as if inline (`sqlConstants`); moving the text out of the call no longer hid it from the scanner. Specs: `src/hfs-stacks-release.spec.mjs`.
|
|
14
|
+
|
|
3
15
|
## 4.11.18 - 2026-10-30
|
|
4
16
|
|
|
5
17
|
- Fixed: `HFS_STACKS_SHAPE` (R10) accepts the sealed member `app secret set` writes, `<env>/secrets/<slug>.enc.yaml` (ruling app-secrets-one-standard, `scripts/lib/sealed-member.mjs`), beside the legacy `<slug>.enc`. The `.starcistacks` slot (`knowledge/hfs/slots.yaml`, both editions) allowed only `<slug>.enc`, so every standard member was refused; the messages and `goesTo` name `.enc.yaml`. Spec: `src/hfs-stacks-shape.spec.mjs` holds one of each.
|
package/package.json
CHANGED
|
@@ -31,35 +31,35 @@ pins:
|
|
|
31
31
|
source: packages/event-stream/package.json
|
|
32
32
|
why: 'the one server-sent-events client of every front end (fe-stack event-stream, owner:event-stream-package): the transport client layer (modules/api/sse/clients) creates one instance for the app with the bearer token source and the stream operations follow on it; it carries Last-Event-ID resume, the capped doubling backoff, the heartbeat timeout, the single 401 renewal and the useSWRSubscription adapter, so no app keeps a hand-written reader.'
|
|
33
33
|
'@starci/grammar':
|
|
34
|
-
version: 0.15.
|
|
34
|
+
version: 0.15.32
|
|
35
35
|
group: starci
|
|
36
36
|
install: registry
|
|
37
37
|
side: fe
|
|
38
38
|
source: packages/grammar/package.json
|
|
39
39
|
why: 'the grammar front ends read: the brand layer sets `--font-sans` and `--font-mono` and the grammar reads them; it carries the Input tel kind, the copyable and read-only Input, the IconButton disclosure props and count badge, ChatBubble, FillViewport, Textarea mentions and Enter-to-send, the leading PrimaryRailLayout rail, the plate-less Image, ListRow, the soft Alert, Progress steps, the floating primary IconButton, FlowGraph, the STATE-8 loading views and the bordered selectable TagGroup chips. The runtime source version wins for a @starci package.'
|
|
40
40
|
'@starci/eslint-canon-be':
|
|
41
|
-
version: 3.8.
|
|
41
|
+
version: 3.8.19
|
|
42
42
|
group: starci
|
|
43
43
|
install: registry
|
|
44
44
|
side: be
|
|
45
45
|
source: packages/eslint-canon-be/package.json
|
|
46
46
|
why: 'the back-end ESLint canon: `loadHfs(import.meta.url)` of be/eslint.config.mjs finds the app-root hfs.json (kind app) and gives every linted file the view of the be side, and the project graph is built per side; its bundled runtime copies (slots, canon-pins, failure codes, the architecture machine) put .starcistacks and .sops.yaml at the app root; `starciBeConfig({ hfs: loadHfs(import.meta.url) })` is the typed factory and the BE-CONVENTION laws are its rules.'
|
|
47
47
|
'@starci/eslint-canon-fe':
|
|
48
|
-
version: 9.5.
|
|
48
|
+
version: 9.5.21
|
|
49
49
|
group: starci
|
|
50
50
|
install: registry
|
|
51
51
|
side: fe
|
|
52
52
|
source: packages/eslint-canon-fe/package.json
|
|
53
53
|
why: 'the front-end ESLint canon: `loadHfs(import.meta.url)` of fe/eslint.config.mjs finds the app-root hfs.json (kind app) and gives every linted file the view of the fe side, and the project graph is built per side; its bundled runtime copies (slots, canon-pins, failure codes, the architecture machine) put .starcistacks and .sops.yaml at the app root; the front end has no tests (FE_NO_TESTS R97 in hfs) and no-vietnamese-in-source (R91) applies.'
|
|
54
54
|
'@starci/eslint-grammar-core':
|
|
55
|
-
version: 0.15.
|
|
55
|
+
version: 0.15.32
|
|
56
56
|
group: starci
|
|
57
57
|
install: registry
|
|
58
58
|
side: fe
|
|
59
59
|
source: packages/eslint-grammar-core/package.json
|
|
60
60
|
why: 'the StarCi Grammar component API lint, versioned with @starci/grammar; front ends compose this family package with the universal FE canon.'
|
|
61
61
|
'@starci/eslint-grammar-offset-pop':
|
|
62
|
-
version: 0.15.
|
|
62
|
+
version: 0.15.32
|
|
63
63
|
group: starci
|
|
64
64
|
install: registry
|
|
65
65
|
side: fe
|
|
@@ -85,7 +85,7 @@ pins:
|
|
|
85
85
|
side: both
|
|
86
86
|
source: packages/prettier-config/package.json
|
|
87
87
|
'@starci/jest-preset':
|
|
88
|
-
version: 2.5.
|
|
88
|
+
version: 2.5.2
|
|
89
89
|
group: starci
|
|
90
90
|
install: registry
|
|
91
91
|
side: be
|
|
@@ -106,7 +106,7 @@ pins:
|
|
|
106
106
|
source: packages/ai-router/package.json
|
|
107
107
|
why: 'the AI pool router of a back end: a NestJS module that routes OpenAI-compatible chat, stream and embeddings calls across keys, models and providers, with @starci/ai-router/testing for its specs; @starci/jest-preset compiles it as an ESM-only dependency.'
|
|
108
108
|
'@starci/hfs':
|
|
109
|
-
version: 4.11.
|
|
109
|
+
version: 4.11.20
|
|
110
110
|
group: starci
|
|
111
111
|
install: registry
|
|
112
112
|
side: both
|
|
@@ -918,7 +918,7 @@ rules:
|
|
|
918
918
|
code: "BE_TEST_TOPOLOGY"
|
|
919
919
|
editions: [lite, full]
|
|
920
920
|
docs: [docs/quality-bar.md#r47-test-topology]
|
|
921
|
-
law: "One jest config, projects `unit`, `integration`, `e2e` and `contract`, live by folder, `diagnostics: false`; unit specs are `<name>.<role>.spec.ts` beside the file they test: required for the roles of `ruleParams.be.unitRoles` (`<name>.service.spec.ts` beside a `<name>.service.ts`, `<name>.cli.spec.ts` beside a cli command `<name>.cli.ts` of `src/features/cli`), optional for any other logic role (`ruleParams.be.logicRoles`) inside a slot whose `coverage` is required, except that the commit adding a measured logic file stages its `<name>.<role>.spec.ts` beside it (owner 2026-10-20, judged by `starci app hygiene` in the pre-commit hook), and nowhere else but beside a webhook or realtime door that has no service of its own (`<provider>.webhook.spec.ts`, `<channel>.gateway.spec.ts`, `<x>.subscription.spec.ts`) (every unit-tested subject has exactly one; any other `*.spec.ts` outside `be/src/tests/{world,integration,e2e,contract}` is a finding, including specs in apps), and the unit project collects coverage from the logic roles of the measured roots only (the scope derived from the slot manifest, R204) with a per-file threshold of 100 on lines, branches, functions and statements (`test` runs `--coverage`; `importHelpers` and `tslib`); `be/src/tests/world/` is the ONLY test infrastructure: `global-setup.ts` starts the app's own stack (`.starcistacks/<env>`, named by `stack` in `test-world.config.ts`, the declaration of the test-world library in its one named form `export const { useTestWorld, useSandbox } = defineTestWorld({...})` (a default export is not read): every service it declares runs REAL, behind toxiproxy, images and versions read from the stack at run time, never spelled in test source) or attaches to a warm one that answers, and runs the migrations once over the cli app's connections (the runner of the cli migrate command); `global-teardown.ts` stops only what its setup started; `use-test-world.ts` exports `useTestWorld({ apps } | { modules })` (`world.apps.<name>.api`, `world.db.<connection>`, `world.infra.<service>` with `latency(ms)`, `cut()` and `restore()` on the real service, `world.fake.<provider>`, `world.waitFor`) and `fakes/<provider>/` holds the network-edge fakes (`failNext`, `replayWebhook`, `delay`, payload fixtures) of external SaaS the team does not operate ONLY: a fake of a service the stack declares is refused, except stateless compute that needs special hardware or an external model (GPU inference, a self-hosted embedding model), whose `stacks` entry in `test-world.config.ts` declares `{ fakedBy: <fake>, reason }` with a non-empty `reason` (a stateful service, or one with a persistent volume, is never accepted); it alone owns containers, DataSource, migrations and `process.env`; nothing under `be/src/tests` overrides a provider or DI token; `be/src/tests/integration/<capability>/*.integration-spec.ts` (`{ modules }`, with the real peer apps its client calls beside them as `apps`; real infrastructure, no HTTP door of ours), `be/src/tests/e2e/<area>/*.e2e-spec.ts` (`{ apps }`) and `be/src/tests/contract/<provider>/*.contract-spec.ts` (provider sandboxes, skipped without sandbox config, run only by `test:contract`, never by `test` or `test:e2e`) agree folder with suffix; an integration or e2e spec passes `useTestWorld` one object literal with plain keys (no variable, spread or computed key) and calls it; the contract layer has no skip either: a contract spec writes `sandbox.describe(...)` from the test-world library's `useSandbox(...)`, and when the sandbox config is absent that describe registers one failing test naming the missing keys (the body never runs), and every `fakes/<provider>/` that serves payload fixtures (`payloads/*.json`) has a `contract/<provider>/*.contract-spec.ts` that references those fixtures and asserts `shapeOf(real)` equals `shapeOf(fixture)` (the helper `shapeOf` is named by `ruleParams.be.contractShape` of the slot manifest; fakes the test-world library provides are guarded by the library); no `.test.ts`, `int-spec` or `harness-spec`, no `live/` and no `be/src/tests/e2e/world`."
|
|
921
|
+
law: "One jest config, projects `unit`, `integration`, `e2e` and `contract`, live by folder, `diagnostics: false`; unit specs are `<name>.<role>.spec.ts` beside the file they test: required for the roles of `ruleParams.be.unitRoles` (`<name>.service.spec.ts` beside a `<name>.service.ts`, `<name>.cli.spec.ts` beside a cli command `<name>.cli.ts` of `src/features/cli`), optional for any other logic role (`ruleParams.be.logicRoles`) inside a slot whose `coverage` is required and beside a logic file such a slot declares (`logic`: `passport.tokens.spec.ts` beside `passport.tokens.ts`), except that the commit adding a measured logic file stages its `<name>.<role>.spec.ts` beside it (owner 2026-10-20, judged by `starci app hygiene` in the pre-commit hook), and nowhere else but beside a webhook or realtime door that has no service of its own (`<provider>.webhook.spec.ts`, `<channel>.gateway.spec.ts`, `<x>.subscription.spec.ts`) (every unit-tested subject has exactly one; any other `*.spec.ts` outside `be/src/tests/{world,integration,e2e,contract}` is a finding, including specs in apps), and the unit project collects coverage from the logic roles of the measured roots and the logic files their slots declare only (the scope derived from the slot manifest, R204) with a per-file threshold of 100 on lines, branches, functions and statements (`test` runs `--coverage`; `importHelpers` and `tslib`); `be/src/tests/world/` is the ONLY test infrastructure: `global-setup.ts` starts the app's own stack (`.starcistacks/<env>`, named by `stack` in `test-world.config.ts`, the declaration of the test-world library in its one named form `export const { useTestWorld, useSandbox } = defineTestWorld({...})` (a default export is not read): every service it declares runs REAL, behind toxiproxy, images and versions read from the stack at run time, never spelled in test source) or attaches to a warm one that answers, and runs the migrations once over the cli app's connections (the runner of the cli migrate command); `global-teardown.ts` stops only what its setup started; `use-test-world.ts` exports `useTestWorld({ apps } | { modules })` (`world.apps.<name>.api`, `world.db.<connection>`, `world.infra.<service>` with `latency(ms)`, `cut()` and `restore()` on the real service, `world.fake.<provider>`, `world.waitFor`) and `fakes/<provider>/` holds the network-edge fakes (`failNext`, `replayWebhook`, `delay`, payload fixtures) of external SaaS the team does not operate ONLY: a fake of a service the stack declares is refused, except stateless compute that needs special hardware or an external model (GPU inference, a self-hosted embedding model), whose `stacks` entry in `test-world.config.ts` declares `{ fakedBy: <fake>, reason }` with a non-empty `reason` (a stateful service, or one with a persistent volume, is never accepted); it alone owns containers, DataSource, migrations and `process.env`; nothing under `be/src/tests` overrides a provider or DI token; `be/src/tests/integration/<capability>/*.integration-spec.ts` (`{ modules }`, with the real peer apps its client calls beside them as `apps`; real infrastructure, no HTTP door of ours), `be/src/tests/e2e/<area>/*.e2e-spec.ts` (`{ apps }`) and `be/src/tests/contract/<provider>/*.contract-spec.ts` (provider sandboxes, skipped without sandbox config, run only by `test:contract`, never by `test` or `test:e2e`) agree folder with suffix; an integration or e2e spec passes `useTestWorld` one object literal with plain keys (no variable, spread or computed key) and calls it; the contract layer has no skip either: a contract spec writes `sandbox.describe(...)` from the test-world library's `useSandbox(...)`, and when the sandbox config is absent that describe registers one failing test naming the missing keys (the body never runs), and every `fakes/<provider>/` that serves payload fixtures (`payloads/*.json`) has a `contract/<provider>/*.contract-spec.ts` that references those fixtures and asserts `shapeOf(real)` equals `shapeOf(fixture)` (the helper `shapeOf` is named by `ruleParams.be.contractShape` of the slot manifest; fakes the test-world library provides are guarded by the library); no `.test.ts`, `int-spec` or `harness-spec`, no `live/` and no `be/src/tests/e2e/world`."
|
|
922
922
|
kinds: [check, codemod, lint]
|
|
923
923
|
gates: [land, ci]
|
|
924
924
|
failureCodes: ["BE_TEST_TOPOLOGY", "BE_CONTRACT_UNGUARDED", "BE_UNIT_SPEC_NOT_STAGED"]
|
|
@@ -3525,7 +3525,7 @@ rules:
|
|
|
3525
3525
|
code: "HFS_COVERAGE_SCOPE_DRIFT"
|
|
3526
3526
|
editions: [lite, full]
|
|
3527
3527
|
docs: [docs/quality-bar.md#r204-coverage-scope]
|
|
3528
|
-
law: "What a back end measures at 100 per file is derived once from the slot manifest (the `coverage: required|none` field of every be slot
|
|
3528
|
+
law: "What a back end measures at 100 per file is derived once from the slot manifest (the `coverage: required|none` field of every be slot, ruleParams.be.logicRoles and the `logic` files a required slot declares, scripts/hfs/coverage-scope.mjs), and the three files that state it are its render: be/jest.config.js (thresholds), the `sonar.coverage.exclusions` line of sonar-project.properties, and codecov.yml (paths and one component per service app plus platform, each at 100). A difference is drift; the scope is never edited by hand."
|
|
3529
3529
|
kinds: [check, codemod]
|
|
3530
3530
|
gates: [land, ci]
|
|
3531
3531
|
failureCodes: ["HFS_COVERAGE_SCOPE_DRIFT"]
|
|
@@ -4642,7 +4642,7 @@ rules:
|
|
|
4642
4642
|
- {path: packages/hfs/src/hfs-boot-proof.spec.mjs, edition: lite}
|
|
4643
4643
|
- id: R273
|
|
4644
4644
|
code: "HFS_COVERAGE_BELOW"
|
|
4645
|
-
law: "An app check supplied with a coverage-from lcov report proves 100 percent lines, functions and branches per tracked back-end logic file in the edition's slot-derived measured scope; a missing source record or unavailable metric is refused. The unit runner also enforces statement coverage. Reports list the measured scope and the source files outside it, including features, cli and webhooks."
|
|
4645
|
+
law: "An app check supplied with a coverage-from lcov report proves 100 percent lines, functions and branches per tracked back-end logic file (a logic-role file or a file its slot declares in `logic`) in the edition's slot-derived measured scope; a missing source record or unavailable metric is refused. The unit runner also enforces statement coverage. Reports list the measured scope and the source files outside it, including features, cli and webhooks."
|
|
4646
4646
|
kinds: [check]
|
|
4647
4647
|
gates: [ci]
|
|
4648
4648
|
failureCodes: ["HFS_COVERAGE_BELOW"]
|
|
@@ -94,10 +94,14 @@ versioning:
|
|
|
94
94
|
# allows / forbids names inside the instance; the loader exposes them, slot-check enforces them.
|
|
95
95
|
# tests unit-beside | e2e | none.
|
|
96
96
|
# coverage required | none, on every tracked slot of profile be. A required slot's subtree is measured at 100 per file on every
|
|
97
|
-
# ruleParams.be.logicRoles file
|
|
98
|
-
# is excluded from Sonar's coverage. scripts/hfs/coverage-scope.mjs
|
|
99
|
-
# sonar.coverage.exclusions and the Codecov paths and components from this
|
|
100
|
-
# Orthogonal to the lite `editions`: an edition never changes what a slot measures.
|
|
97
|
+
# ruleParams.be.logicRoles file and on every file a slot of it declares in `logic` (lines, branches, functions,
|
|
98
|
+
# statements); a none slot's subtree is never measured and is excluded from Sonar's coverage. scripts/hfs/coverage-scope.mjs
|
|
99
|
+
# derives the jest per-file thresholds, Sonar's sonar.coverage.exclusions and the Codecov paths and components from this
|
|
100
|
+
# field and `logic` and nowhere else (R204). Orthogonal to the lite `editions`: an edition never changes what a slot measures.
|
|
101
|
+
# logic on a coverage-required unit-beside directory slot: the files of the slot that carry logic without a logic-role suffix
|
|
102
|
+
# (`<name>.<part>.ts`, relative to the slot path, each one the slot requires or allows, none of a logic role). Each is
|
|
103
|
+
# measured at 100 per file like a logic-role file, and its `<name>.<part>.spec.ts` beside it is a legitimate unit spec
|
|
104
|
+
# (R47, R48): the slot admits it without listing it. No role name is added to ruleParams.be.logicRoles.
|
|
101
105
|
# composedBy the app kinds allowed to compose a transport slot (an app of another kind imports none of its modules); on an
|
|
102
106
|
# owner slot (be.cli) the app kinds that list its root module, every folder of the root holding one static module.
|
|
103
107
|
# budget size budgets (lines per file, files per slot, exports).
|
|
@@ -2012,6 +2016,7 @@ slots:
|
|
|
2012
2016
|
owner: true
|
|
2013
2017
|
requires: [index.ts, passport.config.ts, passport.options.ts, passport.decorators.ts, passport.tokens.ts, passport.password.ts, passport.cookie.ts] # Secrets, no defaults (R44); options and named injectors (R83); tokens and JWKS; bcrypt; the refresh cookie
|
|
2014
2018
|
allows: [index.ts, passport.config.ts, passport.options.ts, passport.decorators.ts, passport.tokens.ts, passport.password.ts, passport.cookie.ts, strategies/, errors/]
|
|
2019
|
+
logic: [passport.tokens.ts, passport.password.ts, passport.cookie.ts] # JWT sign and verify over the own JWKS, bcrypt, the refresh cookie: measured at 100 per file
|
|
2015
2020
|
tests: unit-beside
|
|
2016
2021
|
rules: [BE_TIER_DIRECTION, BE_ERROR_HOME, BE_SECRET_DEFAULT, BE_INFRA_OWNER, BE_AUTH_PASSPORT_OWNER, BE_AUTH_JWT_OWN_JWKS, BE_AUTH_REFRESH_COOKIE]
|
|
2017
2022
|
coverage: required
|
|
@@ -2028,8 +2033,8 @@ slots:
|
|
|
2028
2033
|
tracked: tracked
|
|
2029
2034
|
tier: integrations
|
|
2030
2035
|
owner: true
|
|
2031
|
-
requires: [index.ts, storage.config.ts, storage.options.ts, storage.decorators.ts, storage.client.ts]
|
|
2032
|
-
allows: [index.ts, storage.config.ts, storage.options.ts, storage.decorators.ts, storage.client.ts, errors/]
|
|
2036
|
+
requires: [index.ts, object-storage.config.ts, object-storage.options.ts, object-storage.decorators.ts, object-storage.client.ts]
|
|
2037
|
+
allows: [index.ts, object-storage.module.ts, object-storage.module-definition.ts, object-storage.config.ts, object-storage.options.ts, object-storage.decorators.ts, object-storage.client.ts, errors/]
|
|
2033
2038
|
tests: unit-beside
|
|
2034
2039
|
rules: [BE_TIER_DIRECTION, BE_ERROR_HOME, BE_SECRET_DEFAULT, BE_INFRA_OWNER, BE_STORAGE_OWNER]
|
|
2035
2040
|
coverage: required
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { braceVariants, globExpression } from '../lib/glob.mjs';
|
|
3
|
+
import { declaredLogicOf } from './manifest-shape.mjs';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* What a slot's `requires`, `allows` and `forbids` entries (knowledge/hfs/slots.yaml) say about a file, read through the
|
|
@@ -8,9 +9,26 @@ import { braceVariants, globExpression } from '../lib/glob.mjs';
|
|
|
8
9
|
*
|
|
9
10
|
* An entry is a name relative to the slot instance root: `<var>` is the instance's bound variable when the slot binds it
|
|
10
11
|
* (`<feature>`, `<capability>`) and one path segment of any text otherwise (`<action>`), `*` and `?` stay inside a segment,
|
|
11
|
-
* `{a,b}` alternates, a trailing `/` names a directory and everything below it.
|
|
12
|
+
* `{a,b}` alternates, a trailing `/` names a directory and everything below it. A slot also admits, unlisted, the unit spec beside each
|
|
13
|
+
* measured file it names (isMeasuredSpec): a file it declares in `logic`, or a named file of a logic role.
|
|
12
14
|
*/
|
|
13
15
|
const VAR = /<([A-Za-z][A-Za-z0-9-]*)>/g;
|
|
16
|
+
const SPEC = /\.spec\.ts$/;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Whether `relative` is the unit spec `<stem>.spec.ts` of a measured file beside it that the slot names: a file the slot declares in
|
|
20
|
+
* `logic`, or a `requires`/`allows` file of a logic role (ruleParams.be.logicRoles), in a slot whose coverage is required and whose tests
|
|
21
|
+
* are unit-beside. The slot admits that spec without listing it, as unit-test-colocated (R47) accepts it.
|
|
22
|
+
*/
|
|
23
|
+
function isMeasuredSpec(resolver, classified, slot, relative, named) {
|
|
24
|
+
if (!SPEC.test(relative) || slot.coverage !== 'required' || slot.tests !== 'unit-beside') return false;
|
|
25
|
+
const subject = relative.replace(SPEC, '.ts');
|
|
26
|
+
if (declaredLogicOf(slot).includes(subject)) return true;
|
|
27
|
+
const role = /\.([a-z0-9-]+)\.ts$/.exec(subject)?.[1];
|
|
28
|
+
// An app resolver keeps no rule parameters of its own: a path on a side reads that side's.
|
|
29
|
+
const params = classified.side ? resolver.sides?.[classified.side]?.ruleParams() : resolver.ruleParams?.();
|
|
30
|
+
return (params?.logicRoles ?? []).includes(role) && named.some(matcher => matcher.expression.test(subject));
|
|
31
|
+
}
|
|
14
32
|
|
|
15
33
|
function matchersOf(entries, bindings) {
|
|
16
34
|
return (entries ?? []).flatMap(entry => {
|
|
@@ -36,7 +54,8 @@ export function slotAdmitsFile(resolver, file) {
|
|
|
36
54
|
if (classified.status === 'no-slot' || classified.status === 'ambiguous' || !classified.slot) return null;
|
|
37
55
|
const slot = resolver.slot(classified.slot);
|
|
38
56
|
const relative = relativeToRoot(classified.path, classified.root);
|
|
39
|
-
const
|
|
57
|
+
const named = matchersOf([...(slot.requires ?? []), ...(slot.allows ?? [])], classified.bindings);
|
|
58
|
+
const hit = named.some(matcher => matcher.expression.test(relative)) || isMeasuredSpec(resolver, classified, slot, relative, named);
|
|
40
59
|
const forbidden = matchersOf(slot.forbids, classified.bindings).some(matcher => matcher.expression.test(relative) || matcher.expression.test(`${relative}/`));
|
|
41
60
|
return hit && !forbidden;
|
|
42
61
|
}
|
|
@@ -51,7 +70,9 @@ export function allowsFile(resolver, file) {
|
|
|
51
70
|
const slot = resolver.slot(classified.slot);
|
|
52
71
|
if (!slot?.allows?.length) return null;
|
|
53
72
|
const relative = relativeToRoot(classified.path, classified.root);
|
|
54
|
-
const
|
|
73
|
+
const named = matchersOf([...(slot.requires ?? []), ...slot.allows], classified.bindings);
|
|
74
|
+
const hit = named.find(matcher => matcher.expression.test(relative));
|
|
75
|
+
const spec = !hit && isMeasuredSpec(resolver, classified, slot, relative, named);
|
|
55
76
|
const forbidden = matchersOf(slot.forbids, classified.bindings).find(matcher => matcher.expression.test(relative) || matcher.expression.test(`${relative}/`));
|
|
56
|
-
return { slot: slot.id, root: classified.root, relative, allowed: Boolean(hit) && !forbidden, entry: hit?.entry, forbiddenBy: forbidden?.entry, allows: slot.allows };
|
|
77
|
+
return { slot: slot.id, root: classified.root, relative, allowed: (Boolean(hit) || spec) && !forbidden, entry: hit?.entry, forbiddenBy: forbidden?.entry, allows: slot.allows };
|
|
57
78
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// In both editions every jwtVerify call holds the JWT policy (R260, jwtPolicyProblems).
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { machineKit } from './machine-ast.mjs';
|
|
7
|
-
import { importedFrom, jwtPolicyProblems, reportAt, unwrap } from './jwt-ast.mjs';
|
|
7
|
+
import { fromConfig, importedFrom, jwtPolicyProblems, reportAt, unwrap } from './jwt-ast.mjs';
|
|
8
8
|
import { accessName } from '../../lib/ts-ast.mjs';
|
|
9
9
|
|
|
10
10
|
const PASSPORT_SLOT = 'be.integrations.passport';
|
|
@@ -87,7 +87,11 @@ function verifyJwtCall(kit, checker, file, node, counters, violations) {
|
|
|
87
87
|
const issuer = property('issuer');
|
|
88
88
|
const audience = values('audience');
|
|
89
89
|
const algorithms = values('algorithms');
|
|
90
|
-
|
|
90
|
+
// The audience is pinned by a literal or, as R260 accepts, by typed configuration (the skeleton's TokenOptions.audience).
|
|
91
|
+
const audienceEntry = property('audience');
|
|
92
|
+
const pinnedAudience = (audience !== null && audience.length > 0)
|
|
93
|
+
|| (audienceEntry != null && fromConfig(kit.ts, checker, kit.valueOfProperty(audienceEntry)));
|
|
94
|
+
const good = jwksArgument(kit, checker, node.arguments[1]) && issuer != null && pinnedAudience
|
|
91
95
|
&& algorithms !== null && algorithms.length > 0;
|
|
92
96
|
if (!good) {
|
|
93
97
|
reportAt(violations, kit, BE_JWT_VERIFIED, file, node, 'jwtVerify must check the app\'s own key set (createLocalJWKSet(...) over the keys integrations/passport signs with) and pin issuer, audience and a non-empty algorithms list; jwtVerify then enforces signature and exp.');
|
|
@@ -62,7 +62,7 @@ const configType = (checker, node) => {
|
|
|
62
62
|
};
|
|
63
63
|
|
|
64
64
|
/** Trace an issuer or audience to typed configuration values through local URL/string transformations. */
|
|
65
|
-
const fromConfig = (ts, checker, expression, seen = new Set()) => {
|
|
65
|
+
export const fromConfig = (ts, checker, expression, seen = new Set()) => {
|
|
66
66
|
const node = unwrap(ts, expression);
|
|
67
67
|
if (!node || seen.has(node)) return false;
|
|
68
68
|
const next = new Set(seen).add(node);
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// coverage-scope.mjs - THE derivation of what a back end measures (R204 HFS_COVERAGE_SCOPE_DRIFT).
|
|
2
2
|
//
|
|
3
|
-
// One input: the slot manifest. Every tracked slot of the be profile declares `coverage: required | none`,
|
|
4
|
-
// `ruleParams.be.logicRoles` names the roles that carry logic
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
3
|
+
// One input: the slot manifest. Every tracked slot of the be profile declares `coverage: required | none`,
|
|
4
|
+
// `ruleParams.be.logicRoles` names the roles that carry logic, and a required slot may declare in `logic` the files of its own that
|
|
5
|
+
// carry logic without a logic-role suffix. A file `<name>.<role>.ts` of a logic role inside a required slot, and every declared logic
|
|
6
|
+
// file, is measured at 100 per file; every other file of the back end is not. Three consumers read this module and nothing else:
|
|
7
|
+
// - the jest preset: `jestCoverage` (roots x roles, the declared logic files, and the none subtrees inside a root) becomes the
|
|
8
|
+
// per-file thresholds and collectCoverageFrom of the rendered be/jest.config.js;
|
|
8
9
|
// - Sonar: `sonarCoverageExclusions` are the complement (SonarQube has no inclusions and no negation), rendered into
|
|
9
10
|
// sonar.coverage.exclusions;
|
|
10
11
|
// - Codecov: `codecovPaths` are the measured roots, and `coverageComponents` one component per service app plus platform,
|
|
@@ -12,7 +13,7 @@
|
|
|
12
13
|
// starci app sync renders the three for an app, scripts/checks/check-examples-ci.mjs for the example apps of the runtime repository,
|
|
13
14
|
// and `starci app check` compares the files with this derivation. Nothing here lists a path of a product: it all comes from slots.yaml.
|
|
14
15
|
import { braceVariants, globExpression } from '../lib/glob.mjs';
|
|
15
|
-
import { logicRolesOf } from './manifest-shape.mjs';
|
|
16
|
+
import { declaredLogicOf, logicRolesOf } from './manifest-shape.mjs';
|
|
16
17
|
import { byCodeUnit } from '../lib/list.mjs';
|
|
17
18
|
import { trimTrailingSlashes } from './trailing-slashes.mjs';
|
|
18
19
|
|
|
@@ -68,7 +69,7 @@ function addRequiredPatterns(sonar, required, suffixes) {
|
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
function addEntryPatterns(sonar, slot, entry, isRole) {
|
|
71
|
-
if (!entry.endsWith('.ts') || entry.includes('<role>')) return;
|
|
72
|
+
if (!entry.endsWith('.ts') || entry.includes('<role>') || declaredLogicOf(slot).includes(entry)) return;
|
|
72
73
|
for (const name of braceVariants(entry)) {
|
|
73
74
|
if (isRole.test(star(name).replaceAll('*', 'x'))) continue;
|
|
74
75
|
for (const dir of variantsOf(slot)) sonar.add(`be/${dir}${star(name)}`.replace(/\/\/+/g, '/'));
|
|
@@ -116,6 +117,7 @@ const minimal = (patterns) => {
|
|
|
116
117
|
* roles ruleParams.be.logicRoles;
|
|
117
118
|
* roots the minimal required directories (be-relative, `*` for a placeholder, trailing slash), sorted;
|
|
118
119
|
* excludes the none directories inside a root (never measured though their root is);
|
|
120
|
+
* files the declared logic files of the required slots (be-relative, `*` for a placeholder) outside every none directory, sorted;
|
|
119
121
|
* none the minimal none paths of the whole back end (a directory ends in a slash), sorted;
|
|
120
122
|
* sonar sonar.coverage.exclusions, repository-relative from the app root, sorted;
|
|
121
123
|
* codecovPaths the measured roots as `be/<root>**`.
|
|
@@ -135,13 +137,15 @@ export function coverageScope(manifest, providers = []) {
|
|
|
135
137
|
const noneUnique = [...new Set(nonePaths)];
|
|
136
138
|
const noneMinimal = noneUnique.filter((path) => !noneUnique.some((other) => other !== path && isDir(other) && nested(dirOf(path), other)));
|
|
137
139
|
const excludes = noneMinimal.filter((path) => isDir(path) && roots.some((root) => nested(path, root))).sort(byCodeUnit);
|
|
140
|
+
const declared = required.flatMap((slot) => declaredLogicOf(slot).flatMap((file) => variantsOf(slot).map((dir) => `${dir}${file}`)));
|
|
141
|
+
const files = [...new Set(declared)].filter((file) => !noneMinimal.some((path) => isDir(path) && nested(dirOf(file), path))).sort(byCodeUnit);
|
|
138
142
|
const suffixes = manifest.ruleParams.be.suffixes;
|
|
139
143
|
const sonar = new Set(noneMinimal.map((path) => `be/${path}${isDir(path) ? '**' : ''}`));
|
|
140
144
|
for (const role of suffixes.filter((suffix) => !roles.includes(suffix))) sonar.add(`be/**/*.${role}.ts`);
|
|
141
145
|
addRequiredPatterns(sonar, required, suffixes);
|
|
142
146
|
sonar.add('fe/**');
|
|
143
147
|
noneMinimal.sort(byCodeUnit);
|
|
144
|
-
return { roles, roots, excludes, none: noneMinimal, sonar: withoutCovered([...sonar]).sort(byCodeUnit), codecovPaths: roots.map((root) => `be/${root}**`) };
|
|
148
|
+
return { roles, roots, files, excludes, none: noneMinimal, sonar: withoutCovered([...sonar]).sort(byCodeUnit), codecovPaths: roots.map((root) => `be/${root}**`) };
|
|
145
149
|
}
|
|
146
150
|
|
|
147
151
|
/** The glob a root measures: every file of a logic role below it (`src/modules/domain/*\/**\/*.{service,policy}.ts`). */
|
|
@@ -150,10 +154,10 @@ export const rootGlob = (root, roles) => {
|
|
|
150
154
|
return `${root}**/*.${roleGlob}.ts`;
|
|
151
155
|
};
|
|
152
156
|
|
|
153
|
-
/** The jest coverage options of the rendered be/jest.config.js: { roots, roles, excludes }. */
|
|
157
|
+
/** The jest coverage options of the rendered be/jest.config.js: { roots, roles, files, excludes }. */
|
|
154
158
|
export function jestCoverage(manifest, providers = []) {
|
|
155
|
-
const { roots, roles, excludes } = coverageScope(manifest, providers);
|
|
156
|
-
return { roots, roles, excludes: excludes.map((dir) => `${dir}**`) };
|
|
159
|
+
const { roots, roles, files, excludes } = coverageScope(manifest, providers);
|
|
160
|
+
return { roots, roles, files, excludes: excludes.map((dir) => `${dir}**`) };
|
|
157
161
|
}
|
|
158
162
|
|
|
159
163
|
/** Sonar's sonar.coverage.exclusions of an app: the complement of the measured files, repository-relative from the app root. */
|
|
@@ -225,11 +229,20 @@ function assignRoot({ root, files, services, imports, platformPaths, ownedBy })
|
|
|
225
229
|
}
|
|
226
230
|
}
|
|
227
231
|
|
|
228
|
-
/**
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const
|
|
234
|
-
|
|
232
|
+
/**
|
|
233
|
+
* The one test of whether a be-relative file is measured, over a coverage scope: a declared logic file of `files`, or `<name>.<role>.ts`
|
|
234
|
+
* of a logic role below a measured root and inside no none directory of it. isMeasured and R273 (rules/coverage-below.mjs) ask it.
|
|
235
|
+
*/
|
|
236
|
+
export function measuredBy({ roots, roles, files, excludes }) {
|
|
237
|
+
const declared = files.map((file) => globExpression(file));
|
|
238
|
+
const rootGlobs = roots.map((dir) => globExpression(`${dir}**`));
|
|
239
|
+
const excludeGlobs = excludes.map((dir) => globExpression(`${dir}**`));
|
|
240
|
+
return (file) => {
|
|
241
|
+
if (declared.some((glob) => glob.test(file))) return true;
|
|
242
|
+
const role = /\.([a-z][a-z0-9-]*)\.ts$/.exec(file)?.[1];
|
|
243
|
+
return Boolean(role) && roles.includes(role) && rootGlobs.some((glob) => glob.test(file)) && !excludeGlobs.some((glob) => glob.test(file));
|
|
244
|
+
};
|
|
235
245
|
}
|
|
246
|
+
|
|
247
|
+
/** True when the be-relative `file` is measured by the scope of the whole manifest (measuredBy). */
|
|
248
|
+
export const isMeasured = (manifest, file) => measuredBy(coverageScope(manifest))(file);
|
|
@@ -58,6 +58,40 @@ export const unitRolesOf = (manifest) => manifest.ruleParams.be.unitRoles;
|
|
|
58
58
|
/** The roles that carry logic (ruleParams.be.logicRoles): measured at 100 per file inside a coverage-required slot. */
|
|
59
59
|
export const logicRolesOf = (manifest) => manifest.ruleParams.be.logicRoles;
|
|
60
60
|
|
|
61
|
+
/** A declared logic file: `<name>.<part>.ts` below the slot path, kebab-case parts, no placeholder, glob or spec. */
|
|
62
|
+
const LOGIC_FILE = /^(?:[a-z0-9]+(?:-[a-z0-9]+)*\/)*[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)+\.ts$/;
|
|
63
|
+
|
|
64
|
+
/** The role suffix of a file name (`passport.tokens.ts` gives `tokens`). */
|
|
65
|
+
export const suffixOf = (file) => /\.([a-z0-9-]+)\.ts$/.exec(file)?.[1] ?? null;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The files a slot declares as logic (`logic`, names relative to the slot path): a file that carries logic without a logic-role suffix.
|
|
69
|
+
* Each is measured at 100 per file like a logic-role file (scripts/hfs/coverage-scope.mjs), and its `<stem>.spec.ts` beside it is a
|
|
70
|
+
* legitimate unit spec its slot admits (scripts/hfs/allows.mjs, eslint-canon-be unit-test-colocated). No role name is added for it.
|
|
71
|
+
*/
|
|
72
|
+
export const declaredLogicOf = (slot) => (Array.isArray(slot?.logic) ? slot.logic : []);
|
|
73
|
+
|
|
74
|
+
/** The unit spec beside a declared logic file: `passport.tokens.ts` gives `passport.tokens.spec.ts`. */
|
|
75
|
+
export const declaredLogicSpecOf = (file) => file.replace(/\.ts$/, '.spec.ts');
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Shape problems of a slot's `logic`: a non-empty list of unique `<name>.<part>.ts` files, each one the slot requires or allows by that
|
|
79
|
+
* exact name, on a tracked directory slot of profile be that is coverage: required and unit-beside, and (given the logic roles) none
|
|
80
|
+
* already of a logic role, which its role measures.
|
|
81
|
+
*/
|
|
82
|
+
export function slotLogicProblems(slot, at, logicRoles = []) {
|
|
83
|
+
if (slot.logic === undefined) return [];
|
|
84
|
+
const list = slot.logic;
|
|
85
|
+
if (!strList(list) || !list.length || new Set(list).size !== list.length || !list.every((file) => LOGIC_FILE.test(file) && !file.endsWith('.spec.ts'))) return [`${at}: logic must be a non-empty list of unique <name>.<part>.ts files relative to the slot path`];
|
|
86
|
+
const bad = [];
|
|
87
|
+
const home = typeof slot.path === 'string' && slot.path.endsWith('/') && slot.tracked === 'tracked' && Array.isArray(slot.profiles) && slot.profiles.includes('be') && slot.coverage === 'required' && slot.tests === 'unit-beside';
|
|
88
|
+
if (!home) bad.push(`${at}: logic belongs to a tracked directory slot of profile be whose coverage is required and whose tests are unit-beside`);
|
|
89
|
+
const named = [...(slot.requires ?? []), ...(slot.allows ?? [])];
|
|
90
|
+
for (const file of list.filter((entry) => !named.includes(entry))) bad.push(`${at}: logic file ${file} must be one the slot requires or allows by that name`);
|
|
91
|
+
for (const file of list.filter((entry) => logicRoles.includes(suffixOf(entry)))) bad.push(`${at}: logic file ${file} is of the logic role ${suffixOf(file)}, which measures it already`);
|
|
92
|
+
return bad;
|
|
93
|
+
}
|
|
94
|
+
|
|
61
95
|
|
|
62
96
|
/** Shape problems of ruleParams.be.unitRoles: unique roles of the suffix vocabulary, each spec `<role>.spec`. */
|
|
63
97
|
export function unitRolesProblems(be) {
|
|
@@ -87,7 +121,7 @@ export const MANIFEST_KINDS = [APP_KIND, RUNTIME_KIND];
|
|
|
87
121
|
export const manifestKind = (m) => (isPlainObject(m) && m.kind !== undefined ? m.kind : APP_KIND);
|
|
88
122
|
const strList = (v) => stringList(v);
|
|
89
123
|
|
|
90
|
-
const APP_SLOT_KEYS = ['id', 'profiles', 'path', 'presence', 'tracked', 'tier', 'tests', 'owner', 'appKind', 'minInstances', 'requiredWhen', 'requiredInstances', 'requires', 'pattern', 'trigger', 'allows', 'forbids', 'layers', 'kinds', 'roles', 'composedBy', 'budget', 'managedBy', 'liteManagedBy', 'rules', 'goesTo', 'why', 'since', 'perConnection', 'parent', 'editions', 'editionWhy', 'litePresence', 'lite', 'provider', 'coverage', 'entries', 'outcomeHome', 'templateNa', 'exemplifiedBy', 'role', 'importedBy', 'rewrittenBy'];
|
|
124
|
+
const APP_SLOT_KEYS = ['id', 'profiles', 'path', 'presence', 'tracked', 'tier', 'tests', 'owner', 'appKind', 'minInstances', 'requiredWhen', 'requiredInstances', 'requires', 'pattern', 'trigger', 'allows', 'forbids', 'layers', 'kinds', 'roles', 'composedBy', 'budget', 'managedBy', 'liteManagedBy', 'rules', 'goesTo', 'why', 'since', 'perConnection', 'parent', 'editions', 'editionWhy', 'litePresence', 'lite', 'provider', 'coverage', 'entries', 'outcomeHome', 'templateNa', 'exemplifiedBy', 'role', 'importedBy', 'rewrittenBy', 'logic'];
|
|
91
125
|
/** The roles a file slot may play that a rule reads (`role`): the entity registry of persistence.md BE-PERSISTENCE-3 (architecture/entity-registry.mjs). */
|
|
92
126
|
const SLOT_ROLES = ['entity-registry'];
|
|
93
127
|
/** The fields a slot's `lite` overlay may hold: the same keys it would carry in the slot body, resolved under edition lite. */
|
|
@@ -267,7 +301,7 @@ function slotPolicyProblems(slot, at) {
|
|
|
267
301
|
return bad;
|
|
268
302
|
}
|
|
269
303
|
|
|
270
|
-
export function slotProblems(slot, index, kind, { appScope = 'app', scopes = [] } = {}) {
|
|
304
|
+
export function slotProblems(slot, index, kind, { appScope = 'app', scopes = [], logicRoles = [] } = {}) {
|
|
271
305
|
const runtime = kind === RUNTIME_KIND;
|
|
272
306
|
const slotKeys = new Set(runtime ? RUNTIME_SLOT_KEYS : APP_SLOT_KEYS);
|
|
273
307
|
const tracked = runtime ? RUNTIME_TRACKED : TRACKED;
|
|
@@ -277,6 +311,7 @@ export function slotProblems(slot, index, kind, { appScope = 'app', scopes = []
|
|
|
277
311
|
bad.push(...slotLocationProblems(slot, at, runtime, tracked), ...slotPatternProblems(slot, at), ...slotListProblems(slot, at));
|
|
278
312
|
if (!runtime) bad.push(...slotAppOptionProblems(slot, at), ...slotLiteOverlayProblems(slot, at));
|
|
279
313
|
bad.push(...slotEntryProblems(slot, at), ...slotPolicyProblems(slot, at));
|
|
314
|
+
if (!runtime) bad.push(...slotLogicProblems(slot, at, logicRoles));
|
|
280
315
|
return bad;
|
|
281
316
|
}
|
|
282
317
|
|
|
@@ -3,9 +3,8 @@
|
|
|
3
3
|
// lcov carries lines, functions and branches; the unit runner also enforces its statement threshold.
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import { coverageScope } from '../coverage-scope.mjs';
|
|
6
|
+
import { coverageScope, measuredBy } from '../coverage-scope.mjs';
|
|
7
7
|
import { editionRuleParams, effectiveSlot, slotInEdition } from '../edition-slots.mjs';
|
|
8
|
-
import { globExpression } from '../../lib/glob.mjs';
|
|
9
8
|
import { byCodeUnit } from '../../lib/list.mjs';
|
|
10
9
|
import { found } from './read.mjs';
|
|
11
10
|
|
|
@@ -102,17 +101,11 @@ function inventory({ files, all, repo, manifest }) {
|
|
|
102
101
|
const prefix = repo.profile === 'app' || repo.sides ? 'be/' : '';
|
|
103
102
|
const effective = manifestOfEdition(manifest, repo.edition ?? 'full');
|
|
104
103
|
const scope = coverageScope(effective, repo.providers ?? repo.sides?.be?.providers ?? []);
|
|
105
|
-
const
|
|
106
|
-
const excludes = scope.excludes.map((dir) => globExpression(`${dir}**`));
|
|
104
|
+
const measures = measuredBy(scope);
|
|
107
105
|
const candidates = [...new Set((all ?? files ?? []).map(slash))].filter((file) => file.startsWith(prefix) && file.endsWith('.ts') && !SPEC.test(file)).sort(byCodeUnit);
|
|
108
106
|
const measured = [];
|
|
109
107
|
const unmeasured = [];
|
|
110
|
-
for (const file of candidates)
|
|
111
|
-
const relative = file.slice(prefix.length);
|
|
112
|
-
const role = /\.([a-z][a-z0-9-]*)\.ts$/.exec(relative)?.[1];
|
|
113
|
-
const measuredFile = scope.roles.includes(role) && roots.some((root) => root.test(relative)) && !excludes.some((exclude) => exclude.test(relative));
|
|
114
|
-
(measuredFile ? measured : unmeasured).push(file);
|
|
115
|
-
}
|
|
108
|
+
for (const file of candidates) (measures(file.slice(prefix.length)) ? measured : unmeasured).push(file);
|
|
116
109
|
return { measured, unmeasured, unmeasuredScopes: scope.none.map((entry) => `${prefix}${entry}`), scope, prefix };
|
|
117
110
|
}
|
|
118
111
|
|
|
@@ -269,25 +269,61 @@ function sqlObservations(text, file) {
|
|
|
269
269
|
|
|
270
270
|
function sourceSqlObservations(source, file) {
|
|
271
271
|
const observations = [];
|
|
272
|
+
const constants = sqlConstants(source);
|
|
272
273
|
const visit = node => {
|
|
273
274
|
if (ts.isCallExpression(node) && /(?:^|\.)(?:query|execute)$/.test(node.expression.getText())) {
|
|
274
275
|
const argument = unwrap(node.arguments[0]);
|
|
275
|
-
const text =
|
|
276
|
-
if (text
|
|
276
|
+
const text = argument && ts.isIdentifier(argument) ? constants.get(argument.text) : argument;
|
|
277
|
+
if (text) observations.push(...templateObservations(text, file));
|
|
277
278
|
}
|
|
278
279
|
if (ts.isTaggedTemplateExpression(node) && /(?:^|\.)sql$/.test(node.tag.getText()))
|
|
279
|
-
observations.push(...
|
|
280
|
+
observations.push(...templateObservations(node.template, file));
|
|
280
281
|
ts.forEachChild(node, visit);
|
|
281
282
|
};
|
|
282
283
|
visit(source);
|
|
283
284
|
return observations;
|
|
284
285
|
}
|
|
285
286
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
287
|
+
/** The file's `const NAME = <string or template>` statements, so SQL named before its query call is judged as if inline. */
|
|
288
|
+
function sqlConstants(source) {
|
|
289
|
+
const constants = new Map();
|
|
290
|
+
const visit = node => {
|
|
291
|
+
if (ts.isVariableDeclarationList(node) && (node.flags & ts.NodeFlags.Const)) {
|
|
292
|
+
for (const declaration of node.declarations) {
|
|
293
|
+
const value = unwrap(declaration.initializer);
|
|
294
|
+
if (ts.isIdentifier(declaration.name) && value && (ts.isStringLiteralLike(value) || ts.isTemplateExpression(value)))
|
|
295
|
+
constants.set(declaration.name.text, value);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
ts.forEachChild(node, visit);
|
|
299
|
+
};
|
|
300
|
+
visit(source);
|
|
301
|
+
return constants;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const DYNAMIC = 'starci_dynamic_sql';
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* The observations of an application SQL text. A template is read with each `${}` as NULL; when that does not parse (an
|
|
308
|
+
* interpolated identifier: `LISTEN ${channel}`, `SET x = ${n}`, `FROM ${fn}(...)`), it is read again with each `${}` as an
|
|
309
|
+
* identifier. A function whose name is interpolated bare may be pg_cron, so it stays an unknown observation; the skeleton's
|
|
310
|
+
* `callDbFunction` quotes `"${schema}"."${name}"`, which parses as it is.
|
|
311
|
+
*/
|
|
312
|
+
function templateObservations(node, file) {
|
|
313
|
+
if (ts.isStringLiteralLike(node)) return sqlObservations(node.text, file);
|
|
314
|
+
if (!ts.isTemplateExpression(node)) return [];
|
|
315
|
+
const spell = placeholder => node.head.text + node.templateSpans.map(span => `${placeholder}${span.literal.text}`).join('');
|
|
316
|
+
const nulls = spell('NULL');
|
|
317
|
+
if (parseSql(nulls)) return sqlObservations(nulls, file);
|
|
318
|
+
const named = spell(DYNAMIC);
|
|
319
|
+
const tree = parseSql(named);
|
|
320
|
+
if (!tree) return [{ id: null, cadence: null, at: file }];
|
|
321
|
+
let dynamicCall = false;
|
|
322
|
+
walkSql(tree, value => {
|
|
323
|
+
if (value.FuncCall && (value.FuncCall.funcname ?? []).some(part => part.String?.sval === DYNAMIC)) dynamicCall = true;
|
|
324
|
+
});
|
|
325
|
+
if (dynamicCall) return [{ id: null, cadence: null, at: file }];
|
|
326
|
+
return sqlObservations(named, file);
|
|
291
327
|
}
|
|
292
328
|
|
|
293
329
|
function recurringObservations({ doc, repoRoot, files, file, issues }) {
|
|
@@ -53,7 +53,8 @@ function checkAppKindAndTierShapes(m, bad) {
|
|
|
53
53
|
|
|
54
54
|
function checkSlotShapes(m, bad) {
|
|
55
55
|
if (!Array.isArray(m.slots) || !m.slots.length) { bad.push('slots must be a non-empty list'); return false; }
|
|
56
|
-
|
|
56
|
+
const logicRoles = Array.isArray(m.ruleParams?.be?.logicRoles) ? m.ruleParams.be.logicRoles : [];
|
|
57
|
+
m.slots.forEach((slot, index) => bad.push(...slotProblems(slot, index, APP_KIND, { appScope: APP_SCOPE, scopes: SCOPES, logicRoles })));
|
|
57
58
|
return true;
|
|
58
59
|
}
|
|
59
60
|
|
package/sync/index.mjs
CHANGED
|
@@ -279,13 +279,13 @@ export function componentsYaml(components, { prefix = '', ids = id => id } = {})
|
|
|
279
279
|
return components.map(component => [` - component_id: ${ids(component.id)}`, ` name: ${ids(component.name)}`, ' paths:', ...component.paths.map(glob => ` - ${JSON.stringify(prefix + glob)}`)].join('\n')).join('\n');
|
|
280
280
|
}
|
|
281
281
|
|
|
282
|
-
/** The managed be/jest.config.js option text of a coverage scope { roots, roles, excludes }, laid out exactly as prettier lays it out (width 120, indent 4). */
|
|
282
|
+
/** The managed be/jest.config.js option text of a coverage scope { roots, roles, files, excludes }, laid out exactly as prettier lays it out (width 120, indent 4). */
|
|
283
283
|
export function jestCoverageSource(coverage) {
|
|
284
284
|
const list = (key, items) => {
|
|
285
285
|
const one = ` ${key}: [${items.map(item => JSON.stringify(item)).join(', ')}],`;
|
|
286
286
|
return one.length <= 120 ? one : [` ${key}: [`, ...items.map(item => ` ${JSON.stringify(item)},`), ' ],'].join('\n');
|
|
287
287
|
};
|
|
288
|
-
return ['{', list('roots', coverage.roots), list('roles', coverage.roles), list('excludes', coverage.excludes), ' }'].join('\n');
|
|
288
|
+
return ['{', list('roots', coverage.roots), list('roles', coverage.roles), list('files', coverage.files), list('excludes', coverage.excludes), ' }'].join('\n');
|
|
289
289
|
}
|
|
290
290
|
|
|
291
291
|
/**
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Test } from "@nestjs/testing"
|
|
2
|
+
import type { Response } from "express"
|
|
3
|
+
import { mock } from "@starci/jest-preset"
|
|
4
|
+
import { clearRefreshCookie, newRefreshToken, refreshTokenHash, setRefreshCookie } from "./passport.cookie"
|
|
5
|
+
|
|
6
|
+
const COOKIE: unique symbol = Symbol("passport.cookie")
|
|
7
|
+
|
|
8
|
+
const OPTIONS = { name: "refresh", path: "/auth/refresh", ttlSeconds: 600 }
|
|
9
|
+
|
|
10
|
+
const build = async () => {
|
|
11
|
+
const moduleRef = await Test.createTestingModule({
|
|
12
|
+
providers: [{ provide: COOKIE, useValue: { clearRefreshCookie, newRefreshToken, refreshTokenHash, setRefreshCookie } }],
|
|
13
|
+
}).compile()
|
|
14
|
+
return moduleRef.get<{
|
|
15
|
+
clearRefreshCookie: typeof clearRefreshCookie
|
|
16
|
+
newRefreshToken: typeof newRefreshToken
|
|
17
|
+
refreshTokenHash: typeof refreshTokenHash
|
|
18
|
+
setRefreshCookie: typeof setRefreshCookie
|
|
19
|
+
}>(COOKIE)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe("refresh tokens", () => {
|
|
23
|
+
it("stores the sha256 of a token, never the token", async () => {
|
|
24
|
+
const subject = await build()
|
|
25
|
+
|
|
26
|
+
expect(subject.refreshTokenHash("abc")).toBe("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it("mints a 256-bit base64url token paired with its own hash", async () => {
|
|
30
|
+
const subject = await build()
|
|
31
|
+
const minted = subject.newRefreshToken()
|
|
32
|
+
|
|
33
|
+
expect(Buffer.from(minted.token, "base64url")).toHaveLength(32)
|
|
34
|
+
expect(minted.hash).toBe(subject.refreshTokenHash(minted.token))
|
|
35
|
+
expect(subject.newRefreshToken().token).not.toBe(minted.token)
|
|
36
|
+
})
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
describe("refresh cookie", () => {
|
|
40
|
+
it("sets the rotated token httpOnly, Secure, SameSite=Strict on the refresh path for its lifetime", async () => {
|
|
41
|
+
const subject = await build()
|
|
42
|
+
const response = mock<Response>()
|
|
43
|
+
|
|
44
|
+
subject.setRefreshCookie(response, OPTIONS, "token-1")
|
|
45
|
+
|
|
46
|
+
expect(response.cookie).toHaveBeenCalledWith("refresh", "token-1", { httpOnly: true, secure: true, sameSite: "strict", path: "/auth/refresh", maxAge: 600_000 })
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it("clears the cookie with the attributes it was set with", async () => {
|
|
50
|
+
const subject = await build()
|
|
51
|
+
const response = mock<Response>()
|
|
52
|
+
|
|
53
|
+
subject.clearRefreshCookie(response, OPTIONS)
|
|
54
|
+
|
|
55
|
+
expect(response.clearCookie).toHaveBeenCalledWith("refresh", { httpOnly: true, secure: true, sameSite: "strict", path: "/auth/refresh" })
|
|
56
|
+
})
|
|
57
|
+
})
|
package/templates/be/skeleton-lite/src/modules/integrations/passport/passport.password.spec.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Test } from "@nestjs/testing"
|
|
2
|
+
import { hashPassword, verifyPassword } from "./passport.password"
|
|
3
|
+
|
|
4
|
+
const PASSWORD: unique symbol = Symbol("passport.password")
|
|
5
|
+
|
|
6
|
+
const build = async () => {
|
|
7
|
+
const moduleRef = await Test.createTestingModule({
|
|
8
|
+
providers: [{ provide: PASSWORD, useValue: { hashPassword, verifyPassword } }],
|
|
9
|
+
}).compile()
|
|
10
|
+
return moduleRef.get<{ hashPassword: typeof hashPassword; verifyPassword: typeof verifyPassword }>(PASSWORD)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
describe("hashPassword and verifyPassword", () => {
|
|
14
|
+
it("hashes at bcrypt cost 12 and verifies only the password it hashed", async () => {
|
|
15
|
+
const subject = await build()
|
|
16
|
+
const stored = await subject.hashPassword("correct horse")
|
|
17
|
+
|
|
18
|
+
expect(stored.slice(0, 7)).toBe("$2b$12$")
|
|
19
|
+
expect(await subject.verifyPassword("correct horse", stored)).toBe(true)
|
|
20
|
+
expect(await subject.verifyPassword("wrong horse", stored)).toBe(false)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it("never matches an account that has no password hash", async () => {
|
|
24
|
+
const subject = await build()
|
|
25
|
+
|
|
26
|
+
expect(await subject.verifyPassword("correct horse", null)).toBe(false)
|
|
27
|
+
})
|
|
28
|
+
})
|
package/templates/be/skeleton-lite/src/modules/integrations/passport/passport.tokens.spec.ts
CHANGED
|
@@ -1,32 +1,88 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Test } from "@nestjs/testing"
|
|
2
|
+
import { exportPKCS8, generateKeyPair, SignJWT } from "jose"
|
|
2
3
|
import { Secret } from "@modules/platform/config"
|
|
3
|
-
import {
|
|
4
|
+
import { PassportErrorCode } from "./errors/passport.error"
|
|
5
|
+
import { createTokenKit, tokenKit } from "./passport.tokens"
|
|
4
6
|
|
|
5
|
-
const
|
|
7
|
+
const TOKENS: unique symbol = Symbol("passport.tokens")
|
|
8
|
+
|
|
9
|
+
type SigningKey = Awaited<ReturnType<typeof generateKeyPair>>["privateKey"]
|
|
10
|
+
|
|
11
|
+
const ISSUER = "https://api.example.test"
|
|
12
|
+
const AUDIENCE = "app"
|
|
13
|
+
|
|
14
|
+
const build = async () => {
|
|
15
|
+
const moduleRef = await Test.createTestingModule({
|
|
16
|
+
providers: [{ provide: TOKENS, useValue: { createTokenKit, tokenKit } }],
|
|
17
|
+
}).compile()
|
|
18
|
+
return moduleRef.get<{ createTokenKit: typeof createTokenKit; tokenKit: typeof tokenKit }>(TOKENS)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const keyPair = async () => {
|
|
6
22
|
const { privateKey } = await generateKeyPair("ES256", { extractable: true })
|
|
7
|
-
return {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
23
|
+
return { privateKey, options: { issuer: ISSUER, audience: AUDIENCE, privateKey: new Secret(await exportPKCS8(privateKey)), keyId: "k1", accessTtlSeconds: 60 } }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A token the kit's own key signs with the given claims, so only the claim checks can refuse it. */
|
|
27
|
+
const ownSigned = (privateKey: SigningKey, claims: Record<string, unknown>, { subject = "user-1", expires = true } = {}) => {
|
|
28
|
+
const jwt = new SignJWT(claims).setProtectedHeader({ alg: "ES256", kid: "k1" }).setIssuer(ISSUER).setAudience(AUDIENCE).setIssuedAt()
|
|
29
|
+
if (subject !== "") jwt.setSubject(subject)
|
|
30
|
+
if (expires) jwt.setExpirationTime("60s")
|
|
31
|
+
return jwt.sign(privateKey)
|
|
14
32
|
}
|
|
15
33
|
|
|
16
34
|
describe("createTokenKit", () => {
|
|
17
|
-
it("verifies its own token against its own key set and publishes only the public key", async () => {
|
|
18
|
-
const
|
|
19
|
-
const
|
|
35
|
+
it("verifies its own token with an email against its own key set and publishes only the public key", async () => {
|
|
36
|
+
const subject = await build()
|
|
37
|
+
const { options } = await keyPair()
|
|
38
|
+
const kit = await subject.createTokenKit(options)
|
|
20
39
|
|
|
21
|
-
expect(
|
|
40
|
+
expect(await kit.verify(await kit.issue({ id: "user-1", email: "a@example.test" }))).toEqual({ kind: "ok", value: { id: "user-1", role: "authenticated", email: "a@example.test" } })
|
|
22
41
|
expect(kit.jwks.keys).toHaveLength(1)
|
|
42
|
+
expect(kit.jwks.keys[0]).toMatchObject({ kid: "k1", alg: "ES256", use: "sig", kty: "EC", crv: "P-256" })
|
|
23
43
|
expect(kit.jwks.keys[0]).not.toHaveProperty("d")
|
|
24
44
|
})
|
|
25
45
|
|
|
26
|
-
it("
|
|
27
|
-
const
|
|
28
|
-
const
|
|
46
|
+
it("issues a token without an email claim for a user who has none", async () => {
|
|
47
|
+
const subject = await build()
|
|
48
|
+
const { options } = await keyPair()
|
|
49
|
+
const kit = await subject.createTokenKit(options)
|
|
50
|
+
|
|
51
|
+
expect(await kit.verify(await kit.issue({ id: "user-2" }))).toEqual({ kind: "ok", value: { id: "user-2", role: "authenticated" } })
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it("refuses a token another key signed, naming the failed signature", async () => {
|
|
55
|
+
const subject = await build()
|
|
56
|
+
const kit = await subject.createTokenKit((await keyPair()).options)
|
|
57
|
+
const other = await subject.createTokenKit((await keyPair()).options)
|
|
58
|
+
|
|
59
|
+
expect(await kit.verify(await other.issue({ id: "user-1" }))).toEqual({
|
|
60
|
+
kind: "refused",
|
|
61
|
+
code: PassportErrorCode.AccessTokenInvalid,
|
|
62
|
+
params: { cause: "JWSSignatureVerificationFailed: signature verification failed" },
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it("refuses a correctly signed token whose subject, expiry or role is not the one it issues", async () => {
|
|
67
|
+
const subject = await build()
|
|
68
|
+
const { privateKey, options } = await keyPair()
|
|
69
|
+
const kit = await subject.createTokenKit(options)
|
|
70
|
+
const invalid = { kind: "refused", code: PassportErrorCode.AccessTokenInvalid }
|
|
71
|
+
|
|
72
|
+
expect(await kit.verify(await ownSigned(privateKey, { role: "authenticated" }, { subject: "" }))).toEqual(invalid)
|
|
73
|
+
expect(await kit.verify(await ownSigned(privateKey, { role: "authenticated" }, { expires: false }))).toEqual(invalid)
|
|
74
|
+
expect(await kit.verify(await ownSigned(privateKey, { role: "service_role" }))).toEqual(invalid)
|
|
75
|
+
expect(await kit.verify(await ownSigned(privateKey, { role: "authenticated", email: 7 }))).toEqual({ kind: "ok", value: { id: "user-1", role: "authenticated" } })
|
|
76
|
+
})
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
describe("tokenKit", () => {
|
|
80
|
+
it("signs, verifies and publishes through the one key import it starts", async () => {
|
|
81
|
+
const subject = await build()
|
|
82
|
+
const { options } = await keyPair()
|
|
83
|
+
const kit = subject.tokenKit(options)
|
|
29
84
|
|
|
30
|
-
expect(
|
|
85
|
+
expect(await kit.verify(await kit.issue({ id: "user-3", email: "c@example.test" }))).toEqual({ kind: "ok", value: { id: "user-3", role: "authenticated", email: "c@example.test" } })
|
|
86
|
+
expect((await kit.jwks()).keys.map((key) => key.kid)).toEqual(["k1"])
|
|
31
87
|
})
|
|
32
88
|
})
|