Leantel

Quickstart: TypeScript (Node and Express)

An Express app that signs people in with Leantel, protects an API route, and receives webhooks. Tested with Node 22, Express 5, openid-client 6, jose 6 and express-session. Read auth.md for an explanation of each step. For a single-page app with no backend, see auth.md section 4 instead.

1. Set up

In the Leantel console, create a Web app with a backend. Register https://<your app>/callback as a redirect URL and https://<your app>/ as a sign-out redirect URL. To try it on your computer first, also register http://localhost:<port> versions of both URLs: Leantel accepts exact http://localhost and http://127.0.0.1 URLs for apps with a backend, and for single-page apps in development workspaces; the port must match exactly. Then:

npm init -y && npm pkg set type=module
npm i express express-session openid-client jose
npm i -D typescript tsx @types/express @types/express-session @types/node
.env.example
LEANTEL_ISSUER=
LEANTEL_CLIENT_ID=
LEANTEL_CLIENT_SECRET=
LEANTEL_REDIRECT_URI=
LEANTEL_POST_LOGOUT_URI=
LEANTEL_AUDIENCE=
LEANTEL_WEBHOOK_SECRET=
SESSION_SECRET=
APP_API_URL=

2. Sign in and out

src/sign-in.ts
import * as oidc from "openid-client";
import type { Request, Response, Router } from "express";
import express from "express";

declare module "express-session" {
  interface SessionData {
    flow?: { state: string; nonce: string; verifier: string };
    user?: { userId: string; tenantId: string; idToken: string };
    tokens?: { accessToken: string; refreshToken?: string; expiresAt: number };
  }
}

let configuration: Promise<oidc.Configuration> | undefined;

function leantel(): Promise<oidc.Configuration> {
  configuration ??= oidc.discovery(
    new URL(process.env.LEANTEL_ISSUER!),
    process.env.LEANTEL_CLIENT_ID!,
    process.env.LEANTEL_CLIENT_SECRET!,
  );
  return configuration;
}

export async function accessToken(request: Request): Promise<string | undefined> {
  const tokens = request.session.tokens;
  if (!tokens) return undefined;
  if (Date.now() < tokens.expiresAt - 30_000) return tokens.accessToken;
  if (!tokens.refreshToken) return undefined;
  try {
    const refreshed = await oidc.refreshTokenGrant(await leantel(), tokens.refreshToken);
    request.session.tokens = {
      accessToken: refreshed.access_token,
      refreshToken: refreshed.refresh_token ?? tokens.refreshToken,
      expiresAt: Date.now() + (refreshed.expiresIn() ?? 0) * 1000,
    };
    return refreshed.access_token;
  } catch {
    return undefined;
  }
}

export async function signInRoutes(): Promise<Router> {
  const config = await leantel();
  const router = express.Router();

  router.get("/login", async (request: Request, response: Response) => {
    const verifier = oidc.randomPKCECodeVerifier();
    const flow = { state: oidc.randomState(), nonce: oidc.randomNonce(), verifier };
    request.session.flow = flow;
    const parameters: Record<string, string> = {
      redirect_uri: process.env.LEANTEL_REDIRECT_URI!,
      scope: "openid email",
      code_challenge: await oidc.calculatePKCECodeChallenge(verifier),
      code_challenge_method: "S256",
      state: flow.state,
      nonce: flow.nonce,
    };
    if (request.query.signup === "1") parameters.prompt = "create";
    response.redirect(oidc.buildAuthorizationUrl(config, parameters).href);
  });

  router.get("/callback", async (request: Request, response: Response) => {
    const flow = request.session.flow;
    if (!flow) {
      response.status(400).send("Sign-in expired. Try again.");
      return;
    }
    delete request.session.flow;
    const currentUrl = new URL(request.originalUrl, process.env.LEANTEL_REDIRECT_URI!);
    const tokens = await oidc.authorizationCodeGrant(config, currentUrl, {
      pkceCodeVerifier: flow.verifier,
      expectedState: flow.state,
      expectedNonce: flow.nonce,
      idTokenExpected: true,
    });
    const claims = tokens.claims()!;
    request.session.regenerate((error) => {
      if (error) {
        response.status(500).send("Sign-in failed.");
        return;
      }
      request.session.user = { userId: claims.sub, tenantId: String(claims.tenant_id), idToken: tokens.id_token! };
      request.session.tokens = {
        accessToken: tokens.access_token,
        refreshToken: tokens.refresh_token,
        expiresAt: Date.now() + (tokens.expiresIn() ?? 0) * 1000,
      };
      response.redirect("/");
    });
  });

  router.get("/logout", (request: Request, response: Response) => {
    const idToken = request.session.user?.idToken ?? "";
    request.session.destroy(() => {
      const logoutUrl = oidc.buildEndSessionUrl(config, {
        id_token_hint: idToken,
        post_logout_redirect_uri: process.env.LEANTEL_POST_LOGOUT_URI!,
      });
      response.redirect(logoutUrl.href);
    });
  });

  return router;
}

/login?signup=1 opens the sign-up page instead. accessToken returns a valid access token for the signed-in person, refreshing it when it has expired. Refresh tokens rotate, so it saves the new pair every time; reusing an old refresh token signs the person out.

3. Protect an API route

src/api.ts
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";
import type { NextFunction, Request, Response } from "express";

export interface AccessClaims extends JWTPayload {
  sub: string;
  tenant_id: string;
  client_id: string;
  scope: string;
  roles?: string[];
}

declare global {
  namespace Express {
    interface Locals {
      claims?: AccessClaims;
    }
  }
}

const issuer = process.env.LEANTEL_ISSUER!;
const keys = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));

export async function verifyAccessToken(request: Request, response: Response, next: NextFunction) {
  const token = request.headers.authorization?.match(/^Bearer (.+)$/)?.[1];
  try {
    const { payload } = await jwtVerify<AccessClaims>(token ?? "", keys, {
      issuer,
      audience: process.env.LEANTEL_AUDIENCE!,
      algorithms: ["RS256"],
      typ: "at+jwt",
      clockTolerance: 60,
      requiredClaims: ["exp", "iat", "sub", "jti", "client_id", "tenant_id"],
    });
    response.locals.claims = payload;
    next();
  } catch {
    response.set("WWW-Authenticate", 'Bearer error="invalid_token"').status(401).send("Invalid token");
  }
}

export function requirePermission(permission: string) {
  return (request: Request, response: Response, next: NextFunction) => {
    const permissions = response.locals.claims?.scope.split(" ") ?? [];
    if (!permissions.includes(permission)) {
      response.set("WWW-Authenticate", 'Bearer error="insufficient_scope"').status(403).send(`Missing permission ${permission}`);
      return;
    }
    next();
  };
}

A bad or missing token gets 401. To require a permission on a route, add requirePermission("app:use") after verifyAccessToken; a token without the permission gets 403. Set up Auth gives your workspace the permission app:use and the role member, which everyone who signs up gets; add your own permissions under APIs and permissions and grant them through roles (auth.md section 7).

4. Receive webhooks

src/webhook.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import type { Request, Response } from "express";

export interface WebhookEvent {
  id: string;
  type: string;
  tenant_id: string;
  occurred_at: string;
  data: Record<string, unknown>;
}

export function isValidSignature(header: string, rawBody: Buffer, secret: string, now = Date.now()): boolean {
  const parts = Object.fromEntries(header.split(",").map((part) => part.split("=", 2)));
  const timestamp = Number(parts.t);
  if (!Number.isInteger(timestamp) || Math.abs(now / 1000 - timestamp) > 300) return false;
  const expected = createHmac("sha256", secret).update(`${parts.t}.`).update(rawBody).digest("hex");
  const received = String(parts.v1 ?? "");
  return expected.length === received.length && timingSafeEqual(Buffer.from(expected), Buffer.from(received));
}

export function webhookHandler(
  alreadyHandled: (eventId: string) => Promise<boolean>,
  handle: (event: WebhookEvent) => Promise<void>,
) {
  return async (request: Request, response: Response) => {
    const rawBody = request.body as Buffer;
    if (!isValidSignature(request.get("Auth-Signature") ?? "", rawBody, process.env.LEANTEL_WEBHOOK_SECRET!)) {
      response.status(401).send("Invalid signature");
      return;
    }
    const event = JSON.parse(rawBody.toString("utf8")) as WebhookEvent;
    if (!(await alreadyHandled(event.id))) await handle(event);
    response.sendStatus(200);
  };
}

5. Wire it up

src/server.ts
import express from "express";
import session from "express-session";
import { accessToken, signInRoutes } from "./sign-in.js";
import { verifyAccessToken } from "./api.js";
import { webhookHandler } from "./webhook.js";

const app = express();
app.set("trust proxy", 1);
app.post(
  "/webhooks/leantel",
  express.raw({ type: "application/json" }),
  webhookHandler(
    async () => false,
    async (event) => console.log("leantel event", event.type, event.id),
  ),
);
app.use(
  session({
    secret: process.env.SESSION_SECRET!,
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true, secure: process.env.LEANTEL_REDIRECT_URI!.startsWith("https://"), sameSite: "lax" },
  }),
);
app.use(await signInRoutes());
app.get("/", async (request, response) => {
  const token = await accessToken(request);
  if (!token) {
    response.send('<a href="/login">Sign in</a>');
    return;
  }
  const api = await fetch(`${process.env.APP_API_URL}/api/me`, { headers: { authorization: `Bearer ${token}` } });
  response.status(api.status).type("application/json").send(await api.text());
});
app.get("/api/me", verifyAccessToken, (request, response) => {
  response.json({ tenantId: response.locals.claims!.tenant_id, userId: response.locals.claims!.sub });
});
app.listen(3000);

The webhook route uses express.raw so the signature is checked against the exact bytes Leantel sent; register it before any JSON body parser. express-session's default memory store is for trying it out; use a real session store in production.

6. Check it works

  • npx tsx src/server.ts, open /login: you land on your branded Leantel sign-in page, then back on /, which calls your API's /api/me with the access token and shows your tenantId and userId. Set APP_API_URL to your app's own URL.
  • curl -i https://<your app>/api/me (no token) → 401.
  • In the console, Webhooks → Send test event → your log shows it.