feat(document-workbench): wire customer upload, structuring, credits and readiness
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

- 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.
This commit is contained in:
2026-11-02 14:46:10 +01:00
parent ac1ac73be8
commit b3239487b7
37 changed files with 3152 additions and 59 deletions
+15
View File
@@ -24,6 +24,21 @@ export interface CreditBalance {
export class PostgresCreditLedger {
constructor(private readonly sql: RepositorySql) {}
/** Read-only balance for the authenticated tenant. Never creates a row. */
async balance(tenantId: string): Promise<CreditBalance> {
if (typeof tenantId !== "string" || !tenantId.trim() || tenantId.length > 256) {
throw new Error("Invalid credit tenant");
}
return withCreditTenant(this.sql, tenantId, async (tx) => {
const rows = await tx<{ available: string; reserved: string }[]>`
SELECT available, reserved FROM opt_credit_accounts WHERE tenant_id = ${tenantId}`;
const row = rows[0];
return row
? { available: Number(row.available), reserved: Number(row.reserved) }
: { available: 0, reserved: 0 };
});
}
async apply(command: CreditCommand): Promise<{ replay: boolean; balance: CreditBalance }> {
const { tenantId, idempotencyKey, kind, reference, amount } = command;
if (
@@ -0,0 +1,111 @@
import { createHash } from 'node:crypto';
import type { Doc0UploadReceipt } from './doc0-upload-client';
import type { TextSource } from './structured-output-validation';
export class Doc0SourceUnavailableError extends Error {
constructor() { super('DOC0 extracted source could not be verified; review or reconciliation is required'); this.name = 'Doc0SourceUnavailableError'; }
}
const MAX_RESPONSE_BYTES = 1024 * 1024;
const MAX_SEGMENTS = 100;
const MAX_SOURCE_BYTES = 192 * 1024;
async function boundedJson(response: Response): Promise<unknown> {
if (!response.ok || !response.body) throw new Error('source unavailable');
const reader = response.body.getReader();
try {
const chunks: Uint8Array[] = [];
let size = 0;
for (;;) {
const part = await reader.read();
if (part.done) break;
size += part.value.byteLength;
if (size > MAX_RESPONSE_BYTES) { void reader.cancel().catch(() => undefined); throw new Error('source too large'); }
chunks.push(part.value);
}
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))) as unknown;
} finally { reader.releaseLock(); }
}
/**
* Read a bounded DOC0 index for a verified upload receipt. The caller must
* independently authenticate and authorize the tenant/project/actor, and
* DOC0 must enforce the same project policy. The segment index is not proof
* of OCR accuracy, semantic correctness, or complete source extraction.
*/
export class Doc0SourceClient {
private readonly baseUrl: string;
private readonly token: string;
private readonly fetchImpl: typeof fetch;
private readonly timeoutMs: number;
constructor(options: { baseUrl: string; serviceToken: string; fetchImpl?: typeof fetch; timeoutMs?: number }) {
let url: URL;
try { url = new URL(options.baseUrl); } catch { throw new Error('Invalid DOC0 source configuration'); }
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !options.serviceToken.trim()
|| (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1000 || options.timeoutMs > 300000))) {
throw new Error('Invalid DOC0 source configuration');
}
this.baseUrl = url.toString().replace(/\/+$/, '');
this.token = options.serviceToken;
this.fetchImpl = options.fetchImpl ?? fetch;
this.timeoutMs = options.timeoutMs ?? 120000;
}
async read(input: {
tenantId: string; projectId: string; actorId: string; requestId: string; receipt: Doc0UploadReceipt;
}): Promise<{ sources: TextSource[]; reportedTextSha256: string }> {
const snapshot = structuredClone(input);
const { tenantId, projectId, actorId, requestId, receipt } = snapshot;
if (![tenantId, projectId, actorId, requestId, receipt?.documentId, receipt?.versionId]
.every((value) => typeof value === 'string' && /^[\x21-\x7e]{1,256}$/.test(value))
|| !/^[0-9a-f]{64}$/.test(receipt?.checksumSha256 ?? '') || receipt?.pipelineStage !== 'parsed') {
throw new Doc0SourceUnavailableError();
}
let value: unknown;
try {
const response = await this.fetchImpl(`${this.baseUrl}/v1/doc0/documents/${encodeURIComponent(receipt.documentId)}/versions/${encodeURIComponent(receipt.versionId)}/segments?limit=${MAX_SEGMENTS}&offset=0`, {
method: 'GET', redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(this.timeoutMs),
headers: { authorization: `Bearer ${this.token}`, 'x-tenant-id': tenantId, 'x-actor-id': actorId, 'x-request-id': requestId },
});
value = await boundedJson(response);
} catch { throw new Doc0SourceUnavailableError(); }
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Doc0SourceUnavailableError();
const page = value as { texts?: unknown; segments?: unknown; offset?: unknown };
if (page.offset !== 0 || !Array.isArray(page.texts) || page.texts.length !== 1 || !Array.isArray(page.segments)) {
throw new Doc0SourceUnavailableError();
}
const meta = page.texts[0] as Record<string, unknown> | null;
if (!meta || meta.tenantId !== tenantId || meta.documentId !== receipt.documentId || meta.versionId !== receipt.versionId
|| typeof meta.documentTextId !== 'string' || !meta.documentTextId || typeof meta.parserRunId !== 'string' || !meta.parserRunId
|| meta.segmentsTruncated !== false || !Number.isSafeInteger(meta.segmentCount) || (meta.segmentCount as number) < 1
|| (meta.segmentCount as number) > MAX_SEGMENTS || meta.segmentCount !== page.segments.length
|| !Number.isSafeInteger(meta.charCount) || (meta.charCount as number) < 1
|| typeof meta.textSha256 !== 'string' || !/^[0-9a-f]{64}$/.test(meta.textSha256)) {
throw new Doc0SourceUnavailableError();
}
const ids = new Set<string>();
const sources: TextSource[] = [];
let priorEnd = 0;
for (const [index, value] of page.segments.entries()) {
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Doc0SourceUnavailableError();
const segment = value as Record<string, unknown>;
if (segment.tenantId !== tenantId || segment.documentId !== receipt.documentId || segment.versionId !== receipt.versionId
|| segment.documentTextId !== meta.documentTextId || segment.parserRunId !== meta.parserRunId
|| segment.sourceVersionSha256 !== receipt.checksumSha256 || segment.sequence !== index
|| typeof segment.segmentId !== 'string' || !segment.segmentId || ids.has(segment.segmentId)
|| typeof segment.text !== 'string' || !segment.text || !Number.isSafeInteger(segment.charStart)
|| !Number.isSafeInteger(segment.charEnd) || (segment.charStart as number) < priorEnd
|| (segment.charEnd as number) - (segment.charStart as number) !== segment.text.length
|| (segment.charEnd as number) > (meta.charCount as number)
|| segment.segmentSha256 !== createHash('sha256').update(segment.text, 'utf8').digest('hex')) {
throw new Doc0SourceUnavailableError();
}
ids.add(segment.segmentId);
priorEnd = segment.charEnd as number;
sources.push({ id: segment.segmentId, text: segment.text });
}
if (Buffer.byteLength(JSON.stringify(sources), 'utf8') > MAX_SOURCE_BYTES) throw new Doc0SourceUnavailableError();
return { sources, reportedTextSha256: meta.textSha256 };
}
}
+148
View File
@@ -0,0 +1,148 @@
/**
* Server-owned, versioned credit price book.
*
* Prices are a business decision, not a code default: this module never
* invents a price. It parses an explicit `OPT_CREDIT_PRICE_BOOK` JSON document
* and fails closed when it is missing or invalid, so the checkout route can
* answer "price book not configured" instead of charging an arbitrary amount.
*
* Expected shape (all money in minor units, all quantities safe integers):
*
* {
* "version": "2026-11-01",
* "currency": "SEK",
* "packs": [{ "id": "starter", "credits": 100, "amountMinor": 9900 }],
* "metering": {
* "pagesPerCredit": 5,
* "inputTokensPerCredit": 20000,
* "outputTokensPerCredit": 4000
* }
* }
*/
export interface CreditPack {
id: string;
credits: number;
amountMinor: number;
}
export interface CreditMetering {
pagesPerCredit: number;
inputTokensPerCredit: number;
outputTokensPerCredit: number;
}
export interface CreditPriceBook {
version: string;
currency: string;
packs: readonly CreditPack[];
metering: CreditMetering;
}
const MAX_SAFE = Number.MAX_SAFE_INTEGER;
function safePositive(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 && value <= MAX_SAFE;
}
function safePositiveOrZero(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= MAX_SAFE;
}
function parsePack(raw: unknown, currency: string): CreditPack {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new Error('Each credit pack must be an object');
}
const pack = raw as Record<string, unknown>;
if (
typeof pack.id !== 'string' ||
!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(pack.id) ||
!safePositive(pack.credits) ||
!safePositive(pack.amountMinor) ||
(pack.currency !== undefined && pack.currency !== currency)
) {
throw new Error('Invalid credit pack');
}
return { id: pack.id, credits: pack.credits, amountMinor: pack.amountMinor };
}
export function parseCreditPriceBook(raw: unknown): CreditPriceBook {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new Error('Price book must be an object');
}
const doc = raw as Record<string, unknown>;
const version = doc.version;
const currency = doc.currency;
if (
typeof version !== 'string' ||
!/^\d{4}-\d{2}-\d{2}(?:\.\d+)?$/.test(version) ||
typeof currency !== 'string' ||
!/^[A-Z]{3}$/.test(currency) ||
!Array.isArray(doc.packs) ||
doc.packs.length === 0 ||
doc.packs.length > 100
) {
throw new Error('Invalid price book header or packs');
}
const packs = doc.packs.map((pack) => parsePack(pack, currency));
const ids = new Set(packs.map((pack) => pack.id));
if (ids.size !== packs.length) throw new Error('Duplicate credit pack id');
if (!doc.metering || typeof doc.metering !== 'object' || Array.isArray(doc.metering)) {
throw new Error('Price book metering is required');
}
const metering = doc.metering as Record<string, unknown>;
if (
!safePositive(metering.pagesPerCredit) ||
!safePositive(metering.inputTokensPerCredit) ||
!safePositive(metering.outputTokensPerCredit)
) {
throw new Error('Invalid metering rates');
}
return {
version,
currency,
packs,
metering: {
pagesPerCredit: metering.pagesPerCredit,
inputTokensPerCredit: metering.inputTokensPerCredit,
outputTokensPerCredit: metering.outputTokensPerCredit,
},
};
}
/** Returns `undefined` (fail closed) when the price book is absent or invalid. */
export function readCreditPriceBook(env: NodeJS.ProcessEnv = process.env): CreditPriceBook | undefined {
const raw = env.OPT_CREDIT_PRICE_BOOK;
if (!raw || !raw.trim()) return undefined;
try {
return parseCreditPriceBook(JSON.parse(raw));
} catch {
return undefined;
}
}
export function findPack(book: CreditPriceBook, packId: string): CreditPack | undefined {
return book.packs.find((pack) => pack.id === packId);
}
/** Round each metered unit up to its billing block, exactly like credit-quote. */
export function creditsForUsage(
book: CreditPriceBook,
units: { pages: number; inputTokens: number; outputTokens: number },
): number {
if (
!safePositiveOrZero(units.pages) ||
!safePositiveOrZero(units.inputTokens) ||
!safePositiveOrZero(units.outputTokens)
) {
throw new Error('Usage units must be nonnegative safe integers');
}
const blocks =
Math.ceil(units.pages / book.metering.pagesPerCredit) +
Math.ceil(units.inputTokens / book.metering.inputTokensPerCredit) +
Math.ceil(units.outputTokens / book.metering.outputTokensPerCredit);
if (!Number.isSafeInteger(blocks) || blocks < 0) {
throw new Error('Credit estimate outside supported range');
}
return blocks;
}
+35
View File
@@ -0,0 +1,35 @@
/**
* 0pt project authorization for the document workbench.
*
* Reuses the universal `@siax/access` OpenFGA relationship primitive (the same
* one DOC0 proved) instead of a per-repo copy. FAIL CLOSED: when OpenFGA is not
* configured, or the relationship source is unavailable, the answer is "no".
*/
import { OpenFgaRelationships, isProjectAccessAllowed } from '@siax/access';
import { readDocumentWorkbenchRuntime } from './runtime-config';
export interface ProjectScope {
tenantId: string;
projectId: string;
actorId: string;
}
export type ProjectAuthorizer = (scope: ProjectScope) => Promise<boolean>;
export function createProjectAuthorizer(env: NodeJS.ProcessEnv = process.env): ProjectAuthorizer {
const runtime = readDocumentWorkbenchRuntime(env);
let relationships: OpenFgaRelationships | undefined;
if (runtime.openfga) {
try {
relationships = new OpenFgaRelationships(runtime.openfga);
} catch {
relationships = undefined;
}
}
return async (scope) => isProjectAccessAllowed(scope, { relationships });
}
/** True when the server has enough configuration to authorize at all. */
export function projectAuthorizationConfigured(env: NodeJS.ProcessEnv = process.env): boolean {
return Boolean(readDocumentWorkbenchRuntime(env).openfga);
}
+105
View File
@@ -0,0 +1,105 @@
/**
* Server-side runtime configuration for the document workbench.
*
* Every integration is optional to BOOT and mandatory to USE: a route that
* needs DOC0/INF0/PAY0 returns a typed "not configured" error instead of
* fabricating success. URLs must be trusted HTTPS endpoints; tokens are never
* logged or returned.
*
* This module is deliberately framework-neutral and free of product imports so
* it can be lifted into a shared package without change.
*/
export interface HttpsEndpoint {
baseUrl: string;
serviceToken: string;
}
export interface DocumentWorkbenchRuntime {
doc0?: HttpsEndpoint & { maxUploadBytes: number };
inf0?: HttpsEndpoint;
pay0?: HttpsEndpoint;
n0d?: HttpsEndpoint;
st0re?: HttpsEndpoint;
openfga?: {
baseUrl: string;
storeId: string;
modelId: string;
serviceToken: string;
};
}
const DEFAULT_MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
function first(...values: Array<string | undefined>): string | undefined {
for (const value of values) {
if (typeof value === 'string' && value.trim()) return value.trim();
}
return undefined;
}
/** Only absolute HTTPS endpoints with no credentials/query/hash are trusted. */
export function isTrustedHttpsUrl(value: string | undefined): value is string {
if (!value) return false;
try {
const url = new URL(value);
return url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash;
} catch {
return false;
}
}
function endpoint(
env: NodeJS.ProcessEnv,
urlNames: readonly string[],
tokenNames: readonly string[],
): HttpsEndpoint | undefined {
const baseUrl = first(...urlNames.map((name) => env[name]));
const serviceToken = first(...tokenNames.map((name) => env[name]));
if (!isTrustedHttpsUrl(baseUrl) || !serviceToken) return undefined;
return { baseUrl: baseUrl.replace(/\/+$/, ''), serviceToken };
}
function positiveInt(value: string | undefined, fallback: number): number {
if (!value) return fallback;
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
}
export function readDocumentWorkbenchRuntime(env: NodeJS.ProcessEnv = process.env): DocumentWorkbenchRuntime {
const doc0 = endpoint(env, ['DOC0_URL', 'DOC0_API_URL'], ['DOC0_SERVICE_TOKEN', 'DOC0_SVC_PAT']);
const inf0 = endpoint(env, ['INF0_URL', 'INF0_API_URL'], ['INF0_API_TOKEN', 'INF0_SERVICE_TOKEN']);
const pay0 = endpoint(env, ['PAY0_URL', 'PAY0_API_URL'], ['PAY0_API_TOKEN', 'PAY0_SERVICE_TOKEN']);
const n0d = endpoint(env, ['N0D_URL', 'N0D_API_URL'], ['N0D_API_TOKEN', 'N0D_SERVICE_TOKEN']);
const st0re = endpoint(env, ['ST0RE_URL', 'ST0RE_API_URL'], ['ST0RE_API_TOKEN', 'ST0RE_SERVICE_TOKEN']);
const openfgaBase = first(env.OPENFGA_API_URL);
const openfgaStore = first(env.OPENFGA_STORE_ID);
const openfgaModel = first(env.OPENFGA_MODEL_ID);
const openfgaToken = first(env.OPENFGA_AUTH_TOKEN, env.OPENFGA_AUTH_KEY);
return {
...(doc0
? {
doc0: {
...doc0,
maxUploadBytes: positiveInt(env.OPT_MAX_UPLOAD_BYTES, DEFAULT_MAX_UPLOAD_BYTES),
},
}
: {}),
...(inf0 ? { inf0 } : {}),
...(pay0 ? { pay0 } : {}),
...(n0d ? { n0d } : {}),
...(st0re ? { st0re } : {}),
...(isTrustedHttpsUrl(openfgaBase) && openfgaStore && openfgaModel && openfgaToken
? {
openfga: {
baseUrl: openfgaBase.replace(/\/+$/, ''),
storeId: openfgaStore,
modelId: openfgaModel,
serviceToken: openfgaToken,
},
}
: {}),
};
}
@@ -0,0 +1,97 @@
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,
};
}