@starci/hfs 4.11.19 → 4.11.21
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 +15 -0
- package/package.json +1 -1
- package/release/index.mjs +2 -2
- package/release/urgent.mjs +11 -43
- 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/modules/schemas/application-stacks.schema.yaml +8 -8
- 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/secret-standard.mjs +15 -5
- package/runtime/scripts/hfs/slot-manifest-shape.mjs +2 -1
- package/runtime/scripts/hfs/stack-deploy-config.mjs +6 -3
- package/runtime/scripts/hfs/stacks-gate.mjs +6 -0
- package/src/main.mjs +4 -4
- package/stack/cli.mjs +18 -5
- package/stack/urgent-release.mjs +45 -0
- 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/release/lint-baseline.mjs +0 -123
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.11.21 - 2026-10-30
|
|
4
|
+
|
|
5
|
+
- Changed: an urgent release runs typecheck and the build only (owner ruling urgent-typecheck-build, contexts/harness/decisions.md): `URGENT_CHECKS` are the release gates `typecheck`, `build`, `build-be` and `build-fe` the app declares (`release/urgent.mjs`); app check, lint and the tests wait for the back-fill. `--lint-baseline` is retired with lint itself and refused (`RELEASE_URGENT_LINT_BASELINE_RETIRED`); `release/lint-baseline.mjs` is gone.
|
|
6
|
+
- Added: the one-command urgent release. `starci app stack deploy --env <env> --urgent --reason "<text>" --execute` with no `--image` and no `--source-sha` releases HEAD (unless it already has a pushed urgent record; a tag already on HEAD is adopted), builds and pushes its images on this machine before the deploy's Docker transport reaches the server, and deploys their digests under the unchanged floor (`stack/urgent-release.mjs`, wired in `stack/cli.mjs`; `--reason` and `--remote` belong to it; `STACK_URGENT_REASON_MISSING`). A dry run plans the release and the build and stops. Specs: `src/stack-urgent-release.spec.mjs`, `src/release-urgent.spec.mjs`.
|
|
7
|
+
- Changed: `deploy.remote.sealed` is one member name (`sealed: vps`: `vps.enc.yaml` holds VPS_HOST, VPS_USER, `privateKey` and `knownHosts`), read as the member of all three SSH roles (`stack-deploy-config.mjs`, schema `deployRemote.sealed`). The three-role object `{ ops, sshKey, knownHosts }` is refused (STACKS_DEPLOY_CONFIG_INVALID), its message naming `starci app secret migrate <env> <member> --to vps --into-existing` to fold a member per role into one (owner, 2026-10-30: one form only). Spec: `src/hfs-stacks-deploy-schema.spec.mjs`.
|
|
8
|
+
- Changed: `secret audit` takes a grouped member as declared, not MIXED_PROVIDERS: the member `deploy.remote.sealed` names groups VPS_HOST, VPS_USER, privateKey and knownHosts, and a `secrets:` entry naming a member may list the keys it groups (`keys: [...]`, schema `secret.keys`) instead of an entry per key; the stacks gate refuses a listed key the envelope does not hold, and an entry with both `key` and `keys` (`secret-standard.mjs` `declaredGroup`, `stacks-gate.mjs`). Spec: `src/hfs-secret-standard.spec.mjs`.
|
|
9
|
+
- Changed: the bundled canon pins name eslint-canon-be 3.8.20, eslint-canon-fe 9.5.22 and the Grammar family 0.15.33.
|
|
10
|
+
|
|
11
|
+
## 4.11.20 - 2026-10-30
|
|
12
|
+
|
|
13
|
+
- 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.
|
|
14
|
+
- 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`.
|
|
15
|
+
- 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`.
|
|
16
|
+
- 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.
|
|
17
|
+
|
|
3
18
|
## 4.11.19 - 2026-10-30
|
|
4
19
|
|
|
5
20
|
- 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.
|
package/package.json
CHANGED
package/release/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// index.mjs - `starci app release <gate|push>` and the plumbing the release and database verbs share: the context built from the app's IO, strict flag
|
|
2
2
|
// parsing, the optional `release:` / `database:` blocks of .starcistacks/application-stacks.yaml, text and --json output and the exit-code mapping.
|
|
3
3
|
// starci app release gate [--execute] [--sonar] [--source <ref>] [--tag-prefix <prefix>] [--backfill <tag>] [--json]
|
|
4
|
-
// starci app release push [--execute] [--remote <name>] [--urgent --reason <text>
|
|
4
|
+
// starci app release push [--execute] [--remote <name>] [--urgent --reason <text>] [--json]
|
|
5
5
|
// `harness` of the app IO ({ version, role, openTicket }) is what the starci CLI hands in: the caller's role an urgent record names and the ticket
|
|
6
6
|
// queue a red back-fill files into.
|
|
7
7
|
// Every action is a dry run unless --execute is given. A refusal is a StackError (exit 2); a failed step returns ok false (exit 1).
|
|
@@ -58,7 +58,7 @@ function readPackage(root) {
|
|
|
58
58
|
}
|
|
59
59
|
|
|
60
60
|
/** The normalised `release:` block (tolerant of absence) with the package version: { root, version, gates, tagPrefix, defaultBranch, requireCi }. */
|
|
61
|
-
function loadReleaseConfig(root) {
|
|
61
|
+
export function loadReleaseConfig(root) {
|
|
62
62
|
const pkg = readPackage(root);
|
|
63
63
|
if (typeof pkg.version !== 'string' || !VERSION.test(pkg.version)) throw refusal(RELEASE_CODE, 'package.json needs a version like 1.2.3 (the release tag derives from it)');
|
|
64
64
|
const declaration = readDeclaration(root);
|
package/release/urgent.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// urgent.mjs - `starci app release push --urgent --reason "<text>"`, the sanctioned urgent path (owner ruling urgent-release, 2026-10-29: an urgent
|
|
2
|
-
// deploy needs no CI). It runs only the fast local checks (
|
|
2
|
+
// deploy needs no CI). It runs only the fast local checks (typecheck and the build: owner ruling urgent-typecheck-build, 2026-10-30), or
|
|
3
3
|
// reuses a green row the gate already recorded for HEAD with the same command and an unchanged log; tags HEAD (annotated) and pushes the default
|
|
4
4
|
// branch and the tag in ONE atomic push through the repository's hook (never --no-verify, `git push --dry-run --atomic` first); then writes the
|
|
5
5
|
// URGENT record <git common dir>/starci-release/<HEAD>.urgent.json naming who (the caller's role), why (the reason), each check with its verdict and the
|
|
@@ -11,15 +11,14 @@ import { firstLine } from '../stack/context.mjs';
|
|
|
11
11
|
import { failure, refusal } from '../stack/errors.mjs';
|
|
12
12
|
import { assertUnmoved, git, inspect, releaseDir, runGate, summaryOf } from './gate.mjs';
|
|
13
13
|
import { assertNames, branchRefs, probe, tagRefs } from './push.mjs';
|
|
14
|
-
import { baselineLint } from './lint-baseline.mjs';
|
|
15
14
|
import { URGENT_RULING, URGENT_SCHEMA, greenRow, recordRow, writeUrgent } from './records.mjs';
|
|
16
15
|
|
|
17
|
-
/**
|
|
18
|
-
|
|
16
|
+
/**
|
|
17
|
+
* The fast local checks of an urgent release, by gate name, in the order they run: what can break production, the types and the build
|
|
18
|
+
* (owner ruling urgent-typecheck-build, 2026-10-30). App check, lint and the tests wait for the back-fill (`release gate --backfill`).
|
|
19
|
+
*/
|
|
20
|
+
export const URGENT_CHECKS = Object.freeze(['typecheck', 'build', 'build-be', 'build-fe']);
|
|
19
21
|
const REASON_MAX = 500;
|
|
20
|
-
const CHANGED_MAX = 200;
|
|
21
|
-
const PATH_WORD = /^[A-Za-z0-9_@%+=:,./\\-]+$/u;
|
|
22
|
-
const MANAGED_LINT = 'npm run lint';
|
|
23
22
|
|
|
24
23
|
/** The reason, one line of plain text; an urgent release without one is refused. */
|
|
25
24
|
function reasonOf(value) {
|
|
@@ -29,37 +28,11 @@ function reasonOf(value) {
|
|
|
29
28
|
return reason;
|
|
30
29
|
}
|
|
31
30
|
|
|
32
|
-
/** The
|
|
33
|
-
function
|
|
34
|
-
const found = git(ctx, ['describe', '--tags', '--abbrev=0', '--match', `${prefix}[0-9]*`, 'HEAD^'], { allowFail: true });
|
|
35
|
-
return found.code === 0 && found.stdout !== '' ? found.stdout : null;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** The lint row of an urgent release: the managed whole-app lint narrowed to the source files changed since the previous release tag. */
|
|
39
|
-
function changedLint(ctx, gate, prefix) {
|
|
40
|
-
if (gate.command.join(' ') !== MANAGED_LINT) return { gate, note: null };
|
|
41
|
-
const since = previousTag(ctx, prefix);
|
|
42
|
-
if (!since) return { gate, note: 'no previous release tag: the whole app is linted' };
|
|
43
|
-
const files = git(ctx, ['diff', '--name-only', '--diff-filter=d', `${since}..HEAD`]).stdout.split('\n').map((file) => file.trim())
|
|
44
|
-
.filter((file) => /\.(?:[cm]?[jt]sx?|css)$/u.test(file));
|
|
45
|
-
if (files.length === 0) return { gate: null, note: `no source file changed since ${since}` };
|
|
46
|
-
if (files.length > CHANGED_MAX || !files.every((file) => PATH_WORD.test(file))) return { gate, note: `${files.length} changed file(s) since ${since}: the whole app is linted` };
|
|
47
|
-
return { gate: { ...gate, command: ['npx', 'starci', 'app', 'lint', '--changed', ...files] }, note: `${files.length} file(s) changed since ${since}` };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* The urgent checks this app declares, from its release gates; a lint row is narrowed to the changed files, or, with `lintBaseline` (a release
|
|
52
|
-
* tag), judged whole against that tag's findings (lint-baseline.mjs), which only the managed lint can be.
|
|
53
|
-
*/
|
|
54
|
-
function urgentGates(ctx, config, prefix, lintBaseline) {
|
|
31
|
+
/** The urgent checks this app declares, from its release gates, in URGENT_CHECKS order. */
|
|
32
|
+
function urgentGates(config) {
|
|
55
33
|
const declared = URGENT_CHECKS.map((name) => config.gates.find((gate) => gate.name === name)).filter(Boolean);
|
|
56
34
|
if (declared.length === 0) throw refusal('RELEASE_URGENT_NO_CHECKS', `the release gates declare none of ${URGENT_CHECKS.join(', ')}: an urgent release still runs its fast local checks`);
|
|
57
|
-
return declared.map((gate) => {
|
|
58
|
-
if (gate.name !== 'lint') return { name: gate.name, gate, note: null };
|
|
59
|
-
if (lintBaseline === undefined) return { name: gate.name, ...changedLint(ctx, gate, prefix) };
|
|
60
|
-
if (gate.command.join(' ') !== MANAGED_LINT) throw refusal('RELEASE_URGENT_LINT_BASELINE_UNMANAGED', `--lint-baseline judges the managed lint (${MANAGED_LINT}), and this app's lint gate runs ${gate.command.join(' ')}`);
|
|
61
|
-
return { name: gate.name, gate, baseline: lintBaseline, note: `the whole app, judged against ${lintBaseline}: only a finding new since it is red (owner ruling urgent-lint-baseline)` };
|
|
62
|
-
});
|
|
35
|
+
return declared.map((gate) => ({ name: gate.name, gate, note: null }));
|
|
63
36
|
}
|
|
64
37
|
|
|
65
38
|
/** Runs (or reuses) each check in order and stops at the first red one. Returns the rows of the record. */
|
|
@@ -71,12 +44,6 @@ function runChecks(ctx, checks, { common, head, dir, platform }) {
|
|
|
71
44
|
rows.push({ name: check.name, command: null, pass: true, reused: false, detail: check.note, log: null, logSha256: null });
|
|
72
45
|
continue;
|
|
73
46
|
}
|
|
74
|
-
if (check.baseline !== undefined) {
|
|
75
|
-
const row = baselineLint(ctx, check.gate, { tag: check.baseline, dir, platform });
|
|
76
|
-
rows.push({ ...row, reused: false, note: check.note });
|
|
77
|
-
if (!row.pass) break;
|
|
78
|
-
continue;
|
|
79
|
-
}
|
|
80
47
|
const command = check.gate.command.join(' ');
|
|
81
48
|
const reused = greenRow(common, head, check.name, command);
|
|
82
49
|
if (reused) {
|
|
@@ -104,6 +71,7 @@ function planOf(checks) {
|
|
|
104
71
|
*/
|
|
105
72
|
export async function releaseUrgentPush(ctx, config, options = {}) {
|
|
106
73
|
const reason = reasonOf(options.reason);
|
|
74
|
+
if (options.lintBaseline !== undefined) throw refusal('RELEASE_URGENT_LINT_BASELINE_RETIRED', 'an urgent release no longer lints (owner ruling urgent-typecheck-build): lint runs in the back-fill, so --lint-baseline has nothing to judge');
|
|
107
75
|
const role = options.role ?? 'unset';
|
|
108
76
|
const remote = options.remote ?? 'origin';
|
|
109
77
|
const branch = config.defaultBranch;
|
|
@@ -112,7 +80,7 @@ export async function releaseUrgentPush(ctx, config, options = {}) {
|
|
|
112
80
|
const { head, chosen } = facts;
|
|
113
81
|
const common = releaseDir(ctx);
|
|
114
82
|
const dir = path.join(common, head.slice(0, 12));
|
|
115
|
-
const checks = urgentGates(
|
|
83
|
+
const checks = urgentGates(config);
|
|
116
84
|
const out = [...facts.out, `urgent ${URGENT_RULING}`, `reason ${reason}`, `role ${role}`, ...planOf(checks)];
|
|
117
85
|
const data = { head, tag: chosen.tag, remote, branch, urgent: true, reason, role, checks: [], pushed: false };
|
|
118
86
|
if (facts.red.length > 0) return { ok: false, lines: [...out, ...facts.red.map((item) => `RED: ${item}`), 'nothing run, nothing pushed.'], data: { ...data, red: facts.red } };
|
|
@@ -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.33
|
|
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.20
|
|
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.22
|
|
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.33
|
|
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.33
|
|
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.21
|
|
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
|
|
@@ -650,14 +650,8 @@ $defs:
|
|
|
650
650
|
pattern: '^[A-Za-z0-9][A-Za-z0-9._-]*$'
|
|
651
651
|
releasesBase: {$ref: '#/$defs/deployAbsolutePath'}
|
|
652
652
|
sealed:
|
|
653
|
-
description: 'Owner-machine session for prepare and
|
|
654
|
-
|
|
655
|
-
additionalProperties: false
|
|
656
|
-
required: [ops, sshKey, knownHosts]
|
|
657
|
-
properties:
|
|
658
|
-
ops: {$ref: '#/$defs/deployName'}
|
|
659
|
-
sshKey: {$ref: '#/$defs/deployName'}
|
|
660
|
-
knownHosts: {$ref: '#/$defs/deployName'}
|
|
653
|
+
description: 'Owner-machine session for prepare, doctor and deploy: the one member of .starcistacks/<environment>/secrets holding VPS_HOST, VPS_USER, privateKey and knownHosts.'
|
|
654
|
+
$ref: '#/$defs/deployName'
|
|
661
655
|
serverRecipient:
|
|
662
656
|
description: The deploy server's public age recipient, recorded by starci app secret server-key <env> --execute.
|
|
663
657
|
type: string
|
|
@@ -865,5 +859,11 @@ $defs:
|
|
|
865
859
|
where: {type: string, minLength: 1}
|
|
866
860
|
member: {type: string, pattern: '^[a-z0-9][a-z0-9-]*$', description: "The provider member holding this key (`secrets/<member>`, the slug of where); with key, the entry declares one key of it."}
|
|
867
861
|
key: {type: string, pattern: '^[A-Z][A-Z0-9_]*$', description: "The one key of the member this entry declares; materialized as its own file, read by the app as <KEY>_FILE."}
|
|
862
|
+
keys:
|
|
863
|
+
description: The keys a member groups on purpose (several providers in one member), declared in one entry instead of an entry per key; every one must be in the member's envelope.
|
|
864
|
+
type: array
|
|
865
|
+
minItems: 1
|
|
866
|
+
uniqueItems: true
|
|
867
|
+
items: {type: string, pattern: '^[A-Za-z][A-Za-z0-9_]*$'}
|
|
868
868
|
recipientPolicy: {type: string, minLength: 1, description: "Which age recipients the envelope is encrypted to: its environment's rule of the app's managed .sops.yaml."}
|
|
869
869
|
keyCustody: {type: string, minLength: 1, description: "Where the shared decrypting identity is held; docs/host-secrets.md owns host custody and its execution prerequisites."}
|
|
@@ -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
|
|
|
@@ -20,21 +20,31 @@ export const providerOf = (key) => key.split("_")[0].toLowerCase();
|
|
|
20
20
|
const sameSet = (left, right) => left.length === right.length && left.every((item) => right.includes(item));
|
|
21
21
|
const keyList = (keys) => keys.join(", ");
|
|
22
22
|
|
|
23
|
+
/** The member a `secrets:` entry names: `member`, else the slug of `where`, else its `name`. */
|
|
24
|
+
const memberOfEntry = (entry) => entry?.member ?? /^secrets\/([a-z0-9-]+)/u.exec(entry?.where ?? "")?.[1] ?? entry?.name;
|
|
25
|
+
|
|
23
26
|
/** The keys an environment's `secrets:` declares for `member`: an entry naming `key` with that `member`, or a whole-member entry. */
|
|
24
27
|
function declaredKeys(spec, member, keys) {
|
|
25
28
|
const entries = Array.isArray(spec?.secrets) ? spec.secrets : [];
|
|
26
|
-
const memberOfEntry = (entry) => entry?.member ?? /^secrets\/([a-z0-9-]+)/u.exec(entry?.where ?? "")?.[1] ?? entry?.name;
|
|
27
29
|
if (entries.some((entry) => entry?.key === undefined && memberOfEntry(entry) === member)) return keys;
|
|
28
30
|
return entries.filter((entry) => entry?.key !== undefined && memberOfEntry(entry) === member).map((entry) => entry.key);
|
|
29
31
|
}
|
|
30
32
|
|
|
33
|
+
/** The keys of the one sealed SSH member `deploy.remote.sealed` names (stack/remote.mjs): the deploy transport reads exactly these. */
|
|
34
|
+
const SSH_GROUP = Object.freeze(["VPS_HOST", "VPS_USER", "privateKey", "knownHosts"]);
|
|
35
|
+
|
|
31
36
|
/**
|
|
32
|
-
* True when the stack groups `member` on purpose: the environment's `secrets
|
|
33
|
-
*
|
|
37
|
+
* True when the stack groups `member` on purpose: every key of it is declared in the environment's `secrets:`, per key (`key` with
|
|
38
|
+
* `member: <member>`) or in the `keys` list of an entry naming the member, or is a key of the sealed SSH member the deploy names.
|
|
39
|
+
* A member the owner groups (an app's own keys, the keys one service reads, the VPS session) holds keys of several first words by design.
|
|
34
40
|
*/
|
|
35
41
|
function declaredGroup(spec, member, keys) {
|
|
36
42
|
const entries = Array.isArray(spec?.secrets) ? spec.secrets : [];
|
|
37
|
-
|
|
43
|
+
const sealed = spec?.deploy?.remote?.sealed;
|
|
44
|
+
const ssh = (typeof sealed === "string" ? [sealed] : Object.values(sealed ?? {})).includes(member) ? SSH_GROUP : [];
|
|
45
|
+
const declared = (key) => ssh.includes(key) || entries.some((entry) => memberOfEntry(entry) === member
|
|
46
|
+
&& (entry?.key === key || (Array.isArray(entry?.keys) && entry.keys.includes(key))));
|
|
47
|
+
return keys.length > 0 && keys.every(declared);
|
|
38
48
|
}
|
|
39
49
|
|
|
40
50
|
/** The tracked member file names of one environment, or null outside a git work tree. */
|
|
@@ -75,7 +85,7 @@ export function auditSecrets(repoRoot, environment = null) {
|
|
|
75
85
|
const providers = [...new Set(envelope.keys.map(providerOf))];
|
|
76
86
|
if (isLegacyName(name)) add("LEGACY_MEMBER", `is a dotenv .enc member; move it: starci app secret migrate ${env} ${member} [--to <provider>] --execute`);
|
|
77
87
|
if (providers.length > 1 && !declaredGroup(spec, member, envelope.keys))
|
|
78
|
-
add("MIXED_PROVIDERS", `holds keys of ${providers.length} providers by their first word (${providers.join(", ")}) that the stack does not group in it; split it (starci app secret split ${env} ${member} [--group KEY=member] --execute) or declare
|
|
88
|
+
add("MIXED_PROVIDERS", `holds keys of ${providers.length} providers by their first word (${providers.join(", ")}) that the stack does not group in it; split it (starci app secret split ${env} ${member} [--group KEY=member] --execute) or declare its keys in environments.${env}.secrets (an entry naming ${member} with keys: [...])`);
|
|
79
89
|
const wanted = recipientsFor(repoRoot, path.join(directory, `${member}${MEMBER_SUFFIX}`));
|
|
80
90
|
if (!isLegacyName(name) && wanted.length && !sameSet(wanted, envelope.recipients))
|
|
81
91
|
add("RECIPIENT_DRIFT", `is sealed to ${keyList(envelope.recipients)}, its environment's rule names ${keyList(wanted)}; seal it again: starci app secret migrate ${env} ${member} --execute`);
|
|
@@ -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
|
|
|
@@ -65,9 +65,12 @@ function remote(c, block) {
|
|
|
65
65
|
if (block.releasesBase !== undefined && (!REMOTE_BASE.test(String(block.releasesBase)) || String(block.releasesBase).includes('..')))
|
|
66
66
|
c.problem('deploy.remote.releasesBase', 'must be an absolute path without ..');
|
|
67
67
|
let sealed = null;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
sealed
|
|
68
|
+
// One member holds VPS_HOST, VPS_USER, privateKey and knownHosts (`sealed: vps`); it plays all three SSH roles of the transport.
|
|
69
|
+
if (typeof block.sealed === 'string') {
|
|
70
|
+
nameField(c, 'deploy.remote.sealed', block.sealed);
|
|
71
|
+
sealed = Object.fromEntries(FIELDS.sealed.map((key) => [key, block.sealed]));
|
|
72
|
+
} else if (block.sealed !== undefined) {
|
|
73
|
+
c.problem('deploy.remote.sealed', 'names one member holding VPS_HOST, VPS_USER, privateKey and knownHosts (sealed: vps); fold a member per role into it with starci app secret migrate <env> <member> --to vps --into-existing');
|
|
71
74
|
}
|
|
72
75
|
return { host: block.host ?? 'vps', releasesBase: block.releasesBase ?? null, sealed, serverRecipient: block.serverRecipient ?? null };
|
|
73
76
|
}
|
|
@@ -264,6 +264,12 @@ const checkSecret=(secret,at,{envDir,environment,root,tracked,secretNames,add})=
|
|
|
264
264
|
add('encrypted-ref-invalid',`${at}.where`,'secret must resolve to <where>.enc.yaml (or a legacy <where>.enc) as a recognizable SOPS envelope, an existing regular file below the environment directory');
|
|
265
265
|
else if(nonempty(secret.key)&&!envelopeOf(fs.readFileSync(enc,'utf8')).keys.includes(secret.key))
|
|
266
266
|
add('encrypted-ref-invalid',`${at}.key`,`the member at ${secret.where} holds no ${secret.key}`);
|
|
267
|
+
else if(Array.isArray(secret.keys)){
|
|
268
|
+
// A grouped member declares its keys in one entry; each must be in the envelope, and one entry declares one key or a group, not both.
|
|
269
|
+
if(nonempty(secret.key))add('encrypted-ref-invalid',`${at}.keys`,'an entry declares one key (key) or a group (keys), not both');
|
|
270
|
+
const held=envelopeOf(fs.readFileSync(enc,'utf8')).keys;
|
|
271
|
+
for(const key of secret.keys.filter(key=>!held.includes(key)))add('encrypted-ref-invalid',`${at}.keys`,`the member at ${secret.where} holds no ${key}`);
|
|
272
|
+
}
|
|
267
273
|
if(nonempty(secret.where)&&!plain)
|
|
268
274
|
add('materialized-path-invalid',`${at}.where`,'secret plaintext path and its existing ancestors must remain below the environment directory without symlinks');
|
|
269
275
|
if(!String(secret.recipientPolicy??'').trim()||!String(secret.keyCustody??'').trim())
|
package/src/main.mjs
CHANGED
|
@@ -116,11 +116,11 @@ starci app db migrate [--execute] [--url-env <NAME>] [--json] [--cwd <dir>]
|
|
|
116
116
|
starci app db post-cutover [--execute] [--green-at <ISO> | --owner-confirms-old-app-gone] [--url-env <NAME>] [--json] [--cwd <dir>]
|
|
117
117
|
starci app db drift [--url-env <NAME>] [--json] [--cwd <dir>]
|
|
118
118
|
starci app release gate [--execute] [--source <ref>] [--tag-prefix <prefix>] [--backfill <tag>] [--json] [--cwd <dir>]
|
|
119
|
-
starci app release push [--execute] [--remote <name>] [--urgent --reason <text>
|
|
119
|
+
starci app release push [--execute] [--remote <name>] [--urgent --reason <text>] [--json] [--cwd <dir>]
|
|
120
120
|
starci app upgrade [--plan] [--cwd <dir>]
|
|
121
121
|
starci app stack <up|down|status> [--stack <dir>] [--services <list>] [--k3d] [--force] [--json] [--cwd <dir>]
|
|
122
122
|
starci app stack <prepare|doctor|connect|disconnect|build-args|render|deploy|converge|verify|rollback|prune|backup|jobs> --env <env> [--execute] [--json] [--cwd <dir>]
|
|
123
|
-
starci app stack deploy --env <env> --source-sha <sha> --
|
|
123
|
+
starci app stack deploy --env <env> --urgent (--reason <text> [--remote <name>] | --source-sha <sha> --image <service>=<ref>) [--db-url-env <NAME>] [--backup-out <dir>] [--first-start --db-service <service>] [--execute] [--json] [--cwd <dir>]
|
|
124
124
|
starci app explain <path> [--cwd <dir>] [--json]
|
|
125
125
|
starci app emit [--cwd <dir>]
|
|
126
126
|
starci app new service <dir> <name> [--inject <binding>...] [--cwd <dir>]
|
|
@@ -435,8 +435,8 @@ function declaredEdition(cwd) {
|
|
|
435
435
|
* `starci app stack`: the deploy actions (prepare, doctor, render, deploy, converge, verify, rollback, prune, backup, jobs, ...) are the Swarm
|
|
436
436
|
* tooling of stack/cli.mjs; up, down and status are the full edition's test-world infrastructure.
|
|
437
437
|
*/
|
|
438
|
-
async function stackAppMain(argv, { cwd, edition, stackMain, stdout: out, stderr: err, env, sops, hostIdentity, stackIo }) {
|
|
439
|
-
if (STACK_ACTIONS.includes(argv[0])) return deployStackMain(argv, { ...stackIo, cwd, stdout: out, stderr: err, env, hostIdentity, ...(sops ? { sops } : {}) });
|
|
438
|
+
async function stackAppMain(argv, { cwd, edition, stackMain, stdout: out, stderr: err, env, sops, hostIdentity, stackIo, harness }) {
|
|
439
|
+
if (STACK_ACTIONS.includes(argv[0])) return deployStackMain(argv, { ...stackIo, cwd, stdout: out, stderr: err, env, hostIdentity, harness, ...(sops ? { sops } : {}) });
|
|
440
440
|
if ((edition ?? declaredEdition(cwd)) === 'lite') throw new Error('starci app stack up|down|status manage the local test world of the full edition; a lite app starts its local database with npm run db:start');
|
|
441
441
|
const run = stackMain ?? await installedStackMain(cwd);
|
|
442
442
|
return run(argv, { cwd, out, err });
|
package/stack/cli.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { loadDeployConfig } from './config.mjs';
|
|
|
8
8
|
import { withDockerTransport } from './docker-transport.mjs';
|
|
9
9
|
import { StackError, EXIT, refusal } from './errors.mjs';
|
|
10
10
|
import { parseTargetBinding, bindStackTarget, nativeToolEnvironment } from './target-binding.mjs';
|
|
11
|
+
import { oneCommand, prepareUrgentRelease } from './urgent-release.mjs';
|
|
11
12
|
|
|
12
13
|
/** The actions that drive the docker CLI of the operator machine (pointed at the manager by docker-transport.mjs when the key is sealed). */
|
|
13
14
|
const DOCKER_ACTIONS = new Set(['deploy', 'accept', 'converge', 'verify', 'rollback', 'prune']);
|
|
@@ -15,7 +16,7 @@ const DOCKER_ACTIONS = new Set(['deploy', 'accept', 'converge', 'verify', 'rollb
|
|
|
15
16
|
export const ACTIONS = Object.freeze(['prepare', 'doctor', 'connect', 'disconnect', 'build-args', 'render', 'deploy', 'converge', 'verify', 'rollback', 'prune', 'backup', 'jobs', 'task', 'ingress', 'retire', 'build', 'accept']);
|
|
16
17
|
|
|
17
18
|
const BOOLEAN = new Set(['--execute', '--json', '--swarm-state', '--init-swarm', '--owner-approved', '--fix-live-restore', '--skip-public', '--skip-internal', '--allow-unpinned', '--push', '--urgent', '--first-start']);
|
|
18
|
-
const VALUE = new Set(['--env', '--image', '--source-sha', '--previous', '--out', '--release', '--since', '--timeout', '--retry', '--keep', '--app', '--ssh-cmd', '--extra-compose', '--project', '--target-binding', '--db-url-env', '--backup-out', '--db-service']);
|
|
19
|
+
const VALUE = new Set(['--env', '--image', '--source-sha', '--previous', '--out', '--release', '--since', '--timeout', '--retry', '--keep', '--app', '--ssh-cmd', '--extra-compose', '--project', '--target-binding', '--db-url-env', '--backup-out', '--db-service', '--reason', '--remote']);
|
|
19
20
|
const REPEAT = new Set(['--image', '--keep', '--extra-compose', '--project']);
|
|
20
21
|
|
|
21
22
|
/** Splits argv into { flags, positional }; an unknown flag or a flag without its value is a refusal. */
|
|
@@ -72,7 +73,7 @@ const OPTIONS = {
|
|
|
72
73
|
images: parseImages(flags.image), sourceSha: flags['source-sha'], execute: flags.execute === true,
|
|
73
74
|
out: flags.out ? path.resolve(cwd, flags.out) : null, timeoutSeconds: number(flags, 'timeout'), retrySeconds: number(flags, 'retry'), skipPublic: flags['skip-public'] === true,
|
|
74
75
|
urgent: flags.urgent === true, dbUrlEnv: flags['db-url-env'], backupOut: flags['backup-out'] ? path.resolve(cwd, flags['backup-out']) : undefined,
|
|
75
|
-
firstStart: flags['first-start'] === true, dbService: flags['db-service'],
|
|
76
|
+
firstStart: flags['first-start'] === true, dbService: flags['db-service'], reason: flags.reason, remote: flags.remote,
|
|
76
77
|
}),
|
|
77
78
|
converge: ({ flags }) => ({ since: flags.since, timeoutSeconds: number(flags, 'timeout') }),
|
|
78
79
|
verify: ({ flags }) => ({ retrySeconds: number(flags, 'retry'), skipPublic: flags['skip-public'] === true, skipInternal: flags['skip-internal'] === true }),
|
|
@@ -127,15 +128,27 @@ export async function stackMain(argv, io = {}) {
|
|
|
127
128
|
if (binding && (!['deploy', 'verify'].includes(action) || flags['ssh-cmd'] || flags['skip-public'] || flags['skip-internal']))
|
|
128
129
|
throw refusal('STACK_USAGE', 'the bound native consumer supports only complete deploy or verify');
|
|
129
130
|
const config = bindStackTarget(ctx, loadDeployConfig({ repoRoot: ctx.cwd, env: flags.env ?? 'production' }), binding);
|
|
130
|
-
if (action !== 'deploy' && (flags.urgent || flags['db-url-env'] || flags['backup-out'] || flags['first-start'] || flags['db-service'])) throw refusal('STACK_USAGE', '--urgent, --db-url-env, --backup-out, --first-start
|
|
131
|
+
if (action !== 'deploy' && (flags.urgent || flags['db-url-env'] || flags['backup-out'] || flags['first-start'] || flags['db-service'] || flags.reason || flags.remote)) throw refusal('STACK_USAGE', '--urgent, --db-url-env, --backup-out, --first-start, --db-service, --reason and --remote belong to deploy');
|
|
132
|
+
if (!flags.urgent && (flags.reason || flags.remote)) throw refusal('STACK_USAGE', '--reason and --remote release HEAD in the one-command urgent deploy: add --urgent');
|
|
131
133
|
if (!flags.urgent && (flags['first-start'] || flags['db-service'])) throw refusal('STACK_USAGE', '--first-start and --db-service are the first start of an empty database under the urgent floor: add --urgent');
|
|
132
134
|
if (action === 'deploy' && !flags.urgent && (flags['db-url-env'] || flags['backup-out'])) throw refusal('STACK_USAGE', '--db-url-env and --backup-out choose the urgent floor\'s database and backup folder: add --urgent');
|
|
133
|
-
|
|
135
|
+
let options = OPTIONS[action]({ flags, positional, cwd: ctx.cwd });
|
|
136
|
+
// The one-command urgent deploy releases HEAD and builds its images here, before the Docker transport reaches the server.
|
|
137
|
+
let prepared = null;
|
|
138
|
+
if (action === 'deploy' && oneCommand(options)) {
|
|
139
|
+
prepared = await prepareUrgentRelease(ctx, config, { ...options, role: io.harness?.role ?? ctx.env.STARCI_ROLE });
|
|
140
|
+
if (!prepared.images) {
|
|
141
|
+
print(ctx, action, flags, prepared);
|
|
142
|
+
return prepared.ok ? EXIT.ok : EXIT.failed;
|
|
143
|
+
}
|
|
144
|
+
options = { ...options, images: prepared.images, sourceSha: prepared.sourceSha };
|
|
145
|
+
}
|
|
134
146
|
const handler = await handlerOf(action, io.importer ?? ((file) => import(file)));
|
|
135
147
|
const sshCmd = flags['ssh-cmd'] ?? null;
|
|
136
148
|
const call = (context) => handler(context, config, { ...options, sshCmd });
|
|
137
149
|
const toolContext = nativeToolContext(ctx, binding);
|
|
138
|
-
const
|
|
150
|
+
const ran = DOCKER_ACTIONS.has(action) ? await withDockerTransport(toolContext, config, { sshCmd }, call) : await call(toolContext);
|
|
151
|
+
const result = prepared ? { ...ran, lines: [...prepared.lines, ...(ran.lines ?? [])] } : ran;
|
|
139
152
|
print(ctx, action, flags, result);
|
|
140
153
|
// A floor step of an urgent deploy that failed is a refusal with its own code (urgent-floor.mjs), printed after the lines that led to it.
|
|
141
154
|
if (result.refused) {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// urgent-release.mjs - the one-command urgent release (owner ruling urgent-typecheck-build, 2026-10-30):
|
|
2
|
+
// starci app stack deploy --env <env> --urgent --reason "<text>" [--execute]
|
|
3
|
+
// with no --image and no --source-sha takes HEAD from the laptop to the server in one command, CI not involved:
|
|
4
|
+
// 1. the urgent release of HEAD (release/urgent.mjs: typecheck and the build, tag, one atomic push, the urgent record), skipped when HEAD
|
|
5
|
+
// already has a pushed urgent record;
|
|
6
|
+
// 2. the images of that tag built and pushed on THIS machine's Docker (stack/build.mjs), which yields their digests;
|
|
7
|
+
// 3. the urgent deploy of those digests (stack/urgent-floor.mjs): backup, migrate preview then execute, deploy, verify, rollback on red.
|
|
8
|
+
// Steps 1 and 2 run before the deploy's Docker transport reaches the server, so nothing is ever built on the server. A dry run prints the
|
|
9
|
+
// urgent release plan and the build plan and stops: the deploy plan needs the digests the build makes.
|
|
10
|
+
import { buildImages } from './build.mjs';
|
|
11
|
+
import { refusal } from './errors.mjs';
|
|
12
|
+
import { git, releaseDir } from '../release/gate.mjs';
|
|
13
|
+
import { loadReleaseConfig } from '../release/index.mjs';
|
|
14
|
+
import { readUrgent } from '../release/records.mjs';
|
|
15
|
+
import { releaseUrgentPush } from '../release/urgent.mjs';
|
|
16
|
+
|
|
17
|
+
/** True when an urgent deploy names neither images nor a source commit: the one-command form. */
|
|
18
|
+
export const oneCommand = (options) => options.urgent === true && !options.sourceSha && Object.keys(options.images ?? {}).length === 0;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Steps 1 and 2 on the local machine. options: { execute, reason, role, remote }. Returns { ok, lines, data } to print when it stops (a dry run,
|
|
22
|
+
* a red step), or { ok: true, lines, images, sourceSha } for the deploy to continue with.
|
|
23
|
+
*/
|
|
24
|
+
export async function prepareUrgentRelease(ctx, config, options, deps = {}) {
|
|
25
|
+
const d = { buildImages, loadReleaseConfig, releaseUrgentPush, ...deps };
|
|
26
|
+
const head = git(ctx, ['rev-parse', 'HEAD']).stdout;
|
|
27
|
+
const lines = [`one-command urgent release of ${head.slice(0, 12)} (owner ruling urgent-typecheck-build): urgent release, local build and push, urgent deploy`];
|
|
28
|
+
const record = readUrgent(releaseDir(ctx), head);
|
|
29
|
+
if (record?.pushed === true) lines.push(`urgent release ${record.tag} of ${head.slice(0, 10)} already pushed: reused`);
|
|
30
|
+
else {
|
|
31
|
+
if (options.reason === undefined) throw refusal('STACK_URGENT_REASON_MISSING', 'the one-command urgent deploy releases HEAD first and says why: --reason "<text>"');
|
|
32
|
+
const pushed = await d.releaseUrgentPush(ctx, d.loadReleaseConfig(ctx.cwd), { execute: options.execute, reason: options.reason, role: options.role, remote: options.remote });
|
|
33
|
+
lines.push(...pushed.lines);
|
|
34
|
+
if (!pushed.ok) return { ok: false, lines, data: { head, step: 'release', ...pushed.data } };
|
|
35
|
+
if (options.execute !== true) {
|
|
36
|
+
lines.push('then: the images of that tag are built and pushed on this machine (stack build --push), then the urgent deploy runs the floor on their digests.');
|
|
37
|
+
return { ok: true, lines: [...lines, 'dry run: nothing tagged, built or deployed.'], data: { head, step: 'release', executed: false } };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const built = await d.buildImages(ctx, config, { push: true, execute: options.execute === true });
|
|
41
|
+
lines.push(...built.lines);
|
|
42
|
+
if (!built.ok) return { ok: false, lines, data: { head, step: 'build', ...built.data } };
|
|
43
|
+
if (options.execute !== true) return { ok: true, lines: [...lines, 'then: the urgent deploy runs the floor on the pushed digests.', 'dry run: nothing built or deployed.'], data: { head, step: 'build', executed: false } };
|
|
44
|
+
return { ok: true, lines, images: built.data.images, sourceSha: built.data.sha };
|
|
45
|
+
}
|
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
|
})
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
// lint-baseline.mjs - the lint row of an urgent release judged against a baseline release tag (`release push --urgent --lint-baseline <tag>`,
|
|
2
|
-
// owner ruling urgent-lint-baseline 2026-10-29: an app whose lint backlog predates the release ships when the release adds no finding of its own).
|
|
3
|
-
// The managed lint (`npm run lint`, which ends in `starci app lint`) runs twice, each writing its findings as a Sonar Generic Issue Import file
|
|
4
|
-
// (`-- --sonar <file>`): at HEAD, and at the baseline tag in a throwaway `git worktree` that borrows HEAD's installs (each node_modules folder is
|
|
5
|
-
// linked in as a directory junction, unlinked before the worktree is removed, never deleted through). A finding is the same finding when its
|
|
6
|
-
// engine, rule, file and message match (lines move); a finding left over is then matched on engine, rule and message alone (a file that moved).
|
|
7
|
-
// What HEAD holds beyond the baseline is new: zero new findings is green, any is red, and a lint that could not run on either side is red. The
|
|
8
|
-
// row names both counts and both reports with their sha256, and the new findings go to lint-new.json beside the record, so the back-fill's full
|
|
9
|
-
// gate (which this changes nothing in) still sees the whole backlog.
|
|
10
|
-
import { createHash, randomBytes } from 'node:crypto';
|
|
11
|
-
import fs from 'node:fs';
|
|
12
|
-
import os from 'node:os';
|
|
13
|
-
import path from 'node:path';
|
|
14
|
-
import { refusal } from '../stack/errors.mjs';
|
|
15
|
-
import { git, runGate } from './gate.mjs';
|
|
16
|
-
|
|
17
|
-
/** The owner's ruling a baseline-judged lint row cites. */
|
|
18
|
-
export const LINT_BASELINE_RULING = 'owner ruling urgent-lint-baseline 2026-10-29: an urgent release whose lint is red only with findings its baseline tag already had ships; a new finding is red';
|
|
19
|
-
const LINK_DEPTH = 3;
|
|
20
|
-
const NEW_SHOWN = 50;
|
|
21
|
-
|
|
22
|
-
const sha256 = (file) => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
23
|
-
|
|
24
|
-
/** The findings of a Sonar Generic Issue Import file as { engine, rule, file, line, message }, or null when it is missing or unreadable. */
|
|
25
|
-
export function sonarFindings(file) {
|
|
26
|
-
let doc;
|
|
27
|
-
try { doc = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
|
|
28
|
-
if (!doc || !Array.isArray(doc.issues)) return null;
|
|
29
|
-
return doc.issues.map((issue) => ({
|
|
30
|
-
engine: String(issue.engineId ?? ''), rule: String(issue.ruleId ?? ''), file: String(issue.primaryLocation?.filePath ?? ''),
|
|
31
|
-
line: issue.primaryLocation?.textRange?.startLine ?? null, message: String(issue.primaryLocation?.message ?? ''),
|
|
32
|
-
}));
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** The findings of `head` the `baseline` does not hold: matched on engine, rule, file and message, then the rest on engine, rule and message. */
|
|
36
|
-
export function newFindings(head, baseline) {
|
|
37
|
-
const take = (pool, key) => { const left = pool.get(key) ?? 0; if (left === 0) return false; pool.set(key, left - 1); return true; };
|
|
38
|
-
const exact = (finding) => `${finding.engine}\u0000${finding.rule}\u0000${finding.file}\u0000${finding.message}`;
|
|
39
|
-
const loose = (finding) => `${finding.engine}\u0000${finding.rule}\u0000${finding.message}`;
|
|
40
|
-
const exactPool = new Map();
|
|
41
|
-
for (const finding of baseline) exactPool.set(exact(finding), (exactPool.get(exact(finding)) ?? 0) + 1);
|
|
42
|
-
const unmatched = head.filter((finding) => !take(exactPool, exact(finding)));
|
|
43
|
-
const loosePool = new Map();
|
|
44
|
-
for (const finding of baseline) {
|
|
45
|
-
const left = exactPool.get(exact(finding)) ?? 0;
|
|
46
|
-
if (left > 0) { exactPool.set(exact(finding), left - 1); loosePool.set(loose(finding), (loosePool.get(loose(finding)) ?? 0) + 1); }
|
|
47
|
-
}
|
|
48
|
-
return unmatched.filter((finding) => !take(loosePool, loose(finding)));
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Every node_modules folder of `root` within LINK_DEPTH levels (never inside one), app-relative. */
|
|
52
|
-
function installFolders(root) {
|
|
53
|
-
const found = [];
|
|
54
|
-
const walk = (rel, depth) => {
|
|
55
|
-
let entries;
|
|
56
|
-
try { entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true }); } catch { return; }
|
|
57
|
-
for (const entry of entries) {
|
|
58
|
-
if (!entry.isDirectory() || entry.name === '.git') continue;
|
|
59
|
-
const child = rel ? path.join(rel, entry.name) : entry.name;
|
|
60
|
-
if (entry.name === 'node_modules') found.push(child);
|
|
61
|
-
else if (depth < LINK_DEPTH) walk(child, depth + 1);
|
|
62
|
-
}
|
|
63
|
-
};
|
|
64
|
-
walk('', 0);
|
|
65
|
-
return found;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Removes a link made by this module: the link alone, never what it points at. */
|
|
69
|
-
function unlink(link) {
|
|
70
|
-
try { fs.unlinkSync(link); } catch { try { fs.rmdirSync(link); } catch { /* already gone */ } }
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** The lint of `gate` with its findings written to `report`: { row, findings } (findings null when the lint could not run). */
|
|
74
|
-
function lintTo(ctx, gate, { name, report, dir, platform }) {
|
|
75
|
-
fs.rmSync(report, { force: true });
|
|
76
|
-
const row = runGate(ctx, { ...gate, name, command: [...gate.command, '--', '--sonar', report] }, { dir, platform, credentialNames: [] });
|
|
77
|
-
const ran = row.pass || row.detail === 'exit 1';
|
|
78
|
-
return { row, findings: ran ? sonarFindings(report) : null };
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* The lint row of an urgent release against `tag`: { name, command, pass, detail, log, logSha256, baseline }. Refuses a tag that is not a
|
|
83
|
-
* commit. `dir` is the record folder of HEAD, where both reports, both logs and lint-new.json are written.
|
|
84
|
-
*/
|
|
85
|
-
export function baselineLint(ctx, gate, { tag, dir, platform }) {
|
|
86
|
-
const commit = git(ctx, ['rev-parse', '--verify', '--quiet', `${tag}^{commit}`], { allowFail: true });
|
|
87
|
-
if (commit.code !== 0 || commit.stdout === '') throw refusal('RELEASE_URGENT_LINT_BASELINE_TAG', `--lint-baseline ${tag} names no commit`);
|
|
88
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
89
|
-
const headReport = path.join(dir, 'lint-head.sonar.json');
|
|
90
|
-
const head = lintTo(ctx, gate, { name: 'lint', report: headReport, dir, platform });
|
|
91
|
-
const row = (pass, detail, baseline = null) => ({ ...head.row, pass, detail, baseline: baseline && { tag, commit: commit.stdout, ruling: LINT_BASELINE_RULING, ...baseline } });
|
|
92
|
-
if (head.findings === null) return row(false, `the lint at HEAD could not run (${head.row.detail})`);
|
|
93
|
-
if (head.findings.length === 0) return row(true, 'no finding at HEAD', { findings: 0, headFindings: 0, newFindings: 0 });
|
|
94
|
-
const tree = path.join(os.tmpdir(), `starci-lint-baseline-${randomBytes(4).toString('hex')}`);
|
|
95
|
-
const links = [];
|
|
96
|
-
const added = git(ctx, ['worktree', 'add', '--detach', tree, commit.stdout], { allowFail: true });
|
|
97
|
-
if (added.code !== 0) return row(false, `the baseline worktree of ${tag} could not be made`);
|
|
98
|
-
try {
|
|
99
|
-
for (const rel of installFolders(ctx.cwd)) {
|
|
100
|
-
const link = path.join(tree, rel);
|
|
101
|
-
if (fs.existsSync(link) || !fs.existsSync(path.dirname(link))) continue;
|
|
102
|
-
fs.symlinkSync(path.join(ctx.cwd, rel), link, 'junction');
|
|
103
|
-
links.push(link);
|
|
104
|
-
}
|
|
105
|
-
const baseReport = path.join(dir, 'lint-baseline.sonar.json');
|
|
106
|
-
const base = lintTo(Object.create(ctx, { cwd: { value: tree } }), gate, { name: 'lint-baseline', report: baseReport, dir, platform });
|
|
107
|
-
if (base.findings === null) return row(false, `the lint at the baseline ${tag} could not run (${base.row.detail}; log ${base.row.log})`);
|
|
108
|
-
const fresh = newFindings(head.findings, base.findings);
|
|
109
|
-
fs.writeFileSync(path.join(dir, 'lint-new.json'), `${JSON.stringify(fresh, null, 2)}\n`);
|
|
110
|
-
const counts = {
|
|
111
|
-
findings: base.findings.length, headFindings: head.findings.length, newFindings: fresh.length,
|
|
112
|
-
headReport, headReportSha256: sha256(headReport), baselineReport: baseReport, baselineReportSha256: sha256(baseReport), baselineLog: base.row.log,
|
|
113
|
-
newShown: fresh.slice(0, NEW_SHOWN).map((finding) => `${finding.file}:${finding.line ?? '-'} ${finding.rule} ${finding.message}`),
|
|
114
|
-
};
|
|
115
|
-
const detail = `${head.findings.length} finding(s) at HEAD, ${base.findings.length} at ${tag}, ${fresh.length} new${fresh.length > 0 ? ` (${path.join(dir, 'lint-new.json')})` : ''}`;
|
|
116
|
-
return row(fresh.length === 0, detail, counts);
|
|
117
|
-
} finally {
|
|
118
|
-
links.reverse().forEach(unlink);
|
|
119
|
-
// A link still present would let the removal delete through it into HEAD's installs: the worktree then stays for a person to unlink.
|
|
120
|
-
if (links.every((link) => !fs.existsSync(link))) git(ctx, ['worktree', 'remove', '--force', tree], { allowFail: true });
|
|
121
|
-
else ctx.stderr?.(`lint baseline: ${tree} keeps a linked node_modules; unlink it (cmd /c rmdir <link>) before removing the worktree\n`);
|
|
122
|
-
}
|
|
123
|
-
}
|