wake-alarm/phone_app/lib/services/room_proof_settings.dart
Krzysztof kuhy Rudnicki 150a8cd7e5 Require two tags, the walk, and three answers to dismiss
The dismiss gate was an OR — NFC tag *or* QR *or* (25 steps + 2 min) —
followed by one challenge. QR never worked at ring time (no scanner
package, no CAMERA permission, `onQrScanned` had no caller), so the real
bar was "walk 25 steps, wait 2 minutes, answer one question" and the NFC
tag was already fully bypassable.

It is now a strict, latched sequence owned by `DismissGate`:

    tag 1 -> 25 steps + 2 min -> tag 2 -> 3 challenges

Every stage is required, in that order, and a stage once passed never
reverts. That last part also fixes a real bug: `_onNfcTag` and `_trySteps`
both assigned the room-proof result straight onto `_inRoom`, so a wrong
tag tapped after the gate had passed sent the user back to the start.

Two *distinct* tags are required; the same id in both slots is refused at
registration, since one tag satisfying both stages removes the walk that
is the whole point. The existing single-tag registration migrates into
slot 1 rather than being stranded.

Answers are cumulative, not consecutive: a wrong one costs the attempt and
nothing else.

The bypass is the only fallback and is deliberately narrow. After 5 minutes
of ringing, or immediately when NFC is off or fewer than two distinct tags
are registered, the two *tag* stages are skipped and the count rises to 6.
The walk is never skipped — jumping straight to the challenges would let
someone lie in bed for five minutes and answer questions without standing
up, which is weaker than the gate this replaces. Without some such hatch a
dead tag at 06:00 leaves an alarm that cannot be switched off at all.

Also deletes the `flash` challenge outright, along with the now-orphaned
`generateCode`/`kDismissCodeLength`/`_dismissChars`. It was the only kind
that removed its prompt from the screen, which is unsolvable for someone
who has just walked in from another room.

The ring screen takes an injectable clock: `Stopwatch` reads the wall
clock, which `tester.pump()` does not advance, so without that seam no
widget test could reach the two-minute floor or the five-minute bypass.

Verified on the Pixel 6a: the existing tag migrated into slot 1 and both
rows render. 102 Dart tests pass; analyzer clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
2026-08-30 15:09:00 +02:00

92 lines
3.4 KiB
Dart

import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
/// Persisted room-proof configuration: the two registered NFC tags.
///
/// Two tags, in two different places, are what force the walk. Registering
/// fewer than [requiredTagCount] does not weaken the sequence into something
/// easier — it makes the NFC stages unsatisfiable, which is why the ring
/// screen drops straight to the bypass when [isComplete] is false.
class RoomProofSettings {
/// Creates settings from the registered tag ids, one per slot.
const RoomProofSettings({this.nfcTagIds = const <String>['', '']});
/// SharedPreferences key holding the tag ids as a JSON list.
static const String kNfcTagsKey = 'roomProof.nfcTagIds';
/// The pre-two-tag key, migrated into slot 0 on first load.
static const String kLegacyNfcTagKey = 'roomProof.nfcTagId';
/// How many tags the strict sequence needs.
static const int requiredTagCount = 2;
/// Registered tag ids by slot; an empty string means that slot is unset.
///
/// Always [requiredTagCount] long, so slot writes never have to grow it.
final List<String> nfcTagIds;
/// The tag registered for [slot], or null when that slot is unset.
String? tagAt(int slot) {
if (slot < 0 || slot >= nfcTagIds.length) return null;
final id = nfcTagIds[slot];
return id.isEmpty ? null : id;
}
/// Whether every slot holds a distinct tag, so the sequence is satisfiable.
///
/// Distinctness matters: two slots holding the same id would let one tap
/// satisfy both stages, collapsing the walk this whole gate exists to force.
bool get isComplete {
final ids = <String>{};
for (var slot = 0; slot < requiredTagCount; slot++) {
final id = tagAt(slot);
if (id == null || !ids.add(id)) return false;
}
return true;
}
/// Normalises [raw] to exactly [requiredTagCount] slots.
static List<String> _padded(List<String> raw) => List<String>.generate(
requiredTagCount,
(i) => i < raw.length ? raw[i] : '',
);
/// Loads the stored configuration, migrating a single legacy tag if present.
static Future<RoomProofSettings> load() async {
final prefs = await SharedPreferences.getInstance();
final stored = prefs.getString(kNfcTagsKey);
if (stored != null) {
return RoomProofSettings(nfcTagIds: _padded(_decode(stored)));
}
// One-time migration: an existing install has a tag registered under the
// old key, and silently losing it would leave the user unable to dismiss
// by the normal path on the first morning after the update.
final legacy = prefs.getString(kLegacyNfcTagKey);
return RoomProofSettings(
nfcTagIds: _padded(<String>[?legacy]),
);
}
/// Decodes the stored JSON list, treating anything malformed as unset.
static List<String> _decode(String stored) {
try {
final decoded = jsonDecode(stored);
if (decoded is! List) return const <String>[];
return decoded.whereType<String>().toList();
} on FormatException {
return const <String>[];
}
}
/// Stores [tagId] in [slot], leaving the other slot untouched.
static Future<void> saveNfcTagAt(int slot, String tagId) async {
final current = await load();
final next = List<String>.of(current.nfcTagIds);
if (slot < 0 || slot >= next.length) return;
next[slot] = tagId;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(kNfcTagsKey, jsonEncode(next));
}
}