busa-sdk 0.14.1 → 0.16.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,211 @@
1
+ import { BusabaseOAuthError, BUSABASE_AIRAPP_CLIENT_ID, refreshBusabaseOAuthToken, revokeBusabaseOAuthToken } from './chunk-WSHJMHUS.js';
2
+ import { normalizeBaseUrl } from './chunk-5NYQX65A.js';
3
+ import { randomUUID } from 'crypto';
4
+ import { readFileSync, rmSync, mkdirSync, chmodSync, writeFileSync, renameSync } 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 busabaseAirAppDynamicClientsPath = (appId, options = {}) => join(busabaseAirAppCredentialsDir(options), `${assertAppId(appId)}.clients.json`);
25
+ var normalizeOrigin = (raw) => {
26
+ const url = new URL(normalizeBaseUrl(raw));
27
+ if (url.username || url.password || url.search || url.hash) {
28
+ throw new BusabaseOAuthError("invalid_base_url", "Busabase base URL must be an origin");
29
+ }
30
+ return url.origin;
31
+ };
32
+ var writeOwnerOnlyJson = (path, value) => {
33
+ const directory = dirname(path);
34
+ mkdirSync(directory, { recursive: true, mode: 448 });
35
+ try {
36
+ chmodSync(directory, 448);
37
+ } catch {
38
+ }
39
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
40
+ writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}
41
+ `, { mode: 384 });
42
+ try {
43
+ chmodSync(temporaryPath, 384);
44
+ } catch {
45
+ }
46
+ renameSync(temporaryPath, path);
47
+ };
48
+ var parseCredential = (raw, expectedAppId) => {
49
+ let value;
50
+ try {
51
+ value = JSON.parse(raw);
52
+ } catch {
53
+ throw new BusabaseOAuthError("invalid_local_credential", "AirApp OAuth credential is invalid");
54
+ }
55
+ const item = value;
56
+ 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") {
57
+ throw new BusabaseOAuthError("invalid_local_credential", "AirApp OAuth credential is invalid");
58
+ }
59
+ if (item.selectedSpace !== void 0 && (typeof item.selectedSpace !== "object" || item.selectedSpace === null || typeof item.selectedSpace.id !== "string" || typeof item.selectedSpace.name !== "string")) {
60
+ throw new BusabaseOAuthError("invalid_local_credential", "AirApp OAuth credential is invalid");
61
+ }
62
+ return item;
63
+ };
64
+ function loadBusabaseAirAppOAuthCredential(appId, options = {}) {
65
+ const path = busabaseAirAppCredentialPath(appId, options);
66
+ try {
67
+ return parseCredential(readFileSync(path, "utf8"), appId);
68
+ } catch (error) {
69
+ if (error.code === "ENOENT") return null;
70
+ throw error;
71
+ }
72
+ }
73
+ function storeBusabaseAirAppOAuthCredential(input, options = {}) {
74
+ if (!input.tokenSet.refreshToken) {
75
+ throw new BusabaseOAuthError(
76
+ "missing_refresh_token",
77
+ "A refresh token is required for a persistent local AirApp login"
78
+ );
79
+ }
80
+ const credential = {
81
+ version: STORE_VERSION,
82
+ appId: assertAppId(input.appId),
83
+ baseUrl: normalizeOrigin(input.baseUrl),
84
+ clientId: input.clientId ?? BUSABASE_AIRAPP_CLIENT_ID,
85
+ accessToken: input.tokenSet.accessToken,
86
+ refreshToken: input.tokenSet.refreshToken,
87
+ expiresAt: input.tokenSet.expiresAt,
88
+ scope: input.tokenSet.scope,
89
+ tokenType: input.tokenSet.tokenType,
90
+ ...input.selectedSpace ? { selectedSpace: input.selectedSpace } : {}
91
+ };
92
+ writeOwnerOnlyJson(busabaseAirAppCredentialPath(input.appId, options), credential);
93
+ return credential;
94
+ }
95
+ var dynamicClientKey = (baseUrl, redirectUri) => `${normalizeOrigin(baseUrl)}|${new URL(redirectUri).toString()}`;
96
+ var loadDynamicClientRegistry = (appId, options) => {
97
+ const empty = {
98
+ version: STORE_VERSION,
99
+ appId: assertAppId(appId),
100
+ clients: {}
101
+ };
102
+ let raw;
103
+ try {
104
+ raw = readFileSync(busabaseAirAppDynamicClientsPath(appId, options), "utf8");
105
+ } catch (error) {
106
+ if (error.code === "ENOENT") return empty;
107
+ throw error;
108
+ }
109
+ try {
110
+ const value = JSON.parse(raw);
111
+ if (value.version !== STORE_VERSION || value.appId !== appId || typeof value.clients !== "object" || value.clients === null) {
112
+ return empty;
113
+ }
114
+ const clients = Object.fromEntries(
115
+ Object.entries(value.clients).filter(([, clientId]) => typeof clientId === "string")
116
+ );
117
+ return { ...empty, clients };
118
+ } catch {
119
+ return empty;
120
+ }
121
+ };
122
+ function loadBusabaseAirAppDynamicClientId(input, options = {}) {
123
+ const registry = loadDynamicClientRegistry(input.appId, options);
124
+ return registry.clients[dynamicClientKey(input.baseUrl, input.redirectUri)] ?? null;
125
+ }
126
+ function storeBusabaseAirAppDynamicClientId(input, options = {}) {
127
+ const registry = loadDynamicClientRegistry(input.appId, options);
128
+ const key = dynamicClientKey(input.baseUrl, input.redirectUri);
129
+ delete registry.clients[key];
130
+ const entries = [...Object.entries(registry.clients), [key, input.clientId]];
131
+ writeOwnerOnlyJson(busabaseAirAppDynamicClientsPath(input.appId, options), {
132
+ ...registry,
133
+ clients: Object.fromEntries(entries.slice(-32))
134
+ });
135
+ }
136
+ async function getBusabaseAirAppAccessToken(appId, options = {}, fetchImpl = fetch) {
137
+ const credential = loadBusabaseAirAppOAuthCredential(appId, options);
138
+ if (!credential) return null;
139
+ const expiresAt = Date.parse(credential.expiresAt);
140
+ if (Number.isFinite(expiresAt) && expiresAt > Date.now() + REFRESH_WINDOW_MS) return credential;
141
+ const credentialPath = busabaseAirAppCredentialPath(appId, options);
142
+ const activeRefresh = refreshesByCredentialPath.get(credentialPath);
143
+ if (activeRefresh) return activeRefresh;
144
+ const refresh = (async () => {
145
+ const tokenSet = await refreshBusabaseOAuthToken(
146
+ {
147
+ baseUrl: credential.baseUrl,
148
+ refreshToken: credential.refreshToken,
149
+ clientId: credential.clientId
150
+ },
151
+ fetchImpl
152
+ );
153
+ return storeBusabaseAirAppOAuthCredential(
154
+ {
155
+ appId,
156
+ baseUrl: credential.baseUrl,
157
+ clientId: credential.clientId,
158
+ tokenSet: {
159
+ ...tokenSet,
160
+ refreshToken: tokenSet.refreshToken ?? credential.refreshToken
161
+ },
162
+ selectedSpace: credential.selectedSpace
163
+ },
164
+ options
165
+ );
166
+ })();
167
+ refreshesByCredentialPath.set(credentialPath, refresh);
168
+ try {
169
+ return await refresh;
170
+ } finally {
171
+ if (refreshesByCredentialPath.get(credentialPath) === refresh) {
172
+ refreshesByCredentialPath.delete(credentialPath);
173
+ }
174
+ }
175
+ }
176
+ function storeBusabaseAirAppSelectedSpace(appId, selectedSpace, options = {}) {
177
+ const credential = loadBusabaseAirAppOAuthCredential(appId, options);
178
+ if (!credential) {
179
+ throw new BusabaseOAuthError(
180
+ "missing_local_credential",
181
+ "Connect this local AirApp before selecting a Space"
182
+ );
183
+ }
184
+ const next = {
185
+ ...credential,
186
+ ...selectedSpace ? { selectedSpace } : { selectedSpace: void 0 }
187
+ };
188
+ writeOwnerOnlyJson(busabaseAirAppCredentialPath(appId, options), next);
189
+ return next;
190
+ }
191
+ function clearBusabaseAirAppOAuthCredential(appId, options = {}) {
192
+ rmSync(busabaseAirAppCredentialPath(appId, options), { force: true });
193
+ }
194
+ async function revokeBusabaseAirAppOAuthCredential(appId, options = {}, fetchImpl = fetch) {
195
+ const credential = loadBusabaseAirAppOAuthCredential(appId, options);
196
+ if (!credential) return;
197
+ try {
198
+ await revokeBusabaseOAuthToken(
199
+ {
200
+ baseUrl: credential.baseUrl,
201
+ token: credential.refreshToken,
202
+ clientId: credential.clientId
203
+ },
204
+ fetchImpl
205
+ );
206
+ } finally {
207
+ clearBusabaseAirAppOAuthCredential(appId, options);
208
+ }
209
+ }
210
+
211
+ export { busabaseAirAppCredentialPath, busabaseAirAppCredentialsDir, busabaseAirAppDynamicClientsPath, clearBusabaseAirAppOAuthCredential, getBusabaseAirAppAccessToken, loadBusabaseAirAppDynamicClientId, loadBusabaseAirAppOAuthCredential, revokeBusabaseAirAppOAuthCredential, storeBusabaseAirAppDynamicClientId, storeBusabaseAirAppOAuthCredential, storeBusabaseAirAppSelectedSpace };
@@ -4,6 +4,7 @@ import { normalizeBaseUrl } from './chunk-5NYQX65A.js';
4
4
  var BUSABASE_AIRAPP_CLIENT_ID = "busabase-airapp";
5
5
 
6
6
  // src/oauth.ts
7
+ var AIRAPP_OAUTH_SCOPE = "api";
7
8
  var BusabaseOAuthError = class extends Error {
8
9
  code;
9
10
  status;
@@ -46,6 +47,45 @@ var digestBase64Url = async (value) => {
46
47
  for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
47
48
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
48
49
  };
50
+ async function registerBusabaseAirAppOAuthClient(input, fetchImpl = fetch) {
51
+ const baseUrl = oauthBaseUrl(input.baseUrl);
52
+ const redirectUri = new URL(input.redirectUri).toString();
53
+ const response = await fetchImpl(new URL("/api/oauth/register", baseUrl), {
54
+ method: "POST",
55
+ headers: { "content-type": "application/json" },
56
+ body: JSON.stringify({
57
+ client_name: input.appId,
58
+ client_kind: "airapp",
59
+ scope: AIRAPP_OAUTH_SCOPE,
60
+ redirect_uris: [redirectUri],
61
+ grant_types: ["authorization_code", "refresh_token"],
62
+ response_types: ["code"],
63
+ token_endpoint_auth_method: "none"
64
+ })
65
+ });
66
+ const body = await response.json().catch(() => null);
67
+ if (!response.ok) {
68
+ throw new BusabaseOAuthError(
69
+ typeof body?.error === "string" ? body.error : "client_registration_failed",
70
+ typeof body?.error_description === "string" ? body.error_description : `Busabase OAuth client registration failed (${response.status})`,
71
+ response.status
72
+ );
73
+ }
74
+ if (typeof body?.client_id !== "string" || !Array.isArray(body.redirect_uris) || body.redirect_uris.length !== 1 || body.redirect_uris[0] !== redirectUri) {
75
+ throw new BusabaseOAuthError(
76
+ "invalid_client_registration",
77
+ "Busabase returned an invalid OAuth client registration"
78
+ );
79
+ }
80
+ const grantedScopes = typeof body.scope === "string" ? body.scope.split(/\s+/).filter(Boolean) : null;
81
+ if (!grantedScopes?.includes(AIRAPP_OAUTH_SCOPE)) {
82
+ throw new BusabaseOAuthError(
83
+ "unsupported_airapp_registration",
84
+ `This Busabase server did not grant the "${AIRAPP_OAUTH_SCOPE}" scope to a dynamically registered AirApp. Upgrade Busabase, or run the AirApp on a loopback address to use the shared AirApp client.`
85
+ );
86
+ }
87
+ return { clientId: body.client_id, redirectUri };
88
+ }
49
89
  async function createBusabaseOAuthRequest(input) {
50
90
  const baseUrl = oauthBaseUrl(input.baseUrl);
51
91
  const redirectUri = new URL(input.redirectUri).toString();
@@ -58,7 +98,7 @@ async function createBusabaseOAuthRequest(input) {
58
98
  response_type: "code",
59
99
  client_id: clientId,
60
100
  resource,
61
- scope: "api",
101
+ scope: AIRAPP_OAUTH_SCOPE,
62
102
  code_challenge: await digestBase64Url(codeVerifier),
63
103
  code_challenge_method: "S256",
64
104
  redirect_uri: redirectUri,
@@ -172,4 +212,4 @@ async function revokeBusabaseOAuthToken(input, fetchImpl = fetch) {
172
212
  }
173
213
  }
174
214
 
175
- export { BUSABASE_AIRAPP_CLIENT_ID, BusabaseOAuthError, createBusabaseOAuthRequest, exchangeBusabaseOAuthCode, parseBusabaseOAuthCallback, refreshBusabaseOAuthToken, revokeBusabaseOAuthToken };
215
+ export { AIRAPP_OAUTH_SCOPE, BUSABASE_AIRAPP_CLIENT_ID, BusabaseOAuthError, createBusabaseOAuthRequest, exchangeBusabaseOAuthCode, parseBusabaseOAuthCallback, refreshBusabaseOAuthToken, registerBusabaseAirAppOAuthClient, revokeBusabaseOAuthToken };