Skip to main content

An approvals inbox in your own app

Show pending requests to approvers inside your product, and send their decisions to LumoAuth.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonPlain HTTPExpressFastAPI

What it shows​

  1. An approver signs in to your app. The app asks for the scope jit:approve.
  2. Your server lists the requests that wait for a person, with the access token of that approver.
  3. The approver clicks approve or deny, and your server sends the decision to LumoAuth with the same token.
  4. LumoAuth checks who may decide, and the agent gets its answer.

Your server never decides with an API key: an API key cannot hold jit:approve. Each decision is made by a person, and the audit log names that person.

Before you start​

  • An application through which approvers sign in, with the scope jit:approve. The setup script registers the application Approvals desk, with the redirect address http://localhost:3000/auth/callback.
  • A person who decides. This person needs the permission jit.approve. The setup script creates the role Agent reviewer, which holds only this permission. With APPROVER_EMAIL, it gives the role to that person. Administrators hold the permission already.
  • The approver must not own the agent: the owner of an agent cannot decide the requests of that agent.
  • An agent that asks. The agent of Ask a person for a permission, for one task does, and its setup gives the agent to another owner.
  • Check that your plan includes just-in-time permissions in the plans matrix.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYFor the setup script only: an API key with the scopes admin:clients:read, admin:clients:write, admin:roles:read, admin:roles:write and admin:users:read. The inbox itself uses the token of the approver.
APPROVER_EMAILOptional, for the setup script: the email address of a person who gets the role "Agent reviewer".
LUMOAUTH_CLIENT_IDThe client ID of the application "Approvals desk". The setup script prints it.
PORTOptional. The port of the server, and of the redirect address that the setup script registers. Default: 3000.
SESSION_SECRETOptional. The secret that signs the session cookie. Without it, every start of the server signs everybody out.
APPROVER_ACCESS_TOKENFor inbox.sh only: the access token of a signed-in approver, with the scope jit:approve. Your app gets it at sign-in.

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

APPROVER_EMAIL=riley.park@example.com node approvals/inbox-in-your-app/setup.mjs
setup.mjs
// Creates what the inbox needs: the application through which approvers sign
// in, and a role that lets a person decide the requests of agents. Run it
// again at any time.
//
// node approvals/inbox-in-your-app/setup.mjs
// APPROVER_EMAIL=riley.park@example.com node approvals/inbox-in-your-app/setup.mjs
//
// The API key needs the scopes admin:clients:read, admin:clients:write,
// admin:roles:read, admin:roles:write and admin:users:read.
import { call, ensure, list, printEnv } from '../../_lib/admin.mjs';

const redirectUris = [`http://localhost:${process.env.PORT ?? 3000}/auth/callback`];
const application = await ensure('/admin/clients', (c) => c.name === 'Approvals desk', {
name: 'Approvals desk',
redirectUris,
// A public application signs in with PKCE and has no secret to keep.
isConfidential: false,
// jit:approve lets the token of an approver list and decide requests.
scopes: ['openid', 'profile', 'email', 'jit:approve'],
});
// A second run with another port replaces the redirect address.
await call('PATCH', `/admin/clients/${application.clientId}`, { redirectUris });

// An approver needs the permission jit.approve, and nothing else.
const role = await ensure('/admin/roles', (r) => r.slug === 'agent-reviewer', {
name: 'Agent reviewer',
slug: 'agent-reviewer',
description: 'May approve and deny the requests of agents.',
});
await call('PUT', `/admin/roles/${role.id}/permissions`, { permissions: ['jit.approve'] });

// Adds the role to one person, and keeps the other roles of that person.
const email = process.env.APPROVER_EMAIL;
if (email) {
const approver = (await list('/admin/users')).find((u) => u.email === email);
if (!approver) throw new Error(`No user with the email address ${email}.`);
await call('POST', `/admin/roles/${role.id}/users`, { userId: approver.id });
console.log(`${email} holds the role "${role.name}".`);
}

console.log(`The application "${application.name}" and the role "${role.name}" are ready.`);
printEnv({ LUMOAUTH_CLIENT_ID: application.clientId });

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. Each version was run with the agent of the recipe for just-in-time permissions. An approver signed in, saw the request, and approved or denied it. A person without the role got 403.

approvals/inbox-in-your-app/js/server.mjs
// The server side of an approvals inbox in your own app. An approver signs
// in, and the server lists and decides the requests of agents with the token
// of that person.
//
// node approvals/inbox-in-your-app/js/server.mjs
import { randomBytes } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import express from 'express';
import session from 'express-session';
import { LumoAuthBackend, lumoAuthMiddleware, requireAuth } from '@lumoauth/express';

const baseUrl = process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev';
const orgId = process.env.LUMOAUTH_ORG_ID;
const port = process.env.PORT ?? 3000;

const app = express();
app.use(express.json());
app.use(
session({
// Use a fixed secret and a real session store outside a test.
secret: process.env.SESSION_SECRET ?? randomBytes(32).toString('hex'),
resave: false,
saveUninitialized: false,
// A browser does not send a lax cookie with a form that another site
// posts. So no other site can approve a request in the name of the approver.
cookie: { httpOnly: true, sameSite: 'lax' },
}),
);

// Adds /auth/login, /auth/callback and /auth/logout. The scope jit:approve
// makes the token of the approver valid for the calls below.
app.use(
lumoAuthMiddleware({
baseUrl,
organization: orgId,
clientId: process.env.LUMOAUTH_CLIENT_ID,
scope: 'openid profile email jit:approve',
}),
);

// The token of the signed-in approver. The middleware keeps it in the session.
const approverToken = (req) => req.session.__lumoAuth.tokens.access_token;
const approver = requireAuth({ scopes: ['jit:approve'] });

app.get('/', (req, res) => {
if (!req.user) return res.redirect('/auth/login');
res.sendFile(fileURLToPath(new URL('../inbox.html', import.meta.url)));
});

// The queue: the requests that this person may decide.
app.get('/api/approvals', approver, async (req, res) => {
const lumo = new LumoAuthBackend({ baseUrl, orgId, secretKey: approverToken(req) });
try {
res.json(await lumo.jit.listPendingRequests());
} catch (error) {
// A person without jit.approve gets 403, unless a request waits for their own consent.
res.status(error.statusCode ?? 500).json(error.body ?? { error: error.code });
}
});

// A decision. The SDK has no call for it, so this is plain HTTP.
app.post('/api/approvals/:id/:decision', approver, async (req, res) => {
const { id, decision } = req.params;
if (decision !== 'approve' && decision !== 'deny') return res.status(404).end();
if (!req.is('application/json')) return res.status(415).end();
const note = req.body?.note || undefined;
const answer = await fetch(`${baseUrl}/orgs/${orgId}/api/v1/jit/${decision}/${encodeURIComponent(id)}`, {
method: 'POST',
headers: { Authorization: `Bearer ${approverToken(req)}`, 'Content-Type': 'application/json' },
// Notes and reasons stay inside the organization. The agent does not see them.
body: JSON.stringify(decision === 'approve' ? { notes: note } : { reason: note }),
});
const result = await answer.json();
console.log(`${id}: ${result.status ?? result.error}`);
// LumoAuth checks who may decide. Pass its answer on, also a refusal.
res.status(answer.status).json(result);
});

app.listen(port, () => console.log(`inbox: http://localhost:${port}`));
approvals/inbox-in-your-app/inbox.html
<!doctype html>
<!-- A bare page for a first test of the server. In a React app, the
approvals inbox pattern shows the same list. -->
<meta charset="utf-8">
<title>Approvals</title>
<h1>Approvals</h1>
<ul id="list"></ul>
<script>
async function load() {
const rows = await (await fetch('/api/approvals')).json();
const items = rows.map((row) => {
const item = document.createElement('li');
const { type, actions = [], identifier = '' } = row.authorization_details;
// An agent writes these texts, so the page shows them as text, never as HTML.
item.textContent = `${row.agent_name}: ${actions.join(', ')} ${type} ${identifier} (${row.risk_level}). ${row.justification ?? ''} `;
for (const decision of ['approve', 'deny']) {
const button = document.createElement('button');
button.textContent = decision;
button.onclick = async () => {
await fetch(`/api/approvals/${row.request_id}/${decision}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ note: 'Decided in the approvals desk.' }),
});
load();
};
item.append(button);
}
return item;
});
document.getElementById('list').replaceChildren(...items);
}
load();
</script>
node approvals/inbox-in-your-app/js/server.mjs

The two servers do the same: they add the routes for sign-in, GET /api/approvals for the list, and POST /api/approvals/{id}/approve or /deny for a decision. inbox.html is a bare page for a first test. In a React app, the approvals inbox pattern shows the same list. The curl script shows the same calls of the API, for a server in another language.

To try it:

  1. Start a server, and open http://localhost:3000. Sign in as the approver.
  2. In a second terminal, run the agent of the recipe for just-in-time permissions. It stops at "waiting for a person".
  3. Reload the page. It shows the request of "Invoice agent": the action approve, the type invoices, the record INV-7741 and the reason.
  4. Click approve or deny.

Check the result​

Output
inbox: http://localhost:3000
jit_4655efb5727b7a9748026588321611f3: approved
  • The agent prints request: approved and collects its token. After deny, it prints request: denied.
  • The request leaves the list. A second decision on it, from any approver, gets invalid_request with "Request is not pending approval".
  • A person without jit.approve gets the status 403 and insufficient_permissions for the list.
  • Open Audit logs under Security in the portal. The event jit.permission_approved names the approver.
  • sh approvals/inbox-in-your-app/http/inbox.sh prints one line for each waiting request, such as jit_4655… Invoice agent: approve invoices INV-7741 (low).

Limits​

  • The list does not change by itself. To learn of a new request at once, subscribe a webhook to the event jit.approval_required, and reload the list when it arrives. Receive webhooks shows a receiver.
  • The list holds the 50 newest requests that the person may decide. Expired requests are left out.
  • LumoAuth allows 60 calls in a minute for each approver, separately for the list, for approve and for deny.
  • A note of the approver stays in the organization: the audit log and the inbox of the portal show it, the agent does not.
  • The portal and the mobile app can decide several requests at once. The API decides one request in each call.