@ultrst-armada/kloks 2.2.9 → 3.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.
Files changed (51) hide show
  1. package/.krusbl-release-attestation.json +3 -3
  2. package/package.json +1 -1
  3. package/packages/backend/dist/auth/LuthOAuthUserInfo.d.ts +10 -0
  4. package/packages/backend/dist/auth/OidcBff.d.ts +3 -2
  5. package/packages/backend/dist/auth/OidcBffEnv.d.ts +6 -7
  6. package/packages/backend/dist/auth/index.d.ts +0 -3
  7. package/packages/backend/dist/auth/index.js +2 -26
  8. package/packages/backend/dist/{chunk-AKVBFHHD.js → chunk-2SNWR4FI.js} +88 -57
  9. package/packages/backend/dist/{chunk-UI7AYFAU.js → chunk-363J52AF.js} +0 -48
  10. package/packages/backend/dist/{chunk-GCVR257U.js → chunk-3SDRLTD6.js} +1 -1
  11. package/packages/backend/dist/chunk-7HD7OEUY.js +177 -0
  12. package/packages/backend/dist/chunk-B5DCG4UC.js +602 -0
  13. package/packages/backend/dist/{chunk-7XTURV44.js → chunk-F7BO3GLA.js} +2 -2
  14. package/packages/backend/dist/{chunk-RHW75K46.js → chunk-IAW6N73D.js} +49 -1
  15. package/packages/backend/dist/{chunk-IRKJ6HKP.js → chunk-IXEKOWY4.js} +1 -1
  16. package/packages/backend/dist/{chunk-4X4QGVAO.js → chunk-NRW4TECO.js} +1 -1
  17. package/packages/backend/dist/{chunk-3ZL2DX73.js → chunk-PAU25K7F.js} +5 -172
  18. package/packages/backend/dist/{chunk-NUBA6A5T.js → chunk-VN2NR3KT.js} +1 -1
  19. package/packages/backend/dist/{chunk-R4B3KPHY.js → chunk-YFISFDBW.js} +36 -15
  20. package/packages/backend/dist/control-plane/ControlPlaneManager.d.ts +6 -3
  21. package/packages/backend/dist/index.d.ts +0 -2
  22. package/packages/backend/dist/index.js +7 -25
  23. package/packages/backend/dist/krnl-services.js +6 -6
  24. package/packages/backend/dist/node.d.ts +0 -1
  25. package/packages/backend/dist/node.js +20 -95
  26. package/packages/backend/dist/provider-services/index.js +7 -7
  27. package/packages/backend/dist/provider-services/node.d.ts +2 -0
  28. package/packages/backend/dist/provider-services/node.js +15 -4
  29. package/packages/backend/dist/provider-services/saved-account-crypto.d.ts +19 -0
  30. package/packages/backend/dist/provider-services/saved-account-probe.d.ts +26 -0
  31. package/packages/backend/dist/provider-services/saved-account-store.d.ts +29 -0
  32. package/packages/backend/dist/services/node.js +5 -4
  33. package/packages/backend/dist/srkl/index.js +3 -2
  34. package/packages/backend/dist/workspace/node.js +5 -4
  35. package/packages/backend/dist/{workspaceFileCore-XPT6WTFY.js → workspaceFileCore-2KCVSECY.js} +3 -2
  36. package/packages/client/dist/auth.d.ts +9 -21
  37. package/packages/client/dist/auth.js +1 -23
  38. package/packages/client/dist/chunk-QGZHKLOK.js +75 -0
  39. package/packages/client/dist/index.d.ts +2 -3
  40. package/packages/client/dist/index.js +1 -23
  41. package/packages/backend/dist/auth/BaseAccountProvider.d.ts +0 -7
  42. package/packages/backend/dist/auth/CanonicalAuthClient.d.ts +0 -6
  43. package/packages/backend/dist/auth/UnifiedAuthCore.d.ts +0 -23
  44. package/packages/backend/dist/auth/UniversalLuthInitialization.d.ts +0 -55
  45. package/packages/backend/dist/chunk-2COYZMUJ.js +0 -78
  46. package/packages/backend/dist/chunk-MDTLU7H4.js +0 -58
  47. package/packages/backend/dist/chunk-U5VPYALB.js +0 -261
  48. package/packages/backend/dist/luth/LuthDiscoveryService.d.ts +0 -15
  49. package/packages/backend/dist/luth/index.d.ts +0 -1
  50. package/packages/client/dist/chunk-4HR374IB.js +0 -148
  51. /package/packages/backend/dist/{auth/UnifiedAuthCore.test.d.ts → provider-services/saved-account-store.test.d.ts} +0 -0
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "packageName": "@ultrst-armada/kloks",
4
- "version": "2.2.9",
5
- "sourceCommit": "8fd058dee8dda59fe3cee4cf60b1d68803f52867",
4
+ "version": "3.0.1",
5
+ "sourceCommit": "be1e39a508ab28f52fea669af747e4b0d811416c",
6
6
  "releaseWorkflow": "npm Release",
7
- "workflowRunId": "44814035725"
7
+ "workflowRunId": "44887403503"
8
8
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultrst-armada/kloks",
3
- "version": "2.2.9",
3
+ "version": "3.0.1",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -0,0 +1,10 @@
1
+ export interface OfficialLuthUser {
2
+ id: string;
3
+ email: string;
4
+ name: string;
5
+ }
6
+ /**
7
+ * Resource-server OAuth authentication: official live UserInfo only.
8
+ * No password grant, synthetic local session, x-api-key or Origin authority.
9
+ */
10
+ export declare function verifyLuthOAuthAccessToken(token: string, transport?: typeof fetch): Promise<OfficialLuthUser | null>;
@@ -14,9 +14,10 @@ export interface OAuthBffDatabase {
14
14
  export interface OAuthBffConfig {
15
15
  /** Luth's exact Better Auth issuer, including /api/auth. */
16
16
  issuer: string;
17
- /** Exact, administratively verified Luth OAuth client and callback binding. */
17
+ /** Luth-issued OAuth client registered dynamically, never preapproved by origin. */
18
18
  clientId: string;
19
- clientSecret: string;
19
+ /** Optional: public PKCE clients do not have a secret. */
20
+ clientSecret?: string;
20
21
  appId: string;
21
22
  redirectUri: string;
22
23
  /** Stable server-side secret, never serialized to a browser or log. */
@@ -1,19 +1,18 @@
1
1
  /**
2
- * All runtime configuration for ULTRST deployments is reached using these
3
- * four canonical bindings. Application credentials are kept in the protected
4
- * system database, never passed as Worker/Vercel/local environment variables.
2
+ * App-local OAuth client registration cache. This is NOT a trusted origins
3
+ * table: any app independently creates its OAuth client through Luth's
4
+ * anonymous RFC 7591 Dynamic Client Registration endpoint.
5
5
  */
6
6
  export interface CanonicalApplicationAuthEnvironment {
7
7
  APP_URL?: unknown;
8
- SYSTEM_DATABASE_URL?: unknown;
8
+ SYSTEM_DATABASE_URL_1?: unknown;
9
9
  SYSTEM_DATABASE_URL_2?: unknown;
10
10
  SYSTEM_DATABASE_URL_3?: unknown;
11
11
  [key: string]: unknown;
12
12
  }
13
13
  /**
14
- * Resolve a *fresh* application credential on every request. A revoked Luth
15
- * client or removed origin stops new operations immediately, rather than
16
- * remaining authorized by a stale in-memory credential cache.
14
+ * The app owns its opaque HttpOnly session and registered redirect URI.
15
+ * Luth alone owns OAuth client issuance, login, consent and token validity.
17
16
  */
18
17
  export declare function createCanonicalApplicationOAuthBff(request: Request, env: CanonicalApplicationAuthEnvironment, applicationId: string): {
19
18
  handle: (current: Request) => Promise<Response>;
@@ -1,5 +1,2 @@
1
- export * from './CanonicalAuthClient.js';
2
- export * from './UnifiedAuthCore.js';
3
1
  export * from './OidcBff.js';
4
2
  export * from './OidcBffEnv.js';
5
- export * from './UniversalLuthInitialization.js';
@@ -1,32 +1,8 @@
1
1
  import {
2
2
  createCanonicalApplicationOAuthBff,
3
3
  createOAuthBff
4
- } from "../chunk-AKVBFHHD.js";
5
- import {
6
- LuthAuthClient,
7
- LuthAuthClient2,
8
- LuthAuthError,
9
- createLuthAuthClient,
10
- createLuthAuthClient2,
11
- createUniversalLuthRuntimeService,
12
- resolveClientEnvironment,
13
- resolveClientOrigin
14
- } from "../chunk-MDTLU7H4.js";
15
- import {
16
- loginSystemUser,
17
- resolveUserFromToken
18
- } from "../chunk-2COYZMUJ.js";
4
+ } from "../chunk-2SNWR4FI.js";
19
5
  export {
20
- LuthAuthClient2 as CanonicalAuthClient,
21
- LuthAuthClient,
22
- LuthAuthError,
23
6
  createCanonicalApplicationOAuthBff,
24
- createLuthAuthClient2 as createCanonicalAuthClient,
25
- createLuthAuthClient,
26
- createOAuthBff,
27
- createUniversalLuthRuntimeService,
28
- loginSystemUser,
29
- resolveClientEnvironment,
30
- resolveClientOrigin,
31
- resolveUserFromToken
7
+ createOAuthBff
32
8
  };
@@ -54,7 +54,7 @@ function sameValue(left, right) {
54
54
  function configOrigin(config) {
55
55
  const url = new URL(config.redirectUri);
56
56
  const issuer = new URL(config.issuer);
57
- if (issuer.protocol !== "https:" || issuer.pathname !== "/api/auth" || issuer.search || issuer.hash || !config.clientId || !config.clientSecret || !config.appId || url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
57
+ if (issuer.protocol !== "https:" || issuer.pathname !== "/api/auth" || issuer.search || issuer.hash || !config.clientId || !config.appId || url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
58
58
  throw new Error("INVALID_VERIFIED_OAUTH_BFF_CONFIGURATION");
59
59
  }
60
60
  return url;
@@ -84,7 +84,9 @@ function reply(body, status) {
84
84
  return Response.json(body, { status, headers: { "cache-control": "no-store" } });
85
85
  }
86
86
  function clientCredentials(config) {
87
- return new URLSearchParams({ client_id: config.clientId, client_secret: config.clientSecret });
87
+ const fields = new URLSearchParams({ client_id: config.clientId });
88
+ if (config.clientSecret) fields.set("client_secret", config.clientSecret);
89
+ return fields;
88
90
  }
89
91
  async function exchange(config, body) {
90
92
  const response = await (config.fetcher || fetch)(config.issuer + "/oauth2/token", {
@@ -313,74 +315,103 @@ function createOAuthBff(config) {
313
315
  // src/auth/OidcBffEnv.ts
314
316
  import { neon } from "@neondatabase/serverless";
315
317
  import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
316
- function createCanonicalApplicationOAuthBff(request, env, applicationId) {
317
- if (!/^[a-z0-9][a-z0-9_-]{0,119}$/.test(applicationId)) {
318
- throw new Error("INVALID_APP_ID");
318
+ function secret() {
319
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
320
+ return Array.from(bytes, (x) => x.toString(16).padStart(2, "0")).join("");
321
+ }
322
+ function redirectOf(request, env) {
323
+ const raw = String(env.APP_URL || "").trim();
324
+ if (!raw) throw new Error("APP_URL_UNAVAILABLE");
325
+ const app = new URL(raw);
326
+ if (app.protocol !== "https:" && !(app.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(app.hostname)) || app.origin !== raw.replace(/\/$/, "") || new URL(request.url).origin !== app.origin) {
327
+ throw new Error("APPLICATION_ORIGIN_MISMATCH");
319
328
  }
320
- const origin = String(env.APP_URL || "").trim();
321
- const candidates = [
322
- env.SYSTEM_DATABASE_URL,
329
+ return app.origin + "/api/auth/oidc/callback";
330
+ }
331
+ function connections(env) {
332
+ const values = [
333
+ env.SYSTEM_DATABASE_URL_1,
323
334
  env.SYSTEM_DATABASE_URL_2,
324
335
  env.SYSTEM_DATABASE_URL_3
325
- ].filter((value) => typeof value === "string" && !!value.trim()).map((value) => value.trim());
326
- if (!origin || !candidates.length) throw new Error("CANONICAL_APP_AUTH_NOT_PROVISIONED");
327
- const verifiedOrigin = new URL(origin);
328
- if (verifiedOrigin.origin !== origin.replace(/\/$/, "") || !["http:", "https:"].includes(verifiedOrigin.protocol) || new URL(request.url).origin !== verifiedOrigin.origin) {
329
- throw new Error("APPLICATION_ORIGIN_MISMATCH");
336
+ ];
337
+ return values.filter((value) => typeof value === "string" && !!value.trim()).map((value) => value.trim());
338
+ }
339
+ async function selfRegister(appId, redirectUri) {
340
+ const issuer = DEFAULT_LUTH_URL.replace(/\/$/, "");
341
+ const response = await fetch(issuer + "/api/auth/oauth2/register", {
342
+ method: "POST",
343
+ credentials: "omit",
344
+ redirect: "error",
345
+ cache: "no-store",
346
+ headers: { "content-type": "application/json", accept: "application/json" },
347
+ body: JSON.stringify({
348
+ client_name: appId,
349
+ redirect_uris: [redirectUri],
350
+ application_type: "web",
351
+ token_endpoint_auth_method: "none",
352
+ response_types: ["code"],
353
+ grant_types: ["authorization_code", "refresh_token"],
354
+ scope: "openid profile email offline_access"
355
+ })
356
+ });
357
+ if (!response.ok) throw new Error("LUTH_PUBLIC_OAUTH_REGISTRATION_DENIED");
358
+ const value = await response.json();
359
+ if (typeof value.client_id !== "string" || !value.client_id || !Array.isArray(value.redirect_uris) || value.redirect_uris.length !== 1 || value.redirect_uris[0] !== redirectUri || value.token_endpoint_auth_method !== "none" || value.client_secret != null) {
360
+ throw new Error("LUTH_PUBLIC_OAUTH_REGISTRATION_INVALID");
330
361
  }
362
+ return value.client_id;
363
+ }
364
+ function createCanonicalApplicationOAuthBff(request, env, applicationId) {
365
+ if (!/^[a-z0-9][a-z0-9_-]{0,119}$/.test(applicationId)) {
366
+ throw new Error("INVALID_APP_ID");
367
+ }
368
+ const redirectUri = redirectOf(request, env);
369
+ const databaseUrls = connections(env);
370
+ if (!databaseUrls.length) throw new Error("SYSTEM_DATABASE_UNAVAILABLE");
331
371
  async function resolve(current) {
332
- if (new URL(current.url).origin !== verifiedOrigin.origin) {
372
+ if (redirectOf(current, env) !== redirectUri) {
333
373
  throw new Error("APPLICATION_ORIGIN_MISMATCH");
334
374
  }
335
- const settingsKey = applicationId + "|" + verifiedOrigin.origin;
336
- const statement = `
337
- SELECT c."clientId" AS client_id,
338
- cred.credentials #> ARRAY['applicationOAuth', $3::text] AS settings
339
- FROM public."ultrst-apps" a
340
- JOIN public.luth_ecosystems e ON e.id = a.ecosystem_id
341
- JOIN public.luth_auth_origins o
342
- ON o.app_id = a.app_id AND o.ecosystem_id = a.ecosystem_id
343
- JOIN public."oauthClient" c
344
- ON c.metadata->>'appId' = a.app_id
345
- AND c.metadata->>'origin' = o.origin
346
- JOIN public."ultrst-credentials" cred ON cred.id = 'system'
347
- WHERE a.app_id = $1 AND a.status = 'active' AND e.status = 'active'
348
- AND o.origin = $2 AND o.enabled = true
349
- AND COALESCE(c.disabled, false) = false
350
- LIMIT 2
351
- `;
352
375
  let lastError;
353
- for (const dbUrl of candidates) {
354
- const sql = neon(dbUrl);
355
- let rows;
376
+ for (const url of databaseUrls) {
377
+ const sql = neon(url);
356
378
  try {
357
- rows = [...await sql(statement, [applicationId, verifiedOrigin.origin, settingsKey])];
379
+ let rows = [...await sql(
380
+ "SELECT client_id,encryption_secret FROM public.kloks_oidc_registrations WHERE app_id=$1 AND redirect_uri=$2 LIMIT 2",
381
+ [applicationId, redirectUri]
382
+ )];
383
+ if (!rows.length) {
384
+ const clientId = await selfRegister(applicationId, redirectUri);
385
+ await sql(
386
+ "INSERT INTO public.kloks_oidc_registrations (app_id,redirect_uri,client_id,encryption_secret) VALUES ($1,$2,$3,$4) ON CONFLICT (app_id,redirect_uri) DO NOTHING",
387
+ [applicationId, redirectUri, clientId, secret()]
388
+ );
389
+ rows = [...await sql(
390
+ "SELECT client_id,encryption_secret FROM public.kloks_oidc_registrations WHERE app_id=$1 AND redirect_uri=$2 LIMIT 2",
391
+ [applicationId, redirectUri]
392
+ )];
393
+ }
394
+ if (rows.length !== 1 || typeof rows[0]?.client_id !== "string" || typeof rows[0]?.encryption_secret !== "string" || rows[0].encryption_secret.length < 32) {
395
+ throw new Error("OAUTH_CLIENT_REGISTRATION_INVALID");
396
+ }
397
+ return createOAuthBff({
398
+ appId: applicationId,
399
+ issuer: DEFAULT_LUTH_URL.replace(/\/$/, "") + "/api/auth",
400
+ clientId: rows[0].client_id,
401
+ redirectUri,
402
+ encryptionSecret: rows[0].encryption_secret,
403
+ database: {
404
+ async query(statement, values) {
405
+ const result = await sql(statement, [...values]);
406
+ return { rows: [...result] };
407
+ }
408
+ }
409
+ });
358
410
  } catch (error) {
359
411
  lastError = error;
360
- continue;
361
- }
362
- if (rows.length !== 1) throw new Error("CANONICAL_APP_AUTH_NOT_PROVISIONED");
363
- const raw = rows[0].settings;
364
- const credential = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
365
- if (typeof credential.clientId !== "string" || typeof credential.clientSecret !== "string" || typeof credential.bffSecret !== "string" || credential.bffSecret.length < 32 || credential.clientId !== rows[0].client_id || !credential.clientSecret) {
366
- throw new Error("CANONICAL_APP_AUTH_NOT_PROVISIONED");
367
412
  }
368
- return createOAuthBff({
369
- appId: applicationId,
370
- issuer: DEFAULT_LUTH_URL.replace(/\/$/, "") + "/api/auth",
371
- clientId: credential.clientId,
372
- clientSecret: credential.clientSecret,
373
- redirectUri: verifiedOrigin.origin + "/api/auth/oidc/callback",
374
- encryptionSecret: credential.bffSecret,
375
- database: {
376
- async query(query, values) {
377
- const result = await sql(query, [...values]);
378
- return { rows: [...result] };
379
- }
380
- }
381
- });
382
413
  }
383
- throw new Error(lastError ? "SYSTEM_DATABASE_UNAVAILABLE" : "CANONICAL_APP_AUTH_NOT_PROVISIONED");
414
+ throw new Error(lastError ? "OAUTH_CLIENT_REGISTRATION_UNAVAILABLE" : "SYSTEM_DATABASE_UNAVAILABLE");
384
415
  }
385
416
  return {
386
417
  handle: async (current) => (await resolve(current)).handle(current),
@@ -40,50 +40,6 @@ function validQuota(metric) {
40
40
  return metric.used !== null && metric.limit !== null && Number.isFinite(metric.used) && Number.isFinite(metric.limit) && metric.used >= 0 && metric.limit > 0 && typeof metric.resetAt === "string" && Number.isFinite(Date.parse(metric.resetAt));
41
41
  }
42
42
 
43
- // src/provider-services/compute-operations.ts
44
- function connectionFor(input, expected) {
45
- if (input.providerId !== expected) throw new Error("Credential/provider mismatch");
46
- return input;
47
- }
48
- function requiredProject(input, name, pattern) {
49
- if (!pattern.test(input)) throw new Error("Invalid " + name);
50
- return input;
51
- }
52
- async function getRailwayAccount(connection, transport = fetch) {
53
- const client = createProviderClient(connectionFor(connection, "railway"), transport);
54
- const { data } = await client.request({
55
- path: "/graphql/v2",
56
- method: "POST",
57
- body: { query: "query FrnesIdentity { me { name email } }" }
58
- });
59
- if (data.errors?.length || !data.data?.me || typeof data.data.me !== "object" || !(typeof data.data.me.email === "string" && data.data.me.email.trim() || typeof data.data.me.name === "string" && data.data.me.name.trim()))
60
- throw new Error("Railway account token could not be authorized");
61
- return data.data.me;
62
- }
63
- async function listFlyApps(connection, transport = fetch) {
64
- const client = createProviderClient(connectionFor(connection, "fly"), transport);
65
- const { data } = await client.request({ path: "/v1/apps" });
66
- if (!Array.isArray(data?.apps) || data.apps.some((item) => typeof item.name !== "string" || !item.name))
67
- throw new Error("Invalid Fly Machines app listing");
68
- return data.apps;
69
- }
70
- async function listRenderServices(connection, transport = fetch) {
71
- const client = createProviderClient(connectionFor(connection, "render"), transport);
72
- const { data } = await client.request({ path: "/v1/services", query: { limit: 20 } });
73
- if (!Array.isArray(data) || data.some((item) => typeof item.service?.id !== "string" || !item.service.id || typeof item.service.name !== "string" || !item.service.name))
74
- throw new Error("Invalid Render services response");
75
- return data;
76
- }
77
- async function listGoogleCloudRunServices(connection, project, region, transport = fetch) {
78
- connectionFor(connection, "google-cloud-run");
79
- const projectId = requiredProject(project, "Google project ID", /^[a-z][a-z0-9-]{4,61}[a-z0-9]$/);
80
- const location = requiredProject(region, "Google Cloud location", /^[a-z][a-z0-9-]{1,40}$/);
81
- const { data } = await createProviderClient(connection, transport).request({ path: `/v2/projects/${projectId}/locations/${location}/services` });
82
- if (!data || data.services !== void 0 && (!Array.isArray(data.services) || data.services.some((item) => typeof item.name !== "string" || !item.name)))
83
- throw new Error("Invalid Cloud Run service listing");
84
- return data.services || [];
85
- }
86
-
87
43
  // src/provider-services/compute-routing.ts
88
44
  var COMPUTE_PROFILE_PRESETS = Object.freeze({
89
45
  low: Object.freeze({ cpuVcpus: 1, memoryGiB: 1 }),
@@ -347,10 +303,6 @@ async function invokeFlyMachineHttp(input, transport = fetch) {
347
303
 
348
304
  export {
349
305
  calculateProviderCapacity,
350
- getRailwayAccount,
351
- listFlyApps,
352
- listRenderServices,
353
- listGoogleCloudRunServices,
354
306
  COMPUTE_PROFILE_PRESETS,
355
307
  validateComputeSpec,
356
308
  resolveComputeSpec,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createGoogleDriveWorkspaceClient
3
- } from "./chunk-3ZL2DX73.js";
3
+ } from "./chunk-PAU25K7F.js";
4
4
  import {
5
5
  queryUnifiedDb
6
6
  } from "./chunk-3RTRATDJ.js";
@@ -0,0 +1,177 @@
1
+ // src/core/systemCredentialsCore.ts
2
+ function parseCredentials(value) {
3
+ if (typeof value === "string") {
4
+ try {
5
+ const parsed = JSON.parse(value);
6
+ return parsed && typeof parsed === "object" ? parsed : {};
7
+ } catch {
8
+ return {};
9
+ }
10
+ }
11
+ return value && typeof value === "object" ? value : {};
12
+ }
13
+ async function readSystemCredentialsRecord(queryDb, targetId = "system") {
14
+ const result = await queryDb(
15
+ 'SELECT id, credentials, created_at, updated_at FROM public."ultrst-credentials" WHERE id = $1 LIMIT 1',
16
+ [targetId]
17
+ );
18
+ const row = result.rows[0];
19
+ if (!row) return { id: targetId, credentials: {} };
20
+ return {
21
+ id: String(row.id || targetId),
22
+ credentials: parseCredentials(row.credentials),
23
+ ...row.created_at ? { created_at: new Date(row.created_at).toISOString() } : {},
24
+ ...row.updated_at ? { updated_at: new Date(row.updated_at).toISOString() } : {}
25
+ };
26
+ }
27
+ async function getSystemCredentialsRecord(queryDb, targetId = "system") {
28
+ await queryDb(`
29
+ CREATE TABLE IF NOT EXISTS public."ultrst-credentials" (
30
+ id TEXT PRIMARY KEY,
31
+ credentials JSONB NOT NULL DEFAULT '{}'::jsonb,
32
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
33
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
34
+ )
35
+ `);
36
+ await queryDb(`
37
+ ALTER TABLE public."ultrst-credentials"
38
+ ADD COLUMN IF NOT EXISTS credentials JSONB NOT NULL DEFAULT '{}'::jsonb
39
+ `);
40
+ await queryDb(`
41
+ INSERT INTO public."ultrst-credentials" (id, credentials)
42
+ VALUES ($1, '{}'::jsonb)
43
+ ON CONFLICT (id) DO NOTHING
44
+ `, [targetId]);
45
+ const result = await queryDb(
46
+ 'SELECT id, credentials, created_at, updated_at FROM public."ultrst-credentials" WHERE id = $1 LIMIT 1',
47
+ [targetId]
48
+ );
49
+ const row = result.rows[0];
50
+ if (!row) return { id: targetId, credentials: {} };
51
+ return {
52
+ id: String(row.id || targetId),
53
+ credentials: parseCredentials(row.credentials),
54
+ ...row.created_at ? { created_at: new Date(row.created_at).toISOString() } : {},
55
+ ...row.updated_at ? { updated_at: new Date(row.updated_at).toISOString() } : {}
56
+ };
57
+ }
58
+ async function getGoogleDriveOAuthConfiguration(queryDb) {
59
+ const record = await getSystemCredentialsRecord(queryDb, "system");
60
+ const root = record.credentials || {};
61
+ const oauth = root.googleDriveOAuth || root.googleOAuth || {};
62
+ const clientId = typeof oauth.clientId === "string" ? oauth.clientId.trim() : "";
63
+ const clientSecret = typeof oauth.clientSecret === "string" ? oauth.clientSecret.trim() : "";
64
+ const redirectUri = typeof oauth.redirectUri === "string" ? oauth.redirectUri.trim() : "";
65
+ const stateSecret = typeof oauth.stateSecret === "string" ? oauth.stateSecret.trim() : "";
66
+ const missing = [];
67
+ if (!clientId) missing.push("client ID");
68
+ if (!clientSecret) missing.push("client secret");
69
+ if (!redirectUri) missing.push("redirect URI");
70
+ if (!stateSecret || stateSecret.length < 32) missing.push("OAuth state signing secret (minimum 32 characters)");
71
+ if (missing.length) {
72
+ throw new Error(
73
+ `[STORAGE_PROVIDER_CONFIGURATION_MISSING] Google Drive OAuth system configuration is incomplete: ${missing.join(", ")}. Configure system.ultrst-credentials.googleDriveOAuth.`
74
+ );
75
+ }
76
+ let parsedRedirect;
77
+ try {
78
+ parsedRedirect = new URL(redirectUri);
79
+ } catch {
80
+ throw new Error("[STORAGE_PROVIDER_CONFIGURATION_INVALID] Google Drive OAuth redirect URI must be an absolute URL.");
81
+ }
82
+ if (parsedRedirect.protocol !== "https:" && parsedRedirect.hostname !== "localhost") {
83
+ throw new Error("[STORAGE_PROVIDER_CONFIGURATION_INVALID] Google Drive OAuth redirect URI must use HTTPS (localhost is allowed for development).");
84
+ }
85
+ const allowedReturnOrigins = Array.isArray(oauth.allowedReturnOrigins) ? oauth.allowedReturnOrigins.flatMap((value) => {
86
+ if (typeof value !== "string") return [];
87
+ try {
88
+ const url = new URL(value.trim());
89
+ if (url.protocol !== "https:" && url.hostname !== "localhost") return [];
90
+ return [url.origin];
91
+ } catch {
92
+ return [];
93
+ }
94
+ }) : [];
95
+ return { clientId, clientSecret, redirectUri, stateSecret, allowedReturnOrigins };
96
+ }
97
+ function decodeStorageEncryptionKey(value) {
98
+ if (!/^[A-Za-z0-9_-]{43}$/.test(value)) {
99
+ throw new Error("[STORAGE_SECRET_CONFIGURATION_INVALID] The canonical storage encryption key is malformed.");
100
+ }
101
+ const base64 = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(44, "=");
102
+ let binary;
103
+ try {
104
+ binary = atob(base64);
105
+ } catch {
106
+ throw new Error("[STORAGE_SECRET_CONFIGURATION_INVALID] The canonical storage encryption key is malformed.");
107
+ }
108
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
109
+ if (bytes.length !== 32) {
110
+ throw new Error("[STORAGE_SECRET_CONFIGURATION_INVALID] The canonical storage encryption key must decode to exactly 32 bytes.");
111
+ }
112
+ return bytes;
113
+ }
114
+ async function getStorageConnectionEncryptionKey(queryDb) {
115
+ const record = await readSystemCredentialsRecord(queryDb, "system");
116
+ const storage = record.credentials?.storageConnections && typeof record.credentials.storageConnections === "object" ? record.credentials.storageConnections : {};
117
+ const current = typeof storage.encryptionKey === "string" ? storage.encryptionKey.trim() : "";
118
+ if (!current) {
119
+ throw new Error("[STORAGE_SECRET_CONFIGURATION_MISSING] The system-owned storage encryption key is missing; encrypted user connections were not modified.");
120
+ }
121
+ decodeStorageEncryptionKey(current);
122
+ const version = storage.encryptionKeyVersion == null ? 1 : Number(storage.encryptionKeyVersion);
123
+ if (version !== 1) {
124
+ throw new Error("[STORAGE_SECRET_CONFIGURATION_UNSUPPORTED] The canonical storage encryption key version is not supported.");
125
+ }
126
+ return current;
127
+ }
128
+ async function getOrCreateStorageConnectionEncryptionKey(queryDb) {
129
+ const record = await getSystemCredentialsRecord(queryDb, "system");
130
+ const root = record.credentials || {};
131
+ const storage = root.storageConnections && typeof root.storageConnections === "object" ? root.storageConnections : {};
132
+ const current = typeof storage.encryptionKey === "string" ? storage.encryptionKey.trim() : "";
133
+ if (current) {
134
+ decodeStorageEncryptionKey(current);
135
+ const version2 = storage.encryptionKeyVersion == null ? 1 : Number(storage.encryptionKeyVersion);
136
+ if (version2 !== 1) {
137
+ throw new Error("[STORAGE_SECRET_CONFIGURATION_UNSUPPORTED] The canonical storage encryption key version is not supported.");
138
+ }
139
+ return current;
140
+ }
141
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
142
+ let binary = "";
143
+ for (const byte of bytes) binary += String.fromCharCode(byte);
144
+ const generated = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
145
+ decodeStorageEncryptionKey(generated);
146
+ await queryDb(
147
+ `UPDATE public."ultrst-credentials"
148
+ SET credentials = jsonb_set(
149
+ COALESCE(credentials, '{}'::jsonb),
150
+ '{storageConnections}',
151
+ COALESCE(credentials->'storageConnections', '{}'::jsonb)
152
+ || jsonb_build_object('encryptionKey', $1::text, 'encryptionKeyVersion', 1),
153
+ true
154
+ ),
155
+ updated_at = NOW()
156
+ WHERE id = $2
157
+ AND NULLIF(credentials #>> '{storageConnections,encryptionKey}', '') IS NULL`,
158
+ [generated, "system"]
159
+ );
160
+ const refreshed = await getSystemCredentialsRecord(queryDb, "system");
161
+ const persisted = typeof refreshed.credentials?.storageConnections?.encryptionKey === "string" ? refreshed.credentials.storageConnections.encryptionKey.trim() : "";
162
+ if (!persisted) {
163
+ throw new Error("[STORAGE_SECRET_CONFIGURATION_UNAVAILABLE] Unable to resolve the canonical storage encryption key.");
164
+ }
165
+ decodeStorageEncryptionKey(persisted);
166
+ const version = refreshed.credentials.storageConnections.encryptionKeyVersion == null ? 1 : Number(refreshed.credentials.storageConnections.encryptionKeyVersion);
167
+ if (version !== 1) {
168
+ throw new Error("[STORAGE_SECRET_CONFIGURATION_UNSUPPORTED] The canonical storage encryption key version is not supported.");
169
+ }
170
+ return persisted;
171
+ }
172
+
173
+ export {
174
+ getGoogleDriveOAuthConfiguration,
175
+ getStorageConnectionEncryptionKey,
176
+ getOrCreateStorageConnectionEncryptionKey
177
+ };