Files
0pt/src/document-workbench/stripe-credit-verification.ts
T
admin b3239487b7
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (push) Successful in 10s
CI (SIAX Cloud) / sonar (pull_request) Skipped
Security Scan (SIAX Cloud) / security (push) Successful in 13s
masterplan-lock / check (pull_request) Successful in 7s
CI (SIAX Cloud) / security (push) Successful in 26s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 17s
CI (SIAX Cloud) / security (pull_request) Successful in 19s
CI (SIAX Cloud) / quality (push) Successful in 1m9s
CI (SIAX Cloud) / quality (pull_request) Successful in 2m26s
CI (SIAX Cloud) / integration (pull_request) Successful in 2m33s
feat(document-workbench): wire customer upload, structuring, credits and readiness
- POST /api/0pt/documents/upload: real multipart bytes into DOC0 through the
  durable attempt journal and the existing coordinator; verified tenant/actor
  only, project authorization fail-closed.
- POST /api/0pt/documents/structure: DOC0 segments -> INF0 -> evidence-bound
  validation -> optional JSON/CSV export, with credit reserve/settle.
- Credits: balance, server-owned price book, Stripe Checkout and idempotent
  webhook reconciliation via a Stripe re-read of session + payment intent.
- /portal/dokument and /portal/krediter: SIAX-styled workspace.
- @siax/access: universal, framework-neutral OpenFGA project relationship
  primitive reusable by DOC0/N0D/other products.
- Readiness: real Redis PING probe instead of presence-only; queue is now a
  live dependency when configured.
- Dockerfile: copy every workspace manifest so --frozen-lockfile works.
- Format/build hygiene: .prettierignore, .worktrees ignored, valid manifest YAML.
2026-11-02 14:46:10 +01:00

98 lines
3.2 KiB
TypeScript

import type Stripe from 'stripe';
import type { CreditCommand } from './credit-ledger';
import type { CreditPurchaseSnapshot } from './pay0-credit-verification';
/**
* Stripe-backed credit verification.
*
* The webhook is only a trigger: this class re-reads the checkout session and
* its payment intent from Stripe and derives the grant from that authoritative
* response. Nothing in the webhook body is trusted for price, credits or
* tenant. The resulting command is idempotent per (tenant, purchase).
*
* This does not implement refunds, chargebacks or partial captures beyond
* refusing to grant when Stripe reports anything other than a fully paid,
* unrefunded session.
*/
export interface StripeCheckoutReader {
checkout: {
sessions: {
retrieve(id: string, options: { expand: string[] }): Promise<Stripe.Checkout.Session>;
};
};
}
export class StripeCreditVerificationError extends Error {
constructor(
message: string,
readonly reason: 'not_found' | 'mismatch' | 'not_paid' | 'refunded' | 'unsupported',
) {
super(message);
this.name = 'StripeCreditVerificationError';
}
}
export async function verifyStripeCreditPurchase(
stripe: StripeCheckoutReader,
snapshot: CreditPurchaseSnapshot,
context: { tenantId: string },
): Promise<CreditCommand> {
if (
context.tenantId !== snapshot.tenantId ||
!snapshot.checkoutSessionId.trim() ||
!Number.isSafeInteger(snapshot.credits) ||
snapshot.credits <= 0
) {
throw new StripeCreditVerificationError('Invalid or mismatched credit purchase', 'mismatch');
}
const session = await stripe.checkout.sessions.retrieve(snapshot.checkoutSessionId, {
expand: ['payment_intent'],
});
if (session.id !== snapshot.checkoutSessionId) {
throw new StripeCreditVerificationError('Session id mismatch', 'mismatch');
}
if (
session.metadata?.kind !== '0pt_credit_purchase' ||
session.metadata?.tenant_id !== snapshot.tenantId ||
session.metadata?.purchase_id !== snapshot.purchaseId
) {
throw new StripeCreditVerificationError('Session metadata does not belong to this purchase', 'mismatch');
}
if (
session.amount_total !== snapshot.amountMinor ||
session.currency?.toUpperCase() !== snapshot.currency
) {
throw new StripeCreditVerificationError(
'Session amount or currency does not match the server price snapshot',
'mismatch',
);
}
if (session.payment_status !== 'paid') {
throw new StripeCreditVerificationError('Session is not paid', 'not_paid');
}
const intent = session.payment_intent;
if (!intent || typeof intent === 'string') {
throw new StripeCreditVerificationError('Payment intent was not expanded', 'unsupported');
}
if (
intent.status !== 'succeeded' ||
intent.currency?.toUpperCase() !== snapshot.currency ||
(typeof intent.amount_received === 'number' && intent.amount_received < snapshot.amountMinor)
) {
throw new StripeCreditVerificationError(
'Payment intent is not a completed capture of the snapshot amount',
'not_paid',
);
}
return {
tenantId: snapshot.tenantId,
idempotencyKey: `credit_purchase:${snapshot.tenantId}:${snapshot.purchaseId}`,
kind: 'verified_payment',
reference: intent.id,
amount: snapshot.credits,
};
}