---
title: Authorization
description: Policies control who may run a function, and record rules control what they may do.
---

Authorization checks the scope before the handler runs and checks record access inside the handler.

<Diagram caption="To publish a function through oRPC or AI, give it an authorize policy that returns true for allowed calls.">
  <Flow>
    <Node title="Call" subtitle="Supplies the current scope" />
    <Fan>
      <Node slot="from" title="authorize" subtitle="Checks only the scope" tone="accent" />
      <Node title="handler" subtitle="True allows the call" />
      <Node title="forbidden" subtitle="Policy returns another value" tone="muted" />
    </Fan>
  </Flow>
</Diagram>

```ts twoslash
import { init } from "logic-sdk";

type Member = { actor: { id: string } };
type Scope = Member | { actor: null };
const { query } = init<{ scope: Scope }>();
// ---cut---
const member = (scope: Scope): scope is Member => scope.actor !== null;

/** Read the current member's ID. */
export const memberId = query({
  authorize: member,
  async handler(ctx) {
    return ctx.scope.actor.id;
  },
});
```

## Policies

- **Timing.** The policy runs on every call, including nested calls, before input validation or a new transaction.
- **Access (1).** Return exactly `true` to allow the call to proceed. A type guard narrows `ctx.scope` in the handler.
- **Denial (2).** Every other return value gives `forbidden`, including a Promise. Policies are synchronous and read only the scope.

## Publishing

Set `authorize` on every published function, including functions reachable from routes or Server Actions. AI and oRPC check it at build time and runtime. To allow anyone, use a policy that returns `true`:

```ts
export const anyone = () => true;
```

Set an [output schema](/docs/concepts/output).

## Internal functions

Keep [internal functions](/docs/concepts/functions#internal-functions) off the public API. Their policies still apply. For signed-out webhooks and authentication callbacks, see [Callbacks](/docs/guides/callbacks).

## Record rules (`can*`)

Load through a helper that filters by `ctx.scope.accountId`. For a missing or out-of-account record, throw `ctx.error.notFound()`. Apply the same account filter to writes.

```ts
const booking = await findBooking(ctx, input.bookingId);
if (!canCancel(ctx.scope.actor, booking)) throw ctx.error.deny();
```

Make `canCancel` a synchronous predicate. Use it in list queries for UI flags such as `can.cancel`, and check it again in the mutation.

If a rule must hold at commit, put it in the write's `WHERE` clause or re-select the row `FOR UPDATE` and check again.

## See also

[Scope](/docs/concepts/scope), [Functions](/docs/concepts/functions), [Errors](/docs/concepts/errors)
