@ultrst-armada/kloks 1.26.6 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -7
- package/packages/backend/dist/{chunk-BVXGUHLZ.js → chunk-AOZSDRNY.js} +1 -1
- package/packages/backend/dist/chunk-G4EDIAHW.js +0 -0
- package/packages/backend/dist/{chunk-T6BJHFWZ.js → chunk-LMOM7CST.js} +2 -2
- package/packages/backend/dist/chunk-OQRQCDS6.js +109 -0
- package/packages/backend/dist/chunk-OWMQLML7.js +451 -0
- package/packages/backend/dist/{chunk-Y5ENDXU2.js → chunk-SQKG3S6P.js} +2 -10
- package/packages/backend/dist/{chunk-NGEB3CF5.js → chunk-Z6G32NQQ.js} +8 -3
- package/packages/backend/dist/core/SrklStorageService.test.d.ts +1 -0
- package/packages/backend/dist/krnl-services.js +5 -4
- package/packages/backend/dist/node.js +9 -21
- package/packages/backend/dist/services/node.js +4 -3
- package/packages/backend/dist/storage/GoogleDriveStorageService.d.ts +31 -9
- package/packages/backend/dist/storage/GoogleDriveWorkspaceService.d.ts +23 -6
- package/packages/backend/dist/storage/StorageAdapterFactory.d.ts +2 -2
- package/packages/backend/dist/storage/node.d.ts +0 -2
- package/packages/backend/dist/storage/node.js +5 -17
- package/packages/backend/dist/storage-workspace.js +4 -335
- package/packages/backend/dist/workspace/node.js +3 -2
- package/packages/backend/package.json +3 -7
- package/packages/client/dist/auth.d.ts +20 -1
- package/packages/client/dist/auth.js +13 -3
- package/packages/client/dist/chunk-5JMYSB7L.js +133 -0
- package/packages/client/dist/index.d.ts +1 -1
- package/packages/client/dist/index.js +13 -3
- package/packages/client/package.json +1 -1
- package/packages/state-graph/dist/browser.js +24 -24
- package/packages/state-graph/dist/index.js +24 -24
- package/packages/backend/dist/chunk-3FZSYSJC.js +0 -86
- package/packages/backend/dist/chunk-G7PPVOFP.js +0 -369
- package/packages/backend/dist/storage/GoogleDriveAdapter.d.ts +0 -41
- package/packages/backend/dist/storage/GoogleDriveOAuth.d.ts +0 -34
- package/packages/backend/dist/storage/googleDriveSdk.d.ts +0 -1
- package/packages/client/dist/chunk-B4WOPCRZ.js +0 -26
- package/packages/state-graph/dist/{chunk-YUJC367F.js → chunk-UKTICGGV.js} +3 -3
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultrst-armada/kloks",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public",
|
|
7
7
|
"registry": "https://registry.npmjs.org/"
|
|
8
8
|
},
|
|
9
|
-
"description": "Kloks
|
|
9
|
+
"description": "Kloks \u2014 Public Backend, State-Graph, Audio/MIDI & Service Package Library built on KrnlTS (@kloks/*)",
|
|
10
10
|
"type": "module",
|
|
11
11
|
"main": "./index.js",
|
|
12
12
|
"module": "./index.js",
|
|
@@ -271,7 +271,7 @@
|
|
|
271
271
|
"verify:package-exports": "node scripts/verify-package-exports.mjs"
|
|
272
272
|
},
|
|
273
273
|
"dependencies": {
|
|
274
|
-
"@dinilmusick/gutts": "^2.0
|
|
274
|
+
"@dinilmusick/gutts": "^2.1.0",
|
|
275
275
|
"@webcontainer/api": "^1.6.4",
|
|
276
276
|
"ws": "^8.18.0",
|
|
277
277
|
"zod": "^3.24.1",
|
|
@@ -283,7 +283,6 @@
|
|
|
283
283
|
"@neondatabase/serverless": "^0.10.0 || ^1.0.0",
|
|
284
284
|
"@supabase/supabase-js": "^2.45.0",
|
|
285
285
|
"@ultrst-armada/krnl": "^1.0.11",
|
|
286
|
-
"googleapis": "^189.0.0",
|
|
287
286
|
"react": "^18.0.0 || ^19.0.0",
|
|
288
287
|
"@types/node": ">=20.0.0",
|
|
289
288
|
"@types/react": "^18.0.0 || ^19.0.0"
|
|
@@ -304,9 +303,6 @@
|
|
|
304
303
|
"@ultrst-armada/krnl": {
|
|
305
304
|
"optional": true
|
|
306
305
|
},
|
|
307
|
-
"googleapis": {
|
|
308
|
-
"optional": true
|
|
309
|
-
},
|
|
310
306
|
"react": {
|
|
311
307
|
"optional": true
|
|
312
308
|
},
|
|
File without changes
|
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
} from "./chunk-FZKBTF34.js";
|
|
5
5
|
import {
|
|
6
6
|
workspaceGraphService
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-AOZSDRNY.js";
|
|
8
8
|
import {
|
|
9
9
|
StorageAdapterFactory
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-SQKG3S6P.js";
|
|
11
11
|
import {
|
|
12
12
|
createWorkspace,
|
|
13
13
|
deleteWorkspace,
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BaseStorageAdapter
|
|
3
|
+
} from "./chunk-5F5V7NAG.js";
|
|
4
|
+
import {
|
|
5
|
+
GoogleDriveWorkspaceService
|
|
6
|
+
} from "./chunk-OWMQLML7.js";
|
|
7
|
+
|
|
8
|
+
// src/storage/GoogleDriveStorageService.ts
|
|
9
|
+
var GoogleDriveStorageService = class extends BaseStorageAdapter {
|
|
10
|
+
runtimeAuth;
|
|
11
|
+
workspacePromise;
|
|
12
|
+
constructor(config, runtimeAuth = {}) {
|
|
13
|
+
super({ ...config, provider: "google_drive" });
|
|
14
|
+
this.runtimeAuth = runtimeAuth;
|
|
15
|
+
}
|
|
16
|
+
async workspace() {
|
|
17
|
+
if (!this.workspacePromise) {
|
|
18
|
+
this.workspacePromise = (async () => {
|
|
19
|
+
const credentials = await this.runtimeAuth.getCredentials?.();
|
|
20
|
+
const tokens = credentials ?? {
|
|
21
|
+
accessToken: this.config.googleAccessToken || "",
|
|
22
|
+
...this.config.googleRefreshToken ? { refreshToken: this.config.googleRefreshToken } : {},
|
|
23
|
+
...this.config.googleAccessTokenExpiresAt ? { expiresAt: this.config.googleAccessTokenExpiresAt } : {}
|
|
24
|
+
};
|
|
25
|
+
const options = {
|
|
26
|
+
clientId: this.config.googleClientId || "",
|
|
27
|
+
clientSecret: this.runtimeAuth.clientSecret,
|
|
28
|
+
redirectUri: this.config.googleRedirectUri || "",
|
|
29
|
+
tokens,
|
|
30
|
+
rootFolderId: this.config.googleRootFolderId,
|
|
31
|
+
googleAccountId: this.config.googleAccountId,
|
|
32
|
+
fetcher: this.runtimeAuth.fetcher,
|
|
33
|
+
persistTokens: async (next) => {
|
|
34
|
+
await this.runtimeAuth.persistCredentials?.({ ...next });
|
|
35
|
+
this.config.googleAccessToken = next.accessToken;
|
|
36
|
+
this.config.googleRefreshToken = next.refreshToken;
|
|
37
|
+
this.config.googleAccessTokenExpiresAt = next.expiresAt;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
return new GoogleDriveWorkspaceService(options);
|
|
41
|
+
})().catch((error) => {
|
|
42
|
+
this.workspacePromise = void 0;
|
|
43
|
+
throw error;
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
return this.workspacePromise;
|
|
47
|
+
}
|
|
48
|
+
async read(path) {
|
|
49
|
+
return (await this.workspace()).read(path);
|
|
50
|
+
}
|
|
51
|
+
async write(path, data, contentType) {
|
|
52
|
+
return (await this.workspace()).write(path, data, contentType);
|
|
53
|
+
}
|
|
54
|
+
async delete(path) {
|
|
55
|
+
return (await this.workspace()).delete(path);
|
|
56
|
+
}
|
|
57
|
+
async exists(path) {
|
|
58
|
+
return (await this.workspace()).exists(path);
|
|
59
|
+
}
|
|
60
|
+
async list(path = "") {
|
|
61
|
+
return (await this.workspace()).list(path);
|
|
62
|
+
}
|
|
63
|
+
async stat(path) {
|
|
64
|
+
return (await this.workspace()).stat(path);
|
|
65
|
+
}
|
|
66
|
+
async mkdir(path) {
|
|
67
|
+
return (await this.workspace()).mkdir(path);
|
|
68
|
+
}
|
|
69
|
+
async listFolders(parentFolderId) {
|
|
70
|
+
return (await this.workspace()).listFolders(parentFolderId);
|
|
71
|
+
}
|
|
72
|
+
async selectRootFolder(folderId) {
|
|
73
|
+
const folder = await (await this.workspace()).selectRootFolder(folderId);
|
|
74
|
+
this.config.googleRootFolderId = folder.id;
|
|
75
|
+
return folder;
|
|
76
|
+
}
|
|
77
|
+
async getAccountIdentity() {
|
|
78
|
+
const identity = await (await this.workspace()).getAccountIdentity();
|
|
79
|
+
this.config.googleAccountId = identity.accountId;
|
|
80
|
+
return identity;
|
|
81
|
+
}
|
|
82
|
+
async refreshTokens() {
|
|
83
|
+
const tokens = await (await this.workspace()).refreshTokens();
|
|
84
|
+
this.config.googleAccessToken = tokens.accessToken;
|
|
85
|
+
this.config.googleRefreshToken = tokens.refreshToken;
|
|
86
|
+
this.config.googleAccessTokenExpiresAt = tokens.expiresAt;
|
|
87
|
+
return tokens;
|
|
88
|
+
}
|
|
89
|
+
getConnectionMetadata() {
|
|
90
|
+
return {
|
|
91
|
+
provider: "google_drive",
|
|
92
|
+
...this.config.googleClientId ? { googleClientId: this.config.googleClientId } : {},
|
|
93
|
+
...this.config.googleRedirectUri ? { googleRedirectUri: this.config.googleRedirectUri } : {},
|
|
94
|
+
...this.config.googleAccountId ? { googleAccountId: this.config.googleAccountId } : {},
|
|
95
|
+
...this.config.googleRootFolderId ? { googleRootFolderId: this.config.googleRootFolderId } : {}
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
async testConnection() {
|
|
99
|
+
const result = await (await this.workspace()).testConnection();
|
|
100
|
+
if (result.ok && typeof result.details?.accountId === "string") {
|
|
101
|
+
this.config.googleAccountId = result.details.accountId;
|
|
102
|
+
}
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export {
|
|
108
|
+
GoogleDriveStorageService
|
|
109
|
+
};
|
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
// src/storage/GoogleDriveWorkspaceService.ts
|
|
2
|
+
var GOOGLE_DRIVE_WORKSPACE_SCOPE = "https://www.googleapis.com/auth/drive";
|
|
3
|
+
var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
4
|
+
var GOOGLE_API_URL = "https://www.googleapis.com/drive/v3";
|
|
5
|
+
var GOOGLE_UPLOAD_URL = "https://www.googleapis.com/upload/drive/v3";
|
|
6
|
+
var FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
|
|
7
|
+
var PKCE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]{43,128}$/;
|
|
8
|
+
var PKCE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
9
|
+
var SAFE_OAUTH_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
10
|
+
"access_denied",
|
|
11
|
+
"invalid_client",
|
|
12
|
+
"invalid_grant",
|
|
13
|
+
"invalid_request",
|
|
14
|
+
"invalid_scope",
|
|
15
|
+
"server_error",
|
|
16
|
+
"temporarily_unavailable",
|
|
17
|
+
"unauthorized_client",
|
|
18
|
+
"unsupported_grant_type"
|
|
19
|
+
]);
|
|
20
|
+
function encodeBytes(parts) {
|
|
21
|
+
const encoder = new TextEncoder();
|
|
22
|
+
const buffers = parts.map((part) => typeof part === "string" ? encoder.encode(part) : part);
|
|
23
|
+
const output = new Uint8Array(buffers.reduce((sum, item) => sum + item.length, 0));
|
|
24
|
+
let offset = 0;
|
|
25
|
+
for (const item of buffers) {
|
|
26
|
+
output.set(item, offset);
|
|
27
|
+
offset += item.length;
|
|
28
|
+
}
|
|
29
|
+
return output;
|
|
30
|
+
}
|
|
31
|
+
function encodeBase64Url(bytes) {
|
|
32
|
+
let binary = "";
|
|
33
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
34
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
35
|
+
}
|
|
36
|
+
function validatePkceVerifier(verifier) {
|
|
37
|
+
if (!PKCE_VERIFIER_PATTERN.test(verifier)) {
|
|
38
|
+
throw new Error("Google Drive PKCE verifier must contain 43 to 128 URL-safe characters.");
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function quoteDriveQuery(value) {
|
|
42
|
+
return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
|
43
|
+
}
|
|
44
|
+
async function parseJson(response) {
|
|
45
|
+
return response.json().catch(() => ({}));
|
|
46
|
+
}
|
|
47
|
+
async function persistTokensSafely(persistTokens, tokens) {
|
|
48
|
+
if (!persistTokens) return;
|
|
49
|
+
try {
|
|
50
|
+
await persistTokens({ ...tokens });
|
|
51
|
+
} catch {
|
|
52
|
+
throw new Error("Google Drive credentials could not be persisted securely.");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
var GoogleDriveWorkspaceService = class _GoogleDriveWorkspaceService {
|
|
56
|
+
options;
|
|
57
|
+
fetcher;
|
|
58
|
+
tokens;
|
|
59
|
+
refreshPromise;
|
|
60
|
+
constructor(options) {
|
|
61
|
+
if (!options.clientId?.trim()) throw new Error("Google Drive OAuth client ID is required.");
|
|
62
|
+
if (!options.redirectUri?.trim()) throw new Error("Google Drive OAuth redirect URI is required.");
|
|
63
|
+
this.options = options;
|
|
64
|
+
this.fetcher = options.fetcher || fetch;
|
|
65
|
+
this.tokens = { ...options.tokens || { accessToken: "" } };
|
|
66
|
+
}
|
|
67
|
+
/** Generate a cryptographically random RFC 7636 verifier using Web Crypto. */
|
|
68
|
+
static createPkceCodeVerifier() {
|
|
69
|
+
const bytes = new Uint8Array(32);
|
|
70
|
+
crypto.getRandomValues(bytes);
|
|
71
|
+
return encodeBase64Url(bytes);
|
|
72
|
+
}
|
|
73
|
+
/** Create the S256 challenge corresponding to a previously stored verifier. */
|
|
74
|
+
static async createPkceCodeChallenge(codeVerifier) {
|
|
75
|
+
validatePkceVerifier(codeVerifier);
|
|
76
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
|
|
77
|
+
return encodeBase64Url(new Uint8Array(digest));
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Validate callback state against the value stored by the initiating server-side session.
|
|
81
|
+
* Call this at the callback boundary before exchanging the returned authorization code.
|
|
82
|
+
*/
|
|
83
|
+
static validateOAuthState(expectedState, returnedState) {
|
|
84
|
+
if (!expectedState?.trim() || !returnedState?.trim() || expectedState !== returnedState) {
|
|
85
|
+
throw new Error("Google Drive OAuth state validation failed. Restart the authorization flow.");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
static createAuthorizationUrl(options, state, scopes = [GOOGLE_DRIVE_WORKSPACE_SCOPE], codeChallenge) {
|
|
89
|
+
if (!options.clientId?.trim() || !options.redirectUri?.trim()) {
|
|
90
|
+
throw new Error("Google Drive OAuth client ID and redirect URI are required.");
|
|
91
|
+
}
|
|
92
|
+
if (!state?.trim()) throw new Error("A non-empty Google Drive OAuth state is required.");
|
|
93
|
+
const requestedScopes = scopes.length ? scopes : [GOOGLE_DRIVE_WORKSPACE_SCOPE];
|
|
94
|
+
if (!requestedScopes.includes(GOOGLE_DRIVE_WORKSPACE_SCOPE) || requestedScopes.some((scope) => !(scope === GOOGLE_DRIVE_WORKSPACE_SCOPE || scope.startsWith(`${GOOGLE_DRIVE_WORKSPACE_SCOPE}.`)))) {
|
|
95
|
+
throw new Error("Google Drive workspace authorization requires Drive storage scopes only.");
|
|
96
|
+
}
|
|
97
|
+
if (codeChallenge !== void 0 && !PKCE_CHALLENGE_PATTERN.test(codeChallenge)) {
|
|
98
|
+
throw new Error("Google Drive PKCE S256 challenge must be a 43-character base64url value.");
|
|
99
|
+
}
|
|
100
|
+
const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");
|
|
101
|
+
url.searchParams.set("client_id", options.clientId);
|
|
102
|
+
url.searchParams.set("redirect_uri", options.redirectUri);
|
|
103
|
+
url.searchParams.set("response_type", "code");
|
|
104
|
+
url.searchParams.set("access_type", "offline");
|
|
105
|
+
url.searchParams.set("prompt", "consent");
|
|
106
|
+
url.searchParams.set("include_granted_scopes", "true");
|
|
107
|
+
url.searchParams.set("scope", requestedScopes.join(" "));
|
|
108
|
+
url.searchParams.set("state", state);
|
|
109
|
+
if (codeChallenge) {
|
|
110
|
+
url.searchParams.set("code_challenge", codeChallenge);
|
|
111
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
112
|
+
}
|
|
113
|
+
return url.toString();
|
|
114
|
+
}
|
|
115
|
+
static async exchangeAuthorizationCode(options, code, existingRefreshToken, codeVerifier) {
|
|
116
|
+
if (!options.clientId?.trim() || !options.redirectUri?.trim()) {
|
|
117
|
+
throw new Error("Google Drive OAuth client ID and redirect URI are required.");
|
|
118
|
+
}
|
|
119
|
+
if (!code?.trim()) throw new Error("Google Drive authorization code is required.");
|
|
120
|
+
if (codeVerifier !== void 0) validatePkceVerifier(codeVerifier);
|
|
121
|
+
const tokens = await _GoogleDriveWorkspaceService.requestTokens(
|
|
122
|
+
options.fetcher || fetch,
|
|
123
|
+
{
|
|
124
|
+
client_id: options.clientId,
|
|
125
|
+
...options.clientSecret ? { client_secret: options.clientSecret } : {},
|
|
126
|
+
redirect_uri: options.redirectUri,
|
|
127
|
+
grant_type: "authorization_code",
|
|
128
|
+
code,
|
|
129
|
+
...codeVerifier ? { code_verifier: codeVerifier } : {}
|
|
130
|
+
},
|
|
131
|
+
existingRefreshToken
|
|
132
|
+
);
|
|
133
|
+
await persistTokensSafely(options.persistTokens, tokens);
|
|
134
|
+
return tokens;
|
|
135
|
+
}
|
|
136
|
+
static async requestTokens(fetcher, fields, existingRefreshToken) {
|
|
137
|
+
let response;
|
|
138
|
+
try {
|
|
139
|
+
response = await fetcher(GOOGLE_TOKEN_URL, {
|
|
140
|
+
method: "POST",
|
|
141
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
142
|
+
body: new URLSearchParams(fields),
|
|
143
|
+
cache: "no-store"
|
|
144
|
+
});
|
|
145
|
+
} catch {
|
|
146
|
+
throw new Error("Google Drive OAuth token request failed before receiving a response.");
|
|
147
|
+
}
|
|
148
|
+
const data = await parseJson(response);
|
|
149
|
+
if (!response.ok || typeof data.access_token !== "string" || !data.access_token) {
|
|
150
|
+
const safeCode = typeof data.error === "string" && SAFE_OAUTH_ERROR_CODES.has(data.error) ? ` (${data.error})` : "";
|
|
151
|
+
throw new Error(`Google Drive OAuth token request failed${safeCode}.`);
|
|
152
|
+
}
|
|
153
|
+
const refreshToken = typeof data.refresh_token === "string" && data.refresh_token ? data.refresh_token : existingRefreshToken;
|
|
154
|
+
const expiresIn = Number(data.expires_in);
|
|
155
|
+
return {
|
|
156
|
+
accessToken: data.access_token,
|
|
157
|
+
...refreshToken ? { refreshToken } : {},
|
|
158
|
+
...Number.isFinite(expiresIn) && expiresIn > 0 ? { expiresAt: Date.now() + expiresIn * 1e3 } : {},
|
|
159
|
+
...typeof data.token_type === "string" ? { tokenType: data.token_type } : {}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/** Force a refresh through this instance's shared refresh/persistence lifecycle. */
|
|
163
|
+
async refreshTokens() {
|
|
164
|
+
await this.getAccessToken(true);
|
|
165
|
+
return { ...this.tokens };
|
|
166
|
+
}
|
|
167
|
+
async getAccessToken(forceRefresh = false, rejectedAccessToken) {
|
|
168
|
+
const expiresSoon = typeof this.tokens.expiresAt === "number" && this.tokens.expiresAt <= Date.now() + 6e4;
|
|
169
|
+
const hasUsableToken = Boolean(this.tokens.accessToken) && !expiresSoon;
|
|
170
|
+
if (!forceRefresh && hasUsableToken) return this.tokens.accessToken;
|
|
171
|
+
if (forceRefresh && hasUsableToken && rejectedAccessToken && this.tokens.accessToken !== rejectedAccessToken) {
|
|
172
|
+
return this.tokens.accessToken;
|
|
173
|
+
}
|
|
174
|
+
if (!this.tokens.refreshToken) {
|
|
175
|
+
throw new Error("Google Drive credentials are missing or expired. Reconnect the Google account.");
|
|
176
|
+
}
|
|
177
|
+
if (!this.refreshPromise) {
|
|
178
|
+
const refreshToken = this.tokens.refreshToken;
|
|
179
|
+
this.refreshPromise = _GoogleDriveWorkspaceService.requestTokens(
|
|
180
|
+
this.fetcher,
|
|
181
|
+
{
|
|
182
|
+
client_id: this.options.clientId,
|
|
183
|
+
...this.options.clientSecret ? { client_secret: this.options.clientSecret } : {},
|
|
184
|
+
refresh_token: refreshToken,
|
|
185
|
+
grant_type: "refresh_token"
|
|
186
|
+
},
|
|
187
|
+
refreshToken
|
|
188
|
+
).then(async (tokens) => {
|
|
189
|
+
await persistTokensSafely(this.options.persistTokens, tokens);
|
|
190
|
+
this.tokens = { ...tokens };
|
|
191
|
+
return { ...this.tokens };
|
|
192
|
+
}).finally(() => {
|
|
193
|
+
this.refreshPromise = void 0;
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
const refreshed = await this.refreshPromise;
|
|
197
|
+
return refreshed.accessToken;
|
|
198
|
+
}
|
|
199
|
+
async api(path, init = {}, retry = true) {
|
|
200
|
+
const token = await this.getAccessToken();
|
|
201
|
+
const headers = new Headers(init.headers);
|
|
202
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
203
|
+
let response;
|
|
204
|
+
try {
|
|
205
|
+
response = await this.fetcher(
|
|
206
|
+
path.startsWith("https://") ? path : `${GOOGLE_API_URL}/${path.replace(/^\/+/, "")}`,
|
|
207
|
+
{
|
|
208
|
+
...init,
|
|
209
|
+
headers,
|
|
210
|
+
cache: "no-store"
|
|
211
|
+
}
|
|
212
|
+
);
|
|
213
|
+
} catch {
|
|
214
|
+
throw new Error("Google Drive request failed before receiving a response.");
|
|
215
|
+
}
|
|
216
|
+
if (response.status === 401 && retry && this.tokens.refreshToken) {
|
|
217
|
+
await this.getAccessToken(true, token);
|
|
218
|
+
return this.api(path, init, false);
|
|
219
|
+
}
|
|
220
|
+
if (!response.ok) {
|
|
221
|
+
throw new Error(`Google Drive request failed with HTTP ${response.status}.`);
|
|
222
|
+
}
|
|
223
|
+
return response;
|
|
224
|
+
}
|
|
225
|
+
async listFiles(parentId, query = "trashed = false") {
|
|
226
|
+
const files = [];
|
|
227
|
+
let pageToken = "";
|
|
228
|
+
do {
|
|
229
|
+
const url = new URL(`${GOOGLE_API_URL}/files`);
|
|
230
|
+
url.searchParams.set("q", `'${quoteDriveQuery(parentId)}' in parents and ${query}`);
|
|
231
|
+
url.searchParams.set("fields", "nextPageToken,files(id,name,mimeType,size,modifiedTime,parents)");
|
|
232
|
+
url.searchParams.set("pageSize", "1000");
|
|
233
|
+
url.searchParams.set("supportsAllDrives", "true");
|
|
234
|
+
url.searchParams.set("includeItemsFromAllDrives", "true");
|
|
235
|
+
if (pageToken) url.searchParams.set("pageToken", pageToken);
|
|
236
|
+
const data = await parseJson(await this.api(url.toString()));
|
|
237
|
+
if (Array.isArray(data.files)) files.push(...data.files);
|
|
238
|
+
pageToken = typeof data.nextPageToken === "string" ? data.nextPageToken : "";
|
|
239
|
+
} while (pageToken);
|
|
240
|
+
return files;
|
|
241
|
+
}
|
|
242
|
+
async findChild(parentId, name) {
|
|
243
|
+
const matches = await this.listFiles(
|
|
244
|
+
parentId,
|
|
245
|
+
`name = '${quoteDriveQuery(name)}' and trashed = false`
|
|
246
|
+
);
|
|
247
|
+
return matches.find((item) => Boolean(item.id));
|
|
248
|
+
}
|
|
249
|
+
async resolveParent(relativePath, create = false) {
|
|
250
|
+
let parent = this.options.rootFolderId || "root";
|
|
251
|
+
for (const segment of relativePath.replace(/\\/g, "/").split("/").filter(Boolean)) {
|
|
252
|
+
let child = await this.findChild(parent, segment);
|
|
253
|
+
if (!child && create) {
|
|
254
|
+
const data = await parseJson(await this.api("files", {
|
|
255
|
+
method: "POST",
|
|
256
|
+
headers: { "Content-Type": "application/json" },
|
|
257
|
+
body: JSON.stringify({
|
|
258
|
+
name: segment,
|
|
259
|
+
mimeType: FOLDER_MIME_TYPE,
|
|
260
|
+
parents: [parent]
|
|
261
|
+
})
|
|
262
|
+
}));
|
|
263
|
+
child = data;
|
|
264
|
+
}
|
|
265
|
+
if (!child?.id || child.mimeType !== FOLDER_MIME_TYPE) {
|
|
266
|
+
throw new Error(`Google Drive folder not found: ${segment}`);
|
|
267
|
+
}
|
|
268
|
+
parent = child.id;
|
|
269
|
+
}
|
|
270
|
+
return parent;
|
|
271
|
+
}
|
|
272
|
+
splitPath(value) {
|
|
273
|
+
const normalized = value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
|
274
|
+
const index = normalized.lastIndexOf("/");
|
|
275
|
+
return index < 0 ? { parent: "", name: normalized } : { parent: normalized.slice(0, index), name: normalized.slice(index + 1) };
|
|
276
|
+
}
|
|
277
|
+
async getAccountIdentity() {
|
|
278
|
+
const url = new URL(`${GOOGLE_API_URL}/about`);
|
|
279
|
+
url.searchParams.set("fields", "user(permissionId,emailAddress)");
|
|
280
|
+
const data = await parseJson(await this.api(url.toString()));
|
|
281
|
+
const accountId = data.user?.permissionId || data.user?.emailAddress;
|
|
282
|
+
if (typeof accountId !== "string" || !accountId) {
|
|
283
|
+
throw new Error("Google Drive did not return a stable account identity.");
|
|
284
|
+
}
|
|
285
|
+
if (this.options.googleAccountId && this.options.googleAccountId !== accountId) {
|
|
286
|
+
throw new Error("Google Drive account identity does not match the saved storage connection.");
|
|
287
|
+
}
|
|
288
|
+
this.options.googleAccountId = accountId;
|
|
289
|
+
return {
|
|
290
|
+
accountId,
|
|
291
|
+
...typeof data.user?.emailAddress === "string" ? { email: data.user.emailAddress } : {}
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
async listFolders(parentFolderId = this.options.rootFolderId || "root") {
|
|
295
|
+
const files = await this.listFiles(
|
|
296
|
+
parentFolderId,
|
|
297
|
+
`mimeType = '${FOLDER_MIME_TYPE}' and trashed = false`
|
|
298
|
+
);
|
|
299
|
+
return files.flatMap((file) => file.id && file.name ? [{
|
|
300
|
+
id: file.id,
|
|
301
|
+
name: file.name,
|
|
302
|
+
mimeType: FOLDER_MIME_TYPE,
|
|
303
|
+
parentIds: file.parents || [],
|
|
304
|
+
modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
|
|
305
|
+
}] : []);
|
|
306
|
+
}
|
|
307
|
+
async resolveFolder(folderId) {
|
|
308
|
+
if (!folderId?.trim()) throw new Error("A Google Drive folder ID is required.");
|
|
309
|
+
const url = new URL(`${GOOGLE_API_URL}/files/${encodeURIComponent(folderId)}`);
|
|
310
|
+
url.searchParams.set("fields", "id,name,mimeType,parents,modifiedTime");
|
|
311
|
+
url.searchParams.set("supportsAllDrives", "true");
|
|
312
|
+
const file = await parseJson(await this.api(url.toString()));
|
|
313
|
+
if (!file.id || !file.name || file.mimeType !== FOLDER_MIME_TYPE) {
|
|
314
|
+
throw new Error("The selected Google Drive item is not a folder.");
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
id: file.id,
|
|
318
|
+
name: file.name,
|
|
319
|
+
mimeType: file.mimeType,
|
|
320
|
+
parentIds: file.parents || [],
|
|
321
|
+
modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
async selectRootFolder(folderId) {
|
|
325
|
+
const folder = await this.resolveFolder(folderId);
|
|
326
|
+
this.options.rootFolderId = folder.id;
|
|
327
|
+
return folder;
|
|
328
|
+
}
|
|
329
|
+
async read(path) {
|
|
330
|
+
const { parent, name } = this.splitPath(path);
|
|
331
|
+
if (!name) throw new Error("A Google Drive file path is required.");
|
|
332
|
+
const parentId = await this.resolveParent(parent);
|
|
333
|
+
const file = await this.findChild(parentId, name);
|
|
334
|
+
if (!file?.id || file.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive file not found: ${path}`);
|
|
335
|
+
const url = new URL(`${GOOGLE_API_URL}/files/${encodeURIComponent(file.id)}`);
|
|
336
|
+
url.searchParams.set("alt", "media");
|
|
337
|
+
return new Uint8Array(await (await this.api(url.toString())).arrayBuffer());
|
|
338
|
+
}
|
|
339
|
+
async write(path, bytes, contentType = "application/octet-stream") {
|
|
340
|
+
const { parent, name } = this.splitPath(path);
|
|
341
|
+
if (!name) throw new Error("A Google Drive file name is required.");
|
|
342
|
+
if (!contentType.trim() || /[\r\n]/.test(contentType)) {
|
|
343
|
+
throw new Error("A valid Google Drive file content type is required.");
|
|
344
|
+
}
|
|
345
|
+
const parentId = await this.resolveParent(parent, true);
|
|
346
|
+
const existing = await this.findChild(parentId, name);
|
|
347
|
+
if (existing?.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive path is a folder: ${path}`);
|
|
348
|
+
const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
|
|
349
|
+
const boundary = `kloks-drive-${crypto.randomUUID()}`;
|
|
350
|
+
const body = encodeBytes([
|
|
351
|
+
`--${boundary}\r
|
|
352
|
+
Content-Type: application/json; charset=UTF-8\r
|
|
353
|
+
\r
|
|
354
|
+
`,
|
|
355
|
+
JSON.stringify({
|
|
356
|
+
name,
|
|
357
|
+
mimeType: contentType,
|
|
358
|
+
...!existing?.id ? { parents: [parentId] } : {}
|
|
359
|
+
}),
|
|
360
|
+
`\r
|
|
361
|
+
--${boundary}\r
|
|
362
|
+
Content-Type: ${contentType}\r
|
|
363
|
+
\r
|
|
364
|
+
`,
|
|
365
|
+
data,
|
|
366
|
+
`\r
|
|
367
|
+
--${boundary}--\r
|
|
368
|
+
`
|
|
369
|
+
]);
|
|
370
|
+
const endpoint = existing?.id ? `${GOOGLE_UPLOAD_URL}/files/${encodeURIComponent(existing.id)}?uploadType=multipart&supportsAllDrives=true` : `${GOOGLE_UPLOAD_URL}/files?uploadType=multipart&supportsAllDrives=true`;
|
|
371
|
+
await this.api(endpoint, {
|
|
372
|
+
method: existing?.id ? "PATCH" : "POST",
|
|
373
|
+
headers: { "Content-Type": `multipart/related; boundary=${boundary}` },
|
|
374
|
+
body: body.buffer
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
async delete(path) {
|
|
378
|
+
const { parent, name } = this.splitPath(path);
|
|
379
|
+
const parentId = await this.resolveParent(parent);
|
|
380
|
+
const file = await this.findChild(parentId, name);
|
|
381
|
+
if (!file?.id) return;
|
|
382
|
+
await this.api(`files/${encodeURIComponent(file.id)}?supportsAllDrives=true`, { method: "DELETE" });
|
|
383
|
+
}
|
|
384
|
+
async exists(path) {
|
|
385
|
+
try {
|
|
386
|
+
await this.stat(path);
|
|
387
|
+
return true;
|
|
388
|
+
} catch (error) {
|
|
389
|
+
if (error instanceof Error && /not found|HTTP 404/i.test(error.message)) return false;
|
|
390
|
+
throw error;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
async list(path = "") {
|
|
394
|
+
const parentId = await this.resolveParent(path);
|
|
395
|
+
const files = await this.listFiles(parentId);
|
|
396
|
+
return files.flatMap((file) => file.name ? [{
|
|
397
|
+
path: path ? `${path.replace(/\/+$/, "")}/${file.name}` : file.name,
|
|
398
|
+
size: Number(file.size || 0),
|
|
399
|
+
modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0,
|
|
400
|
+
...file.id ? { id: file.id } : {},
|
|
401
|
+
...file.mimeType ? { mimeType: file.mimeType } : {},
|
|
402
|
+
isFolder: file.mimeType === FOLDER_MIME_TYPE
|
|
403
|
+
}] : []);
|
|
404
|
+
}
|
|
405
|
+
async stat(path) {
|
|
406
|
+
const { parent, name } = this.splitPath(path);
|
|
407
|
+
const parentId = await this.resolveParent(parent);
|
|
408
|
+
const file = await this.findChild(parentId, name);
|
|
409
|
+
if (!file?.id) throw new Error(`Google Drive file not found: ${path}`);
|
|
410
|
+
return {
|
|
411
|
+
path,
|
|
412
|
+
size: Number(file.size || 0),
|
|
413
|
+
modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0,
|
|
414
|
+
...file.id ? { id: file.id } : {},
|
|
415
|
+
...file.mimeType ? { mimeType: file.mimeType } : {},
|
|
416
|
+
isFolder: file.mimeType === FOLDER_MIME_TYPE
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
async mkdir(path) {
|
|
420
|
+
await this.resolveParent(path, true);
|
|
421
|
+
}
|
|
422
|
+
async testConnection() {
|
|
423
|
+
const started = Date.now();
|
|
424
|
+
try {
|
|
425
|
+
const identity = await this.getAccountIdentity();
|
|
426
|
+
return {
|
|
427
|
+
ok: true,
|
|
428
|
+
latencyMs: Date.now() - started,
|
|
429
|
+
details: { accountId: identity.accountId, email: identity.email, rootFolderId: this.options.rootFolderId || "root" }
|
|
430
|
+
};
|
|
431
|
+
} catch (error) {
|
|
432
|
+
return {
|
|
433
|
+
ok: false,
|
|
434
|
+
latencyMs: Date.now() - started,
|
|
435
|
+
error: error instanceof Error ? error.message : "Google Drive connection failed."
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
getConnectionMetadata() {
|
|
440
|
+
return {
|
|
441
|
+
provider: "google_drive",
|
|
442
|
+
...this.options.googleAccountId ? { googleAccountId: this.options.googleAccountId } : {},
|
|
443
|
+
...this.options.rootFolderId ? { googleRootFolderId: this.options.rootFolderId } : {}
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
export {
|
|
449
|
+
GOOGLE_DRIVE_WORKSPACE_SCOPE,
|
|
450
|
+
GoogleDriveWorkspaceService
|
|
451
|
+
};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
} from "./chunk-
|
|
2
|
+
GoogleDriveStorageService
|
|
3
|
+
} from "./chunk-OQRQCDS6.js";
|
|
4
4
|
import {
|
|
5
5
|
normalizeBackblazeCredentials,
|
|
6
6
|
resolveBackblazeEndpoint
|
|
@@ -546,13 +546,6 @@ var SupabaseStorageAdapter = class extends BaseStorageAdapter {
|
|
|
546
546
|
}
|
|
547
547
|
};
|
|
548
548
|
|
|
549
|
-
// src/storage/GoogleDriveStorageService.ts
|
|
550
|
-
var GoogleDriveStorageService = class extends GoogleDriveAdapter {
|
|
551
|
-
constructor(config, runtimeAuth = {}) {
|
|
552
|
-
super({ ...config, provider: "google_drive" }, runtimeAuth);
|
|
553
|
-
}
|
|
554
|
-
};
|
|
555
|
-
|
|
556
549
|
// src/storage/StorageAdapterFactory.ts
|
|
557
550
|
var StorageAdapterFactory = class {
|
|
558
551
|
static create(config, runtimeOptions = {}) {
|
|
@@ -585,6 +578,5 @@ export {
|
|
|
585
578
|
BucketStorageService,
|
|
586
579
|
BackblazeB2Adapter,
|
|
587
580
|
SupabaseStorageAdapter,
|
|
588
|
-
GoogleDriveStorageService,
|
|
589
581
|
StorageAdapterFactory
|
|
590
582
|
};
|
|
@@ -6,8 +6,8 @@ import {
|
|
|
6
6
|
updateWorkspace
|
|
7
7
|
} from "./chunk-JGUWYVOL.js";
|
|
8
8
|
import {
|
|
9
|
-
|
|
10
|
-
} from "./chunk-
|
|
9
|
+
GoogleDriveStorageService
|
|
10
|
+
} from "./chunk-OQRQCDS6.js";
|
|
11
11
|
import {
|
|
12
12
|
b2DownloadFile,
|
|
13
13
|
b2ListFileNames,
|
|
@@ -350,13 +350,18 @@ async function syncWorkspace(workspaceId) {
|
|
|
350
350
|
if (isGoogleDrive) {
|
|
351
351
|
const creds = workspace.storageConfig || connection?.credentials || connection || {};
|
|
352
352
|
const rootFolderId = creds.googleRootFolderId || creds.rootFolderId || workspace.googleRootFolderId;
|
|
353
|
-
const adapter = new
|
|
353
|
+
const adapter = new GoogleDriveStorageService({
|
|
354
354
|
provider: "google_drive",
|
|
355
355
|
googleAccessToken: creds.googleAccessToken || creds.accessToken,
|
|
356
356
|
googleAccessTokenExpiresAt: creds.googleAccessTokenExpiresAt,
|
|
357
357
|
googleRefreshToken: creds.googleRefreshToken || creds.refreshToken,
|
|
358
358
|
googleClientId: creds.googleClientId || process.env.GOOGLE_CLIENT_ID,
|
|
359
|
+
googleRedirectUri: creds.googleRedirectUri || process.env.GOOGLE_REDIRECT_URI,
|
|
360
|
+
googleAccountId: creds.googleAccountId,
|
|
359
361
|
googleRootFolderId: rootFolderId
|
|
362
|
+
}, {
|
|
363
|
+
// OAuth secrets remain in server environment, never in workspace connection records.
|
|
364
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET
|
|
360
365
|
});
|
|
361
366
|
try {
|
|
362
367
|
const remoteFiles = await adapter.list("");
|