From 017ab777d241eab899f7e1d52b21dca5e519c7c0 Mon Sep 17 00:00:00 2001 From: JasonYv Date: Tue, 3 Nov 2026 20:04:07 +0800 Subject: [PATCH 1/2] fix: read the Stripe secrets without the white space they were pasted with The first purchase in Stripe's test mode found every webhook delivery refused as signed with another secret: the signing secret had been saved with the space before it on the line stripe listen prints, and Mallok keeps a secret exactly as pasted. Neither secret can contain white space, so every reading now goes through one function that trims it, and a test holds the shop to that one place. --- src/plugins/shop/lib/checkout.ts | 5 +- src/plugins/shop/lib/order-admin.ts | 7 +-- src/plugins/shop/lib/scheduled.ts | 3 +- src/plugins/shop/lib/stripe-check.ts | 5 +- src/plugins/shop/lib/stripe-secrets.ts | 21 ++++++++ src/plugins/shop/routes/stripe-webhook.ts | 3 +- test/shop/checkout.test.ts | 63 +++++++++++++++++++++++ test/shop/order-page.test.ts | 22 ++++++++ 8 files changed, 120 insertions(+), 9 deletions(-) create mode 100644 src/plugins/shop/lib/stripe-secrets.ts diff --git a/src/plugins/shop/lib/checkout.ts b/src/plugins/shop/lib/checkout.ts index 2f73003..c640690 100644 --- a/src/plugins/shop/lib/checkout.ts +++ b/src/plugins/shop/lib/checkout.ts @@ -31,6 +31,7 @@ import { shippingCountriesStatement, } from './shipping.js'; import { MAX_CHARGE_MINOR, MIN_CHARGE_MINOR } from './stripe-client.js'; +import { stripeSecret } from './stripe-secrets.js'; /** The length each field may have. The form carries the same in `maxlength`. */ export const CHECKOUT_LIMITS = { @@ -243,8 +244,8 @@ export async function readCheckout( export function stripeKeys( secrets: Readonly>, ): { secretKey: string; webhookSecret: string } | null { - const secretKey = secrets.stripe_secret_key ?? ''; - const webhookSecret = secrets.stripe_webhook_secret ?? ''; + const secretKey = stripeSecret(secrets, 'stripe_secret_key'); + const webhookSecret = stripeSecret(secrets, 'stripe_webhook_secret'); // Without the signing secret no payment could ever be confirmed: an order // would be paid for and wait for ever. return secretKey === '' || webhookSecret === '' diff --git a/src/plugins/shop/lib/order-admin.ts b/src/plugins/shop/lib/order-admin.ts index db44be2..974267c 100644 --- a/src/plugins/shop/lib/order-admin.ts +++ b/src/plugins/shop/lib/order-admin.ts @@ -29,6 +29,7 @@ import { createRefund, StripeRequestError, } from './stripe-client.js'; +import { stripeSecret } from './stripe-secrets.js'; /** * A refund asked of Stripe, or the word that the payment had been refunded @@ -213,7 +214,7 @@ export async function cancelOrders( confirm: 'Tick the box to cancel these orders.', }); } - const secretKey = ctx.secrets.stripe_secret_key ?? ''; + const secretKey = stripeSecret(ctx.secrets, 'stripe_secret_key'); const problems: string[] = []; let done = 0; for (const order of await readOrders(ctx.db, ids)) { @@ -295,7 +296,7 @@ export async function refundOrders( confirm: 'Tick the box to refund these orders in full.', }); } - const secretKey = ctx.secrets.stripe_secret_key ?? ''; + const secretKey = stripeSecret(ctx.secrets, 'stripe_secret_key'); if (secretKey === '') { return refused( 'Set the Stripe secret key first: the refund is made at Stripe.', @@ -391,7 +392,7 @@ export async function refundRefusedPayments( confirm: 'Tick the box to refund these payments in full.', }); } - const secretKey = ctx.secrets.stripe_secret_key ?? ''; + const secretKey = stripeSecret(ctx.secrets, 'stripe_secret_key'); if (secretKey === '') { return refused( 'Set the Stripe secret key first: the refund is made at Stripe.', diff --git a/src/plugins/shop/lib/scheduled.ts b/src/plugins/shop/lib/scheduled.ts index ebbed89..de34ca6 100644 --- a/src/plugins/shop/lib/scheduled.ts +++ b/src/plugins/shop/lib/scheduled.ts @@ -26,6 +26,7 @@ import { setStateStatement, } from './state.js'; import { closeCheckoutSession } from './stripe-client.js'; +import { stripeSecret } from './stripe-secrets.js'; /** * How often the rates are fetched. The ECB publishes once per working day, so @@ -215,7 +216,7 @@ export async function runScheduledTick( now.toISOString(), now, ).run(); - const key = ctx.secrets?.stripe_secret_key ?? ''; + const key = stripeSecret(ctx.secrets, 'stripe_secret_key'); const cancelled = await closeLapsedOrders( db, now, diff --git a/src/plugins/shop/lib/stripe-check.ts b/src/plugins/shop/lib/stripe-check.ts index 974e95c..5a8f35f 100644 --- a/src/plugins/shop/lib/stripe-check.ts +++ b/src/plugins/shop/lib/stripe-check.ts @@ -9,12 +9,13 @@ import type { PluginContext, PluginSecretVerdict } from 'mallok/worker'; import { STRIPE_API_VERSION } from './stripe-client.js'; +import { stripeSecret } from './stripe-secrets.js'; export async function checkStripeSecretKey( ctx: Pick, fetchImpl: typeof fetch = fetch, ): Promise { - const key = ctx.secrets.stripe_secret_key ?? ''; + const key = stripeSecret(ctx.secrets, 'stripe_secret_key'); if (key === '') { return { ok: false, message: 'Not set.' }; } @@ -60,7 +61,7 @@ export async function checkStripeSecretKey( export async function checkStripeWebhookSecret( ctx: Pick, ): Promise { - const secret = ctx.secrets.stripe_webhook_secret ?? ''; + const secret = stripeSecret(ctx.secrets, 'stripe_webhook_secret'); if (secret === '') { return { ok: false, message: 'Not set.' }; } diff --git a/src/plugins/shop/lib/stripe-secrets.ts b/src/plugins/shop/lib/stripe-secrets.ts new file mode 100644 index 0000000..2505b73 --- /dev/null +++ b/src/plugins/shop/lib/stripe-secrets.ts @@ -0,0 +1,21 @@ +/** + * The two Stripe secrets, as the shop reads them from Mallok's store. + * + * Mallok keeps a secret exactly as it was pasted, white space and all. Copied + * from the line `stripe listen` prints, a signing secret came with the space + * before it, and every delivery failed its signature from then on, with + * nothing in the admin to say why (found in the first purchase in Stripe's + * test mode, 2026-11-03). Neither secret can contain white space, so what is + * around one is not part of it. Every reading goes through here: one that did + * not would take a key the others accept, or refuse one they take. + */ + +export type StripeSecretName = 'stripe_secret_key' | 'stripe_webhook_secret'; + +/** The secret as Stripe issued it, or '' when it is not set. */ +export function stripeSecret( + secrets: Readonly> | undefined, + name: StripeSecretName, +): string { + return (secrets?.[name] ?? '').trim(); +} diff --git a/src/plugins/shop/routes/stripe-webhook.ts b/src/plugins/shop/routes/stripe-webhook.ts index 6f53328..e920bb3 100644 --- a/src/plugins/shop/routes/stripe-webhook.ts +++ b/src/plugins/shop/routes/stripe-webhook.ts @@ -18,13 +18,14 @@ import type { PluginRequestContext, RouteInput } from 'mallok/worker'; import { FOLLOW_UP_JOB } from '../lib/order-follow-up.js'; +import { stripeSecret } from '../lib/stripe-secrets.js'; import { handleStripeWebhook } from '../lib/stripe-webhook.js'; export async function stripeWebhook( _input: RouteInput, ctx: PluginRequestContext, ): Promise { - const secret = ctx.secrets.stripe_webhook_secret ?? ''; + const secret = stripeSecret(ctx.secrets, 'stripe_webhook_secret'); if (secret === '') { console.log( JSON.stringify({ event: 'shop_stripe_webhook', kind: 'no_secret' }), diff --git a/test/shop/checkout.test.ts b/test/shop/checkout.test.ts index d04dc9b..b80db5c 100644 --- a/test/shop/checkout.test.ts +++ b/test/shop/checkout.test.ts @@ -1,3 +1,4 @@ +/// import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; import type { CartFacts } from '../../src/plugins/shop/lib/cart-pricing.js'; import { @@ -207,6 +208,40 @@ describe('the settings checkout reads', () => { ).toEqual({ secretKey: 'sk_test_1', webhookSecret: 'whsec_1' }); }); + it('reads a key without the white space it was pasted with', () => { + // Copied from the line `stripe listen` prints, a signing secret comes + // with the space before it; from a web page, often a line break after. + expect( + stripeKeys({ + stripe_secret_key: ' sk_test_1\n', + stripe_webhook_secret: ' whsec_1', + }), + ).toEqual({ secretKey: 'sk_test_1', webhookSecret: 'whsec_1' }); + expect( + stripeKeys({ + stripe_secret_key: 'sk_test_1', + stripe_webhook_secret: ' ', + }), + ).toBeNull(); + }); + + it('reads the Stripe secrets in one place, so that no reading keeps the white space', () => { + const sources = import.meta.glob('../../src/plugins/shop/**/*.ts', { + eager: true, + import: 'default', + query: '?raw', + }); + const reading = /secrets\??\.\s*stripe_|secrets\??\.\[\s*['"]stripe_/; + + const elsewhere = Object.entries(sources) + .filter(([path]) => !path.endsWith('/lib/stripe-secrets.ts')) + .filter(([, text]) => reading.test(text)) + .map(([path]) => path); + + expect(Object.keys(sources).length).toBeGreaterThan(20); + expect(elsewhere).toEqual([]); + }); + it('charges no tax unless told Stripe is to', () => { expect(taxModeOf({})).toBe('none'); expect(taxModeOf({ tax_mode: 'stripe' })).toBe('stripe'); @@ -434,4 +469,32 @@ describe('the Stripe keys’ checks', () => { ).ok, ).toBe(false); }); + + it('checks each secret as the shop will use it, without the white space around it', async () => { + let authorization = ''; + const recording = (async ( + _input: RequestInfo | URL, + init?: RequestInit, + ) => { + authorization = new Headers(init?.headers).get('authorization') ?? ''; + return new Response('{}', { status: 200 }); + }) as unknown as typeof fetch; + + expect( + ( + await checkStripeSecretKey( + { secrets: { stripe_secret_key: ' sk_test_abc\n' } }, + recording, + ) + ).ok, + ).toBe(true); + expect(authorization).toBe('Bearer sk_test_abc'); + expect( + ( + await checkStripeWebhookSecret({ + secrets: { stripe_webhook_secret: ' whsec_abc' }, + }) + ).ok, + ).toBe(true); + }); }); diff --git a/test/shop/order-page.test.ts b/test/shop/order-page.test.ts index 0dce681..fd7451a 100644 --- a/test/shop/order-page.test.ts +++ b/test/shop/order-page.test.ts @@ -243,6 +243,28 @@ describe('a payment, from Stripe’s delivery to the buyer’s inbox', () => { expect(row?.status).toBe('pending'); }); + it('takes payments with secrets saved with the white space they were pasted with', async () => { + // The first purchase in Stripe's test mode failed here: the signing + // secret was saved with the space before it on the line `stripe listen` + // prints, and every delivery was refused as signed with another secret. + await setShopSecrets({ + stripe_secret_key: ' sk_test_order_page\n', + stripe_webhook_secret: ` ${WEBHOOK_SECRET}`, + }); + const order = await placedOrder(); + + const response = await deliverPayment(order.id, 103_900); + + const session = stripe?.calls.findLast( + (call) => call.path === '/v1/checkout/sessions', + ); + expect(session?.headers.get('authorization')).toBe( + 'Bearer sk_test_order_page', + ); + expect(response.status).toBe(200); + expect(await stockOf('hb-m8')).toBe(900); + }); + it('refuses a delivery signed with another secret', async () => { const order = await placedOrder(); From 74a0e6491f6c7b7ddfe4fb029861fcc1c4719296 Mon Sep 17 00:00:00 2001 From: JasonYv Date: Tue, 3 Nov 2026 20:05:56 +0800 Subject: [PATCH 2/2] docs: record the first purchase in Stripe's test mode and what it found Phase 2's last exit criterion, run against a local site on the owner's sandbox: paid, delivered twice, refunded, expired and cancelled. The README, its translation and SECURITY.md no longer say it has not been run, and say what is still untried at Stripe and how to recover an event stripe listen missed. --- CLAUDE.md | 2 +- README.md | 8 ++-- README.zh-CN.md | 8 ++-- SECURITY.md | 8 ++-- .../2026-09-30-nundar-on-mallok-design.md | 43 ++++++++++++++++++- 5 files changed, 55 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 56e2bb7..f7041a1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -70,7 +70,7 @@ Mallok decides the contracts on both sides. Its documentation is the reference: - **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. -- **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. +- **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. Every reading of a Stripe secret goes through `stripeSecret` (`lib/stripe-secrets.ts`), which drops the white space it was pasted with — Mallok keeps a secret as typed, and a signing secret saved with a space before it refused every delivery (design §22); `test/shop/checkout.test.ts` fails when another file reads one. - **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. diff --git a/README.md b/README.md index 6addb3a..5b95830 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, 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. +> **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 has been run end to end in Stripe's test mode against a local site, and nothing has been deployed — see [What works today](#what-works-today). It is not ready to run a real shop. --- @@ -65,7 +65,7 @@ Nundar builds on `mallok@0.1.0-rc.11`, the first release with the plugin API the | **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) | | **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 | +| **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 | Not yet tried at Stripe: Stripe Tax, Apple Pay and Google Pay, a card that asks for authentication, an order in EUR or GBP; 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 | | @@ -174,7 +174,7 @@ The shop takes payments through Stripe's hosted checkout, on your own Stripe acc 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. +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. The listener's login lapses after a while: it may reconnect and stop forwarding, or stop with an expired OAuth token, and what Stripe sent meanwhile does not reach the shop — start it again and deliver a missed event with `stripe events resend `. ## Commands @@ -192,7 +192,7 @@ To try it on a local site (`npm run dev`), Stripe's command-line tool can forwar ## Deploying -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. +Not yet. A purchase has been run end to end in Stripe's test mode against a local site — paid, delivered twice, refunded, and orders expired and cancelled (design §22) — but nothing here has been deployed or measured on a real Cloudflare account. 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 e5421e7..03efbde 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@ **[Mallok](https://github.com/fobstack/mallok) 的商城插件和商城主题。** 为想靠买家真实搜索词获得流量的跨境卖家而做,不去和所有人争抢同一个大词。 -> **状态:开发中。** Nundar 正在 Mallok 上重建。目录、购物车、询价、通过 Stripe 结账、卖家的订单/客户/销售视图,以及第二套主题,在本地都能用;还没有在 Stripe 上完整跑通过一笔购买,也还没有部署过,见[现在能用什么](#现在能用什么)。目前还不能用来经营真实店铺。 +> **状态:开发中。** Nundar 正在 Mallok 上重建。目录、购物车、询价、通过 Stripe 结账、卖家的订单/客户/销售视图,以及第二套主题,在本地都能用;已经在本地站点上用 Stripe 测试模式完整跑通过一笔购买,但还没有部署过,见[现在能用什么](#现在能用什么)。目前还不能用来经营真实店铺。 --- @@ -64,7 +64,7 @@ Nundar 基于 `mallok@0.1.0-rc.11`,这是第一个带有商城其余部分所 | **询盘** | 在购物车页填一张表单(回复给谁、留言),把整个购物车作为一张询价单发出。没有价格的尺寸也可以加入购物车来询价。买家提交后看到询盘编号;卖家收到一封邮件,直接回复即可回到买家,并在后台看到每张询盘及其明细,可以标记、导出 CSV 或删除 | 表单前面的人机验证(等 Mallok 提供),因此给买家的确认邮件默认关闭,需要手动开启 | | **带走你的数据** | 商城持有的数据都在站点导出(`mallok export`)里,和内容放在一起:规格、价格、库存台账、订单、付款事件、询盘和商城自己的设置,各为 `shop/` 下的一个 JSON 文件,按存储原样导出 | 把这些文件再导入;单次请求装不下的大表的导出(两者都要等 Mallok) | | **运费** | 在后台设置区域:每个区域包含哪些国家、每种币种的固定运费,以及货款达到多少免运费。不在任何区域里的国家,结账时不会出现 | 按重量计费 | -| **结账与付款** | 结账页沿用站点自己的设计和语言,不需要脚本:选择订单寄往的国家,看到该国的运费和总价,填写买家的公司和地址,然后到 Stripe 托管的页面付款——银行卡或 Link,按商城自己的标价,关闭 Stripe 的货币换算。默认不收税,商城可开启 Stripe Tax。订单有自己的页面,通过签名链接打开;Stripe 付款后带买家回到这个链接,每封邮件也都附带它。无论 Stripe 通知多少次,一笔付款只扣一次库存;付款金额要和订单总额对得上;付款后从购物车里移除已下单的商品;未付款的订单在付款页失效一小时后取消 | 还没有在 Stripe 测试模式下实际跑通一笔购买(需要商城自己的测试密钥);买家账户;商城自己的发票;部分退款 | +| **结账与付款** | 结账页沿用站点自己的设计和语言,不需要脚本:选择订单寄往的国家,看到该国的运费和总价,填写买家的公司和地址,然后到 Stripe 托管的页面付款——银行卡或 Link,按商城自己的标价,关闭 Stripe 的货币换算。默认不收税,商城可开启 Stripe Tax。订单有自己的页面,通过签名链接打开;Stripe 付款后带买家回到这个链接,每封邮件也都附带它。无论 Stripe 通知多少次,一笔付款只扣一次库存;付款金额要和订单总额对得上;付款后从购物车里移除已下单的商品;未付款的订单在付款页失效一小时后取消 | 还没有在 Stripe 上试过:Stripe Tax、Apple Pay 和 Google Pay、需要身份验证的银行卡、以 EUR 或 GBP 计价的订单;买家账户;商城自己的发票;部分退款 | | **后台订单处理** | 每张订单连同明细、地址和金额:标记已发货(运单号和承运商)、已送达,取消未付款的订单,全额退款——先在 Stripe 退款再记账,货未发出时默认退回库存;对付款时库存已售完的订单,补货后照常履约。商城无法收下的付款单独列出,供退款。订单确认、发货、退款或被卖家取消时,用买家的语言写信通知;每张新订单和每笔待退款都通知卖家 | | | **客户与销售** | 每个下过单或发过询价的邮箱地址,下面列出它的订单和询盘,以及在各币种下的消费额;按月统计的销售——已收款、已退款、净额和平均订单额——以及按商品统计,均分币种 | | | **找回订单** | 不用注册账户:买家输入下单用的邮箱,会收到一封邮件,里面的链接在一天内可以查看用这个邮箱付过款的全部订单。无论有没有订单,页面上的回答都一样;每个访客、每个邮箱的请求次数都有限制 | | @@ -173,7 +173,7 @@ npm run seed:local 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 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 的测试卡付款。这个监听程序的登录过一段时间会失效:它可能自动重连后不再转发,也可能以 OAuth 令牌过期报错退出,期间 Stripe 发出的事件不会到达商城——重新启动它,再用 `stripe events resend <事件 id>` 重发漏掉的事件。 ## 常用命令 @@ -191,7 +191,7 @@ npm run seed:local ## 部署 -暂时不要部署。商城现在可以收款了,但在有人依赖它之前,还要先在真实的 Stripe 账号上用测试模式完整跑通一笔购买;并且这里的一切都还没有在真实的 Cloudflare 账号上实测过。等 Nundar 就绪后,部署走 Mallok 自己的流程:`npx mallok create . --slug `,它会在你自己的 Cloudflare 账号上创建 Worker、D1 数据库和 R2 存储桶,之后 Mallok 的首次运行向导会提供这套示例商城作为起点。这条路径还没有在本仓库上跑过。 +暂时不要部署。已经在本地站点上用 Stripe 测试模式完整跑通过一笔购买——付款、重复送达、退款,以及订单过期和被取消(设计文档 §22)——但这里的一切都还没有部署过,也没有在真实的 Cloudflare 账号上实测过。等 Nundar 就绪后,部署走 Mallok 自己的流程:`npx mallok create . --slug `,它会在你自己的 Cloudflare 账号上创建 Worker、D1 数据库和 R2 存储桶,之后 Mallok 的首次运行向导会提供这套示例商城作为起点。这条路径还没有在本仓库上跑过。 ## 语言和币种 diff --git a/SECURITY.md b/SECURITY.md index 54885c2..82ec774 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -390,9 +390,11 @@ Stated plainly rather than left for an auditor to find: 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. +- **A purchase has been run end to end in Stripe's test mode only on a local + site** (design §22): paid, delivered twice, refunded, expired and cancelled. + Stripe Tax, wallets, a card that asks for authentication and a deployed + site's webhook endpoint have not been tried at Stripe; the tests run against + a stand-in for Stripe's API built from its documentation. ## Dependency posture 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 ad15169..b812f29 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 @@ -309,7 +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). +- *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 was run on 2026-11-03 against a local site (§22), and the quotas wait 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; @@ -816,7 +816,7 @@ And the ones the sheet did not ask about: the Stripe API version is pinned (`202 **Left open.** -1. *A Stripe test-mode purchase, end to end*, on the owner's keys: phase 2's last exit criterion. +1. *A Stripe test-mode purchase, end to end*, on the owner's keys: phase 2's last exit criterion. Run on 2026-11-03 against a local site (§22). 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. @@ -889,3 +889,42 @@ And one the security reviewer raised that is kept, and written in `SECURITY.md`: **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. + +## 22. What the first purchase in Stripe's test mode found (2026-11-03) + +Phase 2's last exit criterion, run on the owner's Stripe sandbox. The shop was `npm run preview`, a local Worker; Stripe's events reached it through `stripe listen --latest` (Stripe CLI 1.55.3). The code is pinned to `2026-10-28.endive`, which Stripe's changelog listed that day as its latest version, so the events the listener sent were in the shape the webhook reads. Four orders, all for 50 of TI-HEX-M8-30 shipped to the United States: $240.00 and $35.00 shipping. + +1. *Paid.* + - Read back through Stripe's API, the Checkout session matched the order: test mode, $275.00 in USD, the one line at its snapshot price, one shipping option named after the zone, card and Link only, adaptive pricing off, the order's id in its metadata, and the expiry the order recorded. + - Paid on Stripe's page with a test card. `payment_intent.succeeded` was delivered and answered 200. The order became paid; stock went from 3,000 to 2,950 with one ledger row; the cart was emptied; an `order.paid` row and a follow-up job were written. + - The same event delivered again (`stripe events resend`) was answered 200 and took nothing. +2. *Refunded* in full from the admin's orders panel, back to stock. Stripe's refund of $275.00 succeeded first; then the order read `refunded`, stock went back to 3,000 with its ledger row, and an `order.refunded` row was written. +3. *Expired*, twice: two orders whose payment pages lapsed unpaid. Stripe's `checkout.session.expired` cancelled each (`expired`). Stock was not touched, and no email was owed to the buyer. +4. *Cancelled from the admin* while unpaid. The session was closed at Stripe first (Stripe then reported it `expired`), and only then was the order cancelled (`seller`). Stripe's expiry event that followed was answered 200 and changed nothing. The cart kept its line. + +Two ticks of Mallok's scheduled handler, run by hand on the local Worker (`/cdn-cgi/handler/scheduled`), carried out the follow-ups: the buyer's confirmation, refund and cancellation were handed to Mallok, and nothing was sent for the two expiries. Mallok's email jobs then failed for want of an email provider, which a local site does not have. + +**What it found.** + +1. *A secret saved with white space around it refused every delivery.* + - The signing secret had been saved with the space before it on the line `stripe listen` prints, and Mallok keeps a secret exactly as pasted. Every delivery was answered 400, as signed with another secret, and nothing in the admin said why. A shop running like that confirms no payment. + - Seen by signing a request with the listener's secret, which was refused, and again with a space before it, which was taken. + - The fix: neither secret can contain white space, so every reading now goes through `lib/stripe-secrets.ts`, which trims it, and a test fails when any other file reads one. + - Its three tests went red with the trim taken away, and the one-place test went red with one raw reading put back. + - Mallok's side is M48. +2. *`stripe listen` stops forwarding once its login lapses.* + - Twice the listener reconnected on its own, forwarded nothing Stripe sent after that, and some time later stopped with "expired OAuth token". Neither expiry was forwarded when it happened. + - This is Stripe's command-line tool, not the shop. A missed event is delivered again with `stripe events resend `, which is how both expiries reached the shop. The README now says so. + +**Not verified.** + +- Not tried at Stripe: + - Stripe Tax, which needs registrations; + - Apple Pay and Google Pay; + - a card that fails or asks for authentication; + - an order in EUR or GBP; + - an endpoint created in Stripe's dashboard rather than the CLI's forwarding. +- Not looked at here: + - Stripe's hosted page, which the owner paid on in their own browser; + - the order page Stripe returned them to. +- No site was deployed and no email was delivered.