@kleora-io/core 0.0.0 → 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/credentials/store.ts","../src/credentials/device-grant.ts","../src/credentials/issuer.ts","../src/credentials/session.ts","../src/management-client.ts"],"names":[],"mappings":";;;;;;AAiBO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAChC,IAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAc,OAAA,EAAiB,OAAA,EAAwB;AACjE,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAkBO,IAAM,QAAA,GAAN,cAAuB,eAAA,CAAgB;AAAA,EACnC,IAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CACE,IAAA,EACA,MAAA,EACA,KAAA,EACA,QACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,WAAA,EAAa,MAAA,IAAU,KAAA,IAAS,IAAI,CAAA;AAC1C,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AAAA;AAAA,EAGA,iBAAA,GAA6C;AAC3C,IAAA,OAAO;AAAA,MACL,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,OAAO,IAAA,CAAK,KAAA;AAAA,MACZ,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,QAAQ,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AAO,QAAA,CAAS,YAAY,CAAA,KAAM,QAAA,GAC9B,QAAA,CAAS,YAAY,CAAA,GACpB,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,cAAc,CAAA,IAAK;AAAA,GACjD;AACA,EAAA,OAAO,IAAI,QAAA;AAAA,IACT,OAAO,QAAA,CAAS,MAAM,MAAM,QAAA,GAAW,QAAA,CAAS,MAAM,CAAA,GAAI,aAAA;AAAA,IAC1D,QAAA,CAAS,MAAA;AAAA,IACT,OAAO,QAAA,CAAS,OAAO,MAAM,QAAA,GAAW,QAAA,CAAS,OAAO,CAAA,GAAI,MAAA;AAAA,IAC5D,OAAO,QAAA,CAAS,QAAQ,MAAM,QAAA,GAAW,QAAA,CAAS,QAAQ,CAAA,GAAI,MAAA;AAAA,IAC9D;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * The error shapes the two local tools throw and pass through.\n *\n * Declared here rather than imported from `@kleora-io/node`: neither tool\n * depends on any published SDK. The tools have no database connection and no\n * service credential of their own, and the same isolation argument applies to\n * code: a process that administers a person's whole\n * Account should not inherit behaviour from a package meant for verifying\n * end-user tokens in someone else's backend).\n *\n * One copy, not two, and that is a correctness requirement rather than\n * tidiness: the MCP server and the CLI both render these, and a second\n * `ApiError` in the dependency graph would make `instanceof` lie in whichever\n * of them imported the other's.\n */\n\n/** Base class for everything these packages throw. */\nexport class KleoraToolError extends Error {\n readonly code: string\n\n constructor(code: string, message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = 'KleoraToolError'\n this.code = code\n }\n}\n\n/**\n * What `ApiError` carries beyond `type`/`status`/`detail` — the same shape\n * `@kleora-io/node` calls `ProblemDetails`.\n */\nexport interface ProblemDetails {\n /** The RFC 9457 document exactly as it arrived, extension members included. */\n document: Record<string, unknown>\n /** `Retry-After` in seconds, falling back to the document's `retry_after`. */\n retryAfter: number | null\n requestId: string | undefined\n}\n\n/**\n * An RFC 9457 problem document from the management API, passed through with\n * its `type`, `title`, `detail` and `status`.\n */\nexport class ApiError extends KleoraToolError {\n readonly type: string\n readonly title: string | undefined\n readonly status: number\n readonly detail: string | undefined\n readonly problem: ProblemDetails\n\n constructor(\n type: string,\n status: number,\n title: string | undefined,\n detail: string | undefined,\n problem: ProblemDetails,\n ) {\n super('api_error', detail ?? title ?? type)\n this.name = 'ApiError'\n this.type = type\n this.status = status\n this.title = title\n this.detail = detail\n this.problem = problem\n }\n\n /** The RFC 9457 document, verbatim plus its four standard fields. */\n toProblemDocument(): Record<string, unknown> {\n return {\n type: this.type,\n title: this.title,\n status: this.status,\n detail: this.detail,\n ...this.problem.document,\n }\n }\n}\n\n/**\n * The management API could not be reached at all — refused, timed out, DNS\n * failure. Deliberately distinguishable from a permission failure: an agent\n * or a script must not read an outage as \"you cannot do that\".\n */\nexport class ManagementApiUnreachable extends KleoraToolError {\n constructor(message: string, options?: ErrorOptions) {\n super('management_api_unreachable', message, options)\n this.name = 'ManagementApiUnreachable'\n }\n}\n\n/**\n * The person denied the device approval (RFC 8628 `access_denied`). Surfaced\n * plainly; nothing is stored.\n */\nexport class AuthorizationDenied extends KleoraToolError {\n constructor() {\n super('access_denied', 'The device authorization was denied.')\n this.name = 'AuthorizationDenied'\n }\n}\n","/**\n * Where the refresh token lives: the OS keychain, falling back to a `0600` file\n * under the user's config directory when there is no keychain. Never an\n * environment variable, never a command-line argument — neither appears\n * anywhere in this module, and nothing in either tool reads a credential from\n * either.\n *\n * Never a file inside the user's project, which is the one placement this\n * module makes structurally impossible: the path is always built from\n * `homedir()`.\n *\n * The access token is never written here at all — it lives in memory only\n * (`session.ts`), for the life of the process.\n */\nimport { randomUUID } from 'node:crypto'\nimport { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\n/** One stored credential, keyed by profile. */\nexport interface CredentialStore {\n get(profile: string): Promise<string | null>\n set(profile: string, refreshToken: string): Promise<void>\n delete(profile: string): Promise<void>\n /** For `kleora_whoami` and diagnostics — never the secret itself. */\n readonly backend: 'keychain' | 'file'\n}\n\n/**\n * Which store a tool is asking for. The two tools deliberately do **not**\n * share a stored credential and cannot: a refresh token is bound to the\n * OAuth client it was issued to, and each tool is its own client. What they\n * share is this code.\n *\n * A single `~/.kleora` directory would be tidier and is deliberately not\n * done — moving a live credential store makes every existing MCP user sign in\n * again for no benefit they can see.\n */\nexport interface CredentialStoreOptions {\n /** The keychain service name: `kleora-mcp` or `kleora-cli`. */\n service: string\n /** Where the `0600` fallback lives: `~/.kleora-mcp` or `~/.kleora-cli`. */\n configDir: string\n}\n\n/** `~/.<name>`; overridable for tests, never by a flag a person sets. */\nexport function defaultConfigDir(name: string): string {\n return join(homedir(), `.${name}`)\n}\n\n/**\n * Tries the OS keychain via `@napi-rs/keyring` (an optional dependency); falls\n * back to the file store the moment\n * loading it, or any one call to it, fails. A Linux box with no secret\n * service running is the ordinary case this exists for, not an edge case:\n * the fallback has to work as well as the keychain does, not merely exist.\n */\nexport async function createCredentialStore({\n service,\n configDir,\n}: CredentialStoreOptions): Promise<CredentialStore> {\n const fileStore = new FileCredentialStore(configDir)\n const keyring = await loadKeyring()\n if (keyring === null) return fileStore\n return new KeychainCredentialStore(service, keyring, fileStore)\n}\n\n/** The shape of `@napi-rs/keyring`'s `AsyncEntry` this module actually uses. */\ninterface KeyringModule {\n AsyncEntry: new (service: string, account: string) => {\n // 2.0 resolves a missing entry to `undefined`, 2.1 to `null`; both mean \"none\".\n getPassword(): Promise<string | null | undefined>\n setPassword(password: string): Promise<void>\n deleteCredential(): Promise<boolean>\n }\n}\n\nasync function loadKeyring(): Promise<KeyringModule | null> {\n try {\n // A dynamic import, not a static one: the whole point of an optional\n // dependency is that a platform with no prebuilt binary for it — or no\n // keychain at all — still installs and still runs this server, on the\n // file fallback.\n return await import('@napi-rs/keyring')\n } catch {\n return null\n }\n}\n\nclass KeychainCredentialStore implements CredentialStore {\n readonly backend = 'keychain'\n #service: string\n #keyring: KeyringModule\n #fallback: FileCredentialStore\n /** Set once any call fails, so a dead keychain is not retried per call. */\n #broken = false\n\n constructor(service: string, keyring: KeyringModule, fallback: FileCredentialStore) {\n this.#service = service\n this.#keyring = keyring\n this.#fallback = fallback\n }\n\n async get(profile: string): Promise<string | null> {\n if (this.#broken) return this.#fallback.get(profile)\n try {\n const entry = new this.#keyring.AsyncEntry(this.#service, profile)\n const value = await entry.getPassword()\n return value ?? null\n } catch {\n this.#broken = true\n return this.#fallback.get(profile)\n }\n }\n\n async set(profile: string, refreshToken: string): Promise<void> {\n if (this.#broken) return this.#fallback.set(profile, refreshToken)\n try {\n const entry = new this.#keyring.AsyncEntry(this.#service, profile)\n await entry.setPassword(refreshToken)\n } catch {\n this.#broken = true\n await this.#fallback.set(profile, refreshToken)\n }\n }\n\n async delete(profile: string): Promise<void> {\n if (this.#broken) return this.#fallback.delete(profile)\n try {\n const entry = new this.#keyring.AsyncEntry(this.#service, profile)\n await entry.deleteCredential()\n } catch {\n this.#broken = true\n await this.#fallback.delete(profile)\n }\n }\n}\n\n/**\n * A `0600` file per profile under `configDir`. `mode` on `writeFileSync` is\n * still subject to the process umask, so every write is followed by an\n * explicit `chmodSync` — the guarantee is the final permission bits, not\n * merely the flag passed to the syscall that created the file.\n */\nexport class FileCredentialStore implements CredentialStore {\n readonly backend = 'file'\n #dir: string\n\n constructor(dir: string) {\n this.#dir = dir\n }\n\n // Every one of these is synchronous under the hood (`node:fs`'s sync API,\n // deliberately — this runs at most once per tool call, never in a hot\n // loop) but returns a `Promise` regardless, so `KeychainCredentialStore`\n // can fall back to it without its callers caring which backend answered.\n get(profile: string): Promise<string | null> {\n try {\n const raw = readFileSync(this.#path(profile), 'utf8')\n const parsed: unknown = JSON.parse(raw)\n if (typeof parsed === 'object' && parsed !== null && 'refreshToken' in parsed) {\n const refreshToken = parsed.refreshToken\n if (typeof refreshToken === 'string') return Promise.resolve(refreshToken)\n }\n return Promise.resolve(null)\n } catch (error) {\n if (isNotFound(error)) return Promise.resolve(null)\n return Promise.reject(asError(error))\n }\n }\n\n set(profile: string, refreshToken: string): Promise<void> {\n try {\n mkdirSync(this.#dir, { recursive: true, mode: 0o700 })\n chmodSync(this.#dir, 0o700)\n const path = this.#path(profile)\n // Write beside the target and rename, so a process killed mid-write\n // never leaves a half-written credential file for the next run to parse.\n const tmp = `${path}.${randomUUID()}.tmp`\n writeFileSync(tmp, JSON.stringify({ refreshToken }), { mode: 0o600 })\n chmodSync(tmp, 0o600)\n renameSync(tmp, path)\n return Promise.resolve()\n } catch (error) {\n return Promise.reject(asError(error))\n }\n }\n\n delete(profile: string): Promise<void> {\n try {\n rmSync(this.#path(profile))\n return Promise.resolve()\n } catch (error) {\n if (isNotFound(error)) return Promise.resolve()\n return Promise.reject(asError(error))\n }\n }\n\n #path(profile: string): string {\n // Profile names come from configuration, never from a tool argument or\n // API response, but a filesystem path is still built from a string the\n // person typed — encoded rather than trusted to contain no `/`.\n return join(this.#dir, `credentials-${encodeURIComponent(profile)}.json`)\n }\n}\n\nfunction isNotFound(error: unknown): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'\n}\n\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n","/**\n * The OAuth 2.0 device authorization grant (RFC 8628) against the issuer: the\n * credential both the CLI and the MCP server run on.\n */\nimport { ManagementApiUnreachable } from '../errors.js'\n\nexport interface DeviceAuthorization {\n deviceCode: string\n userCode: string\n verificationUri: string\n verificationUriComplete: string\n expiresIn: number\n interval: number\n}\n\nexport interface Tokens {\n accessToken: string\n refreshToken: string | undefined\n expiresIn: number\n}\n\n/** RFC 8628 section 3.2 / RFC 6749 section 5.2 error codes this module distinguishes. */\nexport type OAuthErrorCode =\n | 'authorization_pending'\n | 'slow_down'\n | 'access_denied'\n | 'expired_token'\n | 'invalid_grant'\n | 'unauthorized_client'\n | 'other'\n\nexport class OAuthError extends Error {\n readonly code: OAuthErrorCode\n constructor(code: OAuthErrorCode, description: string | undefined) {\n super(description ?? code)\n this.name = 'OAuthError'\n this.code = code\n }\n}\n\nexport interface DeviceGrantOptions {\n issuer: string\n clientId: string\n /**\n * `kleora-mcp/{version}` or `kleora-cli/{version}`. Passed in rather than\n * read from a constant here, because this module is shared and the whole\n * value of the two tools having their own OAuth client is that an audit event\n * can say which of them acted — a shared `User-Agent` would undo half of that\n * in the request log.\n */\n userAgent: string\n fetch: typeof globalThis.fetch\n}\n\nasync function postForm(\n url: string,\n body: Record<string, string>,\n fetchImpl: typeof globalThis.fetch,\n userAgent: string,\n): Promise<Record<string, unknown>> {\n let response: Response\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n 'User-Agent': userAgent,\n },\n body: new URLSearchParams(body),\n })\n } catch (error) {\n throw new ManagementApiUnreachable(`could not reach ${url}`, { cause: error })\n }\n\n let document: Record<string, unknown> = {}\n try {\n document = (await response.json()) as Record<string, unknown>\n } catch {\n // fall through with an empty document; the status code alone still tells\n // the caller something.\n }\n\n if (!response.ok) {\n const rawCode = typeof document['error'] === 'string' ? document['error'] : 'other'\n const code: OAuthErrorCode = isKnownCode(rawCode) ? rawCode : 'other'\n const description =\n typeof document['error_description'] === 'string' ? document['error_description'] : undefined\n throw new OAuthError(code, description)\n }\n return document\n}\n\nfunction isKnownCode(value: string): value is OAuthErrorCode {\n return [\n 'authorization_pending',\n 'slow_down',\n 'access_denied',\n 'expired_token',\n 'invalid_grant',\n 'unauthorized_client',\n ].includes(value)\n}\n\n/** RFC 8628 sections 3.1–3.2: `POST /oauth/device_authorization`. */\nexport async function startDeviceAuthorization({\n issuer,\n clientId,\n userAgent,\n fetch: fetchImpl,\n}: DeviceGrantOptions): Promise<DeviceAuthorization> {\n const document = await postForm(\n `${issuer}/oauth/device_authorization`,\n { client_id: clientId },\n fetchImpl,\n userAgent,\n )\n return {\n deviceCode: requireString(document, 'device_code'),\n userCode: requireString(document, 'user_code'),\n verificationUri: requireString(document, 'verification_uri'),\n verificationUriComplete:\n typeof document['verification_uri_complete'] === 'string'\n ? document['verification_uri_complete']\n : requireString(document, 'verification_uri'),\n expiresIn: requireNumber(document, 'expires_in'),\n interval: typeof document['interval'] === 'number' ? document['interval'] : 5,\n }\n}\n\n/**\n * One poll of `POST /oauth/token` with\n * `urn:ietf:params:oauth:grant-type:device_code`. Throws `OAuthError` for\n * every RFC 8628 poll outcome that is not success — the caller\n * (`session.ts`) is what turns `authorization_pending` into \"not an error,\n * this is the sign-in\".\n */\nexport async function pollDeviceToken({\n issuer,\n clientId,\n deviceCode,\n userAgent,\n fetch: fetchImpl,\n}: DeviceGrantOptions & { deviceCode: string }): Promise<Tokens> {\n const document = await postForm(\n `${issuer}/oauth/token`,\n {\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: deviceCode,\n client_id: clientId,\n },\n fetchImpl,\n userAgent,\n )\n return tokensOf(document)\n}\n\n/** `grant_type=refresh_token`, for a stored credential. The refresh token rotates on every use. */\nexport async function refreshAccessToken({\n issuer,\n clientId,\n refreshToken,\n userAgent,\n fetch: fetchImpl,\n}: DeviceGrantOptions & { refreshToken: string }): Promise<Tokens> {\n const document = await postForm(\n `${issuer}/oauth/token`,\n { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: clientId },\n fetchImpl,\n userAgent,\n )\n return tokensOf(document)\n}\n\n/**\n * RFC 7009 section 2.1: `POST /oauth/revoke` with the refresh token, which\n * revokes its whole rotation family and writes one\n * `refresh_token.revoked` audit event.\n *\n * This is the server-side half of \"uninstalling leaves no live credential\n * behind\": deleting the stored token alone would leave the\n * authorization itself alive and refreshable by anyone who had copied the\n * file. An unknown or already-dead token answers `200` with no effect\n * (RFC 7009 section 2.2), so calling this twice is not an error.\n */\nexport async function revokeRefreshToken({\n issuer,\n clientId,\n refreshToken,\n userAgent,\n fetch: fetchImpl,\n}: DeviceGrantOptions & { refreshToken: string }): Promise<void> {\n await postForm(\n `${issuer}/oauth/revoke`,\n { token: refreshToken, token_type_hint: 'refresh_token', client_id: clientId },\n fetchImpl,\n userAgent,\n )\n}\n\nfunction tokensOf(document: Record<string, unknown>): Tokens {\n return {\n accessToken: requireString(document, 'access_token'),\n refreshToken: typeof document['refresh_token'] === 'string' ? document['refresh_token'] : undefined,\n expiresIn: requireNumber(document, 'expires_in'),\n }\n}\n\nfunction requireString(document: Record<string, unknown>, key: string): string {\n const value = document[key]\n if (typeof value !== 'string') throw new ManagementApiUnreachable(`the issuer's response has no '${key}'`)\n return value\n}\n\nfunction requireNumber(document: Record<string, unknown>, key: string): number {\n const value = document[key]\n if (typeof value !== 'number') throw new ManagementApiUnreachable(`the issuer's response has no '${key}'`)\n return value\n}\n","/**\n * Where the device grant runs: the platform issuer, as the management API\n * reports it.\n *\n * Both tools used to *derive* it, by swapping the first DNS label of the API's\n * origin for `id`. The hosted API is on `kleora.io` and every issuer is on\n * `kleora.eu`, so the derivation held only through a hard-coded exception,\n * and would have named a host nobody serves for the next region. Now the tool\n * asks the deployment — `GET {baseUrl}/api/v1/platform`, anonymously, since\n * the answer is where a credential comes from — and uses what it says.\n *\n * An explicit issuer (`--issuer`, `KLEORA_ISSUER`, `KLEORA_MCP_ISSUER`) still\n * wins and makes no request at all: a development topology the deployment\n * cannot describe from the inside is exactly what the override is for.\n */\nimport { ManagementApiUnreachable } from '../errors.js'\n\nexport const PLATFORM_PATH = '/api/v1/platform'\n\nexport interface IssuerDiscoveryOptions {\n /** The management API's origin, e.g. `https://api.kleora.io`, no trailing slash. */\n baseUrl: string\n userAgent: string\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * `GET {baseUrl}/api/v1/platform` → its `issuer`, without a trailing slash.\n *\n * Every failure is a `ManagementApiUnreachable` naming the URL it asked, because\n * the only thing a person can do about any of them is check the base URL or\n * pass the issuer explicitly — and the message says both.\n */\nexport async function discoverIssuer({\n baseUrl,\n userAgent,\n fetch: fetchImpl = globalThis.fetch,\n}: IssuerDiscoveryOptions): Promise<string> {\n const url = `${baseUrl}${PLATFORM_PATH}`\n const hint = 'Check the API base URL, or pass the issuer explicitly.'\n let response: Response\n try {\n response = await fetchImpl(url, {\n headers: { Accept: 'application/json', 'User-Agent': userAgent },\n })\n } catch (error) {\n throw new ManagementApiUnreachable(`could not reach ${url} to find the issuer. ${hint}`, {\n cause: error,\n })\n }\n if (!response.ok) {\n throw new ManagementApiUnreachable(\n `${url} answered ${String(response.status)}, so the issuer is unknown. ${hint}`,\n )\n }\n\n let document: unknown\n try {\n document = await response.json()\n } catch {\n document = null\n }\n const issuer =\n typeof document === 'object' && document !== null\n ? (document as Record<string, unknown>)['issuer']\n : undefined\n if (typeof issuer !== 'string' || !isHttpUrl(issuer)) {\n throw new ManagementApiUnreachable(`${url} did not name an issuer. ${hint}`)\n }\n return issuer.replace(/\\/+$/, '')\n}\n\n/**\n * The issuer to use, asked for at most once: `explicit` when given, otherwise\n * whatever `discoverIssuer` answers.\n *\n * Lazy on purpose. A command that never reaches the issuer — anything run\n * under an API key, `--help`, a usage error — makes no discovery request, and a\n * long-lived MCP server makes one per process rather than one per tool call. A\n * failed discovery is not remembered, so the next call asks again.\n */\nexport function issuerResolver(\n explicit: string | undefined,\n options: IssuerDiscoveryOptions,\n): () => Promise<string> {\n if (explicit !== undefined) {\n const value = explicit\n return () => Promise.resolve(value)\n }\n let pending: Promise<string> | null = null\n return () => {\n pending ??= discoverIssuer(options).catch((error: unknown) => {\n pending = null\n throw error\n })\n return pending\n }\n}\n\nfunction isHttpUrl(value: string): boolean {\n try {\n const url = new URL(value)\n return url.protocol === 'https:' || url.protocol === 'http:'\n } catch {\n return false\n }\n}\n","/**\n * One profile's credential lifecycle.\n *\n * The access token lives in memory only, for the life of this object. The\n * refresh token is read from and written to a `CredentialStore` — never held\n * here longer than one call needs it. There is exactly one thing this class\n * remembers across calls that is not a secret: a pending, unapproved device\n * authorization, so that a retried tool call polls the same code instead of\n * starting a new one every time.\n */\nimport { ManagementApiUnreachable } from '../errors.js'\nimport {\n OAuthError,\n pollDeviceToken,\n refreshAccessToken,\n startDeviceAuthorization,\n type Tokens,\n} from './device-grant.js'\nimport type { CredentialStore } from './store.js'\n\nexport interface SessionOptions {\n /**\n * The platform issuer, or a function that finds it (`issuerResolver`). A\n * function is called only when a request to the issuer is actually about to\n * be made, so a session that never refreshes never asks.\n */\n issuer: string | (() => Promise<string>)\n clientId: string\n profile: string\n store: CredentialStore\n /** `kleora-mcp/{version}` or `kleora-cli/{version}`. */\n userAgent: string\n fetch?: typeof globalThis.fetch\n /** Access tokens are treated as expired this many seconds early. */\n clockSkewSeconds?: number\n}\n\nexport type SessionState =\n | { status: 'ready'; accessToken: string }\n | {\n status: 'authorization_required'\n verificationUri: string\n verificationUriComplete: string\n userCode: string\n message: string\n }\n | { status: 'denied' }\n\nexport type NotReadyState = Exclude<SessionState, { status: 'ready' }>\n\n/**\n * Thrown by the `getAccessToken` callback a `ManagementClient` is built\n * with, when the session is not `ready`. The MCP server catches this and\n * turns it into a tool result that says \"not an error — this is the sign-in\"\n * rather than letting it surface as a protocol-level failure.\n */\nexport class SessionNotReady extends Error {\n readonly state: NotReadyState\n constructor(state: NotReadyState) {\n super(`session not ready: ${state.status}`)\n this.name = 'SessionNotReady'\n this.state = state\n }\n}\n\ninterface Pending {\n deviceCode: string\n interval: number\n expiresAt: number\n verificationUri: string\n verificationUriComplete: string\n userCode: string\n lastPollAt: number\n}\n\nexport class Session {\n readonly #issuer: () => Promise<string>\n readonly #clientId: string\n readonly #profile: string\n readonly #store: CredentialStore\n readonly #userAgent: string\n readonly #fetch: typeof globalThis.fetch\n readonly #skewMs: number\n\n #accessToken: string | null = null\n #accessTokenExpiresAt = 0\n #pending: Pending | null = null\n\n constructor(options: SessionOptions) {\n const issuer = options.issuer\n this.#issuer = typeof issuer === 'string' ? () => Promise.resolve(issuer) : issuer\n this.#clientId = options.clientId\n this.#profile = options.profile\n this.#store = options.store\n this.#userAgent = options.userAgent\n this.#fetch = options.fetch ?? globalThis.fetch\n this.#skewMs = (options.clockSkewSeconds ?? 30) * 1000\n }\n\n /**\n * The access token to call the management API with, or the instructions to\n * show the person instead of a result: \"not an error — this is the\n * sign-in.\"\n */\n async ensureAccessToken(): Promise<SessionState> {\n if (this.#accessToken !== null && Date.now() < this.#accessTokenExpiresAt - this.#skewMs) {\n return { status: 'ready', accessToken: this.#accessToken }\n }\n\n const fromRefresh = await this.#tryStoredCredential()\n if (fromRefresh !== null) return fromRefresh\n\n return this.#advanceDeviceFlow()\n }\n\n /**\n * An access token from the **stored** credential only — never starting a\n * device flow.\n *\n * This is the CLI's entry point rather than `ensureAccessToken` above, and\n * the difference is a deliberate behavioural split rather than a\n * convenience. With no credential for the profile, a CLI command says so\n * and names `kleora login`, exiting `3`. **It does not start a device flow\n * unbidden**: an interactive sign-in in the middle of a piped command is a\n * hang.\n *\n * An MCP host, by contrast, has a place to show a verification URL and a\n * turn to show it on, which is why `ensureAccessToken` may begin one there.\n * `null` means \"nothing stored, or what was stored is dead and has been\n * deleted\" — both of which the caller answers with the same sentence.\n */\n async accessTokenFromStoredCredential(): Promise<string | null> {\n if (this.#accessToken !== null && Date.now() < this.#accessTokenExpiresAt - this.#skewMs) {\n return this.#accessToken\n }\n const state = await this.#tryStoredCredential()\n return state !== null && state.status === 'ready' ? state.accessToken : null\n }\n\n /** Forces the next call to re-authorise, even if a token is cached in memory. */\n invalidate(): void {\n this.#accessToken = null\n this.#accessTokenExpiresAt = 0\n }\n\n /** `null` means \"no usable stored credential — try the device flow instead\". */\n async #tryStoredCredential(): Promise<SessionState | null> {\n const stored = await this.#store.get(this.#profile)\n if (stored === null) return null\n\n let tokens: Tokens\n try {\n tokens = await refreshAccessToken({\n issuer: await this.#issuer(),\n clientId: this.#clientId,\n refreshToken: stored,\n userAgent: this.#userAgent,\n fetch: this.#fetch,\n })\n } catch (error) {\n if (error instanceof OAuthError) {\n // A refresh token that is rejected (revoked, reused or expired): the\n // stored credential is deleted and the next call starts a fresh\n // device flow. A silently retried dead token is a\n // loop this class refuses to run.\n await this.#store.delete(this.#profile)\n return null\n }\n throw error\n }\n await this.#storeTokens(tokens)\n return { status: 'ready', accessToken: tokens.accessToken }\n }\n\n /** Starts a device flow if none is pending, or polls the one already running. */\n async #advanceDeviceFlow(): Promise<SessionState> {\n if (this.#pending === null || Date.now() >= this.#pending.expiresAt) {\n const auth = await startDeviceAuthorization({\n issuer: await this.#issuer(),\n clientId: this.#clientId,\n userAgent: this.#userAgent,\n fetch: this.#fetch,\n })\n this.#pending = {\n deviceCode: auth.deviceCode,\n interval: auth.interval,\n expiresAt: Date.now() + auth.expiresIn * 1000,\n verificationUri: auth.verificationUri,\n verificationUriComplete: auth.verificationUriComplete,\n userCode: auth.userCode,\n lastPollAt: 0,\n }\n return this.#pendingState(\n 'No Kleora credential is authorised yet. Open the verification URL, ' +\n 'enter the code, and approve. Then call this tool again.',\n )\n }\n\n const pending = this.#pending\n // The device grant's own interval is enforced by the issuer\n // (RFC 8628 section 3.5): a poll made sooner just gets `slow_down`,\n // which this branch absorbs by widening the interval rather than\n // treating it as a failure. One HTTP request either way.\n pending.lastPollAt = Date.now()\n try {\n const tokens = await pollDeviceToken({\n issuer: await this.#issuer(),\n clientId: this.#clientId,\n deviceCode: pending.deviceCode,\n userAgent: this.#userAgent,\n fetch: this.#fetch,\n })\n this.#pending = null\n await this.#storeTokens(tokens)\n return { status: 'ready', accessToken: tokens.accessToken }\n } catch (error) {\n if (!(error instanceof OAuthError)) throw error\n switch (error.code) {\n case 'authorization_pending':\n return this.#pendingState('Still waiting for approval in the browser.')\n case 'slow_down':\n pending.interval += 5\n return this.#pendingState(\n `Polling too fast; the issuer asked for a wider interval. Wait a little longer before retrying.`,\n )\n case 'access_denied':\n this.#pending = null\n return { status: 'denied' }\n case 'expired_token':\n // The code timed out with nobody approving it. This is treated\n // the same as a rejected refresh token: start over rather than\n // fail — the next call gets a fresh code immediately.\n this.#pending = null\n return this.#advanceDeviceFlow()\n default:\n throw new ManagementApiUnreachable(`the issuer refused the poll: ${error.code}`, {\n cause: error,\n })\n }\n }\n }\n\n async #storeTokens(tokens: Tokens): Promise<void> {\n this.#accessToken = tokens.accessToken\n this.#accessTokenExpiresAt = Date.now() + tokens.expiresIn * 1000\n if (tokens.refreshToken !== undefined) {\n // The refresh token rotates on every use; the\n // old value is simply overwritten, never appended anywhere.\n await this.#store.set(this.#profile, tokens.refreshToken)\n }\n }\n\n #pendingState(message: string): SessionState {\n const pending = this.#pending\n if (pending === null) throw new Error('invariant: #pendingState called with no pending flow')\n return {\n status: 'authorization_required',\n verificationUri: pending.verificationUri,\n verificationUriComplete: pending.verificationUriComplete,\n userCode: pending.userCode,\n message,\n }\n }\n}\n","/**\n * A thin, generic `fetch` wrapper over the management API's operations — the\n * whole security argument of both local tools, in code: this is the *only*\n * way either the CLI or the MCP server reaches Kleora's data, over HTTPS, with\n * the caller's own bearer token. No ORM, no service credential, no query the\n * API does not already expose.\n *\n * Generic over an `Operation` rather than one method per endpoint, because\n * both callers already know which operation they are invoking — the MCP\n * server from a tool name, the CLI from a noun and a verb — and a second,\n * hand-written switch here would be the same map twice.\n *\n * `Operation` is declared **structurally** rather than imported from either\n * package's generated tree: each generates its own from the management API's\n * OpenAPI document and both shapes satisfy this one, so this module depends on\n * neither generator's output.\n */\nimport { ApiError, ManagementApiUnreachable, type ProblemDetails } from './errors.js'\n\n/** What this client needs to know about an operation in order to call it. */\nexport interface Operation {\n readonly operationId: string\n readonly method: 'get' | 'post' | 'put' | 'patch' | 'delete'\n readonly path: string\n readonly pathParams: readonly string[]\n readonly queryParams: readonly string[]\n readonly hasBody: boolean\n}\n\nexport interface ManagementClientOptions {\n baseUrl: string\n /** Resolves to a fresh bearer token for every call — never cached here. */\n getAccessToken: () => Promise<string>\n /** `kleora-mcp/{version}` or `kleora-cli/{version}`. */\n userAgent: string\n fetch?: typeof globalThis.fetch\n timeoutMs?: number\n /**\n * Concurrent requests this client will have in flight at once: a small\n * number, deliberately. A host that fires several tool calls at once, or a\n * `--all` walk, must not turn a local tool into a burst against the\n * account's own limits.\n */\n maxConcurrent?: number\n /**\n * Called once per attempt, for the CLI's `--debug`, which prints the\n * request method, path, status, duration and `X-Request-Id` of every call\n * to stderr. It is\n * handed no credential and no body, which is what makes `--debug` output\n * safe to paste into a support reply.\n */\n onTrace?: (trace: RequestTrace) => void\n}\n\n/** What `--debug` prints. Deliberately carries nothing secret. */\nexport interface RequestTrace {\n method: string\n /** Path and query only — never the `Authorization` header, never a body. */\n path: string\n /** `null` when nothing answered at all. */\n status: number | null\n durationMs: number\n requestId: string | undefined\n /** Set when the request failed before a status existed. */\n error?: string\n}\n\nexport interface CallOptions {\n /**\n * Extra request headers: `Idempotency-Key` on a write, `X-Request-Id` when\n * the caller wants to correlate one. **Never a credential** — the only\n * `Authorization` header this client sends is the one it builds from\n * `getAccessToken`, and it is applied after these so a caller cannot\n * replace it.\n */\n headers?: Record<string, string>\n /**\n * Whether repeating this request is safe after a `429`. Defaults to `true`.\n * A non-idempotent `POST` is never retried without an `Idempotency-Key`, so\n * a caller making a keyless `POST` passes `false`.\n */\n idempotent?: boolean\n}\n\n/** A response, body included as the bytes that arrived. */\nexport interface RawResponse {\n status: number\n /**\n * The body exactly as it arrived, unparsed. The CLI's `--json` prints the\n * response body as it arrived, not a re-serialisation of a parsed object,\n * which is what lets an older CLI against a newer API pass\n * through fields it has never heard of.\n */\n text: string\n headers: Headers\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000\nconst DEFAULT_MAX_CONCURRENT = 4\n/** Bounds the `Retry-After` backoff — never an unbounded loop. */\nconst MAX_RETRIES = 3\n\nexport interface OperationArgs {\n [name: string]: unknown\n}\n\nexport class ManagementClient {\n readonly baseUrl: string\n readonly #getAccessToken: () => Promise<string>\n readonly #userAgent: string\n readonly #fetch: typeof globalThis.fetch\n readonly #timeoutMs: number\n readonly #maxConcurrent: number\n readonly #onTrace: ((trace: RequestTrace) => void) | undefined\n #inFlight = 0\n #queue: Array<() => void> = []\n\n constructor(options: ManagementClientOptions) {\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.#getAccessToken = options.getAccessToken\n this.#userAgent = options.userAgent\n this.#fetch = options.fetch ?? globalThis.fetch\n this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n this.#maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT\n this.#onTrace = options.onTrace\n }\n\n /**\n * Calls one operation and parses the body. `args` is a flat argument\n * object; this method is what splits it back into path, query and body using\n * the operation's own metadata — never a lookup this package invents.\n */\n async call(\n operation: Operation,\n args: OperationArgs,\n options: CallOptions = {},\n ): Promise<unknown> {\n const response = await this.request(operation, args, options)\n if (response.status === 204 || response.text === '') return undefined\n return JSON.parse(response.text) as unknown\n }\n\n /** The same call, with the body left as the bytes that arrived. */\n async request(\n operation: Operation,\n args: OperationArgs,\n options: CallOptions = {},\n ): Promise<RawResponse> {\n await this.#acquire()\n try {\n return await this.#withRetry(operation, args, options, 0)\n } finally {\n this.#release()\n }\n }\n\n async #withRetry(\n operation: Operation,\n args: OperationArgs,\n options: CallOptions,\n attempt: number,\n ): Promise<RawResponse> {\n const url = this.#urlFor(operation, args)\n const body = this.#bodyFor(operation, args)\n const token = await this.#getAccessToken()\n\n const headers: Record<string, string> = {\n Accept: 'application/json, application/problem+json',\n ...(options.headers ?? {}),\n Authorization: `Bearer ${token}`,\n 'User-Agent': this.#userAgent,\n }\n if (body !== undefined) headers['Content-Type'] = 'application/json'\n\n const method = operation.method.toUpperCase()\n const startedAt = Date.now()\n let response: Response\n try {\n response = await this.#fetch(url, {\n method,\n headers,\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: AbortSignal.timeout(this.#timeoutMs),\n })\n } catch (error) {\n this.#onTrace?.({\n method,\n path: url.pathname + url.search,\n status: null,\n durationMs: Date.now() - startedAt,\n requestId: undefined,\n error: error instanceof Error ? error.message : String(error),\n })\n throw new ManagementApiUnreachable(`could not reach ${this.baseUrl}`, { cause: error })\n }\n\n this.#onTrace?.({\n method,\n path: url.pathname + url.search,\n status: response.status,\n durationMs: Date.now() - startedAt,\n requestId: response.headers.get('x-request-id') ?? undefined,\n })\n\n if (response.status === 429 && attempt < MAX_RETRIES && options.idempotent !== false) {\n const retryAfter = retryAfterSeconds(response)\n if (retryAfter !== null) {\n await sleep(retryAfter * 1000)\n return this.#withRetry(operation, args, options, attempt + 1)\n }\n }\n\n if (!response.ok) throw await toApiError(response)\n return {\n status: response.status,\n text: response.status === 204 ? '' : await response.text(),\n headers: response.headers,\n }\n }\n\n #urlFor(operation: Operation, args: OperationArgs): URL {\n const path = operation.path.replace(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = args[name]\n if (typeof value !== 'string' || value === '') {\n // Unreachable once the caller has validated `args` — ajv against the\n // tool's schema in the MCP server, the command's own parser in the\n // CLI. This is the backstop, not the primary defence.\n throw new Error(`operation '${operation.operationId}' needs a path parameter '${name}'`)\n }\n return encodeURIComponent(value)\n })\n const url = new URL(this.baseUrl + path)\n for (const name of operation.queryParams) {\n const value = args[name]\n if (value === undefined || value === null) continue\n for (const item of Array.isArray(value) ? value : [value]) {\n if (typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean') {\n url.searchParams.append(name, String(item))\n }\n }\n }\n return url\n }\n\n #bodyFor(operation: Operation, args: OperationArgs): Record<string, unknown> | undefined {\n if (!operation.hasBody) return undefined\n const excluded = new Set<string>([...operation.pathParams, ...operation.queryParams])\n const body: Record<string, unknown> = {}\n for (const [name, value] of Object.entries(args)) {\n if (excluded.has(name)) continue\n if (value !== undefined) body[name] = value\n }\n return body\n }\n\n /** A tiny counting semaphore — no dependency for something this small. */\n #acquire(): Promise<void> {\n if (this.#inFlight < this.#maxConcurrent) {\n this.#inFlight++\n return Promise.resolve()\n }\n return new Promise((resolve) => {\n this.#queue.push(() => {\n this.#inFlight++\n resolve()\n })\n })\n }\n\n #release(): void {\n this.#inFlight--\n const next = this.#queue.shift()\n if (next) next()\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/** `Retry-After` in seconds, from either the delta-seconds or the HTTP-date form. */\nexport function retryAfterSeconds(response: Response): number | null {\n const raw = response.headers.get('retry-after')?.trim()\n if (!raw) return null\n const seconds = Number(raw)\n if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds, 60)\n const at = Date.parse(raw)\n if (Number.isFinite(at)) return Math.min(Math.max(0, Math.round((at - Date.now()) / 1000)), 60)\n return null\n}\n\nasync function toApiError(response: Response): Promise<ApiError> {\n let document: Record<string, unknown> = {}\n try {\n const body: unknown = JSON.parse(await response.text())\n if (typeof body === 'object' && body !== null && !Array.isArray(body)) {\n document = body as Record<string, unknown>\n }\n } catch {\n // A non-JSON error body (an intermediary's HTML page) still becomes an\n // `ApiError` carrying the status; see this client's callers.\n }\n const problem: ProblemDetails = {\n document,\n retryAfter: retryAfterSeconds(response),\n requestId:\n typeof document['request_id'] === 'string'\n ? document['request_id']\n : (response.headers.get('x-request-id') ?? undefined),\n }\n return new ApiError(\n typeof document['type'] === 'string' ? document['type'] : 'about:blank',\n response.status,\n typeof document['title'] === 'string' ? document['title'] : undefined,\n typeof document['detail'] === 'string' ? document['detail'] : undefined,\n problem,\n )\n}\n"]}
package/package.json CHANGED
@@ -1 +1,57 @@
1
- {"name":"@kleora-io/core","version":"0.0.0","description":"Name reserved for Kleora. The first release is coming.","license":"Apache-2.0"}
1
+ {
2
+ "name": "@kleora-io/core",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "The credential store, device-grant client, in-memory session and generic management API client shared by the Kleora CLI and the Kleora MCP server.",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://github.com/kleora-io/kleora-cli/tree/main/packages/core#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kleora-io/kleora-cli.git",
11
+ "directory": "packages/core"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/kleora-io/kleora-cli/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "sideEffects": false,
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "LICENSE",
35
+ "README.md"
36
+ ],
37
+ "optionalDependencies": {
38
+ "@napi-rs/keyring": "^2.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@eslint/js": "^10.0.1",
42
+ "@types/node": "^24.10.0",
43
+ "eslint": "^10.0.0",
44
+ "tsup": "^8.5.1",
45
+ "typescript": "^5.9.3",
46
+ "typescript-eslint": "^8.68.0",
47
+ "vitest": "^4.1.11"
48
+ },
49
+ "scripts": {
50
+ "build": "tsup",
51
+ "lint": "eslint .",
52
+ "lint:fix": "eslint . --fix",
53
+ "typecheck": "tsc --noEmit",
54
+ "test": "vitest run",
55
+ "test:watch": "vitest"
56
+ }
57
+ }