Commit Graph

114 Commits

Author SHA1 Message Date
null e39b32f4af chore(functions): add stamp-build.js + wire it into build script (Batch F follow-up) 2026-07-16 03:10:10 -05:00
null 884cf9f614 chore(build): stop committing functions/dist; delete stale schema cruft (kill the artifact-drift class)
The dist-stale bug (deployed onCoupleKeyRotated lacked committed src twice) was
one instance of a class: a tracked build artifact whose source is elsewhere,
with no guard they match. Fix it at the root — don't track the artifact.

- functions/dist: git rm --cached (104 files) + gitignored. src is truth; dist
  is tsc output that ships (main: dist/index.js). The predeploy hook already
  builds it at deploy and backend-ci builds it for tests, so the old
  "committed for reproducibility" rationale is dead — committing it only hid
  drift behind noisy .js/.js.map diffs. You cannot ship stale what you don't
  track; a deploy on a fresh clone now fails loudly (missing dist) instead of
  shipping old code.
- app/schemas: deleted the stale com.couplesconnect.app.data.local dir — dead
  cruft from the package rename to app.closer, and living proof the class isn't
  hypothetical. The live app.closer schema stays committed (legitimate Room
  migration provenance, validated by AssetDatabaseVerifyTest).
- ERM rewritten: the dist-committed convention is reversed; the app.db + schema
  cousins documented as same-class-but-guarded.

No behavior change — dist remains on disk (untracked) so local/predeploy/CI
builds and deploys are unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 02:58:38 -05:00
null 8a9bd41fe5 fix(functions): rebuild stale dist + predeploy build hook (FUNCTIONS-DIST-STALE)
The phrase-change 🔑 alert never fired live because the deployed artifact
didn't contain it — functions/dist is committed and is what deploys, and I
changed functions/src without rebuilding it. My own gates were green and
irrelevant: tsc --noEmit emits nothing, ts-jest compiles in memory. The user
deployed twice, faithfully, and shipped my stale artifact both times. "git
status clean" is not "deployable current".

Two fixes: dist rebuilt (diff confirms exactly one stale function,
onCoupleKeyRotated — the phrase edge), and firebase.json now carries a
predeploy hook (npm run build) so every functions deploy compiles first —
the mistake class is structurally gone rather than remembered. Landmine
written up as FUNCTIONS-DIST-STALE in the manual: when verifying "is X
deployed", compare against dist/, not src/ — src is the intent, dist is
the truth.

Functions tests green (108).
2026-07-16 01:29:20 -05:00
null 5716aead8f feat(crypto): wire "change recovery phrase" with a partner handshake (closes the desync landmine)
The API existed and was deliberately unwired, carrying warnings at three layers:
re-wrapping the couple key under a new phrase leaves the PARTNER's stored copy
stale, so their Settings → Security reveals a phrase that unwraps nothing and the
"lost your phrase? ask your partner" path — the whole reason both partners hold it
— hands over a dud. This makes it shippable rather than deleting it.

The phrase can't travel via the server in plaintext, but it can travel sealed to
the key both partners already hold. And the WRAP moves last:

  phase 1  publish the new phrase (enc:v1: under the couple key) + phraseGeneration
  phase 2  each device confirms it can read it (ack)
  phase 3  once BOTH acked, re-wrap under it + phraseWrapGeneration

Until phase 3 the old phrase unwraps everything, so an interrupted change is a
no-op instead of an unrecoverable couple. A device stores the new phrase only when
the wrap is actually made from it — the stored phrase and the wrap never disagree,
which is the invariant the landmine is about. An old client that ignores the fields
never acks, so the change simply never completes: it degrades to "nothing
happened", the right failure direction for a crypto rollout.

Two design notes against the plan. (1) The plan's "disable Rotate mid-handshake"
guard is gone: nothing stores the new phrase until the wrap moves, so a rotation
landing mid-handshake wraps under the phrase everyone still has, and phase 3 runs
in a TRANSACTION that re-reads keyGeneration — without it, a phase-3 write racing a
rotation republishes a wrap of the pre-rotation keyset and rolls the rotation back,
stranding the partner. The transaction subsumes the guard; a UI gate would have been
theatre. (2) Either device completes phase 3, so an offline changer can't leave the
couple showing a phrase the wrap doesn't honour.

I ALSO FOUND THE HARNESS I SHOULD HAVE BEEN USING: firestore-tests/ runs the rules
against the emulator. It immediately proved three bugs in my own rules, two of them
critical, all now fixed and pinned by 20 new tests (141 total, mutation-checked):

  - phase 3 was DEAD for every couple. `request.resource.data.keyGeneration` errors
    when the field never existed — couples are created without it — so the first
    phrase change of any couple was denied AFTER the UI had already shown the user
    their new phrase. The dud-phrase outcome, relocated. Both sides now default.
  - `phraseWrapGeneration` was in the allowlist but guarded by NOTHING: a bare
    one-field write passed (an unchanged wrap short-circuits the wrap clause), and
    the partner's client trusts that field as proof the wrap moved — so one write
    made them overwrite their working phrase with one that unwraps nothing.
    Permanently, silently, no crypto needed. Now only a genuine phase 3 may move it.
  - phase 3 never checked the acks server-side (client-only), so a client could
    complete before the partner had the phrase — exactly what the handshake exists
    to prevent. The rules now require both members' acks at the current generation.
    A fourth, caught by the tests themselves: the predicate didn't require the wrap
    to actually change, so advancing the generation alone still passed.

Also: the harness revealed the C-ROTATE-001 rules I shipped earlier broke a
standing test ("a member can re-wrap the couple key — allowed"). No live flow used
it (updateWrappedKey was dead code, now deleted), and the test encoded the very
behaviour the hardening removes — rewritten to assert the new invariant plus the
lawful rotation path.

Rules deploy is user-gated and NOT yet done; the client tolerates the old rules
(phase 1 is rejected, nothing breaks). Android suite + 108 functions tests + 141
rules tests green. Live 2-device verification still pending on the throwaway couple.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 21:57:58 -05:00
null 2c44cc6ff2 feat(crypto): couple-key rotation, phase 1 — rotate forward (Future.md security #3)
A couple-key compromise currently exposes everything, forever, because the key
never changes. This adds the rotation ceremony: a fresh AES-256-GCM key becomes
the keyset's primary while the old keys stay for reads. The keyset is a Tink
keyring and every enc:v1: blob carries its key-id internally, so all history
keeps decrypting with zero wire-format changes — none of the 25 isCiphertext
rule sites move. Phase 1 protects FUTURE content only (a stolen keyset still
contains the old key); forward secrecy for history is phase 2, which builds on
the keyGeneration plumbing laid here. The Security-screen copy says so plainly.

The ceremony (CoupleRepositoryImpl.rotateCoupleKey): read the couple fresh so
concurrent rotations collide at the rules instead of overwriting each other →
prepareRotation builds the rotated keyset and re-wraps it under the SAME phrase
(fail-closed with a typed error when this device lacks keyset or phrase; nothing
persisted anywhere) → ONE merge write lands the new wrap + a strictly-increasing
keyGeneration atomically, so the partner can never observe a bumped generation
pointing at the old wrap → only then commitRotation stores locally. A failed
server write leaves the device coherent on the old key; a crash after it
self-heals through the same adoption path as the partner.

Adoption (CoupleEncryptionManager.adoptRotationIfNeeded, hooked into Home's
healing block, synchronously before the screen settles — until the rotated
keyset is stored, new content renders locked): couple.keyGeneration ahead of the
local generation → unwrap the published wrap with the locally-stored phrase →
replace the keyset. Replaced only on success, never deleted on failure, so old
content survives anything. No phrase on this device → needsRecovery, and both
recovery flows already deliver the rotated keyset for free (phrase entry unwraps
the current wrap; partner-assist exports the current keyset). Same phrase both
sides is the entire distribution trick — no new ceremony, no partner action.

Server: onCoupleKeyRotated (couples/{id} update, pure isKeyGenerationIncrease
edge guard so streak/rhythm/re-wrap updates never fire it, and a rules-forbidden
downgrade or redelivered stale event never alerts) sends both members the 🔑
security alert through the house pipeline, bypassing quiet hours like the
restore self-alerts. The push is also functional: the partner's closed app can't
read new-key content until it next loads Home — the tap takes them there.

Rules: isUpdatingRecoveryWrap admits keyGeneration, strictly increasing
(monotonic like encryptionVersion), untouched for plain phrase re-wraps.

Tests (real Tink, mocks stop at storage): history readable after rotation + NEW
writes unreadable by the old keyset — mutation-checked by dropping setPrimary,
which kills exactly that test (a rotation that forgets setPrimary passes
everything else while protecting nothing) — same-phrase unwrap reads both eras
(the partner's whole adoption, proven), prepare persists nothing until commit,
fail-closed without phrase/keyset, adoption state machine incl. corrupt-wrap.
Android suite green, assembleDebug clean, functions 105/105, tsc clean.

Deploy (scoped): firebase deploy --only firestore:rules and
--only functions:onCoupleKeyRotated. Live verify follows deploys.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 02:49:50 -05:00
null b47be4e34c chore(functions): rebuild dist for the restore cleanup + alert-precision batches
dist/ is what firebase deploy ships (no predeploy hook), so the compiled output
travels with the source it came from. Contains cleanupRestoreRequests,
queueAndPush, and the excludeTokens seam.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 02:39:50 -05:00
null 2dd09d5d0d feat(restore): spare the requesting device its own "was this you?" alert (Future.md security #2)
The restore self-alerts fan out to every device the recipient owns — including
the new device that is doing the requesting. "Was this you?" sent to the asker
is noise; the copies that matter go to their partner and to any OTHER device the
real owner still holds (the phished-password-without-device-loss case), and
those are untouched. For a legit single-device owner the self-alert becomes a
clean no-op, which was the point.

The requesting device identifies itself: RestoreManager fetches its own FCM
token at request time and the doc carries it as a create-only, optional
requesterFcmToken. Doc-embedded on purpose — MainActivity's token registration
races the restore flow on a fresh device, so cross-referencing fcmTokens
server-side can't reliably name the requester. Strictly best-effort on the
client (runCatching → null → field omitted, never written hollow): a restore
must never block or fail over a notification nicety, pinned by test.

sendPushToUser gains optional excludeTokens (filtered after merge/dedupe;
excluding everything is a clean zero no-op via the existing empty-list guard),
threaded through the shared queueAndPush — the notification_queue record is
still written, so the in-app alert history stays complete — and applied to the
two self-alerts only; the partner "help them restore" push is deliberately
unfiltered. Rules: requesterFcmToken joins the create allowlist as an optional
plain string (opaque device identifier, no format to pin); partner-update and
status-flip rules are unaffected since the field is create-only. Old clients
never send it; the server reads it only if present — no deploy-order coupling.

Tests: 3 new push.test.ts cases (exclusion, exclude-all no-op, absent-list
unchanged) — mutation check on the filter kills exactly those; 2 new
RestoreManagerTest cases (token embedded; FCM failure never blocks the request).
Functions 101/101, tsc clean; Android suite + assembleDebug green.

Deploy (scoped): firebase deploy --only firestore:rules, then
--only functions:onRestoreRequested,functions:onRestoreFulfilled.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 02:39:20 -05:00
null 8496bbedac feat(functions): hourly cleanup of expired restore requests (Future.md security #1)
A restore_requests doc left behind — partner wrapped the couple key but the
recipient never completed, or nobody ever answered — keeps its ECIES keybox
forever. It's sealed to the recipient alone, so it's not exploitable, but key
material has no business lying around, and expiry was enforced only client-side
(fulfil-time check, delete-before-re-request, delete-on-complete): a request
whose device disappeared simply lived forever.

cleanupExpiredRestoreRequests runs hourly (requests expire in 30 min, so a
stranded keybox now lives ~1.5 h at most) over a collectionGroup query on
expiresAt — chosen over iterating couples deliberately, because it also reaps
requests orphaned under already-deleted couple docs, which a parent iteration
can never see. Backed by a new COLLECTION_GROUP fieldOverride on
restore_requests.expiresAt (expiresAt is epoch millis, not a Timestamp, which
also rules out native Firestore TTL).

Deletes only on positive evidence: a pure predicate re-verifies every query hit
(a real expiresAt past a 5-min grace so a mid-completion restore is never raced;
a day-old createdAt as the defensive fallback when expiresAt is unusable;
neither → leave it and log). Status is deliberately irrelevant — a
DECLINED-after-READY doc still carries the keybox.

Requests that expired recently while still waiting on someone (REQUESTED/READY)
nudge the requester — "start a new one whenever you're ready" — through the
house pipeline (notification_queue + sendPushToUser, quiet hours respected).
The doc is deleted BEFORE the nudge, so a notify failure costs a nudge, never a
duplicate; a 2-h notify window keeps the first deploy from blasting the ancient
backlog. queueAndPush moves from being file-local in onRestoreRequested.ts to a
shared notifications/queueAndPush.ts — the cleanup needed identical semantics,
and two copies of notification plumbing is how the same bug ends up existing
twice.

Sweep never throws (a scheduled-function throw retries in a storm; the next
hourly run IS the retry): per-doc Promise.allSettled, one summary log line via
the structured logger.

15 new tests; grace-window mutation check kills exactly the guard test.
Functions suite 98/98, tsc clean. Deploy (scoped — the RevenueCat webhook must
stay undeployed): firebase deploy --only firestore:indexes, then
--only functions:cleanupExpiredRestoreRequests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 02:32:59 -05:00
null f74f0e96f5 feat(daily): wildcard-day picker branch + authoring spec (Option A)
The client's DailyModeResolver promotes ~10% of days (dayOfYear % 10 == 3) to a
'Wildcard' theme, but there were zero wildcard questions and the server never
assigned one — so those days showed the Wildcard banner over a normal weekday
question. This adds the server half:

- pickDailyQuestionId now detects wildcard days (new pure, tested dayOfYearUtc /
  isWildcardDay helpers mirroring the client cadence) and prefers the mode_wildcard
  pool. Until that content is seeded it falls back to the day's WEEKDAY mode (not
  the whole pool), so it's a safe no-op pre-content. +3 unit tests (fn 80 -> 83).
- Authoring spec for the missing content added to
  seed/questions/DAILY_SINGLE_CHOICE_WEEKDAY_SYSTEM.md (## Wildcard Mode): 12 free
  single_choice, day-agnostic voice, REQUIRED mode_wildcard tag, id scheme, schema,
  and the post-authoring rollout (asset-db data-only insert + Firestore pointer seed
  + deploy).

Content authoring handed to another agent per the guide. Takes effect after the
wildcard rows land in app.db + Firestore and assignDailyQuestion is deployed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 16:39:59 -05:00
null 89d06eeb7d fix(billing): correct RevenueCat webhook auth to HMAC-SHA256 + enable export
The webhook verified an Ed25519 signature in an X-Signature header, but RevenueCat
offers no public-key signing — it sends HMAC-SHA256 in X-RevenueCat-Webhook-Signature
(t=<ts>,v1=<hex>) computed over "<ts>.<rawBody>". As written, every real event would
have 401'd and premium would never sync for the partner.

- Rewrite verification to HMAC-SHA256 with a +/-5-min timestamp replay guard and a
  constant-time compare; extract a pure verifyWebhookSignature() for unit testing.
- Rename secret REVENUECAT_SIGNING_KEY -> REVENUECAT_WEBHOOK_SECRET (it is an HMAC
  secret, not an Ed25519 key). Never deployed, so no migration.
- Uncomment the export in index.ts (deploy still gated on seeding the secret).
- Add revenueCatWebhook.test.ts: valid / tampered / wrong-secret / missing / stale.
- Reconcile Future.md + Engineering_Reference_Manual.md to the real scheme.

Verified against the live account: the entitlement identifier is now closer_premium,
so events match entitlementLogic. Build + 80 tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 03:43:59 -05:00
null 3cd3195e3f build(functions): bump runtime Node 20 → 22 (Node 20 decommissioned 2026-10-30)
Node 20 was deprecated 2026-04-30 and deploys are blocked after 2026-10-30. nodejs22 is GA
for BOTH gens (deprecation 2027-04-30) — required because the runtime is codebase-wide and
onUserDelete stays gen1. nodejs24 was checked per plan and rejected: 2nd-gen only.

- functions/package.json engines.node 20 → 22 (the deploy-facing change; dist unaffected)
- .github/workflows/backend-ci.yml: both setup-node pins 20 → 22 so CI matches prod

Verified pre-deploy: tsc clean, 70 tests green, emulator discovery loads all 35 / 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 03:42:18 -05:00
null 7d015e3ab9 fix(functions): gcf_gen1 fractional CPU to fit the Cloud Run CPU quota
Deploys kept failing container healthchecks with "Quota exceeded for total allowable CPU
per project per region" even in small batches: v2 gives every instance a full vCPU (needed
for concurrency 80), and ~35 services at 1 vCPU exceeds this new project's default Cloud Run
CPU quota under any accounting. cpu:'gcf_gen1' restores the gen1 fractional tiers
(256MiB → 1/6 vCPU) — a 6x smaller footprint, identical to how these functions ran on gen1.
Concurrency must be 1 with cpu<1; costless at dev scale. At launch: raise the quota, drop
these two options to restore full-vCPU concurrency.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 03:04:26 -05:00
null 9b62957052 fix(functions): lower global maxInstances 20→5 to fit the Cloud Run CPU quota
2nd-gen deploy failed with "Quota exceeded for total allowable CPU per project per region":
each function is a Cloud Run service and the regional CPU-allocation quota is charged as the
sum of (maxInstances × vCPU) across all functions. At maxInstances 20 × ~34 v2 functions =
~680 vCPU, over this new project's default (~560). Dropping to 5 → 170 vCPU, well under.

5 instances × ~80 concurrent requests still serves ~400 in flight — fine pre-launch. For
production, request a Cloud Run CPU quota increase and raise this back up.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 02:44:06 -05:00
null 30eaa0cd61 build(functions): keep revenueCatWebhook out of the deploy until RevenueCat exists
RevenueCat isn't set up, so exporting revenueCatWebhook forced a Secret Manager entry:
defineSecret('REVENUECAT_SIGNING_KEY') runs at module load, and Firebase validates every
declared secret across the whole codebase at deploy time (even functions excluded via --only),
failing with "no latest version of the secret". Comment out the export so the file isn't loaded
during discovery — no secret, no validation. revenueCatWebhook.ts (already migrated to v2) is
untouched; re-enable by uncommenting the export, seeding the real key, and deploying it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 02:01:23 -05:00
null bf4cc41cd9 refactor(functions): B6d finish logger migration in shared helpers
Migrate the last console.* call sites (the shared helpers entitlementLogic.ts and
pruneTokens.ts) to firebase-functions/logger, completing the structured-logging sweep.
Zero console.* remain under functions/src.

Final verification of the whole v1→v2 migration:
- tsc clean under firebase-functions v7.2.5; 70 jest tests green.
- Emulator discovery loads all 36 functions in us-central1 with 0 errors and no
  outdated-SDK warning; onUserDelete remains a v1 auth trigger, the rest are v2.
- Grep gates clean: no functions.https.onCall/.firestore.document/.pubsub.schedule,
  no context.auth/app/params, no console.* in src, no messaging.send outside push.ts,
  no raw FCM tokens in any log.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 00:10:10 -05:00
null 4c077c4d7c refactor(functions): B6c split game part-finished trigger + reorder reads (#11)
Split the single broad onGamePartFinished (couples/{coupleId}/{gameType}/{sessionId}
wildcard, which fired a no-op invocation on every write to ANY couple subcollection) into
four narrow, explicitly-pathed triggers sharing one handler:
onThisOrThatPartFinished, onWheelPartFinished, onHowWellPartFinished, onDesireSyncPartFinished.
Behavior is identical for the four game collections; the spurious invocations for
messages/reactions/etc. are eliminated. (Background triggers have no client name dependency;
the old export is dropped and the four deploy fresh — the deploy runbook already accounts for
this.)

onGameSessionUpdate: move the `!change.after.exists` deletion guard ABOVE its four reads
(session/couple/userA/userB) so a delete/no-op event returns before doing any reads. The
delicate exactly-once claim-flag logic is otherwise untouched.

Build clean; 70 tests green. Discovery loads all four split triggers as v2 in us-central1
(36 functions total); old onGamePartFinished gone. dist rebuilt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 00:08:18 -05:00
null eb4bab0b90 perf(functions): B6b bound the unbounded couple scanners (#10)
assignDailyQuestion and aggregateOutcomeStats previously did an unbounded
db.collection('couples').get() (loading every couple into memory), and aggregate did a
serial outcomes.get() per couple (O(couples) round-trips). Both now paginate the couple
scan (orderBy __name__ + startAfter, 300/200 per page — no custom index needed):

- assignDailyQuestion: each page's create() writes fan out with the burst bounded to a page
  instead of all couples at once; ALREADY_EXISTS stays the idempotent no-op.
- aggregateOutcomeStats: reads each page's outcomes in parallel instead of serially.
  couples.length still counts every couple, so the aggregate windows + totalCouples are
  unchanged (pure aggregate() helper and its tests untouched).

This is the one behavior-touching improvement flagged in the plan; the 512MiB/300s resource
options from B2 remain the safety net. Build clean; 70 tests green. dist rebuilt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 00:05:32 -05:00
null d601498e96 build(functions): B6a bump firebase-functions to v7 (latest)
Bump firebase-functions ^5.1.0 → ^7.2.5. The whole codebase now uses the v2 API
(firebase-functions/v2/*) with onUserDelete explicitly on firebase-functions/v1, so the
v6/v7 removal of the root v1 namespace is a no-op for us. firebase-admin unchanged (v7 does
not peer-require a bump).

The plan assumed v6 was latest; the actual latest is v7.2.5 (v7 released after the plan was
written). Verified under v7: tsc clean, 70 tests green, emulator discovery loads all 33
functions in us-central1 with zero errors and the "outdated firebase-functions" warning gone
(v6.6.0 still tripped that warning).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 00:03:17 -05:00
null a5af32d3d2 refactor(functions): B4+B5 migrate webhook to v2 + pin onUserDelete on v1
B4 — revenueCatWebhook: functions.https.onRequest → firebase-functions/v2/https onRequest,
with REVENUECAT_SIGNING_KEY bound as a Secret Manager secret via defineSecret (injected into
process.env, so the Ed25519 verify + process-before-ack/500-retry logic is unchanged). Request
type retyped to the v2 Request; console → logger. The key must be seeded in Secret Manager at
deploy (runbook) — it isn't in the repo.

B5 — onUserDelete: kept on the v1 API (2nd gen has no auth.user().onDelete), imported explicitly
from firebase-functions/v1 and wrapped in runWith({ timeoutSeconds: 300, memory: '512MB' }) for
its dual recursiveDelete + Storage sweep. Adopts shared getUserTokens/sendPushToUser + logger;
preserves the original "only notify if the partner has a live token" behavior.
(wrapReleaseKey's HttpsError→v2 swap already landed in B3.)

Build clean; 70 tests green. dist rebuilt. Still on firebase-functions v5.1.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 00:00:29 -05:00
null e0c2d67373 refactor(functions): B3 migrate 12 callables to v2 + harden
Migrate all callables off functions.https.onCall to firebase-functions/v2/https onCall:
createInvite, acceptInvite, leaveCouple, submitOutcome, sendGentleReminder,
sendThinkingOfYou, checkDeviceIntegrity, syncEntitlement, assignDailyQuestionCallable,
wrapReleaseKey. context.auth/app → request.auth/app, data arg → request.data. The 8
client-hardcoded callable names are preserved verbatim (verified via emulator discovery).
The manual `if (!request.app)` App Check check is a 1:1 port (no enforceAppCheck switch).

Hardening folded in:
- acceptInviteCallable: await the previously fire-and-forget partner_joined push (gen 2
  freezes the instance after the response) — still swallows push errors so a failed push
  never fails the accept.
- checkDeviceIntegrity: 10s timeout on the Play Integrity client.request so a hung upstream
  can't pin the instance (fail-closed catch already handles the throw); memory 512MiB.
- wrapReleaseKey: memory 512MiB (tink); HttpsError swapped to v2; lazy tink require + graceful
  failure preserved.
- Error mapping with `if (e instanceof HttpsError) throw e` re-throw guard around the risky
  DB sections in acceptInvite, leaveCouple, submitOutcome, sendGentleReminder,
  sendThinkingOfYou — raw errors map to a clean 'internal' without masking intentional codes
  (resource-exhausted rate limits, permission-denied, etc.). leaveCouple's best-effort
  recursiveDelete sweep now swallows errors (the transactional leave already succeeded).
- Adopt shared sendPushToUser()/logger; remove copied token readers + plaintext token logging.

Delete dead placeholder callables notifications/reminders.ts (sendDailyQuestionReminder,
sendPartnerAnsweredNotification) — no client caller; wrote sent:false rows nothing consumed.

Build clean; 70 tests green; discovery loads all callables as v2 in us-central1. dist rebuilt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:58:32 -05:00
null 6681bf1518 refactor(functions): B2 migrate 8 scheduled functions to v2 + harden
Migrate all scheduled jobs off functions.pubsub.schedule().onRun() to
firebase-functions/v2/scheduler onSchedule({ schedule, timeZone, ...opts }, handler):
sendChallengeDayReminders, unlockDueMemoryCapsules, sendDailyQuestionProactiveReminder,
sendStreakReminder, sendReengagementReminder, assignDailyQuestion (scheduled export),
aggregateOutcomeStats, scheduledOutcomesReminder.

Hardening folded in:
- Fan-out isolation: Promise.all → Promise.allSettled in dailyQuestionReminder (outer+inner),
  reengagement, gameRetention (both jobs), scheduledOutcomesReminder — one bad couple can no
  longer abort a whole run. streakReminder / assignDailyQuestion already isolated.
- Resource options: assignDailyQuestion + aggregateOutcomeStats memory 512MiB + timeout 300s
  (they iterate all couples); the four fan-out reminders get timeout 180s.
- Adopt shared sendPushToUser()/logger everywhere; remove five copied getUserTokens() and the
  copied send/prune blocks (no plaintext token logging remains here).
- Consolidate duplicated date/time helpers into notifications/time.ts (chicagoDateKey, toMillis),
  replacing streakReminder's + scheduledOutcomesReminder's per-file copies.

assignDailyQuestion.ts callable export stays v1 for now (migrates in B3); its tested CST helpers
are untouched. Scanner pagination for assignDailyQuestion/aggregateOutcomes is deferred to B6.

Build clean; 70 tests green (tested pure helpers preserved). dist rebuilt. Still on v5.1.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:50:59 -05:00
null 4040abbf28 refactor(functions): B1 migrate 13 Firestore triggers to v2 + harden
Migrate all Firestore triggers off the v1 API to firebase-functions/v2/firestore
(onDocumentCreated/Updated/Written); context.params→event.params, snap→event.data,
change.before/after→event.data.before/after. Region stays us-central1 (global option).

Hardening folded in (all reuse in-repo patterns):
- Adopt the shared sendPushToUser()/getUserTokens() helper in every trigger, removing
  ~7 copied token readers and the copied send/prune blocks. FCM tokens are no longer
  logged in plaintext anywhere here (redacted inside push.ts).
- console.* → firebase-functions/logger (structured).
- Idempotency: new claimOnce() (atomic create-if-absent marker under
  couples/{id}/notif_marks) dedupes at-least-once redelivery on the non-idempotent
  senders (onAnswerWritten/Revealed, onMessageWritten, onCoupleLeave, onEntitlementChanged,
  onDateReflectionWritten/Revealed, onDateHistoryCreated). Fail-open. onGameSessionUpdate/
  onGamePartFinished/notifyOnDateMatch already had transactional claim-flags — preserved.
- onRestoreRequested: the plan's "claim" is implemented as the existing 60s time-WINDOW
  (lastRestorePartnerAlertAt), not a permanent recipientUid marker — a permanent marker
  would wrongly block legitimate re-requests (restore docs are deleted+recreated by design).

Faithful port of onGameSessionUpdate/onGamePartFinished (broad wildcard + allowlist kept);
the trigger split and read reorder are deferred to B6 as separate commits.

Build clean; 70 tests green (+ new idempotency.test.ts, push token/prune tests). Emulator
discovery loads all triggers as v2 in us-central1. firebase-functions still v5.1.1 (v6 bump
deferred to B6). dist rebuilt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:46:17 -05:00
null fbf4e7957c build(functions): B0 v2 foundation — global options, shared push helper, structured logging
Groundwork for the v1→v2 Cloud Functions migration; no function is migrated yet
(all 35 still load as v1, verified via emulator discovery).

- options.ts: setGlobalOptions({ region: 'us-central1', maxInstances: 20 }), imported
  first in index.ts so it applies before any v2 function is defined. Region pin is
  load-bearing — the Android client uses the default region.
- notifications/push.ts: single canonical getUserTokens() + sendPushToUser() that
  batches via messaging.sendEachForMulticast() and prunes dead tokens, to replace the
  ~10 copied token readers and ~19 copied send/prune blocks in later batches.
- log.ts: firebase-functions/logger re-export + redactToken() (FCM tokens are secrets).
- push.test.ts: 9 unit tests (token merge/dedupe, BatchResponse→dead-token mapping,
  send/prune/no-op/whole-batch-failure paths). 67 tests green.

firebase-functions stays at v5.1.1 for the migration (supports both the root v1 API and
the /v2 subpaths); bump to v6 is deferred to the final batch once nothing references the
root namespace, so the build stays green at every step.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:36:16 -05:00
null 3acba138a3 chore(functions): rebuild dist for deployed daily-question + game-copy changes
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 22:31:02 -05:00
null f2321d3536 fix(functions): server-authoritative, mode-aware, deterministic daily question
Replace pickRandomQuestionId (empty pool → unresolvable q_default_daily fallback)
with pickDailyQuestionId(date): computes today's weekday mode (mirrors the client
DailyModeResolver.DOW_DEFAULTS, FROZEN) and deterministically indexes the free
daily pool by epochDay % poolSize — the SAME question the free client would pick,
now assigned server-side.

Fixes two things at the root:
- The daily 'questions' pool was empty, so every couple got q_default_daily, which
  the client can't resolve → each device fell back to its own local selection
  (the DQ-MISMATCH-001 class; the client half was pinned to the free pool in C1).
- Partners in different time zones computed different device-local weekdays and got
  different questions; a single server-assigned id makes both devices identical.

Firestore 'questions' seeded with the 75 free daily_fun_mc weekday questions (ids
match the client asset DB so getQuestionById resolves them). Pool fetched once and
filtered in memory — no composite index needed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 21:57:22 -05:00
null fda53175a9 feat(games): nudge + per-game copy + score a11y batch C4 from UX review
- Waiting-on-partner screen: 'Send a little nudge 💜' button (shown while the
  partner is still playing, not once it's your turn) reusing the generic
  thinking-of-you callable (10/day, quiet-hours-safe server-side); one-shot
  Toast on result incl. friendly rate-limit copy. Verified live: nudge →
  partner_activity push landed on the partner.
- Per-game banner copy: YOUR_TURN/RESULTS in-app banner now branches on gameType
  ('Your turn — guess their answers' for How Well, 'only mutual yeses ever show'
  for Desire Sync, etc.) instead of one generic line; mirrored in the Cloud
  Function's partner_completed_part push (yourTurnBody). Verified live.
- Accessibility: merged contentDescription on the This or That MatchScoreBadge
  ('You matched on N of M') and the How Well score ring Canvas ('You guessed N
  of M correctly') — both were split/Canvas visuals invisible to TalkBack.

Unit + functions typecheck green; assembleDebug clean. Server copy change needs
a functions deploy (bundled with the C1 finish-guard).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 21:50:39 -05:00
null 4ab79d34c4 fix(ui,games): defect-polish batch C1 from P3/UX review
- Challenges catalog: hide the 🔒 Premium badge once the couple has premium
  (A-003b; matches the Play hub's showPremiumBadge pattern). Verified live
  both directions under an authorized grant/revoke cycle.
- Game banner lifecycle (BANNER-LIFE-001): entering a session's screen now
  consumes any banner pointing at it (GamePromptController.consumeForSession
  wired into ActiveGameSessionMonitor.enter), and activity from a DIFFERENT
  session may replace a stale persistent banner. Verified live: no banner on
  reveal; stale RESULTS banner replaced by a new session's prompt.
- Waiting/join screen: says 'Your turn — {name} already played their part'
  for the non-starter once a first part landed (new partHasFinished mapped
  from partFinishNotifiedAt; completedByUsers only fills at reveal). Session
  observe mapping now also carries completedByUsers/joinedByUsers.
- How Well results: matched-row colors are now a theme-aware container+content
  pair (dark mode was near-invisible: fixed pale-green container under
  onSurfaceVariant text).
- Date Match: top card fully opaque — next card's text no longer bleeds
  through (was alpha 0.96).
- functions: don't send 'X finished — see your results!' for abandoned/quit
  sessions (status flips to completed with empty completedByUsers; a real
  completion always has both uids). Found live when a quit triggered a false
  banner. Needs deploy (bundled with C4).

Unit + functions suites green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 21:03:22 -05:00
null e5868bd6b1 fix(games,daily): correctness batch from games review
- Game answer listeners (ToT/HowWell/DesireSync): close(err) instead of
  swallowing snapshot errors, + .catch in each VM's observeReveal surfacing a
  retryable ERROR (GameCopy.SYNC_ERROR + retrySync re-attach) — games no longer
  hang on WAITING forever on listener failure (GAME-HANG-001; matches the
  Wheel/Capsule sources' established pattern).
- Daily question: paired fallback pool is now premium-INDEPENDENT so both
  partners always resolve the same deterministic question; viewer-premium pools
  broke the couple contract when entitlement state differed or flipped mid-day
  (DQ-MISMATCH-001, reproduced live: partners answered different questions).
- Daily reveal: humanize raw option-id fallbacks so slugs never render
  (DQ-SLUG-001, e.g. 'fake_awards_should_be_mandatory').
- assignDailyQuestion.ts: replace hardcoded CST_OFFSET_HOURS=-6 with DST-safe
  Intl America/Chicago helpers (DST-001) + 5 regression tests (CDT/CST labeling,
  6PM reveal instant, spring-forward round-trip).

Verified live 2-device: identical daily question on both partners post-fix;
ToT full loop 5/5 reveal regression clean. Unit 244 + functions 58 green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 19:41:41 -05:00
null 89cbd7cb55 refactor(functions): type callable payloads instead of `any`
Change the 5 https.onCall handlers from `data: any` to
`data: Record<string, unknown>`, so payload fields are `unknown` and must go
through the existing validators rather than being implicitly-typed. No behavior
change (every field was already validated); tsc + 53 function tests green.

Left as-is deliberately: `catch (err: unknown)` narrowing (churn, marginal) and
the untyped Tink handles in wrapReleaseKeyCallable (the crypto lib ships no types).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 22:06:45 -05:00
null eeac3c9383 build(functions): compile dist for outcome aggregation
Tracked dist output rebuilt to match src (aggregateOutcomeStats export +
aggregateOutcomes module), keeping the deployed bundle in sync with source.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 21:10:02 -05:00
null 943507b72a feat(functions): privacy-safe outcome-stat aggregation
aggregateOutcomeStats (scheduled) rolls up per-couple check-in deltas
(couples/{id}/outcomes/day_30|60|90) into the "X% feel closer in N weeks" stat
WITHOUT reading any E2EE content — only the self-reported deltas.

Privacy: counts/percentages only (no couple id or individual scores);
minimum-cohort suppression (N<50 → window omitted, no percentages); EXPORT-ONLY
via the top-level aggregate_stats collection, now explicitly deny-all in
firestore.rules (owner reads via console).

Pure aggregate()/extractCoupleOutcome() unit-tested incl. below-threshold
suppression + a no-PII assertion (6 tests); rules deny client read/write of
aggregate_stats (2 tests). Full functions 53/53, rules 121/121.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 21:06:57 -05:00
null 95c3bc21fa feat(dates): Firestore-backed date catalog + sponsored ideas
- DateIdea gains sponsored/sponsorName/externalUrl (native, clearly-labeled ads
  — no tracking SDK).
- FirestoreDateIdeaDataSource reads the server-curated date_ideas collection
  (defensive: malformed docs skipped, https-only externalUrl); DateMatchRepo
  serves remote first, falling back to the shipped static seed when empty/failed
  so the feature always has content. Fallback verified live (Date Match renders
  the seed) + unit-tested (remote-present / empty / failure).
- Date card shows a "Sponsored · <name>" pill and a "Learn more" link (opened via
  the system browser, https-only, no click IDs).
- Local admin seeder (functions/scripts/seedDateIdeas.ts + date_ideas_seed.json,
  generated from the Kotlin seed + 1 sponsored example) — idempotent by id, has a
  --dry-run; NOT a deployed endpoint. Verified: 38 docs upserted to the emulator,
  1 sponsored, tsc builds.

Owner: run the seeder against prod (GOOGLE_APPLICATION_CREDENTIALS) to populate
date_ideas; add real sponsor content.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 21:02:22 -05:00
null 896bf26b28 feat: date reflection reveal, UI upgrade plan, seed updates, ime-scan script 2026-07-01 04:12:58 -05:00
null d8408a2c44 chore(functions): rebuild dist with pruneDeadTokens wired into all 19 push sites 2026-06-30 23:45:42 -05:00
null afd1eab299 feat(users): wire pruneDeadTokens into onUserDelete 2026-06-30 23:45:36 -05:00
null 2488e18790 feat(notifications): wire pruneDeadTokens into streakReminder 2026-06-30 23:45:31 -05:00
null 40e4f48131 feat(notifications): wire pruneDeadTokens into dailyQuestionReminder 2026-06-30 23:45:26 -05:00
null 355edd0887 feat(couples): wire pruneDeadTokens into acceptInviteCallable 2026-06-30 23:45:21 -05:00
null f55c49010d feat(notifications): wire pruneDeadTokens into sendThinkingOfYouCallable 2026-06-30 23:36:09 -05:00
null 5306d40c72 feat(notifications): wire pruneDeadTokens into sendGentleReminderCallable 2026-06-30 23:35:59 -05:00
null e35b8151c6 feat(notifications): wire pruneDeadTokens into reengagement 2026-06-30 23:35:49 -05:00
null 35eca7d08d feat(notifications): wire pruneDeadTokens into gameRetention 2026-06-30 23:35:42 -05:00
null 7b5790da43 feat(billing): wire pruneDeadTokens into onEntitlementChanged 2026-06-30 23:35:38 -05:00
null c7181e276f feat(questions): wire pruneDeadTokens into onMessageWritten 2026-06-30 23:35:29 -05:00
null 8b3356e60d feat(questions): wire pruneDeadTokens into onAnswerWritten 2026-06-30 23:35:24 -05:00
null 9ca9f19c51 feat(questions): wire pruneDeadTokens into onAnswerRevealed 2026-06-30 23:35:20 -05:00
null 13c0769efb feat(games): wire pruneDeadTokens into onGameSessionUpdate 2026-06-30 23:35:15 -05:00
null ffa038ca56 feat(dates): wire pruneDeadTokens into onDateReflectionWritten 2026-06-30 23:35:07 -05:00
null 2aa08efd39 feat(dates): wire pruneDeadTokens into onDateHistoryCreated 2026-06-30 23:35:00 -05:00
null f8240e01a9 feat(dates): wire pruneDeadTokens into createDateMatch 2026-06-30 23:34:56 -05:00