Note
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?).
Follow CONTRIBUTING.md to start local PostgreSQL and Redis, copy the matching env template, apply migrations, seed sample data and choose how to authenticate. See PostgreSQL integration tests to run the database-backed suites locally.
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 withX-PN-Actor: telegram:<id>, which only a service token withbackend:tg:act-asmay send. - Without a token: refused (
UNAUTHORIZED). There is no anonymous access, and handlers always receive the token's actor inctx.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, or when two of its users are merged (see "Account
merges" below); 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.
PoliNetwork Auth can merge two of its users into one: user from then no longer exists, its subject is an alias of
into, and its roles are held by into. Auth announces each merge with an account-merged Security Event Token on
POST /internal/events, before the access change it causes (auth-kit docs/contract.md §3.2). auth-kit verifies it,
and src/idp/account-merge.ts applies it in one transaction, once per jti: a retry waits for an attempt still running
and then finds it applied, and the same { from, into } applied twice changes nothing more. A merge into a user that
was merged since lands on the user it became.
- Live state keyed on the subject is repointed to
into:- People: a record linked to
fromfollows the account tointo. Ifintohas a record too, an automatic one (made by People for a role given in Auth, untouched since) is folded into the other; two records made by people stay apart:into's keeps the link,from's is unlinked, its roles back topending, and it is flaggedneeds_attentionfor HR to merge the two (linking.attention;linking.linkorlinking.dismissAttentionclears the flag). Role changes still queued forfromare sent anyway, since Auth applies them tointo; a queued unlink of a record the merge unlinked is cancelled (one Auth applied anyway, already on its way, is recorded as applied), and the record can be linked again once the others are answered. Auth's People directory may list merges too (merged: [{ from, into }]): People applies them before the roles, so a directory read that arrives before the event never takes the roles of a merged account. - Regolamenti: draft memberships (keeping the higher access where both were members) and deleghe (where both hold an active one for the same document, the longer-lasting one stays and the other is revoked by "PoliNetwork Auth").
- eSign: pending signatures and open signing jobs.
intogetsfrom's profile, with the CIE identity bound to it, when it has none, once: a later event forfromdoesn't bind an identity a manager reset since.
- People: a record linked to
- Columns recording who did something (
*_by,actor_sub,created_by_sub, …) keep the old subject.fromis kept incommon_merged_subjects(a chain of merges points at the last user): names shown for it resolve tointo, and rights that come from having done something (a draft's creator, a comment's author, an eSign request's requester) carry over tointo. - Each merge is kept in
common_account_mergeswith what it changed, and in the audit log aspeople.accountMerged.
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 withctx.audit.set(...).fieldskeeps 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 insoci_activity.people.persons.deleteis the exception: the record's history goes with it, so its event isfulland keeps a snapshot of what was deleted (see Deleting and merging records)..meta(audit.none(why)): not recorded, e.g. the bot's ingestion, or Telegram moderation, whichtg_audit_logkeeps under its own retention rules.
Handlers call ctx.audit.skip() when a call changed nothing, and ctx.audit.add({ action, target, error }) for one more
event next to the call's own, with only that action, target and outcome: a bulk call records each row this way. 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. Account merges announced by the IdP are recorded explicitly, as
people.accountMerged by the polinetwork-auth service.
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 fromGET /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 toPOST /api/internal/people-rolesthrough thepeople_role_commandsoutbox: each command has an ID Auth applies at most once, so the cron sends it again until Auth answers. The assignment showssentuntil Auth confirms it, and Auth's reason when it refuses. - A record that isn't linked yet: its assignments stay
pendingin 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 role its actor can no longer give at linking (they lost a permission since, or it would be their own) isn't
sent: it stays current as
needs_approval, with its start date and the reason, and so does one Auth refuses at linking.linking.approvals(people:read) lists them, andassignments.approvegives them acting as whoever approves, after the same rules. Before invites go out,assignments.checkPending(people:read) lists the pending roles whose assigner couldn't give them now, andassignments.adopttakes them over.approveandadopttake up to 500 assignments, withdryRun, and answer row by row.me.statustells any signed-in account its record and where each of its roles stands.
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. An expired invite is no longer open: the record's account block showsnone, andlinking.inviteslists it withstatus: "expired"so it can be sent again. - 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.
HR and agents (through the admin MCP) work on many records at once with the same checks as the single-row procedures:
| Procedure | Input | Same rules as |
|---|---|---|
persons.createMany |
{ people, allowDuplicates?, dryRun? } |
persons.create |
admins.assignMany |
{ personIds, since, capoId?, dryRun? } |
admins.assign |
teams.addMembers |
{ teamId, since, members: { personId, role, fields? }[], dryRun? } |
teams.addMember |
linking.sendInvites |
{ personIds, dryRun? } |
linking.sendInvite |
linking.revokeInvites |
{ personIds, dryRun? } |
linking.revokeInvite |
assignments.approve, assignments.adopt |
{ assignmentIds, dryRun? } |
see above |
- Each row passes or fails on its own. The answer has one row per input row, in order:
{ index, personId, status, reason?, message }.done;skippedfor an expected no-op (already an admin or in the team, already linked, an invite that still works, no open invite, a likely duplicate);failedwhen a check refused it, with the reason code and a message that says what to do. dryRun: trueruns every check and returns the same rows, then rolls the transaction back: nothing is saved and nothing is sent to Auth. The dashboard's confirmation dialog and agents use it to say what will happen.- One transaction per batch (one lock, one read of the register), of at most 500 rows, each person once. Role
changes on linked records are then sent to Auth one command per record, with the register read once before and
Auth's answers saved 25 at a time, and a row Auth refused fails with
auth_refused. - Role changes answer within about 20 seconds.
assignManyandaddMemberssend commands to Auth only while their delivery budget lasts, then answer{ batchId, rows }: the rows not sent yet say Auth hasn't answered, and the outbox sends them (the cron sweep sends queued commands for up to 30 seconds a minute).batches.get({ batchId })shows each of the batch's changes aswaiting,doneorfailed, to whoever made the call and to People readers.batchIdis null when nothing went to Auth (records not linked yet, or a dry run). createManyflags likely duplicates: a row with the contact email, or the first and last name (ignoring case, accents and spacing), of an existing record or of an earlier row is skipped aspossible_duplicate, unlessallowDuplicateslists its index.sendInvitesskips records whose invite still works (sendInvitesends one again), replaces expired ones, and says how many emails it queued and at most about how long the outbox will take to send them (estimatedSeconds). To a caller withoutpeople:read, an ID that doesn't exist answers like a record they may not invite to. The outbox sendsPEOPLE_MAIL_PER_MINUTEemails a minute (default 20, at most 30). Exchange Online accepts about 30 a minute per mailbox, and the Soci outbox sends up to 20 a minute from the same sender, so the two together can go over it when both are busy. The outbox claims one email at a time, and doesn't send an invite's email once the invite has been withdrawn, replaced, accepted or has expired. An open invite whose email failed is replaced too.- History: each row writes the record's activity as the single-row procedure does, and an audit event with that
procedure's action and the record as target (
deniedfor a row refused for a missing permission,failurefor another refusal). The call's own event names the counts (3 done, 1 skipped, 0 failed). Dry runs and calls that skipped every row record nothing.approveandadopt, which have no single-row procedure, record one event naming the records they changed.
Each invite shows where its email stands, in linking.invites and in the record's account block:
mail: { status: "pending" | "sending" | "sent" | "failed", error, attemptedAt }. An expired invite is listed with
status: "expired"; it can be sent again, or withdrawn to take it off the list.
- Transient failures are tried again. Graph's throttling (429), its server errors (5xx), no answer and a 30-second
timeout leave the email
pending, with the failure inerror, and the outbox tries it again after 1, 2, 4 and 8 minutes, or after Graph'sRetry-Afterup to 12 minutes: at most 5 attempts within an hour, thenfailed. Emails due for a retry go first, and a transient failure stops that minute's sending. The outbox turns off the Graph client's own retries and cancels a request it stops waiting for, so that an email it tries again isn't also sent by the request it gave up on. - Any other failure is permanent (an address Graph refuses, the sender's mailbox refused):
failed, with Graph's message, and the record's activity says so. Nobody received the link: correct the contact email if needed and send the invite again, which issues a new link. An email whose outcome is unknown (the backend stopped while sending it) isfailedtoo. sentmeans Graph accepted it. Graph accepts an email for an address that doesn't exist; the recipient's server rejects it later with a bounce to the sender's mailbox, which People doesn't read. An invite that wassentbut never opened may have bounced: check the contact email.- The link isn't kept.
people_invitesstores only the token's hash. The email's text inpeople_mailholds the link only until it is sent, fails for good or is cancelled; then the token is replaced with[redacted]. Migration0058_people_invite_mail_statusredacted the emails already in one of those states.
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.
-
persons.delete({ personId, dryRun? })(admin:access+people:delete, separate frompeople:write: it goes to the Direttivo and the HR Lead) deletes a record that never became real: never linked to an account (not now, not by an accepted invite, not in its history, not created for a role held in Auth), and none of its roles ever sent to Auth (allpending, or ended while pending). Its open invites are withdrawn, then it goes with its assignments, invites, emails, HR note and history; admins who had it as Capo Admin of reference have none. Anything else is refused withrecord_was_linkedorrole_was_sent, whose message says what to do instead: end the roles, or merge the record into the right one.persons.getsays beforehand whether it would be allowed, withdeletion: { allowed, reason, message }. The audit log keeps one event with a snapshot of the record: its ID, name, contact email, assignments and invites, with the HR note, the phone, the profile fields, Capo scopes and the history counted, not copied. -
persons.merge({ keepId, removeId, dryRun? })(admin:access+people:write, andpeople:linkwhen a link moves) foldsremoveIdintokeepId, two records of the same person, e.g. HR's record and the automatic one made for a role given by hand in Auth:- Assignments move. Where both hold a current one for a concept, one stays: the one Auth holds, or else
keepId's, with the earliersince, the other's team fields for the keys it lacks, and the other's Capo scope and Capo Admin of reference where it has none. The other is dropped. Ended ones move as history. - The HR note of
removeIdis appended tokeepId's under--- From P-xxxx (Name) ---. - Contact and profile fields (contact email, phone, course, campus, representative seats) fill only gaps in
keepId; other associations are added, all of them (past the 10 an update accepts, the next update has to trim them), and so is the HR note in full, even past the 2000 characterssetNoteaccepts. An attention flag onremoveIdmoves tokeepIdwhen it has none, unless it namedkeepId. - The link of
removeId, if any, moves tokeepId, whose open invites then close and whose attention flag clears. Refused withrecords_both_linkedwhen both are linked to different accounts: merge the accounts in Auth first. Once merged, a linked record's pending roles (its own when the link moved to it, or those that moved onto it) are sent to Auth acting as whoever merged, as after linking by hand: one they can't give waits for approval. Nobody merges into the record linked to their own account (self_link). - Invites, emails, role commands and history move to
keepId,removeId's open invites withdrawn first, and the history interleaves by date with an entry naming what the merge did.removeId's ID is never given again.
The answer lists every assignment of both records as it is afterwards (
kept,moved, ordroppedas it was), the fields filled, whether the note was appended, what happened to the link and how many invites closed: the dashboard's preview runs it withdryRun: true. The audit event nameskeepId, labelled with the record merged into it. - Assignments move. Where both hold a current one for a concept, one stays: the one Auth holds, or else
merge refuses while a role change for either record waits for Auth (auth_pending), and delete while an email to
the record is being sent (mail_sending). For an agent, both are destructive: each needs an explicit instruction per
record.
A person's Telegram is the account they linked to their PoliNetwork Auth account with Telegram's own sign-in. Records,
rows, My area's contacts and roster, and the Capo area carry telegram: { id, username } | null:
idcomes fromGET /api/internal/people-rolesfor the accounts it lists, and from the access snapshot for the others: accounts without a bound role, as long as the snapshot lists them, which it does only for accounts with a permission. An account with neither (e.g. one whose roles wait for approval) showsnull, and thenot_linkedfilter below lists it.usernamecomes fromtg_users, which the bot keeps current: a user it knows without a username has none. For a user the bot never saw it comes from Auth, which saw it when the account was linked, for the accountspeople-roleslists: the snapshot carries no username. Without a username,tg://user?id=<id>still opens the chat.tg_usersis read once People's transaction is over, so a read never holds People's lock while it waits for another database connection.nullfor a record not linked to an account, and for an account without Telegram linked.
persons.list and admins.list take an optional { telegram: "linked" | "not_linked" }, to find who still has to
link Telegram. People keeps no Telegram username of its own: the one HR used to type (telegramUsername) was removed,
with its column, by migration 0059_people_drop_telegram_username, without keeping its values. An older client that
still sends it in persons.create, persons.createMany or persons.update has it dropped, like any unknown key. A
backend from before the migration selects the column, so it fails People calls against a migrated database: replace it
rather than run it alongside, and before rolling back past 0059, run
ALTER TABLE people_persons ADD COLUMN telegram_username text.
A person can be both in People and a socio. The two registers share no key: People records are linked to an Auth
account (account_sub), Soci records to a PoliNetwork APS account (entra_object_id). They are joined at read time
through the account, and the join is never stored:
people_persons.account_sub → access snapshot bySub(sub).entraObjectId → soci_members.entra_object_id
persons.getaddsidentityfor a linked record (nullotherwise): Auth'snameandemail, frompeople-rolesor, for an account without a bound role, Auth's account search;nameVerifiedwhen Auth says whether the name is the association's or self-declared; thetelegramabove; andmicrosoft365Linked, true when the snapshot lists a PoliNetwork APS account for it. A viewer withsoci:readalso getssocio: the register entry (number,statusactiveorended,endReason,admittedOn,endedOn,currentFee), ornull. Withoutsoci:readthe field is absent, so its absence says nothing. When Auth's account search can't be read,nameandemailarenull; when the Libro Soci can't be read,sociois absent (andsocioNumberbelow, andme.get'sidentity.socioisnull). The rest is still served.persons.listandadmins.listadd each row'ssocioNumber(ornull) for viewers withsoci:read.me.getaddsidentity: { telegramLinked, microsoft365Linked, socio }about the signed-in account, also when it has no record (state: "none"), for My area's setup checklist.soci.members.getaddsperson: { id, name, roles }for viewers withpeople:read: the record linked to the account whose PoliNetwork APS account is the socio's, with its current roles, ornull.
The join finds a socio only when the account linked to the record is the one with PoliNetwork APS linked: a socio who
accepted their invite with Google shows as not a socio, with microsoft365Linked: false, until they link PoliNetwork APS
to that account or merge the two accounts in Auth. The snapshot lists only accounts holding a backend permission, so an
account without one (e.g. whose roles wait for approval) shows as not linked too.
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_numberskeeps 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 asemployeeId. - 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. - Admitting an existing account (
members.admitExisting) is for someone who already has a PoliNetwork account: it adds that account to Soci, gives it the chosen number if it has none, and writes the record with the first fee paid. Nothing is created and no email is sent. A record that can't be written takes the account out of Soci again.members.findAccountlooks up one account by its address and says whether it can be admitted (or is already in Soci, or already has a record): there is no listing of the tenant's accounts. - Registering (
members.register) writes a record for an account already in Soci, with its current number; personal fields are optional.members.unregisteredlists the Soci group's accounts without a record. members.listreports 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, findAccount, admitExisting, 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.*.
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.jsonThe 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) oritalian(DD/MM/YYYY). No guessing.scope:active-only,history(requires mapped end date/reason columns; blank ends mean active), orunknown.columns: requirednumber,firstName,lastName,admittedOn; optionalalias,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 requireignoredColumns.endReasonValues: optional exact translations, e.g.{ "dimissioni": "resigned" }; targets arelapsed,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.
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)
runDailyopens 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 untilSOCI_IBANandSOCI_BENEFICIARIare 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 asFormData(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
sendBirthdaysgreets 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 emailto preview) go to the socio's PoliNetwork mailbox through thesoci_mailoutbox, 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. |
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) andesign:requests:manage(create and manage requests).esign:drives:managesets which roles and permissions may use each drive (dashboard: Signatures › Drives). - Graph application permission
Files.ReadWrite.All(orSites.Selectedwith write access to the site), with admin consent, for the drive; emails use the existingMail.Sendsender. - 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 thanMIN_AGENT_VERSION(src/esign/agent-version.ts) gets 426agent_outdatedwhen 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:signandesign: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).
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.
Cards keep their Italian texts in title and description and the English ones in titleEn and descriptionEn (a
Telegram slot only has titleEn); an empty English text means the website shows the Italian one. Migration
0053_website_english_texts translated the cards still showing 0026's text. The acknowledgements' role groups and
people have titleEn and detailEn in the same way.
The development seed also initializes the card slots and selections; --force clears those selections before
replacing the sample FAQ catalog.