Skip to content
PoliNetworkOrgPublic

About

THE backend (future)

Resources

Stars

1 star

Watchers

2 watching

Forks

Repository files navigation

Backend

Note

WIP

This is a rewrite currently WIP that will take time. Drink a coffee and join us if you would like to contribute.

Currently we are building a backend which can be reached by other services/repos with a tRPC client. If you are using another language than TS... then you might fulfill a PR and implement gRPC (are you sure u want pain?).

Quickstart

Requirements:

  • Bun installed
  • A Postgres database

Note

Azure credentials are optional. When AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET are all omitted, the Azure tRPC routes use a seeded in-memory directory. Its changes last until the backend restarts. Set all three variables to connect to Microsoft Graph.

  1. Install packages

    bun install
  2. Setup environment variables in .env (use .env.example as template and see ./src/env.ts as source of truth)

  3. Run the DB migration

    bun db:migrate
  4. Run the server

    bun dev
  5. (Optional) Fill the database with sample data: Telegram users, groups and messages, course groups and labels, projects, associations, FAQs, freshman guides, website documents (with placeholder file links), sample credits for the acknowledgements page, group link reports, audit log entries and grants:

    bun run seed:db

    Each table is seeded only while it is empty. New Telegram messages reference retained users and groups, and missing sample FAQ categories are added when the FAQ table is empty. Grants are only added for Telegram users created by the current run.

    --force replaces the Telegram activity tables, sample web content, audit logs, and grants.

Authentication

Every caller authenticates with a PoliNetwork IdP token (RFC v3, Phase 5):

  • With a token (Authorization: Bearer <IdP access token>): the token is verified with @polinetwork/auth-kit, and the call is fully enforced. Every procedure declares, per actor kind, the scope it needs and, for people, the permission they must hold in the IdP's access snapshot. A token that fails verification is rejected. The bot acts for a Telegram user with X-PN-Actor: telegram:<id>, which only a service token with backend:tg:act-as may send.
  • Without a token: refused (UNAUTHORIZED). There is no anonymous access, and handlers always receive the token's actor in ctx.actor.

Procedures are built with policy(...) from src/trpc.ts; the bare tRPC procedure is not exported, and tests/idp-router.test.ts fails if any procedure lacks a policy.

Who acted always comes from the token, never from the input: procedures take no actor fields (createdBy, modifiedBy, updatedBy, adderId, interruptedById, performerId, adminId). Inputs are plain zod objects, so a key an older client still sends is stripped, not rejected. Content tables record the author in *_by_sub columns; rows written before the IdP migration keep their author's Telegram ID in legacy_*_by_tg_id. Grants are in tg_grants and record the grantor's IdP subject. People sign in only through the IdP: the backend has no login of its own. The bot records moderation actions with tg.auditLog.record, which takes an idempotency key and flags idp_permission actions the snapshot does not back.

The bot's socket.io client authenticates with its service token in auth.token (scope backend:tg:events) and is disconnected when the token expires; a socket without a token is refused. Set OAUTH_BOT_CLIENT_ID on the backend to the same registered OAuth client ID used by the bot. This is the actual client ID, not its display name. Sockets are rejected if this setting is absent, the client ID differs, the token is not a service token or the scope is missing.

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.

Audit log

common_audit_events records who used which permission to change what through the backend. The tRPC audit middleware (src/audit) writes one event per mutation: the action (the procedure path), the caller from the token, the target, the outcome (success, failure when an error is thrown or returned, denied when the policy refuses the caller), the request id shared by the calls of one HTTP request, and when. Calls without a valid token are not recorded.

Every mutation declares how it is recorded in its procedure meta, and a test walks the router so that none ships without one, like its policy:

  • .meta(audit.full()): also the input, the reason and the states before and after that the handler adds with ctx.audit.set(...). fields keeps only those fields of the input, for inputs that carry personal data or free text not worth keeping; a dotted field (output.driveId) keeps one field of a nested object.
  • .meta(audit.minimal({ target })): only the actor, the action, the target and the outcome, for areas that keep their own history behind their own permissions. People records each change in the person's activity history, and the Libro Soci in soci_activity.
  • .meta(audit.none(why)): not recorded, e.g. the bot's ingestion, or Telegram moderation, which tg_audit_log keeps under its own retention rules.

Handlers call ctx.audit.skip() when a call changed nothing. Inputs and states are stored without secrets (password, token, ticket, code, *Key, *Secret fields) or file contents, and are cut when too large. Denied calls keep no input.

Events are deleted 24 months after they were written (AUDIT_EVENTS_RETENTION_MONTHS). Dashboard users with the IdP permission audit:read read the log with audit.list, newest first, paged by cursor and filtered by area, outcome, target, actor, date or text.

Changes made outside the backend's tRPC procedures are not in the log: directly in Telegram or WhatsApp, the cron jobs, the e-signing agent endpoints (each request keeps its own history), the GitHub webhook (regulations publications and document creations completing when their pull request merges, which keep their emanation record and the document's creation state) and roles and permissions in the IdP.

People

The people router is the admin dashboard's register of Group Admins, Capo Admins and team members. Each person is one record in people_persons; their roles are rows in people_assignments, with an append-only history in people_activity.

  • A record linked to a login account (account_sub): PoliNetwork Auth is the source of truth. People reads who holds the roles bound to People from GET /api/internal/people-roles (15 s cache, the last answer during an outage of up to an hour) and creates linked records for people given a bound role by hand in Auth. Changes go to POST /api/internal/people-roles through the people_role_commands outbox: each command has an ID Auth applies at most once, so the cron sends it again until Auth answers. The assignment shows sent until Auth confirms it, and Auth's reason when it refuses.
  • A record that isn't linked yet: its assignments stay pending in the backend, and are sent when the record is linked, acting as whoever links it by hand or, for an invite, as whoever made each assignment.

A record is linked to a login account in exactly two ways, never by matching emails, names or Telegram:

  • Email invite (people:write, or the Lead of one of the person's teams): a single-use link to the contact email, stored hashed, valid for 14 days; a new invite revokes the previous one. Any signed-in account can open it (me.invite) and accept it (me.acceptInvite), with no People permission and whatever its email.
  • By hand (admin:access + people:link): search the IdP directory and link an account; nobody links their own.

Unlinking (people:link) takes the record's roles back in Auth with a role command, then detaches the account; its assignments go back to pending. linking.recent lists the links of the last 30 days, with method, date and who made them, so a mistake or a forwarded invite is easy to spot and undo.

The backend checks every role change with the same rules as Auth (src/people/rules.ts, shaped like Auth's src/auth/people-binding.ts): no self-grants, the right permission per kind, and bounded delegation against the role's permissions. A concept with no role bound in Auth, or with more than one, can't be assigned. Writes are serialized by one transaction lock. Grant idp:people:roles to the backend's OAuth client to let it change roles.

A record's profile: their Politecnico course (course_code, from polimi_courses), campus, other associations, and student representative seats (CCS, school, Senate, Board, or Other with the seat's name). Which CCS and which school follow from the course and are never stored. Rows carry the course and campus; associations and seats are personal data, returned only with people:read (courses.list and associations.suggest need it too) and kept out of the audit log. On update an omitted profile field is left unchanged, so a client that predates them never erases them. The course list is updated once a year from Polimi's manifesti: see scripts/polimi-courses/README.md.

Soci

The soci router is the Libro Soci: one record per admission in soci_members, keyed on the Microsoft 365 account (entra_object_id) and the member number, with the bookkeeping data the association must keep and an append-only history in soci_activity. Records are never deleted, and a re-admission is a new record with a new number. Microsoft 365 stays the source of truth for who is a socio now: a PoliNetwork account in the Soci group. The design is the admin repository's docs/people/soci.md.

  • Numbers are never reused. soci_numbers keeps every number a record has held. A number is free only if no record has ever held it and no Microsoft 365 user has it as employeeId.
  • One active record per codice fiscale. Codes are validated (format, omocodia, check character) and checked against the birth date.
  • Admitting (members.admit) runs the Microsoft 365 workflow (account, employeeId, licences, Soci group, welcome email to a typed address that isn't stored), then writes the record. A record that can't be written deletes the account.
  • Registering (members.register) writes a record for an account already in Soci, with its current number; personal fields are optional. members.unregistered lists the Soci group's accounts without a record.
  • members.list reports mismatches: an active record whose account isn't in Soci, or an ended one whose account is.

Every members.* and fees.* procedure needs admin:access and soci:read (list, get, unregistered, fees list and file) or soci:write (admit, register, update, setNumber, confirm, reject, markPaid). Microsoft 365 writes run one at a time behind an in-process lock (src/azure/member-writes.ts), which also remembers numbers Entra's searches don't show yet. azure.members is read-only: admitting a socio and changing a member number go through soci.members.*.

Local CSV import preview

scripts/soci-import-preview.ts normalizes a UTF-8 Libro Soci CSV locally, without a database, Microsoft 365, environment configuration or emails. It does not start the server, call registration/admission, or offer an apply option. Every candidate remains unresolved pending account/register reconciliation and financial review.

Try the synthetic example from the repository root:

bun --no-env-file scripts/soci-import-preview.ts \
  --input scripts/examples/soci-import.synthetic.csv \
  --mapping scripts/examples/soci-import.mapping.json

The same command is available as soci:preview; use bun --no-env-file --silent run soci:preview if invoking through the package runner to avoid its command echo. Real input, mapping files containing private labels and detailed reports belong outside Git worktrees. Do not paste them into issue/PR bodies or console logs.

Copy the example mapping and explicitly configure:

  • delimiter: comma or semicolon; dateFormat: iso (YYYY-MM-DD) or italian (DD/MM/YYYY). No guessing.
  • scope: active-only, history (requires mapped end date/reason columns; blank ends mean active), or unknown.
  • columns: required number, firstName, lastName, admittedOn; optional alias, codiceFiscale, birthDate, birthPlace, residence, phone, endedOn, endReason, endNote, mailbox, entraObjectId. Values are exact header names after trimming. Each source column has one assignment; remaining headers require ignoredColumns.
  • endReasonValues: optional exact translations, e.g. { "dimissioni": "resigned" }; targets are lapsed, resigned, expelled, deceased, other. No fuzzy matching; keys with leading or trailing spaces are refused.
  • feeEvidence: optional { "label": "Quota 2025/26", "column": "Quota" } entries. Text is retained as unreviewed; blanks are unknown. The tool never creates Paid/Due status, payment dates, amounts or account identities.

The console shows counts and at most 100 coded diagnostics with physical source line references and canonical field names, errors first. Warnings every row carries (membership_unknown, account_unreconciled, fee_evidence_*) are counted per code instead of listed. Exit codes: 0 preview without blocked rows (still unresolved), 2 blocked rows, 1 configuration, structural CSV or file errors. Malformed quoting, missing/duplicate/empty/unmapped headers and invalid UTF-8 stop the preview. Records with invalid fields remain blocked in the report, with diagnostics and source line but no normalized candidate. Rows blocked by an end-date, duplicate or tax-code check keep their candidate so the conflict can be inspected, and count among the normalized rows. Duplicate numbers block every affected row. Admissions sharing a tax code are kept for review when each ends before the next starts; multiple explicitly active admissions (active_code_conflict) and admissions in force at the same time (overlapping_admissions) are blocked.

For a full plaintext report containing personal data, explicitly add --out /private/directory/report.json. The directory must exist outside Git worktrees; the file is created exclusively with mode 0600, and existing files or symlinks are refused. If writing fails partway the partial file is deleted; output_partial means it could not be, and must be removed by hand. Protect and delete this report like the source book. Limits: 10 MiB input, 64 KiB mapping, 50,000 data records, 256 columns and 16,384 characters per cell. UTF-8 BOM, CRLF/LF/CR, quoted cells, escaped quotes and embedded newlines are supported; blank physical lines, including lines of only spaces or tabs, are skipped. Other encodings need a separate local conversion. Local snapshot reconciliation and any future application are separate steps.

Fees

The rules are hard-coded from the Regolamento Interno (src/soci/fees.ts): €5.00 per fee year, 1 September – 31 August (2026/27), renewals until 31 December, and the fee year after a summer admission (1 June – 31 August) is exempt. Fees live in soci_fees, one per socio and year; uploaded receipts in soci_files (PDF, PNG or JPEG up to 10 MB, judged by content, never expired).

  • Admitting or registering records the admission's fee year as paid (method admission).
  • Every day at 08:00 (Europe/Rome) runDaily opens the current fee year for every active socio without a fee: Due, with the opening email (none once 31 December has passed), or Exempt. On 1 and 21 December it reminds every socio whose fee is still Due, unless an opening or rejection email since that day already gave them the deadline. It is idempotent, and does nothing until SOCI_IBAN and SOCI_BENEFICIARI are set.
  • The socio (me.*, people:self, found by the Microsoft 365 object ID in Auth's access snapshot) sees their record, fees and bank details, uploads the transfer receipt as FormData (file, transferDate, declaredCents), and fills in their own empty fields.
  • The Direttivo confirms or rejects (with a reason) an uploaded receipt, or marks a fee as paid by hand, which also opens a fee the year hasn't opened yet.
  • Birthdays: at 08:00 sendBirthdays greets every active socio born that day (29 February: the 28th in years without one), whatever the bank details.
  • Emails (Italian React Email templates, bun run email to preview) go to the socio's PoliNetwork mailbox through the soci_mail outbox, drained every minute. Each email's id is its idempotency key, e.g. reminder:2026:dec-1:12, so a job that runs twice never sends twice.
Variable Purpose
SOCI_IBAN The IBAN soci pay the fee to. Until it and the beneficiary are set, no fee year is opened.
SOCI_BENEFICIARI The account holder shown with the IBAN, e.g. PoliNetwork APS.

E-signing with the CIE

The esign router and /esign/agent/* endpoints let dashboard users sign PDFs with the Italian identity card (CIE). The backend prepares a PAdES baseline B-B signature (incremental update with a visible stamp), the user's PoliNetwork Sign Agent signs the digest with the card, and the backend embeds the CMS, then saves the signed PDF to OneDrive and emails it. See the admin repository's docs/esign/contracts.md for the flow.

Variable Meaning
ESIGN_DRIVES JSON array of the OneDrive/SharePoint libraries the dashboard offers, see below. Without Azure credentials in-memory drives are used.
ESIGN_DASHBOARD_URL Dashboard origin for links in emails (default https://admin.polinetwork.org).
ESIGN_ALLOW_TEST_CERTIFICATES true accepts certificates not issued by the CIE CAs (the agent's development key). Defaults to true outside production.

ESIGN_DRIVES lists one entry per library; id is a stable key stored with each request (lowercase letters, digits and dashes, keep it when changing the rest), label is shown in the dashboard, driveId is the Graph drive ID and rootId the item ID of the folder the dashboard may browse and write (default root, the whole drive):

ESIGN_DRIVES='[{"id":"segreteria","label":"Segreteria","driveId":"b!…"},{"id":"tesoreria","label":"Tesoreria","driveId":"b!…","rootId":"01…"}]'

Requirements:

  • IdP permissions esign:sign (sign and see one's requests) and esign:requests:manage (create and manage requests). esign:drives:manage sets which roles and permissions may use each drive (dashboard: Signatures › Drives).
  • Graph application permission Files.ReadWrite.All (or Sites.Selected with write access to the site), with admin consent, for the drive; emails use the existing Mail.Send sender.
  • The dashboard proxies /api/esign/agent/* to this backend's /esign/agent/*; the agent never calls the backend directly. Those endpoints are authenticated only by the job's single-use ticket.
  • The proxy passes on the agent's User-Agent: PoliNetwork-eSign/<version> (PoliNetwork-Sign-Agent/<version> for 0.1.x, released before the rename). An agent older than MIN_AGENT_VERSION (src/esign/agent-version.ts) gets 426 agent_outdated when it loads a job, before the PIN, and the job fails so the dashboard can say why. No User-Agent, a development or source build (dev, v0.1.1-6-g0cb0f7b) or an unreadable version passes; preparing a signature still refuses an agent without protocol 2.

Emails (src/emails/templates, preview with bun run email):

  • "Signature needed" tells signers their turn started.
  • "Documento firmato" sends the signed PDF to the addresses the request names, in Italian since they are often outside PoliNetwork. The PDF is attached up to 2 MB, otherwise linked from OneDrive; replies go to whoever sent the request.
  • "Request update" tells a request's creator that a signer declined, with the reason, or that everyone signed, unless the creator saw it by signing last or retrying the delivery. When saving or emailing the signed PDF fails, it tells the creator and every manager who may retry (esign:sign and esign:requests:manage, allowed on the request's drives), the last signer included: the delivery runs once they have signed. Nobody is emailed about what they just did, each outcome is emailed once, and an email that fails is only logged.

Signatures are checked against the CIE certification authorities of the Ministero dell'Interno bundled in src/esign/trust. Tests: bunx vitest run tests/esign-*.test.ts (validated with poppler pdfsig when installed).

Freshman content

web.freshman exposes fixed-slot content for the website and authorized admin editors. Migration 0026_freshman_content initializes 10 resources, 8 Telegram links and 5 existing/new FAQs, preserving matching catalog entries. Selected FAQs/categories must be replaced in Freshman before deleting them from the catalog. Each Telegram slot links a group from tg_groups (updateTelegramCard): the website gets the group's current invite link, and the group's title unless the editor set a display name. A slot whose group is deleted has no link until an editor picks another. Migration 0046_freshman_telegram_groups linked the slots whose link matched a group's invite link or public tag; the others keep their old link until an editor picks a group. The development seed also initializes the card slots and selections; --force clears those selections before replacing the sample FAQ catalog.

About

THE backend (future)

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages