feat(structures): add Region/Delegation/Structure schema + seed (ADR-0027 PR 1)
CI / commits (pull_request) Successful in 3m37s
CI / scan (pull_request) Successful in 3m53s
CI / check (pull_request) Failing after 4m0s
CI / a11y (pull_request) Successful in 3m37s
CI / perf (pull_request) Successful in 8m13s

Schema (Prisma): three new public-schema models per ADR-0027 -
Region (INSEE code PK), Delegation (dept code PK + regionCode FK),
Structure (portal-internal code PK + kind discriminator + nullable
unique finess/siret/codePaie + nullable delegationCode FK).

Migration: hand-written, matches the style of init_audit_schema and
users_directory. DDL + CHECK constraint on Structure.kind mirroring
STRUCTURE_KINDS + indexes + inline seed (Region 75 Nouvelle-Aquitaine,
Delegation 33 Gironde, structures 0330800013 + 0330800021 medico-social
Bordeaux/Merignac + siege APF national). Seed is the minimum the 19
test-tenant personas reference; ADR-0029's cascade sync supersedes it
when it ships.

Catalogue (TypeScript): apps/portal-bff/src/structures/structure-kind.ts
exports STRUCTURE_KINDS as const + StructureKind type union +
isStructureKind type guard. Jest spec covers catalogue content,
type guard, narrowing.

Drift gate: extended to scan property-literal "kind: 'X'" expressions
in files that import from structure-kind.ts. Three-layer defense
in depth for Structure.kind = TS type union + Postgres CHECK +
CI gate. 22 spec tests passing.

No consumer code yet - PrismaScopeResolver that dereferences
Structure.code from UserScope.value lives in ADR-0026 PR 2, which
depends on this PR landing first.

Reviewer heads-up: schema.prisma already has a User model (ADR-0020
user-directory cache); ADR-0026 PR 1 introduces a different User
(UUID PK + Person FK). Naming collision flagged for that PR to
resolve - not touched here.
This commit is contained in:
Julien Gautier
2026-05-26 11:12:19 +02:00
parent 670f6303fe
commit 9695c9080b
6 changed files with 515 additions and 9 deletions
+105 -9
View File
@@ -47,6 +47,16 @@ 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';
/**
* A file is only scanned for `Structure.kind` violations if it
* imports from the structure-kind module. Outside that context
* `kind` is a common property name 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['"]/;
/**
* Decorator name → catalogue array name. Adding a third decorator
@@ -131,6 +141,84 @@ export function extractCatalogues(sourceFilePath = CATALOGUE_PATH) {
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)) {
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 !== 'STRUCTURE_KINDS') 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 STRUCTURE_KINDS from ${sourceFilePath}` +
`the script expected a top-level "export const STRUCTURE_KINDS = [...] as const" declaration.`,
);
}
/**
* 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) {
const text = sourceText ?? readFileSync(filePath, 'utf8');
if (!STRUCTURE_KIND_IMPORT_PATTERN.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 isKindKey =
(ts.isIdentifier(name) && name.text === 'kind') ||
(ts.isStringLiteral(name) && name.text === 'kind');
if (isKindKey) {
const init = node.initializer;
if (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) {
if (!validKinds.has(init.text)) {
const { line, character } = sourceFile.getLineAndCharacterOfPosition(init.getStart());
violations.push({
file: filePath,
line: line + 1,
column: character + 1,
callee: 'Structure.kind',
value: init.text,
catalogue: 'STRUCTURE_KINDS',
});
}
}
}
}
ts.forEachChild(node, visit);
}
visit(sourceFile);
return violations;
}
/**
* Walk `dir` recursively and yield every `.ts` file path
* (excluding declaration files and the dirs listed in
@@ -213,24 +301,27 @@ 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 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));
}
}
return { violations: out, catalogues };
return { violations: out, catalogues, structureKinds };
}
function main() {
const { violations, catalogues } = scanWorkspace();
const { violations, catalogues, structureKinds } = scanWorkspace();
if (violations.length === 0) {
const privCount = catalogues.PRIVILEGES.size;
const roleCount = catalogues.FUNCTIONAL_ROLES.size;
const kindCount = structureKinds.size;
console.log(
`catalogue-drift: clean (catalogues: ${privCount} privileges, ${roleCount} roles).`,
`catalogue-drift: clean (catalogues: ${privCount} privileges, ${roleCount} roles, ${kindCount} structure kinds).`,
);
process.exit(0);
}
@@ -249,16 +340,21 @@ function main() {
const rel = relative(WORKSPACE_ROOT, file).replaceAll('\\', '/');
console.error(` ${rel}`);
for (const v of list) {
console.error(
` ${v.line}:${v.column} @${v.callee}('${v.value}') — not in ${v.catalogue}`,
);
// 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. To add a value, amend ` +
`the ADR and the corresponding constant in ` +
`libs/shared/auth/src/lib/authorization.types.ts.`,
`Catalogues are closed in v1 per ADR-0025 (PRIVILEGES / FUNCTIONAL_ROLES) ` +
`and ADR-0027 (STRUCTURE_KINDS). To add a value, amend the ADR and the ` +
`corresponding constant in libs/shared/auth/src/lib/authorization.types.ts ` +
`or apps/portal-bff/src/structures/structure-kind.ts.`,
);
process.exit(1);
}