@manta-eu/auth
v0.25.0
Published
Keycloak login for the SDK CLIs: browser and device-code login, silent token renewal, and credential storage; plus the default deployment the SDK targets
Readme
@manta-eu/auth
Keycloak login for Manta: the SDK CLIs (@manta-eu/codegen, @manta-eu/upload) and a custom app's
own server. It mints and renews tokens; it knows nothing about what a caller does with them. The root
entry adds browser and device-code login with credential storage for the CLIs, and gives each CLI
login/logout/status commands to register on its own commander program.
@manta-eu/auth/web runs without Node — in a browser, a Worker, Deno or Bun — and holds the token
cache, the web-app sign-in below, client credentials, and the issuer helpers.
Documentation: developers.manta.eu
Log in
MANTA_CLIENT_SECRET decides the path.
No secret — a person. userTokenSource() builds a token source that logs in once and renews
silently after that:
import { publicClientFrom, userTokenSource } from "@manta-eu/auth";
const token = userTokenSource(publicClientFrom({ keycloakUrl, keycloakRealm }), { label: "my-cli" });It opens the browser and listens on 127.0.0.1 for Keycloak to hand the login back (the
authorization code flow with PKCE). Over SSH, or on Linux without a display, it prints a link and a
code for a browser on another machine instead; useDeviceCode: true asks for that anywhere. The
token is the person's, so a caller reads only what that person can open.
The login is kept, so later runs renew it silently. It asks for offline_access, so it lasts until
it goes unused for the realm's offline idle limit (30 days by default) or the person logs out.
userTokenSource logs in by itself when nothing is stored and a terminal is attached; without one it
throws and names the login command instead of waiting for a browser.
registerAuthCommands(program, { label }) wires login, status and logout into a commander
program, all reading and writing the same store:
| Command | What it does |
| -------- | ------------------------------------------------------------------- |
| login | Logs in and stores the login. |
| status | Says whether a login is stored, and for whom. Exits 1 when none is. |
| logout | Revokes the login at Keycloak and deletes the stored copy. |
Each takes the same --keycloak-url and --keycloak-realm, because a login belongs to one
Keycloak, realm and client. Both default to hiremanta.com production, from defaultDeployment.
The client defaults to the realm's <realm>-cli, a public client made for this; --client-id is
only needed for another one. Every CLI that registers these commands reads and writes the same
store, so logging in with one serves all of them.
The login lives in the macOS Keychain (service manta-cli), or in ~/.manta/credentials.json with
mode 0600 on Linux, on Windows, and on a Mac whose Keychain refuses it: while locked, e.g. over
SSH, or for a refresh token over about 2.9 KB, the most security takes in one line. The CLI says
on stderr when the file takes over. Only the refresh token is kept. MANTA_CONFIG_DIR moves the file.
A secret — a machine. mintWithClientCredentials() asks for a service account token directly,
with no stored login involved:
import { mintWithClientCredentials } from "@manta-eu/auth";
const accessToken = await mintWithClientCredentials({ baseUrl, realm, clientId, clientSecret, scope });Sign in on your own server
webLoginRoutes gives a custom app's server /login, /callback and /logout, and keeps the person's session in
encrypted cookies, on standard Request and Response:
import { webLoginRoutes } from "@manta-eu/auth/web";
const manta = webLoginRoutes({ client: { clientId, clientSecret }, appUrl, sessionSecret });
const response = await manta.handle(request); // undefined for any other path
const { accessToken, setCookies } = await manta.session(request); // renewed when about to expireOr run the steps yourself:
A custom app's server signs its people in with its client ID and secret, through the authorization code flow with PKCE, on a redirect URL registered for the app:
import { endWebLogin, finishWebLogin, refreshWebLogin, startWebLogin, webLogoutUrl } from "@manta-eu/auth/web";
const client = { baseUrl, realm, clientId, clientSecret };
// 1. Send the person to `url`; keep `state` and `verifier` in their session.
const { url, state, verifier } = await startWebLogin(client, { redirectUri, offlineAccess: true });
// 2. On the redirect, check `state`, then trade the code for tokens.
const tokens = await finishWebLogin(client, { code, redirectUri, verifier });
// 3. Before the access token's five minutes run out, renew it.
const renewed = await refreshWebLogin(client, tokens.refreshToken);
// 4. Sign out of your app only, ending even an offline session...
await endWebLogin(client, renewed.refreshToken);
// ...or out of Manta too, returning to a redirect URL or the app's home URL.
const logoutUrl = webLogoutUrl(client, { idToken: renewed.idToken, postLogoutRedirectUri: homeUrl });Store the refresh token refreshWebLogin returns in place of the old one: Manta's realms rotate it,
and an old one is accepted at most once more. undefined means the person signs in again.
offlineAccess: true keeps the session alive while it is used, until 30 idle days or a year.
Machine access
A custom app with machine access mints its own token, with no person involved:
import { cachedToken, mintWithClientCredentials } from "@manta-eu/auth/web";
const getAccessToken = cachedToken(() => mintWithClientCredentials({ baseUrl, realm, clientId, clientSecret }));Keep the secret on a server; never ship it to a browser.
Tokens for your app's own users
A custom app with machine access gets a token for one of its own users, by the app's id for them, or for a visitor it has not identified, by its session id for them. Manta keeps their chats, and no memories:
import { cachedToken, customAppUserAccessToken } from "@manta-eu/auth/web";
// One cached getter per person, so each reuses their token until it nears expiry. Evict idle entries in a real app.
const tokens = new Map<string, () => Promise<string>>();
const tokenFor = (userId: string) => {
let get = tokens.get(userId);
if (get === undefined) {
get = cachedToken(() =>
customAppUserAccessToken({ clientId, clientSecret, userId, name, email, teams: ["/Sales/EU"] }),
);
tokens.set(userId, get);
}
return get;
};A visitor works the same way, with anonymousId in place of userId: a random id you keep for them, such as one in a
cookie or in your session, following the same rule of 1 to 128 letters, digits or - _ . @ |. Give exactly one of the
two. The same anonymousId brings back that visitor's chats, so keep it private.
It sends the app's secret, so it runs on the app's server only; the token it returns may go to the
browser. datastores narrows the token to some of the datastores the app reaches. teams places
the person in those teams of the app's organization: an empty list places them in none, and leaving
it out places them in every team the app reaches. A refusal throws RefusedRequestError, whose
status tells isTransientStatus whether a retry can help (429, 503) or not (401, 403).
Issuer and discovery
issuerUrl({ baseUrl, realm }) names the realm's issuer, and discoveryUrl({ baseUrl, realm }) its
OpenID Connect discovery document, which most OIDC libraries configure themselves from.
Renewing on refusal
withRenewal(token, call) calls call with a fresh access token, and on a 401 specifically calls
the token source's renew() and retries once — the same pattern Claude Code uses for MCP OAuth. Wrap
any authenticated request with it instead of minting a token by hand.
