diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ccb52cc..4f03d0e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,3 +46,8 @@ jobs: # The one command a newcomer runs first still ends with a filled shop # and an admin login that works - run: npm run preview -- --check + + # The same shop drawn by the second theme, through the Mallok CLI's + # publish and a real Worker, as `npm test` cannot: tests render pages + # inside workerd, and only this publishes the sample with its pictures + - run: npm run preview -- --theme editorial --check diff --git a/CLAUDE.md b/CLAUDE.md index 83d20af..56e2bb7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,19 +16,21 @@ Nundar is in development. `mallok@0.1.0-rc.11` carries plugin API 2 — the exte npm ci npm run build # mallok prepare (stages admin + theme assets) then a deploy dry run npm run preview # a filled local shop on a throwaway database; prints an admin login +npm run preview -- --theme editorial # the same shop, drawn by the second theme npm run dev # wrangler dev with local D1 and R2 that keep their data; starts empty, needs .dev.vars npm run lint # biome check . (npm run lint:fix to apply) npm run typecheck npm test # test:project, then test:shop npm run test:project # node --test: site config and sample content (test/*.test.ts) -npm run test:shop # vitest inside workerd: plugin and theme (test/shop, test/theme) +npm run test:shop # vitest inside workerd: the plugin and both themes (projects `site` and `editorial`) npx vitest run test/shop/rates.test.ts # one file npx vitest run test/shop/cart-route.test.ts -t "MOQ" # tests matching a name npm run smoke # a real request to a real local Worker npm run smoke:shop # the whole shop end to end on a throwaway local Worker +npm run starter:documents # rewrite src/starter/documents.generated.ts after changing content/ ``` -CI (`.github/workflows/ci.yml`) runs `npm ci` → lint → typecheck → test → build → smoke → smoke:shop. +CI (`.github/workflows/ci.yml`) runs `npm ci` → lint → typecheck → test → build → smoke → smoke:shop → `preview --check` for each theme. - **npm only.** Mallok's CLI refuses a project with a pnpm or yarn lockfile. Adding a dependency needs npm 11 (`npx npm@11 install …`): npm 10.9.7 crashes while adding some packages to this tree. `npm ci` works with either. - **Upgrading Mallok** is `npx mallok upgrade --to `, never a hand edit of `package.json`. @@ -42,6 +44,8 @@ CI (`.github/workflows/ci.yml`) runs `npm ci` → lint → typecheck → test - `src/plugins/shop/` — commerce logic and nothing about pages. `plugin.json` is the manifest (validated strictly by `definePlugin`: unknown fields are rejected, every declared hook and route needs an implementation and vice versa). `migrations/` holds SQL, `lib/` the logic, `routes/` the HTTP handlers, `index.ts` wires them. - `src/theme/` — how pages look and nothing else: `theme.json` (kinds, fields, options), `layouts/`, `partials/`, `locales/.json`, `assets/` (the stylesheet, four images, the fonts and their licences, and the scripts `theme.json` declares). It has no tables and no routes. - `content/` and `seed/` — the sample catalogue, a fictional titanium fastener supplier: 31 bundles in four languages, and one variant per SKU. `site.json` — the site's languages, kinds, navigation and theme options, which is where this site's own copy lives. +- `src/starter/` — the same sample as a starter that Mallok's first-run wizard offers (`createMallok({ starters })`): the documents of `content/`, listed in `documents.generated.ts` by `scripts/starter-documents.mjs` — never edit it by hand; `test/starter.test.ts` fails when it is not what `content/` gives — `site.json`'s settings, and the seed's variants and zones as records for the shop's panels, which `test/shop/starter.test.ts` holds to `seed/shop-sample.sql`. A starter carries no files, so its documents are stripped of their pictures (`withoutImages`). +- `src/theme-editorial/` and `src/worker/editorial.ts` — a second theme, and the same site built with it (design §21). It exists so that the theme contract has two implementations: it reads the same kinds, options, plugin layouts and language packs (the commerce theme's own `locales/`), draws them differently, and has no script and no file of its own. A site deploys it by pointing `main` in `wrangler.jsonc` at `src/worker/editorial.ts`. Mallok decides the contracts on both sides. Its documentation is the reference: `PLUGIN_API.md`, `THEME_FORMAT.md` and `CONTENT_FORMAT.md` in the Mallok repository (`node_modules/mallok/types/worker.d.ts` has the types). @@ -54,7 +58,7 @@ Mallok decides the contracts on both sides. Its documentation is the reference: - **Variants are edited in the admin**, in a `records` panel under the editor of every product (`attachTo` in `plugin.json`; the handlers are `lib/variant-records.ts`). Mallok checks each value against the field the manifest declares and never writes the table itself: `saveVariant` judges what only the shop can — a SKU that is taken, a lead time that ends before it starts — and writes the variant, its prices and the stock ledger in one batch after one read. `price` is the base price; `other_prices` are entered by hand and stored `manual`, and need a base price; any other currency is derived from the base price at the stored rate. Whether a derived price is out of date is asked inside the write, of the table as the batch runs — a decision taken from the earlier reading goes wrong when two saves cross. The stock field comes to the form empty and writes only when a figure is typed. A deleted product takes its variants with it (`onContentDelete`, once its last language has gone); one kept because an order names it gives its SKU back. - **Whoever changes what a page shows purges that product's tag**: a save or a delete in the admin, and a repricing chunk for the products whose prices moved, one call for the chunk. A handler does not wait for its purge — Mallok gathers two seconds of purges into one call, and a save that waited would take those two seconds — it hands the promise to `ctx.waitUntil`. A purge that does not happen leaves the pages to expire and is not a failed save. Mallok's `purgeTags` resolves, rather than rejects, when a purge was not attempted or was turned down, so its answer is read (`purgeOutcome`), never assumed. - **`lib/scheduled.ts`** does one small piece of work per minute tick: a repricing chunk in progress, else a rate fetch if due, else clearing expired carts. State between ticks is in `p_shop_state`. -- **Migrations**: additive and idempotent. Mallok's migrator drops whole-line `--` comments, then splits on `;` — a comment must have a line to itself. They run on the Worker's first request, not from a CLI. +- **Migrations**: additive and idempotent. Mallok's migrator drops whole-line `--` comments, then splits on `;` — a comment must have a line to itself. They run on the Worker's first request, not from a CLI, and Mallok records each by its id, so one that has run is never run again: a view is changed by a new migration that drops and makes it again (`0006_review.sql` does so for two of 0005's), never by editing the one that made it. `test/shop/schema.test.ts` lists every migration's id. - **The cart is two routes** (`routes/cart.ts`). `GET /_mallok/p/shop/cart` is the cart page: the plugin returns a view — `lib/cart-view.ts`, whose header is the contract — and the theme's `shop/cart` layout draws it. `POST /_mallok/p/shop/cart/update` is where every form that changes the cart posts: add, set, remove, choose a currency. It never renders: every answer is a 303 to the cart page, and a change that is refused goes there with the reason and the variant in the address (`?refused=below_moq&variant=…`). The cart page reads the figures from the database and says them — nothing else from the address reaches the page. Do not go back to rendering the refusal from the POST: Mallok lists a page under the route that rendered it, so its language switcher and canonical would point at an address that only takes a POST. Mallok keys a handler by its path, so the page and the form cannot share one. The language is the segment after the plugin's id (`/_mallok/p/shop/de/cart`), and `lib/paths.ts` builds every such address. The cart cookie is scoped to `/_mallok/p/shop`, which every language shares: Mallok bypasses its edge cache for any public request that carries a cookie. A cookie that names no live cart — expired, or an id somebody chose — is never taken up: the id is all that protects a cart, so only the shop issues one. - **A product can be bought when a visitor can see it**: `status = 'published' AND published_at <= now`, Mallok's own test — a page published for later is not out yet. Its name and its address are read from the core's `content` table (`title`, `path`), in the buyer's language, else the default one, else any it is out in. - **One rule says which currency a page or a cart is in** (`settleCurrency` in `lib/currency.ts`): the one asked for when everything has a price in it, else the base currency, else whatever is shared. A page and the cart it leads to must not disagree, so neither has a rule of its own. @@ -62,21 +66,33 @@ Mallok decides the contracts on both sides. Its documentation is the reference: - **A public page is the same for every visitor.** What is in a cart is never in one: the header's link to the cart, and the form a product page offers for a size, are rendered into the cached page and identical for all. The hook tells every page where the cart is (`cart_path`, `cart_action`) and costs no query for it. - **A cart is sent as one inquiry** — a request for a quote — by `POST /_mallok/p/shop/cart/inquiry` (`routes/inquiry.ts`, `lib/inquiries.ts`; design §18). Like the cart's other form it never renders: it answers 303 to the cart page with the inquiry's number (`?sent=RFQ-…`) or the kind of reason none was made (`?inquiry=invalid&field=email`), and **nothing a person typed travels in an address**. What can be sent is decided by `readCartFacts`, the cart page's own reading: every line in order, or without a price — a part with no price can be asked about though it cannot be ordered, which is why a product page offers a form for one (`addable` in the page's view). - **The inquiry's write is one batch**: the inquiry, its lines, the job that owes its emails, the cart emptied. The inquiry is written only while the cart is still exactly what is being sent — the same lines and quantities, and no other — and the visitor is under their limit (`MAX_INQUIRIES_PER_HOUR`, exact because it is counted inside the statement; requests with no `ipHash` are counted together), and everything after it is conditional on the inquiry being there — so two forms at once store one inquiry, a cart that changed meanwhile is not sent as it no longer is (`cart_changed`), and a refused one leaves the cart as it was. A request that wrote nothing reads why from the tables (`whyNotStored`), in an order that matters: the limit when the cart is unchanged, then a changed cart, then the same request arriving twice. The limit is also asked before the write, only so that a visitor over it queues no job: Mallok runs five plugin jobs a minute for the whole site. -- **An inquiry's emails are a job** (`lib/inquiry-jobs.ts`), queued with `ctx.enqueueStatement` in that batch and given an id and nothing else. It may run twice: each email is marked on the inquiry once it has been handed to Mallok (`notified_at`, `acknowledged_at`), and only what is not marked is sent. The seller's is in English and answered to the buyer; the buyer's, in their language, is sent only when `inquiry_acknowledge` is on — it is off by default because the form has no challenge in front of it. This is the one place the plugin uses Mallok's jobs; the order code still writes its own outbox, which nothing drains. +- **An inquiry's emails are a job** (`lib/inquiry-jobs.ts`), queued with `ctx.enqueueStatement` in that batch and given an id and nothing else. It may run twice: each email is marked on the inquiry once it has been handed to Mallok (`notified_at`, `acknowledged_at`), and only what is not marked is sent. The seller's is in English and answered to the buyer; the buyer's, in their language, is sent only when `inquiry_acknowledge` is on — it is off by default because the form has no challenge in front of it. Orders use Mallok's jobs too (`FOLLOW_UP_JOB`, below). - **Inquiries are read in the admin** in a `table` panel with their lines as a related table, and marked, exported and deleted by the actions in `lib/inquiry-admin.ts`. An amount is stored twice, as minor units and as the text the buyer saw, because a table panel lists a column as it is stored. `cart_id` and `ip_hash` are in the table and not in the panel. - **An inquiry is the first personal data the shop holds.** It goes in no log and no address, and the plugin's own job carries an id only. Every value goes through `escapeHtml` on its way into an email; a name, a company and a phone number are made one line each (white space collapses; it is not refused, because a refused form comes back empty); an address is held to an allow-list (`EMAIL_PATTERN_SOURCE`), because the admin makes a `mailto:` link of it; a cell of the export that a spreadsheet would run as a formula is made text, and so is every piece a semicolon would make a cell of (`inert`). **What the plugin cannot keep to itself is the email**: `ctx.sendEmail` stores the whole message in Mallok's `job` table, where deleting the inquiry does not reach it. `SECURITY.md` says so; do not claim otherwise. - **What the shop holds is in a site export** (`exportFiles`, `lib/export.ts`; design §19): variants with the slug of their product, prices, the stock ledger, orders and their lines, payment events, the outbox, inquiries and their lines — a JSON file each under `shop/`, a row an object, as stored, with a manifest and the shop's own settings, which Mallok's `site.json` does not carry. Tables are read with `*`, so a column a migration adds is exported without anyone remembering; `test/shop/export.test.ts` fails when a new `p_shop_` table is neither exported nor on its list of those left behind (carts, rates, the scheduler's state), and when an exported table has a column the test does not list — so that a new column is looked at before it is carried out of the shop. A column an export adds to a row has a name no table's column has (`variant_sku`, `product_slug`): of two columns of one name D1 keeps the last. An inquiry's `cart_id` and `ip_hash` stay behind. Nothing is rewritten for a spreadsheet: that is the admin's CSV, which is for reading; this is for carrying. A table over `EXPORT_ROW_LIMIT`, or files over `EXPORT_BYTE_LIMIT` together, fail the export rather than leave rows out, because Mallok then refuses to call it a backup — a file missing rows would pass for one. Both are guards against a Worker's memory and neither is a measurement. The reason is in the endpoint's answer and in the Worker's log (`shop_export_refused`); Mallok's command line and admin show only that the shop failed, and suggest switching the failing plugin off — which would give a backup with nothing of the shop's in it. -- **Orders and payment are built but not reachable** (design §14). `lib/orders.ts` places an order and confirms its payment, `lib/order-fulfilment.ts` ships, cancels and refunds, `lib/outbox.ts` records what each change still owes, `lib/stripe-webhook.ts` decides what a Stripe delivery means and which status to answer, `lib/stripe-signature.ts` and `lib/stripe-client.ts` talk to Stripe over `fetch`, `lib/order-email.ts` builds the buyer's emails. No route, page or admin screen calls them, and nothing drains the outbox: those wait for Mallok. Do not add a route that works around that. +- **Checkout is two routes** (`routes/checkout.ts`, `lib/checkout.ts`; design §20). `GET checkout` is the page: the cart as it will be ordered, a form sent by GET that chooses the country (`?country=DE`), and once one is chosen the shipping, the total and the order form, which carries that country hidden — the page has no script. `POST checkout/place` places the order and answers 303 to Stripe's page, or back to the checkout page with a kind (`?checkout=invalid&field=city`); like the cart's forms it never renders, and nothing typed travels in an address. **`readCheckout` is the one reading of a checkout** — `readCartFacts`, then where the cart can go and what that costs — and `quoteOf` the one sum; the page and the order both use them, and `pricedCartOf` turns that same reading into the order's lines. A country counts only when it is in a zone with a rate in the cart's currency. `lib/checkout-view.ts`'s header is the contract with the theme's `shop/checkout` layout. The shop takes payments only when both Stripe secrets are set (`stripeKeys`); until then the cart offers no checkout and the page says payment is unavailable. +- **The order is written before Stripe is asked for anything**, `pending`, with its cart, its company, its zone's name, its tax mode and the site's origin; then, in tax mode `stripe`, a Stripe customer holding the address it ships to; then the Checkout session, which lapses after `CHECKOUT_LIFETIME_MS`; then the session is recorded on the order. A Stripe failure closes the order (`cancelled`, reason `failed`) and sends the buyer back with `payments_unavailable`. **One cart has one payment open at a time**: placing an order first closes at Stripe the session of every order still waiting from the same cart, and cancels it (`replaced`); the order is written only if no other from the cart is waiting and the visitor has placed fewer than `MAX_CHECKOUTS_PER_HOUR` in the hour, both asked inside the write (`guard` of `createPendingOrder`, `OrderNotPlacedError`); and a placement whose order was closed by another while it opened its session closes that session again. **"Not open" is not "closed"**: a session Stripe will not expire may have just been paid, its word not here yet. `closeCheckoutSession` asks Stripe, and an order whose session is complete is never cancelled — by a new checkout (`paid_meanwhile`), the admin, or the cron. Links and Stripe's return use the site's own domain when it has one (`siteOriginOf`), not the request's host. +- **`lib/stripe-client.ts` is every call to Stripe**, over `fetch`, at `STRIPE_API_VERSION`, each with an idempotency key built from what it acts on. A session carries the order line by line at its snapshot prices and shipping as one fixed option named after the zone, with `adaptive_pricing` off and only `card` and `link` allowed. Its failures are described by Stripe's identifiers (`StripeRequestError`), never its free text. A refund and an expiry carry no idempotency key: Stripe keeps a key's first answer for a day, failures included, and Stripe's own state already stops a full refund being made twice. Check a parameter against Stripe's current API reference before adding one: names change between versions (design §20, finding 1). +- **An order's page** (`routes/order.ts`, `GET order/:orderNo?k=…`, sent with `Referrer-Policy: no-referrer`) opens only with the secret its link carries: an HMAC of the order's id (`lib/order-access.ts`) under a key the shop makes once and keeps in `p_shop_state`, which an export leaves behind. A wrong secret, none and an unknown order all answer the same 404. The page reads the key and never makes it: a GET writes nothing. Links are built by `orderLink` from the origin the order was placed on (`site_origin`), because the emails that carry them are written by a job, which has no request. +- **The webhook route** (`routes/stripe-webhook.ts`, `POST stripe/webhook`, `"body": "raw"`) answers 503 until the signing secret is set, so that Stripe delivers again; otherwise it hands the bytes to `handleStripeWebhook` and answers its status. `payment_intent.succeeded` pays an order, and the payment's `amount_received` and `currency` must fit it (`amountFits`: the total, or with Stripe Tax at least goods and shipping, the rest being the tax); `checkout.session.expired` cancels the order that session was for (`expireOrder`), unless it was paid or given another session meanwhile. +- **What each change owes is carried out by `lib/order-follow-up.ts`**: the buyer's email, the seller's, the purge of the order's products. A job (`FOLLOW_UP_JOB`, the order's id and nothing else) is queued by whatever made the change — the webhook route, an admin action — and the cron takes up rows older than five minutes that a job left behind. Each row is claimed (`claimed_at`) before it runs and marked handled after, so a job and the cron that meet over it send one email; a row that fails, or that another runner holds, holds its order's later rows back; and each email a row owes is marked on it as it is handed over (`progress`, through `once`), so a row run again sends only what it had not. What each topic owes is in that file's header; a cancellation is told to the buyer only when the seller made it. +- **Paying takes what was ordered out of the cart it came from**, in the payment's own batch, for a paid and an oversold order alike, and only the order's own variants. A refused payment leaves the cart. +- **The admin's order actions are `lib/order-admin.ts`**, run from the `orders` and `refused-payments` panels, which list read-only views (`p_shop_order_admin`, `p_shop_order_line_admin`, `p_shop_refused_payment` in `migrations/0004_checkout.sql`) because a table panel lists a column as it is stored. **Money moves at Stripe before the books move here**: a refund is made at Stripe and then recorded, and `charge_already_refunded` is taken as done; a Checkout session is expired at Stripe and then its order cancelled. A refusal answers 422 with a message the admin shows. +- **The cron also closes orders whose payment page lapsed** with no word from Stripe, an hour after it lapsed (or two hours after placing, when no session was recorded): `lib/scheduled.ts`. It asks Stripe first about one with a session, and leaves it when Stripe has it complete or cannot be asked. +- **Only a `pending` order takes a payment.** `oversold → paid` exists for restocking (`fulfilOversold`), not for another payment: a second payment for an oversold order is refused and owed back, as one for a paid order is. A refund is written only if the order is still in the status its stock was decided on (`expectedStatus`). - **A change to an order is conditional on the status it was read in** (`ORDER_STILL_IN_STATUS` in `lib/order-guard.ts`), and the statement that changes the status comes last in its batch. That is what makes a racing second call write nothing. +- **Customers and sales are read-only views listed by table panels** (`migrations/0005_storefront.sql`). A customer is an address — compared without regard to case — that placed an order or sent an inquiry: there are no accounts, and the view keeps nothing of its own. *Spent* counts orders paid, shipped or delivered; a customer's country is where their newest order ships to, and an inquiry's — where the request came from — only for an address that never ordered; *sales by month* reads the outbox, so a payment counts in the month it arrived — as `order.oversold` when the stock had gone, and not again as the `order.paid` a restock writes — and a refund in the month it was made; *sales by product* reads the lines of orders paid, shipped or delivered. Rows that can tie are ordered by a unique column last, or the admin's list changes order between two loads. +- **A buyer finds their orders again by email** (`routes/orders.ts`, `lib/order-lookup.ts`; design §21): `GET orders` asks for the address, `POST orders/link` records the request and emails a link good for `ORDER_LOOKUP_LIFETIME_MS`, which lists that address's orders — each by its own signed link. Only orders a payment was taken for count (`PAID_FOR_STATUSES` in `lib/order-state.ts`): a cancelled order was never paid, and its address is whatever was typed into checkout. The answer is `?sent=1` whether or not there were orders, and both limits — per visitor and per address an hour — are counted inside the write, whether or not there were orders, so neither says who has bought here. Only the link's digest is stored; the table is left out of the export and its expired rows are deleted by the cron's housekeeping, all of them each time. The email and the key that signs the orders' links are queued with `ctx.waitUntil`, after the answer, so that the answer takes the same time whether or not the address has bought — and the tests read Mallok's queue only once it has stopped growing (`settled`). An address is folded by SQLite's `lower()` on both sides, never by JavaScript's, which folds all of Unicode and turns U+212A into an ASCII k. A request reads its address's orders through `p_shop_order_email`, an index on `(lower(email), status)`, and a refused one reads none: `test/shop/order-lookup.test.ts` holds both by the `rows_read` D1 reports. - **A change to an order writes its outbox row in the same batch** (`orderChangedOutbox`). What follows the change — an email, a purge — is owed from that row. Never send from a function's return value: it is lost whenever the Worker stops after the batch. Rows are read back by `seq`, the order they were committed in, never by `created_at`, which is whatever time the caller passed. -- Pure logic (`money`, `pricing`, `ecb`, `order-state`, `currency`, `availability`, `storefront`, `reference`, `inquiry-email`, `stripe-signature`) takes no database; DB functions take a `D1Database` and, where time matters, a `now`. +- Pure logic (`money`, `pricing`, `ecb`, `order-state`, `currency`, `availability`, `storefront`, `reference`, `inquiry-email`, `order-email`, `checkout-view`, `stripe-signature`) takes no database; DB functions take a `D1Database` and, where time matters, a `now`. ### The theme and content - Templates are restricted Liquid. Output is escaped; only `content.html` and `page.head` are emitted verbatim. `page.head` carries hreflang and structured data from Mallok and must stay in `layouts/base.liquid`. - Interface strings are in `locales/*.json` (flat maps, the default locale is the fallback). Site-specific copy — the home page's headline and sections, the footer, the links behind the buttons — is a theme option, never a string in a template; per-language option values go under `themeOptions.$locales` in `site.json`, and `test/project.test.ts` fails when a language is left without one. The tagline is not an option: it is Mallok's own setting, a map of language to text in `site.json`. It follows the site's name in the home page's title, and describes that page unless the `home_description` option gives the language a fuller text. - **Kinds**: `product`, `collection`, `application` (the sample's industry pages, at `/industries`), `case`, `faq`, `tool`, `article`, `page`. Every kind with a `base` has a `listLayout` here, because each list is a page worth having; a kind without one has no list page — its base path answers 404 — and no entry in `site.kinds`. A template links to a kind's list only through `site.kinds.`, inside `{% if %}`: the breadcrumb (`partials/crumbs.liquid`) and the home page's link to the catalogue do, and `test/theme/unlisted.test.ts` holds both on a site that serves products without a list. -- **The cart page is the layout `layouts/shop-cart.liquid`**, declared under `pluginLayouts` in `theme.json` as `shop/cart`. It reads `plugin_page`, not `content`; `plugins` is empty on it. Every control is a plain form posting to `plugin_page.action`, a quantity field carries the minimum order in `min` and the most a line may hold in `max` (`plugin_page.max_quantity`; on a product page `plugins.shop.max_quantity`) and steps by one — the minimum is a floor, not a pack size, by the owner's decision — and the page has no script. The plugin has no words: a refusal or a line's problem arrives as a kind (`below_moq`, `insufficient_stock`, `unavailable`, `no_price`, `quantity_too_large`, `cart_full`), the pack has a `problem_` for each, and the number it is about is printed after the words. The layout titles itself through `{% block title %}` in `layouts/base.liquid`, since Mallok titles a plugin's page with the site's name. Below the cart it draws the form that sends it as a request for a quote, when `plugin_page.can_inquire` says the cart can go as it stands, and above it what became of one that was sent (`plugin_page.sent`, `plugin_page.inquiry_problem`). The form's words are the pack's `quote_*` keys — not `inquiry_*`, which are Mallok's inquiry form's and must stay out of the default pack. Each field carries the plugin's own rule as `required`, `maxlength` and `pattern` — the address's and the name's are the very strings the server compiles (`EMAIL_PATTERN_SOURCE`, `NAME_PATTERN_SOURCE`) — and `test/theme/cart.test.ts` holds those attributes to the constants in `lib/inquiries.ts`: a refused form comes back empty, so a browser has to refuse what the server would, and the server has to take what a browser lets through (a tab in a name, a line break counted once). The field named `website` is one no person may see or reach. +- **The cart page is the layout `layouts/shop-cart.liquid`**, declared under `pluginLayouts` in `theme.json` as `shop/cart`. It reads `plugin_page`, not `content`; `plugins` is empty on it. Every control is a plain form posting to `plugin_page.action`, a quantity field carries the minimum order in `min` and the most a line may hold in `max` (`plugin_page.max_quantity`; on a product page `plugins.shop.max_quantity`) and steps by one — the minimum is a floor, not a pack size, by the owner's decision — and the page has no script. The plugin has no words: a refusal or a line's problem arrives as a kind (`below_moq`, `insufficient_stock`, `unavailable`, `no_price`, `quantity_too_large`, `cart_full`), the pack has a `problem_` for each, and the number it is about is printed after the words. The layout titles itself through `{% block title %}` in `layouts/base.liquid`, since Mallok titles a plugin's page with the site's name. Below the cart it draws the form that sends it as a request for a quote, when `plugin_page.can_inquire` says the cart can go as it stands, and above it what became of one that was sent (`plugin_page.sent`, `plugin_page.inquiry_problem`). The form's words are the pack's `quote_*` keys — not `inquiry_*`, which are Mallok's inquiry form's and must stay out of the default pack. Each field carries the plugin's own rule as `required`, `maxlength` and `pattern` — the address's and the name's are the very strings the server compiles (`EMAIL_PATTERN_SOURCE`, `NAME_PATTERN_SOURCE`) — and `test/theme/cart.test.ts` holds those attributes to the constants in `lib/inquiries.ts`: a refused form comes back empty, so a browser has to refuse what the server would, and the server has to take what a browser lets through (a tab in a name, a line break counted once). The field named `website` is one no person may see or reach. When the shop takes payments and every line can be ordered (`plugin_page.can_check_out`), the cart offers a link to `plugin_page.checkout_path`. +- **The checkout page and an order's page are `layouts/shop-checkout.liquid` (`shop/checkout`) and `layouts/shop-order.liquid` (`shop/order`)**, built the same way: `plugin_page` only, plain forms, no script, every word in the pack — `checkout_*`, with `checkout_problem_` for each refusal and `checkout_` for each field, and `order_status_` for each status. The order form's attributes come from the view (`limits`, `email_pattern`, `name_pattern`), so they cannot drift from the server's; `test/theme/checkout.test.ts` holds them anyway, and holds both pages whole in every state they can be in. - **`plugins.shop` is optional everywhere.** It is absent when the plugin is off, when its read failed, in `mallok build` and in the admin's preview, and a product may have no variants. A template wraps what it prints from it in `{% if %}`, and the page is whole without it: the sizes with their SKUs, and no prices. A variant is found by walking `plugins.shop.variants`, never by `variants[sku]`: Liquid answers `size`, `first` and `last` on any collection itself. The words around a value — "Unit price", "In stock", "business days" — are the theme's, in its packs; `avail_` names the three states. - **A product is one page with its sizes on it**, not a page per size. `facets` are the attributes a buyer filters by; `sizes` maps each SKU to what distinguishes it; `specs` is the full table. `partials/spec-table.liquid` (the specification finder, the catalogue, a collection's products, a product's neighbours) takes its columns from the first product that has `facets` and fills every row by attribute name, so every product in a language must use the same names. Below 72rem the same table is laid out as cards, two to a row on a tablet: seven columns need about 1100px in German. - **References resolve by slug within the same language.** An `application` and a `case` name their `product`; the product page lists them through `content.backrefs.application` and `content.backrefs.case`. A `product` names its `collection`; the collection page lists `content.backrefs.product`. Mallok resolves `reference` only, not `reference[]`. @@ -87,13 +103,12 @@ Mallok decides the contracts on both sides. Its documentation is the reference: - Fonts are files in `assets/fonts/`, declared in `style.css` and preloaded in `layouts/base.liquid`; nothing is loaded from another host. Changing any asset means bumping `version` in `theme.json`: assets are served from a versioned path and cached for good. - Each language of a bundle is its own content item with its own `slug` (`index.md`, `index..md`); Mallok puts them in one `translation_group`. A bundle carries a `mallok.json` only when something outside the content must name it: each product's fixes the `translation_group` that `seed/shop-sample.sql` attaches its variants to. `test/content.test.ts` checks the reference rule, keeps every identity file in step with its bundle, and holds the seed's variants to the SKUs the product pages list. - The default language (English) is unprefixed; others are `//…`. English pages default to USD, the rest to EUR (`lib/currency.ts`), never by IP. +- **The editorial theme follows the commerce theme's contract, not its markup.** Its `theme.json` has the same `kinds`, `options`, `pluginLayouts` and `locales` — `test/theme-editorial/pages.test.ts` fails when they differ, so a change to one is made to both — and it reads `src/theme/locales/*.json`, so a new interface word goes in those packs once. It declares no assets: `mallok prepare` stages the files of the theme at `src/theme` only (M46), so its stylesheet is `partials/style.liquid`, rendered in ``, with the faces systems have: DIN Condensed and DIN Alternate on Apple's, Bahnschrift on Windows, Charter for text. Its one repeated device is `partials/titleblock.liquid`, a drawing's title block, used only for data (a product's facets, a case's results, an industry's highlights). What the commerce theme adds with a script it leaves out, and every page is whole without it. Below 40rem a table of several columns (`class="ledger stack"`) is drawn a row at a time, each value under its column's name from `data-label`, with table roles in the markup because changing a table's display takes its semantics away in some browsers; a new value cell of such a table needs its `data-label`. ### What is not built on plugin API 2 yet `mallok@0.1.0-rc.11` allows each of these; the code here does not use it yet. -- There is no checkout: a cart can be sent as an inquiry and cannot be paid for. -- No raw-body route, so no Stripe webhook, and so no checkout. - The sample's products name one collection each, though `reference[]` is resolved now. When one is built, take it off this list and prove the behaviour with a test or the smoke run. @@ -107,12 +122,16 @@ When one is built, take it off this list and prove the behaviour with a test or - `ctx.enqueueStatement` takes no condition, so a job is queued beside a conditional write even when the write stored nothing. A job has to find nothing to do in that case. - A page cannot be rendered from a `POST` without being listed under the `POST`'s address, so a form the server refuses comes back with its fields empty. - A plugin's export is built whole, in memory, in the one request that exports the site: there is no way to hand Mallok a table a page at a time. So the shop's export has a ceiling of rows a table, and a shop past it cannot be exported at all until Mallok offers one. +- A job has no request and `ctx.site.domain` is null on a `workers.dev` address, so a job cannot know the site's own address: an order records the origin it was placed on, and its links are built from that (M44). +- A related table is ordered by `rowid` unless the panel names an order, and a view has none: every related table here names its `orderBy` (M41). +- An action can answer only success or a refusal, so one that acted on some of the rows ticked and not others answers 422 with what it changed and what it did not (M43). +- `mallok prepare` stages the files of the theme at `src/theme` and no other, so a second theme can have no assets (M46): the editorial theme's stylesheet is in the page. - Nothing tells a plugin of a deletion it missed, and nothing here sweeps up afterwards: a variant with no product may as well be one that was loaded before its product was published, and a sweep cannot tell the two apart. - Switching a plugin on or off, or changing a setting, can leave cached pages as they were — and the admin's "Clear cached pages" can report success without clearing anything. So the plugins are switched on before the first publish (`scripts/lib/local-shop.mjs`, the README), and `test/shop/helpers.ts` deletes the cached home page by hand after changing settings. Keep both until a Mallok release says the purge can be trusted. ## Testing -- Tests in `test/shop` and `test/theme` run inside workerd against the site's own Worker. `test/shop/helpers.ts` brings a site up through Mallok's HTTP API (first request → admin → token → settings → plugin enabled); tables are created by Mallok's migrator, never by hand. Create content with `createContent`, not by inserting rows. +- Tests in `test/shop` and `test/theme` run inside workerd against the site's own Worker (vitest project `site`); `test/theme-editorial` runs against `src/worker/editorial.ts` (project `editorial`), imports the real sample through its starter, and draws every page of it and every shop page — a page added to the sample is checked there without anyone listing it — with its `bare.test.ts` and `unlisted.test.ts` doing for it what the commerce theme's do. `npx vitest run --project editorial` runs that one. `test/shop/helpers.ts` brings a site up through Mallok's HTTP API (first request → admin → token → settings → plugin enabled); tables are created by Mallok's migrator, never by hand. Create content with `createContent`, not by inserting rows. - Mallok caches pages in `caches.default`. In a test, create all content before requesting any page. - A test for a fix must be seen failing without the fix. For new guards, break the guard and confirm the test goes red. - A race is tested by running the calls with `Promise.all`, and such a test only counts once breaking the guard turns it red **every time**: that is the proof the two calls really interleave. Through `SELF.fetch` they do so about half the time, and where a request reads before it writes, the other half never reaches the guard. `holdWrites` in `test/shop/helpers.ts` holds each request at its write until the test has seen them all arrive; the inquiry's races use it. It waits by polling a flag: a promise settled by one request for another stops the Worker. Functions called side by side in one test are the other case: each runs as far as its reading before the next begins, every time. `atTheSameMoment` runs them and fails unless every call had made its reading before any made its write, so that this is seen on every run and not assumed; the payment and fulfilment races use it. What it watches is the order of each call's trips to the database it was handed: tell it how many readings a function makes when that is not one, and have the function use that database and no other. A payment's write is stopped by several keys at once — the status it was read in, the event's keys, the ledger row's id, the outbox row's id — so taking the shared status condition away turns no race between two payments red; the races between two different changes of an order, which have no key in common, do go red. @@ -133,10 +152,13 @@ When one is built, take it off this list and prove the behaviour with a test or - A refused change writes nothing and creates no cart; a sum is stated only for a cart every line of which can be ordered as it stands. - A redirect is judged by the path the browser will read, not the text that was sent: `/.//host` is one slash as typed and another site once resolved. - `stock` carries `CHECK (stock >= 0)`. `test/shop/schema.test.ts` proves a failing decrement rolls back its whole D1 batch, and that `WHERE stock >= qty` does not — the payment write relies on the constraint. -- Stock comes off when a payment is confirmed, never when an order is placed, and only for stock-tracked variants. `markOrderPaid` is one batch — event, stock, ledger, outbox, status — and must stay one: splitting it brings back the state where stock is taken for an unpaid order, or an order is paid and its email never owed. +- Stock comes off when a payment is confirmed, never when an order is placed, and only for stock-tracked variants. `markOrderPaid` is one batch — event, stock, ledger, outbox, the ordered lines out of the cart, status — and must stay one: splitting it brings back the state where stock is taken for an unpaid order, or an order is paid and its email never owed. - One payment takes stock once, however it is reported: the same event again, a different event for the same payment intent, or two deliveries at the same moment. The parallel tests in `test/shop/orders.test.ts` hold this; do not weaken them into sequential ones. - What to do with a payment is read from the data — is it on record, what status is the order in, is the stock there — and read again after a write that failed. Never from the text of an error. -- A payment the order cannot take (cancelled, or settled by another payment) is recorded as `refused` with an outbox row naming the payment to refund. The order and the stock are not touched, and the money is never left without a trace. +- A payment the order cannot take (cancelled, settled by another payment, or not coming to its currency and total — `amountFits`) is recorded as `refused` with an outbox row naming the payment to refund. The order and the stock are not touched, and the money is never left without a trace. +- An oversold order is refunded, or restocked and fulfilled (`fulfilOversold`, which takes the stock then and makes it `paid`). It is never just cancelled: that leaves a payment taken and nobody owing it back. +- Money moves at Stripe before the books move here: a refund is made at Stripe before the order reads `refunded`, and a Checkout session is expired at Stripe before its order reads `cancelled`. A cart has one open payment at a time. +- A refund puts back what the payment took, as the seller chooses: back to stock unless the order has shipped, by default. Refunds are of the whole order. - A webhook body is trusted only after `verifyStripeSignature` has passed on the bytes as received. Answer 5xx only for what delivering again could change — a database failure; Stripe redelivers anything that is not a 2xx for three days. - Money columns check `typeof(x) = 'integer'`: SQLite stores 99.5 in an `INTEGER` column rather than refuse it. - A Stripe failure is described by Stripe's identifiers and the status, never its free-text message: nothing rules out that text repeating a buyer's email address. diff --git a/README.md b/README.md index 0168580..6addb3a 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![CI](https://github.com/fobstack/Nundar/actions/workflows/ci.yml/badge.svg)](https://github.com/fobstack/Nundar/actions/workflows/ci.yml) [![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue)](LICENSE) -> **Status: in development.** Nundar is being rebuilt on Mallok. The catalogue side works today. Prices and a cart are on the pages, and a cart can be sent as a request for a quote; checkout is not there yet — see [What works today](#what-works-today). It is not ready to run a real shop. +> **Status: in development.** Nundar is being rebuilt on Mallok. The catalogue, the cart, requests for a quote, checkout with Stripe, the seller's orders, customers and sales, and a second theme work locally; a purchase at Stripe has not been run end to end yet, and nothing has been deployed — see [What works today](#what-works-today). It is not ready to run a real shop. --- @@ -38,13 +38,15 @@ Each links to the product it discusses, the product lists the pages written abou ## How it is built -Nundar is not a second application beside Mallok. A shop is a Mallok site with two things added: +Nundar is not a second application beside Mallok. A shop is a Mallok site with a plugin and a theme added; the rest is a sample to start from: | Part | Where | What it owns | |---|---|---| -| **Shop plugin** | `src/plugins/shop/` | Variants, prices per currency, stock, minimum order quantities, the cart, the cart sent as an inquiry, exchange-rate repricing | -| **Commerce theme** | `src/theme/` | How the home page, the specification finder and the product, application, collection, case study, question and reference pages look, in four languages | +| **Shop plugin** | `src/plugins/shop/` | Variants, prices per currency, stock, minimum order quantities, the cart, the cart sent as an inquiry, exchange-rate repricing, shipping zones, checkout with Stripe, orders and their emails | +| **Commerce theme** | `src/theme/` | How the home page, the specification finder and the product, application, collection, case study, question, reference, cart, checkout and order pages look, in four languages | +| **Editorial theme** | `src/theme-editorial/` | The same pages drawn the opposite way — see [Themes](#themes) | | **Sample content** | `content/`, `seed/`, `site.json` | A titanium fastener catalogue in four languages: six products in five collections, five industry pages, four case studies, questions and answers, reference pages, and the site's own copy | +| **Starter** | `src/starter/` | The same sample, offered by Mallok's first-run wizard to a newly deployed site | Mallok provides everything else: content and its editor, languages and `hreflang`, the sitemap, the admin and sign-in, media, the edge cache, email. That boundary is deliberate — commerce logic lives only in the plugin, and nothing about pages is reimplemented here. @@ -59,10 +61,15 @@ Nundar builds on `mallok@0.1.0-rc.11`, the first release with the plugin API the | **Pages** | A home page with a specification finder; product pages with their sizes and SKUs, and for each size its price, minimum order, availability and lead time, read from the shop while the page is rendered and cached with it; the same offers in the page's `Product` structured data; a starting price under each product in the finder and the catalogue; collection, industry, case study, question, engineering reference and contact pages — all in English, German, French and Spanish, with `hreflang`, canonicals, sitemap and FAQ structured data; self-hosted fonts; prices in US dollars on English pages and in euros on the others, with a switch to any currency the shop prices in; no client JavaScript except three small scripts, each added to a page that is complete without it: filters for the finder, the currency switch, and calculators on the engineering reference page | Prices beside the products a collection page lists (Mallok does not yet tell a plugin which products a content page shows) | | **Catalogue data** | Variants, prices as integer minor units, stock, MOQ, lead time, a made-to-order policy — edited in the admin, in a form under each product's editor; every change of stock goes into a ledger; a deleted product takes its variants with it | | | **Pricing** | USD base price; EUR and GBP derived from ECB rates with a buffer, rounding to a price point and a drift threshold; manual prices never overwritten; the pages of a product are purged from the cache when one of its prices moves | | -| **Cart** | A form beside each size on a product page, and a cart page in the site's own design and language: set a quantity, remove a line, choose a currency. No script anywhere in it. MOQ, stock and the most a line may hold (500) are enforced by the server, which says what it refused on the cart page | Checkout | +| **Cart** | A form beside each size on a product page, and a cart page in the site's own design and language: set a quantity, remove a line, choose a currency. No script anywhere in it. MOQ, stock and the most a line may hold (500) are enforced by the server, which says what it refused on the cart page | | | **Inquiries** | The cart sent as one request for a quote, from a form on the cart page: who to answer, and a message. A size with no price can go in the cart to be asked about. The buyer lands on the inquiry's number; the seller is told by email, answerable straight to the buyer, and finds every inquiry in the admin with its lines — to mark, export as CSV, or delete | A challenge in front of the form (it waits for Mallok), which is why the email confirming to the buyer is off unless switched on | | **Taking your data with you** | What the shop holds is in the site's export (`mallok export`), beside the content: variants, prices, the stock ledger, orders, payment events, inquiries and the shop's settings, a JSON file each under `shop/`, as stored | An import of those files; an export of a table too large for one request (both wait for Mallok) | -| **Orders and payment** | The logic, tested and not yet reachable: orders with line snapshots, a payment that takes stock exactly once however often Stripe reports it, oversold orders, refunds that return stock, Stripe signature checks, order emails in four languages | The checkout and order pages, the webhook route, and order handling in the admin | +| **Shipping** | Zones set in the admin: the countries each covers, a fixed rate in each currency, and an amount from which it ships free. A country in no zone is not offered at checkout | Rates by weight | +| **Checkout and payment** | A checkout page in the site's own design and language, with no script: the country the order goes to, shipping and the total for it, the buyer's company and address, then Stripe's hosted page to pay — by card, or Link, at the shop's own prices with Stripe's currency conversion off. Tax is not charged unless the shop switches Stripe Tax on. An order's own page, opened by the signed link Stripe returns the buyer to and every email carries. A payment takes stock exactly once however often Stripe reports it, is held to the order's total, and empties what was ordered from the cart; an unpaid order is cancelled an hour after its payment page lapses | A purchase made at Stripe in test mode has not been run yet (it needs a shop's own test keys); buyer accounts; invoices of the shop's own; partial refunds | +| **Orders in the admin** | Every order with its lines, its address and its amounts: mark shipped (tracking number and carrier), delivered, cancel one that was not paid, refund in full — at Stripe first, then the books, with the stock back unless the goods have shipped — or fulfil one that was paid for after its stock had gone, once restocked. Payments the shop could not keep are listed to refund. The buyer is written to in their language when an order is confirmed, shipped, refunded or cancelled; the seller is told of every new order and every refund owed | | +| **Customers and sales** | Every address that ordered or asked for a quote, with its orders and inquiries beneath it and what it has spent in each currency; sales by month — paid, refunded, net and the average order — and by product, per currency | | +| **Finding an order again** | No account to make: a buyer types the address they ordered with and is emailed a link, good for a day, to every order they paid for. The page says the same whether or not there were any, and asking is limited per visitor and per address | | +| **Starting a site** | A site deployed from this repository is offered the sample in Mallok's first-run wizard: the catalogue in four languages, its variants and prices, the shipping zones and the settings, with no command to run | The sample's pictures (a starter carries no files; `npm run preview` publishes them) | The reasoning and the plan are in [`docs/superpowers/specs/2026-09-30-nundar-on-mallok-design.md`](docs/superpowers/specs/2026-09-30-nundar-on-mallok-design.md). @@ -78,6 +85,10 @@ The reasoning and the plan are in [`docs/superpowers/specs/2026-09-30-nundar-on- - A public page is the same for every visitor and stays in the cache: nothing about a cart is in it, and the cart's cookie is sent only to the shop's own routes. - Stock carries a database constraint, so a payment's decrement cannot go negative: a test proves the whole D1 batch rolls back. - Stock comes off when a payment is confirmed, never before, and once: tests deliver the same payment twice at the same moment. +- A payment is checked against its order's currency and total; one that does not fit is kept for a refund, not taken for the order. +- Money moves at Stripe before the shop's books do: a refund is made at Stripe before the order says refunded, and a payment page is closed at Stripe before its order is cancelled. A cart has one payment page open at a time. +- An order's page opens only with the secret its link carries, never with its number alone. +- The form that emails a buyer their orders says the same whether or not there were any, in the same time, and writes only to an address a payment was made from. - A payment is believed only with Stripe's signature on the exact bytes received, and only for five minutes. - A manually set price is never overwritten by an exchange-rate refresh. - Language is decided by the URL alone, never by the visitor's IP. @@ -95,9 +106,11 @@ npm run preview In about a minute `preview` prints the address of a local shop with the sample catalogue in four languages, the address of its admin, and a login for it. Everything is set up for you: an administrator, the two plugins, the settings, the content with its images, the variants. -It is a throwaway. The database lives in a temporary directory and goes when you stop the command with Ctrl+C; the next run starts clean, with a new login. Use `npm run preview -- --port 8800` if port 8799 is taken. +It is a throwaway. The database lives in a temporary directory and goes when you stop the command with Ctrl+C; the next run starts clean, with a new login. Use `npm run preview -- --port 8800` if port 8799 is taken, and `npm run preview -- --theme editorial` to see the same shop in the [other theme](#themes). -To see the same shop checked rather than shown — every kind of page, every navigation link in every language, the cart — run `npm run smoke:shop`. +To see the same shop checked rather than shown — every kind of page, every navigation link in every language, the cart, the checkout page — run `npm run smoke:shop`. + +The preview takes no payments: it has no Stripe keys, so its cart offers no checkout and its checkout page says payment is not available. [Taking payments](#taking-payments) says how to give it some. ### A local site that keeps its data @@ -133,12 +146,41 @@ The sample is a supplier of titanium fasteners that does not exist. Its products - **The site's own copy** — the name, the navigation, the home page's headline and sections, the footer — is in `site.json`. Each language has its own values there; none of it is fixed in the theme. - **Variants and prices** are in `seed/shop-sample.sql`, one variant for each SKU a product page lists, each with a US dollar base price and a euro and a sterling price entered by hand. Leave a currency out and the shop derives its price from the base price and the day's exchange rate. - **Fonts** are served from the site itself (`src/theme/assets/fonts/`), under the SIL Open Font License; the licence texts and the source of each file are beside them. The theme loads nothing from a third party. +- **The starter** (`src/starter/`) is the same sample for Mallok's first-run wizard. Its list of documents is generated: after changing `content/`, run `npm run starter:documents`, or the tests fail. + +## Themes + +Two themes ship, and they are deliberately opposites. A theme is how a page looks and nothing else: what a page says, its `hreflang` and structured data, and every interface word are the same in both, so a theme can make a site look different but cannot change what a search engine reads or what a buyer is told. + +| | Commerce (`src/theme/`, the default) | Editorial (`src/theme-editorial/`) | +|---|---|---| +| Type | Space Grotesk and Inter, served by the site itself | DIN for headings and figures, Charter for text — from the visitor's own system (DIN Condensed and DIN Alternate on Apple's, Bahnschrift on Windows), with fallbacks | +| Look | Light and open, amber on white | An engineering bulletin: titanium grey, graphite and the site's accent, with attributes and results in a drawing's title block | +| Home page | A headline that points at the specification finder, then the collections and the finder | A headline beside a picture of a part, then the industries, the case studies with their results, a catalogue with pictures, and the product types | +| Scripts | Three small ones, each adding to a page that works without it | None | +| Files of its own | A stylesheet, fonts and images | None: its styles are in the page | + +The second exists to keep the contract honest: a contract with one implementation is only a guess. Its tests hold its manifest to the commerce theme's and draw every page of the sample in it. + +To deploy the editorial theme instead, set `main` in `wrangler.jsonc` to `src/worker/editorial.ts`. To build your own, copy `src/theme-editorial/`, give `theme.json` a new `id`, and add a Worker entry like `src/worker/editorial.ts` that names it. A theme with files of its own (fonts, pictures, a script) has to be the one at `src/theme/`: Mallok stages the files of that directory only. + +## Taking payments + +The shop takes payments through Stripe's hosted checkout, on your own Stripe account. Until both of its Stripe secrets are set, it takes none, and says so. + +1. **Shipping zones.** In the admin, under the shop's **Shipping zones**, add a zone for each group of countries you ship to, with its rate in each currency you sell in. A country in no zone cannot be checked out to. The sample has four (`seed/shop-sample.sql`). +2. **The secret key.** In Stripe's dashboard, under Developers → API keys, copy the secret key — `sk_test_…` while you try it out — and enter it in the admin as the shop's **Stripe secret key**. The **Test** button beside it asks Stripe whether it accepts the key. +3. **The webhook endpoint.** In Stripe, add an endpoint at `https:///_mallok/p/shop/stripe/webhook` for the events `payment_intent.succeeded` and `checkout.session.expired`, on API version `2026-10-28.endive` — the version this code was written against. Stripe's dashboard creates an endpoint on the latest version; for another, create it through Stripe's API with `api_version`. Enter the endpoint's signing secret (`whsec_…`) as the shop's **Stripe webhook signing secret**. Until it is set, the shop answers Stripe's deliveries with 503, and Stripe keeps them and delivers them again for up to three days. +4. **The notification address.** The shop's **Notification email** setting is where new orders, refunds owed and inquiries are announced. Email goes through the site's own email settings (Settings → Email). +5. **Optional.** **Tax** set to `stripe` has Stripe Tax add tax at payment, wherever your Stripe account is registered to collect it, for Stripe's fee; it is `none` by default, and prices are without tax. **Terms page** names a page a buyer ticks that they accept. **Order number prefix** is `ND` unless you set another. + +To try it on a local site (`npm run dev`), Stripe's command-line tool can forward test events to it — `stripe listen --forward-to http://localhost:8787/_mallok/p/shop/stripe/webhook --events payment_intent.succeeded,checkout.session.expired --latest` — and prints the signing secret to enter. Without `--latest`, it sends events at your account's default API version. Pay on Stripe's page with one of Stripe's test cards. ## Commands | Command | What it does | |---|---| -| `npm run preview` | A local shop with the sample catalogue and an admin login, on a throwaway database | +| `npm run preview` | A local shop with the sample catalogue and an admin login, on a throwaway database (`-- --theme editorial` for the other theme) | | `npm run dev` | Local development server, with local D1 and R2 that keep their data; starts empty | | `npm run build` | Stage assets, then a production build (a deploy dry run) | | `npm test` | Project checks, then the plugin and theme tests inside the real Workers runtime | @@ -146,10 +188,11 @@ The sample is a supplier of titanium fasteners that does not exist. Its products | `npm run smoke` | A real request to a real local Worker | | `npm run smoke:shop` | The whole shop on a real local Worker | | `npm run seed:local` | Load the sample variants into the local database | +| `npm run starter:documents` | Regenerate the starter's list of documents after changing `content/` | ## Deploying -Not yet. A deployed shop today would show a catalogue with prices and a cart that can be sent as a request for a quote and cannot be paid for: there is no checkout. Nothing here has been measured on a real Cloudflare account either. When Nundar is ready, deployment is Mallok's own: `npx mallok create . --slug `, which creates the Worker, the D1 database and the R2 bucket on your own Cloudflare account. That path has not been run for this repository. +Not yet. The shop can take payments now, and a purchase in Stripe's test mode has still to be run end to end on a real Stripe account before anyone relies on it. Nothing here has been measured on a real Cloudflare account either. When Nundar is ready, deployment is Mallok's own: `npx mallok create . --slug `, which creates the Worker, the D1 database and the R2 bucket on your own Cloudflare account, after which Mallok's first-run wizard offers the sample shop to start from. That path has not been run for this repository. ## Languages and currencies diff --git a/README.zh-CN.md b/README.zh-CN.md index b6096aa..e5421e7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@ **[Mallok](https://github.com/fobstack/mallok) 的商城插件和商城主题。** 为想靠买家真实搜索词获得流量的跨境卖家而做,不去和所有人争抢同一个大词。 -> **状态:开发中。** Nundar 正在 Mallok 上重建。页面上已有价格和购物车,购物车可以作为询价单发出;结账还没有,见[现在能用什么](#现在能用什么)。目前还不能用来经营真实店铺。 +> **状态:开发中。** Nundar 正在 Mallok 上重建。目录、购物车、询价、通过 Stripe 结账、卖家的订单/客户/销售视图,以及第二套主题,在本地都能用;还没有在 Stripe 上完整跑通过一笔购买,也还没有部署过,见[现在能用什么](#现在能用什么)。目前还不能用来经营真实店铺。 --- @@ -37,13 +37,15 @@ ## 它是怎么构成的 -Nundar 不是 Mallok 旁边的第二个应用。一个商城就是一个加了两样东西的 Mallok 站点: +Nundar 不是 Mallok 旁边的第二个应用。一个商城就是加了一个插件和一套主题的 Mallok 站点;其余的是可以拿来起步的示例: | 部分 | 位置 | 负责什么 | |---|---|---| -| **商城插件** | `src/plugins/shop/` | 规格、各币种价格、库存、起订量、购物车、把购物车作为询盘发出、按汇率重新定价 | -| **商城主题** | `src/theme/` | 首页、规格查找表,以及商品页、应用场景页、聚合页、案例页、问答页和资料页的外观,四种语言 | +| **商城插件** | `src/plugins/shop/` | 规格、各币种价格、库存、起订量、购物车、把购物车作为询盘发出、按汇率重新定价、运费区域、通过 Stripe 结账、订单及其邮件 | +| **商城主题** | `src/theme/` | 首页、规格查找表,以及商品页、应用场景页、聚合页、案例页、问答页、资料页、购物车页、结账页和订单页的外观,四种语言 | +| **编辑风主题** | `src/theme-editorial/` | 同样的页面,用相反的方式呈现——见[主题](#主题) | | **示例内容** | `content/`、`seed/`、`site.json` | 一套四种语言的钛紧固件目录:五个聚合页下的六个商品、五个行业页、四个案例、问答、资料页,以及站点自己的文案 | +| **Starter** | `src/starter/` | 同一套示例,由 Mallok 的首次运行向导提供给新部署的站点 | 其余的都由 Mallok 提供:内容和编辑器、多语言和 `hreflang`、sitemap、后台和登录、媒体、边缘缓存、邮件。这条边界是有意划的:交易逻辑只在插件里,页面相关的东西不在这里重做。 @@ -58,10 +60,15 @@ Nundar 基于 `mallok@0.1.0-rc.11`,这是第一个带有商城其余部分所 | **页面** | 带规格查找表的首页;列出尺寸和 SKU 的商品页,每个尺寸带价格、起订量、库存状态和交期(渲染页面时从商城读出,随页面一起缓存);同样的报价写进页面的 `Product` 结构化数据;规格查找表和目录里每个商品名下显示起价;聚合页、行业页、案例页、问答页、工程资料页和联系页——全部有英、德、法、西四种语言,带 `hreflang`、canonical、sitemap 和 FAQ 结构化数据;字体由站点自己提供;英文页面以美元标价,其余语言以欧元标价,并可切换到商城支持的任一币种;除了三个小脚本之外没有客户端 JavaScript,而且页面没有它们也是完整的:给规格查找表加筛选、币种切换、工程资料页上的计算器 | 聚合页所列商品旁的价格(Mallok 目前不会告诉插件一个内容页列出了哪些商品) | | **目录数据** | 规格、以整数最小单位存储的价格、库存、起订量、交期、按单生产策略——在后台每个商品编辑器下方的表单里编辑;库存的每次变动都记入流水;删除商品时一并清理它的规格 | | | **定价** | 美元基准价;欧元和英镑按 ECB 汇率换算,带缓冲、价位取整和漂移阈值;手动价格永不被覆盖;某个商品的价格变动时,清除该商品页面的缓存 | | -| **购物车** | 商品页每个尺寸旁有一个表单;购物车页沿用站点自己的设计和语言,可改数量、移除、选币种,全程不需要脚本。起订量、库存和单行数量上限(500)由服务端校验,被拒绝的原因直接显示在购物车页上 | 结账 | +| **购物车** | 商品页每个尺寸旁有一个表单;购物车页沿用站点自己的设计和语言,可改数量、移除、选币种,全程不需要脚本。起订量、库存和单行数量上限(500)由服务端校验,被拒绝的原因直接显示在购物车页上 | | | **询盘** | 在购物车页填一张表单(回复给谁、留言),把整个购物车作为一张询价单发出。没有价格的尺寸也可以加入购物车来询价。买家提交后看到询盘编号;卖家收到一封邮件,直接回复即可回到买家,并在后台看到每张询盘及其明细,可以标记、导出 CSV 或删除 | 表单前面的人机验证(等 Mallok 提供),因此给买家的确认邮件默认关闭,需要手动开启 | | **带走你的数据** | 商城持有的数据都在站点导出(`mallok export`)里,和内容放在一起:规格、价格、库存台账、订单、付款事件、询盘和商城自己的设置,各为 `shop/` 下的一个 JSON 文件,按存储原样导出 | 把这些文件再导入;单次请求装不下的大表的导出(两者都要等 Mallok) | -| **订单与付款** | 逻辑已写好并有测试,但还没有入口可以用到:带行快照的订单、无论 Stripe 通知多少次都只扣一次库存的付款、超卖订单、退还库存的退款、Stripe 签名校验、四种语言的订单邮件 | 结账页和订单页、webhook 路由、后台的订单处理 | +| **运费** | 在后台设置区域:每个区域包含哪些国家、每种币种的固定运费,以及货款达到多少免运费。不在任何区域里的国家,结账时不会出现 | 按重量计费 | +| **结账与付款** | 结账页沿用站点自己的设计和语言,不需要脚本:选择订单寄往的国家,看到该国的运费和总价,填写买家的公司和地址,然后到 Stripe 托管的页面付款——银行卡或 Link,按商城自己的标价,关闭 Stripe 的货币换算。默认不收税,商城可开启 Stripe Tax。订单有自己的页面,通过签名链接打开;Stripe 付款后带买家回到这个链接,每封邮件也都附带它。无论 Stripe 通知多少次,一笔付款只扣一次库存;付款金额要和订单总额对得上;付款后从购物车里移除已下单的商品;未付款的订单在付款页失效一小时后取消 | 还没有在 Stripe 测试模式下实际跑通一笔购买(需要商城自己的测试密钥);买家账户;商城自己的发票;部分退款 | +| **后台订单处理** | 每张订单连同明细、地址和金额:标记已发货(运单号和承运商)、已送达,取消未付款的订单,全额退款——先在 Stripe 退款再记账,货未发出时默认退回库存;对付款时库存已售完的订单,补货后照常履约。商城无法收下的付款单独列出,供退款。订单确认、发货、退款或被卖家取消时,用买家的语言写信通知;每张新订单和每笔待退款都通知卖家 | | +| **客户与销售** | 每个下过单或发过询价的邮箱地址,下面列出它的订单和询盘,以及在各币种下的消费额;按月统计的销售——已收款、已退款、净额和平均订单额——以及按商品统计,均分币种 | | +| **找回订单** | 不用注册账户:买家输入下单用的邮箱,会收到一封邮件,里面的链接在一天内可以查看用这个邮箱付过款的全部订单。无论有没有订单,页面上的回答都一样;每个访客、每个邮箱的请求次数都有限制 | | +| **开站** | 从本仓库部署的站点,会在 Mallok 的首次运行向导里看到这套示例:四种语言的目录、规格和价格、运费区域和站点设置,不用敲任何命令 | 示例的图片(starter 不能携带文件;`npm run preview` 会连图片一起发布) | 原因和计划见 [`docs/superpowers/specs/2026-09-30-nundar-on-mallok-design.md`](docs/superpowers/specs/2026-09-30-nundar-on-mallok-design.md)。 @@ -77,6 +84,10 @@ Nundar 基于 `mallok@0.1.0-rc.11`,这是第一个带有商城其余部分所 - 公开页面对每个访客都一样,可以一直留在缓存里:页面上没有任何与购物车有关的内容,购物车的 cookie 只发给商城自己的路由。 - 库存带数据库约束,付款时的扣减不可能变成负数:有测试证明整个 D1 batch 会回滚。 - 库存只在付款确认后扣减,绝不提前,而且只扣一次:有测试让同一笔付款在同一时刻到达两次。 +- 每笔付款都要和订单的币种与总额核对;对不上的付款留待退款,不算作这张订单的付款。 +- 钱先在 Stripe 动,账再在商城这边动:先在 Stripe 退款,订单才标记为已退款;先在 Stripe 关闭付款页,订单才取消。一个购物车同一时间只开一个付款页。 +- 订单页只凭链接里的密钥打开,单有订单号打不开。 +- 给买家发送订单链接的表单,无论有没有订单,回答的内容和所用的时间都一样,并且只会写信给付过款的邮箱。 - 一笔付款只有带着 Stripe 对原始字节的签名才会被采信,而且只在五分钟内有效。 - 手动设置的价格永远不会被汇率刷新覆盖。 - 语言只由网址决定,绝不按访客 IP 判断。 @@ -94,9 +105,11 @@ npm run preview 大约一分钟后,`preview` 会打印出一个本地商城的地址(带四种语言的示例目录)、后台地址,以及后台的登录账号。所有准备工作都替你做好了:管理员、两个插件、站点设置、内容和图片、规格数据。 -它是一次性的。数据库放在临时目录里,按 Ctrl+C 停掉命令就一起删除;下次运行从头开始,登录账号也会换。8799 端口被占用时用 `npm run preview -- --port 8800`。 +它是一次性的。数据库放在临时目录里,按 Ctrl+C 停掉命令就一起删除;下次运行从头开始,登录账号也会换。8799 端口被占用时用 `npm run preview -- --port 8800`;想看同一个商城的[另一套主题](#主题),用 `npm run preview -- --theme editorial`。 -如果想看的是"检查"而不是"展示"——每一类页面、每种语言的每个导航链接、购物车——运行 `npm run smoke:shop`。 +如果想看的是"检查"而不是"展示"——每一类页面、每种语言的每个导航链接、购物车、结账页——运行 `npm run smoke:shop`。 + +预览环境不收款:它没有 Stripe 密钥,所以购物车里没有结账按钮,结账页会说明暂时不能付款。怎样让它收款,见[收款](#收款)。 ### 保留数据的本地站点 @@ -132,12 +145,41 @@ npm run seed:local - **站点自己的文案**——名称、导航、首页的标题和各个区块、页脚——在 `site.json` 里。每种语言在那里有各自的值;这些文案没有一句写死在主题里。 - **规格和价格**在 `seed/shop-sample.sql` 里,商品页上列出的每个 SKU 对应一个规格,各有一个美元基准价和手工录入的欧元、英镑价格。某个币种不填,商城就按基准价和当天汇率换算。 - **字体**由站点自己提供(`src/theme/assets/fonts/`),采用 SIL Open Font License;许可文本和每个文件的来源放在同一目录。主题不从任何第三方加载资源。 +- **Starter**(`src/starter/`)是给 Mallok 首次运行向导用的同一套示例。它的文档清单是生成的:改了 `content/` 之后运行 `npm run starter:documents`,否则测试会失败。 + +## 主题 + +内置两套主题,而且是有意做成相反的。主题只决定页面长什么样:页面的内容、`hreflang` 和结构化数据、每一个界面用词,在两套主题里都一样。所以主题能让站点看起来不同,但改变不了搜索引擎读到的内容,也改变不了买家看到的说法。 + +| | 商城主题(`src/theme/`,默认) | 编辑风主题(`src/theme-editorial/`) | +|---|---|---| +| 风格 | 明亮开阔,白底配琥珀色 | 工程简报:钛灰、石墨色加站点强调色,规格和成果放在工程图纸式的标题栏里 | +| 字体 | Space Grotesk 和 Inter,由站点自己提供 | 标题和数字用 DIN,正文用 Charter,都取自访客的系统(Apple 上是 DIN Condensed 和 DIN Alternate,Windows 上是 Bahnschrift),并有后备字体 | +| 首页 | 标题区指向规格查找表,接着是聚合页和查找表 | 大标题旁配一张零件大图,接着是行业、带成果数字的案例、带缩略图的目录表和按类型浏览 | +| 脚本 | 三个小脚本,每个都只是给本来就完整的页面加功能 | 没有 | +| 自带文件 | 样式表、字体和图片 | 没有:样式直接写在页面里 | + +第二套主题的存在是为了让契约保持诚实:只有一个实现的契约只是一种猜测。它的测试要求它的清单与商城主题一致,并用它渲染示例的每一个页面。 + +要改用编辑风主题部署,把 `wrangler.jsonc` 里的 `main` 设为 `src/worker/editorial.ts`。要做自己的主题,复制 `src/theme-editorial/`,给 `theme.json` 一个新的 `id`,再仿照 `src/worker/editorial.ts` 加一个指向它的 Worker 入口。带自己文件(字体、图片、脚本)的主题必须放在 `src/theme/`:Mallok 只准备这个目录里的文件。 + +## 收款 + +商城通过 Stripe 的托管结账页收款,用的是你自己的 Stripe 账号。两个 Stripe 密钥都设好之前,商城不收款,并会如实说明。 + +1. **运费区域。** 在后台商城的 **Shipping zones** 里,为每组要寄送的国家加一个区域,填上你销售的每种币种的运费。不在任何区域里的国家无法结账。示例里有四个区域(`seed/shop-sample.sql`)。 +2. **私钥。** 在 Stripe 后台的 Developers → API keys 里复制私钥(试用时是 `sk_test_…`),填进后台商城的 **Stripe secret key**。旁边的 **Test** 按钮会去问 Stripe 是否接受这个密钥。 +3. **Webhook 端点。** 在 Stripe 里添加端点 `https://<你的站点>/_mallok/p/shop/stripe/webhook`,订阅 `payment_intent.succeeded` 和 `checkout.session.expired` 两个事件,API 版本选 `2026-10-28.endive`——这是本代码编写时所依据的版本。Stripe 后台只能按最新版本创建端点;要用别的版本,请通过 Stripe API 的 `api_version` 参数创建。把端点的签名密钥(`whsec_…`)填进 **Stripe webhook signing secret**。在它设好之前,商城对 Stripe 的投递一律回 503,Stripe 会保留这些事件,在最长三天内重投。 +4. **通知邮箱。** 商城的 **Notification email** 设置决定新订单、待退款和询盘发到哪里。邮件经站点自己的邮件设置发出(Settings → Email)。 +5. **可选。** **Tax** 设为 `stripe`,就由 Stripe Tax 在付款时加税:只在你的 Stripe 账号登记了征税的地区加,按 Stripe 的费率收费。默认是 `none`,标价不含税。**Terms page** 填一个页面,买家要勾选接受它。**Order number prefix** 默认是 `ND`。 + +在本地站点(`npm run dev`)上试用时,可以用 Stripe 的命令行工具把测试事件转发过来——`stripe listen --forward-to http://localhost:8787/_mallok/p/shop/stripe/webhook --events payment_intent.succeeded,checkout.session.expired --latest`——它会打印出要填写的签名密钥。不加 `--latest` 时,事件按你账号的默认 API 版本发送。在 Stripe 的付款页上用 Stripe 的测试卡付款。 ## 常用命令 | 命令 | 作用 | |---|---| -| `npm run preview` | 带示例目录和后台登录账号的本地商城,使用一次性数据库 | +| `npm run preview` | 带示例目录和后台登录账号的本地商城,使用一次性数据库(加 `-- --theme editorial` 看另一套主题) | | `npm run dev` | 本地开发服务器,带保留数据的本地 D1 和 R2;启动时是空的 | | `npm run build` | 准备静态资源,然后做一次生产构建(部署预演) | | `npm test` | 站点检查,然后在真实 Workers 运行时里跑插件和主题测试 | @@ -145,10 +187,11 @@ npm run seed:local | `npm run smoke` | 向真实的本地 Worker 发一次真实请求 | | `npm run smoke:shop` | 在真实的本地 Worker 上走完整个商城 | | `npm run seed:local` | 把示例规格载入本地数据库 | +| `npm run starter:documents` | 改了 `content/` 之后,重新生成 starter 的文档清单 | ## 部署 -暂时不要部署。现在部署出来的商城有带价格的目录和购物车,购物车可以作为询价单发出,但还不能付款:没有结账;并且这里的一切都还没有在真实的 Cloudflare 账号上实测过。等 Nundar 就绪后,部署走 Mallok 自己的流程:`npx mallok create . --slug `,它会在你自己的 Cloudflare 账号上创建 Worker、D1 数据库和 R2 存储桶。这条路径还没有在本仓库上跑过。 +暂时不要部署。商城现在可以收款了,但在有人依赖它之前,还要先在真实的 Stripe 账号上用测试模式完整跑通一笔购买;并且这里的一切都还没有在真实的 Cloudflare 账号上实测过。等 Nundar 就绪后,部署走 Mallok 自己的流程:`npx mallok create . --slug `,它会在你自己的 Cloudflare 账号上创建 Worker、D1 数据库和 R2 存储桶,之后 Mallok 的首次运行向导会提供这套示例商城作为起点。这条路径还没有在本仓库上跑过。 ## 语言和币种 diff --git a/SECURITY.md b/SECURITY.md index 56905bb..54885c2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -41,9 +41,11 @@ security document describes each. Nundar implements none of them again. | Data | Where it lives | Notes | |---|---|---| -| Card numbers, CVV | **Nowhere in Nundar** | Payment goes through Stripe's hosted checkout, so card data never reaches this code. A test lists the columns an order may have. No checkout route exists yet. | -| Buyer email and shipping address | D1, on the order | Written when an order is placed, which nothing can do yet: the order logic is built and has no route. Never written to a log. | -| Stripe keys and the webhook signing secret | Not stored yet | They will be plugin secrets, which Mallok encrypts. No code path reads them today. | +| Card numbers, CVV | **Nowhere in Nundar** | Payment goes through Stripe's hosted checkout, so card data never reaches this code. A test lists the columns an order may have. | +| Buyer email, company, tax number and shipping address | D1, on the order | Written when checkout places an order, before the buyer is sent to Stripe. Never written to a log or put in an address. Read in the admin by a signed-in administrator, or a token with `export`. With Stripe Tax on, the address, company and email are also sent to Stripe as a customer of the seller's account. | +| A mark of the visitor who placed an order | D1, on the order | Mallok's one-way hash of the connecting address, which checkout's limit per visitor counts by. Not in an export. | +| Stripe keys and the webhook signing secret | Plugin secrets | Encrypted by Mallok; never logged, never returned by any endpoint. The admin's **Test** buttons return only a verdict. | +| The key orders' links are signed with | D1, in the shop's state | Made once, at random. Anyone who can read the database can open every order's page — which shows nothing the database does not already hold. Not in an export. Deleting it withdraws every link at once. | | What a buyer says of themselves in an inquiry: name, email address, company, phone, message | D1, on the inquiry | Written when a cart is sent as a request for a quote. It is the first personal data the shop holds. Read in the admin by a signed-in administrator, or a token with `export`; deleted there. Never written to a log or put in an address, and the job the plugin queues carries an id only. **The email is another matter**: once handed to Mallok it sits, whole, in Mallok's own queue — see the residual risks. | | A mark of the visitor who sent an inquiry | D1, on the inquiry | Mallok's one-way hash of the connecting address, which is what the limit per visitor counts by. The address itself is never stored, and the admin's list does not show the mark. | | The shop's part of a site export | Not stored: built when asked | Mallok's export, which needs a signed-in administrator or a token with `export`, includes every order and inquiry — names, email addresses, phone numbers, companies, countries, shipping addresses, messages — as files under `shop/`, and the shop's settings, among them the address inquiries are announced to. Whoever holds an export holds that. It leaves out a cart's id and the mark of an inquiry's sender. | @@ -187,51 +189,97 @@ risks — has no challenge in front of it. What is in its place: at least once, and nearly always once: a Worker stopped between the two sends that email again. The mark means handed to Mallok, not delivered. -### Payment, built and not yet reachable - -The order and payment logic is in the repository with its tests, and no route -calls it yet. These controls are in that code now, so that they are not left -to be remembered when the routes are written: +### Payment - **A payment is believed only with Stripe's signature** over the bytes as - received, compared in constant time, and only within five minutes of the - time Stripe signed it. Only the `v1` scheme is read. With no signing secret - configured, everything is refused. -- **No amount comes from a client.** An order's lines are priced by the - server, and the call that opens a Checkout session takes a single amount, - the order's total, rather than line items a client could have shaped. -- **Stock is taken when a payment is confirmed, never before.** Taking it when - an order is placed would let scripted, unpaid orders empty the catalogue. -- **A payment takes stock once**, whether Stripe delivers the event twice, - sends two events for one payment, or delivers twice at the same moment. - Every write is conditional on the order's status, and tests run the - deliveries in parallel. -- **A payment is all or nothing.** The event, the stock, the ledger, what is - owed afterwards and the order's status are one D1 batch. An order whose - stock has gone is marked `oversold` with nothing taken, for a person to - refund. -- **Money taken is never left without a trace.** A payment for an order that - cannot take it — a cancelled one, or one another payment has settled — is - recorded with the payment to refund, and the order and the stock are left - alone. -- **A webhook fails only for what a retry could fix.** Anything else answered - with an error would be redelivered for three days. A payment naming an - order this shop does not have is answered and not acted on: every shop on a - Stripe account sees every payment of that account. -- **Money is a whole number at the database too.** The order tables check the - storage type of every amount, so a fraction of a minor unit cannot be - stored even by code that forgot to round. -- **A Stripe error never carries what was sent.** It is described by Stripe's - own identifiers and the HTTP status. The free-text message is dropped: - nothing rules out its repeating a value that was sent, such as an email - address. -- **An order's status moves only as the state machine allows**, and only if - the order is still where it was read. An oversold order cannot ship. -- **Order lines are snapshots.** A later change to a product cannot alter what - a past order says was bought, or for how much. -- **Emails escape everything a person typed** — product names, SKUs, tracking - numbers — before it becomes markup in a buyer's inbox. -- **A failure reason never carries personal data.** It names the order by id. + received — Mallok hands the route the raw body — compared in constant time, + and only within five minutes of the time Stripe signed it. Only the `v1` + scheme is read. Until the signing secret is set, every delivery is answered + 503 and nothing is read: Stripe keeps it and delivers it again. +- **No amount comes from a client.** Checkout prices the cart from the + database at the moment it places the order, and the Checkout session is + opened for the order's own lines and shipping. Stripe's currency + conversion is switched off for every session. +- **A payment is held to its order.** Its currency and the amount received + must come to the order's total — or, with Stripe Tax, to at least its goods + and shipping, the rest being the tax. One that does not is recorded for a + refund and the order is not paid. +- **Only an order waiting for its payment takes one.** A second payment, for + an order paid or oversold already, is recorded for a refund. +- **Stock is taken when a payment is confirmed, never before**, and once, + however Stripe reports it; the payment is one D1 batch. +- **A paid session is never cancelled.** Before an order is cancelled — by a + new checkout of the same cart, by the seller, by the cron — its Checkout + session is closed at Stripe; one Stripe has complete is left to its + payment, whose word may still be on its way. +- **One open payment per cart**, and an order written only while no other + from its cart is waiting, asked inside the write. +- **A limit on placing orders**: ten an hour from one visitor, counted in the + order's own write, behind Mallok's strict rate limit. Each placement writes + an order and asks Stripe for a session. +- **Money moves at Stripe before the books do.** A refund is made at Stripe + and then recorded; a refund already made in Stripe's dashboard is + recorded when the admin is asked to make it. +- **An order's page opens only with its link's secret**, an HMAC of the + order's id; a wrong one, none and an unknown order all answer the same + 404. The page sends no referrer, and writes nothing. +- **Redirects** go to the shop's own paths, or to the page Stripe's API + returned for the session. +- **Links point at the site's own domain** when it has one, never at the + host a request named. +- **A Stripe error never carries what was sent.** It is described by + Stripe's identifiers and the HTTP status; the free-text message is dropped. +- **The emails escape everything a person typed**, and the buyer is written + to only once a payment is in, or by the seller's own action: never because + a form was filled in with their address. +- **Logs carry no personal data**: kinds, statuses and order ids. A database + failure answering a webhook with 500 is logged with D1's message, which + names a constraint and never a value. + +### Finding orders again + +There are no buyer accounts. A buyer who has lost an order's link asks for +their orders by the address they ordered with. + +- **The form says the same whether or not there were orders** — that a + link is on its way if any were placed with that address — **and in the + same time**: the email, and the key that signs the orders' links, are + queued after the answer has gone. It tells nobody who has bought here. +- **An address is compared without regard to ASCII case, and only so.** The + database folds ASCII letters and nothing else, and the address typed is + folded by the database too, never by the Worker: JavaScript folds all of + Unicode, and turns U+212A KELVIN SIGN into an ASCII k, so an address + folded there could be sent the orders of another. +- **Only an address a payment was made from is written to.** An order left + waiting, or cancelled because its payment page lapsed, carries whatever + address was typed into checkout, and is not counted. Without that, a + stranger could place an order in someone's name, let it lapse, and have + the shop write to them. +- **Two limits, counted inside the write**: five requests an hour from one + visitor, and three links an hour to one address, whoever asks — so that + the form cannot fill a buyer's inbox. A request counts whether or not the + address has orders, so the limits say nothing either. +- **The link's secret is 32 random bytes**, of which the database keeps only + the SHA-256 digest; it opens the list for 24 hours. The list shows each + order by its own signed link, and the page sends no referrer and writes + nothing. +- **What a request leaves behind** is the address typed, lower-cased, and + the visitor's IP hash, for the day the link is good; the cron's hourly + housekeeping deletes every expired one, all at once, on its next run + after the day. They are not in the export. +- **A request costs the same, however large the shop.** It reads the + address's own orders through an index, and a refused one reads none: D1 + bills rows read, and on the Free plan stops every query for the rest of + the day once they are spent. +- **The address is never in a link or a log.** The email carries the link + and nothing of the orders. + +### Customers and sales in the admin + +The customers panel gathers what orders and inquiries already hold — an +address, a company, a country, counts and totals — and keeps nothing of its +own. Sales are counted from the shop's own records. Both are read-only views +an administrator sees. ## Known residual risks @@ -309,29 +357,47 @@ Stated plainly rather than left for an auditor to find: export succeeds and has nothing of the shop's in it. The reason is in the Worker's log, under `shop_export_refused`. - **Sample content and sample variants are public test data.** Do not load - `seed/shop-sample.sql` into a production database. The sample catalogue + `seed/shop-sample.sql` into a production database, and do not choose the + sample in Mallok's first-run wizard for a site that will sell — or delete + its content, variants and zones before it does. The sample catalogue describes a supplier that does not exist: its certifications, test figures and compliance statements are illustrative, and a real site must replace them with its own before it is published. -- **Nobody is told about a payment that has to be refunded.** An oversold - order, and a payment for an order that was cancelled while its buyer was - still on Stripe's page, are both recorded with a row in the outbox — and - nothing reads the outbox yet. Until something does, a person finds them - only by looking. Cancelling an order should also expire its Checkout - session, so that the second case cannot arise; that is not built either. -- **The amount Stripe reports is not compared with the order's total.** The - session is opened for the order's total by the server, so they agree unless - something on the Stripe side changes what the buyer pays. Not yet decided; - see the design's §14. -- **Orders that are never paid stay in the database as `pending`**, with the - buyer's email and address, until something removes them. Nothing does yet. -- **An order that costs nothing cannot be completed.** Stripe is never asked - to charge zero, and nothing confirms a free order without it yet. +- **Checkout has no challenge in front of it**, for the reason the inquiry + form has none. Ten orders an hour a visitor bound what one address can + make; many addresses together can make many pending orders and Stripe + sessions, and with Stripe Tax as many Stripe customers, which nothing + deletes. A pending order is cancelled an hour after its page lapses, and + stays in the database, cancelled, with the email and address typed in. +- **An order's link does not expire.** Whoever has it — a forwarded email — + sees the order's address, company and tax number. It cannot be withdrawn + for one order; deleting the key in the shop's state withdraws them all. +- **Orders are not deleted.** A cancelled or refunded order keeps the + buyer's details, as records of a sale are usually kept; there is no + retention period and no erasure in the admin. +- **The order emails go through Mallok's queue as the inquiry's do**, and + stay in its `job` table as described above. So does the email that carries + a link to a buyer's orders, link included: whoever can read that table + within the day can open the list. +- **A link to a buyer's orders opens them for a day, for whoever has it** — + and the list it opens carries each order's own link, which does not + expire. Whoever opens a forwarded email within the day can keep those + orders' addresses, companies and tax numbers for good. The link is in the + address of the page it opens, as an order's own link is, and cannot be + withdrawn before it lapses, except by deleting its row. +- **Many addresses together can still have the shop write to real buyers**: + three links an hour to each address that has paid, whoever asks. Nothing + more is disclosed by it — the email goes to the address, not to whoever + asked — and the form has no challenge in front of it, for the reason the + inquiry form has none. +- **A purchase in Stripe's test mode has not been run end to end** on a real + Stripe account. Everything above is tested against a stand-in for Stripe's + API built from its documentation. ## Dependency posture Runtime dependencies are deliberately minimal: `mallok` and `zod`. The ECB feed -is called over plain `fetch`. Every dependency is attack surface that a +and Stripe's API are called over plain `fetch`, with no SDK. Every dependency is attack surface that a self-hosted shop inherits. Before adding one, ask whether the platform or Mallok already provides it. diff --git a/docs/superpowers/specs/2026-09-30-nundar-on-mallok-design.md b/docs/superpowers/specs/2026-09-30-nundar-on-mallok-design.md index 05ca572..ad15169 100644 --- a/docs/superpowers/specs/2026-09-30-nundar-on-mallok-design.md +++ b/docs/superpowers/specs/2026-09-30-nundar-on-mallok-design.md @@ -180,6 +180,8 @@ Timestamps are ISO text, as everywhere in the plugin. ### 5.3 Checkout +As built, with the owner's decisions, in §20. The plan was: + 1. The checkout page (theme layout, plugin route) collects the address. The POST is validated with the same schema as today. 2. The server reprices the cart. This is `priceCart`, ported. It rechecks availability, MOQ and stock, but reserves nothing (2026-09-03 §6.3). 3. One D1 batch writes the order and its line snapshots, with status `pending`. @@ -307,6 +309,7 @@ The phases follow Mallok's own roadmap (`mallok: docs/PRODUCT_VISION.md §9`: 0. **Phase 2: payment (Mallok 0.3)** - *Built ahead, 2026-10-05 (§14):* everything below that needs no Mallok extension point — the order tables, placing an order, the payment batch, refunds, the webhook's decision, the Stripe calls and the order emails. Not built: every route, page and admin screen. +- *Built 2026-10-31 (§20), locally:* shipping zones, the checkout and order pages, the webhook route, the follow-ups, the order panels and their actions, on the owner's nineteen decisions. Of the exit criteria below, the first two hold; the test-mode purchase waits for the owner's Stripe test keys, and the quotas for a deployment (the owner waived measuring CPU now). - Mallok: API-5, 6 (actions with parameters) and 8. - Shop plugin: - Stripe Checkout and the webhook; @@ -320,6 +323,7 @@ The phases follow Mallok's own roadmap (`mallok: docs/PRODUCT_VISION.md §9`: 0. - Free-plan quotas are checked against a day of synthetic traffic. **Phase 3: full storefront (Mallok 1.0)** +- *Built 2026-10-31 (§21), locally:* the customer and sales panels, a buyer's way back to their orders, the starter, and the second theme. The Next.js code was already retired to its tag; no migration was built, because no real data or deployment of it is known. Parity with the old README holds for every commerce item; what is left is Mallok's (§21). - Mallok: API-10. - Nundar: - customer view and sales dashboard as panels; @@ -740,3 +744,148 @@ A site export is how an operator leaves with what is theirs: `mallok export` wri 4. *An operator is not told why the shop's export failed*, and is advised to switch the plugin off. Written up. 3. *Mallok's own inquiry plugin exports its newest thousand rows and no more*, without saying so — found by reading it, while deciding what this export should do past its limit. Written up. + +## 20. What phase 2 changed or found (2026-10-31) + +Phase 2 (§9): checkout and payment, on `mallok@0.1.0-rc.11` as it shipped. The owner was given a sheet of nineteen decisions on 2026-10-31, asked that the whole of it be built locally before anything is deployed, and changed none of them; each was taken as proposed, and each is listed below with what was built for it. **Nothing was deployed and nothing was measured on a Cloudflare account**: the owner said the CPU use of the pages had been looked at before and was not to be measured again now (2026-10-31), so the exit criteria that need a real account are open (below). + +**What a buyer does.** From a cart whose every line can be ordered, goes to checkout; chooses the country the order goes to and sees shipping and the total for it; gives a company, an address and an email; and is sent to Stripe's hosted page to pay. Coming back, they land on their order's own page, which opens with a signed link and with nothing else, and are written to when it is confirmed, shipped, refunded or cancelled by the seller. + +**What a seller does.** Sets shipping zones in the admin; sets the two Stripe secrets; and works orders from a panel that lists them with their lines: ship (tracking number and carrier), mark delivered, cancel one that was not paid, refund in full, or fulfil an oversold one once restocked. Payments the shop could not keep are listed in a panel of their own, to refund. The notification address that was the inquiries' is the shop's now: new orders, oversold ones and refunds owed are sent there. + +**The decisions, as taken.** + +| | Decision | Built as | +|---|---|---| +| D1 | Sell to businesses | A company is required at checkout | +| D2 | No buyer accounts | An order opens with a signed link (`lib/order-access.ts`): an HMAC of its id under a key the shop makes once and keeps in its state | +| D3 | Only methods that settle at once | `allowed_payment_method_types` card and Link. Apple Pay and Google Pay are card wallets with no type of their own; whether a buyer sees them is Stripe's and the account's | +| D4 | A fixed rate per zone, free past an amount | `p_shop_shipping_zone`, `_country`, `_rate`; a records panel; one rate per currency per zone | +| D5 | Ship only to a zone's countries | A country in no zone is not offered and not taken | +| D6 | No tax by default, Stripe Tax as a setting | `tax_mode`. With `stripe`, a Stripe customer is made per order holding the address the order ships to, which is what Checkout works tax out from when it collects no address itself; prices and shipping are `exclusive`; the order's tax is what the payment came to beyond goods and shipping | +| D7 | A tax number, optional, recorded | On the order, its page and the seller's email. Not sent to Stripe | +| D8 | Stripe's own currency conversion off | `adaptive_pricing[enabled]=false` on every session | +| D9 | An hour to pay, then the order is cancelled | `expires_at`; `checkout.session.expired` cancels the order; the cron cancels one Stripe never spoke for, an hour after its page lapsed | +| D10 | The cart emptied when the payment is in | In the payment's own batch, of the order's variants only, for a paid and an oversold order alike | +| D11 | Full refunds only; stock back as chosen | The refund action asks: back to stock unless it has shipped (the default), back to stock, or left as it is | +| D12 | An oversold order is refunded, or restocked and fulfilled | `oversold → paid` by `fulfilOversold`, which takes the stock then; `oversold → cancelled` is gone from the state machine | +| D13 | The order number's prefix a setting | `order_no_prefix`, up to six capitals or digits, `ND` by default | +| D14 | No checkout for a total too small to charge | `too_small` below Stripe's least (0.50 USD or EUR, 0.30 GBP), a total of nothing included; the buyer is pointed to the inquiry | +| D15 | No invoices of the shop's own | Whatever receipt the seller's Stripe account sends, and the shop's confirmation | +| D16 | One notification address for the shop | The setting that was the inquiries' recipient, relabelled | +| D17 | Four buyer emails, in four languages | Confirmed, shipped, refunded, cancelled by the seller — not for a payment page the buyer let lapse: the address was never proven to be theirs | +| D18 | A tracking number required, a carrier from a list | DHL, FedEx, UPS, or Other with its name | +| D19 | Terms to accept when the shop names a page | `terms_path`; a box the form requires, linking to it | + +And the ones the sheet did not ask about: the Stripe API version is pinned (`2026-10-28.endive`), and the webhook endpoint a seller creates is to be set to the same; every payment is held to its order's currency and total, and one that does not fit is refused and owed a refund (`amountFits`); a Checkout session is expired at Stripe before its order is cancelled, never after; what a change owes is carried out by a Mallok job, with the cron behind it; the order records the cart it came from; a payment for an order this database does not have is still answered 200 and left; no coupons, no stock held for a pending order, no payment on account — a quote is what an inquiry is for; email goes through Mallok's site settings. + +**What building it found.** + +1. *Stripe's current API names the payment methods differently.* `payment_method_types` is not among the create parameters of a Checkout session at `2026-10-28.endive`; `allowed_payment_method_types` filters the methods Stripe would offer. Read on 2026-10-31. +2. *Stripe Tax needs an address the session can see.* Checkout works tax out from an address it collects, or from its customer's saved one. Collecting it again on Stripe's page would make the buyer type it twice and let the two differ — the tax would be for one place and the goods go to another. So the shop gives Stripe a customer holding the address the buyer gave here: one per order, because there are no accounts to keep one on. Stripe's documentation also says Google Pay is offered with Stripe Tax only when a shipping address is collected or the customer has one saved; this satisfies that. +3. *A job has no request to take the site's address from.* The emails' links are written by the follow-up job, later. So an order records the address its buyer checked out on (`site_origin`), and the link's secret is an HMAC, which a job can compute again, rather than a random token, which it could not without keeping it readable. The key is in the shop's state, which an export leaves behind: an export opens no order, and a site restored from one gives its old links up. +4. *A job and the cron can meet over one outbox row.* Each row is claimed before its follow-up runs (`claimed_at`); a claim older than ten minutes is taken to belong to a runner that stopped. A row that fails is let go and holds its order's later rows back, so "shipped" never reaches a buyer before "confirmed". +5. *A table panel lists what is stored.* So the orders and the refused payments are listed from read-only views (`p_shop_order_admin`, `p_shop_order_line_admin`, `p_shop_refused_payment`) that spell amounts out from minor units without a float. A view has no `rowid`, which is what Mallok orders related rows by when told nothing, so the lines name their order. +6. *A refund already made in Stripe's dashboard* is refused by Stripe as `charge_already_refunded`. The admin takes that as done and records the refund, rather than leaving an order that can never be marked refunded. +7. *One open payment per cart.* A buyer who comes back from Stripe's page, changes the cart and checks out again would otherwise leave the first page payable. Placing an order first expires the session of every order still waiting from the same cart. +8. *The most one payment can carry* is eight digits of minor units for a payment that is not by card — the strictest of the methods offered — so a larger total is refused (`too_large`) and pointed to the inquiry. The least is Stripe's for the charge's currency; Stripe holds a converted charge to the least of the account's settlement currency, which the shop cannot know, and a session Stripe refuses for it closes the order and tells the buyer that payment is not available. +9. *Until the signing secret is set, Stripe's deliveries are answered 503*, so that Stripe keeps them and delivers again, for up to three days, rather than having them answered 200 and lost. + +**§14's open items, now.** 1, the outbox: drained (finding 4). 2, a payment for a cancelled order: the session is expired first. 3, orders never paid: cancelled (D9). 4, orders that cost nothing: refused (D14). 5 and 6, Adaptive Pricing and the amount: off, and checked. 7, the cart: emptied (D10). 8, refunds: Stripe first, `charge_already_refunded` taken as done, stock as chosen; an order whose first session Stripe failed is closed, and the buyer places a new one. 9: gone (D12). 10: pinned. 11: site email. 12: a setting. 13, a payment for an unknown order: unchanged, still logged and left. 14, a variant deleted outright: still open; nothing deletes a variant that is on an order. + +**What two independent reviews then found.** The code was given to two reviewers, one for commerce correctness and one for security, with the rules it must keep and no account of how it keeps them. Fourteen things, each checked here before it was acted on, and each fixed with a test that fails without the fix: + +1. *A second payment for an oversold order was taken.* `oversold → paid` (D12) made `canTransition` say yes to it: with the stock still short the webhook failed with an illegal transition for three days and left the money untraced; with the stock back it paid the order and wrote the second payment over the first. Only a `pending` order takes a payment now; another for an oversold one is refused and owed back. +2. *"Not open" was taken for "closed".* A session Stripe would not expire may be one that was paid a moment ago, its word not yet arrived — the order here still `pending`. A new checkout from the same cart, the admin's cancel and the cron's sweep all cancelled it, and the payment then arrived for a cancelled order. Stripe is asked now (`closeCheckoutSession`), and an order it has complete is left to its payment: the new checkout is refused with `paid_meanwhile`. +3. *Two placements of one cart could both stay payable.* Closing earlier orders and writing the new one are separate steps. The order is written now only if no other from its cart is waiting, asked inside the write; and a placement whose order was closed by another while it opened its session closes that session again, rather than send the buyer to pay for a cancelled order. +4. *Checkout had no limit of its own.* Each placement writes an order, asks Stripe for a session and, with Stripe Tax, makes a Stripe customer; Mallok's rate limit is best-effort. Ten orders an hour a visitor now, counted in the order's write (`MAX_CHECKOUTS_PER_HOUR`). +5. *An oversold order lost Stripe's tax*: the oversold write did not record it, as the paid write does. It does. +6. *A refund decided its stock on a status read before Stripe was asked.* An order that shipped in between had its goods put back. The refund is now written only if the order is still in the status the choice was made on. +7. *A row another runner held did not hold its order back*: the runner did not read claimed rows, so "shipped" could go out while "confirmed" was in another's hands. Claimed rows are read and hold their order. +8. *A row that owed two emails and failed at the second sent the first again.* Each email is marked on the row as it is handed over (`progress`). +9. *The cron cancelled a lapsed order without asking Stripe.* A payment made in the last moment whose word was delayed past the hour was then refused. The cron asks Stripe first, and without the secret key leaves such an order as it is. +10. *A refund or an expiry that failed could not be asked again for a day*: Stripe keeps the answer to an idempotency key, failures included. Neither carries a key now — a refund of the whole payment cannot be made twice, and expiring is safe to repeat — so the admin's "try again" is true. +11. *The links were built from the request's host.* The site's own domain is used when it has one. +12. *The order page's address carries its secret.* It now says `Referrer-Policy: no-referrer`. +13. *Stripe's answer "not open" was read from every 4xx*, a bad permission included. Only 400 and 404 now. +14. *The webhook logs the message of a database failure*, where checkout logs only an error's kind. Kept: the messages are D1's, which name a constraint and never a value, and a 5xx a seller cannot diagnose is worse. Recorded in `SECURITY.md`. + +**How it was verified.** All of it in workerd, against the site's own Worker: 1,017 tests in `test/shop` and `test/theme`, 206 more than before phase 2 — the checkout page and its form through `SELF.fetch` with a stand-in for Stripe's API in place of the global `fetch`; a payment delivered signed to the real webhook route and carried through Mallok's own scheduled handler to the buyer's and the seller's emails in Mallok's queue; the order page's link, wrong, missing and for another order; every admin action, through its function and once through Mallok's panel API; the follow-up runner with a recording email context, two runners at the same moment, a failing email holding later rows back; the cron's sweep and fallback; the four languages of both pages, every field's attributes held to the server's constants, and both pages whole in every state. Forty-one guards were broken one at a time, before and after the reviews, and each turned a test red — the races on every one of three runs. `npm run smoke:shop` goes from the cart to the German checkout page of a real local Worker with the sample's shipping zones, sees shipping to Germany quoted, and sees that with no Stripe keys no payment is offered, no order placed and a delivery from Stripe answered 503. + +**Not verified.** No payment was made at Stripe, in test mode or otherwise: that needs the owner's test keys, and is the next step. Everything about Stripe here was read in its documentation on 2026-10-31 and run against a stand-in; how Stripe's page looks with these parameters, whether it shows Apple Pay or Google Pay, and what Stripe Tax computes with real registrations were not seen. Emails were seen handed to Mallok's queue, not delivered. Nothing was deployed, and no figure was taken on a Cloudflare account (above). + +**Left open.** + +1. *A Stripe test-mode purchase, end to end*, on the owner's keys: phase 2's last exit criterion. +2. *Partial refunds, invoices, buyer accounts* — not in phase 2 by decision (D11, D15, D2). +3. *A payment for an order this database does not have* is still left with a log line (§14, item 13). +4. *A form the server refuses comes back empty* (M33), which at checkout is an address typed again. The fields carry the server's rules, and the only refusals a browser cannot foresee are a cart that changed and Stripe being unavailable. +5. *With Stripe Tax, each order makes a Stripe customer, and nothing deletes it* — one per order, since there are no accounts; the limit per visitor bounds how many a stranger can make. +6. *An order's link does not expire*, and cannot be withdrawn for one order: only by deleting the key, which withdraws them all. +7. *That the terms were accepted is not recorded* with the order — when, and which version of the page. +8. *The admin cannot say "done" with a message* (M43): an action that changed some orders and not others answers as a refusal that says which. + +## 21. What phase 3 changed or found (2026-10-31) + +Phase 3 (§9): the full storefront, built straight after phase 2 on `mallok@0.1.0-rc.11`, under the same instruction from the owner — the whole of it locally, nothing deployed, the CPU use of pages not measured again (§20). + +**What was built.** + +1. *Customers and sales, as panels* (`migrations/0005_storefront.sql`). There are no buyer accounts (D2), so a customer is an address that placed an order or sent an inquiry, compared without regard to case: the panel gathers what the shop already holds and keeps nothing of its own. Each row has the address's latest company, the country its newest order ships to (or, for an address that never ordered, the one its inquiry came from), its orders and inquiries counted, what it has spent in each currency on orders paid, shipped or delivered — a refunded one is not counted — and its first and last contact; its orders and inquiries open beneath it. *Sales by month* reads the outbox — a payment is counted in the month it arrived, once, whether the order was paid or oversold, and a refund in the month it was made — per currency, with the orders paid, their total, the refunds, net and the average order. *Sales by product* is per SKU and currency, from the lines of orders paid, shipped or delivered. All three are read-only views, spelled out from minor units without a float, as the order panels are (§20, finding 5). +2. *A buyer's way back to their orders* (`lib/order-lookup.ts`, `routes/orders.ts`, the theme's `shop/orders`). The buyer types the address they ordered with and is emailed a link, good for a day, that lists the orders paid for from it, each opening its own page by its signed link (D2). The page says the same whether or not there were any, so the form tells nobody who has bought here; the link's secret is 32 random bytes of which only the digest is kept; a visitor may ask five times an hour and an address be sent three links an hour, whoever asks, counted inside the write; a request is counted whether or not the address has orders, so the limits say nothing either; expired requests are deleted by the cron's housekeeping, and the table is left out of the export. The cart page and every order's page link to it. +3. *The sample as a starter* (`src/starter/`; API-10). A site deployed from this repository can be filled from Mallok's first-run wizard with no command: the 31 bundles in four languages, the nine variants with their prices in three currencies, the four shipping zones, and `site.json`'s settings. The documents are generated from `content/` (`npm run starter:documents`), and a project test fails when the generated file is not what `content/` would give. A starter carries no files, so the sample comes without its pictures, and the theme draws every page whole without them; `npm run preview` still publishes it with them. +4. *A second theme* (`src/theme-editorial/`, `src/worker/editorial.ts`). The old Nundar kept two opposite themes "to keep the contract honest: a contract with one implementation is only a guess"; this does the same for the contract Mallok and the shop give a theme. It reads the same kinds, options, language packs and plugin views — a test holds its manifest to the commerce theme's — and draws them the other way: an engineering bulletin on titanium grey, set in DIN and a book face, with a product's attributes and a case's results in a drawing's title block, the industries and the case studies before the catalogue, a ruled table where the other has a finder, and no script and no file of its own. Its first look — serif on warm paper, one narrow column, no pictures — was turned down by the owner on 2026-11-01 as ugly, and redrawn the same day. What the commerce theme adds with its three scripts is left out, and each page is whole without it as there: the catalogue is a table with no filters, a page states its currency and the cart's form changes it, and the engineering page prints its formulas and tables with no calculator above them. Its stylesheet is in the page, because `mallok prepare` stages the files of the theme at `src/theme` only (M46). A site uses it by pointing `main` in `wrangler.jsonc` at `src/worker/editorial.ts`; `npm run preview -- --theme editorial` shows it, and CI brings it up. + +**What building it found.** + +1. *The order lookup counted orders that were never paid for* — cancelled because their payment page lapsed — and emailed their address a link. The address on such an order is whatever was typed into checkout, which is why the buyer's own emails are not sent for it (D17); counted here, it let a stranger have the shop write to someone who never bought anything. Only the statuses a payment leads to count now (`PAID_FOR_STATUSES`). Found while writing this section, before the review. +2. *A related table is ordered by `rowid` when its panel names no order* (M41), and a view has none: every related table and every panel built on a view here names its order, and those whose rows can tie name a unique column last, or the list changes order between two loads. +3. *Related rows come back with the columns the manifest declares, and only those*: a column the view has and the related table does not name is not sent to the admin, so a test reads what a seller sees, not the view. +4. *The wizard checks a starter's records against the same fields as the admin's form*, so the sample's variants and zones go through `saveVariant` and the zone handler exactly as a seller's would — a SKU taken twice, a price with no base, would be refused there as here. `test/shop/starter.test.ts` imports the starter through Mallok's wizard endpoint and compares what it wrote with what `seed/shop-sample.sql` loads. +5. *A theme cannot have files unless it is the one at `src/theme`* (M46). The editorial theme has none; a second theme with fonts, pictures or a script could not be served. +6. *Below 40rem a table of several columns does not fit a phone*, and German puts a whole name in one word. The editorial theme draws a sizes table, the catalogue and the cart a row at a time there, each value under its column's name (`data-label`), with table roles in the markup so that a screen reader still reads a table; a table in a text scrolls inside itself, as the commerce theme's does; titles hyphenate in the page's language. Measured in a browser on all 131 pages of the sample and the shop, at 320, 375, 768 and 1280 pixels: none scrolls sideways. + +**Phase 3's exit criterion: parity with the old README, item by item.** The list is the "What is in the box" and "Theming" sections of the README at the tag `nextjs-final`. + +| The old Nundar | Now | | +|---|---|---| +| Product and application pages in four languages, `hreflang`, self-referencing canonicals | Mallok renders and caches them, with `hreflang` and `x-default` and a canonical; an application is its own kind (§11, decision 3) | Met | +| `Product`, `Offer`, `Article`, `BreadcrumbList` structured data | `Product` with the shop's offers, `Article`, `FAQPage`, `Organization`: Mallok's and the shop's. No `BreadcrumbList`: Mallok emits none, and a theme cannot write JSON-LD (M47) | Not met — Mallok's | +| A sitemap from the database | Mallok's, with `hreflang` | Met | +| Stock and prices patched in on the client | Replaced on purpose: a page prints a state, not a count, and is purged by tag when a price moves; nothing is fetched after the page loads (§5.1) | By design | +| Cart, checkout and order tracking for guests | Phases 1 and 2, and now every order found again by email | Met | +| The admin in English, with Chinese | Mallok's admin is in English only (M47) | Not met — Mallok's | +| Products, multilingual content, SEO fields with length guidance | Mallok's editor, every language of an item, a description used as the meta description; no length guidance (M47) | Partly — Mallok's | +| Images to R2, the type checked from the file, alt text required | Mallok checks the sniffed type and makes WebP variants; alt text has a default per image and is not required (M47) | Partly — Mallok's | +| Orders by an explicit state machine | `lib/order-state.ts` (phase 2) | Met | +| Customer records, a sales dashboard | Panels (above) | Met | +| Administrator management | One administrator in Mallok 0.1; roles deferred by the owner | Deferred by the owner | +| A translation workbench | Deferred by the owner | Deferred by the owner | +| Integer money; prices recomputed from the database; stock taken after payment, never below zero; signed, idempotent webhooks; MOQ and lead time first-class; a USD base with EUR and GBP from ECB rates, a buffer, price points and a drift threshold | All hold, and are tested (README, "Commerce rules") | Met | +| Two opposite themes; SEO never in a theme; interface words shared | Two themes; `page.head` is Mallok's; the editorial theme reads the commerce theme's packs | Met | +| A security contact at `/.well-known/security.txt` (the old deployment steps) | Not in Mallok (M47) | Not met — Mallok's | + +Every commerce item is met. What is open is Mallok's, listed for the owner as M47, two items of which the owner had already deferred. + +**What two independent reviews then found.** As in phase 2, the code was given to two reviewers, one for correctness and one for security and privacy, with the rules it must keep and not how it keeps them. Each finding was checked here before it was acted on, and each fixed with a test seen failing first: + +1. *An oversold order's refund made a month's net negative.* The sales view counted `order.paid` rows as money received, and an oversold order is paid as `order.oversold`: its refund was counted and its payment was not, and once restocked and fulfilled it was counted in the month of the fulfilment, for money taken earlier. A payment now counts when it is confirmed, either way, and the fulfilment's `order.paid` does not count again. 0005 may have run on a local database, so `0006_review.sql` drops and makes the view again. +2. *An address's case was folded two ways.* The lookup lowered the typed address in JavaScript, which folds all of Unicode, and compared it with SQLite's `lower()`, which folds ASCII only: an address with a capital beyond ASCII found none of its orders, and one holding U+212A KELVIN SIGN — which JavaScript turns into an ASCII k — was sent a link to the orders of the address it folded to, which it had never paid from. Found by both reviewers. SQLite folds both sides now, as the customers view does. +3. *The answer told the time it took.* For an address with paid orders the route waited on two more writes — the key that signs the orders' links, the email queued — before answering, so a stranger could tell a buyer's address by timing it, which the page's words are careful not to tell. Both run after the answer now (`ctx.waitUntil`). +4. *Every request read every paid order.* `lower(email)` had no index, so the count read the paid orders through the status index, refused requests included; D1 bills rows read, and on the Free plan stops every query for the day when they are spent — a public form whose cost grew with the shop. An index on `(lower(email), status)` bounds a request to its address's orders, and a refused request reads none. SQLite tested an `EXISTS` in a `WHERE` against each row rather than once, so the guard is a `CASE`. +5. *Expired requests were cleared fifty an hour*, with the carts' limit: past fifty requests an hour the table grew without end, and typed addresses were kept past the day. Found by both reviewers. One statement deletes them all now. +6. *The editorial theme left empty elements on a site that filled in little*: a sizes cell for a product with none, a SKU for a cart line whose size was deleted, a paragraph of links for a cart with no catalogue and no checkout, and — found by the bare-site test written for it — a footer column for a site that gave no contact. Its tests rendered only the full sample. +7. *A customer's country mixed two meanings*: an order's is where it ships, an inquiry's where the request came from. The shipping country comes first now. +8. *Tests asserted less than their names said*: the starter was not held to which product each variant belongs to, nor to the shipping rates' free-over amounts, nor to French and Spanish pages; the lookup was not shown to list shipped, delivered, refunded or oversold orders; its limits, counted inside the write, had no test of two requests at once; an order's page was drawn only while pending — in both themes, though the guide said both checkout pages were held in every state. Each has its test now. Two requests are held at the write with `holdWrites`, and a read-then-write version of the limits turns those tests red on every run. + +And one the security reviewer raised that is kept, and written in `SECURITY.md`: a lookup link opens the list for a day, and the list carries each order's own link, which does not expire. + +**What was not built, and why.** + +- *A migration from the Next.js schema, and redirects from `/en/*`.* §9 asks for them "if any real shop data exists". None is known to this work: the Next.js version's configuration names no route or domain, and the owner has mentioned no shop that ran on it. If one did, the owner says so; the redirects would then need Mallok — its `redirect` table takes one path at a time and a plugin may not write it, and intercepting requests is the `onRequest` hook this repository does not use for pages. +- *Retiring the Next.js code* needed nothing: it was removed when the rebuild began and is kept at the tag `nextjs-final`. +- *Invoices, partial refunds and buyer accounts* stay out, by D15, D11 and D2. + +**How it was verified.** 1,100 tests in workerd — 83 more than phase 2 left — and 54 project tests: the panels through Mallok's panel API with orders and inquiries made through the shop's own functions; the lookup through `SELF.fetch` from the form to the email in Mallok's queue and back through the link; the starter through Mallok's wizard endpoint, compared with the seed; and the editorial theme on its own Worker, the sample imported through its starter and every one of its pages, the home page and every list in four languages, and the cart, checkout, order and lookup pages drawn and held whole. Before the reviews, twenty-five guards were broken one at a time, and each turned a test red: four in the views, nine in the lookup, three in the starter, eight in the editorial theme, and the generated documents left stale. After them, every fix was preceded by its test failing, and twelve more were broken and turned red: the deferred email (an email sent whatever, three runs of three), the index and the refused-request guard, the four template guards, the starter's product and free-over amount, the limits made read-then-write (three runs of three), and a paid-for status left out. What a request reads is held by the `rows_read` D1 reports, locally. `npm run smoke:shop` and `npm run preview -- --check` pass for the commerce theme, and `npm run preview -- --theme editorial --check` for the editorial one: the real sample published with the Mallok CLI to a real local Worker. The editorial theme was looked at in a browser at phone and desktop widths, and its pages measured for sideways scrolling (finding 6). + +**Not verified.** As in §20: no payment at Stripe, no deployment, no figure from a Cloudflare account, no email delivered — the lookup's link was seen handed to Mallok's queue. The wizard was driven through its endpoint, not clicked through in the admin. The editorial theme was not looked at with a screen reader. The index on an expression and the query plans were seen in workerd's SQLite, not on D1 itself, whose documentation neither names nor rules out an index on an expression; and how long the lookup's answer took before and after finding 3 was not measured anywhere — the fix removes the difference by construction. diff --git a/package.json b/package.json index 2a59aee..7852e5c 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,8 @@ "test:project": "node --experimental-strip-types --test \"test/*.test.ts\"", "test:shop": "vitest run", "seed:local": "wrangler d1 execute DB --local --file=seed/shop-sample.sql", - "smoke:shop": "node scripts/smoke-shop.mjs" + "smoke:shop": "node scripts/smoke-shop.mjs", + "starter:documents": "node scripts/starter-documents.mjs" }, "dependencies": { "mallok": "0.1.0-rc.11", diff --git a/scripts/lib/local-shop.mjs b/scripts/lib/local-shop.mjs index 3a2c810..2e8d45f 100644 --- a/scripts/lib/local-shop.mjs +++ b/scripts/lib/local-shop.mjs @@ -64,12 +64,14 @@ export function portInUse(port) { /** * Starts `wrangler dev` on `port`, keeping its database, its files and its - * cache under `state`. + * cache under `state`. `main` is the Worker to run, when it is not the one + * `wrangler.jsonc` names — `src/worker/editorial.ts`, the same site with the + * second theme. * * `ready` resolves once the Worker answers. `stopped` resolves if it exits on * its own. `stop` ends it and everything it started. */ -export function startWorker({ port, state }) { +export function startWorker({ port, state, main }) { const processGroup = process.platform !== 'win32'; const base = `http://127.0.0.1:${port}`; @@ -78,6 +80,7 @@ export function startWorker({ port, state }) { [ wrangler, 'dev', + ...(main === undefined ? [] : [main]), '--local', '--port', String(port), diff --git a/scripts/preview.mjs b/scripts/preview.mjs index 5c48345..e42817d 100644 --- a/scripts/preview.mjs +++ b/scripts/preview.mjs @@ -15,6 +15,9 @@ * * npm run preview on port 8799 * npm run preview -- --port 8800 on another port + * npm run preview -- --theme editorial + * the same shop, drawn by the second + * theme (src/theme-editorial) * npm run preview -- --check bring it up, check it, take it down * * It brings the shop up through the same code as `npm run smoke:shop`, which @@ -39,9 +42,21 @@ import { const { values } = parseArgs({ options: { port: { type: 'string' }, + theme: { type: 'string', default: 'nundar' }, check: { type: 'boolean', default: false }, }, }); +/** The Worker each theme is built into: one site, two ways of drawing it. */ +const WORKERS = { + nundar: undefined, + editorial: 'src/worker/editorial.ts', +}; +if (!Object.hasOwn(WORKERS, values.theme)) { + process.stderr.write( + `preview: there is no theme "${values.theme}". Use ${Object.keys(WORKERS).join(' or ')}.\n`, + ); + process.exit(1); +} // A person wants an address they can come back to; a check wants whatever // port is free, so that it can run beside a preview someone has open. const port = @@ -64,7 +79,7 @@ if (await portInUse(port)) { const say = (line) => process.stdout.write(`${line}\n`); const state = await mkdtemp(join(tmpdir(), 'nundar-preview-')); -const worker = startWorker({ port, state }); +const worker = startWorker({ port, state, main: WORKERS[values.theme] }); const { base } = worker; let stopping = false; @@ -105,8 +120,10 @@ async function check(login) { home.html.includes(escaped(site.themeOptions.hero_title)), 'the home page does not carry the headline in site.json', ); + // Asked of the links, not of one theme's table, so that either theme + // passes for the same catalogue. expect( - (home.html.match(//g) ?? []).length > 1, + new Set(home.html.match(/href="\/products\/[^"]+"/g) ?? []).size > 1, 'the home page lists no products', ); for (const locale of site.locales) { diff --git a/scripts/smoke-shop.mjs b/scripts/smoke-shop.mjs index 77cf7db..d7c7470 100644 --- a/scripts/smoke-shop.mjs +++ b/scripts/smoke-shop.mjs @@ -9,9 +9,12 @@ * 3. load the sample variants from `seed/shop-sample.sql`; * 4. request every kind of page, follow the navigation in every language, * and fetch the theme's own files; - * 5. add to the cart with the form a product page offers, and read the - * cart page it leads to; - * 6. add a variant the way the admin's form does, and delete it. + * 5. add to the cart with the form a product page offers, read the cart + * page it leads to, and go on to checkout, which quotes shipping and, + * with no Stripe keys set, takes no payment; + * 6. add a variant the way the admin's form does, and delete it; + * 7. send the cart as a request for a quote; + * 8. export the site, and find the shop's data in it. * * It exists because the unit tests, thorough as they are, run each piece in * isolation. This is the one place the theme, the plugin, the content and the @@ -592,6 +595,86 @@ try { 'the German cart page does not show the same cart in German and in euros', ); + // 5b. Checkout, the way the cart page leads to it. The run sets no Stripe + // keys, so the shop takes no payment: the cart offers no checkout, the + // checkout page says so and places nothing, and Stripe's deliveries + // are turned away for Stripe to deliver again. + expect( + !germanCart.includes('/_mallok/p/shop/de/checkout'), + 'the cart page offers checkout though the shop cannot take a payment', + ); + const checkoutPage = await fetch( + `${base}/_mallok/p/shop/de/checkout?country=DE`, + { headers: { cookie: cartCookie }, signal: timeout() }, + ); + const checkout = await checkoutPage.text(); + expect( + checkoutPage.status === 200 && + checkout.includes('

Kasse

') && + /