From e7a3d95d25fa820897059694d7246d3df62a1b46 Mon Sep 17 00:00:00 2001 From: Ronal Sagala Date: Fri, 20 Nov 2026 02:56:46 +0700 Subject: [PATCH 1/2] fix: launch-readiness hardening for production - Security headers on the live web app: Coolify serves dist/ with `serve`, which ignores Netlify's _headers. Add public/serve.json with nosniff, frame DENY, referrer/permissions policy, HSTS and the same cache rules. - Fresh database self-provisions: the migration runner applies the foundation SQL (base-schema, production-bootstrap) when public.stores is missing, so a new project or disaster-recovery deploy no longer crashes on migration 20260430_0002. Copies live in backend/bootstrap (the Docker context is backend/ only); a test keeps them identical to database/. - Rate-limit /api/auth/demo-login: each call bcrypt-hashes and reseeds the demo accounts, and it was the only unthrottled auth endpoint. - npm audit fix (non-breaking): clears the critical @capacitor/android and proxy-addr advisories and the body-parser DoS advisory. - Tests: e2e-local runs only its own spec (the offline spec needs the production build and has its own runner); the fresh-db smoke ignores the demo store's seeded inventory. Co-Authored-By: Claude Opus 5.5 --- backend/Dockerfile | 1 + backend/bootstrap/0001_base-schema.sql | 271 +++++++++ .../bootstrap/0002_production-bootstrap.sql | 564 ++++++++++++++++++ backend/package-lock.json | 46 +- backend/scripts/run-migrations.mjs | 18 + backend/src/core/bootstrapSql.test.ts | 17 + backend/src/routes/auth.ts | 5 +- package-lock.json | 57 +- public/serve.json | 27 + scripts/e2e-local.mjs | 2 +- scripts/smoke-local-fresh-db.mjs | 3 +- 11 files changed, 962 insertions(+), 49 deletions(-) create mode 100644 backend/bootstrap/0001_base-schema.sql create mode 100644 backend/bootstrap/0002_production-bootstrap.sql create mode 100644 backend/src/core/bootstrapSql.test.ts create mode 100644 public/serve.json diff --git a/backend/Dockerfile b/backend/Dockerfile index 36aef3b..60070fd 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -20,6 +20,7 @@ RUN npm ci --omit=dev && npm cache clean --force COPY --from=build /app/dist ./dist COPY migrations ./migrations COPY scripts ./scripts +COPY bootstrap ./bootstrap USER node EXPOSE 8787 diff --git a/backend/bootstrap/0001_base-schema.sql b/backend/bootstrap/0001_base-schema.sql new file mode 100644 index 0000000..a72cba7 --- /dev/null +++ b/backend/bootstrap/0001_base-schema.sql @@ -0,0 +1,271 @@ +-- ############################################################################ +-- ## KaffePOS BASE SCHEMA — foundation tables for a FRESH database. ## +-- ## ## +-- ## Why this file exists: the original stores/profiles/... tables were ## +-- ## created on the legacy hosted database and were never captured in the ## +-- ## repo. Versioned migrations (backend/migrations/) and the runtime ## +-- ## bootstrap (backend/src/schema-bootstrap.ts) both ASSUME these tables ## +-- ## exist, so a brand-new database could not be provisioned from the repo ## +-- ## alone (breaking disaster recovery and new-environment setup). ## +-- ## ## +-- ## Provisioning order for a fresh database: ## +-- ## 1. psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/base-schema.sql +-- ## 2. DATABASE_URL=... npm --prefix backend run migrate ## +-- ## 3. Start the backend (bootstrapAllSchemas creates remaining tables) ## +-- ## ## +-- ## Idempotent: safe to run on an existing database (all IF NOT EXISTS). ## +-- ## Column shapes are reconstructed from the code's column constants ## +-- ## (backend/src/core/helpers.ts) and insert statements, and verified by ## +-- ## booting the app against a scratch database. ## +-- ############################################################################ + +create extension if not exists pgcrypto; + +-- ── Identity ──────────────────────────────────────────────────────────────── +create table if not exists public.profiles ( + id uuid primary key default gen_random_uuid(), + username varchar, + display_name varchar, + email varchar, + avatar_url text, + tier varchar not null default 'free', + tier_expires_at timestamptz, + is_pro boolean not null default false, + pro_plan varchar, + pro_order_id varchar, + pro_activated_at timestamptz, + pro_expires_at timestamptz, + role varchar not null default 'owner', + account_status varchar not null default 'active', + permissions jsonb, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); +create unique index if not exists profiles_username_unique_idx on public.profiles (lower(username)) where username is not null; +create unique index if not exists profiles_email_unique_idx on public.profiles (lower(email)) where email is not null; + +create table if not exists public.stores ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null references public.profiles(id) on delete cascade, + store_name varchar not null, + address text, + whatsapp varchar, + tax_percent numeric not null default 0, + receipt_header text, + receipt_footer text, + logo_url text, + logo_base64 text, + logo_position varchar, + logo_size varchar, + show_logo_on_receipt boolean not null default false, + currency varchar not null default 'IDR', + tagline text, + email varchar, + website varchar, + paper_width varchar, + receipt_font_size varchar, + receipt_show_address boolean not null default true, + receipt_show_whatsapp boolean not null default true, + receipt_show_tax boolean not null default true, + receipt_show_cashier boolean not null default true, + receipt_show_trx_id boolean not null default true, + receipt_divider varchar, + receipt_custom_line1 text, + receipt_custom_line2 text, + timezone varchar, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); +create index if not exists stores_owner_id_idx on public.stores (owner_id); + +-- ── Catalog & sales ──────────────────────────────────────────────────────── +create table if not exists public.menu_items ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + name varchar not null, + price numeric not null default 0, + category varchar, + image_url text, + description text, + is_available boolean not null default true, + sort_order integer not null default 0, + recipe jsonb, + variants jsonb, + modifiers jsonb, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); +create index if not exists menu_items_store_id_idx on public.menu_items (store_id); + +create table if not exists public.transactions ( + id text primary key, + store_id uuid not null references public.stores(id) on delete cascade, + date timestamptz not null default now(), + items jsonb not null default '[]'::jsonb, + subtotal numeric not null default 0, + discount numeric not null default 0, + discount_label varchar, + tax numeric not null default 0, + total numeric not null default 0, + cogs numeric, + paid numeric not null default 0, + change numeric not null default 0, + method varchar not null default 'Tunai', + customer_name varchar, + cashier varchar, + note text, + is_void boolean not null default false, + void_reason text, + void_at timestamptz, + void_by varchar, + created_at timestamptz not null default now() +); +create index if not exists transactions_store_date_idx on public.transactions (store_id, date desc); + +create table if not exists public.expenses ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + date timestamptz not null default now(), + description text not null default '', + amount numeric not null default 0, + category varchar, + cashier varchar, + source varchar, + created_at timestamptz not null default now() +); +create index if not exists expenses_store_date_idx on public.expenses (store_id, date desc); + +create table if not exists public.cash_flow ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + date timestamptz not null default now(), + type varchar not null check (type in ('in', 'out')), + amount numeric not null default 0, + description text, + cashier varchar, + created_at timestamptz not null default now() +); +create index if not exists cash_flow_store_date_idx on public.cash_flow (store_id, date desc); + +create table if not exists public.cash_register ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + date timestamptz not null default now(), + amount numeric not null default 0, + note text, + opened_by varchar, + created_at timestamptz not null default now() +); +create index if not exists cash_register_store_date_idx on public.cash_register (store_id, date desc); + +create table if not exists public.store_accounts ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + username varchar not null, + password_hash text not null, + role varchar not null default 'cashier', + is_active boolean not null default true, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (store_id, username) +); + +-- ── Billing ──────────────────────────────────────────────────────────────── +create table if not exists public.subscriptions ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references public.profiles(id) on delete cascade, + store_id uuid references public.stores(id) on delete set null, + tier varchar, + period varchar, + plan varchar, + billing_cycle varchar, + status varchar not null default 'active', + activated_at timestamptz, + expires_at timestamptz, + amount_paid numeric not null default 0, + payment_amount numeric, + payment_method varchar, + payment_note text, + payment_ref varchar, + converted_from_subscription_id uuid, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); +create index if not exists subscriptions_user_id_idx on public.subscriptions (user_id); +create index if not exists subscriptions_payment_ref_idx on public.subscriptions (payment_ref); + +create table if not exists public.payment_history ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references public.profiles(id) on delete cascade, + subscription_id uuid references public.subscriptions(id) on delete set null, + plan varchar, + billing_cycle varchar, + amount numeric not null default 0, + payment_method varchar, + payment_note text, + payment_ref varchar, + status varchar not null default 'success', + paid_at timestamptz, + created_at timestamptz not null default now() +); +create index if not exists payment_history_user_id_idx on public.payment_history (user_id); +create index if not exists payment_history_payment_ref_idx on public.payment_history (payment_ref); + +-- ── Auth hardening ───────────────────────────────────────────────────────── +create table if not exists public.admin_mfa_settings ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references public.profiles(id) on delete cascade, + secret text not null, + is_enabled boolean not null default false, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (user_id) +); + +create table if not exists public.auth_account_lockouts ( + id uuid primary key default gen_random_uuid(), + email varchar not null, + user_id uuid, + failed_attempts integer not null default 0, + last_failed_at timestamptz, + locked_until timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (email) +); + +create table if not exists public.email_verification_codes ( + id uuid primary key default gen_random_uuid(), + email varchar not null, + purpose varchar not null, + code varchar not null, + expires_at timestamptz not null, + consumed_at timestamptz, + created_at timestamptz not null default now() +); +create index if not exists email_verification_codes_email_idx on public.email_verification_codes (email, purpose); + +-- ── Logging ──────────────────────────────────────────────────────────────── +create table if not exists public.ai_insight_logs ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null, + created_at timestamptz not null default now() +); +create index if not exists ai_insight_logs_user_created_idx on public.ai_insight_logs (user_id, created_at); + +create table if not exists public.ops_event_logs ( + id uuid primary key default gen_random_uuid(), + event_name varchar not null, + status varchar not null, + actor_user_id uuid, + actor_email varchar, + store_id uuid, + transaction_id text, + source varchar, + error_message text, + metadata jsonb, + ip_address varchar, + user_agent text, + created_at timestamptz not null default now() +); +create index if not exists ops_event_logs_event_created_idx on public.ops_event_logs (event_name, created_at desc); diff --git a/backend/bootstrap/0002_production-bootstrap.sql b/backend/bootstrap/0002_production-bootstrap.sql new file mode 100644 index 0000000..454381a --- /dev/null +++ b/backend/bootstrap/0002_production-bootstrap.sql @@ -0,0 +1,564 @@ +-- KaffePOS production bootstrap for self-hosted stack +-- Target: PostgreSQL on Contabo VPS +-- Run against kaffepos_production before cutting over fully from legacy auth. + +create extension if not exists pgcrypto; + +do $$ +declare + profiles_auth_fk text; + insight_auth_fk text; +begin + select con.conname + into profiles_auth_fk + from pg_constraint con + join pg_class rel on rel.oid = con.conrelid + join pg_namespace nsp on nsp.oid = rel.relnamespace + join pg_class ref on ref.oid = con.confrelid + join pg_namespace refnsp on refnsp.oid = ref.relnamespace + where con.contype = 'f' + and nsp.nspname = 'public' + and rel.relname = 'profiles' + and refnsp.nspname = 'auth' + and ref.relname = 'users' + limit 1; + + if profiles_auth_fk is not null then + execute format('alter table public.profiles drop constraint %I', profiles_auth_fk); + end if; + + select con.conname + into insight_auth_fk + from pg_constraint con + join pg_class rel on rel.oid = con.conrelid + join pg_namespace nsp on nsp.oid = rel.relnamespace + join pg_class ref on ref.oid = con.confrelid + join pg_namespace refnsp on refnsp.oid = ref.relnamespace + where con.contype = 'f' + and nsp.nspname = 'public' + and rel.relname = 'ai_insight_logs' + and refnsp.nspname = 'auth' + and ref.relname = 'users' + limit 1; + + if insight_auth_fk is not null then + execute format('alter table public.ai_insight_logs drop constraint %I', insight_auth_fk); + end if; +end $$; + +alter table public.profiles + add column if not exists role text not null default 'owner_admin'; + +alter table public.profiles + add column if not exists account_status text not null default 'active'; + +update public.profiles +set role = 'owner_admin' +where role is null + or role not in ('owner_admin', 'cashier'); + +update public.profiles +set account_status = 'active' +where account_status is null + or account_status not in ('active', 'inactive'); + +do $$ +begin + if not exists ( + select 1 + from pg_constraint + where conname = 'profiles_role_check' + ) then + alter table public.profiles + add constraint profiles_role_check + check (role in ('owner_admin', 'cashier')); + end if; + + if not exists ( + select 1 + from pg_constraint + where conname = 'profiles_account_status_check' + ) then + alter table public.profiles + add constraint profiles_account_status_check + check (account_status in ('active', 'inactive')); + end if; +end $$; + +create table if not exists public.cashier_outlet_assignments ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null references public.profiles(id) on delete cascade, + cashier_id uuid not null references public.profiles(id) on delete cascade, + store_id uuid not null references public.stores(id) on delete cascade, + status text not null default 'active' check (status in ('active', 'inactive')), + created_by uuid references public.profiles(id) on delete set null, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (owner_id, cashier_id) +); + +create index if not exists cashier_outlet_assignments_owner_idx + on public.cashier_outlet_assignments (owner_id, updated_at desc); + +create index if not exists cashier_outlet_assignments_cashier_idx + on public.cashier_outlet_assignments (cashier_id, status); + +create table if not exists public.inventory ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + name text not null, + stock numeric not null default 0, + unit text not null default 'pcs', + min_stock numeric not null default 5, + cost_per_unit numeric not null default 0, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +alter table public.inventory + add column if not exists sku text; + +alter table public.inventory + add column if not exists base_unit text; + +alter table public.inventory + add column if not exists purchase_unit text; + +alter table public.inventory + add column if not exists conversion_ratio numeric; + +alter table public.inventory + add column if not exists is_active boolean not null default true; + +update public.inventory +set base_unit = coalesce(nullif(trim(base_unit), ''), unit) +where base_unit is null or trim(base_unit) = ''; + +update public.inventory +set purchase_unit = coalesce(nullif(trim(purchase_unit), ''), unit) +where purchase_unit is null or trim(purchase_unit) = ''; + +update public.inventory +set conversion_ratio = 1 +where conversion_ratio is null or conversion_ratio <= 0; + +create index if not exists inventory_store_active_name_idx + on public.inventory (store_id, is_active, name); + +create table if not exists public.inventory_unit_conversions ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + ingredient_id uuid references public.inventory(id) on delete cascade, + from_unit text not null, + to_unit text not null, + ratio numeric not null check (ratio > 0), + is_active boolean not null default true, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create index if not exists inventory_unit_conversions_store_idx + on public.inventory_unit_conversions (store_id, is_active, from_unit, to_unit); + +create index if not exists inventory_unit_conversions_ingredient_idx + on public.inventory_unit_conversions (ingredient_id, is_active); + +create table if not exists public.transaction_inventory_audit ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + transaction_id text not null, + inventory_id uuid references public.inventory(id) on delete set null, + action text not null, + qty_delta numeric not null, + stock_before numeric not null, + stock_after numeric not null, + created_at timestamptz not null default now() +); + +create index if not exists transaction_inventory_audit_transaction_idx + on public.transaction_inventory_audit (transaction_id, created_at asc); + +create index if not exists transaction_inventory_audit_store_idx + on public.transaction_inventory_audit (store_id, created_at desc); + +do $$ +begin + if exists ( + select 1 + from information_schema.tables + where table_schema = 'public' + and table_name = 'ai_insight_logs' + ) and not exists ( + select 1 + from pg_constraint + where conname = 'ai_insight_logs_user_id_profiles_fk' + ) then + alter table public.ai_insight_logs + add constraint ai_insight_logs_user_id_profiles_fk + foreign key (user_id) references public.profiles(id) on delete cascade; + end if; +end $$; + +create table if not exists public.app_auth_credentials ( + user_id uuid primary key references public.profiles(id) on delete cascade, + email text not null unique, + password_hash text, + email_verified_at timestamptz, + last_login_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create table if not exists public.app_auth_sessions ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references public.profiles(id) on delete cascade, + token_hash text not null unique, + ip_address text, + user_agent text, + expires_at timestamptz not null, + last_seen_at timestamptz not null default now(), + revoked_at timestamptz, + created_at timestamptz not null default now() +); + +create index if not exists app_auth_sessions_user_id_idx + on public.app_auth_sessions (user_id, expires_at desc) + where revoked_at is null; + +create table if not exists public.app_password_reset_tokens ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references public.profiles(id) on delete cascade, + email text not null, + token_hash text not null unique, + expires_at timestamptz not null, + consumed_at timestamptz, + created_at timestamptz not null default now() +); + +create index if not exists app_password_reset_tokens_email_idx + on public.app_password_reset_tokens (email, created_at desc) + where consumed_at is null; + +create table if not exists public.subscription_payment_sessions ( + id uuid primary key, + user_id uuid not null references public.profiles(id) on delete cascade, + store_id uuid references public.stores(id) on delete set null, + subscription_id uuid references public.subscriptions(id) on delete set null, + plan text not null, + billing_cycle text not null, + amount integer not null, + currency_code text not null default 'IDR', + midtrans_order_id text not null unique, + midtrans_transaction_id text, + snap_token text, + redirect_url text, + payment_type text, + transaction_status text not null default 'pending', + fraud_status text, + status_code text, + expires_at timestamptz, + paid_at timestamptz, + settled_at timestamptz, + metadata jsonb not null default '{}'::jsonb, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create index if not exists subscription_payment_sessions_user_id_idx + on public.subscription_payment_sessions (user_id, created_at desc); + +create index if not exists subscription_payment_sessions_order_id_idx + on public.subscription_payment_sessions (midtrans_order_id); + +create table if not exists public.kitchen_orders ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + transaction_id text references public.transactions(id) on delete set null, + order_number text not null, + source text not null default 'cashier', + customer_name text, + table_number text, + overall_status text not null default 'pending' + check (overall_status in ('pending', 'preparing', 'ready', 'served', 'completed', 'cancelled')), + created_by uuid references public.profiles(id) on delete set null, + created_by_name text, + status_version integer not null default 1, + cancelled_reason text, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (store_id, transaction_id) +); + +create index if not exists kitchen_orders_store_status_created_idx + on public.kitchen_orders (store_id, overall_status, created_at desc); + +create index if not exists kitchen_orders_store_updated_idx + on public.kitchen_orders (store_id, updated_at desc); + +create table if not exists public.kitchen_order_items ( + id uuid primary key default gen_random_uuid(), + order_id uuid not null references public.kitchen_orders(id) on delete cascade, + menu_item_id uuid references public.menu_items(id) on delete set null, + item_name text not null, + qty numeric not null check (qty > 0), + note text, + station text not null default 'other' + check (station in ('kitchen', 'bar', 'dessert', 'other')), + item_status text not null default 'pending' + check (item_status in ('pending', 'preparing', 'ready', 'served', 'completed', 'cancelled')), + status_version integer not null default 1, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create index if not exists kitchen_order_items_order_idx + on public.kitchen_order_items (order_id, created_at asc); + +create index if not exists kitchen_order_items_station_status_idx + on public.kitchen_order_items (station, item_status); + +create table if not exists public.kitchen_order_events ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + order_id uuid not null references public.kitchen_orders(id) on delete cascade, + order_item_id uuid references public.kitchen_order_items(id) on delete set null, + event_type text not null, + old_status text, + new_status text, + changed_by uuid references public.profiles(id) on delete set null, + changed_by_name text, + payload jsonb not null default '{}'::jsonb, + created_at timestamptz not null default now() +); + +create index if not exists kitchen_order_events_store_created_idx + on public.kitchen_order_events (store_id, created_at desc); + +create index if not exists kitchen_order_events_order_created_idx + on public.kitchen_order_events (order_id, created_at asc); + +create table if not exists public.loyalty_settings ( + store_id uuid primary key references public.stores(id) on delete cascade, + stamps_required integer not null default 8 check (stamps_required between 2 and 20), + points_per_rupiah numeric not null default 0.01 check (points_per_rupiah >= 0), + minimum_transaction_amount integer not null default 0 check (minimum_transaction_amount >= 0), + is_active boolean not null default true, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create table if not exists public.loyalty_rewards ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + name text not null, + description text, + type text not null check (type in ('discount_amount', 'discount_percent', 'free_item')), + reward_value integer not null default 0 check (reward_value >= 0), + points_or_stamps_needed integer not null default 0 check (points_or_stamps_needed >= 0), + points_cost integer not null default 0 check (points_cost >= 0), + stamps_cost integer not null default 0 check (stamps_cost >= 0), + is_active boolean not null default true, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create index if not exists loyalty_rewards_store_active_idx + on public.loyalty_rewards (store_id, is_active, created_at asc); + +alter table public.loyalty_rewards + add column if not exists points_or_stamps_needed integer not null default 0 check (points_or_stamps_needed >= 0); + +create table if not exists public.loyalty_customers ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + name text, + phone text not null, + tier text not null default 'regular' check (tier in ('regular', 'kopi_lover', 'vvip')), + total_points integer not null default 0 check (total_points >= 0), + total_visits integer not null default 0 check (total_visits >= 0), + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (store_id, phone) +); + +create index if not exists loyalty_customers_store_phone_idx + on public.loyalty_customers (store_id, phone); + +create table if not exists public.loyalty_tiers ( + id uuid primary key default gen_random_uuid(), + store_id uuid references public.stores(id) on delete cascade, + name text not null, + min_visits integer not null default 0 check (min_visits >= 0), + benefits jsonb not null default '{}'::jsonb, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (store_id, name) +); + +create index if not exists loyalty_tiers_store_min_visits_idx + on public.loyalty_tiers (store_id, min_visits asc); + +create table if not exists public.loyalty_passports ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + customer_name text, + customer_phone text not null, + tier text not null default 'regular' check (tier in ('regular', 'kopi_lover', 'vvip')), + total_stamps integer not null default 0 check (total_stamps >= 0), + available_stamps integer not null default 0 check (available_stamps >= 0), + total_points integer not null default 0 check (total_points >= 0), + available_points integer not null default 0 check (available_points >= 0), + lifetime_spend integer not null default 0 check (lifetime_spend >= 0), + last_visit_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (store_id, customer_phone) +); + +create index if not exists loyalty_passports_store_updated_idx + on public.loyalty_passports (store_id, updated_at desc); + +create index if not exists loyalty_passports_store_phone_idx + on public.loyalty_passports (store_id, customer_phone); + +create table if not exists public.loyalty_stamp_events ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + passport_id uuid not null references public.loyalty_passports(id) on delete cascade, + transaction_id text references public.transactions(id) on delete set null, + stamps integer not null default 1 check (stamps >= 0), + points integer not null default 0 check (points >= 0), + transaction_amount integer not null default 0 check (transaction_amount >= 0), + note text, + created_by uuid references public.profiles(id) on delete set null, + idempotency_key text, + created_at timestamptz not null default now() +); + +create unique index if not exists loyalty_stamp_events_idempotency_idx + on public.loyalty_stamp_events (store_id, idempotency_key) + where idempotency_key is not null; + +create index if not exists loyalty_stamp_events_passport_created_idx + on public.loyalty_stamp_events (passport_id, created_at desc); + +create table if not exists public.loyalty_stamps ( + id uuid primary key default gen_random_uuid(), + customer_id uuid not null references public.loyalty_customers(id) on delete cascade, + transaction_id text references public.transactions(id) on delete set null, + stamps_earned integer not null default 1 check (stamps_earned >= 0), + created_at timestamptz not null default now() +); + +create index if not exists loyalty_stamps_customer_created_idx + on public.loyalty_stamps (customer_id, created_at desc); + +create table if not exists public.loyalty_redemptions ( + id uuid primary key default gen_random_uuid(), + store_id uuid not null references public.stores(id) on delete cascade, + passport_id uuid not null references public.loyalty_passports(id) on delete cascade, + reward_id uuid not null references public.loyalty_rewards(id) on delete restrict, + transaction_id text references public.transactions(id) on delete set null, + points_spent integer not null default 0 check (points_spent >= 0), + stamps_spent integer not null default 0 check (stamps_spent >= 0), + discount_amount integer not null default 0 check (discount_amount >= 0), + status text not null default 'redeemed' check (status in ('pending', 'redeemed', 'void')), + created_by uuid references public.profiles(id) on delete set null, + idempotency_key text, + created_at timestamptz not null default now() +); + +create unique index if not exists loyalty_redemptions_idempotency_idx + on public.loyalty_redemptions (store_id, idempotency_key) + where idempotency_key is not null; + +create index if not exists loyalty_redemptions_passport_created_idx + on public.loyalty_redemptions (passport_id, created_at desc); + +create table if not exists public.challenges ( + id uuid primary key default gen_random_uuid(), + store_id uuid references public.stores(id) on delete cascade, + title text not null, + description text not null default '', + target_type text not null check ( + target_type in ( + 'sell_drink', + 'average_checkout_time', + 'transactions_count', + 'upsell_value', + 'zero_voids' + ) + ), + target_value jsonb not null default '{}'::jsonb, + points_reward integer not null default 0 check (points_reward >= 0), + is_active boolean not null default true, + valid_from date not null default current_date, + valid_to date not null default current_date, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() +); + +create index if not exists challenges_store_active_valid_idx + on public.challenges (store_id, is_active, valid_from, valid_to); + +create unique index if not exists challenges_store_title_day_idx + on public.challenges (store_id, title, valid_from); + +create table if not exists public.user_challenge_progress ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references public.profiles(id) on delete cascade, + challenge_id uuid not null references public.challenges(id) on delete cascade, + current_progress numeric not null default 0 check (current_progress >= 0), + is_completed boolean not null default false, + completed_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (user_id, challenge_id) +); + +create index if not exists user_challenge_progress_user_idx + on public.user_challenge_progress (user_id, updated_at desc); + +create index if not exists user_challenge_progress_challenge_idx + on public.user_challenge_progress (challenge_id, is_completed); + +create table if not exists public.subscription_upgrade_prompt_events ( + id uuid primary key default gen_random_uuid(), + user_id uuid references public.profiles(id) on delete set null, + store_id uuid references public.stores(id) on delete set null, + event_type text not null check (event_type in ('view', 'click', 'dismiss')), + prompt_key text not null, + trigger text not null, + recommended_plan text not null default 'signature', + current_plan text, + metadata jsonb not null default '{}'::jsonb, + created_at timestamptz not null default now() +); + +create index if not exists subscription_upgrade_prompt_events_user_idx + on public.subscription_upgrade_prompt_events (user_id, created_at desc); + +create index if not exists subscription_upgrade_prompt_events_store_trigger_idx + on public.subscription_upgrade_prompt_events (store_id, trigger, created_at desc); + +create table if not exists public.ai_insights_cache ( + store_id uuid primary key references public.stores(id) on delete cascade, + generated_by uuid references public.profiles(id) on delete set null, + payload jsonb not null, + generated_at timestamptz not null default now(), + expires_at timestamptz not null, + updated_at timestamptz not null default now() +); + +create index if not exists ai_insights_cache_expires_idx + on public.ai_insights_cache (expires_at); + +insert into public.app_auth_credentials (user_id, email, email_verified_at, created_at, updated_at) +select p.id, lower(trim(p.email)), now(), now(), now() +from public.profiles p +where p.email is not null + and trim(p.email) <> '' +on conflict (user_id) do update +set + email = excluded.email, + updated_at = now(); diff --git a/backend/package-lock.json b/backend/package-lock.json index f17640d..2548220 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -991,9 +991,9 @@ } }, "node_modules/body-parser": { - "version": "1.20.5", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz", - "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==", + "version": "1.20.9", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz", + "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==", "license": "MIT", "dependencies": { "bytes": "~3.1.2", @@ -1004,7 +1004,7 @@ "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "on-finished": "~2.4.1", - "qs": "~6.15.1", + "qs": "~6.16.0", "raw-body": "~2.5.3", "type-is": "~1.6.18", "unpipe": "~1.0.0" @@ -1014,6 +1014,22 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/body-parser/node_modules/qs": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz", + "integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -1878,9 +1894,9 @@ } }, "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "license": "MIT", "dependencies": { "forwarded": "0.2.0", @@ -1888,12 +1904,16 @@ }, "engines": { "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/qs": { - "version": "6.15.3", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", - "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "version": "6.15.4", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.4.tgz", + "integrity": "sha512-d1zNHS+ltAfSgTmYjzXXH9gy9d6pEb33n0ZtUUkukA8UHhFSjv2mSYRiePyjbRiJh0g5sFJbMdAtMIg01Xf5/w==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", @@ -2383,9 +2403,9 @@ } }, "node_modules/zod": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", - "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/backend/scripts/run-migrations.mjs b/backend/scripts/run-migrations.mjs index ee6b81b..719bc32 100755 --- a/backend/scripts/run-migrations.mjs +++ b/backend/scripts/run-migrations.mjs @@ -11,6 +11,23 @@ import { buildPoolConfig } from './db-config.mjs'; const { Pool } = pg; const __dirname = dirname(fileURLToPath(import.meta.url)); const migrationsDir = join(__dirname, '..', 'migrations'); +// Foundation schema for a brand-new database. Copies of database/*.sql (kept identical by +// backend/src/core/bootstrapSql.test.ts) because the Docker build context is backend/ only. +const bootstrapDir = join(__dirname, '..', 'bootstrap'); + +// Versioned migrations assume public.stores, public.inventory, etc. already exist. On an empty +// database apply the foundation SQL first so a fresh deploy (new project, disaster recovery) works +// without a manual psql step. Every statement in these files is idempotent (IF NOT EXISTS). +async function bootstrapFreshDatabase(client) { + const { rows } = await client.query("select to_regclass('public.stores') is not null as ready"); + if (rows[0]?.ready) return; + + const files = (await readdir(bootstrapDir)).filter((file) => file.endsWith('.sql')).sort(); + for (const file of files) { + console.log(`Fresh database: applying bootstrap ${file}...`); + await client.query(await readFile(join(bootstrapDir, file), 'utf8')); + } +} async function ensureMigrationTable(client) { await client.query(` @@ -43,6 +60,7 @@ async function main() { try { await client.query('BEGIN'); + await bootstrapFreshDatabase(client); await ensureMigrationTable(client); for (const file of files) { diff --git a/backend/src/core/bootstrapSql.test.ts b/backend/src/core/bootstrapSql.test.ts new file mode 100644 index 0000000..d232fdf --- /dev/null +++ b/backend/src/core/bootstrapSql.test.ts @@ -0,0 +1,17 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +// The migration runner applies backend/bootstrap/*.sql on an empty database. Those files are +// copies of database/*.sql (the Docker build context is backend/ only), so keep them identical. +const repoRoot = join(__dirname, '..', '..', '..'); +const pairs: Array<[string, string]> = [ + ['database/base-schema.sql', 'backend/bootstrap/0001_base-schema.sql'], + ['database/production-bootstrap.sql', 'backend/bootstrap/0002_production-bootstrap.sql'], +]; + +describe('fresh-database bootstrap SQL', () => { + it.each(pairs)('%s matches %s', (source, copy) => { + const read = (path: string) => readFileSync(join(repoRoot, path), 'utf8'); + expect(read(copy)).toBe(read(source)); + }); +}); diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts index 904c7ea..50bbf9f 100644 --- a/backend/src/routes/auth.ts +++ b/backend/src/routes/auth.ts @@ -678,7 +678,10 @@ async function handleLogin(req: Request, res: any, next: any) { router.post('/api/auth/login', authLoginRateLimiter, handleLogin); -router.post('/api/auth/demo-login', async (req, res, next) => { +// Same limiter as /api/auth/login: each call bcrypt-hashes and reseeds the demo accounts, so an +// unthrottled public endpoint is an easy way to exhaust CPU and DB connections. The body has no +// email yet when the limiter runs, so it keys on the client IP. +router.post('/api/auth/demo-login', authLoginRateLimiter, async (req, res, next) => { const role = req.body?.role === 'cashier' ? 'cashier' : 'owner'; req.body = { email: role === 'cashier' ? DEMO_CASHIER_EMAIL : DEMO_OWNER_EMAIL, diff --git a/package-lock.json b/package-lock.json index 9f994c6..5456d67 100644 --- a/package-lock.json +++ b/package-lock.json @@ -225,9 +225,9 @@ } }, "node_modules/@capacitor/android": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@capacitor/android/-/android-6.2.1.tgz", - "integrity": "sha512-8gd4CIiQO5LAIlPIfd5mCuodBRxMMdZZEdj8qG8m+dQ1sQ2xyemVpzHmRK8qSCHorsBUCg3D62j2cp6bEBAkdw==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/@capacitor/android/-/android-6.2.3.tgz", + "integrity": "sha512-1x7HUUy5XdQUmAwkMcI8qz0pAmSDXGHVq0XVdCvFswqbE74VGxRuGeo7hUGcgQUWkmqXkVWzMSlAm3Z8NrmQjA==", "license": "MIT", "peerDependencies": { "@capacitor/core": "^6.2.0" @@ -1481,9 +1481,9 @@ } }, "node_modules/@remix-run/router": { - "version": "1.23.2", - "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz", - "integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==", + "version": "1.23.4", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.4.tgz", + "integrity": "sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==", "license": "MIT", "engines": { "node": ">=14.0.0" @@ -3759,9 +3759,9 @@ } }, "node_modules/dompurify": { - "version": "3.4.11", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.11.tgz", - "integrity": "sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==", + "version": "3.4.18", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.18.tgz", + "integrity": "sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==", "license": "(MPL-2.0 OR Apache-2.0)", "optional": true, "optionalDependencies": { @@ -4553,9 +4553,9 @@ } }, "node_modules/fflate": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", - "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", "license": "MIT" }, "node_modules/file-entry-cache": { @@ -7343,12 +7343,12 @@ "license": "MIT" }, "node_modules/react-router": { - "version": "6.30.4", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz", - "integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==", + "version": "6.30.6", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.6.tgz", + "integrity": "sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==", "license": "MIT", "dependencies": { - "@remix-run/router": "1.23.3" + "@remix-run/router": "1.23.4" }, "engines": { "node": ">=14.0.0" @@ -7358,13 +7358,13 @@ } }, "node_modules/react-router-dom": { - "version": "6.30.3", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz", - "integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==", + "version": "6.30.6", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.6.tgz", + "integrity": "sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ==", "license": "MIT", "dependencies": { - "@remix-run/router": "1.23.2", - "react-router": "6.30.3" + "@remix-run/router": "1.23.4", + "react-router": "6.30.6" }, "engines": { "node": ">=14.0.0" @@ -7374,15 +7374,6 @@ "react-dom": ">=16.8" } }, - "node_modules/react-router/node_modules/@remix-run/router": { - "version": "1.23.3", - "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz", - "integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, "node_modules/react-smooth": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz", @@ -9384,9 +9375,9 @@ } }, "node_modules/zod": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", - "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/public/serve.json b/public/serve.json new file mode 100644 index 0000000..33789a2 --- /dev/null +++ b/public/serve.json @@ -0,0 +1,27 @@ +{ + "headers": [ + { + "source": "**/*", + "headers": [ + { "key": "X-Content-Type-Options", "value": "nosniff" }, + { "key": "X-Frame-Options", "value": "DENY" }, + { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }, + { "key": "Permissions-Policy", "value": "camera=(), microphone=(), geolocation=()" }, + { "key": "Strict-Transport-Security", "value": "max-age=31536000; includeSubDomains" }, + { "key": "Cache-Control", "value": "no-cache" } + ] + }, + { + "source": "assets/**", + "headers": [{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }] + }, + { + "source": "**/*.@(svg|png|jpg|webp)", + "headers": [{ "key": "Cache-Control", "value": "public, max-age=604800" }] + }, + { + "source": "sw.js", + "headers": [{ "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" }] + } + ] +} diff --git a/scripts/e2e-local.mjs b/scripts/e2e-local.mjs index 50d2100..87e3fa2 100644 --- a/scripts/e2e-local.mjs +++ b/scripts/e2e-local.mjs @@ -87,7 +87,7 @@ try { console.log('→ running playwright'); try { - execSync('npx playwright test --config e2e/playwright.local.config.ts', { + execSync('npx playwright test e2e/local-auth.spec.ts --config e2e/playwright.local.config.ts', { env: { ...process.env, E2E_WEB_URL: WEB, E2E_EMAIL: EMAIL, E2E_PASSWORD: PASSWORD }, stdio: 'inherit', }); diff --git a/scripts/smoke-local-fresh-db.mjs b/scripts/smoke-local-fresh-db.mjs index b895e1e..ee4f2d4 100644 --- a/scripts/smoke-local-fresh-db.mjs +++ b/scripts/smoke-local-fresh-db.mjs @@ -141,7 +141,8 @@ try { `status=${imp.status} committed=${JSON.stringify(committed)}`, ); - const invCount = Number(psql('select count(*) from public.inventory')); + // Exclude the demo store seeded at startup (DemoAccountService) so only the imported rows count. + const invCount = Number(psql("select count(*) from public.inventory where store_id <> '00000000-0000-4000-8000-00000000de03'")); const recipeLen = Number(psql(`select jsonb_array_length(recipe) from public.menu_items where name='Smoke Produk 1'`)); check('inventory rows persisted', invCount === 10, `count=${invCount}`); check('recipe persisted on product', recipeLen === 1, `len=${recipeLen}`); From 6a08ae59f7e697d1db903ae7327b8d04e4c18630 Mon Sep 17 00:00:00 2001 From: Ronal Sagala Date: Fri, 20 Nov 2026 02:59:24 +0700 Subject: [PATCH 2/2] fix(payments): answer upstream gateway failures with 503 so Cloudflare keeps the JSON error Cloudflare replaces 502/504 origin responses with its own HTML page, so the app showed a generic Bad gateway instead of the Mayar or AI error message. Co-Authored-By: Claude Opus 5.5 --- .../src/payments/providers/mayar.provider.test.ts | 8 ++++---- backend/src/payments/providers/mayar.provider.ts | 14 +++++++------- backend/src/routes/__tests__/webhooks.test.ts | 4 ++-- backend/src/routes/misc.ts | 10 +++++----- backend/src/routes/payment.ts | 6 ++++-- backend/src/services/PaymentService.ts | 4 ++-- 6 files changed, 24 insertions(+), 22 deletions(-) diff --git a/backend/src/payments/providers/mayar.provider.test.ts b/backend/src/payments/providers/mayar.provider.test.ts index 217d348..f2b191f 100644 --- a/backend/src/payments/providers/mayar.provider.test.ts +++ b/backend/src/payments/providers/mayar.provider.test.ts @@ -186,14 +186,14 @@ describe('MayarPaymentProvider', () => { await expect( new MayarPaymentProvider().createPayment({ merchantOrderId: 'KAF-4', amount: 15000, productDetails: 'POS' }), - ).rejects.toMatchObject({ status: 502, message: expect.stringContaining('Mayar menolak permintaan ganda') }); + ).rejects.toMatchObject({ status: 503, message: expect.stringContaining('Mayar menolak permintaan ganda') }); }); - it('fails with 502 when the API key is rejected', async () => { + it('fails with 503 when the API key is rejected', async () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ statusCode: 401, messages: 'Unauthorized' }, 401))); await expect( new MayarPaymentProvider().createPayment({ merchantOrderId: 'KAF-5', amount: 15000, productDetails: 'POS' }), - ).rejects.toMatchObject({ status: 502, message: 'Mayar create payment gagal (401).' }); + ).rejects.toMatchObject({ status: 503, message: 'Mayar create payment gagal (401).' }); }); it('refuses to call Mayar without an API key', async () => { @@ -421,7 +421,7 @@ describe('MayarPaymentProvider', () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ statusCode: 503, messages: 'down' }, 503))); await expect( new MayarPaymentProvider().checkTransactionStatus({ merchantOrderId: 'KAF-1', providerReference: PAYMENT_REQUEST_ID }), - ).rejects.toMatchObject({ status: 502 }); + ).rejects.toMatchObject({ status: 503 }); }); }); diff --git a/backend/src/payments/providers/mayar.provider.ts b/backend/src/payments/providers/mayar.provider.ts index 8e5b548..66cd4dd 100644 --- a/backend/src/payments/providers/mayar.provider.ts +++ b/backend/src/payments/providers/mayar.provider.ts @@ -220,7 +220,7 @@ export class MayarPaymentProvider implements PaymentProvider { }); const body = asRecord(await response.json().catch(() => ({}))); if (response.status >= 500) { - throw new ApiError(502, `Mayar sedang tidak bisa dihubungi (${response.status}).`); + throw new ApiError(503, `Mayar sedang tidak bisa dihubungi (${response.status}).`); } return { status: response.status, ok: response.ok, body }; }); @@ -368,13 +368,13 @@ export class MayarPaymentProvider implements PaymentProvider { }); if (status === 429) { - throw new ApiError(502, 'Mayar menolak permintaan ganda. Tunggu 1 menit lalu coba lagi.'); + throw new ApiError(503, 'Mayar menolak permintaan ganda. Tunggu 1 menit lalu coba lagi.'); } if (!ok) { - throw new ApiError(502, `Mayar create payment gagal (${status}).`); + throw new ApiError(503, `Mayar create payment gagal (${status}).`); } if (!paymentUrl) { - throw new ApiError(502, 'Mayar create payment tidak mengembalikan link pembayaran.'); + throw new ApiError(503, 'Mayar create payment tidak mengembalikan link pembayaran.'); } return { @@ -395,7 +395,7 @@ export class MayarPaymentProvider implements PaymentProvider { merchantOrderId: input.merchantOrderId, error: serializeError(error), }); - throw error instanceof ApiError ? error : new ApiError(502, 'Gagal menghubungi gateway pembayaran Mayar.'); + throw error instanceof ApiError ? error : new ApiError(503, 'Gagal menghubungi gateway pembayaran Mayar.'); } } @@ -493,7 +493,7 @@ export class MayarPaymentProvider implements PaymentProvider { response = await this.request('GET', `${prefix}/${encodeURIComponent(lookupId)}`); } catch (error) { log('warn', 'mayar.check_status_unreachable', { merchantOrderId: input.merchantOrderId, error: serializeError(error) }); - throw error instanceof ApiError ? error : new ApiError(502, 'Gagal menghubungi Mayar untuk cek status pembayaran.'); + throw error instanceof ApiError ? error : new ApiError(503, 'Gagal menghubungi Mayar untuk cek status pembayaran.'); } const { status, ok, body } = response; if (status === 404) { @@ -501,7 +501,7 @@ export class MayarPaymentProvider implements PaymentProvider { } if (!ok) { log('warn', 'mayar.check_status_failed', { status, merchantOrderId: input.merchantOrderId, message: extractMayarMessage(body) }); - throw new ApiError(502, `Mayar check status gagal (${status}).`); + throw new ApiError(503, `Mayar check status gagal (${status}).`); } const data = asRecord(body.data ?? body); diff --git a/backend/src/routes/__tests__/webhooks.test.ts b/backend/src/routes/__tests__/webhooks.test.ts index 3854051..f75e8dc 100644 --- a/backend/src/routes/__tests__/webhooks.test.ts +++ b/backend/src/routes/__tests__/webhooks.test.ts @@ -284,11 +284,11 @@ describe('Mayar webhook route', () => { it('lets Mayar retry when the confirmation call fails', async () => { mocks.verifyCallback.mockResolvedValue(webhookResult()); mocks.poolQuery.mockResolvedValueOnce({ rows: [posOrderRow] }); - mocks.checkTransactionStatus.mockRejectedValue(Object.assign(new Error('Mayar check status gagal (502).'), { status: 502 })); + mocks.checkTransactionStatus.mockRejectedValue(Object.assign(new Error('Mayar check status gagal (502).'), { status: 503 })); const next = vi.fn(); await handler(makeReq(), makeRes(), next); - expect(next).toHaveBeenCalledWith(expect.objectContaining({ status: 502 })); + expect(next).toHaveBeenCalledWith(expect.objectContaining({ status: 503 })); expect(PaymentService.finalizePaidOrder).not.toHaveBeenCalled(); }); }); diff --git a/backend/src/routes/misc.ts b/backend/src/routes/misc.ts index b237c3f..b04b021 100644 --- a/backend/src/routes/misc.ts +++ b/backend/src/routes/misc.ts @@ -142,7 +142,7 @@ router.post('/api/ops/events', async (req, res, next) => { router.post('/api/ai-insight', requirePermission('can_view_reports'), async (req, res, next) => { try { if (!env.GEMINI_API_KEY) { - throw new ApiError(502, 'GEMINI_API_KEY belum dikonfigurasi di backend.'); + throw new ApiError(503, 'GEMINI_API_KEY belum dikonfigurasi di backend.'); } const payload = aiInsightRequestSchema.parse(req.body); @@ -207,10 +207,10 @@ router.post('/api/ai-insight', requirePermission('can_view_reports'), async (req } catch (error) { const message = error instanceof Error ? error.message : String(error); if (message.toLowerCase().includes('abort')) { - throw new ApiError(502, 'Layanan AI timeout. Sistem akan memakai analisis cadangan.'); + throw new ApiError(503, 'Layanan AI timeout. Sistem akan memakai analisis cadangan.'); } - throw new ApiError(502, 'Layanan AI sedang tidak tersedia. Sistem akan memakai analisis cadangan.'); + throw new ApiError(503, 'Layanan AI sedang tidak tersedia. Sistem akan memakai analisis cadangan.'); } finally { clearTimeout(timeoutId); } @@ -218,7 +218,7 @@ router.post('/api/ai-insight', requirePermission('can_view_reports'), async (req if (!geminiResponse.ok) { const errorPayload = (await geminiResponse.json().catch(() => ({}))) as { error?: { message?: string } }; const message = errorPayload.error?.message ?? `Gemini error ${geminiResponse.status}`; - throw new ApiError(502, mapGeminiError(geminiResponse.status, message)); + throw new ApiError(503, mapGeminiError(geminiResponse.status, message)); } const geminiPayload = await geminiResponse.json(); @@ -226,7 +226,7 @@ router.post('/api/ai-insight', requirePermission('can_view_reports'), async (req try { insight = parseGeminiText(geminiPayload); } catch { - throw new ApiError(502, 'Respons AI tidak valid. Coba lagi.'); + throw new ApiError(503, 'Respons AI tidak valid. Coba lagi.'); } await pool.query( diff --git a/backend/src/routes/payment.ts b/backend/src/routes/payment.ts index 40e929b..526f7d1 100644 --- a/backend/src/routes/payment.ts +++ b/backend/src/routes/payment.ts @@ -191,9 +191,11 @@ async function createGenericSubscriptionPayment(req: Parameters