@ultrst-armada/kloks 2.0.3 → 2.0.5
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 +6 -1
- package/packages/backend/dist/api/index.js +2 -1
- package/packages/backend/dist/{chunk-5F5V7NAG.js → chunk-5Y7K7HAT.js} +4 -1
- package/packages/backend/dist/{chunk-SQKG3S6P.js → chunk-AUNIGE6Q.js} +2 -2
- package/packages/backend/dist/chunk-BRNWUIH5.js +197 -0
- package/packages/backend/dist/{chunk-NY2SQOXI.js → chunk-CDRHYO44.js} +4 -1
- package/packages/backend/dist/{chunk-ZBNSK26X.js → chunk-CV55JMT7.js} +6 -5
- package/packages/backend/dist/{chunk-OWMQLML7.js → chunk-EMSSTOOK.js} +33 -2
- package/packages/backend/dist/chunk-FSOOAU6G.js +1132 -0
- package/packages/backend/dist/chunk-GVMVYC6C.js +0 -0
- package/packages/backend/dist/chunk-I6T64MLT.js +171 -0
- package/packages/backend/dist/chunk-ICVDGH2I.js +889 -0
- package/packages/backend/dist/chunk-IP6XWQU2.js +48 -0
- package/packages/backend/dist/chunk-IRNQXVYA.js +746 -0
- package/packages/backend/dist/{chunk-POLVHTHJ.js → chunk-KCPQWJBO.js} +4 -1
- package/packages/backend/dist/chunk-LC6ULEM2.js +125 -0
- package/packages/backend/dist/{chunk-NTKUQVCQ.js → chunk-LMUMMVTU.js} +14 -2
- package/packages/backend/dist/chunk-LMY6MGFD.js +78 -0
- package/packages/backend/dist/{chunk-OQRQCDS6.js → chunk-TRJVVNO7.js} +2 -2
- package/packages/backend/dist/{chunk-KPLDYX5Z.js → chunk-TRP76UR2.js} +33 -26
- package/packages/backend/dist/{chunk-FK3OAUXM.js → chunk-WYEVA4RC.js} +4 -2
- package/packages/backend/dist/{chunk-Z6G32NQQ.js → chunk-XKUWLO2M.js} +12 -9
- package/packages/backend/dist/{chunk-OXEP3AP6.js → chunk-Z2CT2MJ2.js} +158 -1
- package/packages/backend/dist/control-plane/index.js +3 -1
- package/packages/backend/dist/core/b2DirectCore.test.d.ts +1 -0
- package/packages/backend/dist/core/cloudflareIntegrationCore.test.d.ts +1 -0
- package/packages/backend/dist/core/googleDriveOAuthCore.d.ts +51 -0
- package/packages/backend/dist/core/googleDriveOAuthCore.test.d.ts +1 -0
- package/packages/backend/dist/core/index.d.ts +3 -0
- package/packages/backend/dist/core/storageConnectionCore.d.ts +136 -0
- package/packages/backend/dist/core/storageConnectionCore.test.d.ts +1 -0
- package/packages/backend/dist/core/storageConnectionRuntimeCore.d.ts +57 -0
- package/packages/backend/dist/core/storageConnectionRuntimeCore.test.d.ts +1 -0
- package/packages/backend/dist/core/storageContracts.d.ts +77 -0
- package/packages/backend/dist/core/storageProviderRegistry.d.ts +7 -0
- package/packages/backend/dist/core/systemCredentialsCore.d.ts +46 -0
- package/packages/backend/dist/core/unifiedDb.d.ts +12 -2
- package/packages/backend/dist/core/unifiedDb.errors.test.d.ts +1 -0
- package/packages/backend/dist/core/unifiedDbNodeAdapter.d.ts +6 -0
- package/packages/backend/dist/core/workspaceBucketSyncCore.d.ts +3 -4
- package/packages/backend/dist/core/workspaceBucketSyncCore.test.d.ts +1 -0
- package/packages/backend/dist/core/workspaceCore.d.ts +25 -6
- package/packages/backend/dist/core/workspaceDataCore.test.d.ts +1 -0
- package/packages/backend/dist/core/workspaceFileCore.d.ts +25 -7
- package/packages/backend/dist/core/workspaceFileCore.test.d.ts +1 -0
- package/packages/backend/dist/core/workspaceFileNodeAdapter.d.ts +6 -0
- package/packages/backend/dist/core/workspaceStorageDetailsCore.d.ts +4 -8
- package/packages/backend/dist/core/workspaceStorageDetailsCore.test.d.ts +1 -0
- package/packages/backend/dist/development/index.js +1 -1
- package/packages/backend/dist/development/playwrightInspectionService.js +1 -1
- package/packages/backend/dist/development/playwrightInspectionSupport.d.ts +1 -0
- package/packages/backend/dist/index.js +22 -16
- package/packages/backend/dist/krnl-services.d.ts +0 -22
- package/packages/backend/dist/krnl-services.js +8 -19
- package/packages/backend/dist/krnl-services.node.d.ts +28 -0
- package/packages/backend/dist/node.d.ts +3 -0
- package/packages/backend/dist/node.js +645 -463
- package/packages/backend/dist/resolver/index.js +13 -0
- package/packages/backend/dist/resolver/systemDatabaseUrl.d.ts +16 -12
- package/packages/backend/dist/services/node.js +12 -10
- package/packages/backend/dist/srkl/index.js +6 -4
- package/packages/backend/dist/storage/B2DirectClient.d.ts +7 -13
- package/packages/backend/dist/storage/B2DirectClient.test.d.ts +1 -0
- package/packages/backend/dist/storage/GoogleDriveWorkspaceService.d.ts +5 -0
- package/packages/backend/dist/storage/index.js +4 -3
- package/packages/backend/dist/storage/node.js +7 -6
- package/packages/backend/dist/storage-workspace.js +1 -1
- package/packages/backend/dist/workspace/index.js +2 -1
- package/packages/backend/dist/workspace/node.js +12 -7
- package/packages/backend/dist/workspaceFileCore-UURQPP62.js +28 -0
- package/packages/backend/package.json +8 -3
- package/packages/services/dist/index.js +8 -2
- package/packages/state-graph/dist/browser.js +16 -16
- package/packages/state-graph/dist/index.js +16 -16
- package/packages/backend/dist/chunk-4QEMALXF.js +0 -90
- package/packages/backend/dist/chunk-AOZSDRNY.js +0 -159
- package/packages/backend/dist/chunk-GYSZ6CAX.js +0 -19
- package/packages/backend/dist/chunk-JCMB7BIM.js +0 -211
- package/packages/backend/dist/chunk-JGUWYVOL.js +0 -570
- package/packages/backend/dist/chunk-LMOM7CST.js +0 -427
- package/packages/state-graph/dist/{chunk-UKTICGGV.js → chunk-YUJC367F.js} +3 -3
|
@@ -0,0 +1,1132 @@
|
|
|
1
|
+
import {
|
|
2
|
+
authorizeB2,
|
|
3
|
+
b2ListBuckets
|
|
4
|
+
} from "./chunk-I6T64MLT.js";
|
|
5
|
+
import {
|
|
6
|
+
resolveSystemDatabaseUrlCandidates,
|
|
7
|
+
tryResolveSystemDatabaseUrl
|
|
8
|
+
} from "./chunk-IP6XWQU2.js";
|
|
9
|
+
import {
|
|
10
|
+
GoogleDriveWorkspaceService
|
|
11
|
+
} from "./chunk-EMSSTOOK.js";
|
|
12
|
+
|
|
13
|
+
// src/core/unifiedDb.ts
|
|
14
|
+
var neon;
|
|
15
|
+
var defaultSystemEnvironmentResolver = null;
|
|
16
|
+
function configureUnifiedDatabaseEnvironmentResolver(resolver) {
|
|
17
|
+
defaultSystemEnvironmentResolver = resolver;
|
|
18
|
+
}
|
|
19
|
+
function defaultSystemEnvironment() {
|
|
20
|
+
return defaultSystemEnvironmentResolver?.() || {};
|
|
21
|
+
}
|
|
22
|
+
function cleanDbUrl(url) {
|
|
23
|
+
if (typeof url !== "string") return "";
|
|
24
|
+
return url.trim().replace(/^["']|["']$/g, "").trim();
|
|
25
|
+
}
|
|
26
|
+
function getUnifiedDbUrl(env) {
|
|
27
|
+
const supplied = env || {};
|
|
28
|
+
const hasCanonicalBindings = [
|
|
29
|
+
"SYSTEM_DATABASE_URL",
|
|
30
|
+
"SYSTEM_DATABASE_URL_2",
|
|
31
|
+
"SYSTEM_DATABASE_URL_3"
|
|
32
|
+
].some((key) => Object.prototype.hasOwnProperty.call(supplied, key));
|
|
33
|
+
const effective = env === void 0 ? defaultSystemEnvironment() : hasCanonicalBindings ? supplied : { ...defaultSystemEnvironment(), ...supplied };
|
|
34
|
+
return tryResolveSystemDatabaseUrl(effective) || "";
|
|
35
|
+
}
|
|
36
|
+
function isConnectionLevelFailure(error) {
|
|
37
|
+
const value = error;
|
|
38
|
+
const code = String(value?.code || value?.cause?.code || "").toUpperCase();
|
|
39
|
+
if ([
|
|
40
|
+
"ECONNRESET",
|
|
41
|
+
"ECONNREFUSED",
|
|
42
|
+
"ENOTFOUND",
|
|
43
|
+
"EAI_AGAIN",
|
|
44
|
+
"ETIMEDOUT",
|
|
45
|
+
"EHOSTUNREACH",
|
|
46
|
+
"ENETUNREACH",
|
|
47
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
48
|
+
"08000",
|
|
49
|
+
"08001",
|
|
50
|
+
"08003",
|
|
51
|
+
"08004",
|
|
52
|
+
"08006",
|
|
53
|
+
"08007",
|
|
54
|
+
"57P03"
|
|
55
|
+
].includes(code)) return true;
|
|
56
|
+
const message = String(value?.message || error || "").toLowerCase();
|
|
57
|
+
return message.includes("fetch failed") || message.includes("network error") || message.includes("connection terminated unexpectedly") || message.includes("socket hang up") || message.includes("connect timeout");
|
|
58
|
+
}
|
|
59
|
+
async function queryUnifiedDb(sqlText, params = [], env) {
|
|
60
|
+
const supplied = env || {};
|
|
61
|
+
const hasCanonicalBindings = [
|
|
62
|
+
"SYSTEM_DATABASE_URL",
|
|
63
|
+
"SYSTEM_DATABASE_URL_2",
|
|
64
|
+
"SYSTEM_DATABASE_URL_3"
|
|
65
|
+
].some((key) => Object.prototype.hasOwnProperty.call(supplied, key));
|
|
66
|
+
const effectiveEnv = env === void 0 ? defaultSystemEnvironment() : hasCanonicalBindings ? supplied : { ...defaultSystemEnvironment(), ...supplied };
|
|
67
|
+
const databaseUrls = resolveSystemDatabaseUrlCandidates(effectiveEnv);
|
|
68
|
+
if (databaseUrls.length === 0) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
"[UnifiedDB] Missing system database configuration. Set SYSTEM_DATABASE_URL; SYSTEM_DATABASE_URL_2 and SYSTEM_DATABASE_URL_3 are optional failover URLs."
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
if (!neon) {
|
|
74
|
+
const mod = await import("@neondatabase/serverless");
|
|
75
|
+
neon = mod.neon;
|
|
76
|
+
}
|
|
77
|
+
let lastError;
|
|
78
|
+
for (let index = 0; index < databaseUrls.length; index += 1) {
|
|
79
|
+
const databaseUrl = databaseUrls[index];
|
|
80
|
+
try {
|
|
81
|
+
const sql = neon(databaseUrl);
|
|
82
|
+
const rows = await (sql.query ? sql.query(sqlText, params) : sql(sqlText, params));
|
|
83
|
+
return {
|
|
84
|
+
rows: Array.isArray(rows) ? rows : [],
|
|
85
|
+
rowCount: Array.isArray(rows) ? rows.length : 0
|
|
86
|
+
};
|
|
87
|
+
} catch (error) {
|
|
88
|
+
lastError = error;
|
|
89
|
+
const hasNextFallback = index < databaseUrls.length - 1;
|
|
90
|
+
if (!hasNextFallback || !isConnectionLevelFailure(error)) {
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const rawCode = String(
|
|
96
|
+
lastError?.code || lastError?.cause?.code || ""
|
|
97
|
+
).toUpperCase();
|
|
98
|
+
const safeCode = /^[A-Z0-9]{5}$/.test(rawCode) ? rawCode : "";
|
|
99
|
+
console.error("[UnifiedDB] Query execution failed.", safeCode ? { code: safeCode } : void 0);
|
|
100
|
+
const sanitizedError = new Error(
|
|
101
|
+
safeCode ? `[UnifiedDB] Query execution failed (database code ${safeCode}).` : "[UnifiedDB] Query execution failed."
|
|
102
|
+
);
|
|
103
|
+
if (safeCode) Object.assign(sanitizedError, { code: safeCode });
|
|
104
|
+
throw sanitizedError;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/core/systemCredentialsCore.ts
|
|
108
|
+
function parseCredentials(value) {
|
|
109
|
+
if (typeof value === "string") {
|
|
110
|
+
try {
|
|
111
|
+
const parsed = JSON.parse(value);
|
|
112
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
113
|
+
} catch {
|
|
114
|
+
return {};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return value && typeof value === "object" ? value : {};
|
|
118
|
+
}
|
|
119
|
+
async function readSystemCredentialsRecord(queryDb, targetId = "system") {
|
|
120
|
+
const result = await queryDb(
|
|
121
|
+
'SELECT id, credentials, created_at, updated_at FROM public."ultrst-credentials" WHERE id = $1 LIMIT 1',
|
|
122
|
+
[targetId]
|
|
123
|
+
);
|
|
124
|
+
const row = result.rows[0];
|
|
125
|
+
if (!row) return { id: targetId, credentials: {} };
|
|
126
|
+
return {
|
|
127
|
+
id: String(row.id || targetId),
|
|
128
|
+
credentials: parseCredentials(row.credentials),
|
|
129
|
+
...row.created_at ? { created_at: new Date(row.created_at).toISOString() } : {},
|
|
130
|
+
...row.updated_at ? { updated_at: new Date(row.updated_at).toISOString() } : {}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
async function getSystemCredentialsRecord(queryDb, targetId = "system") {
|
|
134
|
+
await queryDb(`
|
|
135
|
+
CREATE TABLE IF NOT EXISTS public."ultrst-credentials" (
|
|
136
|
+
id TEXT PRIMARY KEY,
|
|
137
|
+
credentials JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
138
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
139
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
140
|
+
)
|
|
141
|
+
`);
|
|
142
|
+
await queryDb(`
|
|
143
|
+
ALTER TABLE public."ultrst-credentials"
|
|
144
|
+
ADD COLUMN IF NOT EXISTS credentials JSONB NOT NULL DEFAULT '{}'::jsonb
|
|
145
|
+
`);
|
|
146
|
+
await queryDb(`
|
|
147
|
+
INSERT INTO public."ultrst-credentials" (id, credentials)
|
|
148
|
+
VALUES ($1, '{}'::jsonb)
|
|
149
|
+
ON CONFLICT (id) DO NOTHING
|
|
150
|
+
`, [targetId]);
|
|
151
|
+
const result = await queryDb(
|
|
152
|
+
'SELECT id, credentials, created_at, updated_at FROM public."ultrst-credentials" WHERE id = $1 LIMIT 1',
|
|
153
|
+
[targetId]
|
|
154
|
+
);
|
|
155
|
+
const row = result.rows[0];
|
|
156
|
+
if (!row) return { id: targetId, credentials: {} };
|
|
157
|
+
return {
|
|
158
|
+
id: String(row.id || targetId),
|
|
159
|
+
credentials: parseCredentials(row.credentials),
|
|
160
|
+
...row.created_at ? { created_at: new Date(row.created_at).toISOString() } : {},
|
|
161
|
+
...row.updated_at ? { updated_at: new Date(row.updated_at).toISOString() } : {}
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
async function getGoogleDriveOAuthConfiguration(queryDb) {
|
|
165
|
+
const record = await getSystemCredentialsRecord(queryDb, "system");
|
|
166
|
+
const root = record.credentials || {};
|
|
167
|
+
const oauth = root.googleDriveOAuth || root.googleOAuth || {};
|
|
168
|
+
const clientId = typeof oauth.clientId === "string" ? oauth.clientId.trim() : "";
|
|
169
|
+
const clientSecret = typeof oauth.clientSecret === "string" ? oauth.clientSecret.trim() : "";
|
|
170
|
+
const redirectUri = typeof oauth.redirectUri === "string" ? oauth.redirectUri.trim() : "";
|
|
171
|
+
const stateSecret = typeof oauth.stateSecret === "string" ? oauth.stateSecret.trim() : "";
|
|
172
|
+
const missing = [];
|
|
173
|
+
if (!clientId) missing.push("client ID");
|
|
174
|
+
if (!clientSecret) missing.push("client secret");
|
|
175
|
+
if (!redirectUri) missing.push("redirect URI");
|
|
176
|
+
if (!stateSecret || stateSecret.length < 32) missing.push("OAuth state signing secret (minimum 32 characters)");
|
|
177
|
+
if (missing.length) {
|
|
178
|
+
throw new Error(
|
|
179
|
+
`[STORAGE_PROVIDER_CONFIGURATION_MISSING] Google Drive OAuth system configuration is incomplete: ${missing.join(", ")}. Configure system.ultrst-credentials.googleDriveOAuth.`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
let parsedRedirect;
|
|
183
|
+
try {
|
|
184
|
+
parsedRedirect = new URL(redirectUri);
|
|
185
|
+
} catch {
|
|
186
|
+
throw new Error("[STORAGE_PROVIDER_CONFIGURATION_INVALID] Google Drive OAuth redirect URI must be an absolute URL.");
|
|
187
|
+
}
|
|
188
|
+
if (parsedRedirect.protocol !== "https:" && parsedRedirect.hostname !== "localhost") {
|
|
189
|
+
throw new Error("[STORAGE_PROVIDER_CONFIGURATION_INVALID] Google Drive OAuth redirect URI must use HTTPS (localhost is allowed for development).");
|
|
190
|
+
}
|
|
191
|
+
const allowedReturnOrigins = Array.isArray(oauth.allowedReturnOrigins) ? oauth.allowedReturnOrigins.flatMap((value) => {
|
|
192
|
+
if (typeof value !== "string") return [];
|
|
193
|
+
try {
|
|
194
|
+
const url = new URL(value.trim());
|
|
195
|
+
if (url.protocol !== "https:" && url.hostname !== "localhost") return [];
|
|
196
|
+
return [url.origin];
|
|
197
|
+
} catch {
|
|
198
|
+
return [];
|
|
199
|
+
}
|
|
200
|
+
}) : [];
|
|
201
|
+
return { clientId, clientSecret, redirectUri, stateSecret, allowedReturnOrigins };
|
|
202
|
+
}
|
|
203
|
+
function decodeStorageEncryptionKey(value) {
|
|
204
|
+
if (!/^[A-Za-z0-9_-]{43}$/.test(value)) {
|
|
205
|
+
throw new Error("[STORAGE_SECRET_CONFIGURATION_INVALID] The canonical storage encryption key is malformed.");
|
|
206
|
+
}
|
|
207
|
+
const base64 = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(44, "=");
|
|
208
|
+
let binary;
|
|
209
|
+
try {
|
|
210
|
+
binary = atob(base64);
|
|
211
|
+
} catch {
|
|
212
|
+
throw new Error("[STORAGE_SECRET_CONFIGURATION_INVALID] The canonical storage encryption key is malformed.");
|
|
213
|
+
}
|
|
214
|
+
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
215
|
+
if (bytes.length !== 32) {
|
|
216
|
+
throw new Error("[STORAGE_SECRET_CONFIGURATION_INVALID] The canonical storage encryption key must decode to exactly 32 bytes.");
|
|
217
|
+
}
|
|
218
|
+
return bytes;
|
|
219
|
+
}
|
|
220
|
+
async function getStorageConnectionEncryptionKey(queryDb) {
|
|
221
|
+
const record = await readSystemCredentialsRecord(queryDb, "system");
|
|
222
|
+
const storage = record.credentials?.storageConnections && typeof record.credentials.storageConnections === "object" ? record.credentials.storageConnections : {};
|
|
223
|
+
const current = typeof storage.encryptionKey === "string" ? storage.encryptionKey.trim() : "";
|
|
224
|
+
if (!current) {
|
|
225
|
+
throw new Error("[STORAGE_SECRET_CONFIGURATION_MISSING] The system-owned storage encryption key is missing; encrypted user connections were not modified.");
|
|
226
|
+
}
|
|
227
|
+
decodeStorageEncryptionKey(current);
|
|
228
|
+
const version = storage.encryptionKeyVersion == null ? 1 : Number(storage.encryptionKeyVersion);
|
|
229
|
+
if (version !== 1) {
|
|
230
|
+
throw new Error("[STORAGE_SECRET_CONFIGURATION_UNSUPPORTED] The canonical storage encryption key version is not supported.");
|
|
231
|
+
}
|
|
232
|
+
return current;
|
|
233
|
+
}
|
|
234
|
+
async function getOrCreateStorageConnectionEncryptionKey(queryDb) {
|
|
235
|
+
const record = await getSystemCredentialsRecord(queryDb, "system");
|
|
236
|
+
const root = record.credentials || {};
|
|
237
|
+
const storage = root.storageConnections && typeof root.storageConnections === "object" ? root.storageConnections : {};
|
|
238
|
+
const current = typeof storage.encryptionKey === "string" ? storage.encryptionKey.trim() : "";
|
|
239
|
+
if (current) {
|
|
240
|
+
decodeStorageEncryptionKey(current);
|
|
241
|
+
const version2 = storage.encryptionKeyVersion == null ? 1 : Number(storage.encryptionKeyVersion);
|
|
242
|
+
if (version2 !== 1) {
|
|
243
|
+
throw new Error("[STORAGE_SECRET_CONFIGURATION_UNSUPPORTED] The canonical storage encryption key version is not supported.");
|
|
244
|
+
}
|
|
245
|
+
return current;
|
|
246
|
+
}
|
|
247
|
+
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
248
|
+
let binary = "";
|
|
249
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
250
|
+
const generated = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
251
|
+
decodeStorageEncryptionKey(generated);
|
|
252
|
+
await queryDb(
|
|
253
|
+
`UPDATE public."ultrst-credentials"
|
|
254
|
+
SET credentials = jsonb_set(
|
|
255
|
+
COALESCE(credentials, '{}'::jsonb),
|
|
256
|
+
'{storageConnections}',
|
|
257
|
+
COALESCE(credentials->'storageConnections', '{}'::jsonb)
|
|
258
|
+
|| jsonb_build_object('encryptionKey', $1::text, 'encryptionKeyVersion', 1),
|
|
259
|
+
true
|
|
260
|
+
),
|
|
261
|
+
updated_at = NOW()
|
|
262
|
+
WHERE id = $2
|
|
263
|
+
AND NULLIF(credentials #>> '{storageConnections,encryptionKey}', '') IS NULL`,
|
|
264
|
+
[generated, "system"]
|
|
265
|
+
);
|
|
266
|
+
const refreshed = await getSystemCredentialsRecord(queryDb, "system");
|
|
267
|
+
const persisted = typeof refreshed.credentials?.storageConnections?.encryptionKey === "string" ? refreshed.credentials.storageConnections.encryptionKey.trim() : "";
|
|
268
|
+
if (!persisted) {
|
|
269
|
+
throw new Error("[STORAGE_SECRET_CONFIGURATION_UNAVAILABLE] Unable to resolve the canonical storage encryption key.");
|
|
270
|
+
}
|
|
271
|
+
decodeStorageEncryptionKey(persisted);
|
|
272
|
+
const version = refreshed.credentials.storageConnections.encryptionKeyVersion == null ? 1 : Number(refreshed.credentials.storageConnections.encryptionKeyVersion);
|
|
273
|
+
if (version !== 1) {
|
|
274
|
+
throw new Error("[STORAGE_SECRET_CONFIGURATION_UNSUPPORTED] The canonical storage encryption key version is not supported.");
|
|
275
|
+
}
|
|
276
|
+
return persisted;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// src/core/storageConnectionCore.ts
|
|
280
|
+
var DEFAULT_QUERY = (sql, params) => queryUnifiedDb(sql, params);
|
|
281
|
+
var PUBLIC_FIELDS = [
|
|
282
|
+
"id",
|
|
283
|
+
"provider",
|
|
284
|
+
"label",
|
|
285
|
+
"role",
|
|
286
|
+
"enabled",
|
|
287
|
+
"createdAt",
|
|
288
|
+
"updatedAt",
|
|
289
|
+
"testedAt",
|
|
290
|
+
"testStatus",
|
|
291
|
+
"latencyMs",
|
|
292
|
+
"b2BucketName",
|
|
293
|
+
"bucketName",
|
|
294
|
+
"b2Region",
|
|
295
|
+
"b2Endpoint",
|
|
296
|
+
"googleEmail",
|
|
297
|
+
"googleAccountId",
|
|
298
|
+
"googleRootFolderId",
|
|
299
|
+
"googleRootFolderName"
|
|
300
|
+
];
|
|
301
|
+
function mergeProfileDocuments(primary, legacy) {
|
|
302
|
+
if (Array.isArray(primary) && Array.isArray(legacy)) {
|
|
303
|
+
const primaryHasIds = primary.every((item) => item && typeof item === "object" && typeof item.id === "string");
|
|
304
|
+
const legacyHasIds = legacy.every((item) => item && typeof item === "object" && typeof item.id === "string");
|
|
305
|
+
if (primaryHasIds && legacyHasIds) {
|
|
306
|
+
const merged2 = new Map(primary.map((item) => [item.id, item]));
|
|
307
|
+
for (const item of legacy) {
|
|
308
|
+
const existing = merged2.get(item.id);
|
|
309
|
+
merged2.set(item.id, existing ? mergeProfileDocuments(existing, item) : item);
|
|
310
|
+
}
|
|
311
|
+
return [...merged2.values()];
|
|
312
|
+
}
|
|
313
|
+
const merged = [...primary];
|
|
314
|
+
const seen = new Set(primary.map((item) => JSON.stringify(item)));
|
|
315
|
+
for (const item of legacy) {
|
|
316
|
+
const key = JSON.stringify(item);
|
|
317
|
+
if (!seen.has(key)) {
|
|
318
|
+
merged.push(item);
|
|
319
|
+
seen.add(key);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return merged;
|
|
323
|
+
}
|
|
324
|
+
if (primary && typeof primary === "object" && !Array.isArray(primary) && legacy && typeof legacy === "object" && !Array.isArray(legacy)) {
|
|
325
|
+
const merged = { ...legacy, ...primary };
|
|
326
|
+
for (const key of Object.keys(legacy)) {
|
|
327
|
+
if (Object.prototype.hasOwnProperty.call(primary, key)) {
|
|
328
|
+
merged[key] = mergeProfileDocuments(primary[key], legacy[key]);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return merged;
|
|
332
|
+
}
|
|
333
|
+
return primary === void 0 ? legacy : primary;
|
|
334
|
+
}
|
|
335
|
+
function parseProfiles(value) {
|
|
336
|
+
if (typeof value === "string") {
|
|
337
|
+
try {
|
|
338
|
+
const parsed = JSON.parse(value);
|
|
339
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
340
|
+
} catch {
|
|
341
|
+
return {};
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return value && typeof value === "object" ? value : {};
|
|
345
|
+
}
|
|
346
|
+
var STORAGE_SECRET_FIELDS = [
|
|
347
|
+
"b2KeyId",
|
|
348
|
+
"b2ApplicationKey",
|
|
349
|
+
"keyId",
|
|
350
|
+
"applicationKey",
|
|
351
|
+
"appKey",
|
|
352
|
+
"accessKeyId",
|
|
353
|
+
"secretAccessKey",
|
|
354
|
+
"googleAccessToken",
|
|
355
|
+
"googleAccessTokenExpiresAt",
|
|
356
|
+
"googleRefreshToken",
|
|
357
|
+
"googleTokenType"
|
|
358
|
+
];
|
|
359
|
+
function isMissingOptionalProfileTable(error) {
|
|
360
|
+
if (!error || typeof error !== "object") return false;
|
|
361
|
+
const candidate = error;
|
|
362
|
+
if (candidate.code === "42P01" || candidate.code === "PGRST205") return true;
|
|
363
|
+
const message = typeof candidate.message === "string" ? candidate.message : "";
|
|
364
|
+
return /(?:relation|table).*(?:does not exist|not found)|schema cache.*(?:relation|table)/i.test(message);
|
|
365
|
+
}
|
|
366
|
+
function encodeBase64Url(bytes) {
|
|
367
|
+
let binary = "";
|
|
368
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
369
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
370
|
+
}
|
|
371
|
+
function decodeBase64Url(value) {
|
|
372
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("Storage connection secret envelope is malformed.");
|
|
373
|
+
const base64 = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
374
|
+
const binary = atob(base64);
|
|
375
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
376
|
+
}
|
|
377
|
+
function toCryptoBufferSource(bytes) {
|
|
378
|
+
const buffer = new ArrayBuffer(bytes.byteLength);
|
|
379
|
+
new Uint8Array(buffer).set(bytes);
|
|
380
|
+
return buffer;
|
|
381
|
+
}
|
|
382
|
+
function extractConnectionSecretPayload(connection) {
|
|
383
|
+
const payload = {};
|
|
384
|
+
for (const field of STORAGE_SECRET_FIELDS) {
|
|
385
|
+
if (connection[field] !== void 0 && connection[field] !== null && connection[field] !== "") {
|
|
386
|
+
payload[field] = connection[field];
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (connection.credentials && typeof connection.credentials === "object") {
|
|
390
|
+
payload.credentials = connection.credentials;
|
|
391
|
+
const nested = connection.credentials;
|
|
392
|
+
const aliases = {
|
|
393
|
+
b2KeyId: ["b2KeyId", "keyId"],
|
|
394
|
+
b2ApplicationKey: ["b2ApplicationKey", "applicationKey", "appKey"],
|
|
395
|
+
googleAccessToken: ["googleAccessToken", "accessToken"],
|
|
396
|
+
googleRefreshToken: ["googleRefreshToken", "refreshToken"],
|
|
397
|
+
googleAccessTokenExpiresAt: ["googleAccessTokenExpiresAt", "expiresAt"]
|
|
398
|
+
};
|
|
399
|
+
for (const [target, candidates] of Object.entries(aliases)) {
|
|
400
|
+
if (payload[target] !== void 0) continue;
|
|
401
|
+
const key = candidates.find((candidate) => nested[candidate] !== void 0 && nested[candidate] !== null);
|
|
402
|
+
if (key) payload[target] = nested[key];
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return payload;
|
|
406
|
+
}
|
|
407
|
+
function hasConnectionSecrets(connection) {
|
|
408
|
+
return Object.keys(extractConnectionSecretPayload(connection)).length > 0;
|
|
409
|
+
}
|
|
410
|
+
async function encryptConnectionSecretPayload(userId, connection, payload, query) {
|
|
411
|
+
if (Object.keys(payload).length === 0) return connection;
|
|
412
|
+
if (!connection.id || !connection.provider) {
|
|
413
|
+
throw new Error("A storage connection ID and provider are required before encrypting its credentials.");
|
|
414
|
+
}
|
|
415
|
+
const wrappingKey = await getOrCreateStorageConnectionEncryptionKey(query);
|
|
416
|
+
const key = await crypto.subtle.importKey(
|
|
417
|
+
"raw",
|
|
418
|
+
toCryptoBufferSource(decodeBase64Url(wrappingKey)),
|
|
419
|
+
{ name: "AES-GCM" },
|
|
420
|
+
false,
|
|
421
|
+
["encrypt"]
|
|
422
|
+
);
|
|
423
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
424
|
+
const additionalData = new TextEncoder().encode(
|
|
425
|
+
"ultrst-storage-connection:v1:" + userId + ":" + connection.id + ":" + connection.provider
|
|
426
|
+
);
|
|
427
|
+
const ciphertext = await crypto.subtle.encrypt(
|
|
428
|
+
{ name: "AES-GCM", iv: toCryptoBufferSource(iv), additionalData: toCryptoBufferSource(additionalData) },
|
|
429
|
+
key,
|
|
430
|
+
toCryptoBufferSource(new TextEncoder().encode(JSON.stringify(payload)))
|
|
431
|
+
);
|
|
432
|
+
const safe = { ...connection };
|
|
433
|
+
for (const field of STORAGE_SECRET_FIELDS) delete safe[field];
|
|
434
|
+
delete safe.credentials;
|
|
435
|
+
safe.secretCiphertext = {
|
|
436
|
+
version: 1,
|
|
437
|
+
algorithm: "AES-GCM-256",
|
|
438
|
+
iv: encodeBase64Url(iv),
|
|
439
|
+
ciphertext: encodeBase64Url(new Uint8Array(ciphertext))
|
|
440
|
+
};
|
|
441
|
+
return safe;
|
|
442
|
+
}
|
|
443
|
+
async function hydrateConnectionSecrets(userId, connection, query) {
|
|
444
|
+
const envelope = connection.secretCiphertext;
|
|
445
|
+
let payload = {};
|
|
446
|
+
if (envelope !== void 0) {
|
|
447
|
+
if (envelope?.version !== 1 || envelope?.algorithm !== "AES-GCM-256" || typeof envelope.iv !== "string" || typeof envelope.ciphertext !== "string") {
|
|
448
|
+
throw new Error("The saved storage connection has an unsupported encrypted credential format.");
|
|
449
|
+
}
|
|
450
|
+
try {
|
|
451
|
+
const wrappingKey = await getStorageConnectionEncryptionKey(query);
|
|
452
|
+
const key = await crypto.subtle.importKey(
|
|
453
|
+
"raw",
|
|
454
|
+
toCryptoBufferSource(decodeBase64Url(wrappingKey)),
|
|
455
|
+
{ name: "AES-GCM" },
|
|
456
|
+
false,
|
|
457
|
+
["decrypt"]
|
|
458
|
+
);
|
|
459
|
+
const additionalData = new TextEncoder().encode(
|
|
460
|
+
"ultrst-storage-connection:v1:" + userId + ":" + connection.id + ":" + connection.provider
|
|
461
|
+
);
|
|
462
|
+
const plaintext = await crypto.subtle.decrypt(
|
|
463
|
+
{
|
|
464
|
+
name: "AES-GCM",
|
|
465
|
+
iv: toCryptoBufferSource(decodeBase64Url(envelope.iv)),
|
|
466
|
+
additionalData: toCryptoBufferSource(additionalData)
|
|
467
|
+
},
|
|
468
|
+
key,
|
|
469
|
+
toCryptoBufferSource(decodeBase64Url(envelope.ciphertext))
|
|
470
|
+
);
|
|
471
|
+
const parsed = JSON.parse(new TextDecoder().decode(plaintext));
|
|
472
|
+
if (!parsed || typeof parsed !== "object") throw new Error("invalid payload");
|
|
473
|
+
payload = parsed;
|
|
474
|
+
} catch (error) {
|
|
475
|
+
if (error instanceof Error && error.message.startsWith("[STORAGE_SECRET_CONFIGURATION_")) {
|
|
476
|
+
throw error;
|
|
477
|
+
}
|
|
478
|
+
throw new Error("The saved storage connection credentials could not be decrypted with the current system key.");
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
payload = { ...payload, ...extractConnectionSecretPayload(connection) };
|
|
482
|
+
const hydrated = { ...connection, ...payload };
|
|
483
|
+
if (payload.credentials && typeof payload.credentials === "object") {
|
|
484
|
+
const nested = payload.credentials;
|
|
485
|
+
hydrated.b2KeyId = hydrated.b2KeyId || nested.b2KeyId || nested.keyId;
|
|
486
|
+
hydrated.b2ApplicationKey = hydrated.b2ApplicationKey || nested.b2ApplicationKey || nested.applicationKey || nested.appKey;
|
|
487
|
+
hydrated.googleAccessToken = hydrated.googleAccessToken || nested.googleAccessToken || nested.accessToken;
|
|
488
|
+
hydrated.googleRefreshToken = hydrated.googleRefreshToken || nested.googleRefreshToken || nested.refreshToken;
|
|
489
|
+
hydrated.googleAccessTokenExpiresAt = hydrated.googleAccessTokenExpiresAt || nested.googleAccessTokenExpiresAt || nested.expiresAt;
|
|
490
|
+
}
|
|
491
|
+
return hydrated;
|
|
492
|
+
}
|
|
493
|
+
async function protectConnectionForStorage(userId, connection, query) {
|
|
494
|
+
const hydrated = await hydrateConnectionSecrets(userId, connection, query);
|
|
495
|
+
const payload = extractConnectionSecretPayload(hydrated);
|
|
496
|
+
if (Object.keys(payload).length === 0) return connection;
|
|
497
|
+
return encryptConnectionSecretPayload(userId, hydrated, payload, query);
|
|
498
|
+
}
|
|
499
|
+
async function writeUserProfiles(record, query) {
|
|
500
|
+
if (record.source === "ultrst-users") {
|
|
501
|
+
try {
|
|
502
|
+
const legacy = await query(
|
|
503
|
+
'SELECT app_profiles FROM "srkl_application_profiles" WHERE id = $1 OR email = $2 LIMIT 1',
|
|
504
|
+
[record.id, record.email || record.id]
|
|
505
|
+
);
|
|
506
|
+
if (legacy.rows[0]) {
|
|
507
|
+
const legacyProfiles = parseProfiles(legacy.rows[0].app_profiles);
|
|
508
|
+
const canonicalProfiles = record.profiles;
|
|
509
|
+
const canonicalConnections = Array.isArray(canonicalProfiles.srkl?.storage_connections) ? canonicalProfiles.srkl.storage_connections : [];
|
|
510
|
+
const legacyConnections = Array.isArray(legacyProfiles.srkl?.storage_connections) ? legacyProfiles.srkl.storage_connections : [];
|
|
511
|
+
const byId = /* @__PURE__ */ new Map();
|
|
512
|
+
for (const connection of legacyConnections) {
|
|
513
|
+
if (connection && typeof connection.id === "string") byId.set(connection.id, connection);
|
|
514
|
+
}
|
|
515
|
+
for (const connection of canonicalConnections) {
|
|
516
|
+
if (connection && typeof connection.id === "string") byId.set(connection.id, connection);
|
|
517
|
+
}
|
|
518
|
+
if (!canonicalProfiles.srkl || typeof canonicalProfiles.srkl !== "object") {
|
|
519
|
+
canonicalProfiles.srkl = {};
|
|
520
|
+
}
|
|
521
|
+
canonicalProfiles.srkl.storage_connections = [...byId.values()];
|
|
522
|
+
await query(
|
|
523
|
+
'UPDATE "srkl_application_profiles" SET app_profiles = $1, updated_at = NOW() WHERE id = $2 OR email = $3',
|
|
524
|
+
[JSON.stringify({
|
|
525
|
+
...legacyProfiles,
|
|
526
|
+
srkl: {
|
|
527
|
+
...legacyProfiles.srkl || {},
|
|
528
|
+
storage_connections: canonicalProfiles.srkl.storage_connections
|
|
529
|
+
}
|
|
530
|
+
}), record.id, record.email || record.id]
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
} catch (error) {
|
|
534
|
+
if (!isMissingOptionalProfileTable(error)) throw error;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const table = record.source === "ultrst-users" ? '"ultrst-users"' : '"srkl_application_profiles"';
|
|
538
|
+
await query(
|
|
539
|
+
"UPDATE " + table + " SET app_profiles = $1, updated_at = NOW() WHERE id = $2 OR email = $3",
|
|
540
|
+
[JSON.stringify(record.profiles), record.id, record.email || record.id]
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
async function migrateLegacyConnectionCollections(userId, query) {
|
|
544
|
+
const record = await findUserRecord(userId, query);
|
|
545
|
+
if (!record) return;
|
|
546
|
+
let changed = record.needsProfileMerge;
|
|
547
|
+
for (const value of Object.values(record.profiles)) {
|
|
548
|
+
if (!value || typeof value !== "object") continue;
|
|
549
|
+
const profile = value;
|
|
550
|
+
if (!Array.isArray(profile.storage_connections)) continue;
|
|
551
|
+
const secured = [];
|
|
552
|
+
for (const connection of profile.storage_connections) {
|
|
553
|
+
if (connection && typeof connection === "object" && hasConnectionSecrets(connection)) {
|
|
554
|
+
const next = await protectConnectionForStorage(record.id, connection, query);
|
|
555
|
+
secured.push(next);
|
|
556
|
+
if (next !== connection && !connection.secretCiphertext) changed = true;
|
|
557
|
+
} else {
|
|
558
|
+
secured.push(connection);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
if (changed) profile.storage_connections = secured;
|
|
562
|
+
}
|
|
563
|
+
if (record.source === "ultrst-users") {
|
|
564
|
+
try {
|
|
565
|
+
const legacy = await query(
|
|
566
|
+
'SELECT app_profiles FROM "srkl_application_profiles" WHERE id = $1 OR email = $2 LIMIT 1',
|
|
567
|
+
[record.id, record.email || record.id]
|
|
568
|
+
);
|
|
569
|
+
if (legacy.rows[0]) {
|
|
570
|
+
const profiles = parseProfiles(legacy.rows[0].app_profiles);
|
|
571
|
+
let legacyChanged = false;
|
|
572
|
+
for (const value of Object.values(profiles)) {
|
|
573
|
+
if (!value || typeof value !== "object") continue;
|
|
574
|
+
const profile = value;
|
|
575
|
+
if (!Array.isArray(profile.storage_connections)) continue;
|
|
576
|
+
const secured = [];
|
|
577
|
+
for (const connection of profile.storage_connections) {
|
|
578
|
+
if (connection && typeof connection === "object" && hasConnectionSecrets(connection)) {
|
|
579
|
+
const next = await protectConnectionForStorage(record.id, connection, query);
|
|
580
|
+
secured.push(next);
|
|
581
|
+
if (next !== connection && !connection.secretCiphertext) legacyChanged = true;
|
|
582
|
+
} else {
|
|
583
|
+
secured.push(connection);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
if (legacyChanged) profile.storage_connections = secured;
|
|
587
|
+
}
|
|
588
|
+
if (legacyChanged) {
|
|
589
|
+
await query(
|
|
590
|
+
'UPDATE "srkl_application_profiles" SET app_profiles = $1, updated_at = NOW() WHERE id = $2 OR email = $3',
|
|
591
|
+
[JSON.stringify(profiles), record.id, record.email || record.id]
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
} catch (error) {
|
|
596
|
+
if (!isMissingOptionalProfileTable(error)) throw error;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
if (changed) await writeUserProfiles(record, query);
|
|
600
|
+
}
|
|
601
|
+
function connectionCollections(profiles) {
|
|
602
|
+
const collections = [];
|
|
603
|
+
const srklConnections = profiles.srkl?.storage_connections;
|
|
604
|
+
if (Array.isArray(srklConnections)) collections.push(srklConnections);
|
|
605
|
+
for (const [key, value] of Object.entries(profiles)) {
|
|
606
|
+
if (key === "srkl" || !value || typeof value !== "object") continue;
|
|
607
|
+
const connections = value.storage_connections;
|
|
608
|
+
if (Array.isArray(connections)) collections.push(connections);
|
|
609
|
+
}
|
|
610
|
+
return collections;
|
|
611
|
+
}
|
|
612
|
+
function toPublicStorageConnection(raw) {
|
|
613
|
+
if (!raw || typeof raw.id !== "string" || !raw.id || typeof raw.provider !== "string") return null;
|
|
614
|
+
const safe = {};
|
|
615
|
+
for (const key of PUBLIC_FIELDS) {
|
|
616
|
+
const value = raw[key];
|
|
617
|
+
if (value !== void 0 && value !== null) safe[key] = value;
|
|
618
|
+
}
|
|
619
|
+
safe.label = String(raw.label || raw.name || raw.id);
|
|
620
|
+
safe.enabled = raw.enabled !== false;
|
|
621
|
+
return safe;
|
|
622
|
+
}
|
|
623
|
+
function deduplicateRawConnections(items) {
|
|
624
|
+
const byId = /* @__PURE__ */ new Map();
|
|
625
|
+
for (const item of items) {
|
|
626
|
+
if (!item || typeof item.id !== "string" || !item.id) continue;
|
|
627
|
+
const existing = byId.get(item.id);
|
|
628
|
+
byId.set(item.id, existing ? { ...item, ...existing, id: existing.id } : item);
|
|
629
|
+
}
|
|
630
|
+
return [...byId.values()];
|
|
631
|
+
}
|
|
632
|
+
async function findUserRecord(userId, query) {
|
|
633
|
+
if (!userId?.trim()) return null;
|
|
634
|
+
try {
|
|
635
|
+
const result = await query(
|
|
636
|
+
'SELECT id, email, app_profiles FROM "ultrst-users" WHERE id = $1 OR email = $1 LIMIT 1',
|
|
637
|
+
[userId]
|
|
638
|
+
);
|
|
639
|
+
if (result.rows[0]) {
|
|
640
|
+
const userId2 = String(result.rows[0].id);
|
|
641
|
+
const canonicalProfiles = parseProfiles(result.rows[0].app_profiles);
|
|
642
|
+
let profiles = canonicalProfiles;
|
|
643
|
+
let needsProfileMerge = false;
|
|
644
|
+
try {
|
|
645
|
+
const legacy = await query(
|
|
646
|
+
'SELECT app_profiles FROM "srkl_application_profiles" WHERE id = $1 OR email = $2 LIMIT 1',
|
|
647
|
+
[userId2, String(result.rows[0].email || userId2)]
|
|
648
|
+
);
|
|
649
|
+
if (legacy.rows[0]) {
|
|
650
|
+
profiles = mergeProfileDocuments(profiles, parseProfiles(legacy.rows[0].app_profiles));
|
|
651
|
+
needsProfileMerge = JSON.stringify(profiles) !== JSON.stringify(canonicalProfiles);
|
|
652
|
+
}
|
|
653
|
+
} catch (error) {
|
|
654
|
+
if (!isMissingOptionalProfileTable(error)) throw error;
|
|
655
|
+
}
|
|
656
|
+
return { id: userId2, email: String(result.rows[0].email || "") || void 0, profiles, source: "ultrst-users", needsProfileMerge };
|
|
657
|
+
}
|
|
658
|
+
} catch (error) {
|
|
659
|
+
if (!isMissingOptionalProfileTable(error)) throw error;
|
|
660
|
+
}
|
|
661
|
+
try {
|
|
662
|
+
const result = await query(
|
|
663
|
+
'SELECT id, email, app_profiles FROM "srkl_application_profiles" WHERE id = $1 OR email = $1 LIMIT 1',
|
|
664
|
+
[userId]
|
|
665
|
+
);
|
|
666
|
+
if (result.rows[0]) {
|
|
667
|
+
return {
|
|
668
|
+
id: String(result.rows[0].id),
|
|
669
|
+
email: String(result.rows[0].email || "") || void 0,
|
|
670
|
+
profiles: parseProfiles(result.rows[0].app_profiles),
|
|
671
|
+
source: "srkl_application_profiles",
|
|
672
|
+
needsProfileMerge: false
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
} catch (error) {
|
|
676
|
+
if (!isMissingOptionalProfileTable(error)) throw error;
|
|
677
|
+
}
|
|
678
|
+
return null;
|
|
679
|
+
}
|
|
680
|
+
async function mergeLegacySrklConnections(userId, profiles, query, email) {
|
|
681
|
+
const local = connectionCollections(profiles).flat();
|
|
682
|
+
try {
|
|
683
|
+
const result = await query(
|
|
684
|
+
'SELECT app_profiles FROM "srkl_application_profiles" WHERE id = $1 OR email = $2 LIMIT 1',
|
|
685
|
+
[userId, email || userId]
|
|
686
|
+
);
|
|
687
|
+
if (result.rows[0]) {
|
|
688
|
+
const legacyProfiles = parseProfiles(result.rows[0].app_profiles);
|
|
689
|
+
local.push(...Array.isArray(legacyProfiles.srkl?.storage_connections) ? legacyProfiles.srkl.storage_connections : []);
|
|
690
|
+
}
|
|
691
|
+
} catch (error) {
|
|
692
|
+
if (!isMissingOptionalProfileTable(error)) throw error;
|
|
693
|
+
}
|
|
694
|
+
return deduplicateRawConnections(local);
|
|
695
|
+
}
|
|
696
|
+
async function listUserStorageConnectionsWithSecrets(userId, query = DEFAULT_QUERY) {
|
|
697
|
+
await migrateLegacyConnectionCollections(userId, query);
|
|
698
|
+
const record = await findUserRecord(userId, query);
|
|
699
|
+
if (!record) return [];
|
|
700
|
+
const raw = await mergeLegacySrklConnections(record.id, record.profiles, query, record.email);
|
|
701
|
+
return Promise.all(raw.map((connection) => hydrateConnectionSecrets(record.id, connection, query)));
|
|
702
|
+
}
|
|
703
|
+
async function persistStorageConnectionCollection(userId, connections, query) {
|
|
704
|
+
const record = await findUserRecord(userId, query);
|
|
705
|
+
if (!record) throw new Error("A canonical user profile was not found for this storage connection.");
|
|
706
|
+
const secured = await Promise.all(
|
|
707
|
+
connections.map((connection) => protectConnectionForStorage(record.id, connection, query))
|
|
708
|
+
);
|
|
709
|
+
const incoming = new Map(secured.map((connection) => [String(connection.id), connection]));
|
|
710
|
+
const assigned = /* @__PURE__ */ new Set();
|
|
711
|
+
const profiles = record.profiles;
|
|
712
|
+
for (const value of Object.values(profiles)) {
|
|
713
|
+
if (!value || typeof value !== "object") continue;
|
|
714
|
+
const profile = value;
|
|
715
|
+
if (!Array.isArray(profile.storage_connections)) continue;
|
|
716
|
+
profile.storage_connections = profile.storage_connections.map((current) => {
|
|
717
|
+
const id = String(current?.id || "");
|
|
718
|
+
const next = incoming.get(id);
|
|
719
|
+
if (!next) return null;
|
|
720
|
+
assigned.add(id);
|
|
721
|
+
return next;
|
|
722
|
+
}).filter(Boolean);
|
|
723
|
+
}
|
|
724
|
+
const unassigned = secured.filter((connection) => !assigned.has(String(connection.id)));
|
|
725
|
+
if (unassigned.length) {
|
|
726
|
+
if (!profiles.srkl || typeof profiles.srkl !== "object") profiles.srkl = {};
|
|
727
|
+
const existing = Array.isArray(profiles.srkl.storage_connections) ? profiles.srkl.storage_connections : [];
|
|
728
|
+
const byId = new Map(existing.map((connection) => [String(connection?.id || ""), connection]));
|
|
729
|
+
for (const connection of unassigned) byId.set(String(connection.id), connection);
|
|
730
|
+
profiles.srkl.storage_connections = [...byId.values()];
|
|
731
|
+
}
|
|
732
|
+
await writeUserProfiles(record, query);
|
|
733
|
+
}
|
|
734
|
+
async function setPrimaryUserStorageConnection(userId, connectionId, query = DEFAULT_QUERY) {
|
|
735
|
+
const connections = await listUserStorageConnectionsWithSecrets(userId, query);
|
|
736
|
+
if (!connections.some((connection) => connection.id === connectionId)) {
|
|
737
|
+
throw new Error("Storage connection was not found for this user.");
|
|
738
|
+
}
|
|
739
|
+
const updated = connections.map((connection) => ({
|
|
740
|
+
...connection,
|
|
741
|
+
role: connection.id === connectionId ? "primary" : "redundant_clone"
|
|
742
|
+
}));
|
|
743
|
+
await persistStorageConnectionCollection(userId, updated, query);
|
|
744
|
+
return updated.map(toPublicStorageConnection).filter((item) => Boolean(item));
|
|
745
|
+
}
|
|
746
|
+
async function deleteUserStorageConnection(userId, connectionId, query = DEFAULT_QUERY) {
|
|
747
|
+
const record = await findUserRecord(userId, query);
|
|
748
|
+
if (!record) throw new Error("User profile was not found.");
|
|
749
|
+
const connections = await mergeLegacySrklConnections(record.id, record.profiles, query, record.email);
|
|
750
|
+
if (!connections.some((connection) => connection.id === connectionId)) {
|
|
751
|
+
throw new Error("Storage connection was not found for this user.");
|
|
752
|
+
}
|
|
753
|
+
const isReferenced = (profiles) => Object.values(profiles).some(
|
|
754
|
+
(profile) => profile && typeof profile === "object" && Array.isArray(profile.workspaces) && profile.workspaces.some((workspace) => workspace.storageConnectionId === connectionId)
|
|
755
|
+
);
|
|
756
|
+
let referenced = isReferenced(record.profiles);
|
|
757
|
+
if (!referenced) {
|
|
758
|
+
try {
|
|
759
|
+
const legacy = await query(
|
|
760
|
+
'SELECT app_profiles FROM "srkl_application_profiles" WHERE id = $1 OR email = $2 LIMIT 1',
|
|
761
|
+
[record.id, record.email || record.id]
|
|
762
|
+
);
|
|
763
|
+
if (legacy.rows[0]) referenced = isReferenced(parseProfiles(legacy.rows[0].app_profiles));
|
|
764
|
+
} catch (error) {
|
|
765
|
+
if (!isMissingOptionalProfileTable(error)) throw error;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
if (referenced) {
|
|
769
|
+
throw new Error("This storage connection is associated with a workspace. Change the workspace storage before deleting the connection.");
|
|
770
|
+
}
|
|
771
|
+
let updated = connections.filter((connection) => connection.id !== connectionId);
|
|
772
|
+
if (!updated.some((connection) => connection.role === "primary") && updated.length > 0) {
|
|
773
|
+
updated = updated.map((connection, index) => ({
|
|
774
|
+
...connection,
|
|
775
|
+
role: index === 0 ? "primary" : "redundant_clone"
|
|
776
|
+
}));
|
|
777
|
+
}
|
|
778
|
+
await persistStorageConnectionCollection(userId, updated, query);
|
|
779
|
+
return updated.map(toPublicStorageConnection).filter((item) => Boolean(item));
|
|
780
|
+
}
|
|
781
|
+
async function listUserStorageConnections(userId, query = DEFAULT_QUERY) {
|
|
782
|
+
const connections = await listUserStorageConnectionsWithSecrets(userId, query);
|
|
783
|
+
return connections.map(toPublicStorageConnection).filter((connection) => Boolean(connection));
|
|
784
|
+
}
|
|
785
|
+
async function resolveUserStorageConnectionSecret(userId, connectionId, query = DEFAULT_QUERY, provider) {
|
|
786
|
+
const connections = await listUserStorageConnectionsWithSecrets(userId, query);
|
|
787
|
+
const eligible = provider ? connections.filter((item) => item.provider === provider) : connections;
|
|
788
|
+
if (connectionId) return eligible.find((item) => item.id === connectionId) || null;
|
|
789
|
+
return eligible.find((item) => item.role === "primary" && item.enabled !== false) || eligible.find((item) => item.enabled !== false) || null;
|
|
790
|
+
}
|
|
791
|
+
function normalizeWorkspaceAssociationPrefix(value) {
|
|
792
|
+
if (typeof value !== "string" || !value.trim()) return null;
|
|
793
|
+
const normalized = value.trim().replaceAll("\\", "/").replace(/^\.\//, "");
|
|
794
|
+
const segments = normalized.split("/");
|
|
795
|
+
if (segments.some((segment) => !segment || segment === "." || segment === "..")) return null;
|
|
796
|
+
return segments.join("/");
|
|
797
|
+
}
|
|
798
|
+
async function resolveUserWorkspaceStorageAssociation(userId, connectionId, folderPrefix, query = DEFAULT_QUERY) {
|
|
799
|
+
if (!userId?.trim() || !connectionId?.trim()) return null;
|
|
800
|
+
const requestedPrefix = normalizeWorkspaceAssociationPrefix(folderPrefix);
|
|
801
|
+
if (!requestedPrefix) return null;
|
|
802
|
+
const record = await findUserRecord(userId, query);
|
|
803
|
+
if (!record) return null;
|
|
804
|
+
const workspaces = Object.values(record.profiles).flatMap(
|
|
805
|
+
(profile) => profile && typeof profile === "object" && Array.isArray(profile.workspaces) ? profile.workspaces : []
|
|
806
|
+
);
|
|
807
|
+
const matches = workspaces.filter((workspace) => {
|
|
808
|
+
if (!workspace || typeof workspace !== "object" || !String(workspace.id || "").trim()) return false;
|
|
809
|
+
if (String(workspace.storageConnectionId || "").trim() !== connectionId) return false;
|
|
810
|
+
const provider = String(workspace.storageProvider || "").toLowerCase();
|
|
811
|
+
if (provider && !["backblaze_b2", "google_drive"].includes(provider)) return false;
|
|
812
|
+
const storedPrefix = normalizeWorkspaceAssociationPrefix(
|
|
813
|
+
workspace.localFolderKey || workspace.localFolderName || workspace.workspacePath || workspace.id
|
|
814
|
+
);
|
|
815
|
+
return storedPrefix === requestedPrefix;
|
|
816
|
+
});
|
|
817
|
+
if (matches.length !== 1) return null;
|
|
818
|
+
return { ...matches[0], __ownerUserId: record.id };
|
|
819
|
+
}
|
|
820
|
+
async function persistStorageConnection(userId, connection, query) {
|
|
821
|
+
const existing = await listUserStorageConnectionsWithSecrets(userId, query);
|
|
822
|
+
const next = existing.filter((item) => item.id !== connection.id);
|
|
823
|
+
next.push(connection);
|
|
824
|
+
await persistStorageConnectionCollection(userId, next, query);
|
|
825
|
+
}
|
|
826
|
+
async function testBackblazeCredentials(keyId, applicationKey) {
|
|
827
|
+
const normalizedKeyId = String(keyId || "").trim();
|
|
828
|
+
const normalizedApplicationKey = String(applicationKey || "").trim();
|
|
829
|
+
if (!normalizedKeyId || !normalizedApplicationKey) {
|
|
830
|
+
return { success: false, buckets: [], error: "Backblaze B2 Key ID and Application Key are required." };
|
|
831
|
+
}
|
|
832
|
+
try {
|
|
833
|
+
const auth = await authorizeB2(normalizedKeyId, normalizedApplicationKey);
|
|
834
|
+
const buckets = await b2ListBuckets(normalizedKeyId, normalizedApplicationKey);
|
|
835
|
+
return {
|
|
836
|
+
success: true,
|
|
837
|
+
accountId: auth.accountId,
|
|
838
|
+
buckets: buckets.map((bucket) => ({
|
|
839
|
+
id: String(bucket.bucketId || ""),
|
|
840
|
+
name: String(bucket.bucketName || ""),
|
|
841
|
+
type: typeof bucket.bucketType === "string" ? bucket.bucketType : void 0
|
|
842
|
+
})).filter((bucket) => bucket.name)
|
|
843
|
+
};
|
|
844
|
+
} catch (error) {
|
|
845
|
+
return {
|
|
846
|
+
success: false,
|
|
847
|
+
buckets: [],
|
|
848
|
+
error: error instanceof Error ? error.message : "Backblaze B2 credential validation failed."
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
async function createBackblazeStorageConnection(input, query = DEFAULT_QUERY) {
|
|
853
|
+
const userId = String(input.userId || "").trim();
|
|
854
|
+
const keyId = String(input.keyId || "").trim();
|
|
855
|
+
const applicationKey = String(input.applicationKey || "").trim();
|
|
856
|
+
const bucketName = String(input.bucketName || "").trim();
|
|
857
|
+
if (!userId || !keyId || !applicationKey || !bucketName) {
|
|
858
|
+
throw new Error("A user, B2 Key ID, Application Key, and bucket are required.");
|
|
859
|
+
}
|
|
860
|
+
const test = await testBackblazeCredentials(keyId, applicationKey);
|
|
861
|
+
if (!test.success) throw new Error(test.error || "Backblaze B2 credential validation failed.");
|
|
862
|
+
const selectedBucket = test.buckets.find((bucket) => bucket.name === bucketName);
|
|
863
|
+
if (!selectedBucket) throw new Error("The selected Backblaze bucket is not available to these credentials.");
|
|
864
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
865
|
+
const connection = {
|
|
866
|
+
id: `conn_b2_${crypto.randomUUID()}`,
|
|
867
|
+
provider: "backblaze_b2",
|
|
868
|
+
label: String(input.label || `Backblaze B2 \u2014 ${bucketName}`).trim(),
|
|
869
|
+
role: "redundant_clone",
|
|
870
|
+
enabled: true,
|
|
871
|
+
createdAt: now,
|
|
872
|
+
updatedAt: now,
|
|
873
|
+
testedAt: now,
|
|
874
|
+
testStatus: "ok",
|
|
875
|
+
b2KeyId: keyId,
|
|
876
|
+
b2ApplicationKey: applicationKey,
|
|
877
|
+
b2BucketName: bucketName,
|
|
878
|
+
bucketName,
|
|
879
|
+
b2Region: String(input.region || "us-west-004").trim(),
|
|
880
|
+
b2Endpoint: String(input.endpoint || "s3.us-west-004.backblazeb2.com").trim(),
|
|
881
|
+
providerAccountId: test.accountId
|
|
882
|
+
};
|
|
883
|
+
const record = await findUserRecord(userId, query);
|
|
884
|
+
if (!record) throw new Error("A canonical user profile was not found for this storage connection.");
|
|
885
|
+
const currentConnections = await listUserStorageConnectionsWithSecrets(record.id, query);
|
|
886
|
+
const duplicate = currentConnections.find(
|
|
887
|
+
(item) => item.provider === "backblaze_b2" && String(item.b2KeyId || item.keyId || item.accessKeyId || "") === keyId && String(item.b2BucketName || item.bucketName || "") === bucketName
|
|
888
|
+
);
|
|
889
|
+
if (duplicate) return toPublicStorageConnection(duplicate);
|
|
890
|
+
connection.role = currentConnections.length === 0 ? "primary" : "redundant_clone";
|
|
891
|
+
await persistStorageConnection(record.id, connection, query);
|
|
892
|
+
return toPublicStorageConnection(connection);
|
|
893
|
+
}
|
|
894
|
+
async function listBackblazeBucketsForConnection(userId, connectionId, query = DEFAULT_QUERY) {
|
|
895
|
+
const connection = await resolveUserStorageConnectionSecret(userId, connectionId, query);
|
|
896
|
+
if (!connection || connection.provider !== "backblaze_b2") {
|
|
897
|
+
throw new Error("Backblaze B2 storage connection was not found for this user.");
|
|
898
|
+
}
|
|
899
|
+
const keyId = String(connection.b2KeyId || connection.keyId || connection.accessKeyId || "").trim();
|
|
900
|
+
const applicationKey = String(connection.b2ApplicationKey || connection.applicationKey || connection.appKey || connection.secretAccessKey || "").trim();
|
|
901
|
+
if (!keyId || !applicationKey) throw new Error("The saved Backblaze connection is missing server-side credentials.");
|
|
902
|
+
const result = await testBackblazeCredentials(keyId, applicationKey);
|
|
903
|
+
if (!result.success) throw new Error(result.error || "Backblaze B2 bucket discovery failed.");
|
|
904
|
+
return result.buckets;
|
|
905
|
+
}
|
|
906
|
+
async function getSystemGoogleOAuthConfiguration(query = DEFAULT_QUERY) {
|
|
907
|
+
return getGoogleDriveOAuthConfiguration(query);
|
|
908
|
+
}
|
|
909
|
+
async function getStorageProviderCapabilities(query = DEFAULT_QUERY) {
|
|
910
|
+
let googleOAuthConfigured = false;
|
|
911
|
+
let googleOAuthError = 'Google Drive OAuth system configuration is missing from public."ultrst-credentials" (id="system").';
|
|
912
|
+
try {
|
|
913
|
+
await getSystemGoogleOAuthConfiguration(query);
|
|
914
|
+
googleOAuthConfigured = true;
|
|
915
|
+
} catch (error) {
|
|
916
|
+
googleOAuthError = error instanceof Error ? error.message : googleOAuthError;
|
|
917
|
+
}
|
|
918
|
+
return [
|
|
919
|
+
{
|
|
920
|
+
id: "backblaze_b2",
|
|
921
|
+
displayName: "Backblaze B2",
|
|
922
|
+
enabled: true,
|
|
923
|
+
canSelectExistingConnection: true,
|
|
924
|
+
canCreateConnection: true,
|
|
925
|
+
requiredConfigurationFields: ["keyId", "applicationKey", "bucketName"],
|
|
926
|
+
authorizationMode: "application_key",
|
|
927
|
+
discoveryCapabilities: { accounts: true, buckets: true, folders: false }
|
|
928
|
+
},
|
|
929
|
+
{
|
|
930
|
+
id: "google_drive",
|
|
931
|
+
displayName: "Google Drive",
|
|
932
|
+
enabled: googleOAuthConfigured,
|
|
933
|
+
...!googleOAuthConfigured ? { availabilityReason: googleOAuthError } : {},
|
|
934
|
+
canSelectExistingConnection: true,
|
|
935
|
+
canCreateConnection: googleOAuthConfigured,
|
|
936
|
+
requiredConfigurationFields: [],
|
|
937
|
+
authorizationMode: "oauth2",
|
|
938
|
+
discoveryCapabilities: { accounts: true, buckets: false, folders: true }
|
|
939
|
+
}
|
|
940
|
+
];
|
|
941
|
+
}
|
|
942
|
+
async function persistGoogleDriveTokens(userId, connectionId, tokens, query = DEFAULT_QUERY) {
|
|
943
|
+
if (!userId || !connectionId || !tokens.accessToken) {
|
|
944
|
+
throw new Error("Google Drive credential persistence inputs are incomplete.");
|
|
945
|
+
}
|
|
946
|
+
const connection = await resolveUserStorageConnectionSecret(userId, connectionId, query, "google_drive");
|
|
947
|
+
if (!connection) throw new Error("Google Drive connection is not owned by the authenticated user.");
|
|
948
|
+
const updated = {
|
|
949
|
+
...connection,
|
|
950
|
+
googleAccessToken: tokens.accessToken,
|
|
951
|
+
googleAccessTokenExpiresAt: tokens.expiresAt,
|
|
952
|
+
googleRefreshToken: tokens.refreshToken || connection.googleRefreshToken,
|
|
953
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
954
|
+
};
|
|
955
|
+
await persistStorageConnection(userId, updated, query);
|
|
956
|
+
return toPublicStorageConnection(updated);
|
|
957
|
+
}
|
|
958
|
+
async function createGoogleDriveWorkspaceClient(userId, connectionId, query = DEFAULT_QUERY, rootFolderId) {
|
|
959
|
+
const connection = await resolveUserStorageConnectionSecret(userId, connectionId, query, "google_drive");
|
|
960
|
+
if (!connection || connection.enabled === false) {
|
|
961
|
+
throw new Error("Google Drive connection was not found or is disabled for this user.");
|
|
962
|
+
}
|
|
963
|
+
const system = await getSystemGoogleOAuthConfiguration(query);
|
|
964
|
+
const tokens = {
|
|
965
|
+
accessToken: String(connection.googleAccessToken || ""),
|
|
966
|
+
...connection.googleRefreshToken ? { refreshToken: String(connection.googleRefreshToken) } : {},
|
|
967
|
+
...connection.googleAccessTokenExpiresAt ? { expiresAt: Number(connection.googleAccessTokenExpiresAt) } : {}
|
|
968
|
+
};
|
|
969
|
+
if (!tokens.accessToken && !tokens.refreshToken) {
|
|
970
|
+
throw new Error("Google Drive connection has no saved authorization tokens. Reconnect the Google account.");
|
|
971
|
+
}
|
|
972
|
+
const connectionRootFolderId = String(connection.googleRootFolderId || "root");
|
|
973
|
+
const selectedRootFolderId = String(rootFolderId || connectionRootFolderId);
|
|
974
|
+
const createService = (selectedRoot) => new GoogleDriveWorkspaceService({
|
|
975
|
+
clientId: system.clientId,
|
|
976
|
+
clientSecret: system.clientSecret,
|
|
977
|
+
redirectUri: system.redirectUri,
|
|
978
|
+
tokens,
|
|
979
|
+
rootFolderId: selectedRoot,
|
|
980
|
+
googleAccountId: String(connection.googleAccountId || ""),
|
|
981
|
+
persistTokens: async (nextTokens) => {
|
|
982
|
+
await persistGoogleDriveTokens(userId, connectionId, nextTokens, query);
|
|
983
|
+
}
|
|
984
|
+
});
|
|
985
|
+
if (selectedRootFolderId !== connectionRootFolderId) {
|
|
986
|
+
const rootVerifier = createService(connectionRootFolderId);
|
|
987
|
+
await rootVerifier.assertFolderWithinRoot(selectedRootFolderId);
|
|
988
|
+
}
|
|
989
|
+
return createService(selectedRootFolderId);
|
|
990
|
+
}
|
|
991
|
+
async function completeGoogleDriveAuthorization(userId, code, query = DEFAULT_QUERY) {
|
|
992
|
+
if (!userId?.trim()) throw new Error("A verified Luth user is required to connect Google Drive.");
|
|
993
|
+
const system = await getSystemGoogleOAuthConfiguration(query);
|
|
994
|
+
const tokens = await GoogleDriveWorkspaceService.exchangeAuthorizationCode(
|
|
995
|
+
{
|
|
996
|
+
clientId: system.clientId,
|
|
997
|
+
clientSecret: system.clientSecret,
|
|
998
|
+
redirectUri: system.redirectUri
|
|
999
|
+
},
|
|
1000
|
+
code
|
|
1001
|
+
);
|
|
1002
|
+
const provisional = new GoogleDriveWorkspaceService({
|
|
1003
|
+
clientId: system.clientId,
|
|
1004
|
+
clientSecret: system.clientSecret,
|
|
1005
|
+
redirectUri: system.redirectUri,
|
|
1006
|
+
tokens
|
|
1007
|
+
});
|
|
1008
|
+
const identity = await provisional.getAccountIdentity();
|
|
1009
|
+
const record = await findUserRecord(userId, query);
|
|
1010
|
+
if (!record) throw new Error("A canonical user profile was not found for this Google Drive connection.");
|
|
1011
|
+
const connections = await mergeLegacySrklConnections(record.id, record.profiles, query, record.email);
|
|
1012
|
+
const existing = connections.find(
|
|
1013
|
+
(item) => item.provider === "google_drive" && (item.googleAccountId === identity.accountId || identity.email && item.googleEmail === identity.email)
|
|
1014
|
+
);
|
|
1015
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1016
|
+
const connection = {
|
|
1017
|
+
...existing || {},
|
|
1018
|
+
id: existing?.id || `conn_google_drive_${crypto.randomUUID()}`,
|
|
1019
|
+
provider: "google_drive",
|
|
1020
|
+
label: `Google Drive \u2014 ${identity.email || "Google account"}`,
|
|
1021
|
+
role: existing?.role || (connections.length === 0 ? "primary" : "redundant_clone"),
|
|
1022
|
+
enabled: true,
|
|
1023
|
+
createdAt: existing?.createdAt || now,
|
|
1024
|
+
updatedAt: now,
|
|
1025
|
+
testedAt: now,
|
|
1026
|
+
testStatus: "ok",
|
|
1027
|
+
googleEmail: identity.email || existing?.googleEmail || "",
|
|
1028
|
+
googleAccountId: identity.accountId,
|
|
1029
|
+
googleAccessToken: tokens.accessToken,
|
|
1030
|
+
googleAccessTokenExpiresAt: tokens.expiresAt,
|
|
1031
|
+
googleRefreshToken: tokens.refreshToken || existing?.googleRefreshToken,
|
|
1032
|
+
googleRootFolderId: existing?.googleRootFolderId || "root",
|
|
1033
|
+
googleRootFolderName: existing?.googleRootFolderName || "My Drive"
|
|
1034
|
+
};
|
|
1035
|
+
await persistStorageConnection(record.id, connection, query);
|
|
1036
|
+
return toPublicStorageConnection(connection);
|
|
1037
|
+
}
|
|
1038
|
+
async function listGoogleDriveFoldersForConnection(userId, connectionId, parentFolderId, query = DEFAULT_QUERY) {
|
|
1039
|
+
const drive = await createGoogleDriveWorkspaceClient(userId, connectionId, query);
|
|
1040
|
+
await drive.getAccountIdentity();
|
|
1041
|
+
return drive.listFolders(parentFolderId);
|
|
1042
|
+
}
|
|
1043
|
+
async function selectGoogleDriveRootFolder(userId, connectionId, folderId, query = DEFAULT_QUERY) {
|
|
1044
|
+
const drive = await createGoogleDriveWorkspaceClient(userId, connectionId, query);
|
|
1045
|
+
await drive.getAccountIdentity();
|
|
1046
|
+
const folder = await drive.selectRootFolder(folderId);
|
|
1047
|
+
const connection = await resolveUserStorageConnectionSecret(userId, connectionId, query, "google_drive");
|
|
1048
|
+
if (!connection) throw new Error("Google Drive connection was not found for this user.");
|
|
1049
|
+
await persistStorageConnection(userId, {
|
|
1050
|
+
...connection,
|
|
1051
|
+
googleRootFolderId: folder.id,
|
|
1052
|
+
googleRootFolderName: folder.name,
|
|
1053
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1054
|
+
}, query);
|
|
1055
|
+
return folder;
|
|
1056
|
+
}
|
|
1057
|
+
async function testGoogleDriveConnectionForUser(userId, connectionId, query = DEFAULT_QUERY) {
|
|
1058
|
+
const drive = await createGoogleDriveWorkspaceClient(userId, connectionId, query);
|
|
1059
|
+
const started = Date.now();
|
|
1060
|
+
try {
|
|
1061
|
+
const identity = await drive.getAccountIdentity();
|
|
1062
|
+
const result = await drive.testConnection();
|
|
1063
|
+
return {
|
|
1064
|
+
success: Boolean(result.ok),
|
|
1065
|
+
latencyMs: Number(result.latencyMs || Date.now() - started),
|
|
1066
|
+
...identity.email ? { email: identity.email } : {},
|
|
1067
|
+
...result.error ? { error: result.error } : {}
|
|
1068
|
+
};
|
|
1069
|
+
} catch (error) {
|
|
1070
|
+
return {
|
|
1071
|
+
success: false,
|
|
1072
|
+
latencyMs: Date.now() - started,
|
|
1073
|
+
error: error instanceof Error ? error.message : "Google Drive connection failed."
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
async function writeGoogleDriveFileForConnection(userId, connectionId, path, data, contentType = "application/octet-stream", query = DEFAULT_QUERY) {
|
|
1078
|
+
const drive = await createGoogleDriveWorkspaceClient(userId, connectionId, query);
|
|
1079
|
+
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
1080
|
+
await drive.write(path, bytes, contentType);
|
|
1081
|
+
}
|
|
1082
|
+
async function readGoogleDriveFileForConnection(userId, connectionId, path, query = DEFAULT_QUERY) {
|
|
1083
|
+
const drive = await createGoogleDriveWorkspaceClient(userId, connectionId, query);
|
|
1084
|
+
try {
|
|
1085
|
+
return await drive.read(path);
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
if (error instanceof Error && /not found|HTTP 404/i.test(error.message)) return null;
|
|
1088
|
+
throw error;
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
async function deleteGoogleDriveFileForConnection(userId, connectionId, path, query = DEFAULT_QUERY) {
|
|
1092
|
+
const drive = await createGoogleDriveWorkspaceClient(userId, connectionId, query);
|
|
1093
|
+
await drive.delete(path);
|
|
1094
|
+
}
|
|
1095
|
+
async function listGoogleDriveFilesForConnection(userId, connectionId, path = "", query = DEFAULT_QUERY) {
|
|
1096
|
+
const drive = await createGoogleDriveWorkspaceClient(userId, connectionId, query);
|
|
1097
|
+
return drive.list(path);
|
|
1098
|
+
}
|
|
1099
|
+
async function getGoogleDriveAccountIdentityForUser(userId, connectionId, query = DEFAULT_QUERY) {
|
|
1100
|
+
const drive = await createGoogleDriveWorkspaceClient(userId, connectionId, query);
|
|
1101
|
+
return drive.getAccountIdentity();
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
export {
|
|
1105
|
+
configureUnifiedDatabaseEnvironmentResolver,
|
|
1106
|
+
cleanDbUrl,
|
|
1107
|
+
getUnifiedDbUrl,
|
|
1108
|
+
queryUnifiedDb,
|
|
1109
|
+
toPublicStorageConnection,
|
|
1110
|
+
listUserStorageConnectionsWithSecrets,
|
|
1111
|
+
setPrimaryUserStorageConnection,
|
|
1112
|
+
deleteUserStorageConnection,
|
|
1113
|
+
listUserStorageConnections,
|
|
1114
|
+
resolveUserStorageConnectionSecret,
|
|
1115
|
+
resolveUserWorkspaceStorageAssociation,
|
|
1116
|
+
testBackblazeCredentials,
|
|
1117
|
+
createBackblazeStorageConnection,
|
|
1118
|
+
listBackblazeBucketsForConnection,
|
|
1119
|
+
getSystemGoogleOAuthConfiguration,
|
|
1120
|
+
getStorageProviderCapabilities,
|
|
1121
|
+
persistGoogleDriveTokens,
|
|
1122
|
+
createGoogleDriveWorkspaceClient,
|
|
1123
|
+
completeGoogleDriveAuthorization,
|
|
1124
|
+
listGoogleDriveFoldersForConnection,
|
|
1125
|
+
selectGoogleDriveRootFolder,
|
|
1126
|
+
testGoogleDriveConnectionForUser,
|
|
1127
|
+
writeGoogleDriveFileForConnection,
|
|
1128
|
+
readGoogleDriveFileForConnection,
|
|
1129
|
+
deleteGoogleDriveFileForConnection,
|
|
1130
|
+
listGoogleDriveFilesForConnection,
|
|
1131
|
+
getGoogleDriveAccountIdentityForUser
|
|
1132
|
+
};
|