feat(users): add Person + User + UserScope + lazy provisioner (ADR-0026 PR 1)
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:
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user