Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
2839fa1
fix(auth): remove the anonymous rollback path and legacy compatibilit…
BIA3IA Oct 26, 2026
0a7185d
feat(people): read Telegram group admins from the bot, without storin…
BIA3IA Oct 26, 2026
aa7256b
feat(people): mirror PoliNetwork Auth roles and Microsoft 365 members
viganogabriele Oct 25, 2026
b4b8582
fix(people): survive unreachable PoliNetwork Auth and inherited roles
viganogabriele Oct 25, 2026
58166a2
fix(people)!: grant roles only once PoliNetwork Auth confirms them
viganogabriele Oct 26, 2026
54b934f
fix(people): retry a stale-token 401 once and push roles merged into …
viganogabriele Oct 26, 2026
4b51879
fix(people): read roles and members from their sources on every opera…
BIA3IA Oct 26, 2026
1ca6a81
fix(people)!: use Auth admins without Telegram group assignments
BIA3IA Oct 26, 2026
e8c1d03
feat(people): create minimal Auth people and reconcile approved login…
BIA3IA Oct 27, 2026
ef947e6
Merge remote-tracking branch 'origin/main' into feat/people-single-so…
BIA3IA Oct 28, 2026
f7adc55
feat(people): tell a first sign-in it is awaiting Master Admin approval
BIA3IA Oct 28, 2026
079e944
refactor(people): match accounts with one identity rule and one outco…
BIA3IA Oct 28, 2026
ed52686
fix(people): keep declines, index matching and guard Microsoft 365 links
BIA3IA Oct 28, 2026
892cf45
feat(people): send People emails with a greeting, an explanation and …
BIA3IA Oct 28, 2026
e9fca51
feat(people): list recent links and undo mistaken account matches
BIA3IA Oct 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<id>:member`, `team:<id>: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
Expand Down Expand Up @@ -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.
11 changes: 10 additions & 1 deletion src/azure/functions/members.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,16 @@ export async function getMembers(): Promise<ParsedUser[]> {
.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
Expand Down
4 changes: 3 additions & 1 deletion src/azure/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export type BasicUser = Pick<
// this is the type representing our call to `/users`
export type User = Pick<
Required<TUser>,
"displayName" | "mail" | "givenName" | "surname" | "id" | "assignedLicenses" | "employeeId"
"displayName" | "mail" | "givenName" | "surname" | "id" | "assignedLicenses" | "employeeId" | "createdDateTime"
>

export type ParsedUser = {
Expand All @@ -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[]
}
Expand Down
7 changes: 6 additions & 1 deletion src/emails/mailer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 = <div style={{ whiteSpace: "pre-wrap" }}>{input.text}</div>
const component = (
<PeopleEmail subject={input.subject} firstName={input.firstName} text={input.text} action={input.action} />
)
const attachments = input.attachment
? [
{
Expand Down
89 changes: 89 additions & 0 deletions src/emails/templates/people.tsx
Original file line number Diff line number Diff line change
@@ -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<PeopleEmailProps> = ({ subject, firstName, text, action }) => {
const paragraphs = text.split(/\n\s*\n/)
const title = subject.replace(/^PoliNetwork · | · PoliNetwork$/g, "")
return (
<Html lang="it">
<Tailwind config={{ presets: [pixelBasedPreset] }}>
<Head />
<Preview>{paragraphs[0]}</Preview>
<Body className="m-0 bg-white p-0 font-sans text-base leading-normal">
<Logo />
<Container className="mx-auto bg-white px-5 max-w-[460px]">
<Heading className="m-0 text-center text-2xl font-bold leading-8">
{title.charAt(0).toUpperCase() + title.slice(1)}
</Heading>
<Section className="py-8">
<Text className="my-2 text-base leading-normal">{firstName ? `Ciao ${firstName},` : "Ciao,"}</Text>
{paragraphs.map((p) => (
<Text key={p} className="my-2 whitespace-pre-line text-base leading-normal">
{p}
</Text>
))}
{action && (
<>
<Section className="my-6 text-center">
<Button
href={action.url}
className="rounded-md bg-[#1156AE] px-5 py-3 text-base font-semibold text-white"
>
{action.label}
</Button>
</Section>
<Text className="my-4 text-sm leading-normal text-gray-700">
Se il pulsante non funziona, copia questo indirizzo nel browser:{" "}
<Link href={action.url} className="break-all text-[#1156AE] underline">
{action.url}
</Link>
</Text>
</>
)}
<Text className="my-2 text-base leading-normal">A presto,</Text>
<Text className="my-2 text-base leading-normal">PoliNetwork</Text>
</Section>
</Container>
<Footer>Messaggio automatico di PoliNetwork APS: non rispondere a questa email.</Footer>
</Body>
</Tailwind>
</Html>
)
}

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
103 changes: 103 additions & 0 deletions src/idp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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) => {
Expand Down Expand Up @@ -56,6 +90,7 @@ function configure() {
let snapshot = null
let events = null
let directory: (() => Promise<z.infer<typeof signerDirectory>>) | 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,
Expand Down Expand Up @@ -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 <T>(change: unknown, resultSchema: z.ZodType<T>): Promise<T> => {
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,
Expand All @@ -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 }),
Expand Down
Loading
Loading