@chabi/js 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +160 -2
- package/dist/browser.cjs +620 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +42 -0
- package/dist/browser.d.ts +42 -0
- package/dist/browser.js +277 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-PTMH3FUL.js +334 -0
- package/dist/chunk-PTMH3FUL.js.map +1 -0
- package/dist/errors-CfeLVOW7.d.cts +132 -0
- package/dist/errors-CfeLVOW7.d.ts +132 -0
- package/dist/node.cjs +470 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.cts +36 -0
- package/dist/node.d.ts +36 -0
- package/dist/node.js +117 -0
- package/dist/node.js.map +1 -0
- package/package.json +65 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/browser.ts","../src/errors.ts","../src/client.ts","../src/pkce.ts","../src/session.ts","../src/button.ts"],"sourcesContent":["// \"Sign in with Chabi\" in the browser: redirect sign-in, tokens in localStorage, one refresh at a time across tabs.\nimport { ChabiBase, DEFAULT_BASE_URL } from \"./client.js\";\nimport { ChabiError } from \"./errors.js\";\nimport { challengeFor, randomString } from \"./pkce.js\";\nimport { SessionCore } from \"./session.js\";\nimport type { RefreshLock, TokenStorage, Tokens } from \"./types.js\";\n\nexport { ChabiError, describeError, describeResponse } from \"./errors.js\";\nexport { signInButton } from \"./button.js\";\nexport type * from \"./types.js\";\nexport type { ChabiBase } from \"./client.js\";\n\n/** How long a started sign-in stays valid: the user may take a while to log in or open an email link. */\nconst PENDING_MAX_AGE_MS = 15 * 60 * 1000;\n\nexport type BrowserOptions = {\n /** From the developer portal. */\n clientId: string;\n /** Where Chabi sends the user back. It must exactly match one registered for the app. */\n redirectUri: string;\n baseUrl?: string;\n /** Replaces localStorage. Without it, the SDK also follows sign-in and sign-out in other tabs. */\n storage?: TokenStorage;\n /** Replaces the Web Locks lock that keeps refreshes one at a time across tabs. */\n lock?: RefreshLock;\n};\n\ntype Pending = { verifier: string; createdAt: number };\n\nexport class Chabi extends ChabiBase {\n private readonly clientId: string;\n private readonly redirectUri: string;\n private readonly baseUrl: string;\n private readonly store: ReturnType<typeof safeStore>;\n private readonly pending = pendingStore();\n private finishing: Promise<boolean> | undefined;\n\n constructor(opts: BrowserOptions) {\n const store = safeStore();\n const tokensKey = `chabi.${opts.clientId}.tokens`;\n const storage = opts.storage ?? tokenStorage(store, tokensKey);\n const lock = opts.lock ?? webLock(`chabi-refresh:${opts.clientId}`);\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n super(new SessionCore({ baseUrl, clientId: opts.clientId, storage, lock }));\n this.store = store;\n this.clientId = opts.clientId;\n this.redirectUri = opts.redirectUri;\n this.baseUrl = baseUrl;\n if (!opts.storage && typeof window !== \"undefined\") {\n // Another tab signed in, signed out or refreshed. (A null key means that tab cleared all of localStorage.)\n window.addEventListener(\"storage\", (e) => {\n if (e.key === tokensKey || e.key === null) this.core.adopt(storage.load() as Tokens | null);\n });\n }\n }\n\n /** Sends the user to Chabi to sign in and allow this app. They come back to `redirectUri`. */\n async signIn(): Promise<void> {\n const verifier = randomString();\n const state = randomString();\n this.prunePending();\n this.pending.set(this.pendingKey(state), JSON.stringify({ verifier, createdAt: Date.now() } satisfies Pending));\n const url = new URL(`${this.baseUrl}/oauth/authorize`);\n url.search = new URLSearchParams({\n response_type: \"code\",\n client_id: this.clientId,\n redirect_uri: this.redirectUri,\n code_challenge: await challengeFor(verifier),\n code_challenge_method: \"S256\",\n state,\n }).toString();\n window.location.assign(url.toString());\n }\n\n /**\n * Call on every page load. If this load is the return from Chabi, finishes the sign-in and returns true;\n * otherwise returns false. Throws a ChabiError (kind `access_denied` when the user declined) if it fails.\n */\n handleRedirect(): Promise<boolean> {\n return (this.finishing ??= this.finish());\n }\n\n private async finish(): Promise<boolean> {\n const params = new URLSearchParams(window.location.search);\n if (!params.has(\"code\") && !params.has(\"error\")) return false;\n const code = params.get(\"code\");\n const state = params.get(\"state\") ?? \"\";\n const error = params.get(\"error\");\n\n // Don't leave the code in the address bar or history; keep the app's own query parameters.\n for (const k of [\"code\", \"state\", \"error\", \"error_description\", \"iss\"]) params.delete(k);\n const rest = params.toString();\n window.history.replaceState(window.history.state, \"\", window.location.pathname + (rest ? `?${rest}` : \"\") + window.location.hash);\n\n // One attempt per state: the entry goes whatever happens next.\n const pending = state ? parsePending(this.pending.get(this.pendingKey(state))) : null;\n if (state) this.pending.del(this.pendingKey(state));\n this.prunePending();\n\n if (!pending || Date.now() - pending.createdAt > PENDING_MAX_AGE_MS) {\n throw new ChabiError({ kind: \"signed_out\", status: 0, code: \"sign_in_not_started\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n if (error === \"access_denied\") {\n throw new ChabiError({ kind: \"access_denied\", status: 0, code: \"access_denied\", message: \"You chose not to let this app use your Chabi plan.\" });\n }\n if (error || !code) {\n throw new ChabiError({ kind: \"signed_out\", status: 0, code: error ?? \"sign_in_failed\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n await this.core.exchangeCode({ code, redirectUri: this.redirectUri, verifier: pending.verifier });\n return true;\n }\n\n private pendingKey(state: string) {\n return `chabi.${this.clientId}.signin.${state}`;\n }\n\n private prunePending() {\n const prefix = `chabi.${this.clientId}.signin.`;\n for (const key of this.pending.keys()) {\n if (!key.startsWith(prefix)) continue;\n const p = parsePending(this.pending.get(key));\n if (!p || Date.now() - p.createdAt > PENDING_MAX_AGE_MS) this.pending.del(key);\n }\n }\n}\n\nfunction parsePending(raw: string | null): Pending | null {\n try {\n const p = JSON.parse(raw ?? \"null\") as Pending | null;\n return p && typeof p.verifier === \"string\" && typeof p.createdAt === \"number\" ? p : null;\n } catch {\n return null;\n }\n}\n\n/** localStorage that never throws: when it's unavailable (private mode, blocked storage), a page-lifetime copy. */\nfunction safeStore() {\n const memory = new Map<string, string>();\n const ls = (): Storage | null => {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n };\n // The memory copy is used only for keys localStorage failed on, so changes made by other tabs are never hidden.\n return {\n get(key: string): string | null {\n if (memory.has(key)) return memory.get(key)!;\n try {\n return ls()?.getItem(key) ?? null;\n } catch {\n return null;\n }\n },\n set(key: string, value: string) {\n try {\n const s = ls();\n if (!s) throw new Error(\"no localStorage\");\n s.setItem(key, value);\n memory.delete(key);\n } catch {\n memory.set(key, value);\n }\n },\n del(key: string) {\n memory.delete(key);\n try {\n ls()?.removeItem(key);\n } catch {\n /* nothing to do */\n }\n },\n keys(): string[] {\n const out = new Set(memory.keys());\n try {\n const s = ls();\n for (let i = 0; s && i < s.length; i++) {\n const k = s.key(i);\n if (k) out.add(k);\n }\n } catch {\n /* memory only */\n }\n return [...out];\n },\n };\n}\n\n/**\n * Where a started sign-in waits for the user to come back. It must outlive the page (the return is a fresh load,\n * often in another tab), so memory won't do: localStorage, else sessionStorage, which survives the trip to Chabi\n * in the same tab. With neither, sign-in can't finish, and signIn says so instead of looping.\n */\nfunction pendingStore() {\n const stores = (): Storage[] => {\n const out: Storage[] = [];\n for (const get of [() => localStorage, () => sessionStorage]) {\n try {\n const s = get();\n if (s) out.push(s);\n } catch {\n /* unavailable */\n }\n }\n return out;\n };\n return {\n get(key: string): string | null {\n for (const s of stores()) {\n try {\n const v = s.getItem(key);\n if (v !== null) return v;\n } catch {\n /* try the next */\n }\n }\n return null;\n },\n set(key: string, value: string) {\n for (const s of stores()) {\n try {\n s.setItem(key, value);\n return;\n } catch {\n /* try the next */\n }\n }\n throw new ChabiError({\n kind: \"signed_out\",\n status: 0,\n code: \"storage_blocked\",\n message: \"This browser is blocking storage, so sign-in can't finish. Allow site data for this page, or use a normal (not private) window.\",\n });\n },\n del(key: string) {\n for (const s of stores()) {\n try {\n s.removeItem(key);\n } catch {\n /* nothing to do */\n }\n }\n },\n keys(): string[] {\n const out = new Set<string>();\n for (const s of stores()) {\n try {\n for (let i = 0; i < s.length; i++) {\n const k = s.key(i);\n if (k) out.add(k);\n }\n } catch {\n /* skip */\n }\n }\n return [...out];\n },\n };\n}\n\nfunction tokenStorage(store: ReturnType<typeof safeStore>, key: string): TokenStorage {\n return {\n load() {\n try {\n const t = JSON.parse(store.get(key) ?? \"null\") as Tokens | null;\n return t && typeof t.accessToken === \"string\" && typeof t.refreshToken === \"string\" && Number.isFinite(t.expiresAt) ? t : null;\n } catch {\n return null;\n }\n },\n save: (t) => store.set(key, JSON.stringify(t)),\n clear: () => store.del(key),\n };\n}\n\n/** Web Locks across tabs; without them (rare, older browsers), a lock within this page. */\nfunction webLock(name: string): RefreshLock {\n let tail: Promise<unknown> = Promise.resolve();\n const inPage: RefreshLock = (run) => {\n const next = tail.then(run, run);\n tail = next.catch(() => undefined);\n return next;\n };\n return (run) => {\n const locks = typeof navigator === \"undefined\" ? undefined : (navigator as Navigator & { locks?: LockManager }).locks;\n return locks ? (locks.request(name, run) as ReturnType<typeof run>) : inPage(run);\n };\n}\n","import type { ChabiErrorInfo, ErrorKind } from \"./types.js\";\n\n/** An error the SDK raises itself. `info` is what `describeError` returns for it. */\nexport class ChabiError extends Error {\n readonly info: ChabiErrorInfo;\n constructor(info: ChabiErrorInfo) {\n super(info.message);\n this.name = \"ChabiError\";\n this.info = info;\n }\n}\n\nconst MESSAGES: Record<ErrorKind, string> = {\n out_of_credits: \"You're out of Chabi credits.\",\n app_limit: \"You've reached the monthly limit you set for this app on Chabi.\",\n signed_out: \"Sign in with Chabi to continue.\",\n access_denied: \"You chose not to let this app use your Chabi plan.\",\n rate_limited: \"Too many requests. Please wait a moment and try again.\",\n app_suspended: \"This app can't use Chabi right now.\",\n bad_request: \"Chabi couldn't handle that request.\",\n provider_error: \"The AI provider is having trouble right now. Please try again.\",\n network: \"Couldn't reach Chabi. Check your connection and try again.\",\n unknown: \"Something went wrong. Please try again.\",\n};\n\ntype GatewayBody = { code?: unknown; message?: unknown; upgrade_url?: unknown; manage_url?: unknown };\n\nconst str = (v: unknown) => (typeof v === \"string\" && v ? v : undefined);\n\nfunction kindOf(status: number, code: string | undefined): ErrorKind {\n if (code === \"insufficient_credits\") return \"out_of_credits\";\n if (code === \"app_limit_reached\") return \"app_limit\";\n if (code === \"app_suspended\") return \"app_suspended\";\n if (status === 401) return \"signed_out\";\n if (status === 402) return \"out_of_credits\";\n if (status === 403) return \"app_suspended\";\n if (status === 429) return \"rate_limited\";\n if (status >= 500) return \"provider_error\";\n if (status >= 400) return \"bad_request\";\n return \"unknown\";\n}\n\nfunction build(status: number, body: GatewayBody | undefined, retryAfterHeader: string | null | undefined): ChabiErrorInfo {\n const code = str(body?.code);\n const kind = kindOf(status, code);\n const info: ChabiErrorInfo = { kind, status, message: MESSAGES[kind] };\n if (code) info.code = code;\n const upgradeUrl = str(body?.upgrade_url);\n const manageUrl = str(body?.manage_url);\n if (upgradeUrl) info.upgradeUrl = upgradeUrl;\n if (manageUrl) info.manageUrl = manageUrl;\n const retryAfter = Number(retryAfterHeader);\n if (kind === \"rate_limited\" && retryAfterHeader && Number.isFinite(retryAfter)) info.retryAfter = retryAfter;\n return info;\n}\n\n/**\n * Any error from a Chabi request in one shape: an OpenAI or Anthropic SDK error, a ChabiError, a failed fetch.\n * For a `Response` you got from `chabi.fetch` yourself, use `describeResponse`.\n */\nexport function describeError(e: unknown): ChabiErrorInfo {\n if (e instanceof ChabiError) return e.info.message ? e.info : { ...e.info, message: MESSAGES[e.info.kind] };\n // The official SDKs wrap anything chabi.fetch throws (a failed refresh, say) in their own connection error.\n const cause = (e as { cause?: unknown } | null)?.cause;\n if (cause instanceof ChabiError) return describeError(cause);\n const x = e as { status?: unknown; error?: unknown; headers?: unknown; name?: unknown } | null;\n if (x && typeof x === \"object\" && typeof x.status === \"number\") {\n // OpenAI's SDK puts the gateway's `error` object in err.error; Anthropic's puts the whole body there.\n const outer = x.error as { error?: GatewayBody } & GatewayBody | undefined;\n const body = outer && typeof outer.error === \"object\" ? outer.error : outer;\n const headers = x.headers as { get?: (k: string) => string | null } | Record<string, string> | undefined;\n const retry = typeof (headers as Headers | undefined)?.get === \"function\"\n ? (headers as Headers).get(\"retry-after\")\n : (headers as Record<string, string> | undefined)?.[\"retry-after\"];\n return build(x.status, body, retry);\n }\n // A failed fetch, or the SDKs' APIConnectionError (and its timeout subclass) wrapping one.\n const ctor = (x as { constructor?: { name?: unknown } } | null)?.constructor?.name;\n if (e instanceof TypeError || (typeof ctor === \"string\" && /Connection|Timeout/.test(ctor))) {\n return { kind: \"network\", status: 0, message: MESSAGES.network };\n }\n return { kind: \"unknown\", status: 0, message: MESSAGES.unknown };\n}\n\n/** `describeError` for a `Response`, such as one from `chabi.fetch` that wasn't ok. */\nexport async function describeResponse(res: Response): Promise<ChabiErrorInfo> {\n const body = (await res.clone().json().catch(() => null)) as { error?: GatewayBody } | null;\n return build(res.status, body?.error, res.headers.get(\"retry-after\"));\n}\n","import { ChabiError, describeResponse } from \"./errors.js\";\nimport type { SessionCore } from \"./session.js\";\nimport type { ChangeListener } from \"./types.js\";\n\n/** Where Chabi lives unless an app says otherwise. */\nexport const DEFAULT_BASE_URL = \"https://chabi.dev\";\n\n/** 401 codes that mean the user's access is gone: refreshing can't help, so the SDK signs out. */\nexport const SIGN_OUT_CODES = new Set([\"missing_token\", \"token_revoked\", \"grant_revoked\", \"unknown_app\"]);\n\n/** The placeholder API key handed to the official SDKs. `fetch` replaces it with the user's token. */\nconst PLACEHOLDER_KEY = \"chabi\";\n\ntype SdkConfig = { baseURL: string; apiKey: string; fetch: typeof fetch };\n\n/** What the browser and Node clients share: requests with the user's token, account calls and sign-out. */\nexport class ChabiBase {\n /** A fetch for the official SDKs. It only sets Authorization: bodies, models and other headers pass through. */\n readonly fetch: typeof fetch;\n\n constructor(protected readonly core: SessionCore) {\n this.fetch = (input, init) => this.authorizedFetch(input, init);\n }\n\n get signedIn(): boolean {\n return this.core.signedIn;\n }\n\n /** Options for `new OpenAI(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */\n openai(): SdkConfig {\n return { baseURL: `${this.core.baseUrl}/v1`, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };\n }\n\n /** Options for `new Anthropic(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */\n anthropic(): SdkConfig {\n return { baseURL: this.core.baseUrl, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };\n }\n\n /** The user's credit balance. */\n async credits(): Promise<number> {\n const body = (await this.getJson(\"/v1/credits\")) as { balance_credits: number };\n return body.balance_credits;\n }\n\n /** The display name on the user's Chabi account, or null if they haven't set one. */\n async me(): Promise<{ name: string | null }> {\n const body = (await this.getJson(\"/v1/me\")) as { name?: string | null };\n return { name: body.name ?? null };\n }\n\n /** Signs the user out of this app on this device. */\n signOut(): Promise<void> {\n return this.core.end(\"signed_out\");\n }\n\n /** Called when the user is signed in or out, here or in another tab. Returns a function that unsubscribes. */\n onChange(listener: ChangeListener): () => void {\n return this.core.onChange(listener);\n }\n\n protected async getJson(path: string): Promise<unknown> {\n const res = await this.fetch(`${this.core.baseUrl}${path}`);\n if (!res.ok) throw new ChabiError(await describeResponse(res));\n return res.json();\n }\n\n private async authorizedFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n // The user's token only ever goes to Chabi, even if an app points an SDK somewhere else.\n if (!this.isChabi(input)) return this.core.fetchImpl(input, init);\n\n let token = await this.core.accessToken();\n // Answered like the gateway would, so the official SDKs raise their normal 401 error, without retrying.\n if (!token) return signedOutResponse();\n\n // A Request carries its body as a stream; clone it now so it can be sent again after a refresh.\n const spare = input instanceof Request ? input.clone() : null;\n const replayable = !(init?.body instanceof ReadableStream);\n\n let res = await this.send(input, init, token);\n if (res.status !== 401) return res;\n\n let code = await errorCode(res);\n if (code === \"invalid_token\") {\n const fresh = await this.core.refreshAfterReject(token);\n if (!fresh || !replayable) return res; // signed out by the refresh, or a stream body that's already spent\n token = fresh;\n res = await this.send(spare ?? input, init, token);\n if (res.status !== 401) return res;\n code = await errorCode(res);\n }\n if (code && SIGN_OUT_CODES.has(code)) await this.core.end(\"access_removed\");\n return res;\n }\n\n private isChabi(input: RequestInfo | URL): boolean {\n try {\n const url = new URL(input instanceof Request ? input.url : String(input));\n return url.origin === new URL(this.core.baseUrl).origin;\n } catch {\n return false;\n }\n }\n\n private send(input: RequestInfo | URL, init: RequestInit | undefined, token: string): Promise<Response> {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n headers.set(\"Authorization\", `Bearer ${token}`);\n headers.delete(\"x-api-key\"); // the Anthropic SDK's placeholder key\n return this.core.fetchImpl(input, { ...init, headers });\n }\n}\n\nconst signedOutResponse = () =>\n new Response(JSON.stringify({ error: { code: \"missing_token\", message: \"Sign in with Chabi to continue.\" } }), {\n status: 401,\n headers: { \"Content-Type\": \"application/json\", \"x-should-retry\": \"false\" },\n });\n\nasync function errorCode(res: Response): Promise<string | undefined> {\n const body = (await res.clone().json().catch(() => null)) as { error?: { code?: unknown } } | null;\n return typeof body?.error?.code === \"string\" ? body.error.code : undefined;\n}\n","// PKCE (RFC 7636) on Web Crypto, which browsers and Node 20+ both have as globalThis.crypto.\n\nconst base64url = (bytes: Uint8Array): string => {\n let s = \"\";\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\n\n/** A random base64url string: 32 bytes gives 43 characters, the verifier length RFC 7636 recommends. */\nexport function randomString(bytes = 32): string {\n return base64url(globalThis.crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\n/** The S256 code challenge for a verifier: base64url(SHA-256(verifier)). */\nexport async function challengeFor(verifier: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n return base64url(new Uint8Array(digest));\n}\n","import { ChabiError } from \"./errors.js\";\nimport type { ChangeListener, ChangeReason, RefreshLock, TokenStorage, Tokens } from \"./types.js\";\n\n/** Refresh this long before the access token expires, so a request never goes out with one about to lapse. */\nexport const REFRESH_EARLY_MS = 60_000;\n\nexport type SessionOptions = {\n baseUrl: string;\n clientId: string;\n storage: TokenStorage;\n lock: RefreshLock;\n fetch?: typeof fetch;\n now?: () => number;\n};\n\ntype TokenResponse = { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown };\n\n/**\n * The signed-in user's tokens and everything that changes them. Each refresh token works once, and the gateway\n * ends the whole sign-in when one is sent twice, so every refresh runs inside `lock` and first rereads storage:\n * if another tab (or caller) already refreshed, its tokens are used instead.\n */\nexport class SessionCore {\n readonly baseUrl: string;\n readonly clientId: string;\n private readonly storage: TokenStorage;\n private readonly lock: RefreshLock;\n /** The underlying fetch, for requests that carry the user's token (see ChabiBase.fetch). */\n readonly fetchImpl: typeof fetch;\n private readonly now: () => number;\n private tokens: Tokens | null = null;\n // Bumped by sign-in and sign-out, so a refresh that finishes afterwards can't bring an old session back.\n private generation = 0;\n private readonly listeners = new Set<ChangeListener>();\n\n constructor(opts: SessionOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.clientId = opts.clientId;\n this.storage = opts.storage;\n this.lock = opts.lock;\n this.fetchImpl = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));\n this.now = opts.now ?? Date.now;\n // Synchronous storage (the browser's) is read at once, so `signedIn` is right from the start.\n const loaded = this.storage.load();\n if (!isPromise(loaded)) this.tokens = loaded;\n else loaded.catch(() => {}); // asynchronous storage is read by load(); a failure here must not crash the app\n }\n\n get signedIn(): boolean {\n return this.tokens !== null;\n }\n\n /** Reads storage into memory. Needed once at start for asynchronous storage (Node, Electron). */\n async load(): Promise<void> {\n this.tokens = await this.storage.load();\n }\n\n /** The access token to send, refreshed first when it's within a minute of expiring. Null when signed out. */\n async accessToken(): Promise<string | null> {\n const t = this.tokens;\n if (!t) return null;\n if (t.expiresAt - this.now() > REFRESH_EARLY_MS) return t.accessToken;\n return this.refreshLocked(t.refreshToken, null);\n }\n\n /** The gateway said `rejected` is no longer valid: refresh, unless that already happened since it was sent. */\n async refreshAfterReject(rejected: string): Promise<string | null> {\n const t = this.tokens;\n if (!t) return null;\n if (t.accessToken !== rejected) return t.accessToken;\n return this.refreshLocked(t.refreshToken, rejected);\n }\n\n /** Swaps the code from the sign-in redirect for tokens, saves them and tells listeners. */\n async exchangeCode(p: { code: string; redirectUri: string; verifier: string }): Promise<void> {\n const res = await this.tokenRequest({\n grant_type: \"authorization_code\",\n code: p.code,\n redirect_uri: p.redirectUri,\n client_id: this.clientId,\n code_verifier: p.verifier,\n });\n const tokens = res.ok ? await this.parseTokens(res) : null;\n if (!tokens) {\n throw new ChabiError({ kind: \"signed_out\", status: res.status, code: \"sign_in_failed\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n this.generation += 1;\n await this.storage.save(tokens);\n this.tokens = tokens;\n this.emit(true, \"signed_in\");\n }\n\n /** Forgets the tokens (memory and storage) and tells listeners why. */\n async end(reason: ChangeReason): Promise<void> {\n this.generation += 1;\n const was = this.tokens !== null;\n this.tokens = null;\n await this.storage.clear();\n if (was) this.emit(false, reason);\n }\n\n /** Another tab changed the stored tokens: take its copy, and tell listeners if that signed the user in or out. */\n adopt(tokens: Tokens | null): void {\n const was = this.tokens !== null;\n if (!tokens) this.generation += 1;\n this.tokens = tokens;\n if (was !== (tokens !== null)) this.emit(tokens !== null, tokens ? \"signed_in\" : \"signed_out\");\n }\n\n onChange(listener: ChangeListener): () => void {\n this.listeners.add(listener);\n return () => void this.listeners.delete(listener);\n }\n\n private emit(signedIn: boolean, reason: ChangeReason): void {\n for (const l of [...this.listeners]) {\n try {\n l(signedIn, reason);\n } catch {\n // A listener's own error must not break sign-in or a request.\n }\n }\n }\n\n private refreshLocked(startedWith: string, rejected: string | null): Promise<string | null> {\n return this.lock(async () => {\n const generation = this.generation;\n const stored = await this.storage.load();\n if (generation !== this.generation) return null;\n if (!stored) {\n this.adopt(null); // signed out elsewhere\n return null;\n }\n if (stored.refreshToken !== startedWith) {\n // Someone else refreshed while this caller waited for the lock: use theirs, never resend ours.\n this.tokens = stored;\n return stored.accessToken;\n }\n if (rejected === null && stored.expiresAt - this.now() > REFRESH_EARLY_MS) {\n this.tokens = stored;\n return stored.accessToken;\n }\n\n const res = await this.tokenRequest({ grant_type: \"refresh_token\", refresh_token: stored.refreshToken, client_id: this.clientId });\n if (generation !== this.generation) return null; // signed out while the request was out\n if (!res.ok) {\n if (res.status === 400 || res.status === 401) {\n await this.end(\"expired\");\n return null;\n }\n throw new ChabiError({ kind: \"provider_error\", status: res.status, message: \"Chabi is having trouble right now. Please try again.\" });\n }\n const fresh = await this.parseTokens(res);\n if (generation !== this.generation) return null; // signed out while the reply was read\n if (!fresh) throw new ChabiError({ kind: \"unknown\", status: res.status, message: \"Chabi sent an unexpected reply. Please try again.\" });\n await this.storage.save(fresh); // at once: the old refresh token is already spent\n if (generation !== this.generation) {\n // Signed out while saving: take back what this refresh wrote, but never a newer sign-in's tokens.\n if ((await this.storage.load())?.refreshToken === fresh.refreshToken) await this.storage.clear();\n return null;\n }\n this.tokens = fresh;\n return fresh.accessToken;\n });\n }\n\n private async tokenRequest(fields: Record<string, string>): Promise<Response> {\n try {\n return await this.fetchImpl(`${this.baseUrl}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(fields).toString(),\n });\n } catch {\n throw new ChabiError({ kind: \"network\", status: 0, message: \"Couldn't reach Chabi. Check your connection and try again.\" });\n }\n }\n\n private async parseTokens(res: Response): Promise<Tokens | null> {\n const b = (await res.json().catch(() => ({}))) as TokenResponse;\n if (typeof b.access_token !== \"string\" || typeof b.refresh_token !== \"string\" || typeof b.expires_in !== \"number\") return null;\n return { accessToken: b.access_token, refreshToken: b.refresh_token, expiresAt: this.now() + b.expires_in * 1000 };\n }\n}\n\nconst isPromise = <T>(v: T | Promise<T>): v is Promise<T> => typeof (v as { then?: unknown })?.then === \"function\";\n","// The required \"Sign in with Chabi\" button: the Chabi key logo, then the words. These strings are the ones the\n// docs give developers (gateway/src/docs.ts BUTTON_CSS, gateway/src/icon.ts signInLogoSvg), and a gateway test\n// checks they stay the same. Don't redraw, recolor, stretch or crop the logo.\n\nconst MASK = `<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\"/>`;\n\nexport const SIGN_IN_LOGO_SVG = `<svg width=\"22\" height=\"22\" viewBox=\"0 0 100 100\" aria-hidden=\"true\"><mask id=\"chabi-key\">${MASK}</mask><circle cx=\"50\" cy=\"50\" r=\"50\" fill=\"currentColor\" mask=\"url(#chabi-key)\"/></svg>`;\n\nexport const BUTTON_CSS = [\n \".chabi-signin { display: inline-flex; align-items: center; gap: 10px; padding: 10px 18px; border: 0;\",\n \" border-radius: 8px; background: #E0A526; color: #121212; font: 700 16px/1.2 system-ui, sans-serif; cursor: pointer; }\",\n \".chabi-signin:hover { background: #C99520; }\",\n \"/* Dark style: */\",\n \".chabi-signin.dark { background: #121212; color: #FFFFFF; }\",\n \".chabi-signin.dark svg { color: #E0A526; }\",\n];\n\nlet count = 0;\n\n/** The Sign in with Chabi button, gold (default) or dark. Attach your own click handler that calls `chabi.signIn()`. */\nexport function signInButton(opts: { style?: \"gold\" | \"dark\"; label?: string } = {}): HTMLButtonElement {\n if (!document.querySelector(\"style[data-chabi-signin]\")) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-chabi-signin\", \"\");\n style.textContent = BUTTON_CSS.join(\"\\n\");\n document.head.appendChild(style);\n }\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.className = opts.style === \"dark\" ? \"chabi-signin dark\" : \"chabi-signin\";\n // Each button gets its own mask id: two masks with one id on a page make the second logo disappear.\n const id = `chabi-key-${++count}`;\n button.innerHTML = SIGN_IN_LOGO_SVG.replace('id=\"chabi-key\"', `id=\"${id}\"`).replace(\"url(#chabi-key)\", `url(#${id})`);\n button.append(opts.label ?? \"Sign in with Chabi\");\n return button;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAC3B;AAAA,EACT,YAAY,MAAsB;AAChC,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,WAAsC;AAAA,EAC1C,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,cAAc;AAAA,EACd,eAAe;AAAA,EACf,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,SAAS;AAAA,EACT,SAAS;AACX;AAIA,IAAM,MAAM,CAAC,MAAgB,OAAO,MAAM,YAAY,IAAI,IAAI;AAE9D,SAAS,OAAO,QAAgB,MAAqC;AACnE,MAAI,SAAS,uBAAwB,QAAO;AAC5C,MAAI,SAAS,oBAAqB,QAAO;AACzC,MAAI,SAAS,gBAAiB,QAAO;AACrC,MAAI,WAAW,IAAK,QAAO;AAC3B,MAAI,WAAW,IAAK,QAAO;AAC3B,MAAI,WAAW,IAAK,QAAO;AAC3B,MAAI,WAAW,IAAK,QAAO;AAC3B,MAAI,UAAU,IAAK,QAAO;AAC1B,MAAI,UAAU,IAAK,QAAO;AAC1B,SAAO;AACT;AAEA,SAAS,MAAM,QAAgB,MAA+B,kBAA6D;AACzH,QAAM,OAAO,IAAI,MAAM,IAAI;AAC3B,QAAM,OAAO,OAAO,QAAQ,IAAI;AAChC,QAAM,OAAuB,EAAE,MAAM,QAAQ,SAAS,SAAS,IAAI,EAAE;AACrE,MAAI,KAAM,MAAK,OAAO;AACtB,QAAM,aAAa,IAAI,MAAM,WAAW;AACxC,QAAM,YAAY,IAAI,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AAG,IAAI,EAAE,QAAQ,KAAK;AACjC,kBAAM,IAAI,EAAE,IAAI,CAAC;AACjB,gBAAI,EAAG,KAAI,IAAI,CAAC;AAAA,UAClB;AAAA,QACF,QAAQ;AAAA,QAER;AAAA,MACF;AACA,aAAO,CAAC,GAAG,GAAG;AAAA,IAChB;AAAA,EACF;AACF;AAEA,SAAS,aAAa,OAAqC,KAA2B;AACpF,SAAO;AAAA,IACL,OAAO;AACL,UAAI;AACF,cAAM,IAAI,KAAK,MAAM,MAAM,IAAI,GAAG,KAAK,MAAM;AAC7C,eAAO,KAAK,OAAO,EAAE,gBAAgB,YAAY,OAAO,EAAE,iBAAiB,YAAY,OAAO,SAAS,EAAE,SAAS,IAAI,IAAI;AAAA,MAC5H,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,MAAM,CAAC,MAAM,MAAM,IAAI,KAAK,KAAK,UAAU,CAAC,CAAC;AAAA,IAC7C,OAAO,MAAM,MAAM,IAAI,GAAG;AAAA,EAC5B;AACF;AAGA,SAAS,QAAQ,MAA2B;AAC1C,MAAI,OAAyB,QAAQ,QAAQ;AAC7C,QAAM,SAAsB,CAAC,QAAQ;AACnC,UAAM,OAAO,KAAK,KAAK,KAAK,GAAG;AAC/B,WAAO,KAAK,MAAM,MAAM,MAAS;AACjC,WAAO;AAAA,EACT;AACA,SAAO,CAAC,QAAQ;AACd,UAAM,QAAQ,OAAO,cAAc,cAAc,SAAa,UAAkD;AAChH,WAAO,QAAS,MAAM,QAAQ,MAAM,GAAG,IAA+B,OAAO,GAAG;AAAA,EAClF;AACF;","names":[]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { T as TokenStorage, R as RefreshLock, C as ChabiBase } from './errors-CfeLVOW7.cjs';
|
|
2
|
+
export { a as ChabiError, b as ChabiErrorInfo, c as ChangeListener, d as ChangeReason, E as ErrorKind, e as Tokens, f as describeError, g as describeResponse } from './errors-CfeLVOW7.cjs';
|
|
3
|
+
|
|
4
|
+
/** The Sign in with Chabi button, gold (default) or dark. Attach your own click handler that calls `chabi.signIn()`. */
|
|
5
|
+
declare function signInButton(opts?: {
|
|
6
|
+
style?: "gold" | "dark";
|
|
7
|
+
label?: string;
|
|
8
|
+
}): HTMLButtonElement;
|
|
9
|
+
|
|
10
|
+
type BrowserOptions = {
|
|
11
|
+
/** From the developer portal. */
|
|
12
|
+
clientId: string;
|
|
13
|
+
/** Where Chabi sends the user back. It must exactly match one registered for the app. */
|
|
14
|
+
redirectUri: string;
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
/** Replaces localStorage. Without it, the SDK also follows sign-in and sign-out in other tabs. */
|
|
17
|
+
storage?: TokenStorage;
|
|
18
|
+
/** Replaces the Web Locks lock that keeps refreshes one at a time across tabs. */
|
|
19
|
+
lock?: RefreshLock;
|
|
20
|
+
};
|
|
21
|
+
declare class Chabi extends ChabiBase {
|
|
22
|
+
private readonly clientId;
|
|
23
|
+
private readonly redirectUri;
|
|
24
|
+
private readonly baseUrl;
|
|
25
|
+
private readonly store;
|
|
26
|
+
private readonly pending;
|
|
27
|
+
private finishing;
|
|
28
|
+
constructor(opts: BrowserOptions);
|
|
29
|
+
/** Sends the user to Chabi to sign in and allow this app. They come back to `redirectUri`. */
|
|
30
|
+
signIn(): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Call on every page load. If this load is the return from Chabi, finishes the sign-in and returns true;
|
|
33
|
+
* otherwise returns false. Throws a ChabiError (kind `access_denied` when the user declined) if it fails.
|
|
34
|
+
*/
|
|
35
|
+
handleRedirect(): Promise<boolean>;
|
|
36
|
+
private finish;
|
|
37
|
+
private pendingKey;
|
|
38
|
+
private prunePending;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export { Chabi, ChabiBase, RefreshLock, TokenStorage, signInButton };
|
|
42
|
+
export type { BrowserOptions };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { T as TokenStorage, R as RefreshLock, C as ChabiBase } from './errors-CfeLVOW7.js';
|
|
2
|
+
export { a as ChabiError, b as ChabiErrorInfo, c as ChangeListener, d as ChangeReason, E as ErrorKind, e as Tokens, f as describeError, g as describeResponse } from './errors-CfeLVOW7.js';
|
|
3
|
+
|
|
4
|
+
/** The Sign in with Chabi button, gold (default) or dark. Attach your own click handler that calls `chabi.signIn()`. */
|
|
5
|
+
declare function signInButton(opts?: {
|
|
6
|
+
style?: "gold" | "dark";
|
|
7
|
+
label?: string;
|
|
8
|
+
}): HTMLButtonElement;
|
|
9
|
+
|
|
10
|
+
type BrowserOptions = {
|
|
11
|
+
/** From the developer portal. */
|
|
12
|
+
clientId: string;
|
|
13
|
+
/** Where Chabi sends the user back. It must exactly match one registered for the app. */
|
|
14
|
+
redirectUri: string;
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
/** Replaces localStorage. Without it, the SDK also follows sign-in and sign-out in other tabs. */
|
|
17
|
+
storage?: TokenStorage;
|
|
18
|
+
/** Replaces the Web Locks lock that keeps refreshes one at a time across tabs. */
|
|
19
|
+
lock?: RefreshLock;
|
|
20
|
+
};
|
|
21
|
+
declare class Chabi extends ChabiBase {
|
|
22
|
+
private readonly clientId;
|
|
23
|
+
private readonly redirectUri;
|
|
24
|
+
private readonly baseUrl;
|
|
25
|
+
private readonly store;
|
|
26
|
+
private readonly pending;
|
|
27
|
+
private finishing;
|
|
28
|
+
constructor(opts: BrowserOptions);
|
|
29
|
+
/** Sends the user to Chabi to sign in and allow this app. They come back to `redirectUri`. */
|
|
30
|
+
signIn(): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Call on every page load. If this load is the return from Chabi, finishes the sign-in and returns true;
|
|
33
|
+
* otherwise returns false. Throws a ChabiError (kind `access_denied` when the user declined) if it fails.
|
|
34
|
+
*/
|
|
35
|
+
handleRedirect(): Promise<boolean>;
|
|
36
|
+
private finish;
|
|
37
|
+
private pendingKey;
|
|
38
|
+
private prunePending;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export { Chabi, ChabiBase, RefreshLock, TokenStorage, signInButton };
|
|
42
|
+
export type { BrowserOptions };
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ChabiBase,
|
|
3
|
+
ChabiError,
|
|
4
|
+
DEFAULT_BASE_URL,
|
|
5
|
+
SessionCore,
|
|
6
|
+
challengeFor,
|
|
7
|
+
describeError,
|
|
8
|
+
describeResponse,
|
|
9
|
+
randomString
|
|
10
|
+
} from "./chunk-PTMH3FUL.js";
|
|
11
|
+
|
|
12
|
+
// src/button.ts
|
|
13
|
+
var MASK = `<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"/>`;
|
|
14
|
+
var SIGN_IN_LOGO_SVG = `<svg width="22" height="22" viewBox="0 0 100 100" aria-hidden="true"><mask id="chabi-key">${MASK}</mask><circle cx="50" cy="50" r="50" fill="currentColor" mask="url(#chabi-key)"/></svg>`;
|
|
15
|
+
var BUTTON_CSS = [
|
|
16
|
+
".chabi-signin { display: inline-flex; align-items: center; gap: 10px; padding: 10px 18px; border: 0;",
|
|
17
|
+
" border-radius: 8px; background: #E0A526; color: #121212; font: 700 16px/1.2 system-ui, sans-serif; cursor: pointer; }",
|
|
18
|
+
".chabi-signin:hover { background: #C99520; }",
|
|
19
|
+
"/* Dark style: */",
|
|
20
|
+
".chabi-signin.dark { background: #121212; color: #FFFFFF; }",
|
|
21
|
+
".chabi-signin.dark svg { color: #E0A526; }"
|
|
22
|
+
];
|
|
23
|
+
var count = 0;
|
|
24
|
+
function signInButton(opts = {}) {
|
|
25
|
+
if (!document.querySelector("style[data-chabi-signin]")) {
|
|
26
|
+
const style = document.createElement("style");
|
|
27
|
+
style.setAttribute("data-chabi-signin", "");
|
|
28
|
+
style.textContent = BUTTON_CSS.join("\n");
|
|
29
|
+
document.head.appendChild(style);
|
|
30
|
+
}
|
|
31
|
+
const button = document.createElement("button");
|
|
32
|
+
button.type = "button";
|
|
33
|
+
button.className = opts.style === "dark" ? "chabi-signin dark" : "chabi-signin";
|
|
34
|
+
const id = `chabi-key-${++count}`;
|
|
35
|
+
button.innerHTML = SIGN_IN_LOGO_SVG.replace('id="chabi-key"', `id="${id}"`).replace("url(#chabi-key)", `url(#${id})`);
|
|
36
|
+
button.append(opts.label ?? "Sign in with Chabi");
|
|
37
|
+
return button;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/browser.ts
|
|
41
|
+
var PENDING_MAX_AGE_MS = 15 * 60 * 1e3;
|
|
42
|
+
var Chabi = class extends ChabiBase {
|
|
43
|
+
clientId;
|
|
44
|
+
redirectUri;
|
|
45
|
+
baseUrl;
|
|
46
|
+
store;
|
|
47
|
+
pending = pendingStore();
|
|
48
|
+
finishing;
|
|
49
|
+
constructor(opts) {
|
|
50
|
+
const store = safeStore();
|
|
51
|
+
const tokensKey = `chabi.${opts.clientId}.tokens`;
|
|
52
|
+
const storage = opts.storage ?? tokenStorage(store, tokensKey);
|
|
53
|
+
const lock = opts.lock ?? webLock(`chabi-refresh:${opts.clientId}`);
|
|
54
|
+
const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
55
|
+
super(new SessionCore({ baseUrl, clientId: opts.clientId, storage, lock }));
|
|
56
|
+
this.store = store;
|
|
57
|
+
this.clientId = opts.clientId;
|
|
58
|
+
this.redirectUri = opts.redirectUri;
|
|
59
|
+
this.baseUrl = baseUrl;
|
|
60
|
+
if (!opts.storage && typeof window !== "undefined") {
|
|
61
|
+
window.addEventListener("storage", (e) => {
|
|
62
|
+
if (e.key === tokensKey || e.key === null) this.core.adopt(storage.load());
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Sends the user to Chabi to sign in and allow this app. They come back to `redirectUri`. */
|
|
67
|
+
async signIn() {
|
|
68
|
+
const verifier = randomString();
|
|
69
|
+
const state = randomString();
|
|
70
|
+
this.prunePending();
|
|
71
|
+
this.pending.set(this.pendingKey(state), JSON.stringify({ verifier, createdAt: Date.now() }));
|
|
72
|
+
const url = new URL(`${this.baseUrl}/oauth/authorize`);
|
|
73
|
+
url.search = new URLSearchParams({
|
|
74
|
+
response_type: "code",
|
|
75
|
+
client_id: this.clientId,
|
|
76
|
+
redirect_uri: this.redirectUri,
|
|
77
|
+
code_challenge: await challengeFor(verifier),
|
|
78
|
+
code_challenge_method: "S256",
|
|
79
|
+
state
|
|
80
|
+
}).toString();
|
|
81
|
+
window.location.assign(url.toString());
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Call on every page load. If this load is the return from Chabi, finishes the sign-in and returns true;
|
|
85
|
+
* otherwise returns false. Throws a ChabiError (kind `access_denied` when the user declined) if it fails.
|
|
86
|
+
*/
|
|
87
|
+
handleRedirect() {
|
|
88
|
+
return this.finishing ??= this.finish();
|
|
89
|
+
}
|
|
90
|
+
async finish() {
|
|
91
|
+
const params = new URLSearchParams(window.location.search);
|
|
92
|
+
if (!params.has("code") && !params.has("error")) return false;
|
|
93
|
+
const code = params.get("code");
|
|
94
|
+
const state = params.get("state") ?? "";
|
|
95
|
+
const error = params.get("error");
|
|
96
|
+
for (const k of ["code", "state", "error", "error_description", "iss"]) params.delete(k);
|
|
97
|
+
const rest = params.toString();
|
|
98
|
+
window.history.replaceState(window.history.state, "", window.location.pathname + (rest ? `?${rest}` : "") + window.location.hash);
|
|
99
|
+
const pending = state ? parsePending(this.pending.get(this.pendingKey(state))) : null;
|
|
100
|
+
if (state) this.pending.del(this.pendingKey(state));
|
|
101
|
+
this.prunePending();
|
|
102
|
+
if (!pending || Date.now() - pending.createdAt > PENDING_MAX_AGE_MS) {
|
|
103
|
+
throw new ChabiError({ kind: "signed_out", status: 0, code: "sign_in_not_started", message: "Sign-in didn't complete. Please try again." });
|
|
104
|
+
}
|
|
105
|
+
if (error === "access_denied") {
|
|
106
|
+
throw new ChabiError({ kind: "access_denied", status: 0, code: "access_denied", message: "You chose not to let this app use your Chabi plan." });
|
|
107
|
+
}
|
|
108
|
+
if (error || !code) {
|
|
109
|
+
throw new ChabiError({ kind: "signed_out", status: 0, code: error ?? "sign_in_failed", message: "Sign-in didn't complete. Please try again." });
|
|
110
|
+
}
|
|
111
|
+
await this.core.exchangeCode({ code, redirectUri: this.redirectUri, verifier: pending.verifier });
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
pendingKey(state) {
|
|
115
|
+
return `chabi.${this.clientId}.signin.${state}`;
|
|
116
|
+
}
|
|
117
|
+
prunePending() {
|
|
118
|
+
const prefix = `chabi.${this.clientId}.signin.`;
|
|
119
|
+
for (const key of this.pending.keys()) {
|
|
120
|
+
if (!key.startsWith(prefix)) continue;
|
|
121
|
+
const p = parsePending(this.pending.get(key));
|
|
122
|
+
if (!p || Date.now() - p.createdAt > PENDING_MAX_AGE_MS) this.pending.del(key);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
function parsePending(raw) {
|
|
127
|
+
try {
|
|
128
|
+
const p = JSON.parse(raw ?? "null");
|
|
129
|
+
return p && typeof p.verifier === "string" && typeof p.createdAt === "number" ? p : null;
|
|
130
|
+
} catch {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function safeStore() {
|
|
135
|
+
const memory = /* @__PURE__ */ new Map();
|
|
136
|
+
const ls = () => {
|
|
137
|
+
try {
|
|
138
|
+
return typeof localStorage === "undefined" ? null : localStorage;
|
|
139
|
+
} catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
return {
|
|
144
|
+
get(key) {
|
|
145
|
+
if (memory.has(key)) return memory.get(key);
|
|
146
|
+
try {
|
|
147
|
+
return ls()?.getItem(key) ?? null;
|
|
148
|
+
} catch {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
set(key, value) {
|
|
153
|
+
try {
|
|
154
|
+
const s = ls();
|
|
155
|
+
if (!s) throw new Error("no localStorage");
|
|
156
|
+
s.setItem(key, value);
|
|
157
|
+
memory.delete(key);
|
|
158
|
+
} catch {
|
|
159
|
+
memory.set(key, value);
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
del(key) {
|
|
163
|
+
memory.delete(key);
|
|
164
|
+
try {
|
|
165
|
+
ls()?.removeItem(key);
|
|
166
|
+
} catch {
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
keys() {
|
|
170
|
+
const out = new Set(memory.keys());
|
|
171
|
+
try {
|
|
172
|
+
const s = ls();
|
|
173
|
+
for (let i = 0; s && i < s.length; i++) {
|
|
174
|
+
const k = s.key(i);
|
|
175
|
+
if (k) out.add(k);
|
|
176
|
+
}
|
|
177
|
+
} catch {
|
|
178
|
+
}
|
|
179
|
+
return [...out];
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
function pendingStore() {
|
|
184
|
+
const stores = () => {
|
|
185
|
+
const out = [];
|
|
186
|
+
for (const get of [() => localStorage, () => sessionStorage]) {
|
|
187
|
+
try {
|
|
188
|
+
const s = get();
|
|
189
|
+
if (s) out.push(s);
|
|
190
|
+
} catch {
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
};
|
|
195
|
+
return {
|
|
196
|
+
get(key) {
|
|
197
|
+
for (const s of stores()) {
|
|
198
|
+
try {
|
|
199
|
+
const v = s.getItem(key);
|
|
200
|
+
if (v !== null) return v;
|
|
201
|
+
} catch {
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return null;
|
|
205
|
+
},
|
|
206
|
+
set(key, value) {
|
|
207
|
+
for (const s of stores()) {
|
|
208
|
+
try {
|
|
209
|
+
s.setItem(key, value);
|
|
210
|
+
return;
|
|
211
|
+
} catch {
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
throw new ChabiError({
|
|
215
|
+
kind: "signed_out",
|
|
216
|
+
status: 0,
|
|
217
|
+
code: "storage_blocked",
|
|
218
|
+
message: "This browser is blocking storage, so sign-in can't finish. Allow site data for this page, or use a normal (not private) window."
|
|
219
|
+
});
|
|
220
|
+
},
|
|
221
|
+
del(key) {
|
|
222
|
+
for (const s of stores()) {
|
|
223
|
+
try {
|
|
224
|
+
s.removeItem(key);
|
|
225
|
+
} catch {
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
keys() {
|
|
230
|
+
const out = /* @__PURE__ */ new Set();
|
|
231
|
+
for (const s of stores()) {
|
|
232
|
+
try {
|
|
233
|
+
for (let i = 0; i < s.length; i++) {
|
|
234
|
+
const k = s.key(i);
|
|
235
|
+
if (k) out.add(k);
|
|
236
|
+
}
|
|
237
|
+
} catch {
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return [...out];
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function tokenStorage(store, key) {
|
|
245
|
+
return {
|
|
246
|
+
load() {
|
|
247
|
+
try {
|
|
248
|
+
const t = JSON.parse(store.get(key) ?? "null");
|
|
249
|
+
return t && typeof t.accessToken === "string" && typeof t.refreshToken === "string" && Number.isFinite(t.expiresAt) ? t : null;
|
|
250
|
+
} catch {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
save: (t) => store.set(key, JSON.stringify(t)),
|
|
255
|
+
clear: () => store.del(key)
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
function webLock(name) {
|
|
259
|
+
let tail = Promise.resolve();
|
|
260
|
+
const inPage = (run) => {
|
|
261
|
+
const next = tail.then(run, run);
|
|
262
|
+
tail = next.catch(() => void 0);
|
|
263
|
+
return next;
|
|
264
|
+
};
|
|
265
|
+
return (run) => {
|
|
266
|
+
const locks = typeof navigator === "undefined" ? void 0 : navigator.locks;
|
|
267
|
+
return locks ? locks.request(name, run) : inPage(run);
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
export {
|
|
271
|
+
Chabi,
|
|
272
|
+
ChabiError,
|
|
273
|
+
describeError,
|
|
274
|
+
describeResponse,
|
|
275
|
+
signInButton
|
|
276
|
+
};
|
|
277
|
+
//# sourceMappingURL=browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/button.ts","../src/browser.ts"],"sourcesContent":["// The required \"Sign in with Chabi\" button: the Chabi key logo, then the words. These strings are the ones the\n// docs give developers (gateway/src/docs.ts BUTTON_CSS, gateway/src/icon.ts signInLogoSvg), and a gateway test\n// checks they stay the same. Don't redraw, recolor, stretch or crop the logo.\n\nconst MASK = `<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\"/>`;\n\nexport const SIGN_IN_LOGO_SVG = `<svg width=\"22\" height=\"22\" viewBox=\"0 0 100 100\" aria-hidden=\"true\"><mask id=\"chabi-key\">${MASK}</mask><circle cx=\"50\" cy=\"50\" r=\"50\" fill=\"currentColor\" mask=\"url(#chabi-key)\"/></svg>`;\n\nexport const BUTTON_CSS = [\n \".chabi-signin { display: inline-flex; align-items: center; gap: 10px; padding: 10px 18px; border: 0;\",\n \" border-radius: 8px; background: #E0A526; color: #121212; font: 700 16px/1.2 system-ui, sans-serif; cursor: pointer; }\",\n \".chabi-signin:hover { background: #C99520; }\",\n \"/* Dark style: */\",\n \".chabi-signin.dark { background: #121212; color: #FFFFFF; }\",\n \".chabi-signin.dark svg { color: #E0A526; }\",\n];\n\nlet count = 0;\n\n/** The Sign in with Chabi button, gold (default) or dark. Attach your own click handler that calls `chabi.signIn()`. */\nexport function signInButton(opts: { style?: \"gold\" | \"dark\"; label?: string } = {}): HTMLButtonElement {\n if (!document.querySelector(\"style[data-chabi-signin]\")) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-chabi-signin\", \"\");\n style.textContent = BUTTON_CSS.join(\"\\n\");\n document.head.appendChild(style);\n }\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.className = opts.style === \"dark\" ? \"chabi-signin dark\" : \"chabi-signin\";\n // Each button gets its own mask id: two masks with one id on a page make the second logo disappear.\n const id = `chabi-key-${++count}`;\n button.innerHTML = SIGN_IN_LOGO_SVG.replace('id=\"chabi-key\"', `id=\"${id}\"`).replace(\"url(#chabi-key)\", `url(#${id})`);\n button.append(opts.label ?? \"Sign in with Chabi\");\n return button;\n}\n","// \"Sign in with Chabi\" in the browser: redirect sign-in, tokens in localStorage, one refresh at a time across tabs.\nimport { ChabiBase, DEFAULT_BASE_URL } from \"./client.js\";\nimport { ChabiError } from \"./errors.js\";\nimport { challengeFor, randomString } from \"./pkce.js\";\nimport { SessionCore } from \"./session.js\";\nimport type { RefreshLock, TokenStorage, Tokens } from \"./types.js\";\n\nexport { ChabiError, describeError, describeResponse } from \"./errors.js\";\nexport { signInButton } from \"./button.js\";\nexport type * from \"./types.js\";\nexport type { ChabiBase } from \"./client.js\";\n\n/** How long a started sign-in stays valid: the user may take a while to log in or open an email link. */\nconst PENDING_MAX_AGE_MS = 15 * 60 * 1000;\n\nexport type BrowserOptions = {\n /** From the developer portal. */\n clientId: string;\n /** Where Chabi sends the user back. It must exactly match one registered for the app. */\n redirectUri: string;\n baseUrl?: string;\n /** Replaces localStorage. Without it, the SDK also follows sign-in and sign-out in other tabs. */\n storage?: TokenStorage;\n /** Replaces the Web Locks lock that keeps refreshes one at a time across tabs. */\n lock?: RefreshLock;\n};\n\ntype Pending = { verifier: string; createdAt: number };\n\nexport class Chabi extends ChabiBase {\n private readonly clientId: string;\n private readonly redirectUri: string;\n private readonly baseUrl: string;\n private readonly store: ReturnType<typeof safeStore>;\n private readonly pending = pendingStore();\n private finishing: Promise<boolean> | undefined;\n\n constructor(opts: BrowserOptions) {\n const store = safeStore();\n const tokensKey = `chabi.${opts.clientId}.tokens`;\n const storage = opts.storage ?? tokenStorage(store, tokensKey);\n const lock = opts.lock ?? webLock(`chabi-refresh:${opts.clientId}`);\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n super(new SessionCore({ baseUrl, clientId: opts.clientId, storage, lock }));\n this.store = store;\n this.clientId = opts.clientId;\n this.redirectUri = opts.redirectUri;\n this.baseUrl = baseUrl;\n if (!opts.storage && typeof window !== \"undefined\") {\n // Another tab signed in, signed out or refreshed. (A null key means that tab cleared all of localStorage.)\n window.addEventListener(\"storage\", (e) => {\n if (e.key === tokensKey || e.key === null) this.core.adopt(storage.load() as Tokens | null);\n });\n }\n }\n\n /** Sends the user to Chabi to sign in and allow this app. They come back to `redirectUri`. */\n async signIn(): Promise<void> {\n const verifier = randomString();\n const state = randomString();\n this.prunePending();\n this.pending.set(this.pendingKey(state), JSON.stringify({ verifier, createdAt: Date.now() } satisfies Pending));\n const url = new URL(`${this.baseUrl}/oauth/authorize`);\n url.search = new URLSearchParams({\n response_type: \"code\",\n client_id: this.clientId,\n redirect_uri: this.redirectUri,\n code_challenge: await challengeFor(verifier),\n code_challenge_method: \"S256\",\n state,\n }).toString();\n window.location.assign(url.toString());\n }\n\n /**\n * Call on every page load. If this load is the return from Chabi, finishes the sign-in and returns true;\n * otherwise returns false. Throws a ChabiError (kind `access_denied` when the user declined) if it fails.\n */\n handleRedirect(): Promise<boolean> {\n return (this.finishing ??= this.finish());\n }\n\n private async finish(): Promise<boolean> {\n const params = new URLSearchParams(window.location.search);\n if (!params.has(\"code\") && !params.has(\"error\")) return false;\n const code = params.get(\"code\");\n const state = params.get(\"state\") ?? \"\";\n const error = params.get(\"error\");\n\n // Don't leave the code in the address bar or history; keep the app's own query parameters.\n for (const k of [\"code\", \"state\", \"error\", \"error_description\", \"iss\"]) params.delete(k);\n const rest = params.toString();\n window.history.replaceState(window.history.state, \"\", window.location.pathname + (rest ? `?${rest}` : \"\") + window.location.hash);\n\n // One attempt per state: the entry goes whatever happens next.\n const pending = state ? parsePending(this.pending.get(this.pendingKey(state))) : null;\n if (state) this.pending.del(this.pendingKey(state));\n this.prunePending();\n\n if (!pending || Date.now() - pending.createdAt > PENDING_MAX_AGE_MS) {\n throw new ChabiError({ kind: \"signed_out\", status: 0, code: \"sign_in_not_started\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n if (error === \"access_denied\") {\n throw new ChabiError({ kind: \"access_denied\", status: 0, code: \"access_denied\", message: \"You chose not to let this app use your Chabi plan.\" });\n }\n if (error || !code) {\n throw new ChabiError({ kind: \"signed_out\", status: 0, code: error ?? \"sign_in_failed\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n await this.core.exchangeCode({ code, redirectUri: this.redirectUri, verifier: pending.verifier });\n return true;\n }\n\n private pendingKey(state: string) {\n return `chabi.${this.clientId}.signin.${state}`;\n }\n\n private prunePending() {\n const prefix = `chabi.${this.clientId}.signin.`;\n for (const key of this.pending.keys()) {\n if (!key.startsWith(prefix)) continue;\n const p = parsePending(this.pending.get(key));\n if (!p || Date.now() - p.createdAt > PENDING_MAX_AGE_MS) this.pending.del(key);\n }\n }\n}\n\nfunction parsePending(raw: string | null): Pending | null {\n try {\n const p = JSON.parse(raw ?? \"null\") as Pending | null;\n return p && typeof p.verifier === \"string\" && typeof p.createdAt === \"number\" ? p : null;\n } catch {\n return null;\n }\n}\n\n/** localStorage that never throws: when it's unavailable (private mode, blocked storage), a page-lifetime copy. */\nfunction safeStore() {\n const memory = new Map<string, string>();\n const ls = (): Storage | null => {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n };\n // The memory copy is used only for keys localStorage failed on, so changes made by other tabs are never hidden.\n return {\n get(key: string): string | null {\n if (memory.has(key)) return memory.get(key)!;\n try {\n return ls()?.getItem(key) ?? null;\n } catch {\n return null;\n }\n },\n set(key: string, value: string) {\n try {\n const s = ls();\n if (!s) throw new Error(\"no localStorage\");\n s.setItem(key, value);\n memory.delete(key);\n } catch {\n memory.set(key, value);\n }\n },\n del(key: string) {\n memory.delete(key);\n try {\n ls()?.removeItem(key);\n } catch {\n /* nothing to do */\n }\n },\n keys(): string[] {\n const out = new Set(memory.keys());\n try {\n const s = ls();\n for (let i = 0; s && i < s.length; i++) {\n const k = s.key(i);\n if (k) out.add(k);\n }\n } catch {\n /* memory only */\n }\n return [...out];\n },\n };\n}\n\n/**\n * Where a started sign-in waits for the user to come back. It must outlive the page (the return is a fresh load,\n * often in another tab), so memory won't do: localStorage, else sessionStorage, which survives the trip to Chabi\n * in the same tab. With neither, sign-in can't finish, and signIn says so instead of looping.\n */\nfunction pendingStore() {\n const stores = (): Storage[] => {\n const out: Storage[] = [];\n for (const get of [() => localStorage, () => sessionStorage]) {\n try {\n const s = get();\n if (s) out.push(s);\n } catch {\n /* unavailable */\n }\n }\n return out;\n };\n return {\n get(key: string): string | null {\n for (const s of stores()) {\n try {\n const v = s.getItem(key);\n if (v !== null) return v;\n } catch {\n /* try the next */\n }\n }\n return null;\n },\n set(key: string, value: string) {\n for (const s of stores()) {\n try {\n s.setItem(key, value);\n return;\n } catch {\n /* try the next */\n }\n }\n throw new ChabiError({\n kind: \"signed_out\",\n status: 0,\n code: \"storage_blocked\",\n message: \"This browser is blocking storage, so sign-in can't finish. Allow site data for this page, or use a normal (not private) window.\",\n });\n },\n del(key: string) {\n for (const s of stores()) {\n try {\n s.removeItem(key);\n } catch {\n /* nothing to do */\n }\n }\n },\n keys(): string[] {\n const out = new Set<string>();\n for (const s of stores()) {\n try {\n for (let i = 0; i < s.length; i++) {\n const k = s.key(i);\n if (k) out.add(k);\n }\n } catch {\n /* skip */\n }\n }\n return [...out];\n },\n };\n}\n\nfunction tokenStorage(store: ReturnType<typeof safeStore>, key: string): TokenStorage {\n return {\n load() {\n try {\n const t = JSON.parse(store.get(key) ?? \"null\") as Tokens | null;\n return t && typeof t.accessToken === \"string\" && typeof t.refreshToken === \"string\" && Number.isFinite(t.expiresAt) ? t : null;\n } catch {\n return null;\n }\n },\n save: (t) => store.set(key, JSON.stringify(t)),\n clear: () => store.del(key),\n };\n}\n\n/** Web Locks across tabs; without them (rare, older browsers), a lock within this page. */\nfunction webLock(name: string): RefreshLock {\n let tail: Promise<unknown> = Promise.resolve();\n const inPage: RefreshLock = (run) => {\n const next = tail.then(run, run);\n tail = next.catch(() => undefined);\n return next;\n };\n return (run) => {\n const locks = typeof navigator === \"undefined\" ? undefined : (navigator as Navigator & { locks?: LockManager }).locks;\n return locks ? (locks.request(name, run) as ReturnType<typeof run>) : inPage(run);\n };\n}\n"],"mappings":";;;;;;;;;;;;AAIA,IAAM,OAAO;AAEN,IAAM,mBAAmB,6FAA6F,IAAI;AAE1H,IAAM,aAAa;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAI,QAAQ;AAGL,SAAS,aAAa,OAAoD,CAAC,GAAsB;AACtG,MAAI,CAAC,SAAS,cAAc,0BAA0B,GAAG;AACvD,UAAM,QAAQ,SAAS,cAAc,OAAO;AAC5C,UAAM,aAAa,qBAAqB,EAAE;AAC1C,UAAM,cAAc,WAAW,KAAK,IAAI;AACxC,aAAS,KAAK,YAAY,KAAK;AAAA,EACjC;AACA,QAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,SAAO,OAAO;AACd,SAAO,YAAY,KAAK,UAAU,SAAS,sBAAsB;AAEjE,QAAM,KAAK,aAAa,EAAE,KAAK;AAC/B,SAAO,YAAY,iBAAiB,QAAQ,kBAAkB,OAAO,EAAE,GAAG,EAAE,QAAQ,mBAAmB,QAAQ,EAAE,GAAG;AACpH,SAAO,OAAO,KAAK,SAAS,oBAAoB;AAChD,SAAO;AACT;;;ACtBA,IAAM,qBAAqB,KAAK,KAAK;AAgB9B,IAAM,QAAN,cAAoB,UAAU;AAAA,EAClB;AAAA,EACA;AAAA,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