← Catalog

pi-keycloak-auth

Keycloak OAuth2/OIDC login for the pi coding agent and Oh My Pi: PKCE browser and device flows, offline tokens, automatic refresh, OpenAI-compatible provider with model discovery.

Package

Install

Install with PiG

pig install npm:pi-keycloak-auth

Install with Pi

pi install npm:pi-keycloak-auth
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "extensions": [
    "./dist/index.js"
  ]
}

README

Written by the package's publisher, shown as published in version 0.2.0 (README.md). PiG does not review it.

pi-keycloak-auth

CI npm License: MIT Node OpenSSF Scorecard

Keycloak sign-in for the pi coding agent and Oh My Pi. Log in once with your organization's SSO, then keep working for days: the agent sends a short-lived Keycloak access token to your OpenAI-compatible LLM gateway and refreshes it automatically, with no restart and no new login.

  • Three login methods for a public client with PKCE (S256), never a client secret: browser with automatic redirect capture, browser with a pasted redirect URL, and device code (RFC 8628) for SSH sessions, containers and CI.
  • Offline tokens by default: a session survives nights, weekends and SSO session expiry.
  • Automatic refresh through pi, safe with single-use (rotated) refresh tokens, and resilient to Keycloak or network hiccups.
  • OpenAI-compatible provider whose models are read from the gateway's /v1/models with your token, or declared by you, plus optional static headers.
  • pi and Oh My Pi from the same package and the same configuration file.
  • No runtime dependency: Node built-ins and the global fetch. One 40 KiB file, installable offline.

Contents

Requirements

ComponentVersion
pi (@earendil-works/pi-coding-agent)tested with 1.5.0, on Node ≥ 22.19
or Oh My Pi (@oh-my-pi/pi-coding-agent)tested with 18.18.6, on Bun
Keycloak22 or later, tested with 26.4

Quick start

  1. Ask your Keycloak admin for a public client set up as in Keycloak client.

  2. Install the extension:

    pi install npm:pi-keycloak-auth          # pi
    omp plugin install pi-keycloak-auth      # Oh My Pi
    
  3. Create ~/.pi/agent/keycloak-auth.json (pi) or ~/.omp/agent/keycloak-auth.json (Oh My Pi); either agent also finds the other one's file:

    {
      "issuer": "https://sso.example.com/realms/engineering",
      "clientId": "pi",
      "baseUrl": "https://llm-gateway.example.com/v1"
    }
    
  4. Start pi (or omp), run /login keycloak, sign in, then pick a model with /model. The list comes from your gateway's GET /v1/models, called with your Keycloak token.

Installation

Pick the mode that fits your environment; the extension behaves the same with each.

From npm

pi install npm:pi-keycloak-auth            # latest
pi install npm:pi-keycloak-auth@0.2.0      # pinned

From a local directory or an offline tarball

The package has no dependencies, so nothing is downloaded at install time. pi installs directories, not .tgz files: extract the tarball first.

# on a connected machine: npm pack pi-keycloak-auth, or take the .tgz from a GitHub release
tar -xzf pi-keycloak-auth-<version>.tgz        # creates ./package
pi install ./package

pi install ./pi-keycloak-auth-<version>.tgz reports success, but the extension then fails to load with Unknown file extension ".tgz": always install the extracted directory. A clone of this repository works too, after npm ci && npm run build.

As a single file

Each GitHub release ships pi-keycloak-auth.js (with SHA256SUMS). Drop it into pi's extension folder:

mkdir -p ~/.pi/agent/extensions
cp pi-keycloak-auth.js ~/.pi/agent/extensions/

Update or remove the extension with pi update / pi remove in the first two modes, or by replacing or deleting the file in the third.

With Oh My Pi

Oh My Pi loads the same package; nothing differs but the commands and its agent folder, ~/.omp/agent:

omp plugin install pi-keycloak-auth             # from npm
omp plugin link ./package                       # an extracted tarball or a clone (built)
cp pi-keycloak-auth.js ~/.omp/agent/extensions/ # the single file

Configuration

Settings come from one global file, keycloak-auth.json, and from PI_KC_* environment variables. For each option the file wins over the environment, which wins over the default.

The file is the first one found of:

  1. $PI_KC_CONFIG, a full path; when set, nothing else is tried.
  2. $PI_CODING_AGENT_DIR/keycloak-auth.json when that variable is set. Oh My Pi sets it for named profiles (omp --profile work), so each profile has its own file.
  3. Otherwise the running agent's folder, then the other agent's: ~/.pi/agent for pi, ~/.omp/agent for Oh My Pi (~/$PI_CONFIG_DIR/agent if you renamed its folder). One file therefore serves both agents.

Project-level configuration is never consulted, so a repository you open cannot send your tokens to another issuer or gateway.

{
  "issuer": "https://sso.example.com/realms/engineering",
  "clientId": "pi",
  "baseUrl": "https://llm-gateway.example.com/v1",
  "headers": { "X-Client": "pi" },
  "discoverModels": true,
  "models": [
    { "id": "qwen3-coder", "name": "Qwen3 Coder", "contextWindow": 262144, "maxTokens": 32768 },
    { "id": "gpt-oss-120b", "reasoning": true }
  ]
}
Option (file)EnvironmentDefaultMeaning
issuerPI_KC_ISSUERrequiredRealm URL, https://<host>/realms/<realm>
clientIdPI_KC_CLIENT_IDrequiredPublic client id
baseUrlPI_KC_BASE_URLrequiredGateway base URL, the one ending in /v1
modelsPI_KC_MODELSnoneModels, or details of discovered ones, see Models
discoverModelsPI_KC_DISCOVER_MODELSsee ModelsRead the model list from GET <baseUrl>/models
providerIdPI_KC_PROVIDER_IDkeycloakpi provider id: /login <providerId>, <providerId>/<model>
scopesPI_KC_SCOPESopenidExtra scopes, array or space/comma separated. openid is always sent
offlineAccessPI_KC_OFFLINE_ACCESStrueAdds the offline_access scope
headersPI_KC_HEADERSnoneStatic request headers. Env form: X-Client=pi,X-Team=core. Authorization is refused
callbackHostPI_KC_CALLBACK_HOST127.0.0.1Loopback address of the redirect listener
callbackPortPI_KC_CALLBACK_PORT49170Its port; 0 picks a free one
redirectPathPI_KC_REDIRECT_PATH/callbackPath of the redirect URI
refreshLeewaySecondsPI_KC_REFRESH_LEEWAY_SECONDS30Call Keycloak once the access token has less than this left
browserTimeoutSecondsPI_KC_BROWSER_TIMEOUT_SECONDS300How long a browser login waits for the redirect
loginMethodPI_KC_LOGIN_METHODaskbrowser, paste or device: /login uses it without asking
—PI_KC_CONFIGsee aboveFull path of the configuration file
—PI_KC_LOGwarnsilent, error, warn, info or debug

Models

With no models, the list is discovered: the extension calls the gateway's GET <baseUrl>/models (the OpenAI model list) with your Keycloak access token and your static headers, and offers every id it returns. With models declared, only those are offered, unless discoverModels is true.

When both are used, the gateway decides which models exist and models describes them: a discovered id takes the context window, output limit, reasoning, input and cost of the declared model with the same id. Declared models the gateway does not list are dropped, and the declared list is what is shown before the first discovery.

  • In the file, each entry is a string (the id) or an object with id and optionally name, contextWindow, maxTokens, reasoning, input (["text"] or ["text", "image"]), cost ({ input, output, cacheRead, cacheWrite } in dollars per million tokens) and compat (pi's OpenAI compatibility flags, passed through as is).
  • PI_KC_MODELS takes ids only, comma separated (PI_KC_MODELS=qwen3-coder,gpt-oss-120b).
  • A model known only by its id, declared or discovered, gets contextWindow 128000, maxTokens 16384, input: ["text"], reasoning: false and cost 0. Declare it in the file to set real values: the OpenAI model list carries no such details.

When the list is fetched:

AgentFetchedBetween fetches
piat each interactive start and when /model opens, with a token pi refreshes firstkept in ~/.pi/agent/models-store.json, used by pi -p and --list-models
Oh My Piright after /login, then when its 24-hour model cache expireskept in its model cache

A failed fetch (gateway down, 401) keeps the previous list and logs a warning. Oh My Pi hands the extension the stored token without refreshing it; with Keycloak's short tokens that one has usually expired at the next start, so the extension uses the latest valid token it has seen in the session, or keeps the cached list. In practice the list is refreshed at each login and whenever the cache expires during a working session.

Incomplete configuration

The provider is still registered, as Keycloak (not configured), so it never silently disappears. pi shows a message at startup, and /login and requests fail with it; it names the missing or invalid fields and the config file, e.g. invalid or missing clientId, baseUrl. In this mode the provider points at https://not-configured.invalid, a reserved name that never resolves, and sends nothing anywhere.

Logging in

/login keycloak asks how to sign in:

MethodBest forWhat happens
Browser, redirect captured automaticallydesktops (listed first)pi opens the login page; afterwards the browser shows Authentication complete and tries to close the tab
Browser, paste the redirect URLwhen the callback port cannot be reachedafter sign-in the browser fails to load http://127.0.0.1:…; copy that URL from the address bar into pi (the bare code also works)
Device codeSSH, containers, CI, Linux without display (listed first there)open the shown URL on any device and confirm the code
  • Without a local browser, pi never tries to open one: URLs are printed instead.
  • If the callback port is taken, the browser method switches to the paste method by itself.
  • Starting a new login frees the port held by an abandoned one.
  • loginMethod skips the question and always uses that method.
  • Oh My Pi has no menu for this question: it is asked as text (browser, paste or device; Enter keeps the recommended one, a prefix such as d is enough), and the device code is shown with its URL in the login dialog. Oh My Pi's RPC mode, used by editor integrations, cannot ask before showing a URL: there the recommended method is used, or loginMethod.
  • On a brand-new pi setup, pi then prints Logged in to Keycloak (keycloak), but no default model is configured for provider "keycloak". Use /model to select a model. This is expected: choose a model with /model, or set defaultProvider / defaultModel in pi's settings.

pi stores the credentials in ~/.pi/agent/auth.json (mode 0600), Oh My Pi in its agent database under ~/.omp/agent. /logout removes them.

Keycloak client

One public client is enough. The full guide, with admin-console steps, a kcadm.sh script and an importable definition, is in docs/keycloak-setup.md. In short:

  1. Client authentication off (public client).
  2. Standard flow and OAuth 2.0 Device Authorization Grant on; everything else off.
  3. PKCE code challenge method S256.
  4. Valid redirect URIs http://127.0.0.1:49170/callback (plus http://127.0.0.1/* if callbackPort is 0).
  5. offline_access as an optional client scope; users need the offline_access role (included in default-roles-<realm>).
  6. An Audience mapper adding your gateway's audience to the access token.
  7. Access Token Lifespan of 10–15 minutes. pi refreshes a token as soon as it has less than five minutes left, a threshold fixed in pi. With Keycloak's default 5 minutes every request falls inside that window; the extension still calls Keycloak only in the last 30 s, but pi locks and rewrites auth.json on each of those requests.

What the gateway receives

Authorization: Bearer <Keycloak access token>
X-Client: pi

The bearer is the access token (a JWT with "typ": "Bearer"), never the ID token, so a gateway that already validates Keycloak tokens needs no change. Validate it against the realm keys (<issuer>/protocol/openid-connect/certs) and check:

ClaimExpected
issthe realm URL
audyour gateway's audience (added by the Audience mapper)
azpthe pi client id
expin the future
realm_access.roles, resource_access.<client>.rolesthe roles your gateway requires
scopeincludes offline_access when offline tokens are in use

Token refresh

  • Before each request pi checks the stored token. With less than five minutes left it locks auth.json, calls the extension, and saves the returned pair before unlocking, so several pi processes never redeem the same refresh token twice.
  • The extension calls Keycloak only when less than refreshLeewaySeconds remain. Concurrent refreshes in one process share one call, and each result is remembered in memory for 60 seconds, so a late caller holding a just-rotated refresh token gets the new pair instead of invalid_grant.
  • Keycloak unreachable, 5xx, 429 or timeout: the current access token keeps being used while it is valid, and the refresh is retried on the next request.
  • Refresh token rejected (invalid_grant, e.g. offline session revoked or idle too long): the request fails with Keycloak session expired for "keycloak" (invalid_grant): … Run /login keycloak to sign in again., also shown as a notification.
  • Nothing runs in the background: after a night with pi left open, the first request of the morning refreshes the token and goes through.

Details and the request flow: docs/architecture.md.

Logs

Log lines start with [keycloak-auth] and go to stderr. PI_KC_LOG sets the level: silent, error, warn (default), info, debug. In pi's interactive view they appear above the editor, so keep warn day to day and use debug to troubleshoot.

Tokens, refresh tokens, authorization codes and PKCE verifiers are never logged. As a safety net, anything token-shaped in a log line is masked to at most its last four characters.

Troubleshooting

SymptomCause and fix
not_allowed: Offline tokens not allowed for the user or clientThe user lacks the offline_access role, or the scope is not assigned to the client. Fix the realm, or set offlineAccess: false (sessions then end with the SSO session)
invalid_grant after a long pauseOffline session expired or revoked, or SSO session ended with offlineAccess: false. Run /login keycloak
Keycloak page Invalid parameter: redirect_uriAdd the exact redirect URI to the client (or http://127.0.0.1/* with callbackPort: 0)
unauthorized_client with the device methodEnable OAuth 2.0 Device Authorization Grant on the client
Port 49170 on 127.0.0.1 is already in useAnother program holds the port; the login falls back to pasting. Or set callbackPort: 0
Provider shown as Keycloak (not configured)Read the message: it lists the fields to fix and the config file path
no default model is configured for provider "keycloak"Expected after the first login on a fresh setup: run /model
No Keycloak model in /modelDiscovery failed or has not run yet: PI_KC_LOG=info shows discovered N model(s) or the gateway's answer. With pi, open /model again after the first /login. pi -p only sees models found by an earlier interactive pi
omp --mode rpc refuses to start before the first loginOh My Pi's RPC mode needs a model to start with: declare one in models (with "discoverModels": true to keep discovery) and pass --model keycloak/<id>
Oh My Pi ignores the configurationCheck where it looks: the message names the file. Set PI_KC_CONFIG to point at it explicitly
Unknown file extension ".tgz"Install the extracted tarball directory, not the .tgz
Gateway answers 401 or 403Compare iss, aud and roles in the gateway logs with What the gateway receives; docs/keycloak-setup.md shows how to inspect the token locally
Anything elsePI_KC_LOG=debug pi, then open an issue with the log (it contains no secret)

Security

  • Public client with PKCE S256 on every flow and state checked on every redirect; no client secret exists anywhere.
  • The loopback listener binds 127.0.0.1 only, ignores forged redirects, and stops after one login or the timeout.
  • Credentials are stored by pi with mode 0600; the extension writes nothing else to disk.
  • Report vulnerabilities privately, see SECURITY.md.

Contributing

Issues and pull requests are welcome; see CONTRIBUTING.md and the code of conduct. Release notes are in CHANGELOG.md.

License

MIT © AyRickk