@tokenoftrust/storefront-runner 7.14.1 → 7.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/storefront/src/lib/checkout/commerce/attributionCodes.ts +175 -0
- package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +27 -1
- package/apps/storefront/src/lib/checkout/commerce/commerceAdmission.ts +2 -2
- package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +10 -1
- package/package.json +1 -1
- package/packages/public-runtime/src/activity/catalog.ts +8 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The suspend-only promotional-code kill-switch (`POST /api/apps/v1/attribution/codes/{code}/suspend`,
|
|
3
|
+
* scope `attribution:manage-codes`). Pure D1, scoped to (tenant, stage):
|
|
4
|
+
*
|
|
5
|
+
* - A suspension is one `attribution_code_suspensions` row keyed by the lower-cased code. While it
|
|
6
|
+
* exists, the checkout handoff refuses to apply the code to a new cart in that stage. Carts that
|
|
7
|
+
* already hold the code are left as they are.
|
|
8
|
+
* - Every suspension that lands writes one append-only `attribution_code_suspension_audit` row with
|
|
9
|
+
* the install, stage, code and reason enum only, in the same batch.
|
|
10
|
+
* - Nothing here creates a code, changes its discount terms, or lifts a suspension. Suspending an
|
|
11
|
+
* already-suspended code is a no-op that reports the standing suspension.
|
|
12
|
+
* - The owner reads the stage's suspensions in `/admin` (`listAttributionCodeSuspensions`).
|
|
13
|
+
*/
|
|
14
|
+
import type { CommerceStage } from "@tot/public-runtime";
|
|
15
|
+
import type { Queryable } from "../../catalog/d1/catalog.js";
|
|
16
|
+
import { isPromoCouponCode } from "./cartSession.js";
|
|
17
|
+
|
|
18
|
+
export const SUSPENSION_REASONS = [
|
|
19
|
+
"fda_claim_violation",
|
|
20
|
+
"youth_targeting",
|
|
21
|
+
"missing_warning",
|
|
22
|
+
"fraud_suspected",
|
|
23
|
+
"partner_terminated",
|
|
24
|
+
] as const;
|
|
25
|
+
|
|
26
|
+
export type SuspensionReason = (typeof SUSPENSION_REASONS)[number];
|
|
27
|
+
|
|
28
|
+
export const SUSPENSION_NOTE_MAX = 500;
|
|
29
|
+
export const SUSPENSION_EVIDENCE_URL_MAX = 2048;
|
|
30
|
+
|
|
31
|
+
export interface SuspensionScope {
|
|
32
|
+
tenantId: string;
|
|
33
|
+
stage: CommerceStage;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface SuspendInput {
|
|
37
|
+
reason: SuspensionReason;
|
|
38
|
+
evidenceUrl?: string;
|
|
39
|
+
note?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CodeSuspension {
|
|
43
|
+
code: string;
|
|
44
|
+
reason: SuspensionReason;
|
|
45
|
+
suspendedAt: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface OwnerCodeSuspension extends CodeSuspension {
|
|
49
|
+
installId: string;
|
|
50
|
+
evidenceUrl?: string;
|
|
51
|
+
note?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface SuspensionRow {
|
|
55
|
+
code: string;
|
|
56
|
+
install_id: string;
|
|
57
|
+
reason: SuspensionReason;
|
|
58
|
+
evidence_url: string | null;
|
|
59
|
+
note: string | null;
|
|
60
|
+
claim_id: string;
|
|
61
|
+
suspended_at: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The lower-cased form a code is keyed by, or `null` when it is not a promotional code. */
|
|
65
|
+
export function normalizeAttributionCode(raw: string): string | null {
|
|
66
|
+
const code = raw.trim();
|
|
67
|
+
return isPromoCouponCode(code) ? code.toLowerCase() : null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function isReason(value: unknown): value is SuspensionReason {
|
|
71
|
+
return typeof value === "string" && (SUSPENSION_REASONS as readonly string[]).includes(value);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function isHttpsUrl(value: string): boolean {
|
|
75
|
+
if (value.length > SUSPENSION_EVIDENCE_URL_MAX || !URL.canParse(value)) return false;
|
|
76
|
+
return new URL(value).protocol === "https:";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The closed suspend body `{reason, evidenceUrl?, note?}`, or the 400 message refusing it. */
|
|
80
|
+
export function parseSuspendBody(body: unknown): SuspendInput | string {
|
|
81
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) return "body must be a JSON object";
|
|
82
|
+
const record = body as Record<string, unknown>;
|
|
83
|
+
for (const key of Object.keys(record)) {
|
|
84
|
+
if (key !== "reason" && key !== "evidenceUrl" && key !== "note") return `unknown field: ${key}`;
|
|
85
|
+
}
|
|
86
|
+
if (!isReason(record.reason)) return `reason must be one of ${SUSPENSION_REASONS.join(", ")}`;
|
|
87
|
+
const input: SuspendInput = { reason: record.reason };
|
|
88
|
+
if (record.evidenceUrl !== undefined) {
|
|
89
|
+
if (typeof record.evidenceUrl !== "string" || !isHttpsUrl(record.evidenceUrl)) {
|
|
90
|
+
return "evidenceUrl, when given, must be an https URL";
|
|
91
|
+
}
|
|
92
|
+
input.evidenceUrl = record.evidenceUrl;
|
|
93
|
+
}
|
|
94
|
+
if (record.note !== undefined) {
|
|
95
|
+
if (typeof record.note !== "string" || record.note.length === 0 || record.note.length > SUSPENSION_NOTE_MAX) {
|
|
96
|
+
return `note, when given, must be 1-${SUSPENSION_NOTE_MAX} characters`;
|
|
97
|
+
}
|
|
98
|
+
input.note = record.note;
|
|
99
|
+
}
|
|
100
|
+
return input;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function toSuspension(row: SuspensionRow): CodeSuspension {
|
|
104
|
+
return { code: row.code, reason: row.reason, suspendedAt: row.suspended_at };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function readSuspension(db: Queryable, scope: SuspensionScope, normalized: string): Promise<SuspensionRow | null> {
|
|
108
|
+
return db.first<SuspensionRow>(
|
|
109
|
+
`SELECT code, install_id, reason, evidence_url, note, claim_id, suspended_at FROM attribution_code_suspensions
|
|
110
|
+
WHERE tenant_id = ? AND stage = ? AND normalized_code = ?`,
|
|
111
|
+
scope.tenantId, scope.stage, normalized,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Suspend `code` in the caller's stage. The suspension row and its audit row commit in one batch; a
|
|
117
|
+
* code already suspended writes nothing and reports the standing suspension with `created: false`.
|
|
118
|
+
*/
|
|
119
|
+
export async function suspendAttributionCode(
|
|
120
|
+
db: Queryable,
|
|
121
|
+
scope: SuspensionScope & { installId: string },
|
|
122
|
+
code: string,
|
|
123
|
+
input: SuspendInput,
|
|
124
|
+
now: string = new Date().toISOString(),
|
|
125
|
+
): Promise<{ suspension: CodeSuspension; created: boolean }> {
|
|
126
|
+
const normalized = normalizeAttributionCode(code);
|
|
127
|
+
if (!normalized) throw new Error("suspendAttributionCode requires a validated promotional code");
|
|
128
|
+
if (!db.batch) throw new Error("Atomic D1 batch support is required.");
|
|
129
|
+
// Insert-once per code: a losing writer inserts nothing, and the audit row is gated on its own
|
|
130
|
+
// claim id, so only the writer whose suspension landed records it.
|
|
131
|
+
const claimId = crypto.randomUUID();
|
|
132
|
+
await db.batch([
|
|
133
|
+
{
|
|
134
|
+
sql: `INSERT OR IGNORE INTO attribution_code_suspensions
|
|
135
|
+
(tenant_id, stage, normalized_code, code, install_id, reason, evidence_url, note, claim_id, suspended_at)
|
|
136
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
137
|
+
params: [
|
|
138
|
+
scope.tenantId, scope.stage, normalized, code.trim(), scope.installId, input.reason,
|
|
139
|
+
input.evidenceUrl ?? null, input.note ?? null, claimId, now,
|
|
140
|
+
],
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
sql: `INSERT INTO attribution_code_suspension_audit
|
|
144
|
+
(audit_id, tenant_id, stage, install_id, normalized_code, reason, action, occurred_at)
|
|
145
|
+
SELECT ?, ?, ?, ?, ?, ?, 'suspended', ?
|
|
146
|
+
WHERE EXISTS (SELECT 1 FROM attribution_code_suspensions WHERE claim_id = ?)`,
|
|
147
|
+
params: [crypto.randomUUID(), scope.tenantId, scope.stage, scope.installId, normalized, input.reason, now, claimId],
|
|
148
|
+
},
|
|
149
|
+
]);
|
|
150
|
+
const row = await readSuspension(db, scope, normalized);
|
|
151
|
+
if (!row) throw new Error("A suspension write left no suspension row.");
|
|
152
|
+
return { suspension: toSuspension(row), created: row.claim_id === claimId };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** True when `code` is suspended in this tenant and stage. */
|
|
156
|
+
export async function isAttributionCodeSuspended(db: Queryable, scope: SuspensionScope, code: string): Promise<boolean> {
|
|
157
|
+
const normalized = normalizeAttributionCode(code);
|
|
158
|
+
if (!normalized) return false;
|
|
159
|
+
return (await readSuspension(db, scope, normalized)) !== null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Every suspension in this tenant and stage, newest first, for the owner. */
|
|
163
|
+
export async function listAttributionCodeSuspensions(db: Queryable, scope: SuspensionScope): Promise<OwnerCodeSuspension[]> {
|
|
164
|
+
const rows = await db.all<SuspensionRow>(
|
|
165
|
+
`SELECT code, install_id, reason, evidence_url, note, claim_id, suspended_at FROM attribution_code_suspensions
|
|
166
|
+
WHERE tenant_id = ? AND stage = ? ORDER BY suspended_at DESC, normalized_code ASC`,
|
|
167
|
+
scope.tenantId, scope.stage,
|
|
168
|
+
);
|
|
169
|
+
return rows.map((row) => ({
|
|
170
|
+
...toSuspension(row),
|
|
171
|
+
installId: row.install_id,
|
|
172
|
+
...(row.evidence_url ? { evidenceUrl: row.evidence_url } : {}),
|
|
173
|
+
...(row.note ? { note: row.note } : {}),
|
|
174
|
+
}));
|
|
175
|
+
}
|
|
@@ -57,6 +57,7 @@ import { resolveCartSigning, shopperCartDenialMessage } from "@/lib/checkout/sha
|
|
|
57
57
|
import { effectiveExcise } from "@/lib/checkout/commerce/checkoutExcise";
|
|
58
58
|
import { fromD1 } from "@/lib/catalog/d1/catalog";
|
|
59
59
|
import { readD1 } from "@/lib/publication/shared/env";
|
|
60
|
+
import { isAttributionCodeSuspended } from "@/lib/checkout/commerce/attributionCodes";
|
|
60
61
|
import { handoffStockFinding, MIRROR_LOCATION_UNSPECIFIED, readMirrorBalance } from "@/lib/inventory/mirrorStock";
|
|
61
62
|
import { shopperCatalogProduct, shopperVariantPrice } from "@/lib/customers/accounts/pricing";
|
|
62
63
|
import { requiresShopperPurchase, shopperJson } from "@/lib/customers/accounts/purchaseAccess";
|
|
@@ -237,6 +238,30 @@ export async function ledgerSoldOut(context: APIContext, tenant: TenantConfig, s
|
|
|
237
238
|
return handoffStockFinding(reading ? reading.balance : null) !== null;
|
|
238
239
|
}
|
|
239
240
|
|
|
241
|
+
/**
|
|
242
|
+
* The promotional code a new cart may carry: `null` when a Private App suspended it in this tenant
|
|
243
|
+
* and stage. With a known stage, an unreadable suspension store drops the code rather than applying
|
|
244
|
+
* one that may be suspended. A host with no commerce stage keeps it. Carts that already hold a code
|
|
245
|
+
* are never touched.
|
|
246
|
+
*/
|
|
247
|
+
export async function admittedPromoCoupon(
|
|
248
|
+
context: APIContext,
|
|
249
|
+
tenant: TenantConfig,
|
|
250
|
+
coupon: string | null,
|
|
251
|
+
): Promise<string | null> {
|
|
252
|
+
if (coupon === null) return null;
|
|
253
|
+
const stage = ledgerStage(context.locals.customizationEnv);
|
|
254
|
+
if (!stage) return coupon;
|
|
255
|
+
try {
|
|
256
|
+
const database = await readD1("STOREFRONT_APPS_DB");
|
|
257
|
+
if (!database) return null;
|
|
258
|
+
const suspended = await isAttributionCodeSuspended(fromD1(database), { tenantId: commerceTenantId(tenant), stage }, coupon);
|
|
259
|
+
return suspended ? null : coupon;
|
|
260
|
+
} catch {
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
240
265
|
/** A non-positive ledger balance refuses the handoff. No stage, no sku, or no rows does not. */
|
|
241
266
|
async function refuseSoldOut(context: APIContext, tenant: TenantConfig, sku: string | undefined): Promise<Response | null> {
|
|
242
267
|
return (await ledgerSoldOut(context, tenant, sku)) ? stockUnavailable() : null;
|
|
@@ -399,7 +424,8 @@ async function cartFormPost(context: APIContext, shopper?: GatedHandoff): Promis
|
|
|
399
424
|
}
|
|
400
425
|
// The compliance gate adds the shopper's verification ref; it rides to the cart signed.
|
|
401
426
|
const { entries: withoutVerification, ref } = takeVerificationRef(submitted);
|
|
402
|
-
const { entries, coupon } = takePromoCoupon(withoutVerification, context.request.url);
|
|
427
|
+
const { entries, coupon: requestedCoupon } = takePromoCoupon(withoutVerification, context.request.url);
|
|
428
|
+
const coupon = await admittedPromoCoupon(context, tenant, requestedCoupon);
|
|
403
429
|
const result = await enforceCartSubmission({
|
|
404
430
|
entries,
|
|
405
431
|
mode: commerce.mode,
|
|
@@ -145,7 +145,7 @@ export function admissionMatches(
|
|
|
145
145
|
|
|
146
146
|
/** The fields of a provider order event that bind it to a final-cart admission. */
|
|
147
147
|
export interface AdmissionBoundEvent {
|
|
148
|
-
command: "observe" | "capture" | "refund" | "cancel";
|
|
148
|
+
command: "observe" | "capture" | "refund" | "dispute" | "cancel";
|
|
149
149
|
eventVersion: number;
|
|
150
150
|
sourceEventId: string;
|
|
151
151
|
source: string;
|
|
@@ -157,7 +157,7 @@ export interface AdmissionBoundEvent {
|
|
|
157
157
|
destinationDigest?: string;
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
-
const COMMAND_RANK = { observe: 0, capture: 1, refund: 2,
|
|
160
|
+
const COMMAND_RANK = { observe: 0, capture: 1, refund: 2, dispute: 3, cancel: 4 } as const;
|
|
161
161
|
|
|
162
162
|
/**
|
|
163
163
|
* The newest event that owns the order's cart binding. A paid or cart snapshot owns its lines,
|
|
@@ -92,6 +92,11 @@ export interface SourceOrderWrapper {
|
|
|
92
92
|
schema: typeof SOURCE_SCHEMA;
|
|
93
93
|
event: Record<string, unknown>;
|
|
94
94
|
provenance: Provenance;
|
|
95
|
+
/**
|
|
96
|
+
* The signed-commerce v1.8 accounting forward for this event. A sibling of `event`, so
|
|
97
|
+
* `provenance.exactOriginalEventDigest` stays the digest of the event bytes alone.
|
|
98
|
+
*/
|
|
99
|
+
forwardContract?: Record<string, unknown>;
|
|
95
100
|
}
|
|
96
101
|
export interface SourceHold {
|
|
97
102
|
holdId: string;
|
|
@@ -225,8 +230,12 @@ export function parseSourceWire(
|
|
|
225
230
|
): SourceBegin | SourceResult | SourceOrderWrapper | null {
|
|
226
231
|
if (!isRecord(v) || v.schema !== SOURCE_SCHEMA) return null;
|
|
227
232
|
if (v.kind === "source-order-event") {
|
|
233
|
+
const keys = Object.hasOwn(v, "forwardContract")
|
|
234
|
+
? ["kind", "schema", "event", "provenance", "forwardContract"]
|
|
235
|
+
: ["kind", "schema", "event", "provenance"];
|
|
228
236
|
if (
|
|
229
|
-
!exactKeys(v,
|
|
237
|
+
!exactKeys(v, keys) ||
|
|
238
|
+
(v.forwardContract !== undefined && !isRecord(v.forwardContract)) ||
|
|
230
239
|
!isRecord(v.event) ||
|
|
231
240
|
!exactKeys(v.provenance, [
|
|
232
241
|
"acceptedLedgerGeneration",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "7.14.
|
|
3
|
+
"version": "7.14.3",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE",
|
|
5
5
|
"description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
|
|
6
6
|
"packageManager": "pnpm@11.9.0",
|
|
@@ -568,6 +568,14 @@ export const ACTION_CATALOG = {
|
|
|
568
568
|
argsAllow: ["campaign"], renderedAllow: [],
|
|
569
569
|
desc: "A private app recorded an order attribution.",
|
|
570
570
|
},
|
|
571
|
+
"app.attribution.code_suspended": {
|
|
572
|
+
// apps/v1/attribution/codes/[code]/suspend.ts — an installed private app suspended a
|
|
573
|
+
// promotional code for a compliance reason. Low-volume and owner-relevant → timelined.
|
|
574
|
+
// The code, note and evidence URL are excluded; only the reason enum and stage survive.
|
|
575
|
+
actors: ["agent"], source: "server", sinks: LIFECYCLE,
|
|
576
|
+
argsAllow: ["reason", "stage"], renderedAllow: [],
|
|
577
|
+
desc: "A private app suspended a promotional code.",
|
|
578
|
+
},
|
|
571
579
|
"webhook.delivery.replayed": {
|
|
572
580
|
// apps/{admin,v1}/webhooks/deliveries/[deliveryId]/replay.ts — a webhook delivery was
|
|
573
581
|
// re-enqueued. TWO call sites, ONE key: the admin/ops console (session-authed →
|