feat(payments): bind orders to verified tenant and buyer
CI (SIAX Cloud) / integration (push) Has been skipped
masterplan-lock / check (push) Successful in 4s
CI (SIAX Cloud) / security (push) Successful in 14s
masterplan-lock / check (pull_request) Successful in 4s
CI (SIAX Cloud) / security (pull_request) Successful in 14s
Security Scan (SIAX Cloud) / security (push) Successful in 30s
CI (SIAX Cloud) / quality (push) Successful in 35s
CI (SIAX Cloud) / integration (pull_request) Successful in 25s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 54s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m31s

This commit is contained in:
2026-09-15 19:53:58 +02:00
parent f976f36530
commit a1557b2a7d
19 changed files with 326 additions and 76 deletions
+80 -16
View File
@@ -16,6 +16,9 @@ export interface OrderConfig {
export interface Order {
order_id: string;
/** NULL for legacy anonymous drafts; never inferred from request config. */
tenant_id?: string | null;
buyer_subject?: string | null;
flow: string;
status: string;
config: OrderConfig;
@@ -27,6 +30,16 @@ export interface Order {
created_at: string;
}
export interface OrderOwner {
tenantId: string;
subject: string;
}
/** Collision-free namespace within the existing global idempotency index. */
function ownedIdempotencyKey(owner: OrderOwner, key: string): string {
return `owned:${owner.tenantId.length}:${owner.tenantId}:${key}`;
}
// Non-durable fallback used only until a database is provisioned.
const mem = new Map<string, Order>();
// idempotency_key -> order_id, mirroring the Postgres unique index added by
@@ -53,15 +66,16 @@ function isUniqueViolation(err: unknown): boolean {
return typeof err === "object" && err !== null && (err as { code?: unknown }).code === "23505";
}
function sameSubmission(a: Order, flow: string, config: OrderConfig): boolean {
return a.flow === flow && JSON.stringify(a.config) === JSON.stringify(config);
function sameSubmission(a: Order, flow: string, config: OrderConfig, owner?: OrderOwner): boolean {
return a.flow === flow && JSON.stringify(a.config) === JSON.stringify(config)
&& (!owner || (a.tenant_id === owner.tenantId && a.buyer_subject === owner.subject));
}
export async function findOrderByIdempotencyKey(key: string): Promise<Order | null> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
FROM orders WHERE idempotency_key = ${key} LIMIT 1`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
@@ -118,12 +132,14 @@ export interface CreateOrderResult {
* unique-violation on INSERT is caught and re-resolved the same way a
* pre-existing row would be, rather than surfacing a raw DB error.
*/
export async function createOrder(flow: string, config: OrderConfig, idempotencyKey?: string): Promise<CreateOrderResult> {
const key = idempotencyKey?.trim() || undefined;
export async function createOrder(flow: string, config: OrderConfig, idempotencyKey?: string, owner?: OrderOwner): Promise<CreateOrderResult> {
if (owner && (!owner.tenantId.trim() || !owner.subject.trim())) throw new Error("Verified order owner is required");
const rawKey = idempotencyKey?.trim() || undefined;
const key = rawKey && owner ? ownedIdempotencyKey(owner, rawKey) : rawKey;
if (key) {
const existing = await findOrderByIdempotencyKey(key);
if (existing) {
if (sameSubmission(existing, flow, config)) return { order: existing, replayed: true };
if (sameSubmission(existing, flow, config, owner)) return { order: existing, replayed: true };
throw new IdempotencyKeyConflictError(key);
}
}
@@ -133,13 +149,15 @@ export async function createOrder(flow: string, config: OrderConfig, idempotency
if (sql) {
try {
const [row] = await sql<{ order_id: string; created_at: string }[]>`
INSERT INTO orders (flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, idempotency_key)
VALUES (${flow}, 'draft', ${sql.json(config as Parameters<typeof sql.json>[0])}, ${est.price * 100}, ${est.deposit * 100},
${est.remainder * 100}, ${est.timelineDays}, ${est.estConfidence / 100}, ${key ?? null})
INSERT INTO orders (tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, idempotency_key)
VALUES (${owner?.tenantId ?? null}, ${owner?.subject ?? null}, ${flow}, 'draft', ${sql.json(config as Parameters<typeof sql.json>[0])},
${est.price * 100}, ${est.deposit * 100}, ${est.remainder * 100},
${est.timelineDays}, ${est.estConfidence / 100}, ${key ?? null})
RETURNING order_id, created_at`;
return {
order: {
order_id: row.order_id, flow, status: "draft", config,
order_id: row.order_id, tenant_id: owner?.tenantId ?? null, buyer_subject: owner?.subject ?? null,
flow, status: "draft", config,
total_ore: est.price * 100, deposit_ore: est.deposit * 100, balance_ore: est.remainder * 100,
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: row.created_at,
},
@@ -149,7 +167,7 @@ export async function createOrder(flow: string, config: OrderConfig, idempotency
if (key && isUniqueViolation(err)) {
const raced = await findOrderByIdempotencyKey(key);
if (raced) {
if (sameSubmission(raced, flow, config)) return { order: raced, replayed: true };
if (sameSubmission(raced, flow, config, owner)) return { order: raced, replayed: true };
throw new IdempotencyKeyConflictError(key);
}
}
@@ -159,7 +177,8 @@ export async function createOrder(flow: string, config: OrderConfig, idempotency
const id = (globalThis.crypto?.randomUUID?.() ?? `SX-${Math.floor(1000 + Math.random() * 9000)}`);
const order: Order = {
order_id: id, flow, status: "draft", config,
order_id: id, tenant_id: owner?.tenantId ?? null, buyer_subject: owner?.subject ?? null,
flow, status: "draft", config,
total_ore: est.price * 100, deposit_ore: est.deposit * 100, balance_ore: est.remainder * 100,
est_days: est.timelineDays, est_confidence: est.estConfidence / 100, created_at: new Date().toISOString(),
};
@@ -172,18 +191,43 @@ export async function getOrder(id: string): Promise<Order | null> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
FROM orders WHERE order_id::text = ${id} LIMIT 1`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
return mem.get(id) ?? null;
}
/** Buyer read is scoped in SQL itself; legacy NULL-owned rows are invisible. */
export async function getOwnedOrder(id: string, tenantId: string): Promise<Order | null> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
FROM orders WHERE order_id::text = ${id} AND tenant_id = ${tenantId} LIMIT 1`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
const order = mem.get(id);
return order?.tenant_id === tenantId ? order : null;
}
export async function listOwnedOrders(tenantId: string): Promise<Order[]> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
FROM orders WHERE tenant_id = ${tenantId} ORDER BY created_at DESC LIMIT 100`;
return rows.map(coerceOrder);
}
return [...mem.values()].filter((o) => o.tenant_id === tenantId)
.sort((a, b) => b.created_at.localeCompare(a.created_at));
}
export async function listOrders(): Promise<Order[]> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
SELECT order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at
FROM orders ORDER BY created_at DESC LIMIT 100`;
return rows.map(coerceOrder);
}
@@ -195,7 +239,7 @@ export async function setStatus(id: string, status: string): Promise<Order | nul
if (sql) {
const rows = await sql<Order[]>`
UPDATE orders SET status = ${status}, updated_at = now() WHERE order_id::text = ${id}
RETURNING order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at`;
RETURNING order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
const o = mem.get(id);
@@ -210,7 +254,7 @@ export async function setStatusIfCurrent(id: string, current: string, next: stri
const rows = await sql<Order[]>`
UPDATE orders SET status = ${next}, updated_at = now()
WHERE order_id::text = ${id} AND status = ${current}
RETURNING order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at`;
RETURNING order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
const order = mem.get(id);
@@ -219,3 +263,23 @@ export async function setStatusIfCurrent(id: string, current: string, next: stri
mem.set(id, order);
return order;
}
/** Buyer status change is both atomic and tenant-scoped at the SQL boundary. */
export async function setOwnedStatusIfCurrent(
id: string, tenantId: string, current: string, next: string,
): Promise<Order | null> {
const sql = getSqlForDurableStore("0pt.orders");
if (sql) {
const rows = await sql<Order[]>`
UPDATE orders SET status = ${next}, updated_at = now()
WHERE order_id::text = ${id} AND tenant_id = ${tenantId} AND status = ${current}
RETURNING order_id, tenant_id, buyer_subject, flow, status, config, total_ore, deposit_ore,
balance_ore, est_days, est_confidence, created_at`;
return rows[0] ? coerceOrder(rows[0]) : null;
}
const order = mem.get(id);
if (!order || order.tenant_id !== tenantId || order.status !== current) return null;
order.status = next;
mem.set(id, order);
return order;
}