Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f09c922c46 | ||
|
|
be9ce8ede6 | ||
|
|
7f2681c1c6 | ||
|
|
91fdd958c2 | ||
|
|
b70a2fb607 | ||
|
|
950d52d147 | ||
|
|
d054cd23ed | ||
|
|
f4d8d64b9d | ||
|
|
9763bb410b | ||
|
|
db3ca83f29 | ||
|
|
c219f130c8 | ||
|
|
dc4f457b21 | ||
|
|
9a471b7903 |
No files matched your search
@@ -267,10 +267,13 @@ export STACKCHAIN_PASSKEY_MAX_CHALLENGES_PER_SOURCE=10
|
||||
export STACKCHAIN_PASSKEY_MAX_CHALLENGES=10000
|
||||
# Optional; defaults to STACKCHAIN_STATE_DIR/login-attempts.sqlite3.
|
||||
export STACKCHAIN_LOGIN_ATTEMPT_DB='/var/lib/stackchain-dashboard/login-attempts.sqlite3'
|
||||
# Required for worker-shared live and Find Work snapshots. Keep this key
|
||||
# independent from the Draft key and inject the base64 encoding of exactly 32
|
||||
# random bytes from a secret manager. Never commit it. Missing, malformed,
|
||||
# wrong-key, or modified snapshot state fails closed without returning content.
|
||||
# Required for worker-shared live/Find Work snapshots, synchronized Today/Later
|
||||
# planning state, and the Security activity journal. Keep this key independent
|
||||
# from the Draft key and inject the
|
||||
# base64 encoding of exactly 32 random bytes from a secret manager. Never commit
|
||||
# it. Missing, malformed, wrong-key, or modified state fails closed without
|
||||
# returning content. Legacy Today/Later and Security activity rows migrate
|
||||
# atomically on first use without changing logical revisions or journal IDs.
|
||||
export STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEY='<base64-encoded-32-byte-key>'
|
||||
# Required for cross-device unfiled Draft sync. The single-key setting remains
|
||||
# supported for the first deployment of keyring-capable code and writes v1 envelopes.
|
||||
@@ -384,8 +387,13 @@ place, their live sessions remain valid, and their idle clock starts at migratio
|
||||
The same sheet includes **Security activity**, a reverse-chronological journal of
|
||||
successful token/passkey sign-ins, passkey enrollments, sign-outs, remote device
|
||||
revocations, issue closures, and pull-request merges. The separate SQLite journal
|
||||
retains at most 10,000 events for 90 days and stores only bounded device labels and
|
||||
action targets. It never stores access tokens, cookies, session/CSRF values,
|
||||
retains at most 10,000 events for 90 days. Its bounded event kind, authentication
|
||||
method, device label, and action target are sealed at rest with the private-state
|
||||
encryption key and authenticated against the immutable event ID. Legacy plaintext
|
||||
journals migrate atomically without changing IDs, timestamps, order, or pending
|
||||
operations. Missing or wrong key material and modified ciphertext fail closed with
|
||||
no partial activity response. The journal never stores access tokens, cookies,
|
||||
session/CSRF values,
|
||||
credential IDs, public keys, challenges, attestation data, raw network addresses,
|
||||
request bodies, or comment content. Keep its database on the same class of persistent,
|
||||
writable storage as the session registry. Before passkey credential creation, session
|
||||
@@ -453,6 +461,11 @@ is assembled in source order into one content-addressed JavaScript response. Das
|
||||
HTML and the offline worker reference that exact fingerprint, while the runtime receives
|
||||
immutable caching and HTML/worker responses remain revalidated. The stylesheet and
|
||||
fingerprinted runtime are same-origin assets included atomically in the offline PWA shell.
|
||||
Device Setup also checks whether the browser has granted persistent storage without prompting.
|
||||
Choose **Protect offline work** to request protection from automatic storage-pressure eviction;
|
||||
Stackchain reports **Protected**, **Best effort**, **Denied**, or an unavailable/retryable state
|
||||
truthfully. Offline work continues when protection is unavailable or denied, but the browser may
|
||||
remove best-effort data, so persistence does not replace backups or device security.
|
||||
Use **Sign out & clear this device** on shared devices; it clears Stackchain's
|
||||
offline snapshots, drafts, outboxes, background IndexedDB, and PWA caches without
|
||||
removing unrelated forge preferences. Rotate either dashboard secret by replacing
|
||||
|
||||
@@ -7976,12 +7976,16 @@
|
||||
isIosSafari:() => isIosDevice && /Safari/.test(navigator.userAgent) && !/CriOS|FxiOS|EdgiOS|OPiOS/.test(navigator.userAgent),
|
||||
});
|
||||
installApp.start();
|
||||
const deviceStorage = createDeviceStorage.mount(document);
|
||||
await deviceStorage.start();
|
||||
deviceSetup = createMobileDeviceSetup.mount({
|
||||
document, installApp, promptStorage:localStorage,
|
||||
timerView,
|
||||
offlineAvailable:() => offlineStorageReady,
|
||||
offlineEnabled:() => offlineWorkStore.enabled(),
|
||||
enableOffline:() => setOfflineWorkEnabled(true),
|
||||
storageProtectionReadiness:() => deviceStorage.persistenceReadiness(),
|
||||
protectStorage:() => deviceStorage.requestPersistence(),
|
||||
enablePush:async () => {
|
||||
const controller = await pushControllerReady;
|
||||
if (!controller) return;
|
||||
@@ -7998,7 +8002,6 @@
|
||||
await controller.enableDeadline();
|
||||
},
|
||||
});
|
||||
await createDeviceStorage.mount(document).start();
|
||||
await deviceSetup.start();
|
||||
return deviceSetup;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
let privateRecordCount = 0;
|
||||
let inventoryUnavailable = false;
|
||||
let fullClearArmed = false;
|
||||
let persistence = { state:'unavailable', detail:'Storage protection is unavailable in this browser.', label:'Unavailable' };
|
||||
const ownedCaches = async () => (await options.caches?.keys?.() || [])
|
||||
.filter(name => name.startsWith('stackchain-dashboard-'));
|
||||
|
||||
@@ -37,10 +38,48 @@
|
||||
return Math.round((Number(value) || 0) / (1024 * 1024));
|
||||
}
|
||||
|
||||
async function inspectPersistence() {
|
||||
if (typeof options.storageManager?.persisted !== 'function' || typeof options.storageManager?.persist !== 'function') {
|
||||
persistence = {state:'unavailable', detail:'Storage protection is unavailable in this browser.', label:'Unavailable'};
|
||||
return persistence;
|
||||
}
|
||||
try {
|
||||
const protectedStorage = await options.storageManager.persisted();
|
||||
persistence = protectedStorage
|
||||
? {state:'complete', detail:'Offline work is protected from automatic browser storage cleanup.', label:'Protected'}
|
||||
: {state:'incomplete', detail:'Offline work uses best-effort browser storage and may be removed under storage pressure.', label:'Best effort'};
|
||||
} catch (_error) {
|
||||
persistence = {state:'incomplete', detail:'Storage protection could not be checked. Retry to protect offline work.', label:'Check failed'};
|
||||
}
|
||||
return persistence;
|
||||
}
|
||||
|
||||
function persistenceReadiness() {
|
||||
return {state:persistence.state, detail:persistence.detail};
|
||||
}
|
||||
|
||||
async function requestPersistence() {
|
||||
if (typeof options.storageManager?.persist !== 'function') return persistenceReadiness();
|
||||
let granted = false;
|
||||
try { granted = await options.storageManager.persist(); }
|
||||
catch (_error) {
|
||||
persistence = {state:'incomplete', detail:'Storage protection request failed. Offline work still uses best-effort storage; retry when ready.', label:'Request failed'};
|
||||
options.detail.textContent = options.detail.textContent.replace(/Storage protection: [^·]+/, 'Storage protection: Request failed ');
|
||||
return persistenceReadiness();
|
||||
}
|
||||
await refresh();
|
||||
if (!granted && persistence.state !== 'complete') {
|
||||
persistence = {state:'incomplete', detail:'The browser did not grant storage protection. Offline work still works but may be removed under storage pressure.', label:'Denied'};
|
||||
options.detail.textContent = options.detail.textContent.replace(/Storage protection: [^·]+/, 'Storage protection: Denied ');
|
||||
}
|
||||
return persistenceReadiness();
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
let estimate = null;
|
||||
try { estimate = await options.storageManager?.estimate?.(); }
|
||||
catch (_error) { /* Storage estimates are optional. */ }
|
||||
await inspectPersistence();
|
||||
options.summary.textContent = estimate?.quota
|
||||
? `${megabytes(estimate.usage)} MB of ${megabytes(estimate.quota)} MB browser storage used.`
|
||||
: 'Browser storage usage is unavailable.';
|
||||
@@ -52,7 +91,7 @@
|
||||
privateRecordCount = inventory.recordCount;
|
||||
inventoryUnavailable = inventory.unavailable;
|
||||
const cacheCount = (await ownedCaches()).length;
|
||||
options.detail.textContent = `${itemCount} private browser item${itemCount === 1 ? '' : 's'} · `
|
||||
options.detail.textContent = `Storage protection: ${persistence.label} · ${itemCount} private browser item${itemCount === 1 ? '' : 's'} · `
|
||||
+ `${inventoryUnavailable ? 'private work status unknown' : `${privateRecordCount} private work record${privateRecordCount === 1 ? '' : 's'}`} · `
|
||||
+ `${cacheCount} cached app cop${cacheCount === 1 ? 'y' : 'ies'}`;
|
||||
return { itemCount, privateRecordCount, inventoryUnavailable, cacheCount };
|
||||
@@ -84,7 +123,7 @@
|
||||
privateItemCount = 0;
|
||||
fullClearArmed = false;
|
||||
options.clearAllButton.textContent = 'Clear all private data';
|
||||
options.detail.textContent = '0 private browser items · 0 private work records · 0 cached app copies';
|
||||
options.detail.textContent = `Storage protection: ${persistence.label} · 0 private browser items · 0 private work records · 0 cached app copies`;
|
||||
options.summary.textContent = 'All Stackchain private data was cleared from this device.';
|
||||
} catch (error) {
|
||||
options.summary.textContent = `Private data was not fully cleared: ${error.message}`;
|
||||
@@ -99,5 +138,5 @@
|
||||
return refresh();
|
||||
}
|
||||
|
||||
return { refresh, start };
|
||||
return { refresh, start, persistenceReadiness, requestPersistence };
|
||||
});
|
||||
@@ -112,6 +112,10 @@
|
||||
<div><strong>Keep work available offline</strong><p class="small" id="device-setup-offline-status" role="status"></p></div>
|
||||
<button class="device-setup-action" id="device-setup-offline" type="button">Enable</button>
|
||||
</li>
|
||||
<li class="device-setup-step">
|
||||
<div><strong>Protect offline work</strong><p class="small" id="device-setup-protection-status" role="status"></p></div>
|
||||
<button class="device-setup-action" id="device-setup-protection" type="button">Protect</button>
|
||||
</li>
|
||||
<li class="device-setup-step">
|
||||
<div><strong>Notify me about new updates</strong><p class="small" id="device-setup-push-status" role="status"></p></div>
|
||||
<button class="device-setup-action" id="device-setup-push" type="button">Enable</button>
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
const steps = [
|
||||
['install', options.installButton, options.installStatus, options.install],
|
||||
['offline', options.offlineButton, options.offlineStatus, options.enableOffline],
|
||||
['protection', options.protectionButton, options.protectionStatus, options.protectStorage],
|
||||
['push', options.pushButton, options.pushStatus, options.enablePush],
|
||||
['deadline', options.deadlineButton, options.deadlineStatus, options.enableDeadline],
|
||||
];
|
||||
@@ -108,8 +109,10 @@ function mountMobileDeviceSetup(options) {
|
||||
launcher:qs('#open-device-setup'), closeButton:qs('#close-device-setup'),
|
||||
sheet:qs('#device-setup-sheet'), installButton:qs('#device-setup-install'),
|
||||
offlineButton:qs('#device-setup-offline'), pushButton:qs('#device-setup-push'),
|
||||
protectionButton:qs('#device-setup-protection'),
|
||||
deadlineButton:qs('#device-setup-deadline'),
|
||||
installStatus:qs('#device-setup-install-status'), offlineStatus:qs('#device-setup-offline-status'),
|
||||
protectionStatus:qs('#device-setup-protection-status'),
|
||||
pushStatus:qs('#device-setup-push-status'), deadlineStatus:qs('#device-setup-deadline-status'),
|
||||
readyStatus:qs('#device-setup-ready-status'),
|
||||
promptCard:qs('#device-readiness-card'), promptSummary:qs('#device-readiness-summary'),
|
||||
@@ -126,6 +129,7 @@ function mountMobileDeviceSetup(options) {
|
||||
: options.offlineEnabled()
|
||||
? {state:'complete', detail:qs('#offline-work-status').textContent || 'Offline work is saved.'}
|
||||
: {state:'incomplete', detail:'Private My Work and Today data are not saved offline.'},
|
||||
protection:options.storageProtectionReadiness(),
|
||||
push:qs('#push-updates').disabled
|
||||
? {state:'unavailable', detail:qs('#push-update-status').textContent || 'Update notifications are unavailable.'}
|
||||
: qs('#push-updates').checked
|
||||
@@ -135,6 +139,7 @@ function mountMobileDeviceSetup(options) {
|
||||
}),
|
||||
install:() => options.installApp.install(),
|
||||
enableOffline:options.enableOffline,
|
||||
protectStorage:options.protectStorage,
|
||||
enablePush:options.enablePush,
|
||||
enableDeadline:options.enableDeadline,
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const BASE = new URL('./', self.location.href).pathname;
|
||||
importScripts(BASE + 'static/private-data-registry.js');
|
||||
importScripts(BASE + 'static/background-issue-sync.js');
|
||||
const CACHE = 'stackchain-dashboard-shell-v121';
|
||||
const CACHE = 'stackchain-dashboard-shell-v122';
|
||||
const OFFLINE_LEASE_URL = new URL(BASE + '__offline-session-lease', self.location.origin).href;
|
||||
const OUTAGE_STATUSES = new Set([500, 502, 503, 504]);
|
||||
const NAVIGATION_TIMEOUT_MS = self.__STACKCHAIN_NAVIGATION_TIMEOUT_MS || 4000;
|
||||
|
||||
@@ -114,7 +114,13 @@ def build_frontend(frontend_dir: Path) -> FrontendBuild:
|
||||
f'<meta name="stackchain-feature-{name}" content="{bundle.runtime_name}">'
|
||||
for name, bundle in feature_bundles.items()
|
||||
)
|
||||
dashboard_html = dashboard_html.replace("</head>", feature_metadata + "\n</head>")
|
||||
workspace_preload = (
|
||||
f'<link rel="preload" as="script" '
|
||||
f'href="{feature_bundles["today-timer"].runtime_name}">'
|
||||
)
|
||||
dashboard_html = dashboard_html.replace(
|
||||
"</head>", feature_metadata + "\n" + workspace_preload + "\n</head>"
|
||||
)
|
||||
dashboard_html = dashboard_html.replace(
|
||||
"</body>",
|
||||
f'<script src="{core.runtime_name}"></script>\n</body>',
|
||||
|
||||
+96
-23
@@ -1,12 +1,12 @@
|
||||
"""Durable, account-scoped Later deferrals."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_key
|
||||
|
||||
|
||||
class LaterStore:
|
||||
@@ -17,6 +17,7 @@ class LaterStore:
|
||||
timeout: float = 1.0,
|
||||
operation_limit: int = 4096,
|
||||
operation_retention_seconds: float = 30 * 24 * 60 * 60,
|
||||
encryption_key: bytes | None = None,
|
||||
clock=time.time,
|
||||
):
|
||||
self.path = Path(path)
|
||||
@@ -24,6 +25,10 @@ class LaterStore:
|
||||
self.operation_limit = operation_limit
|
||||
self.operation_retention_seconds = operation_retention_seconds
|
||||
self.clock = clock
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
store="later",
|
||||
)
|
||||
self._initialize()
|
||||
|
||||
def _initialize(self) -> None:
|
||||
@@ -99,11 +104,55 @@ class LaterStore:
|
||||
raise ValueError("login is required")
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _snapshot(row) -> dict:
|
||||
def _snapshot(self, row, login: str) -> tuple[dict, bool]:
|
||||
if row is None:
|
||||
return {"revision": 0, "records": {}}
|
||||
return {"revision": int(row[0]), "records": json.loads(row[1])}
|
||||
return {"revision": 0, "records": {}}, False
|
||||
records, legacy = self._cipher.open(row[1], binding=f"plan:{login}")
|
||||
if not isinstance(records, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
return {"revision": int(row[0]), "records": records}, legacy
|
||||
|
||||
def _sealed_records(self, login: str, records: dict) -> str:
|
||||
return self._cipher.seal(records, binding=f"plan:{login}")
|
||||
|
||||
def _item_revisions(
|
||||
self, connection: sqlite3.Connection, login: str
|
||||
) -> tuple[dict[str, int], dict[str, str]]:
|
||||
revisions: dict[str, int] = {}
|
||||
stored_ids: dict[str, str] = {}
|
||||
for stored_item_id, revision in connection.execute(
|
||||
"SELECT item_id, revision FROM later_item_revisions WHERE login = ?",
|
||||
(login,),
|
||||
):
|
||||
if stored_item_id.startswith("v1:"):
|
||||
item_id, _legacy = self._cipher.open(
|
||||
stored_item_id, binding=f"item-revision:{login}"
|
||||
)
|
||||
else:
|
||||
item_id = stored_item_id
|
||||
if not isinstance(item_id, str) or not item_id:
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
revisions[item_id] = int(revision)
|
||||
stored_ids[item_id] = stored_item_id
|
||||
return revisions, stored_ids
|
||||
|
||||
def _migrate_item_ids(
|
||||
self, connection: sqlite3.Connection, login: str, stored_ids: dict[str, str]
|
||||
) -> dict[str, str]:
|
||||
migrated = dict(stored_ids)
|
||||
for item_id, stored_item_id in stored_ids.items():
|
||||
if stored_item_id.startswith("v1:"):
|
||||
continue
|
||||
sealed_item_id = self._cipher.seal(
|
||||
item_id, binding=f"item-revision:{login}"
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE later_item_revisions SET item_id = ? "
|
||||
"WHERE login = ? AND item_id = ?",
|
||||
(sealed_item_id, login, stored_item_id),
|
||||
)
|
||||
migrated[item_id] = sealed_item_id
|
||||
return migrated
|
||||
|
||||
@staticmethod
|
||||
def _validate_wake_at(wake_at: str | None) -> str:
|
||||
@@ -116,12 +165,21 @@ class LaterStore:
|
||||
return wake_at
|
||||
|
||||
def get(self, login: str) -> dict:
|
||||
login = self._normalize_login(login)
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT revision, records FROM later_plans WHERE login = ?",
|
||||
(self._normalize_login(login),),
|
||||
(login,),
|
||||
).fetchone()
|
||||
return self._snapshot(row)
|
||||
snapshot, legacy_plan = self._snapshot(row, login)
|
||||
_revisions, stored_item_ids = self._item_revisions(connection, login)
|
||||
if row is not None and legacy_plan:
|
||||
connection.execute(
|
||||
"UPDATE later_plans SET records = ? WHERE login = ? AND records = ?",
|
||||
(self._sealed_records(login, snapshot["records"]), login, row[1]),
|
||||
)
|
||||
self._migrate_item_ids(connection, login, stored_item_ids)
|
||||
return snapshot
|
||||
|
||||
def apply(
|
||||
self,
|
||||
@@ -152,7 +210,7 @@ class LaterStore:
|
||||
row = connection.execute(
|
||||
"SELECT revision, records FROM later_plans WHERE login = ?", (login,)
|
||||
).fetchone()
|
||||
snapshot = self._snapshot(row)
|
||||
snapshot, legacy_plan = self._snapshot(row, login)
|
||||
records = dict(snapshot["records"])
|
||||
revision = snapshot["revision"]
|
||||
accepted: list[str] = []
|
||||
@@ -161,15 +219,19 @@ class LaterStore:
|
||||
|
||||
# Existing databases predate per-item revisions. Conservatively mark
|
||||
# active deferrals as changed at the latest known plan revision.
|
||||
item_revisions, stored_item_ids = self._item_revisions(connection, login)
|
||||
stored_item_ids = self._migrate_item_ids(connection, login, stored_item_ids)
|
||||
for item_id in records:
|
||||
connection.execute(
|
||||
"INSERT OR IGNORE INTO later_item_revisions(login, item_id, revision) VALUES (?, ?, ?)",
|
||||
(login, item_id, revision),
|
||||
)
|
||||
item_revisions = dict(connection.execute(
|
||||
"SELECT item_id, revision FROM later_item_revisions WHERE login = ?",
|
||||
(login,),
|
||||
).fetchall())
|
||||
if item_id not in item_revisions:
|
||||
stored_item_id = self._cipher.seal(
|
||||
item_id, binding=f"item-revision:{login}"
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO later_item_revisions(login, item_id, revision) VALUES (?, ?, ?)",
|
||||
(login, stored_item_id, revision),
|
||||
)
|
||||
item_revisions[item_id] = revision
|
||||
stored_item_ids[item_id] = stored_item_id
|
||||
batch_start_item_revisions = dict(item_revisions)
|
||||
|
||||
for operation in operations:
|
||||
@@ -218,21 +280,32 @@ class LaterStore:
|
||||
revision += 1 if changed else 0
|
||||
if changed:
|
||||
item_revisions[item_id] = revision
|
||||
connection.execute(
|
||||
"INSERT INTO later_item_revisions(login, item_id, revision) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(login, item_id) DO UPDATE SET revision = excluded.revision",
|
||||
(login, item_id, revision),
|
||||
)
|
||||
stored_item_id = stored_item_ids.get(item_id)
|
||||
if stored_item_id is None:
|
||||
stored_item_id = self._cipher.seal(
|
||||
item_id, binding=f"item-revision:{login}"
|
||||
)
|
||||
stored_item_ids[item_id] = stored_item_id
|
||||
connection.execute(
|
||||
"INSERT INTO later_item_revisions(login, item_id, revision) VALUES (?, ?, ?)",
|
||||
(login, stored_item_id, revision),
|
||||
)
|
||||
else:
|
||||
connection.execute(
|
||||
"UPDATE later_item_revisions SET revision = ? "
|
||||
"WHERE login = ? AND item_id = ?",
|
||||
(revision, login, stored_item_id),
|
||||
)
|
||||
self._record_operation(connection, login, operation_id)
|
||||
accepted.append(operation_id)
|
||||
|
||||
serialized = json.dumps(records, separators=(",", ":"), sort_keys=True)
|
||||
serialized = self._sealed_records(login, records)
|
||||
if row is None:
|
||||
connection.execute(
|
||||
"INSERT INTO later_plans(login, revision, records) VALUES (?, ?, ?)",
|
||||
(login, revision, serialized),
|
||||
)
|
||||
elif accepted:
|
||||
elif accepted or legacy_plan:
|
||||
connection.execute(
|
||||
"UPDATE later_plans SET revision = ?, records = ? WHERE login = ?",
|
||||
(revision, serialized, login),
|
||||
|
||||
+17
-16
@@ -71,6 +71,7 @@ from src.security_event_store import SecurityEventStore, SecurityEventStoreError
|
||||
from src.suggestion_engine import compute
|
||||
from src.later_store import LaterStore
|
||||
from src.today_store import TodayPlanFull, TodaySessionConflict, TodayStore
|
||||
from src.state_encryption import PrivateStateEncryptionError
|
||||
from src.views import FRONTEND_BUILD, router as frontend_router
|
||||
|
||||
|
||||
@@ -2367,7 +2368,7 @@ async def get_completed_filed_reviews(response: Response):
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
snapshot = await asyncio.to_thread(_completed_filed_review_store().get, login)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Completed Filed review synchronization is unavailable",
|
||||
@@ -2388,7 +2389,7 @@ async def merge_completed_filed_reviews(payload: CompletedFiledReviewBatch):
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc))
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Completed Filed review synchronization is unavailable",
|
||||
@@ -2401,7 +2402,7 @@ async def get_saved_searches(response: Response):
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
snapshot = await asyncio.to_thread(_saved_search_store().get, login)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Saved Search synchronization is unavailable",
|
||||
@@ -2431,7 +2432,7 @@ async def replace_saved_searches(payload: SavedSearchCollection):
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc))
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Saved Search synchronization is unavailable",
|
||||
@@ -2487,7 +2488,7 @@ async def get_today_plan():
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
return await asyncio.to_thread(_today_store().get, login)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Today synchronization is unavailable",
|
||||
@@ -2521,7 +2522,7 @@ async def update_today_plan(payload: TodayOperation | TodayOperationBatch):
|
||||
)
|
||||
except TodayPlanFull:
|
||||
raise HTTPException(status_code=409, detail="Today is limited to 5 items")
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Today synchronization is unavailable",
|
||||
@@ -2534,7 +2535,7 @@ async def get_today_session():
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
return await asyncio.to_thread(_today_store().get_session, login)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Today session synchronization is unavailable",
|
||||
headers={"Retry-After": "1"},
|
||||
@@ -2553,7 +2554,7 @@ async def update_today_session(payload: TodaySessionUpdate):
|
||||
status_code=409,
|
||||
detail={"code": "session_changed", "session": error.session},
|
||||
)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Today session synchronization is unavailable",
|
||||
headers={"Retry-After": "1"},
|
||||
@@ -2565,7 +2566,7 @@ async def get_today_recaps(response: Response):
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
recaps = await asyncio.to_thread(_today_store().list_recaps, login)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Today recap history is unavailable",
|
||||
@@ -2587,7 +2588,7 @@ async def save_today_recap(payload: TodayRecap, response: Response):
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=422, detail=str(error))
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Today recap could not be saved",
|
||||
@@ -2639,7 +2640,7 @@ async def save_today_recap_and_log_time(
|
||||
raise ValueError("time log target must match the saved recap")
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=422, detail=str(error))
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(status_code=503, detail="Today recap could not be saved", headers={"Retry-After": "1"})
|
||||
|
||||
semaphore = asyncio.Semaphore(3)
|
||||
@@ -2708,7 +2709,7 @@ async def get_later_plan():
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
return await asyncio.to_thread(_later_store().get, login)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Later synchronization is unavailable",
|
||||
@@ -2738,7 +2739,7 @@ async def update_later_plan(payload: LaterOperation | LaterOperationBatch):
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=422, detail=str(error))
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Later synchronization is unavailable",
|
||||
@@ -3886,7 +3887,7 @@ async def _remove_notifications_from_live_snapshot(thread_ids: list[int]) -> Non
|
||||
_live_snapshot_value = updated
|
||||
try:
|
||||
await asyncio.to_thread(_live_snapshot_store.remove_notifications, read_ids)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
# The upstream mutation already succeeded; keep process-local filtering.
|
||||
pass
|
||||
|
||||
@@ -4066,7 +4067,7 @@ async def live_snapshot(
|
||||
events_revision=events_revision,
|
||||
notifications_revision=notifications_revision,
|
||||
)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
return JSONResponse(
|
||||
{"error": "Gitea live snapshot state is temporarily unavailable"},
|
||||
status_code=503,
|
||||
@@ -4361,7 +4362,7 @@ async def defer_notification(
|
||||
status_code=503,
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
except (OSError, sqlite3.Error):
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
return JSONResponse(
|
||||
{"error": "Later synchronization is unavailable. Please retry."},
|
||||
status_code=503,
|
||||
|
||||
+137
-23
@@ -7,6 +7,11 @@ from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import (
|
||||
PrivateStateCipher,
|
||||
PrivateStateEncryptionError,
|
||||
private_state_encryption_key,
|
||||
)
|
||||
|
||||
|
||||
class SecurityEventStoreError(RuntimeError):
|
||||
@@ -39,12 +44,22 @@ class SecurityEventStore:
|
||||
max_events: int = 10_000,
|
||||
retention_seconds: int = 90 * 24 * 60 * 60,
|
||||
lock_timeout_seconds: float = 0.1,
|
||||
encryption_key: bytes | None = None,
|
||||
) -> None:
|
||||
self.path = Path(path)
|
||||
self.clock = clock
|
||||
self.max_events = max(1, max_events)
|
||||
self.retention_seconds = max(1, retention_seconds)
|
||||
self.lock_timeout_seconds = lock_timeout_seconds
|
||||
try:
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
store="security-events",
|
||||
)
|
||||
except PrivateStateEncryptionError as exc:
|
||||
raise SecurityEventStoreError(
|
||||
"Security activity is temporarily unavailable"
|
||||
) from exc
|
||||
|
||||
@staticmethod
|
||||
def _bounded(value: str | None, limit: int) -> str | None:
|
||||
@@ -60,10 +75,7 @@ class SecurityEventStore:
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS security_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
kind TEXT NOT NULL,
|
||||
method TEXT,
|
||||
device_label TEXT,
|
||||
target TEXT,
|
||||
payload TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'completed',
|
||||
operation_id TEXT
|
||||
@@ -81,6 +93,11 @@ class SecurityEventStore:
|
||||
connection.execute(
|
||||
"ALTER TABLE security_events ADD COLUMN operation_id TEXT"
|
||||
)
|
||||
plaintext_columns = {"kind", "method", "device_label", "target"}
|
||||
if "payload" not in columns or plaintext_columns.intersection(columns):
|
||||
self._migrate_plaintext(
|
||||
connection, has_payload="payload" in columns
|
||||
)
|
||||
connection.execute(
|
||||
"CREATE INDEX IF NOT EXISTS security_events_created "
|
||||
"ON security_events(created_at DESC, id DESC)"
|
||||
@@ -95,6 +112,56 @@ class SecurityEventStore:
|
||||
"Security activity is temporarily unavailable"
|
||||
) from exc
|
||||
|
||||
def _migrate_plaintext(
|
||||
self, connection: sqlite3.Connection, *, has_payload: bool
|
||||
) -> None:
|
||||
connection.execute("PRAGMA secure_delete = ON")
|
||||
payload_column = "payload," if has_payload else "NULL AS payload,"
|
||||
rows = connection.execute(
|
||||
f"SELECT id, {payload_column} kind, method, device_label, target, "
|
||||
"created_at, status, operation_id FROM security_events ORDER BY id"
|
||||
).fetchall()
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE TABLE security_events_encrypted (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
payload TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'completed',
|
||||
operation_id TEXT
|
||||
)
|
||||
"""
|
||||
)
|
||||
for (
|
||||
event_id,
|
||||
payload,
|
||||
kind,
|
||||
method,
|
||||
device_label,
|
||||
target,
|
||||
created_at,
|
||||
status,
|
||||
operation_id,
|
||||
) in rows:
|
||||
connection.execute(
|
||||
"INSERT INTO security_events_encrypted "
|
||||
"(id, payload, created_at, status, operation_id) VALUES (?, ?, ?, ?, ?)",
|
||||
(
|
||||
event_id,
|
||||
payload
|
||||
or self._seal_event(
|
||||
event_id, kind, method, device_label, target
|
||||
),
|
||||
created_at,
|
||||
status,
|
||||
operation_id,
|
||||
),
|
||||
)
|
||||
connection.execute("DROP TABLE security_events")
|
||||
connection.execute(
|
||||
"ALTER TABLE security_events_encrypted RENAME TO security_events"
|
||||
)
|
||||
|
||||
def _prune(self, connection: sqlite3.Connection, now: int) -> None:
|
||||
connection.execute(
|
||||
"DELETE FROM security_events WHERE created_at < ?",
|
||||
@@ -106,6 +173,24 @@ class SecurityEventStore:
|
||||
(self.max_events,),
|
||||
)
|
||||
|
||||
def _seal_event(
|
||||
self,
|
||||
event_id: int,
|
||||
kind: str,
|
||||
method: str | None,
|
||||
device_label: str | None,
|
||||
target: str | None,
|
||||
) -> str:
|
||||
return self._cipher.seal(
|
||||
{
|
||||
"kind": self._bounded(kind, 48) or "security_event",
|
||||
"method": self._bounded(method, 32),
|
||||
"device_label": self._bounded(device_label, 64),
|
||||
"target": self._bounded(target, 255),
|
||||
},
|
||||
binding=f"event:{event_id}",
|
||||
)
|
||||
|
||||
def record(
|
||||
self,
|
||||
kind: str,
|
||||
@@ -117,16 +202,17 @@ class SecurityEventStore:
|
||||
now = int(self.clock())
|
||||
try:
|
||||
with self._connect() as connection:
|
||||
cursor = connection.execute(
|
||||
"INSERT INTO security_events(created_at, status) VALUES (?, 'completed')",
|
||||
(now,),
|
||||
)
|
||||
event_id = cursor.lastrowid
|
||||
payload = self._seal_event(
|
||||
event_id, kind, method, device_label, target
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO security_events(kind, method, device_label, target, created_at, status) "
|
||||
"VALUES (?, ?, ?, ?, ?, 'completed')",
|
||||
(
|
||||
self._bounded(kind, 48) or "security_event",
|
||||
self._bounded(method, 32),
|
||||
self._bounded(device_label, 64),
|
||||
self._bounded(target, 255),
|
||||
now,
|
||||
),
|
||||
"UPDATE security_events SET payload = ? WHERE id = ?",
|
||||
(payload, event_id),
|
||||
)
|
||||
self._prune(connection, now)
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
@@ -146,16 +232,19 @@ class SecurityEventStore:
|
||||
operation_id = secrets.token_urlsafe(24)
|
||||
try:
|
||||
with self._connect() as connection:
|
||||
cursor = connection.execute(
|
||||
"INSERT INTO security_events(created_at, status, operation_id) "
|
||||
"VALUES (?, 'pending', ?)",
|
||||
(now, operation_id),
|
||||
)
|
||||
event_id = cursor.lastrowid
|
||||
connection.execute(
|
||||
"INSERT INTO security_events(kind, method, device_label, target, created_at, status, operation_id) "
|
||||
"VALUES (?, ?, ?, ?, ?, 'pending', ?)",
|
||||
"UPDATE security_events SET payload = ? WHERE id = ?",
|
||||
(
|
||||
self._bounded(kind, 48) or "security_event",
|
||||
self._bounded(method, 32),
|
||||
self._bounded(device_label, 64),
|
||||
self._bounded(target, 255),
|
||||
now,
|
||||
operation_id,
|
||||
self._seal_event(
|
||||
event_id, kind, method, device_label, target
|
||||
),
|
||||
event_id,
|
||||
),
|
||||
)
|
||||
self._prune(connection, now)
|
||||
@@ -204,7 +293,7 @@ class SecurityEventStore:
|
||||
try:
|
||||
with self._connect() as connection:
|
||||
rows = connection.execute(
|
||||
"SELECT id, kind, method, device_label, target, created_at, status "
|
||||
"SELECT id, payload, created_at, status "
|
||||
f"FROM security_events {where} ORDER BY id DESC LIMIT ?",
|
||||
parameters,
|
||||
).fetchall()
|
||||
@@ -214,7 +303,32 @@ class SecurityEventStore:
|
||||
) from exc
|
||||
has_more = len(rows) > bounded_limit
|
||||
visible = rows[:bounded_limit]
|
||||
events = []
|
||||
try:
|
||||
for event_id, payload, created_at, status in visible:
|
||||
value, _legacy = self._cipher.open(
|
||||
payload, binding=f"event:{event_id}"
|
||||
)
|
||||
if not isinstance(value, dict) or not isinstance(value.get("kind"), str):
|
||||
raise PrivateStateEncryptionError(
|
||||
"private state could not be decrypted"
|
||||
)
|
||||
events.append(
|
||||
SecurityEvent(
|
||||
event_id,
|
||||
value["kind"],
|
||||
value.get("method"),
|
||||
value.get("device_label"),
|
||||
value.get("target"),
|
||||
created_at,
|
||||
status,
|
||||
)
|
||||
)
|
||||
except PrivateStateEncryptionError as exc:
|
||||
raise SecurityEventStoreError(
|
||||
"Security activity is temporarily unavailable"
|
||||
) from exc
|
||||
return SecurityEventPage(
|
||||
events=[SecurityEvent(*row) for row in visible],
|
||||
events=events,
|
||||
next_cursor=visible[-1][0] if has_more else None,
|
||||
)
|
||||
+257
-75
@@ -7,6 +7,7 @@ from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_key
|
||||
|
||||
|
||||
class TodayPlanFull(ValueError):
|
||||
@@ -31,6 +32,7 @@ class TodayStore:
|
||||
operation_limit: int = 4096,
|
||||
operation_retention_seconds: float = 30 * 24 * 60 * 60,
|
||||
recap_limit: int = 100,
|
||||
encryption_key: bytes | None = None,
|
||||
clock=time.time,
|
||||
):
|
||||
self.path = Path(path)
|
||||
@@ -40,6 +42,10 @@ class TodayStore:
|
||||
self.operation_retention_seconds = operation_retention_seconds
|
||||
self.recap_limit = recap_limit
|
||||
self.clock = clock
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
store="today",
|
||||
)
|
||||
self._initialize()
|
||||
|
||||
def _initialize(self) -> None:
|
||||
@@ -162,31 +168,63 @@ class TodayStore:
|
||||
raise ValueError("login is required")
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _snapshot(row) -> dict:
|
||||
def _snapshot(self, row, login: str) -> tuple[dict, bool]:
|
||||
if row is None:
|
||||
return {"revision": 0, "ids": [], "capacity_minutes": None, "estimates": {}}
|
||||
ids = json.loads(row[1])
|
||||
estimates = json.loads(row[3] or "{}")
|
||||
return {"revision": 0, "ids": [], "capacity_minutes": None, "estimates": {}}, False
|
||||
if row[1].startswith("v1:"):
|
||||
payload, legacy = self._cipher.open(row[1], binding=f"plan:{login}")
|
||||
if not isinstance(payload, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
ids = payload.get("ids")
|
||||
estimates = payload.get("estimates")
|
||||
capacity_minutes = payload.get("capacity_minutes")
|
||||
plan_date = payload.get("plan_date")
|
||||
timezone = payload.get("timezone")
|
||||
else:
|
||||
legacy = True
|
||||
ids = json.loads(row[1])
|
||||
estimates = json.loads(row[3] or "{}")
|
||||
capacity_minutes = row[2]
|
||||
plan_date = row[4] if len(row) > 4 else None
|
||||
timezone = row[5] if len(row) > 5 else None
|
||||
if not isinstance(ids, list) or not isinstance(estimates, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
snapshot = {
|
||||
"revision": int(row[0]),
|
||||
"ids": ids,
|
||||
"capacity_minutes": row[2],
|
||||
"capacity_minutes": capacity_minutes,
|
||||
"estimates": {item_id: minutes for item_id, minutes in estimates.items() if item_id in ids},
|
||||
}
|
||||
if len(row) > 4 and row[4]:
|
||||
snapshot["plan_date"] = row[4]
|
||||
snapshot["timezone"] = row[5]
|
||||
return snapshot
|
||||
if plan_date:
|
||||
snapshot["plan_date"] = plan_date
|
||||
snapshot["timezone"] = timezone
|
||||
return snapshot, legacy
|
||||
|
||||
def _sealed_plan(self, login: str, snapshot: dict) -> str:
|
||||
return self._cipher.seal({
|
||||
"ids": snapshot["ids"],
|
||||
"capacity_minutes": snapshot["capacity_minutes"],
|
||||
"estimates": snapshot["estimates"],
|
||||
"plan_date": snapshot.get("plan_date"),
|
||||
"timezone": snapshot.get("timezone"),
|
||||
}, binding=f"plan:{login}")
|
||||
|
||||
def get(self, login: str) -> dict:
|
||||
login = self._normalize_login(login)
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT revision, ids, capacity_minutes, estimates, plan_date, timezone "
|
||||
"FROM today_plans WHERE login = ?",
|
||||
(self._normalize_login(login),),
|
||||
(login,),
|
||||
).fetchone()
|
||||
return self._snapshot(row)
|
||||
snapshot, legacy = self._snapshot(row, login)
|
||||
if row is not None and legacy:
|
||||
connection.execute(
|
||||
"UPDATE today_plans SET ids = ?, capacity_minutes = NULL, estimates = '{}', "
|
||||
"plan_date = NULL, timezone = NULL WHERE login = ? AND ids = ?",
|
||||
(self._sealed_plan(login, snapshot), login, row[1]),
|
||||
)
|
||||
return snapshot
|
||||
|
||||
@staticmethod
|
||||
def _empty_session() -> dict:
|
||||
@@ -195,20 +233,42 @@ class TodayStore:
|
||||
"elapsed_ms": 0, "running": False, "break_deadline_at": None, "updated_at": None,
|
||||
}
|
||||
|
||||
def get_session(self, login: str) -> dict:
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT revision, device_id, identity, elapsed_ms, running, break_deadline_at, updated_at "
|
||||
"FROM today_sessions WHERE login = ?",
|
||||
(self._normalize_login(login),),
|
||||
).fetchone()
|
||||
def _session_snapshot(self, row, login: str) -> tuple[dict, bool]:
|
||||
if row is None:
|
||||
return self._empty_session()
|
||||
return self._empty_session(), False
|
||||
if row[1].startswith("v1:"):
|
||||
payload, legacy = self._cipher.open(row[1], binding=f"session:{login}")
|
||||
if not isinstance(payload, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
return {"revision": int(row[0]), **payload, "updated_at": row[6]}, legacy
|
||||
return {
|
||||
"revision": int(row[0]), "device_id": row[1], "identity": row[2],
|
||||
"elapsed_ms": int(row[3]), "running": bool(row[4]),
|
||||
"break_deadline_at": row[5], "updated_at": row[6],
|
||||
}
|
||||
}, True
|
||||
|
||||
def _sealed_session(self, login: str, session: dict) -> str:
|
||||
return self._cipher.seal({
|
||||
"device_id": session["device_id"], "identity": session["identity"],
|
||||
"elapsed_ms": session["elapsed_ms"], "running": session["running"],
|
||||
"break_deadline_at": session["break_deadline_at"],
|
||||
}, binding=f"session:{login}")
|
||||
|
||||
def get_session(self, login: str) -> dict:
|
||||
login = self._normalize_login(login)
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT revision, device_id, identity, elapsed_ms, running, break_deadline_at, updated_at "
|
||||
"FROM today_sessions WHERE login = ?", (login,),
|
||||
).fetchone()
|
||||
session, legacy = self._session_snapshot(row, login)
|
||||
if row is not None and legacy:
|
||||
connection.execute(
|
||||
"UPDATE today_sessions SET device_id = ?, identity = '', elapsed_ms = 0, "
|
||||
"running = 0, break_deadline_at = NULL WHERE login = ? AND device_id = ?",
|
||||
(self._sealed_session(login, session), login, row[1]),
|
||||
)
|
||||
return session
|
||||
|
||||
def update_session(
|
||||
self, login: str, *, base_revision: int, device_id: str,
|
||||
@@ -222,24 +282,25 @@ class TodayStore:
|
||||
"SELECT revision, device_id, identity, elapsed_ms, running, break_deadline_at, updated_at "
|
||||
"FROM today_sessions WHERE login = ?", (login,)
|
||||
).fetchone()
|
||||
current_revision = int(current[0]) if current else 0
|
||||
current_session, _legacy = self._session_snapshot(current, login)
|
||||
current_revision = current_session["revision"]
|
||||
if base_revision != current_revision:
|
||||
session = self._empty_session() if current is None else {
|
||||
"revision": current_revision, "device_id": current[1], "identity": current[2],
|
||||
"elapsed_ms": int(current[3]), "running": bool(current[4]),
|
||||
"break_deadline_at": current[5], "updated_at": current[6],
|
||||
}
|
||||
raise TodaySessionConflict(session)
|
||||
raise TodaySessionConflict(current_session)
|
||||
revision = current_revision + 1
|
||||
session = {
|
||||
"revision": revision, "device_id": device_id, "identity": identity,
|
||||
"elapsed_ms": elapsed_ms, "running": bool(running),
|
||||
"break_deadline_at": break_deadline_at, "updated_at": updated_at,
|
||||
}
|
||||
connection.execute(
|
||||
"INSERT INTO today_sessions(login, revision, device_id, identity, elapsed_ms, running, break_deadline_at, updated_at) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
|
||||
"ON CONFLICT(login) DO UPDATE SET revision=excluded.revision, device_id=excluded.device_id, "
|
||||
"identity=excluded.identity, elapsed_ms=excluded.elapsed_ms, running=excluded.running, "
|
||||
"break_deadline_at=excluded.break_deadline_at, updated_at=excluded.updated_at",
|
||||
(login, revision, device_id, identity, elapsed_ms, int(running), break_deadline_at, updated_at),
|
||||
(login, revision, self._sealed_session(login, session), "", 0, 0, None, updated_at),
|
||||
)
|
||||
return self.get_session(login)
|
||||
return session
|
||||
|
||||
@staticmethod
|
||||
def _normalize_recap_items(items: list[dict]) -> list[dict]:
|
||||
@@ -273,9 +334,24 @@ class TodayStore:
|
||||
})
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _recap_snapshot(session_id: str, created_at: float, serialized: str) -> dict:
|
||||
items = json.loads(serialized)
|
||||
def _recap_snapshot(
|
||||
self, login: str, encrypted_session_id: str, created_at: float, serialized: str
|
||||
) -> tuple[dict, bool]:
|
||||
if encrypted_session_id.startswith("v1:"):
|
||||
session_id, legacy_session = self._cipher.open(
|
||||
encrypted_session_id, binding=f"recap-id:{login}"
|
||||
)
|
||||
items, legacy_items = self._cipher.open(
|
||||
serialized, binding=f"recap-items:{login}:{session_id}"
|
||||
)
|
||||
else:
|
||||
session_id, legacy_session = encrypted_session_id, True
|
||||
try:
|
||||
items, legacy_items = json.loads(serialized), True
|
||||
except json.JSONDecodeError as error:
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted") from error
|
||||
if not isinstance(session_id, str) or not isinstance(items, list):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
estimated = sum(item["estimate_minutes"] for item in items if item["estimate_minutes"] is not None)
|
||||
actual = sum(item["actual_minutes"] for item in items)
|
||||
return {
|
||||
@@ -285,7 +361,20 @@ class TodayStore:
|
||||
"estimated_minutes": estimated,
|
||||
"actual_minutes": actual,
|
||||
"variance_minutes": actual - estimated,
|
||||
}
|
||||
}, legacy_session or legacy_items
|
||||
|
||||
def _migrate_recap(self, connection, login: str, stored_session: str, snapshot: dict) -> None:
|
||||
encrypted_session = self._cipher.seal(
|
||||
snapshot["session_id"], binding=f"recap-id:{login}"
|
||||
)
|
||||
encrypted_items = self._cipher.seal(
|
||||
snapshot["items"], binding=f"recap-items:{login}:{snapshot['session_id']}"
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE today_recaps SET session_id = ?, items = ? "
|
||||
"WHERE login = ? AND session_id = ?",
|
||||
(encrypted_session, encrypted_items, login, stored_session),
|
||||
)
|
||||
|
||||
def save_recap(self, login: str, session_id: str, items: list[dict]) -> dict:
|
||||
login = self._normalize_login(login)
|
||||
@@ -293,19 +382,25 @@ class TodayStore:
|
||||
raise ValueError("session_id is required and bounded")
|
||||
session_id = session_id.strip()
|
||||
normalized = self._normalize_recap_items(items)
|
||||
serialized = json.dumps(normalized, separators=(",", ":"))
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
existing = connection.execute(
|
||||
"SELECT created_at, items FROM today_recaps WHERE login = ? AND session_id = ?",
|
||||
(login, session_id),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
return self._recap_snapshot(session_id, existing[0], existing[1])
|
||||
existing_rows = connection.execute(
|
||||
"SELECT session_id, created_at, items FROM today_recaps WHERE login = ?", (login,)
|
||||
).fetchall()
|
||||
for existing in existing_rows:
|
||||
snapshot, legacy = self._recap_snapshot(login, *existing)
|
||||
if snapshot["session_id"] == session_id:
|
||||
if legacy:
|
||||
self._migrate_recap(connection, login, existing[0], snapshot)
|
||||
return snapshot
|
||||
created_at = self.clock()
|
||||
encrypted_session_id = self._cipher.seal(session_id, binding=f"recap-id:{login}")
|
||||
serialized = self._cipher.seal(
|
||||
normalized, binding=f"recap-items:{login}:{session_id}"
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO today_recaps(login, session_id, created_at, items) VALUES (?, ?, ?, ?)",
|
||||
(login, session_id, created_at, serialized),
|
||||
(login, encrypted_session_id, created_at, serialized),
|
||||
)
|
||||
connection.execute(
|
||||
"DELETE FROM today_recaps WHERE login = ? AND rowid NOT IN "
|
||||
@@ -313,53 +408,135 @@ class TodayStore:
|
||||
"ORDER BY created_at DESC, rowid DESC LIMIT ?)",
|
||||
(login, login, self.recap_limit),
|
||||
)
|
||||
return self._recap_snapshot(session_id, created_at, serialized)
|
||||
return self._recap_snapshot(login, encrypted_session_id, created_at, serialized)[0]
|
||||
|
||||
def list_recaps(self, login: str, *, limit: int = 30) -> list[dict]:
|
||||
bounded_limit = max(1, min(int(limit), self.recap_limit, 100))
|
||||
login = self._normalize_login(login)
|
||||
with self._connect() as connection:
|
||||
rows = connection.execute(
|
||||
"SELECT session_id, created_at, items FROM today_recaps WHERE login = ? "
|
||||
"ORDER BY created_at DESC, rowid DESC LIMIT ?",
|
||||
(self._normalize_login(login), bounded_limit),
|
||||
(login, bounded_limit),
|
||||
).fetchall()
|
||||
return [self._recap_snapshot(*row) for row in rows]
|
||||
snapshots = []
|
||||
for row in rows:
|
||||
snapshot, legacy = self._recap_snapshot(login, *row)
|
||||
if legacy:
|
||||
self._migrate_recap(connection, login, row[0], snapshot)
|
||||
snapshots.append(snapshot)
|
||||
return snapshots
|
||||
|
||||
def _time_log_snapshot(self, login: str, row) -> tuple[dict, bool]:
|
||||
encrypted_session, encrypted_identity, payload_value, status_value = row
|
||||
if encrypted_session.startswith("v1:"):
|
||||
session_id = self._cipher.open(
|
||||
encrypted_session, binding=f"time-log-session:{login}"
|
||||
)[0]
|
||||
identity = self._cipher.open(
|
||||
encrypted_identity, binding=f"time-log-identity:{login}:{session_id}"
|
||||
)[0]
|
||||
payload, legacy = self._cipher.open(
|
||||
str(payload_value), binding=f"time-log-payload:{login}:{session_id}:{identity}"
|
||||
)
|
||||
if not isinstance(session_id, str) or not isinstance(identity, str) or not isinstance(payload, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
return {
|
||||
"session_id": session_id, "identity": identity,
|
||||
"actual_minutes": payload.get("actual_minutes"), "status": payload.get("status"),
|
||||
"stored_session": encrypted_session, "stored_identity": encrypted_identity,
|
||||
}, legacy
|
||||
return {
|
||||
"session_id": encrypted_session, "identity": encrypted_identity,
|
||||
"actual_minutes": payload_value, "status": status_value,
|
||||
"stored_session": encrypted_session, "stored_identity": encrypted_identity,
|
||||
}, True
|
||||
|
||||
def _sealed_time_log(self, login: str, session_id: str, identity: str, actual: int, status: str) -> tuple[str, str, str]:
|
||||
return (
|
||||
self._cipher.seal(session_id, binding=f"time-log-session:{login}"),
|
||||
self._cipher.seal(identity, binding=f"time-log-identity:{login}:{session_id}"),
|
||||
self._cipher.seal(
|
||||
{"actual_minutes": actual, "status": status},
|
||||
binding=f"time-log-payload:{login}:{session_id}:{identity}",
|
||||
),
|
||||
)
|
||||
|
||||
def _migrate_time_log(self, connection, login: str, snapshot: dict) -> dict:
|
||||
sealed_session, sealed_identity, sealed_payload = self._sealed_time_log(
|
||||
login, snapshot["session_id"], snapshot["identity"],
|
||||
snapshot["actual_minutes"], snapshot["status"],
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE today_time_logs SET session_id = ?, identity = ?, actual_minutes = ?, status = 'sealed' "
|
||||
"WHERE login = ? AND session_id = ? AND identity = ?",
|
||||
(sealed_session, sealed_identity, sealed_payload, login,
|
||||
snapshot["stored_session"], snapshot["stored_identity"]),
|
||||
)
|
||||
return {**snapshot, "stored_session": sealed_session, "stored_identity": sealed_identity}
|
||||
|
||||
def begin_time_log(self, login: str, session_id: str, identity: str, actual_minutes: int) -> str:
|
||||
"""Claim one recap item for upstream logging, returning its current state."""
|
||||
login = self._normalize_login(login)
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
row = connection.execute(
|
||||
"SELECT actual_minutes, status FROM today_time_logs "
|
||||
"WHERE login = ? AND session_id = ? AND identity = ?",
|
||||
(login, session_id, identity),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
rows = connection.execute(
|
||||
"SELECT session_id, identity, actual_minutes, status FROM today_time_logs WHERE login = ?",
|
||||
(login,),
|
||||
).fetchall()
|
||||
match = None
|
||||
for row in rows:
|
||||
candidate, legacy = self._time_log_snapshot(login, row)
|
||||
if candidate["session_id"] == session_id and candidate["identity"] == identity:
|
||||
match = self._migrate_time_log(connection, login, candidate) if legacy else candidate
|
||||
break
|
||||
if match is None:
|
||||
sealed_session, sealed_identity, sealed_payload = self._sealed_time_log(
|
||||
login, session_id, identity, actual_minutes, "pending"
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO today_time_logs(login, session_id, identity, actual_minutes, status) "
|
||||
"VALUES (?, ?, ?, ?, 'pending')",
|
||||
(login, session_id, identity, actual_minutes),
|
||||
"VALUES (?, ?, ?, ?, 'sealed')",
|
||||
(login, sealed_session, sealed_identity, sealed_payload),
|
||||
)
|
||||
return "claimed"
|
||||
if row[0] != actual_minutes:
|
||||
if match["actual_minutes"] != actual_minutes:
|
||||
raise ValueError("logged recap time cannot be changed")
|
||||
if row[1] == "failed":
|
||||
if match["status"] == "failed":
|
||||
sealed_payload = self._sealed_time_log(
|
||||
login, session_id, identity, actual_minutes, "pending"
|
||||
)[2]
|
||||
connection.execute(
|
||||
"UPDATE today_time_logs SET status = 'pending' "
|
||||
"UPDATE today_time_logs SET actual_minutes = ?, status = 'sealed' "
|
||||
"WHERE login = ? AND session_id = ? AND identity = ?",
|
||||
(login, session_id, identity),
|
||||
(sealed_payload, login, match["stored_session"], match["stored_identity"]),
|
||||
)
|
||||
return "claimed"
|
||||
return row[1]
|
||||
return match["status"]
|
||||
|
||||
def finish_time_log(self, login: str, session_id: str, identity: str, *, succeeded: bool) -> None:
|
||||
login = self._normalize_login(login)
|
||||
with self._connect() as connection:
|
||||
connection.execute(
|
||||
"UPDATE today_time_logs SET status = ? "
|
||||
"WHERE login = ? AND session_id = ? AND identity = ? AND status = 'pending'",
|
||||
("logged" if succeeded else "failed", self._normalize_login(login), session_id, identity),
|
||||
)
|
||||
rows = connection.execute(
|
||||
"SELECT session_id, identity, actual_minutes, status FROM today_time_logs WHERE login = ?",
|
||||
(login,),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
match, legacy = self._time_log_snapshot(login, row)
|
||||
if match["session_id"] != session_id or match["identity"] != identity or match["status"] != "pending":
|
||||
continue
|
||||
if legacy:
|
||||
match = self._migrate_time_log(connection, login, match)
|
||||
sealed_payload = self._sealed_time_log(
|
||||
login, session_id, identity, match["actual_minutes"],
|
||||
"logged" if succeeded else "failed",
|
||||
)[2]
|
||||
connection.execute(
|
||||
"UPDATE today_time_logs SET actual_minutes = ?, status = 'sealed' "
|
||||
"WHERE login = ? AND session_id = ? AND identity = ?",
|
||||
(sealed_payload, login, match["stored_session"], match["stored_identity"]),
|
||||
)
|
||||
return
|
||||
|
||||
def apply(
|
||||
self,
|
||||
@@ -384,7 +561,7 @@ class TodayStore:
|
||||
"SELECT revision, ids, capacity_minutes, estimates, plan_date, timezone "
|
||||
"FROM today_plans WHERE login = ?", (login,)
|
||||
).fetchone()
|
||||
snapshot = self._snapshot(row)
|
||||
snapshot, _legacy = self._snapshot(row, login)
|
||||
duplicate = connection.execute(
|
||||
"SELECT 1 FROM today_operations WHERE login = ? AND operation_id = ?",
|
||||
(login, operation_id),
|
||||
@@ -417,19 +594,22 @@ class TodayStore:
|
||||
changed = True
|
||||
|
||||
revision = snapshot["revision"] + (1 if changed else 0)
|
||||
serialized_ids = json.dumps(ids, separators=(",", ":"))
|
||||
serialized_estimates = json.dumps(estimates, separators=(",", ":"))
|
||||
sealed = self._sealed_plan(login, {
|
||||
"ids": ids, "capacity_minutes": snapshot["capacity_minutes"],
|
||||
"estimates": estimates, "plan_date": snapshot.get("plan_date"),
|
||||
"timezone": snapshot.get("timezone"),
|
||||
})
|
||||
if row is None:
|
||||
connection.execute(
|
||||
"INSERT INTO today_plans(login, revision, ids, capacity_minutes, estimates, plan_date, timezone) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
(login, revision, serialized_ids, snapshot["capacity_minutes"], serialized_estimates,
|
||||
snapshot.get("plan_date"), snapshot.get("timezone")),
|
||||
(login, revision, sealed, None, "{}", None, None),
|
||||
)
|
||||
elif changed:
|
||||
connection.execute(
|
||||
"UPDATE today_plans SET revision = ?, ids = ?, estimates = ? WHERE login = ?",
|
||||
(revision, serialized_ids, serialized_estimates, login),
|
||||
"UPDATE today_plans SET revision = ?, ids = ?, capacity_minutes = NULL, "
|
||||
"estimates = '{}', plan_date = NULL, timezone = NULL WHERE login = ?",
|
||||
(revision, sealed, login),
|
||||
)
|
||||
self._record_operation(connection, login, operation_id)
|
||||
result = {
|
||||
@@ -452,7 +632,7 @@ class TodayStore:
|
||||
"SELECT revision, ids, capacity_minutes, estimates, plan_date, timezone "
|
||||
"FROM today_plans WHERE login = ?", (login,)
|
||||
).fetchone()
|
||||
snapshot = self._snapshot(row)
|
||||
snapshot, _legacy = self._snapshot(row, login)
|
||||
ids = list(snapshot["ids"])
|
||||
capacity_minutes = snapshot["capacity_minutes"]
|
||||
estimates = dict(snapshot["estimates"])
|
||||
@@ -581,19 +761,21 @@ class TodayStore:
|
||||
self._record_operation(connection, login, operation_id)
|
||||
accepted.append(operation_id)
|
||||
|
||||
serialized = json.dumps(ids, separators=(",", ":"))
|
||||
serialized_estimates = json.dumps(estimates, separators=(",", ":"))
|
||||
sealed = self._sealed_plan(login, {
|
||||
"ids": ids, "capacity_minutes": capacity_minutes, "estimates": estimates,
|
||||
"plan_date": plan_date, "timezone": timezone,
|
||||
})
|
||||
if row is None:
|
||||
connection.execute(
|
||||
"INSERT INTO today_plans(login, revision, ids, capacity_minutes, estimates, plan_date, timezone) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
(login, revision, serialized, capacity_minutes, serialized_estimates, plan_date, timezone),
|
||||
(login, revision, sealed, None, "{}", None, None),
|
||||
)
|
||||
elif accepted:
|
||||
connection.execute(
|
||||
"UPDATE today_plans SET revision = ?, ids = ?, capacity_minutes = ?, estimates = ?, "
|
||||
"plan_date = ?, timezone = ? WHERE login = ?",
|
||||
(revision, serialized, capacity_minutes, serialized_estimates, plan_date, timezone, login),
|
||||
(revision, sealed, None, "{}", None, None, login),
|
||||
)
|
||||
result = {
|
||||
"revision": revision,
|
||||
|
||||
@@ -29,6 +29,7 @@ def test_release_artifact_bootstraps_mobile_home_and_returns_from_insights(
|
||||
browser_errors: list[str] = []
|
||||
failed_responses: list[str] = []
|
||||
workspace_requests: list[str] = []
|
||||
launch_transfer_events: list[str] = []
|
||||
live_requests: list[str] = []
|
||||
|
||||
try:
|
||||
@@ -38,6 +39,18 @@ def test_release_artifact_bootstraps_mobile_home_and_returns_from_insights(
|
||||
viewport={"width": width, "height": height}, ignore_https_errors=True
|
||||
)
|
||||
page = context.new_page()
|
||||
cdp = context.new_cdp_session(page)
|
||||
cdp.send("Network.enable")
|
||||
cdp.send(
|
||||
"Network.emulateNetworkConditions",
|
||||
{
|
||||
"offline": False,
|
||||
"latency": 100,
|
||||
"downloadThroughput": 48 * 1024,
|
||||
"uploadThroughput": 48 * 1024,
|
||||
"connectionType": "cellular3g",
|
||||
},
|
||||
)
|
||||
page.on("pageerror", lambda error: browser_errors.append(error.stack or str(error)))
|
||||
page.on(
|
||||
"console",
|
||||
@@ -53,9 +66,16 @@ def test_release_artifact_bootstraps_mobile_home_and_returns_from_insights(
|
||||
)
|
||||
page.on(
|
||||
"request",
|
||||
lambda request: workspace_requests.append(request.url)
|
||||
if "feature-today-timer-" in request.url
|
||||
else None,
|
||||
lambda request: (
|
||||
workspace_requests.append(request.url),
|
||||
launch_transfer_events.append("workspace-requested"),
|
||||
)
|
||||
if "feature-today-timer-" in request.url else None,
|
||||
)
|
||||
page.on(
|
||||
"requestfinished",
|
||||
lambda request: launch_transfer_events.append("core-finished")
|
||||
if "/runtime-" in request.url else None,
|
||||
)
|
||||
page.on(
|
||||
"request",
|
||||
@@ -69,6 +89,9 @@ def test_release_artifact_bootstraps_mobile_home_and_returns_from_insights(
|
||||
page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
|
||||
page.locator("#submit-sign-in").click()
|
||||
page.wait_for_url(origin + "/", wait_until="networkidle")
|
||||
assert launch_transfer_events.index("workspace-requested") < (
|
||||
launch_transfer_events.index("core-finished")
|
||||
), launch_transfer_events
|
||||
|
||||
expect(page.locator("#my-work-status")).to_contain_text("2")
|
||||
initial_live_requests = len(live_requests)
|
||||
|
||||
@@ -530,11 +530,20 @@ def test_release_artifact_recovers_admitted_blocker_after_reload_and_opens_next_
|
||||
expect(page.locator("#resume-today-break")).to_be_visible()
|
||||
|
||||
page.evaluate("""() => {
|
||||
const outbox = JSON.parse(localStorage.getItem('stackchain.authored-outbox.v1') ||
|
||||
'{"version":2,"items":[]}');
|
||||
outbox.items.push({
|
||||
id: 'already-admitted-blocker', operationId: 'already-admitted-blocker',
|
||||
kind: 'issue-comment', repository: 'acme/mobile', number: 41,
|
||||
body: 'Blocked after reload waiting for the design owner', ownerLogin: 'timmy',
|
||||
status: 'queued', queuedAt: Date.now()
|
||||
});
|
||||
localStorage.setItem('stackchain.authored-outbox.v1', JSON.stringify(outbox));
|
||||
localStorage.setItem('stackchain.today-progress.v1.timmy', JSON.stringify({
|
||||
version: 1,
|
||||
drafts: {
|
||||
'issue:acme/mobile:41:': {
|
||||
body: 'Blocked waiting for the design owner',
|
||||
body: 'Blocked after reload waiting for the design owner',
|
||||
operation_id: 'already-admitted-blocker',
|
||||
blocker_pending: true,
|
||||
blocker_until: '2000-01-02T03:04:00.000Z'
|
||||
@@ -574,10 +583,23 @@ def test_release_artifact_recovers_admitted_blocker_after_reload_and_opens_next_
|
||||
})""")
|
||||
assert state["today"] == ["issue:acme/mobile:42:"]
|
||||
assert state["later"]["issue:acme/mobile:41:"].startswith("2099-08-19T09:00")
|
||||
comments = [item for item in state["outbox"]["items"] if item["kind"] == "issue-comment"]
|
||||
assert len(comments) == 1
|
||||
assert comments[0]["number"] == 41
|
||||
assert comments[0]["body"] == "Blocked waiting for the design owner"
|
||||
queued_comments = [
|
||||
item for item in state["outbox"]["items"]
|
||||
if item["kind"] == "issue-comment"
|
||||
and item["number"] == 41
|
||||
and item["body"] == "Blocked after reload waiting for the design owner"
|
||||
]
|
||||
delivered_comments = [
|
||||
{"number": number, "body": body}
|
||||
for number, body in fake.comments
|
||||
if number == 41 and body == "Blocked after reload waiting for the design owner"
|
||||
]
|
||||
assert len(queued_comments) <= 1
|
||||
assert len(delivered_comments) <= 1
|
||||
assert queued_comments or delivered_comments
|
||||
receipt = (delivered_comments or queued_comments)[0]
|
||||
assert receipt["number"] == 41
|
||||
assert receipt["body"] == "Blocked after reload waiting for the design owner"
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
assert browser_errors == []
|
||||
browser.close()
|
||||
|
||||
@@ -303,4 +303,4 @@ async def test_unread_update_offers_reply_mark_read_and_next_independent_of_toda
|
||||
assert '.update-reply-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr));' in html
|
||||
assert '.update-reply-actions button { min-height:44px;' in html
|
||||
worker = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
assert "stackchain-dashboard-shell-v121" in worker
|
||||
assert "stackchain-dashboard-shell-v122" in worker
|
||||
@@ -17,6 +17,7 @@ class Target {
|
||||
const summary=new Target(), detail=new Target(), clearCachesButton=new Target(), clearAllButton=new Target();
|
||||
let purgeCalls=0, purgeError='';
|
||||
let inventory={recordCount:0, unavailable:false};
|
||||
let persistence={persisted:false, persistResult:false, persistedCalls:0, persistCalls:0, error:''};
|
||||
const localStorage={
|
||||
values:new Map([['stackchain.draft.1','private'],['other.preference','keep']]),
|
||||
get length(){return this.values.size;},
|
||||
@@ -27,11 +28,16 @@ const caches={
|
||||
async keys(){return Array.from(this.values);},
|
||||
async delete(key){return this.values.delete(key);},
|
||||
};
|
||||
const storageManager={
|
||||
estimate:async()=>({usage:2 * 1024 * 1024, quota:10 * 1024 * 1024}),
|
||||
persisted:async()=>{persistence.persistedCalls++;if(persistence.error)throw new Error(persistence.error);return persistence.persisted;},
|
||||
persist:async()=>{persistence.persistCalls++;persistence.persisted=persistence.persistResult;return persistence.persistResult;},
|
||||
};
|
||||
const controller=createDeviceStorage({
|
||||
summary, detail, clearCachesButton, clearAllButton, localStorage, caches,
|
||||
privateDatabases:['stackchain-background-outbox-v1','stackchain-offline-work-v2'],
|
||||
inspectPrivateDatabases:async()=>inventory,
|
||||
storageManager:{estimate:async()=>({usage:2 * 1024 * 1024, quota:10 * 1024 * 1024})},
|
||||
storageManager,
|
||||
clearPrivateDeviceData:async()=>{purgeCalls++;if(purgeError)throw new Error(purgeError);},
|
||||
});
|
||||
(async()=>{ __SCENARIO__ })().catch(error=>{console.error(error);process.exit(1);});
|
||||
@@ -49,7 +55,104 @@ process.stdout.write(JSON.stringify({summary:summary.textContent,detail:detail.t
|
||||
|
||||
assert result == {
|
||||
"summary": "2 MB of 10 MB browser storage used.",
|
||||
"detail": "1 private browser item · 0 private work records · 1 cached app copy",
|
||||
"detail": "Storage protection: Best effort · 1 private browser item · 0 private work records · 1 cached app copy",
|
||||
}
|
||||
|
||||
|
||||
def test_refresh_checks_storage_protection_without_requesting_permission():
|
||||
result = run_scenario("""
|
||||
await controller.refresh();
|
||||
process.stdout.write(JSON.stringify({
|
||||
readiness:await controller.persistenceReadiness(),
|
||||
persistedCalls:persistence.persistedCalls,
|
||||
persistCalls:persistence.persistCalls,
|
||||
detail:detail.textContent,
|
||||
}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"readiness": {
|
||||
"state": "incomplete",
|
||||
"detail": "Offline work uses best-effort browser storage and may be removed under storage pressure.",
|
||||
},
|
||||
"persistedCalls": 1,
|
||||
"persistCalls": 0,
|
||||
"detail": "Storage protection: Best effort · 1 private browser item · 0 private work records · 1 cached app copy",
|
||||
}
|
||||
|
||||
|
||||
def test_explicit_request_confirms_storage_is_protected_before_claiming_success():
|
||||
result = run_scenario("""
|
||||
await controller.refresh();
|
||||
persistence.persistResult=true;
|
||||
const readiness=await controller.requestPersistence();
|
||||
process.stdout.write(JSON.stringify({
|
||||
readiness,
|
||||
persistedCalls:persistence.persistedCalls,
|
||||
persistCalls:persistence.persistCalls,
|
||||
detail:detail.textContent,
|
||||
}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"readiness": {
|
||||
"state": "complete",
|
||||
"detail": "Offline work is protected from automatic browser storage cleanup.",
|
||||
},
|
||||
"persistedCalls": 2,
|
||||
"persistCalls": 1,
|
||||
"detail": "Storage protection: Protected · 1 private browser item · 0 private work records · 1 cached app copy",
|
||||
}
|
||||
|
||||
|
||||
def test_denied_request_remains_retryable_and_does_not_claim_protection():
|
||||
result = run_scenario("""
|
||||
await controller.refresh();
|
||||
const readiness=await controller.requestPersistence();
|
||||
process.stdout.write(JSON.stringify({readiness,persistCalls:persistence.persistCalls}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"readiness": {
|
||||
"state": "incomplete",
|
||||
"detail": "The browser did not grant storage protection. Offline work still works but may be removed under storage pressure.",
|
||||
},
|
||||
"persistCalls": 1,
|
||||
}
|
||||
|
||||
|
||||
def test_denied_request_keeps_setup_and_storage_panel_in_the_same_state_when_recheck_fails():
|
||||
result = run_scenario("""
|
||||
await controller.refresh();
|
||||
storageManager.persist=async()=>{persistence.persistCalls++;persistence.error='check blocked';return false;};
|
||||
const readiness=await controller.requestPersistence();
|
||||
process.stdout.write(JSON.stringify({readiness,detail:detail.textContent}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"readiness": {
|
||||
"state": "incomplete",
|
||||
"detail": "The browser did not grant storage protection. Offline work still works but may be removed under storage pressure.",
|
||||
},
|
||||
"detail": "Storage protection: Denied · 1 private browser item · 0 private work records · 1 cached app copy",
|
||||
}
|
||||
|
||||
|
||||
def test_failed_request_is_retryable_and_updates_storage_status_without_data_loss():
|
||||
result = run_scenario("""
|
||||
await controller.refresh();
|
||||
storageManager.persist=async()=>{persistence.persistCalls++;throw new Error('blocked');};
|
||||
const readiness=await controller.requestPersistence();
|
||||
process.stdout.write(JSON.stringify({readiness,detail:detail.textContent,persistCalls:persistence.persistCalls}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"readiness": {
|
||||
"state": "incomplete",
|
||||
"detail": "Storage protection request failed. Offline work still uses best-effort storage; retry when ready.",
|
||||
},
|
||||
"detail": "Storage protection: Request failed · 1 private browser item · 0 private work records · 1 cached app copy",
|
||||
"persistCalls": 1,
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +172,7 @@ process.stdout.write(JSON.stringify({
|
||||
"caches": ["other-app"],
|
||||
"storage": ["stackchain.draft.1", "other.preference"],
|
||||
"status": "Cached app copies cleared. Private work was kept.",
|
||||
"detail": "1 private browser item · 0 private work records · 0 cached app copies",
|
||||
"detail": "Storage protection: Best effort · 1 private browser item · 0 private work records · 0 cached app copies",
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +193,7 @@ process.stdout.write(JSON.stringify({warning,calls:purgeCalls,status:summary.tex
|
||||
},
|
||||
"calls": 1,
|
||||
"status": "All Stackchain private data was cleared from this device.",
|
||||
"detail": "0 private browser items · 0 private work records · 0 cached app copies",
|
||||
"detail": "Storage protection: Best effort · 0 private browser items · 0 private work records · 0 cached app copies",
|
||||
}
|
||||
|
||||
|
||||
@@ -112,7 +215,7 @@ process.stdout.write(JSON.stringify({
|
||||
"calls": 0,
|
||||
"label": "Confirm: clear private work",
|
||||
"status": "Private drafts or queued work may not be synced. Press confirm to clear them from this device.",
|
||||
"detail": "0 private browser items · 3 private work records · 1 cached app copy",
|
||||
"detail": "Storage protection: Best effort · 0 private browser items · 3 private work records · 1 cached app copy",
|
||||
}
|
||||
|
||||
|
||||
@@ -132,7 +235,7 @@ process.stdout.write(JSON.stringify({
|
||||
assert result == {
|
||||
"calls": 0,
|
||||
"label": "Confirm: clear private work",
|
||||
"detail": "0 private browser items · private work status unknown · 1 cached app copy",
|
||||
"detail": "Storage protection: Best effort · 0 private browser items · private work status unknown · 1 cached app copy",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ from src.views import dashboard, feature_bundle, runtime_bundle, service_worker
|
||||
|
||||
FRONTEND = Path(__file__).resolve().parents[1] / "frontend"
|
||||
PAGE_SCRIPT = re.compile(r'<script src="(static/[^"]+\.js)"></script>')
|
||||
SCRIPT_PRELOAD = re.compile(r'<link rel="preload" as="script" href="([^"]+)">')
|
||||
|
||||
|
||||
def test_page_runtime_is_one_deterministic_content_addressed_bundle(tmp_path):
|
||||
@@ -119,6 +120,19 @@ def test_product_workflows_are_stable_lazy_feature_chunks(tmp_path):
|
||||
assert security_changed.feature_bundles["security-center"].runtime_name != security_center.runtime_name
|
||||
|
||||
|
||||
def test_mandatory_workspace_fetch_is_preloaded_without_blocking_launch():
|
||||
build = build_frontend(FRONTEND)
|
||||
workspace = build.feature_bundles["today-timer"]
|
||||
|
||||
assert SCRIPT_PRELOAD.findall(build.dashboard_html) == [workspace.runtime_name]
|
||||
assert build.dashboard_html.count(f'<script src="{workspace.runtime_name}"></script>') == 0
|
||||
assert len(build.runtime_gzip_bytes) <= 100 * 1024
|
||||
assert len(workspace.runtime_gzip_bytes) <= 110 * 1024
|
||||
|
||||
shell_block = build.service_worker_source.split("const OPTIONAL_FEATURES = [", 1)[0]
|
||||
assert f"BASE + '{workspace.runtime_name}'" not in shell_block
|
||||
|
||||
|
||||
def test_shipped_browser_bundles_are_valid_javascript(tmp_path):
|
||||
build = build_frontend(FRONTEND)
|
||||
bundles = {"core.js": build.runtime_bytes}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
import httpx
|
||||
@@ -5,6 +6,10 @@ import pytest
|
||||
|
||||
from src import main
|
||||
from src.later_store import LaterStore
|
||||
from src.state_encryption import PrivateStateEncryptionError
|
||||
|
||||
|
||||
PRIVATE_KEY = b"l" * 32
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -65,6 +70,105 @@ def test_deferrals_are_durable_revisioned_idempotent_and_account_scoped(tmp_path
|
||||
) == {"revision": 2, "records": {}}
|
||||
|
||||
|
||||
def test_later_plans_encrypt_private_content_and_authenticate_the_account(tmp_path):
|
||||
path = tmp_path / "later.sqlite3"
|
||||
item_id = "issue:private/repository:363:"
|
||||
wake_at = "2026-08-10T09:17:00.000Z"
|
||||
store = LaterStore(path, encryption_key=PRIVATE_KEY)
|
||||
|
||||
expected = store.apply(
|
||||
"timmy", "op-private", "defer", item_id,
|
||||
wake_at=wake_at, handoff="today",
|
||||
)
|
||||
|
||||
with sqlite3.connect(path) as connection:
|
||||
records = connection.execute(
|
||||
"SELECT records FROM later_plans WHERE login = 'timmy'"
|
||||
).fetchone()[0]
|
||||
stored_item_id = connection.execute(
|
||||
"SELECT item_id FROM later_item_revisions WHERE login = 'timmy'"
|
||||
).fetchone()[0]
|
||||
assert records.startswith("v1:")
|
||||
assert stored_item_id.startswith("v1:")
|
||||
assert item_id not in records + stored_item_id
|
||||
assert wake_at not in records
|
||||
assert "today" not in records
|
||||
assert LaterStore(path, encryption_key=PRIVATE_KEY).get("timmy") == expected
|
||||
with sqlite3.connect(path) as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO later_plans(login, revision, records) VALUES (?, ?, ?)",
|
||||
("alexander", 1, records),
|
||||
)
|
||||
with pytest.raises(PrivateStateEncryptionError, match="private state could not be decrypted"):
|
||||
store.get("alexander")
|
||||
with pytest.raises(PrivateStateEncryptionError, match="private state could not be decrypted"):
|
||||
LaterStore(path, encryption_key=b"x" * 32).get("timmy")
|
||||
|
||||
|
||||
def test_later_read_atomically_migrates_legacy_private_content_without_new_revision(tmp_path):
|
||||
path = tmp_path / "later.sqlite3"
|
||||
item_id = "issue:legacy/private:17:"
|
||||
records = {item_id: {"wake_at": "2026-08-20T08:00:00.000Z", "handoff": "today"}}
|
||||
store = LaterStore(path, encryption_key=PRIVATE_KEY)
|
||||
with sqlite3.connect(path) as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO later_plans(login, revision, records) VALUES (?, ?, ?)",
|
||||
("timmy", 7, json.dumps(records)),
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO later_item_revisions(login, item_id, revision) VALUES (?, ?, ?)",
|
||||
("timmy", item_id, 7),
|
||||
)
|
||||
|
||||
assert store.get("timmy") == {"revision": 7, "records": records}
|
||||
with sqlite3.connect(path) as connection:
|
||||
migrated_plan = connection.execute(
|
||||
"SELECT revision, records FROM later_plans WHERE login = 'timmy'"
|
||||
).fetchone()
|
||||
migrated_revision = connection.execute(
|
||||
"SELECT revision, item_id FROM later_item_revisions WHERE login = 'timmy'"
|
||||
).fetchone()
|
||||
assert migrated_plan[0] == migrated_revision[0] == 7
|
||||
assert migrated_plan[1].startswith("v1:")
|
||||
assert migrated_revision[1].startswith("v1:")
|
||||
assert item_id not in migrated_plan[1] + migrated_revision[1]
|
||||
|
||||
|
||||
def test_duplicate_write_migrates_legacy_later_content_without_advancing_revision(tmp_path):
|
||||
path = tmp_path / "later.sqlite3"
|
||||
item_id = "issue:legacy/private:18:"
|
||||
records = {item_id: "2026-08-21T08:00:00.000Z"}
|
||||
store = LaterStore(path, encryption_key=PRIVATE_KEY)
|
||||
with sqlite3.connect(path) as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO later_plans(login, revision, records) VALUES (?, ?, ?)",
|
||||
("timmy", 4, json.dumps(records)),
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO later_item_revisions(login, item_id, revision) VALUES (?, ?, ?)",
|
||||
("timmy", item_id, 4),
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO later_operations(login, operation_id, created_at) VALUES (?, ?, ?)",
|
||||
("timmy", "already-confirmed", 1.0),
|
||||
)
|
||||
|
||||
result = store.apply(
|
||||
"timmy", "already-confirmed", "restore", item_id, base_revision=4,
|
||||
)
|
||||
|
||||
assert result == {"revision": 4, "records": records}
|
||||
with sqlite3.connect(path) as connection:
|
||||
stored = connection.execute(
|
||||
"SELECT records FROM later_plans WHERE login = 'timmy'"
|
||||
).fetchone()[0]
|
||||
stored_item_id = connection.execute(
|
||||
"SELECT item_id FROM later_item_revisions WHERE login = 'timmy'"
|
||||
).fetchone()[0]
|
||||
assert stored.startswith("v1:")
|
||||
assert stored_item_id.startswith("v1:")
|
||||
|
||||
|
||||
def test_next_day_today_handoff_is_preserved_without_changing_legacy_deferrals(tmp_path):
|
||||
store = LaterStore(tmp_path / "later.sqlite3")
|
||||
|
||||
|
||||
@@ -435,5 +435,5 @@ async def test_dashboard_syncs_every_later_change_and_exposes_account_status():
|
||||
def test_later_sync_ships_atomically_in_the_offline_shell():
|
||||
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/later-sync.js'" in source
|
||||
@@ -256,4 +256,4 @@ def test_markdown_work_bodies_are_mobile_safe_block_containers():
|
||||
assert ".markdown-content { min-width:0; max-width:100%; overflow-wrap:anywhere;" in css
|
||||
assert ".markdown-content pre { max-width:100%; overflow-x:auto;" in css
|
||||
assert ".markdown-content a { min-height:44px;" in css
|
||||
assert "stackchain-dashboard-shell-v121" in worker
|
||||
assert "stackchain-dashboard-shell-v122" in worker
|
||||
@@ -45,7 +45,7 @@ def test_offline_shell_contains_every_local_dashboard_runtime_asset():
|
||||
shell_assets = set(re.findall(r"BASE \+ '([^']+)'", worker.split("async function sessionCsrf", 1)[0]))
|
||||
|
||||
assert local_assets <= shell_assets, f"Offline shell is missing: {sorted(local_assets - shell_assets)}"
|
||||
assert "stackchain-dashboard-shell-v121" in worker
|
||||
assert "stackchain-dashboard-shell-v122" in worker
|
||||
|
||||
|
||||
def test_all_conversation_composers_offer_accessible_mobile_mentions():
|
||||
|
||||
@@ -24,10 +24,12 @@ const closeButton = new FakeTarget();
|
||||
const sheet = new FakeTarget(); sheet.hidden = true;
|
||||
const installButton = new FakeTarget();
|
||||
const offlineButton = new FakeTarget();
|
||||
const protectionButton = new FakeTarget();
|
||||
const pushButton = new FakeTarget();
|
||||
const deadlineButton = new FakeTarget();
|
||||
const installStatus = new FakeTarget();
|
||||
const offlineStatus = new FakeTarget();
|
||||
const protectionStatus = new FakeTarget();
|
||||
const pushStatus = new FakeTarget();
|
||||
const deadlineStatus = new FakeTarget();
|
||||
const readyStatus = new FakeTarget();
|
||||
@@ -46,12 +48,13 @@ const promptStorage = {
|
||||
let readiness = {
|
||||
install:{state:'complete', detail:'Stackchain is installed.'},
|
||||
offline:{state:'incomplete', detail:'Offline work is off.'},
|
||||
protection:{state:'incomplete', detail:'Offline work uses best-effort browser storage.'},
|
||||
push:{state:'unavailable', detail:'Notifications are unavailable.'},
|
||||
deadline:{state:'unavailable', detail:'Deadline reminders are unavailable.'},
|
||||
};
|
||||
const setup = createMobileDeviceSetup({
|
||||
launcher, closeButton, sheet, installButton, offlineButton, pushButton, deadlineButton,
|
||||
installStatus, offlineStatus, pushStatus, deadlineStatus, readyStatus, escapeTarget,
|
||||
launcher, closeButton, sheet, installButton, offlineButton, protectionButton, pushButton, deadlineButton,
|
||||
installStatus, offlineStatus, protectionStatus, pushStatus, deadlineStatus, readyStatus, escapeTarget,
|
||||
promptCard, promptSummary, promptLauncher, promptDismiss,
|
||||
returnButton, isMobile:() => true,
|
||||
timerView:{
|
||||
@@ -62,6 +65,7 @@ const setup = createMobileDeviceSetup({
|
||||
getReadiness:() => { state.events.push('readiness'); return readiness; },
|
||||
install:async () => { state.installCalls += 1; },
|
||||
enableOffline:async () => { state.offlineCalls += 1; },
|
||||
protectStorage:async () => { state.protectionCalls = (state.protectionCalls || 0) + 1; },
|
||||
enablePush:async () => { state.pushCalls += 1; },
|
||||
enableDeadline:async () => { state.deadlineCalls += 1; },
|
||||
});
|
||||
@@ -90,11 +94,33 @@ process.stdout.write(JSON.stringify({
|
||||
"install": "Stackchain is installed.",
|
||||
"offline": "Offline work is off.",
|
||||
"push": "Notifications are unavailable.",
|
||||
"summary": "1 of 2 available steps ready.",
|
||||
"summary": "1 of 3 available steps ready.",
|
||||
"calls": [0, 0, 0],
|
||||
}
|
||||
|
||||
|
||||
def test_storage_protection_runs_only_from_its_explicit_setup_action():
|
||||
result = run_scenario("""
|
||||
await launcher.dispatch('click', {currentTarget:launcher});
|
||||
const callsOnOpen=state.protectionCalls || 0;
|
||||
readiness.protection={state:'complete', detail:'Offline work is protected from automatic browser storage cleanup.'};
|
||||
await protectionButton.dispatch('click');
|
||||
process.stdout.write(JSON.stringify({
|
||||
callsOnOpen,
|
||||
callsAfterAction:state.protectionCalls,
|
||||
detail:protectionStatus.textContent,
|
||||
hidden:protectionButton.hidden,
|
||||
}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"callsOnOpen": 0,
|
||||
"callsAfterAction": 1,
|
||||
"detail": "Offline work is protected from automatic browser storage cleanup.",
|
||||
"hidden": True,
|
||||
}
|
||||
|
||||
|
||||
def test_incomplete_device_is_discoverable_without_triggering_setup_actions():
|
||||
result = run_scenario("""
|
||||
process.stdout.write(JSON.stringify({
|
||||
@@ -106,7 +132,7 @@ process.stdout.write(JSON.stringify({
|
||||
|
||||
assert result == {
|
||||
"hidden": False,
|
||||
"summary": "1 of 2 steps complete",
|
||||
"summary": "1 of 3 steps complete",
|
||||
"calls": [0, 0, 0],
|
||||
}
|
||||
|
||||
@@ -146,6 +172,7 @@ process.stdout.write(JSON.stringify({hiddenAfterDismiss, delay:dismissedUntil -
|
||||
def test_setup_action_rechecks_real_state_before_marking_step_ready():
|
||||
result = run_scenario("""
|
||||
await launcher.dispatch('click', {currentTarget:launcher});
|
||||
readiness.protection = {state:'complete', detail:'Offline work is protected.'};
|
||||
readiness.offline = {state:'complete', detail:'Offline work is saved.'};
|
||||
await offlineButton.dispatch('click');
|
||||
process.stdout.write(JSON.stringify({
|
||||
@@ -227,7 +254,7 @@ process.stdout.write(JSON.stringify({
|
||||
"calls": 1,
|
||||
"detail": "Deadline reminders enabled for 08:00 local time.",
|
||||
"hidden": True,
|
||||
"summary": "3 of 4 available steps ready.",
|
||||
"summary": "3 of 5 available steps ready.",
|
||||
}
|
||||
|
||||
|
||||
@@ -248,7 +275,8 @@ def test_mobile_dashboard_mounts_phone_safe_device_setup_flow():
|
||||
assert 'id="device-setup-today-detour"' in html
|
||||
assert 'id="return-from-device-setup"' in html
|
||||
assert 'aria-labelledby="device-setup-heading"' in html
|
||||
assert all(f'id="device-setup-{step}"' in html for step in ("install", "offline", "push", "deadline"))
|
||||
assert all(f'id="device-setup-{step}"' in html for step in ("install", "offline", "protection", "push", "deadline"))
|
||||
assert 'id="device-setup-protection-status"' in html
|
||||
assert 'id="device-storage-summary"' in html
|
||||
assert 'id="device-storage-detail"' in html
|
||||
assert 'id="clear-device-caches"' in html
|
||||
@@ -260,12 +288,14 @@ def test_mobile_dashboard_mounts_phone_safe_device_setup_flow():
|
||||
assert "createMobileDeviceSetup.mount({" in dashboard
|
||||
assert "timerView," in dashboard
|
||||
assert "isMobile:options.isMobile || (() => innerWidth <= 600)" in MODULE.read_text()
|
||||
assert "createDeviceStorage.mount(document)" in dashboard
|
||||
assert "const deviceStorage = createDeviceStorage.mount(document)" in dashboard
|
||||
assert "storageProtectionReadiness:() => deviceStorage.persistenceReadiness()" in dashboard
|
||||
assert "protectStorage:() => deviceStorage.requestPersistence()" in dashboard
|
||||
assert "clearPrivateDeviceData:root.stackchainPrivateDeviceData" in storage_module
|
||||
assert "promptStorage:localStorage" in dashboard
|
||||
assert "pushControllerReady.then(ensureDeviceSetup)" in dashboard
|
||||
assert "BASE + 'static/mobile-device-setup.js'" in worker
|
||||
assert "stackchain-dashboard-shell-v121" in worker
|
||||
assert "stackchain-dashboard-shell-v122" in worker
|
||||
assert ".device-setup-panel" in css
|
||||
assert ".device-readiness-card" in css
|
||||
assert "overflow-x:hidden" in css
|
||||
|
||||
@@ -243,5 +243,5 @@ async def test_mobile_home_progressively_discloses_secondary_panels_as_insights(
|
||||
def test_mobile_insights_rolls_into_the_offline_shell():
|
||||
worker = (CONTROLLER.parent / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in worker
|
||||
assert "stackchain-dashboard-shell-v122" in worker
|
||||
assert "BASE + 'static/mobile-insights.js'" in worker
|
||||
@@ -358,7 +358,7 @@ async def test_dashboard_wires_thumb_safe_start_day_briefing_into_offline_mobile
|
||||
assert ".mobile-start-day-finish { min-height:44px;" in html
|
||||
assert "max-width:100%; overflow-wrap:anywhere;" in html
|
||||
assert "BASE + 'static/mobile-start-day.js'" in service_worker
|
||||
assert "stackchain-dashboard-shell-v121" in service_worker
|
||||
assert "stackchain-dashboard-shell-v122" in service_worker
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
@@ -410,7 +410,7 @@ async def test_plan_today_wires_cancel_back_and_success_through_overlay_history(
|
||||
def test_plan_today_controller_is_available_in_the_offline_shell():
|
||||
source = SERVICE_WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/plan-today.js'" in source
|
||||
assert "BASE + 'static/plan-today-readiness.js'" in source
|
||||
assert "BASE + 'static/plan-today-preview.js'" in source
|
||||
@@ -61,6 +61,35 @@ async def test_authenticated_security_activity_lists_private_sign_in_history(sec
|
||||
assert b"stackchain_session" not in persisted
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_tampered_security_activity_returns_no_partial_history(security_access):
|
||||
transport = httpx.ASGITransport(app=main.app, raise_app_exceptions=False)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
await client.post(
|
||||
"/api/v1/session",
|
||||
json={
|
||||
"access_token": "correct horse battery staple",
|
||||
"device_label": "Phone",
|
||||
},
|
||||
)
|
||||
with sqlite3.connect(security_access / "security.sqlite3") as connection:
|
||||
payload = connection.execute(
|
||||
"SELECT payload FROM security_events WHERE id = 1"
|
||||
).fetchone()[0]
|
||||
replacement = "A" if payload[-1] != "A" else "B"
|
||||
connection.execute(
|
||||
"UPDATE security_events SET payload = ? WHERE id = 1",
|
||||
(payload[:-1] + replacement,),
|
||||
)
|
||||
|
||||
activity = await client.get("/api/v1/security-events")
|
||||
|
||||
assert activity.status_code == 503
|
||||
assert activity.json() == {
|
||||
"detail": "Security activity is temporarily unavailable"
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_security_activity_limit_is_validated(security_access):
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
|
||||
@@ -1,6 +1,137 @@
|
||||
import sqlite3
|
||||
|
||||
from src.security_event_store import SecurityEventStore
|
||||
import pytest
|
||||
|
||||
from src.security_event_store import SecurityEventStore, SecurityEventStoreError
|
||||
|
||||
|
||||
PRIVATE_KEY = b"e" * 32
|
||||
|
||||
|
||||
def test_security_event_schema_exposes_no_plaintext_metadata_columns(tmp_path):
|
||||
store = SecurityEventStore(
|
||||
tmp_path / "security.sqlite3", clock=lambda: 1_000, encryption_key=PRIVATE_KEY
|
||||
)
|
||||
store.record("issue_closed", method="passkey", target="private/repo#42")
|
||||
|
||||
with sqlite3.connect(store.path) as connection:
|
||||
columns = {
|
||||
row[1]
|
||||
for row in connection.execute("PRAGMA table_info(security_events)")
|
||||
}
|
||||
assert columns == {
|
||||
"id",
|
||||
"payload",
|
||||
"created_at",
|
||||
"status",
|
||||
"operation_id",
|
||||
}
|
||||
|
||||
|
||||
def test_security_event_payload_is_encrypted_at_rest_and_survives_restart(tmp_path):
|
||||
path = tmp_path / "security.sqlite3"
|
||||
canaries = {
|
||||
"kind": "private_issue_closed_canary",
|
||||
"method": "private_passkey_canary",
|
||||
"device_label": "Private Operator Phone Canary",
|
||||
"target": "private-org/roadmap#4242",
|
||||
}
|
||||
store = SecurityEventStore(path, clock=lambda: 1_000, encryption_key=PRIVATE_KEY)
|
||||
|
||||
store.record(**canaries)
|
||||
|
||||
with sqlite3.connect(path) as connection:
|
||||
payload = connection.execute(
|
||||
"SELECT payload FROM security_events"
|
||||
).fetchone()[0]
|
||||
assert payload.startswith("v1:")
|
||||
database_bytes = path.read_bytes()
|
||||
assert all(value.encode() not in database_bytes for value in canaries.values())
|
||||
reopened = SecurityEventStore(path, clock=lambda: 1_001, encryption_key=PRIVATE_KEY)
|
||||
event = reopened.list(limit=10).events[0]
|
||||
assert (event.kind, event.method, event.device_label, event.target) == tuple(
|
||||
canaries.values()
|
||||
)
|
||||
|
||||
|
||||
def test_legacy_security_events_migrate_without_changing_journal_semantics(tmp_path):
|
||||
path = tmp_path / "security.sqlite3"
|
||||
with sqlite3.connect(path) as connection:
|
||||
connection.executescript(
|
||||
"""
|
||||
CREATE TABLE security_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
kind TEXT NOT NULL,
|
||||
method TEXT,
|
||||
device_label TEXT,
|
||||
target TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'completed',
|
||||
operation_id TEXT
|
||||
);
|
||||
INSERT INTO security_events
|
||||
(id, kind, method, device_label, target, created_at, status, operation_id)
|
||||
VALUES
|
||||
(7, 'legacy_sign_in_canary', 'legacy_token_canary',
|
||||
'Legacy Phone Canary', 'dashboard', 900, 'completed', NULL),
|
||||
(9, 'legacy_issue_closed_canary', 'passkey',
|
||||
'Legacy Tablet Canary', 'private/repo#9', 901, 'pending', 'operation-9');
|
||||
"""
|
||||
)
|
||||
|
||||
store = SecurityEventStore(path, clock=lambda: 1_000, encryption_key=PRIVATE_KEY)
|
||||
page = store.list(limit=1)
|
||||
older = store.list(limit=10, cursor=page.next_cursor)
|
||||
|
||||
assert [(event.id, event.kind, event.created_at, event.status) for event in page.events] == [
|
||||
(9, "legacy_issue_closed_canary", 901, "pending")
|
||||
]
|
||||
assert [(event.id, event.kind, event.created_at, event.status) for event in older.events] == [
|
||||
(7, "legacy_sign_in_canary", 900, "completed")
|
||||
]
|
||||
store.finalize("operation-9")
|
||||
assert store.list(limit=1).events[0].status == "completed"
|
||||
with sqlite3.connect(path) as connection:
|
||||
rows = connection.execute(
|
||||
"SELECT id, payload FROM security_events ORDER BY id"
|
||||
).fetchall()
|
||||
assert [row[0] for row in rows] == [7, 9]
|
||||
assert all(row[1].startswith("v1:") for row in rows)
|
||||
database_bytes = path.read_bytes()
|
||||
assert b"legacy_sign_in_canary" not in database_bytes
|
||||
assert b"Legacy Tablet Canary" not in database_bytes
|
||||
|
||||
|
||||
def test_wrong_key_or_tampered_security_activity_fails_closed(tmp_path):
|
||||
path = tmp_path / "security.sqlite3"
|
||||
store = SecurityEventStore(path, clock=lambda: 1_000, encryption_key=PRIVATE_KEY)
|
||||
store.record("issue_closed", target="private/repo#42")
|
||||
|
||||
with pytest.raises(SecurityEventStoreError, match="temporarily unavailable"):
|
||||
SecurityEventStore(
|
||||
path, clock=lambda: 1_001, encryption_key=b"x" * 32
|
||||
).list(limit=10)
|
||||
|
||||
with sqlite3.connect(path) as connection:
|
||||
payload = connection.execute(
|
||||
"SELECT payload FROM security_events WHERE id = 1"
|
||||
).fetchone()[0]
|
||||
replacement = "A" if payload[-1] != "A" else "B"
|
||||
connection.execute(
|
||||
"UPDATE security_events SET payload = ? WHERE id = 1",
|
||||
(payload[:-1] + replacement,),
|
||||
)
|
||||
with pytest.raises(SecurityEventStoreError, match="temporarily unavailable"):
|
||||
store.list(limit=10)
|
||||
|
||||
|
||||
def test_missing_security_activity_encryption_key_fails_with_store_error(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
monkeypatch.delenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEY", raising=False)
|
||||
|
||||
with pytest.raises(SecurityEventStoreError, match="temporarily unavailable"):
|
||||
SecurityEventStore(tmp_path / "security.sqlite3", clock=lambda: 1_000)
|
||||
|
||||
|
||||
def test_security_events_are_private_bounded_and_reverse_chronological(tmp_path):
|
||||
@@ -31,8 +162,7 @@ def test_security_events_are_private_bounded_and_reverse_chronological(tmp_path)
|
||||
row[1] for row in sqlite3.connect(store.path).execute("PRAGMA table_info(security_events)")
|
||||
}
|
||||
assert columns == {
|
||||
"id", "kind", "method", "device_label", "target", "created_at",
|
||||
"status", "operation_id",
|
||||
"id", "payload", "created_at", "status", "operation_id",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -168,13 +168,13 @@ async function dispatchPush(payload) {{
|
||||
def test_offline_activation_migration_rolls_the_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
|
||||
|
||||
def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/my-work.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
@@ -183,7 +183,7 @@ def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/authored-outbox.js'" in source
|
||||
assert "BASE + 'static/background-issue-sync.js'" in source
|
||||
@@ -192,7 +192,7 @@ def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
|
||||
def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/issue-evidence-review.js'" in source
|
||||
assert "BASE + 'static/issue-attachment.js'" in source
|
||||
|
||||
@@ -200,14 +200,14 @@ def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
|
||||
def test_ownership_exit_runtime_rolls_the_offline_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
|
||||
def test_offline_review_next_ships_today_completion_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/today-completion.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -215,7 +215,7 @@ def test_offline_review_next_ships_today_completion_atomically():
|
||||
def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/create-issue-sheet.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -223,7 +223,7 @@ def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/issue-sheet.js'" in source
|
||||
assert "BASE + 'static/checklist-conflict.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
@@ -233,14 +233,14 @@ def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
|
||||
def test_exact_later_picker_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/later-picker.js'" in source
|
||||
|
||||
|
||||
def test_navigation_deadline_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/install-app.js'" in source
|
||||
@@ -249,21 +249,21 @@ def test_navigation_deadline_ships_in_a_new_shell_cache():
|
||||
def test_today_convergence_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
def test_mobile_search_viewport_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/mobile-search-viewport.js'" in source
|
||||
|
||||
|
||||
def test_update_ownership_flow_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/update-ownership.js'" in source
|
||||
|
||||
|
||||
@@ -1137,7 +1137,7 @@ def test_one_session_bound_csrf_proof_is_reused_for_a_background_drain():
|
||||
def test_queue_today_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/queue-today.js'" in source
|
||||
|
||||
|
||||
|
||||
@@ -221,7 +221,7 @@ async def test_today_blocker_opens_existing_preview_and_preserves_readiness_gate
|
||||
def test_readiness_runtime_is_available_in_offline_shell():
|
||||
service_worker = SERVICE_WORKER.read_text()
|
||||
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v121';" in service_worker
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v122';" in service_worker
|
||||
assert "BASE + 'static/today-readiness.js'" in service_worker
|
||||
|
||||
|
||||
|
||||
@@ -4,9 +4,115 @@ import pytest
|
||||
import httpx
|
||||
|
||||
from src import main
|
||||
from src.state_encryption import PrivateStateEncryptionError
|
||||
from src.today_store import TodayPlanFull, TodaySessionConflict, TodayStore
|
||||
|
||||
|
||||
def test_task_bearing_today_journey_is_encrypted_at_rest_and_survives_restart(tmp_path):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
key = b"t" * 32
|
||||
store = TodayStore(path, encryption_key=key, clock=lambda: 1234.5)
|
||||
issue = "issue:private-roadmap/launch:4242:"
|
||||
device = "private-phone-canary"
|
||||
recap_session = "private-recap-canary"
|
||||
|
||||
plan = store.apply_batch("Timmy", [
|
||||
{"operation_id": "add", "action": "add", "item_id": issue},
|
||||
{"operation_id": "configure", "action": "configure", "item_id": "plan",
|
||||
"capacity_minutes": 180, "estimates": {issue: 75}},
|
||||
])
|
||||
session = store.update_session(
|
||||
"timmy", base_revision=0, device_id=device, identity=issue,
|
||||
elapsed_ms=90_000, running=True,
|
||||
)
|
||||
recap = store.save_recap("timmy", recap_session, [
|
||||
{"identity": issue, "estimate_minutes": 75, "actual_minutes": 91}
|
||||
])
|
||||
assert store.begin_time_log("timmy", recap_session, issue, 91) == "claimed"
|
||||
store.finish_time_log("timmy", recap_session, issue, succeeded=True)
|
||||
|
||||
retained = b"".join(
|
||||
candidate.read_bytes()
|
||||
for candidate in (path, path.with_name(path.name + "-wal"))
|
||||
if candidate.exists()
|
||||
)
|
||||
for canary in (issue, device, recap_session):
|
||||
assert canary.encode() not in retained
|
||||
assert retained.count(b"v1:") >= 4
|
||||
|
||||
reopened = TodayStore(path, encryption_key=key)
|
||||
assert reopened.get("timmy") == {
|
||||
key: value for key, value in plan.items()
|
||||
if key not in {"accepted_operation_ids", "duplicate_operation_ids", "rejected_operations"}
|
||||
}
|
||||
assert reopened.get_session("timmy") == session
|
||||
assert reopened.list_recaps("timmy") == [recap]
|
||||
assert reopened.begin_time_log("timmy", recap_session, issue, 91) == "logged"
|
||||
|
||||
|
||||
def test_legacy_today_rows_migrate_on_use_without_changing_behavior(tmp_path):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
key = b"m" * 32
|
||||
store = TodayStore(path, encryption_key=key)
|
||||
issue = "issue:legacy-private/project:7:"
|
||||
with sqlite3.connect(path) as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO today_plans VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
("timmy", 4, f'["{issue}"]', 120, f'{{"{issue}":45}}', "2026-08-19", "UTC"),
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO today_sessions VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
("timmy", 3, "legacy-phone", issue, 5000, 1, None, 99.0),
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO today_recaps VALUES (?, ?, ?, ?)",
|
||||
("timmy", "legacy-session", 88.0,
|
||||
f'[{ {"identity": issue, "estimate_minutes": 45, "actual_minutes": 50} }]'.replace("'", '"')),
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO today_time_logs VALUES (?, ?, ?, ?, ?)",
|
||||
("timmy", "legacy-session", issue, 50, "pending"),
|
||||
)
|
||||
|
||||
assert store.get("timmy")["revision"] == 4
|
||||
assert store.get_session("timmy")["revision"] == 3
|
||||
assert store.list_recaps("timmy")[0]["items"][0]["identity"] == issue
|
||||
assert store.begin_time_log("timmy", "legacy-session", issue, 50) == "pending"
|
||||
|
||||
retained = path.read_bytes()
|
||||
for canary in (issue, "legacy-phone", "legacy-session"):
|
||||
assert canary.encode() not in retained
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_tampered_or_account_substituted_today_state_fails_closed_with_retry(monkeypatch, tmp_path):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
store = TodayStore(path, encryption_key=b"a" * 32)
|
||||
store.apply("timmy", "seed", "add", "issue:private/repo:9:")
|
||||
with sqlite3.connect(path) as connection:
|
||||
payload = connection.execute(
|
||||
"SELECT ids FROM today_plans WHERE login = 'timmy'"
|
||||
).fetchone()[0]
|
||||
connection.execute(
|
||||
"INSERT INTO today_plans(login, revision, ids, estimates) VALUES ('alexander', 1, ?, '{}')",
|
||||
(payload,),
|
||||
)
|
||||
|
||||
with pytest.raises(PrivateStateEncryptionError):
|
||||
store.get("alexander")
|
||||
|
||||
async def user():
|
||||
return {"login": "alexander"}
|
||||
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
monkeypatch.setattr(main, "_today_store", lambda: store)
|
||||
with pytest.raises(main.HTTPException) as raised:
|
||||
await main.get_today_plan()
|
||||
assert raised.value.status_code == 503
|
||||
assert raised.value.detail == "Today synchronization is unavailable"
|
||||
assert raised.value.headers == {"Retry-After": "1"}
|
||||
|
||||
|
||||
def test_active_session_is_durable_and_account_scoped(tmp_path):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
store = TodayStore(path, clock=lambda: 1234.5)
|
||||
|
||||
@@ -191,7 +191,7 @@ sync.enqueueConfiguration(120, {{'issue:r:1:':60}});
|
||||
def test_inflight_today_drain_ships_in_a_new_offline_shell():
|
||||
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v121" in source
|
||||
assert "stackchain-dashboard-shell-v122" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user