diff --git a/backend/src/catalog.mjs b/backend/src/catalog.mjs index 9981fed..4b810bb 100644 --- a/backend/src/catalog.mjs +++ b/backend/src/catalog.mjs @@ -69,6 +69,7 @@ export async function loadCatalog() { const here = d.locationOverrides?.find((x) => x.locationId === SQUARE_LOCATION_ID); const name = o.itemData.variations.length > 1 ? `${o.itemData.name} (${d.name})` : o.itemData.name; info.set(v.id, { + itemId: o.id, name, tracked: Boolean(here?.trackInventory ?? d.trackInventory), soldOut: Boolean(here?.soldOut), @@ -113,3 +114,9 @@ export async function shipWeights(lines) { } return { weights, missing }; } + +// Square ITEM ids for the variations in a cart, for clearing /p/ caches and IndexNow after a sale. +export async function itemIdsFor(lines) { + await loadCatalog(); + return [...new Set(lines.map((l) => cache.info.get(l.variationId)?.itemId).filter(Boolean))]; +} diff --git a/backend/src/checkout.mjs b/backend/src/checkout.mjs index c2f8b6c..63ac114 100644 --- a/backend/src/checkout.mjs +++ b/backend/src/checkout.mjs @@ -3,9 +3,10 @@ import { randomUUID } from "node:crypto"; import { SQUARE_LOCATION_ID, square } from "./config.mjs"; import { respond, EMAIL_RE } from "./http.mjs"; -import { checkStock, shipWeights, unknownLines } from "./catalog.mjs"; +import { checkStock, itemIdsFor, shipWeights, unknownLines } from "./catalog.mjs"; import { shippingCents } from "./shipping.mjs"; import { recordSale } from "./stock.mjs"; +import { afterSale } from "./notify-sale.mjs"; const MAX_LINES = 20; const MAX_QTY = 10; @@ -262,12 +263,14 @@ export async function checkout(b) { const saleAt = Date.now(); const { payment } = await square().payments.complete({ paymentId: auth.id }); recordSale(b.lines, saleAt); + await afterSale(await itemIdsFor(b.lines)); return respond(200, { orderId: order.id, total, status: payment.status, receiptUrl: payment.receiptUrl }); } catch (err) { // The charge may have gone through even though the call failed (e.g. a timeout on the reply). const status = await paymentStatus(auth.id); if (status?.status === "COMPLETED") { recordSale(b.lines, Date.now()); + await afterSale(await itemIdsFor(b.lines)); return respond(200, { orderId: order.id, total, status: status.status, receiptUrl: status.receiptUrl }); } console.error("CHECKOUT_FAILED after authorising; releasing the hold", order.id, err?.message); diff --git a/backend/src/handler.mjs b/backend/src/handler.mjs index d50c3bc..2b789f8 100644 --- a/backend/src/handler.mjs +++ b/backend/src/handler.mjs @@ -4,8 +4,9 @@ // POST /api/checkout -> order + authorise + stock re-check + charge (checkout.mjs) // POST /api/subscribe -> email signup into the Square customer directory (subscribe.mjs) // GET /p/ -> the page for one piece, in the site's own shell (piece.mjs) -// GET /p/sitemap.xml -> every piece's address, for search engines (piece.mjs) -// GET /p/feed.xml -> Atom feed of available pieces, for RSS and Pinterest (piece.mjs) +// GET /p/sitemap.xml -> every piece's address, for search engines (piece.mjs) +// GET /p/feed.xml -> Atom feed of available pieces, for RSS readers (piece.mjs) +// GET /p/merchant.xml -> RSS 2.0 product feed for Google Merchant Center and Pinterest Catalogs (piece.mjs) // Each function serves only the routes in ROUTES (the template gives checkout its own function). import { SquareError } from "square"; import { respond, clientIp } from "./http.mjs"; @@ -13,7 +14,7 @@ import { loadCatalog } from "./catalog.mjs"; import { quote, checkout, declineMessage } from "./checkout.mjs"; import { subscribe, _resetLimits as resetSubscribeLimits } from "./subscribe.mjs"; import { _resetSales } from "./stock.mjs"; -import { piece, sitemap, feed } from "./piece.mjs"; +import { piece, sitemap, feed, merchantFeed } from "./piece.mjs"; const routes = new Set((process.env.ROUTES ?? "catalog,quote,subscribe,checkout,piece").split(",").map((r) => r.trim())); const posts = { "/api/quote": quote, "/api/checkout": checkout, "/api/subscribe": subscribe }; @@ -42,6 +43,7 @@ export async function handler(event) { // decoded, since a malformed escape like /p/%E0 would throw and be answered as an unhandled error. if (method === "GET" && routes.has("piece") && path === "/p/sitemap.xml") return await sitemap(); if (method === "GET" && routes.has("piece") && path === "/p/feed.xml") return await feed(); + if (method === "GET" && routes.has("piece") && path === "/p/merchant.xml") return await merchantFeed(); if (method === "GET" && routes.has("piece") && path?.startsWith("/p/")) return await piece(path.slice(3)); if (method === "POST" && posts[path]) { const body = readBody(event); diff --git a/backend/src/notify-sale.mjs b/backend/src/notify-sale.mjs new file mode 100644 index 0000000..220e469 --- /dev/null +++ b/backend/src/notify-sale.mjs @@ -0,0 +1,84 @@ +// Best-effort post-sale refresh: clears CloudFront's 5-minute /p/* cache for sold pieces and their +// feeds, and notifies IndexNow on production. Never throws, so a CDN or IndexNow hiccup cannot affect +// an already-completed payment response. +const INDEXNOW_KEY = "b8f4c2e9a1d740639e5c82b1f7a3d904"; + +let cfClientPromise; +function cloudFrontInvalidate(distributionId, paths) { + cfClientPromise ??= (async () => { + const pkg = "@aws-sdk/client-cloudfront"; + const { CloudFrontClient, CreateInvalidationCommand } = await import(pkg); + const client = new CloudFrontClient({ region: "us-east-1" }); + return (distId, items) => + client.send( + new CreateInvalidationCommand({ + DistributionId: distId, + InvalidationBatch: { + CallerReference: `sale-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, + Paths: { Quantity: items.length, Items: items }, + }, + }), + { abortSignal: AbortSignal.timeout(3_000) }, + ); + })().catch((err) => { + cfClientPromise = undefined; + throw err; + }); + return cfClientPromise.then((send) => send(distributionId, paths)); +} + +let customInvalidator = null; +/** @param {((distId: string, paths: string[]) => Promise) | null} fn */ +export function _setInvalidator(fn) { + customInvalidator = fn; +} + +/** + * Clears cached piece pages/feeds and pings IndexNow after a completed checkout. + * @param {string[]} itemIds Square catalog ITEM ids included in the completed order + */ +export async function afterSale(itemIds) { + const ids = [...new Set(itemIds.filter(Boolean))]; + if (!ids.length) return; + + const distId = (process.env.DISTRIBUTION_ID ?? "").trim(); + const origin = (process.env.ALLOWED_ORIGIN ?? "").replace(/\/$/, ""); + const prod = process.env.SQUARE_ENV === "production" && /^https:\/\/[^/]+$/.test(origin); + + const tasks = []; + if (distId) { + const paths = [...ids.map((id) => `/p/${encodeURIComponent(id)}`), "/p/sitemap.xml", "/p/feed.xml", "/p/merchant.xml"]; + const run = customInvalidator ?? cloudFrontInvalidate; + tasks.push( + run(distId, paths).catch((err) => { + console.error("SALE_INVALIDATE_FAILED", err?.message ?? err); + }), + ); + } + + if (prod) { + const host = new URL(origin).host; + const urlList = [`${origin}/`, `${origin}/shop.html`, ...ids.map((id) => `${origin}/p/${encodeURIComponent(id)}`)]; + tasks.push( + fetch("https://api.indexnow.org/indexnow", { + method: "POST", + headers: { "content-type": "application/json; charset=utf-8" }, + body: JSON.stringify({ + host, + key: INDEXNOW_KEY, + keyLocation: `${origin}/${INDEXNOW_KEY}.txt`, + urlList, + }), + signal: AbortSignal.timeout(3_000), + }) + .then((res) => { + if (res.status >= 400) console.error("SALE_INDEXNOW_FAILED", `HTTP ${res.status}`); + }) + .catch((err) => { + console.error("SALE_INDEXNOW_FAILED", err?.message ?? err); + }), + ); + } + + if (tasks.length) await Promise.allSettled(tasks); +} diff --git a/backend/src/piece-page.mjs b/backend/src/piece-page.mjs index bf8e8fc..6dfa492 100644 --- a/backend/src/piece-page.mjs +++ b/backend/src/piece-page.mjs @@ -210,6 +210,19 @@ export function parseDimensions(item) { return base; } +/** WA Zone 3 and US Zone 8 label ceilings in whole dollars for one packed parcel, or null when unshippable. */ +function shippingRatesFor(shipLb) { + if (!(shipLb > 0)) return null; + const maxForZone = (zone) => { + const ups = labelDollars("ups", zone, shipLb); + if (ups === null) return null; + return Math.ceil(Math.max(ups, labelDollars("usps", zone, shipLb) ?? 0)); + }; + const wa = maxForZone(3); + const us = maxForZone(8); + return wa === null || us === null ? null : { wa, us }; +} + /** OfferShippingDetails for one parcel (WA Zone 3 + US Zone 8 ceiling + packed weight), or doesNotShip when pickup-only. */ function shippingDetailsFor(shipLb) { if (!(shipLb > 0)) { @@ -219,14 +232,9 @@ function shippingDetailsFor(shipLb) { shippingDestination: { "@type": "DefinedRegion", addressCountry: "US" }, }; } - const maxForZone = (zone) => { - const ups = labelDollars("ups", zone, shipLb); - if (ups === null) return null; - return Math.ceil(Math.max(ups, labelDollars("usps", zone, shipLb) ?? 0)); - }; - const wa = maxForZone(3); - const us = maxForZone(8); - if (wa === null || us === null) return null; + const rates = shippingRatesFor(shipLb); + if (!rates) return null; + const { wa, us } = rates; const handlingTime = { "@type": "QuantitativeValue", minValue: 1, maxValue: 2, unitCode: "DAY" }; const weight = qvLb(shipLb); return [ @@ -488,3 +496,67 @@ export function piecesFeed(items, site) { `\n` ); } + +/** + * Google Merchant Center + Pinterest Catalogs RSS 2.0 XML product feed (/p/merchant.xml). + * Lists every unarchived piece with live availability (in_stock / out_of_stock), explicit + * identifier_exists=no for one-of-a-kind handmade work, Google Product Taxonomy ID, 3D dimensions, + * item + shipping weights, and WA / US Ground shipping rates. + */ +export function piecesMerchantFeed(items, site) { + const entries = items.flatMap((item) => { + const many = item.variations.length > 1; + const url = `${site}/p/${item.id}`; + const photos = photosOf(item); + const dims = parseDimensions(item); + const gpc = googleCategoryFor(item); + const rates = shippingRatesFor(item.shipLb); + const desc = item.description?.trim() || metaDescription(item); + return item.variations.map((v) => { + const id = many ? `${item.id}-${v.id}` : item.id; + const title = many ? `${item.name} (${v.name})` : item.name; + const fields = [ + `${esc(id)}`, + ...(many ? [`${esc(item.id)}`] : []), + `${esc(title)}`, + `${esc(desc)}`, + `${esc(url)}`, + ...(photos[0] ? [`${esc(site + sized(photos[0], 1200, "jpeg"))}`] : []), + ...photos.slice(1, 11).map((p) => `${esc(site + sized(p, 1200, "jpeg"))}`), + `${isOpen(v) ? "in_stock" : "out_of_stock"}`, + `${(v.price / 100).toFixed(2)} ${esc(v.currency ?? "USD")}`, + `new`, + `${SITE_NAME}`, + `no`, + `${esc(gpc.codeValue)}`, + ...(item.category ? [`${esc(item.category)}`] : []), + `${esc(materialOf(item))}`, + ...(dims.depth ? [`${+dims.depth.toFixed(3)} in`] : []), + ...(dims.width ? [`${+dims.width.toFixed(3)} in`] : []), + ...(dims.height ? [`${+dims.height.toFixed(3)} in`] : []), + ...(item.itemLb > 0 ? [`${+Number(item.itemLb).toFixed(2)} lb`] : []), + ...(item.shipLb > 0 ? [`${+Number(item.shipLb).toFixed(2)} lb`] : []), + ...(rates + ? [ + `1`, + `2`, + `USWAGround${rates.wa.toFixed(2)} USD13`, + `USGround${rates.us.toFixed(2)} USD16`, + ] + : []), + ]; + return ` \n ${fields.join("\n ")}\n `; + }); + }); + return ( + `\n` + + `\n` + + ` \n` + + ` ${SITE_NAME}\n` + + ` ${esc(`${site}/shop.html`)}\n` + + ` One-of-a-kind handmade porcelain and stoneware pottery fired in Tacoma, Washington.\n` + + `${entries.join("\n")}\n` + + ` \n` + + `\n` + ); +} diff --git a/backend/src/piece.mjs b/backend/src/piece.mjs index 5308e81..a893e93 100644 --- a/backend/src/piece.mjs +++ b/backend/src/piece.mjs @@ -3,7 +3,7 @@ // under /p/ may only list pages under /p/, which is all it needs, and the /p/* route is already here. import { ALLOWED_ORIGIN } from "./config.mjs"; import { loadCatalog } from "./catalog.mjs"; -import { renderPiece, gonePage, piecesSitemap, piecesFeed } from "./piece-page.mjs"; +import { renderPiece, gonePage, piecesSitemap, piecesFeed, piecesMerchantFeed } from "./piece-page.mjs"; const site = () => (ALLOWED_ORIGIN === "*" ? "" : ALLOWED_ORIGIN); const reply = (status, type, body, cache, extra = {}) => ({ @@ -63,3 +63,7 @@ export async function sitemap() { export async function feed() { return reply(200, "application/atom+xml", piecesFeed(await loadCatalog(), site()), "public, max-age=300"); } + +export async function merchantFeed() { + return reply(200, "application/xml", piecesMerchantFeed(await loadCatalog(), site()), "public, max-age=300"); +} diff --git a/backend/template.yaml b/backend/template.yaml index 93a93b0..0f30964 100644 --- a/backend/template.yaml +++ b/backend/template.yaml @@ -4,6 +4,10 @@ Description: > Square catalog + checkout API for Updraft Pottery Studio (one stack per stage: updraft-api, updraft-staging-api). Deployed by scripts/deploy-api.mjs from deploy/stages.json. +Metadata: + AWSToolsMetrics: + AWSAgentToolkit: aws-cloudformation@3 + Parameters: SquareTokenParam: { Type: String, Description: "SSM SecureString holding the Square access token, e.g. /updraft/prod/square-access-token" } SquareLocationId: { Type: String } @@ -17,6 +21,10 @@ Parameters: Default: arn:aws:iam::724654236968:policy/updraft-lambda-ssm-read Description: Admin-created managed policy allowing ssm:GetParameter on /updraft/* AlertEmail: { Type: String, Default: "", Description: "Where alarms are emailed (SNS asks to confirm once). Empty = no alarms." } + DistributionId: + Type: String + Default: "" + Description: "Optional CloudFront distribution ID so completed checkouts immediately invalidate /p/* caches" Conditions: CapConcurrency: !Not [!Equals [!Ref ApiConcurrency, 0]] @@ -74,7 +82,9 @@ Resources: Timeout: 30 LoggingConfig: { LogGroup: !Ref CheckoutLogs } Environment: - Variables: { ROUTES: checkout } # merged with Globals + Variables: + ROUTES: checkout # merged with Globals + DISTRIBUTION_ID: !Ref DistributionId FunctionUrlConfig: AuthType: AWS_IAM # see Api diff --git a/backend/test/checkout-flow.test.mjs b/backend/test/checkout-flow.test.mjs index 5389303..1927de4 100644 --- a/backend/test/checkout-flow.test.mjs +++ b/backend/test/checkout-flow.test.mjs @@ -280,3 +280,60 @@ test("a shipping quote needs the destination before it has a total", async () => const pickup = await post({ lines, fulfillment: "pickup" }, "/api/quote"); assert.deepEqual([pickup.body.shipping, pickup.body.total], [0, 5000]); }); + +import { _setInvalidator } from "../src/notify-sale.mjs"; +test("a completed sale clears /p/* caches and pings IndexNow on production without ever failing checkout", async (t) => { + const prev = { + dist: process.env.DISTRIBUTION_ID, + env: process.env.SQUARE_ENV, + origin: process.env.ALLOWED_ORIGIN, + }; + t.after(() => { + _setInvalidator(null); + for (const [k, v] of [ + ["DISTRIBUTION_ID", prev.dist], + ["SQUARE_ENV", prev.env], + ["ALLOWED_ORIGIN", prev.origin], + ]) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }); + + const invalidations = []; + const indexNowBodies = []; + _setInvalidator(async (distId, paths) => { + invalidations.push([distId, paths]); + }); + t.mock.method(globalThis, "fetch", async (url, init) => { + if (url === "https://api.indexnow.org/indexnow") { + indexNowBodies.push(JSON.parse(String(init?.body))); + return new Response("", { status: 202 }); + } + throw new Error(`unexpected fetch: ${url}`); + }); + + process.env.DISTRIBUTION_ID = "EDIST123"; + process.env.SQUARE_ENV = "production"; + process.env.ALLOWED_ORIGIN = "https://updraftpotterystudio.com"; + + fresh(); + assert.equal((await post(body("sale-1"))).status, 200); + assert.deepEqual(invalidations, [["EDIST123", ["/p/I1", "/p/sitemap.xml", "/p/feed.xml", "/p/merchant.xml"]]]); + assert.equal(indexNowBodies.length, 1); + assert.deepEqual(indexNowBodies[0].urlList, [ + "https://updraftpotterystudio.com/", + "https://updraftpotterystudio.com/shop.html", + "https://updraftpotterystudio.com/p/I1", + ]); + + // Even if both invalidation and IndexNow throw, checkout still returns 200. + _setInvalidator(async () => { + throw new Error("cdn down"); + }); + t.mock.method(globalThis, "fetch", async () => { + throw new Error("indexnow down"); + }); + fresh(); + assert.equal((await post(body("sale-2"))).status, 200); +}); diff --git a/backend/test/shop-pages.test.mjs b/backend/test/shop-pages.test.mjs index 83d357e..c68a198 100644 --- a/backend/test/shop-pages.test.mjs +++ b/backend/test/shop-pages.test.mjs @@ -367,4 +367,25 @@ test("the pieces' sitemap and Atom feed list pieces with dates and photos", asyn assert.match(atom.headers["content-type"], /application\/atom\+xml/); assert.ok(atom.body.includes("Celadon bowl · $65.00")); assert.ok(atom.body.includes('rel="enclosure" type="image/jpeg"')); + + const merchant = await get("/p/merchant.xml"); + assert.equal(merchant.statusCode, 200); + assert.match(merchant.headers["content-type"], /application\/xml/); + assert.ok(merchant.body.includes('xmlns:g="http://base.google.com/ns/1.0"')); + assert.ok(merchant.body.includes("I1")); + assert.ok(merchant.body.includes("no")); + assert.ok(merchant.body.includes("in_stock")); + assert.ok(merchant.body.includes("65.00 USD")); + assert.ok(merchant.body.includes("3498")); + assert.ok(merchant.body.includes("Bowls")); + assert.ok(merchant.body.includes("Porcelain")); + assert.ok(merchant.body.includes("8 in")); + assert.ok(merchant.body.includes("8 in")); + assert.ok(merchant.body.includes("3.5 in")); + assert.ok(merchant.body.includes("2.25 lb")); + assert.ok(merchant.body.includes("14 lb")); + assert.ok(merchant.body.includes("WAGround33.00 USD")); + assert.ok(merchant.body.includes("USGround52.00 USD")); + assert.equal([...merchant.body.matchAll(//g)].length, 1); + assert.equal([...merchant.body.matchAll(//g)].length, 1); }); diff --git a/deploy/README.md b/deploy/README.md index 6b3ede4..6d7438f 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -14,8 +14,8 @@ which only reaches resources named `updraft-*`, parameters under `/updraft/`, an | Piece | What | |---|---| -| site stack ([`site.yaml`](site.yaml)) | Private S3 bucket, CloudFront, HTTPS certificate, security headers, and a CloudFront Function for canonical 301 redirects (`www` → apex, `/index.html` → `/`, `/shop` → `/shop.html`, etc., enabled automatically once `updraft-publish-ssm` includes `cloudfront:*Function*`); `/api/checkout`, `/api/img` (cached a year) and `/api/*` routed to the functions through origin access control, so the functions only accept requests CloudFront signed; `/p/*` piece pages, `/p/sitemap.xml` and `/p/feed.xml` (cached 5 minutes) go to `Api`. Staging's DNS record is in the stack and carries `X-Robots-Tag: noindex`; production includes the Bing verification CNAME. | -| API stack ([`../backend/template.yaml`](../backend/template.yaml)) | `Api` (catalog, tax quote, signup, `/p/` piece pages, drawn in the published `piece-shell.html`) and `Checkout` (one order at a time, so a one-of-a-kind piece can't sell twice), from one bundle; `Images` (shop photos resized with sharp, its own package). Square token read from SSM. 30-day log groups, and alarms emailed through SNS. | +| site stack ([`site.yaml`](site.yaml)) | Private S3 bucket, CloudFront, HTTPS certificate, security headers, CloudFront standard logs v2 (`updraft-logs*` S3 bucket, 90-day expiry; read with `npm run seo-logs`), and a CloudFront Function for canonical 301 redirects (`www` → apex, `/index.html` → `/`, `/shop` → `/shop.html`, etc.); `/api/checkout`, `/api/img` (cached a year) and `/api/*` routed to the functions through origin access control, so the functions only accept requests CloudFront signed; `/p/*` piece pages, `/p/sitemap.xml`, `/p/feed.xml` and `/p/merchant.xml` (cached 5 minutes) go to `Api`. Staging's DNS record is in the stack and carries `X-Robots-Tag: noindex`; production includes the Bing verification CNAME (use `node scripts/pinterest-verify.mjs ` to add Pinterest's apex TXT value alongside Google Search Console's). | +| API stack ([`../backend/template.yaml`](../backend/template.yaml)) | `Api` (catalog, tax quote, signup, `/p/` piece pages and feeds, drawn in the published `piece-shell.html`) and `Checkout` (one order at a time, so a one-of-a-kind piece can't sell twice; invalidates `/p/*` caches and notifies IndexNow on sale), from one bundle; `Images` (shop photos resized with sharp, its own package). Square token read from SSM. 30-day log groups, and alarms emailed through SNS. | | Square token | SSM Parameter Store SecureString `/updraft//square-access-token` | | Production DNS | apex + `www` A/AAAA aliases to CloudFront, switched with `node scripts/dns-cutover.mjs` | diff --git a/deploy/copper-bell-publish-policy.json b/deploy/copper-bell-publish-policy.json index 1139059..7642b9d 100644 --- a/deploy/copper-bell-publish-policy.json +++ b/deploy/copper-bell-publish-policy.json @@ -29,6 +29,7 @@ "cloudfront:*Invalidation*", "cloudfront:*CachePolic*", "cloudfront:*Tag*", + "cloudfront:AllowVendedLogDeliveryForResource", "acm:*Certificate*", "acm:*Tags*", "route53:Get*", @@ -37,6 +38,7 @@ "cloudformation:GetTemplateSummary", "logs:DescribeLogGroups", "logs:DescribeMetricFilters", + "logs:*Delivery*", "ssm:DescribeParameters", "cloudwatch:DescribeAlarms" ], @@ -98,7 +100,8 @@ ], "Resource": [ "arn:aws:logs:us-east-1:724654236968:log-group:/updraft/*", - "arn:aws:logs:us-east-1:724654236968:log-group:/aws/lambda/updraft-*" + "arn:aws:logs:us-east-1:724654236968:log-group:/aws/lambda/updraft-*", + "arn:aws:logs:us-east-1:724654236968:delivery*" ] }, { diff --git a/deploy/lambda-ssm-read-policy.json b/deploy/lambda-ssm-read-policy.json index 94bdd9f..b64b1df 100644 --- a/deploy/lambda-ssm-read-policy.json +++ b/deploy/lambda-ssm-read-policy.json @@ -6,6 +6,12 @@ "Effect": "Allow", "Action": "ssm:GetParameter", "Resource": "arn:aws:ssm:us-east-1:724654236968:parameter/updraft/*" + }, + { + "Sid": "InvalidatePiecePagesOnSale", + "Effect": "Allow", + "Action": "cloudfront:CreateInvalidation", + "Resource": "arn:aws:cloudfront::724654236968:distribution/*" } ] } diff --git a/deploy/site.yaml b/deploy/site.yaml index 006f57e..333a04a 100644 --- a/deploy/site.yaml +++ b/deploy/site.yaml @@ -5,6 +5,10 @@ Description: > Lambda functions, which only CloudFront can call (origin access control of type lambda). Production DNS is switched by scripts/dns-cutover.mjs; staging's record is part of this stack (ManageDns). +Metadata: + AWSToolsMetrics: + AWSAgentToolkit: aws-cloudformation@3 + Parameters: DomainName: { Type: String, Default: updraftpotterystudio.com } HostedZoneId: { Type: String, Default: Z88UBBDI22ZJ9, Description: Route 53 zone for DomainName (used for certificate validation) } @@ -29,6 +33,11 @@ Parameters: Default: "false" AllowedValues: ["true", "false"] Description: "Attach the CloudFront Function that 301-redirects www, /index.html, and extensionless page paths" + EnableAccessLogs: + Type: String + Default: "false" + AllowedValues: ["true", "false"] + Description: "Deliver CloudFront standard logs v2 (JSON) to a private S3 bucket with 90-day retention" Conditions: HasApi: !Not [!Equals [!Ref ApiDomain, ""]] @@ -43,6 +52,7 @@ Conditions: Prod: !Equals [!Ref NameSuffix, ""] DisallowRobots: !Equals [!Ref Indexable, "false"] EdgeRedirects: !Equals [!Ref EnableEdgeRedirects, "true"] + AccessLogs: !Equals [!Ref EnableAccessLogs, "true"] Resources: SiteBucket: @@ -408,8 +418,88 @@ Resources: TTL: "300" ResourceRecords: [verify.bing.com] + # Cookie-free CloudFront standard logs v2 (gzipped JSON lines) for search-bot crawls, top pages, and utm_source shares. + AccessLogsBucket: + Type: AWS::S3::Bucket + Condition: AccessLogs + DeletionPolicy: Retain + UpdateReplacePolicy: Retain + Properties: + BucketName: !Sub updraft-logs${NameSuffix}-${AWS::AccountId} + PublicAccessBlockConfiguration: { BlockPublicAcls: true, BlockPublicPolicy: true, IgnorePublicAcls: true, RestrictPublicBuckets: true } + OwnershipControls: { Rules: [{ ObjectOwnership: BucketOwnerEnforced }] } + BucketEncryption: { ServerSideEncryptionConfiguration: [{ ServerSideEncryptionByDefault: { SSEAlgorithm: AES256 } }] } + VersioningConfiguration: { Status: Enabled } + LifecycleConfiguration: + Rules: + - Id: ExpireAccessLogsAfter90Days + Status: Enabled + ExpirationInDays: 90 + NoncurrentVersionExpiration: { NoncurrentDays: 7 } + AbortIncompleteMultipartUpload: { DaysAfterInitiation: 7 } + + AccessLogsBucketPolicy: + Type: AWS::S3::BucketPolicy + Condition: AccessLogs + Properties: + Bucket: !Ref AccessLogsBucket + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: DenyInsecureTransport + Effect: Deny + Principal: "*" + Action: "s3:*" + Resource: [!GetAtt AccessLogsBucket.Arn, !Sub "${AccessLogsBucket.Arn}/*"] + Condition: + Bool: { "aws:SecureTransport": "false" } + - Sid: AWSLogDeliveryWrite + Effect: Allow + Principal: { Service: delivery.logs.amazonaws.com } + Action: s3:PutObject + Resource: !Sub "${AccessLogsBucket.Arn}/*" + Condition: + StringEquals: { "aws:SourceAccount": !Ref AWS::AccountId } + ArnLike: { "aws:SourceArn": !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:delivery-source:*" } + - Sid: AWSLogDeliveryCheck + Effect: Allow + Principal: { Service: delivery.logs.amazonaws.com } + Action: [s3:GetBucketAcl, s3:ListBucket] + Resource: !GetAtt AccessLogsBucket.Arn + Condition: + StringEquals: { "aws:SourceAccount": !Ref AWS::AccountId } + ArnLike: { "aws:SourceArn": !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:delivery-source:*" } + + AccessLogsSource: + Type: AWS::Logs::DeliverySource + Condition: AccessLogs + Properties: + Name: !Sub updraft-cf-logs-src${NameSuffix} + LogType: ACCESS_LOGS + ResourceArn: !Sub "arn:aws:cloudfront::${AWS::AccountId}:distribution/${Distribution}" + + AccessLogsDestination: + Type: AWS::Logs::DeliveryDestination + Condition: AccessLogs + DependsOn: AccessLogsBucketPolicy + Properties: + Name: !Sub updraft-cf-logs-dst${NameSuffix} + DeliveryDestinationType: S3 + DestinationResourceArn: !GetAtt AccessLogsBucket.Arn + OutputFormat: json + + AccessLogsDelivery: + Type: AWS::Logs::Delivery + Condition: AccessLogs + Properties: + DeliverySourceName: !Ref AccessLogsSource + DeliveryDestinationArn: !GetAtt AccessLogsDestination.Arn + Outputs: BucketName: { Value: !Ref SiteBucket } DistributionId: { Value: !Ref Distribution } DistributionDomain: { Value: !GetAtt Distribution.DomainName } CertificateArn: { Value: !Ref Certificate } + LogsBucketName: + Condition: AccessLogs + Value: !Ref AccessLogsBucket diff --git a/docs/seo-plan.md b/docs/seo-plan.md index ecad439..f2dccf9 100644 --- a/docs/seo-plan.md +++ b/docs/seo-plan.md @@ -2,16 +2,18 @@ This plan helps people find the studio and its pieces in search, and gives shared links and the newsletter more to work with. It was written on 16 October 2026 against master 6a9f848, after reading the site's build and backend and glazecalc's search plan (`glazecalc/docs/seo-plan.md`, ADR 16). Effort: S = under a day, M = one to three days, L = a week or more. Paths are from the repo root. -## Status: items 1–5, 7 & 12 built; item 6 (external search accounts) in progress +## Status: items 1–5, 7, 9, 10, 12 & 15 built; item 6 (external search accounts) in progress Built across `seo-pieces` (PRs #9 / #11) and the follow-up SEO & breadcrumbs rounds: -- **Piece pages, sitemap & Atom feed (`/p/`, `/p/sitemap.xml`, `/p/feed.xml`):** Live in `piece-shell.html` with `Add to cart`, progressive `Share this piece`, `Home › Shop › › ` breadcrumbs, `Product` JSON-LD (including Google Product Taxonomy `CategoryCode` + shop `category`, 3D inch `depth`/`width`/`height` dimensions, unpacked `Product.weight` from `item_lb` in `LBR`, `OfferShippingDetails` with WA + US rates and packed `weight` from `ship_lb` in `LBR` or `doesNotShip`, `material`, `countryOfOrigin`, `availableDeliveryMethod`, and `MerchantReturnPolicy`), `` entries in `/p/sitemap.xml`, and an Atom 1.0 feed of available pieces at `/p/feed.xml` (for RSS and Pinterest). -- **Canonical 301 redirects & `X-Robots-Tag`:** CloudFront Function in `deploy/site.yaml` (auto-enabled once `updraft-publish-ssm` includes `cloudfront:*Function*`, mirrored in `scripts/serve.mjs`) `301`-redirects `www.*` → apex, `/index.html` → `/`, and extensionless paths (`/shop` → `/shop.html`, etc.). `/api/*`, `410` responses, and staging responses carry `X-Robots-Tag: noindex`. +- **Piece pages, sitemap, Atom feed & Merchant Center XML feed (`/p/`, `/p/sitemap.xml`, `/p/feed.xml`, `/p/merchant.xml`):** Live in `piece-shell.html` with `Add to cart`, progressive `Share this piece` (`?utm_source=share`), `Home › Shop › › ` breadcrumbs, `Product` JSON-LD (including Google Product Taxonomy `CategoryCode` + shop `category`, 3D inch `depth`/`width`/`height` dimensions, unpacked `Product.weight` from `item_lb` in `LBR`, `OfferShippingDetails` with WA + US rates and packed `weight` from `ship_lb` in `LBR` or `doesNotShip`, `material`, `countryOfOrigin`, `availableDeliveryMethod`, and `MerchantReturnPolicy`), `` entries in `/p/sitemap.xml`, an Atom 1.0 feed at `/p/feed.xml`, and a Google Shopping RSS 2.0 feed at `/p/merchant.xml` (with `identifier_exists=no`, dimensions, weights, and shipping for Google Merchant Center and Pinterest Catalogs). +- **Canonical 301 redirects & `X-Robots-Tag`:** Live in production (`updraft-publish-ssm` + `EnableEdgeRedirects=true` on staging and prod, mirrored in `scripts/serve.mjs`): CloudFront Function `301`-redirects `www.*` → apex, `/index.html` → `/`, and extensionless paths (`/shop` → `/shop.html`, etc.). `/api/*`, `410` responses, and staging responses carry `X-Robots-Tag: noindex`. - **Site-wide breadcrumbs & publish-time prerendering:** Every static subpage renders `