feat: lock idle dashboard sessions (#463)
CI / lint (pull_request) Successful in 56s
CI / build-release (pull_request) Successful in 5s
CI / release-candidate (pull_request) Has been skipped

This commit is contained in:
timmy committed 2026-08-10 07:45:00 +00:00
1 parent 9904f17e3d
commit 0b992543f1
12 files changed
+402 -27

No files matched your search

+4
View File
@@ -35,6 +35,10 @@
status.textContent = 'Your session expired. Private drafts remain on this device. Sign in to continue.';
return;
}
if (reason === 'session-idle') {
status.textContent = 'Stackchain locked after inactivity. Your drafts and queued work are still on this device. Sign in to resume.';
return;
}
if (reason !== 'session-revoked') return;
button.disabled = true;
status.textContent = 'This device was remotely signed out. Clearing Stackchain private data…';
+8
View File
@@ -115,6 +115,11 @@ async function purgeRevokedSessionData() {
clients.forEach(client => client.postMessage?.({ type: 'stackchain-session-revoked' }));
}
async function notifyIdleSession() {
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
clients.forEach(client => client.postMessage?.({ type: 'stackchain-session-idle' }));
}
async function storeOfflineLease(expiresAt) {
if (!Number.isInteger(expiresAt) || expiresAt <= 0) return;
const cache = await caches.open(CACHE);
@@ -177,6 +182,9 @@ async function fetchJson(url, options = {}) {
if (response.status === 401 && code === 'session_revoked') {
await purgeRevokedSessionData();
}
if (response.status === 401 && code === 'session_idle') {
await notifyIdleSession();
}
const error = new Error(payload.error || payload.detail?.message || payload.detail || 'Background issue delivery failed.');
error.status = response.status;
error.code = code;
+41 -1
View File
@@ -15,6 +15,7 @@
serviceWorker: root.navigator?.serviceWorker,
MessageChannel: root.MessageChannel,
location: root.location,
addActivityListener: (type, listener, options) => root.addEventListener(type, listener, options),
confirmAction: message => root.confirm(message),
promptAuthorization: details => root.prompt(
`Confirm ${String(details.action || 'this action').replaceAll('_', ' ')} by entering your dashboard access token.`,
@@ -27,6 +28,7 @@
});
root.fetch = boundary.fetch;
const attach = () => {
boundary.startActivityHeartbeat();
const button = root.document.getElementById('sign-out');
if (button) button.addEventListener('click', () => boundary.signOut());
const allDevicesButton = root.document.getElementById('sign-out-all');
@@ -91,16 +93,19 @@
root.stackchainSession = boundary;
}
})(typeof window !== 'undefined' ? window : this, function createSessionBoundary({
cookie, origin, base, fetchImpl, localStorage, sessionStorage, indexedDB, caches, serviceWorker, MessageChannel, location, confirmAction,
cookie, origin, base, fetchImpl, localStorage, sessionStorage, indexedDB, caches, serviceWorker, MessageChannel, location, confirmAction, addActivityListener,
promptAuthorization = () => null,
onExpired = () => {},
onClearError = () => {},
requestTimeoutMs = 15000,
activityHeartbeatIntervalMs = 60000,
now = () => Date.now(),
setTimer = (callback, delay) => setTimeout(callback, delay),
}) {
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
let expirationStarted = false;
let lastActivityHeartbeatAt = Number.NEGATIVE_INFINITY;
let activityHeartbeat = null;
async function handleRemoteRevocation() {
if (expirationStarted) return;
@@ -117,10 +122,19 @@
location.replace(base + 'login?reason=session-expired');
}
function handleSessionIdle() {
if (expirationStarted) return;
expirationStarted = true;
location.replace(base + 'login?reason=session-idle');
}
async function handleServiceWorkerMessage(event) {
if (event?.data?.type === 'stackchain-session-revoked') {
await handleRemoteRevocation();
}
if (event?.data?.type === 'stackchain-session-idle') {
handleSessionIdle();
}
if (event?.data?.type === 'stackchain-session-expired') {
await handleSessionExpiry();
}
@@ -253,6 +267,9 @@
if (payload.code === 'session_revoked') {
expirationStarted = false;
await handleRemoteRevocation();
} else if (payload.code === 'session_idle') {
expirationStarted = false;
handleSessionIdle();
} else {
expirationStarted = false;
await handleSessionExpiry();
@@ -261,6 +278,27 @@
return response;
}
function recordActivity() {
const current = now();
if (
expirationStarted
|| activityHeartbeat
|| current - lastActivityHeartbeatAt < activityHeartbeatIntervalMs
) return Promise.resolve(false);
lastActivityHeartbeatAt = current;
activityHeartbeat = sessionFetch(base + 'api/v1/session/activity', { method: 'POST' })
.then(response => response.ok)
.catch(() => false)
.finally(() => { activityHeartbeat = null; });
return activityHeartbeat;
}
function startActivityHeartbeat() {
['pointerdown', 'keydown', 'touchstart'].forEach(type => {
addActivityListener?.(type, recordActivity, { passive: true });
});
}
async function refreshOfflineLease() {
try {
const response = await sessionFetch(base + 'api/v1/session');
@@ -391,5 +429,7 @@
handleServiceWorkerMessage,
refreshOfflineLease,
resumeQueuedWork,
recordActivity,
startActivityHeartbeat,
};
});