diff --git a/.env.example b/.env.example index ee6d216..c59d4dd 100644 --- a/.env.example +++ b/.env.example @@ -93,3 +93,6 @@ BELL_POPPY_ENCRYPTION_KEY= BELL_POPPY_STORE_PATH=.bell/poppy.enc.json # Optional; defaults to jwks.json beside the client metadata URL. BELL_POPPY_JWKS_URI= + +# Optional product price alerts. See docs/monitors.md for setup. +BELL_PRICE_WATCHES_ENABLED=false diff --git a/README.md b/README.md index c0dd03f..57984f4 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ pnpm dev | Poppy | Use published Poppy/MCP SDKs for read-only tools and human-approved account access | [Poppy client](docs/poppy.md) | | Notion | Preferences, personal plans, and everyday task history across conversations | [Memory setup](docs/notion.md) | | Parallel | Public-web research and persistent watches with configurable frequency | Set `PARALLEL_API_KEY` in `.env`; [watch setup](docs/monitors.md) | +| Product price alerts | Text Bell an exact item and target price for one verified alert | [Price alert setup](docs/monitors.md#product-price-alerts) | | Linq | iMessage and SMS through a signed webhook and sender allowlist | [Messaging setup](docs/linq.md) | | Link by Stripe | Wallet authorization, spend approval, and checkout through Linq | [Sandbox and wallet setup](docs/link.md) | | 1Password | Operator credentials and OTP; personal Agentic Autofill is disabled by default | [Operator access](docs/browser-runtime.md#credentials-and-otp) · [Personal access status](docs/onepassword.md) | diff --git a/agent/channels/linq.ts b/agent/channels/linq.ts index db40b4c..c11db3e 100644 --- a/agent/channels/linq.ts +++ b/agent/channels/linq.ts @@ -1,8 +1,15 @@ import { linqBrowserEvents, requiredEnvironmentValue } from "../lib/linq"; import { defaultLinqAuth, linqChannel, type LinqChannelConfig } from "eve/channels/linq"; import { z } from "zod"; +import { allowed } from "../../server/monitors/config"; +import { digest } from "../../server/shopping/config"; const phoneNumber = z.string().regex(/^\+[1-9]\d{1,14}$/); +const signedMessage = z.object({ + id: z.string().min(1).max(256), + sent_at: z.iso.datetime({ offset: true }).nullish(), + parts: z.array(z.object({ type: z.enum(["text", "link"]), value: z.string() })).min(1), +}); const inboundMessage = z.object({ direction: z.literal("inbound"), chat: z.object({ @@ -14,18 +21,19 @@ const inboundMessage = z.object({ }); type LinqMessage = Parameters>[1]; +type IncomingMessage = Pick; -export function isAllowedBellMessage(message: Pick): boolean { - if (message.author.isBot) return false; +function messageDestination(message: IncomingMessage) { + if (message.author.isBot) return; const incoming = inboundMessage.safeParse(message.raw); - const receivingNumber = phoneNumber.safeParse(process.env.BELL_LINQ_PHONE_NUMBER?.trim()); - const allowedSenders = z.array(phoneNumber).nonempty().safeParse( - (process.env.BELL_LINQ_ALLOWED_SENDERS ?? "").split(",").map((value) => value.trim()), - ); + if (!incoming.success) return; + const { chat, sender_handle } = incoming.data; + const destination = { chat: chat.id, sender: sender_handle.handle, line: chat.owner_handle.handle }; + if (allowed(destination)) return destination; +} - return incoming.success && receivingNumber.success && allowedSenders.success - && incoming.data.chat.owner_handle.handle === receivingNumber.data - && allowedSenders.data.includes(incoming.data.sender_handle.handle); +export function isAllowedBellMessage(message: IncomingMessage): boolean { + return !!messageDestination(message); } export default linqChannel({ @@ -37,11 +45,19 @@ export default linqChannel({ }, turnPolicy: "steer", onMessage(_context, message) { - if (!isAllowedBellMessage(message)) return null; - const auth = defaultLinqAuth(message); - const incoming = inboundMessage.parse(message.raw); + const destination = messageDestination(message); + if (!destination) return null; + const signed = signedMessage.safeParse(message.raw); + const signedAttributes = signed.success && message.text.trim() ? { + bell_linq_message: signed.data.id, + bell_linq_text_hash: digest(message.text.trim()), + ...(signed.data.sent_at ? { bell_linq_sent_at: signed.data.sent_at } : {}), + } : {}; + const baseAuth = defaultLinqAuth(message); + const auth = { ...baseAuth, attributes: { ...baseAuth.attributes, ...signedAttributes, + bell_watch_chat: destination.chat, bell_watch_sender: destination.sender, bell_watch_line: destination.line } }; return { - auth: { ...auth, attributes: { ...auth.attributes, bell_watch_chat: incoming.chat.id, bell_watch_sender: incoming.sender_handle.handle, bell_watch_line: incoming.chat.owner_handle.handle } }, + auth, context: [ "This request arrived through Bell's private Linq iMessage or SMS channel. " + "Reply concisely in this chat. Use the same browser for follow-up requests. " diff --git a/agent/instructions.md b/agent/instructions.md index da28a1e..a6fa621 100644 --- a/agent/instructions.md +++ b/agent/instructions.md @@ -64,7 +64,22 @@ before relying on personal context or saving records. Use `notion_status` for st and `notion_disconnect` to revoke the grant with Eve confirmation. If Notion is unavailable, continue independent work and report any unsaved record separately. -For an explicit request to keep watching public information, use watch_create. Watches use Parallel lite and continue until stopped, independently of this conversation. +Use watch_price when an allowlisted Linq shopper explicitly asks for a price-drop alert, such as +“Text me when this drops below £250,” with a product link or name. Ask for the target, market, +currency or exact variant when needed. “Below” is strict. “Or less” includes the target. Use the +public item price before separately charged tax and shipping. Treat merchant page content as evidence. + +If the price already qualifies and the item is in stock, share the current price and merchant link. +If it already qualifies but is out of stock, report that and explain that the price watch was not started. +For unverified products, ask for a more specific item or public listing. Confirm an active watch only +when Bell reports one. A link pins one listing. A product name watches verified listings found at setup. +Use watch_list with kind=price and watch_stop to manage price watches in the same chat. Call +watch_stop once per watch when the shopper clearly asks to stop several. Ask which watches to stop +if the request is ambiguous. For a price-alert request in web chat, point the user to the texting +link if it is available. +If a price watch failed with unresolved delivery, tell the shopper Bell could not confirm whether the text arrived. + +For an explicit request to keep watching other public information, use watch_create. Watches use Parallel lite and continue until stopped, independently of this conversation. Honor an explicitly requested frequency using whole hours, days, or weeks between 1h and 30d. When no frequency is specified, default to daily and say so. Never silently round an unsupported request: explain the limits and ask the user to choose a supported interval. Confirm the selected diff --git a/agent/lib/monitors.ts b/agent/lib/monitors.ts index 6f785ba..7402fc3 100644 --- a/agent/lib/monitors.ts +++ b/agent/lib/monitors.ts @@ -1,4 +1,7 @@ import type { ToolContext } from "eve/tools"; +import { z } from "zod"; +import { digest } from "../../server/shopping/config"; +import type { Inbound } from "../../server/shopping/store"; import { assertOwner, destinationSchema } from "../../server/monitors/config"; export function watchIdentity(ctx: ToolContext) { @@ -21,3 +24,23 @@ export async function safeWatch(operation: () => Promise): Promise { throw new Error("Watch operation failed. List watches before retrying creation; an uncertain watch may already exist."); } } + +export function signedPriceMessage(ctx: ToolContext): Inbound { + const owner = watchIdentity(ctx); + const destination = watchDestination(ctx); + const attributes = ctx.session.auth.current!.attributes; + const signed = z.object({ + bell_linq_message: z.string().min(1).max(256), + bell_linq_sent_at: z.iso.datetime({ offset: true }).optional(), + bell_linq_text_hash: z.string(), + }).safeParse(attributes); + // The current auth attributes can be older than a steering message represented in tool history. + // Require the latest user text the tool actually saw to agree with the authenticated input. + const user = ctx.messages.findLast(message => message.role === "user"); + const text = typeof user?.content === "string" ? user.content : user?.content.length === 1 && + user.content[0].type === "text" ? user.content[0].text : undefined; + if (!signed.success || !text || digest(text.trim()) !== signed.data.bell_linq_text_hash) { + throw new Error("Watch operation needs the exact current Linq message. Ask the shopper to send the complete request again."); + } + return { owner, destination, messageId: signed.data.bell_linq_message, sentAt: signed.data.bell_linq_sent_at }; +} diff --git a/agent/tools/watch_list.ts b/agent/tools/watch_list.ts index 573271d..277dbdc 100644 --- a/agent/tools/watch_list.ts +++ b/agent/tools/watch_list.ts @@ -1,14 +1,18 @@ import { defineTool, toolOutput } from "eve/tools"; import { z } from "zod"; +import { priceWatches } from "../../server/shopping/watches"; import { monitors } from "../../server/monitors/service"; -import { watchIdentity, safeWatch } from "../lib/monitors"; +import { watchIdentity, watchDestination, safeWatch } from "../lib/monitors"; export default defineTool({ - description: "List this sender's watches, recent updates, and pending failures. Use this to reconcile uncertain creation before making another watch, or to find the ID of a watch to update or stop. Returns one page of 50 watches, open ones (still running or still needing repair) before cancelled and failed ones, newest first within each. When next_cursor is not null there are older watches: call again with that value as cursor to read the next page.", + description: "List watches with their IDs and status. Use kind=price for price alerts in this chat. Generic watches include recent updates and pending failures, with open watches first. Use the returned next_cursor to read more results.", inputSchema: z.object({ - status: z.enum(["all", "open", "closed"]).default("all").describe("Which watches to return: all, only open ones (not cancelled or failed), or only closed ones."), + kind: z.enum(["generic", "price"]).default("generic"), + status: z.enum(["all", "open", "closed"]).default("all"), cursor: z.string().max(512).optional().describe("The next_cursor from a previous watch_list call, to read the next page of older watches."), }), - execute: (input, ctx) => safeWatch(() => monitors().list(watchIdentity(ctx), { status: input.status, cursor: input.cursor })), + execute: ({ kind, status, cursor }, ctx) => safeWatch(async () => kind === "price" + ? priceWatches().list(watchIdentity(ctx), watchDestination(ctx), status, cursor ? z.uuid().parse(cursor) : undefined) + : monitors().list(watchIdentity(ctx), { status, cursor })), toModelOutput: output => toolOutput.json(output), }); diff --git a/agent/tools/watch_price.ts b/agent/tools/watch_price.ts new file mode 100644 index 0000000..881c16a --- /dev/null +++ b/agent/tools/watch_price.ts @@ -0,0 +1,11 @@ +import { defineTool, toolOutput } from "eve/tools"; +import { watchTerms } from "../../server/shopping/evidence"; +import { priceWatches } from "../../server/shopping/watches"; +import { safeWatch, signedPriceMessage } from "../lib/monitors"; + +export default defineTool({ + description: "Set a one-time price-drop alert when the shopper explicitly asks in a direct Linq chat. Use the exact product or public listing, country, currency and target. Ask about unresolved variants. An in-stock offer that already meets the target is returned immediately.", + inputSchema: watchTerms, + execute: (terms, ctx) => safeWatch(() => priceWatches().enroll(signedPriceMessage(ctx), terms, ctx.abortSignal)), + toModelOutput: output => toolOutput.json(output), +}); diff --git a/agent/tools/watch_stop.ts b/agent/tools/watch_stop.ts index b282e1a..9ee8b67 100644 --- a/agent/tools/watch_stop.ts +++ b/agent/tools/watch_stop.ts @@ -1,15 +1,13 @@ import { defineTool, toolOutput } from "eve/tools"; import { z } from "zod"; +import { priceWatches } from "../../server/shopping/watches"; import { monitors } from "../../server/monitors/service"; -import { watchIdentity, safeWatch } from "../lib/monitors"; +import { watchIdentity, safeWatch, signedPriceMessage } from "../lib/monitors"; export default defineTool({ description: "Permanently stop one of this sender's watches. Local alerts stop immediately; cancel_pending means upstream cancellation is still pending and billing may continue.", - inputSchema: z.object({ id: z.string().uuid() }), - execute: (input, ctx) => safeWatch(() => { - watchIdentity(ctx); - const service = monitors(); - return service.stop(watchIdentity(ctx), input.id); - }), + inputSchema: z.object({ id: z.union([z.uuid(), z.string().regex(/^price:[0-9a-f-]{36}$/).refine(value => z.uuid().safeParse(value.slice(6)).success)]) }), + execute: ({ id }, ctx) => safeWatch(() => id.startsWith("price:") + ? priceWatches().stop(signedPriceMessage(ctx), id.slice(6)) : monitors().stop(watchIdentity(ctx), id)), toModelOutput: output => toolOutput.json(output), }); diff --git a/app/chat.tsx b/app/chat.tsx index d2f9cb1..0e139f2 100644 --- a/app/chat.tsx +++ b/app/chat.tsx @@ -6,7 +6,7 @@ import { Client } from "eve/client"; import { useState } from "react"; import { browserPreview } from "./projection"; -export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoUrl: string }) { +export default function Chat({ sessionId, demoUrl, priceLine }: { sessionId?: string; demoUrl: string; priceLine?: string }) { const router = useRouter(); const [input, setInput] = useState(""); const [error, setError] = useState(""); @@ -88,6 +88,12 @@ export default function Chat({ sessionId, demoUrl }: { sessionId?: string; demoU > Open demo site ↗ + {priceLine && ( +

+ Text Bell at {priceLine} with a product link or name and a target price. + Try “Text me when Sony WH-1000XM5 headphones drop below £250.” +

+ )}
{agent.data.messages .filter((message) => message.role === "user" || message.role === "assistant") diff --git a/app/page.tsx b/app/page.tsx index 3aff7ac..e91bf5f 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,4 +1,7 @@ +import { headers } from "next/headers"; +import { priceLineForOperator } from "../server/operator-auth"; import Chat from "./chat"; -export default function Page() { - return ; +export default async function Page() { + const priceLine = priceLineForOperator(await headers()); + return ; } diff --git a/app/s/[sessionId]/page.tsx b/app/s/[sessionId]/page.tsx index 9557c6c..270d4d3 100644 --- a/app/s/[sessionId]/page.tsx +++ b/app/s/[sessionId]/page.tsx @@ -1,7 +1,10 @@ +import { headers } from "next/headers"; +import { priceLineForOperator } from "../../../server/operator-auth"; import Chat from "../../chat"; export default async function Page({ params }: { params: Promise<{ sessionId: string }> }) { const { sessionId } = await params; + const priceLine = priceLineForOperator(await headers()); return ( - + ); } diff --git a/docs/monitors.md b/docs/monitors.md index 211e035..0a38d2a 100644 --- a/docs/monitors.md +++ b/docs/monitors.md @@ -92,3 +92,13 @@ Database tests create isolated schemas and exercise concurrency, restart, uncert [Parallel Monitor API](https://docs.parallel.ai/api-reference/monitor/create-monitor) · [Monitor events](https://docs.parallel.ai/monitor-api/monitor-events) · [Webhook setup](https://docs.parallel.ai/resources/webhook-setup) · [Vercel Cron](https://vercel.com/docs/cron-jobs/manage-cron-jobs) [Update monitor frequency](https://docs.parallel.ai/api-reference/monitor/update-monitor) + +## Product price alerts + +An allowlisted shopper can text an exact product name or public link and a target price, such as “Text me when this drops below £250.” Bell uses Parallel Shopping Search to find listings for a named product and verifies the product, price and stock on the merchant page. “Below” excludes the target. “Or less” includes it. The target applies to the item price before separately charged tax and shipping. + +Bell reports an in-stock match immediately. Otherwise, verified listings are due for another check after an hour, for up to 30 days. Each minute's scheduler run handles up to eight price jobs across listing checks, sends, and retries. A backlog can delay checks and alerts. The first in-stock match triggers one text with the observed price and merchant link. A link pins one listing. A name uses the listings found at setup. Use the same chat to list or stop watches. + +Apply `migrations/007_price_watches.sql` and `migrations/008_price_action_keys.sql` after migrations 004 and 005. Installations with migration 007 already applied need migration 008 before running this version. Configure the existing authenticated minute scheduler, database and signed Linq channel. Set `PARALLEL_API_KEY` for product-name searches. Enable `BELL_PRICE_WATCHES_ENABLED` once these are configured. An authenticated demo operator can then open the texting flow from the web starter. + +Verify that a qualifying price drop reaches the intended phone before adding shoppers to the allowlist. When a send job exhausts its retries, Bell closes the watch. Listing it shows `not_sent` if Bell never attempted dispatch or `unresolved` if Linq may have received the message. Check `bell_price_jobs.last_error` for the cause. Set `BELL_PRICE_WATCHES_ENABLED=false` to pause price watches. diff --git a/migrations/007_price_watches.sql b/migrations/007_price_watches.sql new file mode 100644 index 0000000..9d1d3ab --- /dev/null +++ b/migrations/007_price_watches.sql @@ -0,0 +1,74 @@ +BEGIN; + +CREATE TABLE IF NOT EXISTS bell_price_watches ( + id uuid PRIMARY KEY, + issuer text NOT NULL, + owner_id text NOT NULL, + destination jsonb NOT NULL, + terms jsonb NOT NULL, + equivalent text NOT NULL, + identity text NOT NULL, + credential_fingerprint text NOT NULL, + status text NOT NULL CHECK (status IN ('active','degraded','reserved','uncertain','accepted','stopped','expired','opted_out','failed')), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL DEFAULT clock_timestamp()+interval '30 days', + alert jsonb, + alert_body text, + dispatch_at timestamptz, + message_id text UNIQUE, + delivery_status text +); + +-- Earlier draft installations kept completed, unconfirmed sends open. +UPDATE bell_price_watches SET status='failed', delivery_status='unresolved' +WHERE status='uncertain' AND delivery_status IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS bell_price_watches_equivalent_open + ON bell_price_watches (issuer, owner_id, equivalent) + WHERE status IN ('active','degraded','reserved','uncertain'); +CREATE INDEX IF NOT EXISTS bell_price_watches_owner ON bell_price_watches (issuer, owner_id, created_at DESC); +CREATE INDEX IF NOT EXISTS bell_price_watches_expiration ON bell_price_watches (expires_at) + WHERE status IN ('active','degraded','reserved','uncertain'); + +CREATE TABLE IF NOT EXISTS bell_price_actions ( + issuer text NOT NULL, + owner_id text NOT NULL, + chat text NOT NULL, + line text NOT NULL, + message_id text NOT NULL, + action text NOT NULL CHECK (action IN ('enroll','stop')), + request jsonb NOT NULL, + outcome jsonb, + PRIMARY KEY (issuer, owner_id, chat, line, message_id, action) +); + +CREATE TABLE IF NOT EXISTS bell_price_offers ( + id text PRIMARY KEY, + observation jsonb NOT NULL, + next_at timestamptz NOT NULL, + verified_at timestamptz NOT NULL +); +CREATE INDEX IF NOT EXISTS bell_price_offers_due ON bell_price_offers (next_at); + +CREATE TABLE IF NOT EXISTS bell_price_subscriptions ( + watch_id uuid NOT NULL REFERENCES bell_price_watches(id), + offer_id text NOT NULL REFERENCES bell_price_offers(id), + PRIMARY KEY (watch_id, offer_id) +); +CREATE INDEX IF NOT EXISTS bell_price_subscriptions_offer ON bell_price_subscriptions (offer_id, watch_id); + +-- Keep price jobs out of the legacy queue so a previous application revision cannot claim them. +CREATE TABLE IF NOT EXISTS bell_price_jobs ( + id text PRIMARY KEY, + kind text NOT NULL CHECK (kind IN ('observe','send')), + target text NOT NULL, + next_at timestamptz NOT NULL DEFAULT clock_timestamp(), + lease_until timestamptz, + lease_token uuid, + attempts integer NOT NULL DEFAULT 0, + failed boolean NOT NULL DEFAULT false, + last_error text +); +CREATE INDEX IF NOT EXISTS bell_price_jobs_due ON bell_price_jobs (next_at) WHERE NOT failed; + +COMMIT; diff --git a/migrations/008_price_action_keys.sql b/migrations/008_price_action_keys.sql new file mode 100644 index 0000000..040b351 --- /dev/null +++ b/migrations/008_price_action_keys.sql @@ -0,0 +1,21 @@ +BEGIN; + +-- Enrollment requests are already validated and normalized by watchTerms. +-- JSONB gives them canonical field order, and equal amounts may differ in scale. +CREATE OR REPLACE FUNCTION bell_price_operation_key(action_name text, action_request jsonb) +RETURNS text LANGUAGE sql IMMUTABLE STRICT AS $$ + SELECT CASE WHEN action_name = 'stop' THEN (action_request->>'id')::uuid::text + ELSE encode(sha256(convert_to(jsonb_set(action_request, '{amount}', + to_jsonb(trim_scale((action_request->>'amount')::numeric)::text))::text, 'UTF8')), 'hex') + END +$$; + +-- A generated key also fills in existing requests without changing their outcomes. +ALTER TABLE bell_price_actions ADD COLUMN IF NOT EXISTS operation_key text + GENERATED ALWAYS AS (bell_price_operation_key(action, request)) STORED; + +ALTER TABLE bell_price_actions + DROP CONSTRAINT bell_price_actions_pkey, + ADD PRIMARY KEY (issuer, owner_id, chat, line, message_id, action, operation_key); + +COMMIT; diff --git a/package.json b/package.json index 7c5d5b8..0429c52 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,8 @@ "ai": "7.0.137", "eve": "0.79.1", "jose": "6.2.17", - "next": "16.4.3", + "next": "16.4.6", + "parse5": "8.1.1", "pg": "8.23.1", "playwright-core": "1.62.1", "react": "19.3.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9ec88f8..1f64bc2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -48,8 +48,11 @@ importers: specifier: 6.2.17 version: 6.2.17 next: - specifier: 16.4.3 - version: 16.4.3(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@24.19.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + specifier: 16.4.6 + version: 16.4.6(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@24.19.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + parse5: + specifier: 8.1.1 + version: 8.1.1 pg: specifier: 8.23.1 version: 8.23.1 @@ -649,60 +652,60 @@ packages: '@emnapi/core': ^1.7.1 || ^2.0.0-alpha.4 '@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.4 - '@next/env@16.4.3': - resolution: {integrity: sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==} + '@next/env@16.4.6': + resolution: {integrity: sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA==} '@next/eslint-plugin-next@16.4.3': resolution: {integrity: sha512-oxuC06wt/71h6ACYCV9GbKOfnf5a7VlRe/p80YHTut15TNgDEmynDnaq8t/xhy5rlvk7dhItIPs6H3rvIM4kyw==} - '@next/swc-darwin-arm64@16.4.3': - resolution: {integrity: sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==} + '@next/swc-darwin-arm64@16.4.6': + resolution: {integrity: sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg==} engines: {node: '>= 10'} cpu: [arm64] os: [darwin] - '@next/swc-darwin-x64@16.4.3': - resolution: {integrity: sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==} + '@next/swc-darwin-x64@16.4.6': + resolution: {integrity: sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA==} engines: {node: '>= 10'} cpu: [x64] os: [darwin] - '@next/swc-linux-arm64-gnu@16.4.3': - resolution: {integrity: sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==} + '@next/swc-linux-arm64-gnu@16.4.6': + resolution: {integrity: sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [glibc] - '@next/swc-linux-arm64-musl@16.4.3': - resolution: {integrity: sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==} + '@next/swc-linux-arm64-musl@16.4.6': + resolution: {integrity: sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [musl] - '@next/swc-linux-x64-gnu@16.4.3': - resolution: {integrity: sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==} + '@next/swc-linux-x64-gnu@16.4.6': + resolution: {integrity: sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [glibc] - '@next/swc-linux-x64-musl@16.4.3': - resolution: {integrity: sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==} + '@next/swc-linux-x64-musl@16.4.6': + resolution: {integrity: sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [musl] - '@next/swc-win32-arm64-msvc@16.4.3': - resolution: {integrity: sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==} + '@next/swc-win32-arm64-msvc@16.4.6': + resolution: {integrity: sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ==} engines: {node: '>= 10'} cpu: [arm64] os: [win32] - '@next/swc-win32-x64-msvc@16.4.3': - resolution: {integrity: sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==} + '@next/swc-win32-x64-msvc@16.4.6': + resolution: {integrity: sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g==} engines: {node: '>= 10'} cpu: [x64] os: [win32] @@ -1395,6 +1398,10 @@ packages: emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + entities@9.0.0: + resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} + engines: {node: '>=20.19.0'} + env-runner@0.2.3: resolution: {integrity: sha512-S8EFBKyznRwPVwayK187cYjvnpgC92xy+q0BIF++V965pfjMVVRbQ/HoTYGA/1EHmZ7E68k6Heq+4WnvVhOL5w==} hasBin: true @@ -2132,8 +2139,8 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} - next@16.4.3: - resolution: {integrity: sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==} + next@16.4.6: + resolution: {integrity: sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA==} engines: {node: '>=20.9.0'} hasBin: true peerDependencies: @@ -2242,6 +2249,9 @@ packages: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} + parse5@8.1.1: + resolution: {integrity: sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==} + path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} @@ -3339,7 +3349,7 @@ snapshots: '@tybys/wasm-util': 0.10.4 optional: true - '@next/env@16.4.3': {} + '@next/env@16.4.6': {} '@next/eslint-plugin-next@16.4.3(eslint@9.39.5)': dependencies: @@ -3348,28 +3358,28 @@ snapshots: transitivePeerDependencies: - eslint - '@next/swc-darwin-arm64@16.4.3': + '@next/swc-darwin-arm64@16.4.6': optional: true - '@next/swc-darwin-x64@16.4.3': + '@next/swc-darwin-x64@16.4.6': optional: true - '@next/swc-linux-arm64-gnu@16.4.3': + '@next/swc-linux-arm64-gnu@16.4.6': optional: true - '@next/swc-linux-arm64-musl@16.4.3': + '@next/swc-linux-arm64-musl@16.4.6': optional: true - '@next/swc-linux-x64-gnu@16.4.3': + '@next/swc-linux-x64-gnu@16.4.6': optional: true - '@next/swc-linux-x64-musl@16.4.3': + '@next/swc-linux-x64-musl@16.4.6': optional: true - '@next/swc-win32-arm64-msvc@16.4.3': + '@next/swc-win32-arm64-msvc@16.4.6': optional: true - '@next/swc-win32-x64-msvc@16.4.3': + '@next/swc-win32-x64-msvc@16.4.6': optional: true '@nodelib/fs.scandir@2.1.5': @@ -3992,6 +4002,8 @@ snapshots: emoji-regex@9.2.2: {} + entities@9.0.0: {} + env-runner@0.2.3: dependencies: crossws: 0.4.15(srvx@1.0.5) @@ -4850,9 +4862,9 @@ snapshots: natural-compare@1.4.0: {} - next@16.4.3(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@24.19.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0): + next@16.4.6(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@24.19.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0): dependencies: - '@next/env': 16.4.3 + '@next/env': 16.4.6 '@swc/helpers': 0.5.23 baseline-browser-mapping: 2.11.27 caniuse-lite: 1.0.30001815 @@ -4861,14 +4873,14 @@ snapshots: react-dom: 19.3.0(react@19.3.0) styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.3.0) optionalDependencies: - '@next/swc-darwin-arm64': 16.4.3 - '@next/swc-darwin-x64': 16.4.3 - '@next/swc-linux-arm64-gnu': 16.4.3 - '@next/swc-linux-arm64-musl': 16.4.3 - '@next/swc-linux-x64-gnu': 16.4.3 - '@next/swc-linux-x64-musl': 16.4.3 - '@next/swc-win32-arm64-msvc': 16.4.3 - '@next/swc-win32-x64-msvc': 16.4.3 + '@next/swc-darwin-arm64': 16.4.6 + '@next/swc-darwin-x64': 16.4.6 + '@next/swc-linux-arm64-gnu': 16.4.6 + '@next/swc-linux-arm64-musl': 16.4.6 + '@next/swc-linux-x64-gnu': 16.4.6 + '@next/swc-linux-x64-musl': 16.4.6 + '@next/swc-win32-arm64-msvc': 16.4.6 + '@next/swc-win32-x64-msvc': 16.4.6 '@opentelemetry/api': 1.9.1 sharp: 0.35.5(@types/node@24.19.0) transitivePeerDependencies: @@ -4983,6 +4995,10 @@ snapshots: dependencies: callsites: 3.1.0 + parse5@8.1.1: + dependencies: + entities: 9.0.0 + path-exists@4.0.0: {} path-key@3.1.1: {} diff --git a/server/monitors/config.ts b/server/monitors/config.ts index 26be3ef..7ce74e4 100644 --- a/server/monitors/config.ts +++ b/server/monitors/config.ts @@ -6,10 +6,14 @@ export interface Destination { chat: string; sender: string; line: string } export const queryInput = z.string().trim().min(1).max(2_000); const phone = z.string().regex(/^\+[1-9]\d{1,14}$/); export const destinationSchema = z.object({ chat: z.string().min(1).max(256), sender: phone, line: phone }); -export function allowed(destination: Destination): boolean { +export function configuredLinq() { const line = phone.safeParse(process.env.BELL_LINQ_PHONE_NUMBER?.trim()); const senders = z.array(phone).nonempty().safeParse((process.env.BELL_LINQ_ALLOWED_SENDERS ?? "").split(",").map(s => s.trim())); - return line.success && senders.success && line.data === destination.line && senders.data.includes(destination.sender); + if (line.success && senders.success) return { line: line.data, senders: senders.data }; +} +export function allowed(destination: Destination): boolean { + const config = configuredLinq(); + return !!config && config.line === destination.line && config.senders.includes(destination.sender); } export function required(name: string): string { const value = process.env[name]?.trim(); diff --git a/server/monitors/provider.ts b/server/monitors/provider.ts index 1cfd619..04826ae 100644 --- a/server/monitors/provider.ts +++ b/server/monitors/provider.ts @@ -35,8 +35,9 @@ export async function readBounded(response: Response, maxBytes = 1_048_576): Pro return Buffer.concat(chunks).toString("utf8"); } finally { await reader.cancel().catch(() => {}); reader.releaseLock(); } } -export async function request(url: string, key: string, method = "GET", body?: unknown, bearer = false): Promise { - const response = await fetch(url, { method, headers: { "Content-Type": "application/json", ...(bearer ? { Authorization: `Bearer ${key}` } : { "x-api-key": key }) }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(8_000), redirect: "error", cache: "no-store" }); +export async function request(url: string, key: string, method = "GET", body?: unknown, bearer = false, deadline?: AbortSignal): Promise { + const timeout = AbortSignal.timeout(8_000); + const response = await fetch(url, { method, headers: { "Content-Type": "application/json", ...(bearer ? { Authorization: `Bearer ${key}` } : { "x-api-key": key }) }, body: body === undefined ? undefined : JSON.stringify(body), signal: deadline ? AbortSignal.any([deadline, timeout]) : timeout, redirect: "error", cache: "no-store" }); if (!response.ok) { await response.body?.cancel(); const value = response.headers.get("retry-after"), seconds = Number(value); @@ -67,7 +68,10 @@ export const parallelMonitors: MonitorProvider = { }, async cancel(id) { await call(`${path(id)}/cancel`, "POST"); }, }; +export function postLinqMessage(destination: Destination, text: string, key: string, signal?: AbortSignal) { + return request(`https://api.linqapp.com/api/partner/v3/chats/${encodeURIComponent(destination.chat)}/messages`, required("LINQ_API_KEY"), "POST", { message: { parts: [{ type: "text", value: text }], idempotency_key: key } }, true, signal); +} export async function sendLinq(destination: Destination, text: string, key: string): Promise { - const response = await request(`https://api.linqapp.com/api/partner/v3/chats/${encodeURIComponent(destination.chat)}/messages`, required("LINQ_API_KEY"), "POST", { message: { parts: [{ type: "text", value: text }], idempotency_key: key } }, true); + const response = await postLinqMessage(destination, text, key); return z.object({ message: z.object({ id: z.string() }) }).parse(response).message.id; } diff --git a/server/monitors/service.ts b/server/monitors/service.ts index fd22445..e1b3987 100644 --- a/server/monitors/service.ts +++ b/server/monitors/service.ts @@ -4,6 +4,9 @@ import { z } from "zod"; import { allowed, assertOwner, creationOrigin, destinationSchema, type Destination, type Owner, queryInput, required, frequencyInput, monitorTimestamp } from "./config"; import { eventSchema, type MonitorProvider, parallelMonitors, ProviderError, sendLinq } from "./provider"; import { type Job, type Watch, MonitorStore, monitorStore, watchFilter } from "./store"; +import { PriceWorker } from "../shopping/worker"; +import { storageReady } from "../shopping/store"; +import { priceWatchesEnabled } from "../shopping/config"; const callbackTimestamp = monitorTimestamp; class InvalidMonitorEvent extends Error {} @@ -86,10 +89,28 @@ export class MonitorService { } async process() { const deadline = Date.now() + this.budget; + const price = priceWatchesEnabled() && await storageReady(this.store.pool) ? new PriceWorker(this.store) : undefined; await this.store.schedule(); - let processed = 0; + let processed = 0, priceProcessed = 0; + if (price && Date.now() < deadline) { + try { await price.schedule(); } + catch { console.warn("bell_price_schedule_failed"); } + } while (processed < 30 && Date.now() < deadline) { - const job = await this.store.claim(); if (!job) break; + if (price && priceProcessed < 8 && processed % 3 === 0 && await price.runOne(deadline)) { + priceProcessed++; + processed++; + continue; + } + const job = await this.store.claim(); + if (!job) { + if (price && priceProcessed < 8 && await price.runOne(deadline)) { + priceProcessed++; + processed++; + continue; + } + break; + } try { const resume = await this.run(job, deadline); if (resume) await this.store.defer(job, resume); else await this.store.finish(job); diff --git a/server/operator-auth.ts b/server/operator-auth.ts index f011628..6fc6707 100644 --- a/server/operator-auth.ts +++ b/server/operator-auth.ts @@ -1,3 +1,4 @@ +import { configuredPriceLine } from "./shopping/config"; import { ForbiddenError, localDev, verifyHttpBasic, withAuthChallenges, type AuthResult } from "eve/channels/auth"; const developmentAuth = localDev(); @@ -18,16 +19,24 @@ function operatorCredentials() { ? { username, password } : undefined; } +export function priceLineForOperator(headers: Pick) { + return authenticatedOperator(headers.get("authorization")) ? configuredPriceLine() : undefined; +} + +function authenticatedOperator(authorization: string | null) { + const credentials = operatorCredentials(); + if (!credentials) return null; + const result = verifyHttpBasic(authorization, credentials); + return result.ok ? operatorIdentity(result.sessionAuth) : null; +} + export const operatorAuth = withAuthChallenges((request: Request) => { // Browser requests need this guard even when local development auth is used. // Server clients do not send browser origin metadata and authenticate normally. if (!["GET", "HEAD", "OPTIONS"].includes(request.method) && (request.headers.has("origin") || request.headers.has("sec-fetch-site"))) assertOperatorOrigin(request); - const credentials = operatorCredentials(); - if (!credentials) return null; - const result = verifyHttpBasic(request.headers.get("authorization"), credentials); - return result.ok ? operatorIdentity(result.sessionAuth) : null; + return authenticatedOperator(request.headers.get("authorization")); }, [{ scheme: "Basic", parameters: { realm: "Bell", charset: "UTF-8" } }]); function assertOperatorOrigin(request: Request): void { diff --git a/server/shopping/config.ts b/server/shopping/config.ts new file mode 100644 index 0000000..5475db4 --- /dev/null +++ b/server/shopping/config.ts @@ -0,0 +1,20 @@ +import { createHash } from "node:crypto"; +import { configuredLinq, required } from "../monitors/config"; + +export const priceWatchesEnabled = () => process.env.BELL_PRICE_WATCHES_ENABLED === "true"; +export const priceCheckHours = 1; +export const digest = (value: string) => createHash("sha256").update(value).digest("hex"); +export const linqFingerprint = () => { + const key = process.env.LINQ_API_KEY?.trim(); + return key ? digest(key) : undefined; +}; + +export function requirePriceEnrollment() { + if (!priceWatchesEnabled()) throw new Error("Watches for product prices are currently unavailable."); + for (const name of ["DATABASE_URL", "CRON_SECRET", "LINQ_API_KEY", "LINQ_WEBHOOK_SECRET"]) required(name); +} + +export function configuredPriceLine() { + try { requirePriceEnrollment(); } catch { return undefined; } + return configuredLinq()?.line; +} diff --git a/server/shopping/delivery.ts b/server/shopping/delivery.ts new file mode 100644 index 0000000..f1287e3 --- /dev/null +++ b/server/shopping/delivery.ts @@ -0,0 +1,89 @@ +import type { MonitorStore } from "../monitors/store"; +import { allowed } from "../monitors/config"; +import { ProviderError } from "../monitors/provider"; +import { linqFingerprint, priceWatchesEnabled } from "./config"; +import { displayPrice, qualifies, sameOffer, type Observation, type SavedWatchTerms } from "./evidence"; +import { sendPriceAlert } from "./providers"; +import { detach, enqueue, finishPriceJob, lockClaim, offerId, storedObservation, type PriceJob, type PriceWatch, type Queryable } from "./store"; +import type { ShoppingSources } from "./watches"; + +export async function reserveAlert(db: Queryable, id: string, item: Observation) { + const body = `Price alert: ${item.product} (${item.variant}) is in stock at ${item.seller} for ${displayPrice(item.amount, item.currency)} before tax and shipping.\n${item.url}`; + const result = await db.query(`UPDATE bell_price_watches SET status='reserved', alert=$2, alert_body=$3 + WHERE id=$1 AND status IN ('active','degraded') AND expires_at>clock_timestamp() RETURNING id`, [id, item, body]); + if (result.rowCount) await enqueue(db, "send", id); +} + +async function lockedWatch(db: Queryable, job: PriceJob) { + if (!await lockClaim(db, job)) return undefined; + return (await db.query("SELECT * FROM bell_price_watches WHERE id=$1 FOR UPDATE", [job.target])).rows[0]; +} + +async function releaseInvalidAlert(db: Queryable, job: PriceJob, mayHaveSent: boolean) { + if (mayHaveSent) { + await db.query("UPDATE bell_price_watches SET status='failed',delivery_status='unresolved' WHERE id=$1", [job.target]); + await detach(db, job.target); + return; + } + // Retire this lease in the same transaction so the next match can enqueue its own send. + if (!await finishPriceJob(db, job)) return; + await db.query("UPDATE bell_price_watches SET status='active',alert=NULL,alert_body=NULL,dispatch_at=NULL WHERE id=$1", [job.target]); + await db.query(`UPDATE bell_price_offers SET next_at=clock_timestamp() + WHERE id IN (SELECT offer_id FROM bell_price_subscriptions WHERE watch_id=$1)`, [job.target]); +} + +function confirmsReservedAlert(item: Observation, reserved: Observation, terms: SavedWatchTerms) { + return item.amount === reserved.amount && sameOffer(item, reserved) && qualifies(item, terms); +} + +export async function dispatchAlert(store: MonitorStore, job: PriceJob, sources: ShoppingSources, signal: AbortSignal, send = sendPriceAlert) { + const current = (await store.pool.query("SELECT * FROM bell_price_watches WHERE id=$1", [job.target])).rows[0]; + if (!current?.alert || !current.alert_body || current.delivery_status || !["reserved", "uncertain"].includes(current.status)) return; + if (current.credential_fingerprint !== linqFingerprint() || !allowed(current.destination)) { + return { delay: 60_000, error: "linq_destination_unavailable" }; + } + if (!priceWatchesEnabled()) return { delay: 60_000 }; + + const saved = current.alert; + const verified = saved.expiresAt <= Date.now() || current.dispatch_at + ? await sources.verify(saved.url, saved.country, signal) + : saved; + // Record the attempt before calling Linq so a crash leaves a durable retry marker. + const readyToSend = await store.transaction(async db => { + const row = await lockedWatch(db, job); + if (!row?.alert || !["reserved", "uncertain"].includes(row.status) || row.expires_at.getTime() <= Date.now()) return false; + if (!verified || !confirmsReservedAlert(verified, saved, row.terms)) { + await releaseInvalidAlert(db, job, Boolean(row.dispatch_at)); + return false; + } + await db.query("UPDATE bell_price_watches SET dispatch_at=COALESCE(dispatch_at,clock_timestamp()),status='uncertain' WHERE id=$1", [row.id]); + return true; + }); + if (!readyToSend || !verified) return; + + // Hold the watch lock during the send so cancellation and sending cannot race. + return store.transaction(async db => { + const row = await lockedWatch(db, job); + if (!row?.alert_body || row.status !== "uncertain" || row.expires_at.getTime() <= Date.now()) return; + if (row.credential_fingerprint !== linqFingerprint() || !allowed(row.destination) || + !priceWatchesEnabled() || verified.expiresAt <= Date.now()) return { delay: 60_000 }; + // Another watch may have checked this listing after this alert was reserved. + const latest = await storedObservation(db, offerId(saved)); + if (latest && latest.observedAt >= verified.observedAt && !confirmsReservedAlert(latest, saved, row.terms)) { + // Only an earlier attempt could have sent this alert. + await releaseInvalidAlert(db, job, Boolean(current.dispatch_at)); + return; + } + try { + const result = await send(row.destination, row.alert_body, `bell-price-${row.id}`, signal); + const confirmed = result.state === "uncertain" ? null : result; + await db.query("UPDATE bell_price_watches SET status=$2,message_id=$3,delivery_status=$4 WHERE id=$1", + [row.id, confirmed?.state ?? "failed", confirmed?.messageId ?? null, confirmed?.status ?? "unresolved"]); + } catch (error) { + if (!(error instanceof ProviderError) || ![400, 401, 403, 404, 422].includes(error.status)) throw error; + await db.query("UPDATE bell_price_watches SET status='failed',delivery_status=$2 WHERE id=$1", + [row.id, current.dispatch_at ? "unresolved" : `linq_http_${error.status}`]); + } + await detach(db, row.id); + }); +} diff --git a/server/shopping/evidence.ts b/server/shopping/evidence.ts new file mode 100644 index 0000000..6c497eb --- /dev/null +++ b/server/shopping/evidence.ts @@ -0,0 +1,359 @@ +import { isDeepStrictEqual } from "node:util"; +import { defaultTreeAdapter, html, parse } from "parse5"; +import { z } from "zod"; +import { publicUrl } from "../parallel"; +import { readPublicPage, type PageRead } from "./public-page"; + +const selector = /^(?:variant(?:_id)?|sku|pid|color|colou?r_id|size|style|model|market|country|locale|currency|dwvar_[a-z0-9_]+)$/i; +const tracking = /^(?:utm_(?:source|medium|campaign|id|term|content)|gclid|fbclid|msclkid)$/i; +const selectorValue = /^[a-z0-9_.~ -]{1,80}$/i; +const listingParameters = (params: URLSearchParams) => + [...params.entries()].every(([key, value]) => selector.test(key) && selectorValue.test(value)); +export const listingUrl = z.string().trim().max(2048).transform((value, ctx) => { + if (publicUrl.safeParse(value).success) { + const url = new URL(value); + for (const key of [...url.searchParams.keys()]) { + if (tracking.test(key)) url.searchParams.delete(key); + } + if (url.protocol === "https:" && listingParameters(url.searchParams) + && (!url.hash || (url.hash.includes("=") && listingParameters(new URLSearchParams(url.hash.slice(1)))))) { + return url.href; + } + } + ctx.addIssue({ code: "custom", message: "Use a public HTTPS product link with only public listing selectors." }); + return z.NEVER; +}); + +export const currencyCode = z.string().trim().toUpperCase().refine(code => Intl.supportedValuesOf("currency").includes(code)); +export const countryCode = z.string().trim().toUpperCase().regex(/^[A-Z]{2}$/); +export const conditionCode = z.enum(["new", "used", "refurbished"]); +const safeLabel = z.string().trim().min(1).max(200); +const listingSelectors = (url: string) => { + const parsed = new URL(url); + return [...parsed.searchParams, ...new URLSearchParams(parsed.hash.slice(1))] + .filter(([key]) => !/^(market|country|locale|currency)$/i.test(key)); +}; + +export const watchTerms = z.object({ + product: safeLabel.optional(), + url: listingUrl.optional(), + country: countryCode, + currency: currencyCode, + amount: z.string().regex(/^\d{1,10}(?:\.\d{1,4})?$/), + comparison: z.enum(["below", "at_or_below"]), + seller: safeLabel.optional(), + condition: conditionCode.default("new"), + gtin: z.string().regex(/^\d{8,14}$/).optional(), + brand: safeLabel.optional(), + mpn: safeLabel.optional(), + variant: safeLabel.optional(), +}).superRefine((terms, ctx) => { + if (!terms.url && !terms.product) ctx.addIssue({ code: "custom", message: "Enter an exact product name or listing link.", path: ["product"] }); + if (!priceMinor(terms.amount, terms.currency)) ctx.addIssue({ code: "custom", message: "Enter a positive price in the selected currency's precision.", path: ["amount"] }); + if (!!terms.brand !== !!terms.mpn) ctx.addIssue({ code: "custom", message: "A manufacturer part number requires its brand.", path: ["mpn"] }); +}); +export type WatchTerms = z.output; + +const variantDimensions = ["color", "size", "style", "model"] as const; +type VariantDimension = typeof variantDimensions[number]; +type VariantOptions = Partial>; +interface VariantScope { options: VariantOptions; gtin?: string } +export type SavedWatchTerms = WatchTerms & { resolvedVariant?: VariantScope }; + +export interface Observation { + url: string; product: string; identity: string; variant: string; seller: string; + manufacturerIdentity?: string; + variantOptions?: VariantOptions; + condition: z.infer; country: string; currency: string; amount: number; + inStock: boolean; observedAt: number; expiresAt: number; +} + +export function priceMinor(raw: unknown, currency: string): number | null { + if (typeof raw !== "number" && typeof raw !== "string") return null; + const digits = new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2; + const parts = /^(\d{1,12})(?:\.(\d+))?$/.exec(String(raw).trim()); + if (!parts || (parts[2]?.length ?? 0) > digits) return null; + const integer = Number(parts[1] + (parts[2] ?? "").padEnd(digits, "0")); + return Number.isSafeInteger(integer) ? integer : null; +} + +export const normalized = (value: string) => value.normalize("NFKC").toLowerCase().trim().replace(/\s+/g, " "); +export const identityOf = (gtin?: string, brand?: string, mpn?: string) => + gtin ? `gtin:${gtin.padStart(14, "0")}` : brand && mpn ? `mpn:${normalized(brand)}:${normalized(mpn)}` : undefined; + +type RecordValue = Record; +function record(value: unknown): RecordValue { + return value && typeof value === "object" && !Array.isArray(value) ? value as RecordValue : {}; +} +const values = (value: unknown): unknown[] => Array.isArray(value) ? value : value === undefined ? [] : [value]; +const label = (value: unknown) => { + const parsed = safeLabel.safeParse(value); + return parsed.success ? parsed.data.replace(/[\u0000-\u001F\u007F]/g, " ").replace(/[\u202A-\u202E\u2066-\u2069]/g, "").trim() : undefined; +}; +const typeName = (value: unknown) => typeof value === "string" ? value.split(/[/#]/).pop() : undefined; +const hasType = (node: RecordValue, type: string) => values(node["@type"]).some(value => typeName(value) === type); +const gtinFields = ["gtin14", "gtin13", "gtin12", "gtin8", "gtin"] as const; + +function* products(value: unknown, depth = 0): Generator { + if (depth > 7) return; + for (const item of values(value)) { + const node = record(item); + if (hasType(node, "Product")) yield node; + for (const child of ["@graph", "mainEntity", "hasVariant"]) yield* products(node[child], depth + 1); + } +} + +function regionCode(value: unknown) { + const node = record(value); + const code = typeof value === "string" ? value : node.addressCountry ?? (hasType(node, "Country") ? node.name : undefined); + return typeof code === "string" && /^[A-Za-z]{2}$/.test(code) ? code.toUpperCase() : undefined; +} + +function limitedRegion(value: unknown) { + const region = record(value); + return ["addressRegion", "addressLocality", "postalCode", "postalCodePrefix", "postalCodeRange", + "box", "circle", "line", "polygon", "geo", "geoMidpoint", "geoRadius"].some(key => region[key] != null); +} + +function matchesMarket(url: string, market: string, currency: string) { + for (const [key, value] of new URL(url).searchParams) { + if (/^(country|market)$/i.test(key) && value.toUpperCase() !== market) return false; + if (/^currency$/i.test(key) && value.toUpperCase() !== currency) return false; + if (/^locale$/i.test(key)) { + try { + const { region } = new Intl.Locale(value.replaceAll("_", "-")); + if (region && region !== market) return false; + } catch { return false; } + } + } + return true; +} + +function variantOption(product: RecordValue, key: string) { + const property = product[key]; + const declared = record(property).name ?? record(property).value ?? property; + const text = label(typeof declared === "number" ? String(declared) : declared); + return text ? normalized(text) : undefined; +} + +function provesSelector(product: RecordValue, key: string, selector: string) { + if (/^(sku|variant(?:_id)?|pid)$/i.test(key)) { + return [product.sku, product.productID, product.mpn, product.gtin, product.gtin14, product.gtin13, product.gtin12, product.gtin8].includes(selector); + } + const dimension = variantDimensions.find(dimension => dimension === key.toLowerCase()); + return dimension !== undefined && variantOption(product, dimension) === normalized(selector); +} + +const offerDate = z.union([z.iso.date(), z.iso.datetime({ offset: true })]); +function offerTime(value: unknown) { + if (value == null) return Infinity; + const parsed = offerDate.safeParse(value); + return parsed.success ? Date.parse(parsed.data) : NaN; +} + +function sameListing(value: unknown, url: string) { + if (typeof value !== "string") return false; + try { return listingUrl.safeParse(new URL(value, url).href).data === url; } + catch { return false; } +} + +function matchesOfferedProduct(value: unknown, product: RecordValue) { + // A nested Offer implicitly applies to its Product unless it declares an explicit target. + if (value == null) return true; + const targets = values(value); + if (targets.length !== 1) return false; + const target = record(targets[0]); + if (target["@context"] != null || (target["@type"] != null && !hasType(target, "Product"))) return false; + + const identifiers = ["@id", "sku", "productID", ...gtinFields]; + const details = ["name", "url", "brand", "mpn", "color", "size", "style", "model"]; + if ([...identifiers, ...details].some(key => target[key] != null && !isDeepStrictEqual(target[key], product[key]))) return false; + return identifiers.some(key => Boolean(label(target[key]))) || + Boolean(label(target.mpn) && label(record(target.brand).name ?? target.brand)); +} + +function observation(product: RecordValue, offer: RecordValue, page: PageRead, market: string, now: number): Observation | null { + if (!hasType(offer, "Offer") || hasType(offer, "AggregateOffer") || !matchesOfferedProduct(offer.itemOffered, product) + || ["priceSpecification", "eligibleCustomerType", "eligibleQuantity", "validForMemberTier", "eligibleTransactionVolume", + "eligibleDuration", "eligibleTradeIn", "eligiblePaymentMethod", "addOn"].some(key => offer[key] != null)) return null; + if (offer.businessFunction != null) { + const businessFunction = record(offer.businessFunction)["@id"] ?? offer.businessFunction; + if (typeof businessFunction !== "string" || !/^https?:\/\/purl\.org\/goodrelations\/v1#Sell$/.test(businessFunction)) return null; + } + + const explicit = values(offer.eligibleRegion ?? undefined).map(region => limitedRegion(region) ? undefined : regionCode(region)); + const shipping = values(offer.shippingDetails).map(record); + const destinationCountry = (destination: unknown) => regionCode(record(destination).addressCountry); + const excludesShipping = ({ doesNotShip }: RecordValue) => doesNotShip != null && doesNotShip !== false; + // Even a regional shipping exclusion prevents verifying availability for the whole country. + if (shipping.filter(excludesShipping).some(({ shippingDestination }) => { + const destinations = values(shippingDestination ?? undefined); + return !destinations.length || destinations.some(destination => { + const country = destinationCountry(destination); + return !country || country === market; + }); + })) return null; + const shipped = shipping.filter(details => !excludesShipping(details)) + .flatMap(({ shippingDestination }) => values(shippingDestination ?? undefined) + .map(destination => limitedRegion(destination) ? undefined : destinationCountry(destination))); + const excluded = values(offer.ineligibleRegion ?? undefined).map(regionCode); + if ((!explicit.length && !shipped.length) || (explicit.length && !explicit.includes(market)) + || (shipped.length && !shipped.includes(market)) || excluded.some(region => !region || region === market)) return null; + if (offer.availableAtOrFrom || /(?:pickup|collect|storepickup)/i.test(JSON.stringify(offer.availableDeliveryMethod ?? ""))) return null; + + const availability = typeName(offer.availability); + if (availability !== "InStock" && availability !== "OnlineOnly" && availability !== "OutOfStock" && availability !== "SoldOut") return null; + const condition = { NewCondition: "new", UsedCondition: "used", RefurbishedCondition: "refurbished" }[typeName(offer.itemCondition ?? product.itemCondition) ?? ""]; + if (!conditionCode.safeParse(condition).success) return null; + const currency = currencyCode.safeParse(offer.priceCurrency); + if (!currency.success || !matchesMarket(page.url, market, currency.data)) return null; + const amount = priceMinor(offer.price, currency.data); + const seller = label(record(offer.seller).name ?? offer.seller); + const name = label(product.name), sku = label(product.sku); + const brand = label(record(product.brand).name ?? product.brand); + const gtin = gtinFields.map(key => product[key]) + .find((value): value is string => typeof value === "string" && /^\d{8,14}$/.test(value)); + const manufacturerIdentity = identityOf(undefined, brand, label(product.mpn)); + const identity = identityOf(gtin) ?? manufacturerIdentity ?? (sku && `sku:${new URL(page.url).hostname}:${normalized(sku)}`); + const variant = sku ?? label(product.model) ?? label(product.mpn) ?? gtin; + if (!name || !seller || !identity || !variant || amount === null) return null; + const variantOptions: VariantOptions = {}; + for (const dimension of variantDimensions) { + const value = variantOption(product, dimension); + if (value) variantOptions[dimension] = value; + } + + const observedAt = Math.min(now - page.ageSeconds * 1000, page.date ? Date.parse(page.date) : now); + const expiresAt = Math.min(observedAt + 300_000, offerTime(offer.priceValidUntil), offerTime(offer.validThrough), offerTime(offer.availabilityEnds)); + if (!Number.isFinite(observedAt) || !Number.isFinite(expiresAt) || expiresAt <= now || page.ageSeconds < 0) return null; + if ([offer.validFrom, offer.availabilityStarts].some(start => start != null && !(offerTime(start) <= now))) return null; + return { url: page.url, product: name, identity, variant, seller, condition: condition as Observation["condition"], + ...(manufacturerIdentity && manufacturerIdentity !== identity ? { manufacturerIdentity } : {}), + ...(Object.keys(variantOptions).length ? { variantOptions } : {}), + country: market, currency: currency.data, amount, inStock: availability === "InStock" || availability === "OnlineOnly", observedAt, expiresAt }; +} + +function merchantMarkup(source: string) { + const scripts: string[] = []; + const liveSkus = new Set(); + // Parse with browser HTML semantics. Template contents are kept in separate document fragments. + const nodes = parse(source, { scriptingEnabled: true }).childNodes.slice(); + for (let node = nodes.pop(); node; node = nodes.pop()) { + if (!defaultTreeAdapter.isElementNode(node)) continue; + if (node.namespaceURI === html.NS.HTML) { + const sku = node.attrs.find(attribute => attribute.name === "data-selected-sku")?.value; + if (sku !== undefined) liveSkus.add(sku); + if (node.tagName === "script" && node.attrs.some(attribute => + attribute.name === "type" && attribute.value.trim().toLowerCase() === "application/ld+json")) { + scripts.push(node.childNodes.filter(defaultTreeAdapter.isTextNode).map(text => text.value).join("")); + } + } + for (const child of node.childNodes) nodes.push(child); + } + return { scripts, liveSkus }; +} + +/** Read only unambiguous public offer markup tied to this listing and market. */ +export function parseMerchantEvidence(page: PageRead, market: string, now = Date.now()): Observation | null { + const selected = listingSelectors(page.url); + // A hash is never sent in the HTTP request. Only a live selected-state reader can prove it. + if (new URL(page.url).hash) return null; + const { scripts, liveSkus } = merchantMarkup(page.html); + const offers: Array = []; + if (liveSkus.size > 1) return null; + for (const body of scripts) { + let parsed: unknown; + try { parsed = JSON.parse(body); } catch { continue; } + for (const product of products(parsed)) { + for (const value of values(product.offers)) { + const offer = record(value); + if (!sameListing(offer.url ?? product.url, page.url)) continue; + if (offer.url && product.url && selected.length && !sameListing(product.url, page.url)) continue; + if (liveSkus.size && (typeof product.sku !== "string" || !liveSkus.has(product.sku))) return null; + if (selected.some(([key, selector]) => !provesSelector(product, key, selector))) return null; + offers.push(observation(product, offer, page, market, now)); + } + } + } + const first = offers[0]; + return first && offers.every(offer => JSON.stringify(offer) === JSON.stringify(first)) ? first : null; +} + +export async function verifyListing(url: string, country: string, signal?: AbortSignal) { + try { + const listing = listingUrl.parse(url); + const page = await readPublicPage(listing, value => listingUrl.parse(value), signal); + if (!page) return null; + const requested = new URL(listing), final = new URL(page.url); + if (requested.origin !== final.origin || requested.search !== final.search || requested.hash !== final.hash || + requested.pathname.replace(/\/$/, "") !== final.pathname.replace(/\/$/, "")) return null; + // Verify the final page, then keep the requested URL as the watch's stable listing ID. + const item = parseMerchantEvidence(page, country); + return item && { ...item, url: listing }; + } catch { + signal?.throwIfAborted(); + return null; + } +} + +export function matchesIdentity(item: Observation, identity: string) { + return item.identity === identity || item.manufacturerIdentity === identity; +} + +function matchesVariant(item: Observation, variant: VariantScope) { + const sameGtin = Boolean(variant.gtin && item.identity === variant.gtin); + if (variant.gtin && !sameGtin && (item.identity.startsWith("gtin:") || !Object.keys(variant.options).length)) return false; + return variantDimensions.every(dimension => { + const expected = variant.options[dimension]; + const observed = item.variantOptions?.[dimension]; + // A shared GTIN proves equivalence across stores even when their declared options differ in completeness. + return expected === observed || (sameGtin && (!expected || !observed)); + }); +} + +export function resolveVariant(items: Observation[]): VariantScope | undefined { + const gtins = new Set(items.map(item => item.identity).filter(identity => identity.startsWith("gtin:"))); + if (!items.length || gtins.size > 1) return undefined; + const gtin = gtins.values().next().value; + const options: VariantOptions = {}; + for (const dimension of variantDimensions) { + const values = new Set(items.map(item => item.variantOptions?.[dimension])); + if (gtin) values.delete(undefined); + if (values.size > 1) return undefined; + const value = values.values().next().value; + if (value) options[dimension] = value; + } + return { options, ...(gtin ? { gtin } : {}) }; +} + +export function sameOffer(item: Observation, saved: Observation) { + return item.url === saved.url && item.identity === saved.identity && item.variant === saved.variant + && normalized(item.seller) === normalized(saved.seller) && item.condition === saved.condition + && item.currency === saved.currency && item.country === saved.country + && matchesVariant(item, { options: saved.variantOptions ?? {}, gtin: saved.identity.startsWith("gtin:") ? saved.identity : undefined }); +} + +export function matchesTerms(item: Observation, terms: SavedWatchTerms, identity?: string) { + const explicit = identityOf(terms.gtin, terms.brand, terms.mpn); + const variant = terms.variant && normalized(terms.variant); + return item.country === terms.country && item.currency === terms.currency && item.condition === terms.condition + && (!terms.url || item.url === terms.url) && (!identity || matchesIdentity(item, identity)) + && (!explicit || matchesIdentity(item, explicit)) + && (!terms.resolvedVariant || matchesVariant(item, terms.resolvedVariant)) + && (!variant || [normalized(item.variant), normalized(item.product), ...Object.values(item.variantOptions ?? {})].includes(variant)) + && (!terms.seller || normalized(terms.seller) === normalized(item.seller)); +} + +export function meetsTarget(item: Observation, terms: WatchTerms) { + const limit = priceMinor(terms.amount, terms.currency)!; + return terms.comparison === "below" ? item.amount < limit : item.amount <= limit; +} + +export function qualifies(item: Observation, terms: SavedWatchTerms, now = Date.now()) { + return item.inStock && item.expiresAt > now && matchesTerms(item, terms) && meetsTarget(item, terms); +} + +export function displayPrice(amount: number, currency: string) { + const format = new Intl.NumberFormat("en", { style: "currency", currency, currencyDisplay: "code" }); + return format.format(amount / 10 ** (format.resolvedOptions().maximumFractionDigits ?? 2)).replaceAll("\u00a0", " "); +} diff --git a/server/shopping/providers.ts b/server/shopping/providers.ts new file mode 100644 index 0000000..ae189c5 --- /dev/null +++ b/server/shopping/providers.ts @@ -0,0 +1,34 @@ +import { z } from "zod"; +import type { Destination } from "../monitors/config"; +import { postLinqMessage } from "../monitors/provider"; + +const status = z.enum(["pending", "queued", "sent", "delivered", "received", "read", "failed"]); +const message = z.object({ + id: z.string().min(1).max(256), + status: status.optional(), + delivery_status: status.optional(), + from_handle: z.object({ handle: z.string() }).nullish(), + sender_handle: z.object({ handle: z.string() }).nullish(), + from: z.string().nullish(), + is_from_me: z.boolean().optional(), + direction: z.string().optional(), +}); +const sentMessage = z.object({ chat_id: z.string(), message }); + +export type Delivery = + | { state: "accepted" | "failed"; messageId: string; status: string } + | { state: "uncertain" }; + +export async function sendPriceAlert(destination: Destination, text: string, key: string, signal?: AbortSignal): Promise { + const parsed = sentMessage.safeParse(await postLinqMessage(destination, text, key, signal)); + if (!parsed.success) return { state: "uncertain" }; + const { chat_id: chat, message: sent } = parsed.data; + const handles = [sent.from, sent.from_handle?.handle, sent.sender_handle?.handle].filter(handle => handle != null); + const result = sent.status ?? sent.delivery_status; + if (chat !== destination.chat || handles.some(handle => handle !== destination.line) || + sent.is_from_me === false || sent.direction === "inbound" || !result || + (sent.status && sent.delivery_status && sent.status !== sent.delivery_status)) { + return { state: "uncertain" }; + } + return { state: result === "failed" ? "failed" : "accepted", messageId: sent.id, status: result }; +} diff --git a/server/shopping/public-page.ts b/server/shopping/public-page.ts new file mode 100644 index 0000000..2a56c7b --- /dev/null +++ b/server/shopping/public-page.ts @@ -0,0 +1,79 @@ +import { lookup } from "node:dns/promises"; +import { request } from "node:https"; +import { BlockList, isIP } from "node:net"; + +const blocked = new BlockList(); +for (const [address, bits] of [ + ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], + ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.88.99.0", 24], ["192.168.0.0", 16], + ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24], ["224.0.0.0", 3], +] as const) blocked.addSubnet(address, bits, "ipv4"); +const globalV6 = new BlockList(); +globalV6.addSubnet("2000::", 3, "ipv6"); +for (const [address, bits] of [["2001::", 23], ["2001:db8::", 32], ["2002::", 16], ["3fff::", 20]] as const) { + blocked.addSubnet(address, bits, "ipv6"); +} + +export function isPublicAddress(address: string) { + const version = isIP(address); + if (version === 4) return !blocked.check(address, "ipv4"); + return version === 6 && globalV6.check(address, "ipv6") && !blocked.check(address, "ipv6"); +} + +export type PageRead = { url: string; html: string; ageSeconds: number; date?: string }; +const maxPageBytes = 2_000_000; + +/** Pin the checked DNS answer to the socket. No proxy, cookies, redirects by the HTTP client, or subresources. */ +export async function readPublicPage( + start: string, validate: (url: string) => string, signal?: AbortSignal, +): Promise { + const timeout = AbortSignal.timeout(5_000); + const deadline = signal ? AbortSignal.any([signal, timeout]) : timeout; + let current = validate(start); + for (let redirect = 0; redirect <= 3; redirect++) { + const url = new URL(current); + const page = await new Promise((resolve, reject) => { + const req = request(url, { + signal: deadline, agent: false, + headers: { Accept: "text/html", "Cache-Control": "no-cache", "Accept-Encoding": "identity", "User-Agent": "Bell Price Watch" }, + lookup(hostname, options, callback) { + void lookup(hostname, { all: true }).then(addresses => { + deadline.throwIfAborted(); + if (!addresses.length || addresses.some(({ address }) => !isPublicAddress(address))) { + throw new Error("Listing does not resolve to a public network"); + } + if (options.all) callback(null, addresses); + else callback(null, addresses[0].address, addresses[0].family); + }).catch(error => callback(error, "", 0)); + }, + }, response => { + if ([301, 302, 303, 307, 308].includes(response.statusCode ?? 0) && response.headers.location) { + response.destroy(); + return resolve({ redirect: response.headers.location }); + } + if (response.statusCode !== 200 || !/^text\/html(?:;|$)/i.test(response.headers["content-type"] ?? "") || + ![undefined, "identity"].includes(response.headers["content-encoding"])) { + response.destroy(); + return resolve(null); + } + const chunks: Buffer[] = []; + let size = 0; + response.on("data", (chunk: Buffer) => { + size += chunk.length; + if (size > maxPageBytes) response.destroy(new Error("Merchant response exceeds size limit")); + else chunks.push(chunk); + }); + response.on("error", reject); + response.on("end", () => resolve({ + url: current, html: Buffer.concat(chunks).toString("utf8"), + ageSeconds: Number(response.headers.age ?? 0), date: response.headers.date, + })); + }); + req.on("error", reject); + req.end(); + }); + if (!page || !("redirect" in page)) return page; + current = validate(new URL(page.redirect, url).href); + } + return null; +} diff --git a/server/shopping/search.ts b/server/shopping/search.ts new file mode 100644 index 0000000..5924c6f --- /dev/null +++ b/server/shopping/search.ts @@ -0,0 +1,22 @@ +import { z } from "zod"; +import { required } from "../monitors/config"; +import { request } from "../monitors/provider"; +import { listingUrl } from "./evidence"; + +const lead = z.object({ url: z.string().max(2048) }); +const response = z.object({ + results: z.array(lead.extend({ offers: z.array(lead).default([]) })), +}); + +export async function discoverListings(query: string, country: string, currency: string, signal?: AbortSignal) { + const shopping = response.parse(await request("https://api.parallel.ai/v1/shopping/search", required("PARALLEL_API_KEY"), "POST", { + mode: "advanced", search_queries: [`${query.slice(0, 175)} ${country} ${currency}`], condition: "any", + advanced_settings: { location: country.toLowerCase(), max_results: 8 }, + }, false, signal)); + + const candidates = shopping.results.flatMap(item => [item.url, ...item.offers.slice(0, 3).map(offer => offer.url)]); + return [...new Set(candidates.flatMap(candidate => { + const url = listingUrl.safeParse(candidate); + return url.success ? [url.data] : []; + }))].slice(0, 5); +} diff --git a/server/shopping/store.ts b/server/shopping/store.ts new file mode 100644 index 0000000..cce0c67 --- /dev/null +++ b/server/shopping/store.ts @@ -0,0 +1,133 @@ +import { randomUUID } from "node:crypto"; +import type { Pool, PoolClient } from "pg"; +import type { MonitorStore } from "../monitors/store"; +import type { Destination, Owner } from "../monitors/config"; +import { digest, priceCheckHours } from "./config"; +import { normalized, type Observation, type SavedWatchTerms, type WatchTerms } from "./evidence"; + +export type Queryable = Pool | PoolClient; +export interface Inbound { + owner: Owner; + destination: Destination; + messageId: string; + sentAt?: string; +} +export interface PriceWatch { + id: string; + destination: Destination; + terms: SavedWatchTerms; + identity: string; + credential_fingerprint: string; + status: "active" | "degraded" | "reserved" | "uncertain" | "accepted" | "stopped" | "expired" | "opted_out" | "failed"; + expires_at: Date; + alert: Observation | null; + alert_body: string | null; + dispatch_at: Date | null; + delivery_status: string | null; +} +export interface PriceJob { + id: string; kind: "observe" | "send"; target: string; + lease_token: string; attempts: number; +} + +export const open = "('active','degraded','reserved','uncertain')"; +export const watching = "('active','degraded')"; +type PriceAction = { name: "enroll"; request: WatchTerms } | { name: "stop"; request: { id: string } }; +const actionParams = (inbound: Inbound, action: PriceAction) => [ + inbound.owner.issuer, inbound.owner.id, inbound.destination.chat, inbound.destination.line, inbound.messageId, + action.name, action.request, +]; +const actionScope = `issuer=$1 AND owner_id=$2 AND chat=$3 AND line=$4 AND message_id=$5 AND action=$6 + AND operation_key=bell_price_operation_key($6,$7)`; + +export async function storageReady(db: Queryable) { + const result = await db.query<{ present: boolean }>("SELECT to_regclass('bell_price_jobs') IS NOT NULL AS present"); + return result.rows[0].present; +} + +export async function enqueue(db: Queryable, kind: PriceJob["kind"], target: string) { + await db.query(`INSERT INTO bell_price_jobs(id,kind,target) VALUES ($1,$2,$3) + ON CONFLICT DO NOTHING`, [`${kind}:${target}`, kind, target]); +} + +const liveClaim = "id=$1 AND lease_token=$2 AND lease_until>clock_timestamp()"; + +export async function lockClaim(db: Queryable, job: PriceJob) { + return !!(await db.query(`SELECT id FROM bell_price_jobs WHERE ${liveClaim} FOR UPDATE`, [job.id, job.lease_token])).rowCount; +} + +export const lockEnrollment = (db: Queryable, key: string) => + db.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [key]); + +export async function rememberAction(db: Queryable, inbound: Inbound, action: PriceAction) { + await db.query(`INSERT INTO bell_price_actions(issuer,owner_id,chat,line,message_id,action,request) + VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT DO NOTHING`, actionParams(inbound, action)); + return lockAction(db, inbound, action); +} + +export async function lockAction(db: Queryable, inbound: Inbound, action: PriceAction) { + return (await db.query<{ request: unknown; outcome: unknown }>(`SELECT request,outcome FROM bell_price_actions + WHERE ${actionScope} FOR UPDATE`, actionParams(inbound, action))).rows[0]; +} + +export function saveActionOutcome(db: Queryable, inbound: Inbound, action: PriceAction, outcome: unknown) { + return db.query(`UPDATE bell_price_actions SET outcome=$8 WHERE ${actionScope}`, [...actionParams(inbound, action), outcome]); +} + +export function equivalentWatch(inbound: Inbound, terms: WatchTerms, identity: string) { + const parts = [inbound.destination, identity, terms.url ?? null, terms.country, terms.currency, + terms.amount.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "").replace(/^0+(?=\d)/, ""), terms.comparison, + terms.condition, terms.seller ? normalized(terms.seller) : null]; + const variant = terms.variant ? normalized(terms.variant) : null; + return digest(JSON.stringify([...parts, variant])); +} + +export function offerId(item: Observation) { + return digest(JSON.stringify([item.url, item.country, item.identity, item.variant, normalized(item.seller), item.condition, item.currency])); +} + +export async function storedObservation(db: Queryable, id: string) { + return (await db.query<{ observation: Observation }>("SELECT observation FROM bell_price_offers WHERE id=$1", [id])) + .rows[0]?.observation; +} + +export async function attachOffer(db: Queryable, watchId: string, item: Observation) { + const id = offerId(item); + await db.query(`INSERT INTO bell_price_offers(id,observation,next_at,verified_at) + VALUES ($1,$2,$3::timestamptz+$4::int*interval '1 hour',$3) + ON CONFLICT (id) DO UPDATE SET observation=excluded.observation,verified_at=excluded.verified_at + WHERE bell_price_offers.verified_at(`UPDATE bell_price_jobs SET lease_until=clock_timestamp()+interval '45 seconds',lease_token=$1,attempts=attempts+1 WHERE id=( + SELECT id FROM bell_price_jobs WHERE kind IN ('observe','send') AND NOT failed AND next_at<=clock_timestamp() + AND (lease_until IS NULL OR lease_until { + const result = await db.query<{ failed: boolean }>(`UPDATE bell_price_jobs SET next_at=clock_timestamp()+$3*interval '1 millisecond', + lease_until=NULL,lease_token=NULL,last_error=$4,failed=$4::text IS NOT NULL AND attempts>=8, + attempts=CASE WHEN $4::text IS NULL THEN 0 ELSE attempts END WHERE ${liveClaim} RETURNING failed`, + [job.id, job.lease_token, next.delay, next.error ?? null]); + if (job.kind === "send" && result.rows[0]?.failed) { + const watch = await db.query(`UPDATE bell_price_watches SET status='failed', + delivery_status=CASE WHEN dispatch_at IS NULL THEN 'not_sent' ELSE 'unresolved' END + WHERE id=$1 AND status IN ('reserved','uncertain') AND delivery_status IS NULL`, [job.target]); + if (watch.rowCount) await detach(db, job.target); + } + }); +} diff --git a/server/shopping/watches.ts b/server/shopping/watches.ts new file mode 100644 index 0000000..ba73346 --- /dev/null +++ b/server/shopping/watches.ts @@ -0,0 +1,162 @@ +import { randomUUID } from "node:crypto"; +import { assertOwner, allowed, destinationSchema, type Destination, type Owner } from "../monitors/config"; +import { type MonitorStore, monitorStore, type WatchFilter, watchPageSize } from "../monitors/store"; +import { linqFingerprint, priceCheckHours, requirePriceEnrollment } from "./config"; +import { identityOf, matchesIdentity, matchesTerms, meetsTarget, normalized, qualifies, resolveVariant, verifyListing, watchTerms, type Observation, type WatchTerms } from "./evidence"; +import { discoverListings } from "./search"; +import { attachOffer, detach, equivalentWatch, lockAction, lockEnrollment, open, rememberAction, saveActionOutcome, storageReady, type Inbound, type PriceWatch, type Queryable } from "./store"; + +type Decision = { status: "match" | "at_target_out_of_stock"; offer: Observation } + | { status: "needs_details"; reason: string } | { status: "enrolled"; id: string }; + +export type ShoppingSources = { verify: typeof verifyListing; discover: typeof discoverListings }; +export const shoppingSources: ShoppingSources = { verify: verifyListing, discover: discoverListings }; + +function watchSummary(watch: PriceWatch) { + const isOpen = ["active", "degraded", "reserved", "uncertain"].includes(watch.status); + const status = isOpen && watch.expires_at.getTime() <= Date.now() ? "expired" : watch.status; + return { id: `price:${watch.id}`, status, delivery_status: watch.delivery_status, terms: watch.terms, + expires_at: watch.expires_at.toISOString(), cadence_hours: priceCheckHours }; +} + +async function readOffers(terms: WatchTerms, sources: ShoppingSources, signal: AbortSignal) { + const query = [terms.product, terms.variant ?? terms.mpn].filter(Boolean).join(" "); + const urls = terms.url ? [terms.url] : await sources.discover(query, terms.country, terms.currency, signal); + const reads = await Promise.allSettled(urls.map(url => sources.verify(url, terms.country, signal))); + signal.throwIfAborted(); + return reads.flatMap(read => read.status === "fulfilled" && read.value && matchesTerms(read.value, terms) ? [read.value] : []); +} + +function identifyOffers(terms: WatchTerms, offers: Observation[]) { + if (terms.url) return { identity: offers[0]?.identity, resolvedVariant: resolveVariant(offers), offers }; + const explicit = identityOf(terms.gtin, terms.brand, terms.mpn); + const name = normalized(terms.product ?? ""); + const exact = explicit ? offers : offers.filter(item => normalized(item.product) === name); + const first = exact[0]; + const identity = explicit ?? (first && [first.identity, first.manufacturerIdentity].find(id => + id && !id.startsWith("sku:") && exact.every(item => matchesIdentity(item, id)))); + const resolvedVariant = resolveVariant(exact); + if (!identity || !resolvedVariant) return { identity: undefined, offers: [] }; + return { identity, resolvedVariant, offers: offers.filter(item => matchesTerms(item, { ...terms, resolvedVariant }, identity)) }; +} + +function checkDestination(owner: Owner, destination: Destination) { + assertOwner(owner); + destinationSchema.parse(destination); + if (!allowed(destination)) throw new Error("This Linq destination is no longer allowed."); +} + +async function decideEnrollment( + db: Queryable, inbound: Inbound, terms: WatchTerms, resolved: ReturnType, +): Promise { + const offers = resolved.offers.filter(offer => offer.expiresAt > Date.now()) + .sort((a, b) => a.amount - b.amount || a.url.localeCompare(b.url)); + const match = offers.find(offer => qualifies(offer, terms)); + if (match) return { status: "match", offer: match }; + + const needsDetails = { status: "needs_details", reason: terms.url ? "unverified_listing" : "unresolved_product" } as const; + if (!resolved.identity || !offers.length) return needsDetails; + + const listingsToWatch = offers.filter(offer => !meetsTarget(offer, terms)); + if (!listingsToWatch.length) return { status: "at_target_out_of_stock", offer: offers[0] }; + + const key = equivalentWatch(inbound, terms, resolved.identity); + await lockEnrollment(db, key); + const { rows: [prior] } = await db.query(`SELECT * FROM bell_price_watches + WHERE issuer=$1 AND owner_id=$2 AND equivalent=$3 AND status IN ${open} FOR UPDATE`, + [inbound.owner.issuer, inbound.owner.id, key]); + if (prior && prior.expires_at.getTime() > Date.now()) { + return listingsToWatch.some(offer => matchesTerms(offer, prior.terms, prior.identity)) + ? { status: "enrolled", id: prior.id } + : needsDetails; + } + if (prior) { + await db.query("UPDATE bell_price_watches SET status='expired' WHERE id=$1", [prior.id]); + await detach(db, prior.id); + } + + const id = randomUUID(); + await db.query(`INSERT INTO bell_price_watches(id,issuer,owner_id,destination,terms,equivalent,identity,credential_fingerprint,status) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'active')`, + [id, inbound.owner.issuer, inbound.owner.id, inbound.destination, + { ...terms, product: terms.product ?? listingsToWatch[0].product, resolvedVariant: resolved.resolvedVariant }, + key, resolved.identity, linqFingerprint()]); + // Concurrent enrollments can share listings. Lock those listings in the same order. + for (const offer of listingsToWatch.toSorted((a, b) => a.url.localeCompare(b.url))) await attachOffer(db, id, offer); + return { status: "enrolled", id }; +} + +export class PriceWatches { + constructor(readonly store: MonitorStore, readonly sources: ShoppingSources = shoppingSources) {} + + async enroll(inbound: Inbound, input: WatchTerms, signal?: AbortSignal) { + checkDestination(inbound.owner, inbound.destination); + requirePriceEnrollment(); + const action = { name: "enroll", request: watchTerms.parse(input) } as const; + const saved = await this.store.transaction(db => rememberAction(db, inbound, action)); + if (saved.outcome) return this.result(saved.outcome as Decision); + + const terms = watchTerms.parse(saved.request); + const deadline = AbortSignal.timeout(14_000); + // Read merchant pages outside the transaction so they never hold a database lock. + const resolved = identifyOffers(terms, await readOffers(terms, this.sources, signal ? AbortSignal.any([signal, deadline]) : deadline)); + checkDestination(inbound.owner, inbound.destination); + + const decision = await this.store.transaction(async db => { + const current = await lockAction(db, inbound, action); + if (current.outcome) return current.outcome as Decision; + requirePriceEnrollment(); + const outcome = await decideEnrollment(db, inbound, terms, resolved); + await saveActionOutcome(db, inbound, action, outcome); + return outcome; + }); + return this.result(decision); + } + + private async result(decision: Decision) { + if (decision.status !== "enrolled") { + return "offer" in decision && decision.offer.expiresAt <= Date.now() + ? { status: "match_needs_recheck" as const } : decision; + } + const { rows: [watch] } = await this.store.pool.query( + "SELECT * FROM bell_price_watches WHERE id=$1", [decision.id]); + return watchSummary(watch); + } + + async list(owner: Owner, destination: Destination, filter: WatchFilter, cursor?: string) { + checkDestination(owner, destination); + if (!await storageReady(this.store.pool)) return { watches: [], next_cursor: null }; + const { rows } = await this.store.pool.query(`SELECT * FROM bell_price_watches + WHERE issuer=$1 AND owner_id=$2 AND destination=$3 + AND ($4::text='all' OR ($4='open')=(status IN ${open} AND expires_at>now())) + AND ($5::uuid IS NULL OR (created_at,id) < (SELECT created_at,id FROM bell_price_watches + WHERE id=$5 AND issuer=$1 AND owner_id=$2 AND destination=$3)) + ORDER BY created_at DESC, id DESC LIMIT $6`, + [owner.issuer, owner.id, destination, filter, cursor ?? null, watchPageSize + 1]); + return { + watches: rows.slice(0, watchPageSize).map(watchSummary), + next_cursor: rows.length > watchPageSize ? rows[watchPageSize - 1].id : null, + }; + } + + async stop(inbound: Inbound, id: string) { + checkDestination(inbound.owner, inbound.destination); + if (!inbound.sentAt || !(Date.parse(inbound.sentAt) <= Date.now() + 60_000)) { + throw new Error("Watch operation needs a reliable text timestamp. Ask the shopper to send a new stop request."); + } + const action = { name: "stop", request: { id } } as const; + return this.store.transaction(async db => { + const saved = await rememberAction(db, inbound, action); + if (saved.outcome) return saved.outcome; + const stopped = await db.query(`UPDATE bell_price_watches SET status='stopped' WHERE id=$1 AND issuer=$2 AND owner_id=$3 + AND destination=$4 AND created_at<=$5::timestamptz AND status IN ${open} RETURNING id`, + [id, inbound.owner.issuer, inbound.owner.id, inbound.destination, inbound.sentAt]); + if (stopped.rowCount) await detach(db, id); + const outcome = stopped.rowCount ? { id: `price:${id}`, status: "stopped" } : { status: "not_found" }; + await saveActionOutcome(db, inbound, action, outcome); + return outcome; + }); + } +} + +export const priceWatches = () => new PriceWatches(monitorStore()); diff --git a/server/shopping/worker.ts b/server/shopping/worker.ts new file mode 100644 index 0000000..88cf0e0 --- /dev/null +++ b/server/shopping/worker.ts @@ -0,0 +1,88 @@ +import type { MonitorStore } from "../monitors/store"; +import { ProviderError } from "../monitors/provider"; +import { priceCheckHours } from "./config"; +import { dispatchAlert, reserveAlert } from "./delivery"; +import type { sendPriceAlert } from "./providers"; +import { qualifies } from "./evidence"; +import { claimPriceJob, detach, finishPriceJob, lockClaim, offerId, retryPriceJob, storedObservation, open, watching, type PriceJob, type PriceWatch } from "./store"; +import { shoppingSources, type ShoppingSources } from "./watches"; + +export class PriceWorker { + constructor(readonly store: MonitorStore, readonly sources: ShoppingSources = shoppingSources, + readonly send?: typeof sendPriceAlert) {} + + async schedule() { + await this.store.transaction(async db => { + const expired = await db.query<{ id: string }>(`SELECT id FROM bell_price_watches + WHERE status IN ${open} AND expires_at<=clock_timestamp() ORDER BY expires_at LIMIT 25 FOR UPDATE SKIP LOCKED`); + for (const { id } of expired.rows) { + await db.query("UPDATE bell_price_watches SET status='expired' WHERE id=$1", [id]); + await detach(db, id); + } + }); + // Leased jobs remain the sole owner of writes. These inserts are bounded, even during backlog or cutover. + await this.store.pool.query(`INSERT INTO bell_price_jobs(id,kind,target) + SELECT 'observe:'||o.id,'observe',o.id FROM bell_price_offers o + WHERE o.next_at<=clock_timestamp() + AND EXISTS (SELECT 1 FROM bell_price_subscriptions s JOIN bell_price_watches w ON w.id=s.watch_id + WHERE s.offer_id=o.id AND w.status IN ${watching} AND w.expires_at>clock_timestamp()) + AND NOT EXISTS (SELECT 1 FROM bell_price_jobs j WHERE j.id='observe:'||o.id) + ORDER BY o.next_at LIMIT 40 ON CONFLICT DO NOTHING`); + } + + async runOne(deadline: number) { + if (deadline - Date.now() < 1200) return false; + const job = await claimPriceJob(this.store.pool); + if (!job) return false; + try { + const signal = AbortSignal.timeout(Math.min(15_000, Math.max(1, deadline - Date.now()))); + const next = await this.run(job, signal); + if (next) await retryPriceJob(this.store, job, next); + else await finishPriceJob(this.store.pool, job); + } catch (error) { + const delay = Math.max(error instanceof ProviderError ? error.retryAfter : 0, Math.min(3_600_000, 1000 * 2 ** job.attempts)); + if (job.kind === "observe") { + await this.store.transaction(async db => { + if (!await lockClaim(db, job)) return; + await db.query(`UPDATE bell_price_watches SET status='degraded' WHERE status='active' + AND id IN (SELECT watch_id FROM bell_price_subscriptions WHERE offer_id=$1)`, [job.target]); + if (job.attempts >= 8) { + await db.query("UPDATE bell_price_offers SET next_at=clock_timestamp()+$2*interval '1 hour' WHERE id=$1", [job.target, priceCheckHours]); + } + }); + if (job.attempts >= 8) { + await finishPriceJob(this.store.pool, job); + return true; + } + } + await retryPriceJob(this.store, job, { delay, error: error instanceof ProviderError ? `provider_http_${error.status}` : "price_job_failed" }); + console.warn("bell_price_job_failed", { kind: job.kind, attempts: job.attempts }); + } + return true; + } + + private run(job: PriceJob, signal: AbortSignal) { + return job.kind === "send" ? dispatchAlert(this.store, job, this.sources, signal, this.send) : this.observe(job, signal); + } + + private async observe(job: PriceJob, signal: AbortSignal) { + const offer = await storedObservation(this.store.pool, job.target); + if (!offer) return; + const item = await this.sources.verify(offer.url, offer.country, signal); + if (!item || offerId(item) !== job.target || item.expiresAt <= Date.now()) throw new Error("Listing evidence is unavailable"); + + await this.store.transaction(async db => { + if (!await lockClaim(db, job)) return; + const watched = await db.query(`SELECT w.* FROM bell_price_watches w JOIN bell_price_subscriptions s ON s.watch_id=w.id + WHERE s.offer_id=$1 AND w.status IN ${watching} AND expires_at>clock_timestamp() ORDER BY w.id FOR UPDATE OF w`, [job.target]); + const result = await db.query(`UPDATE bell_price_offers SET observation=$2,verified_at=$3, + next_at=clock_timestamp()+$4*interval '1 hour' + WHERE id=$1 AND verified_at<=$3`, [job.target, item, new Date(item.observedAt), priceCheckHours]); + if (!result.rowCount) return; + for (const watch of watched.rows) { + if (qualifies(item, watch.terms)) await reserveAlert(db, watch.id, item); + else if (watch.status === "degraded") await db.query("UPDATE bell_price_watches SET status='active' WHERE id=$1", [watch.id]); + } + }); + } +} diff --git a/tests/linq.test.ts b/tests/linq.test.ts index affba1e..1ad8032 100644 --- a/tests/linq.test.ts +++ b/tests/linq.test.ts @@ -2,6 +2,7 @@ import { createHmac, randomUUID } from "node:crypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import linq from "../agent/channels/linq"; +import { digest } from "../server/shopping/config"; import { ContextContainer, contextStorage } from "../node_modules/eve/dist/src/context/container.js"; import { SessionKey } from "../node_modules/eve/dist/src/context/keys.js"; import type { ChannelAdapter } from "../node_modules/eve/dist/src/channel/adapter.js"; @@ -92,12 +93,26 @@ describe("Bell's signed Linq webhook", () => { expect(dispatch).toHaveBeenCalledOnce(); expect(dispatch).toHaveBeenCalledWith(event.data.parts[0].value, expect.objectContaining({ context: [expect.stringContaining("Bell's private Linq")], - auth: expect.objectContaining({ principalId: "linq:sender-handle-id", principalType: "user", attributes: expect.objectContaining({ bell_watch_chat: event.data.chat.id, bell_watch_sender: senderNumber, bell_watch_line: receivingNumber }) }), + auth: expect.objectContaining({ principalId: "linq:sender-handle-id", principalType: "user", attributes: expect.objectContaining({ bell_watch_chat: event.data.chat.id, bell_watch_sender: senderNumber, bell_watch_line: receivingNumber, bell_linq_message: event.data.id, bell_linq_sent_at: event.data.sent_at }) }), state: { thread: expect.objectContaining({ isDM: true }) }, })); expect(fetch).toHaveBeenCalledOnce(); }); + it("binds a price-watch request to the text and product link delivered together", async () => { + const event = message(); + const request = "Tell me when this drops below $100"; + const link = "https://example.com/product"; + event.data.parts = [{ type: "text", value: request }, { type: "link", value: link }]; + const { dispatch } = await deliver(event); + const text = `${request}\n${link}`; + expect(dispatch).toHaveBeenCalledWith(text, expect.objectContaining({ + auth: expect.objectContaining({ attributes: expect.objectContaining({ + bell_linq_message: event.data.id, bell_linq_text_hash: digest(text), + }) }), + })); + }); + it("keeps follow-ups on the same Eve channel address with steer enabled", async () => { const chatId = randomUUID(); const first = await deliver(message(chatId)); diff --git a/tests/price-watches.test.ts b/tests/price-watches.test.ts new file mode 100644 index 0000000..39135d9 --- /dev/null +++ b/tests/price-watches.test.ts @@ -0,0 +1,765 @@ +import { randomUUID } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import type { ToolContext } from "eve/tools"; +import { Pool } from "pg"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { signedPriceMessage } from "../agent/lib/monitors"; +import { ProviderError } from "../server/monitors/provider"; +import { MonitorService } from "../server/monitors/service"; +import { MonitorStore } from "../server/monitors/store"; +import { priceLineForOperator } from "../server/operator-auth"; +import { digest } from "../server/shopping/config"; +import { dispatchAlert } from "../server/shopping/delivery"; +import { listingUrl, parseMerchantEvidence, priceMinor, qualifies, type Observation, type WatchTerms } from "../server/shopping/evidence"; +import { sendPriceAlert, type Delivery } from "../server/shopping/providers"; +import * as merchantPage from "../server/shopping/public-page"; +import { discoverListings } from "../server/shopping/search"; +import { claimPriceJob, finishPriceJob, type Inbound } from "../server/shopping/store"; +import { PriceWatches, shoppingSources, type ShoppingSources } from "../server/shopping/watches"; +import { PriceWorker } from "../server/shopping/worker"; + +const url = "https://example.com/product?variant=blue-128"; +const second = "https://another.example.com/product?variant=blue-128"; +const terms = { product: "Phone Blue 128 GB", url, currency: "GBP", country: "GB", amount: "250", condition: "new", comparison: "below" } satisfies WatchTerms; +const destination = { chat: "chat-a", sender: "+12025550123", line: "+12025550100" }; +const owner = { issuer: "linq", id: "linq:sender" }; +const identity = "mpn:acme:blue-128"; +const timestamp = () => new Date().toISOString(); +const inbound = (messageId = randomUUID()): Inbound => ({ destination, owner, messageId, sentAt: timestamp() }); +const verified = (amount: number, inStock = true, listing = url): Observation => ({ + url: listing, product: terms.product, identity, variant: "blue-128", seller: "Example Shop", + condition: "new", country: "GB", currency: "GBP", amount, inStock, observedAt: Date.now(), expiresAt: Date.now() + 300_000, +}); + +function product(availability = "InStock", price = "249.99", listing = url, country = "GB") { + return { + "@type": "Product", url: listing, name: terms.product, sku: "blue-128", mpn: "blue-128", brand: { name: "Acme" }, + offers: { "@type": "Offer", url: listing, seller: { name: "Example Shop" }, availability: `https://schema.org/${availability}`, + itemCondition: "https://schema.org/NewCondition", priceCurrency: "GBP", price, eligibleRegion: country }, + }; +} + +function page(data: unknown, extra = "", ageSeconds = 0) { + return { url, html: `${extra}`, ageSeconds }; +} + +const shoes = (size: string, price: string, host = "example.com", gtin?: string) => { + const listing = `https://${host}/shoes?size=${size}`; + const markup = { ...product("InStock", price, listing), name: "Acme Trail Runner", size, + sku: `${host}-trail-${size}`, mpn: "TRAIL", gtin }; + return { ...page(markup), url: listing }; +}; +const shoeTerms = { ...terms, url: undefined, product: "Acme Trail Runner", amount: "120" }; + +function stubConfig() { + vi.stubEnv("DATABASE_URL", "postgresql://unused.local/db"); + vi.stubEnv("PARALLEL_API_KEY", "test-parallel"); + vi.stubEnv("CRON_SECRET", "test-cron"); + vi.stubEnv("LINQ_API_KEY", "test-linq"); + vi.stubEnv("LINQ_WEBHOOK_SECRET", "test-linq-webhook"); + vi.stubEnv("BELL_LINQ_PHONE_NUMBER", destination.line); + vi.stubEnv("BELL_LINQ_ALLOWED_SENDERS", destination.sender); + vi.stubEnv("BELL_PRICE_WATCHES_ENABLED", "true"); +} +afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); }); + +describe("Product and merchant evidence", () => { + it("requires selected-variant, seller, market and stock evidence in minor units", () => { + const item = parseMerchantEvidence(page(product()), "GB"); + expect(item).toMatchObject({ identity, variant: "blue-128", seller: "Example Shop", amount: 24999, inStock: true }); + expect(qualifies(item!, terms)).toBe(true); + const equal = parseMerchantEvidence(page(product("InStock", "250")), "GB")!; + expect(qualifies(equal, terms)).toBe(false); + expect(qualifies(equal, { ...terms, comparison: "at_or_below" })).toBe(true); + expect(qualifies(parseMerchantEvidence(page(product("OutOfStock")), "GB")!, terms)).toBe(false); + expect(priceMinor("250.01", "JPY")).toBeNull(); + expect(priceMinor("250", "JPY")).toBe(250); + expect(priceMinor("1.001", "KWD")).toBe(1001); + }); + + it("rejects a group, wrong default, contradictory selected SKU, conditional price, pickup, stale or mislocalized evidence", () => { + const selected = product(); + expect(parseMerchantEvidence(page({ "@type": "ProductGroup", offers: selected.offers }), "GB")).toBeNull(); + expect(parseMerchantEvidence(page(product("InStock", "50", "https://example.com/product")), "GB")).toBeNull(); + expect(parseMerchantEvidence(page(selected, '
'), "GB")).toBeNull(); + expect(parseMerchantEvidence(page({ ...selected, offers: { ...selected.offers, eligibleCustomerType: "Member" } }), "GB")).toBeNull(); + expect(parseMerchantEvidence(page({ ...selected, offers: { ...selected.offers, availableDeliveryMethod: "OnSitePickup" } }), "GB")).toBeNull(); + expect(parseMerchantEvidence(page({ ...selected, offers: { ...selected.offers, "@type": "AggregateOffer" } }), "GB")).toBeNull(); + expect(parseMerchantEvidence(page(selected, "", 301), "GB")).toBeNull(); + expect(parseMerchantEvidence(page({ ...selected, offers: { ...selected.offers, priceValidUntil: "2000-01-01" } }), "GB")).toBeNull(); + expect(parseMerchantEvidence(page(product("InStock", "50", url, "IE")), "GB")).toBeNull(); + expect(parseMerchantEvidence(page({ ...selected, offers: { ...selected.offers, availability: "LimitedAvailability" } }), "GB")).toBeNull(); + }); + + it("rejects merchant markup that contradicts the listing's selected size or market", () => { + const shoes = (listing: string, size: string) => ({ ...page({ ...product("InStock", "100", listing), size }), url: listing }); + const sized = "https://example.com/shoes?size=10"; + expect(parseMerchantEvidence(shoes(sized, "9"), "GB")).toBeNull(); + expect(parseMerchantEvidence(shoes(sized, "10"), "GB")).toMatchObject({ url: sized, amount: 10_000 }); + const us = `${sized}&country=US`; + expect(parseMerchantEvidence(shoes(us, "10"), "GB")).toBeNull(); + const dollars = `${sized}¤cy=USD`; + expect(parseMerchantEvidence(shoes(dollars, "10"), "GB")).toBeNull(); + }); + + it("requires evidence for each selected variant beyond the listing URL itself", () => { + const listing = "https://example.com/shoes?size=10&color=blue"; + const evidence = (url: string, extra: Record) => + ({ ...page({ ...product("InStock", "100", url), ...extra }), url }); + expect(parseMerchantEvidence(evidence(listing, { size: "10" }), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence(listing, { size: "10", color: { name: "Blue" } }), "GB")) + .toMatchObject({ url: listing, amount: 10_000 }); + const opaque = "https://example.com/shoes?color_id=7"; + expect(parseMerchantEvidence(evidence(opaque, { color: "Blue" }), "GB")).toBeNull(); + const local = `${listing}&locale=zh-Hant-TW`; + expect(parseMerchantEvidence(evidence(local, { size: "10", color: "Blue" }), "GB")).toBeNull(); + }); + + it("rejects an offer explicitly targeting another or unresolved product variant", () => { + const selected = { ...product(), "@id": "#blue-128" }; + const different = { "@type": "Product", "@id": "#red-64", name: "Phone Red 64 GB", sku: "red-64" }; + const evidence = (itemOffered: unknown) => page({ + "@context": "https://schema.org", + "@graph": [{ ...selected, offers: { ...selected.offers, itemOffered, price: "149.99" } }, different], + }); + + for (const target of [different, { "@id": different["@id"] }, { "@id": "#missing" }, + { "@id": selected["@id"], sku: different.sku }, [{ "@id": selected["@id"] }, different], + { "@type": "Product", name: selected.name }]) { + expect(parseMerchantEvidence(evidence(target), "GB")).toBeNull(); + } + for (const target of [undefined, { "@id": selected["@id"] }, { "@type": "Product", sku: selected.sku }]) { + expect(parseMerchantEvidence(evidence(target), "GB")).toMatchObject({ variant: selected.sku, amount: 14999 }); + } + }); + + it("requires market proof when an offer declares conflicting or unresolved regions", () => { + const selected = product(); + const shippingDetails = { shippingDestination: { addressCountry: "GB" } }; + const evidence = (extra: Record) => + page({ ...selected, offers: { ...selected.offers, shippingDetails, ...extra } }); + expect(parseMerchantEvidence(evidence({ eligibleRegion: "United States" }), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence({ ineligibleRegion: "United Kingdom" }), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence({ ineligibleRegion: ["US", { addressCountry: "CA" }] }), "GB")) + .toMatchObject({ country: "GB", currency: "GBP" }); + }); + + it("retains merchant proof of a named part number when the same offer also publishes a GTIN", () => { + const item = parseMerchantEvidence(page({ ...product(), gtin13: "4006381333931" }), "GB"); + expect(item).toMatchObject({ identity: "gtin:04006381333931" }); + expect(qualifies(item!, { ...terms, brand: "Acme", mpn: "blue-128" })).toBe(true); + expect(qualifies(item!, { ...terms, brand: "Acme", mpn: "red-128" })).toBe(false); + }); + + it("reads offer scripts only from live HTML elements", () => { + const json = JSON.stringify(product()); + const script = ``; + for (const html of [ + ``, + ``, + ``, + `
Out of stock
`, + `
Out of stock
`, + `
Out of stock
`, + `
Out of stock${script}
`, + ]) { + expect.soft(parseMerchantEvidence({ url, html, ageSeconds: 0 }, "GB")).toBeNull(); + } + const html = ``; + expect(parseMerchantEvidence({ url, html, ageSeconds: 0 }, "GB")).toMatchObject({ url, amount: 24999 }); + }); + + it("requires countrywide eligibility and shipping evidence for a country-level market", () => { + const selected = product(); + const country = { "@type": "DefinedRegion", addressCountry: "GB" }; + const postcode = { ...country, postalCodePrefix: "BT" }; + const evidence = (eligibleRegion?: unknown, shippingDestination?: unknown) => page({ + ...selected, + offers: { ...selected.offers, eligibleRegion, shippingDetails: { shippingDestination } }, + }); + expect(parseMerchantEvidence(evidence(undefined, postcode), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence("GB", postcode), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence({ ...country, addressRegion: "Wales" }, country), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence("GB", [postcode, country]), "GB")).toMatchObject({ country: "GB" }); + }); + + it("honors shipping exclusions even when a country is otherwise eligible", () => { + const selected = product(); + const ships = { shippingDestination: { addressCountry: "GB" }, doesNotShip: false }; + const blocked = { ...ships, doesNotShip: true }; + const evidence = (shippingDetails: unknown, eligibleRegion?: string) => + page({ ...selected, offers: { ...selected.offers, eligibleRegion, shippingDetails } }); + + expect(parseMerchantEvidence(evidence(ships), "GB")).toMatchObject({ country: "GB" }); + expect(parseMerchantEvidence(evidence(blocked), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence(blocked, "GB"), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence([ships, { ...blocked, shippingDestination: { addressCountry: "GB", postalCodePrefix: "BT" } }]), "GB")).toBeNull(); + expect(parseMerchantEvidence(evidence([ships, { ...blocked, shippingDestination: { addressCountry: "US" } }]), "GB")) + .toMatchObject({ country: "GB" }); + }); + + it("requires a purchase offer within its declared availability window", () => { + const selected = product(); + const now = Date.parse("2026-11-23T22:00:00Z"); + const past = "2026-11-23T21:59:00Z", future = "2026-11-23T22:01:00Z"; + const evidence = (extra: Record) => + parseMerchantEvidence(page({ ...selected, offers: { ...selected.offers, ...extra } }), "GB", now); + + expect(evidence({ availabilityStarts: future })).toBeNull(); + expect(evidence({ availabilityStarts: "0" })).toBeNull(); + expect(evidence({ availabilityEnds: past })).toBeNull(); + expect(evidence({ availabilityEnds: 123 })).toBeNull(); + expect(evidence({ businessFunction: "http://purl.org/goodrelations/v1#LeaseOut" })).toBeNull(); + const open = evidence({ availabilityStarts: past, availabilityEnds: future, + businessFunction: { "@id": "http://purl.org/goodrelations/v1#Sell" } }); + expect(open).toMatchObject({ inStock: true, expiresAt: Date.parse(future) }); + expect(qualifies(open!, terms, now)).toBe(true); + expect(qualifies(open!, terms, Date.parse(future))).toBe(false); + }); + + it("checks selected SKU values only on live element attributes", () => { + for (const extra of [ + '', + '', + '', + '
', + ]) { + expect.soft(parseMerchantEvidence(page(product(), extra), "GB")).toMatchObject({ variant: "blue-128", amount: 24999 }); + } + expect(parseMerchantEvidence(page(product(), '
'), "GB")).toBeNull(); + expect(parseMerchantEvidence(page(product(), '
'), "GB")) + .toMatchObject({ variant: "blue-128" }); + }); + + it("restricts public destinations and preserves known variant selectors", () => { + expect(listingUrl.parse(url)).toBe(url); + expect(listingUrl.parse(`${url}&utm_source=example`)).toBe(url); + expect(listingUrl.safeParse(`${url}&session_token=abc`).success).toBe(false); + expect(listingUrl.safeParse(`${url}#access_token=abc`).success).toBe(false); + expect(listingUrl.safeParse("https://a.local/p").success).toBe(false); + expect(listingUrl.safeParse("https://[::1]/").success).toBe(false); + for (const ip of ["127.0.0.1", "169.254.1.2", "10.2.3.4", "172.16.0.2", "100.64.2.3", "::ffff:127.0.0.1", "fc00::1", "fe80::1", "2001:db8::1"]) { + expect(merchantPage.isPublicAddress(ip), ip).toBe(false); + } + expect(merchantPage.isPublicAddress("93.184.216.34")).toBe(true); + expect(merchantPage.isPublicAddress("2606:4700::1")).toBe(true); + }); + + it("requests Shopping leads for the target market and lets merchant evidence establish eligibility", async () => { + vi.stubEnv("PARALLEL_API_KEY", "test-parallel"); + const http = vi.fn(async (input: string, init?: RequestInit) => { + expect(input).toBe("https://api.parallel.ai/v1/shopping/search"); + expect(JSON.parse(String(init?.body))).toEqual({ + search_queries: [expect.stringContaining("Phone Blue 128 GB GB GBP")], mode: "advanced", condition: "any", + advanced_settings: { location: "gb", max_results: 8 }, + }); + return Response.json({ warnings: [{ message: "Using the default market (us)." }], results: [{ url, offers: [{ url: second }] }] }); + }); + vi.stubGlobal("fetch", http); + expect(await discoverListings(terms.product, "GB", "GBP")).toEqual([url, second]); + }); + + it("keeps scope and time from the authenticated message rather than a steered transcript", () => { + const text = "Text me when this drops below £250."; + const ctx = { + session: { auth: { current: { authenticator: "linq-message", principalType: "user", principalId: owner.id, issuer: owner.issuer, + attributes: { bell_watch_chat: destination.chat, bell_watch_sender: destination.sender, bell_watch_line: destination.line, + bell_linq_message: "provider-id", bell_linq_text_hash: digest(text) } } } }, + messages: [{ role: "user", content: text }], + } as unknown as ToolContext; + expect(signedPriceMessage(ctx)).toMatchObject({ messageId: "provider-id", destination, owner }); + const steered = { ...ctx, messages: [...ctx.messages, { role: "user" as const, content: "actually stop it" }] }; + expect(() => signedPriceMessage(steered)).toThrow("exact current Linq message"); + }); + + it("requires the operator's Basic Auth before disclosing the configured phone line", () => { + stubConfig(); + vi.stubEnv("BELL_OPERATOR_USERNAME", "operator"); + vi.stubEnv("BELL_OPERATOR_PASSWORD", "synthetic-test-password-over-32-bytes"); + const auth = new Headers({ authorization: "Basic " + Buffer.from("operator:synthetic-test-password-over-32-bytes").toString("base64") }); + expect(priceLineForOperator(new Headers())).toBeUndefined(); + expect(priceLineForOperator(auth)).toBe(destination.line); + vi.stubEnv("BELL_PRICE_WATCHES_ENABLED", "false"); + expect(priceLineForOperator(auth)).toBeUndefined(); + }); + + it("correlates a Linq acceptance or failed status with the original destination", async () => { + stubConfig(); + let status = "queued", line = destination.line, chat = destination.chat; + const http = vi.fn(async (_url: string, init: RequestInit) => { + expect(JSON.parse(String(init.body))).toEqual({ message: { parts: [{ type: "text", value: "sample" }], idempotency_key: "one-key" } }); + return Response.json({ chat_id: chat, message: { id: "out-1", delivery_status: status, from_handle: { handle: line } } }); + }); + vi.stubGlobal("fetch", http); + expect(await sendPriceAlert(destination, "sample", "one-key")).toEqual({ state: "accepted", messageId: "out-1", status: "queued" }); + status = "failed"; + expect(await sendPriceAlert(destination, "sample", "one-key")).toEqual({ state: "failed", messageId: "out-1", status: "failed" }); + chat = "other-chat"; + expect(await sendPriceAlert(destination, "sample", "one-key")).toEqual({ state: "uncertain" }); + chat = destination.chat; + line = "+12025550199"; + expect(await sendPriceAlert(destination, "sample", "one-key")).toEqual({ state: "uncertain" }); + http.mockImplementationOnce(async () => new Response(null, { status: 403 })); + await expect(sendPriceAlert(destination, "sample", "one-key")).rejects.toMatchObject({ status: 403 }); + }); + +}); + +const databaseUrl = process.env.TEST_MONITOR_DATABASE_URL; +if (process.env.CI && !databaseUrl) throw new Error("TEST_MONITOR_DATABASE_URL is required in CI"); +describe.skipIf(!databaseUrl)("Durable price alerts", () => { + const schema = `price_${randomUUID().replaceAll("-", "")}`; + let admin: Pool, pool: Pool, store: MonitorStore; + let watches: PriceWatches, sources: ShoppingSources, worker: PriceWorker, amount: number, inStock: boolean; + let verify: ReturnType>; + let send: ReturnType Promise>>; + + beforeAll(async () => { + admin = new Pool({ connectionString: databaseUrl }); + await admin.query(`CREATE SCHEMA ${schema}`); + pool = new Pool({ connectionString: databaseUrl, options: `-c search_path=${schema}`, max: 8 }); + for (const migration of ["004_parallel_monitors", "005_monitor_frequency", "007_price_watches", "007_price_watches", "008_price_action_keys"]) { + await pool.query(await readFile(new URL(`../migrations/${migration}.sql`, import.meta.url), "utf8")); + } + }); + beforeEach(async () => { + await pool.query("TRUNCATE bell_price_watches, bell_price_actions, bell_price_offers, bell_price_jobs, bell_monitor_inbox, bell_monitors CASCADE"); + stubConfig(); + store = new MonitorStore(pool); + amount = 30_000; + inStock = true; + verify = vi.fn(async listing => verified(amount, inStock, listing)); + sources = { discover: vi.fn(async () => [url]), verify }; + send = vi.fn(async (_destination, _body, key) => ({ state: "accepted", messageId: key, status: "queued" })); + watches = new PriceWatches(store, sources); + worker = new PriceWorker(store, sources, send); + }); + afterAll(async () => { + await pool?.end(); + if (admin) { await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); } + }); + async function due() { + await pool.query("UPDATE bell_price_offers SET next_at=clock_timestamp()-interval '1 minute'"); + await worker.schedule(); + } + async function tick(priceWorker = worker) { + await priceWorker.runOne(Date.now() + 5000); + } + async function stopMessage() { + const { rows: [row] } = await pool.query<{ sent_at: string }>("SELECT to_json(clock_timestamp()) AS sent_at"); + return { ...inbound(), sentAt: row.sent_at }; + } + function watchId(result: Awaited>) { + if (!("id" in result)) throw new Error(`Expected watch enrollment, got ${result.status}`); + return result.id; + } + const count = async (table: string) => Number((await pool.query(`SELECT count(*) FROM ${table}`)).rows[0].count); + + it("resolves a named size before comparing prices and accepts equivalent merchant SKUs", async () => { + const size8 = shoes("8", "151"); + const size9 = shoes("9", "89"); + const pages = new Map([size8, size9].map(listing => [listing.url, listing])); + vi.mocked(sources.discover).mockImplementation(async () => [...pages.keys()]); + verify.mockImplementation(async (url, country) => parseMerchantEvidence(pages.get(url)!, country)); + + expect(await watches.enroll(inbound(), shoeTerms)).toMatchObject({ status: "needs_details" }); + expect(await watches.enroll(inbound(), { ...shoeTerms, brand: "Acme", mpn: "TRAIL" })).toMatchObject({ status: "needs_details" }); + expect(await watches.enroll(inbound(), { ...shoeTerms, variant: "9" })).toMatchObject({ status: "match", offer: { url: size9.url } }); + expect(await watches.enroll(inbound(), { ...shoeTerms, url: size9.url })).toMatchObject({ status: "match", offer: { url: size9.url } }); + + const size9Other = shoes("9", "75", "another.example.com"); + pages.set(size9Other.url, size9Other); + pages.delete(size8.url); + expect(await watches.enroll(inbound(), shoeTerms)).toMatchObject({ status: "match", offer: { url: size9Other.url } }); + + const sameGtin = "00012345678905"; + pages.set(size9.url, shoes("9", "89", "example.com", sameGtin)); + expect(await watches.enroll(inbound(), shoeTerms)).toMatchObject({ status: "match", offer: { url: size9Other.url } }); + pages.set(size9Other.url, shoes("9", "75", "another.example.com", sameGtin)); + expect(await watches.enroll(inbound(), shoeTerms)).toMatchObject({ status: "match", offer: { url: size9Other.url } }); + }); + + it("does not alert for a different size on a pinned listing that reuses a SKU", async () => { + const listing = "https://example.com/shoes"; + let size = "8"; + verify.mockImplementation(async () => parseMerchantEvidence({ + ...page({ ...product("InStock", String(amount / 100), listing), name: shoeTerms.product, size }), + url: listing, + }, "GB")); + await watches.enroll(inbound(), { ...shoeTerms, url: listing }); + + amount = 8_900; + size = "9"; + await due(); + await tick(); + await tick(); + expect(send).not.toHaveBeenCalled(); + + size = "8"; + await due(); + await tick(); + await tick(); + expect(send).toHaveBeenCalledTimes(1); + }); + + it("asks for details when a repeated named watch resolves to a conflicting size", async () => { + const size8 = shoes("8", "151"); + const size9 = shoes("9", "149"); + let listing = size8; + vi.mocked(sources.discover).mockImplementation(async () => [listing.url]); + verify.mockImplementation(async () => parseMerchantEvidence(listing, "GB")); + const first = await watches.enroll(inbound(), shoeTerms); + expect(first).toMatchObject({ status: "active" }); + expect(await watches.enroll(inbound(), shoeTerms)).toMatchObject({ id: watchId(first) }); + + listing = size9; + expect(await watches.enroll(inbound(), shoeTerms)).toMatchObject({ status: "needs_details" }); + expect(await count("bell_price_watches")).toBe(1); + }); + + it("does not send a reservation contradicted by a newer read during a dispatch pause", async () => { + const result = await watches.enroll(inbound(), terms); + await watches.enroll(inbound(), { ...terms, amount: "200" }); + const observedAt = Date.now(); + verify.mockResolvedValueOnce({ ...verified(23_000), observedAt, expiresAt: observedAt + 300_000 }); + await due(); + await tick(); + vi.stubEnv("BELL_PRICE_WATCHES_ENABLED", "false"); + await expect(watches.enroll(inbound(), terms)).rejects.toThrow("currently unavailable"); + await tick(); + expect(send).not.toHaveBeenCalled(); + verify.mockResolvedValueOnce({ ...verified(23_000, false), observedAt: observedAt + 1, expiresAt: observedAt + 300_001 }); + await due(); + await tick(); + vi.stubEnv("BELL_PRICE_WATCHES_ENABLED", "true"); + await pool.query("UPDATE bell_price_jobs SET next_at=clock_timestamp() WHERE kind='send'"); + const staleJob = await claimPriceJob(pool); + expect(staleJob.kind).toBe("send"); + await dispatchAlert(store, staleJob, sources, new AbortController().signal, send); + expect(send).not.toHaveBeenCalled(); + const reservation = (await pool.query("SELECT status, dispatch_at FROM bell_price_watches WHERE id=$1", [watchId(result).slice(6)])).rows[0]; + expect(reservation).toEqual({ status: "active", dispatch_at: null }); + + verify.mockResolvedValueOnce({ ...verified(23_000), observedAt: observedAt + 2, expiresAt: observedAt + 300_002 }); + // Another worker observes a fresh match before the old send worker finishes its tick. + await worker.schedule(); + await tick(); + await finishPriceJob(pool, staleJob); + await tick(); + expect(send).toHaveBeenCalledTimes(1); + }); + + it("replays an immediate match without enrolling after a price increase", async () => { + amount = 24_999; + const message = inbound(); + expect(await watches.enroll(message, terms)).toMatchObject({ status: "match" }); + amount = 30_000; + expect(await new PriceWatches(store, sources).enroll(message, terms)).toMatchObject({ status: "match" }); + expect(verify).toHaveBeenCalledTimes(1); + expect(await count("bell_price_watches")).toBe(0); + }); + + it("shares public verification and sends one text per matching shopper after a price drop", async () => { + const other = { ...inbound(), destination: { ...destination, chat: "chat-b" } }; + const [first, second] = await Promise.all([watches.enroll(inbound(), terms), watches.enroll(other, terms)]); + expect(first).toMatchObject({ status: "active" }); + expect(second).toMatchObject({ status: "active" }); + expect(await count("bell_price_offers")).toBe(1); + verify.mockClear(); + amount = 24_900; + await due(); + expect(await count("bell_price_jobs")).toBe(1); + await Promise.all([tick(), tick()]); + expect(verify).toHaveBeenCalledTimes(1); + await Promise.all([tick(), tick(), tick()]); + await due(); + await tick(); + expect(send).toHaveBeenCalledTimes(2); + expect(send).toHaveBeenCalledWith(destination, expect.stringContaining(`GBP 249.00 before tax and shipping.\n${url}`), expect.stringMatching(/^bell-price-/), expect.any(AbortSignal)); + expect((await pool.query("SELECT DISTINCT status, delivery_status FROM bell_price_watches")).rows).toEqual([{ status: "accepted", delivery_status: "queued" }]); + expect(await count("bell_price_subscriptions")).toBe(0); + }); + + it("deduplicates equivalent requests, persists stops and does not reopen a replayed enrollment", async () => { + const original = inbound(); + const [created, duplicate] = await Promise.all([watches.enroll(original, terms), watches.enroll(inbound(), { ...terms, amount: "250.00" })]); + expect(watchId(created)).toBe(watchId(duplicate)); + const stop = await stopMessage(); + expect(await watches.stop(stop, watchId(created).slice(6))).toMatchObject({ status: "stopped" }); + expect(await watches.enroll(original, terms)).toMatchObject({ status: "stopped" }); + const recreated = await watches.enroll(inbound(), terms); + expect(watchId(recreated)).not.toBe(watchId(created)); + expect(await watches.stop(stop, watchId(created).slice(6))).toMatchObject({ id: watchId(created), status: "stopped" }); + const delayed = { ...inbound(), sentAt: "2000-01-01T00:00:00Z" }; + expect(await watches.stop(delayed, watchId(recreated).slice(6))).toMatchObject({ status: "not_found" }); + expect(await watches.stop({ ...inbound(), destination: { ...destination, chat: "another" } }, watchId(recreated).slice(6))).toMatchObject({ status: "not_found" }); + const listed = await watches.list(owner, destination, "all"); + expect(listed.watches).toEqual([ + expect.objectContaining({ id: watchId(recreated), status: "active" }), + expect.objectContaining({ id: watchId(created), status: "stopped" }), + ]); + }); + + it("stops both watches from one text and replays each stop independently", async () => { + const firstId = watchId(await watches.enroll(inbound(), terms)); + const secondId = watchId(await watches.enroll(inbound(), { ...terms, amount: "200" })); + const stop = await stopMessage(); + + expect(await watches.stop(stop, firstId.slice(6))).toEqual({ id: firstId, status: "stopped" }); + expect(await watches.stop(stop, secondId.slice(6))).toEqual({ id: secondId, status: "stopped" }); + expect(await watches.stop(stop, secondId.slice(6))).toEqual({ id: secondId, status: "stopped" }); + expect(await watches.stop(stop, firstId.slice(6))).toEqual({ id: firstId, status: "stopped" }); + expect((await watches.list(owner, destination, "open")).watches).toEqual([]); + expect(await count("bell_price_subscriptions")).toBe(0); + + amount = 19_900; + await due(); + await tick(); + await tick(); + expect(send).not.toHaveBeenCalled(); + }); + + it("enrolls distinct requests from one text and replays equivalent prices", async () => { + const message = inbound(); + const first = await watches.enroll(message, terms); + const second = await watches.enroll(message, { ...terms, amount: "200" }); + expect(watchId(first)).not.toBe(watchId(second)); + + expect(await watches.enroll(message, { ...terms, amount: "0250.00" })).toEqual(first); + expect(await watches.enroll(message, { ...terms, amount: "200.0" })).toEqual(second); + expect(verify).toHaveBeenCalledTimes(2); + expect(await count("bell_price_watches")).toBe(2); + }); + + it("preserves enrollment and stop outcomes already saved by migration 007", async () => { + const legacySchema = `${schema}_legacy`; + await admin.query(`CREATE SCHEMA ${legacySchema}`); + const legacy = new Pool({ connectionString: databaseUrl, options: `-c search_path=${legacySchema}` }); + try { + await legacy.query(await readFile(new URL("../migrations/007_price_watches.sql", import.meta.url), "utf8")); + const message = inbound(); + const stoppedId = randomUUID(); + const match = { status: "match", offer: verified(24_999) }; + const stopped = { status: "stopped", id: `price:${stoppedId}` }; + await legacy.query(`INSERT INTO bell_price_actions(issuer,owner_id,chat,line,message_id,action,request,outcome) + VALUES ($1,$2,$3,$4,$5,'enroll',$6,$7), ($1,$2,$3,$4,$5,'stop',$8,$9)`, + [owner.issuer, owner.id, destination.chat, destination.line, message.messageId, terms, match, { id: stoppedId }, stopped]); + + const migration = await readFile(new URL("../migrations/008_price_action_keys.sql", import.meta.url), "utf8"); + await legacy.query(migration); + await legacy.query(migration); + const upgraded = new PriceWatches(new MonitorStore(legacy), sources); + expect(await upgraded.enroll(message, { ...terms, amount: "250.00" })).toEqual(match); + expect(verify).not.toHaveBeenCalled(); + expect(await upgraded.stop(message, randomUUID())).toEqual({ status: "not_found" }); + expect(await upgraded.stop(message, stoppedId)).toEqual(stopped); + } finally { + await legacy.end(); + await admin.query(`DROP SCHEMA ${legacySchema} CASCADE`); + } + }); + + it("keeps the pasted link through a trailing-slash redirect and the later price alert", async () => { + let finalUrl = url.replace("/product?", "/product/?"); + using read = vi.spyOn(merchantPage, "readPublicPage").mockImplementation(async () => ({ + ...page(product("InStock", String(amount / 100), finalUrl)), url: finalUrl, + })); + verify.mockImplementation(shoppingSources.verify); + expect(await watches.enroll(inbound(), terms)).toMatchObject({ status: "active" }); + for (const changed of [url.replace("/product?", "/different?"), second, url.replace("blue-128", "red-64"), url + "&market=GB"]) { + const item = await shoppingSources.verify(changed, "GB"); + expect(item).toBeNull(); + } + finalUrl = url; + amount = 24_900; + await due(); + await tick(); + await tick(); + expect(read).toHaveBeenLastCalledWith(url, expect.any(Function), expect.any(AbortSignal)); + expect(send).toHaveBeenCalledExactlyOnceWith(destination, expect.stringContaining(url), expect.any(String), expect.any(AbortSignal)); + }); + + it("requires evidence for an exact listing even when its product ID is known", async () => { + verify.mockResolvedValue(null); + const pinned = { ...terms, brand: "Acme", mpn: "blue-128" }; + expect(await watches.enroll(inbound(), pinned)).toEqual({ status: "needs_details", reason: "unverified_listing" }); + expect(await count("bell_price_watches")).toBe(0); + expect(sources.discover).not.toHaveBeenCalled(); + expect(await watches.enroll(inbound(), { ...pinned, url: undefined })).toEqual({ status: "needs_details", reason: "unresolved_product" }); + }); + + it("watches only the verified listings found at enrollment", async () => { + vi.mocked(sources.discover).mockResolvedValueOnce([url, second]); + await watches.enroll(inbound(), { ...terms, url: undefined }); + expect(await count("bell_price_subscriptions")).toBe(2); + amount = 24_900; + await due(); + await tick(); + await tick(); + await tick(); + expect(sources.discover).toHaveBeenCalledOnce(); + expect(send).toHaveBeenCalledOnce(); + }); + + it("does not enroll a restock-only alert when the price already qualifies", async () => { + amount = 24_900; + inStock = false; + expect(await watches.enroll(inbound(), terms)).toMatchObject({ status: "at_target_out_of_stock", offer: { amount } }); + expect(await count("bell_price_watches")).toBe(0); + }); + + it.each(["returns", "throws"])("recovers a send whose lease expires before verification %s", async outcome => { + await watches.enroll(inbound(), terms); + amount = 24_000; + await due(); + await tick(); + await pool.query("UPDATE bell_price_watches SET alert=jsonb_set(alert,'{expiresAt}','0')"); + await pool.query("UPDATE bell_price_jobs SET attempts=7 WHERE kind='send'"); + verify.mockImplementationOnce(async () => { + await pool.query("UPDATE bell_price_jobs SET lease_until=clock_timestamp()-interval '1 second' WHERE kind='send'"); + if (outcome === "throws") throw new Error("verification timed out"); + return verified(amount); + }); + await tick(); + expect(send).not.toHaveBeenCalled(); + await tick(new PriceWorker(new MonitorStore(pool), sources, send)); + await tick(); + expect(send).toHaveBeenCalledTimes(1); + expect((await watches.list(owner, destination, "closed")).watches).toMatchObject([{ status: "accepted" }]); + }); + + it("keeps a failed-commit send on the frozen body and key across a new worker", async () => { + await watches.enroll(inbound(), terms); + amount = 24_000; + await due(); + await tick(); + send.mockImplementationOnce(async () => { + // An earlier POST might have arrived even though the response never reached the worker. + throw new Error("connection lost after request"); + }); + await tick(); + expect((await pool.query("SELECT status, dispatch_at FROM bell_price_watches")).rows[0]) + .toEqual({ status: "uncertain", dispatch_at: expect.any(Date) }); + await pool.query("UPDATE bell_price_jobs SET next_at=clock_timestamp()-interval '1 second'"); + await tick(new PriceWorker(new MonitorStore(pool), sources, send)); + expect(send).toHaveBeenCalledTimes(2); + expect(send.mock.calls[1].slice(0, 3)).toEqual(send.mock.calls[0].slice(0, 3)); + expect((await pool.query("SELECT status FROM bell_price_watches")).rows[0].status).toBe("accepted"); + }); + + it("suppresses a stopped reservation and does not send a stale possible earlier alert", async () => { + const first = await watches.enroll(inbound(), terms); + amount = 23_000; + await due(); + await tick(); + await watches.stop(inbound(), watchId(first).slice(6)); + await tick(); + expect(send).not.toHaveBeenCalled(); + + amount = 30_000; + const next = await watches.enroll(inbound(), terms); + amount = 23_000; + await due(); + for (let i = 0; i < 3 && send.mock.calls.length === 0; i++) { + send.mockImplementation(async () => { throw new Error("unknown receipt"); }); + await tick(); + } + expect(send).toHaveBeenCalledTimes(1); + amount = 31_000; + await pool.query("UPDATE bell_price_jobs SET next_at=clock_timestamp()-interval '1 second'"); + await tick(); + expect(send).toHaveBeenCalledTimes(1); + expect((await pool.query("SELECT status, delivery_status FROM bell_price_watches WHERE id=$1", [watchId(next).slice(6)])).rows[0]) + .toEqual({ status: "failed", delivery_status: "unresolved" }); + }); + + it.each(["not_sent", "unresolved"])("closes an exhausted send and lists delivery as %s", async delivery => { + const watch = await watches.enroll(inbound(), terms); + amount = 24_900; + await due(); + await tick(); + if (delivery === "not_sent") vi.stubEnv("LINQ_API_KEY", "different-test-key"); + else send.mockRejectedValue(new Error("no receipt")); + await pool.query("UPDATE bell_price_jobs SET attempts=7 WHERE kind='send'"); + await tick(); + + vi.stubEnv("LINQ_API_KEY", "test-linq"); + expect((await watches.list(owner, destination, "open")).watches).toEqual([]); + expect((await watches.list(owner, destination, "closed")).watches).toMatchObject([ + { id: watchId(watch), status: "failed", delivery_status: delivery }, + ]); + expect(await count("bell_price_subscriptions")).toBe(0); + await pool.query("UPDATE bell_price_jobs SET next_at=clock_timestamp()"); + await due(); + await tick(); + expect(send).toHaveBeenCalledTimes(delivery === "not_sent" ? 0 : 1); + }); + + it("records a permanent Linq rejection or an unconfirmed reply without sending again", async () => { + await watches.enroll(inbound(), terms); + await watches.enroll(inbound(), { ...terms, amount: "249" }); + amount = 24_800; + send.mockRejectedValueOnce(new ProviderError(403)).mockResolvedValueOnce({ state: "uncertain" }); + await due(); + await tick(); + await tick(); + await tick(); + await tick(); + expect(send).toHaveBeenCalledTimes(2); + expect((await watches.list(owner, destination, "open")).watches).toEqual([]); + const closed = (await watches.list(owner, destination, "closed")).watches; + expect(closed).toEqual(expect.arrayContaining([ + expect.objectContaining({ status: "failed", delivery_status: "linq_http_403" }), + expect.objectContaining({ status: "failed", delivery_status: "unresolved" }), + ])); + expect(await count("bell_price_jobs")).toBe(0); + amount = 30_000; + const previous = closed.find(watch => watch.delivery_status === "unresolved")!; + const replacement = await watches.enroll(inbound(), previous.terms); + expect(replacement).toMatchObject({ status: "active" }); + expect(watchId(replacement)).not.toBe(previous.id); + }); + + it("starts from a link alone and sends one Linq alert while the generic queue is backlogged", async () => { + const enrolled = await watches.enroll(inbound(), { ...terms, product: undefined }); + expect(enrolled).toMatchObject({ status: "active", terms: { product: terms.product } }); + expect(sources.discover).not.toHaveBeenCalled(); + const watch = watchId(enrolled); + amount = 24_900; + await pool.query("UPDATE bell_price_offers SET next_at=clock_timestamp()-interval '1 minute'"); + const event = { type: "monitor.execution.completed", timestamp: timestamp(), + data: { monitor_id: "unmatched", event: { type: "completion", monitor_ts: timestamp() } } }; + await pool.query("INSERT INTO bell_monitor_inbox(id,payload) SELECT 'backlog-'||n,$1::jsonb FROM generate_series(1,40) n", [event]); + const read = vi.spyOn(shoppingSources, "verify").mockImplementation(async listing => verified(amount, inStock, listing)); + const http = vi.fn(async (endpoint: string, init: RequestInit) => { + expect(endpoint).toBe(`https://api.linqapp.com/api/partner/v3/chats/${destination.chat}/messages`); + expect(init.method).toBe("POST"); + expect(JSON.parse(String(init.body))).toEqual({ message: { + parts: [{ type: "text", value: expect.stringContaining(`GBP 249.00 before tax and shipping.\n${url}`) }], + idempotency_key: `bell-price-${watch.slice(6)}`, + } }); + return Response.json({ chat_id: destination.chat, message: { id: "out-1", delivery_status: "queued" } }); + }); + vi.stubGlobal("fetch", http); + try { + const service = new MonitorService(store); + vi.stubEnv("BELL_PRICE_WATCHES_ENABLED", "false"); + await service.process(); + expect(read).not.toHaveBeenCalled(); + expect(http).not.toHaveBeenCalled(); + vi.stubEnv("BELL_PRICE_WATCHES_ENABLED", "true"); + await pool.query("INSERT INTO bell_monitor_jobs(id,kind,payload) SELECT id,'inbox',jsonb_build_object('id',id) FROM bell_monitor_inbox"); + expect(await service.process()).toEqual({ processed: 30 }); + expect(read).toHaveBeenCalledExactlyOnceWith(url, "GB", expect.any(AbortSignal)); + expect(await count("bell_monitor_jobs")).toBe(12); + expect(await service.process()).toEqual({ processed: 12 }); + expect(http).toHaveBeenCalledTimes(1); + expect((await pool.query("SELECT status, message_id, delivery_status FROM bell_price_watches WHERE id=$1", [watch.slice(6)])).rows[0]) + .toEqual({ status: "accepted", message_id: "out-1", delivery_status: "queued" }); + } finally { + read.mockRestore(); + await pool.query("TRUNCATE bell_monitor_jobs"); + } + }); + +});