@tokenoftrust/storefront-runner 7.6.16 → 7.6.18
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/components/content/storefront/content/BulkQuoteForm.astro +396 -0
- package/apps/storefront/src/components/content/storefront/content/ProseSections.astro +3 -0
- package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +67 -0
- package/apps/storefront/src/lib/access/auth/loginGate.ts +30 -0
- package/apps/storefront/src/lib/access/auth/session.ts +12 -0
- package/apps/storefront/src/lib/content/prose.ts +36 -0
- package/apps/storefront/src/lib/engagement/contact/bulkQuote.ts +521 -0
- package/apps/storefront/src/lib/engagement/contact/submitToken.ts +29 -13
- package/apps/storefront/src/middleware/controlPlane.ts +8 -0
- package/apps/storefront/src/middleware/index.ts +8 -3
- package/apps/storefront/src/pages/api/contact/token.ts +11 -5
- package/package.json +1 -1
- package/packages/cli/src/visual-parity.mjs +3 -1
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bulk / custom wholesale quote request: its public wire contract, its strict
|
|
3
|
+
* parser, the sealed envelope it is stored as, and the typed record the /admin inbox
|
|
4
|
+
* and order conversion read back. Browser-safe: no server imports.
|
|
5
|
+
*
|
|
6
|
+
* GET {apiBasePath}/api/contact/token?form=bulk-quote → 200 { ok:true, token }
|
|
7
|
+
* POST {apiBasePath}/api/contact/bulk-quote ← BulkQuoteSubmission (application/json, same origin)
|
|
8
|
+
* → 201 { ok:true, quoteId:"bq_<32 hex>" }
|
|
9
|
+
* 400 invalid_json | invalid_input (+ field)
|
|
10
|
+
* 403 forbidden_origin | invalid_token
|
|
11
|
+
* 409 stage-unknown · 413 too_large
|
|
12
|
+
* 415 unsupported_media_type · 429 rate_limited
|
|
13
|
+
* 503 unavailable · 500 store_failed
|
|
14
|
+
*
|
|
15
|
+
* Storage: a quote is one `contact_messages` row whose id is the quote id. Name, email
|
|
16
|
+
* and phone use the row's sealed contact columns and blind indexes; everything else is
|
|
17
|
+
* the versioned {@link BulkQuoteEnvelope}, sealed as the row's message. The server
|
|
18
|
+
* mints the id, so the `bq_` prefix is a trusted classification: a contact message id
|
|
19
|
+
* is always a UUID. A row whose id and envelope disagree is not a quote.
|
|
20
|
+
*
|
|
21
|
+
* Buyer identity (`orgId`, `shopperId`) comes only from a server-verified session and
|
|
22
|
+
* is null when the buyer is anonymous. The submission carries no identity field; one
|
|
23
|
+
* sent anyway is an unknown field and refuses.
|
|
24
|
+
*
|
|
25
|
+
* Order conversion loads a quote by id: {@link isBulkQuoteId} admits the reference,
|
|
26
|
+
* the owner or support read returns the stored message, and {@link toBulkQuoteRecord}
|
|
27
|
+
* turns it into a {@link BulkQuoteRecord} (null when the row is not a valid quote).
|
|
28
|
+
*/
|
|
29
|
+
import { CONTACT_LIMITS } from "./contract.js";
|
|
30
|
+
|
|
31
|
+
export const BULK_QUOTE_FORM = "bulk-quote" as const;
|
|
32
|
+
export const BULK_QUOTE_KIND = "bulk-quote" as const;
|
|
33
|
+
export const BULK_QUOTE_ENVELOPE_VERSION = 1 as const;
|
|
34
|
+
|
|
35
|
+
export const BULK_QUOTE_UNITS = [
|
|
36
|
+
"each",
|
|
37
|
+
"case",
|
|
38
|
+
"gallon",
|
|
39
|
+
"pail",
|
|
40
|
+
"drum",
|
|
41
|
+
"tote",
|
|
42
|
+
"pound",
|
|
43
|
+
"kilogram",
|
|
44
|
+
"liter",
|
|
45
|
+
"custom",
|
|
46
|
+
] as const;
|
|
47
|
+
export type BulkQuoteUnit = (typeof BULK_QUOTE_UNITS)[number];
|
|
48
|
+
|
|
49
|
+
export const BULK_QUOTE_LIMITS = {
|
|
50
|
+
// Every text field at its limit, at 3 UTF-8 bytes per character, plus JSON structure.
|
|
51
|
+
bodyBytes: 64 * 1024,
|
|
52
|
+
businessName: 160,
|
|
53
|
+
name: CONTACT_LIMITS.name,
|
|
54
|
+
email: CONTACT_LIMITS.email,
|
|
55
|
+
phone: CONTACT_LIMITS.phone,
|
|
56
|
+
lineItemsMin: 1,
|
|
57
|
+
lineItems: 25,
|
|
58
|
+
description: 500,
|
|
59
|
+
sku: 64,
|
|
60
|
+
packSize: 60,
|
|
61
|
+
quantityMax: 1_000_000,
|
|
62
|
+
destinationRegion: 64,
|
|
63
|
+
destinationPostalCode: 12,
|
|
64
|
+
freightNotes: 1000,
|
|
65
|
+
poNumber: 64,
|
|
66
|
+
timeline: 200,
|
|
67
|
+
notes: 2000,
|
|
68
|
+
} as const;
|
|
69
|
+
|
|
70
|
+
/** A quote id: `bq_` and 32 lowercase hex digits, minted by the server. */
|
|
71
|
+
const QUOTE_ID = /^bq_[0-9a-f]{32}$/;
|
|
72
|
+
/** Every id a contact_messages row may carry: a contact message UUID or a quote id. */
|
|
73
|
+
export const CONTACT_MESSAGE_ID_SHAPE =
|
|
74
|
+
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|bq_[0-9a-f]{32})$/;
|
|
75
|
+
/** A SQL LIKE pattern (with `ESCAPE '\'`) matching exactly the quote rows. */
|
|
76
|
+
export const BULK_QUOTE_ID_LIKE = "bq\\_%";
|
|
77
|
+
|
|
78
|
+
export function isBulkQuoteId(value: unknown): value is string {
|
|
79
|
+
return typeof value === "string" && QUOTE_ID.test(value);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function mintBulkQuoteId(): string {
|
|
83
|
+
return `bq_${crypto.randomUUID().replace(/-/g, "")}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface BulkQuoteLineItem {
|
|
87
|
+
description: string;
|
|
88
|
+
sku: string | null;
|
|
89
|
+
quantity: number;
|
|
90
|
+
unit: BulkQuoteUnit;
|
|
91
|
+
packSize: string | null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface BulkQuoteFreight {
|
|
95
|
+
destinationRegion: string | null;
|
|
96
|
+
destinationPostalCode: string | null;
|
|
97
|
+
liftgate: boolean;
|
|
98
|
+
notes: string | null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface BulkQuoteBuyer {
|
|
102
|
+
orgId: string | null;
|
|
103
|
+
shopperId: string | null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The submission body. `company` is the honeypot: render it hidden and send it empty. */
|
|
107
|
+
export interface BulkQuoteSubmission {
|
|
108
|
+
token: string;
|
|
109
|
+
businessName: string;
|
|
110
|
+
name: string;
|
|
111
|
+
email: string;
|
|
112
|
+
phone?: string;
|
|
113
|
+
lineItems: Array<{
|
|
114
|
+
description: string;
|
|
115
|
+
sku?: string;
|
|
116
|
+
quantity: number;
|
|
117
|
+
unit: BulkQuoteUnit;
|
|
118
|
+
packSize?: string;
|
|
119
|
+
}>;
|
|
120
|
+
destinationRegion?: string;
|
|
121
|
+
destinationPostalCode?: string;
|
|
122
|
+
liftgate?: boolean;
|
|
123
|
+
freightNotes?: string;
|
|
124
|
+
poNumber?: string;
|
|
125
|
+
timeline?: string;
|
|
126
|
+
notes?: string;
|
|
127
|
+
company?: string;
|
|
128
|
+
challenge?: string;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export type BulkQuoteField =
|
|
132
|
+
| "businessName"
|
|
133
|
+
| "name"
|
|
134
|
+
| "email"
|
|
135
|
+
| "phone"
|
|
136
|
+
| "lineItems"
|
|
137
|
+
| "description"
|
|
138
|
+
| "sku"
|
|
139
|
+
| "quantity"
|
|
140
|
+
| "unit"
|
|
141
|
+
| "packSize"
|
|
142
|
+
| "destinationRegion"
|
|
143
|
+
| "destinationPostalCode"
|
|
144
|
+
| "liftgate"
|
|
145
|
+
| "freightNotes"
|
|
146
|
+
| "poNumber"
|
|
147
|
+
| "timeline"
|
|
148
|
+
| "notes"
|
|
149
|
+
| "unknown";
|
|
150
|
+
|
|
151
|
+
/** The parsed request: contact columns plus the quote detail that is sealed as the message. */
|
|
152
|
+
export interface ParsedBulkQuote {
|
|
153
|
+
contact: { name: string; email: string; phone: string };
|
|
154
|
+
businessName: string;
|
|
155
|
+
lineItems: BulkQuoteLineItem[];
|
|
156
|
+
freight: BulkQuoteFreight;
|
|
157
|
+
poNumber: string | null;
|
|
158
|
+
timeline: string | null;
|
|
159
|
+
notes: string | null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export type BulkQuoteParse =
|
|
163
|
+
| { ok: true; quote: ParsedBulkQuote }
|
|
164
|
+
| { ok: false; field: BulkQuoteField; index?: number };
|
|
165
|
+
|
|
166
|
+
/** The sealed message of a quote row. */
|
|
167
|
+
export interface BulkQuoteEnvelope {
|
|
168
|
+
v: typeof BULK_QUOTE_ENVELOPE_VERSION;
|
|
169
|
+
kind: typeof BULK_QUOTE_KIND;
|
|
170
|
+
quoteId: string;
|
|
171
|
+
businessName: string;
|
|
172
|
+
lineItems: BulkQuoteLineItem[];
|
|
173
|
+
freight: BulkQuoteFreight;
|
|
174
|
+
poNumber: string | null;
|
|
175
|
+
timeline: string | null;
|
|
176
|
+
notes: string | null;
|
|
177
|
+
buyer: BulkQuoteBuyer;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** One quote, as /admin renders it and order conversion consumes it. */
|
|
181
|
+
export interface BulkQuoteRecord {
|
|
182
|
+
quoteId: string;
|
|
183
|
+
status: "unread" | "read";
|
|
184
|
+
createdAt: string;
|
|
185
|
+
readAt: string | null;
|
|
186
|
+
pagePath: string | null;
|
|
187
|
+
contact: { name: string; email: string; phone: string };
|
|
188
|
+
businessName: string;
|
|
189
|
+
lineItems: BulkQuoteLineItem[];
|
|
190
|
+
freight: BulkQuoteFreight;
|
|
191
|
+
poNumber: string | null;
|
|
192
|
+
timeline: string | null;
|
|
193
|
+
notes: string | null;
|
|
194
|
+
buyer: BulkQuoteBuyer;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** The stored-message shape {@link toBulkQuoteRecord} reads: what the contact store opens. */
|
|
198
|
+
export interface StoredContactMessage {
|
|
199
|
+
id: string;
|
|
200
|
+
name: string;
|
|
201
|
+
email: string;
|
|
202
|
+
phone: string;
|
|
203
|
+
message: string;
|
|
204
|
+
pagePath: string | null;
|
|
205
|
+
status: "unread" | "read";
|
|
206
|
+
createdAt: string;
|
|
207
|
+
readAt: string | null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
211
|
+
const SINGLE_LINE_STRIP = /[\r\n\0]/g;
|
|
212
|
+
const NUL = /\0/g;
|
|
213
|
+
const POSTAL_CODE = /^[A-Za-z0-9][A-Za-z0-9 -]*$/;
|
|
214
|
+
const UNITS = new Set<string>(BULK_QUOTE_UNITS);
|
|
215
|
+
|
|
216
|
+
const TOP_LEVEL_KEYS = new Set([
|
|
217
|
+
"token",
|
|
218
|
+
"businessName",
|
|
219
|
+
"name",
|
|
220
|
+
"email",
|
|
221
|
+
"phone",
|
|
222
|
+
"lineItems",
|
|
223
|
+
"destinationRegion",
|
|
224
|
+
"destinationPostalCode",
|
|
225
|
+
"liftgate",
|
|
226
|
+
"freightNotes",
|
|
227
|
+
"poNumber",
|
|
228
|
+
"timeline",
|
|
229
|
+
"notes",
|
|
230
|
+
"company",
|
|
231
|
+
"challenge",
|
|
232
|
+
]);
|
|
233
|
+
const LINE_ITEM_KEYS = new Set(["description", "sku", "quantity", "unit", "packSize"]);
|
|
234
|
+
|
|
235
|
+
function singleLine(value: string): string {
|
|
236
|
+
return value.replace(SINGLE_LINE_STRIP, "").trim();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function multiLine(value: string): string {
|
|
240
|
+
return value.replace(NUL, "").trim();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
244
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
type Text = { ok: true; value: string } | { ok: false };
|
|
248
|
+
|
|
249
|
+
/** An optional string: absent or null is "", anything else must be a string within `max`. */
|
|
250
|
+
function text(raw: unknown, max: number, shape: (value: string) => string): Text {
|
|
251
|
+
if (raw === undefined || raw === null) return { ok: true, value: "" };
|
|
252
|
+
if (typeof raw !== "string") return { ok: false };
|
|
253
|
+
const value = shape(raw);
|
|
254
|
+
return value.length <= max ? { ok: true, value } : { ok: false };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function orNull(value: string): string | null {
|
|
258
|
+
return value === "" ? null : value;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function parseLineItem(raw: unknown): { ok: true; item: BulkQuoteLineItem } | { ok: false; field: BulkQuoteField } {
|
|
262
|
+
if (!isPlainObject(raw)) return { ok: false, field: "lineItems" };
|
|
263
|
+
for (const key of Object.keys(raw)) if (!LINE_ITEM_KEYS.has(key)) return { ok: false, field: "unknown" };
|
|
264
|
+
const description = text(raw.description, BULK_QUOTE_LIMITS.description, multiLine);
|
|
265
|
+
if (!description.ok || description.value === "") return { ok: false, field: "description" };
|
|
266
|
+
const sku = text(raw.sku, BULK_QUOTE_LIMITS.sku, singleLine);
|
|
267
|
+
if (!sku.ok) return { ok: false, field: "sku" };
|
|
268
|
+
const quantity = raw.quantity;
|
|
269
|
+
if (typeof quantity !== "number" || !Number.isFinite(quantity) || quantity <= 0 || quantity > BULK_QUOTE_LIMITS.quantityMax) {
|
|
270
|
+
return { ok: false, field: "quantity" };
|
|
271
|
+
}
|
|
272
|
+
if (typeof raw.unit !== "string" || !UNITS.has(raw.unit)) return { ok: false, field: "unit" };
|
|
273
|
+
const packSize = text(raw.packSize, BULK_QUOTE_LIMITS.packSize, singleLine);
|
|
274
|
+
if (!packSize.ok) return { ok: false, field: "packSize" };
|
|
275
|
+
return {
|
|
276
|
+
ok: true,
|
|
277
|
+
item: {
|
|
278
|
+
description: description.value,
|
|
279
|
+
sku: orNull(sku.value),
|
|
280
|
+
quantity,
|
|
281
|
+
unit: raw.unit as BulkQuoteUnit,
|
|
282
|
+
packSize: orNull(packSize.value),
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Parse one submission body. Every top-level and line-item key must be known; strings are
|
|
289
|
+
* capped and single-line values lose CR, LF and NUL. The token, challenge and honeypot are
|
|
290
|
+
* the route's to check and are only admitted here as known keys.
|
|
291
|
+
*/
|
|
292
|
+
export function parseBulkQuoteSubmission(body: Record<string, unknown>): BulkQuoteParse {
|
|
293
|
+
for (const key of Object.keys(body)) if (!TOP_LEVEL_KEYS.has(key)) return { ok: false, field: "unknown" };
|
|
294
|
+
|
|
295
|
+
const businessName = text(body.businessName, BULK_QUOTE_LIMITS.businessName, singleLine);
|
|
296
|
+
if (!businessName.ok || businessName.value === "") return { ok: false, field: "businessName" };
|
|
297
|
+
const name = text(body.name, BULK_QUOTE_LIMITS.name, singleLine);
|
|
298
|
+
if (!name.ok || name.value === "") return { ok: false, field: "name" };
|
|
299
|
+
const email = text(body.email, BULK_QUOTE_LIMITS.email, (v) => singleLine(v).toLowerCase());
|
|
300
|
+
if (!email.ok || !EMAIL_RE.test(email.value)) return { ok: false, field: "email" };
|
|
301
|
+
const phone = text(body.phone, BULK_QUOTE_LIMITS.phone, singleLine);
|
|
302
|
+
if (!phone.ok) return { ok: false, field: "phone" };
|
|
303
|
+
|
|
304
|
+
const rawItems = body.lineItems;
|
|
305
|
+
if (!Array.isArray(rawItems) || rawItems.length < BULK_QUOTE_LIMITS.lineItemsMin || rawItems.length > BULK_QUOTE_LIMITS.lineItems) {
|
|
306
|
+
return { ok: false, field: "lineItems" };
|
|
307
|
+
}
|
|
308
|
+
const lineItems: BulkQuoteLineItem[] = [];
|
|
309
|
+
for (const [index, raw] of rawItems.entries()) {
|
|
310
|
+
const parsed = parseLineItem(raw);
|
|
311
|
+
if (!parsed.ok) return { ok: false, field: parsed.field, index };
|
|
312
|
+
lineItems.push(parsed.item);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const region = text(body.destinationRegion, BULK_QUOTE_LIMITS.destinationRegion, singleLine);
|
|
316
|
+
if (!region.ok) return { ok: false, field: "destinationRegion" };
|
|
317
|
+
const postal = text(body.destinationPostalCode, BULK_QUOTE_LIMITS.destinationPostalCode, singleLine);
|
|
318
|
+
if (!postal.ok || (postal.value !== "" && !POSTAL_CODE.test(postal.value))) return { ok: false, field: "destinationPostalCode" };
|
|
319
|
+
const liftgate = body.liftgate;
|
|
320
|
+
if (liftgate !== undefined && liftgate !== null && typeof liftgate !== "boolean") return { ok: false, field: "liftgate" };
|
|
321
|
+
const freightNotes = text(body.freightNotes, BULK_QUOTE_LIMITS.freightNotes, multiLine);
|
|
322
|
+
if (!freightNotes.ok) return { ok: false, field: "freightNotes" };
|
|
323
|
+
const poNumber = text(body.poNumber, BULK_QUOTE_LIMITS.poNumber, singleLine);
|
|
324
|
+
if (!poNumber.ok) return { ok: false, field: "poNumber" };
|
|
325
|
+
const timeline = text(body.timeline, BULK_QUOTE_LIMITS.timeline, singleLine);
|
|
326
|
+
if (!timeline.ok) return { ok: false, field: "timeline" };
|
|
327
|
+
const notes = text(body.notes, BULK_QUOTE_LIMITS.notes, multiLine);
|
|
328
|
+
if (!notes.ok) return { ok: false, field: "notes" };
|
|
329
|
+
|
|
330
|
+
return {
|
|
331
|
+
ok: true,
|
|
332
|
+
quote: {
|
|
333
|
+
contact: { name: name.value, email: email.value, phone: phone.value },
|
|
334
|
+
businessName: businessName.value,
|
|
335
|
+
lineItems,
|
|
336
|
+
freight: {
|
|
337
|
+
destinationRegion: orNull(region.value),
|
|
338
|
+
destinationPostalCode: orNull(postal.value),
|
|
339
|
+
liftgate: liftgate === true,
|
|
340
|
+
notes: orNull(freightNotes.value),
|
|
341
|
+
},
|
|
342
|
+
poNumber: orNull(poNumber.value),
|
|
343
|
+
timeline: orNull(timeline.value),
|
|
344
|
+
notes: orNull(notes.value),
|
|
345
|
+
},
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The sealed message text for one quote. */
|
|
350
|
+
export function encodeBulkQuoteEnvelope(quoteId: string, quote: ParsedBulkQuote, buyer: BulkQuoteBuyer): string {
|
|
351
|
+
if (!isBulkQuoteId(quoteId)) throw new Error("bulk quote id malformed");
|
|
352
|
+
const envelope: BulkQuoteEnvelope = {
|
|
353
|
+
v: BULK_QUOTE_ENVELOPE_VERSION,
|
|
354
|
+
kind: BULK_QUOTE_KIND,
|
|
355
|
+
quoteId,
|
|
356
|
+
businessName: quote.businessName,
|
|
357
|
+
lineItems: quote.lineItems,
|
|
358
|
+
freight: quote.freight,
|
|
359
|
+
poNumber: quote.poNumber,
|
|
360
|
+
timeline: quote.timeline,
|
|
361
|
+
notes: quote.notes,
|
|
362
|
+
buyer: { orgId: buyer.orgId, shopperId: buyer.shopperId },
|
|
363
|
+
};
|
|
364
|
+
return JSON.stringify(envelope);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const ENVELOPE_KEYS = ["businessName", "buyer", "freight", "kind", "lineItems", "notes", "poNumber", "quoteId", "timeline", "v"].sort().join(",");
|
|
368
|
+
const IDENTITY = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
369
|
+
|
|
370
|
+
function nullableText(value: unknown, max: number): value is string | null {
|
|
371
|
+
return value === null || (typeof value === "string" && value !== "" && value.length <= max);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function identity(value: unknown): value is string | null {
|
|
375
|
+
return value === null || (typeof value === "string" && IDENTITY.test(value));
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Decode one stored message as the quote whose id it carries. Null when the id is not a
|
|
380
|
+
* quote id, or when the envelope is not exactly a valid version-1 quote for that id.
|
|
381
|
+
*/
|
|
382
|
+
export function decodeBulkQuoteEnvelope(id: string, message: string): BulkQuoteEnvelope | null {
|
|
383
|
+
if (!isBulkQuoteId(id)) return null;
|
|
384
|
+
let parsed: unknown;
|
|
385
|
+
try {
|
|
386
|
+
parsed = JSON.parse(message);
|
|
387
|
+
} catch (error) {
|
|
388
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
389
|
+
parsed = undefined;
|
|
390
|
+
}
|
|
391
|
+
if (!isPlainObject(parsed) || Object.keys(parsed).sort().join(",") !== ENVELOPE_KEYS) return null;
|
|
392
|
+
const e = parsed;
|
|
393
|
+
if (e.v !== BULK_QUOTE_ENVELOPE_VERSION || e.kind !== BULK_QUOTE_KIND || e.quoteId !== id) return null;
|
|
394
|
+
if (typeof e.businessName !== "string" || e.businessName === "" || e.businessName.length > BULK_QUOTE_LIMITS.businessName) return null;
|
|
395
|
+
if (!Array.isArray(e.lineItems) || e.lineItems.length < BULK_QUOTE_LIMITS.lineItemsMin || e.lineItems.length > BULK_QUOTE_LIMITS.lineItems) return null;
|
|
396
|
+
const lineItems: BulkQuoteLineItem[] = [];
|
|
397
|
+
for (const raw of e.lineItems) {
|
|
398
|
+
if (!isPlainObject(raw) || Object.keys(raw).sort().join(",") !== "description,packSize,quantity,sku,unit") return null;
|
|
399
|
+
const parsedItem = parseLineItem({
|
|
400
|
+
description: raw.description,
|
|
401
|
+
sku: raw.sku,
|
|
402
|
+
quantity: raw.quantity,
|
|
403
|
+
unit: raw.unit,
|
|
404
|
+
packSize: raw.packSize,
|
|
405
|
+
});
|
|
406
|
+
if (!parsedItem.ok || parsedItem.item.description !== raw.description) return null;
|
|
407
|
+
lineItems.push(parsedItem.item);
|
|
408
|
+
}
|
|
409
|
+
const f = e.freight;
|
|
410
|
+
if (!isPlainObject(f) || Object.keys(f).sort().join(",") !== "destinationPostalCode,destinationRegion,liftgate,notes") return null;
|
|
411
|
+
if (!nullableText(f.destinationRegion, BULK_QUOTE_LIMITS.destinationRegion)) return null;
|
|
412
|
+
if (!nullableText(f.destinationPostalCode, BULK_QUOTE_LIMITS.destinationPostalCode)) return null;
|
|
413
|
+
if (typeof f.liftgate !== "boolean" || !nullableText(f.notes, BULK_QUOTE_LIMITS.freightNotes)) return null;
|
|
414
|
+
if (!nullableText(e.poNumber, BULK_QUOTE_LIMITS.poNumber)) return null;
|
|
415
|
+
if (!nullableText(e.timeline, BULK_QUOTE_LIMITS.timeline)) return null;
|
|
416
|
+
if (!nullableText(e.notes, BULK_QUOTE_LIMITS.notes)) return null;
|
|
417
|
+
const b = e.buyer;
|
|
418
|
+
if (!isPlainObject(b) || Object.keys(b).sort().join(",") !== "orgId,shopperId" || !identity(b.orgId) || !identity(b.shopperId)) return null;
|
|
419
|
+
return {
|
|
420
|
+
v: BULK_QUOTE_ENVELOPE_VERSION,
|
|
421
|
+
kind: BULK_QUOTE_KIND,
|
|
422
|
+
quoteId: id,
|
|
423
|
+
businessName: e.businessName,
|
|
424
|
+
lineItems,
|
|
425
|
+
freight: {
|
|
426
|
+
destinationRegion: f.destinationRegion,
|
|
427
|
+
destinationPostalCode: f.destinationPostalCode,
|
|
428
|
+
liftgate: f.liftgate,
|
|
429
|
+
notes: f.notes,
|
|
430
|
+
},
|
|
431
|
+
poNumber: e.poNumber,
|
|
432
|
+
timeline: e.timeline,
|
|
433
|
+
notes: e.notes,
|
|
434
|
+
buyer: { orgId: b.orgId, shopperId: b.shopperId },
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** The quote a stored message holds, or null when it is not a valid quote. */
|
|
439
|
+
export function toBulkQuoteRecord(message: StoredContactMessage): BulkQuoteRecord | null {
|
|
440
|
+
const envelope = decodeBulkQuoteEnvelope(message.id, message.message);
|
|
441
|
+
if (!envelope) return null;
|
|
442
|
+
return {
|
|
443
|
+
quoteId: envelope.quoteId,
|
|
444
|
+
status: message.status,
|
|
445
|
+
createdAt: message.createdAt,
|
|
446
|
+
readAt: message.readAt,
|
|
447
|
+
pagePath: message.pagePath,
|
|
448
|
+
contact: { name: message.name, email: message.email, phone: message.phone },
|
|
449
|
+
businessName: envelope.businessName,
|
|
450
|
+
lineItems: envelope.lineItems,
|
|
451
|
+
freight: envelope.freight,
|
|
452
|
+
poNumber: envelope.poNumber,
|
|
453
|
+
timeline: envelope.timeline,
|
|
454
|
+
notes: envelope.notes,
|
|
455
|
+
buyer: envelope.buyer,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export type BulkQuoteErrorCode =
|
|
460
|
+
| "not_found"
|
|
461
|
+
| "invalid_json"
|
|
462
|
+
| "invalid_input"
|
|
463
|
+
| "forbidden_origin"
|
|
464
|
+
| "invalid_token"
|
|
465
|
+
| "too_large"
|
|
466
|
+
| "unsupported_media_type"
|
|
467
|
+
| "rate_limited"
|
|
468
|
+
| "unavailable"
|
|
469
|
+
| "stage-unknown"
|
|
470
|
+
| "store_failed";
|
|
471
|
+
|
|
472
|
+
export type BulkQuoteSubmitResponse =
|
|
473
|
+
| { ok: true; quoteId: string }
|
|
474
|
+
| { ok: false; error: BulkQuoteErrorCode; field?: BulkQuoteField; index?: number };
|
|
475
|
+
|
|
476
|
+
export interface BulkQuoteClientResult {
|
|
477
|
+
status: number;
|
|
478
|
+
body: BulkQuoteSubmitResponse;
|
|
479
|
+
/** True when the buyer should keep their entries and may try again. */
|
|
480
|
+
retryable: boolean;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const RETRYABLE = new Set([429, 500, 503]);
|
|
484
|
+
|
|
485
|
+
function apiUrl(apiBasePath: string, path: string): string {
|
|
486
|
+
return `${apiBasePath.replace(/\/+$/, "")}${path}`;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Fetch a fresh bulk-quote submit token. Call when the form is shown, not on submit. */
|
|
490
|
+
export async function fetchBulkQuoteToken(apiBasePath: string, fetchImpl: typeof fetch = fetch): Promise<string> {
|
|
491
|
+
const res = await fetchImpl(apiUrl(apiBasePath, `/api/contact/token?form=${BULK_QUOTE_FORM}`), {
|
|
492
|
+
headers: { accept: "application/json" },
|
|
493
|
+
credentials: "same-origin",
|
|
494
|
+
});
|
|
495
|
+
if (!res.ok) throw new Error(`bulk quote token unavailable (${res.status})`);
|
|
496
|
+
const body = (await res.json()) as { ok?: unknown; token?: unknown };
|
|
497
|
+
if (body.ok !== true || typeof body.token !== "string") throw new Error("bulk quote token malformed");
|
|
498
|
+
return body.token;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** Post one quote request. A transport failure throws; every HTTP outcome resolves. */
|
|
502
|
+
export async function submitBulkQuote(
|
|
503
|
+
apiBasePath: string,
|
|
504
|
+
submission: BulkQuoteSubmission,
|
|
505
|
+
fetchImpl: typeof fetch = fetch,
|
|
506
|
+
): Promise<BulkQuoteClientResult> {
|
|
507
|
+
const res = await fetchImpl(apiUrl(apiBasePath, "/api/contact/bulk-quote"), {
|
|
508
|
+
method: "POST",
|
|
509
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
510
|
+
credentials: "same-origin",
|
|
511
|
+
body: JSON.stringify(submission),
|
|
512
|
+
});
|
|
513
|
+
const raw = await res.text();
|
|
514
|
+
let body: BulkQuoteSubmitResponse;
|
|
515
|
+
try {
|
|
516
|
+
body = JSON.parse(raw) as BulkQuoteSubmitResponse;
|
|
517
|
+
} catch {
|
|
518
|
+
body = { ok: false, error: res.ok ? "store_failed" : "unavailable" };
|
|
519
|
+
}
|
|
520
|
+
return { status: res.status, body, retryable: RETRYABLE.has(res.status) };
|
|
521
|
+
}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Server-signed minimum-time-to-submit token for the contact
|
|
2
|
+
* Server-signed minimum-time-to-submit token for the public contact forms.
|
|
3
3
|
*
|
|
4
|
-
* `issueContactToken` signs `{ tenant, issuedAt }` with HMAC-SHA256 under
|
|
5
|
-
* `CONTACT_FORM_TOKEN_SECRET
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* `issueContactToken` signs `{ tenant, form, issuedAt }` with HMAC-SHA256 under
|
|
5
|
+
* `CONTACT_FORM_TOKEN_SECRET`, behind a per-form MAC prefix; `verifyContactToken`
|
|
6
|
+
* accepts it only for the same tenant and the same form, between
|
|
7
|
+
* {@link CONTACT_TOKEN_MIN_AGE_MS} and {@link CONTACT_TOKEN_MAX_AGE_MS} after issue.
|
|
8
|
+
* A token for one form never authorizes another. A script that posts without first
|
|
9
|
+
* loading the form, or posts faster than a person can type, is refused. Web Crypto only.
|
|
9
10
|
*
|
|
10
11
|
* Wire form: `v1.<base64url(JSON payload)>.<base64url(HMAC)>`.
|
|
11
12
|
*/
|
|
@@ -14,9 +15,21 @@ import { CONTACT_TOKEN_MAX_AGE_MS, CONTACT_TOKEN_MIN_AGE_MS } from "./contract.j
|
|
|
14
15
|
const VERSION = "v1";
|
|
15
16
|
const encoder = new TextEncoder();
|
|
16
17
|
|
|
18
|
+
/** The public forms a submit token can be issued for. */
|
|
19
|
+
export type ContactFormKind = "contact" | "bulk-quote";
|
|
20
|
+
|
|
21
|
+
const MAC_PREFIX: Record<ContactFormKind, string> = {
|
|
22
|
+
contact: "contact-form",
|
|
23
|
+
"bulk-quote": "bulk-quote-form",
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export function isContactFormKind(value: unknown): value is ContactFormKind {
|
|
27
|
+
return typeof value === "string" && Object.hasOwn(MAC_PREFIX, value);
|
|
28
|
+
}
|
|
29
|
+
|
|
17
30
|
export type ContactTokenVerdict =
|
|
18
31
|
| { ok: true }
|
|
19
|
-
| { ok: false; reason: "malformed" | "bad_signature" | "wrong_tenant" | "too_early" | "expired" };
|
|
32
|
+
| { ok: false; reason: "malformed" | "bad_signature" | "wrong_form" | "wrong_tenant" | "too_early" | "expired" };
|
|
20
33
|
|
|
21
34
|
function base64url(bytes: Uint8Array): string {
|
|
22
35
|
let bin = "";
|
|
@@ -36,17 +49,18 @@ function hmacKey(secret: string, usage: "sign" | "verify"): Promise<CryptoKey> {
|
|
|
36
49
|
return crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
|
|
37
50
|
}
|
|
38
51
|
|
|
39
|
-
function signedBytes(payload: string): Uint8Array<ArrayBuffer> {
|
|
40
|
-
return new Uint8Array(encoder.encode(
|
|
52
|
+
function signedBytes(form: ContactFormKind, payload: string): Uint8Array<ArrayBuffer> {
|
|
53
|
+
return new Uint8Array(encoder.encode(`${MAC_PREFIX[form]}:${VERSION}:${payload}`));
|
|
41
54
|
}
|
|
42
55
|
|
|
43
56
|
export async function issueContactToken(
|
|
44
57
|
secret: string,
|
|
45
58
|
tenantId: string,
|
|
46
59
|
nowMs: number = Date.now(),
|
|
60
|
+
form: ContactFormKind = "contact",
|
|
47
61
|
): Promise<string> {
|
|
48
|
-
const payload = base64url(encoder.encode(JSON.stringify({ tenant: tenantId, issuedAt: nowMs })));
|
|
49
|
-
const mac = await crypto.subtle.sign("HMAC", await hmacKey(secret, "sign"), signedBytes(payload));
|
|
62
|
+
const payload = base64url(encoder.encode(JSON.stringify({ tenant: tenantId, form, issuedAt: nowMs })));
|
|
63
|
+
const mac = await crypto.subtle.sign("HMAC", await hmacKey(secret, "sign"), signedBytes(form, payload));
|
|
50
64
|
return `${VERSION}.${payload}.${base64url(new Uint8Array(mac))}`;
|
|
51
65
|
}
|
|
52
66
|
|
|
@@ -55,6 +69,7 @@ export async function verifyContactToken(
|
|
|
55
69
|
token: string,
|
|
56
70
|
tenantId: string,
|
|
57
71
|
nowMs: number = Date.now(),
|
|
72
|
+
form: ContactFormKind = "contact",
|
|
58
73
|
): Promise<ContactTokenVerdict> {
|
|
59
74
|
const parts = token.split(".");
|
|
60
75
|
if (parts.length !== 3 || parts[0] !== VERSION) return { ok: false, reason: "malformed" };
|
|
@@ -63,10 +78,10 @@ export async function verifyContactToken(
|
|
|
63
78
|
const payloadBytes = fromBase64url(payload);
|
|
64
79
|
if (!sigBytes || !payloadBytes) return { ok: false, reason: "malformed" };
|
|
65
80
|
|
|
66
|
-
const valid = await crypto.subtle.verify("HMAC", await hmacKey(secret, "verify"), sigBytes, signedBytes(payload));
|
|
81
|
+
const valid = await crypto.subtle.verify("HMAC", await hmacKey(secret, "verify"), sigBytes, signedBytes(form, payload));
|
|
67
82
|
if (!valid) return { ok: false, reason: "bad_signature" };
|
|
68
83
|
|
|
69
|
-
let claims: { tenant?: unknown; issuedAt?: unknown };
|
|
84
|
+
let claims: { tenant?: unknown; form?: unknown; issuedAt?: unknown };
|
|
70
85
|
try {
|
|
71
86
|
claims = JSON.parse(new TextDecoder().decode(payloadBytes)) as typeof claims;
|
|
72
87
|
} catch {
|
|
@@ -75,6 +90,7 @@ export async function verifyContactToken(
|
|
|
75
90
|
if (typeof claims.issuedAt !== "number" || !Number.isFinite(claims.issuedAt)) {
|
|
76
91
|
return { ok: false, reason: "malformed" };
|
|
77
92
|
}
|
|
93
|
+
if (claims.form !== form) return { ok: false, reason: "wrong_form" };
|
|
78
94
|
if (claims.tenant !== tenantId) return { ok: false, reason: "wrong_tenant" };
|
|
79
95
|
const age = nowMs - claims.issuedAt;
|
|
80
96
|
if (age < CONTACT_TOKEN_MIN_AGE_MS) return { ok: false, reason: "too_early" };
|
|
@@ -34,6 +34,7 @@ import {
|
|
|
34
34
|
evaluateLoginGate,
|
|
35
35
|
isApiPath,
|
|
36
36
|
isAppCredentialRequest,
|
|
37
|
+
isHoldReadBearerRequest,
|
|
37
38
|
isAppTokenPath,
|
|
38
39
|
isAuthPath,
|
|
39
40
|
isAdminPath,
|
|
@@ -124,6 +125,7 @@ async function serveControlPlaneInScope(input: ControlPlaneInput): Promise<Respo
|
|
|
124
125
|
// a Sign-in button (auth paths are exempt so sign-in itself is reachable). The
|
|
125
126
|
// grant `resource` is the tenant's appDomain — never input.
|
|
126
127
|
let appTestStage = false;
|
|
128
|
+
let holdReadBearer = false;
|
|
127
129
|
if (input.hostLoginGated && !input.internalContentGrant) {
|
|
128
130
|
// From the platform registry by id, NOT off `tenant` — that object resolves
|
|
129
131
|
// from TENANT_CACHE KV first, so a record written before this field existed
|
|
@@ -187,6 +189,11 @@ async function serveControlPlaneInScope(input: ControlPlaneInput): Promise<Respo
|
|
|
187
189
|
authorization: request.headers.get("authorization"),
|
|
188
190
|
formGrantType,
|
|
189
191
|
});
|
|
192
|
+
holdReadBearer = isHoldReadBearerRequest({
|
|
193
|
+
method: request.method,
|
|
194
|
+
renderPath,
|
|
195
|
+
authorization: request.headers.get("authorization"),
|
|
196
|
+
});
|
|
190
197
|
}
|
|
191
198
|
|
|
192
199
|
// Canonical admin tenant landing: an AUTHENTICATED viewer who is not a
|
|
@@ -234,6 +241,7 @@ async function serveControlPlaneInScope(input: ControlPlaneInput): Promise<Respo
|
|
|
234
241
|
// The publication render path, never the raw request path.
|
|
235
242
|
renderPath,
|
|
236
243
|
appCredential: appTestStage,
|
|
244
|
+
holdReadBearer,
|
|
237
245
|
});
|
|
238
246
|
if (decision.action === "redirect") {
|
|
239
247
|
// Admin and the cockpit hard-redirect to sign-in rather than rendering the
|
|
@@ -36,7 +36,7 @@ import { visitorRegionFor, withVisitorRegionCookie } from "@/lib/compliance/shar
|
|
|
36
36
|
import { tryServeStaticBundle } from "./staticBundle.js";
|
|
37
37
|
import { resolveCandidateContentPin } from "./candidatePin.js";
|
|
38
38
|
import { resolveRequestPreviewContext } from "./previewContext.js";
|
|
39
|
-
import { parseGateMode } from "@/lib/access/auth/loginGate";
|
|
39
|
+
import { isHoldReadBearerRequest, parseGateMode } from "@/lib/access/auth/loginGate";
|
|
40
40
|
import { evaluateDemoGate, hostInGateList } from "@/lib/access/shared/demoGate";
|
|
41
41
|
import { isMaintenanceOn, maintenanceResponse } from "@/lib/access/shared/maintenance";
|
|
42
42
|
import { HEALTH_PATH, healthResponse } from "@/lib/observability/shared/health";
|
|
@@ -59,7 +59,7 @@ import {
|
|
|
59
59
|
import { mirrorBalanceKey, parseMirrorBalances, publicMirrorStage } from "@/lib/inventory/mirrorBalanceProjection";
|
|
60
60
|
import { serveControlPlane } from "./controlPlane.js";
|
|
61
61
|
import { KvSessionStore, readSession, SESSION_COOKIE } from "@/lib/access/auth/session";
|
|
62
|
-
import { agentMayReach, agentSessionGateRefusal } from "@/lib/access/auth/agentSessionGate";
|
|
62
|
+
import { agentMayReach, agentSessionGateRefusal, holdReadMixedCredentialsRefusal } from "@/lib/access/auth/agentSessionGate";
|
|
63
63
|
import { mintOpaqueBrokerAssertion } from "@/lib/access/auth/brokerAssertion";
|
|
64
64
|
import {
|
|
65
65
|
applyInternalContentResponsePolicy,
|
|
@@ -132,10 +132,15 @@ async function agentGate(
|
|
|
132
132
|
if (!context.request.headers.get("cookie")) return null;
|
|
133
133
|
const sid = context.cookies.get(SESSION_COOKIE)?.value ?? null;
|
|
134
134
|
if (!sid) return null;
|
|
135
|
+
// The hold-reasons read takes a bearer or a cookie session, never both: this combination is
|
|
136
|
+
// refused before the cookie's session is looked up, so the cookie cannot decide the outcome.
|
|
137
|
+
if (isHoldReadBearerRequest({ method, renderPath, authorization: context.request.headers.get("authorization") })) {
|
|
138
|
+
return holdReadMixedCredentialsRefusal();
|
|
139
|
+
}
|
|
135
140
|
const sessionKv = await readKv("SESSION");
|
|
136
141
|
if (!sessionKv) return null;
|
|
137
142
|
const session = await readSession(new KvSessionStore(sessionKv), sid, Math.floor(Date.now() / 1000));
|
|
138
|
-
return agentSessionGateRefusal(session, method, renderPath);
|
|
143
|
+
return agentSessionGateRefusal(session, method, renderPath, await readEnv("COMMERCE_STAGE"));
|
|
139
144
|
}
|
|
140
145
|
|
|
141
146
|
async function serveRequest(
|