A cold start is not a biometric sheet: no grace on restore
An app that locks after inactivity has to judge an absence at two different moments: when it returns to the foreground, and when a stored session is loaded into a process that has just started. Both moments hand you the same data, a last-activity timestamp and a question about whether the session is still live, so the temptation is to answer them with one code path. That is a mistake. The foreground path grants a short grace period so a Face ID sheet cannot shut a user out of the very step that lets them back in, and granting that same grace to a cold start turns force-quitting the app into a way around the lock.
We keep a small library for this problem, sessionlock. Its premise is that you cannot count elapsed time with a timer: setTimeout does not run while the app is backgrounded, and on iOS it does not run while the device is asleep either. So the library stores timestamps and compares them instead. There are two places where that comparison happens, foreground() and restore(), and they are deliberately not the same function.
Two absences that are not the same kind#
foreground() measures an absence that may well have been nothing. A biometric prompt backgrounds the app. So does a permission dialog and a share sheet. Counting that as leaving shuts the user out of the step that lets them back in and traps them in a loop, so a short grace period (DEFAULT_GRACE_MS is 1500) covers the round trip. It covers only a session that was still live on the way out: one already past its idle deadline locks as the app is left, so the trip cannot reopen it. We have written separately about why that grace check has to be the first question asked on return rather than a special case bolted onto the background timeout, and that ordering is what makes backgroundAfterMs: 0 usable on an app that opens with Face ID.
restore() measures something else entirely. Nobody taps through a biometric prompt and comes back in a new process. A cold start is evidence of a different class of event: the user force-quit the app, the OS reclaimed its memory, the device rebooted, the process crashed. None of those is a round trip through a system sheet, and none of them is bounded by anything at all. The comment in src/lock.ts records what happened when the two paths were one, because routing restore() through foreground() once made force-quitting a way around the lock. A session idle for an hour came back open, since the restored snapshot read as a sub-second trip through a prompt.
So restore() is the entry point for a session that survived a cold start, and it does not route the stored snapshot through foreground(). It records the current state and reason, then answers the only question a new process can answer honestly: how old is this?
restore() refuses before it measures#
Before any age arithmetic, three snapshots are refused outright: one that readable() rejects, one that is already locked, and one that carries no lastActivityAt. Each of those closes the lock through #close, with storedReason() deciding what to call it.
/**
* A snapshot arrives from storage, where its type is a promise rather than a
* guarantee: an older version of the app wrote it, a write was cut short, a
* value was edited by hand. A snapshot that cannot be read is no reason to
* leave a session open.
*/
function readable(snapshot: Snapshot): boolean {
if (snapshot.state !== "locked" && snapshot.state !== "unlocked") return false;
if (snapshot.reason !== null && !REASONS.includes(snapshot.reason)) return false;
if (snapshot.lastActivityAt && !Number.isFinite(new Date(snapshot.lastActivityAt).getTime())) {
return false;
}
return true;
}
function storedReason(reason: LockReason | null): LockReason {
return reason !== null && REASONS.includes(reason) ? reason : "manual";
}Two details in there are worth copying into whatever you build. First, the state survives storage but the label does not have to: an unknown or null reason becomes manual rather than being passed through, so a corrupted field cannot invent a reason the lock never issued. Second, a snapshot with no lastActivityAt closes the lock. There is no "assume it is young" branch, because the whole decision rests on that one field. With it missing there is nothing to measure, and a measurement you cannot make is not evidence that the session is live.
The background limit is checked first#
For a readable, unlocked snapshot, restore() copies lastActivityAt into #lastActivityAt, sets #state to unlocked, clears #reason and #leftForegroundAt, and computes away as now minus the stored activity. That single number is then compared against backgroundAfterMs first and idleAfterMs second: at or past the background limit the lock closes with reason backgrounded; otherwise at or past the idle limit it closes with idle; younger than both, and the session stays open.
The order follows from what the number means. The entire age of a restored session is time the app was not in front of its user, and for part of it the process was not even running, so the limit that applies to an app sitting in the switcher is the one that applies here. That limit is usually the shorter of the two. Checking idle first would let a session that is past the background limit but short of the idle limit come back open, which is precisely the exposure the separate background timeout exists to close.
console.log("\napp force-quit, reopened an hour later");
const cold = make();
const stored: Snapshot = {
state: "unlocked",
lastActivityAt: new Date(at - 60 * MINUTE).toISOString(),
reason: null,
};
show("restoring a session last used an hour ago", make().restore(stored));
show("restoring one used a minute ago", cold.restore({
state: "unlocked",
lastActivityAt: new Date(at - MINUTE).toISOString(),
reason: null,
}));app force-quit, reopened an hour later
restoring a session last used an hour ago locked (backgrounded)
restoring one used a minute ago unlockedOne consequence to know before you read the reason field anywhere that matters: backgroundAfterMs defaults to idleAfterMs, so unless you set it, an idled-out restored session reports backgrounded rather than idle. The state is correct either way, since the label belongs to whichever check fired, and at equal limits that is the background one. If your lock screen distinguishes the two in copy, set both options explicitly instead of relying on the default.
The wall clock is the other thing to hold in mind. now defaults to () => new Date() because the wall clock is the one that keeps counting while the device sleeps and the process is suspended, and that is exactly the interval being measured. The price is that it can be set. A stored snapshot stamped later than now makes the absence negative, and a negative number is under every limit, so a naive implementation would read it as a brief trip through a prompt. It locks instead, with reason backgrounded, on the same principle as the missing timestamp: an absence that cannot be measured is not evidence that the session is still live.
Restoring a lock is usually silent#
Whichever path is taken, #announce compares the previous state and reason pair against the new one and notifies subscribers only on a real change. Restoring a locked snapshot into an instance that is already locked for the same reason tells nobody, because there was no change to report. That matches the contract subscribe advertises: every real change, a lock closing or a closed session being opened again, but not an unlock() on one already open.
The practical consequence for the UI layer is that you should not drive your first render off the subscription. restore() returns the resulting Snapshot; render from that, then let the subscription carry changes from there. Our mobile and QA roles treat this as a standing review note on anything that gates a screen: the initial state comes from a return value, never from an event you hope will arrive.
What it costs to run#
The mechanism itself is cheap, one subtraction and two comparisons, no timer, no reads or writes. The real costs sit either side of it.
You need the snapshot on disk. How often to write it is the app's decision, and the departure is the obvious moment, because that is the last point the app controls before it may never run again. Writing on every interaction buys very little and costs a flush per tap.
And a stored timestamp is an input to a security decision even though it is not a secret. readable() exists because a value may have been written by an older version of the app, cut short mid-write, or edited by hand, but it catches corruption, not a plausible lie. Nothing in a locally stored, locally validated timestamp stops someone who can rewrite the sandbox from forward-dating their own activity. If that is in your threat model, put the snapshot where the platform protects it, and keep the authority for anything that actually matters on the server.
Two moments, two rules, and the rule for the second one is the simpler of the pair: measure the age, check the shorter limit first, grant nothing. The grace period is a concession to one specific thing the operating system does to a running app. A process that is not running was not doing that.