UnlockOS Developers
← Back to blog
🔐

One Verb, One Truth: Safe State Changes for Smart Locks

Nov 23, 2026→Nov 29, 2026
9 min
145 commits
Depth 8/10
securitystate-machinetypescriptpostgresqlreliability

Introduction

When software decides whether a door opens, every shortcut becomes a liability. A reservation that is cancelled but whose key is still valid is not a cosmetic bug — it is unauthorized physical access. A credential that silently expires mid-stay is not a UX problem — it is a guest locked out of their room at midnight.

This article walks through a set of engineering patterns we have been consolidating in the UnlockOS SDK: funnelling all state transitions through a single verb, pushing authorization down to the database, adding step-up authentication to privileged surfaces, keeping the error channel honest, and running destructive automation behind blast-radius controls. All examples are generalized — they are patterns, not internal implementation dumps.


1. One Verb for Every State Transition

The most dangerous property of an access-control system is having more than one way to change state. Over time, a reservation can be written from a dozen places: the admin UI, an iCal sync, a PMS importer, a cancellation webhook, an auto-checkout job. If each of those does its own UPDATE reservations SET ..., then key issuance, key revocation, and audit logging are re-implemented (and forgotten) a dozen times.

The fix is a single change verb: one function that owns the transition, and therefore owns every side effect that must accompany it.

export type ReservationChange =
  | { kind: 'create'; input: ReservationInput }
  | { kind: 'reschedule'; reservationId: string; startAt: Date; endAt: Date }
  | { kind: 'cancel'; reservationId: string; reason: CancelReason }
  | { kind: 'preempt'; reservationId: string; byReservationId: string };

export interface ChangeResult {
  reservation: Reservation;
  keyEffects: KeyEffect[];
  auditId: string;
}

export async function applyReservationChange(
  ctx: RequestContext,
  change: ReservationChange,
): Promise<ChangeResult> {
  return withTransaction(ctx, async (tx) => {
    const before = await loadForUpdate(tx, change);
    assertTransitionAllowed(before?.status, change);
    const after = await writeReservation(tx, before, change);
    const keyEffects = await reconcileKeys(tx, before, after);
    const auditId = await appendAudit(tx, { ctx, before, after, keyEffects });
    return { reservation: after, keyEffects, auditId };
  });
}

Three things are now structurally guaranteed rather than remembered by a reviewer:

  1. Key reconciliation always runs. Cancel a reservation and the key is closed in the same transaction. Move the dates and the key window moves with it.
  2. Audit is not optional. Every transition produces an audit row inside the same transaction. If the audit write fails, the state change rolls back.
  3. Illegal transitions are rejected centrally. assertTransitionAllowed is a small finite-state table, and it is the only place that needs reviewing when the lifecycle evolves.
const ALLOWED: Record<ReservationStatus, ReservationStatus[]> = {
  draft: ['confirmed', 'cancelled'],
  confirmed: ['checked_in', 'cancelled', 'preempted'],
  checked_in: ['checked_out'],
  checked_out: [],
  cancelled: [],
  preempted: ['cancelled'],
};

export function assertTransitionAllowed(
  from: ReservationStatus | undefined,
  change: ReservationChange,
): void {
  if (change.kind === 'create') {
    if (from !== undefined) throw new InvalidTransitionError('exists', 'create');
    return;
  }
  if (from === undefined) throw new InvalidTransitionError('missing', change.kind);
  const to = TARGET_STATUS[change.kind];
  if (!ALLOWED[from].includes(to)) throw new InvalidTransitionError(from, to);
}

Make the rule mechanically enforceable

A convention that is only documented will be violated within a quarter. The cheap and durable move is to add a CI check that fails any reservation write that bypasses the verb. A lint rule over the repository is enough:

// eslint-plugin-local/no-direct-reservation-write.ts
const FORBIDDEN_TABLES = new Set(['reservations', 'reservation_keys']);
const ALLOWLIST = [/src\\/domain\\/reservation\\/applyReservationChange\\.ts$/];

export const rule = {
  create(context) {
    const filename = context.getFilename();
    if (ALLOWLIST.some((re) => re.test(filename))) return {};
    return {
      CallExpression(node) {
        if (!isSupabaseTableCall(node)) return;
        const table = literalArg(node, 0);
        if (table && FORBIDDEN_TABLES.has(table) && isMutation(node)) {
          context.report({ node, message: `Write '${table}' through applyReservationChange.` });
        }
      },
    };
  },
};

When we introduced this check, it immediately found several cancellation paths that had been closing reservations without closing their keys. That is the value of mechanized invariants: they surface the cases nobody remembered to grep for.


2. Authorization Belongs in the Database, Not Only in the App

An SDK that talks to a database directly from clients cannot rely on application code for authorization. The client is attacker-controlled. The only trustworthy boundary is the database's own grant and row-level-security model, and the only safe default is deny.

Two classes of mistake come up repeatedly:

Privileged helper functions left executable by clients. A SECURITY DEFINER function runs with the owner's privileges. If PUBLIC or the anonymous/authenticated role can execute it, it becomes a privilege-escalation gadget regardless of what the UI does.

-- Default-deny for anything that runs as the definer.
REVOKE ALL ON FUNCTION public.rollback_initial_setup(uuid) FROM PUBLIC;
REVOKE ALL ON FUNCTION public.rollback_initial_setup(uuid) FROM anon, authenticated;
GRANT EXECUTE ON FUNCTION public.rollback_initial_setup(uuid) TO service_role;
-- Trigger functions should never be callable directly either.
REVOKE ALL ON FUNCTION public.tg_sync_membership() FROM PUBLIC, anon, authenticated;

Membership tables writable by the very clients they authorize. If a client can insert a row into facility_managers, it can forge its own authorization. The membership tables must be read-only (or invisible) to clients and written only by trusted server paths.

REVOKE INSERT, UPDATE, DELETE ON TABLE public.facility_managers FROM anon, authenticated;
ALTER TABLE public.facility_managers ENABLE ROW LEVEL SECURITY;
CREATE POLICY facility_managers_read_own ON public.facility_managers
  FOR SELECT TO authenticated
  USING (user_id = auth.uid());

A useful regression test is to assert the grant surface itself, so a future migration cannot quietly re-open it:

-- Fails CI if any definer function is executable by a client role.
SELECT p.proname
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'
  AND p.prosecdef
  AND (has_function_privilege('anon', p.oid, 'EXECUTE')
    OR has_function_privilege('authenticated', p.oid, 'EXECUTE'))
  AND p.proname <> ALL (ARRAY['intentionally_public_fn']);

If this query returns rows, the build fails. Security posture becomes a test, not a memory.


3. Step-Up Authentication for Privileged Surfaces

Not all authenticated sessions are equal. A session that logged in with a password an hour ago should not be able to reach internal operator tooling that can pause facilities or drive hardware. Two properties matter: the assurance level (was MFA used?) and the freshness of that assurance.

const MAX_AAL2_AGE_MS = 15 * 60 * 1000;

export function requireFreshAal2(session: Session): void {
  if (session.aal !== 'aal2') {
    throw new StepUpRequiredError('mfa_required');
  }
  const verifiedAt = session.amr
    .filter((m) => m.method === 'totp' || m.method === 'webauthn')
    .map((m) => m.timestamp * 1000)
    .sort((a, b) => b - a)[0];
  if (verifiedAt === undefined || Date.now() - verifiedAt > MAX_AAL2_AGE_MS) {
    throw new StepUpRequiredError('reauth_required');
  }
}

The same check must exist on the server for every privileged endpoint; hiding a menu item is presentation, not authorization.

Role predicates deserve the same discipline. An "internal manager" role that is scoped to a single facility must not be mistaken for an unscoped platform-wide role. Keeping all of these predicates in one module makes the distinction auditable:

export const facilityRolePredicates = {
  isFacilityManager: (m: Membership, facilityId: string) =>
    m.role === 'manager' && m.facilityId === facilityId,
  // Internal tooling access requires an *unscoped* membership.
  isInternalManager: (m: Membership) =>
    m.role === 'internal_manager' && m.facilityId === null,
  countInternalManagers: (ms: Membership[]) =>
    ms.filter(facilityRolePredicates.isInternalManager).length,
} as const;

Finally, revocation must be immediate. If role claims are cached in a JWT, removing a membership has no effect until the token expires. Either keep privileged checks on a live database lookup, or force a claims refresh as part of the revocation transaction.


4. Keep the Error Channel Honest

An alerting pipeline that cries wolf is worse than no pipeline. In access control there are three distinct categories, and conflating them destroys the signal:

Category Example Destination
Expected domain refusal "This reservation is not yet checkin-able" User message + audit log
Environmental failure Guest phone lost connectivity mid-request Retry + metric
Genuine fault Lock driver threw on a valid command Error tracker, paged

Modelling refusals as typed results instead of exceptions makes the classification explicit at the call site:

export type CheckinOutcome =
  | { ok: true; key: IssuedKey }
  | { ok: false; code: 'NOT_CHECKINABLE' | 'ALREADY_CLOSED' | 'QR_REQUIRED'; message: string };

export async function checkIn(input: CheckinInput): Promise<CheckinOutcome> {
  const window = await loadCheckinWindow(input.reservationId);
  if (!window.isOpen(now())) {
    return { ok: false, code: 'NOT_CHECKINABLE', message: window.explain() };
  }
  // ... genuine faults below still throw and reach the error tracker.
  const key = await issueKey(input);
  return { ok: true, key };
}

For whatever still reaches the reporter, filter by cause, not by string soup, and make sure each real fault is reported exactly once and under a stable fingerprint:

const EXPECTED_CODES = new Set(['NOT_CHECKINABLE', 'ALREADY_CLOSED', 'QR_REQUIRED']);

Sentry.init({
  beforeSend(event, hint) {
    const err = hint?.originalException;
    if (err instanceof DomainRefusal && EXPECTED_CODES.has(err.code)) return null;
    if (isNetworkFailure(err)) return null; // offline guests are not a server defect
    if (err instanceof DomainFault) {
      event.fingerprint = ['{{ default }}', err.code];
    }
    return event;
  },
});

function isNetworkFailure(err: unknown): boolean {
  return err instanceof TypeError && /fetch|network|load failed/i.test(err.message);
}

On the server side, the mirror of this is: report every 5xx and every uncaught exception from edge functions, with the request id attached. Silence on the server is never a feature.

export function serve(handler: Handler): void {
  Deno.serve(async (req) => {
    const requestId = crypto.randomUUID();
    try {
      const res = await handler(req, { requestId });
      if (res.status >= 500) captureServerError(res, { requestId, url: req.url });
      return res;
    } catch (err) {
      captureServerError(err, { requestId, url: req.url });
      return json({ error: 'internal_error', requestId }, 500);
    }
  });
}

Wrapping every function in a shared serve helper is a small refactor with an outsized payoff: observability stops depending on whether each author remembered to add a try/catch.


5. Credentials Expire: Fail Closed, Pause Explicitly

Integrations hold tokens for upstream lock vendors and PMS systems, and those tokens die. The failure mode to avoid is a background job that retries a dead credential thousands of times, locking the account and burning rate limit.

The pattern is a circuit breaker with a crucial nuance: only trip on a definite signal. A 401 with an explicit invalid-token body is definite. A timeout is not — tripping on it would turn a transient blip into a facility-wide outage.

type TokenVerdict = 'alive' | 'dead' | 'unknown';

async function classifyTokenFailure(res: Response): Promise<TokenVerdict> {
  if (res.status !== 401 && res.status !== 403) return 'alive';
  const body = await res.clone().json().catch(() => null);
  if (body?.error_code === 'TOKEN_EXPIRED' || body?.error_code === 'TOKEN_REVOKED') {
    return 'dead';
  }
  return 'unknown'; // ambiguous: back off, do not pause the facility
}

export async function runTick(facilityId: string): Promise<void> {
  const res = await callVendor(facilityId);
  const verdict = await classifyTokenFailure(res);
  if (verdict === 'dead') {
    await pauseFacility(facilityId, { reason: 'vendor_token_dead', pausedAt: new Date() });
    return;
  }
  if (verdict === 'unknown') {
    await scheduleBackoff(facilityId);
    return;
  }
  await recordSuccess(facilityId);
}

Resuming must be a deliberate, human action against the newest pause record — never an automatic retry, and never a resume of a stale row that a race condition left behind.


6. Blast-Radius Controls for Hardware Automation

We run long-horizon burn-in tests that repeatedly unlock physical locks to measure firmware and network reliability. Automation that commands real hardware needs guardrails that are structural, not procedural:

const MIN_INTERVAL_MINUTES = 3;      // protect battery and vendor rate limits
const MAX_INTERVAL_MINUTES = 1440;
const MAX_LOCKS_PER_TICK = 25;       // bound the work of a single invocation

export async function startBurnIn(req: StartRequest, ctx: RequestContext): Promise<void> {
  requireFreshAal2(ctx.session);
  if (await isKillSwitchOn()) throw new OperationDisabledError('burnin_kill_switch');
  if (req.intervalMinutes < MIN_INTERVAL_MINUTES || req.intervalMinutes > MAX_INTERVAL_MINUTES) {
    throw new ValidationError('intervalMinutes', `must be ${MIN_INTERVAL_MINUTES}-${MAX_INTERVAL_MINUTES}`);
  }
  const locks = await loadLocks(req.lockIds);
  const bound = locks.filter((l) => l.customerFacilityId !== null);
  if (bound.length > 0) {
    throw new ForbiddenError(`refusing customer-bound locks: ${bound.map((l) => l.id).join(', ')}`);
  }
  await enqueue(locks.slice(0, MAX_LOCKS_PER_TICK), req);
}

Four independent safeties, any one of which stops the run: a global kill switch, a validated interval floor, a hard refusal to touch any lock bound to a customer facility, and a per-tick work bound so a runaway queue cannot amplify.

The analysis side has its own correctness requirement. When classifying attempts into buckets ("succeeded immediately", "succeeded after retry", "failed"), the windows must be disjoint and exhaustive, otherwise an attempt is double-counted and the reliability number is a fiction:

export function classify(attempt: Attempt): Bucket {
  const ms = attempt.respondedAt.getTime() - attempt.requestedAt.getTime();
  if (!attempt.succeeded) return 'failed';
  if (ms < 5_000) return 'fast';
  if (ms < 30_000) return 'slow';     // [5s, 30s) — no overlap with 'fast'
  return 'degraded';                   // [30s, ∞)
}

And timestamps must come from the authoritative source. Recording our wall clock as status_checked_at instead of the lock's own report time silently inflates latency and corrupts every downstream conclusion. For hardware telemetry, always store the device's reported time alongside the receipt time.


7. Serializing Bookings Against Configuration Changes

Shared physical resources — lockers, meeting rooms, entrances — create a classic race: a booking is validated against a configuration that changes before the booking commits. Two guests end up holding the same locker, or a booking lands on a resource that just switched from hourly rental to permanent assignment.

The remedy is to serialize the two writers on a common lock and persist the whole configuration through one transactional RPC rather than a sequence of client-issued updates.

CREATE OR REPLACE FUNCTION public.book_locker(
  p_locker_id uuid, p_start timestamptz, p_end timestamptz, p_user uuid
) RETURNS uuid LANGUAGE plpgsql SECURITY DEFINER AS $$
DECLARE v_booking_id uuid; v_use text;
BEGIN
  PERFORM pg_advisory_xact_lock(hashtextextended(p_locker_id::text, 0));
  SELECT use_mode INTO v_use FROM lockers WHERE id = p_locker_id FOR UPDATE;
  IF v_use IS DISTINCT FROM 'hourly_rental' THEN
    RAISE EXCEPTION 'LOCKER_NOT_RENTABLE' USING ERRCODE = 'P0001';
  END IF;
  IF EXISTS (SELECT 1 FROM locker_bookings b WHERE b.locker_id = p_locker_id
             AND b.status = 'active' AND tstzrange(b.start_at, b.end_at) && tstzrange(p_start, p_end)) THEN
    RAISE EXCEPTION 'LOCKER_ALREADY_BOOKED' USING ERRCODE = 'P0001';
  END IF;
  INSERT INTO locker_bookings (locker_id, start_at, end_at, user_id, status)
  VALUES (p_locker_id, p_start, p_end, p_user, 'active') RETURNING id INTO v_booking_id;
  RETURN v_booking_id;
END; $$;

Belt and braces: back the application check with a database constraint, so even a code path that forgets the RPC cannot create an overlap.

ALTER TABLE locker_bookings
  ADD CONSTRAINT locker_bookings_no_overlap
  EXCLUDE USING gist (locker_id WITH =, tstzrange(start_at, end_at) WITH &&)
  WHERE (status = 'active');

8. Credentials Are Time-Bound — Re-Issue, Never Replay

Short-lived QR codes and PINs are a security feature, but they interact badly with naive caching. If a stored credential is replayed after its validity window, the guest sees a code that simply does not work and concludes the lock is broken.

The rule is: on every display, evaluate validity; if expired, re-issue rather than replay.

export async function presentKey(reservationId: string, now: Date): Promise<KeyView> {
  const stored = await loadStoredKey(reservationId);
  if (stored && isValidAt(stored, now) && lockSupports(stored.form)) {
    return { state: 'ready', key: stored };
  }
  const stay = await loadStay(reservationId);
  if (stay.endAt <= now) {
    return { state: 'stay_over', message: 'This stay has ended.' };
  }
  const reissued = await applyReservationChange(ctx, { kind: 'reissue_key', reservationId });
  return reissued.keyEffects.length > 0
    ? { state: 'ready', key: reissued.keyEffects[0].key }
    : { state: 'pending', message: 'Your key is on its way.' };
}

Two details worth stealing:

  • pending is a first-class state. While a key is being provisioned asynchronously, telling the guest "on its way" is both accurate and calming; telling them "failed" generates a support call for a system that is working correctly.
  • Expiry must be rendered in the facility's timezone. A key that expires at 11:00 local time shown as 02:00 UTC is a correctness bug in the human's head. Always format access windows in the clock the operator and guest actually use, and store the facility timezone as data.
export function formatExpiry(expiresAt: Date, facilityTimeZone: string): string {
  return new Intl.DateTimeFormat('en-GB', {
    dateStyle: 'medium', timeStyle: 'short', timeZone: facilityTimeZone,
  }).format(expiresAt);
}

Summary

Trust in a physical access system is not produced by any single feature. It is produced by removing the opportunities for a mistake to exist:

  • Funnel every state transition through one verb, so key reconciliation and audit logging cannot be forgotten — and enforce it with a CI rule, not a convention.
  • Default-deny at the database. Revoke execute on definer functions, revoke client writes on membership tables, and assert the grant surface in tests.
  • Require fresh, high-assurance sessions for privileged tooling, on the server, and make revocation immediate.
  • Separate domain refusals from genuine faults so the error channel stays trustworthy, and wrap every function in a shared handler so 5xx responses are always reported.
  • Trip circuit breakers only on definite signals, and require a deliberate human resume.
  • Bound automation that touches hardware with kill switches, validated intervals, per-tick limits, and hard refusals on production resources.
  • Serialize contended resources with transactional RPCs plus exclusion constraints.
  • Re-issue expired credentials rather than replaying them, and render every expiry in the facility's own clock.

None of these is clever. That is the point: the systems people trust with their front doors are the boring, mechanically-enforced ones.

Key Insights

1
State Management

A single change verb owns every side effect

Routing all reservation writes through one transactional function guarantees that key reconciliation, transition validation, and audit logging happen together — and a CI lint rule makes bypassing it a build failure rather than a code-review gamble.

2
Security

Default-deny grants, verified by tests

SECURITY DEFINER functions and membership tables must be unexecutable and unwritable by client roles; a SQL assertion over pg_proc privileges turns security posture into a regression test that future migrations cannot quietly undo.

3
Authentication

Step-up auth with freshness, enforced server-side

Internal admin surfaces require not just MFA (aal2) but recently verified MFA, checked on the server for every privileged endpoint, with role predicates centralized so scoped and unscoped memberships cannot be confused.

4
Error Handling

Domain refusals are not faults

Modelling expected outcomes as typed results and filtering network failures out of the error tracker keeps alerts meaningful, while a shared serve() wrapper ensures every 5xx and uncaught exception is reported with a request id.

5
Reliability

Trip circuit breakers only on definite signals

Pausing an integration on an explicit TOKEN_EXPIRED response protects against retry storms, while treating ambiguous failures as 'unknown' and backing off prevents a transient blip from causing a facility-wide outage.

6
Concurrency

Serialize contended resources at the database

An advisory lock plus SELECT FOR UPDATE inside one RPC prevents bookings from racing configuration changes, and a GiST exclusion constraint makes overlapping reservations impossible even for code paths that skip the RPC.