1. Overview#
Trace is a cross-platform intelligence workspace (targeting iOS, Android, and Web from a single Expo Router codebase) designed to run asynchronous Open-Source Intelligence (OSINT) investigations on a person, organization, or domain (target_name) and stream structured dossiers back to the user in real time.
The repository is currently at Phase 1 (Database Security Boundary & Client Data Layer). Phase 1 completes the hardened PostgreSQL migration (supabase/migrations/20261003000000_investigations.sql), the typed client data-access module (lib/api.ts), and bundler isolation (metro.config.js) for the server-side investigation worker (worker/investigator.js), which executes the Tavily → Nemotron extraction → orchestration → synthesis pipeline in Phase 3.
2. The Problem#
When mobile or web clients connect directly to a Supabase (PostgREST) database using an anon / authenticated JWT, naive table schemas create three severe security and reliability flaws:
- Client-side status and result spoofing: If
authenticatedusers are granted table-wideINSERTorUPDATEpermissions, any user can open DevTools or craft acurlrequest to setstatus = 'completed'and inject fabricatedresult_jsoninto their workspace. - Unbounded job queue flooding: Without database-level concurrency limits, a single user can enqueue hundreds of expensive multi-step AI/web investigation jobs simultaneously.
- Inconsistent state invariants: Allowing a row to transition to
status = 'completed'whileresult_jsonisNULL(or storing a JSON array/primitive instead of a structured dossier object) causes runtime crashes across mobile clients subscribed tosupabase_realtime.
3. The Approach#
Instead of introducing an intermediate CRUD proxy API just to validate inputs, Trace pushes all ownership, sanitization, and rate-limiting invariants directly into PostgreSQL constraints, column privileges, Row-Level Security (RLS), and PL/pgSQL triggers:
- Column-Level `INSERT` Privilege (`grant insert (target_name)`): Authenticated users can only supply
target_nameon insert. They cannot writeuser_id,status,result_json, orerror_message. - Zero Client `UPDATE` Policy: Authenticated users can
SELECT,INSERT, andDELETEtheir own rows, but no `UPDATE` policy exists for theauthenticatedrole. Only the server-side worker running withservice_rolecredentials can transitionstatus(pending → running → completed | failed) and writeresult_json. - Database-Enforced Concurrency Cap: A
BEFORE INSERTPL/pgSQL trigger (investigations_before_insert) counts the user's currently active (pendingorrunning) investigations using a partial index (investigations_active_idx) and aborts the transaction with SQLSTATEP0001ifactive_count >= 3.
| Security & Integrity Requirement | PostgreSQL Mechanism in Trace | Failure Mode Prevented |
|---|---|---|
| Prevent result/status tampering | grant insert (target_name) + no UPDATE RLS policy | Clients cannot forge dossiers or mutate job state |
| Enforce valid dossier shape | CHECK (status <> 'completed' or result_json is not null) + jsonb_typeof = 'object' | Completed jobs never render with missing or non-object JSON |
| Cap concurrent worker load | investigations_before_insert() trigger + partial index | Prevents a single user from exhausting worker capacity |
| Isolate server worker code | metro.config.js blocklist on worker/ | Server worker scripts are never bundled into the mobile/web app |
4. System Architecture#
Clients interact with public.investigations over PostgREST and subscribe to row updates via supabase_realtime, while all state mutations and external AI/search calls are isolated inside the server-side worker.
Target input, investigation list, and real-time status subscription
Mirrors DB validation (2–160 chars, no control chars) and maps P0001 trigger errors
GRANT INSERT (target_name) ONLY; SELECT/DELETE own rows; zero client UPDATE policy
Normalizes whitespace, rejects [[:cntrl:]], resets status='pending', caps active jobs at 3
Verifies jsonb_typeof(result_json) = 'object' and non-null results on completion
Phase 3 pipeline: Tavily search → Nemotron extraction → orchestration → synthesis
5. Engineering Deep Dive#
5.1 Table Invariants, Partial Indexing, and Column Privileges#
In supabase/migrations/20261003000000_investigations.sql, public.investigations uses CHECK constraints to guarantee that result_json is always a JSON object (never a top-level array or primitive) and that no row can be marked completed without a non-null result.
To make concurrency checks fast without scanning historical completed investigations, the migration defines a partial index (WHERE status IN ('pending', 'running')) alongside strict privilege revocation:
create table if not exists public.investigations (
id uuid primary key default gen_random_uuid(),
user_id uuid not null default auth.uid()
references auth.users (id) on delete cascade,
target_name text not null,
status text not null default 'pending',
result_json jsonb,
error_message text,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint investigations_status_check
check (status in ('pending', 'running', 'completed', 'failed')),
constraint investigations_target_name_length
check (char_length(target_name) between 2 and 160),
constraint investigations_result_is_object
check (result_json is null or jsonb_typeof(result_json) = 'object'),
-- A completed investigation must carry a result.
constraint investigations_completed_has_result
check (status <> 'completed' or result_json is not null)
);
-- Active work lookups (rate limiting, worker sweeps).
create index if not exists investigations_active_idx
on public.investigations (user_id, status)
where status in ('pending', 'running');
-- Revoke default privileges and grant column-restricted INSERT
revoke all on public.investigations from anon, authenticated;
grant select, delete on public.investigations to authenticated;
grant insert (target_name) on public.investigations to authenticated;
grant all on public.investigations to service_role;5.2 Input Normalization and Concurrency Trigger (`investigations_before_insert`)#
Even with column-level grants, a client could submit leading/trailing whitespace, ASCII control characters, or excessive concurrent requests. The investigations_before_insert() PL/pgSQL trigger runs as SECURITY DEFINER with an empty search_path = '' (preventing search-path hijacking), collapses internal whitespace, rejects POSIX control characters ([[:cntrl:]]), and enforces the 3-job concurrency ceiling:
create or replace function public.investigations_before_insert()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
active_count integer;
begin
-- Collapse whitespace and trim.
new.target_name := btrim(regexp_replace(new.target_name, '\s+', ' ', 'g'));
-- Reject control characters.
if new.target_name ~ '[[:cntrl:]]' then
raise exception 'Target contains invalid characters' using errcode = '22023';
end if;
-- Users may only create fresh, unprocessed investigations.
if auth.role() = 'authenticated' then
new.status := 'pending';
new.result_json := null;
new.error_message := null;
select count(*) into active_count
from public.investigations
where user_id = new.user_id
and status in ('pending', 'running');
if active_count >= 3 then
raise exception 'You already have 3 investigations in progress. Wait for one to finish.'
using errcode = 'P0001';
end if;
end if;
return new;
end;
$$;5.3 Mirroring Database Constraints in the Client Data Layer (`lib/api.ts`)#
In lib/api.ts, validateTarget() mirrors the exact PostgreSQL length (2..160) and control-character rules so users get instant UI feedback before a network round-trip. When a database error does occur, toApiError() inspects the Postgres error code—surfacing the safe user-facing message when error.code === 'P0001' (our concurrency trigger) while masking internal database details behind clean fallbacks:
export const SUMMARY_COLUMNS =
"id, target_name, status, error_message, created_at, updated_at";
export const TARGET_MIN = 2;
export const TARGET_MAX = 160;
export class TraceApiError extends Error {}
export function validateTarget(
raw: string
): { value: string } | { error: string } {
const value = raw.replace(/\s+/g, " ").trim();
if (value.length < TARGET_MIN)
return { error: "Enter at least two characters." };
if (value.length > TARGET_MAX)
return { error: `Keep the target under ${TARGET_MAX} characters.` };
if (/[\u0000-\u001F\u007F]/.test(value))
return { error: "The target contains invalid characters." };
return { value };
}
function toApiError(
error: { message?: string; code?: string } | null,
fallback: string
) {
if (!error) return new TraceApiError(fallback);
// P0001 = raised by our insert trigger (e.g. concurrency cap) — message is user-safe.
if (error.code === "P0001" && error.message)
return new TraceApiError(error.message);
if (error.code === "42501")
return new TraceApiError("You do not have access to this investigation.");
if (error.code === "PGRST116")
return new TraceApiError("Investigation not found.");
return new TraceApiError(fallback);
}6. Technical Demo#
Technical walkthrough recording coming soon
Architectural walkthrough of Trace's Phase 1 database boundary: column-level INSERT grants, zero client UPDATE policies, PL/pgSQL concurrency triggers, and Metro bundler isolation for the server-side worker.
Walkthrough Sequence & Checkpoints
- 00:00Why Client-Direct BaaS Apps Leak Privilege — The danger of letting mobile/web clients write status or result columns in Supabase.
- 01:10Column-Level Grants & Zero-Update RLS — Walking through 20261003000000_investigations.sql: grant insert (target_name) and service_role isolation.
- 02:30PL/pgSQL Concurrency Trigger & Error Mapping — How investigations_before_insert enforces a 3-job active cap per user and surfaces SQLSTATE P0001 to lib/api.ts.
View Written Walkthrough Summary / Transcript ▾
When building mobile and web applications directly against Backend-as-a-Service platforms like Supabase, a common architectural mistake is relying on client-side TypeScript code to set job statuses or enforce rate limits.
In Trace—an OSINT intelligence workspace built with Expo Router for iOS, Android, and Web—authenticated clients talk directly to PostgREST, but the PostgreSQL schema treats every client request as untrusted.
First, we revoke all default table privileges and grant authenticated users INSERT permission on one column only: target_name. Users have zero UPDATE policies. Second, a BEFORE INSERT PL/pgSQL trigger normalizes whitespace, rejects control characters, forces status to pending, and counts the user's active investigations—raising a custom P0001 exception if they already have 3 investigations running.
7. Challenges and Trade-offs#
- Preventing Metro from Bundling Server Worker Code: Because Expo Router and the server-side worker (
worker/investigator.js) live in the same repository, Metro's recursive file watcher can accidentally include Node-only worker scripts in the mobile bundle. Configuringmetro.config.jsto explicitly block theworker/directory ensured strict build-time separation. - Avoiding Over-Fetching `result_json` in Workspace Lists: A completed OSINT dossier (
result_json) can be десятки of kilobytes of nested JSON. FetchingSELECT *on the workspace list screen wastes mobile bandwidth. Inlib/api.ts,listInvestigations()projects onlySUMMARY_COLUMNS(id, target_name, status, error_message, created_at, updated_at), deferring the fullresult_jsonfetch until the user opens a specific dossier (getInvestigation(id)). - RLS Policy Performance on Every Row: In PostgreSQL RLS policies, writing
auth.uid() = user_iddirectly can evaluateauth.uid()per-row. Wrapping the call in a scalar subquery (using ((select auth.uid()) = user_id)) allows the Postgres query planner to evaluateauth.uid()once per statement as anInitPlan.
8. Testing and Validation#
- TypeScript & Expo Verification: Verified with
npx tsc --noEmitandnpx expo lintacross the mobile/web workspace. - SQL Constraint & Trigger Verification: Validated that inserting a row with
< 2characters, control characters (\u0007), a 4th concurrentpendingrow for the same user, or attempting anUPDATEasauthenticatedis rejected at the database layer. - Current Status (Phase 1 vs. Phase 3): The database schema, RLS policies, realtime publication, and client data-access layer are complete. The server-side worker (
worker/investigator.js) is currently an intentional stub that exits with status1until the Phase 3 Nebius Serverless Jobs + Tavily pipeline is wired.
9. What I Learned#
- Column-level `GRANT INSERT (col)` is an underused superpower in PostgREST/Supabase: Combining column-level privileges with
FORCE ROW LEVEL SECURITYand aBEFORE INSERTtrigger eliminates entire classes of parameter-tampering bugs without writing a single line of middleware code. - Use custom SQLSTATE codes (`P0001`) for intentional domain errors: Distinguishing user-safe business-rule exceptions (
P0001) from unexpected constraint or permission failures (42501) lets the frontend display helpful error messages without leaking internal schema details.
10. Future Improvements#
- Phase 3 (Nebius & Tavily Worker Implementation): Complete
worker/investigator.jsto poll pending jobs usingservice_role, execute multi-query Tavily discovery, extract entities via NVIDIA Nemotron, and write structured dossiers back toresult_json. - Dossier Citation Graph View: Add an interactive source-attribution view in the Expo detail screen linking every synthesized claim to its underlying URL and retrieval timestamp.