diff --git a/README.md b/README.md index cba8215..1cc3bed 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,22 @@ The bot's socket.io client authenticates with its service token in `auth.token` The IdP notifies `POST /internal/events` when access changes; the backend also polls the snapshot every 30 s. The last good signing keys and snapshot are stored in `common_idp_state`, so a restart during an IdP outage resumes from them. Permission checks deny once the snapshot is more than an hour old. Configuration is in `.env.example`. +## People register sources + +People keeps one source of truth for each fact and stores no copy of the others. Every People operation reads them first (PoliNetwork Auth cached in memory for 15 seconds, the Soci group for 5 minutes) and lays them over the register: + +| Fact | Source | People keeps | +| --- | --- | --- | +| Who is an admin, a team member or a team Lead | **PoliNetwork Auth**: the roles Master Admin bound to People (`admin`, `team::member`, `team::lead`), read with `GET /api/internal/people-roles` | When each role started and ended, why, and People's own details (Capo Admin scope, team fields) | +| Who is a member, and their number | **The Microsoft 365 Soci group** and each account's `employeeId` | Suspension or expiry, the admission date, fees, receipts | + +People doesn't track which Telegram groups an admin administers: being an admin means holding the bound `admin` role in Auth. A Capo Admin's area lists the admins who have them as Capo of reference. + +- **Roles.** Holders without a record get one (name only, linked to their account). A record without an account is linked automatically only by a Microsoft 365 identity (object ID or `@polinetwork.org` address); a match by Telegram ID or another verified address goes to HR as an `identity-match` review. When an identity points at a record linked to another account, nothing changes hands and the records are flagged for review. On linked records Auth decides every bound concept: an admin or team entry is active exactly while its role is held. Unlinked records, and any concept with no bound role, stay owned by People. If Auth hasn't answered for an hour, People refuses to work rather than decide who leads or administers from an old answer. +- **Members.** Each member of the Soci group is matched by Microsoft 365 account or address, or gets a new record, and takes the account's `employeeId` as member number; a member without a usable number is flagged for review. A member of the register who is no longer in the group becomes former, unless admitted in the last two days, which the group listing may not show yet. While Microsoft 365 has never answered, memberships stay as they are. Memberships that appear from the group get no automatic fee reminders in that year. + +When the dashboard changes a linked record's admin or team role, or a census answer, import, merge or account link does, the backend sends the IdP one command per person with `POST /api/internal/people-roles`: the desired state of each changed concept, the dashboard user it authenticated, and a command ID. The IdP picks the assignments, checks that user may make every one of them (no self-grants, `people:write` or `people:appoint`, bounded delegation) and applies all of them or none. The command is saved first, as an outbox, and sent after the People transaction commits; until the IdP confirms it, the record shows the roles Auth holds, so a requested role never grants access, and other role edits of that person are refused. Direct dashboard actions fail when the IdP refuses; census answers, imports, merges and links note the refusal and flag the record for review. When the IdP doesn't answer, the sweep sends the same command again: the IdP applies an ID once and answers with the current roles. Writes need the backend's OAuth client to hold the `idp:people:roles` scope on the internal resource; reads use the existing `idp:access:read` token. + ## E-signing with the CIE The `esign` router and `/esign/agent/*` endpoints let dashboard users sign PDFs with the Italian identity card @@ -114,3 +130,9 @@ Signatures are checked against the CIE certification authorities of the Minister catalog entries. Selected FAQs/categories must be replaced in Freshman before deleting them from the catalog. The development seed also initializes the card slots and selections; `--force` clears those selections before replacing the sample FAQ catalog. + +### People before login + +New manual People records are created in Auth, including their initial admin/team roles, with optional contacts and no census prerequisites. The backend uses Auth's stable registration ID to retain the register record after a Master Admin approves its real login account. Declared Telegram contacts never establish a verified identity, and a preliminary person is not automatically linked by name or contact alone. Auth reports each account's verified identity (`verifiedEmail`, Microsoft 365 object ID, Telegram ID and username); People matches records against it with one rule (`src/people/identity.ts`) and one outcome policy (`src/people/linking.ts`), described in the admin dashboard's `docs/people/linking.md`. Approval of a preliminary link and the role transfer happen atomically in Auth. Linking lists the links of the last 30 days (`linking.recent`) so HR can undo a mistaken one: unlinking takes the record's roles off the account in Auth (for a preliminary person a Master Admin gives them back to it), and the record is never proposed to that account again. Production creation fails explicitly if Auth is unavailable; the local-only option exists for the test harness. + +Deploy the Auth preliminary-person migration/API before this backend and the matching admin dashboard. Existing historical records/imports are not automatically migrated by this feature. diff --git a/src/azure/functions/members.ts b/src/azure/functions/members.ts index 57dd98f..bd547d6 100644 --- a/src/azure/functions/members.ts +++ b/src/azure/functions/members.ts @@ -39,7 +39,16 @@ export async function getMembers(): Promise { .api(`/users`) .header("ConsistencyLevel", "eventual") .count(true) - .select(["displayName", "mail", "givenName", "surname", "id", "assignedLicenses", "employeeId"]) + .select([ + "displayName", + "mail", + "givenName", + "surname", + "id", + "assignedLicenses", + "employeeId", + "createdDateTime", + ]) .filter("endswith(mail, '@polinetwork.org') or endswith(userPrincipalName, '@polinetwork.org')") .get(), true diff --git a/src/azure/types.ts b/src/azure/types.ts index 3e53196..c719760 100644 --- a/src/azure/types.ts +++ b/src/azure/types.ts @@ -19,7 +19,7 @@ export type BasicUser = Pick< // this is the type representing our call to `/users` export type User = Pick< Required, - "displayName" | "mail" | "givenName" | "surname" | "id" | "assignedLicenses" | "employeeId" + "displayName" | "mail" | "givenName" | "surname" | "id" | "assignedLicenses" | "employeeId" | "createdDateTime" > export type ParsedUser = { @@ -29,6 +29,8 @@ export type ParsedUser = { givenName: string | null surname: string | null employeeId: string | null + /** When the account was created, as Graph returns it; absent in the seeded directory. */ + createdDateTime?: string | null isMember: boolean assignedLicensesIds: string[] } diff --git a/src/emails/mailer.tsx b/src/emails/mailer.tsx index f85d993..2e91eea 100644 --- a/src/emails/mailer.tsx +++ b/src/emails/mailer.tsx @@ -6,6 +6,7 @@ import { env } from "@/env" import type { RequestUpdate } from "@/esign/service" import { logger } from "@/logger" import MemberNumberChanged from "./templates/member-number-changed" +import PeopleEmail from "./templates/people" import RequestUpdateEmail, { requestUpdateSubject } from "./templates/request-update" import SignatureRequestEmail from "./templates/signature-request" import SignedDocumentEmail, { type SignedDocumentProps } from "./templates/signed-document" @@ -126,9 +127,13 @@ export async function sendPeopleEmail(input: { to: string subject: string text: string + firstName: string | null + action: { label: string; url: string } | null attachment: { fileName: string; contentType: string; content: Uint8Array } | null }) { - const component =
{input.text}
+ const component = ( + + ) const attachments = input.attachment ? [ { diff --git a/src/emails/templates/people.tsx b/src/emails/templates/people.tsx new file mode 100644 index 0000000..d71935e --- /dev/null +++ b/src/emails/templates/people.tsx @@ -0,0 +1,89 @@ +import { + Body, + Button, + Container, + Head, + Heading, + Html, + Link, + Preview, + pixelBasedPreset, + Section, + Tailwind, + Text, +} from "@react-email/components" +import { Footer } from "../components/footer" +import { Logo } from "../components/logo" +import type { EmailTemplate } from "../types" + +export type PeopleEmailProps = { + subject: string + /** The recipient's first name, for the greeting. */ + firstName: string | null + /** Paragraphs separated by blank lines. */ + text: string + action: { label: string; url: string } | null +} + +/** Every People email: members and volunteers read them in Italian. */ +const PeopleEmail: EmailTemplate = ({ subject, firstName, text, action }) => { + const paragraphs = text.split(/\n\s*\n/) + const title = subject.replace(/^PoliNetwork · | · PoliNetwork$/g, "") + return ( + + + + {paragraphs[0]} + + + + + {title.charAt(0).toUpperCase() + title.slice(1)} + +
+ {firstName ? `Ciao ${firstName},` : "Ciao,"} + {paragraphs.map((p) => ( + + {p} + + ))} + {action && ( + <> +
+ +
+ + Se il pulsante non funziona, copia questo indirizzo nel browser:{" "} + + {action.url} + + + + )} + A presto, + PoliNetwork +
+
+
Messaggio automatico di PoliNetwork APS: non rispondere a questa email.
+ +
+ + ) +} + +PeopleEmail.PreviewProps = { + subject: "PoliNetwork · collega il tuo account", + firstName: "Mario", + text: "Ti abbiamo invitato a collegare il tuo account PoliNetwork alla tua scheda nell'associazione.\n\nScadenza dell'invito: 11 novembre 2026.", + action: { + label: "Collega il tuo account", + url: "https://admin.polinetwork.org/dashboard/account/me?peopleInvite=abc", + }, +} + +export default PeopleEmail diff --git a/src/idp/index.ts b/src/idp/index.ts index 48d1069..25dd6a1 100644 --- a/src/idp/index.ts +++ b/src/idp/index.ts @@ -12,6 +12,7 @@ import { import { z } from "zod" import { env } from "@/env" import { logger } from "@/logger" +import { type PeopleRoles, RoleChangeError } from "@/people/roles" import { authenticate, type RequestAuth } from "./auth" import { dbPersistence } from "./persistence" @@ -20,6 +21,39 @@ const PROJECTION = "backend" const signerDirectory = z.array( z.object({ sub: z.string(), name: z.string(), email: z.string().nullable(), emailVerified: z.boolean().optional() }) ) +const peopleDirectory = z.object({ + roles: z.array(z.object({ key: z.string(), name: z.string(), binding: z.string() })), + users: z.array( + z.object({ + sub: z.string(), + registrationId: z.string().optional(), + provisional: z.boolean().optional(), + previousSub: z.string().optional(), + firstName: z.string().optional(), + lastName: z.string().optional(), + phone: z.string().nullable().optional(), + declaredTelegramId: z.string().nullable().optional(), + declaredTelegramUsername: z.string().nullable().optional(), + name: z.string(), + email: z.string().nullable(), + verifiedEmail: z.string().nullish(), + azureId: z.string().nullish(), + telegramId: z.string().nullable(), + telegramUsername: z.string().nullable(), + roles: z.array(z.string()), + assigned: z.array(z.string()).optional(), + since: z.record(z.string(), z.string().regex(/^\d{4}-\d{2}-\d{2}$/)).optional(), + }) + ), +}) +/** The person's bound roles after a role command, as `POST /api/internal/people-roles` answers. */ +const roleResult = z.object({ + roles: peopleDirectory.shape.roles, + held: z.array(z.string()), + assigned: z.array(z.string()), +}) +/** Lets the backend give and take back the roles bound to People, for the dashboard user it authenticated. */ +const PEOPLE_ROLES_SCOPE = "idp:people:roles" function report(component: string) { return (error: unknown) => { @@ -56,6 +90,7 @@ function configure() { let snapshot = null let events = null let directory: (() => Promise>) | null = null + let peopleRoles: PeopleRoles | null = null if (env.OAUTH_INTERNAL_RESOURCE_URI && env.OAUTH_BACKEND_CLIENT_ID && env.OAUTH_BACKEND_PRIVATE_JWK) { const tokens = serviceTokenSource({ clientId: env.OAUTH_BACKEND_CLIENT_ID, @@ -85,6 +120,73 @@ function configure() { if (!response.ok) throw new Error(`IdP signer directory returned ${response.status}`) return signerDirectory.parse(await response.json()) } + // A separate token, so a client not yet granted the write scope still pulls the snapshot. + const roleTokens = serviceTokenSource({ + clientId: env.OAUTH_BACKEND_CLIENT_ID, + privateKey: parsePrivateKey(env.OAUTH_BACKEND_PRIVATE_JWK), + tokenUrl: endpoints.tokenUrl, + tokenAudience: endpoints.tokenAudience, + resource: env.OAUTH_INTERNAL_RESOURCE_URI, + scopes: [PEOPLE_ROLES_SCOPE], + onError: report("people roles token source"), + }) + const peopleRolesUrl = new URL("/api/internal/people-roles", endpoints.snapshotUrl) + peopleRoles = { + async directory() { + const token = await tokens.getToken() + const response = await fetch(peopleRolesUrl, { + headers: { Authorization: `Bearer ${token}` }, + signal: AbortSignal.timeout(10_000), + }) + if (response.status === 401) tokens.invalidate() + if (!response.ok) throw new Error(`IdP People roles returned ${response.status}`) + return peopleDirectory.parse(await response.json()) + }, + change: (change) => sendPeopleCommand(change, roleResult), + update: (input) => sendPeopleCommand(input, z.object({ sub: z.string() })), + create: (input) => sendPeopleCommand(input, z.object({ sub: z.string() })), + link: (input) => sendPeopleCommand(input, z.object({ sub: z.string() })), + unlink: (input) => sendPeopleCommand(input, z.object({ sub: z.string() })), + } + const sendPeopleCommand = async (change: unknown, resultSchema: z.ZodType): Promise => { + const send = async () => { + let token: string + try { + token = await roleTokens.getToken() + } catch { + throw new RoleChangeError(503, `no token to change roles; is ${PEOPLE_ROLES_SCOPE} granted to this backend?`) + } + try { + return await fetch(peopleRolesUrl, { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify(change), + signal: AbortSignal.timeout(10_000), + }) + } catch { + throw new RoleChangeError(503, "PoliNetwork Auth could not be reached") + } + } + let response = await send() + // A stale cached token: ask for a new one and send the same command once more. A second 401 is a refusal. + if (response.status === 401) { + roleTokens.invalidate() + response = await send() + if (response.status === 401) roleTokens.invalidate() + } + if (response.ok) { + // The command was applied, but without a readable answer People can't confirm it: retry it by ID. + const result = resultSchema.safeParse(await response.json().catch(() => null)) + if (!result.success) throw new RoleChangeError(503, "PoliNetwork Auth sent an unreadable answer") + return result.data + } + const body = (await response.json().catch(() => null)) as { error?: unknown } | null + throw new RoleChangeError( + response.status, + typeof body?.error === "string" ? body.error : `request failed (${response.status})` + ) + } + events = createAccessEventHandler({ keyStore, issuer: endpoints.issuer, @@ -101,6 +203,7 @@ function configure() { keyStore, snapshot, directory, + peopleRoles, /** Fetch API handler for `POST /internal/events`, or null without a snapshot. */ events, verify: (token: string) => verifyAccessToken(token, { issuer: endpoints.issuer, audience, keyStore }), diff --git a/src/people/contract.ts b/src/people/contract.ts index f948ffd..acfb141 100644 --- a/src/people/contract.ts +++ b/src/people/contract.ts @@ -32,7 +32,15 @@ export const MEMBER_STATUSES = ["active", "suspended", "expired", "former"] as c export const FEE_STATUSES = ["due", "receipt", "paid", "unpaid"] as const export const ACCOUNT_STATUSES = ["none", "invite", "linked", "review"] as const export const CENSUS_ANSWERS = ["continues", "leaving"] as const -export const REVIEW_KINDS = ["telegram-conflict", "ask-to-be-added", "two-records", "not-me", "name-only"] as const +export const REVIEW_KINDS = [ + "telegram-conflict", + "ask-to-be-added", + "two-records", + "not-me", + "name-only", + "preliminary-link", + "identity-match", +] as const /** A receipt's pipeline: issued unsigned, signed by an officer, emailed to the member; or the email failed, or voided. */ export const RECEIPT_STATUSES = ["toSign", "signed", "sent", "failed", "voided"] as const export const PAYMENT_METHODS = ["transfer", "cash"] as const @@ -59,7 +67,6 @@ export type PhotoConsent = (typeof PHOTO_CONSENTS)[number] export type Signer = (typeof SIGNERS)[number] const personRefSchema = z.object({ id: z.string(), name: z.string() }) -const groupSchema = z.object({ chatId: z.string(), title: z.string() }) export const profileSchema = z.object({ firstName: z.string(), @@ -70,9 +77,11 @@ export const profileSchema = z.object({ phone: z.string().nullable(), telegramUsername: z.string().nullable(), telegramId: z.string().nullable(), + /** Empty, like `year`, for people known only from PoliNetwork Auth or Microsoft 365 until HR completes them. */ course: z.string(), year: z.string(), - campus: campusSchema, + /** `null` until known: people known only from PoliNetwork Auth or Microsoft 365. */ + campus: campusSchema.nullable(), otherAssociations: z.array(z.string()), studentRepresentative: z.string().nullable(), }) @@ -91,9 +100,6 @@ export const adminRoleSchema = z.object({ since: z.string(), endedOn: z.string().nullable(), endReason: z.string().nullable(), - /** Detected by the bot. */ - groups: z.array(groupSchema), - requested: z.array(groupSchema.extend({ requestedOn: z.string() })), availableAsCapo: z.boolean(), capoOfReference: personRefSchema.nullable(), /** Set when this person is a Capo Admin, e.g. "Ingegneria Informatica". */ @@ -134,7 +140,15 @@ export const accountSchema = z.discriminatedUnion("status", [ expiresOn: z.string(), sentBy: z.string(), }), - z.object({ status: z.literal("linked"), email: z.string(), via: z.string(), linkedOn: z.string(), how: z.string() }), + z.object({ + status: z.literal("linked"), + email: z.string(), + via: z.string(), + linkedOn: z.string(), + how: z.string(), + /** Who made the link: the account holder, an admin's sub, or `system`. Absent on older links. */ + by: z.string().optional(), + }), z.object({ status: z.literal("review"), reviewId: z.string(), issue: z.string() }), ]) @@ -145,6 +159,7 @@ export const consentsSchema = z.object({ /** One row of the People lists: everything but notes, activity and discrepancies. */ export const personRowSchema = z.object({ + preliminary: z.boolean().optional(), id: z.string(), profile: profileSchema, /** `null` without `people:members:read`, except on the viewer's own record: `isMember` still says whether they are one. */ @@ -159,6 +174,7 @@ export const personRowSchema = z.object({ }) export const discrepancySchema = z.object({ + /** `admin-removal` is only on older records: People no longer tracks which Telegram groups an admin keeps. */ kind: z.enum(["declared-member", "telegram-mismatch", "needs-review", "admin-removal"]), message: z.string(), suggestedTelegram: z.string().nullable(), @@ -318,6 +334,22 @@ export const inviteSchema = z.object({ }) export type Invite = z.infer +/** A link made recently, so HR can spot and undo a mistaken one. */ +export const recentLinkSchema = z.object({ + personId: z.string(), + name: z.string(), + email: z.string(), + via: z.string(), + how: z.string(), + linkedOn: z.string(), + linkedBy: z.enum(["account-holder", "admin", "system", "unknown"]), + /** Created in Auth before its first login: only a Master Admin can undo the link. */ + preliminary: z.boolean(), +}) +export type RecentLink = z.infer +/** How far back Linking lists recent links. */ +export const RECENT_LINK_DAYS = 30 + export const accountMatchSchema = z.object({ id: z.string(), name: z.string(), @@ -387,9 +419,7 @@ export type ImportPreview = z.infer export const capoAreaSchema = z.object({ scope: z.string(), - groups: z.array(groupSchema.extend({ admins: z.number().int().nullable() })), admins: z.array(personRowSchema), - requests: z.array(z.object({ id: z.string(), person: personRefSchema, group: groupSchema, requestedOn: z.string() })), }) export type CapoArea = z.infer @@ -447,11 +477,18 @@ export const myAreaSchema = z.discriminatedUnion("state", [ name: z.string(), course: z.string(), year: z.string(), - campus: campusSchema, + campus: campusSchema.nullable(), roles: z.array(z.string()), }), reason: z.string(), }), + z.object({ + /** People already holds a record made before this account's first sign-in; a Master Admin decides the link. */ + state: z.literal("awaiting-approval"), + /** Only when a verified email or Telegram account matched: weaker matches may be someone else's record. */ + candidate: z.object({ id: z.string(), name: z.string(), roles: z.array(z.string()) }).nullable(), + reason: z.string(), + }), z.object({ state: z.literal("none"), request: z.object({ sentOn: z.string() }).nullable() }), ]) export type MyArea = z.infer @@ -523,7 +560,7 @@ export const TEAMS = { ], }, design: { - name: "Design & Social", + name: "Design & Marketing", fields: [ { key: "tools", @@ -586,8 +623,21 @@ export const personInputSchema = z.object({ year: z.enum(YEARS), campus: campusSchema, }) -export const createPersonInputSchema = personInputSchema.extend({ admin: z.boolean() }) -export const updatePersonInputSchema = personInputSchema.extend({ id: personIdSchema }) +export const createPersonInputSchema = personInputSchema.extend({ + requestId: z.uuid().optional(), + personalEmail: z.union([z.literal(""), z.email().max(254)]).default(""), + phone: z.string().trim().max(40).default(""), + telegramUsername: telegramUsernameSchema.default(""), + telegramId: z.union([z.literal(""), z.string().regex(/^[1-9]\d{0,19}$/)]).default(""), + course: z.string().trim().max(120).default(""), + year: z.union([z.literal(""), z.enum(YEARS)]).default(""), + campus: campusSchema.nullable().default(null), + admin: z.boolean().default(false), + teams: z.array(teamIdSchema).max(TEAM_IDS.length).default([]), +}) +export const updatePersonInputSchema = createPersonInputSchema + .omit({ admin: true, teams: true, telegramId: true, requestId: true }) + .extend({ id: personIdSchema }) export const setNoteInputSchema = z.object({ id: personIdSchema, note: z.string().trim().max(2000) }) export const createMemberInputSchema = z.object({ @@ -657,8 +707,6 @@ export const linkAccountInputSchema = z.object({ reason: reasonSchema, }) -export const joinRequestInputSchema = z.object({ requestId: opaqueIdSchema }) - export const askToBeAddedInputSchema = z.object({ roles: z .array(z.enum(["admin", "team", "member"])) @@ -672,7 +720,6 @@ export const answerCensusInputSchema = z.object({ course: z.string().trim().min(1).max(120), year: z.enum(YEARS), campus: campusSchema, - keepGroups: z.array(z.string().max(120)).max(100), keepTeams: z.array(teamIdSchema).max(TEAM_IDS.length), reason: z.string().trim().max(200), note: z.string().trim().max(500), @@ -753,7 +800,7 @@ export const sendSignedInputSchema = z.object({ }) export const transferInputSchema = z.object({ transferDate: dateSchema, amountCents: amountCentsSchema }) -export type CreatePersonInput = z.infer +export type CreatePersonInput = z.input export type UpdatePersonInput = z.infer export type SetNoteInput = z.infer export type CreateMemberInput = z.infer diff --git a/src/people/identity.ts b/src/people/identity.ts new file mode 100644 index 0000000..eac2bd4 --- /dev/null +++ b/src/people/identity.ts @@ -0,0 +1,120 @@ +import { nameOf } from "./model" +import type { Account, Person } from "./types" + +/** + * The one rule for "is this account the same person as this record?" (admin docs/people/linking.md §4.2). + * The account's evidence was verified by PoliNetwork Auth; the record's was declared by HR, a census or a preliminary + * person, except the Microsoft 365 identity. Nothing here links anything: `linking.ts` decides what a match leads to. + */ + +/** What both sides share, strongest first. `email` is the personal or the Microsoft 365 address. */ +export type Evidence = "microsoft-365" | "email" | "telegram" | "username" | "name" +export type Strength = "verified" | "username" | "name" + +export type Match = + | { kind: "none" } + | { kind: "one"; person: Person; evidence: Evidence; strength: Strength } + /** + * Several records claim the verified identity, the record's Telegram account is someone else's, or the record holds + * another Microsoft 365 account. + */ + | { + kind: "conflict" + reason: "two-records" | "telegram-conflict" | "microsoft-365-conflict" + person: Person + other: Person | null + } + +const lower = (value: string | null | undefined) => value?.trim().toLowerCase() || null +const username = (value: string | null | undefined) => lower(value)?.replace(/^@/, "") || null + +export const strengthOf = (evidence: Evidence): Strength => + evidence === "username" || evidence === "name" ? evidence : "verified" + +/** The strongest evidence linking `account` to `p`, or null. */ +export function evidenceBetween(p: Person, account: Account): Evidence | null { + if (account.azureId && p.azureId === account.azureId) return "microsoft-365" + const email = lower(account.verifiedEmail) + if (email && (lower(p.profile.personalEmail) === email || lower(p.member?.m365Email) === email)) return "email" + if (account.telegramId && p.profile.telegramId === account.telegramId) return "telegram" + const handle = username(account.telegramUsername) + if (handle && username(p.profile.telegramUsername) === handle) return "username" + const name = lower(account.name) + if (name && lower(nameOf(p)) === name) return "name" + return null +} + +/** + * Records by every key `evidenceBetween` compares, so matching an account costs a few lookups instead of a pass over + * the register. Built once per pass; `add` a record again after changing its identities. + */ +export class RecordIndex { + private readonly keys = new Map>() + constructor(persons: Iterable) { + for (const p of persons) this.add(p) + } + add(p: Person) { + for (const key of [ + p.azureId && `azure:${p.azureId}`, + lower(p.profile.personalEmail) && `email:${lower(p.profile.personalEmail)}`, + lower(p.member?.m365Email) && `email:${lower(p.member?.m365Email)}`, + p.profile.telegramId && `telegram:${p.profile.telegramId}`, + username(p.profile.telegramUsername) && `username:${username(p.profile.telegramUsername)}`, + lower(nameOf(p)) && `name:${lower(nameOf(p))}`, + ]) + if (key) this.keys.set(key, (this.keys.get(key) ?? new Set()).add(p)) + } + /** Records sharing at least one key with the account; `evidenceBetween` says how strongly. */ + candidates(account: Account): Set { + const found = new Set() + for (const key of [ + account.azureId && `azure:${account.azureId}`, + lower(account.verifiedEmail) && `email:${lower(account.verifiedEmail)}`, + account.telegramId && `telegram:${account.telegramId}`, + username(account.telegramUsername) && `username:${username(account.telegramUsername)}`, + lower(account.name) && `name:${lower(account.name)}`, + ]) + for (const p of (key && this.keys.get(key)) || []) found.add(p) + return found + } +} + +/** Whether `p` shares a verified identity with the account. */ +export function sharesVerified(p: Person, account: Account) { + const evidence = evidenceBetween(p, account) + return !!evidence && strengthOf(evidence) === "verified" +} + +/** + * Matches an account against the records that could be theirs: not linked to an account yet, or preliminary Auth + * persons waiting for one. The first tier with a hit decides. Only verified evidence can conflict: an ambiguous + * username or name proves nothing, so it matches nobody. + */ +export function matchAccount(index: RecordIndex, account: Account, rejected: ReadonlySet): Match { + const hits = [...index.candidates(account)].flatMap((p) => { + if ((p.accountSub && !p.authProvisional) || rejected.has(p.id)) return [] + const evidence = evidenceBetween(p, account) + return evidence ? [{ person: p, evidence, strength: strengthOf(evidence) }] : [] + }) + for (const strength of ["verified", "username", "name"] as const) { + const tier = hits.filter((hit) => hit.strength === strength) + if (!tier.length) continue + if (strength !== "verified") return tier.length === 1 ? { kind: "one", ...tier[0] } : { kind: "none" } + if (tier.length > 1) { + // One record has the address or Microsoft 365 identity, another the Telegram account. + const byTelegram = tier.filter((hit) => hit.evidence === "telegram") + const byOther = tier.filter((hit) => hit.evidence !== "telegram") + if (byTelegram.length === 1 && byOther.length === 1) + return { kind: "conflict", reason: "telegram-conflict", person: byOther[0].person, other: byTelegram[0].person } + return { kind: "conflict", reason: "two-records", person: tier[0].person, other: tier[1].person } + } + const [only] = tier + const { profile, azureId } = only.person + if (profile.telegramId && account.telegramId && profile.telegramId !== account.telegramId) + return { kind: "conflict", reason: "telegram-conflict", person: only.person, other: null } + if (azureId && account.azureId && azureId !== account.azureId) + return { kind: "conflict", reason: "microsoft-365-conflict", person: only.person, other: null } + return { kind: "one", ...only } + } + return { kind: "none" } +} diff --git a/src/people/imports.ts b/src/people/imports.ts index f3deefc..e37f4f2 100644 --- a/src/people/imports.ts +++ b/src/people/imports.ts @@ -2,7 +2,7 @@ import { TRPCError } from "@trpc/server" import { XMLParser, XMLValidator } from "fast-xml-parser" import { Unzip, UnzipInflate } from "fflate" import { z } from "zod" -import { type CensusAnswer, createPersonInputSchema, teamIdSchema } from "./contract" +import { type CensusAnswer, personInputSchema, teamIdSchema } from "./contract" import { fail, hash } from "./model" export const MAX_FILE_BYTES = 10 * 1024 * 1024 @@ -164,7 +164,6 @@ const aliases: Record = { answeredOn: ["answeredOn", "completiontime", "oradicompletamento"], admin: ["admin", "amministratore"], teams: ["teams", "team"], - requestedGroups: ["requestedGroups", "gruppirichiesti"], availableAsCapo: ["availableAsCapo", "disponibilecomecapo"], otherAssociations: ["otherAssociations", "altreassociazioni"], studentRepresentative: ["studentRepresentative", "rappresentantestudenti"], @@ -175,7 +174,6 @@ const aliases: Record = { const volunteerInput = z.object({ admin: z.boolean(), teams: z.array(teamIdSchema).max(5), - requestedGroups: z.array(z.string().regex(/^-\d{1,16}$/)).max(100), availableAsCapo: z.boolean(), otherAssociations: z.array(z.string().max(100)).max(20).optional(), studentRepresentative: z.string().max(200).optional(), @@ -203,7 +201,7 @@ export async function parseImport(file: File) { if (indexes[required] < 0) fail("BAD_REQUEST", `Missing census column: ${required}`) return rows.slice(1).map((cells, i) => { const get = (key: string) => cells[indexes[key]]?.trim() ?? "" - const profile = createPersonInputSchema.safeParse({ + const profile = personInputSchema.safeParse({ ...Object.fromEntries(Object.keys(aliases).map((key) => [key, get(key)])), admin: false, }) @@ -223,7 +221,6 @@ export async function parseImport(file: File) { const volunteer = volunteerInput.safeParse({ admin: yes("admin"), teams: split("teams").map((t) => t.toLowerCase()), - requestedGroups: split("requestedGroups"), availableAsCapo: yes("availableAsCapo"), otherAssociations: indexes.otherAssociations >= 0 ? split("otherAssociations") : undefined, studentRepresentative: indexes.studentRepresentative >= 0 ? get("studentRepresentative") : undefined, diff --git a/src/people/index.ts b/src/people/index.ts index 9d363a2..703fde2 100644 --- a/src/people/index.ts +++ b/src/people/index.ts @@ -1,3 +1,4 @@ +import { azureDirectory } from "@/azure/directory" import { DB, SCHEMA } from "@/db" import { sendPeopleEmail } from "@/emails/mailer" import { idp } from "@/idp" @@ -5,7 +6,7 @@ import { decryptUser } from "@/utils/users" import { provisionMember, setMemberNumber } from "./azure-members" import { peopleConfig } from "./config" import { transferType } from "./files" -import { fail, receiptEligible } from "./model" +import { receiptEligible } from "./model" import { createPeopleService } from "./service" import { createPeoplePgStore } from "./store-pg" @@ -18,19 +19,6 @@ export function permissionsFor(sub: string) { export const people = createPeopleService({ store: createPeoplePgStore(DB), config: peopleConfig, - async directory() { - if (!idp?.directory) fail("PRECONDITION_FAILED", "The IdP account directory is not configured") - return (await idp.directory()).map((a) => ({ - ...a, - emailVerified: a.emailVerified === true, - telegramId: idp?.snapshot?.current()?.bySub(a.sub)?.telegramId ?? null, - })) - }, - // Group admins are native Telegram status (RFC v3 decision 2), which the backend does not store. - async telegramGroups() { - const groups = await DB.select().from(SCHEMA.TG.groups) - return groups.map((g) => ({ chatId: String(g.telegramId), title: g.title, admins: null })) - }, async telegramUsers() { const users = await DB.select().from(SCHEMA.TG.users) return Promise.all( @@ -46,6 +34,24 @@ export const people = createPeopleService({ }, provisionMember, setMemberNumber, + peopleRoles: idp?.peopleRoles ?? null, + async azureMembers() { + return (await azureDirectory.getMembers()).flatMap((u) => + u.isMember && u.mail + ? [ + { + id: u.id, + mail: u.mail, + givenName: u.givenName, + surname: u.surname, + displayName: u.displayName, + employeeId: u.employeeId, + createdOn: u.createdDateTime?.slice(0, 10) ?? null, + }, + ] + : [] + ) + }, sendMail: sendPeopleEmail, async inspectSigned(sub, bytes) { const { esign } = await import("@/esign") diff --git a/src/people/linking.ts b/src/people/linking.ts new file mode 100644 index 0000000..f9a0256 --- /dev/null +++ b/src/people/linking.ts @@ -0,0 +1,266 @@ +import { randomUUID } from "node:crypto" +import type * as C from "./contract" +import { type Evidence, type Match, matchAccount, RecordIndex } from "./identity" +import { fail, log, ref } from "./model" +import type { RoleDirectory } from "./roles" +import type { Account, PeopleState, Person, StoredReview } from "./types" + +/** + * What a match between an account and a record leads to (admin docs/people/linking.md §4.3), and the state changes + * every linking path shares. `identity.ts` decides who matches; this decides who may confirm it. + */ + +/** What the account holder sees while a review about them is open. */ +export type Shown = "record" | "notice" | "hidden" + +export type Decision = + | { action: "none" } + /** Only for an account holding a People role, by a Microsoft 365 identity. */ + | { action: "link"; person: Person } + /** "Is this you?": the account holder confirms. */ + | { action: "confirm"; person: Person; evidence: Evidence } + | { action: "review"; kind: C.ReviewKind; person: Person; other: Person | null; message: string; shown: Shown } + +/** Every login account in Auth's People directory; preliminary persons are records, not accounts. */ +export const accountsOf = (directory: RoleDirectory): Account[] => + directory.users.filter((u) => !u.provisional).map(accountOf) + +export const accountOf = (u: RoleDirectory["users"][number]): Account => ({ + sub: u.sub, + name: u.name, + email: u.email, + verifiedEmail: u.verifiedEmail ?? null, + azureId: u.azureId ?? null, + telegramId: u.telegramId, + telegramUsername: u.telegramUsername, + holdsPeopleRole: u.roles.length > 0, +}) + +export const carriesRoles = (p: Person) => p.admin?.status === "active" || p.teams.some((t) => !t.endedOn) + +const PROVED = { + "microsoft-365": "Microsoft 365 account", + email: "email address", + telegram: "Telegram account", +} as const satisfies Partial> + +const lower = (value: string | null | undefined) => value?.trim().toLowerCase() || null + +/** The verified address is the `@polinetwork.org` one Microsoft 365 gave this record, not one HR typed. */ +const sameMicrosoft365Address = (p: Person, account: Account) => { + const email = lower(account.verifiedEmail) + return !!email?.endsWith("@polinetwork.org") && lower(p.member?.m365Email) === email +} + +/** The outcome policy. Who may approve is enforced where the link is made: Auth for a preliminary person. */ +export function decide(match: Match, account: Account): Decision { + if (match.kind === "none") return { action: "none" } + if (match.kind === "conflict") + return { + action: "review", + kind: match.reason === "microsoft-365-conflict" ? "identity-match" : match.reason, + person: match.person, + other: match.other, + message: { + "two-records": "Several records use the same verified identity", + "telegram-conflict": "Verified email and Telegram identity disagree", + "microsoft-365-conflict": + "The sign-in matches this record, but the record holds another Microsoft 365 account: HR must check before linking.", + }[match.reason], + shown: "notice", + } + const { person, evidence } = match + const review = (kind: C.ReviewKind, message: string, shown: Shown): Decision => ({ + action: "review", + kind, + person, + other: null, + message, + shown, + }) + if (evidence === "name") + return person.authProvisional + ? review( + "name-only", + "Only the name matches. This may be a different person; a Master Admin must check before linking.", + "hidden" + ) + : review("name-only", "Name-only matches require HR review", "hidden") + if (evidence === "username") + return person.authProvisional + ? review( + "preliminary-link", + "The signed-in Telegram username matches the one recorded for this person. Usernames can change hands; a Master Admin must check before linking.", + "notice" + ) + : review( + "identity-match", + "Only the Telegram username matches. Usernames can change hands; HR must check before linking.", + "notice" + ) + const proved = PROVED[evidence] + if (person.authProvisional) + return review( + "preliminary-link", + `The verified ${proved} matches this preliminary person. A Master Admin must approve the link.`, + "record" + ) + if (account.holdsPeopleRole) { + if (evidence === "microsoft-365" || (evidence === "email" && sameMicrosoft365Address(person, account))) + return { action: "link", person } + return review( + "identity-match", + `This account holds a People role in Auth and its verified ${proved} matches this record. Contacts on records are typed by HR or imported, so HR must confirm before linking.`, + "record" + ) + } + if (carriesRoles(person)) + return review( + "identity-match", + `The verified ${proved} matches this record, which carries roles: HR links it and Auth grants the roles.`, + "record" + ) + return { action: "confirm", person, evidence } +} + +/** What matching reads from the register, computed once per pass over many accounts. */ +export type MatchContext = { index: RecordIndex; rejected: Map> } + +/** Indexes the records and, per account, the records it was told aren't theirs ("This isn't me", Decline). */ +export function matchContext(s: PeopleState): MatchContext { + const rejected = new Map>() + for (const r of Object.values(s.reviews)) + for (const id of r.rejectedPersonIds) rejected.set(r.sub, (rejected.get(r.sub) ?? new Set()).add(id)) + return { index: new RecordIndex(Object.values(s.persons)), rejected } +} + +/** The decision for an account against the whole register. */ +export const decideFor = (s: PeopleState, account: Account, context = matchContext(s)) => + decide(matchAccount(context.index, account, context.rejected.get(account.sub) ?? new Set()), account) + +/** Opens a review, or returns the open one for the same account, kind and record. */ +export function openReview( + s: PeopleState, + account: Account, + kind: C.ReviewKind, + p: Person | null, + message: string, + since: string, + shown: Shown = "hidden" +): StoredReview { + const existing = Object.values(s.reviews).find( + (r) => r.sub === account.sub && r.kind === kind && !r.resolved && (r.record?.id ?? null) === (p?.id ?? null) + ) + if (existing) return existing + const id = randomUUID() + s.reviews[id] = { + id, + kind, + since, + account: { name: account.name, email: account.email ?? "", telegram: account.telegramId, via: "IdP" }, + record: p ? ref(p) : null, + other: null, + message, + sub: account.sub, + resolved: false, + rejectedPersonIds: [], + shown, + } + return s.reviews[id] +} + +export function reviewFor( + s: PeopleState, + account: Account, + decision: Extract, + since: string +) { + const r = openReview(s, account, decision.kind, decision.person, decision.message, since, decision.shown) + Object.assign(r, { + other: decision.other ? ref(decision.other) : null, + message: decision.message, + shown: decision.shown, + }) + return r +} + +/** + * Sets the record's account. Fails when the account belongs to another record or the record to another account. + * A preliminary person is linked by Auth instead (`PeopleRoles.link`). Returns whether the record had no account. + */ +export function attachAccount( + s: PeopleState, + p: Person, + account: Account, + actor: string, + how: string, + at: { date: string; now: Date }, + via = "IdP" +) { + if (Object.values(s.persons).some((other) => other.id !== p.id && other.accountSub === account.sub)) + fail("CONFLICT", "This account is already linked to another person") + if (p.authProvisional) fail("FORBIDDEN", "A Master Admin must approve this preliminary Auth person through Linking") + if (p.accountSub && p.accountSub !== account.sub) fail("CONFLICT", "Unlink the existing account first") + const wasLinked = !!p.accountSub + p.accountSub = account.sub + p.account = { status: "linked", email: account.email ?? "", via, linkedOn: at.date, how, by: actor } + p.invite = null + log(p, actor, `Linked account ${account.sub}: ${how}`, at.now) + return !wasLinked +} + +/** What My area shows someone signed in without a linked record. Opens the review the policy asks for. */ +export function signInState( + s: PeopleState, + account: Account, + since: string +): + | { state: "match"; person: Person; evidence: Evidence } + | { state: "awaiting"; person: Person | null; review: StoredReview } + | { state: "none" } { + const decision = decideFor(s, account) + if (decision.action === "confirm") return { state: "match", person: decision.person, evidence: decision.evidence } + if (decision.action === "review") reviewFor(s, account, decision, since) + const open = Object.values(s.reviews).filter( + (r) => r.sub === account.sub && !r.resolved && (r.shown === "record" || r.shown === "notice") + ) + if (!open.length) return { state: "none" } + const [only] = open + const person = open.length === 1 && only.shown === "record" && only.record ? s.persons[only.record.id] : null + return { state: "awaiting", person: person ?? null, review: only } +} + +/** The sentence My area shows while a review about the account holder is open. */ +export function awaitingReason(review: StoredReview, person: Person | null) { + if (!person) + return "An admin is checking whether you're already on PoliNetwork's lists. You don't need to ask to be added." + const approver = review.kind === "preliminary-link" ? "A Master Admin" : "HR" + return `Your verified sign-in matches this record. ${approver} will confirm the link: you don't need to ask to be added.` +} + +/** + * Preliminary persons wait for someone to sign in, who may never open My area: every account not linked yet is + * matched against them when Auth's directory changes, and reviews that no longer apply are closed. + */ +export function reconcilePreliminary(s: PeopleState, accounts: Account[], since: string) { + const persons = Object.values(s.persons) + const open = Object.values(s.reviews).filter( + (r) => !r.resolved && (r.kind === "preliminary-link" || !!(r.record && s.persons[r.record.id]?.authProvisional)) + ) + if (!open.length && !persons.some((p) => p.authProvisional)) return + const linked = new Set(persons.flatMap((p) => (p.accountSub && !p.authProvisional ? [p.accountSub] : []))) + const context = matchContext(s) + const decisions = new Map() + for (const account of accounts) { + if (linked.has(account.sub)) continue + const decision = decideFor(s, account, context) + decisions.set(account.sub, decision) + if (decision.action === "review" && decision.person.authProvisional) reviewFor(s, account, decision, since) + } + // Only reviews this matching opened: a correction request on a linked record is not one. + for (const r of open) { + const p = r.record ? s.persons[r.record.id] : undefined + const decision = decisions.get(r.sub) + if (decision?.action !== "review" || decision.kind !== r.kind || decision.person.id !== p?.id) r.resolved = true + } +} diff --git a/src/people/merge.ts b/src/people/merge.ts index 7bb795e..d64d3af 100644 --- a/src/people/merge.ts +++ b/src/people/merge.ts @@ -47,10 +47,6 @@ export function mergePeople( first.admin.capoScope ??= second.admin.capoScope first.admin.capoOfReference ??= second.admin.capoOfReference first.admin.availableAsCapo ||= second.admin.availableAsCapo - for (const g of second.admin.groups) - if (!first.admin.groups.some((t) => t.chatId === g.chatId)) first.admin.groups.push(g) - for (const g of second.admin.requested) - if (!first.admin.requested.some((t) => t.chatId === g.chatId)) first.admin.requested.push(g) } first.profile.telegramId ??= second.profile.telegramId first.profile.phone ||= second.profile.phone @@ -93,7 +89,6 @@ export function mergePeople( if (second.notes) first.notes = [first.notes, `${second.id}: ${second.notes}`].filter(Boolean).join("\n") first.activity = [...first.activity, ...second.activity].sort((a, b) => b.at.localeCompare(a.at)) first.discrepancies.push(...second.discrepancies) - first.pendingGroupRemovals = [...(first.pendingGroupRemovals ?? []), ...(second.pendingGroupRemovals ?? [])] for (const p of Object.values(s.persons)) if (p.admin?.capoOfReference?.id === second.id) p.admin.capoOfReference = { id: first.id, name: `${first.profile.firstName} ${first.profile.lastName}` } diff --git a/src/people/model.ts b/src/people/model.ts index 6f4456e..41560d1 100644 --- a/src/people/model.ts +++ b/src/people/model.ts @@ -1,7 +1,7 @@ import { createHash, randomUUID } from "node:crypto" import { TRPCError } from "@trpc/server" import * as C from "./contract" -import type { Officer, PeopleConfig, PeopleState, Person, StoredReceipt, UnitOfWork, Viewer } from "./types" +import type { MailAction, Officer, PeopleConfig, PeopleState, Person, StoredReceipt, UnitOfWork, Viewer } from "./types" export function fail( code: "BAD_REQUEST" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "PRECONDITION_FAILED", @@ -26,6 +26,11 @@ export function academicYear(date: string) { const y = Number(date.slice(0, 4)) - (Number(date.slice(5, 7)) < 9 ? 1 : 0) return `${y}/${String(y + 1).slice(-2)}` } +/** A `YYYY-MM-DD` date as Italian emails write it, e.g. "31 ottobre 2026". */ +export const longDate = (date: string) => + new Intl.DateTimeFormat("it-IT", { timeZone: "UTC", day: "numeric", month: "long", year: "numeric" }).format( + new Date(`${date}T00:00:00Z`) + ) export const dueDate = (year: string) => `${year.slice(0, 4)}-10-31` export function find(state: PeopleState, id: string) { return state.persons[id] ?? fail("NOT_FOUND", "Person not found") @@ -44,7 +49,7 @@ export function requireOwn(s: PeopleState, v: Viewer) { requireSelf(v) return own(s, v) ?? fail("FORBIDDEN", "Confirm your account link first") } -export function leads(p: Person | null, team?: C.TeamId) { +export function leads(p: Pick | null, team?: C.TeamId) { return p?.teams.filter((m) => !m.endedOn && m.role === "lead" && (!team || m.team === team)).map((m) => m.team) ?? [] } export function teamAccess(s: PeopleState, v: Viewer, team: C.TeamId, write: boolean) { @@ -87,6 +92,7 @@ export function row( const contacts = self || general(v, "people:read") || scopedContacts return C.personRowSchema.parse({ ...p, + preliminary: p.authProvisional === true, profile: { ...p.profile, personalEmail: contacts ? p.profile.personalEmail : null, @@ -100,14 +106,10 @@ export function row( export function record(s: PeopleState, p: Person, v: Viewer, config: PeopleConfig, date: string): C.PersonRecord { const self = own(s, v)?.id === p.id const read = general(v, "people:read") - const pendingMessages = new Set(p.pendingGroupRemovals?.map((pending) => pending.message)) - const discrepancies: C.Discrepancy[] = p.discrepancies.map((item) => - pendingMessages.has(item.message) ? { ...item, kind: "admin-removal" } : item - ) return C.personRecordSchema.parse({ ...row(s, p, v, config, date), notes: read ? p.notes : null, - discrepancies: read ? discrepancies : self ? discrepancies.filter((d) => pendingMessages.has(d.message)) : [], + discrepancies: read ? p.discrepancies : [], activity: read ? p.activity : self @@ -132,10 +134,15 @@ export function newPerson(s: PeopleState, input: C.CreatePersonInput, date: stri const p: Person = { id: `P-${String(sequence).padStart(4, "0")}`, profile: { - ...input, + firstName: input.firstName, + lastName: input.lastName, + personalEmail: input.personalEmail || null, + course: input.course || "", + year: input.year || "", + campus: input.campus ?? null, phone: input.phone || null, telegramUsername: input.telegramUsername || null, - telegramId: null, + telegramId: input.telegramId || null, otherAssociations: [], studentRepresentative: null, }, @@ -146,8 +153,6 @@ export function newPerson(s: PeopleState, input: C.CreatePersonInput, date: stri since: date, endedOn: null, endReason: null, - groups: [], - requested: [], availableAsCapo: false, capoOfReference: null, capoScope: null, @@ -204,8 +209,7 @@ export function queue( to: string, subject: string, text: string, - fileId: string | null = null, - receiptId: string | null = null + action: MailAction | null = null ) { if (s.outbox[id]?.status === "failed") { s.outbox[id].status = "pending" @@ -218,8 +222,9 @@ export function queue( to, subject, text, - fileId, - receiptId, + action, + fileId: null, + receiptId: null, status: "pending", attemptedAt: null, error: null, diff --git a/src/people/roles.ts b/src/people/roles.ts new file mode 100644 index 0000000..4be5ffb --- /dev/null +++ b/src/people/roles.ts @@ -0,0 +1,438 @@ +import * as C from "./contract" +import { sharesVerified } from "./identity" +import { accountOf, attachAccount, decideFor, matchContext, reviewFor } from "./linking" +import { academicYear, log, newPerson } from "./model" +import type { PeopleState, Person } from "./types" + +/** + * Roles in PoliNetwork Auth that Master Admin bound to People: `admin`, `team::member` or `team::lead`. + * PoliNetwork Auth is the source of truth for who holds them; People mirrors them on each person's record and changes + * them through `PeopleRoles.change`, which checks again what the acting dashboard user may do. + */ +export type RoleDirectory = { + roles: { key: string; name: string; binding: string }[] + users: { + sub: string + registrationId?: string + provisional?: boolean + previousSub?: string + firstName?: string + lastName?: string + phone?: string | null + declaredTelegramId?: string | null + declaredTelegramUsername?: string | null + name: string + /** Contact address, for display. */ + email: string | null + /** The address Auth verified; the only one People matches on. */ + verifiedEmail?: string | null + azureId?: string | null + telegramId: string | null + telegramUsername: string | null + /** Bound roles held, including through a parent role. */ + roles: string[] + /** Those given directly, the only ones a change can take back; all of `roles` when absent. */ + assigned?: string[] + /** When each held role was first given (`YYYY-MM-DD`), when Auth says. */ + since?: Record + }[] +} +export type RoleChange = { + id: string + actor: string + sub: string + reason: string + changes: ({ kind: "admin"; active: boolean } | { kind: "team"; team: C.TeamId; role: "member" | "lead" | null })[] +} +export type RoleResult = { roles: RoleDirectory["roles"]; held: string[]; assigned: string[] } +export type CreateAuthPerson = { + operation: "create-person" + id: string + actor: string + firstName: string + lastName: string + email: string + phone: string + telegramId: string + telegramUsername: string + changes: RoleChange["changes"] +} +export type LinkAuthPerson = { + operation: "link-person" + id: string + actor: string + personId: string + userId: string + reason: string +} +export type UnlinkAuthPerson = { + operation: "unlink-person" + id: string + actor: string + personId: string + reason: string +} +export type UpdateAuthPerson = Omit & { + operation: "update-person" + personId: string +} +export type PeopleRoles = { + update?(input: UpdateAuthPerson): Promise<{ sub: string }> + create?(input: CreateAuthPerson): Promise<{ sub: string }> + link?(input: LinkAuthPerson): Promise<{ sub: string }> + unlink?(input: UnlinkAuthPerson): Promise<{ sub: string }> + directory(): Promise + change(change: RoleChange): Promise +} +/** A member of the Microsoft 365 Soci group. */ +export type AzureMember = { + id: string + mail: string + givenName: string | null + surname: string | null + displayName: string | null + employeeId: string | null + /** The account's creation date (`YYYY-MM-DD`), the best known admission date. */ + createdOn: string | null +} + +/** PoliNetwork Auth refused or failed a role change; `status` is its HTTP status. */ +export class RoleChangeError extends Error { + constructor( + readonly status: number, + message: string + ) { + super(message) + } +} + +type TeamRole = C.TeamMembership["role"] +export type Bound = { admin: string[]; teams: Record> } +/** A person's active roles, as People shows them. */ +export type RoleView = { admin: boolean; teams: Partial> } + +const isTeam = (value: string): value is C.TeamId => (C.TEAM_IDS as readonly string[]).includes(value) + +/** Role keys by what they mean in People. Bindings to unknown teams are ignored. */ +export function boundRoles(directory: RoleDirectory): Bound { + const bound: Bound = { + admin: [], + teams: Object.fromEntries( + C.TEAM_IDS.map((id) => [id, { member: [] as string[], lead: [] as string[] }]) + ) as Bound["teams"], + } + for (const role of directory.roles) { + if (role.binding === "admin") bound.admin.push(role.key) + const [kind, team, as] = role.binding.split(":") + if (kind === "team" && isTeam(team) && (as === "member" || as === "lead")) bound.teams[team][as].push(role.key) + } + return bound +} + +const teamBound = (bound: Bound, team: C.TeamId) => bound.teams[team].member.length + bound.teams[team].lead.length > 0 + +/** The roles PoliNetwork Auth says this account holds; a Lead role wins over a member one. */ +export function wantedView(bound: Bound, held: readonly string[]): RoleView { + const view: RoleView = { admin: bound.admin.some((key) => held.includes(key)), teams: {} } + for (const team of C.TEAM_IDS) { + if (bound.teams[team].lead.some((key) => held.includes(key))) view.teams[team] = "lead" + else if (bound.teams[team].member.some((key) => held.includes(key))) view.teams[team] = "member" + } + return view +} + +export function roleView(p: Pick): RoleView { + const view: RoleView = { admin: p.admin?.status === "active", teams: {} } + for (const t of p.teams) if (!t.endedOn) view.teams[t.team] = t.role + return view +} + +/** Send desired organizational states; Auth chooses and validates the actual role assignments. */ +export function roleChanges(before: RoleView, after: RoleView): RoleChange["changes"] { + const changes: RoleChange["changes"] = [] + if (before.admin !== after.admin) changes.push({ kind: "admin", active: after.admin }) + for (const team of C.TEAM_IDS) + if (before.teams[team] !== after.teams[team]) changes.push({ kind: "team", team, role: after.teams[team] ?? null }) + return changes +} + +/** A record with only a name, for someone People hears of from PoliNetwork Auth or Microsoft 365. */ +export function blankPerson(s: PeopleState, name: { first: string; last: string }, date: string) { + const p = newPerson( + s, + { + firstName: name.first, + lastName: name.last, + personalEmail: "", + phone: "", + telegramUsername: "", + course: "", + year: "Graduated", + campus: "External", + admin: false, + }, + date + ) + Object.assign(p.profile, { personalEmail: null, course: "", year: "", campus: null }) + return p +} + +function splitName(name: string) { + const parts = name.trim().split(/\s+/).filter(Boolean) + return { first: parts.shift() ?? "", last: parts.join(" ") } +} + +const lower = (value: string | null | undefined) => value?.trim().toLowerCase() || null + +type Clock = { date: string; now: Date } +/** Asks HR to look at the record, once per distinct reason. */ +export function flagForReview(p: Person, message: string) { + if (!p.discrepancies.some((d) => d.message === message)) + p.discrepancies.push({ kind: "needs-review", message, suggestedTelegram: null }) +} + +/** + * Mirrors PoliNetwork Auth's bound roles on People records: + * - everyone holding one gets a record: theirs, one matched by `linking.ts` (linked automatically only by a + * Microsoft 365 identity, otherwise reviewed by HR), or a new one; + * - on linked records, a bound role's entry starts when the role is held and ends when it was mirrored and is no + * longer held. Previously local entries on linked records also follow Auth. + * Concepts with no bound role (for example a team nobody bound yet) stay owned by People. + */ +export function syncDirectory(s: PeopleState, directory: RoleDirectory, at: Clock) { + const bound = boundRoles(directory) + const persons = () => Object.values(s.persons) + const users = new Map(directory.users.map((u) => [u.sub, u])) + // Auth lists every account: look records up by key instead of scanning the register for each one. + const context = matchContext(s) + const bySub = new Map(persons().flatMap((p) => (p.accountSub ? [[p.accountSub, p] as const] : []))) + const byRegistration = new Map( + persons().flatMap((p) => (p.authRegistrationId ? [[p.authRegistrationId, p] as const] : [])) + ) + for (const u of directory.users) { + const wanted = wantedView(bound, u.roles) + const existing = bySub.get(u.sub) ?? (u.registrationId ? byRegistration.get(u.registrationId) : undefined) + const holds = wanted.admin || Object.keys(wanted.teams).length > 0 + // Accounts without a bound role only refresh the identities of the record already linked to them. + if (!existing && !u.registrationId && !holds) continue + const account = accountOf(u) + // Records other than its own holding this account's verified identity. + const holders = [...context.index.candidates(account)].filter( + (other) => + other !== existing && + !other.authProvisional && + (!!existing || !!other.accountSub) && + sharesVerified(other, account) + ) + let p: Person + // Never move an identity off the record holding it, or give it a second record: HR decides. + if (holders.length || (existing?.azureId && u.azureId && existing.azureId !== u.azureId)) { + for (const other of existing ? [existing, ...holders] : holders) + flagForReview( + other, + `PoliNetwork Auth account ${u.sub} matches more than one record: check their account links.` + ) + continue + } + if (existing) { + p = existing + if (p.account.status === "linked") p.account.email = u.email ?? p.account.email + } else if (u.registrationId) { + p = blankPerson(s, splitName(u.name), at.date) + log(p, "system", "Created from a preliminary person in PoliNetwork Auth", at.now) + } else { + const decision = decideFor(s, account, context) + if (decision.action === "review") { + reviewFor(s, account, decision, at.date) + continue + } + if (decision.action === "link") p = decision.person + else { + p = blankPerson(s, splitName(u.name), at.date) + log(p, "system", "Created from a role held in PoliNetwork Auth", at.now) + } + attachAccount(s, p, account, "system", "Holds a People role in PoliNetwork Auth", at, "PoliNetwork Auth") + bySub.set(u.sub, p) + } + if (u.registrationId) { + p.authRegistrationId = u.registrationId + p.authProvisional = u.provisional === true + p.accountSub = u.sub + p.profile.firstName = u.firstName ?? p.profile.firstName + p.profile.lastName = u.lastName ?? p.profile.lastName + p.profile.phone = u.phone ?? null + if (u.provisional) { + p.account = { status: "none" } + p.profile.personalEmail = u.email + p.profile.telegramId = u.declaredTelegramId ?? null + p.profile.telegramUsername = u.declaredTelegramUsername ?? null + } else if (p.account.status !== "linked") { + p.account = { + status: "linked", + email: u.email ?? "", + via: "PoliNetwork Auth", + linkedOn: at.date, + how: "Master Admin approved the preliminary identity", + } + } + } + // Microsoft 365 members are matched by this ID, so a later PoliNetwork address doesn't make a second record. + if (u.azureId) p.azureId = u.azureId + if (!p.profile.telegramId && u.telegramId) p.profile.telegramId = u.telegramId + p.profile.telegramUsername ||= u.telegramUsername + context.index.add(p) + } + + for (const p of persons()) { + if (!p.accountSub || (p.account.status !== "linked" && !p.authProvisional) || p.roleCommand) continue + const u = users.get(p.accountSub) + syncPersonRoles(p, bound, wantedView(bound, u?.roles ?? []), at, u?.since) + } +} + +/** The earliest date Auth gave one of these roles, or today when it doesn't say. */ +function sinceOf(keys: readonly string[], since: Record | undefined, today: string) { + return ( + keys + .map((key) => since?.[key]) + .filter((d): d is string => !!d) + .sort()[0] ?? today + ) +} + +/** + * For linked records Auth owns every bound concept, including previously local entries: an entry is active exactly + * while its role is held, starting when Auth gave it. + */ +export function syncPersonRoles(p: Person, bound: Bound, wanted: RoleView, at: Clock, since?: Record) { + if (bound.admin.length) { + if (wanted.admin && p.admin?.status !== "active") { + p.admin = { + availableAsCapo: false, + capoOfReference: null, + capoScope: null, + ...p.admin, + status: "active", + since: sinceOf(bound.admin, since, at.date), + endedOn: null, + endReason: null, + } + log(p, "system", "Started admin role: held in PoliNetwork Auth", at.now) + } else if (!wanted.admin && p.admin?.status === "active") { + Object.assign(p.admin, { + status: "former", + endedOn: at.date, + endReason: "Not held in PoliNetwork Auth", + capoScope: null, + }) + log(p, "system", "Ended admin role: not held in PoliNetwork Auth", at.now) + } + } + for (const team of C.TEAM_IDS) { + if (!teamBound(bound, team)) continue + const role = wanted.teams[team] + const active = p.teams.find((t) => t.team === team && !t.endedOn) + if (role && !active) { + p.teams.push({ + team, + role, + since: sinceOf(bound.teams[team][role], since, at.date), + endedOn: null, + endReason: null, + fields: {}, + }) + log(p, "system", `Joined ${team} as ${role}: held in PoliNetwork Auth`, at.now) + } else if (role && active && active.role !== role) { + active.role = role + log(p, "system", `Became ${role} of ${team}: held in PoliNetwork Auth`, at.now) + } else if (!role && active) { + Object.assign(active, { endedOn: at.date, endReason: "Not held in PoliNetwork Auth" }) + log(p, "system", `Ended ${team}: not held in PoliNetwork Auth`, at.now) + } + } +} + +/** How long a member admitted from People may be missing from the Soci group listing before it counts. */ +const ADMISSION_GRACE_DAYS = 2 + +const usableNumber = (employeeId: string | null) => { + const digits = employeeId?.trim() ?? "" + return { digits, number: /^\d{1,4}$/.test(digits) ? digits.padStart(4, "0") : null } +} + +/** + * Applies the Microsoft 365 Soci group, which decides who is a member and their number (`employeeId`): + * - each group member is matched by Microsoft 365 account or address, or by the PoliNetwork address of a linked + * account, otherwise gets a new record, and takes the account's number; + * - a member of the register who is no longer in the group becomes former, unless admitted in the last + * {@link ADMISSION_GRACE_DAYS} days, which the group listing may not show yet. + * The register keeps only what Microsoft 365 doesn't: suspension or expiry, the admission date, fees and history. + */ +export function syncMembers(s: PeopleState, members: AzureMember[], at: Clock) { + const persons = () => Object.values(s.persons) + const inGroup = new Set() + for (const m of members) { + const mail = lower(m.mail) + if (!mail) continue + const matches = persons().filter( + (p) => + p.azureId === m.id || + lower(p.member?.m365Email) === mail || + (p.account.status === "linked" && lower(p.account.email) === mail) + ) + if (matches.length > 1 || matches.some((p) => p.azureId && p.azureId !== m.id)) { + for (const p of matches) + flagForReview(p, "Microsoft 365 identities match conflicting People records; review the account links.") + continue + } + const match = matches[0] + const p = + match ?? + blankPerson( + s, + m.givenName || m.surname + ? { first: m.givenName?.trim() ?? "", last: m.surname?.trim() ?? "" } + : splitName(m.displayName ?? mail.split("@")[0]), + at.date + ) + if (!match) log(p, "system", "Created from the Microsoft 365 Soci group", at.now) + p.azureId ??= m.id + inGroup.add(p.id) + const { digits, number } = usableNumber(m.employeeId) + if (!number || persons().some((other) => other !== p && other.member?.number === number)) { + flagForReview(p, `In the Microsoft 365 Soci group without a usable member number (${digits || "none"})`) + if (p.member) p.member.m365Email = m.mail + continue + } + if (p.member) { + if (p.member.number !== number) log(p, "system", `Member number ${number} in Microsoft 365`, at.now) + if (p.member.status === "former") { + p.member.status = "active" + log(p, "system", "Back in the Microsoft 365 Soci group", at.now) + } + Object.assign(p.member, { number, m365Email: m.mail }) + continue + } + p.member = { + number, + status: "active", + admittedOn: m.createdOn ?? at.date, + fee: "due", + m365Email: m.mail, + } + p.importedFeeYear = academicYear(at.date) + log( + p, + "system", + `Member ${number} in the Microsoft 365 Soci group${m.createdOn ? "; admission date taken from the account's creation" : ""}`, + at.now + ) + } + + const grace = new Date(at.now.getTime() - ADMISSION_GRACE_DAYS * 86_400_000).toISOString().slice(0, 10) + for (const p of persons()) + if (p.member && p.member.status !== "former" && !inGroup.has(p.id) && p.member.admittedOn < grace) { + p.member.status = "former" + log(p, "system", "Not in the Microsoft 365 Soci group: no longer a member", at.now) + } +} diff --git a/src/people/router.ts b/src/people/router.ts index adeeb14..02e3626 100644 --- a/src/people/router.ts +++ b/src/people/router.ts @@ -152,6 +152,7 @@ export function createPeopleRouter(people: PeopleService) { .mutation(({ ctx, input }) => people.resolveReview(ctx.viewer, input)), dismiss: write.input(C.reviewInputSchema).mutation(({ ctx, input }) => people.dismissReview(ctx.viewer, input)), invites: read.output(C.inviteSchema.array()).query(({ ctx }) => people.listInvites(ctx.viewer)), + recent: read.output(C.recentLinkSchema.array()).query(({ ctx }) => people.listRecentLinks(ctx.viewer)), sendInvite: write .input(C.personRefInputSchema) .mutation(({ ctx, input }) => people.sendInvite(ctx.viewer, input)), @@ -167,12 +168,6 @@ export function createPeopleRouter(people: PeopleService) { }), capo: createTRPCRouter({ get: self.output(C.capoAreaSchema).query(({ ctx }) => people.getCapoArea(ctx.viewer)), - approve: self - .input(C.joinRequestInputSchema) - .mutation(({ ctx, input }) => people.handleJoinRequest(ctx.viewer, input, true)), - decline: self - .input(C.joinRequestInputSchema) - .mutation(({ ctx, input }) => people.handleJoinRequest(ctx.viewer, input, false)), }), me: createTRPCRouter({ roles: self.output(C.myRolesSchema).query(({ ctx }) => people.getMyRoles(ctx.viewer)), diff --git a/src/people/service.ts b/src/people/service.ts index a06bfbf..828e6f0 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -1,7 +1,17 @@ import { randomBytes, randomUUID } from "node:crypto" import { zipSync } from "fflate" import * as C from "./contract" +import { evidenceBetween } from "./identity" import { MAX_FILE_BYTES, parseImport } from "./imports" +import { + accountsOf, + attachAccount, + awaitingReason, + decideFor, + openReview, + reconcilePreliminary, + signInState, +} from "./linking" import { mergePeople } from "./merge" import { academicYear, @@ -15,6 +25,7 @@ import { hash, leads, log, + longDate, nameOf, newestReceipts, newPerson, @@ -33,15 +44,30 @@ import { validateFields, } from "./model" import { receiptPdf } from "./pdf" +import { + type AzureMember, + boundRoles, + flagForReview, + type PeopleRoles, + RoleChangeError, + type RoleDirectory, + type RoleResult, + roleChanges, + roleView, + syncDirectory, + syncMembers, + syncPersonRoles, + wantedView, +} from "./roles" import type { Account, ImportRow, + MailAction, PeopleConfig, PeopleState, PeopleStore, Person, StoredReceipt, - TelegramGroup, TelegramUser, UnitOfWork, Viewer, @@ -51,8 +77,8 @@ export type PeopleOptions = { store: PeopleStore config: PeopleConfig now?: () => Date - directory: () => Promise - telegramGroups: () => Promise + /** Accounts when People runs without PoliNetwork Auth (development and tests); otherwise Auth's People directory. */ + directory?: () => Promise telegramUsers: () => Promise provisionMember: (person: Person, number: string) => Promise<{ id: string; email: string }> setMemberNumber: (person: Person, number: string) => Promise @@ -61,37 +87,272 @@ export type PeopleOptions = { to: string subject: string text: string + /** The recipient's first name, for the greeting. */ + firstName: string | null + action: MailAction | null attachment: { fileName: string; contentType: string; content: Uint8Array } | null }) => Promise verifySigned: (sub: string, requestId: string, bytes: Uint8Array) => Promise<{ signer: string; content: Uint8Array }> inspectSigned: (sub: string, bytes: Uint8Array) => Promise<{ signer: string }> completeSigned: (sub: string, requestId: string, bytes: Uint8Array) => Promise transferType: (bytes: Uint8Array) => Promise + /** Roles bound to People in PoliNetwork Auth; `null` when the backend can't reach it. */ + allowLocalPeople?: boolean + peopleRoles?: PeopleRoles | null + /** Members of the Microsoft 365 Soci group. */ + azureMembers?: () => Promise +} + +/** + * How long People reuses what it read from its sources, in memory only: it stores no copy of them. PoliNetwork Auth + * decides who holds which role, Microsoft 365 who is a member and their number, Telegram who administers a group. + */ +export const SOURCE_TTL_MS = { directory: 15_000, members: 5 * 60_000 } +/** Past this, People refuses to work rather than decide who leads or administers from an old answer. */ +export const DIRECTORY_MAX_AGE_MS = 60 * 60_000 +/** At most one extra read of Auth this often for an account it didn't list. */ +const UNKNOWN_ACCOUNT_REREAD_MS = 2_000 +type RoleSnapshot = Pick +const PENDING_ROLES = "A role change for this person is waiting for PoliNetwork Auth; try again in a moment." +const AWAITING_AUTH = "Awaiting confirmation from PoliNetwork Auth" + +/** + * The roles of a record about to be linked that PoliNetwork Auth has confirmed: none. Its active roles are ended until + * Auth confirms them, so a role Auth refuses never grants access; their history and details are kept. + */ +function unconfirmed(p: Person, on: string): RoleSnapshot { + const ended = { endedOn: on, endReason: AWAITING_AUTH } + return structuredClone({ + admin: + p.admin?.status === "active" ? { ...p.admin, ...ended, status: "former" as const, capoScope: null } : p.admin, + teams: p.teams.map((t) => (t.endedOn ? t : { ...t, ...ended })), + }) } export function createPeopleService(options: PeopleOptions) { const { store, config } = options + /** The account holder's area in the dashboard, where every People email leads. */ + const AREA = `${config.dashboardUrl}/dashboard/account/me` + const feeReminder = (f: { year: string; dueOn: string; amountCents: number }) => + `ti ricordiamo che la quota associativa ${f.year} di PoliNetwork, di ${(f.amountCents / 100).toLocaleString("it-IT", { style: "currency", currency: "EUR" })}, è da versare. Scadenza: ${longDate(f.dueOn)}.\n\nNella tua area personale trovi le coordinate per il bonifico e puoi caricare la ricevuta. Se l'hai già versata, ignora questo messaggio.` const now = options.now ?? (() => new Date()) const date = () => today(now()) const year = () => academicYear(date()) - const tx = (fn: (u: UnitOfWork) => Promise | T) => store.transaction(async (u) => fn(u)) + /** + * A People transaction on the register alone. Role commands it records for PoliNetwork Auth are delivered after it + * commits, so the People lock is never held across a call to Auth; a refused direct dashboard change (`strict`) then + * fails the call. Only internal work (deliveries, the sweep) uses it directly: everything else goes through `tx`. + */ + const commit = async (fn: (u: UnitOfWork) => Promise | T): Promise => { + let queued: { personId: string; strict: boolean }[] = [] + const result = await store.transaction(async (u) => { + const known = new Set(Object.values(u.state.persons).flatMap((p) => p.roleCommand?.request.id ?? [])) + const result = await fn(u) + queued = Object.values(u.state.persons).flatMap((p) => + p.roleCommand && !known.has(p.roleCommand.request.id) ? [{ personId: p.id, strict: p.roleCommand.strict }] : [] + ) + return result + }) + for (const command of queued) { + const error = await deliverRoleCommand(command.personId) + if (error && command.strict) + fail( + error.status === 403 ? "FORBIDDEN" : error.status === 404 ? "NOT_FOUND" : "PRECONDITION_FAILED", + error.message + ) + } + return result + } + type SourceRead = { value: T; at: number; revision: number } + let directoryRead: SourceRead | null = null + /** When an unknown account last made People read Auth again, so unknown callers can't make it read on every call. */ + let unknownAccountReadAt = 0 + let membersRead: SourceRead | null = null + /** Who holds the roles bound to People, from PoliNetwork Auth; null when People has no Auth to ask. */ + async function readDirectory(force = false): Promise | null> { + if (!options.peopleRoles) return null + const at = now().getTime() + if (!force && directoryRead && at - directoryRead.at < SOURCE_TTL_MS.directory) return directoryRead + // A role command confirmed while Auth answers would make this answer older than the register's history. + const revision = await commit((u) => u.state.counters.roleRevision ?? 0) + try { + directoryRead = { value: await options.peopleRoles.directory(), at, revision } + } catch (error) { + if (!directoryRead || at - directoryRead.at > DIRECTORY_MAX_AGE_MS) + fail("PRECONDITION_FAILED", "PoliNetwork Auth can't be reached: People can't tell who holds which role") + console.error(error) + } + return directoryRead + } + /** Login accounts and the identity each proved, from the same PoliNetwork Auth answer as the roles. */ + async function readAccounts(force = false): Promise { + if (!options.peopleRoles) return (await options.directory?.()) ?? [] + const read = await readDirectory(force) + return read ? accountsOf(read.value) : [] + } + /** The signed-in account; Auth is read again for one it doesn't know yet, so a first sign-in is not missed. */ + async function readAccount(sub: string): Promise { + const known = (await readAccounts()).find((a) => a.sub === sub) + if (known || now().getTime() - unknownAccountReadAt < UNKNOWN_ACCOUNT_REREAD_MS) return known + unknownAccountReadAt = now().getTime() + return (await readAccounts(true)).find((a) => a.sub === sub) + } + /** The Microsoft 365 Soci group; null without Microsoft 365, or while it has never answered. */ + async function readMembers(force = false): Promise | null> { + if (!options.azureMembers) return null + const at = now().getTime() + if (!force && membersRead && at - membersRead.at < SOURCE_TTL_MS.members) return membersRead + try { + membersRead = { value: await options.azureMembers(), at, revision: 0 } + } catch (error) { + console.error(error) + } + return membersRead + } + /** Lays the sources over the register: their answer wins, and the register keeps only history and its own data. */ + function applySources( + s: PeopleState, + directory: SourceRead | null, + members: SourceRead | null + ) { + const at = { date: date(), now: now() } + if (directory) { + if (directory.revision === (s.counters.roleRevision ?? 0)) { + syncDirectory(s, directory.value, at) + // Stored with the register, so a transaction that fails doesn't skip the next pass. + if (s.counters.preliminaryReconciledAt !== directory.at) { + reconcilePreliminary(s, accountsOf(directory.value), at.date) + s.counters.preliminaryReconciledAt = directory.at + } + } else directoryRead = null + } + if (members) syncMembers(s, members.value, at) + } + /** A People transaction that first lays PoliNetwork Auth and Microsoft 365 over the register. */ + const tx = async (fn: (u: UnitOfWork) => Promise | T): Promise => { + const [directory, members] = await Promise.all([readDirectory(), readMembers()]) + return commit((u) => { + applySources(u.state, directory, members) + return fn(u) + }) + } const currentFee = (p: Person) => fee(p, config, date()) ?? fail("CONFLICT", "This person is not a current member") - function hydrateGroups(s: PeopleState, groups: TelegramGroup[]) { - for (const p of Object.values(s.persons)) - if (p.admin && p.profile.telegramId) { - const telegramId = p.profile.telegramId - const known = new Set(groups.filter((g) => g.admins).map((g) => g.chatId)) - p.admin.groups = [ - ...p.admin.groups.filter((g) => !known.has(g.chatId)), - ...groups.filter((g) => g.admins?.includes(telegramId)).map(({ chatId, title }) => ({ chatId, title })), - ] - p.pendingGroupRemovals = p.pendingGroupRemovals?.filter((pending) => { - if (!known.has(pending.chatId) || p.admin?.groups.some((g) => g.chatId === pending.chatId)) return true - p.discrepancies = p.discrepancies.filter((d) => d.message !== pending.message) - log(p, "system", `Telegram confirmed admin removal from ${pending.chatId}`, now()) - return false - }) + const roleViews = (s: PeopleState) => + new Map( + Object.values(s.persons).map((p) => [p.id, structuredClone({ admin: p.admin, teams: p.teams })]) + ) + /** Lets a sync tell whether a role changed while it read PoliNetwork Auth. */ + const bumpRoles = (s: PeopleState) => { + s.counters.roleRevision = (s.counters.roleRevision ?? 0) + 1 + } + const settled = (p: Person) => { + if (p.roleCommand) fail("CONFLICT", PENDING_ROLES) + } + + /** + * Turns the roles just changed on linked records into one command each for PoliNetwork Auth, acting as `actor`, who + * must be allowed to there too. Until Auth confirms it, the record keeps the roles it had (`before`): a requested + * role grants nothing. `strict` (a direct dashboard action) fails the call on a refusal; otherwise (census, import, + * linking) the refusal is noted on the record for HR. + */ + function pushRoles( + s: PeopleState, + before: Map, + actor: string, + reason: string, + strict: boolean + ) { + if (!options.peopleRoles) return + for (const p of Object.values(s.persons)) { + const was = before.get(p.id) + if (!was || !p.accountSub || (p.account.status !== "linked" && !p.authProvisional)) continue + const changes = roleChanges(roleView(was), roleView(p)) + if (!changes.length) continue + settled(p) + p.roleCommand = { + // PoliNetwork Auth keeps reasons of up to 500 characters. + request: { id: randomUUID(), actor, sub: p.accountSub, reason: reason.slice(0, 500), changes }, + desired: structuredClone({ admin: p.admin, teams: p.teams }), + strict, } + for (const change of changes) + if (change.kind === "admin") p.admin = structuredClone(was.admin) + else + p.teams = [ + ...p.teams.filter((t) => t.team !== change.team), + ...structuredClone(was.teams.filter((t) => t.team === change.team)), + ] + log(p, actor, `Asked PoliNetwork Auth to change roles: ${reason}`, now()) + bumpRoles(s) + } + } + + /** + * Sends a person's pending role command and applies Auth's answer. A refusal drops it; no answer (Auth unreachable, + * failing, or the response lost) keeps it for the sweep to send again with the same ID, which Auth applies once. + */ + async function deliverRoleCommand(personId: string): Promise { + const pending = await commit((u) => structuredClone(u.state.persons[personId]?.roleCommand)) + if (!pending || !options.peopleRoles) return null + const { request } = pending + let result: RoleResult + try { + result = await options.peopleRoles.change(request) + } catch (error) { + if (!(error instanceof RoleChangeError)) console.error(error) + const failure = error instanceof RoleChangeError ? error : new RoleChangeError(503, "No answer") + const unanswered = failure.status >= 500 || failure.status === 408 || failure.status === 429 + await commit((u) => { + const p = u.state.persons[personId] + if (p?.roleCommand?.request.id !== request.id) return + if (unanswered) { + if (!pending.unanswered) + log( + p, + request.actor, + `PoliNetwork Auth didn't answer (${failure.message}); the change will be retried`, + now() + ) + p.roleCommand.unanswered = true + return + } + delete p.roleCommand + for (const t of p.teams) if (t.endReason === AWAITING_AUTH) t.endReason = "Not confirmed by PoliNetwork Auth" + if (p.admin?.endReason === AWAITING_AUTH) p.admin.endReason = "Not confirmed by PoliNetwork Auth" + log(p, request.actor, `PoliNetwork Auth refused the role change: ${failure.message}`, now()) + if (!pending.strict) + flagForReview( + p, + `PoliNetwork Auth refused a role change (${request.reason}): ${failure.message} Its roles stay as Auth holds them: change them again from People or in Auth.` + ) + bumpRoles(u.state) + }) + return new RoleChangeError( + failure.status, + unanswered + ? "PoliNetwork Auth didn't answer. The change is saved and will be retried automatically: don't repeat it." + : `PoliNetwork Auth: ${failure.message}` + ) + } + await commit((u) => { + const p = u.state.persons[personId] + if (p?.roleCommand?.request.id !== request.id) return + for (const change of request.changes) + if (change.kind === "admin") p.admin = pending.desired.admin + else + p.teams = [ + ...p.teams.filter((t) => t.team !== change.team), + ...pending.desired.teams.filter((t) => t.team === change.team), + ] + delete p.roleCommand + log(p, request.actor, `PoliNetwork Auth confirmed the role change: ${request.reason}`, now()) + // What Auth holds after the command wins, for example a role it kept through a parent role. + const bound = boundRoles({ roles: result.roles, users: [] }) + syncPersonRoles(p, bound, wantedView(bound, result.held), { date: date(), now: now() }) + bumpRoles(u.state) + }) + directoryRead = null + return null } function assertReceiptConfig(s: PeopleState) { if (!config.legalName || !config.address || !config.taxCode) @@ -213,86 +474,46 @@ export function createPeopleService(options: PeopleOptions) { log(p, actor, `Issued receipt ${receipt.number}`, now()) return { receipt: receipt.number } } - function link(s: PeopleState, p: Person, account: Account, actor: string, reason: string) { - if (Object.values(s.persons).some((other) => other.id !== p.id && other.accountSub === account.sub)) - fail("CONFLICT", "This account is already linked to another person") - if (p.accountSub && p.accountSub !== account.sub) fail("CONFLICT", "Unlink the existing account first") - p.accountSub = account.sub - p.account = { status: "linked", email: account.email ?? "", via: "IdP", linkedOn: date(), how: reason } - p.invite = null - log(p, actor, `Linked account ${account.sub}: ${reason}`, now()) + /** The one way a record gets an account: Auth links a preliminary person, People links any other record. */ + async function linkRecord(s: PeopleState, p: Person, account: Account, actor: string, reason: string) { + if (await linkPreliminaryPerson(s, p, account, actor, reason)) return + if (attachAccount(s, p, account, actor, reason, { date: date(), now: now() })) + pushRoles(s, new Map([[p.id, unconfirmed(p, date())]]), actor, `Linked in People: ${reason}`, false) } - function candidate(s: PeopleState, v: Viewer, account: Account | undefined) { - if (!account) return null - const rejected = new Set( - Object.values(s.reviews) - .filter((r) => r.sub === v.sub) - .flatMap((r) => r.rejectedPersonIds) - ) - const emailMatches = - account.emailVerified && account.email - ? Object.values(s.persons).filter( - (p) => p.profile.personalEmail?.toLowerCase() === account.email?.toLowerCase() - ) - : [] - const telegramMatch = v.telegramId - ? Object.values(s.persons).find((p) => p.profile.telegramId === v.telegramId) - : null - if (emailMatches.length > 1) { - const r = review(s, v, account, "two-records", emailMatches[0], "Several records use the same verified email") - r.other = ref(emailMatches[1]) - return null - } - if ( - emailMatches[0] && - ((telegramMatch && telegramMatch.id !== emailMatches[0].id) || - (v.telegramId && emailMatches[0].profile.telegramId && emailMatches[0].profile.telegramId !== v.telegramId)) - ) { - const r = review( - s, - v, - account, - "telegram-conflict", - emailMatches[0], - "Verified email and Telegram identity disagree" - ) - r.other = telegramMatch ? ref(telegramMatch) : null - return null - } - const candidates = Object.values(s.persons).filter( - (p) => - !p.accountSub && - !rejected.has(p.id) && - ((v.telegramId && p.profile.telegramId === v.telegramId) || - (account.emailVerified && - account.email && - p.profile.personalEmail?.toLowerCase() === account.email.toLowerCase())) - ) - if (candidates.length === 1) return candidates[0] - const nameMatch = Object.values(s.persons).find( - (p) => nameOf(p).toLowerCase() === account.name.toLowerCase() && !rejected.has(p.id) - ) - if (nameMatch) review(s, v, account, "name-only", nameMatch, "Name-only matches require HR review") - return null - } - function review(s: PeopleState, v: Viewer, account: Account, kind: C.ReviewKind, p: Person | null, message: string) { - const existing = Object.values(s.reviews).find((r) => r.sub === v.sub && r.kind === kind && !r.resolved) - if (existing) return existing - const id = randomUUID() - s.reviews[id] = { - id, - kind, - since: date(), - account: { name: account.name, email: account.email ?? "", telegram: account.telegramId, via: "IdP" }, - record: p ? ref(p) : null, - other: null, - message, - sub: v.sub, - resolved: false, - rejectedPersonIds: [], + async function linkPreliminaryPerson(s: PeopleState, p: Person, account: Account, actor: string, reason: string) { + if (!p.authProvisional || !p.authRegistrationId) return false + settled(p) + if (Object.values(s.persons).some((other) => other.id !== p.id && other.accountSub === account.sub)) + fail("CONFLICT", "This account already has a People record; review the duplicate before linking") + if (!options.peopleRoles?.link) fail("PRECONDITION_FAILED", "Auth identity linking is unavailable") + const result = await options.peopleRoles.link({ + operation: "link-person", + id: randomUUID(), + actor, + personId: p.authRegistrationId, + userId: account.sub, + reason, + }) + if (result.sub !== account.sub) fail("PRECONDITION_FAILED", "Auth returned another account for this link") + p.accountSub = result.sub + p.authProvisional = false + p.account = { + status: "linked", + email: account.email ?? "", + via: "PoliNetwork Auth", + linkedOn: date(), + how: "Master Admin approved the preliminary identity", + by: actor, } - return s.reviews[id] + directoryRead = null + bumpRoles(s) + log(p, actor, `Auth approved the preliminary identity link: ${reason}`, now()) + return true } + const roleNames = (p: Person) => [ + ...(p.admin?.status === "active" ? ["Admin"] : []), + ...p.teams.filter((t) => !t.endedOn).map((t) => C.TEAMS[t.team].name), + ] const receiptForOfficer = (s: PeopleState, v: Viewer, id: string, cie: boolean) => { requireGeneral(v, "people:receipts:sign") const r = findReceipt(s, id) @@ -321,23 +542,45 @@ export function createPeopleService(options: PeopleOptions) { return { async listPeople(v: Viewer) { requireGeneral(v, "people:read") - const telegramGroups = await options.telegramGroups() return tx((u) => { - hydrateGroups(u.state, telegramGroups) activeCampaign(u.state) return Object.values(u.state.persons).map((p) => row(u.state, p, v, config, date())) }) }, async getPerson(v: Viewer, input: { id: string }) { requireGeneral(v, "people:read") - const telegramGroups = await options.telegramGroups() return tx((u) => { - hydrateGroups(u.state, telegramGroups) return record(u.state, find(u.state, input.id), v, config, date()) }) }, - async createPerson(v: Viewer, input: C.CreatePersonInput) { + async createPerson(v: Viewer, raw: C.CreatePersonInput) { requireGeneral(v, "people:write") + const input = C.createPersonInputSchema.parse(raw) + if (options.peopleRoles?.create) { + const created = await options.peopleRoles.create({ + operation: "create-person", + id: input.requestId ?? randomUUID(), + actor: v.sub, + firstName: input.firstName, + lastName: input.lastName, + email: input.personalEmail, + phone: input.phone, + telegramId: input.telegramId, + telegramUsername: input.telegramUsername, + changes: [ + ...(input.admin ? [{ kind: "admin" as const, active: true }] : []), + ...input.teams.map((team) => ({ kind: "team" as const, team, role: "member" as const })), + ], + }) + directoryRead = null + return tx((u) => { + const person = Object.values(u.state.persons).find((p) => p.accountSub === created.sub) + if (!person) fail("PRECONDITION_FAILED", "Auth saved the person; refresh People before retrying") + return { id: person.id } + }) + } + if (!options.allowLocalPeople) + fail("PRECONDITION_FAILED", "Auth person creation is unavailable; no local person was created") return tx((u) => { const p = newPerson(u.state, input, date()) log(p, v.sub, "Created person", now()) @@ -347,8 +590,24 @@ export function createPeopleService(options: PeopleOptions) { }, async updatePerson(v: Viewer, input: C.UpdatePersonInput) { requireGeneral(v, "people:write") - return tx((u) => { + return tx(async (u) => { const p = find(u.state, input.id) + if (p.authRegistrationId) { + if (!options.peopleRoles?.update) fail("PRECONDITION_FAILED", "Auth contact editing is unavailable") + await options.peopleRoles.update({ + operation: "update-person", + id: randomUUID(), + actor: v.sub, + personId: p.authRegistrationId, + firstName: input.firstName, + lastName: input.lastName, + email: input.personalEmail, + phone: input.phone, + telegramId: p.profile.telegramId ?? "", + telegramUsername: input.telegramUsername, + }) + directoryRead = null + } const { id: _, ...profile } = input Object.assign(p.profile, profile) log(p, v.sub, "Updated profile", now()) @@ -388,6 +647,8 @@ export function createPeopleService(options: PeopleOptions) { assertReceiptConfig(u.state) } const azure = await options.provisionMember(p, input.number) + // Microsoft 365 now lists the new member: read the Soci group again. + membersRead = null p.azureId = azure.id p.member = { number: input.number, @@ -428,6 +689,7 @@ export function createPeopleService(options: PeopleOptions) { if (Object.values(u.state.persons).some((o) => o.id !== p.id && o.member?.number === input.number)) fail("CONFLICT", "Member number already used") await options.setMemberNumber(p, input.number) + membersRead = null p.member.number = input.number log(p, v.sub, `Changed member number to ${input.number}`, now()) }) @@ -454,18 +716,21 @@ export function createPeopleService(options: PeopleOptions) { }, async endAdmin(v: Viewer, input: C.EndAdminInput) { requireGeneral(v, "people:write") - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) const p = find(u.state, input.personId) if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") if (p.admin.capoScope) requireGeneral(v, "people:appoint") Object.assign(p.admin, { status: "former", endedOn: date(), endReason: input.reason, capoScope: null }) log(p, v.sub, `Ended admin role: ${input.reason}`, now()) + pushRoles(u.state, before, v.sub, input.reason, true) }) }, async setCapoScope(v: Viewer, input: C.CapoScopeInput) { requireGeneral(v, "people:appoint") return tx((u) => { const p = find(u.state, input.personId) + settled(p) if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") p.admin.capoScope = input.scope || null log(p, v.sub, `Set Capo Admin scope: ${input.scope ?? "none"}`, now()) @@ -475,6 +740,7 @@ export function createPeopleService(options: PeopleOptions) { requireGeneral(v, "people:write") return tx((u) => { const p = find(u.state, input.personId) + settled(p) if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") const capo = input.capoId ? find(u.state, input.capoId) : null if (capo && (capo.id === p.id || capo.admin?.status !== "active" || !capo.admin.capoScope)) @@ -515,13 +781,20 @@ export function createPeopleService(options: PeopleOptions) { }) }, async addTeamMember(v: Viewer, input: C.AddTeamMemberInput) { - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) teamAccess(u.state, v, input.teamId, true) if (input.role === "lead") requireGeneral(v, "people:appoint") validateFields(input.teamId, input.fields) const p = find(u.state, input.personId) if (p.teams.some((t) => t.team === input.teamId && !t.endedOn)) fail("CONFLICT", "Already active in this team") - if (input.role === "lead" && Object.values(u.state.persons).some((p) => leads(p, input.teamId).length)) + // Including a Lead appointment PoliNetwork Auth hasn't confirmed yet. + if ( + input.role === "lead" && + Object.values(u.state.persons).some( + (p) => leads(p, input.teamId).length || (p.roleCommand && leads(p.roleCommand.desired, input.teamId).length) + ) + ) fail("CONFLICT", "End the existing Lead appointment first") if (input.since > date()) fail("BAD_REQUEST", "Start date is in the future") p.teams.push({ @@ -533,6 +806,7 @@ export function createPeopleService(options: PeopleOptions) { fields: input.fields, }) log(p, v.sub, `Joined ${input.teamId} as ${input.role}`, now()) + pushRoles(u.state, before, v.sub, `Added to ${C.TEAMS[input.teamId].name} from People`, true) activeCampaign(u.state) }) }, @@ -541,6 +815,7 @@ export function createPeopleService(options: PeopleOptions) { teamAccess(u.state, v, input.teamId, true) validateFields(input.teamId, input.fields) const p = find(u.state, input.personId) + settled(p) const t = p.teams.find((t) => t.team === input.teamId && !t.endedOn) if (!t) fail("CONFLICT", "No active team membership") t.fields = input.fields @@ -548,7 +823,8 @@ export function createPeopleService(options: PeopleOptions) { }) }, async endTeamMembership(v: Viewer, input: C.EndTeamInput) { - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) teamAccess(u.state, v, input.teamId, true) const p = find(u.state, input.personId) const t = p.teams.find((t) => t.team === input.teamId && !t.endedOn) @@ -557,6 +833,7 @@ export function createPeopleService(options: PeopleOptions) { if (input.lastDay < t.since || input.lastDay > date()) fail("BAD_REQUEST", "Invalid last day") Object.assign(t, { endedOn: input.lastDay, endReason: input.reason }) log(p, v.sub, `Ended ${input.teamId}: ${input.reason}${input.note ? `; ${input.note}` : ""}`, now()) + pushRoles(u.state, before, v.sub, input.reason, true) }) }, async listCampaigns(v: Viewer) { @@ -622,7 +899,8 @@ export function createPeopleService(options: PeopleOptions) { id, p.profile.personalEmail, `Censimento PoliNetwork ${c.year}`, - `Conferma la tua partecipazione: ${config.dashboardUrl}/dashboard/account/me` + `è aperto il censimento ${c.year} di PoliNetwork: ogni anno chiediamo a chi fa parte dell'associazione se continua e di aggiornare corso, anno e sede. Ci vogliono un paio di minuti.\n\nPuoi rispondere dalla tua area personale. Chiusura del censimento: ${longDate(c.closesOn)}.`, + { label: "Rispondi al censimento", url: AREA } ) p.reminders[c.id] = now().toISOString() entry.reminders++ @@ -771,8 +1049,8 @@ export function createPeopleService(options: PeopleOptions) { }, async importCommit(v: Viewer, input: C.ImportCommitInput) { requireGeneral(v, "people:write") - const telegramGroups = await options.telegramGroups() - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) const batch = u.state.imports[input.importId] if (!batch || batch.owner !== v.sub || batch.expiresAt < now().toISOString()) fail("NOT_FOUND", "Import preview expired") @@ -802,7 +1080,9 @@ export function createPeopleService(options: PeopleOptions) { personalEmail: r.profile.personalEmail ?? "", phone: r.profile.phone ?? "", telegramUsername: r.profile.telegramUsername ?? "", + telegramId: r.profile.telegramId ?? "", year: C.personInputSchema.shape.year.parse(r.profile.year), + campus: C.campusSchema.parse(r.profile.campus), admin: false, }, date() @@ -839,25 +1119,11 @@ export function createPeopleService(options: PeopleOptions) { since: r.entry.answeredOn ?? date(), endedOn: null, endReason: null, - groups: [], - requested: [], availableAsCapo: false, capoOfReference: null, capoScope: null, } - if (p.admin) { - p.admin.availableAsCapo = r.volunteer.availableAsCapo - for (const id of r.volunteer.requestedGroups) { - const group = telegramGroups.find((g) => g.chatId === id) - if (!group) fail("BAD_REQUEST", `Unknown requested Telegram group: ${id}`) - if (!p.admin.requested.some((g) => g.chatId === id)) - p.admin.requested.push({ - chatId: group.chatId, - title: group.title, - requestedOn: r.entry.answeredOn ?? date(), - }) - } - } + if (p.admin) p.admin.availableAsCapo = r.volunteer.availableAsCapo for (const team of r.volunteer.teams) if (!p.teams.some((t) => t.team === team && !t.endedOn)) p.teams.push({ @@ -892,6 +1158,7 @@ export function createPeopleService(options: PeopleOptions) { imported++ } batch.committed = true + pushRoles(u.state, before, v.sub, `Census ${c.year} import`, false) return { imported } }) }, @@ -911,6 +1178,9 @@ export function createPeopleService(options: PeopleOptions) { if (!r || r.resolved) fail("CONFLICT", "Review already handled") r.resolved = true if (r.record) { + // A dismissed single-record match would only open again: matching skips the record for this account. + if (r.kind === "identity-match" || r.kind === "name-only" || r.kind === "preliminary-link") + r.rejectedPersonIds.push(r.record.id) const p = find(u.state, r.record.id) if (p.account.status === "review") p.account = { status: "none" } log(p, v.sub, `Dismissed review ${r.id}`, now()) @@ -919,8 +1189,8 @@ export function createPeopleService(options: PeopleOptions) { }, async resolveReview(v: Viewer, input: C.ResolveReviewInput) { requireGeneral(v, "people:write") - const accounts = await options.directory() - return tx((u) => { + const accounts = await readAccounts() + return tx(async (u) => { const r = u.state.reviews[input.reviewId] if (!r || r.resolved) fail("CONFLICT", "Review already handled") const linkChoices = ["move-telegram", "link-other", "link-first", "link-second", "link-anyway"] @@ -930,6 +1200,8 @@ export function createPeopleService(options: PeopleOptions) { "two-records": ["link-first", "link-second", "merge-first"], "not-me": ["link-anyway", "add-new", "decline"], "name-only": ["link-anyway", "add-new", "decline"], + "preliminary-link": ["link-anyway", "decline"], + "identity-match": ["link-anyway", "decline"], } if (!allowed[r.kind].includes(input.resolution)) fail("BAD_REQUEST", "Resolution does not apply to this review") const account = accounts.find((a) => a.sub === r.sub) @@ -947,7 +1219,7 @@ export function createPeopleService(options: PeopleOptions) { } find(u.state, target.id).profile.telegramId = account.telegramId } - link(u.state, find(u.state, target.id), account, v.sub, input.reason) + await linkRecord(u.state, find(u.state, target.id), account, v.sub, input.reason) } else if (input.resolution === "add-new") { if (!account) fail("CONFLICT", "IdP account no longer exists") const parts = account.name.trim().split(/\s+/) @@ -978,7 +1250,7 @@ export function createPeopleService(options: PeopleOptions) { ) ) p.profile.telegramId = account.telegramId - link(u.state, p, account, v.sub, input.reason) + await linkRecord(u.state, p, account, v.sub, input.reason) } else if (input.resolution === "ask-details") { if (!account?.email || !r.record) fail("CONFLICT", "No contact address") queue( @@ -987,7 +1259,7 @@ export function createPeopleService(options: PeopleOptions) { `review-details:${r.id}:${randomUUID()}`, account.email, "PoliNetwork · verifica anagrafica", - input.reason + `stiamo collegando il tuo account PoliNetwork alla tua scheda nell'associazione e prima di farlo dobbiamo verificare alcuni dati. Questo è il messaggio del team HR:\n\n${input.reason}` ) } else if (input.resolution === "merge-first") { if (!r.record || !r.other || !account) fail("CONFLICT", "Two records and a registered account are required") @@ -995,18 +1267,32 @@ export function createPeopleService(options: PeopleOptions) { const second = find(u.state, r.other.id) if ([first.accountSub, second.accountSub].some((sub) => sub && sub !== account.sub)) fail("CONFLICT", "Unlink the other account before merging") + settled(first) + settled(second) + const before = roleViews(u.state) + // Auth confirmed only the linked record's roles: diff the merged result against those. + if (!first.accountSub && second.accountSub) { + const confirmed = before.get(second.id) + if (confirmed) before.set(first.id, confirmed) + } + const linked = !!first.accountSub || !!second.accountSub r.mergedRecord = structuredClone(second) mergePeople(u.state, first, second, v, config, now()) - link(u.state, first, account, v.sub, input.reason) + await linkRecord(u.state, first, account, v.sub, input.reason) + // Roles merged into an already linked record reach PoliNetwork Auth like any other change. + if (linked) pushRoles(u.state, before, v.sub, `Merged ${second.id}: ${input.reason}`, false) } else if (input.resolution === "unlink" && r.record) { const p = find(u.state, r.record.id) if (p.accountSub === r.sub) { + settled(p) p.accountSub = null p.account = { status: "none" } log(p, v.sub, `Unlinked account: ${input.reason}`, now()) } } r.resolved = true + // Matching skips this record for this account from now on, so the review doesn't open again. + if (input.resolution === "decline" && r.record) r.rejectedPersonIds.push(r.record.id) if (r.record) log(find(u.state, r.record.id), v.sub, `Resolved ${r.kind}: ${input.resolution}; ${input.reason}`, now()) }) @@ -1019,6 +1305,36 @@ export function createPeopleService(options: PeopleOptions) { ) ) }, + async listRecentLinks(v: Viewer) { + requireGeneral(v, "people:read") + const since = new Date(now().getTime() - C.RECENT_LINK_DAYS * 86400000).toISOString().slice(0, 10) + return tx((u) => + Object.values(u.state.persons) + .flatMap((p) => { + if (p.account.status !== "linked" || p.account.linkedOn < since) return [] + const by = p.account.by + return [ + { + personId: p.id, + name: nameOf(p), + email: p.account.email, + via: p.account.via, + how: p.account.how, + linkedOn: p.account.linkedOn, + linkedBy: !by + ? ("unknown" as const) + : by === p.accountSub + ? ("account-holder" as const) + : by === "system" + ? ("system" as const) + : ("admin" as const), + preliminary: !!p.authRegistrationId, + }, + ] + }) + .sort((a, b) => b.linkedOn.localeCompare(a.linkedOn)) + ) + }, async sendInvite(v: Viewer, input: { personId: string }) { requireGeneral(v, "people:write") return tx((u) => { @@ -1040,7 +1356,8 @@ export function createPeopleService(options: PeopleOptions) { `invite:${p.id}:${p.invite.hash}`, p.profile.personalEmail, "PoliNetwork · collega il tuo account", - `${config.dashboardUrl}/dashboard/account/me?peopleInvite=${token}` + `il team HR di PoliNetwork ti invita a collegare il tuo account PoliNetwork alla tua scheda nell'associazione. Una volta collegato, nella tua area personale trovi i tuoi dati, i tuoi ruoli e le quote associative.\n\nPremi il pulsante e accedi con l'account che usa questo indirizzo email (${p.profile.personalEmail}). Il collegamento avviene subito, non devi fare altro.\n\nScadenza dell'invito: ${longDate(p.invite.expiresAt.slice(0, 10))}. Se non ti aspettavi questo messaggio, ignoralo: senza il tuo accesso non succede niente.`, + { label: "Collega il tuo account", url: `${AREA}?peopleInvite=${token}` } ) log(p, v.sub, "Queued account invitation", now()) }) @@ -1057,7 +1374,7 @@ export function createPeopleService(options: PeopleOptions) { }, async searchAccounts(v: Viewer, input: C.SearchAccountsInput) { requireGeneral(v, "people:write") - const accounts = await options.directory() + const accounts = await readAccounts() return tx((u) => { const p = find(u.state, input.personId) const q = input.query.toLowerCase() @@ -1066,6 +1383,7 @@ export function createPeopleService(options: PeopleOptions) { .slice(0, 100) .map((a) => { const linked = Object.values(u.state.persons).find((p) => p.accountSub === a.sub) + const evidence = evidenceBetween(p, a) return { id: a.sub, name: a.name, @@ -1074,9 +1392,9 @@ export function createPeopleService(options: PeopleOptions) { via: "IdP", linkedTo: linked ? ref(linked) : null, reason: - a.telegramId && a.telegramId === p.profile.telegramId + evidence === "telegram" ? ("same-telegram" as const) - : a.email?.toLowerCase() === p.profile.personalEmail?.toLowerCase() + : evidence === "email" || evidence === "microsoft-365" ? ("same-email" as const) : ("similar-name" as const), } @@ -1085,31 +1403,70 @@ export function createPeopleService(options: PeopleOptions) { }, async linkAccount(v: Viewer, input: C.LinkAccountInput) { requireGeneral(v, "people:write") - const account = (await options.directory()).find((a) => a.sub === input.accountId) + const account = (await readAccounts()).find((a) => a.sub === input.accountId) if (!account) fail("NOT_FOUND", "IdP account not found") - return tx((u) => link(u.state, find(u.state, input.personId), account, v.sub, input.reason)) + return tx((u) => linkRecord(u.state, find(u.state, input.personId), account, v.sub, input.reason)) }, + /** + * Undoes a link, typically a mistaken one. The account loses the record's roles in Auth: for a preliminary person a + * Master Admin gives them back to it there; otherwise People removes them and keeps owning them on the record. The + * record is never proposed to that account again, and the identities it copied from the account are dropped. + */ async unlinkAccount(v: Viewer, input: { personId: string }) { requireGeneral(v, "people:write") - return tx((u) => { + const known = await readDirectory() + return tx(async (u) => { const p = find(u.state, input.personId) - if (!p.accountSub) fail("CONFLICT", "Account not linked") - p.accountSub = null + if (!p.accountSub || p.authProvisional) fail("CONFLICT", "Account not linked") + settled(p) + const sub = p.accountSub + const reason = "Unlinked in People" + if (p.authRegistrationId) { + if (!options.peopleRoles?.unlink) fail("PRECONDITION_FAILED", "Auth identity linking is unavailable") + await options.peopleRoles.unlink({ + operation: "unlink-person", + id: randomUUID(), + actor: v.sub, + personId: p.authRegistrationId, + reason, + }) + p.accountSub = p.authRegistrationId + p.authProvisional = true + } else { + const held = known?.value.users.find((user) => user.sub === sub)?.roles ?? [] + const changes = known + ? roleChanges(wantedView(boundRoles(known.value), held), { admin: false, teams: {} }) + : [] + if (changes.length && options.peopleRoles) + await options.peopleRoles.change({ id: randomUUID(), actor: v.sub, sub, reason, changes }) + // Without an account its roles can't follow PoliNetwork Auth: People owns them from now on. + p.accountSub = null + } + directoryRead = null + bumpRoles(u.state) p.account = { status: "none" } - log(p, v.sub, "Unlinked account", now()) + const account = (known && accountsOf(known.value).find((a) => a.sub === sub)) || null + if (account) { + if (account.azureId && p.azureId === account.azureId) p.azureId = null + if (account.telegramId && p.profile.telegramId === account.telegramId) p.profile.telegramId = null + const r = openReview(u.state, account, "not-me", p, "Unlinked in People", date()) + r.resolved = true + r.rejectedPersonIds.push(p.id) + } + log(p, v.sub, `Unlinked account ${sub}`, now()) }) }, async acceptInvite(v: Viewer, input: { token: string }) { requireSelf(v) - const account = (await options.directory()).find((a) => a.sub === v.sub) + const account = await readAccount(v.sub) if (!account?.email) fail("FORBIDDEN", "Verified account email required") - return tx((u) => { + return tx(async (u) => { const p = Object.values(u.state.persons).find( (p) => p.invite?.hash === hash(input.token) && p.invite.expiresAt > now().toISOString() ) if (!p || p.profile.personalEmail?.toLowerCase() !== account.email?.toLowerCase()) fail("NOT_FOUND", "Invitation expired or not addressed to this account") - link(u.state, p, account, v.sub, "Accepted email invitation") + await linkRecord(u.state, p, account, v.sub, "Accepted email invitation") }) }, @@ -1123,32 +1480,33 @@ export function createPeopleService(options: PeopleOptions) { async getMyArea(v: Viewer): Promise { requireSelf(v) const linked = await tx((u) => !!own(u.state, v)) - const accounts = linked ? [] : await options.directory() + const account = linked ? undefined : await readAccount(v.sub) return tx((u) => { const p = own(u.state, v) if (!p) { - const match = candidate( - u.state, - v, - accounts.find((a) => a.sub === v.sub) - ) - if (match) + const view = account ? signInState(u.state, account, date()) : ({ state: "none" } as const) + if (view.state === "match") return { state: "match", candidate: { - ...ref(match), - course: match.profile.course, - year: match.profile.year, - campus: match.profile.campus, - roles: [ - ...(match.admin?.status === "active" ? ["Admin"] : []), - ...match.teams.filter((t) => !t.endedOn).map((t) => C.TEAMS[t.team].name), - ], + ...ref(view.person), + course: view.person.profile.course, + year: view.person.profile.year, + campus: view.person.profile.campus, + roles: roleNames(view.person), }, reason: - v.telegramId && match.profile.telegramId === v.telegramId + view.evidence === "telegram" ? "Same verified Telegram account" - : "Same verified email address", + : view.evidence === "microsoft-365" + ? "Same Microsoft 365 account" + : "Same verified email address", + } + if (view.state === "awaiting") + return { + state: "awaiting-approval", + candidate: view.person ? { ...ref(view.person), roles: roleNames(view.person) } : null, + reason: awaitingReason(view.review, view.person), } const asked = Object.values(u.state.reviews).find( (r) => r.sub === v.sub && r.kind === "ask-to-be-added" && !r.resolved @@ -1227,56 +1585,53 @@ export function createPeopleService(options: PeopleOptions) { }, async confirmMatch(v: Viewer) { requireSelf(v) - const account = (await options.directory()).find((a) => a.sub === v.sub) - return tx((u) => { + const account = await readAccount(v.sub) + return tx(async (u) => { if (own(u.state, v)) return - const p = candidate(u.state, v, account) - if (!p || !account) fail("CONFLICT", "No unique verified match to confirm") - link(u.state, p, account, v.sub, "Confirmed verified identity match") + const decision = account ? decideFor(u.state, account) : null + if (!account || decision?.action !== "confirm") fail("CONFLICT", "No unique verified match to confirm") + await linkRecord(u.state, decision.person, account, v.sub, "Confirmed verified identity match") }) }, async rejectMatch(v: Viewer) { requireSelf(v) - const account = (await options.directory()).find((a) => a.sub === v.sub) + const account = await readAccount(v.sub) return tx((u) => { - const p = candidate(u.state, v, account) - if (!p || !account) fail("CONFLICT", "No match to reject") - const r = review(u.state, v, account, "not-me", p, "The account holder rejected this match") - r.rejectedPersonIds.push(p.id) + const decision = account ? decideFor(u.state, account) : null + if (!account || decision?.action !== "confirm") fail("CONFLICT", "No match to reject") + const r = openReview( + u.state, + account, + "not-me", + decision.person, + "The account holder rejected this match", + date() + ) + r.rejectedPersonIds.push(decision.person.id) }) }, async askToBeAdded(v: Viewer, input: C.AskToBeAddedInput) { requireSelf(v) - const account = (await options.directory()).find((a) => a.sub === v.sub) + const account = await readAccount(v.sub) if (!account) fail("PRECONDITION_FAILED", "IdP account unavailable") return tx((u) => { if (own(u.state, v)) fail("CONFLICT", "Already linked to a person") - review(u.state, v, account, "ask-to-be-added", null, JSON.stringify(input)) + if (signInState(u.state, account, date()).state === "awaiting") + fail("CONFLICT", "An admin is already checking your existing record") + openReview(u.state, account, "ask-to-be-added", null, JSON.stringify(input), date()) }) }, async answerCensus(v: Viewer, input: C.AnswerCensusInput) { - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) const p = requireOwn(u.state, v) const c = activeCampaign(u.state) if (c.status !== "open" || c.closesOn < date()) fail("CONFLICT", "Census is closed") if (!p.census.some((e) => e.year === c.year)) fail("FORBIDDEN", "Not expected in this campaign") if (p.census.some((e) => e.year === c.year && e.answer)) fail("CONFLICT", "Census already answered") - if ( - input.keepTeams.some((id) => !p.teams.some((t) => t.team === id && !t.endedOn)) || - input.keepGroups.some((id) => !p.admin?.groups.some((g) => g.chatId === id)) - ) - fail("BAD_REQUEST", "You can only retain your own roles and groups") + if (input.keepTeams.some((id) => !p.teams.some((t) => t.team === id && !t.endedOn))) + fail("BAD_REQUEST", "You can only retain your own roles") if (input.answer === "leaving" && !input.reason) fail("BAD_REQUEST", "A leaving reason is required") - for (const group of p.admin?.groups ?? []) { - if (input.answer === "continues" && input.keepGroups.includes(group.chatId)) continue - p.pendingGroupRemovals ??= [] - const pending = p.pendingGroupRemovals - if (pending.some((g) => g.chatId === group.chatId)) continue - const message = `Telegram admin removal pending: ${group.title} (${group.chatId}). HR must remove the admin rights; requested in census ${c.year}.` - pending.push({ chatId: group.chatId, message }) - p.discrepancies.push({ kind: "admin-removal", message, suggestedTelegram: null }) - log(p, v.sub, message, now()) - } Object.assign(p.profile, { course: input.course, year: input.year, campus: input.campus }) if (input.answer === "continues") { for (const t of p.teams) @@ -1300,15 +1655,17 @@ export function createPeopleService(options: PeopleOptions) { })), v.sub ) + // Giving up one's own roles is always allowed in PoliNetwork Auth. + pushRoles(u.state, before, v.sub, `Census ${c.year}: ${input.answer}`, false) }) }, async requestCorrection(v: Viewer, input: C.CorrectionInput) { - const account = (await options.directory()).find((a) => a.sub === v.sub) + const account = await readAccount(v.sub) return tx((u) => { const p = requireOwn(u.state, v) if (!account) fail("PRECONDITION_FAILED", "IdP account unavailable") const text = `Correction: ${input.field} → ${input.value}; ${input.note}` - const r = review(u.state, v, account, "name-only", p, text) + const r = openReview(u.state, account, "name-only", p, text, date()) if (!r.message?.includes(text)) r.message = [r.message, text].filter(Boolean).join("\n") log(p, v.sub, `Requested correction: ${input.field}`, now()) }) @@ -1323,75 +1680,23 @@ export function createPeopleService(options: PeopleOptions) { }, async getCapoArea(v: Viewer): Promise { requireSelf(v) - const telegramGroups = await options.telegramGroups() return tx((u) => { - hydrateGroups(u.state, telegramGroups) const p = requireOwn(u.state, v) const scope = p.admin?.status === "active" ? p.admin.capoScope : null if (!scope) fail("FORBIDDEN", "No active Capo Admin scope") const scoped = Object.values(u.state.persons).filter( (other) => other.admin?.status === "active" && other.admin.capoOfReference?.id === p.id ) - const ids = new Set( - [...(p.admin?.groups ?? []), ...scoped.flatMap((p) => p.admin?.groups ?? [])].map((g) => g.chatId) - ) - const groups = telegramGroups.filter((g) => ids.has(g.chatId)) - const allowed = new Set(groups.map((g) => g.chatId)) return { scope, - groups: groups.map((g) => ({ chatId: g.chatId, title: g.title, admins: g.admins?.length ?? null })), admins: scoped.map((p) => { const r = row(u.state, p, v, config, date(), true) r.profile.personalEmail = null return r }), - requests: scoped.flatMap( - (p) => - p.admin?.requested - .filter((g) => allowed.has(g.chatId)) - .map((g) => ({ - id: `${p.id}:${g.chatId}`, - person: ref(p), - group: { chatId: g.chatId, title: g.title }, - requestedOn: g.requestedOn, - })) ?? [] - ), } }) }, - async handleJoinRequest(v: Viewer, input: { requestId: string }, approve: boolean) { - requireSelf(v) - const telegramGroups = await options.telegramGroups() - return tx((u) => { - hydrateGroups(u.state, telegramGroups) - const me = requireOwn(u.state, v) - if (me.admin?.status !== "active" || !me.admin.capoScope) fail("FORBIDDEN", "No active Capo Admin scope") - const p = Object.values(u.state.persons).find( - (p) => - p.admin?.status === "active" && - p.admin.capoOfReference?.id === me.id && - p.admin.requested.some((g) => `${p.id}:${g.chatId}` === input.requestId) - ) - const g = p?.admin?.requested.find((g) => `${p.id}:${g.chatId}` === input.requestId) - const groupIds = new Set( - [ - ...me.admin.groups, - ...Object.values(u.state.persons) - .filter((p) => p.admin?.status === "active" && p.admin.capoOfReference?.id === me.id) - .flatMap((p) => p.admin?.groups ?? []), - ].map((g) => g.chatId) - ) - if (!p?.admin || !g || !groupIds.has(g.chatId)) fail("CONFLICT", "Request already handled") - p.admin.requested = p.admin.requested.filter((r) => r !== g) - if (approve) - p.discrepancies.push({ - kind: "needs-review", - message: `Approved for ${g.title}; awaiting bot confirmation of Telegram administration`, - suggestedTelegram: null, - }) - log(p, v.sub, `${approve ? "Approved" : "Declined"} request to join ${g.title}`, now()) - }) - }, async getFeeReview(v: Viewer, input: { personId: string }) { requireGeneral(v, "people:fees:write") @@ -1457,7 +1762,8 @@ export function createPeopleService(options: PeopleOptions) { `fee-rejection:${randomUUID()}`, p.profile.personalEmail, "PoliNetwork · verifica del bonifico", - input.reason + `abbiamo controllato la ricevuta del bonifico per la quota associativa ${f.year} e non abbiamo potuto accettarla. Questo è il motivo:\n\n${input.reason}\n\nPuoi caricare una nuova ricevuta dalla tua area personale.`, + { label: "Apri la tua area", url: AREA } ) log(p, v.sub, `Rejected fee receipt: ${input.reason}`, now()) }) @@ -1501,14 +1807,10 @@ export function createPeopleService(options: PeopleOptions) { continue } const id = `fee-reminder:${p.id}:${f.year}:${date()}` - queue( - u.state, - p, - id, - p.member.m365Email, - `PoliNetwork · quota ${f.year}`, - `Quota associativa da versare entro il ${f.dueOn}: ${config.dashboardUrl}/dashboard/account/me` - ) + queue(u.state, p, id, p.member.m365Email, `PoliNetwork · quota ${f.year}`, feeReminder(f), { + label: "Apri la tua area", + url: AREA, + }) f.lastReminder = now().toISOString() ids.push(id) log(p, v.sub, `Queued fee reminder ${f.year}`, now()) @@ -1808,7 +2110,7 @@ export function createPeopleService(options: PeopleOptions) { }, async deliverPending(onlyIds?: readonly string[]) { // Claim and record intent before network I/O. Unknown outcomes require an explicit retry. - const claimed = await tx((u) => { + const claimed = await commit((u) => { for (const mail of Object.values(u.state.outbox)) if ( mail.status === "sending" && @@ -1832,19 +2134,30 @@ export function createPeopleService(options: PeopleOptions) { mail.status = "sending" mail.attemptedAt = now().toISOString() } - return pending + return pending.map((mail) => ({ + ...mail, + firstName: u.state.persons[mail.personId]?.profile.firstName ?? null, + })) }) for (const mail of claimed) { let error: string | null = null try { const fileId = mail.fileId - const file = fileId ? await tx((u) => u.getFile(fileId)) : null + const file = fileId ? await commit((u) => u.getFile(fileId)) : null if (mail.fileId && !file) throw new Error("Attachment is missing") - await options.sendMail({ id: mail.id, to: mail.to, subject: mail.subject, text: mail.text, attachment: file }) + await options.sendMail({ + id: mail.id, + to: mail.to, + subject: mail.subject, + text: mail.text, + firstName: mail.firstName, + action: mail.action ?? null, + attachment: file, + }) } catch (err) { error = err instanceof Error ? err.message : String(err) } - await tx((u) => { + await commit((u) => { const current = u.state.outbox[mail.id] if (current.status !== "sending" || current.attemptedAt !== mail.attemptedAt) return current.status = error ? "failed" : "sent" @@ -1880,8 +2193,28 @@ export function createPeopleService(options: PeopleOptions) { }) } }, + /** Reads PoliNetwork Auth and the Microsoft 365 Soci group now, without the cache, and lays them over the register. */ + async syncSources() { + const [directory, members] = await Promise.all([readDirectory(true), readMembers(true)]) + await commit((u) => { + applySources(u.state, directory, members) + activeCampaign(u.state) + }) + }, async sweep() { - await tx(async (u) => { + const pending = await commit((u) => + Object.values(u.state.persons) + .filter((p) => p.roleCommand) + .map((p) => p.id) + ) + for (const id of pending) await deliverRoleCommand(id) + // Fee reminders follow the current members: lay the sources over the register when they answer. + const sources = await Promise.all([readDirectory(), readMembers()]).catch((error: unknown) => { + console.error(error) + return null + }) + await commit(async (u) => { + if (sources) applySources(u.state, ...sources) activeCampaign(u.state) for (const [id, batch] of Object.entries(u.state.batches)) if (batch.expiresAt < now().toISOString()) { @@ -1892,19 +2225,15 @@ export function createPeopleService(options: PeopleOptions) { if (batch.expiresAt < now().toISOString()) delete u.state.imports[id] for (const p of Object.values(u.state.persons)) { const f = fee(p, config, date()) - if (!f || f.status !== "due" || !p.member?.m365Email) continue + if (!f || f.status !== "due" || !p.member?.m365Email || p.importedFeeYear === f.year) continue const days = Math.round((Date.parse(f.dueOn) - Date.parse(date())) / 86400000) if (![14, 3].includes(days)) continue const id = `fee-auto:${p.id}:${f.year}:${days}` if (u.state.outbox[id]) continue - queue( - u.state, - p, - id, - p.member.m365Email, - `PoliNetwork · quota ${f.year}`, - `Scadenza quota associativa: ${f.dueOn}. ${config.dashboardUrl}/dashboard/account/me` - ) + queue(u.state, p, id, p.member.m365Email, `PoliNetwork · quota ${f.year}`, feeReminder(f), { + label: "Apri la tua area", + url: AREA, + }) f.lastReminder = now().toISOString() log(p, "system", `Queued automatic fee reminder ${f.year} (${days} days)`, now()) } diff --git a/src/people/store-pg.ts b/src/people/store-pg.ts index d775ee0..91e115f 100644 --- a/src/people/store-pg.ts +++ b/src/people/store-pg.ts @@ -217,7 +217,7 @@ export async function completeReceiptSignature(tx: Transaction, commit: Signatur receiptId: receipt.id, to: receipt.recipient, subject: `Ricevuta ${receipt.number} · PoliNetwork`, - text: `Quota associativa ${receipt.year}. In allegato la ricevuta firmata.`, + text: `grazie per aver versato la quota associativa ${receipt.year} di PoliNetwork. In allegato trovi la ricevuta ${receipt.number}, firmata digitalmente: conservala, vale come prova del pagamento.`, fileId, status: "pending", attemptedAt: null, diff --git a/src/people/types.ts b/src/people/types.ts index 6ac15ab..a2d8b73 100644 --- a/src/people/types.ts +++ b/src/people/types.ts @@ -2,13 +2,28 @@ import type { Campaign, CensusEntry, FeeDetail, ImportPreview, PersonRecord, Rec export type Viewer = { sub: string; telegramId: string | null; can: (permission: string) => boolean } export type Person = Omit & { + authRegistrationId?: string + authProvisional?: boolean accountSub: string | null azureId: string | null feeYears: Record[]; fileId: string | null }> answers: Record reminders: Record invite: { hash: string; expiresAt: string } | null - pendingGroupRemovals?: { chatId: string; message: string }[] + /** The fee year whose membership came from Microsoft 365: its automatic reminders are skipped. */ + importedFeeYear?: string + /** + * A role change sent to PoliNetwork Auth and not yet answered. `admin` and `teams` keep the roles Auth confirmed; + * `desired` replaces them for the changed concepts once Auth confirms, so a requested role never grants access. + */ + roleCommand?: { + request: import("./roles").RoleChange + desired: Pick + /** A direct dashboard action, whose caller sees a refusal; otherwise HR is asked to review it. */ + strict: boolean + /** Auth didn't answer at least once; the sweep sends it again with the same ID. */ + unanswered?: true + } } export type StoredReceipt = Receipt & { officerPersonId: string @@ -23,12 +38,13 @@ export type StoredReview = Review & { resolved: boolean rejectedPersonIds: string[] mergedRecord?: Person + /** What the account holder sees while it is open (`linking.ts`); hidden when absent. */ + shown?: import("./linking").Shown } export type ImportRow = { volunteer: { admin: boolean teams: import("./contract").TeamId[] - requestedGroups: string[] availableAsCapo: boolean otherAssociations?: string[] studentRepresentative?: string @@ -68,6 +84,7 @@ export type SignedBatch = { signer: string | null }[] } +export type MailAction = { label: string; url: string } export type Outbox = { id: string personId: string @@ -75,6 +92,8 @@ export type Outbox = { to: string subject: string text: string + /** The button under the text; absent on emails queued before it existed. */ + action?: MailAction | null fileId: string | null status: "pending" | "sending" | "sent" | "failed" attemptedAt: string | null @@ -131,13 +150,18 @@ export type UnitOfWork = { export interface PeopleStore { transaction(fn: (uow: UnitOfWork) => Promise): Promise } +/** A PoliNetwork Auth login account and the identity it proved there. */ export type Account = { sub: string name: string + /** Contact address, for display only. */ email: string | null + /** The address Auth verified; the only one People matches on. */ + verifiedEmail: string | null + azureId?: string | null telegramId: string | null - emailVerified?: boolean + telegramUsername?: string | null + /** Holds a role bound to People in Auth. */ + holdsPeopleRole?: boolean } export type TelegramUser = { id: string; name: string; username: string | null } -/** `admins` is null while the group's admin list is unknown: People then keeps the groups it last knew. */ -export type TelegramGroup = { chatId: string; title: string; admins: string[] | null } diff --git a/tests/people-emails.test.ts b/tests/people-emails.test.ts new file mode 100644 index 0000000..fff26b1 --- /dev/null +++ b/tests/people-emails.test.ts @@ -0,0 +1,45 @@ +import { render } from "@react-email/components" +import { createElement } from "react" +import { describe, expect, it } from "vitest" +import PeopleEmail, { type PeopleEmailProps } from "@/emails/templates/people" +import { harness, master } from "./people-fixtures" + +/** The email's text, on one line. */ +async function text(props: PeopleEmailProps) { + return (await render(createElement(PeopleEmail, props), { plainText: true })).replace(/\s+/g, " ") +} + +describe("People emails", () => { + it("greets the recipient, explains, and offers the link as a button and as text", async () => { + const body = await text({ + subject: "PoliNetwork · collega il tuo account", + firstName: "Luca", + text: "Primo paragrafo.\n\nSecondo paragrafo.", + action: { label: "Collega il tuo account", url: "https://example.org/x" }, + }) + expect(body).toContain("Ciao Luca,") + expect(body).toContain("Primo paragrafo. Secondo paragrafo.") + expect(body).toContain("Collega il tuo account") + expect(body).toContain("Se il pulsante non funziona, copia questo indirizzo nel browser") + expect(body).toContain("non rispondere a questa email") + }) + + it("sends an invitation that says who invites, why, how and until when", async () => { + const h = harness() + await h.seed() + await h.service.unlinkAccount(master, { personId: "P-0003" }) + await h.service.sendInvite(master, { personId: "P-0003" }) + await h.service.deliverPending() + const [mail] = h.sendMail.mock.calls.at(-1) ?? [] + expect(mail).toMatchObject({ + to: "luca@example.org", + subject: "PoliNetwork · collega il tuo account", + firstName: "Luca", + action: { label: "Collega il tuo account", url: expect.stringContaining("peopleInvite=") }, + }) + expect(mail?.text).toContain("il team HR di PoliNetwork ti invita") + expect(mail?.text).toContain("luca@example.org") + expect(mail?.text).toMatch(/Scadenza dell'invito: \d{1,2} \w+ \d{4}\./) + expect(mail?.text).not.toContain("peopleInvite=") + }) +}) diff --git a/tests/people-fixtures.ts b/tests/people-fixtures.ts index 6ca83d9..e4f2530 100644 --- a/tests/people-fixtures.ts +++ b/tests/people-fixtures.ts @@ -61,9 +61,27 @@ export function harness(overrides: Partial = {}) { let clock = new Date("2026-10-18T10:00:00Z") const requests = new Map() const accounts: Account[] = [ - { sub: "president", name: "Mario Rossi", email: "mario@example.org", emailVerified: true, telegramId: "101" }, - { sub: "vice", name: "Anna Bianchi", email: "anna@example.org", emailVerified: true, telegramId: "102" }, - { sub: "member", name: "Luca Verdi", email: "luca@example.org", emailVerified: true, telegramId: "103" }, + { + sub: "president", + name: "Mario Rossi", + email: "mario@example.org", + verifiedEmail: "mario@example.org", + telegramId: "101", + }, + { + sub: "vice", + name: "Anna Bianchi", + email: "anna@example.org", + verifiedEmail: "anna@example.org", + telegramId: "102", + }, + { + sub: "member", + name: "Luca Verdi", + email: "luca@example.org", + verifiedEmail: "luca@example.org", + telegramId: "103", + }, ] const store: PeopleOptions["store"] = { transaction(fn) { @@ -115,9 +133,9 @@ export function harness(overrides: Partial = {}) { const service = createPeopleService({ store, config, + allowLocalPeople: true, now: () => clock, directory: async () => accounts, - telegramGroups: async () => [], telegramUsers: async () => [], provisionMember, setMemberNumber, diff --git a/tests/people-identity.test.ts b/tests/people-identity.test.ts new file mode 100644 index 0000000..9a8ff81 --- /dev/null +++ b/tests/people-identity.test.ts @@ -0,0 +1,237 @@ +import { describe, expect, it } from "vitest" +import { type Evidence, matchAccount, RecordIndex, strengthOf } from "@/people/identity" +import { decide } from "@/people/linking" +import { newPerson } from "@/people/model" +import { type Account, emptyState, type Person } from "@/people/types" +import { profile } from "./people-fixtures" + +const register = emptyState() +/** A record without roles or account, with its own ID; `extra` adjusts it. */ +function record(first: string, last: string, extra: (p: Person) => void = () => {}) { + const p = newPerson(register, { ...profile(first, last), admin: false }, "2026-10-01") + extra(p) + return p +} +const account = (extra: Partial = {}): Account => ({ + sub: "login", + name: "Someone Else", + email: null, + verifiedEmail: null, + azureId: null, + telegramId: null, + telegramUsername: null, + ...extra, +}) +const none = new Set() +const index = (persons: Person[]) => new RecordIndex(persons) + +describe("one identity rule", () => { + const mario = record("Mario", "Rossi", (p) => { + p.profile.telegramId = "101" + }) + + it.each([ + ["Microsoft 365 object ID", account({ azureId: "az-1" }), "microsoft-365"], + ["verified personal email, any case", account({ verifiedEmail: "MARIO@example.org" }), "email"], + ["Telegram ID", account({ telegramId: "101" }), "telegram"], + ["Telegram username, with @ and any case", account({ telegramUsername: "@Mario_Test" }), "username"], + ["full name", account({ name: "mario rossi" }), "name"], + ])("matches by %s", (_, signedIn, evidence) => { + const p = structuredClone(mario) + p.azureId = "az-1" + expect(matchAccount(index([p]), signedIn, none)).toMatchObject({ kind: "one", evidence }) + }) + + it("never matches on an address Auth did not verify", () => { + expect(matchAccount(index([mario]), account({ email: "mario@example.org" }), none)).toEqual({ kind: "none" }) + }) + + it("matches the Microsoft 365 address of a member", () => { + const member = record("Anna", "Bianchi", (p) => { + p.member = { + number: "0001", + status: "active", + admittedOn: "2025-01-01", + fee: "due", + m365Email: "a.b@polinetwork.org", + } + }) + expect(matchAccount(index([member]), account({ verifiedEmail: "a.b@polinetwork.org" }), none)).toMatchObject({ + kind: "one", + evidence: "email", + }) + }) + + it("prefers verified evidence over a username or name on other records", () => { + const homonym = record("Mario", "Rossi") + const handle = record("Luca", "Verdi", (p) => { + p.profile.telegramUsername = "mario_test" + }) + const match = matchAccount( + index([homonym, handle, mario]), + account({ telegramId: "101", name: "Mario Rossi" }), + none + ) + expect(match).toMatchObject({ kind: "one", person: { id: mario.id }, evidence: "telegram" }) + }) + + it("reports conflicting verified evidence and ignores ambiguous weak evidence", () => { + const twin = record("Maria", "Rossi", (p) => { + p.profile.personalEmail = "mario@example.org" + }) + expect(matchAccount(index([mario, twin]), account({ verifiedEmail: "mario@example.org" }), none)).toMatchObject({ + kind: "conflict", + reason: "two-records", + }) + const byEmail = record("Anna", "Bianchi") + expect( + matchAccount(index([byEmail, mario]), account({ verifiedEmail: "anna@example.org", telegramId: "101" }), none) + ).toMatchObject({ + kind: "conflict", + reason: "telegram-conflict", + person: { id: byEmail.id }, + other: { id: mario.id }, + }) + expect( + matchAccount(index([mario]), account({ verifiedEmail: "mario@example.org", telegramId: "999" }), none) + ).toMatchObject({ kind: "conflict", reason: "telegram-conflict", other: null }) + expect(matchAccount(index([mario, record("Mario", "Rossi")]), account({ name: "Mario Rossi" }), none)).toEqual({ + kind: "none", + }) + }) + + it("skips records linked to an account and records the account holder rejected", () => { + const linked = record("Mario", "Rossi", (p) => { + p.accountSub = "other" + p.profile.telegramId = "101" + }) + expect(matchAccount(index([linked]), account({ telegramId: "101" }), none)).toEqual({ kind: "none" }) + expect(matchAccount(index([mario]), account({ telegramId: "101" }), new Set([mario.id]))).toEqual({ kind: "none" }) + const preliminary = record("Mario", "Rossi", (p) => { + p.accountSub = "people:1" + p.authProvisional = true + p.profile.telegramId = "101" + }) + expect(matchAccount(index([preliminary]), account({ telegramId: "101" }), none)).toMatchObject({ kind: "one" }) + }) +}) + +describe("one outcome policy", () => { + const one = (person: Person, evidence: Evidence) => + ({ kind: "one", person, evidence, strength: strengthOf(evidence) }) as const + const plain = record("Mario", "Rossi") + const withRoles = record("Mario", "Rossi", (p) => { + p.teams.push({ team: "it", role: "member", since: "2026-01-01", endedOn: null, endReason: null, fields: {} }) + }) + const preliminary = record("Mario", "Rossi", (p) => { + p.authProvisional = true + }) + const member = record("Mario", "Rossi", (p) => { + p.member = { + number: "0001", + status: "active", + admittedOn: "2025-01-01", + fee: "due", + m365Email: "m.r@polinetwork.org", + } + }) + + it.each([ + [ + "the account holder confirms a verified match on a record that grants nothing", + plain, + "email", + {}, + { action: "confirm" }, + ], + [ + "HR approves a verified match on a record that carries roles (D1)", + withRoles, + "email", + {}, + { action: "review", kind: "identity-match", shown: "record" }, + ], + [ + "a Master Admin approves a verified match on a preliminary person", + preliminary, + "telegram", + {}, + { action: "review", kind: "preliminary-link", shown: "record" }, + ], + [ + "a username on a preliminary person is shown as being checked", + preliminary, + "username", + {}, + { action: "review", kind: "preliminary-link", shown: "notice" }, + ], + [ + "a username on another record goes to HR", + plain, + "username", + {}, + { action: "review", kind: "identity-match", shown: "notice" }, + ], + ["a name alone is a hidden hint", plain, "name", {}, { action: "review", kind: "name-only", shown: "hidden" }], + [ + "a role holder is linked by a Microsoft 365 identity", + withRoles, + "microsoft-365", + { holdsPeopleRole: true }, + { action: "link" }, + ], + [ + "a role holder is linked by the PoliNetwork address Microsoft 365 gave the record", + member, + "email", + { holdsPeopleRole: true, verifiedEmail: "m.r@polinetwork.org" }, + { action: "link" }, + ], + [ + "a role holder matching a PoliNetwork address typed on the record goes to HR", + plain, + "email", + { holdsPeopleRole: true, verifiedEmail: "mario@polinetwork.org" }, + { action: "review", kind: "identity-match" }, + ], + [ + "a role holder's Telegram ID goes to HR (D2)", + plain, + "telegram", + { holdsPeopleRole: true }, + { action: "review", kind: "identity-match" }, + ], + [ + "a role holder's personal address goes to HR (D2)", + plain, + "email", + { holdsPeopleRole: true, verifiedEmail: "m@gmail.com" }, + { action: "review", kind: "identity-match" }, + ], + ] as const)("%s", (_, p, evidence, extra, expected) => { + expect(decide(one(p, evidence), account(extra))).toMatchObject(expected) + }) + + it("sends a record holding another Microsoft 365 account to HR instead of linking it", () => { + const p = record("Luca", "Verdi", (r) => { + r.azureId = "az-old" + r.member = { + number: "0002", + status: "active", + admittedOn: "2025-01-01", + fee: "due", + m365Email: "l.v@polinetwork.org", + } + }) + const signedIn = account({ azureId: "az-new", verifiedEmail: "l.v@polinetwork.org", holdsPeopleRole: true }) + const match = matchAccount(index([p]), signedIn, none) + expect(match).toMatchObject({ kind: "conflict", reason: "microsoft-365-conflict" }) + expect(decide(match, signedIn)).toMatchObject({ action: "review", kind: "identity-match" }) + }) + + it("reviews a conflict and tells the account holder it is being checked", () => { + expect( + decide({ kind: "conflict", reason: "two-records", person: plain, other: withRoles }, account()) + ).toMatchObject({ action: "review", kind: "two-records", other: { id: withRoles.id }, shown: "notice" }) + }) +}) diff --git a/tests/people-imports.test.ts b/tests/people-imports.test.ts index 5ac3541..82ef0c1 100644 --- a/tests/people-imports.test.ts +++ b/tests/people-imports.test.ts @@ -94,7 +94,6 @@ describe("People census imports", () => { course: "New course", year: "3rd year", campus: "Bovisa", - keepGroups: [], keepTeams: [], reason: "", note: "", diff --git a/tests/people-linking.test.ts b/tests/people-linking.test.ts new file mode 100644 index 0000000..096dcda --- /dev/null +++ b/tests/people-linking.test.ts @@ -0,0 +1,187 @@ +import { describe, expect, it, vi } from "vitest" +import type { PeopleRoles, RoleDirectory } from "@/people/roles" +import { SOURCE_TTL_MS } from "@/people/service" +import { harness, master, viewer } from "./people-fixtures" + +/** Auth's People directory with these accounts; role commands succeed without changing anything. */ +function auth(users: RoleDirectory["users"]) { + const directory: RoleDirectory = { + roles: [ + { key: "admin", name: "Admin", binding: "admin" }, + { key: "it", name: "IT", binding: "team:it:member" }, + ], + users, + } + const roles: PeopleRoles = { + directory: vi.fn(async () => structuredClone(directory)), + change: vi.fn(async (command) => ({ + roles: directory.roles, + held: users.find((u) => u.sub === command.sub)?.roles ?? [], + assigned: [], + })), + } + return { directory, roles } +} +const login = (sub: string, extra: Partial = {}) => ({ + sub, + name: "Luca Verdi", + email: null, + verifiedEmail: null, + azureId: null, + telegramId: null, + telegramUsername: null, + roles: [], + ...extra, +}) + +describe("account linking against PoliNetwork Auth's directory", () => { + it("offers “Is this you?” for a verified email, which Auth now reports", async () => { + const a = auth([login("luca-login", { email: "luca@gmail.com", verifiedEmail: "luca@example.org" })]) + const h = harness({ peopleRoles: a.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const p = state.persons["P-0003"] + p.accountSub = null + p.account = { status: "none" } + p.admin = null + p.profile.telegramId = null + }) + const self = viewer("luca-login", ["people:self"]) + expect(await h.service.getMyArea(self)).toMatchObject({ + state: "match", + candidate: { id: "P-0003" }, + reason: "Same verified email address", + }) + await h.service.confirmMatch(self) + expect(h.state().persons["P-0003"]).toMatchObject({ accountSub: "luca-login", account: { status: "linked" } }) + }) + + it("links a role holder automatically only by a Microsoft 365 identity", async () => { + const a = auth([login("luca-login", { azureId: "az-luca", roles: ["it"] })]) + const h = harness({ peopleRoles: a.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const p = state.persons["P-0003"] + p.accountSub = null + p.account = { status: "none" } + p.azureId = "az-luca" + }) + await h.service.syncSources() + expect(h.state().persons["P-0003"]).toMatchObject({ + accountSub: "luca-login", + account: { status: "linked", via: "PoliNetwork Auth" }, + teams: [{ team: "it", role: "member" }], + }) + expect(Object.keys(h.state().persons)).toHaveLength(3) + }) + + it("finds a first sign-in that Auth lists after People last read it", async () => { + const a = auth([]) + const h = harness({ peopleRoles: a.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const p = state.persons["P-0003"] + p.accountSub = null + p.account = { status: "none" } + p.admin = null + }) + const self = viewer("new-login", ["people:self"]) + expect(await h.service.getMyArea(self)).toMatchObject({ state: "none" }) + a.directory.users.push(login("new-login", { telegramId: "103" })) + // Within the cache lifetime, an unknown account makes People ask Auth again, at most every 2 seconds. + expect(await h.service.getMyArea(self)).toMatchObject({ state: "none" }) + h.advance(2_000) + expect(await h.service.getMyArea(self)).toMatchObject({ state: "match", candidate: { id: "P-0003" } }) + expect(await h.service.listReviews(master)).toEqual([]) + }) + + it("keeps a declined match declined: a role holder then gets a record of their own", async () => { + const a = auth([login("luca-login", { telegramId: "103", roles: ["it"] })]) + const h = harness({ peopleRoles: a.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const p = state.persons["P-0003"] + p.accountSub = null + p.account = { status: "none" } + }) + await h.service.syncSources() + const [review] = await h.service.listReviews(master) + expect(review).toMatchObject({ kind: "identity-match", record: { id: "P-0003" } }) + await h.service.resolveReview(master, { reviewId: review.id, resolution: "decline", reason: "Different person" }) + h.advance(SOURCE_TTL_MS.directory + 1) + await h.service.syncSources() + expect(await h.service.listReviews(master)).toEqual([]) + const persons = Object.values(h.state().persons) + expect(persons.find((p) => p.accountSub === "luca-login")).toMatchObject({ teams: [{ team: "it" }] }) + expect(h.state().persons["P-0003"].accountSub).toBeNull() + }) + + it("lists a link the account holder made and lets HR undo it for good", async () => { + const a = auth([login("luca-login", { verifiedEmail: "luca@example.org" })]) + const h = harness({ peopleRoles: a.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const p = state.persons["P-0003"] + p.accountSub = null + p.account = { status: "none" } + p.admin = null + p.profile.personalEmail = "luca@example.org" + p.profile.telegramId = null + }) + const self = viewer("luca-login", ["people:self"]) + await h.service.confirmMatch(self) + expect(await h.service.listRecentLinks(master)).toContainEqual( + expect.objectContaining({ personId: "P-0003", linkedBy: "account-holder", preliminary: false }) + ) + await h.service.unlinkAccount(master, { personId: "P-0003" }) + expect(h.state().persons["P-0003"]).toMatchObject({ accountSub: null, account: { status: "none" } }) + expect(await h.service.listRecentLinks(master)).not.toContainEqual(expect.objectContaining({ personId: "P-0003" })) + // “Is this you?” doesn't come back for the same account. + expect(await h.service.getMyArea(self)).toMatchObject({ state: "none" }) + }) + + it("takes the record's roles off the account in Auth when HR undoes the link", async () => { + const a = auth([login("luca-login", { telegramId: "103", roles: ["it"] })]) + const h = harness({ peopleRoles: a.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const p = state.persons["P-0003"] + p.accountSub = null + p.account = { status: "none" } + }) + await h.service.syncSources() + const [review] = await h.service.listReviews(master) + await h.service.resolveReview(master, { reviewId: review.id, resolution: "link-anyway", reason: "Checked" }) + await h.service.unlinkAccount(master, { personId: "P-0003" }) + expect(a.roles.change).toHaveBeenLastCalledWith( + expect.objectContaining({ sub: "luca-login", changes: [{ kind: "team", team: "it", role: null }] }) + ) + expect(h.state().persons["P-0003"]).toMatchObject({ accountSub: null, profile: { telegramId: null } }) + // Auth no longer lists the role, so the account gets no record of its own. + a.directory.users[0].roles = [] + h.advance(SOURCE_TTL_MS.directory + 1) + await h.service.syncSources() + expect(Object.values(h.state().persons).some((p) => p.accountSub === "luca-login")).toBe(false) + expect(await h.service.listReviews(master)).toEqual([]) + }) + + it("does not reopen a declined preliminary link when Auth's directory is read again", async () => { + const a = auth([]) + a.directory.users.push({ + ...login("people:1", { name: "Pre Login", email: "pre@example.org" }), + registrationId: "people:1", + provisional: true, + firstName: "Pre", + lastName: "Login", + }) + a.directory.users.push(login("real", { name: "Someone", verifiedEmail: "pre@example.org" })) + const h = harness({ peopleRoles: a.roles, allowLocalPeople: false }) + await h.service.syncSources() + const [review] = await h.service.listReviews(master) + expect(review).toMatchObject({ kind: "preliminary-link", account: { name: "Someone" } }) + await h.service.resolveReview(master, { reviewId: review.id, resolution: "decline", reason: "Different person" }) + h.advance(SOURCE_TTL_MS.directory + 1) + await h.service.syncSources() + expect(await h.service.listReviews(master)).toEqual([]) + }) +}) diff --git a/tests/people-postgres.fixture.ts b/tests/people-postgres.fixture.ts index b80028f..3a58634 100644 --- a/tests/people-postgres.fixture.ts +++ b/tests/people-postgres.fixture.ts @@ -60,9 +60,27 @@ try { const president = viewer("president") const vice = viewer("vice") const directory = [ - { sub: "president", name: "Mario Rossi", email: "president@example.org", emailVerified: true, telegramId: "101" }, - { sub: "vice", name: "Anna Bianchi", email: "vice@example.org", emailVerified: true, telegramId: "102" }, - { sub: "member", name: "Luca Verdi", email: "member@example.org", emailVerified: true, telegramId: "103" }, + { + sub: "president", + name: "Mario Rossi", + email: "president@example.org", + verifiedEmail: "president@example.org", + telegramId: "101", + }, + { + sub: "vice", + name: "Anna Bianchi", + email: "vice@example.org", + verifiedEmail: "vice@example.org", + telegramId: "102", + }, + { + sub: "member", + name: "Luca Verdi", + email: "member@example.org", + verifiedEmail: "member@example.org", + telegramId: "103", + }, ] const outboxCalls: string[] = [] const eligible = (r: PeopleState["receipts"][string], sub: string, state: PeopleState, requireEsign: boolean) => @@ -94,7 +112,6 @@ try { store, config, directory: async () => directory, - telegramGroups: async () => [], telegramUsers: async () => [], provisionMember: async (p) => ({ id: `azure-${p.id}`, @@ -310,7 +327,13 @@ try { admittedOn: "2026-10-01", fee: "due", }) - directory.push({ sub: "sara", name: "Sara Neri", email: "sara@example.org", emailVerified: true, telegramId: "104" }) + directory.push({ + sub: "sara", + name: "Sara Neri", + email: "sara@example.org", + verifiedEmail: "sara@example.org", + telegramId: "104", + }) await people.getMyArea(viewer("sara")) const review = (await people.listReviews(president)).find((r) => r.kind === "two-records") assert.ok(review) diff --git a/tests/people-registration.test.ts b/tests/people-registration.test.ts new file mode 100644 index 0000000..4afc8c2 --- /dev/null +++ b/tests/people-registration.test.ts @@ -0,0 +1,260 @@ +import assert from "node:assert/strict" +import { describe, expect, it, vi } from "vitest" +import { + type CreateAuthPerson, + type LinkAuthPerson, + type PeopleRoles, + RoleChangeError, + type RoleDirectory, + type UnlinkAuthPerson, +} from "@/people/roles" +import { SOURCE_TTL_MS } from "@/people/service" +import { harness, master, viewer } from "./people-fixtures" + +function authPeople() { + const directory: RoleDirectory = { + roles: [ + { key: "admin", name: "Admin", binding: "admin" }, + { key: "it", name: "IT", binding: "team:it:member" }, + ], + users: [], + } + const roles: PeopleRoles = { + directory: vi.fn(async () => structuredClone(directory)), + change: vi.fn(async () => ({ roles: directory.roles, held: [], assigned: [] })), + create: vi.fn(async (input: CreateAuthPerson) => { + const sub = `people:${input.id}` + if (!directory.users.some((user) => user.sub === sub)) + directory.users.push({ + sub, + registrationId: sub, + provisional: true, + name: `${input.firstName} ${input.lastName}`, + firstName: input.firstName, + lastName: input.lastName, + email: input.email || null, + phone: input.phone || null, + telegramId: null, + declaredTelegramId: input.telegramId || null, + declaredTelegramUsername: input.telegramUsername || null, + telegramUsername: null, + roles: input.changes.flatMap((change) => (change.kind === "admin" ? ["admin"] : [change.team])), + }) + return { sub } + }), + link: vi.fn(async (input: LinkAuthPerson) => { + if (input.actor !== "president") throw new RoleChangeError(403, "Master Admin required") + const person = directory.users.find((person) => person.registrationId === input.personId) + if (!person) throw new Error("Person not found") + // Auth reports the linked registration through the login account, as one user. + const login = directory.users.find((user) => user.sub === input.userId) + directory.users = directory.users.filter((user) => user !== login) + Object.assign(person, { previousSub: person.sub, sub: input.userId, provisional: false }) + person.verifiedEmail = login?.verifiedEmail ?? null + return { sub: input.userId } + }), + unlink: vi.fn(async (input: UnlinkAuthPerson) => { + if (input.actor !== "president") throw new RoleChangeError(403, "Master Admin required") + const person = directory.users.find((person) => person.registrationId === input.personId) + if (!person) throw new Error("Person not found") + // The login account is listed on its own again, without the person's roles. + directory.users.push({ ...person, registrationId: undefined, previousSub: undefined, roles: [] }) + Object.assign(person, { sub: input.personId, provisional: true, previousSub: undefined, verifiedEmail: null }) + return { sub: input.personId } + }), + } + return { directory, roles } +} + +describe("People before the first Auth login", () => { + it("creates with names and roles only in Auth, and keeps blank census data", async () => { + const auth = authPeople() + const h = harness({ peopleRoles: auth.roles, allowLocalPeople: false }) + const input = { + requestId: "7b3c7576-3f7d-4ef8-9765-82e00cf0a04e", + firstName: "Mario", + lastName: "Rossi", + teams: ["it" as const], + admin: true, + } + const created = await h.service.createPerson(master, input) + expect(await h.service.createPerson(master, input)).toEqual(created) + const person = await h.service.getPerson(master, created) + expect(person).toMatchObject({ + preliminary: true, + profile: { firstName: "Mario", lastName: "Rossi", course: "", year: "", campus: null, personalEmail: null }, + admin: { status: "active" }, + teams: [{ team: "it", role: "member" }], + account: { status: "none" }, + }) + expect(await h.service.listPeople(master)).toHaveLength(1) + expect(auth.roles.create).toHaveBeenCalledWith( + expect.objectContaining({ + actor: master.sub, + changes: [ + { kind: "admin", active: true }, + { kind: "team", team: "it", role: "member" }, + ], + }) + ) + }) + + it("requires Master approval and retains the register identity and roles after linking", async () => { + const auth = authPeople() + const h = harness({ peopleRoles: auth.roles, allowLocalPeople: false }) + const created = await h.service.createPerson(master, { + firstName: "Mario", + lastName: "Rossi", + personalEmail: "new@example.org", + teams: ["it"], + admin: true, + }) + const registration = auth.directory.users[0] + assert.ok(registration.registrationId) + auth.directory.users.push({ + sub: "new-login", + name: "Mario Rossi", + email: "new@example.org", + verifiedEmail: "new@example.org", + telegramId: null, + telegramUsername: null, + roles: [], + }) + h.advance(SOURCE_TTL_MS.directory + 1) + // The person signing in learns they were found, and isn't sent to ask to be added. + const self = viewer("new-login", ["people:self"]) + expect(await h.service.getMyArea(self)).toEqual({ + state: "awaiting-approval", + candidate: { id: created.id, name: "Mario Rossi", roles: ["Admin", "IT"] }, + reason: expect.stringContaining("A Master Admin will confirm the link"), + }) + await expect(h.service.askToBeAdded(self, { note: "" } as never)).rejects.toThrow("already checking") + // The verified match is the only review: the same name doesn't add a name-only one. + const reviews = await h.service.listReviews(master) + expect(reviews.map((r) => r.kind)).toEqual(["preliminary-link"]) + const [review] = reviews + expect(review).toMatchObject({ kind: "preliminary-link", record: { id: created.id } }) + expect(await h.service.getMyRoles(viewer("new-login", ["people:self"]))).toEqual({ capoScope: null, leads: [] }) + const input = { + reviewId: review.id, + resolution: "link-anyway", + reason: "Verified the email belongs to this person", + } + await expect(h.service.resolveReview(viewer("vice", ["admin:access", "people:write"]), input)).rejects.toThrow( + "Master Admin required" + ) + expect((await h.service.getPerson(master, created)).account.status).toBe("none") + await h.service.resolveReview(master, input) + expect(await h.service.getPerson(master, created)).toMatchObject({ + preliminary: false, + account: { status: "linked" }, + admin: { status: "active" }, + teams: [{ team: "it", role: "member" }], + }) + expect(await h.service.listPeople(master)).toHaveLength(1) + expect(await h.service.listReviews(master)).toEqual([]) + + // The link shows among recent ones; undoing it needs a Master Admin and gives the roles back to the person. + expect(await h.service.listRecentLinks(master)).toEqual([ + expect.objectContaining({ personId: created.id, preliminary: true, linkedBy: "admin" }), + ]) + await expect( + h.service.unlinkAccount(viewer("vice", ["admin:access", "people:write"]), { personId: created.id }) + ).rejects.toThrow("Master Admin required") + await h.service.unlinkAccount(master, { personId: created.id }) + expect(auth.roles.unlink).toHaveBeenCalledWith( + expect.objectContaining({ operation: "unlink-person", personId: registration.registrationId }) + ) + h.advance(SOURCE_TTL_MS.directory + 1) + expect(await h.service.getPerson(master, created)).toMatchObject({ + preliminary: true, + account: { status: "none" }, + admin: { status: "active" }, + teams: [{ team: "it", role: "member" }], + }) + expect(await h.service.listPeople(master)).toHaveLength(1) + expect(await h.service.listRecentLinks(master)).toEqual([]) + // The same account isn't proposed this person again. + expect(await h.service.getMyArea(self)).toMatchObject({ state: "none" }) + expect(await h.service.listReviews(master)).toEqual([]) + }) + + it("recovers a confirmed Auth link without creating a duplicate after a backend restart", async () => { + const auth = authPeople() + const h = harness({ peopleRoles: auth.roles, allowLocalPeople: false }) + const created = await h.service.createPerson(master, { firstName: "Mario", lastName: "Rossi", admin: true }) + const registration = auth.directory.users[0] + registration.previousSub = registration.sub + registration.sub = "first-login" + registration.provisional = false + h.advance(SOURCE_TTL_MS.directory + 1) + const restarted = harness({ peopleRoles: auth.roles, store: h.store, allowLocalPeople: false }) + expect(await restarted.service.listPeople(master)).toHaveLength(1) + expect(await restarted.service.getPerson(master, created)).toMatchObject({ + preliminary: false, + account: { status: "linked" }, + admin: { status: "active" }, + }) + }) + + it("does not auto-claim a preliminary person from a declared Telegram contact", async () => { + const auth = authPeople() + const h = harness({ peopleRoles: auth.roles, allowLocalPeople: false }) + const created = await h.service.createPerson(master, { + firstName: "Mario", + lastName: "Rossi", + telegramId: "123", + admin: true, + }) + auth.directory.users.push({ + sub: "different-login", + name: "Mario Rossi", + email: null, + telegramId: "123", + telegramUsername: null, + roles: ["admin"], + }) + h.advance(SOURCE_TTL_MS.directory + 1) + // The role holder's Telegram account matches the declared contact: a Master Admin decides, and no second + // record is made meanwhile. + expect(await h.service.listPeople(master)).toHaveLength(1) + expect(await h.service.getPerson(master, created)).toMatchObject({ preliminary: true, account: { status: "none" } }) + expect(await h.service.listReviews(master)).toEqual([ + expect.objectContaining({ kind: "preliminary-link", record: expect.objectContaining({ id: created.id }) }), + ]) + expect(auth.roles.link).not.toHaveBeenCalled() + }) + + it("tells a weaker match it is being checked without showing the record", async () => { + const auth = authPeople() + const h = harness({ peopleRoles: auth.roles, allowLocalPeople: false }) + await h.service.createPerson(master, { firstName: "Anna", lastName: "Bianchi", telegramUsername: "anna_pn" }) + const registration = auth.directory.users[0] + assert.ok(registration.registrationId) + auth.directory.users.push({ + sub: "tg-login", + name: "Someone", + email: null, + verifiedEmail: null, + telegramId: "77", + telegramUsername: "Anna_PN", + roles: [], + }) + h.advance(SOURCE_TTL_MS.directory + 1) + expect(await h.service.getMyArea(viewer("tg-login", ["people:self"]))).toEqual({ + state: "awaiting-approval", + candidate: null, + reason: expect.stringContaining("You don't need to ask to be added"), + }) + const [review] = await h.service.listReviews(master) + expect(review).toMatchObject({ kind: "preliminary-link", message: expect.stringContaining("Usernames can change") }) + }) + + it("fails without Auth instead of creating a local authority", async () => { + const h = harness({ allowLocalPeople: false }) + await expect( + h.service.createPerson(master, { firstName: "Mario", lastName: "Rossi", admin: true }) + ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" }) + expect(await h.service.listPeople(master)).toEqual([]) + }) +}) diff --git a/tests/people-roles.test.ts b/tests/people-roles.test.ts new file mode 100644 index 0000000..65b1148 --- /dev/null +++ b/tests/people-roles.test.ts @@ -0,0 +1,680 @@ +import assert from "node:assert/strict" +import { describe, expect, it, vi } from "vitest" +import { + type AzureMember, + type PeopleRoles, + type RoleChange, + RoleChangeError, + type RoleDirectory, + roleChanges, +} from "@/people/roles" +import { DIRECTORY_MAX_AGE_MS, SOURCE_TTL_MS } from "@/people/service" +import { harness, master, viewer } from "./people-fixtures" + +const ROLES: RoleDirectory["roles"] = [ + { key: "admin", name: "Admin", binding: "admin" }, + { key: "it-core", name: "IT Core", binding: "team:it:member" }, + { key: "it-lead", name: "IT Lead", binding: "team:it:lead" }, + { key: "design-member", name: "Member Design & Marketing", binding: "team:design:member" }, + { key: "design-lead", name: "Lead Design & Marketing", binding: "team:design:lead" }, + { key: "odd", name: "Unknown team", binding: "team:chess:member" }, +] + +/** Atomic, idempotent Auth contract fake. Individual assignment effects are exposed for assertions. */ +function fakeAuth(users: RoleDirectory["users"], refuse: (change: RoleChange) => string | null = () => null) { + const changes: { actor: string; sub: string; role: string; action: "assign" | "unassign"; reason: string }[] = [] + const receipts = new Map() + const result = (sub: string) => ({ + roles: ROLES, + held: users.find((u) => u.sub === sub)?.roles ?? [], + assigned: users.find((u) => u.sub === sub)?.roles ?? [], + }) + const roles: PeopleRoles = { + directory: vi.fn(async () => structuredClone({ roles: ROLES, users })), + change: vi.fn(async (command: RoleChange) => { + if (receipts.has(command.id)) return structuredClone(result(command.sub)) + const reason = refuse(command) + if (reason) throw new RoleChangeError(403, reason) + let user = users.find((u) => u.sub === command.sub) + if (!user) { + user = { sub: command.sub, name: command.sub, email: null, telegramId: null, telegramUsername: null, roles: [] } + users.push(user) + } + const next = new Set(user.roles) + for (const change of command.changes) { + const prefix = change.kind === "admin" ? "admin" : `team:${change.team}:` + const bound = ROLES.filter((r) => r.binding.startsWith(prefix)) + if (!bound.length) continue + for (const r of bound) next.delete(r.key) + const desired = + change.kind === "admin" + ? change.active + ? "admin" + : null + : change.role + ? `team:${change.team}:${change.role}` + : null + if (desired) { + const role = bound.find((r) => r.binding === desired) + if (!role) throw new RoleChangeError(409, "Missing binding") + next.add(role.key) + } + } + for (const role of user.roles) + if (!next.has(role)) + changes.push({ actor: command.actor, sub: command.sub, role, action: "unassign", reason: command.reason }) + for (const role of next) + if (!user.roles.includes(role)) + changes.push({ actor: command.actor, sub: command.sub, role, action: "assign", reason: command.reason }) + user.roles = [...next].sort() + receipts.set(command.id, JSON.stringify(command)) + return structuredClone(result(command.sub)) + }), + } + return { roles, changes, users } +} + +const user = (sub: string, roles: string[], extra: Partial = {}) => ({ + sub, + name: "Giulia Neri", + email: null, + telegramId: null, + telegramUsername: null, + roles, + ...extra, +}) + +describe("roleChanges", () => { + it("sends one desired state per changed concept, leaving concrete assignments to Auth", () => { + expect(roleChanges({ admin: false, teams: {} }, { admin: true, teams: { it: "member" } })).toEqual([ + { kind: "admin", active: true }, + { kind: "team", team: "it", role: "member" }, + ]) + expect(roleChanges({ admin: false, teams: { it: "lead" } }, { admin: false, teams: {} })).toEqual([ + { kind: "team", team: "it", role: null }, + ]) + }) +}) + +describe("People mirrors PoliNetwork Auth", () => { + it("creates and links records for role holders, and asks HR before linking one by Telegram ID", async () => { + const auth = fakeAuth([ + user("u-new", ["design-lead"], { name: "Giulia Neri", email: "giulia.neri@polinetwork.org" }), + user("u-tg", ["it-core"], { name: "Luca V.", telegramId: "777", telegramUsername: "lucav" }), + user("u-none", []), + ]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + state.persons["P-0003"].accountSub = null + state.persons["P-0003"].account = { status: "none" } + state.persons["P-0003"].profile.telegramId = "777" + }) + await h.service.syncSources() + const persons = Object.values(h.state().persons) + expect(persons).toHaveLength(4) + const giulia = persons.find((p) => p.accountSub === "u-new") + expect(giulia).toMatchObject({ + profile: { firstName: "Giulia", lastName: "Neri", campus: null, course: "", year: "", personalEmail: null }, + account: { status: "linked", via: "PoliNetwork Auth" }, + teams: [{ team: "design", role: "lead", endedOn: null }], + }) + // A Telegram ID on a record was typed by HR or imported: HR confirms before the role holder gets it. + expect(h.state().persons["P-0003"]).toMatchObject({ accountSub: null, teams: [] }) + const [review] = await h.service.listReviews(master) + expect(review).toMatchObject({ kind: "identity-match", record: { id: "P-0003" } }) + await h.service.resolveReview(master, { reviewId: review.id, resolution: "link-anyway", reason: "Checked" }) + expect(h.state().persons["P-0003"]).toMatchObject({ accountSub: "u-tg", teams: [{ team: "it", role: "member" }] }) + const rows = await h.service.listPeople(master) + expect(rows.find((r) => r.id === giulia?.id)?.profile.campus).toBeNull() + }) + + it("Auth owns bound concepts on linked records, including legacy local roles", async () => { + const auth = fakeAuth([user("president", ["admin", "it-core"])]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + expect(h.state().persons["P-0001"]).toMatchObject({ + admin: { status: "active" }, + teams: [{ team: "it", endedOn: null }], + }) + // A local role cannot retain authority once its concept is owned by Auth. + expect(h.state().persons["P-0002"].admin?.status).toBe("former") + auth.users[0].roles = [] + await h.service.syncSources() + const p = h.state().persons["P-0001"] + expect(p.admin).toMatchObject({ status: "former", endReason: "Not held in PoliNetwork Auth" }) + expect(p.teams[0].endedOn).toBe("2026-10-18") + expect(h.state().persons["P-0002"].admin?.status).toBe("former") + }) + + it("scopes the Capo area to assigned Auth admins without Telegram group data", async () => { + const auth = fakeAuth([user("president", ["admin"]), user("member", ["admin"])]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + await h.store.transaction(async ({ state }) => { + const capo = state.persons["P-0001"].admin + const former = state.persons["P-0002"].admin + const active = state.persons["P-0003"].admin + assert.ok(capo && former && active) + capo.capoScope = "Ingegneria Informatica" + const reference = { id: "P-0001", name: "Mario Rossi" } + former.capoOfReference = reference + active.capoOfReference = reference + }) + const capo = viewer("president", ["people:self"]) + const area = await h.service.getCapoArea(capo) + expect(Object.keys(area).sort()).toEqual(["admins", "scope"]) + expect(area.admins.map((p) => p.id)).toEqual(["P-0003"]) + expect(area.admins[0].profile.personalEmail).toBeNull() + expect(area.admins[0].member).toBeNull() + expect(area.admins[0].admin).not.toHaveProperty("groups") + expect(area.admins[0].admin).not.toHaveProperty("requested") + + auth.users[1].roles = [] + await h.service.syncSources() + expect((await h.service.getCapoArea(capo)).admins).toEqual([]) + auth.users[0].roles = [] + await h.service.syncSources() + await expect(h.service.getCapoArea(capo)).rejects.toMatchObject({ code: "FORBIDDEN" }) + }) + + it("gives and takes back the role when the dashboard changes a linked record", async () => { + const auth = fakeAuth([]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.addTeamMember(master, { + teamId: "design", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + expect(auth.changes).toEqual([ + { actor: "president", sub: "member", role: "design-member", action: "assign", reason: expect.any(String) }, + ]) + expect(h.state().persons["P-0003"].teams).toMatchObject([{ team: "design", role: "member", endedOn: null }]) + await h.service.endTeamMembership(master, { + teamId: "design", + personId: "P-0003", + lastDay: "2026-10-18", + reason: "Moved on", + note: "", + }) + expect(auth.changes.at(-1)).toMatchObject({ role: "design-member", action: "unassign", reason: "Moved on" }) + expect(h.state().persons["P-0003"].teams).toMatchObject([{ team: "design", endedOn: "2026-10-18" }]) + }) + + it("rolls the dashboard change back when PoliNetwork Auth refuses it", async () => { + const auth = fakeAuth([], () => "This role grants permissions you do not hold (tg:trusted).") + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await expect( + h.service.addTeamMember(master, { + teamId: "it", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + ).rejects.toMatchObject({ code: "FORBIDDEN", message: expect.stringContaining("tg:trusted") }) + expect(h.state().persons["P-0003"].teams).toEqual([]) + }) + + it("keeps unlinked records owned by People", async () => { + const auth = fakeAuth([]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + const { id } = await h.service.createPerson(master, { + firstName: "Sara", + lastName: "Blu", + personalEmail: "sara@example.org", + phone: "", + telegramUsername: "", + course: "Design della Comunicazione", + year: "1st year", + campus: "Bovisa", + admin: false, + }) + await h.service.addTeamMember(master, { + teamId: "design", + personId: id, + role: "member", + since: "2026-10-01", + fields: {}, + }) + expect(auth.roles.change).not.toHaveBeenCalled() + }) + + it("notes a refused census change instead of failing the answer", async () => { + const auth = fakeAuth([user("member", ["it-core"])], () => "Refused for the test.") + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + await h.service.answerCensus(viewer("member", ["people:self"]), { + answer: "leaving", + course: "Ingegneria Informatica", + year: "3rd year", + campus: "Leonardo", + keepTeams: [], + reason: "Graduating", + note: "", + }) + const p = h.state().persons["P-0003"] + expect(p.census[0].answer).toBe("leaving") + expect( + p.activity.some((a) => a.text.includes("PoliNetwork Auth refused the role change: Refused for the test.")) + ).toBe(true) + }) +}) + +describe("PoliNetwork Auth unreachable", () => { + it("notes the failure on a census answer instead of failing it", async () => { + const auth = fakeAuth([user("member", ["it-core"])]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + vi.mocked(auth.roles.change).mockRejectedValue(new RoleChangeError(503, "PoliNetwork Auth could not be reached")) + await h.service.answerCensus(viewer("member", ["people:self"]), { + answer: "leaving", + course: "Ingegneria Informatica", + year: "3rd year", + campus: "Leonardo", + keepTeams: [], + reason: "Graduating", + note: "", + }) + const p = h.state().persons["P-0003"] + expect(p.census[0].answer).toBe("leaving") + expect(p.activity.some((a) => a.text.includes("didn't answer"))).toBe(true) + // Still a member until Auth answers: the sweep sends the same command again. + expect(p.teams[0]).toMatchObject({ team: "it", endedOn: null }) + expect(p.roleCommand?.unanswered).toBe(true) + }) +}) + +describe("People mirrors the Microsoft 365 Soci group", () => { + const member = (id: string, mail: string, employeeId: string | null, extra: Partial = {}) => ({ + id, + mail, + givenName: "Marta", + surname: "Gialli", + displayName: "Marta Gialli", + employeeId, + createdOn: "2025-03-02", + ...extra, + }) + + it("adds members with their number, merges with linked accounts and flags unusable numbers", async () => { + const auth = fakeAuth([user("u-marta", ["it-core"], { email: "marta.gialli@polinetwork.org" })]) + const members = [ + member("az-1", "marta.gialli@polinetwork.org", "42"), + member("az-2", "nonumber@polinetwork.org", null, { givenName: "Paolo", surname: "Viola" }), + ] + const h = harness({ peopleRoles: auth.roles, azureMembers: async () => members }) + await h.service.syncSources() + const persons = Object.values(h.state().persons) + expect(persons).toHaveLength(2) + expect(persons[0]).toMatchObject({ + accountSub: "u-marta", + azureId: "az-1", + member: { number: "0042", status: "active", admittedOn: "2025-03-02", m365Email: "marta.gialli@polinetwork.org" }, + teams: [{ team: "it" }], + }) + expect(persons[1]).toMatchObject({ member: null, discrepancies: [{ kind: "needs-review" }] }) + await h.service.syncSources() + expect(Object.values(h.state().persons)).toHaveLength(2) + expect(h.state().persons[persons[1].id].discrepancies).toHaveLength(1) + }) + + it("sends no automatic fee reminders for the year a membership was imported", async () => { + const h = harness({ azureMembers: async () => [member("az-1", "marta.gialli@polinetwork.org", "42")] }) + h.setDate("2026-10-28T08:00:00Z") + await h.service.sweep() + expect(Object.keys(h.state().outbox)).toEqual([]) + }) + + it("reads the Soci group again only after its cache expires", async () => { + const azureMembers = vi.fn(async () => []) + const h = harness({ azureMembers }) + await h.service.sweep() + await h.service.listPeople(master) + expect(azureMembers).toHaveBeenCalledTimes(1) + h.advance(SOURCE_TTL_MS.members) + await h.service.sweep() + expect(azureMembers).toHaveBeenCalledTimes(2) + }) + + it("takes who is a member and their number from the Soci group", async () => { + const members = [member("az-1", "marta.gialli@polinetwork.org", "42")] + const h = harness({ azureMembers: async () => members }) + h.setDate("2026-10-10T08:00:00Z") + await h.service.syncSources() + const id = Object.keys(h.state().persons)[0] + members[0].employeeId = "43" + await h.service.syncSources() + expect(h.state().persons[id].member).toMatchObject({ number: "0043", status: "active" }) + + members.length = 0 + await h.service.syncSources() + expect(h.state().persons[id].member).toMatchObject({ number: "0043", status: "former" }) + + members.push(member("az-1", "marta.gialli@polinetwork.org", "43")) + await h.service.syncSources() + expect(h.state().persons[id].member?.status).toBe("active") + }) + + it("keeps a member admitted in the last days whom the Soci group listing doesn't show yet", async () => { + const members = [member("az-1", "marta.gialli@polinetwork.org", "42", { createdOn: "2026-10-09" })] + const h = harness({ azureMembers: async () => members }) + h.setDate("2026-10-10T08:00:00Z") + await h.service.syncSources() + const id = Object.keys(h.state().persons)[0] + members.length = 0 + await h.service.syncSources() + expect(h.state().persons[id].member?.status).toBe("active") + h.setDate("2026-10-12T08:00:00Z") + await h.service.syncSources() + expect(h.state().persons[id].member?.status).toBe("former") + }) + + it("leaves memberships alone while Microsoft 365 has never answered", async () => { + const h = harness({ + azureMembers: async () => { + throw new Error("Graph unavailable") + }, + }) + await h.seed() + const before = Object.values(h.state().persons).filter((p) => p.member?.status === "active").length + await h.service.syncSources() + expect(Object.values(h.state().persons).filter((p) => p.member?.status === "active")).toHaveLength(before) + }) +}) + +describe("Auth is the authority for People role commands", () => { + it("never leaves a refused linked Lead authorized, even after synchronization", async () => { + const auth = fakeAuth([user("member", [])], () => "Appointing a Lead requires people:appoint") + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const p = state.persons["P-0003"] + p.accountSub = null + p.account = { status: "none" } + p.teams.push({ team: "it", role: "lead", since: "2026-10-01", endedOn: null, endReason: null, fields: {} }) + }) + await h.service.linkAccount(master, { personId: "P-0003", accountId: "member", reason: "Verified identity" }) + // Ended, not deleted, and HR is asked to look at it. + expect(h.state().persons["P-0003"]).toMatchObject({ + teams: [{ team: "it", role: "lead", since: "2026-10-01", endReason: "Not confirmed by PoliNetwork Auth" }], + discrepancies: [{ kind: "needs-review", message: expect.stringContaining("people:appoint") }], + }) + await h.service.syncSources() + expect(h.state().persons["P-0003"].teams.some((t) => !t.endedOn)).toBe(false) + await expect( + h.service.listTeamCandidates(viewer("member", ["people:self"]), { teamId: "it" }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + }) + + it("sends the roles of an unlinked record merged into a linked one to Auth", async () => { + const auth = fakeAuth([user("member", [])]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const first = state.persons["P-0002"] + first.accountSub = null + first.account = { status: "none" } + first.profile.telegramId = null + first.teams.push({ team: "it", role: "member", since: "2026-10-01", endedOn: null, endReason: null, fields: {} }) + state.reviews.R1 = { + id: "R1", + kind: "two-records", + sub: "member", + resolved: false, + rejectedPersonIds: [], + record: { id: "P-0002" }, + other: { id: "P-0003" }, + } as never + }) + await h.service.resolveReview(master, { reviewId: "R1", resolution: "merge-first", reason: "Same student" }) + expect(auth.roles.change).toHaveBeenCalled() + expect(vi.mocked(auth.roles.change).mock.calls[0][0].changes).toContainEqual({ + kind: "team", + team: "it", + role: "member", + }) + }) + + it("sends a revocation as one atomic command and preserves confirmed roles when refused", async () => { + const auth = fakeAuth([user("member", ["it-core", "it-lead"])], () => "Refused") + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + await expect( + h.service.endTeamMembership(master, { + personId: "P-0003", + teamId: "it", + lastDay: "2026-10-18", + reason: "Leaving", + note: "", + }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + expect(auth.roles.change).toHaveBeenCalledTimes(1) + expect(vi.mocked(auth.roles.change).mock.calls[0][0].changes).toEqual([{ kind: "team", team: "it", role: null }]) + expect(auth.users[0].roles).toEqual(["it-core", "it-lead"]) + expect(h.state().persons["P-0003"].teams[0]).toMatchObject({ role: "lead", endedOn: null }) + }) + + it("recovers a lost response after restart using the persisted command ID, without granting pending roles", async () => { + const auth = fakeAuth([]) + const change = auth.roles.change + auth.roles.change = vi.fn(async (command) => { + await change(command) + throw new RoleChangeError(503, "Response lost after commit") + }) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await expect( + h.service.addTeamMember(master, { + teamId: "it", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + ).rejects.toMatchObject({ message: expect.stringContaining("don't repeat") }) + const pending = h.state().persons["P-0003"].roleCommand + expect(pending).toBeDefined() + expect(h.state().persons["P-0003"].teams).toEqual([]) + auth.roles.change = vi.fn(change) + const restarted = harness({ store: h.store, peopleRoles: auth.roles }) + await restarted.service.sweep() + expect(vi.mocked(auth.roles.change).mock.calls[0][0].id).toBe(pending?.request.id) + expect(auth.changes).toHaveLength(1) + expect(h.state().persons["P-0003"].roleCommand).toBeUndefined() + expect(h.state().persons["P-0003"].teams[0]).toMatchObject({ team: "it", role: "member", endedOn: null }) + }) + + it("does not confirm an inherited revocation refused by Auth", async () => { + const auth = fakeAuth([user("member", ["it-core"])]) + auth.roles.change = vi.fn(async () => { + throw new RoleChangeError(409, "The role is inherited. Change its granting role in Auth.") + }) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + await expect( + h.service.endTeamMembership(master, { + personId: "P-0003", + teamId: "it", + lastDay: "2026-10-18", + reason: "Leaving", + note: "", + }) + ).rejects.toMatchObject({ message: expect.stringContaining("inherited") }) + expect(h.state().persons["P-0003"].teams[0].endedOn).toBeNull() + }) + + it("refreshes linked identities before importing Microsoft 365 and avoids a duplicate person", async () => { + const auth = fakeAuth([user("member", ["it-core"], { email: "luca@gmail.com" })]) + let members: AzureMember[] = [] + const h = harness({ peopleRoles: auth.roles, azureMembers: async () => members }) + await h.seed() + await h.service.syncSources() + auth.users[0].email = "luca@polinetwork.org" + auth.users[0].azureId = "azure-luca" + members = [ + { + id: "azure-luca", + mail: "luca@polinetwork.org", + givenName: "Luca", + surname: "Verdi", + displayName: "Luca Verdi", + employeeId: "42", + createdOn: "2020-01-01", + }, + ] + await h.service.syncSources() + expect(Object.values(h.state().persons)).toHaveLength(3) + expect(h.state().persons["P-0003"]).toMatchObject({ + azureId: "azure-luca", + member: { number: "0042" }, + account: { email: "luca@polinetwork.org" }, + }) + }) + + it("does not hold the People transaction open while contacting Auth", async () => { + const auth = fakeAuth([]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + const change = auth.roles.change + auth.roles.change = async (command) => { + await h.service.listPeople(master) + return change(command) + } + await h.service.addTeamMember(master, { + teamId: "it", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + }, 2000) + + it("does not overwrite a confirmed command with a snapshot fetched before it", async () => { + const auth = fakeAuth([]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + const old = await auth.roles.directory() + let release!: (value: RoleDirectory) => void + let fetched!: () => void + const started = new Promise((resolve) => { + fetched = resolve + }) + vi.mocked(auth.roles.directory).mockImplementationOnce(() => { + fetched() + return new Promise((resolve) => { + release = resolve + }) + }) + const sync = h.service.syncSources() + await started + await h.service.addTeamMember(master, { + teamId: "it", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + release(old) + await sync + expect(h.state().persons["P-0003"].teams[0].endedOn).toBeNull() + }) + + it("keeps reads working and refuses other edits of the person while a command waits for Auth", async () => { + const auth = fakeAuth([user("member", ["admin", "it-core"])]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + vi.mocked(auth.roles.change).mockRejectedValueOnce(new RoleChangeError(503, "Timed out")) + const end = { personId: "P-0003", teamId: "it" as const, lastDay: "2026-10-18", reason: "Leaving", note: "" } + await expect(h.service.endTeamMembership(master, end)).rejects.toMatchObject({ code: "PRECONDITION_FAILED" }) + // Reading the pending person must not be refused. + expect((await h.service.getPerson(master, { id: "P-0003" })).admin).toMatchObject({ status: "active" }) + await expect( + h.service.updateTeamFields(master, { personId: "P-0003", teamId: "it", fields: {} }) + ).rejects.toMatchObject({ code: "CONFLICT" }) + await expect(h.service.unlinkAccount(master, { personId: "P-0003" })).rejects.toMatchObject({ code: "CONFLICT" }) + await expect(h.service.endTeamMembership(master, end)).rejects.toMatchObject({ code: "CONFLICT" }) + await h.service.sweep() + const p = h.state().persons["P-0003"] + expect(p.roleCommand).toBeUndefined() + expect(p.teams[0]).toMatchObject({ endedOn: "2026-10-18", endReason: "Leaving" }) + expect(p.admin).toMatchObject({ status: "active" }) + expect(p.activity.filter((a) => a.text.includes("didn't answer"))).toHaveLength(1) + }) + + it("refreshes a linked record's identities without rewriting how it was linked", async () => { + const auth = fakeAuth([user("member", [], { email: "luca@polinetwork.org", azureId: "azure-luca" })]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + expect(h.state().persons["P-0003"]).toMatchObject({ + azureId: "azure-luca", + account: { status: "linked", email: "luca@polinetwork.org", via: "IdP", linkedOn: "2026-10-01", how: "test" }, + }) + }) + + it("asks HR instead of guessing when Auth and Microsoft 365 identities match different records", async () => { + const auth = fakeAuth([user("member", ["it-core"], { telegramId: "101" })]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + // P-0001 holds Telegram 101 but is linked to another account: neither record changes hands. + expect(h.state().persons["P-0001"]).toMatchObject({ + accountSub: "president", + discrepancies: [{ kind: "needs-review", message: expect.stringContaining("member") }], + }) + expect(h.state().persons["P-0003"].discrepancies).toHaveLength(1) + }) +}) + +describe("People reads PoliNetwork Auth on every operation", () => { + it("shows a role given in Auth without any sync", async () => { + const auth = fakeAuth([user("u-giulia", ["it-lead"])]) + const h = harness({ peopleRoles: auth.roles }) + const rows = await h.service.listPeople(master) + expect(rows.find((r) => r.teams.some((t) => t.team === "it" && t.role === "lead" && !t.endedOn))).toBeTruthy() + }) + + it("starts a role when Auth gave it", async () => { + const auth = fakeAuth([ + user("u-giulia", ["admin", "it-core"], { since: { admin: "2024-09-01", "it-core": "2025-02-10" } }), + ]) + const h = harness({ peopleRoles: auth.roles }) + const person = (await h.service.listPeople(master)).find((r) => r.admin) + expect(person?.admin?.since).toBe("2024-09-01") + expect(person?.teams).toMatchObject([{ team: "it", role: "member", since: "2025-02-10" }]) + }) + + it("ends a role taken back in Auth on the next operation after the cache expires", async () => { + const auth = fakeAuth([user("u-giulia", ["it-lead"])]) + const h = harness({ peopleRoles: auth.roles }) + await h.service.listPeople(master) + auth.users[0].roles = [] + h.advance(SOURCE_TTL_MS.directory) + const rows = await h.service.listPeople(master) + expect(rows.flatMap((r) => r.teams).filter((t) => !t.endedOn)).toEqual([]) + }) + + it("refuses to work when Auth has not answered for too long, but rides out a short outage", async () => { + const auth = fakeAuth([user("u-giulia", ["admin"])]) + const h = harness({ peopleRoles: auth.roles }) + await h.service.listPeople(master) + vi.mocked(auth.roles.directory).mockRejectedValue(new Error("down")) + h.advance(SOURCE_TTL_MS.directory) + await expect(h.service.listPeople(master)).resolves.toBeTruthy() + h.advance(DIRECTORY_MAX_AGE_MS) + await expect(h.service.listPeople(master)).rejects.toMatchObject({ code: "PRECONDITION_FAILED" }) + }) +}) diff --git a/tests/people-router.test.ts b/tests/people-router.test.ts index c0abeb2..dc91c5d 100644 --- a/tests/people-router.test.ts +++ b/tests/people-router.test.ts @@ -65,7 +65,7 @@ describe("People tRPC contract", () => { const procedures = (r as unknown as { _def: { procedures: Record } })._def .procedures const defs = Object.entries(procedures) - expect(defs.length).toBe(62) + expect(defs.length).toBe(61) for (const [, proc] of defs) expect(proc._def.meta).toMatchObject({ policy: { user: { scope: "backend:admin" } } }) for (const path of [ "persons.list", @@ -73,7 +73,8 @@ describe("People tRPC contract", () => { "teams.candidates", "census.importPreview", "linking.resolve", - "capo.approve", + "linking.recent", + "capo.get", "me.roles", "fees.review", "receipts.prepareSignatures", diff --git a/tests/people.test.ts b/tests/people.test.ts index df779a5..c63f288 100644 --- a/tests/people.test.ts +++ b/tests/people.test.ts @@ -137,7 +137,7 @@ describe("People authorization and projections", () => { "Correction: Personal email → luca.new@example.org; New address" ) }) - it("does not grant record roles or mutation rights to an unconfirmed match", async () => { + it("does not grant record roles or mutation rights to a match waiting for HR", async () => { const h = harness() await h.seed() await h.store.transaction(async ({ state }) => { @@ -148,13 +148,15 @@ describe("People authorization and projections", () => { p.teams.push({ team: "it", role: "lead", since: "2026-10-01", endedOn: null, endReason: null, fields: {} }) }) const v = viewer("president", ["people:self"], "101") - expect(await h.service.getMyArea(v)).toMatchObject({ state: "match", candidate: { id: "P-0001" } }) + // The record carries roles, so HR approves the link: the account holder can't confirm it themselves. + expect(await h.service.getMyArea(v)).toMatchObject({ state: "awaiting-approval", candidate: { id: "P-0001" } }) expect(await h.service.getMyRoles(v)).toEqual({ capoScope: null, leads: [] }) await expect(h.service.getCapoArea(v)).rejects.toMatchObject({ code: "FORBIDDEN" }) await expect(h.service.revokePhotoConsent(v)).rejects.toMatchObject({ code: "FORBIDDEN" }) - await h.service.rejectMatch(v) - expect(await h.service.getMyArea(v)).toMatchObject({ state: "none" }) await expect(h.service.confirmMatch(v)).rejects.toMatchObject({ code: "CONFLICT" }) + expect(await h.service.listReviews(master)).toEqual([ + expect.objectContaining({ kind: "identity-match", record: expect.objectContaining({ id: "P-0001" }) }), + ]) }) it("does not trust an unverified directory email for self matching", async () => { const h = harness() @@ -162,10 +164,14 @@ describe("People authorization and projections", () => { await h.store.transaction(async ({ state }) => { state.persons["P-0003"].accountSub = null state.persons["P-0003"].account = { status: "none" } + // A record that grants nothing is the one the account holder may confirm. + state.persons["P-0003"].admin = null }) - h.accounts[2].emailVerified = false + // Without its Telegram account, which would match on its own. + h.accounts[2].telegramId = null + h.accounts[2].verifiedEmail = null expect(await h.service.getMyArea(viewer("member", ["people:self"]))).toMatchObject({ state: "none" }) - h.accounts[2].emailVerified = true + h.accounts[2].verifiedEmail = "luca@example.org" expect(await h.service.getMyArea(viewer("member", ["people:self"]))).toMatchObject({ state: "match" }) }) it("prevents account takeover and invalidates old invitation tokens", async () => { @@ -176,12 +182,12 @@ describe("People authorization and projections", () => { ).rejects.toMatchObject({ code: "CONFLICT" }) await h.service.unlinkAccount(master, { personId: "P-0003" }) await h.service.sendInvite(master, { personId: "P-0003" }) - const first = Object.values(h.state().outbox).at(-1)?.text.split("peopleInvite=")[1] ?? "" + const first = Object.values(h.state().outbox).at(-1)?.action?.url.split("peopleInvite=")[1] ?? "" await h.service.sendInvite(master, { personId: "P-0003" }) await expect(h.service.acceptInvite(viewer("member", ["people:self"]), { token: first })).rejects.toMatchObject({ code: "NOT_FOUND", }) - const last = Object.values(h.state().outbox).at(-1)?.text.split("peopleInvite=")[1] ?? "" + const last = Object.values(h.state().outbox).at(-1)?.action?.url.split("peopleInvite=")[1] ?? "" await expect(h.service.acceptInvite(viewer("vice", ["people:self"]), { token: last })).rejects.toMatchObject({ code: "NOT_FOUND", }) @@ -409,83 +415,36 @@ describe("People payments, receipt ownership and delivery", () => { }) }) -it("retains deselected census groups as pending HR work until Telegram confirms removal", async () => { - const groups = [{ chatId: "-1001", title: "Test group", admins: ["103"] }] - const h = harness({ telegramGroups: async () => groups }) +it("shows a Capo Admin their admins, and records an admin's census answer without Telegram groups", async () => { + const h = harness() await h.seed() - await h.service.listPeople(master) - await h.service.answerCensus(viewer("member", ["people:self"], "103"), { - answer: "continues", - course: "Computer science", - year: "2nd year", - campus: "Leonardo", - keepGroups: [], - keepTeams: [], - reason: "", - note: "", - }) - let person = await h.service.getPerson(master, { id: "P-0003" }) - expect(person.admin?.groups).toHaveLength(1) - expect(person.discrepancies).toContainEqual( - expect.objectContaining({ - kind: "admin-removal", - message: expect.stringContaining("Telegram admin removal pending: Test group (-1001)"), - }) - ) - expect(h.state().persons["P-0003"].pendingGroupRemovals).toHaveLength(1) await h.store.transaction(async ({ state }) => { - state.persons["P-0003"].discrepancies[0].kind = "needs-review" - state.persons["P-0003"].discrepancies.push({ - kind: "needs-review", - message: "HR-only identity review", - suggestedTelegram: null, + const admin = (capoScope: string | null, capoOfReference: { id: string; name: string } | null) => ({ + status: "active" as const, + since: "2026-10-01", + endedOn: null, + endReason: null, + availableAsCapo: false, + capoOfReference, + capoScope, }) + state.persons["P-0001"].admin = admin("Ingegneria Informatica", null) + state.persons["P-0003"].admin = admin(null, { id: "P-0001", name: "Mario Rossi" }) }) - const ownArea = await h.service.getMyArea(viewer("member", ["people:self"], "103")) - expect(ownArea).toMatchObject({ - state: "linked", - person: { - discrepancies: [ - expect.objectContaining({ - kind: "admin-removal", - message: expect.stringContaining("Telegram admin removal pending:"), - }), - ], - }, - }) - groups[0].admins = [] - person = await h.service.getPerson(master, { id: "P-0003" }) - expect(person.admin?.groups).toHaveLength(0) - expect(person.discrepancies).not.toContainEqual( - expect.objectContaining({ message: expect.stringContaining("Telegram admin removal pending:") }) - ) - expect(h.state().persons["P-0003"].pendingGroupRemovals).toHaveLength(0) - expect(await h.service.getMyArea(viewer("member", ["people:self"], "103"))).toMatchObject({ - state: "linked", - person: { discrepancies: [] }, - }) -}) - -it("keeps groups and pending removals while Telegram group admins are unknown", async () => { - const groups: { chatId: string; title: string; admins: string[] | null }[] = [ - { chatId: "-1001", title: "Test group", admins: ["103"] }, - ] - const h = harness({ telegramGroups: async () => groups }) - await h.seed() - await h.service.listPeople(master) + const area = await h.service.getCapoArea(viewer("president", ["people:self"], "101")) + expect(Object.keys(area).sort()).toEqual(["admins", "scope"]) + expect(area.scope).toBe("Ingegneria Informatica") + expect(area.admins.map((a) => a.id)).toEqual(["P-0003"]) await h.service.answerCensus(viewer("member", ["people:self"], "103"), { answer: "continues", course: "Computer science", year: "2nd year", campus: "Leonardo", - keepGroups: [], keepTeams: [], reason: "", note: "", }) - groups[0].admins = null const person = await h.service.getPerson(master, { id: "P-0003" }) - expect(person.admin?.groups).toEqual([{ chatId: "-1001", title: "Test group" }]) - expect(person.discrepancies).toContainEqual(expect.objectContaining({ kind: "admin-removal" })) - expect(h.state().persons["P-0003"].pendingGroupRemovals).toHaveLength(1) + expect(person.admin).toMatchObject({ status: "active" }) + expect(person.discrepancies).toEqual([]) })