@bazariodev/auth-session
v0.1.0
Published
On-demand access session lifecycle with an application adapter.
Readme
Auth Session
Manage one access session with on-demand refresh. The application supplies an adapter for the durable session and owns the login flow.
Install
npm install @bazariodev/auth-sessionThe only runtime dependency is @bazariodev/fsm.
Usage
import { createAuthSession } from '@bazariodev/auth-session';
// The application supplies this adapter and completes login first.
const session = createAuthSession({ adapter });
const restored = await session.restore();
if (restored.ok) {
const access = await session.getAccess();
if (access.ok) await sendRequest(access.value.token);
}The adapter must supply refresh(signal) and signOut(). It owns the durable
credential, its storage, network deadlines, and cleanup. It must honor cancellation
where possible. The application supplies sendRequest in this example.
This fake adapter shows login, reload, refresh, and sign-out. It is not a backend
adapter. It returns unavailable only when it skips the request before sending it.
import { createAuthSession } from '@bazariodev/auth-session';
let time = 0;
let durableSession = false;
let canSend = true;
const adapter = {
async refresh(signal) {
if (!durableSession) return { kind: 'no-session' };
if (!canSend || signal.aborted) return { kind: 'unavailable' };
return {
kind: 'granted',
grant: { accountKey: 'account-1', token: 'example-token', expiresIn: 60_000 },
};
},
async signOut() {
durableSession = false;
},
};
durableSession = true; // The application completed login.
const first = createAuthSession({ adapter, now: () => time });
await first.restore();
const afterReload = createAuthSession({ adapter, now: () => time });
await afterReload.restore();
time = 60_000;
canSend = false;
const skipped = await afterReload.getAccess();
console.log(skipped, afterReload.snapshot.value); // unavailable, expired
canSend = true;
const refreshed = await afterReload.getAccess();
console.log(refreshed.ok); // true
await afterReload.signOut();
const empty = await createAuthSession({ adapter }).restore();
console.log(empty); // no-sessionBehavior
- Construction does not access the network or storage. Call
restore()after login and on startup. Complete sign-out before a new login. - Access is held in memory. Snapshots contain state and non-secret metadata only. Read access immediately before use. Check it again after a separate wait.
- The session ignores exceptions from listeners and continues notification.
expiresInis the positive safe integer lifetime in milliseconds at handoff. The adapter can subtract a safety margin. The default clock isDate.now.- Requests share an in-flight refresh. The package makes at most one adapter call per operation and does not retry automatically.
- Each grant increases
revision. Pass the rejected revision to the instance that issued it. An old revision from the same session uses current access when usable. A revision outside the current session returnssuperseded. - Refresh must keep the account key. A typed
unavailablekeeps the session expired and permits a later request. A thrown or invalid refresh ends the local session: the adapter must resolve an uncertain server outcome before it reuses a credential. - Sign-out clears local access, aborts and drains pending adapter work, then calls
adapter
signOut. A failed cleanup stays insigning-out; callsignOutagain to retry. The adapter must prevent retired work from changing the durable session after cleanup. Clear a removable local credential before remote cleanup. - A new instance can restore after failed cleanup if a durable credential remains. The backend defines cookie and remote revocation behavior.
- The snapshot records the last transition. Access checks expiry on each request, including after sleep. No background timer or cross-tab coordination is included.
API
| Member | Result |
| --- | --- |
| createAuthSession({ adapter, now? }) | Create a session. now returns a finite clock reading in Unix milliseconds. |
| snapshot | FSM snapshot with state and metadata. |
| subscribe(listener) | Subscribe to transitions. Returns an unsubscribe function. |
| restore() | Restore a durable session or join an active restore. |
| getAccess(rejectedRevision?) | Get usable access or refresh it. |
| signOut() | Clear local and durable access, or retry cleanup. |
A grant has a nonempty accountKey, a nonempty token, and expiresIn.
The account key must not be secret. Access contains accountKey, token,
expiresAt, and revision. Adapter refresh returns { kind: 'granted', grant },
{ kind: 'no-session' }, or { kind: 'unavailable' }.
Errors
Operations return { ok: true, value } or { ok: false, reason }. Reasons are
no-session, unavailable, busy, and superseded. Adapter errors are not exposed.
A failed restore returns no-session for an absent session and unavailable for
other failures. restore() returns busy during sign-out. getAccess() returns
no-session without a session. An operation retired by sign-out returns superseded.
If the clock fails, the caller receives unavailable. A failed reading during grant
installation ends the local session. A failed reading of cached access keeps the current state.
TypeScript
The package includes declarations for its adapter, session, results, access, and
snapshots. It uses @bazariodev/fsm
for snapshots and subscriptions. Browser consumers need the DOM or WebWorker library.
Node.js consumers need typings that provide AbortSignal.
License
MIT
