Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ SENTRY_ORG=
SENTRY_PROJECT=
SENTRY_AUTH_TOKEN=

# Internal-only demo seeding. Leave unset in production.
ENABLE_SEED_DEMO=

# Payment providers (stubbed — fill in when ready)
STRIPE_SECRET_KEY=
STRIPE_PUBLISHABLE_KEY=
Expand Down
14 changes: 9 additions & 5 deletions docs/AUTHORIZATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,15 @@ Not role-gated by design (token/secret auth instead, unchanged by #49):

**Reviewed, intentionally unchanged:** `POST /api/demo/reset` uses
`requireApiProfile()` (any authenticated company member), not a role check.
It only ever mutates `is_demo=true` tenant data, isn't in #49's priority
list, and `ResetDemoButton` may be shown to any authenticated demo-tenant
member via `DemoBanner`. Restricting it wasn't required and there's no
evidence the current UX is wrong — flagged here rather than silently left
inconsistent with everything else.
It does a full destructive wipe of the caller's own company (every job,
quote, and status_event, not just `is_demo=true` rows), but the route
re-verifies `isSandboxDemoCompany()` before calling `resetDemoTenant()`, so
it can only ever target a purpose-built sandbox tenant on
`SANDBOX_DEMO_SLUGS` (see `src/lib/demo.ts`), never a real customer's data.
It isn't in #49's priority list, and `ResetDemoButton` may be shown to any
authenticated demo-tenant member via `DemoBanner`. Restricting it further
wasn't required and there's no evidence the current UX is wrong — flagged
here rather than silently left inconsistent with everything else.

## `POST /api/jobs` — technician tenant ownership

Expand Down
63 changes: 63 additions & 0 deletions scripts/lib/seedDemoGuard.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* Preflight guard for scripts/seed-demo-tenant.mjs. Pulled out into its own
* module so it can run before ANY Supabase write and be unit-tested without
* a live database.
*
* seed-demo-tenant.mjs does a full destructive wipe of whatever company its
* slug resolves to, and can silently reassign existing Supabase Auth users
* (the demo login, the three technician logins) to a different company if
* their email/handle collide. The public demo's defaults are safe BECAUSE
* they're only ever applied to the public demo's own company -- any other
* slug must come with its own non-default credentials and technician handle
* suffix, or this refuses to run.
*
* Mirrors SANDBOX_DEMO_SLUGS in src/lib/demo.ts -- this script is a plain
* .mjs with no bundler, so it can't import that TypeScript module directly.
* Keep both lists in sync.
*/
export const SANDBOX_DEMO_SLUGS = ["swiftdispatch-demo", "swiftdispatch-preview"];

export const PUBLIC_DEMO_SLUG = "swiftdispatch-demo";
export const PUBLIC_DEMO_EMAIL = "demo@swiftdispatch.app";
export const PUBLIC_DEMO_PASSWORD = "demo";

/**
* @param {{ slug: string, userEmail: string, userPassword: string, handleSuffix: string }} config
* @throws {Error} if the config would let this script hijack the public
* demo's auth users or wipe a company outside the sandbox allowlist.
*/
export function validateSeedConfig({ slug, userEmail, userPassword, handleSuffix }) {
if (!SANDBOX_DEMO_SLUGS.includes(slug)) {
throw new Error(
`Refusing to seed "${slug}" -- it is not on SANDBOX_DEMO_SLUGS. This script does a full ` +
`destructive wipe of whatever company the slug resolves to. Add the slug to ` +
`SANDBOX_DEMO_SLUGS in both src/lib/demo.ts and scripts/lib/seedDemoGuard.mjs first if this ` +
`is a new purpose-built sandbox tenant.`,
);
}

if (slug === PUBLIC_DEMO_SLUG) return;

if (userEmail === PUBLIC_DEMO_EMAIL) {
throw new Error(
`Refusing to seed "${slug}" with the public demo's login email (${PUBLIC_DEMO_EMAIL}). ` +
`Set DEMO_USER_EMAIL to a distinct address, or this reassigns the public demo's login to ` +
`this company.`,
);
}

if (userPassword === PUBLIC_DEMO_PASSWORD) {
throw new Error(
`Refusing to seed "${slug}" with the public demo's default password. Set DEMO_USER_PASSWORD ` +
`to a real generated password -- this tenant's credentials are meant to be shared privately.`,
);
}

if (!handleSuffix) {
throw new Error(
`Refusing to seed "${slug}" without DEMO_HANDLE_SUFFIX. Reusing the public demo's technician ` +
`handles (miatorres, leogrant, averybrooks) would hijack their Supabase Auth logins into ` +
`this company.`,
);
}
}
55 changes: 55 additions & 0 deletions scripts/lib/seedDemoGuard.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, expect, it } from "vitest";
import { validateSeedConfig } from "./seedDemoGuard.mjs";

const PUBLIC_DEFAULTS = {
slug: "swiftdispatch-demo",
userEmail: "demo@swiftdispatch.app",
userPassword: "demo",
handleSuffix: "",
};

const PREVIEW_TENANT = {
slug: "swiftdispatch-preview",
userEmail: "preview@swiftdispatch.app",
userPassword: "a-real-generated-password",
handleSuffix: "preview",
};

describe("validateSeedConfig", () => {
it("allows the canonical public demo defaults", () => {
expect(() => validateSeedConfig(PUBLIC_DEFAULTS)).not.toThrow();
});

it("allows a fully-specified preview tenant", () => {
expect(() => validateSeedConfig(PREVIEW_TENANT)).not.toThrow();
});

it("refuses a custom slug with the public demo's default email", () => {
expect(() =>
validateSeedConfig({ ...PREVIEW_TENANT, userEmail: "demo@swiftdispatch.app" }),
).toThrow(/public demo's login email/);
});

it("refuses a custom slug with the public demo's default password", () => {
expect(() => validateSeedConfig({ ...PREVIEW_TENANT, userPassword: "demo" })).toThrow(
/public demo's default password/,
);
});

it("refuses a custom slug with an empty technician handle suffix", () => {
expect(() => validateSeedConfig({ ...PREVIEW_TENANT, handleSuffix: "" })).toThrow(
/DEMO_HANDLE_SUFFIX/,
);
});

it("refuses a slug that isn't on SANDBOX_DEMO_SLUGS, before any other check", () => {
expect(() =>
validateSeedConfig({
slug: "acme-hvac",
userEmail: "demo@swiftdispatch.app",
userPassword: "demo",
handleSuffix: "",
}),
).toThrow(/not on SANDBOX_DEMO_SLUGS/);
});
});
70 changes: 54 additions & 16 deletions scripts/seed-demo-tenant.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
/**
* One-time setup for the public demo tenant.
* One-time setup for a sandbox demo tenant.
*
* Creates the demo company, public login user (demo / demo), technicians,
* and quote template — then seeds the initial job set.
* Creates the demo company, login user, technicians, and quote template —
* then seeds the initial job set.
*
* Safe to re-run: all operations are idempotent.
*
* After initial setup, daily resets are handled automatically by the
* Vercel cron job calling POST /api/internal/reset-demo (05:00 UTC = 00:00 EST).
* Vercel cron job calling POST /api/internal/reset-demo (05:00 UTC = 00:00 EST)
* for every company whose slug is on SANDBOX_DEMO_SLUGS (src/lib/demo.ts) --
* add the new slug there too, or the nightly reset will silently skip it.
*
* Defaults to the public demo tenant (swiftdispatch-demo, demo@swiftdispatch.app
* / demo) for back-compat with existing usage. Override via env vars to
* provision a second, separately-credentialed sandbox tenant -- e.g. a
* private one shared directly with trusted prospects rather than linked from
* the public site:
*
* DEMO_SLUG=swiftdispatch-preview \
* DEMO_COMPANY_NAME="SwiftDispatch Preview" \
* DEMO_USER_EMAIL=preview@swiftdispatch.app \
* DEMO_USER_PASSWORD=<a real generated password, not "demo"> \
* DEMO_HANDLE_SUFFIX=preview \
* node scripts/seed-demo-tenant.mjs
*
* DEMO_HANDLE_SUFFIX must be unique per tenant -- technician logins are
* shared Supabase Auth users keyed by handle@internal.swiftdispatch.app, so
* reusing a handle across tenants reassigns that technician's login to
* whichever company was seeded last instead of creating a separate one.
*
* Usage:
* node scripts/seed-demo-tenant.mjs
Expand All @@ -17,6 +37,7 @@ import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createClient } from "@supabase/supabase-js";
import { validateSeedConfig } from "./lib/seedDemoGuard.mjs";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Expand Down Expand Up @@ -46,32 +67,46 @@ if (!supabaseUrl || !serviceRoleKey) {

const supabase = createClient(supabaseUrl, serviceRoleKey);

const DEMO_COMPANY_SLUG = "swiftdispatch-demo";
const DEMO_COMPANY_SLUG = process.env.DEMO_SLUG ?? "swiftdispatch-demo";
const HANDLE_SUFFIX = process.env.DEMO_HANDLE_SUFFIX ?? "";

const COMPANY = {
name: "SwiftDispatch Demo",
name: process.env.DEMO_COMPANY_NAME ?? "SwiftDispatch Demo",
slug: DEMO_COMPANY_SLUG,
email: "demo@swiftdispatch.app",
email: process.env.DEMO_COMPANY_EMAIL ?? "demo@swiftdispatch.app",
phone: "555-0100",
timezone: "America/New_York",
sms_sender_name: "SwiftDispatch",
sms_sender_name: process.env.DEMO_SMS_SENDER_NAME ?? "SwiftDispatch",
payment_provider: "manual",
demo_mode_enabled: true,
};

// Public demo credentials — safe to display on marketing pages
// Public demo credentials (defaults) — safe to display on marketing pages.
// A tenant seeded with DEMO_USER_EMAIL/DEMO_USER_PASSWORD overrides should
// NOT reuse a memorable password like "demo" -- these are meant to be
// shared privately with named people, not published.
const DEMO_USER = {
email: "demo@swiftdispatch.app",
password: "demo",
email: process.env.DEMO_USER_EMAIL ?? "demo@swiftdispatch.app",
password: process.env.DEMO_USER_PASSWORD ?? "demo",
role: "dispatcher",
};

const TECHNICIANS = [
{ name: "Mia Torres", phone: "+15551234567", handle: "miatorres", pin: "1234", authPassword: "123456" },
{ name: "Leo Grant", phone: "+15557654321", handle: "leogrant", pin: "5678", authPassword: "567890" },
{ name: "Avery Brooks", phone: "+15553459876", handle: "averybrooks", pin: "9012", authPassword: "901234" },
{ name: "Mia Torres", phone: "+15551234567", handle: `miatorres${HANDLE_SUFFIX}`, pin: "1234", authPassword: "123456" },
{ name: "Leo Grant", phone: "+15557654321", handle: `leogrant${HANDLE_SUFFIX}`, pin: "5678", authPassword: "567890" },
{ name: "Avery Brooks", phone: "+15553459876", handle: `averybrooks${HANDLE_SUFFIX}`, pin: "9012", authPassword: "901234" },
];

// Runs before any Supabase call below -- refuses to start rather than
// silently hijacking the public demo's auth users or wiping the wrong
// company. See scripts/lib/seedDemoGuard.mjs for what it checks and why.
validateSeedConfig({
slug: DEMO_COMPANY_SLUG,
userEmail: DEMO_USER.email,
userPassword: DEMO_USER.password,
handleSuffix: HANDLE_SUFFIX,
});

const TEMPLATE = {
name: "Standard Diagnostic + Repair",
estimated_duration_minutes: 90,
Expand Down Expand Up @@ -259,9 +294,9 @@ async function seedJobs(companyId, techIds) {
// ─── Main ─────────────────────────────────────────────────────────────────────

async function main() {
console.log("Setting up demo tenant…");
console.log(`Setting up demo tenant (slug: ${DEMO_COMPANY_SLUG})…`);
const companyId = await ensureCompany();
console.log(` Company: ${companyId}`);
console.log(` Company: ${COMPANY.name} (${companyId})`);

const demoAuthUser = await ensureAuthUser(DEMO_USER.email, DEMO_USER.password);
await ensureUserProfile(demoAuthUser, companyId, DEMO_USER.role);
Expand All @@ -280,9 +315,12 @@ async function main() {
console.log(` Jobs seeded: ${seeded}`);

console.log("\nDemo tenant ready.");
console.log(` Slug: ${DEMO_COMPANY_SLUG}`);
console.log(` Login: ${DEMO_USER.email} / ${DEMO_USER.password}`);
console.log(` Daily reset: POST /api/internal/reset-demo (05:00 UTC = 00:00 EST)`);
console.log(` Vercel cron: set CRON_SECRET env var — already configured in vercel.json`);
console.log(` Make sure "${DEMO_COMPANY_SLUG}" is listed in SANDBOX_DEMO_SLUGS (src/lib/demo.ts),`);
console.log(` or the nightly reset will silently skip this tenant.`);
}

main().catch((err) => { console.error(err); process.exit(1); });
Loading
Loading