@asaidimu/iam
v9.0.0
Published
A lightweight, type-safe Identity and Access Management (IAM) system for client-side JavaScript/TypeScript applications.
Maintainers
Readme
@asaidimu/iam
A type-safe identity, session, and access-control toolkit for client-side JavaScript and TypeScript applications.
The library separates four concerns:
- Authority — your server or backend decides who the user is.
- Session state — the authenticator owns a revisioned local snapshot.
- Persistence and transport — you can supply storage and cross-tab adapters.
- Authorization — the access controller evaluates rules against a snapshot.
Identity snapshots are local views of authority. They can be stale, expired, locked, or unavailable. Client-side authorization is advisory; the server must enforce the real boundary.
Install
npm install @asaidimu/iam
# or
bun add @asaidimu/iamTypeScript definitions are included.
Quick start
createAuthenticator is asynchronous.
import { createAuthenticator } from "@asaidimu/iam";
interface UserProps {
id: string;
name: string;
}
type AuthParams = [username: string, password: string];
const provider = await createAuthenticator<UserProps, AuthParams>({
onAuthenticate: async (username, password) => {
const response = await fetch("/api/login", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (!response.ok) return null;
return {
permissions: ["dashboard:view", "posts:read"],
properties: { id: "user-123", name: "Ada" },
};
},
onDeauthenticate: async (properties) => {
await fetch("/api/logout", { method: "POST" });
return true;
},
});
const ok = await provider.authenticate("ada", "secret");
const identity = await provider.identity();
if (ok && identity) {
console.log(identity.properties.name);
}Snapshots
Read state through getSnapshot(), not by inferring it from identity().
import type { IdentitySnapshot } from "@asaidimu/iam";
const snapshot: IdentitySnapshot<UserProps> = provider.getSnapshot();
switch (snapshot.status) {
case "authenticated":
break;
case "expired":
case "locked":
case "error":
case "unauthenticated":
break;
}Every snapshot includes:
| Field | Meaning |
| --- | --- |
| status | unauthenticated, authenticated, expired, locked, or error |
| identity | Last known identity, or null |
| revision | Monotonic revision for the state owner |
| expiresAt | Session expiry timestamp, or null |
| lastActivity | Last recorded activity timestamp |
| source | initial, authenticate, restore, refresh, external, or persistence |
| updatedAt | When this snapshot was produced |
| error | Optional diagnostic error |
getSnapshot() is synchronous and pure. It does not clear state, write storage,
start timers, or call the network.
ensureFresh() is the explicit revalidation path. It may lock an idle session
or otherwise reconcile state, and then returns the current snapshot.
const current = await provider.ensureFresh();
const unsubscribe = provider.subscribe((next) => {
console.log(next.status, next.revision);
});Lifecycle hooks
| Hook | Purpose |
| --- | --- |
| onAuthenticate(...args) | Return an identity on successful login, or null on rejection |
| onDeauthenticate(properties) | Clear the backend session |
| onRefresh(identity) | Return a refreshed identity, or null when the server rejects the session |
| onVerify(identity) | Validate a persisted identity during startup |
| onRestore() | Ask the server who the current user is when no identity is persisted |
| onLoad(identity) | Post-load notification; typed as Promise<void> |
| onAuthChange(callback) | External authority pushes identity changes into the authenticator |
onRestore runs at startup when no identity exists, and from refresh() when no
identity exists. It is optional. Returning null means “no session”, not an
error.
onVerify only runs for persisted identities. onLoad runs once after the final
startup state is settled.
Refresh semantics
Use refreshResult() when callers need to distinguish rejection from an
unavailable authority.
const result = await provider.refreshResult();
switch (result.status) {
case "refreshed":
// New identity and expiry were written.
break;
case "unchanged":
// No onRefresh hook is configured.
break;
case "unauthenticated":
// The server rejected the session; identity was cleared.
break;
case "unavailable":
// Network/5xx error; the last known identity was preserved.
break;
}The legacy refresh() method returns the current identity or null, and keeps
the identity on unavailable.
Automatic refresh uses the same contract. A thrown refresh error preserves the
identity; a null result clears it.
Sessions
const provider = await createAuthenticator({
// ...
session: {
ttl: 60 * 60 * 1000,
refreshLeadTime: 10 * 60 * 1000,
},
});refreshLeadTime is the lead time before expiry, not a polling interval.
refreshInterval remains as a deprecated alias.
Persistence
Persistence must implement SimplePersistence from
@asaidimu/utils-persistence. The authenticator owns the persisted state shape.
import { WebStoragePersistence } from "@asaidimu/utils-persistence";
import type { ProviderState } from "@asaidimu/iam";
const persistence = new WebStoragePersistence<ProviderState<UserProps>>({
version: "1.0.0",
app: "my-app",
storageKey: "iam-session",
});
const provider = await createAuthenticator<UserProps, AuthParams>({
// ...
persistence,
});You can also provide an explicit store, transport, clock, or activity
source. These are adapters; the authenticator does not expose its internal store
through the public API.
const provider = await createAuthenticator({
// ...
clock: () => Date.now(),
transport: {
publish(snapshot) {},
subscribe(listener) {
return () => {};
},
},
});The legacy scope option remains for advanced container users. It owns state
and cannot be combined with store, persistence, or transport; conflicting
configuration throws IAMError with code INVALID_CONFIG.
For workers and coordinators, an IndexedDB persistence adapter is available on a subpath:
import { createIndexedDBPersistence } from "@asaidimu/iam/identity/persistence";
const persistence = createIndexedDBPersistence({
version: "1.0.0",
app: "my-app",
database: "my-app",
collection: "iam-session",
});Coordination
Coordination adapters are optional and are not exported from the default entry.
Single-flight refresh
import { refreshWithWebLock } from "@asaidimu/iam/coordination/web-locks";
const result = await refreshWithWebLock({
read: () => provider.getSnapshot(),
refresh: () => provider.refreshResult(),
timeoutMs: 10_000,
ifAvailable: true,
});The adapter acquires a per-operation iam:refresh lock. After acquiring it
re-reads the snapshot; if another tab already advanced the revision, the refresh
is skipped. It does not hold a lifetime leadership lock.
Cross-tab snapshots
import { createBroadcastTransport } from "@asaidimu/iam/coordination/broadcast";
const transport = createBroadcastTransport({
channelName: "my-app:iam",
onRevisionGap: () => {
// re-read durable state or ask the coordinator to resync
},
});Pass the transport to createAuthenticator({ transport }) to publish local
snapshots and apply remote revisions.
Security policy
Idle locking is optional. The authenticator owns the policy; the browser or an
ActivitySource provides activity signals.
const provider = await createAuthenticator({
// ...
security: {
enabled: true,
maxIdleTime: 10 * 60 * 1000,
warningTime: 30 * 1000,
lockOnWindowBlur: true,
onIdleWarning: (remainingMs) => {
console.warn(`Session expires in ${remainingMs}ms`);
},
onIdleTimeout: () => {
console.warn("Session locked due to inactivity");
},
onSessionLocked: () => {
console.warn("Session locked");
},
onSecurityEvent: (event, details) => {
console.log(event, details);
},
},
});Idle timeout fires once per idle period. Activity resets the timer without
re-running onVerify or onLoad.
For worker or custom environments, provide an activity source:
const provider = await createAuthenticator({
// ...
activity: {
getLastActivity: () => lastActivity,
subscribe: (listener) => {
return activityBus.subscribe(listener);
},
},
});Access control
import {
createAccessController,
type IAMRuleSet,
} from "@asaidimu/iam";
const rules: IAMRuleSet<UserProps, { ownerId: string }> = new Map([
[
"posts:edit",
({ identity, resource }) =>
identity?.id === resource.ownerId,
],
]);
const access = createAccessController(provider, rules, {
maxSnapshotAge: 60_000,
allowStale: false,
});
const decision = await access.authorize("posts:edit", {
ownerId: "user-123",
});
if (!decision.allowed) {
console.warn(decision.reason);
}The controller accepts an IdentityReader or a legacy IdentityProvider. It
denies unauthenticated, expired, locked, error, and stale snapshots by
default. Set allowStale: true to opt into last-known identity behavior.
Rule cache
Rule caching is disabled by default. Opt in explicitly:
const access = createAccessController(provider, rules, {
cache: {
maxEntries: 100,
key: (permission, resource) => {
if (!resource) return "none";
return `${permission}:${(resource as { id: string }).id}`;
},
},
});Entries are keyed by snapshot revision, permission/rule ID, and the caller-supplied resource key. They are bounded and cleared when the revision changes. Resource checks without a cache key are not cached.
Do not cache rules that depend on mutable external state or on resources whose
key does not change when the rule input changes. cacheTTL is deprecated and
ignored.
Role interfaces
Use the narrowest interface that fits your consumer:
import type {
IdentityReader,
SessionCommands,
SessionPersistence,
SessionTransport,
ActivitySource,
IdleCapability,
} from "@asaidimu/iam";IdentityReader—getSnapshot,subscribe, optionalensureFreshSessionCommands—authenticate,deauthenticate,refresh, optionaldestroySessionPersistence—load,save,clearSessionTransport—publish,subscribeActivitySource— activity timestamp and optional subscriptionIdleCapability— idle-time queries and reset
IdentityProvider remains as a deprecated compatibility facade. Convert
between the old and new contracts with toIdentityReader() and
fromIdentityReader().
Documentation
- Snapshot and freshness details:
docs/state.md - Migration from 8.x:
docs/migration-9.md
Development
bun install
bun run typecheck
bun run lint
bun run test:run
bun run buildThe test suite covers snapshot contracts, persistence, refresh failures, restore lifecycle, security timers, access freshness, and rule-cache invalidation.
License
MIT
