Closer/functions/dist/couples/onCoupleKeyRotated.js

84 lines
4.2 KiB
JavaScript
Raw Normal View History

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
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.onCoupleKeyRotated = void 0;
exports.isKeyGenerationIncrease = isKeyGenerationIncrease;
const admin = __importStar(require("firebase-admin"));
const firestore_1 = require("firebase-functions/v2/firestore");
const queueAndPush_1 = require("../notifications/queueAndPush");
const log_1 = require("../log");
/**
* Fires when a couple's key generation increases one member rotated the couple key.
*
* Two jobs in one push, sent to BOTH members (every device):
* 1. Security signal ("was this you?" philosophy, same class as the restore self-alerts bypasses
* quiet hours, no preference toggle): a key rotation is worth knowing about even when benign.
* 2. Functional pickup nudge: the partner's closed app still holds only the old key and cannot
* decrypt anything written under the new one until it next loads Home the tap gets them there,
* where the existing adoption path unwraps the rotated keyset. No key material is read or logged.
*/
/** Pure edge guard: fire only when keyGeneration strictly increases (ignores every other update). */
function isKeyGenerationIncrease(before, after) {
const b = typeof before === 'number' ? before : 0;
const a = typeof after === 'number' ? after : 0;
return a > b;
}
exports.onCoupleKeyRotated = (0, firestore_1.onDocumentUpdated)('couples/{coupleId}', async (event) => {
var _a, _b, _c;
const before = (_a = event.data) === null || _a === void 0 ? void 0 : _a.before.data();
const after = (_b = event.data) === null || _b === void 0 ? void 0 : _b.after.data();
if (!isKeyGenerationIncrease(before === null || before === void 0 ? void 0 : before.keyGeneration, after === null || after === void 0 ? void 0 : after.keyGeneration))
return;
const { coupleId } = event.params;
const db = admin.firestore();
const userIds = ((_c = after === null || after === void 0 ? void 0 : after.userIds) !== null && _c !== void 0 ? _c : []);
if (userIds.length === 0)
return;
log_1.logger.log(`[onCoupleKeyRotated] couple=${coupleId} generation=${after === null || after === void 0 ? void 0 : after.keyGeneration}`);
// Per-member isolation: one failed send must not cost the other member their alert.
const results = await Promise.allSettled(userIds.map((uid) => (0, queueAndPush_1.queueAndPush)(db, uid, {
type: 'couple_key_rotated',
title: '🔑 Security update',
body: 'Your shared key was rotated. Open the app and everything continues as normal.',
coupleId,
bypassQuietHours: true,
})));
results.forEach((r, i) => {
if (r.status === 'rejected') {
log_1.logger.warn('[onCoupleKeyRotated] alert failed', { uid: userIds[i], error: String(r.reason) });
}
});
});
//# sourceMappingURL=onCoupleKeyRotated.js.map