> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Roles and grants

> One kind of authority: declare roles as bundles of scoped rights, expose functions with allow, and issue and revoke grants as grave acts.

Bijection has one kind of authority: the **grant**. A grant is the fact that a
principal holds a set of rights under a label until an instant. Every positive
authority is a grant: a person's role, a sign-in session, a trusted identity
provider, an agent's delegation, an invitation, the rights of your own code,
and the open entries that `anyone` and `signedIn` reach. Nothing is admitted
without one.

A **right** is one verb over one object at one scope: `enter(f)` enters a
function, `clear(l)` reads and commits under a label, `issue` issues grants,
and `read`, `write`, `release`, `revoke`, `erase` and `hold` work the same
way. The scope is the member the grant holds under, so a grant under
`tenant.of("acme")` enters, clears and issues only in `acme`.

A **role** is a named bundle of rights. A grant carries its role's name, so a
[guard](https://docs.bijection.com/access/guards.md) can ask which role an act came through
(`a.offer.role`).

## Exposure: `allow`

```ts bijection/orders.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, query, role, t } from "@bijectionhq/bijection";
import { clerk, tenant } from "./access";

/** Exposed to holders of clerk, in the caller's tenant. */
export const place = mutation({ under: tenant, allow: [clerk], args: { number: t.string } }, async (ctx, { number }) => {
  /* … */
});

/** Exposed to every caller, signed in or not. */
export const status = query({ allow: [role.anyone] }, () => "open");

/** Internal: no allow. Only this app's own code, its tasks and its reactions reach it. */
export const reprice = mutation({ args: { number: t.string } }, async (ctx, { number }) => {
  /* … */
});
```

* `allow: [roles]` declares the entry right: each listed role carries
  `enter` of the function. A function with `allow` is **exposed** at its
  tree path. Without `allow` it is **internal**. `allow: []` is refused:
  leave `allow` out instead.
* `role.anyone` names every principal, and `role.signedIn` every
  authenticated person. `allow: [role.anyone]` declares a **class grant**
  that the program issues at install and the lock prints; it clears no
  label above public, so an entry it opens runs at the public label.
  Nothing is ambient. See [Open entries](https://docs.bijection.com/access/decisions.md#open-entries).
* `bijection check --write-lock` writes every role, with the functions it
  enters and the labels it clears, and every class grant to
  `bijection.lock`. Review that diff whenever exposure changes.

## Declare roles

```ts bijection/access.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, role, t } from "@bijectionhq/bijection";

export const tenant = label.family(t.string);
export const clerk = role({ clear: [tenant.all] });
export const manager = role({ include: [clerk], issue: true });
```

| Option | Meaning |
| - | - |
| `enter` | Exposed functions a holder may call besides those whose `allow` names the role, such as a mounted library's functions. It never exposes a function: only `allow` does. |
| `clear` | The labels a holder may read and run under. Use `family.all` to clear the family's members. |
| `include` | Roles whose rights a holder holds too. |
| `issue` | `true`: a holder may issue and revoke this role and every role it includes. Nobody issues what they do not hold. |
| `erase` | The units a holder may erase. Use an erasable table declaration to grant erasure of its facts, or `"facts"` for all erasable tables in the role's app. |
| `hold` | The units a holder may place under a legal hold and lift. |
| `register` | The families whose members a holder may found (`register(family)`). |
| `attest` | The tenant issuer shapes a holder may trust. |

A role takes no name: its name is its path (`access.clerk`). `check` reports
`AllowBelowLabel` when a role in `allow` does not clear the function's
`under`.

## Two grants cover together

An act is covered when the caller's surviving grants, together, hold every
right it needs. A person who holds `clerk` and `financeView` as two grants can
call a function that needs both, exactly as if one grant held both:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const clerk = role({ clear: [tenant] });
export const financeView = role({ clear: [finance] });

export const margin = query({ under: tenant.and(finance), allow: [clerk], args: { number: t.string } }, async (ctx, { number }) => {
  /* … */
});
```

To require that one grant alone covers an entry, add the `coverAlone` rule
from the [guard library](https://docs.bijection.com/access/guards.md#library-rules) to it.

Your code is covered the same way: the function needs its entry, the
clearances of its label, and the reads, writes and releases it performs. The
frame's clearance is the set of labels that both the caller's grants and the
code's grants clear.

## Grant and revoke

`ctx.grant` and `ctx.revoke` are grave acts: each is named in the code,
listed by `bijection check` for the function that does it, and the only way
`sys.grants` changes.

```ts bijection/team.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, t } from "@bijectionhq/bijection";
import { revokeRole } from "@bijectionhq/library-members";
import { clerk, manager, tenant } from "./access";

export const hire = mutation(
  { under: tenant, allow: [manager], args: { to: t.principal, until: t.maybe(t.instant) } },
  async (ctx, { to, until }) =>
    await ctx.grant(clerk, { to, under: ctx.frame.under, until }),
);

/** Ends the person's clerk grants in this tenant; their other roles stay. */
export const fire = mutation({ under: tenant, allow: [manager], args: { from: t.principal } }, async (ctx, { from }) => {
  await revokeRole(ctx, { holder: from, role: clerk, label: ctx.frame.under });
});
```

* `ctx.grant(role, { to, under, until?, from?, only? })`
  issues a new grant of the role to `to` at the mutation's exact commit label.
  It returns the grant's point, `sys.grants(id)`. Delegations and invitations
  use the same issue rule. Founding issues the declared founder grant at the
  fresh member during registration.
  * `to` is a principal, an agent (`agent:…`), an invitation bearer
    (`sys.grants.invitation({ token })`).
  * `from` names the parent: a grant the frame holds. Without it the host
    picks one of the issuer's surviving grants.
  * `only` is the new grant's entire right set, keyed by verb. For example,
    `only: { enter: [move] }` grants entry to `move` alone. List clearance
    in `clear` when the child needs it. Each listed right must be covered by
    the role, the parent and the code.
* A grant is issued from one **parent**: a live grant of the issuer that
  survived the act's guards. The parent must carry `issue` for the role at
  every scope the new grant holds under, and must already hold every right
  the new grant carries. Nobody issues what they do not hold.
* The new grant never goes to the issuer, to the person the issuer acts for,
  or to anyone on the call chain.
* `ctx.revoke(grant)` ends that grant. Its holder may revoke it, and so may
  the holder of any grant up its chain. A selection,
  `sys.grants.where({ label, role, holder })` or `sys.grants.where({ label, role, parent })`,
  ends every live grant it names and refuses `Absent` if none match. Use
  `issuer` in place of `role` to select an issuer's trust grants.
* A grant lives only while its parent lives. Revoking or expiring a grant
  ends every grant issued under it.
* When the observer label of the grant is below the frame, pass
  `{ release }` as the last argument to issue or revoke it. The release
  belongs in the function's `releases:` declaration.
* A principal is named by its `PrincipalId`, the kind-qualified id
  `ctx.frame.as.id` answers: `person:` and a random ID the host keeps for
  each sign-in identity (never the provider's subject).

Read grants at an exact label for one declared role or issuer. The frame
must clear the label and the performing site must have read reach to the
declaration.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const held = await ctx.page(sys.grants.where({ label: ctx.frame.under, role: clerk, holder: sys.grants.holder(principal) }), { size: 50 });
```

Each fact is `{ id, holder, rights, parent, roleChain, label, expiresAtMs }`:

* `id` and `parent` are `{ label, key }`. The opaque `key` names the original issuance.
* `holder` is `{ kind, id }`, a `principal`, a `class` (`anyone` or
  `signedIn`) or an invitation `bearer`;
* `rights` lists `{ verb, object, scope }`;
* `roleChain` is the grant's role path, then the roles of the grants it was
  issued from. A grant binds its role by name, so a release that replaces the
  role keeps the grant;
* `label` is where the grant is observed, and `expiresAtMs` its end (null
  until revoked).

A grant carries nothing else: the details of a session or an installation
key live in the platform's sessions and keys records, keyed by the grant's
id. `sys.grants.mine()` reads the caller's own live grants from a function
under `label.principals`.

The six data writes refuse `sys` tables; only the grave acts change them.
Every issue and revocation is recorded in `sys.grantTransitions` with who did
it, whom they acted for, the call chain and the grants that admitted it. From
the terminal, call the mutation that performs the act:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection mutate team.hire to=person:alice until:=null --under access.tenant/acme
bijection mutate team.fire from=person:alice --under access.tenant/acme
```

[Guards](https://docs.bijection.com/access/guards.md) on `act.grant(role)` and `act.revoke(role)` can
refuse an issue or a revocation.

## Revocation and expiry

A grant past its `until`, revoked, or under a parent that is no longer live
admits nothing from then on. A revocation is an assertion, not a retraction:
it asserts the grant again with its `until` at the revoking instant, so the
grant's history stays readable. Every decision reads the grants it used, so
revoking a grant conflicts with any transaction still deciding through it:
that transaction is decided again or refused. Work already committed is
decided again at each later step against the submitter's live grants (see
[How an act is decided](https://docs.bijection.com/access/decisions.md)). Revocation cannot recall data a
frame already read or a release already disclosed.

## Session-bound roles

Break-glass access, or a role that needs a fresh second factor, is a short
grant plus guards. A lead who holds the role issues a short grant of it to a
colleague, and guards keep the grant short and the sign-in fresh:

```ts bijection/hr.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { act, forbid, label, mutation, role, t } from "@bijectionhq/bijection";
import { freshMfa } from "@bijectionhq/library-policies";

export const personnel = label();
export const hr = role({ clear: [personnel] });
export const hrLead = role({ include: [hr], issue: true });

export const openAccess = mutation({ allow: [hrLead], under: personnel, args: { to: t.principal } }, async (ctx, { to }) =>
  await ctx.grant(hr, { to, under: personnel, until: ctx.frame.now.entry.add({ minutes: 15 }) }),
);

export const shortAccess = forbid(act.grant(hr), {
  message: "HR access lasts at most fifteen minutes.",
  where: (a) => a.grant.until.isNull().or(a.grant.until.greaterThan(a.now.add({ minutes: 15 }))),
});

export const freshFactor = freshMfa(act.enter(readFile), { role: hr, within: { minutes: 10 } });
```

`a.now` is the host's clock. `freshMfa` refuses acting as `hr` unless
`a.mfaAge`, the age in seconds of the caller's last second factor read from
the verified credential, is at most ten minutes. The caller can supply
neither. `breakGlass` from the same library adds a stated reason
([library rules](https://docs.bijection.com/access/guards.md#library-rules)), and a guard can also read the
open incident (see [fact reads](https://docs.bijection.com/access/guards.md#read-facts)).

## Reactions hold roles

A reaction (a function with `on:`) runs as the installation. It declares the
roles it holds while it runs with `roles: [...]`, and holds nothing else:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const nightly = mutation({ on: every({ hours: 24 }), roles: [clerk], under: tenant }, async (ctx) => {
  /* … */
});
```

## Invitations and delegation

`@bijectionhq/library-members` builds the two common ways to hand authority
on. Both issue grants with `ctx.grant`, under the same rules:

```ts bijection/sharing.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { delegation, members } from "@bijectionhq/library-members";

/** Managers invite people to clerk or financeView in their tenant. */
export const team = members({ roles: [manager, clerk, financeView], under: tenant });

/** Clerks lend their clerk grant to an agent for up to eight hours. */
export const lend = delegation({ allow: [clerk], upTo: [clerk], until: { hours: 8 } });
```

* **An invitation** is a grant issued to a bearer. At the tenant member,
  `team.invite({ subject: null, role, email, until })` creates a pending
  invitation and returns `{ invitation, token }`. The invitee calls
  `team.accept({ token })` at public and reads the returned receipt with
  `team.acceptance({ receipt })`. Members checks the verified email and
  redemption deadline at the exact tenant member, issues the child grant
  there and consumes the pending invitation. The inviter cannot redeem
  their own invitation.
* **Direct bearer redemption** runs at the bearer's exact label. Use
  `invitations().redeem({ grant, token })` for public bearers or recipients
  who already clear that label. Use Members for tenant invitations that
  grant the invitee their first clearance there.
* **A delegation** is a grant issued from one of your own grants to an agent
  acting for you. `lend.delegate({ agent, role, until })` lends one child of
  your surviving grant of `role` (one of `upTo`), ending at `until`, and no
  later than the library's `until` from now. It keeps that grant's role, dies
  with it, and every act the agent performs records you as the person it
  acts for. Your guards that read your holdings, such as separation of
  duties, apply to the agent too. `lend.revoke({ grant })` ends it.

Delegate by issuing:
`ctx.grant(role, { to: agent, from: grant, under, until, only? })` issues one child of a grant you hold (it keeps that grant's
role, dies with it, and the agent's accountable principal is you); or place
`delegation({ allow, upTo, until })` from `@bijectionhq/library-members` and
call its `delegate({ agent, role, until? })`.

`allow` names the roles that may call each library's functions, as on
your own functions.

## Membership directory

`members({ roles, roster })` from `@bijectionhq/library-members` is the
membership library: who holds which of the app's roles, and the functions to
invite and revoke them. It returns a subtree; place it in the tree.

A membership keeps its grants, directory and invitations at a protected
`roster` label that every managed role clears. The roster is one of the app's own labels, often the one its
roles already clear. With `under: family` instead, each member of the family
keeps its own membership.

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app, label, role } from "@bijectionhq/bijection";
import { members } from "@bijectionhq/library-members";

const staff = label();
const clerk = role({ clear: [staff] });
const manager = role({ include: [clerk], issue: true });

export default app({ staff, clerk, manager, team: members({ roles: [clerk, manager], roster: staff }) }, { founders: [manager] });
```

The library's functions declare `allow` over the managed roles, and
`accept`, `acceptance`, `acceptPending` and `me` declare `allow: [role.signedIn]`,
a [class grant](https://docs.bijection.com/access/decisions.md#open-entries). The roster or member's
clearance still applies to `me`.

| Function | Allowed | Does |
| - | - | - |
| `team.invite({ subject, role, until, email })` | holders of a managed role that may issue `role` | With `subject`, grants `role` (null: the first managed role the caller may issue) until `until` (null: until revoked). With `subject: null`, creates a pending invitation and answers `{ invitation, token }`, bound to `email` when given. |
| `team.accept({ token })` | `role.signedIn` | Queues redemption at the exact roster or member and returns `{ receipt }`. The request starts at public. |
| `team.acceptance({ receipt })` | `role.signedIn` | Reads the caller's receipt in their own principal member. A redemption becomes `accepted` or `unavailable`. A contact lookup becomes `discovered` and lists the resulting redemption receipts. |
| `team.acceptPending()` | `role.signedIn` | Queues a lookup for the caller's trusted verified email and returns `{ receipt }`. A caller without a verified email gets `{ receipt: null }`. |
| `team.pending()` | issuers | The pending invitations for the roles the caller may issue. |
| `team.revoke({ subject, role, invitation })` | issuers | Revokes the subject's grants of the role, or a pending invitation. |
| `team.erase({ invitation })` | issuers | Erases a pending invitation's invitee: erases its fact, which is the email's erasure unit, and ends its pending grant. |
| `team.me()`; `team.me({ member })` with a family | signed-in callers with clearance at the roster or requested member | `{ subject, roles }`: the caller's principal and their live managed roles at that exact label. The list is empty if the caller has clearance and holds no live managed grant there. With a family, supply the member key returned by registration. |
| `team.list()` | holders of any managed role | Up to 256 `{ subject, role, until }` facts, by role then subject. |

Unused arguments are `null`. An invitation expires after seven days, or at
`until` if earlier. An invitation bound to an email needs the recipient's
current sign-in to present the same
[trusted verified email](https://docs.bijection.com/access/authentication#trust-verified-email-for-invitations).
The invitation's erasable fact keeps the email and bearer proof at its
roster or member. A declared release publishes the pending locator,
routing label, program issuer, role and deadline. The task compares the
requester's verified email proof at that member before issuing a child
from the bearer grant. A second release delivers the result to the
requester's own principal member. Tokenless lookup checks the caller's
verified address against a protected keyed order. Each matching pending
invitation goes to its exact member, which checks the address and
deadline again. The discovery receipt never includes email or grant IDs.

The issuing program's grant keeps the bearer invitation live. The
original inviter is accountable at the member and cannot accept their own
invitation. Revoking the bearer grant ends its redemptions.

`team.erase({ invitation })` closes the invitation's email and bearer proof
in every retained version of the fact. For a pending invitation it also
ends the grant and withdraws the public locator. Erasing the retained
versions of an accepted invitation leaves the accepter's role in force.

With `under: tenant` (a family), the issuers' functions (`invite`, `pending`,
`revoke`, `erase`, `list`) run `under: tenant`, the directory and invitations
are the caller's member's facts, and grants clear that member. The client picks the
member: `client.under(tenant.of("acme"))`.

The member task issues the role, inserts the directory row and consumes
the invitation in one append. The membership end is independent of the
redemption deadline. With a family, `me` runs under the caller's own
principal member and reads the caller's grants.

## Initial owner

Name the founder roles on your app, then name their recipient when you
create the installation.

```ts bijection/install.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app } from "@bijectionhq/bijection";
import * as roles from "./access";
import * as team from "./team";

export default app({ roles, team }, { founders: [roles.manager] });
```

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection installation create "$PROJECT_ID" notes --installation-id "$INSTALLATION_ID" --type prod --founder you@example.com
```

The first deploy issues the founder grants from the app's own grant. With an
email nomination, the first app sign-in that verifies that email redeems the
pending grants. Use an exact principal ID (the `person:…` ID
`ctx.frame.as.id` answers) for a direct grant. The lock lists the founder
roles (`founders …`).

### Found a family member

Founding a member is the `register(family)` right, held by both the caller
and the code. The caller holds it through a role's `register: [family]`, or
through a class grant the app declares; the code holds it through the
mutation's own `register: [family]`:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const tenant = label.family(t.key(orgs), { founder: tenantAdmin });

export const open = mutation({ allow: [role.signedIn], register: [tenant] }, async (ctx) => {
  return await ctx.register(tenant);
});

export default app({ tenant, tenantAdmin, open }, { classes: { signedIn: { register: [tenant] } } });
```

`classes: { signedIn: { register: [tenant] } }` gives the `signedIn` class
grant the right to found `tenant` members; `anyone` takes the same shape.
A founding runs at the public label and registers the member in its own
step. The family's `founder` role is then issued by the program's grant to
the registrant under the new member, in the same commit, so it outlives the
registrant's other grants and still records who registered. The lock prints
it as `founder <family> -> <role> parent program:<app> at register`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.