Developer Reference
Sign in
Sign users in with @chabi/js, or by hand in any language, on the web and on desktop.
Updated November 2026
Sign in
In JavaScript or TypeScript, use @chabi/js. It runs the sign-in, keeps the user's tokens, refreshes them one at a time across tabs, and signs the user out when they remove your app's access. It has no dependencies, and the official OpenAI and Anthropic SDKs still make every request. Plain shows the flow by hand, for other languages.
With @chabi/js
npm install @chabi/jsimport { Chabi, signInButton } from "@chabi/js";import OpenAI from "openai";const chabi = new Chabi({clientId: "<your client_id>",redirectUri: "<your redirect URI>", // exactly as registered});// On every page load: finishes the sign-in when the user comes back from Chabi.await chabi.handleRedirect().catch((err) => showError(err.info.message));if (!chabi.signedIn) {const button = signInButton(); // the required button, logo includedbutton.onclick = () => chabi.signIn();document.body.append(button);}// Signed in or out, here or in another tab. reason: signed_in, signed_out, access_removed or expired.chabi.onChange((signedIn, reason) => render(signedIn, reason));const client = new OpenAI({ ...chabi.openai(), dangerouslyAllowBrowser: true });
- If a sign-in fails,
handleRedirect()throws aChabiError;err.info.kindisaccess_deniedwhen the user declined. chabi.anthropic()does the same for the Anthropic SDK.chabi.credits()andchabi.me()give the user's balance and account name, andchabi.signOut()signs out.- Desktop apps use
@chabi/js/node: see DESKTOP APPS.
Without the SDK
For other languages, or to see what the SDK does: OAuth 2.0 authorization code flow with PKCE. There's no client secret, so it works in apps that run entirely in the browser.
1. Send the user to sign in
const b64url = (b) =>btoa(String.fromCharCode(...new Uint8Array(b))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));const state = b64url(crypto.getRandomValues(new Uint8Array(16)));// localStorage, not sessionStorage: email sign-in links can come back in a new tab.localStorage.setItem("chabi:" + state, JSON.stringify({ verifier, at: Date.now() }));const challenge = b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)),);location.assign("https://chabi.dev/oauth/authorize?" + new URLSearchParams({response_type: "code",client_id: "<your client_id>",redirect_uri: "<your redirect URI>",code_challenge: challenge,code_challenge_method: "S256",state,}));
2. At your redirect URI, swap the code for the user's token
const params = new URLSearchParams(location.search);if (params.get("error")) {throw new Error(params.get("error_description") ?? "Sign-in was cancelled.");}const key = "chabi:" + params.get("state");const pending = JSON.parse(localStorage.getItem(key) ?? "null");localStorage.removeItem(key); // each state works onceif (!pending || Date.now() - pending.at > 15 * 60_000) {throw new Error("This sign-in didn't start here, or took too long. Please try again.");}const verifier = pending.verifier;history.replaceState(null, "", location.pathname); // drop ?code from the address barconst res = await fetch("https://chabi.dev/oauth/token", {method: "POST",headers: { "Content-Type": "application/x-www-form-urlencoded" },body: new URLSearchParams({grant_type: "authorization_code",code: params.get("code"),redirect_uri: "<your redirect URI>",client_id: "<your client_id>",code_verifier: verifier,}),});const { access_token: userToken, refresh_token, expires_in } = await res.json();
- The code works once and expires after a minute. A missing
stateentry means the sign-in didn't start in this browser: start again, never skip the check. - The token is for this user in this app only, so it's safe in the browser. It lasts 30 days (
expires_in, in seconds).
3. Keep the user signed in
Before the token expires, or when a request gets 401 invalid_token, POST grant_type=refresh_token, refresh_token and client_id to /oauth/token for a new pair. Each refresh token works once, so always store the new one. Sending one a second time ends the sign-in, including the access token it gave out (it looks like a stolen token). So only one refresh may run at a time across all open tabs: a promise shared within one page isn't enough. The Web Locks API handles it:
// used: the refresh token this tab was holding when it decided to refresh.async function refresh(used) {return navigator.locks.request("chabi-refresh", async () => {// Reread inside the lock: if another tab refreshed while we waited, use its tokens.const saved = JSON.parse(localStorage.getItem("chabi:tokens"));if (saved.refresh_token !== used) return saved;const res = await fetch("https://chabi.dev/oauth/token", {method: "POST",body: new URLSearchParams({grant_type: "refresh_token",refresh_token: saved.refresh_token,client_id: "<your client_id>",}),});if (!res.ok) throw new Error("signed_out"); // invalid_grant: sign in againconst t = await res.json();const tokens = { ...t, expires_at: Date.now() + t.expires_in * 1000 };localStorage.setItem("chabi:tokens", JSON.stringify(tokens));return tokens;});}
- A refresh token lasts 90 days from its last use; after that, or on
invalid_grant, send the user through step 1 again. - Users can remove your app's access from their account at any time. Its token stops working within a minute (401
grant_revoked).
Sign-in button
Every "Sign in with Chabi" button must show the Chabi key logo, so users recognise it in every app. Use one of the two styles below:
<button class="chabi-signin" type="button"><svg width="22" height="22" viewBox="0 0 100 100" aria-hidden="true"><mask id="chabi-key"><rect width="100" height="100" fill="#fff"/><circle cx="33" cy="50" r="15" fill="#000"/><circle cx="33" cy="50" r="7" fill="#fff"/><path d="M45 46L82 46L82 62L77 62L77 54L73 54L73 62L68 62L68 54L45 54Z" fill="#000"/></mask><circle cx="50" cy="50" r="50" fill="currentColor" mask="url(#chabi-key)"/></svg>Sign in with Chabi</button>
.chabi-signin { display: inline-flex; align-items: center; gap: 10px; padding: 10px 18px; border: 0;border-radius: 8px; background: #E0A526; color: #121212; font: 700 16px/1.2 system-ui, sans-serif; cursor: pointer; }.chabi-signin:hover { background: #C99520; }/* Dark style: */.chabi-signin.dark { background: #121212; color: #FFFFFF; }.chabi-signin.dark svg { color: #E0A526; }
- The logo comes first, then the words Sign in with Chabi (or Continue with Chabi). Size, padding and corner radius can change to fit your app.
- Don't redraw, recolor, stretch, rotate or crop the logo, and keep it at least 20px. It's gold on dark backgrounds and dark on the gold button.
- Prefer a file? https://chabi.dev/chabi-logo.svg is the gold logo.
Desktop apps
Desktop apps use the same flow (OAuth for native apps, RFC 8252). Open sign-in in the user's system browser, not a web view inside your app: users can see it's really Chabi, they're often already signed in, and Google sign-in refuses embedded web views. Then get the code back one of two ways:
- loopback
- Register
http://127.0.0.1/callback. Your app listens on any free port and useshttp://127.0.0.1:<port>/callbackas the redirect URI: the port doesn't have to match. Works in every language with no installer changes. - app scheme
- Register your own scheme, like
com.yourcompany.app:/callback(reverse domain name, so it doesn't clash). The browser asks the user to open your app, which receives the URL. Needs the scheme registered with the OS (e.g. Electron'sapp.setAsDefaultProtocolClient).
With @chabi/js in Node or Electron
import { Chabi } from "@chabi/js/node";import { app, shell } from "electron";import OpenAI from "openai";const chabi = new Chabi({clientId: "<your client_id>",storage: keychainStorage, // { load, save, clear }: encrypt with safeStorageopenBrowser: (url) => shell.openExternal(url),onReturn: () => { win.show(); app.focus({ steal: true }); },});await chabi.load();if (!chabi.signedIn) await chabi.signIn(); // system browser, back on 127.0.0.1const client = new OpenAI(chabi.openai());
Register http://127.0.0.1/callback as a redirect URI. Outside Electron, memoryStorage() from the same package keeps the tokens for one run.
Loopback by hand
import http from "node:http";import crypto from "node:crypto";import open from "open"; // opens the system browser (in Electron: shell.openExternal)const verifier = crypto.randomBytes(32).toString("base64url");const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");const state = crypto.randomBytes(16).toString("base64url");// Any free port on this machine.const server = http.createServer();await new Promise((ready) => server.listen(0, "127.0.0.1", ready));const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;await open("https://chabi.dev/oauth/authorize?" + new URLSearchParams({response_type: "code",client_id: "<your client_id>",redirect_uri: redirectUri,code_challenge: challenge,code_challenge_method: "S256",state,}));// The browser comes back here after the user allows (or denies) your app.const params = await new Promise((done) => server.on("request", (req, res) => {const url = new URL(req.url, redirectUri);if (url.pathname !== "/callback") return res.writeHead(404).end();res.end("Signed in. You can close this tab and go back to the app.");server.close();done(url.searchParams);}));if (params.get("state") !== state) throw new Error("Sign-in didn't come from this app.");if (params.get("error")) {throw new Error(params.get("error_description") ?? "Sign-in was cancelled.");}const res = await fetch("https://chabi.dev/oauth/token", {method: "POST",body: new URLSearchParams({grant_type: "authorization_code",code: params.get("code"),redirect_uri: redirectUri, // the same one, port includedclient_id: "<your client_id>",code_verifier: verifier,}),});const { access_token: userToken, refresh_token, expires_in } = await res.json();
- When the browser comes back to your callback, bring your app's window to the front before answering the tab (in Electron:
win.show()andapp.focus({ steal: true })), and have the tab say the user can close it. Then they're back in your app without hunting for it. - Keep both tokens in the OS keychain (macOS Keychain, Windows Credential Manager; in Electron,
safeStorage), not in a plain file. Refresh as for websites, above. - Then call models exactly as in REQUESTS, from your app's own code. There's no secret to protect: the token only spends this user's credits in your app.