domma-cms 1.47.5 → 1.47.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.47.6] - 2026-11-08
4
+
5
+ - **Plugins: `options.auth.authenticateSelf`**, core's sign-in check without the plugin admin-scope rule, for plugin routes that act only on the caller's own record (a shop customer's account or reorder). A confined role such as `shop-customer` got 403 "Your account cannot use <plugin>" there. It keeps every token rule: an access token is required and a refresh token is refused. Plugin `authenticate` is unchanged. See "authenticateSelf" in docs/plugin-development.md - never use it for admin APIs or other users' data.
6
+
3
7
  ## [1.47.5] - 2026-11-08
4
8
 
5
9
  - **Security: the site's own records are never written through the public collections API.** `roles`, `user-profiles`, API tokens, projects and the other built-in collections refuse create, update and delete on `/api/v1/:slug` and `/api/collections/:slug/public` whatever their API settings say - with `roles` create set to public, an anonymous request could make a top-level role. Admins change them in the admin as before; the Tools' notes, tasks and contacts (each user's own rows) are unchanged.
package/CLAUDE.md CHANGED
@@ -175,6 +175,10 @@ Seeded on first run with: `super-admin` (0), `admin` (1), `user` (2); admins add
175
175
  browser as `adminScope` on `/api/auth/permissions`; `admin/js/lib/admin-scope.js` decides per route and
176
176
  `app.js` applies it in three places (router guard, after login, before `R.init()`). Core must not name a
177
177
  plugin's roles - the job-board `JB_ROLES` list that used to live in app.js is what this replaced.
178
+ - **Plugin API scope.** The `authenticate` a plugin gets (`pluginScope.js` `authenticateFor`) also refuses a confined
179
+ user unless one of the plugin's screens is in their scope. `auth.authenticateSelf` is core's check alone (same token
180
+ rules), for routes acting only on the caller's own record; the route must check ownership against
181
+ `request.user.id`. Never hand it to admin APIs or routes on other users' data. Both come from `pluginAuthGuards()`.
178
182
  - Role saves go through `keepRoleSystemFields()` in `routes/api/collections.js`: `plugin` and `grantedBy` are
179
183
  pinned to the stored values, because clients send whole records.
180
184
 
@@ -1559,6 +1559,8 @@ Domma CMS is extended by plugins: self-contained folders under `plugins/<slug>/`
1559
1559
  - Since: 0.88.0
1560
1560
  - **Plugin API scope** - A user whose roles confine them to some admin screens (`role.admin.allow`) can call a plugin's authenticated routes only if one of that plugin's screens is in their scope; others get 403 "Your account cannot use <plugin>".
1561
1561
  - Where: `server/services/pluginScope.js` · Since: 0.86.0
1562
+ - **`auth.authenticateSelf`** - Core's sign-in check (access token required, refresh token refused) without the admin-scope rule, for plugin routes that act only on the caller's own record (`request.user.id`), such as a shop customer's account or reorder. Never for admin APIs or other users' data; the route checks ownership itself.
1563
+ - Where: `pluginAuthGuards()` in `server/services/pluginScope.js` · Since: unreleased
1562
1564
  - **Static files** - Only `plugins/<slug>/admin/**` and `plugins/<slug>/public/**` are served (at `/plugins/<slug>/...`); `plugin.js`, `config.js`, `data/` are never reachable.
1563
1565
  - **Cache-busting** - Admin view entries and `admin.css` are stamped with the newest mtime of the plugin's `admin/` tree and `_lib/admin`, so an update reaches the browser without a hard refresh.
1564
1566
 
@@ -181,7 +181,8 @@ The `options` object exposes the following auth middleware helpers:
181
181
 
182
182
  | Helper | Description |
183
183
  |---|---|
184
- | `authenticate` | Verifies the JWT Bearer token; rejects with `401` if missing or invalid |
184
+ | `authenticate` | Verifies the JWT Bearer token; rejects with `401` if missing or invalid. A user whose roles confine them to some admin screens (`role.admin.allow`) also gets `403` unless one of this plugin's screens is in their scope |
185
+ | `authenticateSelf` | The same token check as `authenticate` (an access token is required, refresh tokens are refused, `401` otherwise) **without** the admin-scope rule. Only for routes that act on nothing but the caller's own record - see below |
185
186
  | `requireAdmin` | Requires the authenticated user to have admin role level (level 0 or 1) |
186
187
  | `requirePermission(resource, action?)` | Requires a role holding `resource` (or `resource.action`) - use this with your own resources, see below |
187
188
  | `requireRole(roles)` | Requires one of the named roles as the PRIMARY role - prefer `requirePermission`, which the admin can re-assign |
@@ -189,6 +190,31 @@ The `options` object exposes the following auth middleware helpers:
189
190
 
190
191
  All routes registered inside `plugin.js` are automatically prefixed with `/api/plugins/<name>/`.
191
192
 
193
+ #### `authenticateSelf` - routes on the caller's own record
194
+
195
+ A signed-in visitor whose role is confined to a few admin screens - a shop customer, a job seeker - gets `403 "Your
196
+ account cannot use <plugin>"` from `authenticate` on every plugin whose screens they cannot open. That is right for
197
+ the plugin's admin API, and wrong for a route that serves the visitor themselves: their account page, their orders,
198
+ a reorder. Those routes use `authenticateSelf`:
199
+
200
+ ```js
201
+ const {authenticate, authenticateSelf} = options.auth;
202
+ // Engines before authenticateSelf: fall back to authenticate (confined roles then get 403, as before).
203
+ const selfAuth = authenticateSelf || authenticate;
204
+
205
+ fastify.post('/public/reorder/:id', {preHandler: [selfAuth]}, async (request, reply) => {
206
+ const order = await findOrder(request.params.id);
207
+ if (!order || order.customerId !== request.user.id) return reply.code(404).send({error: 'Not found'});
208
+ // ...act on this order only
209
+ });
210
+ ```
211
+
212
+ > **Warning.** `authenticateSelf` says only *who* the caller is - any signed-in account passes it, whatever its role.
213
+ > Use it only on a route that reads or writes nothing but the caller's own data, and check ownership against
214
+ > `request.user.id` (or the email on the caller's user record) in the handler, answering as if the record did not
215
+ > exist when it is someone else's. Never use it for an admin API, a listing of other people's records, settings, or
216
+ > anything another user owns; those use `authenticate` with `requirePermission`.
217
+
192
218
  ---
193
219
 
194
220
  ## Roles & Permissions
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.47.5",
3
+ "version": "1.47.6",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "note": "Written by `make sync-free-tier` in dcms-marketplace. Do not edit these plugins here - edit them there and sync.",
3
- "source": "dcms-marketplace@2611cf2",
3
+ "source": "dcms-marketplace@2c732ad",
4
4
  "plugins": {
5
5
  "blog": {
6
6
  "version": "1.10.3",
@@ -234,10 +234,10 @@
234
234
  }
235
235
  },
236
236
  "shopping-cart": {
237
- "version": "1.7.4",
237
+ "version": "1.7.5",
238
238
  "files": {
239
- "CHANGELOG.md": "0dd30ec7fde5f4b1c5a5743852d925eb849f764e7de8971b3fc2e2e34b948983",
240
- "CLAUDE.md": "9e62730419a01b05e70559fea238b8334a6f46ebed27a5943d7b477abfcce9a1",
239
+ "CHANGELOG.md": "ab9b67778aa31e08b84fef455ecac5ce9665c12b032a735a0a029ebc4b967547",
240
+ "CLAUDE.md": "5d44664c00ab20f38f6f02559214bdd17082e46c0cc9b20f3847f2da8d85297d",
241
241
  "admin/css/index.css": "cdd7790511deef162ad30e299b4512d289583e978ba3b87d65945cdf1da3cdda",
242
242
  "admin/lib/chart.js": "b01ce5cfac773c8df8efccab50b67d3dfa99fbead0037d817553db4a6688d4d6",
243
243
  "admin/lib/drafts.js": "9e71b939f6c98d5c25875f35b02c367a5e89e0d2c6d084d6a4de0c71128930a2",
@@ -261,18 +261,18 @@
261
261
  "lib/payments.js": "d2a39bf42373c78c716c1a35f606f9cce1901d0dab5f6bd00bebde9b35f0328c",
262
262
  "lib/pricing.js": "5644f2dd55fc3cfd7f40b0169dea5fb547e8b302239b8c17f23cfa177e42eab5",
263
263
  "lib/refunds.js": "73db567d97d40f68806c0d8dcb7235a12f5f86662739febf4b2229695ace40e4",
264
- "lib/render.js": "2a2b9ab4a24728186e1e45e6429c7406a6d5ca3d4b43db1758bbd54405d105b7",
264
+ "lib/render.js": "1255422fc4acfbc323dc38bc90106e5ca3ee250d24f2879891a4c3206ca4faa0",
265
265
  "lib/sales.js": "bc6c39d70c2ce83f4109474071e6b048dc6554c4b11ac03dbeccbdfdb5881368",
266
266
  "lib/samples.js": "912b3d5bd543dffa5f870caf3c2b873f642fd55e3ebf3f97e1b31eeaaac77d3b",
267
267
  "lib/shop.js": "baa5dfc4e410210e8ba13678997ee5752eb2ebe72fc4d3e449465d29b60b458d",
268
268
  "lib/summary.js": "ff947ccf0f63cc3095946612460f3ea7ff742803395802179b3ccd66fe961dfa",
269
- "plugin.js": "650025fefd7426ffc8334807c3e88c6496067350479e2551efcf61d53c74b630",
270
- "plugin.json": "ed9dd04c57e12d722fe6ea0d8642c9ea2c07b785b0ac6a18ca64f6408893fbcb",
269
+ "plugin.js": "9fe8439e66d605d466db7fb619cf42254498c4feaaa879256f5de89c7da792a3",
270
+ "plugin.json": "3db09fce4a902981c0641084457075b3d5deafe41315ae2d4690a56f29a072dd",
271
271
  "plugin.public.js": "d4304e85895f7e8e2397e64cc7a8e118e94b65c2f271369f880d92e7d32f83f8",
272
272
  "public/account.js": "5f644016c098c7879c59948d662f5997cb61680996204ecb7897baab8945d434",
273
- "public/cart.js": "7338141392ec653ff616eb75688d2a2ad08cff8427d7020d381f540be0037b73",
273
+ "public/cart.js": "01492eb04b13bd347dc7721fb002644b499dadee1777a9b67e5d0fe9a1ad6698",
274
274
  "public/lib/money.js": "d22b2b6f80dde6f7887b69e24188c05ea93c02217aba639b5331aa3bd616f4fc",
275
- "public/lib/orders.js": "e18d054bf385e9c15544628c81ad7746179eea74c33dbcce42dd2525f3fa210e",
275
+ "public/lib/orders.js": "fab6c3ae3cdb35f37d338bfd9ce921ac98629dedb8249e814804309865e06c64",
276
276
  "public/lib/products.js": "ace3b66b3a5033c061c01bef86c8529ba91449bcb47f7be4fbada072a9c63e1e",
277
277
  "public/lib/session.js": "4f71e98818a52cf2321c8dc57e33e5591deb04ebb2c0bea19dd6758827719a08",
278
278
  "public/samples/candle-2.svg": "aca5691b9168467caf6feb7622ab154ee92504be8b887ac6c818db22476e7bed",
@@ -287,11 +287,13 @@
287
287
  "public/samples/tee.svg": "287a82d7fc00acb1543b3209927ae20dcbe3d4b2a2b3de03574ab0c463385f3c",
288
288
  "public/samples/tote-2.svg": "9c7f41cc57866e71973e413a6c87f46be48f7488d3490ceea58e24559c334813",
289
289
  "public/samples/tote.svg": "01de817a32c8d3d8ea47ff491049f439ca3e4d4fce943dbdc62a4187139e016c",
290
- "public/shop.css": "ac42d386b014556e175b12164cf4ff2fbdcf7b273c32ed7f55da7cc1f43c103b",
290
+ "public/shop.css": "2c26ec5f3421951ab89b9d356e8fb1613b45f4cee8fee0ac57f17ef011ef112f",
291
291
  "roles/shop-customer.json": "3f3366c536c9fbf2b2ce146bb3090b008d5fbfe22752e764eb8e5a1de9cd611c",
292
292
  "templates/shop.html": "4649e57d23458833a157799dc80141824eb0f658d96734bd1859c68e0ba9a8b9",
293
- "tests/accounts.test.js": "79b0e91e4310d076960b2a768ada02185b6cf05cab83052ee825b13978e0a9dc",
293
+ "tests/account-scope.test.js": "2efe258126fabcc9dabdfb325f776b290a9cfbc04467958ea984bd4bcb7fcd4d",
294
+ "tests/accounts.test.js": "3319229600101802b4cb7d4f47b288e0a1f93fa441bccb3bffba17e8e17a6871",
294
295
  "tests/api.test.js": "15c71751a3d31171707cbb3119d21b85c1c59fb7a67272b318dd4655809ac8d2",
296
+ "tests/checkout-wording.test.js": "c5ec247353af5aab30c22b1db3ec90696f7fa011516cae44a36fa5b54260466e",
295
297
  "tests/commission.test.js": "fbc4cf83e0ed6446a09e57e4ff37a9608c81947c633c78ac6049eb0aedf6cb58",
296
298
  "tests/drafts.test.js": "2dec0cfeadd6df1d3b90f3fd8bce1f33762811eb6e94cd7325bcb8ec31edac42",
297
299
  "tests/email.test.js": "2190b6dd7cc9afad99d2170f002343fe3dad306aa14ac718428e5df0be54ded1",
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.7.5] - 2026-11-08
4
+ - Customer accounts work again: a signed-in customer at `<shop>/account` saw the sign-in form come back, because `GET /account` answered 403 "Your account cannot use Shopping Cart". Core's plugin scope (CMS 0.86.0+) refuses the plugin's signed-in routes to a role confined to other admin screens, and `shop-customer` is confined to My Profile - so accounts never worked on any CMS that shipped them (1.6.35 to 1.47.2). The three `/account` routes now take core's own sign-in check (`accountAuth`, or `auth.authenticateSelf` when the CMS passes one); every admin route keeps the scoped one, so a customer is still refused the Shop's admin APIs (`tests/account-scope.test.js`, against the real sign-in and scope).
5
+ - Checkout's button and the line under it follow the payment method picked: Pay offline says "Place order" and shows the shop's offline instructions, not "Pay £…" and the card-page line; PayPal says "Pay £… with PayPal"; card keeps "Pay £…" (`payWording` in public/lib/orders.js).
6
+ - The product page keeps the shop's own capitals in the collection label ("or collect from our Leeds workshop", not "our leeds workshop"); only a leading capital is lowered (`collectPhrase`).
7
+ - "Keep shopping" and "Sign in for faster checkout" at the top of checkout are kept apart by a dot.
8
+
3
9
  ## [1.7.4] - 2026-11-08
4
10
  - The product list counts options without pluralising their name: "Units: 2 options", not "2 unitss" (`optionsText` in public/lib/products.js).
5
11
  - The receipt's Download buttons (and [buy-button] links) are readable on every theme: their text is the theme's own on-primary colour (`--dm-primary-text`), and the site's content-link colour no longer paints over it (it made them primary text on a primary button).
@@ -172,7 +172,13 @@ these, behaves as 1.1.
172
172
  replaced. A confirmation email that fails removes the account again (502). Needs SMTP (`mailReady`).
173
173
  - Signing in, refresh, logout and the new password are CORE's routes (`/api/auth/login|refresh|logout|reset-password`);
174
174
  the Cart issues core's reset token (`issueResetToken`) and mails a link to `<shop>/account/reset`, never /admin.
175
- Tokens live in localStorage `dm-shop:account`; account routes take core's Bearer (`authenticate`).
175
+ Tokens live in localStorage `dm-shop:account`; account routes take core's Bearer through `accountAuth` (below).
176
+ - **`/account` routes use `accountAuth`, never the `authenticate` the plugin is handed.** That one is wrapped by core's
177
+ `pluginScope.js` and refuses anyone whose role confines them to admin screens outside this plugin - `shop-customer` is
178
+ confined to My Profile, so 1.4.0-1.7.4 answered every customer 403 "Your account cannot use Shopping Cart" (the tests
179
+ mocked authenticate and never saw it). `accountAuth` = `auth.authenticateSelf` if core ever passes one, else core's own
180
+ `middleware/auth.js authenticate` (same token check, no admin-screen rule). Only routes that act on `request.user.id`'s
181
+ own record may use it; admin routes stay on `can()`. `tests/account-scope.test.js` runs the real wrapper.
176
182
  - An account's orders = orders with its (confirmed) email, any time - nothing linked. `meta.shop` keeps phone and up
177
183
  to 8 addresses. Delete my account: customers only (staff 409), with the password; orders stay.
178
184
  - Checkout fills in a signed-in customer (details + first saved address); the receipt offers "Save your details"
@@ -170,7 +170,7 @@ export function productHtml({entry, settings, base, descriptionHtml, related}) {
170
170
  <p class="shop-stock" data-shop-stock>${soldOut ? '' : left !== Infinity && settings.showStockLeft && left <= (Number(settings.lowStockAt) || 0) ? `Only ${left} left` : ''}</p>
171
171
  </form>
172
172
  <ul class="shop-assure">
173
- ${p.shippable !== false ? `<li>${ICON.truck}<span>${Number(settings.freeShippingOver) > 0 ? `Free delivery over ${esc(formatMoney(settings.freeShippingOver, cur, {compact: true}))}` : esc(settings.shippingLabel || 'Delivery')}${settings.allowCollection ? ` · or ${esc(String(settings.collectionLabel || 'collect').toLowerCase())}` : ''}</span></li>` : `<li>${ICON.check}<span>Nothing to ship - yours as soon as it is paid</span></li>`}
173
+ ${p.shippable !== false ? `<li>${ICON.truck}<span>${Number(settings.freeShippingOver) > 0 ? `Free delivery over ${esc(formatMoney(settings.freeShippingOver, cur, {compact: true}))}` : esc(settings.shippingLabel || 'Delivery')}${settings.allowCollection ? ` · or ${esc(collectPhrase(settings.collectionLabel))}` : ''}</span></li>` : `<li>${ICON.check}<span>Nothing to ship - yours as soon as it is paid</span></li>`}
174
174
  <li>${ICON.lock}<span>Secure checkout</span></li>
175
175
  </ul>
176
176
  ${descriptionHtml ? `<div class="shop-description">${descriptionHtml}</div>` : ''}
@@ -179,10 +179,23 @@ export function productHtml({entry, settings, base, descriptionHtml, related}) {
179
179
  ${related.length ? `<section class="shop-related"><h2>You may also like</h2>${gridHtml(related, settings, base, {columns: 4})}</section>` : ''}`;
180
180
  }
181
181
 
182
+ /**
183
+ * The collection label as it reads after "Delivery · or ": the shop's own words and capitals, with only a
184
+ * leading capital lowered when the next letter is lower case ("Collect from our Leeds workshop" -> "collect from
185
+ * our Leeds workshop"); "IKEA Leeds" or "PO Box" keep theirs.
186
+ *
187
+ * @param {string} [label]
188
+ * @returns {string}
189
+ */
190
+ export function collectPhrase(label) {
191
+ const s = String(label || '').trim() || 'collect';
192
+ return /^[A-Z][a-z]/.test(s) ? s[0].toLowerCase() + s.slice(1) : s;
193
+ }
194
+
182
195
  /** The basket and checkout, one page. The script fills it from the basket in the browser. */
183
196
  export function cartHtml({settings, base}) {
184
197
  const countries = (settings.countries || ['GB']).map(c => `<option value="${esc(c)}">${esc(COUNTRIES[c] || c)}</option>`).join('');
185
- return `<nav class="shop-crumbs" aria-label="Breadcrumb"><a href="${esc(base)}">${ICON.back}Keep shopping</a>${settings.accounts ? ` <a class="shop-acc-link" href="${esc(base)}/account" data-acc-link>Sign in for faster checkout</a>` : ''}</nav>
198
+ return `<nav class="shop-crumbs" aria-label="Breadcrumb"><a href="${esc(base)}">${ICON.back}Keep shopping</a>${settings.accounts ? `<span class="shop-crumbs-acc" data-acc-link><span aria-hidden="true">·</span> <a class="shop-acc-link" href="${esc(base)}/account">Sign in for faster checkout</a></span>` : ''}</nav>
186
199
  <h1 class="shop-co-title">Your basket</h1>
187
200
  <div class="shop-checkout" data-shop-checkout>
188
201
  <div class="shop-co-main">
@@ -219,7 +232,7 @@ export function cartHtml({settings, base}) {
219
232
  ${settings.termsUrl ? `<label class="shop-terms"><input type="checkbox" name="terms" required> <span>I agree to the <a href="${esc(settings.termsUrl)}" target="_blank" rel="noopener">terms of sale</a></span></label>` : ''}
220
233
  <p class="shop-co-error" data-co-error role="alert" hidden></p>
221
234
  <button type="submit" class="shop-pay-btn" data-co-pay>${ICON.lock}<span>Pay</span></button>
222
- <p class="shop-secure">${ICON.lock} Payment happens on a secure page run by the payment provider. We never see your card.</p>
235
+ <p class="shop-secure" data-co-note data-offline-note="${esc(settings.offlineInstructions || '')}" hidden><span data-co-lock>${ICON.lock}</span><span data-co-notetext></span></p>
223
236
  </section>
224
237
  </form>
225
238
  </div>
@@ -11,6 +11,9 @@
11
11
  * POST /orders/:id/refund · DELETE /orders/:id
12
12
  * GET /settings · PUT /settings · POST /settings/test/:provider
13
13
  *
14
+ * A signed-in customer's own account (core's sign-in, NOT the admin scope - see accountAuth):
15
+ * GET /account · PUT /account · DELETE /account
16
+ *
14
17
  * Shoppers (no sign-in):
15
18
  * GET /catalogue products on sale
16
19
  * POST /quote the basket priced (the ONE pricing: lib/pricing.js)
@@ -33,6 +36,7 @@ import * as accounts from './lib/accounts.js';
33
36
  import {dateIn, rangeFor, salesCsv, salesReport} from './lib/sales.js';
34
37
  import {TYPES as COMMISSION_TYPES, currentCommission, rateFor, rateText} from './lib/commission.js';
35
38
  import {getUserById} from '../../server/services/users.js';
39
+ import {authenticate as coreAuthenticate} from '../../server/middleware/auth.js';
36
40
  import {cleanCharges, cleanCustomLines, cleanLines, priceBasket} from './lib/pricing.js';
37
41
  import {badge, summarise} from './lib/summary.js';
38
42
  import * as pay from './lib/payments.js';
@@ -164,6 +168,14 @@ function registerShortcodes(hooks) {
164
168
  export default async function shoppingCart(fastify, options) {
165
169
  warn = (msg) => fastify.log.warn(msg);
166
170
  const {authenticate, requirePermission} = options.auth;
171
+ // The /account routes are a shopper's own record, not the Shop's admin. The `authenticate` a plugin is handed
172
+ // (core pluginScope.js) also refuses anyone whose role confines them to admin screens outside this plugin -
173
+ // which is exactly the `shop-customer` role (My Profile only), so every signed-in customer got 403 "Your account
174
+ // cannot use Shopping Cart". These three routes take core's own sign-in check instead (the same token check,
175
+ // without the admin-screen rule) and only ever touch request.user.id's own record. Every other signed-in route
176
+ // keeps the scoped `authenticate`, so a customer still cannot reach the admin APIs. `authenticateSelf` is the
177
+ // name an engine-provided equivalent would have; a test passes its own.
178
+ const accountAuth = options.auth.authenticateSelf || coreAuthenticate;
167
179
  const hooks = options.hooks || {};
168
180
  const can = (action) => ({preHandler: [authenticate, requirePermission('shop', action)]});
169
181
  const registry = cartRegistry();
@@ -577,7 +589,7 @@ export default async function shoppingCart(fastify, options) {
577
589
  });
578
590
 
579
591
  /** The signed-in customer: details, saved addresses and the orders placed with their email. */
580
- fastify.get('/account', {preHandler: [authenticate]}, async (request, reply) => {
592
+ fastify.get('/account', {preHandler: [accountAuth]}, async (request, reply) => {
581
593
  const user = await getUserById(request.user.id);
582
594
  if (!user || !user.isActive) return fail(reply, 401, 'Please sign in again.');
583
595
  const s = await liveSettings();
@@ -591,14 +603,14 @@ export default async function shoppingCart(fastify, options) {
591
603
  return {...accounts.describe(user), orders, accounts: Boolean(s.accounts)};
592
604
  });
593
605
 
594
- fastify.put('/account', {preHandler: [authenticate]}, async (request, reply) => {
606
+ fastify.put('/account', {preHandler: [accountAuth]}, async (request, reply) => {
595
607
  try {
596
608
  const b = request.body || {};
597
609
  return await accounts.updateDetails(request.user.id, {name: b.name, phone: b.phone, addresses: b.addresses});
598
610
  } catch (err) { return accountFail(reply, err); }
599
611
  });
600
612
 
601
- fastify.delete('/account', {preHandler: [authenticate], config: {rateLimit: {max: 5, timeWindow: '10 minutes'}}}, async (request, reply) => {
613
+ fastify.delete('/account', {preHandler: [accountAuth], config: {rateLimit: {max: 5, timeWindow: '10 minutes'}}}, async (request, reply) => {
602
614
  try {
603
615
  await accounts.remove(request.user.id, request.body?.password);
604
616
  return {deleted: true};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "shopping-cart",
3
3
  "displayName": "Shopping Cart",
4
- "version": "1.7.4",
4
+ "version": "1.7.5",
5
5
  "tier": "free",
6
6
  "description": "Sell from your site: products with options, stock and pictures, a storefront and a cart that follows shoppers from page to page, and checkout with Stripe, PayPal or payment offline. Orders to fulfil in the sidebar, refunds from the order.",
7
7
  "author": "Domma CMS",
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  import {formatMoney} from './lib/money.js';
19
+ import {payWording} from './lib/orders.js';
19
20
 
20
21
  const API = '/api/plugins/shopping-cart';
21
22
  const KEY = 'dm-shop:basket';
@@ -539,7 +540,20 @@ function checkout() {
539
540
  ${q.adjustments.map(a => `<div class="${a.included ? 'is-included' : a.amount < 0 ? 'is-discount' : ''}"><dt>${esc(a.label)}</dt><dd>${a.stage === 'shipping' && a.amount === 0 ? 'Free' : esc(money(a.amount, cur))}</dd></div>`).join('')}
540
541
  <div class="is-total"><dt>Total</dt><dd>${esc(money(q.total, cur))}</dd></div>
541
542
  </dl>${(q.notes || []).length || good.length ? `<ul class="shop-notes">${good.map(a => `<li class="is-good">${ICON.check} ${esc(a.code)} applied</li>`).join('')}${(q.notes || []).map(n => `<li>${esc(n.message)}</li>`).join('')}</ul>` : ''}`;
542
- $('span', payBtn).textContent = q.total > 0 ? `Pay ${money(q.total, cur)}` : 'Place order';
543
+ renderPay(q);
544
+ }
545
+
546
+ /** The button and the line under it, for the method picked (offline places the order; it takes nothing). */
547
+ const noteEl = $('[data-co-note]', root);
548
+ function renderPay(q) {
549
+ if (!q) return;
550
+ const picked = form.elements.provider?.value || q.methods?.[0]?.id || '';
551
+ const w = payWording(picked, q.total, money(q.total, q.currency), {offlineInstructions: noteEl?.dataset.offlineNote || ''});
552
+ $('span', payBtn).textContent = w.button;
553
+ if (!noteEl) return;
554
+ noteEl.hidden = !w.note;
555
+ $('[data-co-notetext]', noteEl).textContent = w.note;
556
+ $('[data-co-lock]', noteEl).hidden = !w.secure;
543
557
  }
544
558
 
545
559
  function renderMethods(q) {
@@ -592,6 +606,7 @@ function checkout() {
592
606
  renderServices(q);
593
607
  renderTotals(q);
594
608
  renderMethods(q);
609
+ renderPay(q);
595
610
  } catch (err) {
596
611
  linesEl.innerHTML = `<p class="shop-co-error">${esc(err.message)}</p>`;
597
612
  }
@@ -601,6 +616,7 @@ function checkout() {
601
616
  const refreshSoon = () => { clearTimeout(t); t = setTimeout(refresh, 200); };
602
617
  listeners.add(refreshSoon);
603
618
  form.addEventListener('change', (e) => {
619
+ if (e.target.name === 'provider') renderPay(current);
604
620
  if (e.target.name === 'service') { service = e.target.value; session.set('dm-shop:service', service); }
605
621
  if (e.target.name === 'delivery' || e.target.name === 'country' || e.target.name === 'service') refreshSoon();
606
622
  });
@@ -136,3 +136,26 @@ export function orderFacts(ext = {}) {
136
136
  .filter(x => (typeof x.v === 'number' || (typeof x.v === 'string' && x.v.trim() && !ISO_TIME.test(x.v))))
137
137
  .map(x => ({...x, label: x.k.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase()}));
138
138
  }
139
+
140
+ /**
141
+ * What checkout's button and the line under it say for the payment method the shopper has picked. Offline
142
+ * takes nothing now, so it places the order and repeats the shop's own offline instructions; Stripe and PayPal
143
+ * send the shopper to the provider's page. A free order just places. The money is already formatted.
144
+ *
145
+ * @param {string} method - 'stripe' | 'paypal' | 'offline' | '' (none picked)
146
+ * @param {number} total - minor units
147
+ * @param {string} amount - the total, formatted
148
+ * @param {{offlineInstructions?: string}} [s]
149
+ * @returns {{button: string, note: string, secure: boolean}} secure: the note is about a provider's secure page
150
+ */
151
+ export function payWording(method, total, amount, s = {}) {
152
+ if (!(Number(total) > 0)) return {button: 'Place order', note: '', secure: false};
153
+ if (method === 'offline') {
154
+ const own = String(s.offlineInstructions || '').trim();
155
+ return {button: 'Place order', note: own || 'Nothing is taken now: we tell you how to pay once your order is placed.', secure: false};
156
+ }
157
+ if (method === 'paypal') {
158
+ return {button: `Pay ${amount} with PayPal`, note: 'You pay on PayPal\'s own secure page. We never see your card or PayPal details.', secure: true};
159
+ }
160
+ return {button: `Pay ${amount}`, note: 'Payment happens on a secure page run by the payment provider. We never see your card.', secure: true};
161
+ }
@@ -467,7 +467,9 @@ html.shop-locked { overflow: hidden; }
467
467
  .shop-acc-danger summary { cursor: pointer; color: var(--shop-muted); }
468
468
  .shop-linkbtn.is-danger { color: var(--shop-sale); }
469
469
  .shop-acc-link { font-size: .92rem; }
470
- .shop-crumbs .shop-acc-link { float: right; }
470
+ /* "Keep shopping · Sign in for faster checkout": the crumbs are a flex row, so a float never applied and the two ran together. */
471
+ .shop-crumbs { flex-wrap: wrap; }
472
+ .shop-crumbs-acc { display: inline-flex; align-items: center; gap: .4rem; }
471
473
  .shop-r-join { margin-top: 1.25rem; padding-top: 1rem; border-top: 1px solid var(--shop-line); }
472
474
  .shop-r-join h2 { font-size: 1rem; }
473
475
  .shop-r-join form { display: flex; flex-direction: column; gap: .6rem; }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * A signed-in shop customer through the CMS's REAL sign-in and plugin scope - no mocked authenticate. The Cart is
3
+ * registered the way core's plugins.js registers it: `authenticate` wrapped by pluginScope.js `authenticateFor`, the
4
+ * real `requirePermission`, a real JWT. The `shop-customer` role (admin confined to My Profile) used to get 403
5
+ * "Your account cannot use Shopping Cart" on its own account; it must load its account and orders, and must still
6
+ * be refused every admin API.
7
+ *
8
+ * Makes the role if the checkout lacks it, one customer and one order, and removes all three again.
9
+ */
10
+ import {test, before, after} from 'node:test';
11
+ import assert from 'node:assert/strict';
12
+ import fs from 'node:fs/promises';
13
+ import path from 'node:path';
14
+ import {fileURLToPath} from 'node:url';
15
+ import Fastify from 'fastify';
16
+ import jwt from '@fastify/jwt';
17
+ import shoppingCart from '../plugin.js';
18
+ import {authenticate, requirePermission} from '../../../server/middleware/auth.js';
19
+ import {authenticateFor} from '../../../server/services/pluginScope.js';
20
+ import * as roles from '../../../server/services/roles.js';
21
+ import {getEffectiveRoles} from '../../../server/services/userRoles.js';
22
+ import {createUser, deleteUser, getUserByEmail} from '../../../server/services/users.js';
23
+ import {createEntry, deleteEntry} from '../../../server/services/collections.js';
24
+
25
+ const here = path.dirname(fileURLToPath(import.meta.url));
26
+ const manifest = JSON.parse(await fs.readFile(path.join(here, '..', 'plugin.json'), 'utf8'));
27
+ const roleDef = JSON.parse(await fs.readFile(path.join(here, '..', 'roles', 'shop-customer.json'), 'utf8'));
28
+ const PLUGINS = path.resolve('config/plugins.json');
29
+ const EMAIL = 'scope-cat@example.test';
30
+ let app;
31
+ let savedPlugins;
32
+ let madeRole = false;
33
+ let customer;
34
+ let order;
35
+ let token;
36
+
37
+ before(async () => {
38
+ savedPlugins = await fs.readFile(PLUGINS, 'utf8').catch(() => null);
39
+ await roles.load();
40
+ if (!roles.getRoleMap().has(roleDef.name)) madeRole = await roles.ensureRole({...roleDef, plugin: 'shopping-cart'});
41
+ const old = await getUserByEmail(EMAIL);
42
+ if (old) await deleteUser(old.id);
43
+ customer = await createUser({name: 'Cat', email: EMAIL, password: 'a-long-password-1', role: 'shop-customer'});
44
+ delete globalThis[Symbol.for('domma.shopping-cart')];
45
+ app = Fastify();
46
+ await app.register(jwt, {secret: 'account-scope-test-secret'});
47
+ // As server/services/plugins.js hands it over: no `authenticateSelf`, so the Cart uses core's own check.
48
+ const scoped = authenticateFor(authenticate, manifest, (user) => roles.getAdminScope(getEffectiveRoles(user || {})));
49
+ await app.register(shoppingCart, {prefix: '/api/plugins/shopping-cart', auth: {authenticate: scoped, requirePermission},
50
+ settings: {}, hooks: {registerShortcode() {}}});
51
+ await app.ready();
52
+ order = await createEntry('shop-orders', {number: 4242, token: 'tok-scope-test', email: EMAIL, name: 'Cat', status: 'paid',
53
+ total: 12600, currency: 'GBP', lines: [{productId: 'p1', name: 'Walnut board', qty: 1, unitPrice: 12600}]});
54
+ token = app.jwt.sign({id: customer.id, email: EMAIL, name: 'Cat', role: 'shop-customer', additionalRoles: [], type: 'access'});
55
+ });
56
+
57
+ after(async () => {
58
+ await app?.close();
59
+ if (order) await deleteEntry('shop-orders', order.id).catch(() => {});
60
+ if (customer) await deleteUser(customer.id).catch(() => {});
61
+ if (madeRole) await roles.removeRole(roleDef.name);
62
+ if (savedPlugins === null) await fs.rm(PLUGINS, {force: true});
63
+ else await fs.writeFile(PLUGINS, savedPlugins);
64
+ });
65
+
66
+ const call = (method, url, {auth = token, body} = {}) => app.inject({method, url: `/api/plugins/shopping-cart${url}`, payload: body,
67
+ headers: auth ? {authorization: `Bearer ${auth}`} : {}});
68
+
69
+ test('scope: the shop-customer role really is confined to My Profile (the case that broke)', () => {
70
+ const scope = roles.getAdminScope(['shop-customer']);
71
+ assert.ok(scope, 'confined');
72
+ assert.deepEqual(scope.allow, ['/my-profile']);
73
+ });
74
+
75
+ test('scope: a signed-in customer loads their account and past orders', async () => {
76
+ const res = await call('GET', '/account');
77
+ assert.equal(res.statusCode, 200, res.body);
78
+ const body = res.json();
79
+ assert.equal(body.email, EMAIL);
80
+ assert.equal(body.orders.length, 1);
81
+ assert.equal(body.orders[0].number, 4242);
82
+ assert.match(body.orders[0].receipt, /tok-scope-test/);
83
+ const put = await call('PUT', '/account', {body: {name: 'Cat Jones', phone: '0113 000 0000'}});
84
+ assert.equal(put.statusCode, 200, put.body);
85
+ assert.equal(put.json().name, 'Cat Jones');
86
+ });
87
+
88
+ test('scope: the account needs a real sign-in', async () => {
89
+ assert.equal((await call('GET', '/account', {auth: null})).statusCode, 401);
90
+ assert.equal((await call('GET', '/account', {auth: 'not-a-token'})).statusCode, 401);
91
+ const refresh = app.jwt.sign({id: customer.id, role: 'shop-customer', type: 'refresh'});
92
+ assert.equal((await call('GET', '/account', {auth: refresh})).statusCode, 401, 'a refresh token is not a sign-in');
93
+ });
94
+
95
+ test('scope: a customer still cannot reach the Shop admin APIs', async () => {
96
+ for (const [method, url, body] of [['GET', '/orders'], ['GET', '/orders/' + order.id], ['GET', '/summary'], ['GET', '/settings'],
97
+ ['PUT', '/settings', {offlineEnabled: false}], ['GET', '/products'], ['POST', '/products', {name: 'x'}],
98
+ ['PUT', `/orders/${order.id}/status`, {status: 'refunded'}], ['GET', '/sales'], ['GET', '/count']]) {
99
+ const res = await call(method, url, {body});
100
+ assert.equal(res.statusCode, 403, `${method} ${url} answered ${res.statusCode}`);
101
+ }
102
+ });
@@ -49,7 +49,7 @@ before(async () => {
49
49
  req.user = {id: u.id, name: u.name, email: u.email, role: u.role};
50
50
  return undefined;
51
51
  };
52
- await app.register(shoppingCart, {auth: {authenticate, requirePermission: () => async () => {}}, settings: {}, hooks: {registerShortcode() {}}});
52
+ await app.register(shoppingCart, {auth: {authenticate, authenticateSelf: authenticate, requirePermission: () => async () => {}}, settings: {}, hooks: {registerShortcode() {}}});
53
53
  });
54
54
 
55
55
  after(async () => {
@@ -0,0 +1,58 @@
1
+ /**
2
+ * What checkout and the product page say: the pay button and the line under it per payment method (offline takes
3
+ * nothing, so it places the order and repeats the shop's offline instructions), the collection label in the shop's
4
+ * own capitals, and the gap between "Keep shopping" and "Sign in for faster checkout".
5
+ */
6
+ import {test} from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import {payWording} from '../public/lib/orders.js';
9
+ import {cartHtml, collectPhrase, productHtml} from '../lib/render.js';
10
+ import defaults from '../config.js';
11
+
12
+ const PROVIDER_NOTE = /secure page run by the payment provider/;
13
+
14
+ test('wording: offline only places the order and says what the shop says', () => {
15
+ const w = payWording('offline', 12600, '£126.00', {offlineInstructions: 'Pay by bank transfer within 7 days; we post once it arrives.'});
16
+ assert.equal(w.button, 'Place order');
17
+ assert.equal(w.note, 'Pay by bank transfer within 7 days; we post once it arrives.');
18
+ assert.equal(w.secure, false);
19
+ assert.doesNotMatch(w.button, /Pay /);
20
+ assert.doesNotMatch(w.note, PROVIDER_NOTE);
21
+ const plain = payWording('offline', 12600, '£126.00', {offlineInstructions: ' '});
22
+ assert.equal(plain.button, 'Place order');
23
+ assert.ok(plain.note && !PROVIDER_NOTE.test(plain.note), 'a fallback that is not about card pages');
24
+ });
25
+
26
+ test('wording: each method says its own thing', () => {
27
+ assert.deepEqual(payWording('stripe', 12600, '£126.00'), {button: 'Pay £126.00', note: 'Payment happens on a secure page run by the payment provider. We never see your card.', secure: true});
28
+ const pp = payWording('paypal', 12600, '£126.00');
29
+ assert.equal(pp.button, 'Pay £126.00 with PayPal');
30
+ assert.match(pp.note, /PayPal/);
31
+ assert.equal(pp.secure, true);
32
+ assert.deepEqual(payWording('stripe', 0, '£0.00'), {button: 'Place order', note: '', secure: false}, 'nothing to pay');
33
+ });
34
+
35
+ test('checkout page: the note carries the offline instructions; no fixed card wording', () => {
36
+ const html = cartHtml({settings: {...defaults, accounts: false, offlineInstructions: 'Pay at the "workshop" <door>'}, base: '/shop'});
37
+ assert.match(html, /data-offline-note="Pay at the &quot;workshop&quot; &lt;door&gt;"/);
38
+ assert.doesNotMatch(html, PROVIDER_NOTE, 'the card line is the script\'s to choose, per method');
39
+ });
40
+
41
+ test('checkout page: "Keep shopping" and "Sign in" are kept apart, and go together when signed in', () => {
42
+ const html = cartHtml({settings: {...defaults, accounts: true}, base: '/shop'});
43
+ const nav = /<nav class="shop-crumbs"[^]*?<\/nav>/.exec(html)[0];
44
+ assert.match(nav, /Keep shopping<\/a><span class="shop-crumbs-acc" data-acc-link><span aria-hidden="true">·<\/span> <a [^>]*>Sign in for faster checkout<\/a><\/span>/);
45
+ assert.doesNotMatch(cartHtml({settings: {...defaults, accounts: false}, base: '/shop'}), /Sign in for faster checkout|shop-crumbs-acc/);
46
+ });
47
+
48
+ test('collection label: the shop\'s own capitals, only a leading capital lowered', () => {
49
+ assert.equal(collectPhrase('Collect from our Leeds workshop'), 'collect from our Leeds workshop');
50
+ assert.equal(collectPhrase('IKEA Leeds click and collect'), 'IKEA Leeds click and collect');
51
+ assert.equal(collectPhrase('PO Box collection'), 'PO Box collection');
52
+ assert.equal(collectPhrase('collect in York'), 'collect in York');
53
+ assert.equal(collectPhrase(''), 'collect');
54
+ const entry = {id: 'p1', data: {name: 'Board', slug: 'board', price: 12600, status: 'active', images: [], variants: [], options: [], stock: null}};
55
+ const html = productHtml({entry, settings: {...defaults, allowCollection: true, collectionLabel: 'Collect from our Leeds workshop'}, base: '/shop', descriptionHtml: '', related: []});
56
+ assert.match(html, /or collect from our Leeds workshop/);
57
+ assert.doesNotMatch(html, /our leeds workshop/);
58
+ });
@@ -83,3 +83,29 @@ export function authenticateFor(authenticate, manifest, scopeOf) {
83
83
  return out;
84
84
  };
85
85
  }
86
+
87
+ /**
88
+ * The auth preHandlers a plugin is handed in `options.auth`.
89
+ *
90
+ * `authenticate` is core's sign-in check plus the scope rule above.
91
+ * `authenticateSelf` is core's sign-in check alone - every token rule (an
92
+ * access token is required, a refresh token is refused, the same JWT
93
+ * verification), but no admin-scope rule. It exists for routes that act only
94
+ * on the caller's own record (`request.user.id`): a shop customer's account,
95
+ * say, whose role confines them to no plugin's screens. Such a route must
96
+ * read and write nothing but the caller's own data; an admin API or anything
97
+ * touching another user's data uses `authenticate`.
98
+ *
99
+ * @param {Function} authenticate - core's preHandler
100
+ * @param {object} manifest
101
+ * @param {(user: object) => ({home: string, allow: string[]}|null)} scopeOf
102
+ * @returns {{authenticate: Function, authenticateSelf: Function}}
103
+ */
104
+ export function pluginAuthGuards(authenticate, manifest, scopeOf) {
105
+ return {
106
+ authenticate: authenticateFor(authenticate, manifest, scopeOf),
107
+ authenticateSelf: async function authenticateSelf(request, reply) {
108
+ return authenticate(request, reply);
109
+ }
110
+ };
111
+ }
@@ -45,7 +45,7 @@ import {disableDashboardPro, enableDashboardPro, registerWidget, unregisterWidge
45
45
  import {createCollection, getCollection} from './collections.js';
46
46
  import * as defaultRolesService from './roles.js';
47
47
  import {getAdminScope, normaliseAdminScope} from './roles.js';
48
- import {authenticateFor} from './pluginScope.js';
48
+ import {pluginAuthGuards} from './pluginScope.js';
49
49
  import {getEffectiveRoles} from './userRoles.js';
50
50
  import {isDcmStaff} from './staffAccess.js';
51
51
  import * as defaultUsersService from './users.js';
@@ -545,7 +545,8 @@ export async function registerPlugins(fastify) {
545
545
  prefix,
546
546
  // A user confined to some admin screens (role.admin) may call this plugin's
547
547
  // authenticated routes only if one of its screens is among them - see pluginScope.js.
548
- auth: {authenticate: authenticateFor(authenticate, manifest, (user) => getAdminScope(getEffectiveRoles(user || {}))),
548
+ // authenticateSelf skips that rule, for routes acting only on the caller's own record.
549
+ auth: {...pluginAuthGuards(authenticate, manifest, (user) => getAdminScope(getEffectiveRoles(user || {}))),
549
550
  requireRole, requireAdmin, requireVisibility, requirePermission},
550
551
  hooks: {registerShortcode, registerSanitizeRules, registerTransform, registerMenuLocation,
551
552
  // Stamped with the plugin's name, so the Menus editor can say where a Tool came from.