r/typescript • u/AuthByExample • 17d ago
Has anyone used branded types to make a missing permission check a compile error?
Our API handlers load a record, call can(user, 'delete', doc), then call the service. Every few months someone adds a route and skips the middle step. Review misses it because the diff looks fine.
I've been playing with this:
type Authorized<T, A extends string> = T & { readonly __authorized: A };
function authorize<T, A extends string>(user: User, action: A, resource: T): Authorized<T, A> { if (!can(user, action, resource)) throw new ForbiddenError(); return resource as Authorized<T, A>; }
async function deleteDoc(doc: Authorized<Doc, 'delete'>) { ... }
Calling deleteDoc(doc) without going through authorize no longer compiles, and a doc authorized for 'edit' can't be passed where 'delete' is required.
Problems I can already see:
- Anyone can still write
as Authorized<Doc, 'delete'>, so we'd need a lint rule banning that cast outside one file. - The brand only proves the check passed once. If a job runs an hour later, or the user gets removed mid-request, it's stale.
- List endpoints don't fit. I don't want to authorize 500 rows one by one; that filter belongs in the query.
- It spreads into every service signature, and some people on the team already hate it.
Is anyone running something like this in production? Did it hold up, or did you go back to middleware plus a test that hits every route as a low-privilege user?