feat(users): add Person + User + UserScope + lazy provisioner (ADR-0026 PR 1)
CI / scan (pull_request) Successful in 5m32s
CI / commits (pull_request) Successful in 5m34s
CI / check (pull_request) Successful in 6m8s
CI / a11y (pull_request) Successful in 4m51s
CI / perf (pull_request) Successful in 9m33s

Schema: Person golden record + User portal-account overlay (1-to-0-or-1)
+ UserScope (the table behind the ADR-0025 scope axis). All in the
public schema. UserScope.value is opaque (no FK to ADR-0027 tables -
historical scope rows survive structure decommissioning).

Migration: hand-written, follows the existing convention. FKs with
correct ON DELETE actions (RESTRICT on User.personId for the required
relation, CASCADE on UserScope.userId via explicit onDelete: Cascade
in the schema).

Catalogue: PERSON_SOURCES = [self-signin, admin-ui, seed] as const
under apps/portal-bff/src/users/person-source.ts. Defense in depth =
TS type union + drift gate scanner extension (property literal
"source: 'X'" in files importing person-source.ts).

PersonAndUserProvisioner: blocking lazy-create at first OIDC callback.
Fast path = findUnique by entraOid + update lastSignInAt. Cold path =
nested create of Person + User in one transaction. Race-condition
handling: catches P2002 on User.entraOid unique constraint and re-runs
ensureUser. Defense-in-depth isPersonSource check on the constant.

PrincipalBuilder signature: build(user, identity: { userId, personId }).
Principal.user.{id, personId} populated from real UUIDs. ScopeResolver
seam moved from { entraOid } to { userId } so PR 2's PrismaScopeResolver
can key queries on User.id.

SessionEstablisher: new constructor arg personUserProvisioner.
establish() calls ensureUser BEFORE principalBuilder.build so the
identity is available. Entra preferred_username (= AuthenticatedUser.
username) maps to Person.email per ADR-0026 lifecycle. Provisioner
failure short-circuits the whole flow before save / cookie / audit /
directory.

UserDirectoryService stays as the ADR-0020 admin-list cache - folding
it into Person+User is a follow-up after ADR-0026 PR 2 stabilises.

Local verification: drift gate clean (4 / 24 / 7 / 3), 29 drift-gate
spec tests passing, portal-bff lint 0 errors, 766 portal-bff specs
passing.
This commit is contained in:
Julien Gautier
2026-05-26 13:54:41 +02:00
parent cba36394c9
commit 056848e502
15 changed files with 1033 additions and 126 deletions
+117 -59
View File
@@ -48,15 +48,18 @@ 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 `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.
* 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
@@ -148,13 +151,107 @@ export function extractCatalogues(sourceFilePath = CATALOGUE_PATH) {
* 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 !== 'STRUCTURE_KINDS') continue;
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;
@@ -170,55 +267,11 @@ export function extractStructureKinds(sourceFilePath = join(WORKSPACE_ROOT, STRU
}
throw new Error(
`Failed to extract STRUCTURE_KINDS from ${sourceFilePath}` +
`the script expected a top-level "export const STRUCTURE_KINDS = [...] as const" declaration.`,
`Failed to extract ${constName} from ${sourceFilePath}` +
`the script expected a top-level "export const ${constName} = [...] 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
@@ -302,26 +355,29 @@ export function scanWorkspace(workspaceRoot = WORKSPACE_ROOT) {
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 };
return { violations: out, catalogues, structureKinds, personSources };
}
function main() {
const { violations, catalogues, structureKinds } = scanWorkspace();
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).`,
`catalogue-drift: clean (catalogues: ${privCount} privileges, ${roleCount} roles, ${kindCount} structure kinds, ${sourceCount} person sources).`,
);
process.exit(0);
}
@@ -351,10 +407,12 @@ function main() {
}
console.error('');
console.error(
`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.`,
`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);
}
+106 -5
View File
@@ -15,7 +15,9 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
extractCatalogues,
extractPersonSources,
extractStructureKinds,
findPersonSourceViolationsInFile,
findStructureKindViolationsInFile,
findViolationsInFile,
scanWorkspace,
@@ -59,6 +61,17 @@ function makeFixture({ files }) {
export type StructureKind = (typeof STRUCTURE_KINDS)[number];
`,
);
mkdirSync(join(root, 'apps/portal-bff/src/users'), { recursive: true });
writeFileSync(
join(root, 'apps/portal-bff/src/users/person-source.ts'),
`export const PERSON_SOURCES = [
'self-signin',
'admin-ui',
'seed',
] as const;
export type PersonSource = (typeof PERSON_SOURCES)[number];
`,
);
for (const [relativePath, contents] of Object.entries(files)) {
const full = join(root, relativePath);
mkdirSync(join(full, '..'), { recursive: true });
@@ -262,6 +275,91 @@ describe('findStructureKindViolationsInFile', () => {
});
});
describe('extractPersonSources', () => {
it('reads the PERSON_SOURCES catalogue from person-source.ts', () => {
const root = makeFixture({ files: {} });
const sources = extractPersonSources(join(root, 'apps/portal-bff/src/users/person-source.ts'));
assert.deepEqual([...sources].sort(), ['admin-ui', 'seed', 'self-signin']);
});
it('throws when the constant is missing', () => {
const root = mkdtempSync(join(tmpdir(), 'drift-fixture-'));
mkdirSync(join(root, 'apps/portal-bff/src/users'), { recursive: true });
writeFileSync(
join(root, 'apps/portal-bff/src/users/person-source.ts'),
`export const NOT_PERSON_SOURCES = ['foo'] as const;\n`,
);
assert.throws(
() => extractPersonSources(join(root, 'apps/portal-bff/src/users/person-source.ts')),
/PERSON_SOURCES/,
);
});
});
describe('findPersonSourceViolationsInFile', () => {
const validSources = new Set(['self-signin', 'admin-ui', 'seed']);
it('skips files that do not import person-source (would false-positive)', () => {
// `source: 'X'` is an extremely common pattern (event sources, log
// sources, etc.). Without the import filter, every such literal
// would be flagged.
const text = `
const evt = { source: 'logger', message: 'hello' };
`;
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
assert.equal(violations.length, 0);
});
it('returns no violations when every source literal is in the catalogue', () => {
const text = `
import type { PersonSource } from '../users/person-source';
const a = { source: 'self-signin' as PersonSource };
const b = { source: 'seed' as PersonSource };
`;
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
assert.equal(violations.length, 0);
});
it('flags every source literal not in the catalogue', () => {
const text = `
import { PERSON_SOURCES } from '../users/person-source';
const a = { source: 'self-signin' };
const b = { source: 'pleiades' };
const c = { source: 'rogue-source' };
`;
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
assert.equal(violations.length, 2);
const values = violations.map((v) => v.value).sort();
assert.deepEqual(values, ['pleiades', 'rogue-source']);
assert.equal(violations[0].callee, 'Person.source');
assert.equal(violations[0].catalogue, 'PERSON_SOURCES');
});
it('skips non-literal initialisers (variable indirection)', () => {
const text = `
import { PERSON_SOURCES } from '../users/person-source';
const s = 'something';
const a = { source: s };
`;
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
assert.equal(violations.length, 0);
});
it('reports line and column of the offending literal', () => {
const text = [
`import { PERSON_SOURCES } from '../users/person-source';`,
`const x = {`,
` source: 'rogue-source',`,
`};`,
].join('\n');
const violations = findPersonSourceViolationsInFile('virtual.ts', validSources, text);
assert.equal(violations.length, 1);
assert.equal(violations[0].line, 3);
// 'rogue-source' literal starts at column 11 (0-indexed 10, +1 in the report).
assert.equal(violations[0].column, 11);
});
});
describe('scanWorkspace', () => {
it('returns 0 violations on a clean fixture', () => {
const root = makeFixture({
@@ -333,25 +431,28 @@ describe('scanWorkspace', () => {
assert.equal(violations.length, 1);
});
it('aggregates decorator + Structure.kind violations together', () => {
it('aggregates decorator + Structure.kind + Person.source violations together', () => {
const root = makeFixture({
files: {
'apps/portal-bff/src/foo.ts': `
import { STRUCTURE_KINDS } from './structures/structure-kind';
import { PERSON_SOURCES } from './users/person-source';
@RequirePrivilege('Portal.Ghost') class Bad {}
const s = { kind: 'phantom_kind' };
const p = { source: 'rogue-source' };
`,
},
});
const { violations } = scanWorkspace(root);
assert.equal(violations.length, 2);
assert.equal(violations.length, 3);
const values = violations.map((v) => v.value).sort();
assert.deepEqual(values, ['Portal.Ghost', 'phantom_kind']);
assert.deepEqual(values, ['Portal.Ghost', 'phantom_kind', 'rogue-source']);
});
it('returns the structureKinds set alongside catalogues', () => {
it('returns the structureKinds and personSources sets alongside catalogues', () => {
const root = makeFixture({ files: {} });
const { structureKinds } = scanWorkspace(root);
const { structureKinds, personSources } = scanWorkspace(root);
assert.deepEqual([...structureKinds].sort(), ['antenne', 'medico_social', 'siege']);
assert.deepEqual([...personSources].sort(), ['admin-ui', 'seed', 'self-signin']);
});
});