Couples Goals

Self-host your sync server

Get Couples Goals on Google Play

Host your own sync server

Couples Goals ships with a lightweight PHP/MySQL REST API. You can run it on a shared web host, a VPS, or a home server: anything with Apache, PHP, and MySQL.

The app works without a self-hosted server
A built-in default server is available for couples who don't want to self-host. Self-hosting gives you full data ownership and is recommended for privacy-conscious users.

Requirements

ComponentMinimumRecommended
Operating SystemAny Linux distroUbuntu 22.04 LTS
Web ServerApache 2.4Apache 2.4 with mod_ssl
PHP7.48.2+
DatabaseMySQL 5.7 / MariaDB 10.3MariaDB 10.6+
PHP Extensionspdo_mysql, openssl, json
Apache Modulesmod_rewrite, mod_ssl. Disable MultiViews: it interferes with clean URL routing.
TLS CertificateRequired in production (Let's Encrypt is free)

Step-by-step deployment

1

Upload the server files

Copy the entire server/api/ folder to your web root, accessible at a URL like https://api.yourdomain.com/. Also upload server/feedback.php, server/delete-account.php, and server/.htaccess to the root if you want the public feedback page, the account-deletion request page, and this docs site. The account-deletion page is required if you plan to publish an app that uses your server on Google Play, per Play's Account Deletion Requirement (see the Privacy Policy).

2

Create the database

mysql -u root -p
CREATE DATABASE coupleschallenge CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'cc_user'@'localhost' IDENTIFIED BY 'STRONG_PASSWORD_HERE';
GRANT ALL PRIVILEGES ON coupleschallenge.* TO 'cc_user'@'localhost';
FLUSH PRIVILEGES; EXIT;

Import the schema. This single file is the complete, current schema for a fresh install; every table (including the admin panel, vault, premium, and account-deletion tables) is already merged in, so do not run any of the individual migration_*.sql files listed later in this file's own header comment on a brand-new database; those are for upgrading an existing, already-deployed database only, one at a time, in the order they were introduced:

mysql -u cc_user -p coupleschallenge < /path/to/server/api/schema.sql
3

Edit config.php

The server ships api/config.php.example (so updates never overwrite your settings). Copy it once, then edit the copy:

cp api/config.php.example api/config.php
define('DB_HOST',    'localhost');
define('DB_NAME',    'coupleschallenge');
define('DB_USER',    'cc_user');
define('DB_PASS',    'STRONG_PASSWORD_HERE');
define('JWT_SECRET', 'CHANGE_ME_64_HEX_CHARS');
define('APP_ENV',    'production');

Generate a secure JWT secret:

php -r "echo bin2hex(random_bytes(32)) . PHP_EOL;"
Keep JWT_SECRET private
Anyone with this value can forge valid auth tokens. Never commit it to version control.
Optional: Sparky AI Coach cloud fallback
Sparky's on-device generation (Gemini Nano) works with any server, no extra config needed. Its cloud fallback (used only when on-device generation isn't available, and only for Couple Pro accounts) needs an OpenAI API key on your server if you want it active:
define('OPENAI_API_KEY',   'sk-...');
define('SPARKY_ENABLED',   true);
define('SPARKY_DAILY_LIMIT', 20);
Leave SPARKY_ENABLED false (or the key unset) to disable the fallback entirely; the app falls back further, to a static localized line, exactly like it does when the on-device model itself is unavailable.
Optional: instant partner updates (push)
Without this, partner changes still arrive on each phone's regular background sync. To have them arrive within seconds, create a Firebase service account for the app's Firebase project, upload its JSON key outside the web root (readable by the PHP user only), point FCM_SERVICE_ACCOUNT_FILE at it, and run migration_push_tokens.sql. Step-by-step: DEPLOYMENT.md §7.7. This only works with app builds that use the same Firebase project.
Optional: in-app purchases (RevenueCat)
Only relevant if you publish your own build with your own RevenueCat project. REVENUECAT_WEBHOOK_SECRET authenticates RevenueCat's webhook; REVENUECAT_SECRET_API_KEY (a v2 secret key with Purchases: Read and Products: Read) plus REVENUECAT_PROJECT_ID let the server confirm XP bundle purchases. See RevenueCat_Setup_Guide.md §5 and §7.
4

Configure Apache

<Directory /var/www/html>
    Options -MultiViews
    AllowOverride All
    Require all granted
</Directory>
a2enmod rewrite && systemctl restart apache2
Disable MultiViews
Apache's MultiViews content-negotiation intercepts clean URLs like /feedback before mod_rewrite can handle them, causing 404 errors. Always set Options -MultiViews.
5

Set up HTTPS (strongly recommended)

apt install certbot python3-certbot-apache -y
certbot --apache -d api.yourdomain.com
6

Set up the admin panel (optional)

Upload server/admin/ to a directory on your server. Generate an Argon2id password hash:

php -r "echo password_hash('YourPassword', PASSWORD_ARGON2ID);"

Edit admin/admin_config.php and replace ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET. Restrict access by IP allowlist.

Secure the admin panel
The admin panel can disable accounts, reset passwords, and delete user data. Protect it behind a VPN or strict IP allowlist in production.
7

Point the Android app at your server

In the app, go to Settings → Custom server URL and enter:

https://api.yourdomain.com/

The trailing slash is required. Tap Save, then Sync Now: a green status confirms the connection.

Database tables

TablePurpose
usersAccounts; display name, email, bcrypt password, partner_id, XP balances, badges and their earned dates, premium tier
partner_links6-character invite codes; 24-hour TTL
challengesAll challenges; status, visibility, category, sort_order
progress_entriesAll logged activity; entry_type stores YES/NO/SKIP/COUNT/WEIGHT/FREEZE/RECOVERY (FREEZE/RECOVERY are legacy values; see streak_protection_log below for the current account-wide mechanism)
sync_queuePer-user last push/pull timestamps
deleted_challenge_tombstonesHard-deleted challenge UUIDs; prevents resurrection on reinstall
xp_ledgerAppend-only XP earn/spend audit log; ADMIN_ADJUSTMENT source type
streak_protection_logAccount-wide Streak Freeze/Recovery rows: one streak per account, not per challenge
custom_vouchersPartner reward vouchers (PENDING_APPROVAL → AVAILABLE → REDEEMED → FULFILLED)
challenge_modifiersSabotage text modifiers applied to challenges
progress_commentsText comments on progress entries; soft-delete
progress_reactionsEmoji reactions on entries; unique per user per entry
vault_reward_contentCouple-scoped vault milestone content (bucket list items, letters, planner fields, etc.); is_revealed is server-authoritative
vault_contributionsPer-user XP contribution history into the shared vault wallet
vault_mediaVault photo metadata (Memory Box); files stored outside the web root, served exclusively via an authenticated endpoint
vault_milestone_unlocksPermanent record of which vault milestones a couple has redeemed; the store model's single source of ownership truth
vault_celebrationsPer-user record of which milestone-unlock celebrations have already played, so they don't repeat across devices
premium_licensesLicense key hashes for Couple Pro activation; propagates to the linked partner automatically
announcements / announcement_dismissalsAdmin-authored dashboard banners with optional targeting (rollout %, tier, app version, specific users) and per-user dismissal tracking
account_deletion_requestsQueue behind the public /delete-account web form (Google Play's Account Deletion Requirement web-link path); reviewed by an admin before the account is actually removed
install_pingsAnonymous, account-independent install/open telemetry: a random per-install ID, app version, and locale; never linked to any user account
user_feedbackPublic feedback form submissions; managed via admin/feedback.php
admin_users / admin_sessions / admin_backup_codesDB-backed admin accounts with Argon2id password hashing, TOTP MFA, and single-use backup recovery codes; sessions are revocable server-side
admin_audit_logAppend-only log of every admin panel action
admin_login_attemptsFailed admin logins for brute-force rate limiting
sparky_generation_logServer-side Sparky AI Coach fallback call log: trigger type, model, token counts, duration; never the prompt content or generated message text. Used for rate limiting and the admin usage stats panel
sparky_settingsAdmin-configured OpenAI model for the Sparky fallback (falls back to a hardcoded default if this table is empty or unmigrated)
sparky_local_generation_logContent-free ping recorded when the app's on-device (Gemini Nano) Sparky generation succeeds: trigger type only, never the message text. Lets the admin panel compute an on-device-vs-cloud generation ratio
sparky_quota_breach_logOne row per Sparky request rejected for exceeding SPARKY_DAILY_LIMIT: user ID and timestamp only
analytics_eventsFirst-party onboarding funnel & conversion events (no Firebase, no third-party SDK), anonymous and install_id-scoped, user_id attached once known. See the Privacy Policy for exactly what's collected
push_tokensFirebase Cloud Messaging device tokens, one per signed-in device; removed on sign-out, account deletion, or when Google reports them invalid
couple_giftsGift Shop gifts between partners (type, message, chosen option, Pep Talk text, active window, state); deleted when the couple unlinks or either account is deleted
xp_purchasesXP bundles bought with real money: one row per store transaction (the unique key that stops a purchase being credited twice), XP amount, test-purchase flag, and refund state
pushover_settingsAdmin Pushover alert settings: encrypted credentials, priority, sound, and which events alert (new user, upgrade, feedback, log upload, deletion request, account deleted, XP purchase)

API endpoints reference

All endpoints return application/json. Endpoints marked with a lock () require an Authorization: Bearer <token> header.

MethodPathAuthDescription
POSTauth/registerCreate account, returns JWT
POSTauth/loginAuthenticate; returns JWT with token_version claim
GETchallengesList own + partner's shared challenges
POSTchallenges/createCreate a new challenge
PUTchallenges/updateUpdate challenge metadata and visibility
DELETEchallenges/deleteHard-delete a challenge; writes tombstone
POSTprogress/addAdd or update a progress entry (upsert). Supports entry_type: YES/NO/SKIP/COUNT/WEIGHT/FREEZE/RECOVERY
GETprogress/historyGet entries for a challenge
POSTpartner/generate-codeGenerate a 6-character invite code (24 h expiry)
POSTpartner/linkLink two accounts using an invite code; both partner_id fields updated atomically
GETpartner/statusCheck partner link status and partner name
POSTsocial/commentAdd / edit / soft-delete a text comment on an entry
POSTsocial/reactInsert / toggle / replace an emoji reaction
POSTsync/pushPush pending batch (challenges, entries, XP, vouchers, comments, reactions, streak protections, deleted IDs)
GETsync/pull?since=<ms>Pull all data since timestamp. Returns: challenges, entries, XP, vouchers, social, streak protections, tombstones, display_name, server_partner_id, server_partner_name
POSTvouchers/createCreate a custom voucher (starts as PENDING_APPROVAL)
POSTvouchers/redeemRedeem an available voucher (deducts XP)
GETvouchers/statusCheck the status of a specific voucher
POSTgamification/execute-sabotageExecute a Sabotage Shop action: modifier (free), or taxman / mega_drain / shield (Couple Pro, tier-checked server-side)
POSTpremium/activateRedeem a license key; grants Couple Pro to the account and its linked partner
GETpremium/statusCheck the account's current premium tier and expiry
POSTvault/contributeMove XP from the caller's personal balance into the couple's shared vault wallet
POSTvault/redeemRedeem a vault milestone once the wallet covers its cost (and any dependency is already owned); re-validates everything server-side regardless of client state
POSTvault/media/upload.phpUpload a Memory Box photo (multipart/form-data); re-validates the image server-side, stores it outside the web root under a random filename
GETvault/media/serve.php?id=<uuid>Stream a vault photo; checks couple ownership and reveal state before returning bytes
DELETEvault/media/delete.phpDelete your own vault photo (file + DB row)
POSTaccount/delete.phpSelf-service account deletion. Requires, in addition to the JWT, the account's current password in the request body (or, for an account created with Google Sign-In and no password, an exact confirmation phrase); permanently deletes the account and everything it owns, unlinks the partner, never touches the partner's own data
POSTsparky/generateSparky AI Coach server/OpenAI fallback. Couple Pro only, server-side daily rate limit; requires OPENAI_API_KEY configured (see Step 3 above). Returns generated commentary text and a mascot expression key
POSTsparky/log_local_success.phpContent-free telemetry ping recorded when the app's on-device Sparky generation succeeds (trigger type only); feeds the admin on-device-vs-cloud ratio
POSTsparky/streak-loss-coaching.phpStreak Loss Diagnostic full-AI coaching reply. Couple Pro only, shares SPARKY_DAILY_LIMIT with sparky/generate (logged as a distinct STREAK_LOST_COACHING trigger). Validates a custom free-text reason and/or generates a validate-then-recommend-then-encourage coaching reply, optionally naming one of the caller's own active challenges by a scaled-down version of it
POSTtelemetry/track_event.phpOnboarding funnel / conversion event ping, anonymous and install_id-scoped, same no-auth shape as telemetry/install_ping.php; user_id included in the body once an account exists
POSTpush/register_token.phpStore this device's Firebase push token for the signed-in account
POSTpush/unregister_token.phpRemove the device's push token (called on sign-out)
POSTgifts/purchase.phpBuy a Gift Shop gift for the linked partner. The server checks and deducts the XP; a retry with the same client_request_id is never charged twice
POSTgifts/respond.phpRecipient collects a Love Bomb or dismisses a Love Note / Pep Talk
POSTxp/claim-purchases.phpCredit any XP bundle the account bought that isn't credited yet. Takes no input: the server asks RevenueCat what was bought. Returns the XP added and the new balance
POSTpremium/revenuecat-webhook.php RevenueCat server-to-server events: Couple Pro grants and expiry, XP bundle purchases and refunds. Authenticated by REVENUECAT_WEBHOOK_SECRET
server_partner_id in pull response
The pull endpoint always returns the server's authoritative server_partner_id and server_partner_name for the requesting user. The Android client uses these to detect admin-initiated unlinks (server returns empty string when partner_id is NULL) and to recover lost partner state after events like app reinstall or a false-unlink scenario.

Admin panel features

Access at https://yourdomain.com/admin/ with your configured admin credentials.

PageFeatures
Dashboard6 stat tiles (users, challenges, entries, XP, vouchers, sync health), recent activity
All UsersSearchable user list; email, name, XP, partner status, join date
User DetailEnable/disable account, force-logout (token_version bump), reset password, unlink partner, edit display name, view challenges and XP ledger, gift lifetime Couple Pro premium (cascades to the linked partner automatically), view vault balance/media, Danger Zone: delete account and all of its data (uses the same cascade as the in-app self-service path; see Deletion Requests below)
Deletion RequestsReview queue for the public /delete-account web form (Google Play's Account Deletion Requirement web-link path). “Delete Account Now” looks up the submitted email and runs the same deletion cascade as User Detail's Danger Zone and the in-app path: one shared implementation, three entry points
Modify XPAdd/subtract/set individual or shared vault XP; writes ADMIN_ADJUSTMENT ledger row; live ledger view
VouchersBrowse and cancel/delete vouchers by status
ChallengesBrowse all challenges; archive or hard-delete (tombstone written)
FeedbackInbox / Starred / Archived views; mark read/unread; star; archive; delete; admin notes; unread badge in nav
Audit LogPaginated log of every admin action (LOGIN, UNLINK_PARTNER, FEEDBACK_READ, MODIFY_XP, etc.)
Sync StatusUsers with oldest pull timestamps; users who have never synced
Server LogsView/search/filter daily API log files; level/keyword/user/IP filters; JSON context expand; raw download
DB HealthTable row counts and sizes; orphan detection; server info
AnnouncementsCreate/edit targeted dashboard banners (rollout percent, tier, app version, or specific users), with optional image and action link
Install AnalyticsAggregate install/adoption trends from the anonymous install ping table; bot traffic (Play pre-launch report, Firebase Test Lab) is filtered out
Funnel AnalyticsOnboarding step-by-step drop-off, sign-up conversion, estimated paywall conversion, and 24h activation rate from the first-party analytics_events table
NotificationsPushover alerts to the admin's phone for selected events: new user, Couple Pro upgrade, feedback, log upload, deletion request, account deleted, and XP bundle purchased (names the bundle, flags test purchases)
Sparky AI CoachPick/refresh which OpenAI model powers the server fallback; usage stats (calls, success rate, latency, tokens by trigger/model); average generations per active user, on-device-vs-cloud ratio, daily quota-breach rate, and a live "Quota Exceeded Users" table with a one-click per-user Reset action
TroubleshootingReference page: every server endpoint by area, with what each of this API's specific error codes actually means, for support-ticket triage
SecurityAdmin's own TOTP MFA enrollment/management and single-use backup recovery codes
Admin auth is a fully separate system
Admin accounts are DB-backed (not the app's own users table), with Argon2id password hashing, mandatory-capable TOTP multi-factor authentication with backup codes, CSRF-protected forms, revocable server-side sessions, brute-force rate limiting, and an optional IP allowlist. None of this is reachable through the regular app API.

Troubleshooting

SymptomWhat to check
500 on every requestconfig.php DB credentials; PHP error log
404 on all routesmod_rewrite enabled; AllowOverride All in Apache config
404 on /feedback clean URLOptions -MultiViews set in .htaccess or Apache vhost config; RewriteRule ^feedback/?$ /feedback.php [L] present
401 on every requestToken expired or wrong JWT_SECRET; log in again in the app
"Session invalidated" errorAdmin panel force-logout was triggered; log in again
"Account disabled" errorAdmin has disabled the account; contact your server admin
"Database connection failed"DB user permissions; confirm DB service is running
App shows HTTPS errorTLS certificate valid; APP_ENV = 'production' in config.php
Partner code "invalid"Code expired (24 h TTL); generate a fresh code
Deleted challenge reappearsRun migration_tombstone.sql on your server; sync again
Every sync fails right after updating the server filesRun migration_badge_earned_at.sql. The current sync endpoints read and write the users.badge_earned_at column it adds; run it before uploading the new PHP files
Sync or gifts fail after the Gift Shop / Get XP updateRun the migrations in DEPLOYMENT.md §6.1 order (migration_push_tokens.sql, migration_gift_shop.sql, the progress-entry dedup scripts, migration_xp_purchases.sql, migration_pushover_xp_purchase.sql) before uploading the new PHP files
XP bundle bought but never creditedCheck the server log for RevenueCat request failed: it includes RevenueCat's reason. Usually a key without the Purchases/Products read permissions, or a v2 key with no REVENUECAT_PROJECT_ID. Fix the config, then open Get XP in the app: stuck purchases are credited on open
Partner challenges not showing after linkDevice A: tap Refresh on Partner screen. If still missing: check in-app logs for pull errors; verify server_partner_id is returned in pull response (requires updated pull.php)
Partner still shows after admin unlinkTap Sync Now on the affected device. The pull response's server_partner_id field triggers local cleanup automatically.
Display name change not reflected in appTap Sync Now. The pull response returns the server-authoritative display name and updates prefs immediately.
Feedback page 404 at /feedbackMultiViews must be disabled. Add Options -MultiViews to the vhost <Directory> block or in root .htaccess.
Sparky AI Coach always shows the same canned lineA missing server/api/.htaccess rewrite rule causes every sparky/generate request to 404 silently before PHP ever runs (no entry in the PHP or Apache error log, since a rewrite non-match isn't logged as an error). Confirm your .htaccess includes the sparky/ rewrite rules shown in this file's own header comment, then check the admin panel's Sparky AI Coach usage table for real call attempts

Security notes

  • Passwords hashed with bcrypt via PHP's password_hash().
  • JWTs signed with HMAC-SHA256; expire after 30 days; include a token_version claim to support admin force-logout.
  • All queries use PDO prepared statements: SQL injection is not possible.
  • config.php and .sql files are blocked from direct HTTP access by .htaccess rules.
  • Security headers set on all responses: X-Content-Type-Options, X-Frame-Options, Referrer-Policy.
  • Admin panel protected by DB-backed sessions, Argon2id password hashing, TOTP multi-factor authentication with backup codes, CSRF tokens, brute-force rate limiting, and an optional IP allowlist.
  • Feedback form protected by server-side math captcha, CSRF token, honeypot field, and rate limiting (5 submissions/IP/hour).