תפעול החברה
טיוטה: גבול הגישה לניהול
גישה מאומתת של צוות החברה, חיבור נתונים ופקודות Finance מצומצמות.
בעמוד הזה
The Admin reads existing company records. The Finance module adds narrowly scoped expense creation and void commands through the same verified staff boundary; its schema migration must be applied separately before those commands can work. This code does not create a Supabase project or branch, grant customer organization administrators access to company operations, provision staff accounts or add production credentials.
Configuration#
The Admin deployment uses its own explicit identity boundary, separate from the customer product's LNE_BACKEND_ENV contract:
APP_SURFACE=admin
LNE_ADMIN_ENV=production
LNE_ADMIN_ORIGIN=https://admin.linknodesenergy.com
LNE_ADMIN_CLERK_ISSUER=<exact Clerk production issuer>
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=<matching public key>
CLERK_SECRET_KEY=<matching server key in secret storage>
LNE_ADMIN_STAFF_JSON=[{"userId":"[operational-id-redacted]","displayName":"Company staff","role":"ceo"}]
The sample is not a grant to a real user. Provision only verified Clerk user IDs from the selected application. Supported roles are ceo, operations and accountant; the role list is deliberately not derived from user metadata, email domain or customer organization membership. An optional expiresAt field is a UTC ISO timestamp. Duplicate IDs, unknown fields/roles, malformed or empty registries close the boundary.
| Permission | CEO | Operations | Accountant |
|---|---|---|---|
| Aggregate dashboard | Yes | Yes | Yes |
| RevOps financial metrics | Yes | Yes | Yes |
| Customer directory | Yes | Yes | No |
| Subscriptions | Yes | Yes | Yes |
| User directory | Yes | Yes | No |
| Financial transactions | Yes | Yes | Yes |
Finance reports (finance.read) | Yes | Yes | Yes |
Create and void expenses (finance.write) | Yes | Yes | Yes |
| Mail and WhatsApp content | Yes | Yes | No |
| Connection status | Yes | Yes | No |
An accountant's dashboard must remain aggregate. Giving an accountant dashboard.read must never indirectly include user, customer-contact or communications records in its response. Finance/subscription rows may identify their tenant without including unrelated user or contact information.
Request verification#
Every live API request calls requireAdminPermission(permission). This checks the exact deployment surface, issuer, authorized Admin origin, signed user/session identity, absence of an impersonation actor and two genuinely verified factors. Both signed fva ages must remain within 15 minutes, including elapsed time since token issuance. Client flags, device biometrics, role strings and an IdP login label cannot substitute for signed factor evidence.
The backend then reads the current Clerk session and user. Revoked/pending sessions, mismatched IDs, banned/locked/deprovisioned users, impersonation, expired/abandoned sessions and sessions older than eight hours are denied. Provider verification failure denies data access instead of reusing a cached login. The current installed SDK exposes these fields; session and user records never enter a client response.
The exact returned staff object can be passed to adminDatabase(staff, permission) in the same request. A private server-side attestation rejects fabricated or serialized staff objects; the current grant, permission, origin and issuer are checked again. The object expires after 30 seconds and must not be cached across requests. Its displayed name and permissions are presentation data, not a reusable authorization token.
Finance API#
GET /api/admin/finance?month=YYYY-MM requires finance.read and returns the Finance report with its source and coverage status. It performs no mutation. The route validates the month and rejects unknown or repeated query fields before acquiring the database client. Responses, including failures, are private and no-store.
POST /api/admin/finance requires finance.write. The only commands are createExpense and voidExpense; each carries a UUID idempotencyKey. Creation includes the explicitly validated expense fields. Voiding requires the expense UUID and a reason. The actor is the verified staff user's ID, supplied by the server; body fields cannot select an actor or override a role. An unchanged retry retains the same key and receives the original mutation result with replay: true; reuse with changed command details is a conflict. A new intentional command uses a new UUID. The data layer audits these commands and does not expose an arbitrary write endpoint.
Before reading a POST body, the route verifies the current staff identity, MFA and write permission, then requires the request URL origin and the exact Origin header to equal the canonical origin from LNE_ADMIN_ORIGIN and the verified Admin configuration. Missing, null, multiple, cross-origin or noncanonical Origin values are denied. When Sec-Fetch-Site is present it must be exactly same-origin; its absence is permitted only with the required matching Origin. The route does not use a client-controlled forwarded host or a preview flag as authorization.
Only application/json with optional UTF-8 charset is accepted, with no compressed request body. The route enforces a 16 KiB limit on the bytes actually read from the stream as well as rejecting an oversized declared length. Malformed JSON, invalid UTF-8, unknown body fields and invalid expense data fail before database access. Provider and unexpected errors are replaced with a generic response; credentials and underlying database messages never enter API responses. The privileged client is acquired only after authentication and validation, using the exact attested staff object from that request.
Expense commands record internal finance entries. They do not charge a customer, issue a refund, change a subscription price, submit a tax return, contact a supplier or send messages. The Finance VAT view is an estimate with explicit document and deduction evidence; pending evidence must stay visible rather than becoming an inferred zero. The synthetic preview remains UI data only and cannot authorize either API method.
Existing database connection#
Live data additionally requires the existing Supabase variables:
SUPABASE_PROJECT_REF=<existing LinkNodes project>
NEXT_PUBLIC_SUPABASE_URL=https://<same project>.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=<matching public key>
SUPABASE_SERVICE_ROLE_KEY=<matching server key in secret storage>
Production staff identity is restricted to the registered LinkNodes production project references. Development Clerk identity cannot access any of the known production company projects. The Admin does not weaken the customer application's environment checks to obtain database access.
Legacy JWT key roles and project references are checked structurally. New opaque Supabase key formats cannot reveal their project association; an authenticated provider query must validate that binding. The secret is used only in a server-only, permission-gated data layer with explicit selected columns. Do not add arbitrary table/SQL endpoints or serialize database errors, payment tokens or provider credentials.
Development identity can use an isolated HTTPS origin. Local HTTP requires LNE_ADMIN_ALLOW_LOCAL_HTTP=true and a loopback origin outside Vercel. This does not permit Development to read a production database or turn a synthetic UI preview into a live API bypass.
Activation and limits#
Committing this source does not activate staff accounts, connect a mailbox, assign a WhatsApp number, send messages or deploy the Admin. Configure and verify the staff identity boundary before enabling live company reads. Staff registry changes are server configuration changes, not customer-facing role changes. Revoking a Clerk session or blocking the staff user is checked by subsequent requests.
Permissions remain fixed by the server-owned staff role. Finance writes are authorized only by finance.write, scoped to the audited expense commands above. Read grants do not authorize refunds, message delivery, impersonation or other privileged writes. A later release may add a persisted staff registry. Test coverage verifies nonstaff/customer-admin denial, environment mixing, missing/stale MFA, revoked sessions, finance-only access, forged privileged-client contexts, mutation origin enforcement, bounded request bodies and idempotent command forwarding.
References: Clerk session token claims, installed Clerk Backend SDK Session/User types, and the installed Next.js authentication guide.