THE backend (future)
[!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?).
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):
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.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, 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.
into:
from follows the account to into. If into has 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 to pending, and it is flagged
needs_attention for HR to merge the two (linking.attention; linking.link or linking.dismissAttention
clears the flag). Role changes still queued for from are sent anyway, since Auth applies them to into; 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.into gets from's profile, with the CIE identity bound to
it, when it has none, once: a later event for from doesn't bind an identity a manager reset since.*_by, actor_sub, created_by_sub, …) keep the old subject. from is
kept in common_merged_subjects (a chain of merges points at the last user): names shown for it resolve to into,
and rights that come from having done something (a draft's creator, a comment's author, an eSign request's
requester) carry over to into.common_account_merges with what it changed, and in the audit log as people.accountMerged.common_audit_events
[Associazioni] Give the Auth role on approval; Direttivo approves every representative
https://github.com/PoliNetworkOrg/backend/issues/184
Labels: enhancement
[People · Onboarding] A person's account identity, and People ↔ Soci joined at read time
https://github.com/PoliNetworkOrg/backend/issues/173
Labels: people
[People · Onboarding] Telegram from the account linked in Auth, not a typed username
https://github.com/PoliNetworkOrg/backend/issues/172
Labels: people
[People · Onboarding] Delete never-linked records and merge duplicates
https://github.com/PoliNetworkOrg/backend/issues/171
Labels: people
[Groups] Return short join URLs instead of raw invite links to public callers
https://github.com/PoliNetworkOrg/backend/issues/149
Labels: enhancement, group join links
This guide gets a development environment ready for the backend. The README explains how the backend works: authentication, People, the audit log and the e-signing service.
The dashboard's tRPC calls need a bearer token. For local API work, connect to Auth or use the local stand-in. Tests use their own authentication fixtures.
package.json.git clone git@github.com:PoliNetworkOrg/backend.git
cd backend
bun install
cp .env.example .env
docker compose up -d --wait
compose.yaml starts PostgreSQL on localhost:55433 and Redis on localhost:56379, reachable only from your machine.
Run openssl rand -hex 32 and put the result in ENCRYPTION_KEY in .env. Bun loads this file automatically. The
template already matches the Compose services. See src/env.ts for supported settings.
Then apply the migrations and start the server:
bun db:migrate
bun dev
The backend listens on http://localhost:3000. Without the Auth settings below it logs
Token authentication is not configured: every request is rejected and rejects protected API calls.
Optionally, fill the database with sample data (Telegram users, groups and messages, course groups and labels, website content, reports, audit log entries and grants) in a disposable local database:
bun run seed:db
The default seed fills empty tables and uses retained Telegram users and groups as references. Use bun run seed:db --force
only on a disposable database. It can truncate populated Telegram tables with CASCADE and clear data in other tables.
Microsoft 365 is optional: without AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET the Azure routes use a
seeded in-memory directory, reset at every restart, and the e-signing service uses in-memory drives.
Follow steps 1–3 of Connect the local stack
to start Auth, generate the key and register the backend. Then enable the corresponding settings in the backend's .env:
IDP_PUBLIC_URL=http://localhost:3003
# The same identifiers as in Auth's .env.local.
OAUTH_BACKEND_RESOURCE_URI=https://backend.internal.polinetwork.org
OAUTH_INTERNAL_RESOURCE_URI=https://localhost:3003/api/internal
# The backend application registered in Auth, and the private key generated for it.
OAUTH_BACKEND_CLIENT_ID=
OAUTH_BACKEND_PRIVATE_JWK=
Start bun dev, or restart it if already running. A watch restart does not reload .env. The backend verifies tokens
from local Auth and pulls its access snapshot every 30 seconds. When configured, Auth's OAUTH_BACKEND_EVENTS_URL
also triggers a refresh on access changes. Continue with step 4 of the Auth guide to register and start the dashboard.
When your work doesn't touch Auth itself, scripts/regulations/dev-idp.ts can take its place on
http://localhost:4300. It serves the keys and the access snapshot for a fixed set of accounts and gives out tokens for
them, so you register nothing:
Run bun scripts/regulations/dev-idp.ts env and copy its output into .env, replacing any existing IdP settings
for those keys. Keep the generated private key local.
Run bun scripts/regulations/dev-idp.ts serve in its own terminal, then start or restart bun dev.
In a backend terminal, mint a token and call the authenticated me.access procedure:
token=$(bun run regulations:token dev-admin)
curl -fsS -H "Authorization: Bearer $token" http://localhost:3000/api/trpc/me.access
unset token
Expect sub to be dev-admin, stale to be false, and permissions to contain admin:access, people:read
and tg:users:read. If the snapshot is still loading, retry after a few seconds. The token is valid for two hours.
Use the same token in Admin's token-backed agent mode.
The accounts are in scripts/regulations/dev-accounts.json, and docs/regulations-dev.md
lists their permissions. They were made for the regulations editor, so they hold few others: dev-admin has only
admin:access, people:read and tg:users:read. For other permissions, point DEV_IDP_ACCOUNTS at your own file in
the same format when you start the stand-in. It checks no client credentials and refuses to run with
NODE_ENV=production: never point a deployed backend at it.
| Command | What it does |
|---|---|
bun dev | Development server on http://localhost:3000, restarted on every change |
bun run test | Vitest. The default run skips tests that need PostgreSQL |
bun run typecheck | TypeScript checks |
bun run check | Formatting and lint (Biome); bun run check:fix applies the fixes |
bun db:generate | Generates a Drizzle migration after a change to src/db/schema |
bun db:migrate | Applies the migrations |
bun run seed:db | Sample data. Use --force only to reset a disposable database |
| `bun run e |