The projectSkills and evidence4 min read
Security
Guarantees that don’t depend on the code they protect: a database that limits what the storefront can do, server actions that all open with their guard, signed messages, an assistant that can’t make up a number.
What’s exposed is the public storefront, open to the whole Internet. The money, the accounting and customer data are in the ERP. Each limit below stays in place even if the code above it gets something wrong, and a test checks it.
A storefront breach cannot mark an order as paid
The ERP and the storefront run on the same database. If the storefront had the ERP’s rights, an injection, a logic error or a compromised dependency would be enough to mark an order as paid, tamper with an invoice or read the internal notes.
So the storefront connects with a Postgres role that only has the rights its code uses, table by table and column by column. Where it writes, triggers check the shape of what it writes. With this role, the only order the database accepts is a web order awaiting payment.
- tables, out of the 54 in the schema, the public storefront can write to
- 6
- apps/site/scripts/lib/database-grants.ts#SITE_TABLE_GRANTS
- tables the public storefront cannot even read
- 19
- apps/site/scripts/lib/database-grants.ts#SITE_TABLE_GRANTS
packages/db/prisma/migrations/20261024020000_avis_retard_fabricant_et_rupture/migration.sql · lines 6–53CREATE OR REPLACE FUNCTION "Order_site_guard_insert"() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF current_user = 'moriniere_site' AND (
NEW."channel" <> 'WEB'
OR NEW."paymentStatus" <> 'PENDING'
OR NEW."fulfillmentStatus" <> 'UNFULFILLED'
OR NEW."paidAt" IS NOT NULL
OR NEW."confirmedAt" IS NOT NULL
OR NEW."canceledAt" IS NOT NULL
OR NEW."createdById" IS NOT NULL
OR NEW."internalNote" IS NOT NULL
OR NEW."customerId" IS NOT NULL
OR NEW."depositCents" IS NOT NULL
OR NEW."stripeSessionId" IS NOT NULL
OR NEW."stripePaymentIntentId" IS NOT NULL
OR NEW."shippedAt" IS NOT NULL
OR NEW."deliveredAt" IS NOT NULL
OR NEW."workshopDueAt" IS NOT NULL
OR NEW."promisedWorkshopDueAt" IS NOT NULL
OR NEW."workshopDueNoticeSentAt" IS NOT NULL
OR NEW."supplierDelayNoticeSentAt" IS NOT NULL
OR NEW."backorderNoticeSentAt" IS NOT NULL
OR NEW."deliveryAppointmentStartsAt" IS NOT NULL
OR NEW."deliveryAppointmentEndsAt" IS NOT NULL
OR NEW."deliveryAppointmentNoticeSentAt" IS NOT NULL
OR NEW."deliveryNoticeSentAt" IS NOT NULL
OR NEW."deliveryEvidence" IS NOT NULL
OR NEW."deliveryReserves" IS NOT NULL
OR NEW."deliveryReservesNotedAt" IS NOT NULL
OR NEW."carrierClaimedAt" IS NOT NULL
OR NEW."confirmationSentAt" IS NOT NULL
OR NEW."shipmentNoticeSentAt" IS NOT NULL
OR NEW."pickupNoticeSentAt" IS NOT NULL
OR NEW."withdrawalRequestedAt" IS NOT NULL
OR NEW."withdrawalAcknowledgedAt" IS NOT NULL
OR NEW."withdrawalClosedAt" IS NOT NULL
OR NEW."withdrawalClosure" IS NOT NULL
OR NEW."returnClosedAt" IS NOT NULL
OR NEW."billingCorrectedAt" IS NOT NULL
OR NEW."anonymizedAt" IS NOT NULL
OR NEW."anonymizationReason" IS NOT NULL
) THEN
RAISE EXCEPTION 'Order_site_guard_insert : le site ne crée qu''une commande web en attente de paiement';
END IF;
RETURN NEW;
END;
$$;Further reading: The storefront only has the rights it needs, PostgreSQL privileges, ADR 0003, ADR 0004.
Every storefront privilege matches a query in its code, and there are no others
A list of rights you update by hand ends up drifting, in both directions. A forgotten right breaks production. An extra one reopens what you wanted closed.
So a test collects every Prisma query, every nested create and every SQL query in the storefront, then compares them with the list of rights. It fails if it finds a query with no right. It also fails if it finds a write right that no query justifies.
apps/site/test/database-grants.regression.test.ts · lines 352–377it("chaque droit d'écriture est justifié par une écriture du code, une création imbriquée ou une ligne filtrée", () => {
const written = new Set([
...CODE_NEEDS.filter((need) => need.privilege !== "SELECT").map(
(need) => `${need.table}:${need.privilege}`,
),
...NESTED_CREATES.flatMap(({ field }) =>
(RELATION_TARGETS.get(field) ?? []).map((table) => `${table}:INSERT`),
),
...SITE_AUTH_ADAPTER_WRITES.flatMap((write) =>
write.privileges.map((privilege) => `${write.table}:${privilege}`),
),
]);
const unjustified = SITE_TABLE_GRANTS.flatMap((grant: SiteTableGrant) => [
...grantedPrivileges(grant)
.filter((privilege) => privilege !== "SELECT")
.filter((privilege) => !written.has(`${grant.table}:${privilege}`))
.map((privilege) => `${grant.table} ${privilege}`),
...((grant.lockColumns ?? []).length > 0 && !written.has(`${grant.table}:LOCK`)
? [`${grant.table} verrou`]
: []),
]);
expect(unjustified, "droit d'écriture sans écriture dans le code du site : le retirer").toEqual(
[],
);
});The storefront refuses to start with the wrong role
All these limits fall if the storefront connects with the owner role, because of a configuration mistake.
So on a deployment, the storefront checks at startup that it’s connected with its own role, and that this role doesn’t bypass row-level security. If not, it refuses to start, so it never serves without protection.
apps/site/shared/server/database-role-check.ts · lines 26–51export async function assertSiteDatabaseRole(): Promise<void> {
if (env.VERCEL_ENV !== "production" && env.VERCEL_ENV !== "preview") return;
if (isProductionBuildPhase()) return;
const role = await readSessionRole();
if (role instanceof Error) {
logError({
source: "db",
message: "rôle de connexion du site invérifiable au démarrage",
cause: describeError(role).message,
});
return;
}
if (role !== null && role.user === SITE_DATABASE_ROLE && !role.bypassesRls) return;
const message =
`le site ne se connecte pas en ${SITE_DATABASE_ROLE} sans contournement de la RLS\u00A0: ` +
"droits par table, RLS des comptes et gardes des commandes ne s’appliquent plus";
logError({
source: "db",
message,
user: role?.user ?? null,
bypassesRls: role?.bypassesRls ?? null,
});
throw new Error(message);
}Every ERP server action opens with its guard
Every export from a "use server" file is an HTTP entry point. If you add an action without checking the session, anyone can call it.
So a test reads every action file in the ERP. It requires each export to begin with the guard, the one that refuses when there’s no session. The exceptions are named in a list, and that list may only contain files that exist. This scan is tested too: it has to go red on every mistake it’s supposed to catch.
apps/erp/test/admin-guard.regression.test.ts · lines 80–86it.each(actionFiles)(
"chaque export de %s s'ouvre sur la garde qui refuse, ou le fichier est PUBLIC",
(relativePath) => {
const source = readFileSync(resolve(repoRoot, relativePath), "utf8");
expect(actionFaults(relativePath, source, regimeOf(relativePath))).toEqual([]);
},
);Further reading: Accounts and sessions, ADR 0011.
Messages between the applications are signed, timestamped and compared in constant time
When a customer withdraws or deletes their account, the storefront tells the ERP. A forged, altered or replayed message would trigger an action that can’t be undone.
So the body of the message and its timestamp are signed with HMAC-SHA256. The ERP starts by refusing a timestamp outside the window, before it even reads the body. Then it verifies the signature. For the other channels, the shared secrets are compared by hash, in constant time.
apps/erp/shared/server/site-request.ts · lines 28–47export async function verifySiteEvent(request: Request): Promise<SignedSiteEvent> {
const key = env.SITE_EVENTS_SECRET;
if (key === undefined) return { verdict: "unconfigured" };
const timestamp = request.headers.get(SITE_EVENT_TIMESTAMP_HEADER) ?? "";
const signature = request.headers.get(SITE_EVENT_SIGNATURE_HEADER) ?? "";
if (!isSiteEventSignature(signature) || !isFreshSiteEventTimestamp(timestamp, wallClockMs())) {
return { verdict: "refused" };
}
let body: string;
try {
body = await request.text();
} catch {
return { verdict: "refused" };
}
return (await isAuthenticSiteEvent(key, timestamp, body, signature))
? { verdict: "accepted", body }
: { verdict: "refused" };
}Further reading: Webhooks and exchanges.
Changing the Stripe webhook secret cuts nothing off, and does not go unnoticed
A signing secret gets changed. During the switch, Stripe may still sign with the old one. If you refuse those deliveries, you lose payments. But if you accept them without saying anything, an unfinished rotation can stay that way forever.
So the signature is checked with the current secret, then with the previous one if it’s still declared. A delivery validated by the old secret goes through, but it raises an alert.
apps/erp/shared/server/stripe.ts · lines 38–67export async function verifyStripeEvent(
rawBody: string,
signatureHeader: string,
): Promise<Stripe.Event> {
const secret = env.STRIPE_WEBHOOK_SECRET;
if (!secret) {
throw new Error("Webhook Stripe non configuré\u00A0: STRIPE_WEBHOOK_SECRET absente.");
}
try {
return getStripe().webhooks.constructEvent(rawBody, signatureHeader, secret);
} catch (error) {
const previous = env.STRIPE_WEBHOOK_SECRET_PREVIOUS;
if (previous === undefined) throw error;
const event = getStripe().webhooks.constructEvent(rawBody, signatureHeader, previous);
logInfo({
source: "payments",
context: "webhook.signature",
message: "livraison validée par le secret précédent",
eventId: event.id,
eventType: event.type,
});
await sendAlert({
source: "payments",
context: "webhook.signature",
message: "signature validée par le secret PRÉCÉDENT — rotation inachevée",
eventType: event.type,
});
return event;
}
}Further reading: Stripe.
The assistant can’t pull a number out of thin air without the person seeing it
A language model can write an amount, a date or a quantity that looks right and is wrong. In an ERP, a wrong figure shown with confidence is worse than no answer at all.
That’s why, at the end of each turn, the code compares the numbers in the answer with everything Fisher received: the question, the manual excerpts, the open record and the results of its ERP reads. If a number doesn’t come from any source, it’s flagged to the person, right where it’s written.
apps/erp/shared/server/ai/stream.ts · lines 151–181/**
* Chaque chiffre d'une réponse vient de l'ERP : à la fin du tour, ceux que ni
* la question, ni les extraits, ni la fiche, ni une lecture ne portent sont signalés à la personne,
* sous la réponse. Un instantané par tour : le dernier remplace les précédents.
*/
export function figureCheck(runId: string, facts: string): ChatMiddleware {
const known: string[] = [facts];
let text = "";
return {
name: "fisher-figure-check",
onAfterToolCall: (_ctx, info) => {
if (info.ok) known.push(JSON.stringify(info.result));
},
onChunk: (_ctx, chunk) => {
if (chunk.type === "TEXT_MESSAGE_CONTENT") {
text += chunk.delta;
return;
}
if (chunk.type !== "RUN_FINISHED" || text.trim() === "") return;
const unsupported = inventedNumbers(text.replace(LIST_NUMBER, ""), known.join("\n"));
return [
activitySnapshot({
messageId: `chiffres-${runId}`,
activityType: FISHER_FIGURES_ACTIVITY,
content: { chiffres: unsupported },
}),
chunk,
];
},
};
}