@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
161 lines (160 loc) • 4.42 kB
JavaScript
//#region src/auth/idle-clock.ts
const KEY_LAST_ACTIVITY = "softr.idle.v1.lastActivity";
const KEY_SIGNED_OUT = "softr.idle.v1.signedOutAt";
/** Shared clock writes at most this often, so a mousemove is not a storage write in every tab. */
const WRITE_EVERY_MS = 5e3;
/**
* Activity events, listened for on the document in the capture phase. `scroll`
* does not bubble, and capture still sees events a handler stops.
*/
const ACTIVITY_EVENTS = [
"pointerdown",
"pointermove",
"mousedown",
"mousemove",
"wheel",
"keydown",
"touchstart",
"touchmove",
"scroll",
"click",
"input",
"focusin",
"submit"
];
/**
* Starts the idle clock and returns what stops it.
*
* Idle time is checked against the wall clock on a tick, not with one long
* timeout. Browsers delay timers in background tabs, and a laptop that wakes
* from sleep resumes a pending timeout with its full delay left.
*
* `signOut` clears this browser's session. It is the `endIdleSession` server
* function, passed in so a test can run the clock without a server.
*
* `sessionStartedAt` is when the visitor signed in. Activity saved in this
* browser before that belongs to an earlier session and is ignored, so a
* fresh sign-in is never signed straight out. `null` when it is not known.
*/
function startIdleClock(idleMs, signOut, sessionStartedAt) {
const tickMs = Math.min(15e3, Math.max(2e3, Math.floor(idleMs / 30)));
const graceCapMs = idleMs;
let localLast = Date.now();
let lastWrite = 0;
let graceUsed = 0;
let ending = false;
let expired = false;
let finished = false;
const listeners = new AbortController();
function mark(now) {
if (now > localLast) localLast = now;
if (now - lastWrite >= WRITE_EVERY_MS) {
lastWrite = now;
writeStorage(KEY_LAST_ACTIVITY, String(now));
}
}
function onActivity() {
if (expired) return;
if (Date.now() - localLast >= idleMs) {
tick();
if (finished || expired) return;
}
graceUsed = 0;
mark(Date.now());
}
function stop() {
finished = true;
clearInterval(ticker);
listeners.abort();
}
function leave() {
if (finished) return;
stop();
window.location.replace("/");
}
async function endSession() {
if (ending) return;
ending = true;
try {
await signOut();
} catch {
ending = false;
return;
}
writeStorage(KEY_SIGNED_OUT, String(Date.now()));
removeStorage(KEY_LAST_ACTIVITY);
leave();
}
function tick() {
if (finished) return;
if (readStorage(KEY_SIGNED_OUT)) {
leave();
return;
}
if (!expired) {
const now = Date.now();
const shared = Number(readStorage(KEY_LAST_ACTIVITY));
const last = Number.isFinite(shared) && shared > localLast ? shared : localLast;
if (now - last < idleMs) return;
const active = document.activeElement;
if (active !== null && active.tagName === "IFRAME" && document.hasFocus() && graceUsed < graceCapMs && now - last < idleMs + graceCapMs) {
graceUsed += now - last;
mark(now);
return;
}
expired = true;
}
endSession();
}
removeStorage(KEY_SIGNED_OUT);
const saved = Number(readStorage(KEY_LAST_ACTIVITY));
if (sessionStartedAt !== null && Number.isFinite(saved) && saved >= sessionStartedAt && Date.now() - saved >= idleMs) expired = true;
else mark(Date.now());
const ticker = setInterval(tick, tickMs);
const { signal } = listeners;
for (const event of ACTIVITY_EVENTS) document.addEventListener(event, onActivity, {
capture: true,
passive: true,
signal
});
window.addEventListener("focus", onActivity, {
capture: true,
signal
});
document.addEventListener("visibilitychange", () => {
if (document.visibilityState !== "visible") return;
tick();
if (!finished && !expired) onActivity();
}, { signal });
window.addEventListener("storage", (event) => {
if (event.key === KEY_SIGNED_OUT && event.newValue) {
leave();
return;
}
if (event.key === KEY_LAST_ACTIVITY && event.newValue) {
const shared = Number(event.newValue);
if (Number.isFinite(shared) && shared > localLast) localLast = shared;
}
}, { signal });
if (expired) endSession();
return stop;
}
function readStorage(key) {
try {
return window.localStorage.getItem(key);
} catch {
return null;
}
}
function writeStorage(key, value) {
try {
window.localStorage.setItem(key, value);
} catch {}
}
function removeStorage(key) {
try {
window.localStorage.removeItem(key);
} catch {}
}
//#endregion
export { startIdleClock };