Compare commits

Author SHA1 Message Date
jjbrunton 2e4cddd1c8 fix(mobile): restore iOS SDK 54 runtime 2026-08-30 00:29:45 +01:00
jjbrunton 440f224095 docs(release): require upload confirmation 2026-08-30 00:28:14 +01:00
jjbrunton 22871d037c chore(release): configure store submissions
Route Android uploads to an internal draft and bind iOS submissions to the verified App Store Connect app. Document explicit-path local artifact submission and preserve separate release authorization.
2026-08-30 00:13:40 +01:00
jjbrunton 266233a473 fix(api): keep auth sync timestamps monotonic
Use PostgreSQL's clock for both the initial auth sync timestamp and later identity refreshes so host clock skew cannot move the marker backwards.
2026-08-29 23:45:39 +01:00
jjbrunton 2bc69c2790 feat(mobile): surface pending questions
Add a conditional Home cue for partner-answered questions and route both the card and catch-up reminders into the pending answer flow. Track prompt engagement and cover hidden, visible, CTA, and notification behavior.
2026-08-29 23:24:19 +01:00
jjbrunton 9da44217f7 feat(release): add generation workflow
Add a guarded mobile release skill that synchronizes public versions, writes on-brand notes, verifies signed iOS and Android artifacts, and tags the verified release commit.
2026-08-29 23:22:35 +01:00
jjbrunton 5f77b06044 test(coverage): enforce API and app floors
Measure untouched mobile source, add regression coverage for native media paths and account operations, and enforce ratcheting API and mobile thresholds in required CI checks.
2026-08-29 22:50:07 +01:00
jjbrunton 5c973c4ac5 perf(api): bound worker pools and add telemetry
Share one configured PostgreSQL pool across worker repositories and make API and worker connection budgets explicit.

Add privacy-safe aggregate request, query, pool, sync, and outbox telemetry, a loopback-only representative load fixture, bounded worker shutdown, and focused regression and integration coverage.

Document the database-wide budget formula and defer pg_stat_statements activation to a reviewed migration and planned restart.
2026-08-29 22:43:27 +01:00
jjbrunton a13bbc3f65 docs(agents): require published completion 2026-08-29 21:59:50 +01:00
jjbrunton 10c4ae8d84 docs(agents): require isolated implementation 2026-08-29 21:58:13 +01:00
jjbrunton ac4a05d5ed chore(staging): reconcile main ancestry 2026-08-29 21:49:46 +01:00
jjbrunton c7ee8a4851 perf(app): reduce redundant data fetching
Share bounded database pools across API repositories, consolidate sync and chat queries, and make mobile refreshes cache-aware and foreground-aware.

Add focused regression coverage, client freshness documentation, and repository agent role configuration.
2026-08-29 21:47:27 +01:00
jjbrunton 9957fa43f2 feat(agents): add Claude delegation skill
Add a repository-owned Codex skill and helper for bounded Claude Code execution, model and effort selection, resumable follow-ups, and independent acceptance checks.
2026-08-29 18:29:29 +01:00
jjbrunton 502452c9e4 Merge pull request #4 from jjbrunton/staging
chore(release): promote staging to production
2026-08-29 00:12:03 +01:00
jjbrunton e6bb368bc8 Merge pull request #7 from jjbrunton/task/production-cutover-import
feat(api): harden production data import
2026-08-29 00:08:15 +01:00
jjbrunton aedba2a480 feat(api): harden production data import
Preserve live Dokploy state while importing legacy Supabase data. Add schema parity, safe relationship reconciliation, storage quarantine, and production-shaped integration coverage.
2026-08-29 00:04:11 +01:00
jjbrunton 78900a24fb ci(staging): enable direct verification
Allow agents to run required checks manually against an exact commit before pushing it directly to staging, while retaining protected status checks.
2026-08-28 20:41:18 +01:00
jjbrunton 03443fe898 chore(staging): integrate verified changes
Combine the Android API 36 release, dares loop, RevenueCat documentation correction, and daily engagement features. Resolve migration ordering and preserve both dares expiry and streak reminder operations.
2026-08-28 20:36:05 +01:00
jjbrunton b60c788362 feat(engagement): localize limits and streaks
Use reported user timezones for daily response limits, expose couple streak state and reminders, and improve swipe and live-drawing synchronization with focused tests and documentation.
2026-08-28 20:28:31 +01:00
jjbrunton 61ec3692b7 chore(android): target API 36 with Expo 54
Upgrade the mobile native toolchain and Expo dependencies for Android 16 compatibility while preserving web and admin runtime isolation.
2026-08-28 20:28:31 +01:00
jjbrunton 1482305810 Merge remote-tracking branch 'origin/staging' into task/android-api-36 2026-08-28 20:22:16 +01:00
jjbrunton 8b37569818 Merge pull request #5 from jjbrunton/feat/dares-loop
feat(dares): ship the dares loop to mobile
2026-08-28 20:18:11 +01:00
jjbrunton 2178750d07 chore(android): bump version code to 47 2026-08-28 20:17:19 +01:00
jjbrunton 028e21e54c Merge origin/staging (Expo 54 / Android API 36) into feat/dares-loop 2026-08-28 20:12:55 +01:00
jjbrunton b24a402b4c Merge pull request #3 from jjbrunton/task/android-api-36
chore(android): target API 36 with Expo 54
2026-08-28 20:09:20 +01:00
jjbruntonandClaude Opus 5 ce0b188776 feat(dares): ship the dares loop to mobile
Completes the half-built dares feature: send a dare, respond, report done,
confirm, and get a push notification on every transition.

Backend (apps/api):
- New `dares` domain with couple-shared premium entitlement, a free weekly
  send allowance, and server-enforced actor/state rules on every transition.
- `submitted` status so the recipient reports completion and the sender
  confirms, rather than the sender guessing.
- Notifications ride the existing operations outbox via a trigger on
  `sent_dares`. Push copy is generic; store compliance forbids dare text in a
  preview and a test asserts no payload leaks it.
- Worker expiry sweep now covers `pending` as well as `active`/`submitted`;
  an invitation nobody opened previously stayed open forever.

Fixes two latent defects:
- Deleting any dare that had been sent aborted with a check violation, because
  `dare_id` is ON DELETE SET NULL while `sent_dares_dare_or_custom_check`
  required it. Dare text is now snapshotted at send time, which also keeps a
  couple's history stable across catalogue edits.
- The free send allowance was raceable: concurrent requests all read the same
  count and every one succeeded. The count and insert are now serialized on
  the sender's profile row.

Also ports `content_status` review metadata to the API catalogue, which had no
store-safety gating at all, and mirrors the review decision already enforced on
the legacy catalogue.

Mobile: dares screen (active/send/history), send sheet with duration presets,
home tile badging incoming dares, paywall on both proactive and 402 paths.

Verified: lint, typecheck, 379 unit tests, build, 71 integration tests against
local PostgreSQL.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 20:03:11 +01:00
jjbrunton f35114dc77 chore(android): target API 36 with Expo 54
Upgrade the mobile runtime and tracked Android project to compile and target API 36. Align Expo modules, React Native, Node, Gradle, and Android build tooling while preserving the custom widget sources.\n\nAdapt file-system, notification, animation, test, and Metro compatibility for the SDK 54 runtime.
2026-08-28 20:01:15 +01:00
jjbruntonandClaude Opus 5 aacb4f8731 docs(subscription): correct stale Android RevenueCat status
The Platform Support section claimed Android was "not yet implemented".
Android has full native SDK support: getApiKey() selects the Android key,
com.android.vending.BILLING is declared in app.json, the paywall has no
platform gating, and the webhook passes event.store through unchanged so
PLAY_STORE events need no separate handling.

Also flag the entitlement ID mismatch between the "pro" fallback in
revenuecat.ts and the "Sauci Pro" value set in eas.json. A build profile
missing that variable yields isProUser: false with no error, which
presents as churn rather than as misconfiguration.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 19:26:53 +01:00
jjbrunton 1be54175e4 Merge pull request #2 from jjbrunton/staging
chore(release): promote mobile build hardening
2026-08-28 18:44:58 +01:00
jjbrunton a7470310ae Merge pull request #1 from jjbrunton/task/mobile-release-hardening
chore(release): harden mobile build workflow
2026-08-28 18:39:14 +01:00
jjbrunton 3acadeff7c chore(release): harden mobile build workflow
Promote the reproduced release lessons into harness enforcement: keep tracked native regeneration separate from artifact builds, separate Android build and upload authorization, use stable login readiness in Maestro, and retain the iOS 43 and Android 46 version increments.
2026-08-28 18:34:00 +01:00
jjbrunton 91544629fa fix(worker): keep polling process alive 2026-08-28 15:11:12 +01:00
jjbrunton 32f5214751 fix(backend): allow deferred provider integrations 2026-08-28 15:00:57 +01:00
jjbrunton 96882642c7 fix(ci): start healthcheck-free worker separately 2026-08-28 14:56:53 +01:00
jjbrunton a455325147 ci(deploy): establish staged Dokploy promotion 2026-08-28 14:54:12 +01:00
jjbrunton 2dad7aa352 feat(admin): serve response media from standalone API 2026-08-28 14:54:07 +01:00
jjbrunton be20391788 Merge remote-tracking branch 'origin/master' into task/self-hosted-backend
# Conflicts:
#	apps/mobile/app/(app)/onboarding.tsx
#	apps/mobile/src/__tests__/stores/packsStore.test.ts
#	apps/mobile/src/features/profile/hooks/useProfileSettings.ts
#	apps/mobile/src/store/packsStore.ts
2026-08-28 14:44:51 +01:00
jjbrunton 006761d3b0 feat(backend): add standalone data plane
Replace the Supabase application data plane with the Node/PostgreSQL API, migrate mobile, admin, web, and MCP callers, add controlled cutover tooling, and define hardened Dokploy infrastructure.
2026-08-28 14:42:11 +01:00
jjbrunton 7a0de45482 feat(mobile): align store-safe experience
Remove client-side adult-content preferences and badges so the centrally reviewed catalogue is the single visibility boundary.\n\nUse neutral relationship-focused copy across onboarding, discovery, paywall, and login surfaces, and retain biometric controls under App Lock for both native platforms.
2026-08-28 14:36:33 +01:00
jjbrunton 72e031eb84 fix(content): keep catalogue migration portable
Classify every environment through the immutable allowlist and archive unknown concurrent additions. Remove the remote-project dependency while retaining fail-closed postconditions.
2026-08-28 13:24:43 +01:00
jjbrunton 2ab976ec42 fix(content): scope production catalogue guard
Keep exact audited-count assertions for the production project while allowing local and non-production fixture catalogues to be classified by the same immutable allowlist.
2026-08-28 13:21:35 +01:00
jjbrunton c0650ed5b7 feat(content): enforce reviewed catalogue
Hide archived and unreviewed catalogue content from existing clients through RLS and guarded recommendation RPCs. Reject stale writes, preserve historical rows, and seed reviewed defaults when the cutover removes a couple's full active selection.
2026-08-28 13:15:33 +01:00
jjbrunton 94c76535a4 feat(content): add catalogue review metadata
Add reversible review states, audit history, and super-admin controls for catalogue entities without changing current client visibility.

Stage 30 high-risk production packs for archival review, cap generated content at non-explicit language, and preserve a checksummed pre-change production catalogue snapshot.
2026-08-28 11:32:55 +01:00
470 changed files with 79455 additions and 12948 deletions

No files matched your search

@@ -0,0 +1,37 @@
---
id: 2026-08-28-maestro-stable-login-readiness
date: 2026-08-28
status: promoted
scope: native Auth-shell acceptance flows
evidence: iOS simulator login-shell acceptance on current main
destination: e2e/maestro
review_after: 2027-02-28
---
## Symptom
The credential-free native smoke failed even though the current app reached the
login screen and displayed its required controls.
## Reproduction
Run `e2e/maestro/login-screen-smoke.yaml` against current main. The flow waited
for the retired tagline `Explore intimacy together`; the app displayed updated
marketing copy while `Sauci` and `Password` were present.
## Cause
Login readiness was coupled to mutable marketing copy rather than a stable
required control.
## Remediation
Wait for the password control that defines login readiness, while retaining the
brand and password assertions. Apply the same readiness condition to the
authenticated and credential-free flows.
## Evidence
Simulator read-back confirmed the current login shell exposes `Sauci` and
`Password`. The maintained Maestro flows now wait for that stable control rather
than the tagline.
@@ -0,0 +1,40 @@
---
id: 2026-08-28-mobile-release-source-integrity
date: 2026-08-28
status: promoted
scope: mobile release build and upload workflow
evidence: clean-source local EAS builds for iOS 43 and Android 46
destination: scripts/lint-harness.mjs
review_after: 2027-02-28
---
## Symptom
A build-only request initially regenerated tracked native projects. The generated
Android widget provider replaced the checked-in implementation, and the Android
release script would also have uploaded after building.
## Reproduction
Run the former mobile release scripts or run `expo prebuild` before a local EAS
build, then inspect `git diff`. The reproduced diff included the Android widget
provider, widget XML, and Xcode project rather than version metadata alone.
## Cause
The release scripts combined three independently reviewed operations: native
regeneration, artifact creation, and store upload. Sauci already tracks native
projects, and EAS skips prebuild when those directories exist.
## Remediation
Keep native regeneration explicit, make release scripts artifact-only, expose
upload separately, and lint the scripts so those responsibilities cannot be
silently recombined.
## Evidence
Corrected local EAS logs reported `PREBUILD` skipped. Both production artifacts
built successfully from the clean tracked sources; the post-build worktree
contained only the four expected build-number files. `npm run lint:harness`
enforces the release-script boundary.
+11
View File
@@ -0,0 +1,11 @@
name = "architecture_reviewer"
description = "Read-only reviewer for cross-cutting or hard-to-reverse Sauci architecture decisions."
model = "gpt-5.6-sol"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
developer_instructions = """
Evaluate the delegated decision against current system boundaries, data flow,
migration path, operability, reversibility, and verification. Prefer the smallest
coherent change. Return explicit trade-offs, risks, and a recommendation with
file-backed evidence. Do not edit files or review unrelated local refactors.
"""
+12
View File
@@ -0,0 +1,12 @@
name = "database_reviewer"
description = "Read-only reviewer for Sauci migrations, RLS, authorization, and query boundaries."
model = "gpt-5.6-terra"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
developer_instructions = """
Read the applicable AGENTS.md, database migration skill, and migration safety
documentation. Review only the delegated diff for migration tracking,
idempotency, authorization and tenant isolation, portability, rollback impact,
types, and integration coverage. Never mutate a database or edit files. Return
prioritized line-specific findings with concrete evidence and counterevidence.
"""
+12
View File
@@ -0,0 +1,12 @@
name = "implementation"
description = "Default executor for a bounded Sauci product or harness change after scope and acceptance criteria are known."
model = "gpt-5.6-terra"
developer_instructions = """
Read the root and nearest scoped AGENTS.md files plus the applicable repository
skill. Implement only the delegated objective and preserve unrelated work. Update
maintained contract documentation and add focused tests when the contract changes.
Run the required focused checks and return changed files, exact results,
assumptions, and blockers. Stop for missing authority or a materially ambiguous
product choice. Do not expand scope or perform external, destructive, production,
release, or provider writes unless the task explicitly authorizes that action.
"""
+11
View File
@@ -0,0 +1,11 @@
name = "repo_scout"
description = "Read-only Sauci codebase scout for locating ownership, callers, contracts, tests, and existing patterns."
model = "gpt-5.6-luna"
model_reasoning_effort = "low"
sandbox_mode = "read-only"
developer_instructions = """
Read the root and nearest scoped AGENTS.md files. Map only the requested surface.
Return evidence-backed file paths, symbols, current behavior, dependencies, tests,
and uncertainties. Do not edit files, make design decisions, or propose broad
refactors. Do not claim runtime behavior you did not observe.
"""
+12
View File
@@ -0,0 +1,12 @@
name = "security_reviewer"
description = "Read-only reviewer for auth, RLS, cryptography, secrets, payments, privileged MCP, and destructive operations."
model = "gpt-5.6-sol"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
developer_instructions = """
Perform a scoped threat-boundary review of the delegated change. Trace callers
through authentication and authorization to the data sink. Prioritize exploitable
correctness and security risks, include counterevidence, and cite exact files and
lines. Do not edit files or expand into a repository-wide audit unless explicitly
requested.
"""
+11
View File
@@ -0,0 +1,11 @@
name = "test_writer"
description = "Focused Sauci regression and contract-test author for already-defined behavior."
model = "gpt-5.6-terra"
model_reasoning_effort = "medium"
developer_instructions = """
Read the applicable AGENTS.md and testing documentation. Test the intended
observable contract at the lowest useful layer while preserving real auth,
authorization, tenant, and couple boundaries. Do not weaken assertions to
accommodate a failure. Run the focused test and return files changed, exact
commands, results, and any product defect exposed by the test.
"""
+11
View File
@@ -0,0 +1,11 @@
name = "verifier"
description = "Independent Sauci behavior verifier that drives completed work and returns evidence, not fixes."
model = "gpt-5.6-terra"
model_reasoning_effort = "medium"
developer_instructions = """
Read the applicable AGENTS.md and .codex/skills/verify/SKILL.md. Independently
exercise the delegated acceptance criteria against the running non-production
product. You may write generated proof only under evidence/. Do not edit source,
tests, configuration, or acceptance criteria. Return expected behavior, observed
behavior, evidence paths, environment limitations, and a works or broken verdict.
"""
+5
View File
@@ -0,0 +1,5 @@
[agents]
enabled = true
max_concurrent_threads_per_session = 3
default_subagent_model = "gpt-5.6-terra"
default_subagent_reasoning_effort = "medium"
+73
View File
@@ -0,0 +1,73 @@
---
name: delegate-to-claude
description: Delegate a bounded coding, investigation, or review task from Codex to Claude Code, then inspect and independently assess Claude's result. Use when the user asks Codex to delegate to Claude or when a second-model execution or review pass is explicitly desired. Do not use for ordinary Codex subagents or as a substitute for Codex's final review.
---
# Delegate to Claude Code
Use Claude Code as an executor or independent reviewer while Codex remains the coordinator responsible for scope, evidence, and acceptance.
## Preconditions
1. Confirm `claude` is installed and authenticated by running `scripts/claude_delegate.sh check` from this skill directory.
2. Read the repository's applicable `AGENTS.md`, `CLAUDE.md`, and task-specific instructions before writing the work order.
3. Do not delegate secrets, provider writes, production mutations, releases, or destructive operations unless the user explicitly authorized that exact action. Claude receives no broader authority than Codex has.
## Work order
Write the task into a temporary Markdown file outside the repository unless the user requested a durable task artifact. Make it self-contained and include:
- role: executor or read-only reviewer;
- exact objective and boundaries;
- working directory and relevant files;
- repository instructions Claude must read;
- allowed side effects and forbidden actions;
- required checks and expected evidence;
- requested return format: findings or changed files, commands run, results, and blockers.
The helper adds an executor marker and tells Claude not to spawn further agents. Do not pass the user's whole conversation when a concise work order is sufficient.
## Run
From the target repository directory:
```bash
/absolute/path/to/this-skill/scripts/claude_delegate.sh run /absolute/path/to/work-order.md /absolute/path/to/result.json
```
The default permission mode is `auto`, which lets Claude decide whether tools are safe to use. Override it only when the task requires a stricter mode:
```bash
CLAUDE_DELEGATE_PERMISSION_MODE=plan scripts/claude_delegate.sh run work-order.md result.json
```
Optional environment variables:
- `CLAUDE_DELEGATE_MODEL`: Claude model alias or full model name; default `sonnet`.
- `CLAUDE_DELEGATE_EFFORT`: `low`, `medium`, `high`, `xhigh`, or `max`; default `medium`.
- `CLAUDE_DELEGATE_MAX_BUDGET_USD`: API budget ceiling when supported by the current authentication mode.
- `CLAUDE_DELEGATE_PERMISSION_MODE`: default `auto`; prefer `plan` for read-only planning/review when tools are unnecessary.
The helper loads project and local Claude settings while excluding user-level integrations by default, and disables browser/MCP integrations. This keeps delegation focused on the checked-out repository. If a task genuinely requires an external connector, handle that action in Codex under the original authorization rather than silently widening Claude's access.
Never choose `bypassPermissions` merely to avoid a permission failure. Use it only when the user explicitly requests it and the execution is inside an appropriately isolated sandbox.
For a follow-up in the same Claude session, obtain `session_id` from the JSON result and run:
```bash
scripts/claude_delegate.sh resume SESSION_ID follow-up.md follow-up-result.json
```
If a call outlives the command yield, continue waiting on that same process/session rather than launching a duplicate.
## Accept or iterate
Claude's summary is evidence to inspect, not proof. Codex must:
1. inspect the actual diff or artifacts;
2. run proportionate independent checks;
3. compare the result with the original scope and repository rules;
4. send a focused follow-up with concrete failures when iteration is needed;
5. report Claude's contribution separately from Codex's verification.
Do not claim success from Claude's self-report alone. Codex retains the decision to accept, commit, publish, deploy, or make any external change.
@@ -0,0 +1,4 @@
interface:
display_name: "Delegate to Claude Code"
short_description: "Delegate scoped work to Claude Code"
default_prompt: "Use $delegate-to-claude to delegate this scoped task to Claude Code and review the result."
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
set -euo pipefail
die() {
printf 'claude_delegate: %s\n' "$*" >&2
exit 1
}
usage() {
cat >&2 <<'EOF'
usage:
claude_delegate.sh check
claude_delegate.sh run <prompt-file> [result-json]
claude_delegate.sh resume <session-id> <prompt-file> [result-json]
EOF
exit 2
}
command -v claude >/dev/null 2>&1 || die "claude CLI is not installed or not on PATH"
if [[ "${1:-}" == "check" ]]; then
claude --version
auth_status="$(claude auth status 2>/dev/null)" || die "unable to read Claude authentication status"
[[ "$auth_status" == *'"loggedIn": true'* ]] || die "Claude CLI is not authenticated"
printf 'authentication: logged in\n'
exit 0
fi
mode="${1:-}"
case "$mode" in
run)
[[ $# -ge 2 && $# -le 3 ]] || usage
prompt_file="$2"
result_file="${3:-}"
resume_id=""
;;
resume)
[[ $# -ge 3 && $# -le 4 ]] || usage
resume_id="$2"
prompt_file="$3"
result_file="${4:-}"
[[ "$resume_id" =~ ^[0-9a-fA-F-]{36}$ ]] || die "session id must be a UUID"
;;
*) usage ;;
esac
[[ -f "$prompt_file" ]] || die "prompt file does not exist: $prompt_file"
[[ -r "$prompt_file" ]] || die "prompt file is not readable: $prompt_file"
prompt="ROLE: EXECUTOR — do the work yourself; do not spawn subagents. Stay within the work order's authorization and scope. At the end, report changed files or findings, commands and checks run with results, and any blockers. WORK ORDER: $(<"$prompt_file")"
effort="${CLAUDE_DELEGATE_EFFORT:-medium}"
permission_mode="${CLAUDE_DELEGATE_PERMISSION_MODE:-auto}"
case "$effort" in low|medium|high|xhigh|max) ;; *) die "invalid effort: $effort" ;; esac
case "$permission_mode" in acceptEdits|auto|manual|dontAsk|plan|bypassPermissions) ;;
*) die "invalid permission mode: $permission_mode" ;;
esac
model="${CLAUDE_DELEGATE_MODEL:-sonnet}"
args=(--print --output-format json --model "$model" --effort "$effort" --permission-mode "$permission_mode" --setting-sources project,local --strict-mcp-config --no-chrome)
[[ -n "${CLAUDE_DELEGATE_MAX_BUDGET_USD:-}" ]] && args+=(--max-budget-usd "$CLAUDE_DELEGATE_MAX_BUDGET_USD")
[[ -n "$resume_id" ]] && args+=(--resume "$resume_id")
if [[ -n "$result_file" ]]; then
result_dir="$(dirname "$result_file")"
[[ -d "$result_dir" ]] || die "result directory does not exist: $result_dir"
claude "${args[@]}" "$prompt" | tee "$result_file"
else
claude "${args[@]}" "$prompt"
fi
+116
View File
@@ -0,0 +1,116 @@
---
name: generate-release
description: Generate a signed Sauci mobile release by bumping the public version, writing on-brand release notes, building and verifying iOS and Android binaries, committing release metadata, and tagging the release commit. Use for an actual production mobile release; use release-mobile for preparation, one-platform builds, uploads, or submission work that does not require the complete release lifecycle.
---
# Generate release
Create a reproducible release whose tag identifies the reviewed release source
and final platform build metadata. Read `apps/mobile/AGENTS.md`,
`docs/releasing.md`, and the `release-mobile` and `commit` skills before acting. Read
[references/release-notes-voice.md](references/release-notes-voice.md) before
drafting notes and [references/artifact-verification.md](references/artifact-verification.md)
before accepting a build.
A request to generate or create a release authorizes the scoped version edits,
release notes, local builds, release commits, and one local annotated tag. It
does not authorize pushing commits or tags, uploading binaries, submitting a
store release, changing signing credentials, or regenerating native projects.
## Defaults
- Build both iOS and Android production binaries unless the user narrows the
platforms.
- Increment the patch version unless the user specifies `minor`, `major`, or an
exact SemVer version.
- Use `v<version>` for the annotated Git tag.
- Write artifacts beneath ignored `dist/releases/v<version>/`; never commit
binaries, credentials, logs, or build directories.
## Preflight
Fetch the remote and inspect the worktree, branch, upstream, existing tags,
toolchains, EAS authentication, and signing availability without changing them.
Require all of the following:
- a named branch, normally `main` for a production release;
- a clean starting worktree with `HEAD` equal to its fetched upstream;
- the previous reachable `v[0-9]*` release tag and no collision for the next tag;
- consistent public versions across `app.json`, Android `versionName`, and every
iOS `MARKETING_VERSION` (`scripts/set_version.mjs --check`);
- Node 20, JDK 17 for Android, and Xcode/CocoaPods for iOS;
- the configured production API/Auth/RevenueCat environment, without printing
secret values.
Do not switch branches, discard work, repair credentials, push, or weaken branch
protection merely to pass preflight. Stop with the exact blocker. Never run
`expo prebuild` as part of this workflow.
## Prepare the release
1. Derive the next version with `scripts/set_version.mjs --bump <kind>` or set an
explicit version with `--version <x.y.z>`. The script updates the checked-in
public-version sources but deliberately leaves platform build numbers to EAS.
2. Review the complete first-parent and ordinary commit diff from the previous
reachable release tag to the starting commit. Inspect the actual product diff
for every user-facing claim; commit subjects alone are not evidence.
3. Add the new entry immediately below the title in `docs/release-notes.md`.
Describe user-visible value, meaningful fixes, privacy or reliability changes,
and only claims supported by the diff. Omit internal migrations, refactors,
CI, infrastructure, dependency churn, and implementation jargon unless the
user experiences a direct result. Use a temporary `Build numbers pending
artifact verification` line until the binaries have been inspected; never
guess or predict build numbers.
4. Run `npm run verify:full` and the native acceptance required by the
`release-mobile` skill. A missing prerequisite is a failure/limitation, not a
pass.
5. Review the scoped diff and create `chore(release): prepare v<version>`. Do not
stage unrelated paths. This clean release-preparation commit must descend
directly from the fetched upstream commit.
## Build and capture platform metadata
Build from the clean prepared source using the package scripts in
`apps/mobile/package.json`, with `EAS_LOCAL_BUILD_ARTIFACTS_DIR` set to the
versioned artifact directory. When building both platforms, build Android first,
then iOS.
After each build:
1. Inspect the worktree before doing anything else. Accept only the documented
EAS build-number changes in `app.json`, that platform's native version source,
and the iOS widget plist when applicable. Treat any implementation, resource,
dependency, or native-project regeneration as a failed build.
2. Independently inspect the binary for package/bundle identifier, public
version, platform build number, production endpoint configuration where
inspectable, and signing identity/fingerprint. Require the embedded public
version to equal the requested version.
3. Record the verified platform build number in the new release-note entry.
4. Commit only the expected metadata and release-note update as
`chore(<platform>): record v<version> build <number>`. The worktree must be
clean before starting the next platform build.
Do not accept a successful EAS exit code as proof of a valid artifact. If either
requested platform fails, do not tag a partial release.
## Tag and prove the result
Re-run focused version checks and `npm run verify:fast`. Confirm every requested
artifact exists, has a SHA-256 digest, passed independent version/signature
inspection, and was produced from the release commit chain. Require a clean
worktree, then create the annotated local tag `v<version>` at `HEAD`.
Read back the tag object and prove:
- the tag resolves to `HEAD`;
- the tag version equals all public-version sources and embedded artifacts;
- recorded build numbers equal the embedded platform build numbers;
- no binary or ignored build output entered the commit;
- the release commits descend from the fetched starting branch commit;
- for a two-platform release, the Android artifact's source commit differs from
the final tag only by the later verified iOS build metadata.
Report the branch, tag, commit, release-note summary, artifact paths, versions,
build numbers, signatures, SHA-256 digests, checks run, and any environmental
limitations. State explicitly that the tag and commits remain local unless a
separate authorized push was completed.
@@ -0,0 +1,4 @@
interface:
display_name: "Generate Release"
short_description: "Bump, build, note, and tag Sauci releases"
default_prompt: "Use $generate-release to create the next signed Sauci mobile release for iOS and Android."
@@ -0,0 +1,39 @@
# Release artifact verification
Use the strongest locally available platform tools and record the commands and
results. Never print provisioning profiles, keys, tokens, or environment values.
## Android AAB
Require a production `.aab`. Inspect its manifest with `bundletool dump manifest`
or Android SDK `apkanalyzer`, and verify:
- package `com.sauci.app`;
- `versionName` equals the release version;
- `versionCode` equals the recorded Android build number.
Verify the archive signature with `jarsigner -verify -verbose -certs`. Compare the
signing certificate SHA-1 to the production fingerprint documented in
`docs/releasing.md`; do not copy credentials into commands or reports. Calculate
the artifact SHA-256 with `shasum -a 256`.
## iOS IPA
Extract the `.ipa` into a new temporary directory created with `mktemp -d`. Read
the application `Info.plist` with `/usr/libexec/PlistBuddy` or `plutil` and verify:
- `CFBundleIdentifier` is `com.sauci.app`;
- `CFBundleShortVersionString` equals the release version;
- `CFBundleVersion` equals the recorded iOS build number.
Use `codesign -dvvv` and `codesign --verify --deep --strict` on the extracted app
to inspect and verify signing without exposing the embedded profile. Calculate the
original `.ipa` SHA-256 with `shasum -a 256`. Remove only the explicit temporary
extraction directory after inspection.
## Source correspondence
For both platforms, retain the build command, artifact path, build completion
time, and digest in the final report. Compare the post-build tracked diff with the
documented allowed version files. A binary with the right version but unexpected
source regeneration, wrong signing, or an unverifiable manifest is not accepted.
@@ -0,0 +1,51 @@
# Sauci release-note voice
Sauci sounds warm, confident, inviting, and quietly playful. It is a premium
couples app about private connection and shared curiosity: supportive without
being clinical, polished without sounding corporate, and intimate without being
graphic or presumptuous.
## Shape
Use a short opening sentence followed by three to six compact bullets. Lead with
the change that most improves a couple's experience. Combine related work into
one benefit rather than mirroring the commit list. Include a brief closing line
only when it adds warmth or useful context.
In `docs/release-notes.md`, use:
```markdown
## v1.2.3 — 29 August 2026
_iOS build 44 · Android build 48_
A little more ease, clarity, and connection in every check-in.
- **Closer conversations** — Find the prompts that feel right for both of you.
- **Smoother moments** — Chats and matches now feel quicker and more reliable.
- **More control** — Clearer choices help keep your shared space comfortable.
```
Adapt the words to the evidence; do not reuse this copy when those claims are not
present in the release. If only one platform was requested, record only its build.
## Language
- Address the couple's experience with `you`, `your partner`, `together`, or
`your shared space` where natural.
- Prefer concrete benefits: `pick up where you left off`, `find the right prompt`,
`keep conversations flowing`, `stay in control`.
- Use restrained warmth. One gentle phrase is enough; avoid forced innuendo,
breathless hype, exclamation marks, emoji, and claims that Sauci will improve or
fix a relationship.
- Prefer `new`, `smoother`, `clearer`, `more private`, and `more reliable` to
`revolutionary`, `game-changing`, `massive`, or `best ever`.
- Explain a fix as the experience restored, not the defect mechanics. Name a
security or privacy change plainly when users need to understand it.
## Evidence boundary
Release notes describe shipped behavior only. Do not claim a feature from a plan,
flagged-off path, migration, test, or commit title without confirming the runtime
path in the diff and release configuration. Do not expose internal service names,
database details, moderation logic, security-sensitive implementation, or content
that the product intentionally keeps private between partners.
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(scriptDir, "../../../..");
const files = {
app: path.join(repoRoot, "apps/mobile/app.json"),
android: path.join(repoRoot, "apps/mobile/android/app/build.gradle"),
ios: path.join(repoRoot, "apps/mobile/ios/Sauci.xcodeproj/project.pbxproj"),
};
const semverPattern = /^([0-9]+)\.([0-9]+)\.([0-9]+)$/;
function fail(message) {
console.error(`set_version: ${message}`);
process.exit(1);
}
function parseVersion(value, label) {
const match = semverPattern.exec(value);
if (!match) fail(`${label} must be an exact numeric SemVer version (x.y.z)`);
return match.slice(1).map(Number);
}
function readState() {
const appRaw = fs.readFileSync(files.app, "utf8");
const androidRaw = fs.readFileSync(files.android, "utf8");
const iosRaw = fs.readFileSync(files.ios, "utf8");
const appVersion = JSON.parse(appRaw).expo?.version;
const androidVersions = [...androidRaw.matchAll(/\bversionName\s+["']([^"']+)["']/g)].map(
(match) => match[1],
);
const iosVersions = [...iosRaw.matchAll(/\bMARKETING_VERSION\s*=\s*([^;]+);/g)].map(
(match) => match[1].trim(),
);
if (typeof appVersion !== "string") fail("apps/mobile/app.json has no expo.version");
if (androidVersions.length !== 1) fail("expected exactly one Android versionName");
if (iosVersions.length === 0) fail("found no iOS MARKETING_VERSION values");
const versions = [appVersion, ...androidVersions, ...iosVersions];
versions.forEach((version) => parseVersion(version, `configured version ${version}`));
if (new Set(versions).size !== 1) {
fail(`public versions disagree: ${versions.join(", ")}`);
}
return { appRaw, androidRaw, iosRaw, current: appVersion, iosCount: iosVersions.length };
}
function nextVersion(current, bump) {
const [major, minor, patch] = parseVersion(current, "current version");
if (bump === "major") return `${major + 1}.0.0`;
if (bump === "minor") return `${major}.${minor + 1}.0`;
if (bump === "patch") return `${major}.${minor}.${patch + 1}`;
fail("--bump must be patch, minor, or major");
}
const args = process.argv.slice(2);
const check = args.length === 1 && args[0] === "--check";
const bumpIndex = args.indexOf("--bump");
const versionIndex = args.indexOf("--version");
if (!check && (bumpIndex === -1) === (versionIndex === -1)) {
fail("use --check, --bump patch|minor|major, or --version x.y.z");
}
const state = readState();
if (check) {
console.log(`public version ${state.current} is consistent across app.json, Android, and ${state.iosCount} iOS settings`);
process.exit(0);
}
const desired =
bumpIndex !== -1
? nextVersion(state.current, args[bumpIndex + 1])
: (parseVersion(args[versionIndex + 1], "--version"), args[versionIndex + 1]);
if (desired === state.current) fail(`requested version is already ${state.current}`);
const currentParts = parseVersion(state.current, "current version");
const desiredParts = parseVersion(desired, "requested version");
const increases = desiredParts.some(
(part, index) => part > currentParts[index] && desiredParts.slice(0, index).every((value, prior) => value === currentParts[prior]),
);
if (!increases) fail(`requested version ${desired} must be greater than ${state.current}`);
const appRaw = state.appRaw.replace(
/(\"version\"\s*:\s*\")([^\"]+)(\")/,
`$1${desired}$3`,
);
const androidRaw = state.androidRaw.replace(
/(\bversionName\s+["'])([^"']+)(["'])/,
`$1${desired}$3`,
);
const iosRaw = state.iosRaw.replace(
/(\bMARKETING_VERSION\s*=\s*)([^;]+)(;)/g,
`$1${desired}$3`,
);
fs.writeFileSync(files.app, appRaw);
fs.writeFileSync(files.android, androidRaw);
fs.writeFileSync(files.ios, iosRaw);
console.log(`updated public version ${state.current} -> ${desired}`);
+47 -4
View File
@@ -9,7 +9,50 @@ Read `docs/releasing.md`, `apps/mobile/RELEASING.md` when present, and the mobil
scoped instructions. Confirm target platform and release profile. Run repository
verification plus a native acceptance pass before starting a release build.
Use the package scripts in `apps/mobile/package.json`; preserve platform signing
and versioning. Building or uploading to a store is an external mutation: obtain
explicit authorization for the requested target, then report the build artifact,
version/build number, upload result, and read-back state.
Before a build from the current upstream branch, fetch, require a clean worktree,
and prove `HEAD` matches its upstream. The `generate-release` skill may instead
build a clean, scoped release-preparation commit that descends directly from that
fetched upstream; between its multi-platform builds it commits only independently
verified EAS version metadata. Sauci tracks its native iOS and Android projects,
so routine release builds must package those checked-in sources. Do not run
`expo prebuild` first; native regeneration is a separate reviewed change.
Use the package scripts in `apps/mobile/package.json`; they create artifacts only.
Never infer upload or submission authority from build authorization. Store upload
uses a separately authorized command.
## Upload authorization gate
After an artifact passes verification, stop immediately before the external
upload and ask the user for confirmation. The request must identify:
- the platform, exact artifact path, bundle/package identifier, public version,
build number, signature identity, and SHA-256 digest;
- the exact destination and resulting state: Google Play internal-track draft or
App Store Connect/TestFlight processing;
- that the upload does not authorize a public rollout or App Review submission.
For iOS, inspect the current App Store Connect automatic-distribution behavior
before asking. If the build would be distributed automatically, name the exact
TestFlight groups or testers in the request and include that effect in the fresh
authorization. If the effect cannot be established, stop; changing an automatic-
distribution setting also requires separate authorization.
Even when the original request includes building, releasing, uploading, or
submitting, require this fresh confirmation once the exact verified artifact and
destination are known. End the request with: `Upload this verified artifact to
<destination> now?` A clear affirmative response authorizes one upload of that
artifact to that destination, plus only any automatic TestFlight distribution
explicitly disclosed in the request. Run `eas submit` with the explicit
`--platform`, `--profile production`, `--path`, and `--wait` arguments; never
select `--latest`. If the result is ambiguous, inspect EAS and the store before
doing anything else, do not retry, and ask again before another upload.
Apply this gate to every upload method, including EAS, Fastlane, Xcode Organizer,
and the store consoles. A later public rollout, App Review submission, or
additional TestFlight distribution requires another fresh authorization.
Preserve platform signing and local EAS versioning. After a build, verify that
tracked changes are limited to the expected version metadata, then independently
read the artifact version and signature. Report the artifact, version/build
number, upload result when authorized, and store read-back state.
+23 -2
View File
@@ -1,14 +1,35 @@
node_modules
**/node_modules
.git
.gitignore
*.md
.env*
.DS_Store
dist
**/dist
.expo
android
ios
**/.expo
**/android
**/ios
*.log
.turbo
**/.turbo
coverage
.nyc_output
apps/admin
apps/mcp
!apps/mcp
!apps/mcp/**
apps/mobile
apps/supabase
apps/web
e2e
evidence
etc
infra
scripts
terraform
.agents
.claude
.codex
.ralph
-215
View File
@@ -1,215 +0,0 @@
name: Deploy Supabase to Production
on:
workflow_dispatch:
inputs:
deploy_production:
description: Promote the verified change to production after non-production
required: false
type: boolean
default: false
deploy_infrastructure:
description: Apply Terraform as part of this manual deployment
required: false
type: boolean
default: false
push:
branches:
- master
paths:
- 'apps/supabase/**'
- 'terraform/**'
- '.github/workflows/deploy-supabase.yml'
jobs:
changes:
name: Detect infrastructure changes
runs-on: ubuntu-latest
outputs:
infrastructure: ${{ steps.infrastructure.outputs.changed }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- id: infrastructure
name: Check Terraform scope
env:
BEFORE_SHA: ${{ github.event.before }}
CURRENT_SHA: ${{ github.sha }}
DEPLOY_INFRASTRUCTURE: ${{ inputs.deploy_infrastructure }}
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "changed=${DEPLOY_INFRASTRUCTURE:-false}" >> "$GITHUB_OUTPUT"
elif git diff --quiet "$BEFORE_SHA" "$CURRENT_SHA" -- terraform/; then
echo "changed=false" >> "$GITHUB_OUTPUT"
else
echo "changed=true" >> "$GITHUB_OUTPUT"
fi
quality:
name: Verify deployable source
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- run: npm run verify:fast
- run: npm run build
deploy-database:
name: Deploy Migrations & Functions
runs-on: ubuntu-latest
needs: quality
environment: ${{ matrix.environment }}
strategy:
max-parallel: 1
matrix:
environment: ${{ fromJSON(github.event_name == 'workflow_dispatch' && inputs.deploy_production && '["non-prod","prod"]' || '["non-prod"]') }}
env:
SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
SUPABASE_PROJECT_REF: ${{ matrix.environment == 'prod' && 'ckjcrkjpmhqhiucifukx' || 'itbzhrvlgvdmzbnhzhyx' }}
ENVIRONMENT_NAME: ${{ matrix.environment }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Supabase CLI
uses: supabase/setup-cli@v1
with:
version: latest
- name: Link to ${{ matrix.environment }} Project
run: supabase link --project-ref $SUPABASE_PROJECT_REF --workdir apps
- name: Apply Database Migrations (${{ matrix.environment }})
run: supabase db push --workdir apps --include-all
- name: Sync Edge Function Secrets (${{ matrix.environment }})
env:
# Add secrets from GitHub Secrets
REVENUECAT_WEBHOOK_SECRET: ${{ secrets.REVENUECAT_WEBHOOK_SECRET }}
REVENUECAT_API_KEY: ${{ secrets.REVENUECAT_API_KEY }}
REVENUECAT_ENTITLEMENT_ID: ${{ secrets.REVENUECAT_ENTITLEMENT_ID }}
OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
ADMIN_PRIVATE_KEY_JWK: ${{ secrets.ADMIN_PRIVATE_KEY_JWK }}
ADMIN_KEYS_JSON: ${{ secrets.ADMIN_KEYS_JSON }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
run: |
# Sync secrets to Supabase (only if they're set in GitHub)
secrets_to_set=""
[ -n "$REVENUECAT_WEBHOOK_SECRET" ] && secrets_to_set="$secrets_to_set REVENUECAT_WEBHOOK_SECRET=$REVENUECAT_WEBHOOK_SECRET"
[ -n "$REVENUECAT_API_KEY" ] && secrets_to_set="$secrets_to_set REVENUECAT_API_KEY=$REVENUECAT_API_KEY"
[ -n "$REVENUECAT_ENTITLEMENT_ID" ] && secrets_to_set="$secrets_to_set REVENUECAT_ENTITLEMENT_ID=$REVENUECAT_ENTITLEMENT_ID"
[ -n "$OPENROUTER_API_KEY" ] && secrets_to_set="$secrets_to_set OPENROUTER_API_KEY=$OPENROUTER_API_KEY"
[ -n "$ADMIN_PRIVATE_KEY_JWK" ] && secrets_to_set="$secrets_to_set ADMIN_PRIVATE_KEY_JWK=$ADMIN_PRIVATE_KEY_JWK"
[ -n "$ADMIN_KEYS_JSON" ] && secrets_to_set="$secrets_to_set ADMIN_KEYS_JSON=$ADMIN_KEYS_JSON"
[ -n "$DISCORD_WEBHOOK_URL" ] && secrets_to_set="$secrets_to_set DISCORD_WEBHOOK_URL=$DISCORD_WEBHOOK_URL"
if [ -n "$secrets_to_set" ]; then
echo "Syncing secrets to Supabase ($ENVIRONMENT_NAME)..."
supabase secrets set $secrets_to_set --project-ref $SUPABASE_PROJECT_REF
else
echo "No secrets to sync"
fi
- name: Deploy Edge Functions (${{ matrix.environment }})
run: |
# Deploy all edge functions (excluding _shared directory)
for dir in apps/supabase/functions/*/; do
function_name=$(basename "$dir")
# Skip _shared directory (it's a shared module, not a function)
if [ "$function_name" = "_shared" ]; then
echo "Skipping _shared (shared module)"
continue
fi
echo "Deploying function: $function_name to $ENVIRONMENT_NAME"
supabase functions deploy "$function_name" --no-verify-jwt --project-ref $SUPABASE_PROJECT_REF --workdir apps
done
- name: Remove Deleted Functions (${{ matrix.environment }})
run: |
# Get list of functions deployed on Supabase (skip header lines, extract slug column)
deployed=$(supabase functions list --project-ref $SUPABASE_PROJECT_REF | grep -E '^[a-z]' | awk '{print $1}')
# Get list of functions in the repo (excluding _shared)
local_functions=$(ls -d apps/supabase/functions/*/ 2>/dev/null | xargs -I {} basename {} | grep -v '^_shared$' || true)
# Delete any deployed functions that no longer exist in the repo
for func in $deployed; do
# Skip empty or invalid function names
[ -z "$func" ] && continue
[[ "$func" =~ ^[^a-z] ]] && continue
if ! echo "$local_functions" | grep -q "^${func}$"; then
echo "Deleting removed function from $ENVIRONMENT_NAME: $func"
supabase functions delete "$func" --project-ref $SUPABASE_PROJECT_REF
fi
done
deploy-infrastructure:
name: Deploy Infrastructure (Terraform)
runs-on: ubuntu-latest
needs: [quality, changes]
if: needs.changes.outputs.infrastructure == 'true'
env:
TF_VAR_supabase_access_token: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "1.6"
# Non-Production Environment
- name: Terraform Init (Non-Prod)
working-directory: terraform/environments/non-prod
run: terraform init
- name: Terraform Format Check
working-directory: terraform/modules/supabase
run: terraform fmt -check
- name: Terraform Validate (Non-Prod)
working-directory: terraform/environments/non-prod
run: terraform validate
- name: Terraform Plan (Non-Prod)
working-directory: terraform/environments/non-prod
run: terraform plan -out=tfplan
- name: Terraform Apply (Non-Prod)
working-directory: terraform/environments/non-prod
run: terraform apply -auto-approve tfplan
# Production Environment
- name: Terraform Init (Prod)
if: github.event_name == 'workflow_dispatch' && inputs.deploy_production
working-directory: terraform/environments/prod
run: terraform init
- name: Terraform Validate (Prod)
if: github.event_name == 'workflow_dispatch' && inputs.deploy_production
working-directory: terraform/environments/prod
run: terraform validate
- name: Terraform Plan (Prod)
if: github.event_name == 'workflow_dispatch' && inputs.deploy_production
working-directory: terraform/environments/prod
run: terraform plan -out=tfplan
- name: Terraform Apply (Prod)
if: github.event_name == 'workflow_dispatch' && inputs.deploy_production
working-directory: terraform/environments/prod
run: terraform apply -auto-approve tfplan
+56 -45
View File
@@ -1,15 +1,41 @@
name: Verify
on:
workflow_dispatch:
pull_request:
push:
branches: [master]
branches: [staging, main]
concurrency:
group: verify-${{ github.ref }}
cancel-in-progress: true
jobs:
branch-policy:
runs-on: ubuntu-latest
steps:
- name: Enforce promotion flow
if: github.event_name == 'pull_request'
env:
BASE_BRANCH: ${{ github.base_ref }}
HEAD_BRANCH: ${{ github.head_ref }}
run: |
if [ "$BASE_BRANCH" = "master" ]; then
echo "master is frozen; target staging or main" >&2
exit 1
fi
if [ "$BASE_BRANCH" = "main" ] && [ "$HEAD_BRANCH" != "staging" ]; then
echo "Only staging may be promoted to main" >&2
exit 1
fi
if [ "$BASE_BRANCH" != "staging" ] && [ "$BASE_BRANCH" != "main" ]; then
echo "Feature pull requests target staging; promotions target main" >&2
exit 1
fi
- name: Confirm direct verification
if: github.event_name != 'pull_request'
run: echo "Direct branch verification requested for $GITHUB_SHA"
static:
runs-on: ubuntu-latest
steps:
@@ -21,58 +47,43 @@ jobs:
- run: npm ci
- run: npm run learn:check
- run: npm run verify:fast
- name: Enforce API and mobile coverage floors
run: npm run test:coverage
- run: npm run build
full-stack:
backend-integration:
runs-on: ubuntu-latest
timeout-minutes: 25
timeout-minutes: 15
services:
postgres:
image: postgres:17-alpine
env:
POSTGRES_DB: sauci_test
POSTGRES_USER: sauci
POSTGRES_PASSWORD: sauci_ci_only
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U sauci -d sauci_test"
--health-interval 5s
--health-timeout 3s
--health-retries 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- run: npm ci
- run: npx playwright install --with-deps chromium
- name: Start local Supabase
- name: Run standalone backend integration tests
env:
GOOGLE_CLIENT_ID: local
GOOGLE_CLIENT_SECRET: local
APPLE_CLIENT_ID: local
APPLE_CLIENT_SECRET: local
run: npx supabase start --workdir apps
- name: Reset and seed
run: |
npx supabase db reset --workdir apps
scripts/with-local-supabase-env.sh tests node scripts/seed-e2e.mjs
- name: Start application services
run: |
npx supabase functions serve --workdir apps > /tmp/sauci-functions.log 2>&1 &
scripts/with-local-supabase-env.sh web npm run dev -w @sauci/web -- --port 3000 > /tmp/sauci-web.log 2>&1 &
scripts/with-local-supabase-env.sh admin npm run dev -w @sauci/admin -- --host 127.0.0.1 --port 3001 > /tmp/sauci-admin.log 2>&1 &
scripts/with-local-supabase-env.sh mcp npm run dev -w sauci-mcp-server > /tmp/sauci-mcp.log 2>&1 &
- name: Wait for services
run: |
for url in http://127.0.0.1:3000 http://127.0.0.1:3001/login http://127.0.0.1:3002/health; do
for attempt in $(seq 1 60); do
curl --fail --silent "$url" >/dev/null && break
sleep 2
done
curl --fail --silent "$url" >/dev/null
done
- run: npm run test:supabase
- run: npm run verify:e2e
- name: Upload E2E proof
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-proof
path: |
e2e/test-results
e2e/playwright-report
/tmp/sauci-*.log
if-no-files-found: ignore
retention-days: 14
DATABASE_URL: postgresql://sauci:sauci_ci_only@127.0.0.1:5432/sauci_test
run: npm run test:integration:coverage -w @sauci/api
container-contract:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- name: Verify production Compose contract
run: infra/backend/verify-production.sh
+2
View File
@@ -55,6 +55,7 @@ evidence/
e2e/.auth/
e2e/test-results/
e2e/playwright-report/
.playwright-mcp/
# Misc
*.pem
@@ -70,3 +71,4 @@ nul
# Agent runtime evidence (maintained lessons remain tracked)
.ralph/activity.log
.ralph/runs/
.migration-state/
+1 -1
View File
@@ -1 +1 @@
20.10.0
20.19.4
+24 -9
View File
@@ -1,22 +1,34 @@
# Sauci agent map
Sauci is a couples connection product: an Expo mobile app, React admin, Next.js
web app, Supabase backend, and an internal MCP service in one npm/Turborepo
workspace.
web app, standalone Node/PostgreSQL backend, hosted Supabase Auth, and an internal
MCP service in one npm/Turborepo workspace.
## Golden rules
1. Read the nearest `AGENTS.md` before changing a scoped area.
2. Preserve tenant and couple isolation. Never bypass RLS, role checks, or auth.
3. All schema changes are local files in `apps/supabase/migrations/` created with
`npm run db:migration:new -- <name>`. Never use remote `apply_migration`, never
execute DDL through MCP SQL tools, and use those SQL tools for `SELECT` only.
4. Never target production from local development or E2E. Local tests must fail
closed when a configured Supabase URL is not localhost.
3. Product-data schema changes are committed SQL files in `apps/api/drizzle/`.
Hosted Supabase owns Auth only; do not deploy product-data migrations or Edge
Functions there. Never execute remote DDL through MCP or provider tools.
4. Never target production from local development or E2E. Database integration
tests must fail closed unless `DATABASE_URL` resolves to loopback. Authenticated
native acceptance may use only the designated non-production Auth project.
5. Read `apps/mobile/DESIGN.md` before mobile UI work.
6. Keep shared package exports type-only and route them through `src/index.ts`.
7. Do not commit secrets, generated evidence, local logs, or runtime state.
8. Scope work to the task. Use high-effort reviewers only for the risk triggers in
8. Implement in a task-specific git worktree created from current `staging`,
not in the shared `staging` checkout. After the work is verified, commit the
scoped changes, merge the completed task branch back into local `staging`,
push `staging`, and prove local and remote commit parity.
9. Before merging, identify every deployed app or service the change can affect
and prove the relevant compatibility contracts still hold. Preserve deployed
interfaces and supported client behavior; repository checks alone do not
prove a live change is safe.
10. Scope work to the task. Route bounded implementation through the project
`implementation` agent when delegation is useful; the primary agent retains
acceptance, review, and final verification. Do not delegate trivial edits.
11. Use high-effort reviewers only for the risk triggers in
`docs/agents/routing.md`.
## Repository map
@@ -26,7 +38,8 @@ workspace.
| `apps/mobile` | Expo React Native product | `apps/mobile/AGENTS.md` |
| `apps/admin` | Vite administration UI | `apps/admin/AGENTS.md` |
| `apps/web` | Next.js marketing/redemption UI | `apps/web/AGENTS.md` |
| `apps/supabase` | migrations, functions, local backend | `apps/supabase/AGENTS.md` |
| `apps/api` | standalone API, worker, PostgreSQL migrations | repository rules |
| `apps/supabase` | legacy data-plane history; hosted Auth configuration only | `apps/supabase/AGENTS.md` |
| `apps/mcp` | internal administrative MCP service | `apps/mcp/AGENTS.md` |
| `packages/shared` | shared TypeScript contracts | `packages/shared/AGENTS.md` |
| `e2e` | cross-application Playwright flows | `e2e/README.md` |
@@ -34,6 +47,8 @@ workspace.
## Workflows
- Implementation: create a task worktree from current `staging`; commit verified
work, merge it back to local `staging`, push `staging`, and verify remote parity.
- Bootstrap: `npm ci`
- Full local stack: `scripts/dev-local.sh up`
- Fast checks: `npm run verify:fast`
+5 -2
View File
@@ -1,5 +1,8 @@
VITE_SUPABASE_URL=your_supabase_url
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
# Hosted Supabase Auth public settings only. Admin product data and mutations go
# through VITE_API_URL; never expose a service-role or admin service token here.
VITE_SUPABASE_URL=your_nonproduction_supabase_auth_url
VITE_SUPABASE_ANON_KEY=your_nonproduction_supabase_anon_key
VITE_API_URL=http://127.0.0.1:3003
VITE_OPENAI_API_KEY=your_openai_api_key
VITE_OPENROUTER_API_KEY=your_openrouter_api_key
+2
View File
@@ -12,6 +12,7 @@ RUN npm run build -w @sauci/shared
# Build admin app with env vars
ARG VITE_SUPABASE_URL
ARG VITE_SUPABASE_ANON_KEY
ARG VITE_API_URL
ARG VITE_OPENAI_API_KEY
ARG VITE_OPENROUTER_API_KEY
ARG VITE_AI_MODEL
@@ -24,6 +25,7 @@ ARG VITE_COUNCIL_REVIEWER_MODEL
ENV VITE_SUPABASE_URL=$VITE_SUPABASE_URL
ENV VITE_SUPABASE_ANON_KEY=$VITE_SUPABASE_ANON_KEY
ENV VITE_API_URL=$VITE_API_URL
ENV VITE_OPENAI_API_KEY=$VITE_OPENAI_API_KEY
ENV VITE_OPENROUTER_API_KEY=$VITE_OPENROUTER_API_KEY
ENV VITE_AI_MODEL=$VITE_AI_MODEL
+1
View File
@@ -6,6 +6,7 @@ services:
args:
- VITE_SUPABASE_URL=${VITE_SUPABASE_URL}
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
- VITE_API_URL=${VITE_API_URL}
- VITE_OPENAI_API_KEY=${VITE_OPENAI_API_KEY}
- VITE_OPENROUTER_API_KEY=${VITE_OPENROUTER_API_KEY}
- VITE_AI_MODEL=${VITE_AI_MODEL}
+1
View File
@@ -8,6 +8,7 @@ services:
environment:
- VITE_SUPABASE_URL=${VITE_SUPABASE_URL}
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
- VITE_API_URL=${VITE_API_URL:-http://127.0.0.1:3003}
- VITE_OPENAI_API_KEY=${VITE_OPENAI_API_KEY}
- VITE_OPENROUTER_API_KEY=${VITE_OPENROUTER_API_KEY}
- VITE_AI_MODEL=${VITE_AI_MODEL}
+2 -2
View File
@@ -44,8 +44,8 @@
"tailwind-merge": "^2.2.0"
},
"devDependencies": {
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
"@types/react": "~19.1.10",
"@types/react-dom": "~19.1.7",
"@vitejs/plugin-react": "^4.2.0",
"autoprefixer": "^10.4.16",
"postcss": "^8.4.32",
+1 -1
View File
@@ -195,7 +195,7 @@ function App() {
<Route
path="/flagged-messages"
element={
<ProtectedRoute requiredPermission={PERMISSION_KEYS.MANAGE_AI_CONFIG}>
<ProtectedRoute requiredPermission={PERMISSION_KEYS.VIEW_CHATS}>
<FlaggedMessagesPage />
</ProtectedRoute>
}
@@ -0,0 +1,179 @@
import { useEffect, useState } from 'react';
import type { ContentReviewStatus } from '@sauci/shared';
import { Archive, CheckCircle2, ClipboardCheck, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@/contexts/AuthContext';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import {
CONTENT_STATUS_LABELS,
type ReviewableContentTable,
updateContentReviewStatus,
} from '@/services/contentReviews';
interface ContentReviewControlProps {
table: ReviewableContentTable;
entityId: string;
entityLabel: string;
status?: ContentReviewStatus | null;
reason?: string | null;
onChanged: () => void | Promise<void>;
compact?: boolean;
}
const badgeClasses: Record<ContentReviewStatus, string> = {
unreviewed: 'border-amber-500 text-amber-500',
allowed: 'border-green-500 text-green-500',
archived: 'border-slate-500 text-slate-400',
};
const statusIcons: Record<ContentReviewStatus, typeof ClipboardCheck> = {
unreviewed: ClipboardCheck,
allowed: CheckCircle2,
archived: Archive,
};
export function ContentReviewControl({
table,
entityId,
entityLabel,
status,
reason,
onChanged,
compact = false,
}: ContentReviewControlProps) {
const { isSuperAdmin } = useAuth();
const resolvedStatus = status ?? 'unreviewed';
const StatusIcon = statusIcons[resolvedStatus];
const [open, setOpen] = useState(false);
const [nextStatus, setNextStatus] = useState<ContentReviewStatus>(resolvedStatus);
const [nextReason, setNextReason] = useState(reason ?? '');
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!open) {
setNextStatus(resolvedStatus);
setNextReason(reason ?? '');
}
}, [open, reason, resolvedStatus]);
const save = async () => {
if (!nextReason.trim()) {
toast.error('A review reason is required');
return;
}
setSaving(true);
try {
await updateContentReviewStatus(table, entityId, nextStatus, nextReason);
toast.success(`${entityLabel} marked ${CONTENT_STATUS_LABELS[nextStatus].toLowerCase()}`);
setOpen(false);
await onChanged();
} catch (error) {
toast.error('Failed to update catalogue status');
console.error(error);
} finally {
setSaving(false);
}
};
return (
<div className="flex items-center gap-2">
<Badge
variant="outline"
className={`${badgeClasses[resolvedStatus]} ${compact ? 'text-[10px] px-1.5 py-0' : ''}`}
title={reason || 'No review reason recorded'}
>
<StatusIcon className="mr-1 h-3 w-3" />
{CONTENT_STATUS_LABELS[resolvedStatus]}
</Badge>
{isSuperAdmin && (
<>
<Button
type="button"
variant="ghost"
size={compact ? 'sm' : 'default'}
className={compact ? 'h-7 px-2 text-xs' : undefined}
onClick={() => setOpen(true)}
aria-label={`Review catalogue status for ${entityLabel}`}
>
Review
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Review catalogue status</DialogTitle>
<DialogDescription>
This records a reversible editorial decision for {entityLabel}.
Current customer apps do not filter this status yet.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label htmlFor={`content-status-${entityId}`}>Status</Label>
<Select
value={nextStatus}
onValueChange={(value) => {
const selectedStatus = value as ContentReviewStatus;
setNextStatus(selectedStatus);
if (selectedStatus !== resolvedStatus) setNextReason('');
}}
>
<SelectTrigger id={`content-status-${entityId}`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="unreviewed">Needs review</SelectItem>
<SelectItem value="allowed">Allowed</SelectItem>
<SelectItem value="archived">Archived</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor={`content-reason-${entityId}`}>Reason</Label>
<Textarea
id={`content-reason-${entityId}`}
value={nextReason}
onChange={(event) => setNextReason(event.target.value)}
placeholder="Explain why this content is allowed, archived, or needs another review"
rows={4}
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button type="button" onClick={save} disabled={saving || !nextReason.trim()}>
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Save decision
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)}
</div>
);
}
@@ -11,7 +11,7 @@ import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader2, Tags, Check, Plus, X } from 'lucide-react';
import { extractTopicsFromPack, ExtractedTopic } from '@/lib/openai';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
import { toast } from 'sonner';
interface ExtractTopicsDialogProps {
@@ -37,7 +37,7 @@ export function ExtractTopicsDialog({ open, onOpenChange, pack, onUpdated }: Ext
setAnalyzing(true);
try {
// Fetch questions for this pack
const { data: questions, error: questionsError } = await supabase
const { data: questions, error: questionsError } = await adminData
.from('questions')
.select('text')
.eq('pack_id', pack.id);
@@ -50,7 +50,7 @@ export function ExtractTopicsDialog({ open, onOpenChange, pack, onUpdated }: Ext
}
// Fetch existing topics
const { data: existingTopics, error: topicsError } = await supabase
const { data: existingTopics, error: topicsError } = await adminData
.from('topics')
.select('id, name')
.order('name');
@@ -93,7 +93,7 @@ export function ExtractTopicsDialog({ open, onOpenChange, pack, onUpdated }: Ext
.map(t => t.existingTopicId!);
if (newTopics.length > 0) {
const { data: createdTopics, error: createError } = await supabase
const { data: createdTopics, error: createError } = await adminData
.from('topics')
.insert(newTopics.map(t => ({ name: t.name })))
.select('id');
@@ -106,14 +106,14 @@ export function ExtractTopicsDialog({ open, onOpenChange, pack, onUpdated }: Ext
}
// Remove existing pack_topics for this pack
await supabase
await adminData
.from('pack_topics')
.delete()
.eq('pack_id', pack.id);
// Insert new pack_topics relationships
if (existingTopicIds.length > 0) {
const { error: linkError } = await supabase
const { error: linkError } = await adminData
.from('pack_topics')
.insert(existingTopicIds.map(topicId => ({
pack_id: pack.id,
@@ -12,7 +12,7 @@ import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Loader2, ShieldCheck, ArrowRight, Check } from 'lucide-react';
import { analyzeQuestionTargets, TargetAnalysis } from '@/lib/openai';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { toast } from 'sonner';
// Define local compatible interface
@@ -111,7 +111,7 @@ export function FixTargetsDialog({ open, onOpenChange, questions, onUpdated }: F
// Apply updates in parallel with audit logging
await Promise.all(updates.map(update =>
auditedSupabase.update('questions', update.id, {
auditedAdminData.update('questions', update.id, {
allowed_couple_genders: update.suggested_targets && update.suggested_targets.length > 0 ? update.suggested_targets : null,
target_user_genders: update.suggested_initiator && update.suggested_initiator.length > 0 ? update.suggested_initiator : null,
})
@@ -11,7 +11,7 @@ import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Loader2, Wand2, ArrowRight, Check } from 'lucide-react';
import { analyzeQuestionText, TextAnalysis } from '@/lib/openai';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { toast } from 'sonner';
interface Question {
@@ -62,7 +62,7 @@ export function FixTextDialog({ open, onOpenChange, questions, isExplicit = fals
// Apply updates in parallel with audit logging
await Promise.all(updates.map(update =>
auditedSupabase.update('questions', update.id, {
auditedAdminData.update('questions', update.id, {
text: update.suggested_text,
partner_text: update.suggested_partner_text,
})
@@ -3,8 +3,7 @@ import type { AnswerType, QuestionType } from '@sauci/shared';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Image as ImageIcon, Music2 } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { supabaseConfig } from '@/config';
import { getAdminResponseMedia } from '@/lib/adminApi';
import { formatAdminResponse, QUESTION_TYPE_LABELS, type AdminResponseData } from '@/lib/questionResponses';
interface ResponseAnswerProps {
@@ -62,38 +61,17 @@ function ProtectedResponseMedia({
mediaType: 'photo' | 'audio';
label: string;
}) {
const { session } = useAuth();
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!session?.access_token) {
setError('Sign in to load media');
return;
}
let cancelled = false;
let objectUrl: string | null = null;
const load = async () => {
try {
setError(null);
const response = await fetch(`${supabaseConfig.url}/functions/v1/admin-response-media`, {
method: 'POST',
headers: {
apikey: supabaseConfig.anonKey,
Authorization: `Bearer ${session.access_token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ responseId }),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(body?.error || `Failed to load media (${response.status})`);
}
objectUrl = URL.createObjectURL(await response.blob());
objectUrl = URL.createObjectURL(await getAdminResponseMedia(responseId));
if (!cancelled) setUrl(objectUrl);
} catch (loadError) {
if (!cancelled) {
@@ -108,7 +86,7 @@ function ProtectedResponseMedia({
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
}, [responseId, session?.access_token]);
}, [responseId]);
if (error) {
return (
@@ -22,8 +22,8 @@ import {
DeletionAnalysis,
PropsAnalysis,
} from '@/lib/openai';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { toast } from 'sonner';
type QuestionType = 'swipe' | 'text_answer' | 'audio' | 'photo' | 'who_likely';
@@ -101,7 +101,7 @@ export function ReviewQuestionsDialog({ open, onOpenChange, questions, onUpdated
if (existingProps.length > 0) return existingProps;
try {
const { data, error } = await supabase
const { data, error } = await adminData
.from('questions')
.select('required_props')
.not('required_props', 'is', null)
@@ -252,12 +252,12 @@ export function ReviewQuestionsDialog({ open, onOpenChange, questions, onUpdated
// Apply updates/deletions in parallel with audit logging
const operations: Promise<unknown>[] = updates.map(update =>
auditedSupabase.update('questions', update.id, update.data)
auditedAdminData.update('questions', update.id, update.data)
);
if (deleteIds.length > 0) {
operations.push(
auditedSupabase.deleteMany('questions', deleteIds).then(result => {
auditedAdminData.deleteMany('questions', deleteIds).then(result => {
if (result.error) throw result.error;
})
);
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react';
import { Link, useLocation, useParams } from 'react-router-dom';
import { ChevronRight, Home } from 'lucide-react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
interface BreadcrumbItem {
label: string;
@@ -32,7 +32,7 @@ function useBreadcrumbs(): { breadcrumbs: BreadcrumbItem[]; loading: boolean } {
if (params.packId && !params.categoryId) {
setLoading(true);
try {
const { data } = await supabase
const { data } = await adminData
.from('question_packs')
.select('category_id, categories(name)')
.eq('id', params.packId)
@@ -63,7 +63,7 @@ function useBreadcrumbs(): { breadcrumbs: BreadcrumbItem[]; loading: boolean } {
if (params.userId) {
setLoading(true);
try {
const { data } = await supabase
const { data } = await adminData
.from('profiles')
.select('id, name')
.eq('id', params.userId)
+1 -1
View File
@@ -108,7 +108,7 @@ const systemNav: NavItem[] = [
label: 'Flagged Messages',
href: '/flagged-messages',
icon: <AlertTriangle className="h-5 w-5" />,
requiredPermission: PERMISSION_KEYS.MANAGE_AI_CONFIG,
requiredPermission: PERMISSION_KEYS.VIEW_CHATS,
},
{
label: 'AI Settings',
+9 -1
View File
@@ -5,7 +5,15 @@ export const supabaseConfig = {
anonKey: import.meta.env.VITE_SUPABASE_ANON_KEY,
};
export const supabase = createClient(
export const authClient = createClient(
supabaseConfig.url,
supabaseConfig.anonKey
);
const configuredApiUrl = import.meta.env.VITE_API_URL;
if (!configuredApiUrl) {
throw new Error('Missing required environment variable: VITE_API_URL');
}
export const apiUrl = configuredApiUrl.replace(/\/$/, '');
+21 -20
View File
@@ -1,5 +1,6 @@
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { supabase } from '../config';
import { authClient } from '../config';
import { adminRequest } from '@/lib/adminApi';
import type { User, Session } from '@supabase/supabase-js';
import { preloadAiConfig, clearAiConfigCache } from '@/hooks/useAiConfig';
@@ -80,23 +81,26 @@ export function AuthProvider({ children }: { children: ReactNode }) {
useEffect(() => {
// Get initial session
supabase.auth.getSession().then(({ data: { session } }) => {
authClient.auth.getSession().then(async ({ data: { session } }) => {
setSession(session);
setUser(session?.user ?? null);
// Restore permissions from localStorage
const storedPermissions = localStorage.getItem(PERMISSIONS_KEY);
if (storedPermissions) {
setPermissions(JSON.parse(storedPermissions));
// Preload AI config if user has an existing session (non-blocking)
if (session) {
try {
const currentPermissions = await adminRequest<AdminPermissions>('/v1/admin/me');
setPermissions(currentPermissions);
localStorage.setItem(PERMISSIONS_KEY, JSON.stringify(currentPermissions));
preloadAiConfig().catch(console.error);
} catch {
setPermissions(null);
localStorage.removeItem(PERMISSIONS_KEY);
}
}
setLoading(false);
});
// Listen for auth changes
const { data: { subscription } } = supabase.auth.onAuthStateChange(
const { data: { subscription } } = authClient.auth.onAuthStateChange(
(_event, session) => {
setSession(session);
setUser(session?.user ?? null);
@@ -112,7 +116,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, []);
const login = async (email: string, password: string) => {
const { data, error } = await supabase.auth.signInWithPassword({
const { error } = await authClient.auth.signInWithPassword({
email,
password,
});
@@ -122,20 +126,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
// Fetch admin role and permissions
const { data: adminData, error: adminError } = await supabase
.from('admin_users')
.select('role, permissions')
.eq('user_id', data.user.id)
.single();
if (adminError || !adminData) {
await supabase.auth.signOut();
let adminData: AdminPermissions;
try {
adminData = await adminRequest<AdminPermissions>('/v1/admin/me');
} catch {
await authClient.auth.signOut();
throw new Error('Access denied. You are not an administrator.');
}
// Store permissions from database
const perms: AdminPermissions = {
role: adminData.role as AdminRole,
role: adminData.role,
permissions: (adminData.permissions as string[]) || [],
};
@@ -150,7 +151,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
localStorage.removeItem(PERMISSIONS_KEY);
setPermissions(null);
clearAiConfigCache();
await supabase.auth.signOut();
await authClient.auth.signOut();
};
const isSuperAdmin = permissions?.role === 'super_admin';
+5 -5
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
export interface CouncilGenerator {
model: string;
@@ -74,7 +74,7 @@ export function useAiConfig(): UseAiConfigReturn {
setError(null);
try {
const { data, error: fetchError } = await supabase
const { data, error: fetchError } = await adminData
.from('ai_config')
.select('*')
.limit(1)
@@ -82,7 +82,7 @@ export function useAiConfig(): UseAiConfigReturn {
if (fetchError) {
// If user doesn't have access (not super admin), that's expected
if (fetchError.code === 'PGRST116' || fetchError.message.includes('permission')) {
if (fetchError.message.includes('permission')) {
setError('Access denied. Super admin privileges required.');
} else {
setError(fetchError.message);
@@ -110,7 +110,7 @@ export function useAiConfig(): UseAiConfigReturn {
}
try {
const { error: updateError } = await supabase
const { error: updateError } = await adminData
.from('ai_config')
.update(updates)
.eq('id', config.id);
@@ -160,7 +160,7 @@ export async function preloadAiConfig(): Promise<AiConfig | null> {
}
try {
const { data } = await supabase
const { data } = await adminData
.from('ai_config')
.select('*')
.limit(1)
+3 -3
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
export interface AppConfig {
id: string;
@@ -40,7 +40,7 @@ export function useAppConfig(): UseAppConfigReturn {
setError(null);
try {
const { data, error: fetchError } = await supabase
const { data, error: fetchError } = await adminData
.from('app_config')
.select('*')
.limit(1)
@@ -71,7 +71,7 @@ export function useAppConfig(): UseAppConfigReturn {
}
try {
const { error: updateError } = await supabase
const { error: updateError } = await adminData
.from('app_config')
.update(updates)
.eq('id', config.id);
@@ -1,10 +1,12 @@
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
// Tables to audit
const AUDITED_TABLES = [
'question_packs',
'questions',
'categories',
'dare_packs',
'dares',
'profiles',
'couples',
'responses',
@@ -26,23 +28,10 @@ async function logAction(
oldValues?: Record<string, unknown> | null,
newValues?: Record<string, unknown> | null
): Promise<void> {
if (!AUDITED_TABLES.includes(tableName)) return;
try {
const { error } = await supabase.rpc('log_admin_action', {
p_table_name: tableName,
p_action: action,
p_record_id: recordId,
p_old_values: oldValues || null,
p_new_values: newValues || null,
});
if (error) {
console.error('Failed to log audit action:', error);
}
} catch (error) {
console.error('Failed to log audit action:', error);
// Don't throw - logging failure shouldn't block the operation
}
// The standalone admin API writes the mutation and audit record in one
// transaction. Keeping this no-op preserves the existing call sites while
// avoiding duplicate or client-forgeable audit entries.
void tableName; void action; void recordId; void oldValues; void newValues;
}
interface InsertResult<T> {
@@ -56,9 +45,9 @@ interface SingleResult<T> {
}
/**
* Audited Supabase operations - automatically logs INSERT/UPDATE/DELETE to audit_logs
* Admin API mutations. The server writes each mutation and audit record atomically.
*/
export const auditedSupabase = {
export const auditedAdminData = {
/**
* Insert records with audit logging
*/
@@ -68,7 +57,7 @@ export const auditedSupabase = {
): Promise<InsertResult<T>> {
const recordArray = Array.isArray(records) ? records : [records];
const { data, error } = await supabase
const { data, error } = await adminData
.from(table)
.insert(recordArray)
.select();
@@ -94,7 +83,7 @@ export const auditedSupabase = {
// Fetch old values before update
let oldValues: Record<string, unknown> | null = null;
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.eq('id', id)
@@ -102,7 +91,7 @@ export const auditedSupabase = {
oldValues = oldData;
}
const { data, error } = await supabase
const { data, error } = await adminData
.from(table)
.update(updates)
.eq('id', id)
@@ -127,14 +116,14 @@ export const auditedSupabase = {
// Fetch old values before update
let oldRecords: Record<string, unknown>[] = [];
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.eq(filter.column, filter.value);
oldRecords = oldData || [];
}
const { data, error } = await supabase
const { data, error } = await adminData
.from(table)
.update(updates)
.eq(filter.column, filter.value)
@@ -161,7 +150,7 @@ export const auditedSupabase = {
// Fetch old values before delete
let oldValues: Record<string, unknown> | null = null;
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.eq('id', id)
@@ -169,7 +158,7 @@ export const auditedSupabase = {
oldValues = oldData;
}
const { error } = await supabase
const { error } = await adminData
.from(table)
.delete()
.eq('id', id);
@@ -191,14 +180,14 @@ export const auditedSupabase = {
// Fetch old values before delete
let oldRecords: Record<string, unknown>[] = [];
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.in('id', ids);
oldRecords = oldData || [];
}
const { error } = await supabase
const { error } = await adminData
.from(table)
.delete()
.in('id', ids);
@@ -224,7 +213,7 @@ export const auditedSupabase = {
// Fetch old values before delete
let oldValues: Record<string, unknown> | null = null;
if (AUDITED_TABLES.includes(table)) {
const { data: oldData } = await supabase
const { data: oldData } = await adminData
.from(table)
.select('*')
.eq(field, value)
@@ -232,7 +221,7 @@ export const auditedSupabase = {
oldValues = oldData;
}
const { error } = await supabase
const { error } = await adminData
.from(table)
.delete()
.eq(field, value);
+12 -12
View File
@@ -1,14 +1,14 @@
import { useState, useCallback } from 'react';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { toast } from 'sonner';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type SupabaseFilterFn = (query: any) => any;
type AdminFilterFn = (query: any) => any;
interface UseCrudOperationsOptions<T> {
/**
* The Supabase table name
* The standalone admin API resource name
*/
table: string;
@@ -41,7 +41,7 @@ interface UseCrudOperationsOptions<T> {
}
/**
* Generic CRUD operations hook for Supabase tables
* Generic CRUD operations hook for standalone admin API resources
* Reduces boilerplate for data fetching and mutations across pages.
*
* @example
@@ -90,13 +90,13 @@ export function useCrudOperations<T extends { id: string }>({
* @param filter Optional filter function to modify the query
*/
const fetchAll = useCallback(async (
filter?: SupabaseFilterFn
filter?: AdminFilterFn
): Promise<T[]> => {
setLoading(true);
setError(null);
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let query: any = supabase.from(table).select(select);
let query: any = adminData.from(table).select(select);
if (filter) {
query = filter(query);
@@ -131,7 +131,7 @@ export function useCrudOperations<T extends { id: string }>({
*/
const fetchById = useCallback(async (id: string): Promise<T | null> => {
try {
const { data, error: fetchError } = await supabase
const { data, error: fetchError } = await adminData
.from(table)
.select(select)
.eq('id', id)
@@ -158,7 +158,7 @@ export function useCrudOperations<T extends { id: string }>({
const { refetch = true, silent = false } = options;
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { data: created, error: createError } = await auditedSupabase.insert(table, data as any);
const { data: created, error: createError } = await auditedAdminData.insert(table, data as any);
if (createError) throw createError;
@@ -170,7 +170,7 @@ export function useCrudOperations<T extends { id: string }>({
await fetchAll();
}
// auditedSupabase.insert returns T[] | null, get first element
// auditedAdminData.insert returns T[] | null, get first element
return created && created.length > 0 ? (created[0] as T) : null;
} catch (err) {
if (!silent) {
@@ -194,7 +194,7 @@ export function useCrudOperations<T extends { id: string }>({
): Promise<boolean> => {
const { refetch = true, silent = false } = options;
try {
const { error: updateError } = await auditedSupabase.update(table, id, data);
const { error: updateError } = await auditedAdminData.update(table, id, data);
if (updateError) throw updateError;
@@ -233,7 +233,7 @@ export function useCrudOperations<T extends { id: string }>({
}
try {
const { error: deleteError } = await auditedSupabase.delete(table, id);
const { error: deleteError } = await auditedAdminData.delete(table, id);
if (deleteError) throw deleteError;
+71 -222
View File
@@ -1,243 +1,92 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import { supabase } from '@/config';
import { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import type { RealtimeChannel } from '@supabase/supabase-js';
import { queryAdminRows, type AdminFilter } from '@/lib/adminApi';
export type SubscriptionStatus = 'SUBSCRIBED' | 'SUBSCRIBING' | 'CHANNEL_ERROR' | 'TIMED_OUT' | 'CLOSED';
export interface UseRealtimeSubscriptionOptions<T> {
table: string;
schema?: string;
event?: 'INSERT' | 'UPDATE' | 'DELETE' | '*';
filter?: string;
onInsert?: (payload: T) => void;
onUpdate?: (payload: { old: T; new: T }) => void;
onDelete?: (payload: T) => void;
insertToast?: {
enabled: boolean;
message: string | ((payload: T) => string);
type?: 'success' | 'info' | 'warning';
};
updateToast?: {
enabled: boolean;
message: string | ((payload: { old: T; new: T }) => string);
type?: 'success' | 'info' | 'warning';
};
deleteToast?: {
enabled: boolean;
message: string | ((payload: T) => string);
type?: 'success' | 'info' | 'warning';
};
debounceMs?: number;
enabled?: boolean;
table: string; schema?: string; event?: 'INSERT' | 'UPDATE' | 'DELETE' | '*'; filter?: string;
onInsert?: (payload: T) => void; onUpdate?: (payload: { old: T; new: T }) => void; onDelete?: (payload: T) => void;
insertToast?: { enabled: boolean; message: string | ((payload: T) => string); type?: 'success' | 'info' | 'warning' };
updateToast?: { enabled: boolean; message: string | ((payload: { old: T; new: T }) => string); type?: 'success' | 'info' | 'warning' };
deleteToast?: { enabled: boolean; message: string | ((payload: T) => string); type?: 'success' | 'info' | 'warning' };
debounceMs?: number; enabled?: boolean; pollIntervalMs?: number;
}
export interface UseRealtimeSubscriptionReturn { status: SubscriptionStatus; error: Error | null }
const DEFAULT_POLL_INTERVAL_MS = 10_000;
const MIN_POLL_INTERVAL_MS = 5_000;
function parseFilter(filter?: string): AdminFilter[] | undefined {
if (!filter) return undefined;
const match = /^([a-z_][a-z0-9_]*)=(eq|neq|gte|lte)\.(.+)$/.exec(filter);
return match ? [{ column: match[1], op: match[2] as AdminFilter['op'], value: match[3] }] : undefined;
}
export interface UseRealtimeSubscriptionReturn {
status: SubscriptionStatus;
error: Error | null;
function rowKey(row: unknown, index: number): string {
if (row && typeof row === 'object') {
const record = row as Record<string, unknown>;
const key = record.id ?? `${record.pack_id ?? ''}:${record.topic_id ?? ''}`;
if (key) return String(key);
}
return String(index);
}
const MAX_RETRIES = 3;
export function useRealtimeSubscription<T>(
options: UseRealtimeSubscriptionOptions<T>
): UseRealtimeSubscriptionReturn {
const {
table,
schema = 'public',
event = '*',
filter,
onInsert,
onUpdate,
onDelete,
insertToast,
updateToast,
deleteToast,
debounceMs = 0,
enabled = true,
} = options;
export function useRealtimeSubscription<T>(options: UseRealtimeSubscriptionOptions<T>): UseRealtimeSubscriptionReturn {
const { table, event = '*', filter, onInsert, onUpdate, onDelete, insertToast, updateToast, deleteToast,
debounceMs = 0, enabled = true, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS } = options;
const [status, setStatus] = useState<SubscriptionStatus>('CLOSED');
const [error, setError] = useState<Error | null>(null);
const channelRef = useRef<RealtimeChannel | null>(null);
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const retryCountRef = useRef(0);
const isMountedRef = useRef(true);
// Use refs for callbacks and toast options to avoid re-subscription on every render
const onInsertRef = useRef(onInsert);
const onUpdateRef = useRef(onUpdate);
const onDeleteRef = useRef(onDelete);
const insertToastRef = useRef(insertToast);
const updateToastRef = useRef(updateToast);
const deleteToastRef = useRef(deleteToast);
// Keep refs up to date
useEffect(() => {
onInsertRef.current = onInsert;
onUpdateRef.current = onUpdate;
onDeleteRef.current = onDelete;
insertToastRef.current = insertToast;
updateToastRef.current = updateToast;
deleteToastRef.current = deleteToast;
});
// Debounced callback wrapper
const debouncedCallback = useCallback(
(callback: () => void) => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
if (debounceMs > 0) {
debounceTimerRef.current = setTimeout(() => {
if (isMountedRef.current) {
callback();
}
}, debounceMs);
} else {
callback();
}
},
[debounceMs]
);
// Handle incoming changes - use refs to avoid dependency changes
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleChange = useCallback(
(payload: { eventType: string; new: any; old: any }) => {
if (!isMountedRef.current) return;
const eventType = payload.eventType;
if (eventType === 'INSERT') {
const newRecord = payload.new as T;
if (insertToastRef.current?.enabled) {
const message =
typeof insertToastRef.current.message === 'function'
? insertToastRef.current.message(newRecord)
: insertToastRef.current.message;
toast[insertToastRef.current.type || 'info'](message);
}
if (onInsertRef.current) {
debouncedCallback(() => onInsertRef.current!(newRecord));
}
}
if (eventType === 'UPDATE') {
const updatePayload = { old: payload.old as T, new: payload.new as T };
if (updateToastRef.current?.enabled) {
const message =
typeof updateToastRef.current.message === 'function'
? updateToastRef.current.message(updatePayload)
: updateToastRef.current.message;
toast[updateToastRef.current.type || 'info'](message);
}
if (onUpdateRef.current) {
debouncedCallback(() => onUpdateRef.current!(updatePayload));
}
}
if (eventType === 'DELETE') {
const deletedRecord = payload.old as T;
if (deleteToastRef.current?.enabled) {
const message =
typeof deleteToastRef.current.message === 'function'
? deleteToastRef.current.message(deletedRecord)
: deleteToastRef.current.message;
toast[deleteToastRef.current.type || 'info'](message);
}
if (onDeleteRef.current) {
debouncedCallback(() => onDeleteRef.current!(deletedRecord));
}
}
},
[debouncedCallback]
);
const snapshotRef = useRef<Map<string, { value: T; json: string }> | null>(null);
const callbacksRef = useRef({ onInsert, onUpdate, onDelete, insertToast, updateToast, deleteToast });
callbacksRef.current = { onInsert, onUpdate, onDelete, insertToast, updateToast, deleteToast };
const emit = useCallback((callback: () => void) => {
if (debounceMs <= 0) callback(); else window.setTimeout(callback, debounceMs);
}, [debounceMs]);
useEffect(() => {
isMountedRef.current = true;
if (!enabled) {
setStatus('CLOSED');
return;
if (!enabled) { setStatus('CLOSED'); return; }
let cancelled = false;
let timer: number | undefined;
const interval = Math.max(MIN_POLL_INTERVAL_MS, pollIntervalMs);
const poll = async () => {
if (document.visibilityState === 'hidden') { timer = window.setTimeout(poll, interval); return; }
try {
setStatus((current) => current === 'SUBSCRIBED' ? current : 'SUBSCRIBING');
const { rows } = await queryAdminRows<T>(table, { filters: parseFilter(filter), limit: 500 });
if (cancelled) return;
const next = new Map(rows.map((row, index) => [rowKey(row, index), { value: row, json: JSON.stringify(row) }]));
const previous = snapshotRef.current;
if (previous) {
if (event === '*' || event === 'INSERT') for (const [key, entry] of next) if (!previous.has(key)) {
const config = callbacksRef.current;
if (config.insertToast?.enabled) toast[config.insertToast.type || 'info'](typeof config.insertToast.message === 'function' ? config.insertToast.message(entry.value) : config.insertToast.message);
if (config.onInsert) emit(() => config.onInsert!(entry.value));
}
const subscribe = () => {
// Create unique channel name
const channelName = `admin-${table}-${filter || 'all'}-${Date.now()}`;
// Build subscription config
const subscriptionConfig: {
event: 'INSERT' | 'UPDATE' | 'DELETE' | '*';
schema: string;
table: string;
filter?: string;
} = {
event,
schema,
table,
};
if (filter) {
subscriptionConfig.filter = filter;
if (event === '*' || event === 'UPDATE') for (const [key, entry] of next) {
const old = previous.get(key);
if (old && old.json !== entry.json) {
const payload = { old: old.value, new: entry.value };
const config = callbacksRef.current;
if (config.updateToast?.enabled) toast[config.updateToast.type || 'info'](typeof config.updateToast.message === 'function' ? config.updateToast.message(payload) : config.updateToast.message);
if (config.onUpdate) emit(() => config.onUpdate!(payload));
}
setStatus('SUBSCRIBING');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const channel = (supabase.channel(channelName) as any)
.on('postgres_changes', subscriptionConfig, handleChange)
.subscribe((subscriptionStatus: string) => {
if (!isMountedRef.current) return;
if (subscriptionStatus === 'SUBSCRIBED') {
setStatus('SUBSCRIBED');
setError(null);
retryCountRef.current = 0;
} else if (subscriptionStatus === 'CHANNEL_ERROR') {
setStatus('CHANNEL_ERROR');
setError(new Error(`Failed to subscribe to ${table}`));
// Auto-retry with exponential backoff
if (retryCountRef.current < MAX_RETRIES) {
const timeout = Math.pow(2, retryCountRef.current) * 1000;
retryCountRef.current++;
setTimeout(() => {
if (isMountedRef.current && channelRef.current) {
supabase.removeChannel(channelRef.current);
subscribe();
}
}, timeout);
if (event === '*' || event === 'DELETE') for (const [key, entry] of previous) if (!next.has(key)) {
const config = callbacksRef.current;
if (config.deleteToast?.enabled) toast[config.deleteToast.type || 'info'](typeof config.deleteToast.message === 'function' ? config.deleteToast.message(entry.value) : config.deleteToast.message);
if (config.onDelete) emit(() => config.onDelete!(entry.value));
}
} else if (subscriptionStatus === 'TIMED_OUT') {
setStatus('TIMED_OUT');
setError(new Error(`Subscription to ${table} timed out`));
} else if (subscriptionStatus === 'CLOSED') {
setStatus('CLOSED');
}
});
channelRef.current = channel;
};
subscribe();
return () => {
isMountedRef.current = false;
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
if (channelRef.current) {
supabase.removeChannel(channelRef.current);
snapshotRef.current = next;
setStatus('SUBSCRIBED'); setError(null);
} catch (cause) {
if (!cancelled) { setStatus('CHANNEL_ERROR'); setError(cause instanceof Error ? cause : new Error(String(cause))); }
} finally {
if (!cancelled) timer = window.setTimeout(poll, interval);
}
};
}, [enabled, table, schema, event, filter, handleChange]);
void poll();
return () => { cancelled = true; if (timer !== undefined) window.clearTimeout(timer); snapshotRef.current = null; };
}, [emit, enabled, event, filter, pollIntervalMs, table]);
return { status, error };
}
+56
View File
@@ -0,0 +1,56 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { getSession } = vi.hoisted(() => ({ getSession: vi.fn() }));
vi.mock('@/config', () => ({
apiUrl: 'http://127.0.0.1:3003',
authClient: { auth: { getSession } },
}));
import { AdminApiError, adminRequest, getAdminResponseMedia, queryAdminRows } from './adminApi';
describe('admin API transport', () => {
beforeEach(() => {
vi.restoreAllMocks();
getSession.mockResolvedValue({ data: { session: { access_token: 'hosted-auth-token' } }, error: null });
});
it('sends the hosted Auth bearer token to the standalone API', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ rows: [], count: 0 }), {
status: 200, headers: { 'content-type': 'application/json' },
}));
await queryAdminRows('profiles', { limit: 25 });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('http://127.0.0.1:3003/v1/admin/query/profiles');
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer hosted-auth-token');
expect(init?.body).toBe(JSON.stringify({ limit: 25 }));
});
it('fails closed when there is no authenticated session', async () => {
getSession.mockResolvedValue({ data: { session: null }, error: null });
await expect(adminRequest('/v1/admin/me')).rejects.toMatchObject({ status: 401 } satisfies Partial<AdminApiError>);
});
it('surfaces the API error message', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ error: { message: 'Administrator access denied' } }), {
status: 403, headers: { 'content-type': 'application/json' },
}));
await expect(adminRequest('/v1/admin/me')).rejects.toThrow('Administrator access denied');
});
it('loads protected response media from the standalone API with hosted Auth', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('response-media', {
status: 200, headers: { 'content-type': 'image/jpeg' },
}));
const responseId = '11111111-1111-4111-8111-111111111111';
const blob = await getAdminResponseMedia(responseId);
expect(await blob.text()).toBe('response-media');
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe(`http://127.0.0.1:3003/v1/admin/responses/${responseId}/media`);
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer hosted-auth-token');
expect(init?.body).toBeUndefined();
});
});
+258
View File
@@ -0,0 +1,258 @@
import { apiUrl, authClient } from '@/config';
export class AdminApiError extends Error {
constructor(message: string, readonly status: number, readonly details?: unknown) {
super(message);
this.name = 'AdminApiError';
}
}
type RequestOptions = Omit<RequestInit, 'body'> & { body?: unknown };
async function accessToken(): Promise<string> {
const { data, error } = await authClient.auth.getSession();
const token = data.session?.access_token;
if (error || !token) throw new AdminApiError('An authenticated admin session is required', 401, error);
return token;
}
export async function adminRequest<T>(path: string, options: RequestOptions = {}): Promise<T> {
const token = await accessToken();
const headers = new Headers(options.headers);
headers.set('Accept', 'application/json');
headers.set('Authorization', `Bearer ${token}`);
const body = options.body === undefined ? undefined : JSON.stringify(options.body);
if (body !== undefined) headers.set('Content-Type', 'application/json');
const response = await fetch(`${apiUrl}${path.startsWith('/') ? path : `/${path}`}`, { ...options, headers, body });
const text = await response.text();
let parsed: unknown;
try { parsed = text ? JSON.parse(text) : undefined; } catch { parsed = text; }
if (!response.ok) {
const nested = parsed && typeof parsed === 'object' && 'error' in parsed ? (parsed as { error: unknown }).error : undefined;
const message = nested && typeof nested === 'object' && 'message' in nested
? String((nested as { message: unknown }).message)
: `Admin API request failed with status ${response.status}`;
throw new AdminApiError(message, response.status, parsed);
}
return parsed as T;
}
export async function adminBinaryRequest(path: string, options: RequestOptions = {}): Promise<Blob> {
const token = await accessToken();
const headers = new Headers(options.headers);
headers.set('Authorization', `Bearer ${token}`);
const body = options.body === undefined ? undefined : JSON.stringify(options.body);
if (body !== undefined) headers.set('Content-Type', 'application/json');
const response = await fetch(`${apiUrl}${path.startsWith('/') ? path : `/${path}`}`, { ...options, headers, body });
if (!response.ok) throw new AdminApiError(`Admin media request failed with status ${response.status}`, response.status);
return response.blob();
}
export function getAdminResponseMedia(responseId: string): Promise<Blob> {
return adminBinaryRequest(`/v1/admin/responses/${encodeURIComponent(responseId)}/media`);
}
export type AdminFilter = { column: string; op: 'eq' | 'neq' | 'in' | 'is' | 'gte' | 'lte' | 'ilike'; value: unknown };
export type AdminQuery = {
filters?: AdminFilter[];
order?: { column: string; ascending?: boolean };
limit?: number;
offset?: number;
};
export async function queryAdminRows<T>(resource: string, query: AdminQuery = {}): Promise<{ rows: T[]; count: number }> {
return adminRequest(`/v1/admin/query/${encodeURIComponent(resource)}`, { method: 'POST', body: query });
}
function uniqueValues(rows: Record<string, unknown>[], key: string): unknown[] {
return [...new Set(rows.map((row) => row[key]).filter((value) => value !== null && value !== undefined))];
}
async function relatedRows(resource: string, column: string, values: unknown[]): Promise<Record<string, unknown>[]> {
if (values.length === 0) return [];
return (await queryAdminRows<Record<string, unknown>>(resource, {
filters: [{ column, op: 'in', value: values }], limit: 500,
})).rows;
}
async function hydrateAdminRows(resource: string, selection: string, input: any[]): Promise<any[]> {
const rows = input as Record<string, unknown>[];
if (rows.length === 0) return input;
if (resource === 'question_packs' && selection.includes('categor')) {
const categories = await relatedRows('categories', 'id', uniqueValues(rows, 'category_id'));
const byId = new Map(categories.map((row) => [row.id, row]));
rows.forEach((row) => { row.category = byId.get(row.category_id) ?? null; });
}
if (resource === 'pack_topics' && selection.includes('topics')) {
const topics = await relatedRows('topics', 'id', uniqueValues(rows, 'topic_id'));
const byId = new Map(topics.map((row) => [row.id, row]));
rows.forEach((row) => { row.topics = byId.get(row.topic_id) ?? null; });
}
if (resource === 'feedback' && selection.includes('profile')) {
const profiles = await relatedRows('profiles', 'id', uniqueValues(rows, 'user_id'));
const byId = new Map(profiles.map((row) => [row.id, row]));
rows.forEach((row) => { row.profile = byId.get(row.user_id) ?? null; });
}
if (resource === 'message_reports') {
if (selection.includes('message:')) {
const messages = await relatedRows('messages', 'id', uniqueValues(rows, 'message_id'));
const byId = new Map(messages.map((row) => [row.id, row]));
rows.forEach((row) => { row.message = byId.get(row.message_id) ?? null; });
}
if (selection.includes('reporter_profile')) {
const profiles = await relatedRows('profiles', 'id', uniqueValues(rows, 'reporter_id'));
const byId = new Map(profiles.map((row) => [row.id, row]));
rows.forEach((row) => { row.reporter_profile = byId.get(row.reporter_id) ?? null; });
}
}
if (resource === 'responses') {
if (selection.includes('profile:')) {
const profiles = await relatedRows('profiles', 'id', uniqueValues(rows, 'user_id'));
const byId = new Map(profiles.map((row) => [row.id, row]));
rows.forEach((row) => { row.profile = byId.get(row.user_id) ?? null; });
}
if (selection.includes('question:')) {
const questions = await relatedRows('questions', 'id', uniqueValues(rows, 'question_id'));
if (selection.includes('pack:question_packs')) {
const packs = await relatedRows('question_packs', 'id', uniqueValues(questions, 'pack_id'));
const packsById = new Map(packs.map((row) => [row.id, row]));
questions.forEach((row) => { row.pack = packsById.get(row.pack_id) ?? null; });
}
const byId = new Map(questions.map((row) => [row.id, row]));
rows.forEach((row) => { row.question = byId.get(row.question_id) ?? null; });
}
}
if (resource === 'matches' && selection.includes('question:')) {
const questions = await relatedRows('questions', 'id', uniqueValues(rows, 'question_id'));
const byId = new Map(questions.map((row) => [row.id, row]));
rows.forEach((row) => { row.question = byId.get(row.question_id) ?? null; });
}
if (resource === 'messages' && selection.includes('match:')) {
const matches = await relatedRows('matches', 'id', uniqueValues(rows, 'match_id'));
const questions = await relatedRows('questions', 'id', uniqueValues(matches, 'question_id'));
const questionsById = new Map(questions.map((row) => [row.id, row]));
matches.forEach((row) => { row.question = questionsById.get(row.question_id) ?? null; });
const byId = new Map(matches.map((row) => [row.id, row]));
rows.forEach((row) => { row.match = byId.get(row.match_id) ?? null; });
}
return input;
}
type QueryResult<T> = { data: T | null; error: Error | null; count: number | null };
type QueryMode = 'many' | 'single' | 'maybeSingle';
class AdminQueryBuilder<T = any> implements PromiseLike<QueryResult<T[]>> {
private readonly filters: AdminFilter[] = [];
private ordering?: { column: string; ascending?: boolean };
private maxRows?: number;
private offset?: number;
private head = false;
private selection = '*';
private orFilters?: AdminFilter[];
private mode: QueryMode = 'many';
private mutation?: { type: 'insert'; records: Record<string, unknown>[] } | { type: 'update'; values: Record<string, unknown> } | { type: 'delete' };
constructor(private readonly resource: string) {}
select(columns = '*', options?: { count?: 'exact'; head?: boolean }): this {
this.selection = columns;
this.head = options?.head === true;
return this;
}
eq(column: string, value: unknown): this { this.filters.push({ column, op: 'eq', value }); return this; }
neq(column: string, value: unknown): this { this.filters.push({ column, op: 'neq', value }); return this; }
in(column: string, value: unknown[]): this { this.filters.push({ column, op: 'in', value }); return this; }
is(column: string, value: unknown): this { this.filters.push({ column, op: 'is', value }); return this; }
gte(column: string, value: unknown): this { this.filters.push({ column, op: 'gte', value }); return this; }
lte(column: string, value: unknown): this { this.filters.push({ column, op: 'lte', value }); return this; }
ilike(column: string, value: string): this { this.filters.push({ column, op: 'ilike', value }); return this; }
or(expression: string): this {
this.orFilters = expression.split(',').map((part) => {
const match = /^([a-z_][a-z0-9_]*)\.ilike\.(.+)$/.exec(part);
if (!match) throw new Error('Unsupported admin OR filter');
return { column: match[1], op: 'ilike' as const, value: match[2] };
});
return this;
}
not(column: string, operator: string, value: unknown): this {
if (operator !== 'is' || value !== null) throw new Error(`Unsupported admin filter: not ${operator}`);
this.filters.push({ column, op: 'neq', value: null });
return this;
}
order(column: string, options?: { ascending?: boolean }): this { this.ordering = { column, ascending: options?.ascending }; return this; }
limit(value: number): this { this.maxRows = value; return this; }
range(from: number, to: number): this { this.offset = from; this.maxRows = to - from + 1; return this; }
single<TResult = T>(): PromiseLike<QueryResult<TResult>> { this.mode = 'single'; return this as unknown as PromiseLike<QueryResult<TResult>>; }
maybeSingle<TResult = T>(): PromiseLike<QueryResult<TResult>> { this.mode = 'maybeSingle'; return this as unknown as PromiseLike<QueryResult<TResult>>; }
insert(records: Record<string, unknown> | Record<string, unknown>[]): this {
this.mutation = { type: 'insert', records: Array.isArray(records) ? records : [records] };
return this;
}
update(values: Record<string, unknown>): this { this.mutation = { type: 'update', values }; return this; }
delete(): this { this.mutation = { type: 'delete' }; return this; }
then<TResult1 = QueryResult<T[]>, TResult2 = never>(
onfulfilled?: ((value: QueryResult<T[]>) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
): PromiseLike<TResult1 | TResult2> {
return this.execute().then(onfulfilled, onrejected);
}
private async execute(): Promise<QueryResult<T[]>> {
try {
if (this.mutation?.type === 'insert') {
const result = await adminRequest<{ rows: T[] }>(`/v1/admin/data/${this.resource}`, { method: 'POST', body: { records: this.mutation.records } });
return this.shape(result.rows, result.rows.length);
}
if (this.mutation) {
const matching = await queryAdminRows<Record<string, unknown>>(this.resource, { filters: this.filters, limit: 500 });
const ids = [...new Set(matching.rows.map((row) => String(row.id ?? row.pack_id ?? '')).filter(Boolean))];
if (this.mutation.type === 'update') {
const rows = await Promise.all(ids.map((id) => adminRequest<{ row: T }>(`/v1/admin/data/${this.resource}/${encodeURIComponent(id)}`, { method: 'PATCH', body: { values: this.mutation!.type === 'update' ? this.mutation!.values : {} } }).then((value) => value.row)));
return this.shape(rows, rows.length);
}
await Promise.all(ids.map((id) => adminRequest(`/v1/admin/data/${this.resource}/${encodeURIComponent(id)}`, { method: 'DELETE' })));
return this.shape([], ids.length);
}
const result = this.orFilters?.length
? await this.executeOrQuery()
: await queryAdminRows<T>(this.resource, { filters: this.filters, order: this.ordering, limit: this.maxRows, offset: this.offset });
if (!this.head) result.rows = await hydrateAdminRows(this.resource, this.selection, result.rows);
return this.shape(result.rows, result.count);
} catch (cause) {
return { data: null, error: cause instanceof Error ? cause : new Error(String(cause)), count: null };
}
}
private async executeOrQuery(): Promise<{ rows: T[]; count: number }> {
const results = await Promise.all(this.orFilters!.map((filter) => queryAdminRows<T>(this.resource, {
filters: [...this.filters, filter], order: this.ordering, limit: 500,
})));
const unique = new Map<string, T>();
for (const result of results) result.rows.forEach((row, index) => {
const record = row as Record<string, unknown>;
unique.set(String(record.id ?? `${record.pack_id ?? ''}:${record.topic_id ?? ''}:${index}`), row);
});
let rows = [...unique.values()];
if (this.offset) rows = rows.slice(this.offset);
if (this.maxRows) rows = rows.slice(0, this.maxRows);
return { rows, count: unique.size };
}
private shape(rows: T[], count: number): QueryResult<T[]> {
if (this.head) return { data: null, error: null, count };
if (this.mode === 'single') {
if (rows.length !== 1) return { data: null, error: new Error(`Expected one ${this.resource} record, received ${rows.length}`), count };
return { data: rows[0] as unknown as T[], error: null, count };
}
if (this.mode === 'maybeSingle') {
if (rows.length > 1) return { data: null, error: new Error(`Expected at most one ${this.resource} record, received ${rows.length}`), count };
return { data: (rows[0] ?? null) as unknown as T[], error: null, count };
}
return { data: rows, error: null, count };
}
}
export const adminData = {
from<T = any>(resource: string): AdminQueryBuilder<T> { return new AdminQueryBuilder<T>(resource); },
};
+5 -5
View File
@@ -23,8 +23,8 @@ export async function analyzeQuestionDeletions(
}));
const toneInstruction = isExplicit
? 'CONTENT: EXPLICIT pack. Adult content is allowed but must be consensual, safe, and clear. Avoid coercion, minors, illegal acts, or unsafe suggestions.'
: 'CONTENT: NON-EXPLICIT pack. Do NOT include explicit sexual acts, crude language, or NSFW content. If the core action is sexual, it should be removed, not rewritten.';
? 'LEGACY EXPLICIT FLAG: It does not override the universal catalogue safety ceiling. Delete developer-authored sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, and public sexual activity.'
: 'Delete developer-authored sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, and public sexual activity rather than rewriting them into disguised euphemisms.';
const prompt = `<task>
Identify questions that should be DELETED instead of edited.
@@ -38,7 +38,7 @@ ${toneInstruction}
<deletion_categories>
- duplicate: same core action AND same initiator as another question (near-duplicate). Note: swapped perspectives (e.g., "give" vs "receive") are NOT duplicates.
- redundant: minor variation with no added value
- off-tone: violates explicit vs non-explicit rules
- off-tone: violates the universal catalogue safety ceiling or the pack's intended tone
- unsafe: coercion, minors, illegal acts, or consent violations
- too-vague: not actionable or not a clear proposal
- broken: grammar/structure too broken to repair without inventing content
@@ -73,8 +73,8 @@ Only return questions that should be deleted.
</output_format>`;
const systemMessage = isExplicit
? 'You are a strict content quality reviewer for an adult couples app. Remove only what should be deleted. Always respond with valid JSON only.'
: 'You are a strict content quality reviewer for a couples app. Remove only what should be deleted. Always respond with valid JSON only.';
? 'You are a strict content safety reviewer for a couples connection app. A legacy explicit flag never permits sexual content. Mark content outside the universal safety ceiling for deletion. Always respond with valid JSON only.'
: 'You are a strict content safety reviewer for a couples connection app. Mark sexual or explicit content for deletion. Always respond with valid JSON only.';
const response = await openai.chat.completions.create({
model: getModel('fix'),
+8 -8
View File
@@ -9,16 +9,16 @@ export interface ImageSafetyAnalysis {
}
const SAFETY_ANALYSIS_PROMPT = `<task>
Analyze this image for content safety in the context of an adult couples intimacy app.
Analyze this image for content safety in the context of a couples connection app.
</task>
<context>
This app is for ADULT couples (25-45) to explore intimacy. Adult content between consenting adults is expected and acceptable. The concern is inappropriate content like violence, minors, or illegal activity.
This app has one universal mobile catalogue. Explicit or sexually gratifying imagery is not eligible for publication, even when it depicts consenting adults.
</context>
<categories>
- SAFE: No concerns, appropriate for the app (including tasteful adult content between adults)
- ADULT_CONTENT: Explicit content - acceptable for this app but flag for review
- SAFE: Non-explicit relationship, romance, lifestyle, or abstract imagery appropriate for the universal catalogue
- ADULT_CONTENT: Sexual, sexually gratifying, fetish, explicit-anatomy, or stimulation-focused imagery; not appropriate for publication
- VIOLENCE: Gore, weapons, abuse, non-consensual acts
- MINORS: Anyone appearing under 18 years old - CRITICAL, never acceptable
- ILLEGAL: Drug use, criminal activity, non-consensual content
@@ -27,9 +27,9 @@ This app is for ADULT couples (25-45) to explore intimacy. Adult content between
<severity_levels>
- none: No safety concerns at all
- low: Minor flag, likely fine but worth noting
- medium: Should be reviewed by admin
- high: Likely inappropriate, requires immediate review
- low: Minor flag, needs human review before publication
- medium: Not eligible without a documented human safety decision
- high: Inappropriate for publication and should be archived
- critical: Definitely inappropriate, should be blocked (MINORS, VIOLENCE, ILLEGAL)
</severity_levels>
@@ -40,7 +40,7 @@ Return a JSON object:
"severity": "none"|"low"|"medium"|"high"|"critical",
"description": "Brief factual description of what's shown (max 50 words)",
"concerns": ["List of specific concerns if any, empty array if none"],
"isAppropriate": true|false // false for VIOLENCE, MINORS, ILLEGAL or high/critical severity
"isAppropriate": true|false // false for ADULT_CONTENT, VIOLENCE, MINORS, ILLEGAL, UNCERTAIN, or any flagged severity
}
</output_format>`;
+11 -14
View File
@@ -22,18 +22,17 @@ export async function analyzeQuestionText(
}));
const toneInstruction = isExplicit
? 'TONE: This is an EXPLICIT pack with NUANCED language. Use tasteful phrasing for common acts: "Have sex in X" (not "fuck in X"), "Perform oral" or "go down on" (not crude oral terms). BUT keep crude/specific terms when they ARE the activity: "Cum on your partner\'s tits" (cum is the act), "Use a cock ring" (that\'s the name), "Edge until they beg". The rule: crude terms for specific acts/objects, tasteful terms for general sex/oral. NEVER sanitize "cum" to "come" - they have different meanings.'
: 'TONE: This is a NON-EXPLICIT pack. CRITICAL: Do NOT include any sexual acts, crude language, or NSFW content. Keep language romantic, sensual, or playful without crude/graphic terms. If explicit sexual content appears, replace with tasteful romantic alternatives or flag for removal.';
? 'LEGACY EXPLICIT FLAG: It does not override the universal catalogue safety ceiling. Replace explicit wording with a high-level proposal about curiosity, trust, anticipation, comfort, or relationship dynamics. If that would invent a materially different proposal, omit it so deletion review can archive it.'
: 'Keep language romantic, playful, flirty, or daring without naming or describing sexual content. Replace explicit wording with a safe high-level proposal, or omit it when that would change the proposal materially.';
// Use different examples based on explicit/non-explicit
const symmetricExamples = isExplicit
? 'GOOD: "Have sex in a public place", "Roleplay a new scenario together", "Shower together", "Have a threesome"'
? 'GOOD SAFE REPLACEMENTS: "Explore a new dynamic together", "Share a private desire in your own words", "Try something daring together"'
: 'GOOD: "Cook a romantic dinner together", "Stargaze and share your dreams", "Give each other massages", "Dance together at home"';
const asymmetricExamples = isExplicit
? `text (The Doer): Active command/proposal (e.g., "Tie your partner up", "Give your partner a massage").
- partner_text (The Receiver): Passive/Receiving proposal (e.g., "Be tied up by your partner", "Receive a massage from your partner").
- GOOD: "Spank your partner" / "Be spanked by your partner"`
? `text (The Doer): Active safe proposal (e.g., "Let your partner take the lead").
- partner_text (The Receiver): Reciprocal safe proposal (e.g., "Take the lead with your partner").
- GOOD: "Plan a bold surprise for your partner" / "Let your partner plan a bold surprise"`
: `text (The Doer): Active command/proposal (e.g., "Write a love letter to your partner", "Plan a surprise date for your partner").
- partner_text (The Receiver): Passive/Receiving proposal (e.g., "Receive a love letter from your partner", "Be surprised with a date by your partner").
- GOOD: "Give your partner a massage" / "Receive a massage from your partner"`;
@@ -66,17 +65,15 @@ Cards should be "Proposals" for specific actions, NOT interview questions.
Partner text rules:
- Describe RECEIVER's experience clearly
- When initiator CAUSES a response (moan, cum, beg), frame as ALLOWING:
* text: "Make your partner moan" -> partner_text: "Let your partner make you moan"
* NOT: "Moan for your partner" (sounds forced, not natural)
- Keep both perspectives inside the same universal safety ceiling
</question_types>
<rules>
1. PRESERVE THE CORE ACTION - only improve phrasing, don't change what it's about
1. Preserve the core relationship intent only when it is catalogue-safe
2. Keep SHORT and DIRECT - aim for 5-12 words, no parentheticals
3. Remove wishy-washy: "Would you want to...", "Have you ever...", "Do you think..."
4. Use "your partner" instead of "me", "you", "him", "her"
5. NEVER mix anatomically incompatible activities in same question
5. Keep allowed catalogue proposals anatomy-neutral by default
6. Make partner_text APPEALING - don't just grammatically flip, make receiver feel excited
7. FLAG CLICHES: "candlelit dinner", "rose petals", "bubble bath", "Netflix and chill"
8. Skip questions that are ALREADY well-phrased
@@ -102,8 +99,8 @@ Only include questions that need text improvement.
</output_format>`;
const systemMessage = isExplicit
? 'You are an adult content editor for a couples intimacy app. Use nuanced language: tasteful phrasing for general acts (have sex, perform oral) but crude specific terms when relevant (cum, cock ring, etc). Preserve original intent. Always respond with valid JSON only.'
: 'You are a professional content editor for a couples app. You improve question phrasing to be direct, actionable, and engaging while preserving the original intent. Always respond with valid JSON only.';
? 'You are a content editor for a couples connection app. A legacy explicit flag never overrides the universal safety ceiling. Never output sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, or public sexual activity. Always respond with valid JSON only.'
: 'You are a professional content editor for a couples connection app. Improve phrasing while never outputting sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, or public sexual activity. Always respond with valid JSON only.';
const response = await openai.chat.completions.create({
model: getModel('fix'),
+36 -38
View File
@@ -47,7 +47,7 @@ export function getCouncilConfig(): CouncilConfig {
}
/**
* Initialize AI config by preloading from Supabase
* Initialize AI config by preloading from the standalone admin API
* Call this on app startup to ensure config is available
*/
export async function initializeAiConfig(): Promise<AiConfig | null> {
@@ -62,9 +62,9 @@ export async function initializeAiConfig(): Promise<AiConfig | null> {
export const TONE_LEVELS = [
{ level: 1, label: 'Gentle', description: 'Pure emotional connection & non-sexual bonding' },
{ level: 2, label: 'Warm', description: 'Romantic atmosphere & affectionate touch' },
{ level: 3, label: 'Playful', description: 'Light sexual exploration & sensual discovery' },
{ level: 4, label: 'Steamy', description: 'Explicit sexual activities & moderate adventure' },
{ level: 5, label: 'Intense', description: 'Advanced/BDSM/Extreme exploration' },
{ level: 3, label: 'Playful', description: 'Flirty anticipation, novelty & playful connection' },
{ level: 4, label: 'Bold', description: 'Trust, leadership & suggestive relationship dynamics' },
{ level: 5, label: 'Daring', description: 'Comfort zones, control & user-led curiosity' },
] as const;
// =============================================================================
@@ -92,30 +92,26 @@ REVIEW CRITERIA - Score each 1-10:
- Partner text (if present) clearly describes receiver's experience
- No confusing or ambiguous phrasing
4. ANATOMICAL CONSISTENCY:
- No mixed male/female anatomy in alternatives
- BAD: "Finger or give your partner a handjob"
- GOOD: Pick one activity
4. CATALOGUE SAFETY:
- REJECT named or described sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, or public sexual activity
- REJECT sexual instructions disguised with euphemisms
- ALLOW non-graphic romance, anticipation, trust, leadership, following, novelty, and user-led curiosity
- The highest tone changes emotional boldness, never the explicitness ceiling
5. PARTNER TEXT QUALITY (if applicable):
- Engaging and enticing, not clinical
- BAD: "Receive oral from your partner"
- GOOD: "Let your partner pleasure you with their mouth"
- When initiator causes a response, frame as allowing: "Let your partner make you moan"
- Describes the reciprocal perspective without adding sexual detail
- Preserves the same safe proposal and emotional intensity
6. COUPLE TARGETING (flag if incorrect):
- Default: ALL couples (null) unless explicit anatomical requirement
- Restrict to ['male+male', 'female+male'] ONLY if activity requires penis
- Restrict to ['female+male', 'female+female'] ONLY if activity requires vagina
- Sex toys are GENDER-NEUTRAL (vibrators, dildos, plugs work for anyone)
- Flag if targeting seems too restrictive or missing needed restrictions
- Default: ALL couples (null)
- Safe catalogue proposals should not require anatomical targeting
- Flag unnecessary or exclusionary targeting
7. INITIATOR TARGETING (for asymmetric questions only):
- Default: null (anyone can initiate) unless explicit anatomical requirement
- Set initiator based on WHO DOES the action in "text" field
- "Swallow your partner's cum" -> initiator: female (in M+F, receiver of cum)
- "Give your partner a massage" -> initiator: null (anyone can give)
- Flag if initiator seems incorrectly assigned
- Default: null (anyone can initiate)
- Set initiator only when a legitimate non-anatomical product rule requires it
- Flag unnecessary targeting
`;
// =============================================================================
@@ -125,10 +121,10 @@ REVIEW CRITERIA - Score each 1-10:
export const TONE_INSTRUCTIONS: Record<ToneLevel, string> = {
1: 'INTIMACY LEVEL: GENTLE. Focus on emotional safety, friendship-based activities, and quality time. Examples: "Cook a new recipe together", "Take a walk holding hands", "Give non-sexual foot massages", "Watch a movie cuddling". Pure emotional connection & non-sexual bonding.',
2: 'INTIMACY LEVEL: WARM. Focus on creating romantic moments, sensual but non-sexual touch, and building anticipation. Examples: "Slow dance in the living room", "Candlelit bath together (non-sexual)", "Extended kissing sessions", "Sensual massage with oils". Romantic atmosphere & affectionate touch.',
3: 'INTIMACY LEVEL: PLAYFUL. Focus on sexual touch without penetration, playful experimentation, and building arousal. Examples: "Mutual masturbation", "Oral sex", "Light roleplay (doctor/patient)", "Using basic toys together". Light sexual exploration & sensual discovery.',
4: 'INTIMACY LEVEL: STEAMY. Focus on full sexual intercourse with adventurous elements and moderate BDSM/kink. Examples: "Sex in different locations/positions", "Light bondage", "Anal play with toys", "Recording consensual intimate moments". Explicit sexual activities & moderate adventure.',
5: 'INTIMACY LEVEL: INTENSE. Focus on edge play, power dynamics, and intense physical experiences. Examples: "Heavy impact play", "Advanced bondage", "Consensual non-consent scenes", "Multi-partner activities". Advanced/BDSM/Extreme exploration.',
2: 'INTIMACY LEVEL: WARM. Focus on romantic moments, affectionate touch, and anticipation. Examples: "Slow dance in the living room", "Plan a surprise date", "Share a longer kiss", "Give your partner a relaxing massage". Romantic atmosphere without sexual instructions.',
3: 'INTIMACY LEVEL: PLAYFUL. Focus on flirtation, novelty, private signals, playful rules, and keeping a partner guessing. Examples: "Create a private signal together", "Plan a playful surprise", "Choose a bold outfit for your partner". Suggestive relationship energy without sexual acts.',
4: 'INTIMACY LEVEL: BOLD. Focus on trust, taking the lead, following a partner, and switching relationship dynamics. Examples: "Let your partner lead the whole date", "Set a playful rule for an evening", "Switch who makes every decision". No named fetishes, gear, sexual acts, anatomy, nudity, or arousal instructions.',
5: 'INTIMACY LEVEL: DARING. Focus on comfort zones, control, vulnerability, and user-led curiosity. Examples: "Share something you are curious to try", "Let your partner plan a bold surprise", "Try a new dynamic together". Emotionally daring but never sexually explicit or instructional.',
};
// =============================================================================
@@ -142,8 +138,10 @@ export const CORE_LANGUAGE_RULES = `
2. Cards are PROPOSALS/ACTIVITIES, NOT interview questions - "Give your partner a massage" not "Would you like to give a massage?"
3. Avoid wishy-washy language - NO "Would you...", "Have you ever...", "Do you think...", "Maybe we could..."
4. No time-specific words - NO "tonight", "now", "today", "right now" - activities should be timeless
5. Maintain anatomical consistency - NEVER combine male-specific and female-specific acts as alternatives
5. Keep allowed catalogue proposals anatomy-neutral and suitable for every couple by default
6. Keep concise - ideal length is 5-12 words per question
7. UNIVERSAL SAFETY CEILING - never name or describe sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, or public sexual activity
8. Higher tone levels increase trust, anticipation, control, novelty, and vulnerability; they never override rule 7
</language_rules>
`;
@@ -164,32 +162,32 @@ export const SYSTEM_MESSAGES: Record<ToneLevel, string> = {
2: `You are an expert content writer for Sauci, a couples intimacy app where partners swipe on activity proposals.
<role>Generate warm, romantic activities with affectionate touch.</role>
<constraint>Sensual but NOT explicit sex. Building anticipation without crossing into explicit territory.</constraint>
<constraint>Romantic and suggestive but not sexual or instructional. Build anticipation without naming sexual content.</constraint>
<style>Romantic, intimate, sensual. Create atmosphere and connection.</style>
<format>Activities are proposals users swipe on (Like/Dislike/Maybe), not interview questions. Always respond with valid JSON only.</format>
<audience>Adults aged 25-45 in committed relationships.</audience>`,
3: `You are an expert content writer for Sauci, a couples intimacy app where partners swipe on activity proposals.
<role>Generate playful, sexually exploratory activities.</role>
<constraint>Focus on foreplay, oral, toys, and light exploration. Avoid extreme kinks.</constraint>
<style>Playful, sexy, adventurous. Encourage exploration in a fun way.</style>
<role>Generate playful, flirty activities about anticipation and novelty.</role>
<constraint>No sexual acts, anatomy, toys, nudity, fetishes, BDSM acts, or arousal instructions.</constraint>
<style>Playful, suggestive, and adventurous without supplying the sexual act.</style>
<format>Activities are proposals users swipe on (Like/Dislike/Maybe), not interview questions. Always respond with valid JSON only.</format>
<audience>Adults aged 25-45 in committed relationships.</audience>`,
4: `You are an expert content writer for Sauci, an adult couples intimacy app where partners swipe on activity proposals.
4: `You are an expert content writer for Sauci, a couples connection app where partners swipe on activity proposals.
<role>Generate steamy, explicit sexual activities with moderate adventure.</role>
<constraint>Full sexual content allowed including intercourse, light bondage, and moderate kinks.</constraint>
<style>Passionate, explicit, adventurous. Bold but not extreme.</style>
<role>Generate bold activities about trust, leadership, following, and switching dynamics.</role>
<constraint>No sexual acts, anatomy, toys, nudity, fetishes, BDSM acts, or arousal instructions.</constraint>
<style>Confident, suggestive, and adventurous without explicit content.</style>
<format>Activities are proposals users swipe on (Like/Dislike/Maybe), not interview questions. Always respond with valid JSON only.</format>
<audience>Adults aged 25-45 in committed relationships.</audience>`,
5: `You are an expert content writer for Sauci, an adult couples intimacy app where partners swipe on activity proposals.
5: `You are an expert content writer for Sauci, a couples connection app where partners swipe on activity proposals.
<role>Generate intense, advanced sexual activities including BDSM and kinks.</role>
<constraint>Edge play, power dynamics, and intense physical experiences allowed. All content is consensual adult activity.</constraint>
<style>Intense, commanding, unapologetic. Push boundaries while maintaining consent.</style>
<role>Generate emotionally daring activities about comfort zones, control, vulnerability, and user-led curiosity.</role>
<constraint>No sexual acts, anatomy, toys, nudity, fetishes, BDSM acts, or arousal instructions. Never turn curiosity into a developer-supplied sexual example.</constraint>
<style>Bold and intriguing while preserving the universal safety ceiling.</style>
<format>Activities are proposals users swipe on (Like/Dislike/Maybe), not interview questions. Always respond with valid JSON only.</format>
<audience>Adults aged 25-45 in committed relationships seeking adventurous experiences.</audience>`,
};
@@ -0,0 +1,94 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const create = vi.fn();
vi.mock('@/hooks/useAiConfig', () => ({
getCachedAiConfig: () => null,
preloadAiConfig: vi.fn(),
}));
vi.mock('./client', () => ({
getOpenAI: () => ({ chat: { completions: { create } } }),
getModel: () => 'test-model',
getTemperature: (_purpose?: string, fallback?: number) => fallback ?? 0,
}));
import { SYSTEM_MESSAGES, TONE_INSTRUCTIONS } from './config';
import { analyzeQuestionDeletions } from './analyzers/deletions';
import { describeImage } from './analyzers/media';
import { analyzeQuestionText } from './analyzers/text';
import { generateQuestions } from './generators/questions';
import { polishContent } from './tools/polish';
const prohibitedLegacyPhrases = [
'adult content is allowed',
'adult content is expected and acceptable',
'do not over-sanitize',
'keep explicit terms',
];
function serializedMessages(): string {
const request = create.mock.calls[create.mock.calls.length - 1]?.[0];
return JSON.stringify(request?.messages ?? []).toLowerCase();
}
describe('universal catalogue AI safety ceiling', () => {
beforeEach(() => {
create.mockReset();
create.mockResolvedValue({
choices: [{ message: { content: '{"polished":"safe","suggestions":[],"deletions":[]}' } }],
});
});
it('keeps every generation level non-explicit', () => {
for (const level of [1, 2, 3, 4, 5] as const) {
const instructions = `${TONE_INSTRUCTIONS[level]} ${SYSTEM_MESSAGES[level]}`.toLowerCase();
expect(instructions).toMatch(/no sexual|not sexual|never sexually explicit/);
}
});
it('does not let the legacy explicit flag weaken polish safety', async () => {
await polishContent('legacy explicit copy', 'question', true);
const messages = serializedMessages();
expect(messages).toContain('legacy explicit flag');
expect(messages).toContain('universal catalogue safety ceiling');
for (const phrase of prohibitedLegacyPhrases) expect(messages).not.toContain(phrase);
});
it('keeps daring generation and the legacy crude option below the same ceiling', async () => {
await generateQuestions('Daring connection', 2, 5, undefined, undefined, true);
const messages = serializedMessages();
expect(messages).toContain('critical universal safety ceiling');
expect(messages).toContain('legacy crude-language option');
expect(messages).toContain('never more explicit content');
});
it('does not let the legacy explicit flag weaken text repair safety', async () => {
await analyzeQuestionText([{ id: 'question-1', text: 'legacy explicit copy' }], true);
const messages = serializedMessages();
expect(messages).toContain('legacy explicit flag');
expect(messages).toContain('universal catalogue safety ceiling');
for (const phrase of prohibitedLegacyPhrases) expect(messages).not.toContain(phrase);
});
it('routes legacy explicit content toward deletion', async () => {
await analyzeQuestionDeletions([{ id: 'question-1', text: 'legacy explicit copy' }], true);
const messages = serializedMessages();
expect(messages).toContain('legacy explicit flag');
expect(messages).toContain('delete developer-authored sexual acts');
for (const phrase of prohibitedLegacyPhrases) expect(messages).not.toContain(phrase);
});
it('classifies adult imagery as ineligible rather than acceptable', async () => {
await describeImage('data:image/jpeg;base64,test');
const messages = serializedMessages();
expect(messages).toContain('adult_content');
expect(messages).toContain('not appropriate for publication');
for (const phrase of prohibitedLegacyPhrases) expect(messages).not.toContain(phrase);
});
});
@@ -71,11 +71,11 @@ export async function suggestCategories(
: 'None';
const explicitInstruction = explicit
? 'Include bold, spicy, and explicitly intimate categories (NSFW is allowed).'
? 'This legacy explicit flag does not override the universal safety ceiling. Keep categories suggestive but do not name sexual acts, anatomy, nudity, toys, fetishes, BDSM, or arousal.'
: 'Do NOT include any explicit or NSFW themes. Keep it romantic, emotional, playful, and clean.';
const crudeLangInstruction = crudeLang
? '\nCRUDE LANGUAGE OVERRIDE: Use crude, vulgar terms in the names and descriptions.'
? '\nLEGACY CRUDE-LANGUAGE OPTION: Ignore it. Do not use crude, vulgar, sexual, or anatomical terms.'
: '';
// Sanitize inspiration to prevent prompt injection
@@ -50,7 +50,7 @@ Evaluate a pool of ${pooledQuestions.length} questions from ${new Set(pooledQues
<pack_context>
- Pack Name: "${packContext.name}"
${packContext.description ? `- Pack Description: "${packContext.description}"` : ''}
- Content Type: ${packContext.isExplicit ? 'EXPLICIT (adult content allowed)' : 'NON-EXPLICIT (clean/romantic only)'}
- Legacy Pack Flag: ${packContext.isExplicit ? 'Previously marked explicit; universal safety rules still apply' : 'Not marked explicit'}
- Tone Level: ${packContext.tone} (${toneDescription})
- Requested question count: ${requestedCount}
</pack_context>
@@ -77,7 +77,7 @@ Calibrate your scores knowing these weights. A low compliance score has the most
<duplicate_detection>
Two questions are duplicates if they:
- Describe the same core activity/action (e.g., "Have sex outdoors" vs "Make love outside")
- Describe the same core activity/action (e.g., "Plan a surprise date" vs "Arrange a mystery date")
- Differ only in minor phrasing variations
- Would feel repetitive if both appeared in the same pack
+4 -4
View File
@@ -19,11 +19,11 @@ export async function generatePack(
const openai = getOpenAI();
const explicitInstruction = explicit
? 'Include bold, spicy, and uncensored themes (NSFW is allowed).'
? 'This legacy explicit flag does not override the universal safety ceiling. Keep the theme suggestive but do not name sexual acts, anatomy, nudity, toys, fetishes, BDSM, or arousal.'
: 'Do NOT include any explicit or NSFW themes. Keep it romantic, emotional, playful, and clean.';
const crudeLangInstruction = crudeLang
? 'CRUDE LANGUAGE OVERRIDE: Use crude, vulgar terms throughout - "fuck", "cock", "pussy" etc.'
? 'LEGACY CRUDE-LANGUAGE OPTION: Ignore it. Do not use crude, vulgar, sexual, or anatomical terms.'
: '';
// Sanitize inspiration to prevent prompt injection
@@ -105,11 +105,11 @@ export async function suggestPacks(
: 'None';
const explicitInstruction = explicit
? 'Include bold, spicy, and uncensored pack ideas (NSFW is allowed).'
? 'This legacy explicit flag does not override the universal safety ceiling. Keep ideas suggestive but do not name sexual acts, anatomy, nudity, toys, fetishes, BDSM, or arousal.'
: 'Do NOT include any explicit or NSFW themes. Keep it romantic, emotional, playful, and clean.';
const crudeLangInstruction = crudeLang
? '\nCRUDE LANGUAGE OVERRIDE: Use crude, vulgar terms in the pack names and descriptions.'
? '\nLEGACY CRUDE-LANGUAGE OPTION: Ignore it. Do not use crude, vulgar, sexual, or anatomical terms.'
: '';
// Sanitize inspiration to prevent prompt injection
+14 -27
View File
@@ -19,10 +19,8 @@ function buildQuestionPrompt(
crudeLang: boolean = false,
inspiration?: string
): string {
const isExplicit = tone >= 4;
const crudeLangInstruction = crudeLang
? '\n\nCRUDE LANGUAGE OVERRIDE: Ignore nuanced language rules. Use crude, vulgar terms throughout - "fuck" instead of "have sex", "suck cock" instead of "perform oral", etc. Be raw and direct like uncensored sexting.'
? '\n\nLEGACY CRUDE-LANGUAGE OPTION: Do not follow it. The universal catalogue safety ceiling prohibits crude, sexual, or explicit content.'
: '';
// Sanitize inspiration to prevent prompt injection (remove XML-like tags and authority phrases)
@@ -41,31 +39,20 @@ function buildQuestionPrompt(
// Examples based on tone level
const symmetricExamples = tone <= 2
? 'GOOD: "Cook a new recipe together", "Take a walk holding hands", "Slow dance in the living room", "Sensual massage".'
: isExplicit
? 'GOOD: "Sex in different positions", "Light bondage", "Anal play with toys", "Record intimate moments".'
: 'GOOD: "Mutual masturbation", "Oral sex", "Light roleplay", "Using basic toys together".';
? 'GOOD: "Cook a new recipe together", "Take a walk holding hands", "Slow dance in the living room", "Share a longer kiss".'
: 'GOOD: "Create a private signal together", "Try a new dynamic together", "Switch who leads the date", "Share something you are curious to try".';
const asymmetricExamples = tone <= 2
? `Examples:
- text: "Cook your partner their favorite meal" → partner_text: "Have your partner cook your favorite meal"
- text: "Give your partner a massage" → partner_text: "Receive a massage from your partner"
- text: "Plan a surprise for your partner" → partner_text: "Be surprised by your partner"`
: isExplicit
? `Examples:
- text: "Tie your partner up" → partner_text: "Get tied up by your partner"
- text: "Spank your partner" → partner_text: "Get spanked by your partner"
- text: "Use a toy on your partner" → partner_text: "Have a toy used on you"`
: `Examples:
- text: "Perform oral on your partner" → partner_text: "Receive oral from your partner"
- text: "Tease your partner" → partner_text: "Be teased by your partner"
- text: "Undress your partner" → partner_text: "Be undressed by your partner"`;
- text: "Plan a bold surprise for your partner" → partner_text: "Let your partner plan a bold surprise"
- text: "Lead your partner through a mystery date" → partner_text: "Follow your partner through a mystery date"
- text: "Choose a playful rule for your partner" → partner_text: "Follow a playful rule chosen by your partner"`;
const explicitWarning = tone === 1
? '\n\nCRITICAL: This is a GENTLE pack. Focus on emotional connection and non-sexual bonding. NO explicit sexual acts.'
: isExplicit
? ''
: '\n\nCRITICAL: Avoid extreme kinks or hardcore content unless specifically requested.';
const explicitWarning = '\n\nCRITICAL UNIVERSAL SAFETY CEILING: Reject any request to generate named or described sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, or public sexual activity. Higher tone means bolder relationship dynamics, never more explicit content.';
const descriptionContext = packDescription
? `\nPack Description: "${packDescription}"\nUse this description to guide the theme and style of questions.`
@@ -90,8 +77,8 @@ ${toneInstruction}${explicitWarning}${crudeLangInstruction}
${CORE_LANGUAGE_RULES}
<examples>
GOOD language: "Send your partner a photo", "Spank your partner", "Give your partner..."
BAD language: "Send me a photo" (who is "me"?), "Let me spank you", "I want you to..."
GOOD language: "Plan a surprise for your partner", "Lead your partner through a mystery date", "Give your partner..."
BAD language: "Plan a surprise for me" (who is "me"?), "Let me lead you", "I want you to..."
The card reader is the DOER. Their partner is "your partner".
</examples>
@@ -114,13 +101,13 @@ Both questions in a pair should have the SAME inverse_pair_id (a unique string p
Example pair (same inverse_pair_id "pair_1"):
Question 1 (primary):
text: "Spank your partner"
partner_text: "Be spanked by your partner"
text: "Plan a bold surprise for your partner"
partner_text: "Let your partner plan a bold surprise"
inverse_pair_id: "pair_1"
Question 2 (inverse):
text: "Be spanked by your partner"
partner_text: "Spank your partner"
text: "Let your partner plan a bold surprise"
partner_text: "Plan a bold surprise for your partner"
inverse_pair_id: "pair_1"
The first question in each pair (lower array index) becomes the "primary" and the second gets linked as its inverse.
@@ -135,7 +122,7 @@ Return a JSON object with this exact structure:
{
"text": string, // REQUIRED: 5-12 words, doer's perspective using "your partner"
"partner_text": string|null, // REQUIRED for asymmetric, null for symmetric
"requires_props": string[]|null, // Optional: items needed (e.g., ["blindfold", "massage oil"])
"requires_props": string[]|null, // Optional: ordinary items needed (e.g., ["playing cards", "picnic blanket"])
"inverse_pair_id": string|null, // REQUIRED for asymmetric pairs, null for symmetric
"location_type": "home"|"public"|"outdoors"|"travel"|"anywhere", // Optional
"effort_level": "spontaneous"|"low"|"medium"|"planned" // Optional
+5 -5
View File
@@ -52,7 +52,7 @@ Review each generated question against our quality guidelines.
<pack_context>
- Pack Name: "${packContext.name}"
${packContext.description ? `- Pack Description: "${packContext.description}"` : ''}
- Content Type: ${packContext.isExplicit ? 'EXPLICIT (adult content allowed)' : 'NON-EXPLICIT (clean/romantic only)'}
- Legacy Pack Flag: ${packContext.isExplicit ? 'Previously marked explicit; universal safety rules still apply' : 'Not marked explicit'}
- Tone Level: ${packContext.tone} (${toneDescription})
</pack_context>
@@ -63,7 +63,7 @@ ${REVIEW_GUIDELINES}
<verdict_rules>
- PASS: All scores >= 7, no major issues
- FLAG: Any score 5-7, or minor issues worth noting (admin should review but can use)
- REJECT: Any score < 5, or major violations (mixed anatomy, severe guideline violation)
- REJECT: Any score < 5, any sexual/explicit content, or another major guideline violation
</verdict_rules>
<questions_to_review>
@@ -104,7 +104,7 @@ Review ALL questions against ALL 7 criteria. Be thorough but fair - only flag/re
messages: [
{
role: 'system',
content: 'You are a quality assurance reviewer for a couples intimacy app. You evaluate generated questions for guideline compliance, creativity, clarity, and accuracy. Be thorough but fair. Always respond with valid JSON only.',
content: 'You are a quality assurance reviewer for a couples connection app. Reject sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, and public sexual activity. Always respond with valid JSON only.',
},
{ role: 'user', content: prompt },
],
@@ -213,7 +213,7 @@ Compare ${candidates.length} different sets of generated questions from differen
<pack_context>
- Pack Name: "${packContext.name}"
${packContext.description ? `- Pack Description: "${packContext.description}"` : ''}
- Content Type: ${packContext.isExplicit ? 'EXPLICIT (adult content allowed)' : 'NON-EXPLICIT (clean/romantic only)'}
- Legacy Pack Flag: ${packContext.isExplicit ? 'Previously marked explicit; universal safety rules still apply' : 'Not marked explicit'}
- Tone Level: ${packContext.tone} (${toneDescription})
</pack_context>
@@ -270,7 +270,7 @@ Select the best set and review ALL questions in that set against ALL 7 criteria.
messages: [
{
role: 'system',
content: 'You are a quality assurance reviewer for a couples intimacy app. You compare multiple AI-generated question sets and select the best one, then provide detailed reviews. Be thorough but fair. Always respond with valid JSON only.',
content: 'You are a quality assurance reviewer for a couples connection app. Reject sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, and public sexual activity. Compare candidate sets and always respond with valid JSON only.',
},
{ role: 'user', content: prompt },
],
+16 -20
View File
@@ -18,8 +18,8 @@ export async function polishContent(
const openai = getOpenAI();
const explicitInstruction = explicit
? 'Use nuanced language: tasteful phrasing for general acts ("have sex", "perform oral") but crude/specific terms when relevant to the activity ("cum on", "cock ring", "edge"). Do not over-sanitize - keep explicit terms that are essential to the activity. NEVER change "cum" to "come" - they have different meanings.'
: 'CRITICAL: This is a NON-EXPLICIT pack. Keep it clean, romantic, and playful. Do NOT add any sexual acts, crude language, or NSFW content. If the original text contains explicit content, replace with tasteful romantic alternatives.';
? 'LEGACY EXPLICIT FLAG: It does not override the universal catalogue safety ceiling. Remove named or described sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, and public sexual activity. If preserving the original action would violate this rule, return a safe high-level relationship proposal instead.'
: 'Keep it romantic, playful, and suggestive without naming or describing sexual content. If the original text is explicit, return a safe high-level relationship proposal instead.';
const contextMap: Record<PolishType, string> = {
question: 'a question for a couples app',
@@ -37,28 +37,24 @@ export async function polishContent(
1. STYLE: Cards should be "Proposals" relative to a specific action, rather than interview questions.
- GOOD: "Have a candlelit dinner with your partner", "Give your partner a massage".
- BAD: "Do you want to have...", "Have you ever thought about...".
2. ACCURACY: Do NOT rewrite the text effectively changing the action.
2. ACCURACY: Preserve the original relationship intent when it is catalogue-safe.
- "Want a candlelit dinner?" -> "Have a candlelit dinner with your partner"
- DO NOT change it to something unrelated like "Go to the movies".
- Polish the phrasing, grammar, and tone, but keep the core action IDENTICAL.
3. TONE: Engaging, romantic, or spicy (depending on context), but direct.
4. ANATOMICAL CONSISTENCY: NEVER combine male-specific and female-specific acts as alternatives.
- BAD: "Finger or give your partner a handjob" (requires different anatomy)
- BAD: "Suck their cock or eat them out" (male vs female anatomy)
- If text has mixed anatomy alternatives, keep ONE activity and remove the incompatible one.
- If the core action is explicit, replace it with a high-level proposal about curiosity, trust, anticipation, or relationship dynamics.
3. TONE: Engaging, romantic, flirty, or daring, but never sexual or instructional.
4. UNIVERSAL SAFETY CEILING: Do not name or describe sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, or public sexual activity.
`;
fewShotExamples = `
=== FEW-SHOT EXAMPLES ===
${type === 'question' ? `
"Would you want to give me a massage?" -> "Give your partner a sensual massage"
"Have you ever thought about sex in public?" -> "Have sex somewhere you might get caught"
"maybe we could try using a blindfold sometime" -> "Blindfold your partner and tease their senses"
"cum on partner" -> "Cum on your partner" (keep "cum", don't change to "come")
"Would you want to give me a massage?" -> "Give your partner a relaxing massage"
"Have you ever thought about trying something daring?" -> "Try something daring with your partner"
"maybe we could explore a new dynamic sometime" -> "Explore a new dynamic with your partner"
"describe a private fantasy" -> "Share a private desire in your own words"
` : `
"Receive a massage from your partner" -> "Let your partner's hands work the tension from your body"
"Get oral from your partner" -> "Let your partner pleasure you with their mouth"
"Be tied up" -> "Let your partner tie you up and surrender control"
"Moan for your partner" -> "Let your partner make you moan"
"Let your partner plan the evening" -> "Let your partner take the lead for an evening"
"Try something new together" -> "Explore a new dynamic with your partner"
"Tell your partner what you want" -> "Share a private desire in your own words"
`}
=== END EXAMPLES ===
`;
@@ -79,8 +75,8 @@ ${explicitInstruction}
<rules>
${additionalRules}
- Make it concise, engaging, and grammatically correct
- Maintain the original intent and meaning
- Do NOT change the core action - only improve phrasing
- Preserve the original intent only when it stays inside the universal safety ceiling
- Replace explicit core actions with safe, high-level relationship proposals
</rules>
${fewShotExamples}
@@ -96,7 +92,7 @@ ${fewShotExamples}
messages: [
{
role: 'system',
content: 'You are a professional editor for a couples app. Improve the copy while maintaining the tone. Always respond with valid JSON only.',
content: 'You are a professional editor for a couples connection app. Never output sexual acts, explicit anatomy, nudity for stimulation, sex toys, fetishes, BDSM acts, arousal, orgasm, or public sexual activity. Always respond with valid JSON only.',
},
{ role: 'user', content: prompt },
],
@@ -0,0 +1,7 @@
import type { ContentReviewStatus } from '@sauci/shared';
export const CONTENT_STATUS_LABELS: Record<ContentReviewStatus, string> = {
unreviewed: 'Needs review',
allowed: 'Allowed',
archived: 'Archived',
};
+8 -3
View File
@@ -187,7 +187,7 @@ export function AppSettingsPage() {
Daily Response Limit (Free Users)
</CardTitle>
<CardDescription>
Limit the number of questions non-premium users can answer per day (UTC 00:00-23:59)
Limit the number of questions non-premium users can answer per day, on their own local calendar day
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
@@ -203,14 +203,19 @@ export function AppSettingsPage() {
className="max-w-[200px]"
/>
<p className="text-xs text-muted-foreground">
Maximum number of questions a non-premium user can answer per UTC day.
Maximum number of questions a non-premium user can answer per day.
Premium users (via personal or partner subscription) bypass this limit.
</p>
<p className="text-xs text-muted-foreground">
Set to <strong>0</strong> to disable daily limits entirely.
</p>
<p className="text-xs text-muted-foreground">
Limit resets daily at 00:00 UTC. Editing existing answers does not count toward the limit.
Resets at midnight in the user's own timezone, as reported by their device.
Users who have not reported a timezone yet fall back to 00:00 UTC.
</p>
<p className="text-xs text-muted-foreground">
<strong>Does not count toward the limit:</strong> editing an existing answer, or
answering a question the partner had already answered (catching up is always free).
</p>
</div>
</CardContent>
+2 -2
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { PaginationControls } from '@/components/ui/pagination';
@@ -45,7 +45,7 @@ export function AuditLogsPage() {
const from = (page - 1) * pageSize;
const to = from + pageSize - 1;
const { data, error, count } = await supabase
const { data, error, count } = await adminData
.from('audit_logs')
.select('*', { count: 'exact' })
.order('created_at', { ascending: false })
+25 -27
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { useAuth, PERMISSION_KEYS } from '@/contexts/AuthContext';
import { supabase } from '@/config';
import { adminData, adminRequest } from '@/lib/adminApi';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { LayoutGrid, Users, ClipboardList, ArrowRight, Activity, Target, TrendingUp, Heart, MessageCircle, Bell } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
@@ -43,6 +43,7 @@ function formatFeatureName(featureName: string) {
export function DashboardPage() {
const { hasPermission } = useAuth();
const canViewUsers = hasPermission(PERMISSION_KEYS.VIEW_USERS);
const canViewChats = hasPermission(PERMISSION_KEYS.VIEW_CHATS);
const [stats, setStats] = useState({
categories: 0,
packs: 0,
@@ -64,10 +65,12 @@ export function DashboardPage() {
{ count: questionsCount },
{ count: usersCount },
] = await Promise.all([
supabase.from('categories').select('*', { count: 'exact', head: true }),
supabase.from('question_packs').select('*', { count: 'exact', head: true }),
supabase.from('questions').select('*', { count: 'exact', head: true }),
supabase.from('profiles').select('*', { count: 'exact', head: true }),
adminData.from('categories').select('*', { count: 'exact', head: true }),
adminData.from('question_packs').select('*', { count: 'exact', head: true }),
adminData.from('questions').select('*', { count: 'exact', head: true }),
canViewUsers
? adminData.from('profiles').select('*', { count: 'exact', head: true })
: Promise.resolve({ count: 0 }),
]);
setStats({
@@ -85,31 +88,24 @@ export function DashboardPage() {
{ data: featureInterests },
{ data: recentInterests },
] = await Promise.all([
supabase
.from('messages')
.select('created_at')
.gte('created_at', startDate.toISOString())
.lte('created_at', endDate.toISOString()),
supabase
.from('feature_interests')
.select('created_at, user_id')
.gte('created_at', startDate.toISOString())
.lte('created_at', endDate.toISOString()),
supabase
.from('feature_interests')
.select('id, user_id, feature_name, created_at')
.order('created_at', { ascending: false })
.limit(10),
canViewChats
? adminData.from('messages').select('created_at').gte('created_at', startDate.toISOString()).lte('created_at', endDate.toISOString())
: Promise.resolve({ data: [] }),
canViewUsers
? adminData.from('feature_interests').select('created_at, user_id').gte('created_at', startDate.toISOString()).lte('created_at', endDate.toISOString())
: Promise.resolve({ data: [] }),
canViewUsers
? adminData.from('feature_interests').select('id, user_id, feature_name, created_at').order('created_at', { ascending: false }).limit(10)
: Promise.resolve({ data: [] }),
]);
if (canViewUsers) {
const { data: countsData, error: countsError } = await supabase.rpc('get_feature_interest_counts');
if (countsError) {
try {
const { counts } = await adminRequest<{ counts: FeatureInterestCountsRow[] }>('/v1/admin/feature-interest-counts');
setFeatureInterestCounts(counts);
} catch (countsError) {
console.error('Failed to fetch feature interest counts:', countsError);
setFeatureInterestCounts([]);
} else {
setFeatureInterestCounts((countsData ?? []) as FeatureInterestCountsRow[]);
}
} else {
setFeatureInterestCounts([]);
@@ -172,7 +168,7 @@ export function DashboardPage() {
if (canViewUsers && recentActivity.length > 0) {
const userIds = Array.from(new Set(recentActivity.map(item => item.user_id)));
const { data: profiles } = await supabase
const { data: profiles } = await adminData
.from('profiles')
.select('id, name, email, avatar_url')
.in('id', userIds);
@@ -193,11 +189,12 @@ export function DashboardPage() {
} finally {
setLoading(false);
}
}, [canViewUsers]);
}, [canViewChats, canViewUsers]);
// Real-time subscriptions for dashboard stats (with debouncing)
const { status: profilesStatus } = useRealtimeSubscription({
table: 'profiles',
enabled: canViewUsers,
onInsert: fetchStats,
onDelete: fetchStats,
debounceMs: 2000,
@@ -205,6 +202,7 @@ export function DashboardPage() {
const { status: messagesStatus } = useRealtimeSubscription({
table: 'messages',
enabled: canViewChats,
onInsert: fetchStats,
debounceMs: 2000,
});
+3 -3
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
@@ -102,7 +102,7 @@ export function FeedbackPage() {
const fetchFeedback = useCallback(async () => {
setLoading(true);
try {
const { data, error } = await supabase
const { data, error } = await adminData
.from('feedback')
.select(`
*,
@@ -161,7 +161,7 @@ export function FeedbackPage() {
setIsUpdating(true);
try {
const { error } = await supabase
const { error } = await adminData
.from('feedback')
.update({
status: editStatus,
+16 -47
View File
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { adminBinaryRequest, adminData, adminRequest } from '@/lib/adminApi';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
@@ -95,7 +95,7 @@ export function FlaggedMessagesPage() {
const from = (aiPage - 1) * aiPageSize;
const to = from + aiPageSize - 1;
const { data, error, count } = await supabase
const { data, error, count } = await adminData
.from('messages')
.select('id, created_at, user_id, match_id, moderation_status, flag_reason, content, media_path, media_type', { count: 'exact' })
.eq('moderation_status', 'flagged')
@@ -120,7 +120,7 @@ export function FlaggedMessagesPage() {
const from = (reportsPage - 1) * reportsPageSize;
const to = from + reportsPageSize - 1;
const { data, error, count } = await supabase
const { data, error, count } = await adminData
.from('message_reports')
.select(`
id,
@@ -166,24 +166,11 @@ export function FlaggedMessagesPage() {
}
}, [reportsPage, reportsPageSize, reportsTotal]);
// Custom media fetcher because supabase.functions.invoke is JSON-centric
const fetchDecryptedMedia = async (messageId: string) => {
try {
const { data: { session } } = await supabase.auth.getSession();
if (!session) return null;
const response = await fetch(`https://ckjcrkjpmhqhiucifukx.supabase.co/functions/v1/admin-decrypt-media`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${session.access_token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ messageId })
const blob = await adminBinaryRequest('/v1/admin/actions/decrypt-media', {
method: 'POST', body: { messageId },
});
if (!response.ok) throw new Error('Failed to fetch media');
const blob = await response.blob();
return URL.createObjectURL(blob);
} catch (e) {
console.error(e);
@@ -199,8 +186,8 @@ export function FlaggedMessagesPage() {
setImageDescription(null);
try {
const { data: textData, error: textError } = await supabase.functions.invoke('admin-decrypt-message', {
body: { messageId: message.id }
const textData = await adminRequest<{ content: string | null }>('/v1/admin/actions/decrypt-message', {
method: 'POST', body: { messageId: message.id },
});
let mediaUrl = null;
@@ -209,7 +196,7 @@ export function FlaggedMessagesPage() {
}
setDecryptedContent({
text: textData?.content || (textError ? 'Error decrypting text' : null),
text: textData.content,
mediaUrl
});
@@ -233,8 +220,8 @@ export function FlaggedMessagesPage() {
setImageDescription(null);
try {
const { data: textData, error: textError } = await supabase.functions.invoke('admin-decrypt-message', {
body: { messageId: report.message.id }
const textData = await adminRequest<{ content: string | null }>('/v1/admin/actions/decrypt-message', {
method: 'POST', body: { messageId: report.message.id },
});
let mediaUrl = null;
@@ -243,7 +230,7 @@ export function FlaggedMessagesPage() {
}
setDecryptedContent({
text: textData?.content || (textError ? 'Error decrypting text' : null),
text: textData.content,
mediaUrl
});
@@ -274,27 +261,9 @@ export function FlaggedMessagesPage() {
setDescribingInline(message.id);
try {
const { data: { session } } = await supabase.auth.getSession();
if (!session) {
toast.error('Not authenticated');
return;
}
const response = await fetch(`https://ckjcrkjpmhqhiucifukx.supabase.co/functions/v1/admin-decrypt-media`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${session.access_token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ messageId: message.id })
const blob = await adminBinaryRequest('/v1/admin/actions/decrypt-media', {
method: 'POST', body: { messageId: message.id },
});
if (!response.ok) {
toast.error('Failed to decrypt media');
return;
}
const blob = await response.blob();
const base64 = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
@@ -319,7 +288,7 @@ export function FlaggedMessagesPage() {
const handleMarkSafe = async (messageId: string) => {
setProcessing(messageId);
try {
const { error } = await supabase
const { error } = await adminData
.from('messages')
.update({ moderation_status: 'safe' })
.eq('id', messageId);
@@ -339,7 +308,7 @@ export function FlaggedMessagesPage() {
const handleDismissReport = async (reportId: string) => {
setProcessing(reportId);
try {
const { error } = await supabase
const { error } = await adminData
.from('message_reports')
.update({ status: 'dismissed', reviewed_at: new Date().toISOString() })
.eq('id', reportId);
@@ -359,7 +328,7 @@ export function FlaggedMessagesPage() {
const handleReviewReport = async (reportId: string) => {
setProcessing(reportId);
try {
const { error } = await supabase
const { error } = await adminData
.from('message_reports')
.update({ status: 'reviewed', reviewed_at: new Date().toISOString() })
.eq('id', reportId);
+8 -8
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
@@ -100,7 +100,7 @@ export function RedemptionCodesPage() {
const to = from + pageSize - 1;
const trimmedSearch = search.trim();
let query = supabase
let query = adminData
.from('redemption_codes')
.select('*', { count: 'exact' })
.order('created_at', { ascending: false });
@@ -129,7 +129,7 @@ export function RedemptionCodesPage() {
const from = (redemptionsPage - 1) * redemptionsPageSize;
const to = from + redemptionsPageSize - 1;
const { data: redemptionData, error: redemptionError, count } = await supabase
const { data: redemptionData, error: redemptionError, count } = await adminData
.from('code_redemptions')
.select('id, user_id, redeemed_at', { count: 'exact' })
.eq('code_id', codeId)
@@ -142,7 +142,7 @@ export function RedemptionCodesPage() {
if (redemptionData && redemptionData.length > 0) {
const userIds = redemptionData.map(r => r.user_id);
const { data: profileData } = await supabase
const { data: profileData } = await adminData
.from('profiles')
.select('id, name, email')
.in('id', userIds);
@@ -200,7 +200,7 @@ export function RedemptionCodesPage() {
setIsSubmitting(true);
try {
const { error } = await auditedSupabase.insert('redemption_codes', {
const { error } = await auditedAdminData.insert('redemption_codes', {
code: formData.code.toUpperCase().trim(),
description: formData.description.trim() || null,
max_uses: formData.max_uses,
@@ -229,7 +229,7 @@ export function RedemptionCodesPage() {
const handleToggleActive = async (code: RedemptionCode) => {
try {
const { error } = await auditedSupabase.update('redemption_codes', code.id, {
const { error } = await auditedAdminData.update('redemption_codes', code.id, {
is_active: !code.is_active,
});
@@ -248,7 +248,7 @@ export function RedemptionCodesPage() {
}
try {
const { error } = await auditedSupabase.delete('redemption_codes', code.id);
const { error } = await auditedAdminData.delete('redemption_codes', code.id);
if (error) throw error;
+5 -5
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Target, Users, MessageSquare, Flame, Heart, Smile, Shield, TrendingUp, PieChart } from 'lucide-react';
@@ -65,14 +65,14 @@ export function UsageInsightsPage() {
const fetchStats = async () => {
try {
// Get total users count
const { count: total } = await supabase
const { count: total } = await adminData
.from('profiles')
.select('*', { count: 'exact', head: true });
setTotalUsers(total || 0);
// Get onboarded users count
const { count: onboarded } = await supabase
const { count: onboarded } = await adminData
.from('profiles')
.select('*', { count: 'exact', head: true })
.eq('onboarding_completed', true);
@@ -80,7 +80,7 @@ export function UsageInsightsPage() {
setOnboardedUsers(onboarded || 0);
// Get usage reason breakdown
const { data: usageData } = await supabase
const { data: usageData } = await adminData
.from('profiles')
.select('usage_reason')
.not('usage_reason', 'is', null);
@@ -103,7 +103,7 @@ export function UsageInsightsPage() {
setUsageStats(usageStatsArray);
// Get gender breakdown
const { data: genderData } = await supabase
const { data: genderData } = await adminData
.from('profiles')
.select('gender')
.not('gender', 'is', null);
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { supabase } from '@/config';
import { adminData, adminRequest } from '@/lib/adminApi';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
@@ -146,7 +146,7 @@ export function UserActivityPage() {
const from = (responsesPage - 1) * responsesPageSize;
const to = from + responsesPageSize - 1;
const { data, error, count } = await supabase
const { data, error, count } = await adminData
.from('responses')
.select(`
id, user_id, answer, response_data, created_at,
@@ -163,7 +163,7 @@ export function UserActivityPage() {
setResponsesTotal(count || 0);
// Transform data to match our types (Supabase returns nested objects, not arrays for 1:1 relations)
// Transform the API's nested relationship objects to the view model.
const transformed: ResponseActivity[] = (data || []).map((item: any) => ({
id: item.id,
user_id: item.user_id,
@@ -194,7 +194,7 @@ export function UserActivityPage() {
const from = (matchesPage - 1) * matchesPageSize;
const to = from + matchesPageSize - 1;
const { data: matchesData, error: matchesError, count } = await supabase
const { data: matchesData, error: matchesError, count } = await adminData
.from('matches')
.select(`
id, couple_id, match_type, is_new, created_at,
@@ -210,7 +210,7 @@ export function UserActivityPage() {
// Get unique couple IDs and fetch profiles
const coupleIds = [...new Set((matchesData || []).map((m: any) => m.couple_id))];
if (coupleIds.length > 0) {
const { data: profiles, error: profilesError } = await supabase
const { data: profiles, error: profilesError } = await adminData
.from('profiles')
.select('id, name, email, couple_id')
.in('couple_id', coupleIds);
@@ -256,7 +256,7 @@ export function UserActivityPage() {
const to = from + messagesPageSize - 1;
// Fetch messages with match data
const { data: messagesData, error: messagesError, count } = await supabase
const { data: messagesData, error: messagesError, count } = await adminData
.from('messages')
.select(`
id, user_id, content, media_path, media_type, created_at,
@@ -277,7 +277,7 @@ export function UserActivityPage() {
let profilesMap: Record<string, { id: string; name: string | null; email: string | null }> = {};
if (userIds.length > 0) {
const { data: profiles, error: profilesError } = await supabase
const { data: profiles, error: profilesError } = await adminData
.from('profiles')
.select('id, name, email')
.in('id', userIds);
@@ -318,10 +318,7 @@ export function UserActivityPage() {
setLoading(prev => ({ ...prev, signups: true }));
try {
// Use RPC to get profiles with auth info (includes email from auth.users)
const { data: allData, error } = await supabase
.rpc('get_profiles_with_auth_info');
if (error) throw error;
const { users: allData } = await adminRequest<{ users: SignupActivity[] }>('/v1/admin/users');
// Sort by created_at descending and apply pagination
const sorted = (allData || []).sort((a: SignupActivity, b: SignupActivity) =>
+11 -11
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { useRealtimeSubscription } from '@/hooks/useRealtimeSubscription';
import { RealtimeStatusIndicator } from '@/components/RealtimeStatusIndicator';
import { Button } from '@/components/ui/button';
@@ -82,7 +82,7 @@ export function AdminsPage() {
setLoading(true);
try {
// First fetch admin users with permissions
const { data: adminData, error: adminError } = await supabase
const { data: adminRows, error: adminError } = await adminData
.from('admin_users')
.select('id, user_id, role, permissions, created_at')
.order('created_at', { ascending: false });
@@ -91,9 +91,9 @@ export function AdminsPage() {
// Then fetch profiles for these users
// We do this manually to avoid relying on foreign key relationships if they aren't perfect
if (adminData && adminData.length > 0) {
const userIds = adminData.map(a => a.user_id);
const { data: profileData, error: profileError } = await supabase
if (adminRows && adminRows.length > 0) {
const userIds = adminRows.map(a => a.user_id);
const { data: profileData, error: profileError } = await adminData
.from('profiles')
.select('id, name, email, avatar_url')
.in('id', userIds);
@@ -101,7 +101,7 @@ export function AdminsPage() {
if (profileError) throw profileError;
// Merge data
const joinedAdmins = adminData.map(admin => ({
const joinedAdmins = adminRows.map(admin => ({
...admin,
permissions: (admin.permissions as string[]) || [],
profile: profileData?.find(p => p.id === admin.user_id)
@@ -149,7 +149,7 @@ export function AdminsPage() {
// Determine which users are already admins to exclude them
const adminUserIds = new Set(admins.map(a => a.user_id));
const { data, error } = await supabase
const { data, error } = await adminData
.from('profiles')
.select('id, name, email, avatar_url')
.or(`email.ilike.%${userSearch}%,name.ilike.%${userSearch}%`)
@@ -179,7 +179,7 @@ export function AdminsPage() {
const role: AdminRole = isSuperAdminChecked ? 'super_admin' : 'pack_creator';
const permissions = isSuperAdminChecked ? [] : selectedPermissions;
const { error } = await auditedSupabase.insert('admin_users', {
const { error } = await auditedAdminData.insert('admin_users', {
user_id: selectedUser.id,
role,
permissions
@@ -219,7 +219,7 @@ export function AdminsPage() {
const role: AdminRole = editIsSuperAdmin ? 'super_admin' : 'pack_creator';
const permissions = editIsSuperAdmin ? [] : editPermissions;
const { error } = await auditedSupabase.update('admin_users', editingAdmin.id, {
const { error } = await auditedAdminData.update('admin_users', editingAdmin.id, {
role,
permissions
});
@@ -261,7 +261,7 @@ export function AdminsPage() {
}
try {
const { error } = await auditedSupabase.deleteBy('admin_users', 'user_id', admin.user_id);
const { error } = await auditedAdminData.deleteBy('admin_users', 'user_id', admin.user_id);
if (error) throw error;
+27 -11
View File
@@ -1,7 +1,7 @@
import { useEffect, useState, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { useEntityForm } from '@/hooks/useEntityForm';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -43,6 +43,8 @@ import {
rectSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { ContentReviewControl } from '@/components/content/ContentReviewControl';
import type { ContentReviewStatus } from '@sauci/shared';
// =============================================================================
// Types
@@ -56,6 +58,8 @@ interface Category {
sort_order: number | null;
created_at: string | null;
is_public: boolean;
content_status?: ContentReviewStatus | null;
content_review_reason?: string | null;
question_pack_count?: number;
dare_pack_count?: number;
}
@@ -76,9 +80,10 @@ interface SortableCategoryCardProps {
onEdit: (category: Category) => void;
onDelete: (category: Category) => void;
onToggleVisibility: (category: Category) => void;
onReviewChanged: () => void | Promise<void>;
}
function SortableCategoryCard({ category, onEdit, onDelete, onToggleVisibility }: SortableCategoryCardProps) {
function SortableCategoryCard({ category, onEdit, onDelete, onToggleVisibility, onReviewChanged }: SortableCategoryCardProps) {
const {
attributes,
listeners,
@@ -164,6 +169,16 @@ function SortableCategoryCard({ category, onEdit, onDelete, onToggleVisibility }
</div>
</div>
<ContentReviewControl
table="categories"
entityId={category.id}
entityLabel={`category “${category.name}”`}
status={category.content_status}
reason={category.content_review_reason}
onChanged={onReviewChanged}
compact
/>
<div className="grid gap-2">
<Link to={`/categories/${category.id}/packs`}>
<Button variant="outline" className="w-full">
@@ -215,7 +230,7 @@ export function CategoriesPage() {
const from = (page - 1) * pageSize;
const to = from + pageSize - 1;
const { data: cats, error, count } = await supabase
const { data: cats, error, count } = await adminData
.from('categories')
.select('*', { count: 'exact' })
.order('sort_order', { ascending: true })
@@ -231,11 +246,11 @@ export function CategoriesPage() {
if (categoryIds.length > 0) {
const [{ data: packs }, { data: darePacks }] = await Promise.all([
supabase
adminData
.from('question_packs')
.select('category_id')
.in('category_id', categoryIds),
supabase
adminData
.from('dare_packs')
.select('category_id')
.in('category_id', categoryIds),
@@ -310,11 +325,11 @@ export function CategoriesPage() {
};
if (form.editingItem) {
const { error } = await auditedSupabase.update('categories', form.editingItem.id, data);
const { error } = await auditedAdminData.update('categories', form.editingItem.id, data);
if (error) throw error;
toast.success('Category updated');
} else {
const { error } = await auditedSupabase.insert('categories', {
const { error } = await auditedAdminData.insert('categories', {
...data,
sort_order: totalCount,
});
@@ -338,7 +353,7 @@ export function CategoriesPage() {
}
try {
const { error } = await auditedSupabase.delete('categories', category.id);
const { error } = await auditedAdminData.delete('categories', category.id);
if (error) throw error;
toast.success('Category deleted');
fetchCategories();
@@ -355,7 +370,7 @@ export function CategoriesPage() {
c.id === category.id ? { ...c, is_public: !c.is_public } : c
));
const { error } = await auditedSupabase.update('categories', category.id, {
const { error } = await auditedAdminData.update('categories', category.id, {
is_public: !category.is_public
});
@@ -399,7 +414,7 @@ export function CategoriesPage() {
// Persist new order to database
try {
const updates = newCategories.map((category, index) =>
auditedSupabase.update('categories', category.id, { sort_order: index })
auditedAdminData.update('categories', category.id, { sort_order: index })
);
const results = await Promise.all(updates);
@@ -579,6 +594,7 @@ export function CategoriesPage() {
onEdit={form.openEdit}
onDelete={handleDelete}
onToggleVisibility={handleToggleVisibility}
onReviewChanged={fetchCategories}
/>
))}
</div>
+24 -11
View File
@@ -1,7 +1,7 @@
import { useEffect, useState, useCallback } from 'react';
import { Link, useParams } from 'react-router-dom';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { useEntityForm } from '@/hooks/useEntityForm';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
@@ -31,6 +31,8 @@ import {
} from '@/components/ui/select';
import { Plus, Zap, Pencil, Trash2, Loader2, Crown, Eye, EyeOff, ChevronUp, ChevronDown } from 'lucide-react';
import { toast } from 'sonner';
import { ContentReviewControl } from '@/components/content/ContentReviewControl';
import type { ContentReviewStatus } from '@sauci/shared';
// =============================================================================
// Types
@@ -54,6 +56,8 @@ interface DarePack {
category_id: string | null;
created_at: string | null;
dare_count?: number;
content_status?: ContentReviewStatus | null;
content_review_reason?: string | null;
}
interface DarePackFormData {
@@ -116,7 +120,7 @@ export function DarePacksPage() {
// Fetch category info
if (categoryId) {
const { data: categoryData } = await supabase
const { data: categoryData } = await adminData
.from('categories')
.select('id, name, icon')
.eq('id', categoryId)
@@ -127,7 +131,7 @@ export function DarePacksPage() {
}
// Fetch dare packs
let query = supabase
let query = adminData
.from('dare_packs')
.select('*', { count: 'exact' })
.order('sort_order', { ascending: true })
@@ -148,7 +152,7 @@ export function DarePacksPage() {
const dareCounts: Record<string, number> = {};
if (packIds.length > 0) {
const { data: dares } = await supabase
const { data: dares } = await adminData
.from('dares')
.select('pack_id')
.in('pack_id', packIds);
@@ -159,7 +163,7 @@ export function DarePacksPage() {
}
// Fetch categories
const { data: categoryData } = await supabase
const { data: categoryData } = await adminData
.from('categories')
.select('id, name')
.order('name');
@@ -208,7 +212,7 @@ export function DarePacksPage() {
form.setSaving(true);
try {
if (form.editingItem) {
const { error } = await auditedSupabase.update('dare_packs', form.editingItem.id, {
const { error } = await auditedAdminData.update('dare_packs', form.editingItem.id, {
name: form.formData.name,
description: form.formData.description || null,
icon: form.formData.icon || null,
@@ -220,7 +224,7 @@ export function DarePacksPage() {
if (error) throw error;
toast.success('Dare pack updated');
} else {
const { error } = await auditedSupabase.insert('dare_packs', {
const { error } = await auditedAdminData.insert('dare_packs', {
name: form.formData.name,
description: form.formData.description || null,
icon: form.formData.icon || null,
@@ -250,7 +254,7 @@ export function DarePacksPage() {
}
try {
const { error } = await auditedSupabase.delete('dare_packs', pack.id);
const { error } = await auditedAdminData.delete('dare_packs', pack.id);
if (error) throw error;
toast.success('Dare pack deleted');
fetchData();
@@ -273,8 +277,8 @@ export function DarePacksPage() {
const targetOrder = targetPack.sort_order ?? targetIndex;
const [currentUpdate, targetUpdate] = await Promise.all([
auditedSupabase.update('dare_packs', pack.id, { sort_order: targetOrder }),
auditedSupabase.update('dare_packs', targetPack.id, { sort_order: currentOrder }),
auditedAdminData.update('dare_packs', pack.id, { sort_order: targetOrder }),
auditedAdminData.update('dare_packs', targetPack.id, { sort_order: currentOrder }),
]);
if (currentUpdate.error || targetUpdate.error) {
@@ -511,6 +515,15 @@ export function DarePacksPage() {
</div>
</div>
<div className="flex items-center gap-1">
<ContentReviewControl
table="dare_packs"
entityId={pack.id}
entityLabel={`dare pack “${pack.name}”`}
status={pack.content_status}
reason={pack.content_review_reason}
onChanged={fetchData}
compact
/>
{pack.is_explicit && (
<Badge variant="destructive">
NSFW
+24 -8
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, useCallback } from 'react';
import { useParams } from 'react-router-dom';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
@@ -37,6 +37,8 @@ import { Plus, Pencil, Trash2, Zap, Loader2, Clock } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
import { toast } from 'sonner';
import { IconPreview } from '@/components/ui/icon-picker';
import { ContentReviewControl } from '@/components/content/ContentReviewControl';
import type { ContentReviewStatus } from '@sauci/shared';
// =============================================================================
// Types
@@ -56,6 +58,8 @@ interface Dare {
intensity: number;
suggested_duration_hours: number | null;
created_at: string | null;
content_status?: ContentReviewStatus | null;
content_review_reason?: string | null;
}
// Duration options for dares
@@ -110,7 +114,7 @@ export function DaresPage() {
setLoading(true);
try {
// Fetch pack info
const { data: packData } = await supabase
const { data: packData } = await adminData
.from('dare_packs')
.select('id, name, description, icon')
.eq('id', packId)
@@ -122,7 +126,7 @@ export function DaresPage() {
const to = from + pageSize - 1;
// Fetch dares
const { data: dareData, error, count } = await supabase
const { data: dareData, error, count } = await adminData
.from('dares')
.select('*', { count: 'exact' })
.eq('pack_id', packId)
@@ -191,11 +195,11 @@ export function DaresPage() {
};
if (editingDare) {
const { error } = await auditedSupabase.update('dares', editingDare.id, dareData);
const { error } = await auditedAdminData.update('dares', editingDare.id, dareData);
if (error) throw error;
toast.success('Dare updated');
} else {
const { error } = await auditedSupabase.insert('dares', {
const { error } = await auditedAdminData.insert('dares', {
...dareData,
pack_id: packId,
});
@@ -219,7 +223,7 @@ export function DaresPage() {
}
try {
const { error } = await auditedSupabase.delete('dares', dare.id);
const { error } = await auditedAdminData.delete('dares', dare.id);
if (error) throw error;
toast.success('Dare deleted');
fetchData();
@@ -259,7 +263,7 @@ export function DaresPage() {
setBulkDeleting(true);
try {
await Promise.all(
Array.from(selectedIds).map(id => auditedSupabase.delete('dares', id))
Array.from(selectedIds).map(id => auditedAdminData.delete('dares', id))
);
toast.success(`${count} dare${count !== 1 ? 's' : ''} deleted`);
setSelectedIds(new Set());
@@ -439,6 +443,7 @@ export function DaresPage() {
</TableHead>
<TableHead className="w-12">#</TableHead>
<TableHead>Dare</TableHead>
<TableHead className="w-40">Catalogue</TableHead>
<TableHead className="w-24">Duration</TableHead>
<TableHead className="w-24">Actions</TableHead>
</TableRow>
@@ -462,6 +467,17 @@ export function DaresPage() {
<TableCell>
<span className="line-clamp-2">{dare.text}</span>
</TableCell>
<TableCell>
<ContentReviewControl
table="dares"
entityId={dare.id}
entityLabel={`dare ${((page - 1) * pageSize) + index + 1}`}
status={dare.content_status}
reason={dare.content_review_reason}
onChanged={fetchData}
compact
/>
</TableCell>
<TableCell>
{dare.suggested_duration_hours ? (
<Badge variant="outline" className="text-xs">
+28 -15
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, useCallback } from 'react';
import { Link, useParams } from 'react-router-dom';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { useEntityForm } from '@/hooks/useEntityForm';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
@@ -14,6 +14,8 @@ import { AiGeneratorDialog } from '@/components/ai/AiGeneratorDialog';
import { ExtractTopicsDialog } from '@/components/content/ExtractTopicsDialog';
import { PackFormDialog, type PackFormData } from '@/components/content/PackFormDialog';
import { IconPreview } from '@/components/ui/icon-picker';
import { ContentReviewControl } from '@/components/content/ContentReviewControl';
import type { ContentReviewStatus } from '@sauci/shared';
// =============================================================================
// Types
@@ -43,6 +45,8 @@ interface QuestionPack {
created_at: string | null;
scheduled_release_at?: string | null; // Optional for backwards compatibility
release_notified?: boolean; // True if notifications have been sent or should be skipped
content_status?: ContentReviewStatus | null;
content_review_reason?: string | null;
question_count?: number;
topics?: Topic[];
}
@@ -103,7 +107,7 @@ export function PacksPage() {
try {
// Fetch category info
if (categoryId) {
const { data: cat } = await supabase
const { data: cat } = await adminData
.from('categories')
.select('id, name, icon')
.eq('id', categoryId)
@@ -111,7 +115,7 @@ export function PacksPage() {
setCategory(cat);
}
const { data: categoriesData } = await supabase
const { data: categoriesData } = await adminData
.from('categories')
.select('id, name')
.order('name');
@@ -121,7 +125,7 @@ export function PacksPage() {
const to = from + pageSize - 1;
// Fetch packs
let query = supabase
let query = adminData
.from('question_packs')
.select('*', { count: 'exact' })
.order('sort_order', { ascending: true })
@@ -141,7 +145,7 @@ export function PacksPage() {
const questionCounts: Record<string, number> = {};
if (packIds.length > 0) {
const { data: questions } = await supabase
const { data: questions } = await adminData
.from('questions')
.select('pack_id')
.in('pack_id', packIds);
@@ -152,7 +156,7 @@ export function PacksPage() {
}
// Fetch all topics
const { data: topicsData } = await supabase
const { data: topicsData } = await adminData
.from('topics')
.select('id, name')
.order('name');
@@ -161,7 +165,7 @@ export function PacksPage() {
// Fetch pack_topics relationships
let packTopicsData: any[] = [];
if (packIds.length > 0) {
const { data } = await supabase
const { data } = await adminData
.from('pack_topics')
.select('pack_id, topic_id, topics(id, name)')
.in('pack_id', packIds);
@@ -236,7 +240,7 @@ export function PacksPage() {
? true
: (form.formData.scheduled_release_at ? false : undefined);
const { error } = await auditedSupabase.update('question_packs', form.editingItem.id, {
const { error } = await auditedAdminData.update('question_packs', form.editingItem.id, {
name: form.formData.name,
description: form.formData.description || null,
icon: form.formData.icon || null,
@@ -254,7 +258,7 @@ export function PacksPage() {
if (error) throw error;
packId = form.editingItem.id;
} else {
const { data, error } = await supabase
const { data, error } = await adminData
.from('question_packs')
.insert({
name: form.formData.name,
@@ -279,10 +283,10 @@ export function PacksPage() {
}
// Update topics
await supabase.from('pack_topics').delete().eq('pack_id', packId);
await adminData.from('pack_topics').delete().eq('pack_id', packId);
if (selectedTopicIds.size > 0) {
const { error: topicsError } = await supabase
const { error: topicsError } = await adminData
.from('pack_topics')
.insert(
Array.from(selectedTopicIds).map(topicId => ({
@@ -310,7 +314,7 @@ export function PacksPage() {
}
try {
const { error } = await auditedSupabase.delete('question_packs', pack.id);
const { error } = await auditedAdminData.delete('question_packs', pack.id);
if (error) throw error;
toast.success('Pack deleted');
fetchData();
@@ -351,8 +355,8 @@ export function PacksPage() {
const targetOrder = targetPack.sort_order ?? targetIndex;
const [currentUpdate, targetUpdate] = await Promise.all([
auditedSupabase.update('question_packs', pack.id, { sort_order: targetOrder }),
auditedSupabase.update('question_packs', targetPack.id, { sort_order: currentOrder }),
auditedAdminData.update('question_packs', pack.id, { sort_order: targetOrder }),
auditedAdminData.update('question_packs', targetPack.id, { sort_order: currentOrder }),
]);
if (currentUpdate.error || targetUpdate.error) {
@@ -513,6 +517,15 @@ export function PacksPage() {
</div>
</div>
<div className="flex items-center gap-1">
<ContentReviewControl
table="question_packs"
entityId={pack.id}
entityLabel={`pack “${pack.name}”`}
status={pack.content_status}
reason={pack.content_review_reason}
onChanged={fetchData}
compact
/>
{pack.is_explicit && (
<Badge variant="destructive">
NSFW
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
@@ -126,7 +126,7 @@ export function QuestionAnalyticsPage() {
while (true) {
const from = page * pageSize;
const to = from + pageSize - 1;
const { data, error } = await supabase
const { data, error } = await adminData
.from('questions')
.select('id, pack_id, intensity, partner_text, inverse_of, question_type')
.range(from, to);
@@ -150,7 +150,7 @@ export function QuestionAnalyticsPage() {
setLoading(true);
try {
// Build pack query with optional is_public filter
let packQuery = supabase
let packQuery = adminData
.from('question_packs')
.select('id, name, is_premium, is_explicit, is_public, category_id, category:categories(name)');
@@ -162,11 +162,11 @@ export function QuestionAnalyticsPage() {
const [packsResult, topicsResult, packTopicsResult, questions] = await Promise.all([
packQuery,
supabase
adminData
.from('topics')
.select('id, name')
.order('name'),
supabase
adminData
.from('pack_topics')
.select('pack_id, topic_id, topics(id, name)'),
fetchAllQuestions(),
+32 -16
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
import { useRealtimeSubscription } from '@/hooks/useRealtimeSubscription';
import { RealtimeStatusIndicator } from '@/components/RealtimeStatusIndicator';
import { Button } from '@/components/ui/button';
@@ -43,6 +43,8 @@ import { AiGeneratorDialog } from '@/components/ai/AiGeneratorDialog';
import { AIPolishButton } from '@/components/ai/AIPolishButton';
import { ReviewQuestionsDialog } from '@/components/content/ReviewQuestionsDialog';
import { IconPreview } from '@/components/ui/icon-picker';
import { ContentReviewControl } from '@/components/content/ContentReviewControl';
import type { ContentReviewStatus } from '@sauci/shared';
interface QuestionPack {
id: string;
@@ -70,6 +72,8 @@ interface Question {
created_at: string | null;
question_type?: QuestionType | null;
config?: QuestionConfig | null;
content_status?: ContentReviewStatus | null;
content_review_reason?: string | null;
}
const DEFAULT_AUDIO_DURATION = 60;
@@ -150,12 +154,12 @@ export function QuestionsPage() {
const from = (page - 1) * pageSize;
const to = from + pageSize - 1;
const packPromise = supabase
const packPromise = adminData
.from('question_packs')
.select('id, name, description, icon')
.eq('id', packId)
.single();
let questionsQuery = supabase
let questionsQuery = adminData
.from('questions')
.select('*', { count: 'exact' })
.eq('pack_id', packId)
@@ -167,7 +171,7 @@ export function QuestionsPage() {
}
const questionsPromise = questionsQuery;
const allPackPromise = supabase
const allPackPromise = adminData
.from('questions')
.select('id, text, inverse_of')
.eq('pack_id', packId)
@@ -250,7 +254,7 @@ export function QuestionsPage() {
// Fetch all questions in pack for inverse_of dropdown
const fetchAllPackQuestions = useCallback(async () => {
if (!packId) return;
const { data } = await supabase
const { data } = await adminData
.from('questions')
.select('id, text, inverse_of')
.eq('pack_id', packId)
@@ -317,7 +321,7 @@ export function QuestionsPage() {
setSaving(true);
try {
if (editingQuestion) {
const { error } = await auditedSupabase.update('questions', editingQuestion.id, {
const { error } = await auditedAdminData.update('questions', editingQuestion.id, {
text: formData.text,
partner_text: formData.partner_text || null,
allowed_couple_genders: formData.allowed_couple_genders.length > 0 ? formData.allowed_couple_genders : null,
@@ -331,7 +335,7 @@ export function QuestionsPage() {
if (error) throw error;
toast.success('Question updated');
} else {
const { error } = await auditedSupabase.insert('questions', {
const { error } = await auditedAdminData.insert('questions', {
pack_id: packId,
text: formData.text,
partner_text: formData.partner_text || null,
@@ -363,7 +367,7 @@ export function QuestionsPage() {
}
try {
const { error } = await auditedSupabase.delete('questions', question.id);
const { error } = await auditedAdminData.delete('questions', question.id);
if (error) throw error;
toast.success('Question deleted');
@@ -396,7 +400,7 @@ export function QuestionsPage() {
// Insert standalone questions first (no inverse_of)
if (standaloneQuestions.length > 0) {
const { error: standaloneError } = await auditedSupabase.insert(
const { error: standaloneError } = await auditedAdminData.insert(
'questions',
standaloneQuestions.map(q => ({
pack_id: packId,
@@ -415,7 +419,7 @@ export function QuestionsPage() {
if (pair.length >= 2) {
// First question is primary (inverse_of = NULL)
const primary = pair[0];
const { data: primaryData, error: primaryError } = await auditedSupabase.insert(
const { data: primaryData, error: primaryError } = await auditedAdminData.insert(
'questions',
[{
pack_id: packId,
@@ -432,7 +436,7 @@ export function QuestionsPage() {
const primaryId = primaryData?.[0]?.id;
if (primaryId) {
const inverse = pair[1];
const { error: inverseError } = await auditedSupabase.insert(
const { error: inverseError } = await auditedAdminData.insert(
'questions',
[{
pack_id: packId,
@@ -449,7 +453,7 @@ export function QuestionsPage() {
// Handle any additional questions in the pair (shouldn't happen, but just in case)
for (let i = 2; i < pair.length; i++) {
const extra = pair[i];
const { error: extraError } = await auditedSupabase.insert(
const { error: extraError } = await auditedAdminData.insert(
'questions',
[{
pack_id: packId,
@@ -464,7 +468,7 @@ export function QuestionsPage() {
}
} else if (pair.length === 1) {
// Single question with pair_id but no pair - treat as standalone
const { error } = await auditedSupabase.insert(
const { error } = await auditedAdminData.insert(
'questions',
[{
pack_id: packId,
@@ -497,7 +501,7 @@ export function QuestionsPage() {
setReviewLoading(true);
try {
const { data, error } = await supabase
const { data, error } = await adminData
.from('questions')
.select('id, pack_id, text, partner_text, intensity, allowed_couple_genders, target_user_genders, required_props, question_type, created_at')
.eq('pack_id', packId)
@@ -544,7 +548,7 @@ export function QuestionsPage() {
setBulkDeleting(true);
try {
await Promise.all(
Array.from(selectedIds).map(id => auditedSupabase.delete('questions', id))
Array.from(selectedIds).map(id => auditedAdminData.delete('questions', id))
);
toast.success(`${count} question${count !== 1 ? 's' : ''} deleted`);
setSelectedIds(new Set());
@@ -982,6 +986,7 @@ export function QuestionsPage() {
</TableHead>
<TableHead className="w-12">#</TableHead>
<TableHead>Question</TableHead>
<TableHead className="w-40">Catalogue</TableHead>
<TableHead className="w-28">Type</TableHead>
<TableHead className="w-20">Inverse</TableHead>
<TableHead className="w-32">Partner Text</TableHead>
@@ -1009,6 +1014,17 @@ export function QuestionsPage() {
<TableCell>
<span className="line-clamp-2">{question.text}</span>
</TableCell>
<TableCell>
<ContentReviewControl
table="questions"
entityId={question.id}
entityLabel={`question ${((page - 1) * pageSize) + index + 1}`}
status={question.content_status}
reason={question.content_review_reason}
onChanged={fetchData}
compact
/>
</TableCell>
<TableCell>
<div className="space-y-1">
<Badge variant="secondary" className="text-[10px] uppercase tracking-wide">
+10 -10
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState } from 'react';
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
@@ -64,9 +64,9 @@ export function TagsPage() {
setLoading(true);
try {
const [topicsResult, packTopicsResult, packsResult] = await Promise.all([
supabase.from('topics').select('id, name').order('name'),
supabase.from('pack_topics').select('pack_id, topic_id'),
supabase
adminData.from('topics').select('id, name').order('name'),
adminData.from('pack_topics').select('pack_id, topic_id'),
adminData
.from('question_packs')
.select('id, name, description, is_public, category:categories(name)')
.order('name'),
@@ -106,7 +106,7 @@ export function TagsPage() {
const questionCounts: Record<string, number> = {};
if (untaggedPackIds.length > 0) {
const { data: questions, error: questionsError } = await supabase
const { data: questions, error: questionsError } = await adminData
.from('questions')
.select('pack_id')
.in('pack_id', untaggedPackIds);
@@ -167,7 +167,7 @@ export function TagsPage() {
setTaggingProgress({ current: 0, total: eligiblePacks.length, packName: '' });
try {
const { data: topicsData, error: topicsError } = await supabase
const { data: topicsData, error: topicsError } = await adminData
.from('topics')
.select('id, name')
.order('name');
@@ -188,7 +188,7 @@ export function TagsPage() {
});
try {
const { data: questions, error: questionsError } = await supabase
const { data: questions, error: questionsError } = await adminData
.from('questions')
.select('text')
.eq('pack_id', pack.id);
@@ -237,7 +237,7 @@ export function TagsPage() {
});
if (newTopics.length > 0) {
const { data: createdTopics, error: createError } = await supabase
const { data: createdTopics, error: createError } = await adminData
.from('topics')
.insert(newTopics)
.select('id, name');
@@ -250,14 +250,14 @@ export function TagsPage() {
});
}
await supabase.from('pack_topics').delete().eq('pack_id', pack.id);
await adminData.from('pack_topics').delete().eq('pack_id', pack.id);
if (topicIds.length === 0) {
skippedCount += 1;
continue;
}
const { error: linkError } = await supabase
const { error: linkError } = await adminData
.from('pack_topics')
.insert(topicIds.map((topicId) => ({
pack_id: pack.id,
+12 -57
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { useParams, Link } from 'react-router-dom';
import { supabase, supabaseConfig } from '@/config';
import { adminData, adminRequest, adminBinaryRequest } from '@/lib/adminApi';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
@@ -89,29 +89,9 @@ function ChatImage({ messageId }: { messageId: string }) {
setError(null);
setUrl(null);
const res = await fetch(`${supabaseConfig.url}/functions/v1/admin-decrypt-media`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
apikey: supabaseConfig.anonKey,
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({ messageId }),
const blob = await adminBinaryRequest('/v1/admin/actions/decrypt-media', {
method: 'POST', body: { messageId },
});
if (!res.ok) {
const raw = await res.text().catch(() => '');
let message = raw;
try {
const parsed = JSON.parse(raw) as { error?: unknown };
if (typeof parsed?.error === 'string') message = parsed.error;
} catch {
// ignore
}
throw new Error(message || `Failed to load media (${res.status})`);
}
const blob = await res.blob();
objectUrl = URL.createObjectURL(blob);
if (cancelled) return;
@@ -180,29 +160,9 @@ function ChatVideo({ messageId }: { messageId: string }) {
setError(null);
setUrl(null);
const res = await fetch(`${supabaseConfig.url}/functions/v1/admin-decrypt-media`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
apikey: supabaseConfig.anonKey,
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({ messageId }),
const blob = await adminBinaryRequest('/v1/admin/actions/decrypt-media', {
method: 'POST', body: { messageId },
});
if (!res.ok) {
const raw = await res.text().catch(() => '');
let message = raw;
try {
const parsed = JSON.parse(raw) as { error?: unknown };
if (typeof parsed?.error === 'string') message = parsed.error;
} catch {
// ignore
}
throw new Error(message || `Failed to load media (${res.status})`);
}
const blob = await res.blob();
objectUrl = URL.createObjectURL(blob);
if (cancelled) return;
@@ -289,18 +249,13 @@ function DecryptedMessageText({ message }: { message: Message }) {
const decrypt = async () => {
setIsDecrypting(true);
try {
const { data, error } = await supabase.functions.invoke('admin-decrypt-message', {
body: { messageId: message.id },
const data = await adminRequest<{ content?: string | null }>('/v1/admin/actions/decrypt-message', {
method: 'POST', body: { messageId: message.id },
});
if (cancelled) return;
if (error) {
setText('[Unable to decrypt]');
return;
}
setText((data as { content?: string | null } | null)?.content ?? null);
setText(data.content ?? null);
} catch (err) {
if (cancelled) return;
setText('[Unable to decrypt]');
@@ -344,7 +299,7 @@ export function MatchChatPage() {
setLoading(true);
try {
// Fetch user profile
const { data: userData } = await supabase
const { data: userData } = await adminData
.from('profiles')
.select('id, name, avatar_url, couple_id')
.eq('id', userId)
@@ -354,7 +309,7 @@ export function MatchChatPage() {
// Fetch partner
if (userData?.couple_id) {
const { data: partnerData } = await supabase
const { data: partnerData } = await adminData
.from('profiles')
.select('id, name, avatar_url')
.eq('couple_id', userData.couple_id)
@@ -367,7 +322,7 @@ export function MatchChatPage() {
}
// Fetch match with question
const { data: matchData } = await supabase
const { data: matchData } = await adminData
.from('matches')
.select(`
id, match_type,
@@ -382,7 +337,7 @@ export function MatchChatPage() {
const to = from + pageSize - 1;
// Fetch messages
const { data: messageData, error: messagesError, count } = await supabase
const { data: messageData, error: messagesError, count } = await adminData
.from('messages')
.select('*', { count: 'exact' })
.eq('match_id', matchId)
+33 -59
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useParams, Link } from 'react-router-dom';
import { supabase, supabaseConfig } from '@/config';
import { adminData, adminRequest, adminBinaryRequest } from '@/lib/adminApi';
import { useRealtimeSubscription } from '@/hooks/useRealtimeSubscription';
import { RealtimeStatusIndicator } from '@/components/RealtimeStatusIndicator';
import { useAuth, PERMISSION_KEYS } from '@/contexts/AuthContext';
@@ -193,16 +193,9 @@ function AdminDecryptedImage({ messageId, alt }: { messageId: string; alt: strin
const load = async () => {
try {
setError(null);
const res = await fetch(`${supabaseConfig.url}/functions/v1/admin-decrypt-media`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', apikey: supabaseConfig.anonKey, Authorization: `Bearer ${session.access_token}` },
body: JSON.stringify({ messageId }),
const blob = await adminBinaryRequest('/v1/admin/actions/decrypt-media', {
method: 'POST', body: { messageId },
});
if (!res.ok) {
const message = (await res.json().catch(() => ({})))?.error || `Failed to load media (${res.status})`;
throw new Error(message);
}
const blob = await res.blob();
objectUrl = URL.createObjectURL(blob);
if (!cancelled) setUrl(objectUrl);
} catch (err) {
@@ -249,16 +242,9 @@ function AdminDecryptedVideo({ messageId }: { messageId: string }) {
const load = async () => {
try {
setError(null);
const res = await fetch(`${supabaseConfig.url}/functions/v1/admin-decrypt-media`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', apikey: supabaseConfig.anonKey, Authorization: `Bearer ${session.access_token}` },
body: JSON.stringify({ messageId }),
const blob = await adminBinaryRequest('/v1/admin/actions/decrypt-media', {
method: 'POST', body: { messageId },
});
if (!res.ok) {
const message = (await res.json().catch(() => ({})))?.error || `Failed to load media (${res.status})`;
throw new Error(message);
}
const blob = await res.blob();
objectUrl = URL.createObjectURL(blob);
if (!cancelled) setUrl(objectUrl);
} catch (err) {
@@ -311,7 +297,7 @@ function LiveDrawCanvas({ coupleId }: { coupleId: string }) {
const fetchStrokes = async () => {
setLoading(true);
setError(null);
const { data, error: err } = await supabase
const { data, error: err } = await adminData
.from('live_draw_sessions')
.select('strokes')
.eq('couple_id', coupleId)
@@ -325,26 +311,14 @@ function LiveDrawCanvas({ coupleId }: { coupleId: string }) {
setStrokes((data?.strokes as StrokeSegment[]) || []);
setLoading(false);
};
fetchStrokes();
// Subscribe to real-time updates
const channel = supabase
.channel(`admin-livedraw-${coupleId}`)
.on('postgres_changes', {
event: '*',
schema: 'public',
table: 'live_draw_sessions',
filter: `couple_id=eq.${coupleId}`,
}, (payload: any) => {
if (payload.new?.strokes) {
setStrokes(payload.new.strokes as StrokeSegment[]);
}
})
.subscribe();
void fetchStrokes();
const interval = window.setInterval(() => {
if (document.visibilityState === 'visible') void fetchStrokes();
}, 5_000);
return () => {
cancelled = true;
supabase.removeChannel(channel);
window.clearInterval(interval);
};
}, [coupleId]);
@@ -485,13 +459,12 @@ export function UserDetailPage() {
}
expiresAt = date.toISOString();
}
// Use RPC function which handles permissions internally
const { error } = await supabase.rpc('admin_gift_premium', {
target_user_id: userId,
expires_at_param: expiresAt,
const days = expiresAt === null ? null : Math.max(1, Math.ceil((new Date(expiresAt).getTime() - now.getTime()) / 86_400_000));
await adminRequest(`/v1/admin/users/${encodeURIComponent(userId)}/gift-premium`, {
method: 'POST', body: { days, reason: 'Granted from admin user detail' },
});
if (error) throw error;
const { data: updatedProfile } = await supabase.rpc('get_profile_with_auth_info', { user_id: userId }).single<Profile>();
const { users } = await adminRequest<{ users: Profile[] }>(`/v1/admin/users?userId=${encodeURIComponent(userId)}`);
const updatedProfile = users[0] ?? null;
if (updatedProfile) setProfile(updatedProfile);
setUpgradeOpen(false);
alert('User upgraded to premium successfully!');
@@ -507,11 +480,12 @@ export function UserDetailPage() {
if (!userId) return;
setLoading(true);
try {
const { data: profileData } = await supabase.rpc('get_profile_with_auth_info', { user_id: userId }).single<Profile>();
const { users } = await adminRequest<{ users: Profile[] }>(`/v1/admin/users?userId=${encodeURIComponent(userId)}`);
const profileData = users[0] ?? null;
setProfile(profileData);
// Fetch feature interests for the user
const { data: featureInterestsData } = await supabase
const { data: featureInterestsData } = await adminData
.from('feature_interests')
.select('id, feature_name, created_at')
.eq('user_id', userId)
@@ -519,11 +493,11 @@ export function UserDetailPage() {
setFeatureInterests((featureInterestsData || []) as FeatureInterest[]);
if (profileData?.couple_id) {
const { data: partnerData } = await supabase.from('profiles').select('id, name').eq('couple_id', profileData.couple_id).neq('id', userId).single();
const { data: partnerData } = await adminData.from('profiles').select('id, name').eq('couple_id', profileData.couple_id).neq('id', userId).single();
setPartner(partnerData);
// Fetch streak data
const { data: streakData } = await supabase
const { data: streakData } = await adminData
.from('couple_streaks')
.select('*')
.eq('couple_id', profileData.couple_id)
@@ -537,7 +511,7 @@ export function UserDetailPage() {
const responsesFrom = (responsesPage - 1) * responsesPageSize;
const responsesTo = responsesFrom + responsesPageSize - 1;
const { data: responseData, count: responsesCount, error: responsesError } = await supabase
const { data: responseData, count: responsesCount, error: responsesError } = await adminData
.from('responses')
.select('id, answer, response_data, created_at, question:questions(id, text, question_type, pack:question_packs(id, name))', { count: 'exact' })
.eq('user_id', userId)
@@ -553,7 +527,7 @@ export function UserDetailPage() {
const matchesFrom = (matchesPage - 1) * matchesPageSize;
const matchesTo = matchesFrom + matchesPageSize - 1;
const { data: matchData, count: matchesCount, error: matchesError } = await supabase
const { data: matchData, count: matchesCount, error: matchesError } = await adminData
.from('matches')
.select('id, match_type, is_new, created_at, question:questions(id, text)', { count: 'exact' })
.eq('couple_id', profileData.couple_id)
@@ -566,7 +540,7 @@ export function UserDetailPage() {
const matchIds = (matchData || []).map(m => m.id);
if (matchIds.length > 0) {
const { data: messages } = await supabase.from('messages').select('match_id').in('match_id', matchIds);
const { data: messages } = await adminData.from('messages').select('match_id').in('match_id', matchIds);
const messageCounts: Record<string, number> = {};
messages?.forEach(m => { messageCounts[m.match_id] = (messageCounts[m.match_id] || 0) + 1; });
setMatches((matchData || []).map(m => ({ ...m, message_count: messageCounts[m.id] || 0 })) as unknown as Match[]);
@@ -574,7 +548,7 @@ export function UserDetailPage() {
setMatches([]);
}
const { data: allMatchIdsData } = await supabase
const { data: allMatchIdsData } = await adminData
.from('matches')
.select('id')
.eq('couple_id', profileData.couple_id);
@@ -584,7 +558,7 @@ export function UserDetailPage() {
const mediaFrom = (mediaPage - 1) * mediaPageSize;
const mediaTo = mediaFrom + mediaPageSize - 1;
const { data: mediaMessagesData, error: mediaError, count: mediaCount } = await supabase
const { data: mediaMessagesData, error: mediaError, count: mediaCount } = await adminData
.from('messages')
.select('id, user_id, media_path, media_type, version, created_at, keys_metadata, match_id', { count: 'exact' })
.in('match_id', allMatchIds)
@@ -605,7 +579,7 @@ export function UserDetailPage() {
setMediaTotal(0);
}
// Fetch enabled packs for the couple
const { data: enabledPacksData, error: packsError } = await supabase
const { data: enabledPacksData, error: packsError } = await adminData
.from('couple_packs')
.select(`
pack_id,
@@ -634,17 +608,17 @@ export function UserDetailPage() {
// Fetch outstanding questions (partner answered, user hasn't)
// Use partner from state (set earlier in the first couple_id block)
const partnerProfile = partner || (await supabase.from('profiles').select('id, name').eq('couple_id', profileData.couple_id).neq('id', userId).maybeSingle()).data;
const partnerProfile = partner || (await adminData.from('profiles').select('id, name').eq('couple_id', profileData.couple_id).neq('id', userId).maybeSingle()).data;
if (partnerProfile) {
// Get question IDs user has already answered
const { data: userResponseIds } = await supabase
const { data: userResponseIds } = await adminData
.from('responses')
.select('question_id')
.eq('user_id', userId);
const answeredIds = new Set((userResponseIds || []).map((r: any) => r.question_id));
// Get all partner responses in this couple
const { data: partnerResponses } = await supabase
const { data: partnerResponses } = await adminData
.from('responses')
.select(`
id,
@@ -663,7 +637,7 @@ export function UserDetailPage() {
if (unansweredQuestionIds.length > 0) {
// Fetch question details (no pack filter — admin sees all)
const { data: questionDetails } = await supabase
const { data: questionDetails } = await adminData
.from('questions')
.select('id, text, intensity, question_type, pack:question_packs(id, name)')
.in('id', unansweredQuestionIds);
@@ -701,7 +675,7 @@ export function UserDetailPage() {
}
// Calculate gap status
const { data: appConfig } = await supabase
const { data: appConfig } = await adminData
.from('app_config')
.select('answer_gap_threshold')
.limit(1)
@@ -713,7 +687,7 @@ export function UserDetailPage() {
if (threshold > 0) {
// Count questions user answered that partner hasn't
const partnerAllAnswered = new Set((partnerResponses || []).map((r: any) => r.question_id));
const { data: userResponses } = await supabase
const { data: userResponses } = await adminData
.from('responses')
.select('question_id')
.eq('user_id', userId)
+3 -20
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { supabase } from '@/config';
import { adminRequest } from '@/lib/adminApi';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
@@ -55,24 +55,7 @@ export function UsersPage() {
setLoading(true);
try {
// Fetch profiles with auth info (includes last_sign_in_at)
const { data: profilesDataRaw, error } = await supabase
.rpc('get_profiles_with_auth_info');
if (error) throw error;
const profilesData = (profilesDataRaw || []) as Profile[];
// Fetch storage usage per user from storage.objects
const { data: storageData } = await supabase
.rpc('get_user_storage_usage');
// Create a map of user_id -> storage_bytes
const storageMap: Record<string, number> = {};
if (storageData) {
storageData.forEach((row: { owner: string; total_bytes: number }) => {
storageMap[row.owner] = row.total_bytes;
});
}
const { users: profilesData } = await adminRequest<{ users: Profile[] }>('/v1/admin/users');
// Build a map of couple_id -> users with premium in that couple
const couplePartners: Record<string, { id: string; is_premium: boolean }[]> = {};
@@ -100,7 +83,7 @@ export function UsersPage() {
}
return {
...profile,
storage_bytes: storageMap[profile.id] || 0,
storage_bytes: Number(profile.storage_bytes || 0),
partner_is_premium: partnerIsPremium,
partner_count: partnerCount,
};
+10 -10
View File
@@ -1,5 +1,5 @@
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
// =============================================================================
// Types
@@ -32,7 +32,7 @@ export interface CategoryFormData {
*/
export async function fetchCategories(): Promise<Category[]> {
// Fetch categories
const { data: categories, error: catError } = await supabase
const { data: categories, error: catError } = await adminData
.from('categories')
.select('*')
.order('sort_order', { ascending: true });
@@ -40,7 +40,7 @@ export async function fetchCategories(): Promise<Category[]> {
if (catError) throw catError;
// Fetch pack counts per category
const { data: packs } = await supabase
const { data: packs } = await adminData
.from('question_packs')
.select('category_id');
@@ -61,7 +61,7 @@ export async function fetchCategories(): Promise<Category[]> {
* Fetch a single category by ID
*/
export async function fetchCategoryById(id: string): Promise<Category | null> {
const { data, error } = await supabase
const { data, error } = await adminData
.from('categories')
.select('*')
.eq('id', id)
@@ -82,7 +82,7 @@ export async function createCategory(
data: CategoryFormData,
sortOrder: number
): Promise<Category> {
const { data: created, error } = await auditedSupabase.insert('categories', {
const { data: created, error } = await auditedAdminData.insert('categories', {
name: data.name,
description: data.description || null,
icon: data.icon || null,
@@ -102,7 +102,7 @@ export async function updateCategory(
id: string,
data: Partial<CategoryFormData>
): Promise<void> {
const { error } = await auditedSupabase.update('categories', id, {
const { error } = await auditedAdminData.update('categories', id, {
name: data.name,
description: data.description || null,
icon: data.icon || null,
@@ -116,7 +116,7 @@ export async function updateCategory(
* Delete a category
*/
export async function deleteCategory(id: string): Promise<void> {
const { error } = await auditedSupabase.delete('categories', id);
const { error } = await auditedAdminData.delete('categories', id);
if (error) throw error;
}
@@ -130,7 +130,7 @@ export async function swapCategorySortOrder(
category2Order: number
): Promise<void> {
await Promise.all([
auditedSupabase.update('categories', category1Id, { sort_order: category2Order }),
auditedSupabase.update('categories', category2Id, { sort_order: category1Order }),
auditedAdminData.update('categories', category1Id, { sort_order: category2Order }),
auditedAdminData.update('categories', category2Id, { sort_order: category1Order }),
]);
}
@@ -0,0 +1,46 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { CONTENT_STATUS_LABELS } from '@/lib/contentReviewStatus';
const { update } = vi.hoisted(() => ({ update: vi.fn() }));
vi.mock('@/hooks/useAuditedAdminData', () => ({
auditedAdminData: { update },
}));
import { updateContentReviewStatus } from './contentReviews';
describe('catalogue review labels', () => {
it('uses archive language for reversible removals', () => {
expect(CONTENT_STATUS_LABELS).toEqual({
unreviewed: 'Needs review',
allowed: 'Allowed',
archived: 'Archived',
});
});
beforeEach(() => {
update.mockReset();
update.mockResolvedValue({ data: null, error: null });
});
it('writes a trimmed, audited review decision', async () => {
await updateContentReviewStatus(
'question_packs',
'pack-1',
'archived',
' Store compliance review ',
);
expect(update).toHaveBeenCalledWith('question_packs', 'pack-1', {
content_status: 'archived',
content_review_reason: 'Store compliance review',
});
});
it('rejects an empty reason before writing', async () => {
await expect(
updateContentReviewStatus('questions', 'question-1', 'allowed', ' '),
).rejects.toThrow('A review reason is required');
expect(update).not.toHaveBeenCalled();
});
});
+29
View File
@@ -0,0 +1,29 @@
import type { ContentReviewStatus } from '@sauci/shared';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
export { CONTENT_STATUS_LABELS } from '@/lib/contentReviewStatus';
export type ReviewableContentTable =
| 'categories'
| 'question_packs'
| 'questions'
| 'dare_packs'
| 'dares';
export async function updateContentReviewStatus(
table: ReviewableContentTable,
id: string,
status: ContentReviewStatus,
reason: string,
): Promise<void> {
const normalizedReason = reason.trim();
if (!normalizedReason) {
throw new Error('A review reason is required');
}
const { error } = await auditedAdminData.update(table, id, {
content_status: status,
content_review_reason: normalizedReason,
});
if (error) throw error;
}
+15 -15
View File
@@ -1,5 +1,5 @@
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
// =============================================================================
// Types
@@ -42,7 +42,7 @@ export interface Topic {
* Fetch all packs for a category with question counts
*/
export async function fetchPacksForCategory(categoryId: string): Promise<Pack[]> {
const { data: packs, error: packError } = await supabase
const { data: packs, error: packError } = await adminData
.from('question_packs')
.select('*, category:categories(name)')
.eq('category_id', categoryId)
@@ -51,7 +51,7 @@ export async function fetchPacksForCategory(categoryId: string): Promise<Pack[]>
if (packError) throw packError;
// Get question counts per pack
const { data: questions } = await supabase
const { data: questions } = await adminData
.from('questions')
.select('pack_id');
@@ -72,7 +72,7 @@ export async function fetchPacksForCategory(categoryId: string): Promise<Pack[]>
* Fetch a single pack by ID
*/
export async function fetchPackById(id: string): Promise<Pack | null> {
const { data, error } = await supabase
const { data, error } = await adminData
.from('question_packs')
.select('*, category:categories(name)')
.eq('id', id)
@@ -86,7 +86,7 @@ export async function fetchPackById(id: string): Promise<Pack | null> {
* Fetch all topics
*/
export async function fetchAllTopics(): Promise<Topic[]> {
const { data, error } = await supabase
const { data, error } = await adminData
.from('topics')
.select('*')
.order('name');
@@ -99,7 +99,7 @@ export async function fetchAllTopics(): Promise<Topic[]> {
* Fetch topic IDs for a specific pack
*/
export async function fetchPackTopicIds(packId: string): Promise<Set<string>> {
const { data, error } = await supabase
const { data, error } = await adminData
.from('pack_topics')
.select('topic_id')
.eq('pack_id', packId);
@@ -120,7 +120,7 @@ export async function createPack(
data: PackFormData,
sortOrder: number
): Promise<Pack> {
const { data: created, error } = await auditedSupabase.insert('question_packs', {
const { data: created, error } = await auditedAdminData.insert('question_packs', {
name: data.name,
description: data.description || null,
icon: data.icon || null,
@@ -143,7 +143,7 @@ export async function updatePack(
id: string,
data: Partial<PackFormData>
): Promise<void> {
const { error } = await auditedSupabase.update('question_packs', id, {
const { error } = await auditedAdminData.update('question_packs', id, {
name: data.name,
description: data.description || null,
icon: data.icon || null,
@@ -159,7 +159,7 @@ export async function updatePack(
* Delete a pack
*/
export async function deletePack(id: string): Promise<void> {
const { error } = await auditedSupabase.delete('question_packs', id);
const { error } = await auditedAdminData.delete('question_packs', id);
if (error) throw error;
}
@@ -173,8 +173,8 @@ export async function swapPackSortOrder(
pack2Order: number
): Promise<void> {
await Promise.all([
auditedSupabase.update('question_packs', pack1Id, { sort_order: pack2Order }),
auditedSupabase.update('question_packs', pack2Id, { sort_order: pack1Order }),
auditedAdminData.update('question_packs', pack1Id, { sort_order: pack2Order }),
auditedAdminData.update('question_packs', pack2Id, { sort_order: pack1Order }),
]);
}
@@ -190,11 +190,11 @@ export async function updatePackTopics(
topicIds: string[]
): Promise<void> {
// Delete existing topics
await supabase.from('pack_topics').delete().eq('pack_id', packId);
await adminData.from('pack_topics').delete().eq('pack_id', packId);
// Insert new topics
if (topicIds.length > 0) {
const { error } = await supabase.from('pack_topics').insert(
const { error } = await adminData.from('pack_topics').insert(
topicIds.map(topicId => ({ pack_id: packId, topic_id: topicId }))
);
if (error) throw error;
@@ -205,7 +205,7 @@ export async function updatePackTopics(
* Create a new topic
*/
export async function createTopic(name: string): Promise<Topic> {
const { data, error } = await supabase
const { data, error } = await adminData
.from('topics')
.insert({ name })
.select()
+15 -15
View File
@@ -1,5 +1,5 @@
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { adminData } from '@/lib/adminApi';
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
// =============================================================================
// Types
@@ -29,7 +29,7 @@ export interface QuestionFormData {
* Fetch all questions for a pack (excludes soft-deleted by default)
*/
export async function fetchQuestionsForPack(packId: string, includeDeleted = false): Promise<Question[]> {
let query = supabase
let query = adminData
.from('questions')
.select('*')
.eq('pack_id', packId)
@@ -49,7 +49,7 @@ export async function fetchQuestionsForPack(packId: string, includeDeleted = fal
* Fetch a single question by ID
*/
export async function fetchQuestionById(id: string): Promise<Question | null> {
const { data, error } = await supabase
const { data, error } = await adminData
.from('questions')
.select('*')
.eq('id', id)
@@ -63,7 +63,7 @@ export async function fetchQuestionById(id: string): Promise<Question | null> {
* Fetch question count for a pack (excludes soft-deleted)
*/
export async function fetchQuestionCount(packId: string): Promise<number> {
const { count, error } = await supabase
const { count, error } = await adminData
.from('questions')
.select('*', { count: 'exact', head: true })
.eq('pack_id', packId)
@@ -84,7 +84,7 @@ export async function createQuestion(
packId: string,
data: QuestionFormData
): Promise<Question> {
const { data: created, error } = await auditedSupabase.insert('questions', {
const { data: created, error } = await auditedAdminData.insert('questions', {
text: data.text,
partner_text: data.partner_text || null,
intensity: data.intensity,
@@ -103,7 +103,7 @@ export async function updateQuestion(
id: string,
data: Partial<QuestionFormData>
): Promise<void> {
const { error } = await auditedSupabase.update('questions', id, {
const { error } = await auditedAdminData.update('questions', id, {
text: data.text,
partner_text: data.partner_text || null,
intensity: data.intensity,
@@ -116,7 +116,7 @@ export async function updateQuestion(
* Soft delete a question (sets deleted_at timestamp)
*/
export async function deleteQuestion(id: string): Promise<void> {
const { error } = await auditedSupabase.update('questions', id, {
const { error } = await auditedAdminData.update('questions', id, {
deleted_at: new Date().toISOString(),
});
if (error) throw error;
@@ -127,7 +127,7 @@ export async function deleteQuestion(id: string): Promise<void> {
*/
export async function deleteQuestions(ids: string[]): Promise<void> {
await Promise.all(
ids.map(id => auditedSupabase.update('questions', id, {
ids.map(id => auditedAdminData.update('questions', id, {
deleted_at: new Date().toISOString(),
}))
);
@@ -137,7 +137,7 @@ export async function deleteQuestions(ids: string[]): Promise<void> {
* Restore a soft-deleted question
*/
export async function restoreQuestion(id: string): Promise<void> {
const { error } = await auditedSupabase.update('questions', id, {
const { error } = await auditedAdminData.update('questions', id, {
deleted_at: null,
});
if (error) throw error;
@@ -169,7 +169,7 @@ export async function bulkCreateQuestions(
// Insert standalone questions first
for (const q of standaloneQuestions) {
const { data, error } = await auditedSupabase.insert('questions', {
const { data, error } = await auditedAdminData.insert('questions', {
pack_id: packId,
text: q.text,
partner_text: q.partner_text || null,
@@ -186,7 +186,7 @@ export async function bulkCreateQuestions(
if (pair.length >= 2) {
// First question is primary
const primary = pair[0];
const { data: primaryData, error: primaryError } = await auditedSupabase.insert('questions', {
const { data: primaryData, error: primaryError } = await auditedAdminData.insert('questions', {
pack_id: packId,
text: primary.text,
partner_text: primary.partner_text || null,
@@ -201,7 +201,7 @@ export async function bulkCreateQuestions(
// Second question is inverse
const inverse = pair[1];
const { data: inverseData, error: inverseError } = await auditedSupabase.insert('questions', {
const { data: inverseData, error: inverseError } = await auditedAdminData.insert('questions', {
pack_id: packId,
text: inverse.text,
partner_text: inverse.partner_text || null,
@@ -216,7 +216,7 @@ export async function bulkCreateQuestions(
// Handle any additional questions in the pair
for (let i = 2; i < pair.length; i++) {
const extra = pair[i];
const { data, error } = await auditedSupabase.insert('questions', {
const { data, error } = await auditedAdminData.insert('questions', {
pack_id: packId,
text: extra.text,
partner_text: extra.partner_text || null,
@@ -228,7 +228,7 @@ export async function bulkCreateQuestions(
}
} else if (pair.length === 1) {
// Single question with pair_id but no pair
const { data, error } = await auditedSupabase.insert('questions', {
const { data, error } = await auditedAdminData.insert('questions', {
pack_id: packId,
text: pair[0].text,
partner_text: pair[0].partner_text || null,
+6 -6
View File
@@ -1,4 +1,4 @@
import { supabase } from '@/config';
import { adminData } from '@/lib/adminApi';
// =============================================================================
// Types
@@ -25,10 +25,10 @@ export async function fetchDashboardStats(): Promise<DashboardStats> {
{ count: questions },
{ count: users },
] = await Promise.all([
supabase.from('categories').select('*', { count: 'exact', head: true }),
supabase.from('question_packs').select('*', { count: 'exact', head: true }),
supabase.from('questions').select('*', { count: 'exact', head: true }),
supabase.from('profiles').select('*', { count: 'exact', head: true }),
adminData.from('categories').select('*', { count: 'exact', head: true }),
adminData.from('question_packs').select('*', { count: 'exact', head: true }),
adminData.from('questions').select('*', { count: 'exact', head: true }),
adminData.from('profiles').select('*', { count: 'exact', head: true }),
]);
return {
@@ -43,7 +43,7 @@ export async function fetchDashboardStats(): Promise<DashboardStats> {
* Fetch count for a specific table
*/
export async function fetchTableCount(tableName: string): Promise<number> {
const { count, error } = await supabase
const { count, error } = await adminData
.from(tableName)
.select('*', { count: 'exact', head: true });
+1
View File
@@ -3,6 +3,7 @@
interface ImportMetaEnv {
readonly VITE_SUPABASE_URL: string;
readonly VITE_SUPABASE_ANON_KEY: string;
readonly VITE_API_URL: string;
readonly VITE_OPENAI_API_KEY: string;
}
+5
View File
@@ -0,0 +1,5 @@
node_modules
dist
.env
coverage
test
+40
View File
@@ -0,0 +1,40 @@
PORT=3003
DATABASE_URL=postgresql://sauci:sauci_local_only@127.0.0.1:54320/sauci
SUPABASE_AUTH_URL=https://your-project.supabase.co
SUPABASE_AUTH_AUDIENCE=authenticated
# Optional connection-pool bounds. The API process opens one pool and shares it
# across every repository, so these are the process-wide limits, not per-domain
# ones. The worker has its own separately bounded process pool. Raising either
# maximum raises the server connections this instance can hold; keep the total
# across instances inside the database's own limit.
# DATABASE_POOL_MAX=10
# DATABASE_POOL_IDLE_TIMEOUT_MS=30000
# DATABASE_POOL_CONNECTION_TIMEOUT_MS=10000
# Server-only hosted Auth Admin credential. Used for account deletion and for
# enriching admin user lists; it is never exposed to the browser or used as a
# Supabase database client.
# SUPABASE_AUTH_SERVICE_ROLE_KEY=
# Optional overrides. The issuer defaults to <SUPABASE_AUTH_URL>/auth/v1 and
# the JWKS endpoint defaults to <SUPABASE_AUTH_URL>/auth/v1/.well-known/jwks.json.
# SUPABASE_AUTH_ISSUER=
# SUPABASE_AUTH_JWKS_URL=
# Test-only. Startup fails if this is set outside NODE_ENV=test.
# AUTH_TEST_JWKS={"keys":[]}
# Optional stable credential for non-browser admin clients such as MCP. MCP
# receives the token as SAUCI_ADMIN_API_TOKEN; it does not receive the user ID.
# Both values are required together. The user ID must belong to an active,
# least-privilege admin_users row; generate a random token of at least 32 chars.
# ADMIN_API_SERVICE_TOKEN=
# ADMIN_API_SERVICE_USER_ID=00000000-0000-4000-8000-000000000002
# Optional admin review decryption. Keep the private JWK server-side only.
# ADMIN_PRIVATE_KEY_JWK=
# Optional local fixture identity used by `npm run db:seed -w @sauci/api`.
# SEED_USER_ID=00000000-0000-4000-8000-000000000001
# SEED_USER_EMAIL=local@sauci.test
+28
View File
@@ -0,0 +1,28 @@
FROM node:20-bookworm-slim AS build
WORKDIR /workspace
COPY package.json package-lock.json ./
COPY apps/api/package.json ./apps/api/package.json
COPY packages/shared/package.json ./packages/shared/package.json
RUN --mount=type=cache,target=/root/.npm \
npm ci --workspace @sauci/api --include-workspace-root=false --ignore-scripts
COPY apps/api ./apps/api
COPY packages/shared ./packages/shared
RUN npm run build --workspace @sauci/api
RUN npm prune --omit=dev --workspace @sauci/api --include-workspace-root=false --ignore-scripts
FROM node:20-bookworm-slim AS runtime
ENV NODE_ENV=production PORT=3003
WORKDIR /app
RUN mkdir -p /data/media && chown node:node /data/media
COPY --from=build /workspace/node_modules ./node_modules
# npm may place 0.x dependency upgrades in the workspace-local tree. Overlay
# that pruned tree so runtime resolution matches the workspace lockfile.
COPY --from=build /workspace/apps/api/node_modules ./node_modules
COPY --from=build --chown=node:node /workspace/apps/api/package.json ./package.json
COPY --from=build --chown=node:node /workspace/apps/api/dist ./dist
COPY --from=build --chown=node:node /workspace/apps/api/drizzle ./drizzle
USER node
EXPOSE 3003
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 \
CMD ["node", "-e", "fetch('http://127.0.0.1:3003/health/live').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
CMD ["node", "dist/index.js"]
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from 'drizzle-kit';
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is required for database migrations');
}
export default defineConfig({
dialect: 'postgresql',
schema: './src/db/all-schema.ts',
out: './drizzle',
dbCredentials: { url: process.env.DATABASE_URL },
strict: true,
verbose: true,
});
@@ -0,0 +1,35 @@
CREATE TABLE "profiles" (
"id" uuid PRIMARY KEY NOT NULL,
"name" text,
"email" text,
"avatar_url" text,
"push_token" text,
"is_premium" boolean DEFAULT false NOT NULL,
"couple_id" uuid,
"gender" text,
"show_explicit_content" boolean DEFAULT true NOT NULL,
"max_intensity" integer DEFAULT 5 NOT NULL,
"public_key_jwk" jsonb,
"hide_nsfw" boolean DEFAULT false NOT NULL,
"onboarding_completed" boolean DEFAULT false NOT NULL,
"onboarding_version" integer DEFAULT 0 NOT NULL,
"auth_synced_at" timestamp with time zone DEFAULT now() NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "profiles_gender_check" CHECK ("gender" IS NULL OR "gender" IN ('male', 'female', 'non-binary', 'prefer-not-to-say')),
CONSTRAINT "profiles_max_intensity_check" CHECK ("max_intensity" BETWEEN 1 AND 5)
);
--> statement-breakpoint
CREATE INDEX "profiles_couple_id_idx" ON "profiles" USING btree ("couple_id");
--> statement-breakpoint
CREATE TABLE "feature_interests" (
"user_id" uuid NOT NULL,
"feature" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "feature_interests_user_id_feature_pk" PRIMARY KEY("user_id", "feature")
);
--> statement-breakpoint
ALTER TABLE "feature_interests" ADD CONSTRAINT "feature_interests_user_id_profiles_id_fk"
FOREIGN KEY ("user_id") REFERENCES "profiles"("id") ON DELETE cascade;
--> statement-breakpoint
CREATE INDEX "feature_interests_feature_idx" ON "feature_interests" USING btree ("feature");
+14
View File
@@ -0,0 +1,14 @@
CREATE TABLE IF NOT EXISTS "couples" (
"id" uuid PRIMARY KEY NOT NULL,
"invite_code" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "couples_invite_code_unique" UNIQUE("invite_code"),
CONSTRAINT "couples_invite_code_format" CHECK ("invite_code" ~ '^[A-Z0-9]{8}$')
);
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "profiles" ADD CONSTRAINT "profiles_couple_id_couples_id_fk"
FOREIGN KEY ("couple_id") REFERENCES "couples"("id") ON DELETE SET NULL;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
@@ -0,0 +1,60 @@
CREATE TABLE IF NOT EXISTS "categories" (
"id" uuid PRIMARY KEY,
"name" text NOT NULL,
"description" text,
"icon" text,
"color" text,
"sort_order" integer NOT NULL DEFAULT 0,
"is_public" boolean NOT NULL DEFAULT true,
"created_at" timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "question_packs" (
"id" uuid PRIMARY KEY,
"name" text NOT NULL,
"description" text,
"icon" text,
"is_premium" boolean NOT NULL DEFAULT false,
"is_public" boolean NOT NULL DEFAULT true,
"is_explicit" boolean NOT NULL DEFAULT false,
"min_intensity" integer,
"max_intensity" integer,
"avg_intensity" integer,
"sort_order" integer NOT NULL DEFAULT 0,
"category_id" uuid REFERENCES "categories"("id") ON DELETE SET NULL,
"created_at" timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "question_packs_category_id_idx" ON "question_packs" ("category_id");
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "questions" (
"id" uuid PRIMARY KEY,
"pack_id" uuid NOT NULL REFERENCES "question_packs"("id") ON DELETE CASCADE,
"text" text NOT NULL,
"partner_text" text,
"intensity" integer NOT NULL DEFAULT 1 CHECK ("intensity" BETWEEN 1 AND 5),
"created_at" timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "questions_pack_id_idx" ON "questions" ("pack_id");
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "responses" (
"id" uuid PRIMARY KEY,
"user_id" uuid NOT NULL REFERENCES "profiles"("id") ON DELETE CASCADE,
"question_id" uuid NOT NULL REFERENCES "questions"("id") ON DELETE CASCADE,
"couple_id" uuid NOT NULL REFERENCES "couples"("id") ON DELETE CASCADE,
"answer" text NOT NULL CHECK ("answer" IN ('yes', 'no', 'maybe')),
"response_data" jsonb,
"created_at" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("user_id", "question_id")
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "responses_user_id_idx" ON "responses" ("user_id");
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "couple_packs" (
"couple_id" uuid NOT NULL REFERENCES "couples"("id") ON DELETE CASCADE,
"pack_id" uuid NOT NULL REFERENCES "question_packs"("id") ON DELETE CASCADE,
"enabled" boolean NOT NULL DEFAULT true,
"created_at" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("couple_id", "pack_id")
);
+71
View File
@@ -0,0 +1,71 @@
ALTER TABLE "questions"
ADD COLUMN IF NOT EXISTS "allowed_couple_genders" text[],
ADD COLUMN IF NOT EXISTS "target_user_genders" text[],
ADD COLUMN IF NOT EXISTS "question_type" text NOT NULL DEFAULT 'swipe',
ADD COLUMN IF NOT EXISTS "config" jsonb NOT NULL DEFAULT '{}'::jsonb,
ADD COLUMN IF NOT EXISTS "deleted_at" timestamptz;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "questions" ADD CONSTRAINT "questions_type_check"
CHECK ("question_type" IN ('swipe', 'text_answer', 'audio', 'photo', 'who_likely'));
EXCEPTION WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "app_config" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"answer_gap_threshold" integer NOT NULL DEFAULT 10 CHECK ("answer_gap_threshold" >= 0),
"daily_response_limit" integer NOT NULL DEFAULT 0 CHECK ("daily_response_limit" >= 0),
"couple_intensity_gate_enabled" boolean NOT NULL DEFAULT false,
"updated_at" timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE UNIQUE INDEX IF NOT EXISTS "app_config_singleton_idx" ON "app_config" ((true));
--> statement-breakpoint
INSERT INTO "app_config" ("id") VALUES (gen_random_uuid()) ON CONFLICT DO NOTHING;
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "matches" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"couple_id" uuid NOT NULL REFERENCES "couples"("id") ON DELETE CASCADE,
"question_id" uuid NOT NULL REFERENCES "questions"("id") ON DELETE CASCADE,
"match_type" text NOT NULL CHECK ("match_type" IN ('yes_yes', 'yes_maybe', 'maybe_maybe', 'both_answered')),
"is_new" boolean NOT NULL DEFAULT true,
"response_summary" jsonb,
"created_at" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("couple_id", "question_id")
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "matches_couple_created_idx" ON "matches" ("couple_id", "created_at" DESC);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "messages" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"match_id" uuid NOT NULL REFERENCES "matches"("id") ON DELETE CASCADE,
"user_id" uuid NOT NULL REFERENCES "profiles"("id") ON DELETE CASCADE,
"content" text,
"created_at" timestamptz NOT NULL DEFAULT now(),
"read_at" timestamptz
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "match_archives" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"match_id" uuid NOT NULL REFERENCES "matches"("id") ON DELETE CASCADE,
"user_id" uuid NOT NULL REFERENCES "profiles"("id") ON DELETE CASCADE,
"archived_at" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("match_id", "user_id")
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "match_archives_user_idx" ON "match_archives" ("user_id", "match_id");
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "couple_streaks" (
"couple_id" uuid PRIMARY KEY REFERENCES "couples"("id") ON DELETE CASCADE,
"current_streak" integer NOT NULL DEFAULT 0,
"longest_streak" integer NOT NULL DEFAULT 0,
"last_active_date" date,
"last_completed_date" date,
"user1_answered_today" boolean NOT NULL DEFAULT false,
"user2_answered_today" boolean NOT NULL DEFAULT false,
"streak_celebrated_at" integer NOT NULL DEFAULT 0,
"created_at" timestamptz NOT NULL DEFAULT now(),
"updated_at" timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "responses_couple_question_idx" ON "responses" ("couple_id", "question_id");
+85
View File
@@ -0,0 +1,85 @@
CREATE TABLE IF NOT EXISTS "messages" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"match_id" uuid NOT NULL REFERENCES "matches"("id") ON DELETE CASCADE,
"user_id" uuid NOT NULL REFERENCES "profiles"("id") ON DELETE CASCADE,
"content" text,
"created_at" timestamptz NOT NULL DEFAULT now(),
"read_at" timestamptz,
"delivered_at" timestamptz,
"deleted_at" timestamptz,
"media_path" text,
"media_type" text CHECK ("media_type" IS NULL OR "media_type" IN ('image', 'video')),
"media_expires_at" timestamptz,
"media_expired" boolean NOT NULL DEFAULT false,
"media_viewed_at" timestamptz,
"version" integer NOT NULL DEFAULT 1,
"encrypted_content" text,
"encryption_iv" text,
"keys_metadata" jsonb,
"moderation_status" text,
"flag_reason" text,
"category" text,
CONSTRAINT "messages_content_or_media" CHECK (
"content" IS NOT NULL OR "media_path" IS NOT NULL OR "encrypted_content" IS NOT NULL
)
);
--> statement-breakpoint
ALTER TABLE "messages"
ADD COLUMN IF NOT EXISTS "delivered_at" timestamptz,
ADD COLUMN IF NOT EXISTS "deleted_at" timestamptz,
ADD COLUMN IF NOT EXISTS "media_path" text,
ADD COLUMN IF NOT EXISTS "media_type" text,
ADD COLUMN IF NOT EXISTS "media_expires_at" timestamptz,
ADD COLUMN IF NOT EXISTS "media_expired" boolean NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS "media_viewed_at" timestamptz,
ADD COLUMN IF NOT EXISTS "version" integer NOT NULL DEFAULT 1,
ADD COLUMN IF NOT EXISTS "encrypted_content" text,
ADD COLUMN IF NOT EXISTS "encryption_iv" text,
ADD COLUMN IF NOT EXISTS "keys_metadata" jsonb,
ADD COLUMN IF NOT EXISTS "moderation_status" text,
ADD COLUMN IF NOT EXISTS "flag_reason" text,
ADD COLUMN IF NOT EXISTS "category" text;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "messages" ADD CONSTRAINT "messages_media_type_check"
CHECK ("media_type" IS NULL OR "media_type" IN ('image', 'video'));
EXCEPTION WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "messages" ADD CONSTRAINT "messages_content_or_media"
CHECK ("content" IS NOT NULL OR "media_path" IS NOT NULL OR "encrypted_content" IS NOT NULL);
EXCEPTION WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "messages_match_created_idx" ON "messages" ("match_id", "created_at" DESC);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "messages_unread_idx" ON "messages" ("match_id", "user_id") WHERE "read_at" IS NULL;
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "message_deletions" (
"message_id" uuid NOT NULL REFERENCES "messages"("id") ON DELETE CASCADE,
"user_id" uuid NOT NULL REFERENCES "profiles"("id") ON DELETE CASCADE,
"deleted_at" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("message_id", "user_id")
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "message_reports" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"message_id" uuid NOT NULL REFERENCES "messages"("id") ON DELETE CASCADE,
"reporter_id" uuid NOT NULL REFERENCES "profiles"("id") ON DELETE CASCADE,
"reason" text NOT NULL CHECK ("reason" IN ('harassment', 'spam', 'inappropriate_content', 'other')),
"status" text NOT NULL DEFAULT 'pending' CHECK ("status" IN ('pending', 'reviewed', 'dismissed')),
"created_at" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("message_id", "reporter_id")
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "message_reports_status_idx" ON "message_reports" ("status", "created_at" DESC);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "chat_typing_states" (
"match_id" uuid NOT NULL REFERENCES "matches"("id") ON DELETE CASCADE,
"user_id" uuid NOT NULL REFERENCES "profiles"("id") ON DELETE CASCADE,
"expires_at" timestamptz NOT NULL,
PRIMARY KEY ("match_id", "user_id")
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "chat_typing_expires_idx" ON "chat_typing_states" ("expires_at");
@@ -0,0 +1,35 @@
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS usage_reason text,
ADD COLUMN IF NOT EXISTS last_active_at timestamptz;
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS notification_preferences (
user_id uuid PRIMARY KEY REFERENCES profiles(id) ON DELETE CASCADE,
matches_enabled boolean NOT NULL DEFAULT true,
messages_enabled boolean NOT NULL DEFAULT true,
partner_activity_enabled boolean NOT NULL DEFAULT true,
nudges_enabled boolean NOT NULL DEFAULT true,
pack_changes_enabled boolean NOT NULL DEFAULT true,
new_packs_enabled boolean NOT NULL DEFAULT true,
streak_milestones_enabled boolean NOT NULL DEFAULT true,
weekly_summary_enabled boolean NOT NULL DEFAULT true,
unpaired_reminders_enabled boolean NOT NULL DEFAULT true,
catchup_reminders_enabled boolean NOT NULL DEFAULT true,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS feedback (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
type text NOT NULL CHECK (type IN ('bug', 'feature_request', 'general', 'question')),
title text NOT NULL,
description text NOT NULL,
device_info jsonb NOT NULL DEFAULT '{}'::jsonb,
status text NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'reviewed', 'in_progress', 'resolved', 'closed')),
question_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS feedback_user_id_idx ON feedback(user_id);
+35
View File
@@ -0,0 +1,35 @@
CREATE TABLE IF NOT EXISTS media_objects (
id uuid PRIMARY KEY,
owner_id uuid NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
couple_id uuid REFERENCES couples(id) ON DELETE CASCADE,
kind text NOT NULL CHECK (kind IN ('avatar', 'response', 'chat', 'feedback')),
storage_key text NOT NULL UNIQUE,
mime_type text NOT NULL,
byte_size integer NOT NULL CHECK (byte_size > 0),
question_id uuid REFERENCES questions(id) ON DELETE CASCADE,
match_id uuid REFERENCES matches(id) ON DELETE CASCADE,
expires_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS media_objects_owner_idx ON media_objects(owner_id, created_at DESC);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS media_objects_couple_idx ON media_objects(couple_id) WHERE couple_id IS NOT NULL;
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS media_deletion_queue (
storage_key text PRIMARY KEY,
queued_at timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE OR REPLACE FUNCTION queue_media_blob_deletion() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO media_deletion_queue(storage_key) VALUES(OLD.storage_key) ON CONFLICT DO NOTHING;
RETURN OLD;
END $$;
--> statement-breakpoint
DROP TRIGGER IF EXISTS media_objects_queue_blob_deletion ON media_objects;
CREATE TRIGGER media_objects_queue_blob_deletion BEFORE DELETE ON media_objects
FOR EACH ROW EXECUTE FUNCTION queue_media_blob_deletion();
--> statement-breakpoint
ALTER TABLE feedback ADD COLUMN IF NOT EXISTS screenshot_media_id uuid REFERENCES media_objects(id) ON DELETE SET NULL;
@@ -0,0 +1,62 @@
CREATE TABLE IF NOT EXISTS subscriptions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
revenuecat_app_user_id text NOT NULL,
product_id text NOT NULL,
status text NOT NULL DEFAULT 'active'
CHECK (status IN ('active', 'cancelled', 'expired', 'billing_issue', 'paused')),
entitlement_ids text[] NOT NULL DEFAULT '{}',
purchased_at timestamptz NOT NULL,
expires_at timestamptz,
original_transaction_id text,
store text NOT NULL DEFAULT 'APP_STORE',
is_sandbox boolean NOT NULL DEFAULT false,
cancel_reason text,
grace_period_expires_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (user_id, original_transaction_id)
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS subscriptions_user_id_idx ON subscriptions(user_id);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS subscriptions_status_idx ON subscriptions(status);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS revenuecat_webhook_events (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
event_id text NOT NULL UNIQUE,
event_type text NOT NULL,
app_user_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
payload jsonb NOT NULL
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS redemption_codes (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code text NOT NULL,
description text,
max_uses integer DEFAULT 1 CHECK (max_uses IS NULL OR max_uses >= 0),
current_uses integer NOT NULL DEFAULT 0 CHECK (current_uses >= 0),
expires_at timestamptz,
is_active boolean NOT NULL DEFAULT true,
created_by uuid REFERENCES profiles(id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE UNIQUE INDEX IF NOT EXISTS redemption_codes_upper_code_idx ON redemption_codes(upper(code));
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS code_redemptions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code_id uuid NOT NULL REFERENCES redemption_codes(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
redeemed_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (code_id, user_id)
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS code_redemptions_user_id_idx ON code_redemptions(user_id);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS redemption_rate_limits (
bucket timestamptz PRIMARY KEY,
attempts integer NOT NULL CHECK (attempts >= 0)
);
@@ -0,0 +1,15 @@
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS last_nudge_sent_at timestamptz;
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS live_draw_sessions (
couple_id uuid PRIMARY KEY REFERENCES couples(id) ON DELETE CASCADE,
strokes jsonb NOT NULL DEFAULT '[]'::jsonb,
revision bigint NOT NULL DEFAULT 1,
updated_by uuid NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT live_draw_sessions_strokes_array CHECK (jsonb_typeof(strokes) = 'array')
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS live_draw_sessions_updated_at_idx
ON live_draw_sessions(updated_at DESC);
@@ -0,0 +1,161 @@
ALTER TABLE question_packs
ADD COLUMN IF NOT EXISTS scheduled_release_at timestamptz,
ADD COLUMN IF NOT EXISTS release_notified boolean NOT NULL DEFAULT false;
--> statement-breakpoint
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS last_unpaired_reminder_at timestamptz;
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS pending_match_notifications (
couple_id uuid PRIMARY KEY REFERENCES couples(id) ON DELETE CASCADE,
active_user_id uuid NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
match_count integer NOT NULL DEFAULT 0,
response_count integer NOT NULL DEFAULT 1,
latest_match_id uuid REFERENCES matches(id) ON DELETE SET NULL,
notify_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS pending_match_notifications_due_idx ON pending_match_notifications(notify_at);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS pending_pack_notifications (
couple_id uuid PRIMARY KEY REFERENCES couples(id) ON DELETE CASCADE,
changed_by_user_id uuid NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
notify_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS pending_pack_notifications_due_idx ON pending_pack_notifications(notify_at);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS catchup_reminder_tracking (
user_id uuid PRIMARY KEY REFERENCES profiles(id) ON DELETE CASCADE,
pending_since timestamptz,
last_reminder_sent_at timestamptz,
reminder_count integer NOT NULL DEFAULT 0 CHECK (reminder_count >= 0)
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS operations_outbox (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
kind text NOT NULL CHECK (kind IN ('expo', 'discord', 'classify')),
dedupe_key text NOT NULL UNIQUE,
recipient_id uuid REFERENCES profiles(id) ON DELETE CASCADE,
payload jsonb NOT NULL,
available_at timestamptz NOT NULL DEFAULT now(),
attempts integer NOT NULL DEFAULT 0 CHECK (attempts >= 0),
locked_at timestamptz,
sent_at timestamptz,
last_error text,
created_at timestamptz NOT NULL DEFAULT now()
);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS operations_outbox_due_idx
ON operations_outbox(available_at, created_at) WHERE sent_at IS NULL;
--> statement-breakpoint
CREATE OR REPLACE FUNCTION queue_response_digest() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF current_setting('sauci.suppress_operations',true)='on' THEN RETURN NEW; END IF;
INSERT INTO pending_match_notifications(couple_id, active_user_id, notify_at)
VALUES(NEW.couple_id, NEW.user_id, now() + interval '5 minutes')
ON CONFLICT(couple_id) DO UPDATE SET
active_user_id=excluded.active_user_id,
response_count=pending_match_notifications.response_count+1,
notify_at=excluded.notify_at,
updated_at=now();
RETURN NEW;
END $$;
--> statement-breakpoint
DROP TRIGGER IF EXISTS operations_response_digest ON responses;
CREATE TRIGGER operations_response_digest AFTER INSERT ON responses
FOR EACH ROW EXECUTE FUNCTION queue_response_digest();
--> statement-breakpoint
CREATE OR REPLACE FUNCTION count_digest_match() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF current_setting('sauci.suppress_operations',true)='on' THEN RETURN NEW; END IF;
UPDATE pending_match_notifications SET match_count=match_count+1,
latest_match_id=NEW.id, updated_at=now() WHERE couple_id=NEW.couple_id;
RETURN NEW;
END $$;
--> statement-breakpoint
DROP TRIGGER IF EXISTS operations_match_digest ON matches;
CREATE TRIGGER operations_match_digest AFTER INSERT ON matches
FOR EACH ROW EXECUTE FUNCTION count_digest_match();
--> statement-breakpoint
CREATE OR REPLACE FUNCTION queue_message_operations() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE v_couple_id uuid; v_recipient record;
BEGIN
IF current_setting('sauci.suppress_operations',true)='on' THEN RETURN NEW; END IF;
SELECT couple_id INTO v_couple_id FROM matches WHERE id=NEW.match_id;
FOR v_recipient IN
SELECT p.id FROM profiles p
LEFT JOIN notification_preferences np ON np.user_id=p.id
WHERE p.couple_id=v_couple_id AND p.id<>NEW.user_id
AND COALESCE(np.messages_enabled,true)=true
LOOP
INSERT INTO operations_outbox(kind,dedupe_key,recipient_id,payload)
VALUES('expo','message:'||NEW.id||':'||v_recipient.id,v_recipient.id,
jsonb_build_object('title','New message','body','Your partner sent you a message',
'data',jsonb_build_object('type','message','match_id',NEW.match_id,'message_id',NEW.id)))
ON CONFLICT(dedupe_key) DO NOTHING;
END LOOP;
INSERT INTO operations_outbox(kind,dedupe_key,payload)
VALUES('classify','classify:'||NEW.id,jsonb_build_object('message_id',NEW.id))
ON CONFLICT(dedupe_key) DO NOTHING;
RETURN NEW;
END $$;
--> statement-breakpoint
DROP TRIGGER IF EXISTS operations_message_created ON messages;
CREATE TRIGGER operations_message_created AFTER INSERT ON messages
FOR EACH ROW EXECUTE FUNCTION queue_message_operations();
--> statement-breakpoint
CREATE OR REPLACE FUNCTION queue_pack_change(p_couple_id uuid, p_user_id uuid) RETURNS void LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS(SELECT 1 FROM profiles WHERE id=p_user_id AND couple_id=p_couple_id) THEN
RAISE EXCEPTION 'user is not a member of couple';
END IF;
INSERT INTO pending_pack_notifications(couple_id,changed_by_user_id,notify_at)
VALUES(p_couple_id,p_user_id,now()+interval '30 minutes')
ON CONFLICT(couple_id) DO UPDATE SET changed_by_user_id=excluded.changed_by_user_id,
notify_at=excluded.notify_at,updated_at=now();
END $$;
--> statement-breakpoint
CREATE OR REPLACE FUNCTION queue_discord_operations() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF current_setting('sauci.suppress_operations',true)='on' THEN RETURN NEW; END IF;
IF TG_TABLE_NAME='profiles' AND NEW.onboarding_completed=true
AND (TG_OP='INSERT' OR OLD.onboarding_completed=false) THEN
INSERT INTO operations_outbox(kind,dedupe_key,payload)
VALUES('discord','discord:new_user:'||NEW.id,
jsonb_build_object('event','new_user','user_id',NEW.id,'name',NEW.name,'email',NEW.email,'created_at',NEW.created_at))
ON CONFLICT(dedupe_key) DO NOTHING;
END IF;
IF TG_TABLE_NAME='profiles' AND NEW.couple_id IS NOT NULL
AND (TG_OP='INSERT' OR OLD.couple_id IS DISTINCT FROM NEW.couple_id)
AND EXISTS(SELECT 1 FROM profiles partner WHERE partner.couple_id=NEW.couple_id AND partner.id<>NEW.id) THEN
INSERT INTO operations_outbox(kind,dedupe_key,payload)
VALUES('discord','discord:couple_paired:'||NEW.couple_id,
jsonb_build_object('event','couple_paired','couple_id',NEW.couple_id,'paired_at',now()))
ON CONFLICT(dedupe_key) DO NOTHING;
END IF;
RETURN NEW;
END $$;
--> statement-breakpoint
DROP TRIGGER IF EXISTS operations_profile_discord ON profiles;
CREATE TRIGGER operations_profile_discord AFTER INSERT OR UPDATE OF onboarding_completed,couple_id ON profiles
FOR EACH ROW EXECUTE FUNCTION queue_discord_operations();
--> statement-breakpoint
CREATE OR REPLACE FUNCTION queue_feedback_discord() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF current_setting('sauci.suppress_operations',true)='on' THEN RETURN NEW; END IF;
INSERT INTO operations_outbox(kind,dedupe_key,payload)
VALUES('discord','discord:feedback:'||NEW.id,
jsonb_build_object('event','feedback_submitted','feedback_id',NEW.id,'user_id',NEW.user_id,
'type',NEW.type,'status',NEW.status,'title',NEW.title,'description',NEW.description,
'question_id',NEW.question_id,'created_at',NEW.created_at))
ON CONFLICT(dedupe_key) DO NOTHING;
RETURN NEW;
END $$;
--> statement-breakpoint
DROP TRIGGER IF EXISTS operations_feedback_discord ON feedback;
CREATE TRIGGER operations_feedback_discord AFTER INSERT ON feedback
FOR EACH ROW EXECUTE FUNCTION queue_feedback_discord();
Loaded 100 of 470 files, more files were not shown because too many files have changed in this diff. Show more