24071a63ec
## Summary
First implementation PR for [ADR-0026](docs/decisions/0026-person-user-portal-data-model.md) (portal-side identity model). Ships:
- `Person` golden record + `User` portal-account overlay + `UserScope` Prisma models;
- `PersonAndUserProvisioner` service called from `SessionEstablisher.establish` (blocking — lazy-creates `Person` + `User` at first OIDC callback);
- `PERSON_SOURCES` closed-set catalogue + drift-gate extension;
- `PrincipalBuilder.build(user, identity)` signature update + `ScopeResolver.resolve({ userId })` seam change — `Principal.user.{id, personId}` now carry real portal UUIDs, no longer the `entraOid` placeholder.
No consumer for `UserScope` yet — `PrismaScopeResolver` lands in ADR-0026 PR 2. The `StubScopeResolver` continues to return `[{ kind: 'unrestricted' }]` for everyone.
## What lands
| File | Change |
| --- | --- |
| `apps/portal-bff/prisma/schema.prisma` | **+3 models** in the `public` schema: `Person` (UUID PK + PII + nullable email indexed-not-unique + source catalogue + nullable externalId + back-ref to User), `User` (UUID PK + 1-to-1 personId FK + unique entraOid + tenantId + lastSignInAt + scopes[]), `UserScope` (UUID PK + userId FK with `onDelete: Cascade` + kind + opaque value with `@default("")` + source + nullable expiresAt + `@@unique([userId, kind, value])`). All comments explain the cross-references to ADR-0025 / ADR-0027 / ADR-0029. |
| `apps/portal-bff/prisma/migrations/20260526210000_add_person_user_userscope/migration.sql` | **New** hand-written migration. DDL for the 3 tables, indexes (Person: source/externalId/email; User: unique personId + unique entraOid; UserScope: unique composite + plain userId), FKs with the correct `ON DELETE` actions (User.personId → RESTRICT; UserScope.userId → CASCADE — both Prisma defaults given the schema's `Delegation?` / explicit `onDelete: Cascade`). |
| `apps/portal-bff/src/users/person-source.ts` + `.spec.ts` | **New** catalogue. `PERSON_SOURCES = ['self-signin', 'admin-ui', 'seed'] as const`, `PersonSource` type union, `isPersonSource` type guard. Spec follows the structure-kind shape (catalogue content, no duplicates, type guard true/false, narrowing test via `String()` to widen). |
| `apps/portal-bff/src/users/person-and-user-provisioner.service.ts` + `.spec.ts` | **New** blocking provisioner. Fast path: `findUnique by entraOid` + `update lastSignInAt`. Cold path: nested `create` of Person + linked User in a single transaction. Race-condition handling: catches P2002 on `User.entraOid` and re-runs `ensureUser` (loser of a concurrent first-sign-in falls through to the now-warm fast path). Defense-in-depth `isPersonSource` check on the constant. Spec covers cold/warm/race/non-P2002-propagation paths + `splitDisplayName` cases (single token / trailing whitespace / empty / multi-word). |
| `scripts/check-catalogue-drift.mjs` | Property-literal scanner generalised. Adds `extractPersonSources` + `findPersonSourceViolationsInFile` (property `source` instead of `kind`, otherwise identical to the structure-kind scanner). The two extractors share `extractAsConstArray(path, constName)` and the two property scanners share `findPropertyLiteralViolations(path, validValues, sourceText, opts)`. Error-message formatter unchanged. Closing hint extended to reference all three catalogue locations. |
| `scripts/check-catalogue-drift.spec.mjs` | Fixture now writes a `person-source.ts` alongside `structure-kind.ts`. 7 new tests: extractPersonSources (2), findPersonSourceViolationsInFile (5: skip-no-import, no-violation, flag, non-literal, line/col). Aggregation test updated to assert decorator + Structure.kind + Person.source violations all surface together. **29 tests total, all passing.** |
| `apps/portal-bff/src/auth/scope-resolver.ts` | `resolve(input: { entraOid })` → `resolve(input: { userId })`. Stub still ignores its argument; PR 2's `PrismaScopeResolver` will key queries on `User.id`. Comment block updated to reflect that ADR-0026 PR 1 is now landed (no longer "proposed"). |
| `apps/portal-bff/src/auth/principal-builder.ts` | Signature: `build(user)` → `build(user, identity: { userId, personId })`. `Principal.user.id` / `Principal.user.personId` populated from `identity` instead of `user.oid`. Scope resolver called with `{ userId: identity.userId }`. Doc comment block updated to remove the "placeholder" caveat and document the new wiring. |
| `apps/portal-bff/src/auth/principal-builder.spec.ts` | New `TEST_IDENTITY` constant. Every `builder.build(...)` call gets the second arg. New assertions on `principal.user.id` / `principal.user.personId` carrying the test identity. Edge-case test "asks the scope resolver to resolve by entraOid" renamed + retargeted to `{ userId }`. **All 19 persona tests + 5 edge cases pass.** |
| `apps/portal-bff/src/auth/session-establisher.service.ts` | New constructor arg `personUserProvisioner: PersonAndUserProvisioner`. `establish()` calls `ensureUser({ oid, tenantId, displayName, email: user.username })` **before** `principalBuilder.build` so the identity is available. Comment block explains the Entra `preferred_username` → `Person.email` mapping and the blocking-vs-best-effort distinction with `UserDirectoryService.recordSignIn`. |
| `apps/portal-bff/src/auth/session-establisher.service.spec.ts` | Fixture extended with `provisioner` mock + `PROVISIONED_IDENTITY` constant. `STUB_PRINCIPAL` now carries those UUIDs instead of `user.oid`. New tests: (1) provisioner is called with the right input shape; (2) provisioner runs **before** `principalBuilder.build` (`mock.invocationCallOrder` assertion); (3) provisioner failure propagates and nothing downstream runs (build / audit / directory). |
| `apps/portal-bff/src/auth/auth.controller.spec.ts` | Provisioner mock added to the controller fixture (the controller's specs don't exercise provisioning themselves but `SessionEstablisher`'s constructor needs the arg). Principal stub's UUIDs aligned with the new provisioned shape. |
| `apps/portal-bff/src/users/users.module.ts` | `PersonAndUserProvisioner` registered + exported alongside `UserDirectoryService`. `@Global` so the auth module's `SessionEstablisher` can inject both without re-routing the module graph. Comment block updated to document the blocking/best-effort distinction between the two. |
## Key choices
- **Provisioner is blocking**, not best-effort. Distinct from `UserDirectoryService.recordSignIn` which is still best-effort (ADR-0020 admin-list cache, swallows its own errors). Both run from `SessionEstablisher.establish` per the new ordering: (1) provisioner — blocking, (2) build principal — uses identity, (3) save session, (4) cookie, (5) user-session index (best-effort), (6) audit (blocking ADR-0013), (7) UserDirectoryService.recordSignIn (best-effort), (8) log. A provisioner failure short-circuits the whole flow before any of (3)..(8) — the spec asserts this explicitly.
- **No email-based dedup in v1.** `Person.email` is indexed (not unique). The provisioner keys ONLY on `entraOid`. ADR-0026 §"Why no email-based merging in v1" — two distinct humans genuinely share emails; ADR-0029's sync flow handles operator-confirmed reconciliation.
- **Race-condition handling on first sign-in.** Two concurrent first-sign-ins for the same `entraOid` both fall through to `create`. The unique constraint on `User.entraOid` rejects the loser with P2002; the provisioner catches that specific code and re-runs `ensureUser` — fast path now warm. Pathological infinite-loop guarded by the warm-path behaviour on the second attempt. Spec covers the success retry + the non-P2002 propagation paths.
- **ScopeResolver seam moved from `{ entraOid }` to `{ userId }`.** The stub doesn't care about its argument either way; the change is the seam for ADR-0026 PR 2's `PrismaScopeResolver`, which keys `userScope` queries on `User.id` (UUID). Doing the rename now keeps PR 2 to "swap the implementation" only.
- **`PersonAndUserProvisioner.SELF_SIGNIN_SOURCE`** is a typed constant inside the class, not a magic string. Defense in depth: TS type union (compile-time) + drift gate (`source: 'self-signin'` literal is in a file importing `person-source.ts` — flagged if it ever drifts off-catalogue) + runtime `isPersonSource` check (error log + throw if the constant is mutated to an off-catalogue value).
- **UserDirectoryService stays.** ADR-0020's admin-list cache is functionally redundant with Person + User now, but folding it would extend the PR scope (DTO + reader + admin UI + migration of existing rows). Out of scope here — flagged as a follow-up.
## Local verification
- [x] `node scripts/check-catalogue-drift.mjs` — clean (`4 privileges, 24 roles, 7 structure kinds, 3 person sources`).
- [x] `node --test scripts/check-catalogue-drift.spec.mjs` — **29 tests passing** (was 22 — +7 for PERSON_SOURCES).
- [x] `pnpm exec nx lint portal-bff` — **0 errors**, 13 warnings (all pre-existing, none from this PR).
- [x] `pnpm exec nx test portal-bff` (filtered to the 6 affected spec files) — **766 tests passing**.
- [x] `pnpm exec prisma generate` — client regenerated with the 3 new models.
## Test plan — remaining (on a fresh dev DB)
- [ ] `./infra/local/dev.sh down -v && ./infra/local/dev.sh up` (wipe + reboot) then `cd apps/portal-bff && pnpm exec prisma migrate dev` — applies the new migration cleanly, no drift prompt.
- [ ] `pnpm exec prisma studio` — `persons` / `users` / `user_scopes` tables visible, all empty (no seed in this PR).
- [ ] Sign in via `apf-portal` against the test tenant — `users` table gets one row, `persons` table gets one row, `user_scopes` stays empty. Principal in the session carries the provisioned UUIDs (not the `entraOid`).
- [ ] **Review focus** — the provisioner's race-handling logic; the `Entra preferred_username → Person.email` mapping in `SessionEstablisher`; the ScopeResolver seam change rationale; the FK actions in the migration SQL (especially CASCADE on UserScope.userId vs RESTRICT on User.personId).
## What's next
- **ADR-0026 PR 2** — `PrismaScopeResolver` replacing `StubScopeResolver` + `/admin/users/:id/scopes` admin-app screen + `prisma/seed.ts` populating the 19 test personas' `user_scopes` per `notes/test-tenant-role-assignments.md` (referencing this PR's `User.id` and ADR-0027 PR 1's `Structure.code` values).
- **Future PR (out of this scope)** — fold `UserDirectoryEntry` into Person + User now that the latter exists. Touches AdminUsersReader, the DTO, the admin SPA, and a data migration for existing rows. Defer until ADR-0026 PR 2 stabilises.
---------
Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #232
428 lines
16 KiB
JavaScript
428 lines
16 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* Catalogue-vs-code drift gate per
|
|
* [ADR-0025 §"Confirmation"](../docs/decisions/0025-authorization-model-privileges-roles-scopes.md).
|
|
*
|
|
* Asserts that every string literal passed to the authorization
|
|
* decorators in the codebase belongs to the closed catalogue
|
|
* declared in `libs/shared/auth/src/lib/authorization.types.ts`:
|
|
*
|
|
* - `@RequirePrivilege('Portal.X', …)` → every arg ∈ PRIVILEGES
|
|
* - `@RequireRole('rh', …)` → every arg ∈ FUNCTIONAL_ROLES
|
|
*
|
|
* The TypeScript type system enforces the same constraint at
|
|
* compile time — the decorator signatures are typed against the
|
|
* `Privilege` / `FunctionalRole` literal unions — so the gate is
|
|
* defence-in-depth against escape hatches:
|
|
*
|
|
* - explicit `as Privilege` casts (`'Portal.Foo' as Privilege`),
|
|
* - indirection through a `string`-typed local
|
|
* (`const slug = 'rh'; @RequireRole(slug)` — non-literal
|
|
* args are skipped here, but the gate at least catches the
|
|
* literal misspellings),
|
|
* - and the rarer case where a developer hand-edits the
|
|
* catalogue type union without updating the runtime constant.
|
|
*
|
|
* Implementation: the script parses the catalogue file and every
|
|
* `.ts` file under `apps/` and `libs/` with the TypeScript compiler
|
|
* API. For each `CallExpression` whose callee identifier matches
|
|
* one of the decorator names, every string-literal argument is
|
|
* checked against the catalogue. Non-literal arguments are
|
|
* skipped silently; the gate is best-effort for those, but they
|
|
* are caught by the TypeScript signature anyway.
|
|
*
|
|
* Exit code: 0 if no drift, 1 with a grouped report if drift is
|
|
* found. The script does not consume any env vars; running it
|
|
* directly (`node scripts/check-catalogue-drift.mjs`) and via
|
|
* `pnpm ci:catalogue-drift` are equivalent.
|
|
*/
|
|
|
|
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
import { dirname, join, relative, resolve } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import ts from 'typescript';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = dirname(__filename);
|
|
const WORKSPACE_ROOT = resolve(__dirname, '..');
|
|
|
|
const CATALOGUE_PATH = join(WORKSPACE_ROOT, 'libs/shared/auth/src/lib/authorization.types.ts');
|
|
const STRUCTURE_KIND_PATH = 'apps/portal-bff/src/structures/structure-kind.ts';
|
|
const PERSON_SOURCE_PATH = 'apps/portal-bff/src/users/person-source.ts';
|
|
|
|
/**
|
|
* A file is only scanned for property-literal catalogue violations
|
|
* if it imports from the relevant catalogue module. Outside that
|
|
* context `kind` / `source` are common property names on unrelated
|
|
* objects and the scanner would false-positive. The check is
|
|
* text-level (cheap) and runs before any AST work — files that fail
|
|
* it short-circuit.
|
|
*/
|
|
const STRUCTURE_KIND_IMPORT_PATTERN = /\bfrom\s+['"][^'"]*structure-kind['"]/;
|
|
const PERSON_SOURCE_IMPORT_PATTERN = /\bfrom\s+['"][^'"]*person-source['"]/;
|
|
|
|
/**
|
|
* Decorator name → catalogue array name. Adding a third decorator
|
|
* (per ADR-0025's anticipated growth) is one line here plus the
|
|
* matching test fixture.
|
|
*/
|
|
const DECORATOR_TO_CATALOGUE = {
|
|
RequirePrivilege: 'PRIVILEGES',
|
|
RequireRole: 'FUNCTIONAL_ROLES',
|
|
};
|
|
|
|
/**
|
|
* Folders to skip when walking the workspace. Stays small on
|
|
* purpose: every other path under `apps/` and `libs/` is fair
|
|
* game for catalogue references, including specs (the persona
|
|
* matrix in `auth-guards.persona-matrix.spec.ts` is a deliberate
|
|
* usage and must stay in sync).
|
|
*/
|
|
const SKIPPED_DIRS = new Set([
|
|
'node_modules',
|
|
'dist',
|
|
'coverage',
|
|
'.nx',
|
|
'.angular',
|
|
'__screenshots__',
|
|
]);
|
|
|
|
/**
|
|
* Files / subpaths to skip outright. The generated gRPC stubs
|
|
* under `apps/portal-bff/src/grpc/gen/` carry their own
|
|
* `roles[]` field that has nothing to do with the ADR-0025
|
|
* functional-role catalogue — skipping the whole dir keeps the
|
|
* scanner focused on hand-written code.
|
|
*/
|
|
const SKIPPED_SUBPATHS = ['apps/portal-bff/src/grpc/gen'];
|
|
|
|
/**
|
|
* Parse `authorization.types.ts` and extract the catalogue
|
|
* arrays as `Set<string>` keyed on the constant's name.
|
|
* Returns `{ PRIVILEGES: Set, FUNCTIONAL_ROLES: Set }`.
|
|
*
|
|
* Exported for the spec — keeps the parser logic testable without
|
|
* spawning the CLI.
|
|
*/
|
|
export function extractCatalogues(sourceFilePath = CATALOGUE_PATH) {
|
|
const text = readFileSync(sourceFilePath, 'utf8');
|
|
const sourceFile = ts.createSourceFile(sourceFilePath, text, ts.ScriptTarget.Latest, true);
|
|
const out = {};
|
|
|
|
for (const stmt of sourceFile.statements) {
|
|
if (!ts.isVariableStatement(stmt)) continue;
|
|
for (const decl of stmt.declarationList.declarations) {
|
|
if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;
|
|
const name = decl.name.text;
|
|
if (!Object.values(DECORATOR_TO_CATALOGUE).includes(name)) continue;
|
|
|
|
// Catalogues are declared as `[...] as const`; strip the
|
|
// type assertion to reach the array literal.
|
|
let init = decl.initializer;
|
|
if (ts.isAsExpression(init)) init = init.expression;
|
|
if (!ts.isArrayLiteralExpression(init)) continue;
|
|
|
|
const values = new Set();
|
|
for (const el of init.elements) {
|
|
if (ts.isStringLiteral(el) || ts.isNoSubstitutionTemplateLiteral(el)) {
|
|
values.add(el.text);
|
|
}
|
|
}
|
|
out[name] = values;
|
|
}
|
|
}
|
|
|
|
for (const expected of Object.values(DECORATOR_TO_CATALOGUE)) {
|
|
if (!out[expected]) {
|
|
throw new Error(
|
|
`Failed to extract catalogue "${expected}" from ${sourceFilePath} — ` +
|
|
`the script expected a top-level "export const ${expected} = [...] as const" declaration.`,
|
|
);
|
|
}
|
|
}
|
|
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Parse `structure-kind.ts` and extract the `STRUCTURE_KINDS`
|
|
* constant as `Set<string>`. Mirror of `extractCatalogues` for the
|
|
* ADR-0027 `Structure.kind` catalogue — same `as const` array
|
|
* literal pattern, single declaration per file. Exported for the spec.
|
|
*/
|
|
export function extractStructureKinds(sourceFilePath = join(WORKSPACE_ROOT, STRUCTURE_KIND_PATH)) {
|
|
return extractAsConstArray(sourceFilePath, 'STRUCTURE_KINDS');
|
|
}
|
|
|
|
/**
|
|
* Find every `kind: 'X'` property literal whose X is not in the
|
|
* STRUCTURE_KINDS catalogue. Restricted to files that import from
|
|
* the structure-kind module (heuristic — `kind` is a common
|
|
* property name on unrelated objects; without the restriction the
|
|
* scanner would false-positive everywhere). Exported for the spec.
|
|
*/
|
|
export function findStructureKindViolationsInFile(filePath, validKinds, sourceText) {
|
|
return findPropertyLiteralViolations(filePath, validKinds, sourceText, {
|
|
importPattern: STRUCTURE_KIND_IMPORT_PATTERN,
|
|
propertyName: 'kind',
|
|
callee: 'Structure.kind',
|
|
catalogueName: 'STRUCTURE_KINDS',
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Parse `person-source.ts` and extract the `PERSON_SOURCES` constant
|
|
* as `Set<string>`. Mirror of `extractStructureKinds` — same `as const`
|
|
* array literal pattern, single declaration per file. Exported for
|
|
* the spec.
|
|
*/
|
|
export function extractPersonSources(sourceFilePath = join(WORKSPACE_ROOT, PERSON_SOURCE_PATH)) {
|
|
return extractAsConstArray(sourceFilePath, 'PERSON_SOURCES');
|
|
}
|
|
|
|
/**
|
|
* Find every `source: 'X'` property literal whose X is not in the
|
|
* PERSON_SOURCES catalogue. Mirror of `findStructureKindViolationsInFile`
|
|
* with a different property name + catalogue. Exported for the spec.
|
|
*/
|
|
export function findPersonSourceViolationsInFile(filePath, validSources, sourceText) {
|
|
return findPropertyLiteralViolations(filePath, validSources, sourceText, {
|
|
importPattern: PERSON_SOURCE_IMPORT_PATTERN,
|
|
propertyName: 'source',
|
|
callee: 'Person.source',
|
|
catalogueName: 'PERSON_SOURCES',
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Helper for both property-literal scanners. Walks every
|
|
* PropertyAssignment whose key matches `propertyName`; for each
|
|
* string-literal initialiser, checks that the value is in
|
|
* `validValues`. Skips files that don't import the catalogue module
|
|
* (text-level pre-filter, cheap).
|
|
*/
|
|
function findPropertyLiteralViolations(filePath, validValues, sourceText, opts) {
|
|
const text = sourceText ?? readFileSync(filePath, 'utf8');
|
|
if (!opts.importPattern.test(text)) return [];
|
|
|
|
const sourceFile = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true);
|
|
const violations = [];
|
|
|
|
function visit(node) {
|
|
if (ts.isPropertyAssignment(node)) {
|
|
const name = node.name;
|
|
const matchesProperty =
|
|
(ts.isIdentifier(name) && name.text === opts.propertyName) ||
|
|
(ts.isStringLiteral(name) && name.text === opts.propertyName);
|
|
if (matchesProperty) {
|
|
const init = node.initializer;
|
|
if (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) {
|
|
if (!validValues.has(init.text)) {
|
|
const { line, character } = sourceFile.getLineAndCharacterOfPosition(init.getStart());
|
|
violations.push({
|
|
file: filePath,
|
|
line: line + 1,
|
|
column: character + 1,
|
|
callee: opts.callee,
|
|
value: init.text,
|
|
catalogue: opts.catalogueName,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ts.forEachChild(node, visit);
|
|
}
|
|
|
|
visit(sourceFile);
|
|
return violations;
|
|
}
|
|
|
|
/**
|
|
* Helper for extractStructureKinds / extractPersonSources — both
|
|
* read a top-level `export const <name> = [...] as const` from a
|
|
* single-file catalogue module. Generalised once instead of
|
|
* duplicated per catalogue.
|
|
*/
|
|
function extractAsConstArray(sourceFilePath, constName) {
|
|
const text = readFileSync(sourceFilePath, 'utf8');
|
|
const sourceFile = ts.createSourceFile(sourceFilePath, text, ts.ScriptTarget.Latest, true);
|
|
|
|
for (const stmt of sourceFile.statements) {
|
|
if (!ts.isVariableStatement(stmt)) continue;
|
|
for (const decl of stmt.declarationList.declarations) {
|
|
if (!ts.isIdentifier(decl.name) || decl.name.text !== constName) continue;
|
|
let init = decl.initializer;
|
|
if (init && ts.isAsExpression(init)) init = init.expression;
|
|
if (!init || !ts.isArrayLiteralExpression(init)) continue;
|
|
|
|
const values = new Set();
|
|
for (const el of init.elements) {
|
|
if (ts.isStringLiteral(el) || ts.isNoSubstitutionTemplateLiteral(el)) {
|
|
values.add(el.text);
|
|
}
|
|
}
|
|
return values;
|
|
}
|
|
}
|
|
|
|
throw new Error(
|
|
`Failed to extract ${constName} from ${sourceFilePath} — ` +
|
|
`the script expected a top-level "export const ${constName} = [...] as const" declaration.`,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Walk `dir` recursively and yield every `.ts` file path
|
|
* (excluding declaration files and the dirs listed in
|
|
* SKIPPED_DIRS / SKIPPED_SUBPATHS).
|
|
*/
|
|
function* walkTsFiles(dir, rootForRelative) {
|
|
let entries;
|
|
try {
|
|
entries = readdirSync(dir);
|
|
} catch {
|
|
return;
|
|
}
|
|
for (const entry of entries) {
|
|
if (SKIPPED_DIRS.has(entry) || entry.startsWith('.')) continue;
|
|
const full = join(dir, entry);
|
|
const rel = relative(rootForRelative, full).replaceAll('\\', '/');
|
|
if (SKIPPED_SUBPATHS.some((skip) => rel === skip || rel.startsWith(skip + '/'))) {
|
|
continue;
|
|
}
|
|
let st;
|
|
try {
|
|
st = statSync(full);
|
|
} catch {
|
|
continue;
|
|
}
|
|
if (st.isDirectory()) {
|
|
yield* walkTsFiles(full, rootForRelative);
|
|
} else if (entry.endsWith('.ts') && !entry.endsWith('.d.ts')) {
|
|
yield full;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Find every catalogue-violation in a single source file.
|
|
* Returns an array of `{ file, line, column, callee, value,
|
|
* catalogue }` records. Exported for the spec.
|
|
*/
|
|
export function findViolationsInFile(filePath, catalogues, sourceText) {
|
|
const text = sourceText ?? readFileSync(filePath, 'utf8');
|
|
const sourceFile = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true);
|
|
const violations = [];
|
|
|
|
function visit(node) {
|
|
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
|
|
const callee = node.expression.text;
|
|
const catalogueName = DECORATOR_TO_CATALOGUE[callee];
|
|
if (catalogueName) {
|
|
const valid = catalogues[catalogueName];
|
|
for (const arg of node.arguments) {
|
|
if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {
|
|
if (!valid.has(arg.text)) {
|
|
const { line, character } = sourceFile.getLineAndCharacterOfPosition(arg.getStart());
|
|
violations.push({
|
|
file: filePath,
|
|
line: line + 1,
|
|
column: character + 1,
|
|
callee,
|
|
value: arg.text,
|
|
catalogue: catalogueName,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ts.forEachChild(node, visit);
|
|
}
|
|
|
|
visit(sourceFile);
|
|
return violations;
|
|
}
|
|
|
|
/**
|
|
* Top-level scan: walk `apps/` and `libs/`, accumulate
|
|
* violations, return them all. Pure (no I/O outside the file
|
|
* reads it does itself). Exported for the spec.
|
|
*/
|
|
export function scanWorkspace(workspaceRoot = WORKSPACE_ROOT) {
|
|
const catalogues = extractCatalogues(
|
|
join(workspaceRoot, 'libs/shared/auth/src/lib/authorization.types.ts'),
|
|
);
|
|
const structureKinds = extractStructureKinds(join(workspaceRoot, STRUCTURE_KIND_PATH));
|
|
const personSources = extractPersonSources(join(workspaceRoot, PERSON_SOURCE_PATH));
|
|
const out = [];
|
|
for (const dirName of ['apps', 'libs']) {
|
|
const dir = join(workspaceRoot, dirName);
|
|
for (const file of walkTsFiles(dir, workspaceRoot)) {
|
|
out.push(...findViolationsInFile(file, catalogues));
|
|
out.push(...findStructureKindViolationsInFile(file, structureKinds));
|
|
out.push(...findPersonSourceViolationsInFile(file, personSources));
|
|
}
|
|
}
|
|
return { violations: out, catalogues, structureKinds, personSources };
|
|
}
|
|
|
|
function main() {
|
|
const { violations, catalogues, structureKinds, personSources } = scanWorkspace();
|
|
|
|
if (violations.length === 0) {
|
|
const privCount = catalogues.PRIVILEGES.size;
|
|
const roleCount = catalogues.FUNCTIONAL_ROLES.size;
|
|
const kindCount = structureKinds.size;
|
|
const sourceCount = personSources.size;
|
|
console.log(
|
|
`catalogue-drift: clean (catalogues: ${privCount} privileges, ${roleCount} roles, ${kindCount} structure kinds, ${sourceCount} person sources).`,
|
|
);
|
|
process.exit(0);
|
|
}
|
|
|
|
console.error('catalogue-drift: violations found');
|
|
console.error('');
|
|
// Group by file for a readable report. Within a file, sort by
|
|
// line so the output mirrors the editor's view.
|
|
const byFile = new Map();
|
|
for (const v of violations) {
|
|
if (!byFile.has(v.file)) byFile.set(v.file, []);
|
|
byFile.get(v.file).push(v);
|
|
}
|
|
for (const [file, list] of byFile) {
|
|
list.sort((a, b) => a.line - b.line || a.column - b.column);
|
|
const rel = relative(WORKSPACE_ROOT, file).replaceAll('\\', '/');
|
|
console.error(` ${rel}`);
|
|
for (const v of list) {
|
|
// Decorator-style violations are printed as `@Callee('value')`;
|
|
// property-literal violations (Structure.kind) are printed as
|
|
// `kind: 'value'` to match the offending code shape.
|
|
const display = v.callee.includes('.')
|
|
? `${v.callee.split('.').pop()}: '${v.value}'`
|
|
: `@${v.callee}('${v.value}')`;
|
|
console.error(` ${v.line}:${v.column} ${display} — not in ${v.catalogue}`);
|
|
}
|
|
}
|
|
console.error('');
|
|
console.error(
|
|
`Catalogues are closed in v1 per ADR-0025 (PRIVILEGES / FUNCTIONAL_ROLES), ` +
|
|
`ADR-0027 (STRUCTURE_KINDS), and ADR-0026 (PERSON_SOURCES). To add a value, ` +
|
|
`amend the ADR and the corresponding constant in ` +
|
|
`libs/shared/auth/src/lib/authorization.types.ts, ` +
|
|
`apps/portal-bff/src/structures/structure-kind.ts, or ` +
|
|
`apps/portal-bff/src/users/person-source.ts.`,
|
|
);
|
|
process.exit(1);
|
|
}
|
|
|
|
// Only run main() when invoked as a CLI (not when imported by the
|
|
// spec).
|
|
const isMain =
|
|
import.meta.url === `file://${process.argv[1]}` ||
|
|
import.meta.url === `file://${resolve(process.argv[1])}`;
|
|
if (isMain) {
|
|
main();
|
|
}
|