busabase-sdk 0.14.1 → 0.15.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,66 @@
1
+ import { BusabaseAirAppCredentialStoreOptions } from './oauth-node.js';
2
+ import './oauth.js';
3
+
4
+ declare const BUSABASE_AIRAPP_GATEWAY_REASONS: {
5
+ readonly authRequired: "AUTH_REQUIRED";
6
+ readonly authUnavailable: "AUTH_UNAVAILABLE";
7
+ readonly connectionRequired: "CONNECTION_REQUIRED";
8
+ readonly oauthCallbackInvalid: "OAUTH_CALLBACK_INVALID";
9
+ readonly spaceNotAllowed: "SPACE_NOT_ALLOWED";
10
+ readonly spaceSelectionRequired: "SPACE_SELECTION_REQUIRED";
11
+ };
12
+ type GatewayReason = (typeof BUSABASE_AIRAPP_GATEWAY_REASONS)[keyof typeof BUSABASE_AIRAPP_GATEWAY_REASONS];
13
+ interface AuthSpace {
14
+ id: string;
15
+ name: string;
16
+ slug?: string | null;
17
+ plan?: string | null;
18
+ }
19
+ interface GatewayTarget {
20
+ baseUrl: string;
21
+ accessToken: string;
22
+ selectedSpace?: AuthSpace;
23
+ source: "airapp-oauth-local" | "environment" | "open-server";
24
+ }
25
+ interface BusabaseAirAppLocalGatewayOptions {
26
+ appId: string;
27
+ cloudBaseUrl?: string;
28
+ clientId?: string;
29
+ environment?: Record<string, string | undefined>;
30
+ fetch?: typeof fetch;
31
+ now?: () => number;
32
+ oauthPendingTtlMs?: number;
33
+ requestTimeoutMs?: number;
34
+ credentialStore?: BusabaseAirAppCredentialStoreOptions;
35
+ successPath?: string;
36
+ errorPath?: string;
37
+ }
38
+ interface BusabaseAirAppAuthStatus {
39
+ connected: boolean;
40
+ cloudBaseUrl: string;
41
+ baseUrl?: string;
42
+ source?: GatewayTarget["source"];
43
+ readiness: "needs_connection" | "needs_auth" | "needs_space" | "ready" | "retry";
44
+ action: "connect" | "reconnect" | "select_space" | "continue" | "retry";
45
+ requiresSpace?: boolean;
46
+ selectedSpace?: AuthSpace | null;
47
+ space?: AuthSpace | null;
48
+ spaces?: AuthSpace[];
49
+ reason?: GatewayReason;
50
+ message?: string;
51
+ }
52
+ declare class BusabaseAirAppLocalGateway {
53
+ #private;
54
+ constructor(options: BusabaseAirAppLocalGatewayOptions);
55
+ get cloudBaseUrl(): string;
56
+ status(): Promise<BusabaseAirAppAuthStatus>;
57
+ statusResponse: () => Promise<Response>;
58
+ start: (request: Request) => Promise<Response>;
59
+ callback: (request: Request) => Promise<Response>;
60
+ selectSpace: (request: Request) => Promise<Response>;
61
+ logout: (request: Request) => Promise<Response>;
62
+ proxy: (request: Request) => Promise<Response>;
63
+ }
64
+ declare const createBusabaseAirAppLocalGateway: (options: BusabaseAirAppLocalGatewayOptions) => BusabaseAirAppLocalGateway;
65
+
66
+ export { BUSABASE_AIRAPP_GATEWAY_REASONS, type BusabaseAirAppAuthStatus, BusabaseAirAppLocalGateway, type BusabaseAirAppLocalGatewayOptions, createBusabaseAirAppLocalGateway };
@@ -0,0 +1,408 @@
1
+ import { getBusabaseAirAppAccessToken, storeBusabaseAirAppSelectedSpace, storeBusabaseAirAppOAuthCredential, loadBusabaseAirAppOAuthCredential, revokeBusabaseAirAppOAuthCredential } from './chunk-B2AWPFDI.js';
2
+ import { BUSABASE_AIRAPP_CLIENT_ID, BusabaseOAuthError, createBusabaseOAuthRequest, parseBusabaseOAuthCallback, exchangeBusabaseOAuthCode } from './chunk-J2DZKX7A.js';
3
+ import './chunk-5NYQX65A.js';
4
+
5
+ // src/airapp-node.ts
6
+ var DEFAULT_CLOUD_BASE_URL = "https://busabase.com";
7
+ var DEFAULT_PENDING_TTL_MS = 5 * 6e4;
8
+ var DEFAULT_TIMEOUT_MS = 8e3;
9
+ var BUSABASE_AIRAPP_GATEWAY_REASONS = {
10
+ authRequired: "AUTH_REQUIRED",
11
+ authUnavailable: "AUTH_UNAVAILABLE",
12
+ connectionRequired: "CONNECTION_REQUIRED",
13
+ oauthCallbackInvalid: "OAUTH_CALLBACK_INVALID",
14
+ spaceNotAllowed: "SPACE_NOT_ALLOWED",
15
+ spaceSelectionRequired: "SPACE_SELECTION_REQUIRED"
16
+ };
17
+ var jsonError = (status, reason, message, data) => Response.json(
18
+ {
19
+ error: message,
20
+ code: status === 401 ? "UNAUTHORIZED" : status === 403 ? "FORBIDDEN" : status === 409 ? "CONFLICT" : status === 503 ? "SERVICE_UNAVAILABLE" : "BAD_REQUEST",
21
+ data: { reason, ...data }
22
+ },
23
+ { status }
24
+ );
25
+ var normalizeOrigin = (raw, fallback = DEFAULT_CLOUD_BASE_URL) => {
26
+ const withoutApi = String(raw || fallback).trim().replace(/\/+$/, "").replace(/\/api\/v1$/, "");
27
+ let url;
28
+ try {
29
+ url = new URL(withoutApi);
30
+ } catch {
31
+ throw new BusabaseOAuthError("invalid_base_url", "Busabase base URL is invalid");
32
+ }
33
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" && url.pathname !== "") {
34
+ throw new BusabaseOAuthError("invalid_base_url", "Busabase base URL must be an origin");
35
+ }
36
+ const loopback = ["localhost", "127.0.0.1", "::1"].includes(url.hostname);
37
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
38
+ throw new BusabaseOAuthError(
39
+ "invalid_base_url",
40
+ "Busabase requires HTTPS except for a loopback development server"
41
+ );
42
+ }
43
+ return url.origin;
44
+ };
45
+ var requestOrigin = (request) => new URL(request.url).origin;
46
+ var assertSameOrigin = (request) => {
47
+ const origin = request.headers.get("origin");
48
+ if (origin && origin !== requestOrigin(request)) {
49
+ throw new BusabaseOAuthError("origin_mismatch", "Request origin did not match");
50
+ }
51
+ };
52
+ var readInput = async (request) => {
53
+ const contentType = request.headers.get("content-type") || "";
54
+ if (contentType.includes("application/json")) {
55
+ return await request.json().catch(() => ({}));
56
+ }
57
+ const form = await request.formData().catch(() => new FormData());
58
+ return Object.fromEntries(form.entries());
59
+ };
60
+ var safeSpaces = (spaces) => spaces.map(({ id, name, slug, plan }) => ({ id, name, slug, plan }));
61
+ var BusabaseAirAppLocalGateway = class {
62
+ #options;
63
+ #pendingOAuth = /* @__PURE__ */ new Map();
64
+ #environmentSelectedSpace;
65
+ constructor(options) {
66
+ this.#options = {
67
+ ...options,
68
+ appId: options.appId,
69
+ cloudBaseUrl: normalizeOrigin(options.cloudBaseUrl || DEFAULT_CLOUD_BASE_URL),
70
+ clientId: options.clientId || BUSABASE_AIRAPP_CLIENT_ID,
71
+ oauthPendingTtlMs: options.oauthPendingTtlMs ?? DEFAULT_PENDING_TTL_MS,
72
+ requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_TIMEOUT_MS,
73
+ successPath: options.successPath || "/",
74
+ errorPath: options.errorPath || "/"
75
+ };
76
+ }
77
+ get cloudBaseUrl() {
78
+ return this.#options.cloudBaseUrl;
79
+ }
80
+ #fetch() {
81
+ return this.#options.fetch ?? fetch;
82
+ }
83
+ #now() {
84
+ return this.#options.now?.() ?? Date.now();
85
+ }
86
+ #environment() {
87
+ return this.#options.environment ?? process.env;
88
+ }
89
+ async #target() {
90
+ const environment = this.#environment();
91
+ if (environment.BUSABASE_BASE_URL) {
92
+ const selectedSpaceId = environment.BUSABASE_SPACE_ID?.trim();
93
+ return {
94
+ baseUrl: normalizeOrigin(environment.BUSABASE_BASE_URL),
95
+ accessToken: environment.BUSABASE_API_KEY || "",
96
+ source: environment.BUSABASE_API_KEY ? "environment" : "open-server",
97
+ ...selectedSpaceId ? { selectedSpace: { id: selectedSpaceId, name: selectedSpaceId } } : this.#environmentSelectedSpace ? { selectedSpace: this.#environmentSelectedSpace } : {}
98
+ };
99
+ }
100
+ const credential = await getBusabaseAirAppAccessToken(
101
+ this.#options.appId,
102
+ this.#options.credentialStore,
103
+ this.#fetch()
104
+ );
105
+ return credential ? {
106
+ baseUrl: credential.baseUrl,
107
+ accessToken: credential.accessToken,
108
+ source: "airapp-oauth-local",
109
+ ...credential.selectedSpace ? { selectedSpace: credential.selectedSpace } : {}
110
+ } : null;
111
+ }
112
+ async #authInfo(target, spaceId = "") {
113
+ const headers = new Headers({ accept: "application/json" });
114
+ if (target.accessToken) headers.set("authorization", `Bearer ${target.accessToken}`);
115
+ if (spaceId) headers.set("x-busabase-space", spaceId);
116
+ const response = await this.#fetch()(new URL("/api/v1/auth", target.baseUrl), {
117
+ headers,
118
+ signal: AbortSignal.timeout(this.#options.requestTimeoutMs)
119
+ });
120
+ if (!response.ok) {
121
+ throw new BusabaseOAuthError(
122
+ response.status === 401 ? "auth_required" : "auth_verification_failed",
123
+ `Busabase auth verification failed (${response.status})`,
124
+ response.status
125
+ );
126
+ }
127
+ const info = await response.json();
128
+ if (!Array.isArray(info.spaces)) {
129
+ throw new BusabaseOAuthError(
130
+ "invalid_auth_response",
131
+ "Busabase auth response did not include Spaces"
132
+ );
133
+ }
134
+ return info;
135
+ }
136
+ #persistSelectedSpace(target, selectedSpace) {
137
+ if (target.source === "airapp-oauth-local") {
138
+ storeBusabaseAirAppSelectedSpace(
139
+ this.#options.appId,
140
+ selectedSpace ? { id: selectedSpace.id, name: selectedSpace.name } : null,
141
+ this.#options.credentialStore
142
+ );
143
+ } else {
144
+ this.#environmentSelectedSpace = selectedSpace || void 0;
145
+ }
146
+ }
147
+ async status() {
148
+ let target = null;
149
+ try {
150
+ target = await this.#target();
151
+ if (!target) {
152
+ return {
153
+ connected: false,
154
+ cloudBaseUrl: this.cloudBaseUrl,
155
+ readiness: "needs_connection",
156
+ action: "connect",
157
+ reason: BUSABASE_AIRAPP_GATEWAY_REASONS.connectionRequired
158
+ };
159
+ }
160
+ const info = await this.#authInfo(target);
161
+ const spaces = safeSpaces(info.spaces);
162
+ if (!spaces.length) {
163
+ this.#persistSelectedSpace(target, null);
164
+ return {
165
+ connected: true,
166
+ cloudBaseUrl: this.cloudBaseUrl,
167
+ baseUrl: target.baseUrl,
168
+ source: target.source,
169
+ readiness: "needs_space",
170
+ action: "retry",
171
+ requiresSpace: true,
172
+ selectedSpace: null,
173
+ space: null,
174
+ spaces,
175
+ reason: BUSABASE_AIRAPP_GATEWAY_REASONS.spaceSelectionRequired,
176
+ message: "This account has no accessible Busabase Space"
177
+ };
178
+ }
179
+ const selectedSpaceId = target.selectedSpace?.id;
180
+ let selected = selectedSpaceId ? spaces.find((space) => space.id === selectedSpaceId) : void 0;
181
+ if (!selected && spaces.length === 1) selected = spaces[0];
182
+ if (target.selectedSpace && !selected) this.#persistSelectedSpace(target, null);
183
+ if (selected && selected.id !== selectedSpaceId) {
184
+ await this.#authInfo(target, selected.id);
185
+ this.#persistSelectedSpace(target, selected);
186
+ }
187
+ return {
188
+ connected: true,
189
+ cloudBaseUrl: this.cloudBaseUrl,
190
+ baseUrl: target.baseUrl,
191
+ source: target.source,
192
+ readiness: selected ? "ready" : "needs_space",
193
+ action: selected ? "continue" : "select_space",
194
+ requiresSpace: !selected,
195
+ selectedSpace: selected || null,
196
+ space: selected || null,
197
+ spaces,
198
+ ...selected ? {} : { reason: BUSABASE_AIRAPP_GATEWAY_REASONS.spaceSelectionRequired }
199
+ };
200
+ } catch (error) {
201
+ const authRequired = error instanceof BusabaseOAuthError && error.status === 401;
202
+ return {
203
+ connected: Boolean(target) && !authRequired,
204
+ cloudBaseUrl: this.cloudBaseUrl,
205
+ ...target ? { baseUrl: target.baseUrl, source: target.source, requiresSpace: true } : {},
206
+ readiness: authRequired ? "needs_auth" : "retry",
207
+ action: authRequired ? "reconnect" : "retry",
208
+ reason: authRequired ? BUSABASE_AIRAPP_GATEWAY_REASONS.authRequired : BUSABASE_AIRAPP_GATEWAY_REASONS.authUnavailable,
209
+ message: error instanceof Error ? error.message : "Busabase auth verification failed"
210
+ };
211
+ }
212
+ }
213
+ statusResponse = async () => Response.json(await this.status());
214
+ start = async (request) => {
215
+ try {
216
+ assertSameOrigin(request);
217
+ const body = await readInput(request);
218
+ const baseUrl = normalizeOrigin(String(body.base_url || ""), this.cloudBaseUrl);
219
+ const redirectUri = new URL("/auth/callback", requestOrigin(request)).toString();
220
+ const oauthRequest = await createBusabaseOAuthRequest({
221
+ baseUrl,
222
+ redirectUri,
223
+ clientId: this.#options.clientId
224
+ });
225
+ const probe = await this.#fetch()(oauthRequest.authorizeUrl, {
226
+ headers: { accept: "text/html" },
227
+ redirect: "manual",
228
+ signal: AbortSignal.timeout(this.#options.requestTimeoutMs)
229
+ });
230
+ if (probe.status >= 400) {
231
+ throw new BusabaseOAuthError(
232
+ "oauth_unavailable",
233
+ `Busabase OAuth is unavailable (${probe.status})`,
234
+ probe.status
235
+ );
236
+ }
237
+ this.#pendingOAuth.set(oauthRequest.state, {
238
+ ...oauthRequest,
239
+ expiresAt: this.#now() + this.#options.oauthPendingTtlMs
240
+ });
241
+ return Response.redirect(oauthRequest.authorizeUrl, 303);
242
+ } catch (error) {
243
+ const redirect = new URL(this.#options.errorPath, requestOrigin(request));
244
+ redirect.searchParams.set(
245
+ "oauth_error",
246
+ error instanceof Error ? error.message : "Unable to start Busabase OAuth"
247
+ );
248
+ return Response.redirect(redirect, 303);
249
+ }
250
+ };
251
+ callback = async (request) => {
252
+ const callback = new URL(request.url);
253
+ const state = callback.searchParams.get("state") || "";
254
+ const pending = this.#pendingOAuth.get(state);
255
+ this.#pendingOAuth.delete(state);
256
+ try {
257
+ if (!pending || pending.expiresAt <= this.#now()) {
258
+ throw new BusabaseOAuthError("oauth_request_expired", "OAuth request expired");
259
+ }
260
+ const code = parseBusabaseOAuthCallback(callback.toString(), pending);
261
+ const tokenSet = await exchangeBusabaseOAuthCode(pending, code, this.#fetch());
262
+ storeBusabaseAirAppOAuthCredential(
263
+ {
264
+ appId: this.#options.appId,
265
+ baseUrl: pending.baseUrl,
266
+ clientId: this.#options.clientId,
267
+ tokenSet
268
+ },
269
+ this.#options.credentialStore
270
+ );
271
+ return Response.redirect(new URL(this.#options.successPath, requestOrigin(request)), 303);
272
+ } catch (error) {
273
+ const redirect = new URL(this.#options.errorPath, requestOrigin(request));
274
+ redirect.searchParams.set(
275
+ "oauth_error",
276
+ error instanceof Error ? error.message : "Busabase OAuth callback failed"
277
+ );
278
+ return Response.redirect(redirect, 303);
279
+ }
280
+ };
281
+ selectSpace = async (request) => {
282
+ try {
283
+ assertSameOrigin(request);
284
+ const body = await readInput(request);
285
+ const spaceId = String(body.space_id || "").trim();
286
+ const target = await this.#target();
287
+ if (!target) {
288
+ return jsonError(
289
+ 401,
290
+ BUSABASE_AIRAPP_GATEWAY_REASONS.connectionRequired,
291
+ "Connect Busabase before selecting a Space"
292
+ );
293
+ }
294
+ const info = await this.#authInfo(target);
295
+ const selected = info.spaces.find((space) => space.id === spaceId);
296
+ if (!selected) {
297
+ return jsonError(
298
+ 403,
299
+ BUSABASE_AIRAPP_GATEWAY_REASONS.spaceNotAllowed,
300
+ "The selected Space is not accessible to this account"
301
+ );
302
+ }
303
+ await this.#authInfo(target, selected.id);
304
+ this.#persistSelectedSpace(target, selected);
305
+ return Response.json({ ok: true, space: { id: selected.id, name: selected.name } });
306
+ } catch (error) {
307
+ return jsonError(
308
+ 400,
309
+ BUSABASE_AIRAPP_GATEWAY_REASONS.authUnavailable,
310
+ error instanceof Error ? error.message : "Unable to select Busabase Space"
311
+ );
312
+ }
313
+ };
314
+ logout = async (request) => {
315
+ try {
316
+ assertSameOrigin(request);
317
+ if (loadBusabaseAirAppOAuthCredential(this.#options.appId, this.#options.credentialStore)) {
318
+ await revokeBusabaseAirAppOAuthCredential(
319
+ this.#options.appId,
320
+ this.#options.credentialStore,
321
+ this.#fetch()
322
+ ).catch(() => void 0);
323
+ }
324
+ this.#environmentSelectedSpace = void 0;
325
+ return Response.json({ ok: true });
326
+ } catch (error) {
327
+ return jsonError(
328
+ 400,
329
+ BUSABASE_AIRAPP_GATEWAY_REASONS.authUnavailable,
330
+ error instanceof Error ? error.message : "Unable to disconnect Busabase"
331
+ );
332
+ }
333
+ };
334
+ proxy = async (request) => {
335
+ let target;
336
+ try {
337
+ target = await this.#target();
338
+ } catch {
339
+ return jsonError(
340
+ 401,
341
+ BUSABASE_AIRAPP_GATEWAY_REASONS.authRequired,
342
+ "Busabase authentication expired"
343
+ );
344
+ }
345
+ if (!target) {
346
+ return jsonError(
347
+ 401,
348
+ BUSABASE_AIRAPP_GATEWAY_REASONS.connectionRequired,
349
+ "Busabase connection required"
350
+ );
351
+ }
352
+ let selectedSpace = target.selectedSpace;
353
+ if (!selectedSpace) {
354
+ try {
355
+ const info = await this.#authInfo(target);
356
+ if (info.spaces.length === 1) {
357
+ selectedSpace = info.spaces[0];
358
+ this.#persistSelectedSpace(target, selectedSpace);
359
+ }
360
+ } catch {
361
+ return jsonError(
362
+ 503,
363
+ BUSABASE_AIRAPP_GATEWAY_REASONS.authUnavailable,
364
+ "Busabase authentication could not be verified"
365
+ );
366
+ }
367
+ }
368
+ if (!selectedSpace) {
369
+ return jsonError(
370
+ 409,
371
+ BUSABASE_AIRAPP_GATEWAY_REASONS.spaceSelectionRequired,
372
+ "Busabase Space selection required"
373
+ );
374
+ }
375
+ const incoming = new URL(request.url);
376
+ const targetUrl = new URL(incoming.pathname + incoming.search, target.baseUrl);
377
+ const headers = new Headers();
378
+ const contentType = request.headers.get("content-type");
379
+ const accept = request.headers.get("accept");
380
+ if (contentType) headers.set("content-type", contentType);
381
+ if (accept) headers.set("accept", accept);
382
+ headers.set("x-busabase-space", selectedSpace.id);
383
+ if (target.accessToken) headers.set("authorization", `Bearer ${target.accessToken}`);
384
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
385
+ let upstream;
386
+ try {
387
+ upstream = await this.#fetch()(targetUrl, {
388
+ method: request.method,
389
+ headers,
390
+ body: hasBody ? await request.arrayBuffer() : void 0,
391
+ redirect: "manual"
392
+ });
393
+ } catch {
394
+ return jsonError(
395
+ 503,
396
+ BUSABASE_AIRAPP_GATEWAY_REASONS.authUnavailable,
397
+ "Busabase API is temporarily unavailable"
398
+ );
399
+ }
400
+ const responseHeaders = new Headers();
401
+ const upstreamType = upstream.headers.get("content-type");
402
+ if (upstreamType) responseHeaders.set("content-type", upstreamType);
403
+ return new Response(upstream.body, { status: upstream.status, headers: responseHeaders });
404
+ };
405
+ };
406
+ var createBusabaseAirAppLocalGateway = (options) => new BusabaseAirAppLocalGateway(options);
407
+
408
+ export { BUSABASE_AIRAPP_GATEWAY_REASONS, BusabaseAirAppLocalGateway, createBusabaseAirAppLocalGateway };
@@ -0,0 +1,175 @@
1
+ import { BusabaseOAuthError, BUSABASE_AIRAPP_CLIENT_ID, refreshBusabaseOAuthToken, revokeBusabaseOAuthToken } from './chunk-J2DZKX7A.js';
2
+ import { normalizeBaseUrl } from './chunk-5NYQX65A.js';
3
+ import { randomUUID } from 'crypto';
4
+ import { readFileSync, mkdirSync, chmodSync, writeFileSync, renameSync, rmSync } from 'fs';
5
+ import { homedir } from 'os';
6
+ import { join, dirname } from 'path';
7
+
8
+ var STORE_VERSION = 1;
9
+ var APP_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
10
+ var REFRESH_WINDOW_MS = 6e4;
11
+ var refreshesByCredentialPath = /* @__PURE__ */ new Map();
12
+ var assertAppId = (appId) => {
13
+ if (!APP_ID_RE.test(appId)) {
14
+ throw new BusabaseOAuthError(
15
+ "invalid_airapp_id",
16
+ "AirApp id must use letters, digits, dot, dash, or underscore"
17
+ );
18
+ }
19
+ return appId;
20
+ };
21
+ var storeRoot = (options = {}) => options.rootDir ?? join(homedir(), ".busabase");
22
+ var busabaseAirAppCredentialsDir = (options = {}) => join(storeRoot(options), "airapps");
23
+ var busabaseAirAppCredentialPath = (appId, options = {}) => join(busabaseAirAppCredentialsDir(options), `${assertAppId(appId)}.json`);
24
+ var normalizeOrigin = (raw) => {
25
+ const url = new URL(normalizeBaseUrl(raw));
26
+ if (url.username || url.password || url.search || url.hash) {
27
+ throw new BusabaseOAuthError("invalid_base_url", "Busabase base URL must be an origin");
28
+ }
29
+ return url.origin;
30
+ };
31
+ var parseCredential = (raw, expectedAppId) => {
32
+ let value;
33
+ try {
34
+ value = JSON.parse(raw);
35
+ } catch {
36
+ throw new BusabaseOAuthError("invalid_local_credential", "AirApp OAuth credential is invalid");
37
+ }
38
+ const item = value;
39
+ if (item.version !== STORE_VERSION || item.appId !== expectedAppId || typeof item.baseUrl !== "string" || typeof item.clientId !== "string" || typeof item.accessToken !== "string" || typeof item.refreshToken !== "string" || typeof item.expiresAt !== "string" || !Array.isArray(item.scope) || item.scope.some((scope) => typeof scope !== "string") || typeof item.tokenType !== "string") {
40
+ throw new BusabaseOAuthError("invalid_local_credential", "AirApp OAuth credential is invalid");
41
+ }
42
+ if (item.selectedSpace !== void 0 && (typeof item.selectedSpace !== "object" || item.selectedSpace === null || typeof item.selectedSpace.id !== "string" || typeof item.selectedSpace.name !== "string")) {
43
+ throw new BusabaseOAuthError("invalid_local_credential", "AirApp OAuth credential is invalid");
44
+ }
45
+ return item;
46
+ };
47
+ function loadBusabaseAirAppOAuthCredential(appId, options = {}) {
48
+ const path = busabaseAirAppCredentialPath(appId, options);
49
+ try {
50
+ return parseCredential(readFileSync(path, "utf8"), appId);
51
+ } catch (error) {
52
+ if (error.code === "ENOENT") return null;
53
+ throw error;
54
+ }
55
+ }
56
+ function storeBusabaseAirAppOAuthCredential(input, options = {}) {
57
+ if (!input.tokenSet.refreshToken) {
58
+ throw new BusabaseOAuthError(
59
+ "missing_refresh_token",
60
+ "A refresh token is required for a persistent local AirApp login"
61
+ );
62
+ }
63
+ const credential = {
64
+ version: STORE_VERSION,
65
+ appId: assertAppId(input.appId),
66
+ baseUrl: normalizeOrigin(input.baseUrl),
67
+ clientId: input.clientId ?? BUSABASE_AIRAPP_CLIENT_ID,
68
+ accessToken: input.tokenSet.accessToken,
69
+ refreshToken: input.tokenSet.refreshToken,
70
+ expiresAt: input.tokenSet.expiresAt,
71
+ scope: input.tokenSet.scope,
72
+ tokenType: input.tokenSet.tokenType,
73
+ ...input.selectedSpace ? { selectedSpace: input.selectedSpace } : {}
74
+ };
75
+ const path = busabaseAirAppCredentialPath(input.appId, options);
76
+ const directory = dirname(path);
77
+ mkdirSync(directory, { recursive: true, mode: 448 });
78
+ try {
79
+ chmodSync(directory, 448);
80
+ } catch {
81
+ }
82
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
83
+ writeFileSync(temporaryPath, `${JSON.stringify(credential, null, 2)}
84
+ `, { mode: 384 });
85
+ try {
86
+ chmodSync(temporaryPath, 384);
87
+ } catch {
88
+ }
89
+ renameSync(temporaryPath, path);
90
+ return credential;
91
+ }
92
+ async function getBusabaseAirAppAccessToken(appId, options = {}, fetchImpl = fetch) {
93
+ const credential = loadBusabaseAirAppOAuthCredential(appId, options);
94
+ if (!credential) return null;
95
+ const expiresAt = Date.parse(credential.expiresAt);
96
+ if (Number.isFinite(expiresAt) && expiresAt > Date.now() + REFRESH_WINDOW_MS) return credential;
97
+ const credentialPath = busabaseAirAppCredentialPath(appId, options);
98
+ const activeRefresh = refreshesByCredentialPath.get(credentialPath);
99
+ if (activeRefresh) return activeRefresh;
100
+ const refresh = (async () => {
101
+ const tokenSet = await refreshBusabaseOAuthToken(
102
+ {
103
+ baseUrl: credential.baseUrl,
104
+ refreshToken: credential.refreshToken,
105
+ clientId: credential.clientId
106
+ },
107
+ fetchImpl
108
+ );
109
+ return storeBusabaseAirAppOAuthCredential(
110
+ {
111
+ appId,
112
+ baseUrl: credential.baseUrl,
113
+ clientId: credential.clientId,
114
+ tokenSet: {
115
+ ...tokenSet,
116
+ refreshToken: tokenSet.refreshToken ?? credential.refreshToken
117
+ },
118
+ selectedSpace: credential.selectedSpace
119
+ },
120
+ options
121
+ );
122
+ })();
123
+ refreshesByCredentialPath.set(credentialPath, refresh);
124
+ try {
125
+ return await refresh;
126
+ } finally {
127
+ if (refreshesByCredentialPath.get(credentialPath) === refresh) {
128
+ refreshesByCredentialPath.delete(credentialPath);
129
+ }
130
+ }
131
+ }
132
+ function storeBusabaseAirAppSelectedSpace(appId, selectedSpace, options = {}) {
133
+ const credential = loadBusabaseAirAppOAuthCredential(appId, options);
134
+ if (!credential) {
135
+ throw new BusabaseOAuthError(
136
+ "missing_local_credential",
137
+ "Connect this local AirApp before selecting a Space"
138
+ );
139
+ }
140
+ const next = {
141
+ ...credential,
142
+ ...selectedSpace ? { selectedSpace } : { selectedSpace: void 0 }
143
+ };
144
+ const path = busabaseAirAppCredentialPath(appId, options);
145
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
146
+ writeFileSync(temporaryPath, `${JSON.stringify(next, null, 2)}
147
+ `, { mode: 384 });
148
+ try {
149
+ chmodSync(temporaryPath, 384);
150
+ } catch {
151
+ }
152
+ renameSync(temporaryPath, path);
153
+ return next;
154
+ }
155
+ function clearBusabaseAirAppOAuthCredential(appId, options = {}) {
156
+ rmSync(busabaseAirAppCredentialPath(appId, options), { force: true });
157
+ }
158
+ async function revokeBusabaseAirAppOAuthCredential(appId, options = {}, fetchImpl = fetch) {
159
+ const credential = loadBusabaseAirAppOAuthCredential(appId, options);
160
+ if (!credential) return;
161
+ try {
162
+ await revokeBusabaseOAuthToken(
163
+ {
164
+ baseUrl: credential.baseUrl,
165
+ token: credential.refreshToken,
166
+ clientId: credential.clientId
167
+ },
168
+ fetchImpl
169
+ );
170
+ } finally {
171
+ clearBusabaseAirAppOAuthCredential(appId, options);
172
+ }
173
+ }
174
+
175
+ export { busabaseAirAppCredentialPath, busabaseAirAppCredentialsDir, clearBusabaseAirAppOAuthCredential, getBusabaseAirAppAccessToken, loadBusabaseAirAppOAuthCredential, revokeBusabaseAirAppOAuthCredential, storeBusabaseAirAppOAuthCredential, storeBusabaseAirAppSelectedSpace };
@@ -10,6 +10,11 @@ interface BusabaseAirAppOAuthCredential {
10
10
  expiresAt: string;
11
11
  scope: string[];
12
12
  tokenType: string;
13
+ /** Validated target for this local AirApp. Tokens remain user-scoped. */
14
+ selectedSpace?: {
15
+ id: string;
16
+ name: string;
17
+ };
13
18
  }
14
19
  interface BusabaseAirAppCredentialStoreOptions {
15
20
  /** Override only for tests or an explicitly isolated installation. */
@@ -24,10 +29,16 @@ declare function storeBusabaseAirAppOAuthCredential(input: {
24
29
  baseUrl: string;
25
30
  tokenSet: BusabaseOAuthTokenSet;
26
31
  clientId?: string;
32
+ selectedSpace?: BusabaseAirAppOAuthCredential["selectedSpace"];
27
33
  }, options?: BusabaseAirAppCredentialStoreOptions): BusabaseAirAppOAuthCredential;
28
34
  /** Load a valid access token, rotating and persisting the token set when needed. */
29
35
  declare function getBusabaseAirAppAccessToken(appId: string, options?: BusabaseAirAppCredentialStoreOptions, fetchImpl?: typeof fetch): Promise<BusabaseAirAppOAuthCredential | null>;
36
+ /** Persist a Space only after the caller has verified membership through `/api/v1/auth`. */
37
+ declare function storeBusabaseAirAppSelectedSpace(appId: string, selectedSpace: {
38
+ id: string;
39
+ name: string;
40
+ } | null, options?: BusabaseAirAppCredentialStoreOptions): BusabaseAirAppOAuthCredential;
30
41
  declare function clearBusabaseAirAppOAuthCredential(appId: string, options?: BusabaseAirAppCredentialStoreOptions): void;
31
42
  declare function revokeBusabaseAirAppOAuthCredential(appId: string, options?: BusabaseAirAppCredentialStoreOptions, fetchImpl?: typeof fetch): Promise<void>;
32
43
 
33
- export { type BusabaseAirAppCredentialStoreOptions, type BusabaseAirAppOAuthCredential, busabaseAirAppCredentialPath, busabaseAirAppCredentialsDir, clearBusabaseAirAppOAuthCredential, getBusabaseAirAppAccessToken, loadBusabaseAirAppOAuthCredential, revokeBusabaseAirAppOAuthCredential, storeBusabaseAirAppOAuthCredential };
44
+ export { type BusabaseAirAppCredentialStoreOptions, type BusabaseAirAppOAuthCredential, busabaseAirAppCredentialPath, busabaseAirAppCredentialsDir, clearBusabaseAirAppOAuthCredential, getBusabaseAirAppAccessToken, loadBusabaseAirAppOAuthCredential, revokeBusabaseAirAppOAuthCredential, storeBusabaseAirAppOAuthCredential, storeBusabaseAirAppSelectedSpace };
@@ -1,147 +1,3 @@
1
- import { BusabaseOAuthError, BUSABASE_AIRAPP_CLIENT_ID, refreshBusabaseOAuthToken, revokeBusabaseOAuthToken } from './chunk-J2DZKX7A.js';
2
- import { normalizeBaseUrl } from './chunk-5NYQX65A.js';
3
- import { randomUUID } from 'crypto';
4
- import { readFileSync, mkdirSync, chmodSync, writeFileSync, renameSync, rmSync } from 'fs';
5
- import { homedir } from 'os';
6
- import { join, dirname } from 'path';
7
-
8
- var STORE_VERSION = 1;
9
- var APP_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
10
- var REFRESH_WINDOW_MS = 6e4;
11
- var refreshesByCredentialPath = /* @__PURE__ */ new Map();
12
- var assertAppId = (appId) => {
13
- if (!APP_ID_RE.test(appId)) {
14
- throw new BusabaseOAuthError(
15
- "invalid_airapp_id",
16
- "AirApp id must use letters, digits, dot, dash, or underscore"
17
- );
18
- }
19
- return appId;
20
- };
21
- var storeRoot = (options = {}) => options.rootDir ?? join(homedir(), ".busabase");
22
- var busabaseAirAppCredentialsDir = (options = {}) => join(storeRoot(options), "airapps");
23
- var busabaseAirAppCredentialPath = (appId, options = {}) => join(busabaseAirAppCredentialsDir(options), `${assertAppId(appId)}.json`);
24
- var normalizeOrigin = (raw) => {
25
- const url = new URL(normalizeBaseUrl(raw));
26
- if (url.username || url.password || url.search || url.hash) {
27
- throw new BusabaseOAuthError("invalid_base_url", "Busabase base URL must be an origin");
28
- }
29
- return url.origin;
30
- };
31
- var parseCredential = (raw, expectedAppId) => {
32
- let value;
33
- try {
34
- value = JSON.parse(raw);
35
- } catch {
36
- throw new BusabaseOAuthError("invalid_local_credential", "AirApp OAuth credential is invalid");
37
- }
38
- const item = value;
39
- if (item.version !== STORE_VERSION || item.appId !== expectedAppId || typeof item.baseUrl !== "string" || typeof item.clientId !== "string" || typeof item.accessToken !== "string" || typeof item.refreshToken !== "string" || typeof item.expiresAt !== "string" || !Array.isArray(item.scope) || item.scope.some((scope) => typeof scope !== "string") || typeof item.tokenType !== "string") {
40
- throw new BusabaseOAuthError("invalid_local_credential", "AirApp OAuth credential is invalid");
41
- }
42
- return item;
43
- };
44
- function loadBusabaseAirAppOAuthCredential(appId, options = {}) {
45
- const path = busabaseAirAppCredentialPath(appId, options);
46
- try {
47
- return parseCredential(readFileSync(path, "utf8"), appId);
48
- } catch (error) {
49
- if (error.code === "ENOENT") return null;
50
- throw error;
51
- }
52
- }
53
- function storeBusabaseAirAppOAuthCredential(input, options = {}) {
54
- if (!input.tokenSet.refreshToken) {
55
- throw new BusabaseOAuthError(
56
- "missing_refresh_token",
57
- "A refresh token is required for a persistent local AirApp login"
58
- );
59
- }
60
- const credential = {
61
- version: STORE_VERSION,
62
- appId: assertAppId(input.appId),
63
- baseUrl: normalizeOrigin(input.baseUrl),
64
- clientId: input.clientId ?? BUSABASE_AIRAPP_CLIENT_ID,
65
- accessToken: input.tokenSet.accessToken,
66
- refreshToken: input.tokenSet.refreshToken,
67
- expiresAt: input.tokenSet.expiresAt,
68
- scope: input.tokenSet.scope,
69
- tokenType: input.tokenSet.tokenType
70
- };
71
- const path = busabaseAirAppCredentialPath(input.appId, options);
72
- const directory = dirname(path);
73
- mkdirSync(directory, { recursive: true, mode: 448 });
74
- try {
75
- chmodSync(directory, 448);
76
- } catch {
77
- }
78
- const temporaryPath = `${path}.${randomUUID()}.tmp`;
79
- writeFileSync(temporaryPath, `${JSON.stringify(credential, null, 2)}
80
- `, { mode: 384 });
81
- try {
82
- chmodSync(temporaryPath, 384);
83
- } catch {
84
- }
85
- renameSync(temporaryPath, path);
86
- return credential;
87
- }
88
- async function getBusabaseAirAppAccessToken(appId, options = {}, fetchImpl = fetch) {
89
- const credential = loadBusabaseAirAppOAuthCredential(appId, options);
90
- if (!credential) return null;
91
- const expiresAt = Date.parse(credential.expiresAt);
92
- if (Number.isFinite(expiresAt) && expiresAt > Date.now() + REFRESH_WINDOW_MS) return credential;
93
- const credentialPath = busabaseAirAppCredentialPath(appId, options);
94
- const activeRefresh = refreshesByCredentialPath.get(credentialPath);
95
- if (activeRefresh) return activeRefresh;
96
- const refresh = (async () => {
97
- const tokenSet = await refreshBusabaseOAuthToken(
98
- {
99
- baseUrl: credential.baseUrl,
100
- refreshToken: credential.refreshToken,
101
- clientId: credential.clientId
102
- },
103
- fetchImpl
104
- );
105
- return storeBusabaseAirAppOAuthCredential(
106
- {
107
- appId,
108
- baseUrl: credential.baseUrl,
109
- clientId: credential.clientId,
110
- tokenSet: {
111
- ...tokenSet,
112
- refreshToken: tokenSet.refreshToken ?? credential.refreshToken
113
- }
114
- },
115
- options
116
- );
117
- })();
118
- refreshesByCredentialPath.set(credentialPath, refresh);
119
- try {
120
- return await refresh;
121
- } finally {
122
- if (refreshesByCredentialPath.get(credentialPath) === refresh) {
123
- refreshesByCredentialPath.delete(credentialPath);
124
- }
125
- }
126
- }
127
- function clearBusabaseAirAppOAuthCredential(appId, options = {}) {
128
- rmSync(busabaseAirAppCredentialPath(appId, options), { force: true });
129
- }
130
- async function revokeBusabaseAirAppOAuthCredential(appId, options = {}, fetchImpl = fetch) {
131
- const credential = loadBusabaseAirAppOAuthCredential(appId, options);
132
- if (!credential) return;
133
- try {
134
- await revokeBusabaseOAuthToken(
135
- {
136
- baseUrl: credential.baseUrl,
137
- token: credential.refreshToken,
138
- clientId: credential.clientId
139
- },
140
- fetchImpl
141
- );
142
- } finally {
143
- clearBusabaseAirAppOAuthCredential(appId, options);
144
- }
145
- }
146
-
147
- export { busabaseAirAppCredentialPath, busabaseAirAppCredentialsDir, clearBusabaseAirAppOAuthCredential, getBusabaseAirAppAccessToken, loadBusabaseAirAppOAuthCredential, revokeBusabaseAirAppOAuthCredential, storeBusabaseAirAppOAuthCredential };
1
+ export { busabaseAirAppCredentialPath, busabaseAirAppCredentialsDir, clearBusabaseAirAppOAuthCredential, getBusabaseAirAppAccessToken, loadBusabaseAirAppOAuthCredential, revokeBusabaseAirAppOAuthCredential, storeBusabaseAirAppOAuthCredential, storeBusabaseAirAppSelectedSpace } from './chunk-B2AWPFDI.js';
2
+ import './chunk-J2DZKX7A.js';
3
+ import './chunk-5NYQX65A.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "busabase-sdk",
3
- "version": "0.14.1",
3
+ "version": "0.15.0",
4
4
  "description": "Typed TypeScript/JavaScript SDK for the Busabase OpenAPI REST API. Talks to a local or remote `busabase server` (or Busabase Cloud).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/busabase/busabase/tree/main/apps/busabase-sdk",
@@ -30,6 +30,10 @@
30
30
  "./oauth-node": {
31
31
  "types": "./dist/oauth-node.d.ts",
32
32
  "default": "./dist/oauth-node.js"
33
+ },
34
+ "./airapp-node": {
35
+ "types": "./dist/airapp-node.d.ts",
36
+ "default": "./dist/airapp-node.js"
33
37
  }
34
38
  },
35
39
  "files": [
@@ -49,8 +53,8 @@
49
53
  "tsx": "^4.20.5",
50
54
  "typescript": "^5.9.3",
51
55
  "vitest": "^2.1.8",
52
- "busabase-contract": "0.14.1",
53
56
  "open-domains": "0.0.2",
57
+ "busabase-contract": "0.15.0",
54
58
  "openlib": "0.1.1"
55
59
  },
56
60
  "engines": {