When your SDK opens physical doors, a bug is not a rendering glitch — it is an unlocked building. This post walks through a batch of changes we shipped in the UnlockOS SDK that all share one theme: the system must deny access when it is uncertain, and it must be able to prove, afterwards, who did what.
The patterns below are generic. You can apply them to any multi-tenant platform that mixes an edge/serverless API, a Postgres database with Row Level Security, and third-party payment or messaging providers.
1. Step-up authentication enforced twice: API and database
Platform-admin capabilities (granting paid options, writing feature-flag overrides, impersonating tenants) are the keys to the kingdom. A single password is not enough; we require AAL2 — an authenticated session that has completed a second factor.
The critical design decision is that the check is not implemented once in a middleware. It is implemented in the edge function and in RLS policies, so a forgotten route or a direct PostgREST call cannot bypass it.
export class ForbiddenError extends Error {
constructor(public readonly code: 'PLATFORM_ADMIN_REQUIRED' | 'AAL2_REQUIRED') {
super(code);
}
}
export interface SessionClaims {
sub: string;
app_role?: string;
aal?: 'aal1' | 'aal2';
}
export function assertPlatformAdmin(
claims: SessionClaims,
): asserts claims is SessionClaims & { app_role: 'platform_admin'; aal: 'aal2' } {
if (claims.app_role !== 'platform_admin') throw new ForbiddenError('PLATFORM_ADMIN_REQUIRED');
if (claims.aal !== 'aal2') throw new ForbiddenError('AAL2_REQUIRED');
}The same predicate lives in SQL and is reused by every policy that guards privileged tables:
create or replace function app.is_platform_admin()
returns boolean
language sql
stable
as $$
select coalesce(auth.jwt() ->> 'app_role', '') = 'platform_admin'
and coalesce(auth.jwt() ->> 'aal', 'aal1') = 'aal2';
$$;
create policy platform_admin_writes_overrides
on public.feature_flag_overrides
for all
to authenticated
using (app.is_platform_admin())
with check (app.is_platform_admin());Note the asserts signature in TypeScript: after calling assertPlatformAdmin, the compiler knows the claims are privileged. Authorization becomes part of the type flow instead of a comment.
Test the policy, not just the handler. We added an integration job that runs the RLS assertions against a real Postgres instance, because a unit test with a mocked client proves nothing about what the database will accept.
2. Authorize on stable keys, never on display names
A recurring class of privilege bug: code that resolves a role by its human-readable name.
// ❌ names are editable, localized, duplicated per tenant, and sometimes typo'd
const role = await db.roles.findFirst({ where: { name: 'Owner' } });
// ✅ role_key is immutable, unique and part of the schema contract
const OWNER_ROLE_KEY = 'facility_owner' as const;
const role = await db.roles.findFirstOrThrow({ where: { roleKey: OWNER_ROLE_KEY } });If an administrator renames "Owner" to "オーナー", name-based lookups either throw or — worse — match a different tenant's row. We removed every name-based branch from permission level resolution and menu gating, and backed it with a migration that enforces unique (organization_id, role_key).
The generalizable rule: identifiers used in authorization decisions must be opaque, immutable and enumerable as a union type.
export const ROLE_KEYS = ['platform_admin', 'org_owner', 'facility_owner', 'staff', 'guest'] as const;
export type RoleKey = (typeof ROLE_KEYS)[number];
export const ROLE_LEVEL: Record<RoleKey, number> = {
platform_admin: 100,
org_owner: 80,
facility_owner: 60,
staff: 40,
guest: 10,
};An exhaustive Record<RoleKey, number> means adding a role to the union breaks the build until its level is defined — the compiler becomes the reviewer.
3. Feature flags must fail closed
Feature flags control real behaviour, including whether a door may be opened outside configured access hours. The dangerous default is "if the flag service errors, treat the gate as open".
export async function canBypassAccessHours(ctx: EvaluationContext): Promise<boolean> {
try {
return await flags.isEnabled('access_hours_bypass', ctx);
} catch (error) {
logger.error('flag_read_failed', { flag: 'access_hours_bypass', error });
return false; // closed is the only safe answer for a physical lock
}
}Two more rules we applied to the override system:
- Overrides resolve in a fixed, documented precedence:
facility → organization → global default. The same resolver runs in edge functions and in the admin UI, so operators see exactly what the runtime sees. - Unknown write policies are rejected. If an override row carries a policy string the current code does not recognise, the write is refused rather than silently coerced to a permissive default.
const WRITE_POLICIES = ['platform_admin_only'] as const;
type WritePolicy = (typeof WRITE_POLICIES)[number];
function parseWritePolicy(value: string): WritePolicy {
if (!(WRITE_POLICIES as readonly string[]).includes(value)) {
throw new ForbiddenError('PLATFORM_ADMIN_REQUIRED');
}
return value as WritePolicy;
}4. Least privilege at the table level
RLS policies are powerful, but the first question should be: does this client role need write access at all? Configuration tables such as form field definitions are written by operators through the admin API and only ever read by guest clients.
revoke insert, update, delete on public.form_fields from authenticated, anon;
create policy form_fields_read_published
on public.form_fields
for select
to authenticated, anon
using (exists (
select 1 from public.forms f
where f.id = form_fields.form_id
and f.status = 'published'
));Grant revocation is coarser and harder to get wrong than a policy expression. Use it as the outer layer; use policies for the row-level nuance that remains.
5. Clickjacking: an allowlist, not a blanket
Guest-facing check-in apps handle identity documents and unlock actions, so an attacker embedding them in a hostile iframe is a real threat. We refuse cross-origin framing except for our own marketing surfaces.
const FRAME_ANCESTORS = ['https://unlockos.io', 'https://st.unlockos.io'];
export function securityHeaders(): Headers {
const headers = new Headers();
headers.set('Content-Security-Policy', [
`frame-ancestors 'self' ${FRAME_ANCESTORS.join(' ')}`,
"base-uri 'self'",
"form-action 'self'",
].join('; '));
headers.set('X-Content-Type-Options', 'nosniff');
headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
return headers;
}We also added a CI guard that verifies the header middleware is still the real entry point of the deployed bundle — comparing resolved paths rather than string suffixes, because a refactor that moves a file should fail the build, not silently drop headers.
6. Payment state: converge on the provider, never on the redirect
Webhooks are not guaranteed to arrive, and browser redirects are attacker-controllable. A payment state machine must therefore satisfy three properties: a single source of truth (the PSP), idempotent transitions, and an explicit incomplete state when the infrastructure itself is misconfigured.
export type PaymentState = 'pending' | 'authorized' | 'captured' | 'failed' | 'incomplete';
const ALLOWED: Record<PaymentState, readonly PaymentState[]> = {
pending: ['authorized', 'captured', 'failed', 'incomplete'],
authorized: ['captured', 'failed'],
captured: [],
failed: [],
incomplete: ['captured', 'failed'],
};
export function canTransition(from: PaymentState, to: PaymentState): boolean {
return ALLOWED[from].includes(to);
}
export async function reconcile(intentId: string, trigger: 'webhook' | 'return'): Promise<PaymentRow> {
const remote = await psp.retrieveIntent(intentId);
return db.transaction(async (tx) => {
const row = await tx.payments.selectForUpdate(intentId);
const next = mapProviderStatus(remote.status);
if (row.state === next) return row;
if (!canTransition(row.state, next)) {
logger.warn('illegal_payment_transition', { intentId, from: row.state, to: next, trigger });
return row;
}
const updated = await tx.payments.update(intentId, { state: next, settledBy: trigger });
await tx.auditLogs.insert({ type: 'payment.state_changed', subjectId: intentId, from: row.state, to: next });
return updated;
});
}selectForUpdate plus a no-op on identical state makes webhook and return-URL paths safe to race: whichever arrives first wins, and the loser becomes a cheap read. The same reconciliation function serves both triggers, so there is one code path to audit.
Separately, an organization configured for live payments without a registered webhook endpoint is now surfaced as incomplete in the admin and reported to the platform team. Silent degradation is the enemy; a visible broken state is a feature.
7. Lifecycle guards belong in the domain, not the UI
Facilities move through pre_opening → open → closed. Several independent entry points — reservations, walk-in check-in, lesson applications, locker buyback — all need the same answer to "may this facility accept new commitments?". Duplicating the condition in each screen guarantees divergence.
export type FacilityStatus = 'pre_opening' | 'open' | 'closed';
export class DomainError extends Error {
constructor(public readonly code: 'FACILITY_PREOPENING' | 'FACILITY_CLOSED' | 'CONFIG_DEACTIVATED') {
super(code);
}
}
export function assertAcceptsNewCommitments(facility: { status: FacilityStatus }): void {
switch (facility.status) {
case 'open':
return;
case 'pre_opening':
throw new DomainError('FACILITY_PREOPENING');
case 'closed':
throw new DomainError('FACILITY_CLOSED');
}
}The switch over a union with no default is deliberate: adding a status makes the function fail type-checking until the new case is handled. Every guard then returns a stable machine code, which the SDK maps to a localized message:
const MESSAGES: Record<DomainError['code'], { ja: string; en: string }> = {
FACILITY_PREOPENING: { ja: 'この施設は準備中です。', en: 'This facility is not open yet.' },
FACILITY_CLOSED: { ja: 'この施設は閉鎖されています。', en: 'This facility is closed.' },
CONFIG_DEACTIVATED: { ja: 'この設定は無効化されています。', en: 'This configuration is deactivated.' },
};Clients match on codes, humans read messages. Never ask a client to string-match an error sentence.
The same rule caught two downstream bugs: a recurring charge must not be taken for a facility that closed after approval, and a locker must not open — nor accept a buyback — for a reservation configuration that has been deactivated but is still referenced by id. A soft-deleted or deactivated record is still reachable by id; your read path must check status, not merely existence.
8. Audit logs that are both complete and least-privileged
An audit trail only earns trust if three things are true: privileged actions are recorded, readers see only what they are entitled to, and the output is comprehensible.
We extended the catalog to cover role grants and revocations and API key issue / revoke / reactivate — exactly the operations an attacker would use to establish persistence.
export const AUDIT_EVENTS = {
'role.granted': { group: 'access_control', severity: 'high' },
'role.revoked': { group: 'access_control', severity: 'high' },
'api_key.issued': { group: 'credentials', severity: 'high' },
'api_key.revoked': { group: 'credentials', severity: 'high' },
'api_key.reactivated': { group: 'credentials', severity: 'high' },
'payment.state_changed': { group: 'billing', severity: 'info' },
} as const;
export type AuditEventType = keyof typeof AUDIT_EVENTS;
export type AuditEventGroup = (typeof AUDIT_EVENTS)[AuditEventType]['group'];Filtering was moved to the server. A client-side filter over a full result set leaks the existence and shape of events the viewer may not see, and it breaks pagination:
select id, occurred_at, event_type, actor_id, subject_id, metadata
from public.audit_logs
where organization_id = $1
and event_type = any($2::text[])
and occurred_at >= $3
order by occurred_at desc
limit $4 offset $5;The permitted event_type array is derived from the caller's role on the server; it is never accepted verbatim from the request. Finally, the UI renders a catalog label rather than the internal event key — an audit log nobody can read is not evidence.
9. Tests that do not rot
Two failures we fixed were not product bugs but time-dependent fixtures: a membership booking dated with an absolute future date eventually became the past, and a cancellation path re-validated against the real clock at write time, so a fixed seed date silently changed the branch under test.
// ❌ passes today, fails next quarter
const checkIn = new Date('2026-01-10T15:00:00+09:00');
// ✅ expresses the intent: a booking that is still in the future
const checkIn = addDays(startOfToday(), 30);
// ✅ or freeze the clock when the assertion is about the clock itself
vi.useFakeTimers().setSystemTime(new Date('2026-01-10T15:00:00+09:00'));Rule of thumb: if a test asserts on a transition that reads now(), either express dates relative to now() or control now(). Never both half-way. A flaky security test gets muted, and a muted test protects nothing.
We also moved the heavier authorization scenarios into a dedicated Postgres integration job in CI. Policies, triggers and constraints are code; they deserve the same coverage as handlers.
Summary
| Pattern | Why it earns trust |
|---|---|
| AAL2 checked in API and RLS | A missed route cannot bypass step-up auth |
Authorize on role_key, not names |
Renaming or localizing a role cannot escalate privilege |
| Flags fail closed on error | Infrastructure failure never opens a door |
| Revoke grants, then write policies | Coarse least-privilege outside, fine-grained inside |
frame-ancestors allowlist |
Guest unlock flows cannot be clickjacked |
| Reconcile payments from the provider | Redirects and missing webhooks cannot forge state |
| Guard lifecycle in the domain layer | One answer to "is this facility usable?" for all entry points |
| Typed audit catalog + server-side filter | Complete evidence, least-privileged reads |
| Relative or frozen clocks in tests | Security tests stay green for the right reason |
None of these is clever. That is the point: in a system that controls physical access, the right defaults are boring, duplicated at two layers, and enforced by the type checker and the database rather than by discipline.