Split GitHub token lookup out of transport

_sync_transport.py hit 280 lines against the 250 cap and AGENTS.md
258; both failed the all-files gate on origin/main. The token lookup
(config file, then a sibling app's file) moves to _sync_token.py
unchanged. Tests now patch SYNC_CONFIG_FILE and
SYNC_TOKEN_FALLBACK_FILES on _sync_token, where they are read.
AGENTS.md is reflowed to 250 lines with every rule kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
This commit is contained in:
Krzysztof Rudnicki 2026-11-16 08:54:02 +01:00
parent 7a3b767075
commit 677a9f0f00
10 changed files with 163 additions and 159 deletions

132
AGENTS.md
View File

@ -39,8 +39,8 @@ passing sent the user back to the start.
re-baselined at tag 1, so walking to tag 1 already banks them and the stage re-baselined at tag 1, so walking to tag 1 already banks them and the stage
passes on its first poll. The 2-minute elapsed floor (`requiredElapsed`) passes on its first poll. The 2-minute elapsed floor (`requiredElapsed`)
applies **only under bypass/away**, where no tag proved the walk and a applies **only under bypass/away**, where no tag proved the walk and a
shaken phone would count; on the normal path it was two minutes of ringing shaken phone would count; on the normal path it only added two minutes of
nothing could shorten (dropped 2026-09-16). ringing (dropped 2026-09-16).
- **Answers are cumulative, not consecutive.** A wrong one costs the attempt - **Answers are cumulative, not consecutive.** A wrong one costs the attempt
and nothing else. and nothing else.
- **The bypass skips the tags, never the walk.** After - **The bypass skips the tags, never the walk.** After
@ -50,8 +50,7 @@ passing sent the user back to the start.
bed for five minutes and answer questions without standing up — weaker than bed for five minutes and answer questions without standing up — weaker than
the gate this replaced. Do not "simplify" it into that. the gate this replaced. Do not "simplify" it into that.
- **No challenge may hide its prompt.** The memorise-then-hide kind was - **No challenge may hide its prompt.** The memorise-then-hide kind was
deleted, not merely unrouted: the ring screen is reached by walking in from deleted, not merely unrouted: the ring screen is reached by walking in.
another room.
**The dismiss does not end the morning.** Since 2026-09-16 it hands over, in **The dismiss does not end the morning.** Since 2026-09-16 it hands over, in
the same activity, to the silent **morning session**: weigh in → bathroom tag the same activity, to the silent **morning session**: weigh in → bathroom tag
@ -69,10 +68,10 @@ clock, and everything that is a hard crash or a silent no-ring:
**`DOCS-phone-alarm.md`**. **`DOCS-phone-alarm.md`**.
**Free days.** On a day in the shared pool (`~/src/utils/freedays`) the phone **Free days.** On a day in the shared pool (`~/src/utils/freedays`) the phone
does not ring at all: `AlarmReceiver` checks a native cache Dart rewrites does not ring: `AlarmReceiver` checks a native cache Dart rewrites after every
after every mark/release/sync. Picker, cache and its fail-closed contract: mark/release/sync. Picker, cache, fail-closed contract: **`DOCS-free-days.md`**.
**`DOCS-free-days.md`**. Sick days (`~/src/utils/sickdays`, never a free day): Sick days (`~/src/utils/sickdays`, never a free day): phone + pre-alarm sync
phone + pre-alarm sync **`DOCS-sick-days.md`**, PC **`DOCS-wake-enforcement.md`**. **`DOCS-sick-days.md`**, PC **`DOCS-wake-enforcement.md`**.
## Scheduling — a per-minute timer ## Scheduling — a per-minute timer
@ -88,16 +87,17 @@ today's fire instant in **local** time, and fires iff `now` is in
`was_trigger_fired_today()`. Without it the routine restarts on every tick for `was_trigger_fired_today()`. Without it the routine restarts on every tick for
the rest of the 60-minute window: the unit is `Type=simple`, so a start while the rest of the 60-minute window: the unit is `Type=simple`, so a start while
it runs is a no-op, but the moment the workout lock finishes the next tick it runs is a no-op, but the moment the workout lock finishes the next tick
relaunches it on top of the user. This latch replaced the alarm's own relaunches it on top of the user. The latch replaced the alarm's own dismissal
dismissal record when `_alarm.py` was deleted — deleting one without adding the record when `_alarm.py` was deleted; deleting one without adding the other is
other is a silent regression, and that is exactly the trap. a silent regression.
`Persistent=true` plus the 60-minute window is also what replaced the deleted `Persistent=true` plus the 60-minute window also replaced the deleted
systemd-sleep hook: a suspended or just-booted machine still fires. systemd-sleep hook: a suspended or just-booted machine still fires.
## Reading the phone's alarm ## Reading the phone's alarm
`_sync.py` is the only reader. `_sync.py` is the only reader; `_sync_transport.py` fetches, `_sync_token.py`
holds the GitHub-token lookup (stdlib-only).
- Source of truth: a `crdt_sync` log written by `phone_app/` under - Source of truth: a `crdt_sync` log written by `phone_app/` under
`wake-alarm-sync/devices-e2e/<device-id>/alarm.json`, at `wake-alarm-sync/devices-e2e/<device-id>/alarm.json`, at
@ -111,50 +111,45 @@ systemd-sleep hook: a suspended or just-booted machine still fires.
or wrong passphrase reads as "nothing published" (cache, then 08:00) — or wrong passphrase reads as "nothing published" (cache, then 08:00) —
never plaintext. diet_guard reads the same prefix for weigh-ins. never plaintext. diet_guard reads the same prefix for weigh-ins.
- **The Firebase reader discovers device directories; it is not pinned to - **The Firebase reader discovers device directories; it is not pinned to
`devices/phone/`.** The phone's device id is migrating from the fixed `devices/phone/`.** The phone's device id is migrating from the constant
constant `phone` to a per-install uuid, and a pinned reader would silently `phone` to a per-install uuid; a pinned reader would silently stop seeing
stop seeing the alarm and fall back to 08:00 — i.e. the wrong the alarm and fall back to 08:00, the wrong time. `_fetch_firebase_alarm()`
time. `_fetch_firebase_alarm()` lists `SYNC_DEVICES_PREFIX`, reads every lists `SYNC_DEVICES_PREFIX`, reads every device's `alarm.json`, and picks the
device's `alarm.json`, and picks the newest by the hour field's **HLC**, with newest by the hour field's **HLC** (`device_id` breaks exact ties). A payload
`device_id` breaking exact ties. A payload that does not parse is skipped that does not parse is skipped, never allowed to win. `SYNC_ALARM_PATH`
rather than allowed to win. `SYNC_ALARM_PATH` remains as a last-resort read stays as a last-resort read for a backend that lists nothing.
for a backend that lists nothing. - Payload parsing/ranking lives in `_alarm_payload.py` ("what did the phone
- Payload parsing/ranking lives in `_alarm_payload.py`: `_sync.py` owns say"); `_sync.py` owns fetching, caching and fallback.
fetching, caching and fallback; `_alarm_payload.py` owns "what did the phone
actually say".
- **Firebase first, GitHub as the cutover mirror.** Retiring the mirror is - **Firebase first, GitHub as the cutover mirror.** Retiring the mirror is
deleting the GitHub branch plus `SYNC_API_BASE`/`SYNC_REPO_*`. deleting the GitHub branch plus `SYNC_API_BASE`/`SYNC_REPO_*`.
- Firebase config: shared `~/.config/crdt-sync/firebase.json`; the refresh - Firebase config: shared `~/.config/crdt-sync/firebase.json`; the refresh
token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config file token is cached per app under `SYNC_APP_NAME` (`wake_alarm`). The config is
is checked **before** anything is constructed, so an unconfigured machine checked **before** anything is constructed, so an unconfigured machine never
never touches the network. touches the network.
- GitHub token (fallback only): `~/.config/wake_alarm/sync.json` key `token`, - GitHub token (fallback only): `~/.config/wake_alarm/sync.json` key `token`,
else diet_guard's raw `~/.config/diet_guard/sync_token` (screen-locker is else diet_guard's raw `~/.config/diet_guard/sync_token` (screen-locker's is no
Firebase-only since 2026-10-09; its `sync_token` is no longer read). longer read: Firebase-only since 2026-10-09). Needs `repo` scope; the repo is
Needs `repo` scope — the repo is private, so a token without access returns private, so a token without access returns **404, not 403**.
**404, not 403**.
- `crdt_sync` is imported at module scope but **guarded by - `crdt_sync` is imported at module scope but **guarded by
`try/except ImportError`**: the service runs `/usr/bin/python`, not a venv, so `try/except ImportError`**: the service runs `/usr/bin/python`, not a venv, so
a dependency that failed to install must degrade the read to the cache a dependency that failed to install must degrade the read to the cache
rather than crash the per-minute trigger. Both backends need it now (the rather than crash the per-minute trigger. Both backends need it (the GitHub
GitHub mirror is read through `GitHubSyncClient`, encrypted too). Verify with `/usr/bin/python3 -c "import crdt_sync"`, not the mirror is read through `GitHubSyncClient`, encrypted too). Verify with
dev venv. `/usr/bin/python3 -c "import crdt_sync"`, not the dev venv.
- Resolution chain in `get_alarm()`: fresh cache (< 5 min) → live fetch → stale - Resolution chain in `get_alarm()`: fresh cache (< 5 min) → live fetch → stale
cache → 08:00. The cache bounds remote reads to ~288/day cache → 08:00. The cache bounds remote reads to ~288/day.
despite the per-minute tick.
- **A record older than `PUBLISHED_ALARM_MAX_AGE_SECONDS` (14 days) is skipped - **A record older than `PUBLISHED_ALARM_MAX_AGE_SECONDS` (14 days) is skipped
at every step, including the cache.** The check is on when the *phone at every step, including the cache.** The check is on when the *phone
stamped it*, never on when we fetched — checking the fetch is trivially stamped it*, never on when we fetched: the cache is rewritten from the same
defeated, because the cache is rewritten from the same stale record every few stale record every few minutes, so `fetched_at` is always fresh. That is why
minutes, so `fetched_at` is always fresh however old the record behind it is. the winning HLC's instant is carried through `_alarm_payload` →
That is why the winning HLC's instant is carried through `_alarm_payload` →
`_sync_transport` → the cache's `published_at`. Expiring is safe because `_sync_transport` → the cache's `published_at`. Expiring is safe because
08:00 is the latest the phone can ever arm. An **undated** record is 08:00 is the latest the phone can ever arm. An **undated** record is
trusted, not expired: the GitHub mirror has no per-field HLC, so treating trusted: the GitHub mirror has no per-field HLC, so treating "cannot tell"
"cannot tell" as "too old" would break that backend entirely. as "too old" would break that backend entirely.
- **Degraded reads log at INFO, not WARNING.** `get_alarm()` runs every minute; - **Degraded reads log at INFO, not WARNING.** `get_alarm()` runs every minute;
a persistent condition logged loudly is 1440 journal lines a day. `_trigger` a loud persistent condition is 1440 journal lines a day. `_trigger` emits the
emits the single WARNING that matters: firing *now* on a non-phone time. one WARNING that matters: firing *now* on a non-phone time.
- **The morning session is the carrot** (`_session.py`, `wake-alarm-session.timer`, - **The morning session is the carrot** (`_session.py`, `wake-alarm-session.timer`,
**`DOCS-morning-session-pc.md`**): a completed-in-time morning defers the **`DOCS-morning-session-pc.md`**): a completed-in-time morning defers the
workout and LeetCode locks to 11:00 via one signed file both consumers read. workout and LeetCode locks to 11:00 via one signed file both consumers read.
@ -167,11 +162,10 @@ is what `_trigger` starts, and it now runs one leg: `screen_locker.screen_lock`.
Its alarm leg was removed in the same change that deleted `_alarm.py`. Its alarm leg was removed in the same change that deleted `_alarm.py`.
**When this package's module paths change, the orchestrator must change in the **When this package's module paths change, the orchestrator must change in the
same commit.** Leaving it pointing at a module that no longer exists caused a same commit.** A stale path caused a month-long silent production failure
month-long silent production failure once already (2026-05-28, orchestrator (2026-05-28, orchestrator still on `python_pkg.screen_locker.screen_lock` after
still on `python_pkg.screen_locker.screen_lock` after screen-locker's screen-locker's extraction): the alarm fired and dismissed correctly while the
extraction): the alarm fired and dismissed correctly while the workout lock workout lock crashed with `ModuleNotFoundError` on every run.
crashed with `ModuleNotFoundError` on every run.
## Production dependency installation ## Production dependency installation
@ -183,26 +177,26 @@ site-packages:
/usr/bin/python3 -m pip install --user --break-system-packages -e . /usr/bin/python3 -m pip install --user --break-system-packages -e .
``` ```
**Run `install.sh` (or `pip install -e`) from a durable clone**, not a scratch **Run `install.sh` (or `pip install -e`) from a durable clone**
directory — it is editable, so a later `git pull` in that clone updates the (`~/src/wake-alarm`, mirroring `~/src/screen-locker`), not a scratch directory:
running production code. From `/tmp` or via `pip install "wake_alarm @ git+..."` it is editable, so a later `git pull` there updates the running production
you get a snapshot frozen at that commit, and the next push silently does not code. From `/tmp` or via `pip install "wake_alarm @ git+..."` you get a
reach the running service. Convention: `~/src/wake-alarm`, mirroring snapshot frozen at that commit, and the next push silently does not reach the
`~/src/screen-locker`. service.
If you add a dependency and only install it into a dev venv, the service fails A dependency installed only into a dev venv makes the service fail with
with `ModuleNotFoundError` on its next run — this exact gap caused a 3-day `ModuleNotFoundError` on its next run (this gap caused a 3-day diet_guard
diet_guard outage. Verify against `/usr/bin/python3 -c "import <dep>"`. outage). Verify against `/usr/bin/python3 -c "import <dep>"`.
## Uninstalling ## Uninstalling
`uninstall.sh`, never `rm -rf` on the repo: it also removes the root ring `uninstall.sh`, never `rm -rf` on the repo: it also removes the root ring
unit, the logind power-key drop-in and an RTC alarm we armed, and retires the unit, the logind power-key drop-in and an RTC alarm we armed, and retires the
old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls `uninstall.sh --retired-only` as its last step, so old `/usr/local/bin/shutdown` wrapper wherever one survives. `install.sh` calls
**`uninstall.sh` is load-bearing for installing**, not just for removing — `uninstall.sh --retired-only` last, so **`uninstall.sh` is load-bearing for
renaming or deleting it breaks a fresh install. That call is non-fatal and installing** — renaming or deleting it breaks a fresh install. That call is
gated on `sudo -n`: the cleanup needs root, and a hard failure there would non-fatal and gated on `sudo -n`: the cleanup needs root, and a hard failure
abort an install that had already placed the package and enabled the timer. would abort an install that had already placed the package and the timer.
**`/etc/sudoers.d/wake-alarm` is deliberately left in place** even by a full **`/etc/sudoers.d/wake-alarm` is deliberately left in place** even by a full
uninstall. Since 2026-10-01 it is live again: the RTC self-wake's `rtcwake` uninstall. Since 2026-10-01 it is live again: the RTC self-wake's `rtcwake`
@ -213,11 +207,9 @@ and the root ring unit's `systemctl start|stop` lines live there.
- **`wake_state.json` is runtime state, not tracked.** It holds the - **`wake_state.json` is runtime state, not tracked.** It holds the
HMAC-signed once-per-day latch. It was accidentally committed in the HMAC-signed once-per-day latch. It was accidentally committed in the
monorepo and must stay gitignored here. monorepo and must stay gitignored here.
- **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.** - **`WAKE_STATE_FILE` is redirected in `tests/conftest.py`, not per-file.** A
`_trigger` writes it now, and the trigger tests never redirected it — a per-file redirect gets forgotten when a new writer appears (`_trigger` was
per-file redirect is exactly the kind that gets forgotten when a new writer one), and the failure is silent: a green suite that stamped the live file.
appears, and the failure is silent: a green suite that quietly stamped the
live state file.
## Commands ## Commands
@ -229,12 +221,12 @@ and the root ring unit's `systemctl start|stop` lines live there.
- coverage-gaps: `coverage-gaps coverage.xml` - coverage-gaps: `coverage-gaps coverage.xml`
- deploy: `git -C ~/src/wake-alarm pull --ff-only && ~/src/wake-alarm/scripts/deploy.sh` (editable install under /usr/bin/python3 + timers and `_trigger --dry-run` health check, then the release APK onto the Pixel via phone_deploy, health = installed base.apk equals the built one; `--build-only` for board sessions, `--check` for the health check alone; unit or root-file changes still need `bash install.sh`) - deploy: `git -C ~/src/wake-alarm pull --ff-only && ~/src/wake-alarm/scripts/deploy.sh` (editable install under /usr/bin/python3 + timers and `_trigger --dry-run` health check, then the release APK onto the Pixel via phone_deploy, health = installed base.apk equals the built one; `--build-only` for board sessions, `--check` for the health check alone; unit or root-file changes still need `bash install.sh`)
Other: full lint gate `pre-commit run --all-files`; watch live Other: full lint gate `pre-commit run --all-files`; live log
`journalctl --user -fu wake-alarm-trigger.service`; `bash install.sh` / `journalctl --user -fu wake-alarm-trigger.service`; `bash install.sh` /
`bash uninstall.sh`; shell/system scripts gate `bash scripts/vmbox/harness.sh` `bash uninstall.sh`; shell/system scripts gate `bash scripts/vmbox/harness.sh`
(disposable Arch VM, **`DOCS-vmbox.md`**); emulator morning (disposable Arch VM, **`DOCS-vmbox.md`**); emulator morning
`phone_app/scripts/emu_morning.py` (`DOCS-morning-session.md`); ring the phone `phone_app/scripts/emu_morning.py` (`DOCS-morning-session.md`); ring the phone
via `lib/main_ring_probe.dart` (`DOCS-phone-alarm.md` — starts a **real** via `lib/main_ring_probe.dart` (`DOCS-phone-alarm.md`, starts a **real**
alarm). The dev venv lacks `gatelock`: anything importing `_state` (incl. alarm). The dev venv lacks `gatelock`: anything importing `_state` (incl.
`_trigger`) needs `/usr/bin/python3`, not `.venv/bin/python`. `_trigger`) needs `/usr/bin/python3`, not `.venv/bin/python`.

View File

@ -41,8 +41,6 @@ from wake_alarm._sync_transport import (
_FIREBASE_AVAILABLE, _FIREBASE_AVAILABLE,
_fetch_firebase_alarm, _fetch_firebase_alarm,
_fetch_github_alarm, _fetch_github_alarm,
_read_token,
_read_token_fallback,
fetch_remote_alarm, fetch_remote_alarm,
) )
@ -55,8 +53,6 @@ __all__ = [
"Alarm", "Alarm",
"_fetch_firebase_alarm", "_fetch_firebase_alarm",
"_fetch_github_alarm", "_fetch_github_alarm",
"_read_token",
"_read_token_fallback",
"fetch_remote_alarm", "fetch_remote_alarm",
"get_alarm", "get_alarm",
] ]
@ -201,7 +197,7 @@ def get_alarm(*, max_cache_age_seconds: float = ALARM_CACHE_MAX_AGE_SECONDS) ->
return Alarm(remote[0], remote[1], "remote") return Alarm(remote[0], remote[1], "remote")
# Both degraded paths log at INFO for the same per-minute-tick reason as # Both degraded paths log at INFO for the same per-minute-tick reason as
# _read_token above; _trigger warns when it fires on a degraded source. # the transport; _trigger warns when it fires on a degraded source.
if cached is not None: if cached is not None:
_logger.info("Using stale cached alarm — sync read failed") _logger.info("Using stale cached alarm — sync read failed")
return Alarm(cached[0], cached[1], "stale-cache") return Alarm(cached[0], cached[1], "stale-cache")

69
wake_alarm/_sync_token.py Normal file
View File

@ -0,0 +1,69 @@
"""The GitHub-mirror token: this package's own config, then a sibling app's.
Split out of ``_sync_transport.py`` for the 250-line cap. Only the GitHub
fallback needs a token; Firebase authenticates through ``crdt_sync``'s own
cached refresh token. Stdlib-only on purpose: the per-minute trigger runs
``/usr/bin/python`` and must import this even when ``crdt_sync`` failed to
install.
"""
from __future__ import annotations
import json
import logging
from wake_alarm._constants import SYNC_CONFIG_FILE, SYNC_TOKEN_FALLBACK_FILES
_logger = logging.getLogger(__name__)
def _read_token_config() -> str | None:
"""Read the token from this package's own JSON config.
Returns:
The token, or None if the file is missing, unreadable, malformed, or
holds no usable token.
"""
try:
with SYNC_CONFIG_FILE.open() as handle:
config = json.load(handle)
except OSError, json.JSONDecodeError:
return None
if not isinstance(config, dict):
return None
token = config.get("token")
if not isinstance(token, str) or not token:
return None
return token
def _read_token_fallback() -> str | None:
"""Read the token from a sibling app's raw single-line token file.
Returns:
The first usable token found, or None if none of the fallback files
exists or holds one.
"""
for path in SYNC_TOKEN_FALLBACK_FILES:
try:
token = path.read_text().strip()
except OSError:
continue
if token:
_logger.debug("Using sync token from %s", path)
return token
return None
def read_token() -> str | None:
"""Read the GitHub token, preferring this package's own config.
Falls back to diet_guard's token file so one repo-scoped PAT covers
every app syncing through ``kuhyx/syncs``.
Returns:
The token, or None if no configured source holds one.
"""
# No warning on a miss here: the caller reports "no token" once. Logging
# twice for one unconfigured file makes every tick noisy in the journal.
return _read_token_config() or _read_token_fallback()

View File

@ -1,8 +1,9 @@
"""Fetching the alarm the phone pushed — Firebase first, GitHub as mirror. """Fetching the alarm the phone pushed — Firebase first, GitHub as mirror.
Split out of ``_sync.py`` for the 250-line cap, along the seam item 8 needs: Split out of ``_sync.py`` for the 250-line cap, along the seam item 8 needs:
this module is the **transport** (token discovery and the two backends), while this module is the **transport** (the two backends; the GitHub token lives in
``_sync.py`` keeps **resolution** (cache, staleness, fallback) and the CLI. ``_sync_token.py``), while ``_sync.py`` keeps **resolution** (cache, staleness,
fallback) and the CLI.
Both backends hold the same end-to-end encrypted layout Both backends hold the same end-to-end encrypted layout
(``wake-alarm-sync/devices-e2e``), sealed under the shared crdt-sync (``wake-alarm-sync/devices-e2e``), sealed under the shared crdt-sync
@ -21,21 +22,19 @@ real file.
from __future__ import annotations from __future__ import annotations
import json
import logging import logging
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from wake_alarm import _sync_token
from wake_alarm._alarm_payload import newest_alarm from wake_alarm._alarm_payload import newest_alarm
from wake_alarm._constants import ( from wake_alarm._constants import (
SYNC_ALARM_FILENAME, SYNC_ALARM_FILENAME,
SYNC_ALARM_PATH, SYNC_ALARM_PATH,
SYNC_APP_NAME, SYNC_APP_NAME,
SYNC_CONFIG_FILE,
SYNC_HTTP_TIMEOUT_SECONDS, SYNC_HTTP_TIMEOUT_SECONDS,
SYNC_LEGACY_PREFIX, SYNC_LEGACY_PREFIX,
SYNC_REPO_NAME, SYNC_REPO_NAME,
SYNC_REPO_OWNER, SYNC_REPO_OWNER,
SYNC_TOKEN_FALLBACK_FILES,
) )
if TYPE_CHECKING: if TYPE_CHECKING:
@ -123,58 +122,6 @@ def _read_published(client: RemoteStore) -> list[tuple[str, str]]:
return published return published
def _read_token_config() -> str | None:
"""Read the token from this package's own JSON config.
Returns:
The token, or None if the file is missing, unreadable, malformed, or
holds no usable token.
"""
try:
with SYNC_CONFIG_FILE.open() as handle:
config = json.load(handle)
except OSError, json.JSONDecodeError:
return None
if not isinstance(config, dict):
return None
token = config.get("token")
if not isinstance(token, str) or not token:
return None
return token
def _read_token_fallback() -> str | None:
"""Read the token from a sibling app's raw single-line token file.
Returns:
The first usable token found, or None if none of the fallback files
exists or holds one.
"""
for path in SYNC_TOKEN_FALLBACK_FILES:
try:
token = path.read_text().strip()
except OSError:
continue
if token:
_logger.debug("Using sync token from %s", path)
return token
return None
def _read_token() -> str | None:
"""Read the GitHub token, preferring this package's own config.
Falls back to diet_guard's token file so one repo-scoped PAT covers
every app syncing through ``kuhyx/syncs``.
Returns:
The token, or None if no configured source holds one.
"""
# No warning on a miss here: the caller reports "no token" once. Logging
# twice for one unconfigured file makes every tick noisy in the journal.
return _read_token_config() or _read_token_fallback()
def fetch_firebase_logs() -> list[tuple[str, str]] | None: def fetch_firebase_logs() -> list[tuple[str, str]] | None:
"""Fetch every device's decrypted ``alarm.json`` from Firebase. """Fetch every device's decrypted ``alarm.json`` from Firebase.
@ -235,13 +182,13 @@ def _fetch_github_alarm() -> tuple[int, int, float | None] | None:
""" """
if not _FIREBASE_AVAILABLE: if not _FIREBASE_AVAILABLE:
return None return None
token = _read_token() token = _sync_token.read_token()
if token is None: if token is None:
# INFO, not WARNING: get_alarm() runs on every one-minute trigger tick, # INFO, not WARNING: get_alarm() runs on every one-minute trigger tick,
# so a persistent condition logged loudly here is 1440 identical # so a persistent condition logged loudly here is 1440 identical
# journal lines a day. The trigger warns once, at the moment it # journal lines a day. The trigger warns once, at the moment it
# actually fires on a degraded source — that is the actionable event. # actually fires on a degraded source — that is the actionable event.
_logger.info("No sync token configured at %s", SYNC_CONFIG_FILE) _logger.info("No sync token configured at %s", _sync_token.SYNC_CONFIG_FILE)
return None return None
client = GitHubSyncClient( client = GitHubSyncClient(
SYNC_REPO_OWNER, SYNC_REPO_OWNER,

View File

@ -63,9 +63,9 @@ def _patch_paths(
) -> None: ) -> None:
"""Redirect every on-disk path into tmp_path for every test.""" """Redirect every on-disk path into tmp_path for every test."""
with ( with (
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file), patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file), patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files), patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
): ):
yield yield

View File

@ -64,9 +64,9 @@ def _patch_paths(
) -> None: ) -> None:
"""Redirect every on-disk path into tmp_path for every test.""" """Redirect every on-disk path into tmp_path for every test."""
with ( with (
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file), patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file), patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files), patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
): ):
yield yield

View File

@ -61,9 +61,9 @@ def _patch_paths(
) -> None: ) -> None:
"""Redirect every on-disk path into tmp_path for every test.""" """Redirect every on-disk path into tmp_path for every test."""
with ( with (
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file), patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file), patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files), patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
): ):
yield yield

View File

@ -14,7 +14,7 @@ from unittest.mock import patch
from crdt_sync import open_encrypted_client from crdt_sync import open_encrypted_client
import pytest import pytest
from wake_alarm import _sync_transport from wake_alarm import _sync_token, _sync_transport
from wake_alarm._constants import SYNC_DEVICES_PREFIX, SYNC_LEGACY_PREFIX from wake_alarm._constants import SYNC_DEVICES_PREFIX, SYNC_LEGACY_PREFIX
from wake_alarm.tests.conftest import TEST_ARGON2, TEST_PHRASE, DictStore from wake_alarm.tests.conftest import TEST_ARGON2, TEST_PHRASE, DictStore
@ -30,8 +30,8 @@ def config_file(tmp_path: Path) -> Iterator[Path]:
"""This app's GitHub token config, redirected; no sibling fallbacks.""" """This app's GitHub token config, redirected; no sibling fallbacks."""
path = tmp_path / "sync.json" path = tmp_path / "sync.json"
with ( with (
patch.object(_sync_transport, "SYNC_CONFIG_FILE", path), patch.object(_sync_token, "SYNC_CONFIG_FILE", path),
patch.object(_sync_transport, "SYNC_TOKEN_FALLBACK_FILES", ()), patch.object(_sync_token, "SYNC_TOKEN_FALLBACK_FILES", ()),
): ):
yield path yield path

View File

@ -59,9 +59,9 @@ def _patch_paths(
) -> None: ) -> None:
"""Redirect every on-disk path into tmp_path for every test.""" """Redirect every on-disk path into tmp_path for every test."""
with ( with (
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file), patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file), patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files), patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
): ):
yield yield

View File

@ -1,4 +1,4 @@
"""Tests for _sync.py's GitHub token discovery and its sibling fallbacks. """Tests for _sync_token.py's GitHub token discovery and its sibling fallbacks.
Split out of test_sync.py to hold both files under the 250-line gate. Split out of test_sync.py to hold both files under the 250-line gate.
""" """
@ -11,9 +11,9 @@ from unittest.mock import patch
import pytest import pytest
from wake_alarm._sync import ( from wake_alarm._sync_token import (
_read_token,
_read_token_fallback, _read_token_fallback,
read_token,
) )
if TYPE_CHECKING: if TYPE_CHECKING:
@ -58,40 +58,40 @@ def _patch_paths(
) -> None: ) -> None:
"""Redirect every on-disk path into tmp_path for every test.""" """Redirect every on-disk path into tmp_path for every test."""
with ( with (
patch("wake_alarm._sync_transport.SYNC_CONFIG_FILE", config_file), patch("wake_alarm._sync_token.SYNC_CONFIG_FILE", config_file),
patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file), patch("wake_alarm._sync.ALARM_CACHE_FILE", cache_file),
patch("wake_alarm._sync_transport.SYNC_TOKEN_FALLBACK_FILES", fallback_files), patch("wake_alarm._sync_token.SYNC_TOKEN_FALLBACK_FILES", fallback_files),
): ):
yield yield
class TestReadToken: class TestReadToken:
"""Tests for _read_token.""" """Tests for read_token."""
def test_missing_file(self) -> None: def test_missing_file(self) -> None:
"""A missing config file yields no token.""" """A missing config file yields no token."""
assert _read_token() is None assert read_token() is None
def test_malformed_json(self, config_file: Path) -> None: def test_malformed_json(self, config_file: Path) -> None:
"""Unparsable JSON yields no token.""" """Unparsable JSON yields no token."""
config_file.write_text("{not json") config_file.write_text("{not json")
assert _read_token() is None assert read_token() is None
def test_not_a_dict(self, config_file: Path) -> None: def test_not_a_dict(self, config_file: Path) -> None:
"""A JSON array is not a config object.""" """A JSON array is not a config object."""
config_file.write_text("[]") config_file.write_text("[]")
assert _read_token() is None assert read_token() is None
@pytest.mark.parametrize("value", [None, "", 42]) @pytest.mark.parametrize("value", [None, "", 42])
def test_unusable_token_values(self, config_file: Path, value: object) -> None: def test_unusable_token_values(self, config_file: Path, value: object) -> None:
"""Absent, empty and non-string tokens are all rejected.""" """Absent, empty and non-string tokens are all rejected."""
config_file.write_text(json.dumps({"token": value})) config_file.write_text(json.dumps({"token": value}))
assert _read_token() is None assert read_token() is None
def test_valid_token(self, config_file: Path) -> None: def test_valid_token(self, config_file: Path) -> None:
"""A non-empty string token is returned.""" """A non-empty string token is returned."""
config_file.write_text(json.dumps({"token": "ghp_x"})) config_file.write_text(json.dumps({"token": "ghp_x"}))
assert _read_token() == "ghp_x" assert read_token() == "ghp_x"
class TestTokenFallback: class TestTokenFallback:
@ -100,7 +100,7 @@ class TestTokenFallback:
def test_no_fallback_files(self) -> None: def test_no_fallback_files(self) -> None:
"""With nothing on disk anywhere there is no token.""" """With nothing on disk anywhere there is no token."""
assert _read_token_fallback() is None assert _read_token_fallback() is None
assert _read_token() is None assert read_token() is None
def test_reads_raw_single_line_token( def test_reads_raw_single_line_token(
self, fallback_files: tuple[Path, Path] self, fallback_files: tuple[Path, Path]
@ -130,11 +130,11 @@ class TestTokenFallback:
"""wake_alarm's own config takes precedence over a sibling's.""" """wake_alarm's own config takes precedence over a sibling's."""
config_file.write_text(json.dumps({"token": "ghp_own"})) config_file.write_text(json.dumps({"token": "ghp_own"}))
fallback_files[0].write_text("ghp_sibling") fallback_files[0].write_text("ghp_sibling")
assert _read_token() == "ghp_own" assert read_token() == "ghp_own"
def test_falls_back_when_config_absent( def test_falls_back_when_config_absent(
self, fallback_files: tuple[Path, Path] self, fallback_files: tuple[Path, Path]
) -> None: ) -> None:
"""With no own config, the sibling token is used.""" """With no own config, the sibling token is used."""
fallback_files[0].write_text("ghp_sibling") fallback_files[0].write_text("ghp_sibling")
assert _read_token() == "ghp_sibling" assert read_token() == "ghp_sibling"