# Automatic token checks

`/tools/auto-token-check` configures a shared daily schedule for newtopc.com and runwaydo.com. `/home` and the tool show only the current website's active count, latest/previous completed daily results, and ten-day history. Both pages and the status/settings endpoints require HTTPS, authentication, an allowed website host, and a user whose saved domain matches that host. Every result query is scoped on the server using the request host, including history and in-progress status; browser-supplied domain parameters cannot select another website. Administrators on either website can manage the shared hour, but cannot see the other website's results, counts, messages or status.

Choose one whole hour from 00 through 23 and enable the daily schedule. Fresh installations start disabled with the hour unset. The daily migration preserves the previous first hour and enabled state and clears the retired second hour. All scheduling and displayed time labels use the server's Africa/Casablanca timezone rules. Initial activation or changed hours takes effect at the next eligible future slot; saving unchanged settings preserves a due slot. Changing the hour cannot create a second pass on the same local calendar day. Disabling pauses existing work after its current account. Reenabling resumes saved work and schedules the next eligible daily slot.

## Execution

Apply `database/migrations/2026_11_10_000003_create_automatic_token_checks.php` and `database/migrations/2026_11_17_000001_make_auto_token_checks_daily.php`, then install the single worker. Stop the existing worker for the migration and restart it after updating the code:

```bash
cp docs/auto-token-check.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now auto-token-check.service
```

The worker checks for due schedules every 10 seconds. It uses a process-lifetime exclusive file lock at `storage/framework/auto-token-check-worker.lock`; a second worker or manual command on this server cannot process checks concurrently. Run only this single centralized worker if deploying the web application on multiple servers. `php artisan tokens:auto-check --once` is a bounded diagnostic pass and obeys the same lock. Run diagnostics as www-data to preserve lock-file ownership. Systemd gracefully finishes an in-flight account before restarting and releases the OS lock when the process exits.

Once per local calendar day, the worker snapshots only active accounts for the two websites. It processes all newtopc.com accounts, in ascending ID order, before any runwaydo.com account. It uses no thread pool, HTTP pool, or parallel jobs. There is a persisted one-second gap after each account. A later daily pass waits behind the entire earlier pass, including both domains. After server downtime, missed days are coalesced into the latest due slot, avoiding a burst of old checks.

## Credentials and outcomes

Each check always exchanges the stored refresh token for an access token, even when a cached access token is still fresh. Successful token responses are saved, including rotated refresh tokens. Existing Inbox credentials remain encrypted and sync through AccountRegistry. Account/project ownership and the original refresh token are checked under database locks before persisting results; concurrent reauthorization cannot be overwritten by an older check.

Gmail profile identity must match the saved mailbox before the account is counted as confirmed active. Only an OAuth `400 invalid_grant` response marks access revoked. Missing tokens, permission errors, mismatched identities, malformed responses, timeouts and Google service errors do not mark the account revoked or count it as verified active. Moved, deleted, newly revoked or reauthorized accounts are skipped. Previously revoked accounts are excluded from automatic passes; the existing manual validation tool remains separate.

Timeouts, rate limits and transient service failures pause the shared cycle for at least 60 seconds (honoring Retry-After), with increasing waits and at most three attempts per account. After the final failed attempt, the cooldown still applies before the next account or domain. No other domain bypasses this cooldown. Requests have 3-second connect and 8-second overall timeouts. Raw Google errors and credential-bearing exceptions are replaced with fixed messages.

The dashboard distinguishes “Active in project now” from verified active counts in the last two completed checks. Unknown/error outcomes are shown separately and never counted as verified active. Saved per-account progress and domain/cycle counters survive process restarts. Dashboard requests only read the database; they never trigger Google requests.

## Ten-day evolution and archives

The visible window is today plus the preceding nine calendar days in Africa/Casablanca, bounded at local midnight. It uses each cycle's scheduled date, so a slow check finishing after midnight stays on its original day. Both `/home` and the tool show five daily rows per page (`history_page=1` or `2`), including explicit “No check” rows. Old twice-daily records are preserved; only the latest scheduled pass for each day is displayed. Latest/previous cards use completed daily results in the same window. Change compares the previous completed daily result visible in this window; partial results have no change value.

The worker marks completed results with a scheduled date before the window as archived hourly, including when automation is disabled. Archiving preserves domain summaries, per-account results, source accounts and credentials; it does not delete records. Unfinished checks are not archived. Dashboard queries independently enforce the ten-day cutoff and domain scope, so older results remain hidden even if the worker is stopped. There is no cross-domain or public archive endpoint.

## Verification

```bash
php artisan test --compact tests/Feature/Inbox/AutomaticTokenChecksTest.php
node --check public/js/auto-token-check.js
```

Tests use SQLite and fake Google responses. They do not refresh real accounts or enable the production schedule.
