Introduction
A smart lock platform is judged by what it does when things go wrong. A guest's phone loses its session mid check-in, a payment provider returns 503, a card is declined, a facility has not opened yet, a browser tab is resumed after two days of sleep. None of these are bugs — they are the normal weather of a distributed physical-access system. Yet if the system treats them like bugs, two bad things happen at once: the on-call signal drowns in noise, and the guest sees a blank screen instead of a reason.
This article walks through a set of patterns we have converged on while hardening an access-control SDK: a typed failure taxonomy, fail-closed defaults, authorization enforced below the application layer, secret handling that assumes the repository will leak, and a presence gate modelled as an explicit state machine. The code is illustrative, not internal — the goal is that you can apply the same shapes in your own system.
1. A failure taxonomy, not a try/catch
The single highest-leverage change is to stop treating Error as one thing. Split failures into domain refusals (the system worked correctly and said no) and faults (the system failed to do its job). Only faults belong in your error tracker.
export type RefusalCode =
| 'CHECKIN_NOT_RESERVED'
| 'PLAN_NOT_AVAILABLE'
| 'FACILITY_PRE_OPENING'
| 'PRESENCE_REQUIRED'
| 'CHECKIN_WINDOW_CLOSED'
| 'CARD_DECLINED'
| 'OTP_RATE_LIMITED';
export class DomainRefusal extends Error {
readonly kind = 'refusal' as const;
constructor(
readonly code: RefusalCode,
readonly guestMessageKey: string,
readonly context: Record<string, string | number> = {},
) {
super(code);
}
}
export class SystemFault extends Error {
readonly kind = 'fault' as const;
constructor(message: string, readonly cause?: unknown) {
super(message);
}
}The reporting boundary then becomes a single, auditable decision instead of scattered captureException calls:
export function reportIfFault(error: unknown, scope: Record<string, unknown>): void {
if (error instanceof DomainRefusal) {
logger.info('refusal', { code: error.code, ...scope, ...error.context });
return;
}
const fault = error instanceof SystemFault ? error : new SystemFault('unhandled', error);
logger.error('fault', { ...scope, message: fault.message });
errorTracker.captureException(fault, { extra: scope });
}Two rules keep this honest:
- A refusal must carry a stable code and a translatable message key. If the guest cannot be told why, it is not a refusal — it is a fault wearing a disguise. A pre-opening facility rejecting a check-in should surface "this facility has not opened yet", not a generic failure.
- Never silence a code unconditionally. The temptation after a noisy week is to add
CHECKIN_NOT_RESERVEDto a mute list. But that code is only expected in one specific race — a webhook arriving after the guest. Encode the condition, not the code:
function isExpectedNotReserved(stay: StaySnapshot | null): boolean {
// Only expected when we positively know the stay already advanced past arrival.
return stay?.status === 'checked_in' || stay?.status === 'completed';
}
if (!reservation) {
const refusal = new DomainRefusal('CHECKIN_NOT_RESERVED', 'checkin.not_reserved');
if (isExpectedNotReserved(stay)) return refuse(refusal);
throw new SystemFault('reservation missing for an active stay', refusal);
}The mute is scoped by evidence. The moment the invariant breaks in a way you did not predict, the alert fires again.
2. Fail closed when you cannot compute an answer
A pricing call that cannot read the plan must not return 0. A lock that cannot verify presence must not open. The anti-pattern is a nullable return value that silently collapses into a permissive default.
export type Outcome<T> =
| { ok: true; value: T }
| { ok: false; reason: 'unavailable'; code: RefusalCode };
export async function computeFee(stayId: string): Promise<Outcome<Money>> {
const plan = await readPlan(stayId);
if (!plan.ok) return { ok: false, reason: 'unavailable', code: 'PLAN_NOT_AVAILABLE' };
const stay = await readStay(stayId);
if (!stay.ok) return { ok: false, reason: 'unavailable', code: 'PLAN_NOT_AVAILABLE' };
return { ok: true, value: price(plan.value, stay.value) };
}The UI then renders an explicit "fee unavailable" state rather than an attractive, wrong ¥0. Making unavailability a first-class value — instead of null or a thrown exception — forces every call site to decide what to do, and the type checker enforces that decision.
3. Bound every input you did not author
Upstream responses, uploaded files, and clipboard payloads are all adversarial until proven otherwise. Two cheap guards pay for themselves:
const MAX_ERROR_BODY_BYTES = 8 * 1024;
const MAX_IMAGE_BYTES = 1024 * 1024;
async function readBoundedText(response: Response): Promise<string> {
const reader = response.body?.getReader();
if (!reader) return '';
const chunks: Uint8Array[] = [];
let total = 0;
while (total < MAX_ERROR_BODY_BYTES) {
const { done, value } = await reader.read();
if (done || !value) break;
chunks.push(value);
total += value.byteLength;
}
await reader.cancel().catch(() => undefined);
return new TextDecoder().decode(concat(chunks)).slice(0, MAX_ERROR_BODY_BYTES);
}
export function assertUploadable(file: File): void {
if (file.size > MAX_IMAGE_BYTES) {
throw new DomainRefusal('PLAN_NOT_AVAILABLE', 'upload.too_large', { max: MAX_IMAGE_BYTES });
}
}Rejecting an oversized logo at pick time is a usability feature. Bounding an error body you are about to log is a memory-safety and log-injection feature. Both are the same instinct.
4. Authorization the client cannot talk its way out of
If a column decides whether a facility is billed, a demo, or exempt from a control, then that column must not be writable by the tenant whose bill depends on it. Application-layer checks are necessary but not sufficient; put the final word in the database.
-- Only the service role may flip the billing-exempt flag.
create or replace function guard_system_only_columns()
returns trigger language plpgsql security definer as $$
begin
if new.is_demo is distinct from old.is_demo
and current_setting('request.jwt.claim.role', true) is distinct from 'service_role' then
raise exception 'facilities.is_demo is system-managed'
using errcode = '42501';
end if;
return new;
end;
$$;
create trigger facilities_guard_system_columns
before update on public.facilities
for each row execute function guard_system_only_columns();Pair it with row-level security so that reads and writes are tenant-scoped by default:
alter table public.facilities enable row level security;
create policy facilities_member_read on public.facilities
for select using (
exists (
select 1 from public.facility_members m
where m.facility_id = facilities.id and m.user_id = auth.uid()
)
);The property to aim for: an attacker holding a valid tenant token still cannot change the field that controls their own enforcement.
5. Treat the repository as a public surface
Assume every file you commit will eventually be read by someone you did not invite. That means no real keys in source, ever — but it also means being precise about which keys are intentionally public, because a blanket secret scanner that cries wolf gets disabled within a month.
#!/usr/bin/env bash
set -euo pipefail
# Allowlist: keys that are public by design (e.g. anon keys bound by RLS).
ALLOWLIST_FILE=".secrets-allowlist"
PATTERNS='(sk_live_|sk_test_|-----BEGIN [A-Z ]*PRIVATE KEY-----|service_role)'
matches=$(git diff --cached -U0 | grep -nE "^\+.*${PATTERNS}" || true)
if [ -n "$matches" ]; then
filtered=$(echo "$matches" | grep -vFf "$ALLOWLIST_FILE" || true)
if [ -n "$filtered" ]; then
echo "Blocked: possible secret in staged changes" >&2
echo "$filtered" >&2
exit 1
fi
fiThree practices go with it: ship an .env.local.example containing obviously-fake demo values so nobody is tempted to paste a real one; delete bridge/debug pages that exist only to shortcut auth during development; and document which public keys are safe and why ("anon key, all access mediated by RLS").
6. Detect code that is deployed but no longer exists
A subtle supply-chain risk in serverless platforms: an edge function deployed six months ago still answers requests even after its source was deleted from the repository. It is unreviewed, unpatched, and invisible in code search. Make the drift a CI failure.
export async function assertNoOrphanFunctions(): Promise<void> {
const deployed = await platform.listDeployedFunctions();
const inSource = new Set(await listFunctionDirs('supabase/functions'));
const orphans = deployed.filter((fn) => !inSource.has(fn.slug) && fn.status === 'ACTIVE');
if (orphans.length > 0) {
throw new Error(`Deployed functions with no source: ${orphans.map((f) => f.slug).join(', ')}`);
}
}The same check should flag calls to decommissioned APIs still lingering in code paths.
7. Presence as an explicit state machine
Physical access deserves more than a boolean. "The guest is really inside the building" is a claim with a provenance and an expiry, and it is reached through several mutually exclusive routes: a kiosk tablet in the lobby, a printed in-building QR, a lock-housing QR that forwards to a presence endpoint. Modelling it as a discriminated union makes the illegal states unrepresentable.
export type PresenceProof =
| { source: 'kiosk'; kioskId: string; observedAt: string }
| { source: 'in_building_qr'; qrId: string; observedAt: string }
| { source: 'host_review'; reviewerId: string; observedAt: string };
export type CheckinState =
| { status: 'awaiting_identity' }
| { status: 'awaiting_presence'; identityId: string }
| { status: 'presence_verified'; identityId: string; proof: PresenceProof }
| { status: 'completed'; identityId: string; keyId: string }
| { status: 'refused'; code: RefusalCode };
const PRESENCE_TTL_MS = 10 * 60 * 1000;
export function completeCheckin(state: CheckinState, now: number): CheckinState {
if (state.status !== 'presence_verified') {
return { status: 'refused', code: 'PRESENCE_REQUIRED' };
}
if (now - Date.parse(state.proof.observedAt) > PRESENCE_TTL_MS) {
return { status: 'awaiting_presence', identityId: state.identityId };
}
return { status: 'completed', identityId: state.identityId, keyId: issueKey(state.identityId) };
}Three properties fall out for free. The transition function is pure and exhaustively testable. A stale proof degrades to "ask again" rather than to "allow". And because the proof carries its source, the audit log can record how access was granted, not merely that it was.
Roll such a gate out behind a per-facility flag, not globally — one production site first, then widen.
8. Retry only what is safe to retry
A 503 from a payment platform during setup is transient; a card decline is not. Retrying the second is at best useless and at worst a duplicate charge.
const RETRYABLE_STATUS = new Set([502, 503, 504]);
export async function setupPaymentWithRetry(req: SetupRequest, attempts = 3): Promise<Outcome<Setup>> {
for (let attempt = 1; attempt <= attempts; attempt++) {
const res = await platform.createSetupIntent(req, { idempotencyKey: req.idempotencyKey });
if (res.ok) return { ok: true, value: res.value };
if (!RETRYABLE_STATUS.has(res.status) || attempt === attempts) {
return { ok: false, reason: 'unavailable', code: 'CARD_DECLINED' };
}
await sleep(Math.min(2 ** attempt * 250, 2000) + Math.random() * 100);
}
return { ok: false, reason: 'unavailable', code: 'CARD_DECLINED' };
}The idempotency key is non-negotiable: it is what makes the retry a retry rather than a second request. And after the final attempt, hand the guest a retry button — automated backoff should complement, not replace, user agency.
9. Minimise, encrypt, and let people leave
Identity documents and face photos are the most sensitive payload an access system touches. The defensible posture is a narrow one:
- Capture live, never from a file. A face photo taken on the spot cannot be a reused image from the camera roll.
- Store encrypted, with consent recorded as data. The consent row should name the purpose and the version of the terms, not just a boolean.
- Expire by policy, not by cleanup script. Derived artefacts such as issued PIN labels should be rewritten or anonymised on a fixed retention clock.
- Provide export and withdrawal. A self-service path to download your own records and delete your account is both a compliance requirement and the strongest signal that retention limits are real.
create table identity_documents (
id uuid primary key default gen_random_uuid(),
subject_id uuid not null references identities(id) on delete cascade,
ciphertext bytea not null,
key_version int not null,
consent_id uuid not null references consents(id),
retain_until timestamptz not null,
created_at timestamptz not null default now()
);
create index identity_documents_retention_idx on identity_documents (retain_until);10. Tests that encode the invariant, not the implementation
The most valuable tests in a security-critical codebase are the ones that assert a structural property of the source itself. For example: no caller-scoped code path may write audit events with service-role privileges. That is checkable statically.
it('no caller-scoped module writes checkin_events with the service role', async () => {
const files = await glob('src/checkin/**/*.ts');
const violations: string[] = [];
for (const file of files) {
const source = await readFile(file, 'utf8');
const usesServiceRole = /createServiceRoleClient\(/.test(source);
const writesEvents = /from\('checkin_events'\)[\s\S]{0,200}\.insert\(/.test(source);
if (usesServiceRole && writesEvents) violations.push(file);
}
expect(violations).toEqual([]);
});Such a test survives refactors that a behavioural test would not, and it fails loudly the day someone takes a shortcut. Complement it with pure unit tests over the state machine transitions (every status × every event), and integration tests that assert the refusal code returned — not the HTTP status alone — so that guest-facing messaging cannot silently regress.
Summary
Trust in an access-control system is produced by a handful of disciplines, repeated everywhere:
| Discipline | Concrete rule |
|---|---|
| Failure taxonomy | Refusals carry a stable code and a message key; only faults page a human |
| Conditional muting | Suppress by evidence, never by error code alone |
| Fail closed | Unavailable is a value, not a null that defaults to permissive |
| Bounded inputs | Cap every body, file, and field you did not author |
| Layered authz | RLS plus system-only columns, so a tenant token cannot change its own enforcement |
| Secret hygiene | Scanner with an explicit, justified allowlist; fake values in examples |
| Deploy integrity | Fail CI on deployed code with no source |
| Explicit states | Discriminated unions with expiring proofs and recorded provenance |
| Safe retries | Idempotency keys, retryable-status allowlist, user-visible retry |
| Data minimisation | Live capture, encryption, retention clocks, self-service export and withdrawal |
None of these are exotic. What makes them work is applying them uniformly, so that the answer to "what happens when this fails?" is always the same shape: a typed refusal the guest can read, a log line an operator can trace, and a door that stays shut unless the proof is fresh.