T14.2 (D27): the offline sign-in window follows the server

/api/auth/me returns session_expires_at (the session token exp, UTC). The browser
keeps it and never extends it: the fixed 12 hours and the sliding reset are gone.
Offline before that time the app opens as normal. Offline after it the app opens in
read-and-queue mode: no redirect, one mode line, changes are queued and held until
a page load gets a good answer from the server. wpCacheAuth refreshes the cached
user without moving the end time.

D26 and D27 recorded as Accepted. tests/session_expiry_check.py (22 checks) fails
against the old 12 hour rule.
This commit is contained in:
2026-10-17 14:18:53 -07:00
parent 73f0b5e69d
commit 40827d5371
7 changed files with 314 additions and 29 deletions

View File

@@ -1,8 +1,13 @@
# Decisions: October 17, 2026
Status key: **Proposed** means the text is a recommendation. It needs Matt's OK before any build starts.
**Accepted** means Matt approved it and the work may start.
## D26: a sign-in problem never destroys a queued change (Proposed)
Matt accepted D26 and D27 as written on 2026-10-17 (open questions 1, 2 and 3 in `wave-14.md`: hold the changes of
another person, the offline window ends with the session and then works in read-and-queue mode, and a full device
keeps the change in memory and tells the person). The idle time (question 4) was not decided. It belongs to `T13.1`.
## D26: a sign-in problem never destroys a queued change (Accepted)
**Why:** The outbox (`html/project-data.js`) marks any `4xx` answer except `429` as dead. A `401` means the session ended, and it
gets the same treatment. With a session limit (D25, 8 hours) or an idle timeout (T13.1), a crew that works offline past the limit
@@ -18,7 +23,7 @@ change under whoever is signed in, not under the person who made it.
**Tasks:** `T14.1`, `T14.3`. **Needs Matt:** open questions 1 and 3 in `wave-14.md`.
## D27: the offline sign-in window follows the server (Proposed)
## D27: the offline sign-in window follows the server (Accepted)
**Why:** `auth-guard.js` allows the app to open offline for a fixed 12 hours after the last good check, and every page load resets that
time. The server session lasts 8 hours (D25). The two do not agree.

View File

@@ -2,7 +2,7 @@
**Items:** `D26`, `D27`, `BL-061` (`B5` is context only: its wording rules stay, and this wave does not widen it)
**Depends on:** wave 13 merged (it is, except T13.1). Independent of wave 15.
**Decision record:** `docs/waves/decisions-2026-10-17.md` (D26 and D27 are **proposed**; they need Matt's OK, see "Open questions")
**Decision record:** `docs/waves/decisions-2026-10-17.md` (D26 and D27 are **accepted** as of 2026-10-17, see "Open questions")
**Unblocks:** `T13.1` (idle timeout). T13.1 must not reach `main` before T14.1 and T14.2 are done.
**Branch rule:** one task for each pull request. Cut each branch from `main`.
@@ -63,13 +63,15 @@ badge is a `div` with `pointer-events:none`. A badge that must ask a person to s
**Done when:**
- [ ] a queue of N changes meets a `401`: all N are still in the queue, none is dead, `tries` did not change, and the badge state is "held"
- [ ] after a good sign-in, all N changes reach the server in their original order, and the queue is empty
- [ ] a `403` marks only that change dead, with a reason that names the cause
- [ ] a full device store (a forced `QuotaExceededError`) is reported to the caller and the badge. No change disappears silently
- [ ] a change queued by person A is not sent when person B is signed in; it is sent after A signs in
- [ ] `tests/outbox_check.py` covers each case above and fails when `flush()` is put back to the old rule (a mutation check)
- [ ] the full suite passes, at 390 px and 1440 px
- [x] a queue of N changes meets a `401`: all N are still in the queue, none is dead, `tries` did not change, and the badge state is "held"
- [x] after a good sign-in, all N changes reach the server in their original order, and the queue is empty
- [x] a `403` marks only that change dead, with a reason that names the cause
- [x] a full device store (a forced `QuotaExceededError`) is reported to the caller and the badge. No change disappears silently
- [x] a change queued by person A is not sent when person B is signed in; it is sent after A signs in
- [x] `tests/outbox_check.py` covers each case above and fails when `flush()` is put back to the old rule (a mutation check)
- [x] the full suite passes (2026-10-17: 52 of 54 checks pass; the 2 others are `generalinfo_check` and `token_check`, known and not regressions). `mobile_check` covers 390 px. No before and after screenshots were taken: the badge looks the same until T14.3. The badge words for the new states are plain text. T14.3 gives them their final wording and the Sign in control.
**Built (2026-10-17):** commit `73f0b5e`. Open question 1 as accepted: another person's changes are held and the badge names the owner. A change queued before the sign-in check finished has no owner and can be sent by anyone, as before.
---
@@ -99,12 +101,14 @@ badge is a `div` with `pointer-events:none`. A badge that must ask a person to s
**Done when:**
- [ ] `/api/auth/me` returns `session_expires_at`, and it matches the token (`tests/` check, no database change)
- [ ] the fixed 12 hours is gone from `auth-guard.js`
- [ ] opening the app offline before the time works; opening it offline after the time gives read-and-queue mode and does not redirect
- [ ] online with a dead session: redirect to `login.html?next=...`, queue kept, changes sent after sign-in
- [ ] a page load does not extend the cached window
- [ ] the mode line is announced by a screen reader (`aria-live`) and fits at 390 px
- [x] `/api/auth/me` returns `session_expires_at`, and it matches the token (`tests/session_expiry_check.py`, no database change)
- [x] the fixed 12 hours is gone from `auth-guard.js`
- [x] opening the app offline before the time works; opening it offline after the time gives read-and-queue mode and does not redirect
- [x] online with a dead session: redirect to `login.html?next=...`, queue kept, changes sent after sign-in (the send after sign-in is the T14.1 test, section 3)
- [x] a page load does not extend the cached window
- [ ] the mode line is announced by a screen reader (`aria-live`) and fits at 390 px. The line is in the badge, which has `role="status"` (checked). It is **not** checked at 390 px or with a real screen reader. Do this in T14.3, which rebuilds the badge.
**Built (2026-10-17):** `tests/session_expiry_check.py` (22 checks) fails when the old 12 hour rule is put back (7 failures). The mode line shows only in read-and-queue mode, not when the app opens offline before the session ends, because "sign in again" would be wrong while the session is still good. In read-and-queue mode the outbox does not send at all until a page load gets a good answer from the server. Saving display preferences refreshes the cached user and keeps the end time (`wpCacheAuth`).
---
@@ -160,7 +164,9 @@ T13.1 (`6cde6e3`) onto `main`, run `tests/session_idle_check.py` and the same ha
---
## Open questions (needs Matt before T14.1 and T14.2 start)
## Open questions
**Answered 2026-10-17 (Matt accepted the proposal for questions 1, 2 and 3).** Question 4 is still open and belongs to `T13.1`.
1. **Shared devices.** If person B signs in on a device that holds unsent changes from person A, what must happen?
Proposed: hold A's changes, name A in the badge, send them when A signs in. Do not send them as B and do not discard them.

View File

@@ -163,6 +163,31 @@
}
}
// D27. The offline sign-in window is the SERVER session, not a timer of the
// browser's own. /api/auth/me returns `session_expires_at` (the session token's
// exp), and that is what the cache keeps. Only a good answer from the server
// changes it: loading a page offline, or saving preferences, never extends it.
// (This replaced a fixed 12 hour window that slid forward on every page load and
// disagreed with AUTH_SESSION_HOURS.)
function readAuthCache() {
try { return JSON.parse(localStorage.getItem('wp_auth_cache') || 'null'); } catch (e) { return null; }
}
function writeAuthCache(user, expMs) {
try { if (user) localStorage.setItem('wp_auth_cache', JSON.stringify({ user: user, exp: expMs || 0, at: Date.now() })); } catch (e) {}
}
// For callers that refresh the cached user (the preferences dialog): the user
// changes, the end of the session does not.
window.wpCacheAuth = function (user) {
var c = readAuthCache();
writeAuthCache(user, c && c.exp);
};
// 'online' (a good answer from the server), 'offline' (opened from the cache
// before the session ended) or 'readqueue' (opened from the cache after it ended:
// cached data can be read and changes are queued, but nothing is sent until a
// good sign-in). The sync badge shows the one line for 'readqueue'.
window.WP_SESSION_MODE = 'online';
fetch('/api/auth/me', { headers: { 'Accept': 'application/json' } })
.then(function (r) {
if (r.status === 401 || r.status === 403) { try { localStorage.removeItem('wp_auth_cache'); } catch (e) {} goToLogin(); return; }
@@ -171,17 +196,26 @@
var user = data && data.user;
// Remember the last good auth so the PWA can open offline. The server is
// still the real gate; offline writes queue in the outbox until reconnect.
try { if (user) localStorage.setItem('wp_auth_cache', JSON.stringify({ user: user, at: Date.now() })); } catch (e) {}
var expMs = data && data.session_expires_at ? Date.parse(data.session_expires_at) : 0;
writeAuthCache(user, isNaN(expMs) ? 0 : expMs);
proceed(user);
});
})
.catch(function () {
// Offline / API unreachable: fall back to a recent cached auth if present,
// so the app (and the field view) still open without a network.
try {
var c = JSON.parse(localStorage.getItem('wp_auth_cache') || 'null');
if (c && c.user && (Date.now() - (c.at || 0)) < 12 * 3600 * 1000) { proceed(c.user); return; }
} catch (e) {}
// Offline / API unreachable: open from the cached sign-in so the app (and the
// field view) still work without a network. With no cache this device has
// never signed in, so there is nothing to open: go to the sign-in page.
var c = readAuthCache();
if (c && c.user) {
// Before the session ends: open as normal. After it (or when the cache has
// no end time, an older cache): read and queue. The page does NOT redirect,
// because login.html cannot reach Okta without a network.
var live = !!c.exp && Date.now() < c.exp;
window.WP_SESSION_MODE = live ? 'offline' : 'readqueue';
proceed(c.user);
try { document.dispatchEvent(new CustomEvent('wp-session-mode', { detail: window.WP_SESSION_MODE })); } catch (e) {}
return;
}
goToLogin();
});
})();

View File

@@ -276,6 +276,7 @@
_mem = _mem.filter(function (o) { return o.opId !== opId; });
qWrite(qRead().filter(function (o) { return o.opId !== opId; }));
}
function readQueueMode() { try { return window.WP_SESSION_MODE === 'readqueue'; } catch (e) { return false; } }
function sameUser(a, b) { return String(a || '').toLowerCase() === String(b || '').toLowerCase(); }
// Append an op, coalescing by (kind,key) so only the latest write per entity is
@@ -347,7 +348,9 @@
// (429/5xx/network) stay queued.
function flush() {
if (_flushing) return Promise.resolve();
if (_held) { notifySync(); return Promise.resolve(); }
// D27: opened offline after the session ended (read and queue). Changes are kept
// and wait; nothing is sent until a page load gets a good answer from the server.
if (_held || readQueueMode()) { notifySync(); return Promise.resolve(); }
var q = sendableOps();
if (!q.length) { notifySync(); return Promise.resolve(); }
_flushing = true; notifySync();
@@ -468,6 +471,11 @@
if (c.deviceFull) {
el.textContent = '✕ ' + c.unsaved + ' change' + (c.unsaved === 1 ? ' is' : 's are') + ' not saved on this device. Keep this page open until it is sent to the project.';
el.style.color = 'var(--wp-status-error-text)'; el.style.borderColor = 'var(--wp-status-error-border-a)'; el.style.background = 'var(--wp-status-error-bg)'; el.style.display = 'inline-flex';
} else if (readQueueMode()) {
// D27. The one line for read-and-queue mode. T14.3 owns the final wording
// and the sign-in control.
el.textContent = 'Working offline. Sign in again when you have a signal to send your changes.';
el.style.color = 'var(--wp-status-warning-text)'; el.style.borderColor = 'var(--cds-support-warning)'; el.style.background = 'var(--wp-status-warning-bg)'; el.style.display = 'inline-flex';
} else if (c.held) {
el.textContent = '⚠ Sign in again to send your changes to the project. They are kept on this device.';
el.style.color = 'var(--wp-status-warning-text)'; el.style.borderColor = 'var(--cds-support-warning)'; el.style.background = 'var(--wp-status-warning-bg)'; el.style.display = 'inline-flex';
@@ -501,6 +509,7 @@
// D26: the one thing that releases a held queue. auth-guard fires this after a
// good /api/auth/me (or the offline cache), and the next flush finds out for
// itself whether the session is really good: a 401 holds the queue again.
document.addEventListener('wp-session-mode', function () { notifySync(); });
document.addEventListener('wp-auth-ready', function () { _held = false; _backoff = 0; notifySync(); scheduleFlush(0); });
} catch (e) {}
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { notifySync(); scheduleFlush(0); }); }

View File

@@ -220,7 +220,8 @@
.then(function (res) {
if (!res.ok) { msg((res.j && res.j.detail) || ('Could not save (HTTP ' + res.status + ').'), false); return; }
if (res.j && res.j.user) window.WP_USER = res.j.user;
try { localStorage.setItem('wp_auth_cache', JSON.stringify({ user: window.WP_USER, at: Date.now() })); } catch (e) {}
// D27: refresh the cached user, but not the end of the session.
try { if (window.wpCacheAuth) window.wpCacheAuth(window.WP_USER); } catch (e) {}
msg('Saved. Reloading so every date on the page agrees…', true);
// Dates are formatted at render time all over the app; a reload is the
// honest way to apply the change everywhere at once.

View File

@@ -834,12 +834,22 @@ if okta_fake.is_active():
@app.get("/api/auth/me")
def whoami(user: models.User = Depends(auth.get_current_user)):
def whoami(request: Request, user: models.User = Depends(auth.get_current_user)):
"""Who is logged in. The frontend guard calls this on every page load.
`role` is normalized here so no page has to know that a pre-roles account stores
'user' where it now means 'project_user'."""
return {"user": {**user.to_dict(), "role": auth.normalize_role(user.role)}}
'user' where it now means 'project_user'.
D27: `session_expires_at` is the `exp` claim of the session token, as a UTC time.
The browser keeps it so the offline sign-in window ends when the server session
ends. No column holds it: get_current_user has already validated this token, so
the claim is read back from the same cookie."""
claims = auth.is_request_authenticated(request) or {}
exp = claims.get("exp")
expires_at = (datetime.fromtimestamp(exp, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
if isinstance(exp, (int, float)) else None)
return {"user": {**user.to_dict(), "role": auth.normalize_role(user.role)},
"session_expires_at": expires_at}
# ── Display preferences (self-service) ─────────────────────────────────────────

View File

@@ -0,0 +1,220 @@
#!/usr/bin/env python3
"""Does the offline sign-in window follow the server? - D27 / T14.2.
auth-guard.js used to let the app open offline for a fixed 12 hours after the last
good check, and every page load reset that time. The server session lasts
AUTH_SESSION_HOURS (8). This check proves the browser now uses the server's own end
time.
1. /api/auth/me returns session_expires_at and it matches the token's exp
2. the browser keeps it, and the fixed 12 hours is gone from the code
3. offline before that time: the app opens as normal
4. offline after that time: read and queue. No redirect, the mode line shows,
a new change is queued and held, not sent
5. an older cache with no end time is treated as ended (no hidden 12 hours)
6. a page load offline does not extend the cached window
7. no cache at all, offline: sign-in page
8. online with a dead session: sign-in page with next=, and the outbox is kept
9. refreshing the cached user keeps the end of the session
Exit 0 all passed, 1 a failure, 2 could not run.
"""
import base64
import calendar
import json
import os
import re
import subprocess
import sys
import tempfile
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cdp # noqa: E402
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
HERE = os.path.dirname(os.path.abspath(__file__))
HTML = os.path.join(os.path.dirname(HERE), "html")
KEY = "wp_sync_outbox_v1"
# Makes /api/auth/me fail like a missing network when localStorage.x_me_offline is set.
OFFLINE_SHIM = """(() => {
const real = window.fetch.bind(window);
window.fetch = function (u, o) {
let off = false; try { off = !!localStorage.getItem('x_me_offline'); } catch (e) {}
if (off && String(u).indexOf('/api/auth/me') !== -1) return Promise.reject(new TypeError('Failed to fetch'));
return real(u, o);
};
})();"""
STUB = """(() => {
if (!window.__realFetch) window.__realFetch = window.fetch.bind(window);
window.__calls = [];
window.fetch = function (url, opts) {
const m = ((opts && opts.method) || 'GET').toUpperCase();
if (m === 'POST' && /\\/api\\/(wps|sops)$/.test(String(url))) {
window.__calls.push(String(url));
return Promise.resolve(new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }));
}
return window.__realFetch(url, opts);
};
return true;
})()"""
def token_exp(token):
body = token.split(".")[1]
body += "=" * (-len(body) % 4)
return int(json.loads(base64.urlsafe_b64decode(body))["exp"])
def cache(page):
return json.loads(page.eval("localStorage.getItem('wp_auth_cache') || 'null'") or "null")
def load(page, base, path="/field.html"):
page.goto(base + path)
time.sleep(2.0)
def main():
exe = cdp.find_browser()
if not exe:
print("no headless-capable browser found; set WP_BROWSER.")
return 2
tmpdir = tempfile.mkdtemp(prefix="wpsuite-expiry-")
db_path = os.path.join(tmpdir, "check.db")
server = None
try:
tok = seed(db_path)
port = cdp.free_port()
base = "http://127.0.0.1:%d" % port
server = start_server(port, db_path)
if server is None:
print("the test server would not start.")
return 2
print("\nThe offline window follows the server - D27 / T14.2\nTarget: %s" % base)
browser = cdp.Browser(exe)
page = browser.page()
try:
page.ws.call("Page.addScriptToEvaluateOnNewDocument", {"source": OFFLINE_SHIM})
page.clear_cookies()
page.set_cookie("wp_session", tok["root"])
want = token_exp(tok["root"])
print("\n1-2. the server sends its own end time and the browser keeps it")
load(page, base)
me = page.eval("fetch('/api/auth/me').then(r => r.json())")
got = (me or {}).get("session_expires_at")
chk("/api/auth/me returns session_expires_at", bool(got), json.dumps(me)[:200])
chk("it is a UTC time that matches the token exp",
bool(got) and bool(re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$", got)) and
abs(calendar.timegm(time.strptime(got, "%Y-%m-%dT%H:%M:%SZ")) - want) <= 1,
"%s vs %s" % (got, want))
c = cache(page)
chk("the cache holds the server's end time",
bool(c) and abs((c.get("exp") or 0) / 1000.0 - want) <= 1, json.dumps(c)[:200])
src = open(os.path.join(HTML, "auth-guard.js"), encoding="utf-8").read()
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", src, flags=re.S)
chk("the fixed 12 hours is gone from auth-guard.js", "12 * 3600" not in code and "43200000" not in code)
user = json.dumps(c["user"]) if c else "{}"
now_ms = int(time.time() * 1000)
def set_cache(obj):
page.eval("localStorage.setItem('wp_auth_cache', %s); localStorage.setItem('x_me_offline','1'); true"
% json.dumps(json.dumps(obj)))
print("\n3. offline before the end time: opens as normal")
future = now_ms + 3600 * 1000
set_cache({"user": c["user"], "exp": future, "at": 111})
load(page, base)
chk("no redirect", page.eval("location.pathname") == "/field.html", page.eval("location.href"))
chk("the user is the cached user", page.eval("window.WP_USER && window.WP_USER.username") == "root")
chk("mode is offline, not read-and-queue", page.eval("window.WP_SESSION_MODE") == "offline",
page.eval("window.WP_SESSION_MODE"))
print("\n6. a page load offline does not extend the window")
c2 = cache(page)
chk("the end time did not move", c2 and c2.get("exp") == future, json.dumps(c2))
chk("the cache was not rewritten", c2 and c2.get("at") == 111, json.dumps(c2))
print("\n4. offline after the end time: read and queue")
set_cache({"user": c["user"], "exp": now_ms - 3600 * 1000, "at": now_ms})
load(page, base)
chk("no redirect to the sign-in page", page.eval("location.pathname") == "/field.html",
page.eval("location.href"))
chk("the user is the cached user", page.eval("window.WP_USER && window.WP_USER.username") == "root")
chk("mode is read and queue", page.eval("window.WP_SESSION_MODE") == "readqueue",
page.eval("window.WP_SESSION_MODE"))
badge = page.eval("(document.getElementById('wp-sync-badge')||{}).textContent || ''")
chk("the mode line shows", "Working offline. Sign in again when you have a signal to send your changes." in badge,
badge)
chk("the line sits in the live region",
page.eval("(document.getElementById('wp-sync-badge')||{getAttribute(){}}).getAttribute('role')") == "status")
page.eval(STUB)
page.eval("localStorage.removeItem(%r); ProjectData.pushWP({id:'wp_rq', name:'rq'}, 'projA'); true" % KEY)
page.eval("ProjectData.flushSync()")
time.sleep(0.5)
q = json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
chk("a new change is queued", [o.get("key") for o in q] == ["wp_rq"], json.dumps(q)[:200])
chk("and held: nothing was sent", page.eval("window.__calls") == [], str(page.eval("window.__calls")))
print("\n5. an older cache with no end time counts as ended")
set_cache({"user": c["user"], "at": now_ms})
load(page, base)
chk("read and queue, no redirect, no hidden window",
page.eval("location.pathname") == "/field.html" and page.eval("window.WP_SESSION_MODE") == "readqueue",
page.eval("location.href") + " " + str(page.eval("window.WP_SESSION_MODE")))
print("\n9. refreshing the cached user keeps the end of the session")
set_cache({"user": c["user"], "exp": future, "at": 1})
page.eval("window.wpCacheAuth({username: 'renamed'}); true")
c3 = cache(page)
chk("the user changed", c3 and c3["user"].get("username") == "renamed", json.dumps(c3))
chk("the end time did not", c3 and c3.get("exp") == future, json.dumps(c3))
print("\n7. no cache, offline: the sign-in page")
page.eval("localStorage.removeItem('wp_auth_cache'); localStorage.setItem('x_me_offline','1'); true")
load(page, base)
chk("sent to login.html", page.eval("location.pathname") == "/login.html", page.eval("location.href"))
print("\n8. online with a dead session: sign-in page and the outbox is kept")
page.clear_cookies()
page.set_cookie("wp_session", tok["root"])
page.goto(base + "/field.html")
time.sleep(1.5)
page.eval("localStorage.removeItem('x_me_offline'); localStorage.setItem(%r, %s); true" % (
KEY, json.dumps(json.dumps([{"kind": "wp", "key": "wp_keep", "opId": "wp:wp_keep:1", "tries": 0,
"owner": "root", "body": {"id": "wp_keep"}}]))))
page.clear_cookies()
page.set_cookie("wp_session", "not-a-valid-token")
load(page, base)
loc = page.eval("location.pathname + location.search")
chk("online with a dead session: redirect to login.html?next=",
loc.startswith("/login.html") and "next=" in loc, loc)
q = json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
chk("the queued change is still there", [o.get("key") for o in q] == ["wp_keep"], json.dumps(q)[:200])
finally:
page.close()
browser.close()
finally:
if server is not None:
server.kill()
try:
server.wait(timeout=10)
except subprocess.TimeoutExpired:
pass
try:
from server.db import engine
engine.dispose()
except Exception:
pass
print("\n%d passed, %d failed" % (len(_PASS), len(_FAIL)))
return 1 if _FAIL else 0
if __name__ == "__main__":
sys.exit(main())