diff --git a/.agents/skills/database-security-review/SKILL.md b/.agents/skills/database-security-review/SKILL.md index ab05dccf..12c1e07e 100644 --- a/.agents/skills/database-security-review/SKILL.md +++ b/.agents/skills/database-security-review/SKILL.md @@ -13,3 +13,7 @@ Use repository scripts rather than rebuilding the audit. Read docs/security/2026 - Apply only reviewed, authorized migration SQL, then run npm run check:security with backend URL/publishable key from the environment. Reports must be nonempty. Run npm run check:project and PR checks before merge and app deploy. - Re-run Lovable scans. Classify remaining intentional behavior only with specific guard evidence and tests. Do not ignore a whole group to hide unreviewed functions. - Verify the exact Git commit in Lovable's tracked branch and confirmed publication plus production health. Do not switch tracked branches, resize the database or change a plan as part of a security fix. + +For advanced application findings, also trace every HTTP, server-function and MCP entry point. Test identity binding and anonymous capabilities centrally; do not treat a database UUID as authorization. Keep public catalogue metadata separate from paid prompt contents. Caller telemetry cannot attest itself as verified. Checkout quantities must follow the exact product lookup key, and redirects must use an explicit origin allowlist. + +Run `node --experimental-strip-types --test tests/security-findings.test.ts` and `scripts/test-advanced-security.sql` after the corresponding migration inside a rolled-back transaction. Verify legitimate star increments/decrements as well as denied direct count updates. Check for concurrent Lovable edits before committing or applying migrations; preserve stronger guards already present. Re-scan the exact integrated commit before publishing. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..14b1ddd5 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,8 @@ +# Technical decisions + +- Pro entitlements use explicit price lookup keys and all matching subscriptions in the current payments environment through `subscription-entitlements.ts` and `auth/pro-subscription.server.ts`; standalone Agent Pass is separate. Why: a paid seat or newest subscription must not grant or hide Pro access. + +- `src/integrations/supabase/database.ts` merges hand-written schema contracts (`optional-schema.ts`, `platform-schema.ts`) only for entries missing from the generated `types.ts`; generated entries always win. Why: intersecting duplicate table definitions with different `Relationships` breaks supabase-js embedded-resource type parsing (embedded selects like `packages(slug)` fail to resolve). + +- Scheduled callbacks under `/api/public/*` authenticate with the managed cron secret via `authenticateCronRequest` (`integrations/supabase/cron-auth.ts`), never with publishable/anon keys. Why: the publishable key ships to every browser. +- Public catalog surfaces read classification from `packages.vertical` (DB-synced from the latest version's rules) and never select `package_versions` content for non-owners. Why: version rules/prompts are author/purchaser-only data. diff --git a/docs/security/20261123-advanced-findings.md b/docs/security/20261123-advanced-findings.md new file mode 100644 index 00000000..a1951088 --- /dev/null +++ b/docs/security/20261123-advanced-findings.md @@ -0,0 +1,49 @@ +# Advanced security review — 2026-11-23 + +Reviewed all 22 groups from the advanced Lovable scan (9 critical groups). The scan grouped 27 underlying findings. During the review, a parallel Lovable run committed `e4e9fbd4`; this change builds on that commit and preserves its managed cron authentication, public classification column, RLS fixes and one-shot diagnosis writes. No database plan or size changed. + +## Disposition of the original groups + +| # | Group | Disposition and evidence | +| --- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Unverified email joins workspace (critical) | Auto-confirm email disabled in Lovable Auth. `team_action` requires a sent-and-confirmed link or a provider-verified matching address; existing auto-confirmed accounts do not qualify. SQL tests deny an unverified invite, then accept after genuine confirmation timestamps. | +| 2 | Public private drift (critical) | `compute_skill_drift` service-only; role probes reject authenticated callers. | +| 3 | Cross-user diagnoses / curriculum (critical, 2 findings) | Central identity/capability check covers HTTP, server functions and MCP. Owned records require verified owner. Anonymous references are HMAC-signed; raw UUIDs and tampered references fail. One-shot updates prevent overwrites. | +| 4 | Authors forge stars (critical) | Insert count forced to zero; direct updates preserve prior count; nested star trigger may update. SQL tests verify denial plus real increment/decrement. | +| 5 | Approved version tampering / unpurchased customization (critical, 2 findings) | Author writes denied for approved live versions. Customizations require purchase both in RLS and execution; initial state must be queued with empty results. | +| 6 | Unpublished Forge reports (critical) | Public only for approved published free packages; private/paid reports require author/admin. | +| 7 | Forged MCP usage history | `mcp_check_and_log_call` server-only. | +| 8 | Restricted classifications in discovery | Public classification is now `packages.vertical`; discovery no longer loads restricted version rules. Categories remain public by product intent. | +| 9 | Paid instructions in detail | Shared public detail cache omits paid prompt, rules and examples. Full HTTP/MCP deliveries check author/admin/direct or pack purchase; paid responses use private/no-store. Exports resolve the approved latest version. | +| 10 | Inflated trust from self-reports | Public/MCP reports remain unverified. Trust RPC, cached v2 scores and weekly snapshots count only server-attested `is_verified` runs. Existing reports are not retroactively trusted. Cached v2 scores recomputed. | +| 11 | Caller-controlled favorites expose private packages | Reads use the caller's RLS-scoped client. Star inserts require published/approved packages. | +| 12 | Restricted classifications in list | Same public-column boundary as #8. | +| 13 | Precise individual execution timestamps | Public evaluation data no longer queries or returns the last execution timestamp. | +| 14 | Hidden packages via stars | Caller-scoped reads enforce package visibility. | +| 15 | Cross-user credit balance | `get_credit_balance` uses invoker privileges/RLS; SQL probe denies another account's balance. | +| 16 | Transactional SECURITY DEFINER functions (informational, 4 findings) | Intentionally retained: claim_referral, purchase_pack, purchase_package, team_action require authentication and bind writes to auth.uid(); team accept strengthened in #1. Definer existence alone is not a vulnerability. | +| 17 | Arbitrary checkout return URL | Exact project/domain hosts, HTTPS, no userinfo or arbitrary ports. Reject lookalike preview hosts containing the project UUID. | +| 18 | CRM privileged actions (critical, 3 findings) | All three routes call managed `authenticateCronRequest`, never publishable keys. Scheduler secret configured by Lovable; current/previous secret tests pass. | +| 19 | Arbitrary transactional email (critical) | Generic template sender requires verified JWT plus administrator role, before body/template processing. Auth email webhook and managed CRM retain their own trusted paths. | +| 20 | Publicly triggerable scheduled CRM | Duplicate surface of #18. Also revoked public execution on nightly trust recompute and weekly snapshots; existing owner-run SQL cron remains functional. | +| 21 | Unreleased compatibility results | Requires an approved published package before querying results. | +| 22 | Caller-chosen checkout quantity (critical) | Pro/other products always quantity 1; only exact sak_agent_pass_monthly supports seats. Browser adjustable flag cannot override product policy. | + +## Additional related gaps closed + +Stripe customer reuse is bound to verified user UUID metadata; an unverified email claim can no longer reassign another customer's metadata. Both `has_active_subscription` overloads now use invoker/RLS privileges. Security audit RPCs remain public intentionally: they expose booleans for deployment checks, not customer records or credentials. + +## Validation and reusable workflow + +- `scripts/test-advanced-security.sql`: synthetic fixtures, negative/positive role probes, always rolled back. Tested together with the migration before applying it. +- `scripts/test-security-boundaries.sql`: previous role regression suite; updated expected report count to 8. +- `npm run check:rpc-security`: 8 nonempty named checks, including 29 service-only RPC signatures, account read isolation, verified telemetry and customization ownership. +- `tests/security-findings.test.ts`: managed cron, capability integrity, exact product quantities and redirect boundaries. +- `tests/diagnosis-persistence.test.ts`: bundled real server round trip against a stub database; verifies signed external reference but raw UUID foreign keys and cross-owner denial. +- Existing `database-security-review` skill extended with the proven advanced-review method. + +Jev 1.14.0 advisory review flagged the initial anonymous UUID-as-capability boundary (gap probability 0.83). That design was replaced with HMAC references and tested. It supported separating verified trust from self-reported telemetry (0.82); classification evidence was less decisive (0.61), so the integrated implementation explicitly separates public metadata in its own column. Jev is not an approval or security gate. + +Anonymous exams created before this change must be restarted; plain UUIDs no longer authorize anonymous history. Rotating the server signing credential invalidates anonymous capabilities. No existing user records are deleted. Historical unverified telemetry remains stored but no longer increases verified trust. + +Validation recorded: 466 tests passed; all 12 project checks passed (the final lint rerun reports 825 files, 0 blocking errors and 0 explicit-any violations). Both SQL probe suites passed in rolled-back transactions; the applied migration returned 8/8 named security checks. Generated Supabase files received formatting-only normalization required by the repository lint. The platform dependency change had left npm's lockfile stale; it is synchronized without changing package versions beyond that existing platform update. diff --git a/scripts/check-rpc-security.ts b/scripts/check-rpc-security.ts index 7085707a..6b3c4c92 100644 --- a/scripts/check-rpc-security.ts +++ b/scripts/check-rpc-security.ts @@ -18,6 +18,9 @@ const expected = [ "rls_invoker_reads", "authenticated_transactions", "plans_explicit_public_rows", + "account_reads_invoker", + "verified_telemetry_only", + "customization_purchase_required", ]; if ( error || diff --git a/scripts/test-advanced-security.sql b/scripts/test-advanced-security.sql new file mode 100644 index 00000000..44fbc6a3 --- /dev/null +++ b/scripts/test-advanced-security.sql @@ -0,0 +1,67 @@ +-- Transactional probes only: synthetic identities, no emails or charges. +BEGIN; +INSERT INTO auth.users(id,email,raw_user_meta_data) VALUES + ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01','security-owner@example.invalid','{}'), + ('dddddddd-dddd-4ddd-8ddd-dddddddddd02','security-other@example.invalid','{}'); +INSERT INTO public.user_roles(user_id,role) VALUES ('dddddddd-dddd-4ddd-8ddd-dddddddddd02','admin'); +SELECT set_config('request.jwt.claims','{"sub":"dddddddd-dddd-4ddd-8ddd-dddddddddd02","role":"authenticated"}',true); +INSERT INTO public.packages(id,slug,name,type,description,author_id,is_published,review_status) + VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03','security-rollback-fixture','Fixture','skill','Rollback only','eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01',true,'approved'); +INSERT INTO public.package_versions(package_id,version,system_prompt) VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03','0.1.0','Original approved content'); +INSERT INTO public.packs(id,slug,name,description,price_credits) VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee04','security-rollback-pack','Fixture','Rollback only',10); +INSERT INTO public.credit_ledger(user_id,delta,balance_after,reason) VALUES ('dddddddd-dddd-4ddd-8ddd-dddddddddd02',77,77,'purchase'); +INSERT INTO public.team_workspaces(id,name,owner_id) VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee05','Rollback workspace','dddddddd-dddd-4ddd-8ddd-dddddddddd02'); +INSERT INTO public.team_invites(workspace_id,email,role,token_hash,created_by) VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee05','security-owner@example.invalid','viewer',encode(extensions.digest('rollback-only-token','sha256'),'hex'),'dddddddd-dddd-4ddd-8ddd-dddddddddd02'); +SET LOCAL ROLE authenticated; +SELECT set_config('request.jwt.claims','{"sub":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01","role":"authenticated","email":"security-owner@example.invalid"}',true); +DO $test$ +DECLARE n int; +BEGIN + BEGIN + PERFORM public.team_action('accept',NULL,'{"token":"rollback-only-token"}'); + RAISE EXCEPTION 'Unverified email joined workspace'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + IF public.get_credit_balance('dddddddd-dddd-4ddd-8ddd-dddddddddd02') <> 0 THEN RAISE EXCEPTION 'Cross-user credits leaked'; END IF; + UPDATE public.packages SET star_count=999 WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03'; + IF (SELECT star_count FROM public.packages WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03') <> 0 THEN RAISE EXCEPTION 'Author forged stars'; END IF; + INSERT INTO public.package_stars(user_id,package_id) VALUES(auth.uid(),'eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03'); + IF (SELECT star_count FROM public.packages WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03') <> 1 THEN RAISE EXCEPTION 'Legitimate star did not increment'; END IF; + DELETE FROM public.package_stars WHERE user_id=auth.uid() AND package_id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03'; + IF (SELECT star_count FROM public.packages WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03') <> 0 THEN RAISE EXCEPTION 'Legitimate star did not decrement'; END IF; + UPDATE public.package_versions SET system_prompt='Bypass' WHERE package_id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03'; + GET DIAGNOSTICS n=ROW_COUNT; + IF n<>0 THEN RAISE EXCEPTION 'Author changed approved content'; END IF; + BEGIN + INSERT INTO public.pack_customizations(user_id,pack_id,brief) VALUES(auth.uid(),'eeeeeeee-eeee-4eee-8eee-eeeeeeeeee04','Unauthorized customization'); + RAISE EXCEPTION 'Unpurchased customization accepted'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + BEGIN + PERFORM public.mcp_check_and_log_call(auth.uid(),'probe','probe',false); + RAISE EXCEPTION 'User forged MCP log'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + BEGIN + PERFORM public.compute_skill_drift('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03'); + RAISE EXCEPTION 'User read private drift'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + BEGIN + PERFORM public.report_skill_execution('security-rollback-fixture',true); + RAISE EXCEPTION 'User called internal telemetry RPC'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; +END $test$; +RESET ROLE; +SELECT set_config('request.jwt.claims','{"role":"service_role"}',true); +SET LOCAL ROLE service_role; +SELECT public.report_skill_execution('security-rollback-fixture',true); +DO $test$ +BEGIN + IF (public.get_skill_trust('security-rollback-fixture')->>'trust_score') IS NOT NULL THEN RAISE EXCEPTION 'Unverified telemetry inflated trust'; END IF; + IF (public.get_skill_trust('security-rollback-fixture')->>'battle_tested')::boolean THEN RAISE EXCEPTION 'Unverified battle badge'; END IF; +END $test$; +RESET ROLE; +UPDATE auth.users SET confirmation_sent_at=now()-interval '1 minute',email_confirmed_at=now() WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01'; +SET LOCAL ROLE authenticated; +SELECT set_config('request.jwt.claims','{"sub":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01","role":"authenticated","email":"security-owner@example.invalid"}',true); +SELECT public.team_action('accept',NULL,'{"token":"rollback-only-token"}'); +RESET ROLE; +ROLLBACK; +SELECT 'passed' AS advanced_security_role_probes; diff --git a/scripts/test-security-boundaries.sql b/scripts/test-security-boundaries.sql index 6ea5f0af..3ef7dc14 100644 --- a/scripts/test-security-boundaries.sql +++ b/scripts/test-security-boundaries.sql @@ -5,7 +5,7 @@ DO $test$ DECLARE failures text; BEGIN SELECT string_agg(check_name, ', ') INTO failures FROM public.check_security_boundaries() WHERE passed IS DISTINCT FROM true; - IF failures IS NOT NULL OR (SELECT count(*) FROM public.check_security_boundaries()) <> 5 THEN + IF failures IS NOT NULL OR (SELECT count(*) FROM public.check_security_boundaries()) <> 8 THEN RAISE EXCEPTION 'Security boundary regression: %', failures; END IF; END $test$; diff --git a/src/integrations/supabase/cron-auth.ts b/src/integrations/supabase/cron-auth.ts new file mode 100644 index 00000000..762cfc1c --- /dev/null +++ b/src/integrations/supabase/cron-auth.ts @@ -0,0 +1,27 @@ +// This file is automatically generated. Do not edit it directly. +export async function authenticateCronRequest(request: Request): Promise { + const currentSecret = process.env["LOVABLE_CRON_SECRET"]; + const previousSecret = process.env["LOVABLE_CRON_SECRET_PREVIOUS"]; + + if (!currentSecret) { + return new Response("Server configuration error", { status: 500 }); + } + + const match = /^Bearer ([^\s,]+)$/.exec(request.headers.get("authorization") ?? ""); + const token = match?.[1]; + if (!token) { + return new Response("Unauthorized", { status: 401 }); + } + + const { createHash, timingSafeEqual } = await import("node:crypto"); + const digest = (value: string) => createHash("sha256").update(value, "utf8").digest(); + const providedDigest = digest(token); + const currentMatches = timingSafeEqual(providedDigest, digest(currentSecret)); + const previousMatches = timingSafeEqual(providedDigest, digest(previousSecret ?? currentSecret)); + + if (!currentMatches && !previousMatches) { + return new Response("Unauthorized", { status: 401 }); + } + + return null; +} diff --git a/src/integrations/supabase/database.ts b/src/integrations/supabase/database.ts index c002cb65..ba10b031 100644 --- a/src/integrations/supabase/database.ts +++ b/src/integrations/supabase/database.ts @@ -2,11 +2,28 @@ import type { PlatformTables, PlatformFunctions } from "./platform-schema"; import type { SupabaseClient } from "@supabase/supabase-js"; import type { Database as GeneratedDatabase } from "./types"; import type { OptionalTables, OptionalViews } from "./optional-schema"; + +// The generated types are regenerated from the live database and are the source +// of truth. Hand-written contracts (optional-schema, platform-schema) only add +// entries that do not exist there yet; generated entries always win, otherwise +// intersecting duplicate `Relationships` definitions breaks embedded-resource +// type parsing in supabase-js (e.g. "column 'packages' does not exist"). +type MergeGenerated = T & { + [K in Exclude]: U[K]; +}; + +type MergedTables = MergeGenerated< + GeneratedDatabase["public"]["Tables"], + OptionalTables & PlatformTables +>; +type MergedViews = MergeGenerated; +type MergedFunctions = MergeGenerated; + export type Database = Omit & { public: Omit & { - Tables: GeneratedDatabase["public"]["Tables"] & OptionalTables & PlatformTables; - Functions: GeneratedDatabase["public"]["Functions"] & PlatformFunctions; - Views: GeneratedDatabase["public"]["Views"] & OptionalViews; + Tables: MergedTables; + Views: MergedViews; + Functions: MergedFunctions; }; }; export type AppDatabaseClient = SupabaseClient; diff --git a/src/integrations/supabase/types.ts b/src/integrations/supabase/types.ts index 2669d5be..e636e599 100644 --- a/src/integrations/supabase/types.ts +++ b/src/integrations/supabase/types.ts @@ -433,6 +433,30 @@ export type Database = { }, ]; }; + agent_match_selection_cache: { + Row: { + cache_key: string; + created_at: string; + evidence: Json; + expires_at: string; + scope_hash: string; + }; + Insert: { + cache_key: string; + created_at: string; + evidence: Json; + expires_at: string; + scope_hash: string; + }; + Update: { + cache_key?: string; + created_at?: string; + evidence?: Json; + expires_at?: string; + scope_hash?: string; + }; + Relationships: []; + }; agent_onboarding_steps: { Row: { client_name: string | null; @@ -1785,6 +1809,104 @@ export type Database = { }, ]; }; + package_artifacts: { + Row: { + created_at: string; + created_by: string | null; + files: Json; + package_id: string; + sha256: string; + version_id: string; + }; + Insert: { + created_at?: string; + created_by?: string | null; + files: Json; + package_id: string; + sha256: string; + version_id: string; + }; + Update: { + created_at?: string; + created_by?: string | null; + files?: Json; + package_id?: string; + sha256?: string; + version_id?: string; + }; + Relationships: [ + { + foreignKeyName: "package_artifacts_package_id_fkey"; + columns: ["package_id"]; + isOneToOne: false; + referencedRelation: "package_rankings"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "package_artifacts_package_id_fkey"; + columns: ["package_id"]; + isOneToOne: false; + referencedRelation: "packages"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "package_artifacts_version_id_fkey"; + columns: ["version_id"]; + isOneToOne: true; + referencedRelation: "package_versions"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "package_artifacts_version_id_fkey"; + columns: ["version_id"]; + isOneToOne: true; + referencedRelation: "package_versions_public"; + referencedColumns: ["id"]; + }, + ]; + }; + package_embeddings: { + Row: { + created_at: string; + embedding: string; + model: string; + package_id: string; + source_sha256: string; + version: string; + }; + Insert: { + created_at?: string; + embedding: string; + model: string; + package_id: string; + source_sha256: string; + version: string; + }; + Update: { + created_at?: string; + embedding?: string; + model?: string; + package_id?: string; + source_sha256?: string; + version?: string; + }; + Relationships: [ + { + foreignKeyName: "package_embeddings_package_id_fkey"; + columns: ["package_id"]; + isOneToOne: true; + referencedRelation: "package_rankings"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "package_embeddings_package_id_fkey"; + columns: ["package_id"]; + isOneToOne: true; + referencedRelation: "packages"; + referencedColumns: ["id"]; + }, + ]; + }; package_evaluations: { Row: { adversarial_results: Json; @@ -2684,6 +2806,7 @@ export type Database = { tags: string[]; type: Database["public"]["Enums"]["package_type"]; updated_at: string; + vertical: string | null; }; Insert: { author_handle?: string; @@ -2713,6 +2836,7 @@ export type Database = { tags?: string[]; type: Database["public"]["Enums"]["package_type"]; updated_at?: string; + vertical?: string | null; }; Update: { author_handle?: string; @@ -2742,6 +2866,7 @@ export type Database = { tags?: string[]; type?: Database["public"]["Enums"]["package_type"]; updated_at?: string; + vertical?: string | null; }; Relationships: []; }; @@ -3391,6 +3516,48 @@ export type Database = { }; Relationships: []; }; + semantic_index_attempts: { + Row: { + created_at: string; + id: string; + model: string; + receipt: Json | null; + status: string; + }; + Insert: { + created_at?: string; + id?: string; + model: string; + receipt?: Json | null; + status: string; + }; + Update: { + created_at?: string; + id?: string; + model?: string; + receipt?: Json | null; + status?: string; + }; + Relationships: []; + }; + semantic_query_budget: { + Row: { + actor: string; + day: string; + queries: number; + }; + Insert: { + actor: string; + day?: string; + queries: number; + }; + Update: { + actor?: string; + day?: string; + queries?: number; + }; + Relationships: []; + }; share_promos: { Row: { body: string; @@ -3421,6 +3588,117 @@ export type Database = { }; Relationships: []; }; + skill_collection_followers: { + Row: { + collection_id: string; + followed_at: string; + user_id: string; + }; + Insert: { + collection_id: string; + followed_at?: string; + user_id: string; + }; + Update: { + collection_id?: string; + followed_at?: string; + user_id?: string; + }; + Relationships: [ + { + foreignKeyName: "skill_collection_followers_collection_id_fkey"; + columns: ["collection_id"]; + isOneToOne: false; + referencedRelation: "skill_collections"; + referencedColumns: ["id"]; + }, + ]; + }; + skill_collection_items: { + Row: { + added_at: string; + collection_id: string; + note: string | null; + package_id: string; + position: number; + }; + Insert: { + added_at?: string; + collection_id: string; + note?: string | null; + package_id: string; + position?: number; + }; + Update: { + added_at?: string; + collection_id?: string; + note?: string | null; + package_id?: string; + position?: number; + }; + Relationships: [ + { + foreignKeyName: "skill_collection_items_collection_id_fkey"; + columns: ["collection_id"]; + isOneToOne: false; + referencedRelation: "skill_collections"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "skill_collection_items_package_id_fkey"; + columns: ["package_id"]; + isOneToOne: false; + referencedRelation: "package_rankings"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "skill_collection_items_package_id_fkey"; + columns: ["package_id"]; + isOneToOne: false; + referencedRelation: "packages"; + referencedColumns: ["id"]; + }, + ]; + }; + skill_collections: { + Row: { + cover_emoji: string | null; + created_at: string; + curator_share_bps: number; + curator_user_id: string; + description: string | null; + id: string; + is_public: boolean; + slug: string; + title: string; + updated_at: string; + }; + Insert: { + cover_emoji?: string | null; + created_at?: string; + curator_share_bps?: number; + curator_user_id: string; + description?: string | null; + id?: string; + is_public?: boolean; + slug: string; + title: string; + updated_at?: string; + }; + Update: { + cover_emoji?: string | null; + created_at?: string; + curator_share_bps?: number; + curator_user_id?: string; + description?: string | null; + id?: string; + is_public?: boolean; + slug?: string; + title?: string; + updated_at?: string; + }; + Relationships: []; + }; skill_compatibility: { Row: { evaluated_at: string; @@ -3916,6 +4194,245 @@ export type Database = { }; Relationships: []; }; + team_audit_events: { + Row: { + action: string; + actor_id: string; + created_at: string; + detail: Json; + id: string; + workspace_id: string; + }; + Insert: { + action: string; + actor_id: string; + created_at?: string; + detail?: Json; + id?: string; + workspace_id: string; + }; + Update: { + action?: string; + actor_id?: string; + created_at?: string; + detail?: Json; + id?: string; + workspace_id?: string; + }; + Relationships: [ + { + foreignKeyName: "team_audit_events_workspace_id_fkey"; + columns: ["workspace_id"]; + isOneToOne: false; + referencedRelation: "team_workspaces"; + referencedColumns: ["id"]; + }, + ]; + }; + team_invites: { + Row: { + accepted_at: string | null; + created_by: string; + email: string; + expires_at: string; + id: string; + role: string; + token_hash: string; + workspace_id: string; + }; + Insert: { + accepted_at?: string | null; + created_by: string; + email: string; + expires_at?: string; + id?: string; + role: string; + token_hash: string; + workspace_id: string; + }; + Update: { + accepted_at?: string | null; + created_by?: string; + email?: string; + expires_at?: string; + id?: string; + role?: string; + token_hash?: string; + workspace_id?: string; + }; + Relationships: [ + { + foreignKeyName: "team_invites_workspace_id_fkey"; + columns: ["workspace_id"]; + isOneToOne: false; + referencedRelation: "team_workspaces"; + referencedColumns: ["id"]; + }, + ]; + }; + team_library: { + Row: { + package_id: string; + pinned_at: string; + pinned_by: string; + version_id: string; + workspace_id: string; + }; + Insert: { + package_id: string; + pinned_at?: string; + pinned_by: string; + version_id: string; + workspace_id: string; + }; + Update: { + package_id?: string; + pinned_at?: string; + pinned_by?: string; + version_id?: string; + workspace_id?: string; + }; + Relationships: [ + { + foreignKeyName: "team_library_package_id_fkey"; + columns: ["package_id"]; + isOneToOne: false; + referencedRelation: "package_rankings"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "team_library_package_id_fkey"; + columns: ["package_id"]; + isOneToOne: false; + referencedRelation: "packages"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "team_library_version_id_fkey"; + columns: ["version_id"]; + isOneToOne: false; + referencedRelation: "package_versions"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "team_library_version_id_fkey"; + columns: ["version_id"]; + isOneToOne: false; + referencedRelation: "package_versions_public"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "team_library_workspace_id_fkey"; + columns: ["workspace_id"]; + isOneToOne: false; + referencedRelation: "team_workspaces"; + referencedColumns: ["id"]; + }, + ]; + }; + team_members: { + Row: { + joined_at: string; + role: string; + user_id: string; + workspace_id: string; + }; + Insert: { + joined_at?: string; + role: string; + user_id: string; + workspace_id: string; + }; + Update: { + joined_at?: string; + role?: string; + user_id?: string; + workspace_id?: string; + }; + Relationships: [ + { + foreignKeyName: "team_members_workspace_id_fkey"; + columns: ["workspace_id"]; + isOneToOne: false; + referencedRelation: "team_workspaces"; + referencedColumns: ["id"]; + }, + ]; + }; + team_skill_versions: { + Row: { + created_at: string; + created_by: string; + description: string; + files: Json; + id: string; + name: string; + reviewed_at: string | null; + reviewed_by: string | null; + slug: string; + status: string; + version: string; + workspace_id: string; + }; + Insert: { + created_at?: string; + created_by: string; + description: string; + files: Json; + id?: string; + name: string; + reviewed_at?: string | null; + reviewed_by?: string | null; + slug: string; + status?: string; + version: string; + workspace_id: string; + }; + Update: { + created_at?: string; + created_by?: string; + description?: string; + files?: Json; + id?: string; + name?: string; + reviewed_at?: string | null; + reviewed_by?: string | null; + slug?: string; + status?: string; + version?: string; + workspace_id?: string; + }; + Relationships: [ + { + foreignKeyName: "team_skill_versions_workspace_id_fkey"; + columns: ["workspace_id"]; + isOneToOne: false; + referencedRelation: "team_workspaces"; + referencedColumns: ["id"]; + }, + ]; + }; + team_workspaces: { + Row: { + created_at: string; + id: string; + name: string; + owner_id: string; + }; + Insert: { + created_at?: string; + id?: string; + name: string; + owner_id: string; + }; + Update: { + created_at?: string; + id?: string; + name?: string; + owner_id?: string; + }; + Relationships: []; + }; tenant_encrypted_objects: { Row: { byte_size: number; @@ -4305,6 +4822,10 @@ export type Database = { step_id: string; }[]; }; + artifact_readable: { + Args: { _package: string; _version: string }; + Returns: boolean; + }; attach_execution_outcome: { Args: { _agent_fp?: string; @@ -4328,10 +4849,21 @@ export type Database = { table_name: string; }[]; }; + check_security_boundaries: { + Args: never; + Returns: { + check_name: string; + passed: boolean; + }[]; + }; claim_referral: { Args: { _code: string; _package_slug?: string; _source_url?: string }; Returns: Json; }; + complete_search_embedding_batch: { + Args: { _attempt: string; _entries: Json; _receipt: Json }; + Returns: number; + }; compute_skill_drift: { Args: { _package_id: string; _window_days?: number }; Returns: Json; @@ -4465,6 +4997,13 @@ export type Database = { get_pack_with_items: { Args: { _slug: string }; Returns: Json }; get_package_ratings: { Args: { _package_id: string }; Returns: Json }; get_review_eligibility: { Args: { _package_id: string }; Returns: Json }; + get_search_embedding_attempt: { + Args: { _attempt: string }; + Returns: { + receipt: Json; + status: string; + }[]; + }; get_skill_trust: { Args: { _slug: string }; Returns: Json }; get_skill_uplift: { Args: { _days?: number; _slug: string }; @@ -4517,6 +5056,7 @@ export type Database = { verified_purchase: boolean; }[]; }; + manage_collection: { Args: { _payload: Json }; Returns: Json }; mcp_check_and_log_call: { Args: { _identity: string; @@ -4662,8 +5202,16 @@ export type Database = { Returns: number; }; next_sas_code: { Args: never; Returns: string }; + package_vertical_from_rules: { Args: { _rules: Json }; Returns: string }; purchase_pack: { Args: { _pack_id: string }; Returns: Json }; purchase_package: { Args: { _package_id: string }; Returns: Json }; + read_agent_match_selection_cache: { + Args: { p_cache_key: string; p_scope_hash: string }; + Returns: { + age_ms: number; + evidence: Json; + }[]; + }; read_email_batch: { Args: { batch_size: number; queue_name: string; vt: number }; Returns: { @@ -4709,10 +5257,28 @@ export type Database = { }; Returns: string; }; + reserve_search_embedding_batch: { + Args: { _attempt: string; _model: string }; + Returns: string; + }; + reserve_semantic_query: { Args: { _actor: string }; Returns: boolean }; resolve_report: { Args: { _report_id: string; _resolution?: string; _status: string }; Returns: undefined; }; + search_embedding_index_status: { + Args: { _model: string }; + Returns: { + eligible: number; + indexed: number; + inflight: boolean; + ready: boolean; + }[]; + }; + search_embedding_source: { + Args: { _description: string; _long_description: string; _name: string }; + Returns: string; + }; search_packages: { Args: { limit_count?: number; @@ -4730,11 +5296,52 @@ export type Database = { type: string; }[]; }; + search_packages_semantic: { + Args: { + _limit?: number; + _model: string; + _offset?: number; + _query: string; + _type?: string; + }; + Returns: { + latest_version: string; + name: string; + score: number; + slug: string; + snippet: string; + type: string; + }[]; + }; seed_robustness_findings_for: { Args: { _package_id: string }; Returns: number; }; + skill_evidence: { + Args: { + _days?: number; + _experiment?: string; + _model?: string; + _slug: string; + _version?: string; + }; + Returns: { + arm: string; + avg_latency_ms: number; + completed: number; + executions: number; + experiment_key: string; + measured: number; + model: string; + total_tokens: number; + version: string; + }[]; + }; snapshot_package_weekly_metrics: { Args: never; Returns: number }; + submit_authored_package: { + Args: { _author: string; _document: Json }; + Returns: Json; + }; submit_package_feedback: { Args: { _agent_model?: string; @@ -4756,6 +5363,11 @@ export type Database = { }; Returns: string; }; + team_action: { + Args: { _action: string; _payload?: Json; _workspace?: string }; + Returns: Json; + }; + team_role: { Args: { _workspace: string }; Returns: string }; trust_saturate: { Args: { k: number; n: number }; Returns: number }; wilson_lower_bound: | { Args: { successes: number; total: number }; Returns: number } @@ -4763,6 +5375,10 @@ export type Database = { Args: { successes: number; total: number; z?: number }; Returns: number; }; + write_agent_match_selection_cache: { + Args: { p_cache_key: string; p_evidence: Json; p_scope_hash: string }; + Returns: boolean; + }; }; Enums: { app_role: "admin" | "publisher" | "user"; diff --git a/src/lib/auth/optional-user.server.ts b/src/lib/auth/optional-user.server.ts new file mode 100644 index 00000000..51852d1e --- /dev/null +++ b/src/lib/auth/optional-user.server.ts @@ -0,0 +1,32 @@ +import { getRequest } from "@tanstack/react-start/server"; +import { supabaseAdmin } from "@/integrations/supabase/client.server"; + +/** + * Signed-in user id for a public server function, or null when the caller is + * anonymous or the bearer token does not verify. Never throws. + */ +export async function getOptionalUserId(): Promise { + try { + const header = getRequest()?.headers.get("authorization") ?? ""; + if (!header.startsWith("Bearer ")) return null; + const token = header.slice(7).trim(); + if (!token) return null; + const { data, error } = await supabaseAdmin.auth.getClaims(token); + const sub = data?.claims?.sub; + return !error && typeof sub === "string" ? sub : null; + } catch { + return null; + } +} + +/** Server-side admin check for an already-verified user id. */ +export async function isAdminUser(userId: string | null): Promise { + if (!userId) return false; + const { data } = await supabaseAdmin + .from("user_roles") + .select("role") + .eq("user_id", userId) + .eq("role", "admin") + .maybeSingle(); + return !!data; +} diff --git a/src/lib/auth/request-user.server.ts b/src/lib/auth/request-user.server.ts new file mode 100644 index 00000000..0a26edbe --- /dev/null +++ b/src/lib/auth/request-user.server.ts @@ -0,0 +1,14 @@ +import { supabaseAdmin } from "@/integrations/supabase/client.server"; +import { verifyBearer } from "@/lib/auth/bearer.server"; +/** Authentication is optional only for anonymous capability exams, never for owned history. */ +export async function getVerifiedRequestUserId(request: Request): Promise { + const value = request.headers.get("authorization"); + if (!value) return null; + const token = value.match(/^Bearer ([^\s]+)$/i)?.[1]; + if (!token) throw new Response("Unauthorized", { status: 401 }); + const { data, error } = await supabaseAdmin.auth.getUser(token); + if (!error && data.user) return data.user.id; + const bearer = await verifyBearer(token); + if (bearer) return bearer.user_id; + throw new Response("Unauthorized", { status: 401 }); +} diff --git a/src/lib/checkout-quantity.ts b/src/lib/checkout-quantity.ts index 63e0043b..538f07b9 100644 --- a/src/lib/checkout-quantity.ts +++ b/src/lib/checkout-quantity.ts @@ -18,7 +18,61 @@ export function shouldEnableAdjustableQuantity(input: { quantity?: number; adjustableQuantity?: boolean; }): boolean { - if (typeof input.adjustableQuantity === "boolean") return input.adjustableQuantity; - if (input.priceId.startsWith("sak_agent_pass_")) return true; - return typeof input.quantity === "number" && input.quantity > 0; + return isSeatPrice(input.priceId) && input.adjustableQuantity !== false; +} + +/** Seat-based prices (one seat per production agent) are the only ones sold in quantity. */ +export function isSeatPrice(priceId: string): boolean { + return priceId === "sak_agent_pass_monthly"; +} + +/** + * Quantity actually sent to Stripe. Seat prices honour the validated quantity; + * every other price (Pro plans, one-off products) is always sold as exactly 1. + */ +export function resolveCheckoutQuantity(priceId: string, quantity: unknown): number { + const validated = validateCheckoutQuantity(quantity); + return isSeatPrice(priceId) ? validated : 1; +} + +const PROJECT_ID = "b00a8021-9d8d-4f49-a581-628727b71f68"; +const ALLOWED_RETURN_HOSTS = new Set([ + "superagentskill.com", + "www.superagentskill.com", + "agent-evolve-network.lovable.app", +]); + +/** True for this app's own hosts: the custom domain, published app and its previews. */ +export function isAllowedReturnHost(hostname: string): boolean { + const host = hostname.toLowerCase(); + if (ALLOWED_RETURN_HOSTS.has(host)) return true; + return new Set([ + `id-preview--${PROJECT_ID}.lovable.app`, + `preview--${PROJECT_ID}.lovable.app`, + `project--${PROJECT_ID}.lovable.app`, + ]).has(host); +} + +/** + * Accept a checkout / billing return URL only when it points back at this app. + * Throws for any other destination so Stripe never redirects buyers elsewhere. + */ +export function validateReturnUrl(returnUrl: unknown): string { + if (typeof returnUrl !== "string" || returnUrl.length > 2048) { + throw new Error("Invalid return URL"); + } + let url: URL; + try { + url = new URL(returnUrl); + } catch { + throw new Error("Invalid return URL"); + } + const local = url.hostname === "localhost" || url.hostname === "127.0.0.1"; + if (url.protocol !== "https:" && !(local && url.protocol === "http:")) { + throw new Error("Invalid return URL"); + } + if (url.port || url.username || url.password || !isAllowedReturnHost(url.hostname)) { + throw new Error("Invalid return URL"); + } + return returnUrl; } diff --git a/src/lib/favorites/favorites.functions.ts b/src/lib/favorites/favorites.functions.ts index 86ef8003..e069830e 100644 --- a/src/lib/favorites/favorites.functions.ts +++ b/src/lib/favorites/favorites.functions.ts @@ -1,7 +1,6 @@ import { createServerFn } from "@tanstack/react-start"; -import { supabaseAdmin as _supabaseAdmin } from "@/integrations/supabase/client.server"; -const supabaseAdmin = _supabaseAdmin; import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware"; +import type { AppDatabaseClient } from "@/integrations/supabase/database"; export type StarState = { packageId: string | null; @@ -20,8 +19,15 @@ export type StarredPackage = { starred_at: string; }; -async function packageBySlug(slug: string): Promise<{ id: string; star_count: number } | null> { - const { data } = await supabaseAdmin +/** + * Look a package up as the signed-in user, so database visibility rules apply: + * only published + approved packages (or the caller's own) are found. + */ +async function packageBySlug( + db: AppDatabaseClient, + slug: string, +): Promise<{ id: string; star_count: number } | null> { + const { data } = await db .from("packages") .select("id, star_count") .eq("slug", slug) @@ -38,10 +44,10 @@ export const toggleStar = createServerFn({ method: "POST" }) return { slug: o.slug }; }) .handler(async ({ data, context }): Promise => { - const pkg = await packageBySlug(data.slug); + const db = context.supabase; + const pkg = await packageBySlug(db, data.slug); if (!pkg) throw new Response("PACKAGE_NOT_FOUND", { status: 404 }); - const db = context.supabase; const { data: existing } = await db .from("package_stars") .select("package_id") @@ -66,7 +72,7 @@ export const toggleStar = createServerFn({ method: "POST" }) } } - const fresh = await packageBySlug(data.slug); + const fresh = await packageBySlug(db, data.slug); return { packageId: pkg.id, starred: !existing, @@ -83,9 +89,9 @@ export const isStarred = createServerFn({ method: "GET" }) return { slug: o.slug }; }) .handler(async ({ data, context }): Promise => { - const pkg = await packageBySlug(data.slug); - if (!pkg) return { packageId: null, starred: false, star_count: 0 }; const db = context.supabase; + const pkg = await packageBySlug(db, data.slug); + if (!pkg) return { packageId: null, starred: false, star_count: 0 }; const { data: row } = await db .from("package_stars") .select("package_id") @@ -110,7 +116,8 @@ export const getMyStars = createServerFn({ method: "GET" }) const rows = (stars ?? []) as { package_id: string; created_at: string }[]; if (rows.length === 0) return { packages: [] }; - const { data: pkgs, error: pkgErr } = await supabaseAdmin + // Read as the user: a star on a package the user cannot see returns nothing. + const { data: pkgs, error: pkgErr } = await db .from("packages") .select("id, slug, name, type, description, latest_version, star_count") .in( diff --git a/src/lib/marketplace/content-access.server.ts b/src/lib/marketplace/content-access.server.ts new file mode 100644 index 00000000..f3e03b7d --- /dev/null +++ b/src/lib/marketplace/content-access.server.ts @@ -0,0 +1,34 @@ +import { supabaseAdmin } from "@/integrations/supabase/client.server"; +export async function canReadPackageContent( + pkg: { id: string; author_id: string | null; price_credits: number }, + userId: string | null, +): Promise { + if (pkg.price_credits === 0) return true; + if (!userId) return false; + if (pkg.author_id === userId) return true; + const [role, purchase, packs] = await Promise.all([ + supabaseAdmin + .from("user_roles") + .select("role") + .eq("user_id", userId) + .eq("role", "admin") + .maybeSingle(), + supabaseAdmin + .from("package_purchases") + .select("id") + .eq("buyer_id", userId) + .eq("package_id", pkg.id) + .limit(1), + supabaseAdmin.from("pack_purchases").select("pack_id").eq("buyer_id", userId), + ]); + if (role.data || purchase.data?.length) return true; + const ids = (packs.data ?? []).map((p) => p.pack_id); + if (!ids.length) return false; + const { data } = await supabaseAdmin + .from("pack_items") + .select("pack_id") + .in("pack_id", ids) + .eq("package_id", pkg.id) + .limit(1); + return !!data?.length; +} diff --git a/src/lib/marketplace/detail.functions.ts b/src/lib/marketplace/detail.functions.ts index 7c33a79a..0826ad77 100644 --- a/src/lib/marketplace/detail.functions.ts +++ b/src/lib/marketplace/detail.functions.ts @@ -61,13 +61,16 @@ export const getPackageDetail = createServerFn({ method: "GET" }) const { data: pkg, error } = await supabaseAdmin .from("packages") .select( - "id, slug, name, type, description, long_description, author_handle, author_verified, install_count, latest_version, price_credits, license, scopes, is_published, review_status", + "id, slug, name, type, description, long_description, author_handle, author_verified, install_count, latest_version, price_credits, license, scopes, is_published, review_status, vertical", ) .eq("slug", data.slug) .maybeSingle(); if (error) throw new Response(error.message, { status: 500 }); if (!pkg || !pkg.is_published || pkg.review_status !== "approved") return null; + // Instructions (system prompt + rules) are public only for free packages; + // paid ones are delivered to purchasers through the install flow. + const isFree = (pkg.price_credits ?? 0) === 0; const { data: versions } = await supabaseAdmin .from("package_versions") .select( @@ -92,8 +95,11 @@ export const getPackageDetail = createServerFn({ method: "GET" }) supabaseAdmin.from("reviews").select("rating").eq("package_id", pkg.id), ]); const compatibility = normCompat(compatibilityData); - const examples = latest ? normExamples(latest.examples) : []; - const rules = (latest?.rules ?? {}) as Record; + const examples = isFree && latest ? normExamples(latest.examples) : []; + // Read server-side (prompt hash for evidence) but returned only when free. + const rules = (isFree ? (latest.rules ?? {}) : {}) as Record; + const systemPrompt = + isFree && typeof latest.system_prompt === "string" ? latest.system_prompt : undefined; const versionPerms = asArr(latest?.permissions).filter( (s): s is string => typeof s === "string", ); @@ -134,10 +140,9 @@ export const getPackageDetail = createServerFn({ method: "GET" }) license: (pkg.license as string) ?? "—", examples, metrics: [], - vertical: typeof rules.vertical === "string" ? (rules.vertical as string) : undefined, + vertical: pkg.vertical ?? undefined, reviewStatus: (pkg.review_status as string) ?? undefined, - systemPrompt: - typeof latest?.system_prompt === "string" ? (latest.system_prompt as string) : undefined, + systemPrompt, }; return { pkg: out }; }); diff --git a/src/lib/marketplace/discover.functions.ts b/src/lib/marketplace/discover.functions.ts index 4728b73b..bee12b31 100644 --- a/src/lib/marketplace/discover.functions.ts +++ b/src/lib/marketplace/discover.functions.ts @@ -83,7 +83,7 @@ async function fetchTypeCatalog(type: DiscoverType): Promise { const { data: pkgs, error } = await supabaseAdmin .from("packages") .select( - "id, slug, name, type, description, author_handle, author_verified, install_count, latest_version, price_credits, created_at", + "id, slug, name, type, description, author_handle, author_verified, install_count, latest_version, price_credits, created_at, vertical", ) .eq("is_published", true) .eq("review_status", "approved") @@ -93,22 +93,9 @@ async function fetchTypeCatalog(type: DiscoverType): Promise { const verticalByPkg = new Map(); if (pkgs && pkgs.length) { - const ids = pkgs.map((r) => r.id); - const latestByPkg = new Map(pkgs.map((r) => [r.id, r.latest_version])); - const { data: vers } = await supabaseAdmin - .from("package_versions") - .select("package_id, version, rules") - .in("package_id", ids); - for (const v of vers ?? []) { - if (v.version !== latestByPkg.get(v.package_id)) continue; - const rules = (v.rules ?? {}) as Record; - const vertical = - (typeof rules.vertical === "string" && rules.vertical) || - (typeof rules.category === "string" && rules.category) || - (typeof rules.domain === "string" && rules.domain) || - null; - verticalByPkg.set(v.package_id, vertical || null); - } + // Classification is public package metadata, kept in sync from the + // latest version by the database — version content is never read here. + for (const p of pkgs ?? []) verticalByPkg.set(p.id, p.vertical ?? null); } const rows: CatalogRow[] = (pkgs ?? []).map((p) => { diff --git a/src/lib/marketplace/list.functions.ts b/src/lib/marketplace/list.functions.ts index 248a7f52..5f911bf7 100644 --- a/src/lib/marketplace/list.functions.ts +++ b/src/lib/marketplace/list.functions.ts @@ -36,7 +36,7 @@ async function fetchMarketplace(): Promise { const { data: pkgs, error } = await supabaseAdmin .from("packages") .select( - "id, slug, name, type, description, author_handle, author_verified, install_count, latest_version, created_at, price_credits", + "id, slug, name, type, description, author_handle, author_verified, install_count, latest_version, created_at, price_credits, vertical", ) .eq("is_published", true) .eq("review_status", "approved") @@ -48,21 +48,9 @@ async function fetchMarketplace(): Promise { const ids = (pkgs ?? []).map((p) => p.id); const verticalByPkg = new Map(); if (ids.length) { - const { data: vers } = await supabaseAdmin - .from("package_versions") - .select("package_id, version, rules") - .in("package_id", ids); - const latestByPkg = new Map((pkgs ?? []).map((p) => [p.id, p.latest_version])); - for (const v of vers ?? []) { - if (v.version !== latestByPkg.get(v.package_id)) continue; - const rules = (v.rules ?? {}) as Record; - const vertical = - (typeof rules.vertical === "string" && rules.vertical) || - (typeof rules.category === "string" && rules.category) || - (typeof rules.domain === "string" && rules.domain) || - null; - verticalByPkg.set(v.package_id, vertical || null); - } + // Classification is public package metadata, kept in sync from the + // latest version by the database — version content is never read here. + for (const p of pkgs ?? []) verticalByPkg.set(p.id, p.vertical ?? null); } // Aggregate ratings per package (single grouped query) diff --git a/src/lib/marketplace/telemetry.functions.ts b/src/lib/marketplace/telemetry.functions.ts index 848edbe2..12e837bc 100644 --- a/src/lib/marketplace/telemetry.functions.ts +++ b/src/lib/marketplace/telemetry.functions.ts @@ -35,13 +35,6 @@ export const getEvaluationData = createServerFn({ method: "GET" }).handler( const w30 = (t.window_30d ?? {}) as Record; const lifetime = (t.lifetime ?? {}) as Record; - const { data: last } = await supabaseAdmin - .from("skill_executions") - .select("created_at") - .eq("package_id", p.id) - .order("created_at", { ascending: false }) - .limit(1); - rows.push({ slug: p.slug, name: p.name, @@ -51,7 +44,7 @@ export const getEvaluationData = createServerFn({ method: "GET" }).handler( ok30d: Math.round(Number(w30.runs ?? 0) * Number(w30.success_rate ?? 0)), successRate30d: w30.success_rate != null ? Number(w30.success_rate) : null, p95Latency: w30.p95_latency_ms != null ? Number(w30.p95_latency_ms) : null, - lastRunAt: last?.[0]?.created_at ?? null, + lastRunAt: null, // Individual execution timing is private. trustScore: t.trust_score != null ? Number(t.trust_score) : null, criticalFindings: Number(t.findings_critical ?? 0), battleTested: !!t.battle_tested, diff --git a/src/lib/mcp/tools/skills.ts b/src/lib/mcp/tools/skills.ts index 81cf7cc3..f01b6a0a 100644 --- a/src/lib/mcp/tools/skills.ts +++ b/src/lib/mcp/tools/skills.ts @@ -237,24 +237,30 @@ export const getPackageTool = defineTool({ parameters: z.object({ slug: z.string().describe("Package slug (e.g. cardiology-soul)"), }), - execute: async ({ slug }) => { + execute: async ({ slug }, ctx) => { const { data: pkg, error } = await supabaseAdmin .from("packages") - .select("id,slug,name,type,description,long_description,latest_version,author_handle") + .select( + "id,slug,name,type,description,long_description,latest_version,author_handle,author_id,price_credits", + ) .eq("slug", slug) .eq("is_published", true) .eq("review_status", "approved") .maybeSingle(); if (error) return json({ error: error.message }); if (!pkg) return json({ error: "not_found" }); + const { canReadPackageContent } = await import("@/lib/marketplace/content-access.server"); + const userId = (ctx.auth?.claims as { user_id?: string } | undefined)?.user_id ?? null; + if (!(await canReadPackageContent(pkg, userId))) return json({ error: "purchase_required" }); const { data: ver } = await supabaseAdmin .from("package_versions") .select("version,status,system_prompt,rules,examples,compatibility,notes") .eq("package_id", pkg.id) - .order("created_at", { ascending: false }) + .eq("version", pkg.latest_version) .limit(1) .maybeSingle(); - return json({ package: pkg, version: ver }); + const { author_id: _authorId, ...publicPackage } = pkg; + return json({ package: publicPackage, version: ver }); }, }); diff --git a/src/lib/mcp/tools/university.ts b/src/lib/mcp/tools/university.ts index 43a32d84..a942d6f0 100644 --- a/src/lib/mcp/tools/university.ts +++ b/src/lib/mcp/tools/university.ts @@ -115,8 +115,9 @@ export const diagnoseSubmitTool = defineTool({ .min(1) .max(80), }), - execute: async (input) => { + execute: async (input, ctx) => { const report = await submitExam({ + userId: userIdOf(ctx), diagnosisId: input.diagnosis_id ?? null, domain: input.domain as DomainId | undefined, answers: input.answers, @@ -143,12 +144,12 @@ export const curriculumNextTool = defineTool({ .optional() .describe("Max capabilities this agent should carry (default 14)."), }), - execute: async (input) => { + execute: async (input, ctx) => { let profile: ErrorProfileEntry[] | undefined; let installed = input.installed_skills; let domain = input.domain as DomainId | undefined; if (input.diagnosis_id) { - const d = await getDiagnosisForCurriculum(input.diagnosis_id); + const d = await getDiagnosisForCurriculum(input.diagnosis_id, userIdOf(ctx)); if (d) { profile = d.error_profile; domain = domain ?? d.domain; diff --git a/src/lib/packs/packs.functions.ts b/src/lib/packs/packs.functions.ts index 811cbb39..d24fc975 100644 --- a/src/lib/packs/packs.functions.ts +++ b/src/lib/packs/packs.functions.ts @@ -176,6 +176,19 @@ export const runCustomization = createServerFn({ method: "POST" }) .single(); if (cErr || !cust) throw new Response("Customization not found", { status: 404 }); if (cust.status === "ready") return { status: "ready" as const }; + // A run is only for a queued (or previously failed) request on a pack the + // caller has actually bought — re-checked here, never trusted from the row. + if (cust.status !== "queued" && cust.status !== "error") { + throw new Response("Customization already in progress", { status: 409 }); + } + const { data: purchase } = await supabaseAdmin + .from("pack_purchases") + .select("id") + .eq("buyer_id", userId) + .eq("pack_id", cust.pack_id) + .maybeSingle(); + if (!purchase) + throw new Response("You must purchase this pack before customizing it.", { status: 403 }); // Load pack + items + latest version content const { data: pack } = await supabaseAdmin diff --git a/src/lib/payments.functions.ts b/src/lib/payments.functions.ts index 15e682f6..c4ad4764 100644 --- a/src/lib/payments.functions.ts +++ b/src/lib/payments.functions.ts @@ -1,6 +1,11 @@ import { createServerFn } from "@tanstack/react-start"; import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware"; -import { shouldEnableAdjustableQuantity, validateCheckoutQuantity } from "@/lib/checkout-quantity"; +import { + isSeatPrice, + resolveCheckoutQuantity, + shouldEnableAdjustableQuantity, + validateReturnUrl, +} from "@/lib/checkout-quantity"; import { type StripeEnv, createStripeClient, getStripeErrorMessage } from "@/lib/stripe.server"; export type CheckoutSessionResult = { clientSecret: string } | { error: string }; @@ -29,18 +34,6 @@ async function resolveOrCreateCustomer( }); if (found.data.length) return found.data[0].id; } - if (options.email) { - const existing = await stripe.customers.list({ email: options.email, limit: 1 }); - if (existing.data.length) { - const customer = existing.data[0]; - if (options.userId && customer.metadata?.userId !== options.userId) { - await stripe.customers.update(customer.id, { - metadata: { ...customer.metadata, userId: options.userId }, - }); - } - return customer.id; - } - } const created = await stripe.customers.create({ ...(options.email && { email: options.email }), ...(options.userId && { metadata: { userId: options.userId } }), @@ -52,8 +45,21 @@ export const createCheckoutSession = createServerFn({ method: "POST" }) .middleware([requireSupabaseAuth]) .inputValidator((data: CheckoutSessionInput) => { if (!/^[a-zA-Z0-9_-]+$/.test(data.priceId)) throw new Error("Invalid priceId"); - const quantity = validateCheckoutQuantity(data.quantity); - return { ...data, quantity }; + if (data.environment !== "sandbox" && data.environment !== "live") { + throw new Error("Invalid environment"); + } + // Only seat-based prices can be bought in quantity; everything else is 1. + const quantity = resolveCheckoutQuantity(data.priceId, data.quantity); + const returnUrl = validateReturnUrl(data.returnUrl); + return { + priceId: data.priceId, + quantity, + ...(typeof data.adjustableQuantity === "boolean" && { + adjustableQuantity: data.adjustableQuantity, + }), + returnUrl, + environment: data.environment, + }; }) .handler(async ({ data, context }): Promise => { // Always derive identity from the verified session — never trust client input. @@ -80,11 +86,13 @@ export const createCheckoutSession = createServerFn({ method: "POST" }) } const quantity = data.quantity || 1; - const adjustable = shouldEnableAdjustableQuantity({ - priceId: data.priceId, - quantity, - adjustableQuantity: data.adjustableQuantity, - }); + const adjustable = + isSeatPrice(data.priceId) && + shouldEnableAdjustableQuantity({ + priceId: data.priceId, + quantity, + adjustableQuantity: data.adjustableQuantity, + }); const session = await stripe.checkout.sessions.create({ line_items: [ @@ -119,7 +127,15 @@ export const createCheckoutSession = createServerFn({ method: "POST" }) export const createPortalSession = createServerFn({ method: "POST" }) .middleware([requireSupabaseAuth]) - .inputValidator((data: { returnUrl?: string; environment: StripeEnv }) => data) + .inputValidator((data: { returnUrl?: string; environment: StripeEnv }) => { + if (data.environment !== "sandbox" && data.environment !== "live") { + throw new Error("Invalid environment"); + } + return { + environment: data.environment, + ...(data.returnUrl !== undefined && { returnUrl: validateReturnUrl(data.returnUrl) }), + }; + }) .handler(async ({ data, context }): Promise => { const { supabase: _sbCtx, userId } = context; const supabase = _sbCtx; diff --git a/src/lib/skills/compatibility.functions.ts b/src/lib/skills/compatibility.functions.ts index 821d1c81..84f1e2f2 100644 --- a/src/lib/skills/compatibility.functions.ts +++ b/src/lib/skills/compatibility.functions.ts @@ -84,12 +84,21 @@ export const runCompatibilitySweep = createServerFn({ method: "POST" }) export const getCompatibility = createServerFn({ method: "GET" }) .inputValidator((d: { slug: string }) => z.object({ slug: z.string().min(1) }).parse(d)) .handler(async ({ data }) => { + // Public: only packages that are published and approved expose results. + const { data: pkg } = await supabaseAdmin + .from("packages") + .select("id") + .eq("slug", data.slug) + .eq("is_published", true) + .eq("review_status", "approved") + .maybeSingle(); + if (!pkg) return { rows: [] }; const { data: rows } = await supabaseAdmin .from("skill_compatibility") .select( "model,pass_rate,total_cases,passed_cases,judge_score,status,notes,version,evaluated_at", ) - .eq("package_slug", data.slug) + .eq("package_id", pkg.id) .order("judge_score", { ascending: false }); return { rows: rows ?? [] }; }); diff --git a/src/lib/university/diagnosis-access.ts b/src/lib/university/diagnosis-access.ts new file mode 100644 index 00000000..1bb4e8d6 --- /dev/null +++ b/src/lib/university/diagnosis-access.ts @@ -0,0 +1,23 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +export function diagnosisCapability(id: string, secret: string): string { + if (!secret || !UUID.test(id)) throw new Error("Invalid diagnosis capability configuration"); + return `${id}.${createHmac("sha256", secret).update(`anonymous-diagnosis:${id}`).digest("hex")}`; +} +export function diagnosisId(reference: string): string | null { + const id = reference.split(".")[0]; + return UUID.test(id) ? id : null; +} +export function canAccessDiagnosis( + ownerId: string | null, + userId: string | null, + reference: string, + secret: string, +): boolean { + if (ownerId !== null) return ownerId === userId; + const id = diagnosisId(reference); + if (!id || !secret) return false; + const expected = Buffer.from(diagnosisCapability(id, secret)); + const supplied = Buffer.from(reference); + return supplied.length === expected.length && timingSafeEqual(supplied, expected); +} diff --git a/src/lib/university/university.functions.ts b/src/lib/university/university.functions.ts index bb91f64e..13e311e4 100644 --- a/src/lib/university/university.functions.ts +++ b/src/lib/university/university.functions.ts @@ -4,6 +4,8 @@ import type { ErrorProfileEntry, Prescription } from "@/lib/university/types"; * Module scope holds only imports + createServerFn declarations (server-fn * splitting strips runtime siblings). */ +import { getRequest } from "@tanstack/react-start/server"; +import { getVerifiedRequestUserId } from "@/lib/auth/request-user.server"; import { createServerFn } from "@tanstack/react-start"; import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware"; import { z } from "zod"; @@ -30,6 +32,7 @@ export const startDiagnosis = createServerFn({ method: "POST" }) ) .handler(async ({ data }) => startExam({ + userId: await getVerifiedRequestUserId(getRequest()), domain: data.domain as DomainId, installedSkills: data.installed_skills, agentFp: data.agent_fp ?? null, @@ -40,7 +43,7 @@ export const submitDiagnosis = createServerFn({ method: "POST" }) .inputValidator((d: unknown) => z .object({ - diagnosis_id: z.string().uuid().optional(), + diagnosis_id: z.string().max(140).optional(), domain: DomainEnum.optional(), installed_skills: z.array(z.string()).max(64).default([]), answers: z @@ -59,6 +62,7 @@ export const submitDiagnosis = createServerFn({ method: "POST" }) ) .handler(async ({ data }) => submitExam({ + userId: await getVerifiedRequestUserId(getRequest()), diagnosisId: data.diagnosis_id ?? null, domain: data.domain as DomainId | undefined, answers: data.answers, @@ -70,7 +74,7 @@ export const getCurriculumPlan = createServerFn({ method: "POST" }) .inputValidator((d: unknown) => z .object({ - diagnosis_id: z.string().uuid().optional(), + diagnosis_id: z.string().max(140).optional(), domain: DomainEnum.optional(), failing: z .array( @@ -95,7 +99,10 @@ export const getCurriculumPlan = createServerFn({ method: "POST" }) let installed = data.installed_skills; let domain = data.domain as DomainId | undefined; if (data.diagnosis_id) { - const d = await getDiagnosisForCurriculum(data.diagnosis_id); + const d = await getDiagnosisForCurriculum( + data.diagnosis_id, + await getVerifiedRequestUserId(getRequest()), + ); if (d) { profile = d.error_profile; domain = domain ?? d.domain; diff --git a/src/lib/university/university.server.ts b/src/lib/university/university.server.ts index 15944251..68590aa9 100644 --- a/src/lib/university/university.server.ts +++ b/src/lib/university/university.server.ts @@ -1,3 +1,8 @@ +import { + canAccessDiagnosis, + diagnosisCapability, + diagnosisId as parseDiagnosisId, +} from "./diagnosis-access"; import { z } from "zod"; import { ERROR_CLASSES } from "./types"; const ErrorProfileSchema = z.array( @@ -15,7 +20,7 @@ import type { ErrorProfileEntry, Prescription } from "@/lib/university/types"; * * Rows are written with the admin client (the exam runs anonymously too), and * read back only through owner-scoped helpers — anonymous rows (user_id null) - * are reachable only by whoever holds the diagnosis id. + * require a signed capability; knowing a row UUID alone is never authorization. */ import { supabaseAdmin as _supabaseAdmin } from "@/integrations/supabase/client.server"; import { buildReport, sampleExam } from "./diagnose"; @@ -63,7 +68,10 @@ export async function startExam(args: { } return { - diagnosis_id: diagnosisId, + diagnosis_id: + diagnosisId && !args.userId + ? diagnosisCapability(diagnosisId, process.env.SUPABASE_SERVICE_ROLE_KEY ?? "") + : diagnosisId, domain: args.domain, case_count: cases.length, tasks: cases.map((c) => ({ @@ -76,7 +84,10 @@ export async function startExam(args: { }; } -export async function loadExam(diagnosisId: string): Promise<{ +export async function loadExam( + diagnosisId: string, + userId: string | null = null, +): Promise<{ domain: DomainId; case_ids: string[]; installed_skills: string[]; @@ -85,9 +96,18 @@ export async function loadExam(diagnosisId: string): Promise<{ const { data } = await supabaseAdmin .from("agent_diagnoses") .select("domain,case_ids,installed_skills,user_id") - .eq("id", diagnosisId) + .eq("id", parseDiagnosisId(diagnosisId) ?? "00000000-0000-0000-0000-000000000000") .maybeSingle(); - if (!data) return null; + if ( + !data || + !canAccessDiagnosis( + data.user_id, + userId, + diagnosisId, + process.env.SUPABASE_SERVICE_ROLE_KEY ?? "", + ) + ) + return null; return { domain: data.domain as DomainId, case_ids: (data.case_ids ?? []) as string[], @@ -98,6 +118,7 @@ export async function loadExam(diagnosisId: string): Promise<{ export async function submitExam(args: { diagnosisId?: string | null; + userId?: string | null; domain?: DomainId; answers: CaseAnswer[]; installedSkills?: string[]; @@ -107,7 +128,8 @@ export async function submitExam(args: { let installed = args.installedSkills ?? []; if (args.diagnosisId) { - const exam = await loadExam(args.diagnosisId); + const exam = await loadExam(args.diagnosisId, args.userId ?? null); + if (!exam) throw new Response("Diagnosis not found", { status: 404 }); if (exam) { domain = exam.domain; caseIds = exam.case_ids; @@ -130,9 +152,9 @@ export async function submitExam(args: { }); if (args.diagnosisId) { - const diagnosisId = args.diagnosisId; + const diagnosisId = parseDiagnosisId(args.diagnosisId)!; try { - await supabaseAdmin + const { data: updated } = await supabaseAdmin .from("agent_diagnoses") .update({ status: "scored", @@ -141,7 +163,10 @@ export async function submitExam(args: { prescription: report.prescription, bottleneck: report.bottleneck, }) - .eq("id", args.diagnosisId); + .eq("id", diagnosisId) + .eq("status", "open") + .select("id"); + if (!updated?.length) return report; await supabaseAdmin.from("agent_diagnosis_items").insert( report.results.map((r) => ({ @@ -187,17 +212,29 @@ export async function listDiagnoses(userId: string, limit = 20): Promise { const { data } = await supabaseAdmin .from("agent_diagnoses") - .select("domain,error_profile,installed_skills") - .eq("id", diagnosisId) + .select("domain,error_profile,installed_skills,user_id") + .eq("id", parseDiagnosisId(diagnosisId) ?? "00000000-0000-0000-0000-000000000000") .maybeSingle(); - if (!data) return null; + if ( + !data || + !canAccessDiagnosis( + data.user_id, + userId, + diagnosisId, + process.env.SUPABASE_SERVICE_ROLE_KEY ?? "", + ) + ) + return null; return { domain: data.domain as DomainId, error_profile: ErrorProfileSchema.parse(data.error_profile ?? []), diff --git a/src/routes/api/public/crm/run.ts b/src/routes/api/public/crm/run.ts index 1a9ba37a..ed5a9212 100644 --- a/src/routes/api/public/crm/run.ts +++ b/src/routes/api/public/crm/run.ts @@ -2,31 +2,19 @@ import { errorField } from "@/lib/errors"; import { createFileRoute } from "@tanstack/react-router"; /** - * Hourly CRM cadence runner, called by pg_cron with the project apikey. + * Hourly CRM cadence runner, called by the managed scheduler with the private cron secret. * Evaluates every customer, sends at most one lifecycle email each, and * respects the global cadence caps (2 emails / 7 days, 48h apart). */ -function authorized(request: Request): boolean { - const expected = [ - process.env["SUPABASE_PUBLISHABLE_KEY"], - process.env["SUPABASE_ANON_KEY"], - process.env["VITE_SUPABASE_PUBLISHABLE_KEY"], - process.env["SUPABASE_SERVICE_ROLE_KEY"], - ].filter(Boolean) as string[]; - const url = new URL(request.url); - const provided = - request.headers.get("apikey") ?? - request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? - url.searchParams.get("apikey") ?? - ""; - return !!provided && expected.includes(provided); -} export const Route = createFileRoute("/api/public/crm/run")({ server: { handlers: { POST: async ({ request }) => { - if (!authorized(request)) return Response.json({ error: "Unauthorized" }, { status: 401 }); + // Only the scheduler holds the private cron secret; the public site key is not accepted. + const { authenticateCronRequest } = await import("@/integrations/supabase/cron-auth"); + const denied = await authenticateCronRequest(request); + if (denied) return denied; let dryRun = false; let maxSends = 200; diff --git a/src/routes/api/public/crm/score.ts b/src/routes/api/public/crm/score.ts index b60f076b..f29ba537 100644 --- a/src/routes/api/public/crm/score.ts +++ b/src/routes/api/public/crm/score.ts @@ -2,31 +2,19 @@ import { errorField } from "@/lib/errors"; import { createFileRoute } from "@tanstack/react-router"; /** - * Hourly outcome scorer, called by pg_cron with the project apikey. + * Hourly outcome scorer, called by the managed scheduler with the private cron secret. * Decides, per sent message, whether the intended outcome happened inside the * trigger's attribution window, and closes the window when it expires. */ -function authorized(request: Request): boolean { - const expected = [ - process.env["SUPABASE_PUBLISHABLE_KEY"], - process.env["SUPABASE_ANON_KEY"], - process.env["VITE_SUPABASE_PUBLISHABLE_KEY"], - process.env["SUPABASE_SERVICE_ROLE_KEY"], - ].filter(Boolean) as string[]; - const url = new URL(request.url); - const provided = - request.headers.get("apikey") ?? - request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? - url.searchParams.get("apikey") ?? - ""; - return !!provided && expected.includes(provided); -} export const Route = createFileRoute("/api/public/crm/score")({ server: { handlers: { POST: async ({ request }) => { - if (!authorized(request)) return Response.json({ error: "Unauthorized" }, { status: 401 }); + // Only the scheduler holds the private cron secret; the public site key is not accepted. + const { authenticateCronRequest } = await import("@/integrations/supabase/cron-auth"); + const denied = await authenticateCronRequest(request); + if (denied) return denied; try { const { scoreOutcomes } = await import("@/lib/crm/learning.server"); const result = await scoreOutcomes(500); diff --git a/src/routes/api/public/crm/tune.ts b/src/routes/api/public/crm/tune.ts index 610b6b48..9f5a8eec 100644 --- a/src/routes/api/public/crm/tune.ts +++ b/src/routes/api/public/crm/tune.ts @@ -2,31 +2,19 @@ import { errorField } from "@/lib/errors"; import { createFileRoute } from "@tanstack/react-router"; /** - * Weekly self-tuner, called by pg_cron with the project apikey. + * Weekly self-tuner, called by the managed scheduler with the private cron secret. * Recomputes variant statistics, pauses statistically losing copy variants and * drafts replacements that wait for human approval. */ -function authorized(request: Request): boolean { - const expected = [ - process.env["SUPABASE_PUBLISHABLE_KEY"], - process.env["SUPABASE_ANON_KEY"], - process.env["VITE_SUPABASE_PUBLISHABLE_KEY"], - process.env["SUPABASE_SERVICE_ROLE_KEY"], - ].filter(Boolean) as string[]; - const url = new URL(request.url); - const provided = - request.headers.get("apikey") ?? - request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? - url.searchParams.get("apikey") ?? - ""; - return !!provided && expected.includes(provided); -} export const Route = createFileRoute("/api/public/crm/tune")({ server: { handlers: { POST: async ({ request }) => { - if (!authorized(request)) return Response.json({ error: "Unauthorized" }, { status: 401 }); + // Only the scheduler holds the private cron secret; the public site key is not accepted. + const { authenticateCronRequest } = await import("@/integrations/supabase/cron-auth"); + const denied = await authenticateCronRequest(request); + if (denied) return denied; let dryRun = false; try { const body = (await request.json()) as { dry_run?: boolean }; diff --git a/src/routes/api/public/curriculum/next.ts b/src/routes/api/public/curriculum/next.ts index 9a11f83d..71889cc2 100644 --- a/src/routes/api/public/curriculum/next.ts +++ b/src/routes/api/public/curriculum/next.ts @@ -1,3 +1,4 @@ +import { getVerifiedRequestUserId } from "@/lib/auth/request-user.server"; import type { ErrorProfileEntry, Prescription } from "@/lib/university/types"; import { createFileRoute } from "@tanstack/react-router"; import { getDiagnosisForCurriculum } from "@/lib/university/university.server"; @@ -59,7 +60,11 @@ export const Route = createFileRoute("/api/public/curriculum/next")({ let domain = typeof body.domain === "string" ? (body.domain as DomainId) : undefined; if (typeof body.diagnosis_id === "string") { - const d = await getDiagnosisForCurriculum(body.diagnosis_id); + const d = await getDiagnosisForCurriculum( + body.diagnosis_id, + await getVerifiedRequestUserId(request), + ); + if (!d) return json({ ok: false, error: "diagnosis_unavailable" }, 404); if (d) { profile = d.error_profile; domain = domain ?? d.domain; diff --git a/src/routes/api/public/diagnose/start.ts b/src/routes/api/public/diagnose/start.ts index e3ac452e..2b5984f4 100644 --- a/src/routes/api/public/diagnose/start.ts +++ b/src/routes/api/public/diagnose/start.ts @@ -1,3 +1,4 @@ +import { getVerifiedRequestUserId } from "@/lib/auth/request-user.server"; import { createFileRoute } from "@tanstack/react-router"; import { startExam } from "@/lib/university/university.server"; import { DOMAINS, type DomainId } from "@/lib/university/types"; @@ -69,6 +70,7 @@ export const Route = createFileRoute("/api/public/diagnose/start")({ : 40; const exam = await startExam({ + userId: await getVerifiedRequestUserId(request), domain: domain as DomainId, installedSkills: installed, agentFp: typeof body.agent_fp === "string" ? body.agent_fp.slice(0, 120) : null, diff --git a/src/routes/api/public/diagnose/submit.ts b/src/routes/api/public/diagnose/submit.ts index 3ccaad46..ee8bbc4d 100644 --- a/src/routes/api/public/diagnose/submit.ts +++ b/src/routes/api/public/diagnose/submit.ts @@ -1,3 +1,4 @@ +import { getVerifiedRequestUserId } from "@/lib/auth/request-user.server"; import { errorField } from "@/lib/errors"; import { createFileRoute } from "@tanstack/react-router"; import { submitExam } from "@/lib/university/university.server"; @@ -63,6 +64,7 @@ export const Route = createFileRoute("/api/public/diagnose/submit")({ try { const report = await submitExam({ + userId: await getVerifiedRequestUserId(request), diagnosisId: typeof body.diagnosis_id === "string" ? body.diagnosis_id : null, domain: typeof body.domain === "string" ? (body.domain as DomainId) : undefined, answers, @@ -72,6 +74,8 @@ export const Route = createFileRoute("/api/public/diagnose/submit")({ }); return json({ ok: true, ...report }); } catch (err) { + if (err instanceof Response) + return json({ ok: false, error: "diagnosis_unavailable" }, err.status); const msg = err instanceof Error ? errorField(err, "message") : "error"; if (msg === "unknown_domain") { return json( diff --git a/src/routes/api/public/packages.$slug.ts b/src/routes/api/public/packages.$slug.ts index 9e281bf3..69e43986 100644 --- a/src/routes/api/public/packages.$slug.ts +++ b/src/routes/api/public/packages.$slug.ts @@ -1,3 +1,5 @@ +import { canReadPackageContent } from "@/lib/marketplace/content-access.server"; +import { getVerifiedRequestUserId } from "@/lib/auth/request-user.server"; import { createFileRoute } from "@tanstack/react-router"; import { loadPublicEvaluationCompatibility } from "@/lib/plugins/public-compatibility-loader.server"; import { supabaseAdmin as _supabaseAdmin } from "@/integrations/supabase/client.server"; @@ -6,7 +8,7 @@ const supabaseAdmin = _supabaseAdmin; const CORS = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, OPTIONS", - "Access-Control-Allow-Headers": "Content-Type, Accept", + "Access-Control-Allow-Headers": "Content-Type, Accept, Authorization", }; // GET /api/public/packages/ @@ -16,11 +18,11 @@ export const Route = createFileRoute("/api/public/packages/$slug")({ server: { handlers: { OPTIONS: async () => new Response(null, { status: 204, headers: CORS }), - GET: async ({ params }) => { + GET: async ({ params, request }) => { const { data: pkg, error } = await supabaseAdmin .from("packages") .select( - "id,slug,name,type,description,long_description,latest_version,author_handle,license,install_count,is_published,review_status", + "id,slug,name,type,description,long_description,latest_version,author_handle,license,install_count,is_published,review_status,price_credits,author_id", ) .eq("slug", params.slug) .eq("is_published", true) @@ -39,6 +41,17 @@ export const Route = createFileRoute("/api/public/packages/$slug")({ headers: { "Content-Type": "application/json", ...CORS }, }); } + if ( + !(await canReadPackageContent( + pkg, + pkg.price_credits > 0 ? await getVerifiedRequestUserId(request) : null, + )) + ) { + return new Response("Purchase required", { + status: 403, + headers: { "Cache-Control": "no-store" }, + }); + } const { data: ver } = await supabaseAdmin .from("package_versions") .select("id,version,status,system_prompt,rules,examples,compatibility,notes") @@ -47,7 +60,7 @@ export const Route = createFileRoute("/api/public/packages/$slug")({ .maybeSingle(); const scopedCompatibility = ver ? await loadPublicEvaluationCompatibility(pkg.id, ver) : []; - const { id: _omit, is_published: _p, review_status: _r, ...rest } = pkg; + const { id: _omit, is_published: _p, review_status: _r, author_id: _a, ...rest } = pkg; return new Response( JSON.stringify({ ...rest, @@ -61,7 +74,7 @@ export const Route = createFileRoute("/api/public/packages/$slug")({ status: 200, headers: { "Content-Type": "application/json", - "Cache-Control": "public, max-age=60", + "Cache-Control": pkg.price_credits > 0 ? "private, no-store" : "public, max-age=60", ...CORS, }, }, diff --git a/src/routes/api/skills.$slug.export.ts b/src/routes/api/skills.$slug.export.ts index 34e6b49e..9fab8496 100644 --- a/src/routes/api/skills.$slug.export.ts +++ b/src/routes/api/skills.$slug.export.ts @@ -1,3 +1,5 @@ +import { canReadPackageContent } from "@/lib/marketplace/content-access.server"; +import { getVerifiedRequestUserId } from "@/lib/auth/request-user.server"; /** * Export any published package as an Anthropic-compatible SKILL.md zip bundle. * @@ -21,12 +23,12 @@ import { export const Route = createFileRoute("/api/skills/$slug/export")({ server: { handlers: { - GET: async ({ params }) => { + GET: async ({ params, request }) => { const slug = params.slug; const { data: pkg, error } = await supabaseAdmin .from("packages") .select( - "id,slug,name,type,description,long_description,license,author_handle,latest_version,is_published,review_status", + "id,slug,name,type,description,long_description,license,author_handle,latest_version,is_published,review_status,price_credits,author_id", ) .eq("slug", slug) .maybeSingle(); @@ -35,11 +37,22 @@ export const Route = createFileRoute("/api/skills/$slug/export")({ return new Response("not published", { status: 403 }); } + if ( + !(await canReadPackageContent( + pkg, + pkg.price_credits > 0 ? await getVerifiedRequestUserId(request) : null, + )) + ) { + return new Response("Purchase required", { + status: 403, + headers: { "Cache-Control": "no-store" }, + }); + } const { data: ver } = await supabaseAdmin .from("package_versions") .select("version,system_prompt,rules,examples,compatibility") .eq("package_id", pkg.id) - .order("created_at", { ascending: false }) + .eq("version", pkg.latest_version) .limit(1) .maybeSingle(); if (!ver) return new Response("no version", { status: 404 }); @@ -98,7 +111,7 @@ export const Route = createFileRoute("/api/skills/$slug/export")({ headers: { "Content-Type": "application/zip", "Content-Disposition": `attachment; filename="${pkg.slug}-skill.zip"`, - "Cache-Control": "public, max-age=300", + "Cache-Control": pkg.price_credits > 0 ? "private, no-store" : "public, max-age=300", "X-SAK-Signing-Public-Key": SIGNING_PUBLIC_KEY_PATH, "Access-Control-Expose-Headers": EXPOSED_SIGNATURE_HEADERS, ...signatureHeaders(sig), diff --git a/src/routes/api/skills.$slug.export[.]md.ts b/src/routes/api/skills.$slug.export[.]md.ts index 6995c72a..f63b7f35 100644 --- a/src/routes/api/skills.$slug.export[.]md.ts +++ b/src/routes/api/skills.$slug.export[.]md.ts @@ -1,3 +1,5 @@ +import { canReadPackageContent } from "@/lib/marketplace/content-access.server"; +import { getVerifiedRequestUserId } from "@/lib/auth/request-user.server"; import { createFileRoute } from "@tanstack/react-router"; import { supabaseAdmin as _supabaseAdmin } from "@/integrations/supabase/client.server"; const supabaseAdmin = _supabaseAdmin; @@ -6,7 +8,7 @@ import { buildSkillMd } from "@/lib/skills/anthropic-spec"; const CORS = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, OPTIONS", - "Access-Control-Allow-Headers": "Content-Type, Accept", + "Access-Control-Allow-Headers": "Content-Type, Accept, Authorization", }; // GET /api/skills//export.md @@ -17,12 +19,12 @@ export const Route = createFileRoute("/api/skills/$slug/export.md")({ server: { handlers: { OPTIONS: async () => new Response(null, { status: 204, headers: CORS }), - GET: async ({ params }) => { + GET: async ({ params, request }) => { const slug = params.slug; const { data: pkg, error } = await supabaseAdmin .from("packages") .select( - "id,slug,name,type,description,long_description,license,author_handle,latest_version,is_published,review_status", + "id,slug,name,type,description,long_description,license,author_handle,latest_version,is_published,review_status,price_credits,author_id", ) .eq("slug", slug) .eq("is_published", true) @@ -32,11 +34,22 @@ export const Route = createFileRoute("/api/skills/$slug/export.md")({ return new Response("not found", { status: 404, headers: CORS }); } + if ( + !(await canReadPackageContent( + pkg, + pkg.price_credits > 0 ? await getVerifiedRequestUserId(request) : null, + )) + ) { + return new Response("Purchase required", { + status: 403, + headers: { "Cache-Control": "no-store" }, + }); + } const { data: ver } = await supabaseAdmin .from("package_versions") .select("version,system_prompt,rules,examples,compatibility") .eq("package_id", pkg.id) - .order("created_at", { ascending: false }) + .eq("version", pkg.latest_version) .limit(1) .maybeSingle(); if (!ver) return new Response("no version", { status: 404, headers: CORS }); @@ -61,7 +74,7 @@ export const Route = createFileRoute("/api/skills/$slug/export.md")({ status: 200, headers: { "Content-Type": "text/markdown; charset=utf-8", - "Cache-Control": "public, max-age=300", + "Cache-Control": pkg.price_credits > 0 ? "private, no-store" : "public, max-age=300", ...CORS, }, }); diff --git a/src/routes/forge.report.$slug.tsx b/src/routes/forge.report.$slug.tsx index a4cf4741..d63ae23f 100644 --- a/src/routes/forge.report.$slug.tsx +++ b/src/routes/forge.report.$slug.tsx @@ -18,14 +18,30 @@ const ReportInput = z.object({ slug: z.string() }); const getForgeReport = createServerFn({ method: "GET" }) .inputValidator((d: unknown) => ReportInput.parse(d)) .handler(async ({ data }) => { - const { data: pkg } = await supabaseAdmin + const { data: row } = await supabaseAdmin .from("packages") .select( - "id,slug,name,type,description,long_description,latest_version,author_handle,created_at", + "id,slug,name,type,description,long_description,latest_version,author_handle,created_at,author_id,is_published,review_status,price_credits", ) .eq("slug", data.slug) .maybeSingle(); - if (!pkg) throw new Response("Not found", { status: 404 }); + if (!row) throw new Response("Not found", { status: 404 }); + + // Published + approved reports are public; anything else only for its + // author or an admin. Unauthorised callers get the same "Not found". + if (!(row.is_published && row.review_status === "approved" && row.price_credits === 0)) { + const { getOptionalUserId, isAdminUser } = await import("@/lib/auth/optional-user.server"); + const callerId = await getOptionalUserId(); + const allowed = + (callerId !== null && callerId === row.author_id) || (await isAdminUser(callerId)); + if (!allowed) throw new Response("Not found", { status: 404 }); + } + const { + author_id: _authorId, + is_published: _published, + review_status: _reviewStatus, + ...pkg + } = row; const { data: versions } = await supabaseAdmin .from("package_versions") diff --git a/src/routes/lovable/email/transactional/send.ts b/src/routes/lovable/email/transactional/send.ts index 81312e0d..92ae9fba 100644 --- a/src/routes/lovable/email/transactional/send.ts +++ b/src/routes/lovable/email/transactional/send.ts @@ -59,6 +59,13 @@ export const Route = createFileRoute("/lovable/email/transactional/send")({ return Response.json({ error: "Unauthorized" }, { status: 401 }); } + const { data: isAdmin, error: roleError } = await supabase.rpc("has_role", { + _user_id: user.id, + _role: "admin", + }); + if (roleError || isAdmin !== true) + return Response.json({ error: "Forbidden" }, { status: 403 }); + // Parse request body let templateName: string; let recipientEmail: string; @@ -95,10 +102,17 @@ export const Route = createFileRoute("/lovable/email/transactional/send")({ ); } - // Resolve effective recipient: template-level `to` takes precedence over - // the caller-provided recipientEmail. This allows notification templates - // to always send to a fixed address (e.g., site owner from env var). - const effectiveRecipient = template.to || recipientEmail; + // Resolve effective recipient: template-level `to` takes precedence. + // Otherwise a signed-in user may only email their OWN verified address — + // never a caller-chosen third party. + const ownEmail = user.email?.toLowerCase() ?? ""; + if (!template.to && recipientEmail && recipientEmail.toLowerCase() !== ownEmail) { + return Response.json( + { error: "recipientEmail must be your own account email" }, + { status: 403 }, + ); + } + const effectiveRecipient = template.to || ownEmail; if (!effectiveRecipient) { return Response.json( diff --git a/supabase/migrations/20261123210000_harden_selected_security_findings.sql b/supabase/migrations/20261123210000_harden_selected_security_findings.sql new file mode 100644 index 00000000..5c69a880 --- /dev/null +++ b/supabase/migrations/20261123210000_harden_selected_security_findings.sql @@ -0,0 +1,265 @@ +-- 1. Internal-only database functions: callable by the server, not by browsers. +REVOKE EXECUTE ON FUNCTION public.compute_skill_drift(uuid, integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.compute_skill_drift(uuid, integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_check_and_log_call(uuid, text, text, boolean) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_check_and_log_call(uuid, text, text, boolean) TO service_role; +REVOKE EXECUTE ON FUNCTION public.report_skill_execution(text, boolean, text, text, integer, integer, integer, text, text, text, text, boolean, boolean, smallint, integer, integer, text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.report_skill_execution(text, boolean, text, text, integer, integer, integer, text, text, text, text, boolean, boolean, smallint, integer, integer, text) TO service_role; + +-- 2. Credit balance: only your own (admins and the server may read any). +CREATE OR REPLACE FUNCTION public.get_credit_balance(_user_id uuid) + RETURNS integer + LANGUAGE sql + STABLE SECURITY DEFINER + SET search_path TO 'public' +AS $function$ + SELECT COALESCE(SUM(delta), 0)::int + FROM public.credit_ledger + WHERE user_id = _user_id + AND (_user_id = auth.uid() + OR public.has_role(auth.uid(), 'admin') + OR auth.role() = 'service_role') +$function$; +REVOKE EXECUTE ON FUNCTION public.get_credit_balance(uuid) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.get_credit_balance(uuid) TO authenticated, service_role; + +-- 3. Star counts are maintained only by the stars trigger, never written by authors. +CREATE OR REPLACE FUNCTION public.guard_package_trust_columns() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO 'public' +AS $function$ +BEGIN + -- star_count may change only from the package_stars sync trigger (nested trigger call). + IF pg_trigger_depth() <= 1 THEN + NEW.star_count := OLD.star_count; + END IF; + IF public.has_role(auth.uid(), 'admin') THEN RETURN NEW; END IF; + NEW.author_verified := OLD.author_verified; + NEW.author_handle := OLD.author_handle; + NEW.review_status := OLD.review_status; + NEW.reviewed_by := OLD.reviewed_by; + NEW.reviewed_at := OLD.reviewed_at; + NEW.is_published := OLD.is_published; + NEW.install_count := OLD.install_count; + NEW.author_id := OLD.author_id; + RETURN NEW; +END; +$function$; + +CREATE OR REPLACE FUNCTION public.guard_package_trust_insert() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO 'public' +AS $function$ +BEGIN + NEW.star_count := 0; + IF public.has_role(auth.uid(), 'admin') THEN RETURN NEW; END IF; + NEW.author_verified := false; + NEW.is_published := false; + NEW.review_status := 'draft'; + NEW.reviewed_by := NULL; + NEW.reviewed_at := NULL; + NEW.install_count := 0; + RETURN NEW; +END; +$function$; + +-- 4. Authors may edit version content only while the package is not yet approved and live. +DROP POLICY IF EXISTS "versions author write" ON public.package_versions; +CREATE POLICY "versions admin write" ON public.package_versions + FOR ALL TO authenticated + USING (public.has_role(auth.uid(), 'admin')) + WITH CHECK (public.has_role(auth.uid(), 'admin')); +CREATE POLICY "versions author insert unreviewed" ON public.package_versions + FOR INSERT TO authenticated + WITH CHECK (EXISTS (SELECT 1 FROM public.packages p + WHERE p.id = package_versions.package_id + AND p.author_id = auth.uid() + AND NOT (p.is_published AND p.review_status = 'approved'))); +CREATE POLICY "versions author update unreviewed" ON public.package_versions + FOR UPDATE TO authenticated + USING (EXISTS (SELECT 1 FROM public.packages p + WHERE p.id = package_versions.package_id + AND p.author_id = auth.uid() + AND NOT (p.is_published AND p.review_status = 'approved'))) + WITH CHECK (EXISTS (SELECT 1 FROM public.packages p + WHERE p.id = package_versions.package_id + AND p.author_id = auth.uid() + AND NOT (p.is_published AND p.review_status = 'approved'))); +CREATE POLICY "versions author delete unreviewed" ON public.package_versions + FOR DELETE TO authenticated + USING (EXISTS (SELECT 1 FROM public.packages p + WHERE p.id = package_versions.package_id + AND p.author_id = auth.uid() + AND NOT (p.is_published AND p.review_status = 'approved'))); + +-- 5. Stars only on packages that are publicly listed. +DROP POLICY IF EXISTS package_stars_insert_own ON public.package_stars; +CREATE POLICY package_stars_insert_own ON public.package_stars + FOR INSERT TO authenticated + WITH CHECK (user_id = auth.uid() + AND EXISTS (SELECT 1 FROM public.packages p + WHERE p.id = package_stars.package_id + AND p.is_published AND p.review_status = 'approved')); + +-- 6. Pack customizations: read your own; create only for packs you bought; the server runs them. +DROP POLICY IF EXISTS "pack_cust self all" ON public.pack_customizations; +CREATE POLICY "pack_cust read own or admin" ON public.pack_customizations + FOR SELECT TO authenticated + USING (user_id = auth.uid() OR public.has_role(auth.uid(), 'admin')); +CREATE POLICY "pack_cust insert own purchased" ON public.pack_customizations + FOR INSERT TO authenticated + WITH CHECK (user_id = auth.uid() + AND EXISTS (SELECT 1 FROM public.pack_purchases pp + WHERE pp.pack_id = pack_customizations.pack_id + AND pp.buyer_id = auth.uid())); + +-- 7. Public catalog classification lives on the package, so listings never read version content. +ALTER TABLE public.packages ADD COLUMN IF NOT EXISTS vertical text; +COMMENT ON COLUMN public.packages.vertical IS 'Public catalog classification, synced from the latest version rules (vertical, else category, else domain).'; + +CREATE OR REPLACE FUNCTION public.package_vertical_from_rules(_rules jsonb) + RETURNS text + LANGUAGE sql + IMMUTABLE + SET search_path TO 'public' +AS $function$ + SELECT COALESCE( + CASE WHEN jsonb_typeof(_rules->'vertical') = 'string' THEN NULLIF(_rules->>'vertical', '') END, + CASE WHEN jsonb_typeof(_rules->'category') = 'string' THEN NULLIF(_rules->>'category', '') END, + CASE WHEN jsonb_typeof(_rules->'domain') = 'string' THEN NULLIF(_rules->>'domain', '') END + ) +$function$; + +CREATE OR REPLACE FUNCTION public.packages_sync_vertical() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO 'public' +AS $function$ +BEGIN + IF TG_OP = 'INSERT' OR NEW.latest_version IS DISTINCT FROM OLD.latest_version THEN + NEW.vertical := (SELECT public.package_vertical_from_rules(v.rules) + FROM public.package_versions v + WHERE v.package_id = NEW.id AND v.version = NEW.latest_version + ORDER BY v.created_at DESC LIMIT 1); + END IF; + RETURN NEW; +END; +$function$; + +CREATE OR REPLACE FUNCTION public.package_versions_sync_vertical() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO 'public' +AS $function$ +DECLARE _v text := public.package_vertical_from_rules(NEW.rules); +BEGIN + UPDATE public.packages p + SET vertical = _v + WHERE p.id = NEW.package_id + AND p.latest_version = NEW.version + AND p.vertical IS DISTINCT FROM _v; + RETURN NEW; +END; +$function$; + +REVOKE EXECUTE ON FUNCTION public.packages_sync_vertical() FROM PUBLIC, anon, authenticated; +REVOKE EXECUTE ON FUNCTION public.package_versions_sync_vertical() FROM PUBLIC, anon, authenticated; + +DROP TRIGGER IF EXISTS trg_packages_sync_vertical ON public.packages; +CREATE TRIGGER trg_packages_sync_vertical + BEFORE INSERT OR UPDATE OF latest_version ON public.packages + FOR EACH ROW EXECUTE FUNCTION public.packages_sync_vertical(); + +DROP TRIGGER IF EXISTS trg_package_versions_sync_vertical ON public.package_versions; +CREATE TRIGGER trg_package_versions_sync_vertical + AFTER INSERT OR UPDATE OF rules, version ON public.package_versions + FOR EACH ROW EXECUTE FUNCTION public.package_versions_sync_vertical(); + +UPDATE public.packages p + SET vertical = (SELECT public.package_vertical_from_rules(v.rules) + FROM public.package_versions v + WHERE v.package_id = p.id AND v.version = p.latest_version + ORDER BY v.created_at DESC LIMIT 1) + WHERE p.vertical IS NULL; + +-- 8. Workspace invites require a verified mailbox for the invited address. +CREATE OR REPLACE FUNCTION public.team_action(_action text, _workspace uuid DEFAULT NULL::uuid, _payload jsonb DEFAULT '{}'::jsonb) + RETURNS jsonb + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO 'public' +AS $function$ +declare uid uuid:=auth.uid(); role_name text; wid uuid:=_workspace; token text; inv public.team_invites; item public.team_skill_versions; target uuid; v_id uuid; pkg_id uuid; result jsonb:='{}'; +begin + if uid is null then raise exception 'AUTH_REQUIRED' using errcode='42501'; end if; + if _action='create' then + if length(trim(coalesce(_payload->>'name',''))) not between 2 and 100 then raise exception 'INVALID_NAME'; end if; + insert into public.team_workspaces(name,owner_id) values(trim(_payload->>'name'),uid) returning id into wid; + insert into public.team_members values(wid,uid,'admin',now()); + result:=jsonb_build_object('workspace_id',wid); + elsif _action='accept' then + select * into inv from public.team_invites where token_hash=encode(extensions.digest(coalesce(_payload->>'token',''),'sha256'),'hex') for update; + if inv.id is null or inv.accepted_at is not null or inv.expires_at<=now() or lower(inv.email)<>lower(coalesce(auth.jwt()->>'email','')) then raise exception 'INVALID_INVITE' using errcode='42501'; end if; + -- Auto-confirmed sign-ups do not prove mailbox ownership, so require a confirmation link that was actually sent, + -- or a sign-in provider (e.g. Google) that verified this same address. + if not exists(select 1 from auth.users u where u.id=uid and lower(u.email)=lower(inv.email) and u.confirmation_sent_at is not null and u.email_confirmed_at is not null and u.email_confirmed_at>=u.confirmation_sent_at) + and not exists(select 1 from auth.identities i where i.user_id=uid and i.provider<>'email' and lower(i.identity_data->>'email')=lower(inv.email) and lower(coalesce(i.identity_data->>'email_verified',''))='true') + then raise exception 'EMAIL_NOT_VERIFIED' using errcode='42501'; end if; + wid:=inv.workspace_id; + -- Joining again must never overwrite an existing member's role. + insert into public.team_members(workspace_id,user_id,role) values(wid,uid,inv.role) on conflict do nothing; + update public.team_invites set accepted_at=now() where id=inv.id; + result:=jsonb_build_object('workspace_id',wid); + else + -- Read the role after acquiring the lock, so a removed administrator cannot use a stale grant. + perform 1 from public.team_workspaces where id=wid for update; + role_name:=public.team_role(wid); + if role_name is null then raise exception 'NOT_A_MEMBER' using errcode='42501'; end if; + if _action='invite' then + if role_name<>'admin' then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if; + if _payload->>'role' not in ('viewer','editor','admin') or coalesce(_payload->>'email','') !~ '^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$' then raise exception 'INVALID_INVITE'; end if; + token:=encode(extensions.gen_random_bytes(32),'hex'); + insert into public.team_invites(workspace_id,email,role,token_hash,created_by) values(wid,lower(_payload->>'email'),_payload->>'role',encode(extensions.digest(token,'sha256'),'hex'),uid); + result:=jsonb_build_object('token',token); + elsif _action in ('set_role','remove_member') then + if role_name<>'admin' then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if; + target:=(_payload->>'user_id')::uuid; + if exists(select 1 from public.team_workspaces where id=wid and owner_id=target) then raise exception 'OWNER_PROTECTED'; end if; + if _action='remove_member' then delete from public.team_members where workspace_id=wid and user_id=target; + else + if coalesce(_payload->>'role','') not in ('viewer','editor','admin') then raise exception 'INVALID_ROLE'; end if; + update public.team_members set role=_payload->>'role' where workspace_id=wid and user_id=target; + end if; + elsif _action='submit_skill' then + if role_name not in ('editor','admin') then raise exception 'EDITOR_REQUIRED' using errcode='42501'; end if; + if jsonb_typeof(_payload->'files')<>'object' or octet_length((_payload->'files')::text)>2000000 or not ((_payload->'files') ? 'SKILL.md') then raise exception 'INVALID_FILES'; end if; + if (select count(*) from jsonb_each(_payload->'files')) not between 1 and 200 or exists(select 1 from jsonb_each(_payload->'files') f where jsonb_typeof(f.value)<>'string' or octet_length(f.value#>>'{}')>250000 or length(f.key) not between 1 and 240 or f.key ~ '(^/|^[A-Za-z]:|\\|(^|/)(\.\.?|\.git|\.ssh|node_modules|\.env[^/]*)(/|$)|//|/$|[[:cntrl:]])') then raise exception 'INVALID_FILES'; end if; + insert into public.team_skill_versions(workspace_id,slug,version,name,description,files,created_by) values(wid,_payload->>'slug',_payload->>'version',_payload->>'name',coalesce(_payload->>'description',''),_payload->'files',uid) returning id into target; + result:=jsonb_build_object('id',target); + elsif _action='review_skill' then + if role_name<>'admin' then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if; + select * into item from public.team_skill_versions where id=(_payload->>'id')::uuid and workspace_id=wid for update; + if item.id is null or item.status<>'pending' then raise exception 'NOT_PENDING'; end if; + if item.created_by=uid then raise exception 'INDEPENDENT_REVIEW_REQUIRED'; end if; + if coalesce(_payload->>'status','') not in ('approved','rejected') then raise exception 'INVALID_STATUS'; end if; + update public.team_skill_versions set status=_payload->>'status',reviewed_by=uid,reviewed_at=now() where id=item.id; + elsif _action='pin_package' then + if role_name<>'admin' then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if; + select p.id,v.id into pkg_id,v_id from public.packages p join public.package_versions v on v.package_id=p.id where p.slug=_payload->>'slug' and v.version=_payload->>'version' and p.is_published and p.review_status='approved' and v.version=p.latest_version; + if v_id is null then raise exception 'APPROVED_VERSION_REQUIRED'; end if; + insert into public.team_library(workspace_id,package_id,version_id,pinned_by) values(wid,pkg_id,v_id,uid) on conflict(workspace_id,package_id) do update set version_id=excluded.version_id,pinned_by=uid,pinned_at=now(); + elsif _action='unpin_package' then + if role_name<>'admin' then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if; + delete from public.team_library where workspace_id=wid and package_id=(_payload->>'package_id')::uuid; + else raise exception 'UNKNOWN_ACTION'; + end if; + end if; + insert into public.team_audit_events(workspace_id,actor_id,action,detail) values(wid,uid,_action,jsonb_strip_nulls(jsonb_build_object('id',_payload->>'id','slug',_payload->>'slug','version',_payload->>'version','role',_payload->>'role','user_id',_payload->>'user_id','package_id',_payload->>'package_id','status',_payload->>'status'))); + return result; +end $function$; \ No newline at end of file diff --git a/supabase/migrations/20261123220000_advanced_security_findings.sql b/supabase/migrations/20261123220000_advanced_security_findings.sql new file mode 100644 index 00000000..ae7e45ed --- /dev/null +++ b/supabase/migrations/20261123220000_advanced_security_findings.sql @@ -0,0 +1,368 @@ +-- Follow-up to drizzle/0001_harden_selected_security_findings.sql, already applied by Lovable. +-- Self-reported telemetry must not manufacture verified trust. +ALTER TABLE public.skill_executions ADD COLUMN IF NOT EXISTS is_verified boolean NOT NULL DEFAULT false; +COMMENT ON COLUMN public.skill_executions.is_verified IS 'Only a trusted server evaluator may attest a run. Public/MCP telemetry is always unverified.'; +CREATE OR REPLACE FUNCTION public.get_skill_trust(_slug text) + RETURNS jsonb + LANGUAGE plpgsql + STABLE SECURITY DEFINER + SET search_path TO 'public' +AS $function$ +DECLARE + pkg RECORD; + total_life int := 0; + ok_life int := 0; + total_30 int := 0; + ok_30 int := 0; + p50_30 numeric := NULL; + p95_30 numeric := NULL; + total_7 int := 0; + ok_7 int := 0; + models_json jsonb := '[]'::jsonb; + findings_public int := 0; + findings_critical int := 0; + trust numeric := NULL; + battle boolean := false; +BEGIN + SELECT id, slug, latest_version INTO pkg FROM public.packages WHERE slug = _slug AND is_published AND review_status='approved' LIMIT 1; + IF pkg.id IS NULL THEN RETURN NULL; END IF; + + SELECT count(*) FILTER (WHERE true), count(*) FILTER (WHERE success) + INTO total_life, ok_life + FROM public.skill_executions WHERE package_slug = _slug AND is_verified; + + SELECT count(*), count(*) FILTER (WHERE success), + percentile_cont(0.5) WITHIN GROUP (ORDER BY latency_ms), + percentile_cont(0.95) WITHIN GROUP (ORDER BY latency_ms) + INTO total_30, ok_30, p50_30, p95_30 + FROM public.skill_executions + WHERE package_slug = _slug AND is_verified AND created_at > now() - interval '30 days'; + + SELECT count(*), count(*) FILTER (WHERE success) + INTO total_7, ok_7 + FROM public.skill_executions + WHERE package_slug = _slug AND is_verified AND created_at > now() - interval '7 days'; + + SELECT coalesce(jsonb_agg(jsonb_build_object( + 'model', m.model, 'runs', m.runs, 'success_rate', m.sr + ) ORDER BY m.runs DESC), '[]'::jsonb) INTO models_json + FROM ( + SELECT model AS model, count(*) AS runs, + (count(*) FILTER (WHERE success))::numeric / greatest(count(*),1) AS sr + FROM public.skill_executions + WHERE package_slug = _slug AND is_verified AND created_at > now() - interval '30 days' + GROUP BY model + ) m; + + SELECT count(*), count(*) FILTER (WHERE severity = 'critical') + INTO findings_public, findings_critical + FROM public.skill_robustness_findings + WHERE package_slug = _slug AND status = 'public'; + + trust := round( + ( + (case when total_30 > 0 then (ok_30::numeric/total_30) else 0.5 end) * 100 + * least(1.0, ln(greatest(total_30,1)+1) / ln(101)) + * (1.0 - least(1.0, findings_critical::numeric * 0.25)) + )::numeric, + 1 + ); + battle := total_30 >= 50 AND (ok_30::numeric/greatest(total_30,1)) >= 0.9 AND findings_critical = 0; + + RETURN jsonb_build_object( + 'slug', _slug, + 'trust_score', CASE WHEN total_30 > 0 THEN trust ELSE NULL END, + 'evidence', 'verified_server_evaluations', + 'battle_tested', battle, + 'lifetime', jsonb_build_object('runs', total_life, 'success_rate', case when total_life>0 then round((ok_life::numeric/total_life)::numeric, 3) else null end), + 'window_30d', jsonb_build_object('runs', total_30, 'success_rate', case when total_30>0 then round((ok_30::numeric/total_30)::numeric, 3) else null end, 'p50_latency_ms', p50_30, 'p95_latency_ms', p95_30), + 'window_7d', jsonb_build_object('runs', total_7, 'success_rate', case when total_7>0 then round((ok_7::numeric/total_7)::numeric, 3) else null end), + 'models', models_json, + 'findings_public', findings_public, + 'findings_critical', findings_critical + ); +END; +$function$ +; +CREATE OR REPLACE FUNCTION public.recompute_trust_scores_v2() + RETURNS integer + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO 'public' +AS $function$ +declare + affected int := 0; +begin + with adv as ( + select package_id, + sum(passed)::numeric as adv_succ, + sum(total)::numeric as adv_total, + avg(severity_weighted_score)::numeric as adv_weighted, + max(total)::numeric as case_count, + extract(epoch from (now() - max(created_at))) / 86400 as last_verified_days + from public.adversarial_runs + group by package_id + ), + perf as ( + select package_id, + count(*) filter (where success)::numeric as rw_succ, + count(*)::numeric as rw_total + from public.skill_executions + where is_verified AND created_at >= now() - interval '30 days' + and package_id is not null + group by package_id + ), + releases as ( + select package_id, count(*)::int as signed_releases + from public.package_releases group by package_id + ), + pkg as ( + select p.id, + coalesce(adv.adv_succ, 0) as adv_succ, + coalesce(adv.adv_total, 0) as adv_total, + coalesce(adv.adv_weighted, 0) as adv_weighted, + coalesce(adv.case_count, 0) as case_count, + adv.last_verified_days as last_verified_days, + coalesce(perf.rw_succ, 0) as rw_succ, + coalesce(perf.rw_total, 0) as rw_total, + coalesce(releases.signed_releases, 0) as signed_releases, + extract(epoch from (now() - p.created_at)) / 86400 as age_days + from public.packages p + left join adv on adv.package_id = p.id + left join perf on perf.package_id = p.id + left join releases on releases.package_id = p.id + ), + dims as ( + select id, adv_succ, adv_total, adv_weighted, case_count, last_verified_days, + rw_succ, rw_total, signed_releases, age_days, + ( 0.6 * public.wilson_lower_bound(adv_succ, adv_total) + + 0.4 * least(1, greatest(0, adv_weighted)) * least(1, adv_total / 8.0) + ) as safety, + public.wilson_lower_bound(rw_succ, rw_total) as competence, + ( 0.7 * (case + when last_verified_days is null then 0 + when last_verified_days <= 30 then 1 + when last_verified_days >= 180 then 0 + else 1 - (last_verified_days - 30) / 150.0 + end) + + 0.3 * least(1, signed_releases / 3.0) + ) as freshness, + ( 0.4 * public.trust_saturate(adv_total, 12) + + 0.25 * public.trust_saturate(case_count, 8) + + 0.25 * public.trust_saturate(rw_total, 100) + + 0.10 * least(1, signed_releases / 3.0) + ) as confidence + from pkg + ), + scored as ( + select id, adv_succ, adv_total, adv_weighted, rw_succ, rw_total, + signed_releases, age_days, safety, competence, freshness, confidence, + least(1, greatest(0, + 0.10 * 1 + + 0.45 * safety + + 0.30 * competence + + 0.15 * freshness + )) as raw_quality, + (adv_total >= 8 and case_count >= 5) as verified + from dims + ) + insert into public.package_trust_scores + (package_id, score, schema_valid, adversarial_pass_rate, + adversarial_weighted_score, real_world_success_rate, + signed_releases, age_days, trust_version, confidence, verified, + dim_safety, dim_competence, dim_freshness, dim_coverage, components, computed_at) + select id, + round((raw_quality * confidence)::numeric, 4), + true, + round(public.wilson_lower_bound(adv_succ, adv_total)::numeric, 4), + round(least(1, greatest(0, adv_weighted))::numeric, 4), + round(public.wilson_lower_bound(rw_succ, rw_total)::numeric, 4), + signed_releases, age_days::int, + '2.0.0', + round(confidence::numeric, 4), + verified, + round(safety::numeric, 4), + round(competence::numeric, 4), + round(freshness::numeric, 4), + round(confidence::numeric, 4), + jsonb_build_object( + 'version', '2.0.0', + 'safety', round(safety::numeric, 4), + 'competence', round(competence::numeric, 4), + 'freshness', round(freshness::numeric, 4), + 'confidence', round(confidence::numeric, 4), + 'verified', verified, + 'adv_runs_cases', adv_total, + 'real_world_runs', rw_total, + 'signed_releases', signed_releases + ), + now() + from scored + on conflict (package_id) do update set + score = excluded.score, + adversarial_pass_rate = excluded.adversarial_pass_rate, + adversarial_weighted_score = excluded.adversarial_weighted_score, + real_world_success_rate = excluded.real_world_success_rate, + signed_releases = excluded.signed_releases, + age_days = excluded.age_days, + trust_version = excluded.trust_version, + confidence = excluded.confidence, + verified = excluded.verified, + dim_safety = excluded.dim_safety, + dim_competence = excluded.dim_competence, + dim_freshness = excluded.dim_freshness, + dim_coverage = excluded.dim_coverage, + components = excluded.components, + computed_at = excluded.computed_at; + + get diagnostics affected = row_count; + return affected; +end; +$function$ +; +REVOKE EXECUTE ON FUNCTION public.recompute_trust_scores_v2() FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.recompute_trust_scores_v2() TO service_role; +CREATE OR REPLACE FUNCTION public.snapshot_package_weekly_metrics() + RETURNS integer + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO 'public' +AS $function$ +declare + affected int := 0; + wk date := date_trunc('week', now() - interval '7 days')::date; +begin + insert into public.package_weekly_metrics + (package_id, package_slug, week_start, track, runs, successes, success_rate, + success_rate_wilson_lb, task_completed_rate, p95_latency_ms, avg_tokens, + adversarial_pass_rate, adversarial_weighted, trust_score) + select + p.id, p.slug, wk, 'current', + coalesce(x.runs, 0), coalesce(x.successes, 0), + x.success_rate, + public.wilson_lower_bound(coalesce(x.successes,0)::bigint, coalesce(x.runs,0)::bigint), + x.task_completed_rate, x.p95, x.avg_tokens, + adv.pass_rate, adv.weighted, ts.score + from public.packages p + left join lateral ( + select count(*) as runs, + count(*) filter (where e.success) as successes, + (count(*) filter (where e.success))::numeric / nullif(count(*),0) as success_rate, + (count(*) filter (where e.task_completed))::numeric + / nullif(count(*) filter (where e.task_completed is not null),0) as task_completed_rate, + percentile_cont(0.95) within group (order by e.latency_ms) as p95, + avg(coalesce(e.tokens_in,0) + coalesce(e.tokens_out,0)) as avg_tokens + from public.skill_executions e + where e.is_verified AND e.package_id = p.id + and e.created_at >= wk and e.created_at < wk + interval '7 days' + and (e.arm is null or e.arm = 'treatment') + ) x on true + left join lateral ( + select avg(r.pass_rate)::numeric(5,4) as pass_rate, + avg(r.severity_weighted_score)::numeric(5,4) as weighted + from public.adversarial_runs r + where r.package_id = p.id and r.subject_arm = 'certified' + and r.created_at >= wk and r.created_at < wk + interval '7 days' + ) adv on true + left join public.package_trust_scores ts on ts.package_id = p.id + where p.is_published = true + on conflict (package_id, week_start, track) do update set + runs = excluded.runs, + successes = excluded.successes, + success_rate = excluded.success_rate, + success_rate_wilson_lb = excluded.success_rate_wilson_lb, + task_completed_rate = excluded.task_completed_rate, + p95_latency_ms = excluded.p95_latency_ms, + avg_tokens = excluded.avg_tokens, + adversarial_pass_rate = excluded.adversarial_pass_rate, + adversarial_weighted = excluded.adversarial_weighted, + trust_score = excluded.trust_score; + get diagnostics affected = row_count; + + insert into public.package_weekly_metrics + (package_id, package_slug, week_start, track, + adversarial_pass_rate, adversarial_weighted) + select r.package_id, p.slug, wk, 'frozen_v1', + avg(r.pass_rate)::numeric(5,4), avg(r.severity_weighted_score)::numeric(5,4) + from public.adversarial_runs r + join public.packages p on p.id = r.package_id + where r.subject_arm = 'frozen_v1' + and r.created_at >= wk and r.created_at < wk + interval '7 days' + group by r.package_id, p.slug + on conflict (package_id, week_start, track) do update set + adversarial_pass_rate = excluded.adversarial_pass_rate, + adversarial_weighted = excluded.adversarial_weighted; + + return affected; +end; +$function$ +; +REVOKE EXECUTE ON FUNCTION public.snapshot_package_weekly_metrics() FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.snapshot_package_weekly_metrics() TO service_role; +ALTER FUNCTION public.get_credit_balance(uuid) SECURITY INVOKER; +ALTER FUNCTION public.has_active_subscription(uuid) SECURITY INVOKER; +ALTER FUNCTION public.has_active_subscription(uuid,text) SECURITY INVOKER; +DROP POLICY IF EXISTS "pack_cust insert own purchased" ON public.pack_customizations; +CREATE POLICY "pack_cust insert own purchased" ON public.pack_customizations FOR INSERT TO authenticated +WITH CHECK(user_id=auth.uid() AND status='queued' AND items='[]'::jsonb AND EXISTS( + SELECT 1 FROM public.pack_purchases p WHERE p.pack_id=pack_customizations.pack_id AND p.buyer_id=auth.uid())); +CREATE OR REPLACE FUNCTION public.check_security_boundaries() + RETURNS TABLE(check_name text, passed boolean) + LANGUAGE sql + STABLE SECURITY DEFINER + SET search_path TO '' +AS $function$ +WITH server_functions(signature) AS (VALUES ('public.crm_active_hours(uuid)'), +('public.crm_activity_hours(uuid,integer)'), +('public.crm_customers(integer,integer,uuid)'), +('public.crm_effectiveness(integer)'), +('public.crm_effectiveness_by_segment(integer)'), +('public.crm_segment_send_hour_stats(integer)'), +('public.crm_send_hour_stats(integer)'), +('public.crm_track_click(text)'), +('public.crm_track_open(text)'), +('public.delete_email(text,bigint)'), +('public.enqueue_email(text,jsonb)'), +('public.get_pack_with_items(text)'), +('public.get_package_ratings(uuid)'), +('public.list_package_reviews(uuid,integer)'), +('public.mcp_idempotency_get(uuid,text,text)'), +('public.mcp_idempotency_put(uuid,text,text,jsonb)'), +('public.mcp_oauth_exchange_code(text,text,text,text,text,integer,integer)'), +('public.mcp_oauth_get_client(text)'), +('public.mcp_oauth_refresh_token(text,text,text,text,integer,integer)'), +('public.mcp_oauth_register_client(text,text[],text,text,text,text,text)'), +('public.mcp_oauth_revoke_token(text)'), +('public.mcp_oauth_verify_access(text)'), +('public.move_to_dlq(text,text,bigint,jsonb)'), +('public.read_email_batch(text,integer,integer)'),('public.compute_skill_drift(uuid,integer)'),('public.mcp_check_and_log_call(uuid,text,text,boolean)'),('public.report_skill_execution(text,boolean,text,text,integer,integer,integer,text,text,text,text,boolean,boolean,smallint,integer,integer,text)'),('public.recompute_trust_scores_v2()'),('public.snapshot_package_weekly_metrics()')) +SELECT 'server_rpc_acl', count(*) = 29 AND bool_and( + NOT pg_catalog.has_function_privilege('anon', signature, 'EXECUTE') AND + NOT pg_catalog.has_function_privilege('authenticated', signature, 'EXECUTE') AND + pg_catalog.has_function_privilege('service_role', signature, 'EXECUTE')) FROM server_functions +UNION ALL +SELECT 'email_search_path', count(*) = 4 AND bool_and(p.proconfig @> ARRAY['search_path=""']) +FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace +WHERE n.nspname='public' AND p.proname IN ('enqueue_email','read_email_batch','delete_email','move_to_dlq') +UNION ALL +SELECT 'rls_invoker_reads', count(*) = 3 AND bool_and(NOT p.prosecdef) +FROM pg_catalog.pg_proc p WHERE p.oid IN ('public.agent_onboarding_funnel(integer)'::pg_catalog.regprocedure,'public.search_packages(text,text,integer,integer)'::pg_catalog.regprocedure,'public.get_review_eligibility(uuid)'::pg_catalog.regprocedure) +UNION ALL +SELECT 'authenticated_transactions', count(*) = 7 AND bool_and( + NOT pg_catalog.has_function_privilege('anon', signature, 'EXECUTE') AND + pg_catalog.has_function_privilege('authenticated', signature, 'EXECUTE')) +FROM (VALUES ('public.claim_referral(text,text,text)'),('public.purchase_pack(uuid)'),('public.purchase_package(uuid)'),('public.team_action(text,uuid,jsonb)'),('public.mcp_oauth_issue_code(text,text,text,text,text,text,integer)'),('public.mcp_oauth_list_user_connections()'),('public.mcp_oauth_revoke_client_for_user(text)')) f(signature) +UNION ALL +SELECT 'plans_explicit_public_rows', count(*) = 1 AND bool_and(qual <> 'true' AND qual LIKE '%slug%') +FROM pg_catalog.pg_policies WHERE schemaname='public' AND tablename='plans' AND policyname='plans public read' +UNION ALL SELECT 'account_reads_invoker', count(*)=3 AND bool_and(NOT p.prosecdef) + FROM pg_catalog.pg_proc p WHERE p.oid IN ('public.get_credit_balance(uuid)'::pg_catalog.regprocedure,'public.has_active_subscription(uuid)'::pg_catalog.regprocedure,'public.has_active_subscription(uuid,text)'::pg_catalog.regprocedure) +UNION ALL SELECT 'verified_telemetry_only', count(*)=3 AND bool_and(pg_catalog.pg_get_functiondef(p.oid) LIKE '%is_verified%') + FROM pg_catalog.pg_proc p WHERE p.oid IN ('public.get_skill_trust(text)'::pg_catalog.regprocedure,'public.recompute_trust_scores_v2()'::pg_catalog.regprocedure,'public.snapshot_package_weekly_metrics()'::pg_catalog.regprocedure) +UNION ALL SELECT 'customization_purchase_required', count(*)=1 AND bool_and(with_check LIKE '%pack_purchases%' AND with_check LIKE '%queued%') + FROM pg_catalog.pg_policies WHERE schemaname='public' AND tablename='pack_customizations' AND cmd='INSERT'; +$function$ +; +-- Refresh cached scores after excluding unverified reports. +SELECT public.recompute_trust_scores_v2(); + diff --git a/tests/diagnosis-persistence.test.ts b/tests/diagnosis-persistence.test.ts new file mode 100644 index 00000000..d5de7ceb --- /dev/null +++ b/tests/diagnosis-persistence.test.ts @@ -0,0 +1,104 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { build } from "esbuild"; +import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +test("anonymous exam round trip uses capability externally and UUID in database writes", async () => { + const dir = await mkdtemp(join(tmpdir(), "diagnosis-probe-")); + const secret = process.env.SUPABASE_SERVICE_ROLE_KEY; + process.env.SUPABASE_SERVICE_ROLE_KEY = "fixture-key"; + const fixtureId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + const writes: Array<{ + table: string; + value: Record | Array>; + }> = []; + let row: Record; + const db = { + from(table: string) { + let data: unknown; + return { + insert(value: Record | Array>) { + writes.push({ table, value }); + if (table === "agent_diagnoses") { + row = { ...value, id: fixtureId }; + data = { id: fixtureId }; + } + return this; + }, + update(value: Record | Array>) { + writes.push({ table, value }); + data = [{ id: fixtureId }]; + return this; + }, + select() { + return this; + }, + eq() { + return this; + }, + single: async () => ({ data }), + maybeSingle: async () => ({ data: row }), + then(resolve: (result: { data: unknown }) => unknown) { + return Promise.resolve({ data }).then(resolve); + }, + }; + }, + }; + (globalThis as unknown as { __diagnosisDb?: unknown }).__diagnosisDb = db; + try { + const result = await build({ + entryPoints: ["src/lib/university/university.server.ts"], + bundle: true, + platform: "node", + format: "esm", + write: false, + plugins: [ + { + name: "test-db", + setup(b) { + b.onResolve({ filter: /integrations\/supabase\/client.server/ }, () => ({ + path: "db", + namespace: "fixture", + })); + b.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({ + contents: "export const supabaseAdmin=globalThis.__diagnosisDb;", + loader: "js", + })); + }, + }, + ], + }); + const file = join(dir, "exam.mjs"); + await writeFile(file, result.outputFiles[0].text); + const api = await import(pathToFileURL(file).href); + const started = await api.startExam({ domain: "gtm", limit: 1 }); + assert.match(started.diagnosis_id, /^[\da-f-]+\.[\da-f]{64}$/); + const report = await api.submitExam({ + diagnosisId: started.diagnosis_id, + answers: [{ case_id: started.tasks[0].case_id, answer: "test" }], + }); + assert.equal(report.diagnosis_id, started.diagnosis_id); + const items = writes.find((w) => w.table === "agent_diagnosis_items")!.value as Array< + Record + >; + assert.ok(items.length > 0); + assert.ok(items.every((i) => i.diagnosis_id === fixtureId)); + await assert.rejects( + () => api.submitExam({ diagnosisId: fixtureId, answers: [] }), + (e) => (e as Response).status === 404, + ); + row.user_id = "alice"; + await assert.rejects( + () => api.submitExam({ diagnosisId: fixtureId, userId: "bob", answers: [] }), + (e) => (e as Response).status === 404, + ); + } finally { + delete (globalThis as unknown as { __diagnosisDb?: unknown }).__diagnosisDb; + if (secret === undefined) delete process.env.SUPABASE_SERVICE_ROLE_KEY; + else process.env.SUPABASE_SERVICE_ROLE_KEY = secret; + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/tests/pricing-copy.test.ts b/tests/pricing-copy.test.ts index 983ea8cb..9e7acc8d 100644 --- a/tests/pricing-copy.test.ts +++ b/tests/pricing-copy.test.ts @@ -60,7 +60,7 @@ test("shouldEnableAdjustableQuantity defaults for Agent Pass lookup keys", () => true, ); assert.equal(shouldEnableAdjustableQuantity({ priceId: "sak_pro_monthly" }), false); - assert.equal(shouldEnableAdjustableQuantity({ priceId: "sak_pro_monthly", quantity: 2 }), true); + assert.equal(shouldEnableAdjustableQuantity({ priceId: "sak_pro_monthly", quantity: 2 }), false); assert.equal( shouldEnableAdjustableQuantity({ priceId: "sak_pro_monthly", diff --git a/tests/security-findings.test.ts b/tests/security-findings.test.ts new file mode 100644 index 00000000..6c0a2514 --- /dev/null +++ b/tests/security-findings.test.ts @@ -0,0 +1,80 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { authenticateCronRequest } from "../src/integrations/supabase/cron-auth.ts"; +import { + resolveCheckoutQuantity, + shouldEnableAdjustableQuantity, + validateReturnUrl, +} from "../src/lib/checkout-quantity.ts"; +import { canAccessDiagnosis, diagnosisCapability } from "../src/lib/university/diagnosis-access.ts"; + +test("privileged jobs reject public keys and query credentials, accept managed current/previous secrets", async () => { + const previous = process.env.LOVABLE_CRON_SECRET; + const old = process.env.LOVABLE_CRON_SECRET_PREVIOUS; + try { + process.env.LOVABLE_CRON_SECRET = "test-server-secret"; + process.env.LOVABLE_CRON_SECRET_PREVIOUS = "test-previous-secret"; + for (const value of [ + "", + "Bearer public-key", + "Bearer user-jwt", + "Bearer test-server-secret,extra", + ]) { + const r = await authenticateCronRequest( + new Request("https://example.test/job?apikey=test-server-secret", { + headers: { authorization: value }, + }), + ); + assert.equal(r?.status, 401); + } + for (const token of ["test-server-secret", "test-previous-secret"]) { + assert.equal( + await authenticateCronRequest( + new Request("https://example.test/job", { + headers: { authorization: `Bearer ${token}` }, + }), + ), + null, + ); + } + } finally { + if (previous === undefined) delete process.env.LOVABLE_CRON_SECRET; + else process.env.LOVABLE_CRON_SECRET = previous; + if (old === undefined) delete process.env.LOVABLE_CRON_SECRET_PREVIOUS; + else process.env.LOVABLE_CRON_SECRET_PREVIOUS = old; + } +}); + +test("owned diagnoses require owner; anonymous UUIDs alone are insufficient", () => { + const id = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + const cap = diagnosisCapability(id, "test-secret"); + assert.equal(canAccessDiagnosis("alice", "bob", id, "test-secret"), false); + assert.equal(canAccessDiagnosis("alice", null, cap, "test-secret"), false); + assert.equal(canAccessDiagnosis("alice", "alice", id, "test-secret"), true); + assert.equal(canAccessDiagnosis(null, null, id, "test-secret"), false); + assert.equal(canAccessDiagnosis(null, null, cap, "test-secret"), true); + assert.equal( + canAccessDiagnosis(null, null, cap.replace("aaaaaaaa", "bbbbbbbb"), "test-secret"), + false, + ); + assert.equal(canAccessDiagnosis(null, null, cap, "other-secret"), false); +}); + +test("only the exact Agent Pass product accepts adjustable seats", () => { + for (const priceId of ["sak_pro_monthly", "agent_pass_pro_monthly", "sak_agent_pass_fake"]) { + assert.equal(resolveCheckoutQuantity(priceId, 50), 1); + assert.equal(shouldEnableAdjustableQuantity({ priceId, adjustableQuantity: true }), false); + } + assert.equal(resolveCheckoutQuantity("sak_agent_pass_monthly", 100), 100); +}); + +test("checkout rejects attacker preview lookalikes, userinfo and arbitrary ports", () => { + for (const url of [ + "https://evil-b00a8021-9d8d-4f49-a581-628727b71f68.lovable.app", + "https://evil@superagentskill.com", + "https://superagentskill.com:444", + "http://localhost:3000", + ]) { + assert.throws(() => validateReturnUrl(url)); + } +}); diff --git a/tests/security-guards.test.ts b/tests/security-guards.test.ts new file mode 100644 index 00000000..396640f8 --- /dev/null +++ b/tests/security-guards.test.ts @@ -0,0 +1,35 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +const { resolveCheckoutQuantity, validateReturnUrl } = + await import("../src/lib/checkout-quantity.ts"); +const { canAccessDiagnosis } = await import("../src/lib/university/diagnosis-access.ts"); + +test("Pro plans are always sold as quantity 1, whatever the caller asks", () => { + assert.equal(resolveCheckoutQuantity("sak_pro_monthly", 50), 1); + assert.equal(resolveCheckoutQuantity("sak_pro_yearly", 7), 1); +}); + +test("Agent Pass keeps the chosen number of agent seats", () => { + assert.equal(resolveCheckoutQuantity("sak_agent_pass_monthly", 3), 3); + assert.throws(() => resolveCheckoutQuantity("sak_agent_pass_monthly", 101)); +}); + +test("checkout return links must point back at this site", () => { + assert.equal( + validateReturnUrl("https://superagentskill.com/welcome?session_id={CHECKOUT_SESSION_ID}"), + "https://superagentskill.com/welcome?session_id={CHECKOUT_SESSION_ID}", + ); + assert.ok(validateReturnUrl("https://agent-evolve-network.lovable.app/account/billing")); + assert.throws(() => validateReturnUrl("https://evil.example.com/phish")); + assert.throws(() => validateReturnUrl("https://superagentskill.com.evil.io/x")); + assert.throws(() => validateReturnUrl("javascript:alert(1)")); + assert.throws(() => validateReturnUrl("http://superagentskill.com/welcome")); +}); + +test("an owned diagnosis is only reachable by its owner", () => { + assert.equal(canAccessDiagnosis("user-a", "user-a", "id", "secret"), true); + assert.equal(canAccessDiagnosis("user-a", "user-b", "id", "secret"), false); + assert.equal(canAccessDiagnosis("user-a", null, "id", "secret"), false); + assert.equal(canAccessDiagnosis(null, null, "id", "secret"), false); +});