@stacksjs/defaults 0.75.612 → 0.75.614
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/ai/skills/stacks-actions/SKILL.md +209 -1
- package/ai/skills/stacks-api/SKILL.md +1 -1
- package/ai/skills/stacks-buddy/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +120 -9
- package/ai/skills/stacks-database/SKILL.md +4 -2
- package/ai/skills/stacks-email/SKILL.md +15 -0
- package/ai/skills/stacks-middleware/SKILL.md +4 -1
- package/ai/skills/stacks-native/CAPABILITIES.md +1 -1
- package/ai/skills/stacks-native/CATALOG.md +12 -12
- package/ai/skills/stacks-validation/SKILL.md +7 -0
- package/app/Actions/Dashboard/Models/ModelDestroyAction.ts +4 -47
- package/app/Actions/Dashboard/Models/ModelSaveAction.ts +257 -0
- package/app/Actions/Dashboard/Models/ModelStoreAction.ts +4 -31
- package/app/Actions/Dashboard/Models/ModelUpdateAction.ts +5 -61
- package/app/Actions/Dashboard/Models/model-related.ts +2 -3
- package/app/Actions/Dashboard/Models/model-row-writes.ts +188 -0
- package/app/Actions/Storefront/AddToCartAction.ts +12 -15
- package/app/Actions/Storefront/CheckoutContactAction.ts +18 -10
- package/app/Actions/Storefront/CheckoutShippingAction.ts +20 -10
- package/app/Actions/Storefront/PlaceOrderAction.ts +9 -12
- package/app/Actions/Storefront/UpdateCartItemAction.ts +11 -9
- package/app/Middleware/Abilities.ts +4 -3
- package/app/Middleware/Csrf.ts +10 -1
- package/app/Middleware/Throttle.ts +4 -4
- package/functions/dashboard-api.ts +9 -3
- package/functions/dashboard-model-bulk.ts +3 -3
- package/functions/dashboard-model-drafts.test.ts +122 -0
- package/functions/dashboard-model-drafts.ts +228 -0
- package/functions/dashboard-model-record.ts +1 -1
- package/ide/vscode/package.json +1 -1
- package/package.json +5 -5
- package/resources/components/Dashboard/Analytics/AnalyticsPageHeader.stx +3 -13
- package/resources/components/Dashboard/App/RequestsOverview.stx +3 -20
- package/resources/components/Dashboard/App/SourceInventory.stx +1 -5
- package/resources/components/Dashboard/Auth/AccessTokenCreateDialog.stx +11 -28
- package/resources/components/Dashboard/Commerce/CommerceCategoriesDashboard.stx +4 -8
- package/resources/components/Dashboard/Commerce/CommerceCategoryDialog.stx +9 -9
- package/resources/components/Dashboard/Commerce/CommerceCouponDialog.stx +14 -14
- package/resources/components/Dashboard/Commerce/CommerceCouponsDashboard.stx +5 -9
- package/resources/components/Dashboard/Commerce/CommerceCustomerDialog.stx +7 -7
- package/resources/components/Dashboard/Commerce/CommerceCustomersDashboard.stx +3 -7
- package/resources/components/Dashboard/Commerce/CommerceGiftCardDialog.stx +15 -15
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +5 -9
- package/resources/components/Dashboard/Commerce/CommerceManufacturerDialog.stx +12 -15
- package/resources/components/Dashboard/Commerce/CommerceManufacturersDashboard.stx +4 -28
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +15 -15
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +4 -8
- package/resources/components/Dashboard/Commerce/CommerceOverviewDashboard.stx +3 -11
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +8 -9
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +3 -20
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +4 -4
- package/resources/components/Dashboard/Commerce/CommerceProductDialog.stx +14 -14
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +4 -8
- package/resources/components/Dashboard/Commerce/CommerceReviewEditDialog.stx +14 -24
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +5 -43
- package/resources/components/Dashboard/Commerce/CommerceTaxDialog.stx +22 -38
- package/resources/components/Dashboard/Commerce/CommerceTaxesDashboard.stx +5 -33
- package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +16 -30
- package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +4 -28
- package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +15 -9
- package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +8 -9
- package/resources/components/Dashboard/Commerce/Delivery/CourierDialog.stx +14 -12
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRouteDialog.stx +9 -11
- package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveryDialog.stx +15 -9
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +11 -7
- package/resources/components/Dashboard/Commerce/Delivery/ShippingMethodDialog.stx +14 -8
- package/resources/components/Dashboard/Commerce/Delivery/ShippingRateDialog.stx +11 -17
- package/resources/components/Dashboard/Commerce/Delivery/ShippingZoneDialog.stx +18 -12
- package/resources/components/Dashboard/Commerce/PaymentRefundDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/PrintDeviceDialog.stx +5 -5
- package/resources/components/Dashboard/Commerce/PrintDevicesDashboard.stx +4 -8
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +5 -9
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +2 -10
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +14 -67
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +3 -18
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +23 -69
- package/resources/components/Dashboard/Content/AuthorEditorDialog.stx +4 -16
- package/resources/components/Dashboard/Content/BlogDashboard.stx +2 -19
- package/resources/components/Dashboard/Content/BlogPostEditorDialog.stx +31 -51
- package/resources/components/Dashboard/Content/CommentsDashboard.stx +1 -1
- package/resources/components/Dashboard/Content/ContentDashboard.stx +1 -11
- package/resources/components/Dashboard/Content/CreateFolderDialog.stx +1 -4
- package/resources/components/Dashboard/Content/FileManagerDashboard.stx +2 -2
- package/resources/components/Dashboard/Content/PageEditorDialog.stx +8 -17
- package/resources/components/Dashboard/Content/PostEditorDialog.stx +35 -45
- package/resources/components/Dashboard/Content/PostsDashboard.stx +1 -13
- package/resources/components/Dashboard/Content/SeoDashboard.stx +2 -20
- package/resources/components/Dashboard/Content/SeoEditorDialog.stx +4 -38
- package/resources/components/Dashboard/Content/TaxonomyEditorDialog.stx +8 -15
- package/resources/components/Dashboard/Data/ActivityLog.stx +1 -5
- package/resources/components/Dashboard/Deployments/DeploymentList.stx +2 -11
- package/resources/components/Dashboard/Email/InboxMessageList.stx +1 -5
- package/resources/components/Dashboard/Infrastructure/DnsDashboard.stx +2 -16
- package/resources/components/Dashboard/Infrastructure/LogsDashboard.stx +6 -10
- package/resources/components/Dashboard/Infrastructure/MailboxesDashboard.stx +1 -5
- package/resources/components/Dashboard/Infrastructure/ServersDashboard.stx +1 -5
- package/resources/components/Dashboard/Jobs/JobHistory.stx +3 -12
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +57 -51
- package/resources/components/Dashboard/Library/ComponentsDashboard.stx +4 -14
- package/resources/components/Dashboard/Library/DependenciesDashboard.stx +2 -15
- package/resources/components/Dashboard/Library/PackagesDashboard.stx +1 -8
- package/resources/components/Dashboard/Library/SourceScaffoldDialog.stx +1 -12
- package/resources/components/Dashboard/Management/PermissionsDashboard.stx +3 -3
- package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +4 -4
- package/resources/components/Dashboard/Marketing/CampaignDeliveryDialog.stx +3 -5
- package/resources/components/Dashboard/Marketing/CampaignDialog.stx +59 -93
- package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +5 -5
- package/resources/components/Dashboard/Marketing/MarketingListDialog.stx +12 -26
- package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +4 -4
- package/resources/components/Dashboard/Marketing/RecoveryCampaignDialog.stx +12 -43
- package/resources/components/Dashboard/Marketing/SocialPostDialog.stx +7 -41
- package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +5 -5
- package/resources/components/Dashboard/Models/ModelRecordEdit.stx +240 -28
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +7 -23
- package/resources/components/Dashboard/Models/ModelsOverview.stx +2 -12
- package/resources/components/Dashboard/Notifications/NotificationDeliveries.stx +4 -27
- package/resources/components/Dashboard/Notifications/NotificationDeliveryHistory.stx +4 -36
- package/resources/components/Dashboard/Operations/RecoveryDestinationDialog.stx +18 -47
- package/resources/components/Dashboard/Operations/RecoveryPolicyDialog.stx +24 -78
- package/resources/components/Dashboard/Operations/RecoveryRestoreDialog.stx +8 -19
- package/resources/components/Dashboard/Queries/QueryDashboard.stx +3 -21
- package/resources/components/Dashboard/Releases/ReleaseDashboard.stx +2 -9
- package/resources/components/Dashboard/Settings/SettingsDashboard.stx +1 -11
- package/resources/components/Dashboard/UI/Input.stx +50 -1
- package/resources/components/Dashboard/UI/SearchFilter.stx +27 -17
- package/resources/components/Dashboard/UI/Select.stx +4 -1
- package/resources/components/Dashboard/UI/Textarea.stx +16 -1
- package/resources/views/cart.stx +14 -0
- package/resources/views/checkout/contact.stx +15 -1
- package/resources/views/checkout/payment.stx +7 -0
- package/resources/views/checkout/shipping.stx +39 -5
- package/routes/dashboard-api.ts +2 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
2
|
import { config } from '@stacksjs/config'
|
|
3
3
|
import { db, sqlDateTime } from '@stacksjs/database/runtime'
|
|
4
|
-
import {
|
|
4
|
+
import { refuse } from '@stacksjs/router'
|
|
5
5
|
import { randomUUIDv7 } from 'bun'
|
|
6
6
|
import { readCartCookie, writeCartCookie } from '../../Storefront/CartCookie'
|
|
7
7
|
import { storefrontCurrency } from '../../Storefront/StorefrontMoney'
|
|
@@ -22,21 +22,26 @@ const COOKIE_OPTS = {
|
|
|
22
22
|
* on first add so empty visitors don't litter the table.
|
|
23
23
|
* - Idempotent per product: if the same slug is already in the cart we
|
|
24
24
|
* bump the existing line's quantity instead of inserting a duplicate.
|
|
25
|
-
* - Form vs XHR: a normal HTML form post
|
|
26
|
-
*
|
|
27
|
-
*
|
|
25
|
+
* - Form vs XHR: a normal HTML form post goes on to the cart, or to the
|
|
26
|
+
* page its `redirect` field names when that is a page of this shop
|
|
27
|
+
* (`next` below never follows another site); XHR callers (the cart
|
|
28
|
+
* drawer) get JSON and stay on the current page.
|
|
28
29
|
*/
|
|
29
30
|
export default new Action({
|
|
30
31
|
name: 'AddToCartAction',
|
|
31
32
|
description: 'Add a product to the anonymous cart, keyed by cookie session.',
|
|
32
33
|
method: 'POST',
|
|
34
|
+
// The field was followed wherever it pointed, so a link could send a
|
|
35
|
+
// shopper to any site after adding to the cart. The router follows only a
|
|
36
|
+
// path of this application, and goes back to the form's page otherwise.
|
|
37
|
+
next: (_result: unknown, request: any) => String(request.get('redirect') ?? '') || '/cart',
|
|
33
38
|
|
|
34
39
|
async handle(request: any) {
|
|
35
40
|
const slug = String(request.get('slug') ?? '').trim()
|
|
36
41
|
const quantity = Math.max(1, Math.min(99, Number(request.get('quantity') ?? 1) || 1))
|
|
37
42
|
|
|
38
43
|
if (!slug)
|
|
39
|
-
return
|
|
44
|
+
return refuse('Choose a product to add.', { field: 'slug' })
|
|
40
45
|
|
|
41
46
|
const product = await (db as any)
|
|
42
47
|
.selectFrom('products')
|
|
@@ -47,7 +52,7 @@ export default new Action({
|
|
|
47
52
|
.executeTakeFirst()
|
|
48
53
|
|
|
49
54
|
if (!product)
|
|
50
|
-
return
|
|
55
|
+
return refuse('That product is no longer available.', { status: 404 })
|
|
51
56
|
|
|
52
57
|
// readCartCookie verifies the HMAC; tampered cookies return null
|
|
53
58
|
// and the action falls through to the "create new cart" branch as
|
|
@@ -129,15 +134,7 @@ export default new Action({
|
|
|
129
134
|
|
|
130
135
|
await recomputeCartTotals(cart.id)
|
|
131
136
|
|
|
132
|
-
|
|
133
|
-
const wantsHtml = (request.headers?.get?.('accept') || '').includes('text/html')
|
|
134
|
-
const xhr = request.headers?.get?.('x-requested-with') === 'XMLHttpRequest'
|
|
135
|
-
const redirectTarget = String(request.get('redirect') ?? '/cart')
|
|
136
|
-
|
|
137
|
-
if (wantsHtml && !xhr)
|
|
138
|
-
return response.redirect(redirectTarget)
|
|
139
|
-
|
|
140
|
-
return response.json({ ok: true, cart_id: cart.id })
|
|
137
|
+
return { ok: true, cart_id: cart.id }
|
|
141
138
|
},
|
|
142
139
|
})
|
|
143
140
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
2
|
import { db } from '@stacksjs/database/runtime'
|
|
3
|
-
import {
|
|
3
|
+
import { refuse } from '@stacksjs/router'
|
|
4
|
+
import { schema } from '@stacksjs/validation/runtime'
|
|
4
5
|
import { readCartCookie } from '../../Storefront/CartCookie'
|
|
5
6
|
|
|
6
7
|
const CART_COOKIE = 'stacks_cart'
|
|
@@ -14,15 +15,27 @@ export default new Action({
|
|
|
14
15
|
name: 'CheckoutContactAction',
|
|
15
16
|
description: 'Save the shopper email on the active cart.',
|
|
16
17
|
method: 'POST',
|
|
18
|
+
// A browser form goes on to the next step; a script gets `next` in the body.
|
|
19
|
+
next: '/checkout/shipping',
|
|
20
|
+
|
|
21
|
+
// Declared, so the router answers a wrong address the way the caller asked
|
|
22
|
+
// to be answered: the checkout page gets the shopper back on the contact
|
|
23
|
+
// step with the message under the field and what they typed still in it,
|
|
24
|
+
// and a script gets the 422 body. Checked by hand in `handle`, a form was
|
|
25
|
+
// answered with a page of JSON (stacksjs/stacks#3309).
|
|
26
|
+
validations: {
|
|
27
|
+
email: { rule: schema.string().email().required(), message: 'Enter a valid email address.' },
|
|
28
|
+
},
|
|
17
29
|
|
|
18
30
|
async handle(request: any) {
|
|
19
31
|
const email = String(request.get('email') ?? '').trim().toLowerCase()
|
|
32
|
+
// For a caller that runs the action without the router in front of it.
|
|
20
33
|
if (!email || !email.includes('@'))
|
|
21
|
-
return
|
|
34
|
+
return refuse('Enter a valid email address.', { field: 'email' })
|
|
22
35
|
|
|
23
36
|
const token = readCartCookie(request, CART_COOKIE)
|
|
24
37
|
if (!token)
|
|
25
|
-
return
|
|
38
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
26
39
|
|
|
27
40
|
const cart = await (db as any)
|
|
28
41
|
.selectFrom('carts')
|
|
@@ -32,7 +45,7 @@ export default new Action({
|
|
|
32
45
|
.executeTakeFirst()
|
|
33
46
|
|
|
34
47
|
if (!cart)
|
|
35
|
-
return
|
|
48
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
36
49
|
|
|
37
50
|
await (db as any)
|
|
38
51
|
.updateTable('carts')
|
|
@@ -40,11 +53,6 @@ export default new Action({
|
|
|
40
53
|
.where('id', '=', cart.id)
|
|
41
54
|
.execute()
|
|
42
55
|
|
|
43
|
-
|
|
44
|
-
const xhr = request.headers?.get?.('x-requested-with') === 'XMLHttpRequest'
|
|
45
|
-
if (wantsHtml && !xhr)
|
|
46
|
-
return response.redirect('/checkout/shipping')
|
|
47
|
-
|
|
48
|
-
return response.json({ ok: true, next: '/checkout/shipping' })
|
|
56
|
+
return { ok: true, next: '/checkout/shipping' }
|
|
49
57
|
},
|
|
50
58
|
})
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
2
|
import { db } from '@stacksjs/database/runtime'
|
|
3
|
-
import {
|
|
3
|
+
import { refuse } from '@stacksjs/router'
|
|
4
|
+
import { schema } from '@stacksjs/validation/runtime'
|
|
4
5
|
import { readCartCookie } from '../../Storefront/CartCookie'
|
|
5
6
|
|
|
6
7
|
const CART_COOKIE = 'stacks_cart'
|
|
@@ -13,6 +14,19 @@ export default new Action({
|
|
|
13
14
|
name: 'CheckoutShippingAction',
|
|
14
15
|
description: 'Save shipping address on the active cart.',
|
|
15
16
|
method: 'POST',
|
|
17
|
+
// A browser form goes on to the next step; a script gets `next` in the body.
|
|
18
|
+
next: '/checkout/payment',
|
|
19
|
+
|
|
20
|
+
// Declared, so a missing field is answered the way the caller asked: the
|
|
21
|
+
// checkout page gets the shopper back with the message under the field and
|
|
22
|
+
// what they typed kept (stacksjs/stacks#3311). A field of spaces is missing.
|
|
23
|
+
validations: {
|
|
24
|
+
shipping_name: { rule: schema.string().matches(/\S/).required(), message: 'Enter the name to ship to.' },
|
|
25
|
+
shipping_address: { rule: schema.string().matches(/\S/).required(), message: 'Enter the street address.' },
|
|
26
|
+
shipping_city: { rule: schema.string().matches(/\S/).required(), message: 'Enter the city.' },
|
|
27
|
+
shipping_state: { rule: schema.string().matches(/\S/).required(), message: 'Enter the state.' },
|
|
28
|
+
shipping_zip: { rule: schema.string().matches(/\S/).required(), message: 'Enter the ZIP or postal code.' },
|
|
29
|
+
},
|
|
16
30
|
|
|
17
31
|
async handle(request: any) {
|
|
18
32
|
const name = String(request.get('shipping_name') ?? '').trim()
|
|
@@ -21,12 +35,13 @@ export default new Action({
|
|
|
21
35
|
const state = String(request.get('shipping_state') ?? '').trim()
|
|
22
36
|
const zip = String(request.get('shipping_zip') ?? '').trim()
|
|
23
37
|
|
|
38
|
+
// For a caller that runs the action without the router in front of it.
|
|
24
39
|
if (!name || !address || !city || !state || !zip)
|
|
25
|
-
return
|
|
40
|
+
return refuse('All shipping fields are required.')
|
|
26
41
|
|
|
27
42
|
const token = readCartCookie(request, CART_COOKIE)
|
|
28
43
|
if (!token)
|
|
29
|
-
return
|
|
44
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
30
45
|
|
|
31
46
|
const cart = await (db as any)
|
|
32
47
|
.selectFrom('carts')
|
|
@@ -36,7 +51,7 @@ export default new Action({
|
|
|
36
51
|
.executeTakeFirst()
|
|
37
52
|
|
|
38
53
|
if (!cart)
|
|
39
|
-
return
|
|
54
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
40
55
|
|
|
41
56
|
await (db as any)
|
|
42
57
|
.updateTable('carts')
|
|
@@ -51,11 +66,6 @@ export default new Action({
|
|
|
51
66
|
.where('id', '=', cart.id)
|
|
52
67
|
.execute()
|
|
53
68
|
|
|
54
|
-
|
|
55
|
-
const xhr = request.headers?.get?.('x-requested-with') === 'XMLHttpRequest'
|
|
56
|
-
if (wantsHtml && !xhr)
|
|
57
|
-
return response.redirect('/checkout/payment')
|
|
58
|
-
|
|
59
|
-
return response.json({ ok: true, next: '/checkout/payment' })
|
|
69
|
+
return { ok: true, next: '/checkout/payment' }
|
|
60
70
|
},
|
|
61
71
|
})
|
|
@@ -3,7 +3,7 @@ import { Action } from '@stacksjs/actions/runtime'
|
|
|
3
3
|
import { customers } from '@stacksjs/commerce'
|
|
4
4
|
import { config } from '@stacksjs/config'
|
|
5
5
|
import { db } from '@stacksjs/database/runtime'
|
|
6
|
-
import {
|
|
6
|
+
import { refuse } from '@stacksjs/router'
|
|
7
7
|
import { sendOrderConfirmation } from '../../Mail/OrderConfirmation'
|
|
8
8
|
import { readCartCookie } from '../../Storefront/CartCookie'
|
|
9
9
|
import { storefrontCurrency } from '../../Storefront/StorefrontMoney'
|
|
@@ -28,11 +28,13 @@ export default new Action({
|
|
|
28
28
|
name: 'PlaceOrderAction',
|
|
29
29
|
description: 'Convert the active cart into an Order + OrderItems.',
|
|
30
30
|
method: 'POST',
|
|
31
|
+
// A browser form goes to the order it placed; a script gets its id and totals.
|
|
32
|
+
next: (result: { order_id: number }) => `/orders/${result.order_id}`,
|
|
31
33
|
|
|
32
34
|
async handle(request: any) {
|
|
33
35
|
const token = readCartCookie(request, CART_COOKIE)
|
|
34
36
|
if (!token)
|
|
35
|
-
return
|
|
37
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
36
38
|
|
|
37
39
|
const cart = await (db as any)
|
|
38
40
|
.selectFrom('carts')
|
|
@@ -42,7 +44,7 @@ export default new Action({
|
|
|
42
44
|
.executeTakeFirst()
|
|
43
45
|
|
|
44
46
|
if (!cart)
|
|
45
|
-
return
|
|
47
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
46
48
|
|
|
47
49
|
const items = await (db as any)
|
|
48
50
|
.selectFrom('cart_items')
|
|
@@ -51,10 +53,10 @@ export default new Action({
|
|
|
51
53
|
.execute()
|
|
52
54
|
|
|
53
55
|
if (items.length === 0)
|
|
54
|
-
return
|
|
56
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
55
57
|
|
|
56
58
|
if (!cart.email || !cart.shipping_name || !cart.shipping_address)
|
|
57
|
-
return
|
|
59
|
+
return refuse('Checkout details are incomplete. Go back and fill in your email and shipping address.')
|
|
58
60
|
|
|
59
61
|
// One customer per email — repeat shoppers reuse the same row so
|
|
60
62
|
// the dashboard's customer total isn't inflated by checkouts.
|
|
@@ -179,17 +181,12 @@ export default new Action({
|
|
|
179
181
|
console.error(`[PlaceOrderAction] order receipt email failed for order #${order.id}:`, message)
|
|
180
182
|
})
|
|
181
183
|
|
|
182
|
-
|
|
183
|
-
const xhr = request.headers?.get?.('x-requested-with') === 'XMLHttpRequest'
|
|
184
|
-
if (wantsHtml && !xhr)
|
|
185
|
-
return response.redirect(`/orders/${order.id}`)
|
|
186
|
-
|
|
187
|
-
return response.json({
|
|
184
|
+
return {
|
|
188
185
|
ok: true,
|
|
189
186
|
order_id: order.id,
|
|
190
187
|
total,
|
|
191
188
|
subtotal,
|
|
192
189
|
shipping,
|
|
193
|
-
}
|
|
190
|
+
}
|
|
194
191
|
},
|
|
195
192
|
})
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Action } from '@stacksjs/actions/runtime'
|
|
2
2
|
import { db } from '@stacksjs/database/runtime'
|
|
3
|
-
import { response } from '@stacksjs/router'
|
|
3
|
+
import { refuse, response } from '@stacksjs/router'
|
|
4
4
|
import { readCartCookie } from '../../Storefront/CartCookie'
|
|
5
5
|
|
|
6
6
|
const CART_COOKIE = 'stacks_cart'
|
|
@@ -9,11 +9,18 @@ const CART_COOKIE = 'stacks_cart'
|
|
|
9
9
|
* Change the quantity of a cart line, or remove it (quantity=0).
|
|
10
10
|
* Scoped by the caller's cart cookie so one shopper can't poke at
|
|
11
11
|
* another's cart by guessing item ids.
|
|
12
|
+
*
|
|
13
|
+
* The cart page posts plain forms here. The router sends that browser back
|
|
14
|
+
* to the cart with the notice below, and a `fetch()` caller gets the totals
|
|
15
|
+
* (stacksjs/stacks#3312).
|
|
12
16
|
*/
|
|
13
17
|
export default new Action({
|
|
14
18
|
name: 'UpdateCartItemAction',
|
|
15
19
|
description: 'Update or remove a cart item by id, scoped to caller cookie.',
|
|
16
20
|
method: 'POST',
|
|
21
|
+
// A changed quantity shows on the page itself. A line that disappears
|
|
22
|
+
// needs saying.
|
|
23
|
+
notice: (_result: unknown, request: any) => Number(request.get('quantity') ?? 1) === 0 ? 'Removed from your cart.' : '',
|
|
17
24
|
|
|
18
25
|
async handle(request: any) {
|
|
19
26
|
const itemId = Number(request.get('item_id') ?? 0)
|
|
@@ -23,7 +30,7 @@ export default new Action({
|
|
|
23
30
|
// an attacker can't probe for the existence of arbitrary carts.
|
|
24
31
|
const token = readCartCookie(request, CART_COOKIE)
|
|
25
32
|
if (!token)
|
|
26
|
-
return
|
|
33
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
27
34
|
|
|
28
35
|
const cart = await (db as any)
|
|
29
36
|
.selectFrom('carts')
|
|
@@ -32,7 +39,7 @@ export default new Action({
|
|
|
32
39
|
.executeTakeFirst()
|
|
33
40
|
|
|
34
41
|
if (!cart)
|
|
35
|
-
return
|
|
42
|
+
return refuse('Your cart is empty.', { status: 404 })
|
|
36
43
|
|
|
37
44
|
const item = await (db as any)
|
|
38
45
|
.selectFrom('cart_items')
|
|
@@ -42,7 +49,7 @@ export default new Action({
|
|
|
42
49
|
.executeTakeFirst()
|
|
43
50
|
|
|
44
51
|
if (!item)
|
|
45
|
-
return
|
|
52
|
+
return refuse('That item is no longer in your cart.', { status: 404 })
|
|
46
53
|
|
|
47
54
|
if (quantity === 0) {
|
|
48
55
|
await (db as any).deleteFrom('cart_items').where('id', '=', item.id).execute()
|
|
@@ -73,11 +80,6 @@ export default new Action({
|
|
|
73
80
|
.where('id', '=', cart.id)
|
|
74
81
|
.execute()
|
|
75
82
|
|
|
76
|
-
const wantsHtml = (request.headers?.get?.('accept') || '').includes('text/html')
|
|
77
|
-
const xhr = request.headers?.get?.('x-requested-with') === 'XMLHttpRequest'
|
|
78
|
-
if (wantsHtml && !xhr)
|
|
79
|
-
return response.redirect('/cart')
|
|
80
|
-
|
|
81
83
|
return response.json({ ok: true, total_items: totalItems, subtotal })
|
|
82
84
|
},
|
|
83
85
|
})
|
|
@@ -36,9 +36,10 @@ export default new Middleware({
|
|
|
36
36
|
throw new HttpError(401, 'Unauthenticated.')
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
// `
|
|
40
|
-
//
|
|
41
|
-
|
|
39
|
+
// `scopes`, which every token row carries: the Auth middleware stamps a
|
|
40
|
+
// `PersonalAccessToken`, whose `abilities` copy them, and
|
|
41
|
+
// `currentAccessToken()` the plain row, which has no `abilities` at all.
|
|
42
|
+
const tokenAbilities: readonly string[] = Array.isArray(token.scopes) ? token.scopes : []
|
|
42
43
|
|
|
43
44
|
// Wildcard grants all permissions
|
|
44
45
|
if (tokenAbilities.includes('*')) {
|
package/app/Middleware/Csrf.ts
CHANGED
|
@@ -61,6 +61,9 @@ import { Middleware, parseBearerToken } from '@stacksjs/router/middleware'
|
|
|
61
61
|
export const CSRF_COOKIE_NAME = 'X-CSRF-Token'
|
|
62
62
|
const CSRF_SECURE_TRANSPORT = Symbol.for('@stacksjs/router:csrf-secure-transport')
|
|
63
63
|
const CSRF_HEADER_NAME = 'x-csrf-token'
|
|
64
|
+
/** `FORM_REFUSAL` in @stacksjs/router, by its registered name: this module does not load the router. */
|
|
65
|
+
const CSRF_FORM_REFUSAL = Symbol.for('stacks.formRefusal')
|
|
66
|
+
const CSRF_FORM_MESSAGE = 'This form was open too long to be sent safely, so nothing was saved. Check it and send it again.'
|
|
64
67
|
const CSRF_COOKIE_PREFIX = `${CSRF_COOKIE_NAME}=`
|
|
65
68
|
const LEGACY_CSRF_COOKIE_PREFIX = 'csrf-token='
|
|
66
69
|
const JOINED_CSRF_COOKIE_PREFIX = `, ${CSRF_COOKIE_PREFIX}`
|
|
@@ -381,7 +384,13 @@ function assertValidCsrfRequest(request: Request | EnhancedRequest): void {
|
|
|
381
384
|
// mismatch" — it's not in the IANA list but most SPAs already
|
|
382
385
|
// know how to refresh on 419. We use 403 for the strict-correct
|
|
383
386
|
// status code instead (419 is non-standard).
|
|
384
|
-
|
|
387
|
+
const refusal = new HttpError(403, 'CSRF token mismatch')
|
|
388
|
+
// A browser form from this application's own page (a tab left open past
|
|
389
|
+
// the token's life, a second tab that replaced it) goes back to that page
|
|
390
|
+
// with this, and what was typed, instead of the 403 body. A script and a
|
|
391
|
+
// form from anywhere else get the 403 as before (stacksjs/stacks#3311).
|
|
392
|
+
Object.defineProperty(refusal, CSRF_FORM_REFUSAL, { value: { message: CSRF_FORM_MESSAGE, status: 403 } })
|
|
393
|
+
throw refusal
|
|
385
394
|
}
|
|
386
395
|
|
|
387
396
|
export async function validateCsrfRequest(request: Request | EnhancedRequest): Promise<void> {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { EnhancedRequest } from '@stacksjs/router'
|
|
1
2
|
import { clientAddress, createRateLimitMiddleware, Middleware, parseThrottleString, scaledLimit } from '@stacksjs/router'
|
|
2
3
|
|
|
3
4
|
// Cache for rate limiters to avoid creating new instances for each request
|
|
@@ -22,12 +23,11 @@ const RATE_LIMIT_HEADERS = ['X-RateLimit-Limit', 'X-RateLimit-Remaining', 'X-Rat
|
|
|
22
23
|
* that delivered the request is Cloudflare). A client-written
|
|
23
24
|
* `X-Forwarded-For` no longer buys a fresh budget.
|
|
24
25
|
*/
|
|
25
|
-
function throttleKey(request:
|
|
26
|
-
const
|
|
27
|
-
const id = user?.id
|
|
26
|
+
function throttleKey(request: EnhancedRequest): string {
|
|
27
|
+
const id = request._authenticatedUser?.id
|
|
28
28
|
if ((typeof id === 'number' && Number.isFinite(id)) || (typeof id === 'string' && id !== ''))
|
|
29
29
|
return `user:${id}`
|
|
30
|
-
return `ip:${clientAddress(request
|
|
30
|
+
return `ip:${clientAddress(request) ?? 'unknown'}`
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
/**
|
|
@@ -28,12 +28,18 @@ export interface ApiRequestOptions {
|
|
|
28
28
|
export class DashboardApiError extends Error {
|
|
29
29
|
readonly status: number
|
|
30
30
|
readonly fields?: Record<string, string>
|
|
31
|
+
/**
|
|
32
|
+
* The answer's body as it came, for a caller that needs more of it than the
|
|
33
|
+
* message and the fields: where a combined save was refused, say.
|
|
34
|
+
*/
|
|
35
|
+
readonly body?: unknown
|
|
31
36
|
|
|
32
|
-
constructor(message: string, status: number, fields?: Record<string, string
|
|
37
|
+
constructor(message: string, status: number, fields?: Record<string, string>, body?: unknown) {
|
|
33
38
|
super(message)
|
|
34
39
|
this.name = 'DashboardApiError'
|
|
35
40
|
this.status = status
|
|
36
41
|
this.fields = fields
|
|
42
|
+
this.body = body
|
|
37
43
|
}
|
|
38
44
|
}
|
|
39
45
|
|
|
@@ -78,7 +84,7 @@ async function dashboardResponseError(res: Response): Promise<DashboardApiError>
|
|
|
78
84
|
const failure = describeResponseError(res.status, payload)
|
|
79
85
|
if (failure.unexpected)
|
|
80
86
|
console.error('[dashboard-api] Unexpected request failure:', failure.cause)
|
|
81
|
-
return new DashboardApiError(failure.message, res.status, failure.fields)
|
|
87
|
+
return new DashboardApiError(failure.message, res.status, failure.fields, payload)
|
|
82
88
|
}
|
|
83
89
|
|
|
84
90
|
/**
|
|
@@ -104,7 +110,7 @@ export async function dashboardApi<T = unknown>(path: string, options: ApiReques
|
|
|
104
110
|
const failure = describeResponseError(res.status, payload as ApiErrorBody | null)
|
|
105
111
|
if (failure.unexpected)
|
|
106
112
|
console.error('[dashboard-api] Unexpected request failure:', failure.cause)
|
|
107
|
-
throw new DashboardApiError(failure.message, res.status, failure.fields)
|
|
113
|
+
throw new DashboardApiError(failure.message, res.status, failure.fields, payload)
|
|
108
114
|
}
|
|
109
115
|
|
|
110
116
|
return payload as T
|
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
* A selection is acted on one record at a time, each through the endpoint a
|
|
6
6
|
* single row uses, so every guard a single press has applies to each record
|
|
7
7
|
* and nothing about an action changes for it. It is not all or nothing and
|
|
8
|
-
* does not claim to be
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* does not claim to be: one record refused does not take back the others.
|
|
9
|
+
* What is reported is what happened, how many were done and, for the rest,
|
|
10
|
+
* which and why.
|
|
11
11
|
*/
|
|
12
12
|
import { DashboardApiError } from './dashboard-api'
|
|
13
13
|
import type { ModelActionResult, ModelCustomAction, ModelDeleteOutcome } from './dashboard-model-record'
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
import type { ModelDrafts } from './dashboard-model-drafts'
|
|
3
|
+
import { modelDraftChangeCount, modelDraftKey, modelDraftListRows, modelDraftPut, modelDraftRemove, modelDraftRestore, modelDraftRowLabel, modelDraftValues, modelRelatedSaveChanges, saveModelRecordWithRelated } from './dashboard-model-drafts'
|
|
4
|
+
import type { ModelRelatedPanel } from './dashboard-model-record'
|
|
5
|
+
|
|
6
|
+
// An order's lines: the panel a record's edit page shows, as the API sends it.
|
|
7
|
+
const lines: ModelRelatedPanel = {
|
|
8
|
+
kind: 'many',
|
|
9
|
+
model: 'OrderLine',
|
|
10
|
+
slug: 'order-line',
|
|
11
|
+
title: 'Order Lines',
|
|
12
|
+
label: 'Order Line',
|
|
13
|
+
foreignKey: 'order_id',
|
|
14
|
+
field: 'orderId',
|
|
15
|
+
total: 2,
|
|
16
|
+
columns: [{ key: 'sku', label: 'SKU', type: 'text' }, { key: 'unit_price', label: 'Unit Price', type: 'text' }],
|
|
17
|
+
rows: [{ id: 10, sku: 'A-1', unit_price: 5 }, { id: 11, sku: 'B-2', unit_price: 9 }],
|
|
18
|
+
canCreate: true,
|
|
19
|
+
canUpdate: true,
|
|
20
|
+
canDestroy: true,
|
|
21
|
+
fields: [
|
|
22
|
+
{ name: 'sku', label: 'SKU', type: 'text', required: true },
|
|
23
|
+
{ name: 'unitPrice', label: 'Unit Price', type: 'number', required: false },
|
|
24
|
+
] as never,
|
|
25
|
+
values: { 10: { sku: 'A-1', unit_price: 5 }, 11: { sku: 'B-2', unit_price: 9 } },
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe('a record\'s related rows, changed on its edit page', () => {
|
|
29
|
+
it('sends nothing for rows that were only looked at, or edited back to what they were', () => {
|
|
30
|
+
let drafts: ModelDrafts = {}
|
|
31
|
+
expect(modelRelatedSaveChanges([lines], drafts)).toEqual([])
|
|
32
|
+
drafts = modelDraftPut(drafts, lines, '10', { ...modelDraftValues(lines, drafts, '10') })
|
|
33
|
+
expect(modelRelatedSaveChanges([lines], drafts)).toEqual([])
|
|
34
|
+
expect(modelDraftChangeCount([lines], drafts)).toBe(0)
|
|
35
|
+
expect(modelDraftListRows(lines, drafts).map(row => row.state)).toEqual(['kept', 'kept'])
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('sends only the fields an edit changed', () => {
|
|
39
|
+
const start = modelDraftValues(lines, {}, '10')
|
|
40
|
+
const drafts = modelDraftPut({}, lines, '10', { ...start, unitPrice: '7' })
|
|
41
|
+
// As the form sends any field: text, which the server reads as its column's type.
|
|
42
|
+
expect(modelRelatedSaveChanges([lines], drafts)).toEqual([{ slug: 'order-line', create: [], update: [{ id: 10, fields: { unitPrice: '7' } }], destroy: [] }])
|
|
43
|
+
const listed = modelDraftListRows(lines, drafts)
|
|
44
|
+
expect(listed[0]).toMatchObject({ key: '10', state: 'edited' })
|
|
45
|
+
// Shown with the value it will be saved with, under the panel's column.
|
|
46
|
+
expect(listed[0]!.values.unit_price).toBe('7')
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('adds rows under their own keys, and an added row edited again is one row', () => {
|
|
50
|
+
let drafts: ModelDrafts = {}
|
|
51
|
+
const first = modelDraftKey(drafts, 'order-line')
|
|
52
|
+
drafts = modelDraftPut(drafts, lines, first, { sku: 'C-3', unitPrice: '2' })
|
|
53
|
+
const second = modelDraftKey(drafts, 'order-line')
|
|
54
|
+
expect(second).not.toBe(first)
|
|
55
|
+
drafts = modelDraftPut(drafts, lines, second, { sku: 'D-4', unitPrice: '' })
|
|
56
|
+
drafts = modelDraftPut(drafts, lines, first, { sku: 'C-3b', unitPrice: '2' })
|
|
57
|
+
expect(modelRelatedSaveChanges([lines], drafts)[0]!.create).toEqual([
|
|
58
|
+
{ key: first, fields: { sku: 'C-3b', unitPrice: '2' } },
|
|
59
|
+
{ key: second, fields: { sku: 'D-4', unitPrice: null } },
|
|
60
|
+
])
|
|
61
|
+
expect(modelDraftListRows(lines, drafts).map(row => [row.key, row.state])).toEqual([['10', 'kept'], ['11', 'kept'], [first, 'added'], [second, 'added']])
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('deletes a listed row and forgets its edit; a row added here is just dropped', () => {
|
|
65
|
+
let drafts = modelDraftPut({}, lines, '11', { sku: 'B-2', unitPrice: '1' })
|
|
66
|
+
drafts = modelDraftRemove(drafts, lines, '11')
|
|
67
|
+
const added = modelDraftKey(drafts, 'order-line')
|
|
68
|
+
drafts = modelDraftPut(drafts, lines, added, { sku: 'E-5', unitPrice: '3' })
|
|
69
|
+
drafts = modelDraftRemove(drafts, lines, added)
|
|
70
|
+
expect(modelRelatedSaveChanges([lines], drafts)).toEqual([{ slug: 'order-line', create: [], update: [], destroy: [11] }])
|
|
71
|
+
expect(modelDraftListRows(lines, drafts).map(row => row.state)).toEqual(['kept', 'removed'])
|
|
72
|
+
drafts = modelDraftRestore(drafts, lines, '11')
|
|
73
|
+
expect(modelRelatedSaveChanges([lines], drafts)).toEqual([])
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('names a row by its summary values, or by what it is', () => {
|
|
77
|
+
const [first] = modelDraftListRows(lines, {})
|
|
78
|
+
expect(modelDraftRowLabel(lines, first!)).toBe('A-1 · 5')
|
|
79
|
+
expect(modelDraftRowLabel(lines, { key: 'new-1', state: 'added', values: {} })).toBe('New order line')
|
|
80
|
+
expect(modelDraftRowLabel(lines, { key: '12', state: 'kept', values: {} })).toBe('Order Line #12')
|
|
81
|
+
})
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
describe('saving them with the record', () => {
|
|
85
|
+
async function withFetch<T>(answer: Response, run: (asked: Request[]) => Promise<T>): Promise<T> {
|
|
86
|
+
const original = globalThis.fetch
|
|
87
|
+
const asked: Request[] = []
|
|
88
|
+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
89
|
+
asked.push(new Request(new URL(String(input), 'http://dashboard.test'), init))
|
|
90
|
+
return answer
|
|
91
|
+
}) as typeof fetch
|
|
92
|
+
try {
|
|
93
|
+
return await run(asked)
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
globalThis.fetch = original
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
it('sends the record\'s fields and the panels\' changes in one request', async () => {
|
|
101
|
+
const related = [{ slug: 'order-line', create: [], update: [], destroy: [11] }]
|
|
102
|
+
const result = await withFetch(Response.json({ ok: true }), async (asked) => {
|
|
103
|
+
const saved = await saveModelRecordWithRelated('order', 3, { status: 'paid' }, related)
|
|
104
|
+
expect(asked).toHaveLength(1)
|
|
105
|
+
expect(asked[0]!.method).toBe('PATCH')
|
|
106
|
+
expect(new URL(asked[0]!.url).pathname).toBe('/api/dashboard/models/order/3/save')
|
|
107
|
+
expect(await asked[0]!.json()).toEqual({ fields: { status: 'paid' }, related })
|
|
108
|
+
return saved
|
|
109
|
+
})
|
|
110
|
+
expect(result).toEqual({ ok: true })
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
it('says where a refusal was, so the page can point at the row', async () => {
|
|
114
|
+
const refusal = Response.json({ message: 'Validation failed.', errors: { unitPrice: ['Unit Price must be at least 1.'] }, at: { operation: 'create', panel: 'order-line', row: 'new-2' } }, { status: 422 })
|
|
115
|
+
const result = await withFetch(refusal, () => saveModelRecordWithRelated('order', 3, {}, [{ slug: 'order-line', create: [{ key: 'new-2', fields: { unitPrice: 0 } }], update: [], destroy: [] }]))
|
|
116
|
+
expect(result.ok).toBe(false)
|
|
117
|
+
if (result.ok)
|
|
118
|
+
return
|
|
119
|
+
expect(result.at).toEqual({ operation: 'create', panel: 'order-line', row: 'new-2' })
|
|
120
|
+
expect(result.errors).toEqual({ unitPrice: ['Unit Price must be at least 1.'] })
|
|
121
|
+
})
|
|
122
|
+
})
|