Pikku permissions

From pikkujs/pikku · View interactive version

Pikku permissions is an AI agent skill from the GitHub repository pikkujs/pikku. Who may call a function: ownership, roles, "only their own rows": `permissions`, pikkuPermission, pikkuAuth, scopes, MissingScopeError. Open before an `if` on the caller in a body. Sign-in is pikku-auth.

How to use this skill

Skill file

Pikku Permissions

What to reach for and why. For how to call it, run this once: pikku doc auth scopes pikkuPermission pikkuAuth addGlobalPermission defineScope. Depth: references/scopes.md.

First: is the caller a machine with a token?

Then this is NOT a permissions problem. Resolve the token in addHTTPMiddleware('*') middleware that calls setInitialSession, make the function a pikkuFunc, and gate it with scopes (pikku-auth, ../pikku-auth/references/machine-auth.md). A permissions check that verifies a bearer token and returns true is authentication in disguise, and leaves the function sessionless. The only exception is a bootstrap endpoint whose caller has no identity yet (a shared-secret registration, a login): it is sessionless and declares its gate here.

The rule

Authorization goes in the permissions field. Never in the func body.

The one exception is what an anonymous caller may see, after a skipWithoutSession

check: see "Sessionless functions" below.

permissions runs before func and is DECLARED: pikku meta and the auditor can see it. An if in the body is the same check, invisible.

// RIGHT
export const deleteBook = pikkuFunc({
  permissions: { owner: isBookOwner },
  func: async ({ kysely }, { bookId }, { session }) => {
    await kysely
      .deleteFrom('book')
      .where('bookId', '=', bookId)
      .where('ownerId', '=', session.userId) // the write is scoped too, not only the earlier check
      .execute()
  },
})

// WRONG — the gate is buried in the body
export const deleteBook = pikkuFunc({
  func: async ({ kysely }, { bookId }, { session }) => {
    const book = await kysely.selectFrom('book')...executeTakeFirst()
    if (book?.ownerId !== session.userId) throw new ForbiddenError()
    await kysely.deleteFrom('book').where('bookId', '=', bookId).execute()
  },
})

A permission that returns false answers 403 with ForbiddenError from #pikku/error. Tests expect that.

When even knowing the record exists would leak, as with a patient, the permission throws NotFoundError and the caller gets a 404. It is still the permission's job, never the body's. Groups run in order and a throw ends the check, so a NotFoundError from an owner check stops an admin group that follows it: for owner-or-admin write one permission that checks both and throws only when neither grants access.

`auth: true` IS NOT OWNERSHIP

auth: true means "somebody is signed in", not "this row is theirs". With nothing else, ANY signed-in user can delete ANY other user's row by passing its id. Every function that takes a row id needs BOTH: auth: true for the session and a permissions entry for ownership.

Do NOT write an isSignedIn permission returning !!session; auth: true already did that. A permission answers _may this user do this_ (role, ownership, tier), never _is there a session_.

Single row vs list: where ownership goes

A list that fetches everything and then filters in JS is a bug, not a permission.

Writing the checkers

Put them in src/permissions/, one file per entity, and reuse one checker across every function on that entity.

"Only their own X" is both, and a query filter alone never counts:

If a pikkuPermission never reads its data, pikku all warns with PKU586 and

--strict-meta or pikku validate --strict --codegen fails on it: use pikkuAuth. Switch

to pikkuAuth only where the check may refuse a caller with no session: see

"Sessionless functions" below.

A check always has a session and returns true or false. With no session it is not

run, and the call is refused. Both pikkuPermission and pikkuAuth do this.

Sessionless functions: `skipWithoutSession`

A check without skipWithoutSession on a sessionless function fails the build with

PKU587, whether it is on the function or global. Pick one:

export const isNotSuspended = pikkuAuth({
  skipWithoutSession: true,
  func: async ({ kysely }, session) => !(await isSuspended(kysely, session.userId)),
})

export const listBooks = pikkuSessionlessFunc({
  auth: false,
  permissions: { notSuspended: isNotSuspended },
  func: async ({ kysely }, _data, { session }) => {
    let query = kysely.selectFrom('book').selectAll()
    if (!session) query = query.where('visibility', '=', 'public')
    return { books: await query.execute() }
  },
})

Skipped means the call goes through. With no session the check is not called and

counts as passing, in an OR key and in an AND array. So with no session the function

decides what an anonymous caller may see, normally by limiting its query to public

rows. This is the one exception to "authorization never goes in the function body".

A check that must look at the data for anonymous callers cannot use a permission.

In a pikkuPermissionFactory the option goes on the pikkuPermission or pikkuAuth

it returns; the factory takes no options.

OR and AND

permissions: {
  owner: isBookOwner,            // OR — an owner may
  admin: isAdmin,                // OR — an admin may
  editor: [isAdmin, isBookOwner] // AND — both, inside one group
}

Groups are OR'd; entries inside a group array are AND'd.

Roles

If the app has roles, the role lives on the session (see pikku-auth / mapSession) and every mutating or admin-only function names it in permissions. Gate the FUNCTION: hiding an admin button is UX, never enforcement.

Scopes

scopes: ['admin:invoices:void'] is an AND gate checked BEFORE permissions and before input validation. Naming an undeclared scope fails codegen. A grant satisfies a scope if it is that scope, an ancestor, or a wildcard. Most apps need roles, not scopes; use these only when the plan asked for granular grants. The defineScope tree, grant matching and the sessionless restriction: references/scopes.md.

Global permissions

addGlobalPermission([isEmployee]) (from #pikku/auth) is an app-wide baseline every function must additionally pass. It can only narrow access, never grant what a function's own permissions would deny. Multiple calls accumulate and are AND'd. It applies to every function, sessionless ones too: a global reaches the workflow orchestrator and step workers too, so in an app that has sessionless functions it needs skipWithoutSession: true, or the employee check goes on each function instead.

The three gates

All must pass, in this order:

  1. Scopes (scopes): AND'd, checked before input validation, fails closed.
  2. Global permissions (addGlobalPermission): AND'd together, a baseline that only narrows.
  3. The function's own permissions: OR'd groups of AND'd entries.

They are independent: a broad global (e.g. isEmployee) can never satisfy an admin-only function's own requirement. Wire-, tag- and HTTP-route-level permissions (addHTTPPermission, addTagPermission, a permissions field on a wiring) no longer exist; tags are organizational only. Use tag/HTTP middleware for cross-cutting request handling, not authorization.

Webhooks and signed payloads

permissionsInBody: true is for a check that cannot be a permission because the identity arrives in the payload and there is no session: a webhook signature, a signed token, an invite code. It is purely declarative and enforces nothing; it tells the auditor the openness is deliberate. Anything expressible as a permission must be one.

After changes

pikku all --tsc regenerates, then verifies the checker types. A wrong permission signature fails here, not at runtime.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.