@ultrst-armada/kloks 2.2.9 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) 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-R4B3KPHY.js → chunk-B6BQPDJE.js} +31 -10
  10. package/packages/backend/dist/control-plane/ControlPlaneManager.d.ts +6 -3
  11. package/packages/backend/dist/index.d.ts +0 -2
  12. package/packages/backend/dist/index.js +0 -18
  13. package/packages/backend/dist/krnl-services.js +1 -2
  14. package/packages/backend/dist/node.d.ts +0 -1
  15. package/packages/backend/dist/node.js +2 -86
  16. package/packages/client/dist/auth.d.ts +9 -21
  17. package/packages/client/dist/auth.js +1 -23
  18. package/packages/client/dist/chunk-QGZHKLOK.js +75 -0
  19. package/packages/client/dist/index.d.ts +2 -3
  20. package/packages/client/dist/index.js +1 -23
  21. package/packages/backend/dist/auth/BaseAccountProvider.d.ts +0 -7
  22. package/packages/backend/dist/auth/CanonicalAuthClient.d.ts +0 -6
  23. package/packages/backend/dist/auth/UnifiedAuthCore.d.ts +0 -23
  24. package/packages/backend/dist/auth/UnifiedAuthCore.test.d.ts +0 -1
  25. package/packages/backend/dist/auth/UniversalLuthInitialization.d.ts +0 -55
  26. package/packages/backend/dist/chunk-2COYZMUJ.js +0 -78
  27. package/packages/backend/dist/chunk-MDTLU7H4.js +0 -58
  28. package/packages/backend/dist/luth/LuthDiscoveryService.d.ts +0 -15
  29. package/packages/backend/dist/luth/index.d.ts +0 -1
  30. package/packages/client/dist/chunk-4HR374IB.js +0 -148
@@ -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.0",
5
+ "sourceCommit": "0e7389812754238becbf3adf370190fd50b5cb6d",
6
6
  "releaseWorkflow": "npm Release",
7
- "workflowRunId": "44814035725"
7
+ "workflowRunId": "44884992381"
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.0",
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),
@@ -46,10 +46,6 @@ import {
46
46
  import {
47
47
  queryUnifiedDb
48
48
  } from "./chunk-3RTRATDJ.js";
49
- import {
50
- loginSystemUser,
51
- resolveUserFromToken
52
- } from "./chunk-2COYZMUJ.js";
53
49
  import {
54
50
  authorizeB2,
55
51
  b2DownloadFile,
@@ -67,6 +63,36 @@ import {
67
63
  createServiceDefinition
68
64
  } from "@ultrst-armada/krnl";
69
65
 
66
+ // src/auth/LuthOAuthUserInfo.ts
67
+ import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
68
+ async function verifyLuthOAuthAccessToken(token, transport = fetch) {
69
+ const clean = token.trim().replace(/^Bearer\s+/i, "");
70
+ if (!/^[A-Za-z0-9._~-]{16,2048}$/.test(clean)) return null;
71
+ try {
72
+ const issuer = new URL(DEFAULT_LUTH_URL);
73
+ const result = await transport(
74
+ new URL("/api/auth/oauth2/userinfo", issuer.origin),
75
+ {
76
+ method: "GET",
77
+ credentials: "omit",
78
+ cache: "no-store",
79
+ redirect: "error",
80
+ headers: { authorization: "Bearer " + clean, accept: "application/json" }
81
+ }
82
+ );
83
+ if (!result.ok) return null;
84
+ const body = await result.json();
85
+ if (typeof body.sub !== "string" || !body.sub || typeof body.email !== "string" || !body.email) return null;
86
+ return {
87
+ id: body.sub,
88
+ email: body.email,
89
+ name: typeof body.name === "string" ? body.name : body.email
90
+ };
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
70
96
  // src/core/b2ExplorerContext.ts
71
97
  function safeB2ExplorerPath(value) {
72
98
  if (typeof value !== "string" || !value || value.startsWith("/") || value.includes("\\") || /[\x00-\x1f\x7f]/.test(value)) {
@@ -546,15 +572,10 @@ var AuthServiceDefinition = createServiceDefinition({
546
572
  initial: { activeSessions: 0 }
547
573
  },
548
574
  operations: {
549
- login: {
550
- id: "AuthService.login",
551
- name: "login",
552
- handler: async (input) => loginSystemUser(input.email, input.password, Boolean(input.isAdmin), (sql, params) => queryUnifiedDb(sql, params, input.env), input.env)
553
- },
554
575
  resolveUser: {
555
576
  id: "AuthService.resolveUser",
556
577
  name: "resolveUser",
557
- handler: async (input) => resolveUserFromToken(input.tokenOrUserId, (sql, params) => queryUnifiedDb(sql, params, input.env), input.env)
578
+ handler: async (input) => verifyLuthOAuthAccessToken(input.accessToken)
558
579
  }
559
580
  }
560
581
  });
@@ -1,10 +1,13 @@
1
1
  import { SkipoBase } from '@ultrst-armada/kloks/functions/base';
2
- import { BaseAccountProvider } from '../auth/BaseAccountProvider.js';
2
+ import type { OfficialLuthUser } from '../auth/LuthOAuthUserInfo.js';
3
+ export interface OAuthResourceVerifier {
4
+ verifyAccessToken(token: string): Promise<OfficialLuthUser | null>;
5
+ }
3
6
  import { AuditLogger } from './AuditLogger.js';
4
7
  import { DatabaseClusterManager } from './DatabaseClusterManager.js';
5
8
  export declare class ControlPlaneManager extends SkipoBase {
6
- auth: BaseAccountProvider;
9
+ auth: OAuthResourceVerifier;
7
10
  audit: AuditLogger;
8
11
  cluster: DatabaseClusterManager;
9
- constructor(auth: BaseAccountProvider, audit: AuditLogger, cluster: DatabaseClusterManager);
12
+ constructor(auth: OAuthResourceVerifier, audit: AuditLogger, cluster: DatabaseClusterManager);
10
13
  }
@@ -1,6 +1,5 @@
1
1
  /** Portable backend surface. Node filesystem, database, server and service engines are exposed from the explicit /node adapter. */
2
2
  export * from './api/index.js';
3
- export * from './auth/CanonicalAuthClient.js';
4
3
  export * from './storage/index.js';
5
4
  export * from './workspace/index.js';
6
5
  export * from './connectivity/index.js';
@@ -8,4 +7,3 @@ export * from './services/index.js';
8
7
  export * from './resolver/index.js';
9
8
  export type { Runtime, Deployment, FunctionSet, ServiceFacade, OrchestrationFn, BackendFacade, ServiceRegistryRecord, } from './architecture/types.js';
10
9
  export * from './provider-services/index.js';
11
- export * from './auth/UniversalLuthInitialization.js';
@@ -99,16 +99,6 @@ import {
99
99
  withCors
100
100
  } from "./chunk-KCPQWJBO.js";
101
101
  import "./chunk-LMY6MGFD.js";
102
- import {
103
- LuthAuthClient,
104
- LuthAuthClient2,
105
- LuthAuthError,
106
- createLuthAuthClient,
107
- createLuthAuthClient2,
108
- createUniversalLuthRuntimeService,
109
- resolveClientEnvironment,
110
- resolveClientOrigin
111
- } from "./chunk-MDTLU7H4.js";
112
102
  import {
113
103
  BackendRegistry,
114
104
  ConcurrencyConflictError,
@@ -160,7 +150,6 @@ export {
160
150
  BaseStorageAdapter,
161
151
  COMPUTE_PROFILE_PRESETS,
162
152
  CallbackRegistry,
163
- LuthAuthClient2 as CanonicalAuthClient,
164
153
  ConcurrencyConflictError,
165
154
  ConcurrencyManager,
166
155
  EventBus,
@@ -175,8 +164,6 @@ export {
175
164
  JobScheduler,
176
165
  LoadBalancer,
177
166
  LockManager,
178
- LuthAuthClient,
179
- LuthAuthError,
180
167
  RemoteExecutor,
181
168
  SequenceTracker,
182
169
  UnsupportedStorageOperation,
@@ -193,7 +180,6 @@ export {
193
180
  continueDropboxFolder,
194
181
  createBackblazeB2StorageService,
195
182
  createBackendClient,
196
- createLuthAuthClient2 as createCanonicalAuthClient,
197
183
  createCanonicalStorageService,
198
184
  createDropboxStorageService,
199
185
  createEmptyContract,
@@ -201,10 +187,8 @@ export {
201
187
  createFlyMachine,
202
188
  createGitHubStorageService,
203
189
  createGoogleDriveStorageService,
204
- createLuthAuthClient,
205
190
  createProviderClient,
206
191
  createSSEResponse,
207
- createUniversalLuthRuntimeService,
208
192
  b2DownloadFile as downloadBackblazeB2File,
209
193
  fetchCloudflareCapacity,
210
194
  fetchVercelCapacity,
@@ -248,8 +232,6 @@ export {
248
232
  rankComputeRoutes,
249
233
  readOnlyService,
250
234
  resolveBackblazeEndpoint,
251
- resolveClientEnvironment,
252
- resolveClientOrigin,
253
235
  resolveComputeSpec,
254
236
  resolveProviderServiceId,
255
237
  resolveSystemDatabaseUrl,
@@ -27,14 +27,13 @@ import {
27
27
  krnlStorageServiceFacade,
28
28
  krnlWorkspaceServiceDefinition,
29
29
  krnlWorkspaceServiceFacade
30
- } from "./chunk-R4B3KPHY.js";
30
+ } from "./chunk-B6BQPDJE.js";
31
31
  import "./chunk-FZKBTF34.js";
32
32
  import "./chunk-7XTURV44.js";
33
33
  import "./chunk-GCVR257U.js";
34
34
  import "./chunk-IRKJ6HKP.js";
35
35
  import "./chunk-3ZL2DX73.js";
36
36
  import "./chunk-3RTRATDJ.js";
37
- import "./chunk-2COYZMUJ.js";
38
37
  import "./chunk-I6T64MLT.js";
39
38
  import "./chunk-IP6XWQU2.js";
40
39
  import "./chunk-EMSSTOOK.js";
@@ -7,7 +7,6 @@ export * from './data/index.js';
7
7
  export * from './connectivity/index.js';
8
8
  export * from './client/index.js';
9
9
  export * from './srkl/index.js';
10
- export * from './luth/index.js';
11
10
  export type { Runtime, Deployment, FunctionSet, ServiceFacade, OrchestrationFn, BackendFacade, ServiceRegistryRecord, } from './architecture/types.js';
12
11
  export { validateServiceDefinition } from './architecture/types.js';
13
12
  export * from './services/node.js';
@@ -93,7 +93,7 @@ import {
93
93
  import {
94
94
  createCanonicalApplicationOAuthBff,
95
95
  createOAuthBff
96
- } from "./chunk-AKVBFHHD.js";
96
+ } from "./chunk-2SNWR4FI.js";
97
97
  import {
98
98
  BackendProvider,
99
99
  useBackend,
@@ -132,16 +132,6 @@ import {
132
132
  import {
133
133
  SkipoBase
134
134
  } from "./chunk-LMY6MGFD.js";
135
- import {
136
- LuthAuthClient,
137
- LuthAuthClient2,
138
- LuthAuthError,
139
- createLuthAuthClient,
140
- createLuthAuthClient2,
141
- createUniversalLuthRuntimeService,
142
- resolveClientEnvironment,
143
- resolveClientOrigin
144
- } from "./chunk-MDTLU7H4.js";
145
135
  import {
146
136
  BackendRegistry,
147
137
  ConcurrencyConflictError,
@@ -237,7 +227,7 @@ import {
237
227
  readUserWorkspaceStorageFile,
238
228
  verifyGoogleDriveAuthorizationState,
239
229
  writeUserWorkspaceStorageFile
240
- } from "./chunk-R4B3KPHY.js";
230
+ } from "./chunk-B6BQPDJE.js";
241
231
  import {
242
232
  formatCanonicalWorkspaceFolderName,
243
233
  sanitizeWorkspaceName
@@ -305,10 +295,6 @@ import {
305
295
  getUnifiedDbUrl,
306
296
  queryUnifiedDb
307
297
  } from "./chunk-3RTRATDJ.js";
308
- import {
309
- loginSystemUser,
310
- resolveUserFromToken
311
- } from "./chunk-2COYZMUJ.js";
312
298
  import {
313
299
  authorizeB2,
314
300
  b2DeleteFileVersion,
@@ -415,62 +401,6 @@ var FunctionalityTable = class extends BaseDataProvider {
415
401
  }
416
402
  };
417
403
 
418
- // src/luth/LuthDiscoveryService.ts
419
- import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
420
- var cachedLuthUrls = null;
421
- var roundRobinIndex = 0;
422
- async function getRegisteredLuthDeploymentUrls(queryDb) {
423
- if (cachedLuthUrls && Date.now() < cachedLuthUrls.expiresAt && cachedLuthUrls.urls.length > 0) {
424
- return cachedLuthUrls.urls;
425
- }
426
- if (queryDb) {
427
- try {
428
- const res = await queryDb(
429
- `SELECT url FROM "ultrst-luth-deployments" WHERE is_active = true ORDER BY is_primary DESC, priority DESC, created_at ASC`,
430
- []
431
- );
432
- if (res.rows.length > 0) {
433
- const urls = res.rows.map((r) => String(r.url || "").trim().replace(/\/+$/, "")).filter(Boolean);
434
- if (urls.length > 0) {
435
- cachedLuthUrls = { urls, expiresAt: Date.now() + 5 * 60 * 1e3 };
436
- return urls;
437
- }
438
- }
439
- } catch {
440
- try {
441
- const res2 = await queryDb(
442
- `SELECT origin FROM "ultrst-apps" WHERE app_id = 'luth' AND status = 'active' AND origin IS NOT NULL LIMIT 1`,
443
- []
444
- );
445
- if (res2.rows.length > 0 && res2.rows[0].origin) {
446
- const u = String(res2.rows[0].origin).trim().replace(/\/+$/, "");
447
- cachedLuthUrls = { urls: [u], expiresAt: Date.now() + 5 * 60 * 1e3 };
448
- return [u];
449
- }
450
- } catch {
451
- }
452
- }
453
- }
454
- const fallback = [DEFAULT_LUTH_URL];
455
- cachedLuthUrls = { urls: fallback, expiresAt: Date.now() + 5 * 60 * 1e3 };
456
- return fallback;
457
- }
458
- async function getPrimaryLuthDeploymentUrl(queryDb) {
459
- const urls = await getRegisteredLuthDeploymentUrls(queryDb);
460
- return urls[0] || DEFAULT_LUTH_URL;
461
- }
462
- async function getNextLuthDeploymentUrl(queryDb) {
463
- const urls = await getRegisteredLuthDeploymentUrls(queryDb);
464
- if (urls.length === 0) return DEFAULT_LUTH_URL;
465
- const next = urls[roundRobinIndex % urls.length];
466
- roundRobinIndex = (roundRobinIndex + 1) % urls.length;
467
- return next;
468
- }
469
- function clearLuthDiscoveryCache() {
470
- cachedLuthUrls = null;
471
- roundRobinIndex = 0;
472
- }
473
-
474
404
  // src/architecture/types.ts
475
405
  function validateServiceDefinition(def) {
476
406
  if (def.deployment === "remote" && def.runtime !== "server") {
@@ -4620,7 +4550,6 @@ export {
4620
4550
  BucketStorageService,
4621
4551
  CANONICAL_SRKL_URL,
4622
4552
  CallbackRegistry,
4623
- LuthAuthClient2 as CanonicalAuthClient,
4624
4553
  CanonicalStorageProviderService,
4625
4554
  CloudflareProviderService,
4626
4555
  CloudflareResourceFetcher,
@@ -4665,8 +4594,6 @@ export {
4665
4594
  LoadBalancer,
4666
4595
  LocalFSAdapter,
4667
4596
  LockManager,
4668
- LuthAuthClient,
4669
- LuthAuthError,
4670
4597
  MCPEngine,
4671
4598
  MetricsLogger,
4672
4599
  ModelCatalogService,
@@ -4722,7 +4649,6 @@ export {
4722
4649
  buildProjectsList,
4723
4650
  classifyAndFormatError,
4724
4651
  cleanDbUrl,
4725
- clearLuthDiscoveryCache,
4726
4652
  completeGoogleDriveAuthorization,
4727
4653
  completeGoogleDriveAuthorizationCallback,
4728
4654
  computeDeploymentFinalWeight,
@@ -4735,7 +4661,6 @@ export {
4735
4661
  createBackend,
4736
4662
  createBackendClient,
4737
4663
  createCanonicalApplicationOAuthBff,
4738
- createLuthAuthClient2 as createCanonicalAuthClient,
4739
4664
  createCompositeService,
4740
4665
  createCredential,
4741
4666
  createEmptyContract,
@@ -4746,12 +4671,10 @@ export {
4746
4671
  createGraphAssetFolder as createGraphAssetSubfolder,
4747
4672
  createGraphPackage,
4748
4673
  createLocalService,
4749
- createLuthAuthClient,
4750
4674
  createOAuthBff,
4751
4675
  createRemoteService,
4752
4676
  createSSEResponse,
4753
4677
  createSrklClient,
4754
- createUniversalLuthRuntimeService,
4755
4678
  createWavBuffer,
4756
4679
  createWorkspace,
4757
4680
  createWorkspaceGraph,
@@ -4805,15 +4728,12 @@ export {
4805
4728
  getGatewayConfig,
4806
4729
  getGoogleDriveAccountIdentityForUser,
4807
4730
  getGraphPackageById,
4808
- getNextLuthDeploymentUrl,
4809
- getPrimaryLuthDeploymentUrl,
4810
4731
  getPrimarySrklDeploymentUrl2 as getPrimarySrklCoreDeploymentUrl,
4811
4732
  getPrimarySrklDeploymentUrl,
4812
4733
  getProjectById,
4813
4734
  getProviderMeta,
4814
4735
  getPublicRouteByPath,
4815
4736
  getPublicRoutes,
4816
- getRegisteredLuthDeploymentUrls,
4817
4737
  getSrklAccounts,
4818
4738
  getSrklAccounts2 as getSrklCoreAccounts,
4819
4739
  getSrklStatus,
@@ -4874,7 +4794,6 @@ export {
4874
4794
  listWorkspaceGraphs,
4875
4795
  loadCredentialManifest,
4876
4796
  loadWorkspaceData,
4877
- loginSystemUser,
4878
4797
  matchGatewayIngress,
4879
4798
  matchGatewayIngressAsync,
4880
4799
  mcpEngine,
@@ -4903,13 +4822,10 @@ export {
4903
4822
  renameAppInWorkspaceData,
4904
4823
  renameS3Folder,
4905
4824
  resolveBackblazeEndpoint,
4906
- resolveClientEnvironment,
4907
- resolveClientOrigin,
4908
4825
  resolveDynamicRouteFromDb,
4909
4826
  resolveSystemDatabaseClusterNodes,
4910
4827
  resolveSystemDatabaseUrl,
4911
4828
  resolveSystemDatabaseUrlCandidates,
4912
- resolveUserFromToken,
4913
4829
  resolveUserStorageConnectionSecret,
4914
4830
  resolveUserWorkspaceStorageAssociation,
4915
4831
  resolveWorkspaceConnection,
@@ -1,34 +1,22 @@
1
- import { DeploymentEnvironment } from '@dinilmusick/gutts/auth';
2
- export * from '@dinilmusick/gutts/auth';
3
- export { ApplicationAuthClient, ApplicationAuthClientConfig, LuthAuthClient as CanonicalAuthClient, DEFAULT_LUTH_URL, DeploymentEnvironment, EmailSignInCredentials, EmailSignUpData, GoogleSignInOptions, LuthAuthClient, LuthAuthClientConfig, LuthAuthError, LuthAuthTokenStore, LuthSession, LuthSessionResult, LuthUser, RegisterApplicationResult, createApplicationAuthClient, createLuthAuthClient as createCanonicalAuthClient, createLuthAuthClient, hydrateLuthTokenFromUrl, resolveClientEnvironment, resolveClientOrigin } from '@dinilmusick/gutts/auth';
1
+ export { DEFAULT_LUTH_URL } from '@dinilmusick/gutts/auth';
4
2
 
5
3
  interface LuthPrincipal {
6
4
  id: string;
7
5
  email: string;
8
6
  name: string;
9
- role: string;
7
+ role: 'user';
10
8
  }
11
9
  declare const CANONICAL_PUBLIC_ROUTES: (string | RegExp)[];
10
+ /** Never interpret a cookie, API key, user ID or Origin as a Luth token. */
12
11
  declare function extractLuthToken(request: Request): string;
13
- declare function isPublicRoute(pathname: string, extraPublicRoutes?: (string | RegExp)[]): boolean;
12
+ declare function isPublicRoute(path: string, extraPublicRoutes?: (string | RegExp)[]): boolean;
13
+ /**
14
+ * Verify the official OAuth Provider token on every protected request.
15
+ * Never forward an application cookie; never cache identity across revocation.
16
+ */
14
17
  declare function verifyLuthRequest(request: Request, options?: {
15
18
  luthUrl?: string;
16
19
  extraPublicRoutes?: (string | RegExp)[];
17
20
  }): Promise<LuthPrincipal | Response | null>;
18
21
 
19
- interface LuthDeploymentRecord {
20
- id: string;
21
- url: string;
22
- label?: string;
23
- environment?: DeploymentEnvironment;
24
- isActive: boolean;
25
- isPrimary?: boolean;
26
- priority?: number;
27
- }
28
-
29
- /** Creates an authenticated fetch function that automatically injects Luth bearer headers and credentials: 'include'. */
30
- declare function createUniversalAuthFetch(authClient: {
31
- getAuthHeaders: () => HeadersInit;
32
- }): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
33
-
34
- export { CANONICAL_PUBLIC_ROUTES, type LuthDeploymentRecord, type LuthPrincipal, createUniversalAuthFetch, extractLuthToken, isPublicRoute, verifyLuthRequest };
22
+ export { CANONICAL_PUBLIC_ROUTES, type LuthPrincipal, extractLuthToken, isPublicRoute, verifyLuthRequest };
@@ -1,36 +1,14 @@
1
1
  import {
2
- ApplicationAuthClient,
3
2
  CANONICAL_PUBLIC_ROUTES,
4
3
  DEFAULT_LUTH_URL,
5
- LuthAuthClient,
6
- LuthAuthClient2,
7
- LuthAuthError,
8
- createApplicationAuthClient,
9
- createLuthAuthClient,
10
- createLuthAuthClient2,
11
- createUniversalAuthFetch,
12
4
  extractLuthToken,
13
- hydrateLuthTokenFromUrl,
14
5
  isPublicRoute,
15
- resolveClientEnvironment,
16
- resolveClientOrigin,
17
6
  verifyLuthRequest
18
- } from "./chunk-4HR374IB.js";
7
+ } from "./chunk-QGZHKLOK.js";
19
8
  export {
20
- ApplicationAuthClient,
21
9
  CANONICAL_PUBLIC_ROUTES,
22
- LuthAuthClient2 as CanonicalAuthClient,
23
10
  DEFAULT_LUTH_URL,
24
- LuthAuthClient,
25
- LuthAuthError,
26
- createApplicationAuthClient,
27
- createLuthAuthClient2 as createCanonicalAuthClient,
28
- createLuthAuthClient,
29
- createUniversalAuthFetch,
30
11
  extractLuthToken,
31
- hydrateLuthTokenFromUrl,
32
12
  isPublicRoute,
33
- resolveClientEnvironment,
34
- resolveClientOrigin,
35
13
  verifyLuthRequest
36
14
  };
@@ -0,0 +1,75 @@
1
+ // src/auth.ts
2
+ import { DEFAULT_LUTH_URL as DEFAULT_LUTH_URL2 } from "@dinilmusick/gutts/auth";
3
+
4
+ // src/UniversalLuthGuard.ts
5
+ import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
6
+ var CANONICAL_PUBLIC_ROUTES = [
7
+ "/health",
8
+ "/api/health",
9
+ "/api/status",
10
+ "/api/auth/oidc/start",
11
+ "/api/auth/oidc/callback",
12
+ "/api/auth/oidc/session",
13
+ "/api/auth/oidc/logout",
14
+ /^\/api(\/v1)?\/database\/status$/,
15
+ /^\/api(\/v1)?\/guest(\/.*)?$/,
16
+ /^\/api(\/v1)?\/spec(\/.*)?$/
17
+ ];
18
+ function extractLuthToken(request) {
19
+ const authorization = request.headers.get("authorization") || "";
20
+ const match = /^Bearer ([A-Za-z0-9._~-]{16,2048})$/i.exec(authorization.trim());
21
+ return match?.[1] || "";
22
+ }
23
+ function isPublicRoute(path, extraPublicRoutes = []) {
24
+ return [...CANONICAL_PUBLIC_ROUTES, ...extraPublicRoutes].some((route) => typeof route === "string" ? route === path : route.test(path));
25
+ }
26
+ function deny(request, unavailable = false) {
27
+ const mcp = new URL(request.url).pathname.includes("/mcp");
28
+ const status = unavailable ? 503 : 401;
29
+ const message = unavailable ? "Luth OAuth provider unavailable." : "Valid OAuth 2.1 Bearer token required.";
30
+ return Response.json(mcp ? {
31
+ jsonrpc: "2.0",
32
+ id: null,
33
+ error: { code: unavailable ? -32603 : -32001, message }
34
+ } : { success: false, error: message }, {
35
+ status,
36
+ headers: { "cache-control": "no-store" }
37
+ });
38
+ }
39
+ async function verifyLuthRequest(request, options) {
40
+ const path = new URL(request.url).pathname;
41
+ if (request.method === "OPTIONS" || isPublicRoute(path, options?.extraPublicRoutes)) return null;
42
+ const token = extractLuthToken(request);
43
+ if (!token) return deny(request);
44
+ try {
45
+ const issuer = new URL(options?.luthUrl || DEFAULT_LUTH_URL);
46
+ if (issuer.protocol !== "https:") return deny(request, true);
47
+ const response = await fetch(new URL("/api/auth/oauth2/userinfo", issuer.origin), {
48
+ method: "GET",
49
+ credentials: "omit",
50
+ cache: "no-store",
51
+ redirect: "error",
52
+ headers: { authorization: "Bearer " + token, accept: "application/json" }
53
+ });
54
+ if (response.status === 401 || response.status === 403) return deny(request);
55
+ if (!response.ok) return deny(request, true);
56
+ const body = await response.json();
57
+ if (typeof body.sub !== "string" || !body.sub || typeof body.email !== "string" || !body.email) return deny(request);
58
+ return {
59
+ id: body.sub,
60
+ email: body.email,
61
+ name: typeof body.name === "string" && body.name ? body.name : body.email,
62
+ role: "user"
63
+ };
64
+ } catch {
65
+ return deny(request, true);
66
+ }
67
+ }
68
+
69
+ export {
70
+ CANONICAL_PUBLIC_ROUTES,
71
+ extractLuthToken,
72
+ isPublicRoute,
73
+ verifyLuthRequest,
74
+ DEFAULT_LUTH_URL2 as DEFAULT_LUTH_URL
75
+ };
@@ -1,6 +1,5 @@
1
- export { CANONICAL_PUBLIC_ROUTES, LuthDeploymentRecord, LuthPrincipal, createUniversalAuthFetch, extractLuthToken, isPublicRoute, verifyLuthRequest } from './auth.js';
2
- export * from '@dinilmusick/gutts/auth';
3
- export { ApplicationAuthClient, ApplicationAuthClientConfig, LuthAuthClient as CanonicalAuthClient, DEFAULT_LUTH_URL, DeploymentEnvironment, EmailSignInCredentials, EmailSignUpData, GoogleSignInOptions, LuthAuthClient, LuthAuthClientConfig, LuthAuthError, LuthAuthTokenStore, LuthSession, LuthSessionResult, LuthUser, RegisterApplicationResult, createApplicationAuthClient, createLuthAuthClient as createCanonicalAuthClient, createLuthAuthClient, hydrateLuthTokenFromUrl, resolveClientEnvironment, resolveClientOrigin } from '@dinilmusick/gutts/auth';
1
+ export { DEFAULT_LUTH_URL } from '@dinilmusick/gutts/auth';
2
+ export { CANONICAL_PUBLIC_ROUTES, LuthPrincipal, extractLuthToken, isPublicRoute, verifyLuthRequest } from './auth.js';
4
3
 
5
4
  /**
6
5
  * @file queueContracts.ts
@@ -1,21 +1,10 @@
1
1
  import {
2
- ApplicationAuthClient,
3
2
  CANONICAL_PUBLIC_ROUTES,
4
3
  DEFAULT_LUTH_URL,
5
- LuthAuthClient,
6
- LuthAuthClient2,
7
- LuthAuthError,
8
- createApplicationAuthClient,
9
- createLuthAuthClient,
10
- createLuthAuthClient2,
11
- createUniversalAuthFetch,
12
4
  extractLuthToken,
13
- hydrateLuthTokenFromUrl,
14
5
  isPublicRoute,
15
- resolveClientEnvironment,
16
- resolveClientOrigin,
17
6
  verifyLuthRequest
18
- } from "./chunk-4HR374IB.js";
7
+ } from "./chunk-QGZHKLOK.js";
19
8
 
20
9
  // src/browserExecutionClient.ts
21
10
  var BrowserExecutionClient = class {
@@ -190,24 +179,13 @@ var OPFSWorkspaceStorage = class {
190
179
  }
191
180
  };
192
181
  export {
193
- ApplicationAuthClient,
194
182
  BrowserExecutionClient,
195
183
  CANONICAL_PUBLIC_ROUTES,
196
- LuthAuthClient2 as CanonicalAuthClient,
197
184
  DEFAULT_LUTH_URL,
198
- LuthAuthClient,
199
- LuthAuthError,
200
185
  OPFSWorkspaceStorage,
201
186
  WorkspaceAutosaveController,
202
- createApplicationAuthClient,
203
187
  createBrowserExecutionClient,
204
- createLuthAuthClient2 as createCanonicalAuthClient,
205
- createLuthAuthClient,
206
- createUniversalAuthFetch,
207
188
  extractLuthToken,
208
- hydrateLuthTokenFromUrl,
209
189
  isPublicRoute,
210
- resolveClientEnvironment,
211
- resolveClientOrigin,
212
190
  verifyLuthRequest
213
191
  };
@@ -1,7 +0,0 @@
1
- /**
2
- * Canonical account-provider compatibility type.
3
- *
4
- * Auth is owned by Luth; this alias exists only for control-plane APIs that
5
- * historically accepted a BaseAccountProvider.
6
- */
7
- export { LuthAuthClient as BaseAccountProvider, createLuthAuthClient as createBaseAccountProvider, } from '@dinilmusick/gutts';
@@ -1,6 +0,0 @@
1
- export { LuthAuthClient, createLuthAuthClient, resolveClientOrigin, resolveClientEnvironment, } from '@dinilmusick/gutts/auth';
2
- export type { DeploymentEnvironment, EmailSignInCredentials, EmailSignUpData, GoogleSignInOptions, LuthAuthClientConfig, LuthAuthTokenStore, LuthSessionResult, RegisterApplicationResult, LuthUser, LuthSession, } from '@dinilmusick/gutts/auth';
3
- export { LuthAuthError } from '@dinilmusick/gutts/auth';
4
- export { LuthAuthClient as CanonicalAuthClient } from '@dinilmusick/gutts/auth';
5
- export { createLuthAuthClient as createCanonicalAuthClient } from '@dinilmusick/gutts/auth';
6
- export type { LuthUser as CanonicalAuthUser, LuthSession as CanonicalAuthSession } from '@dinilmusick/gutts/auth';
@@ -1,23 +0,0 @@
1
- export interface SystemUser {
2
- id: string;
3
- email: string;
4
- name: string;
5
- username: string;
6
- role: string;
7
- status: string;
8
- appProfiles?: Record<string, unknown>;
9
- emailVerified?: boolean;
10
- }
11
- export type AuthEnvironment = Record<string, unknown>;
12
- export declare function loginSystemUser(email: string, rawPass: string, isAdmin: boolean, _queryDb: (sql: string, params?: unknown[]) => Promise<{
13
- rows: any[];
14
- }>, env?: AuthEnvironment): Promise<{
15
- success: boolean;
16
- status: number;
17
- token?: string;
18
- user?: SystemUser;
19
- error?: string;
20
- }>;
21
- export declare function resolveUserFromToken(tokenOrUserId: string, _queryDb: (sql: string, params?: unknown[]) => Promise<{
22
- rows: any[];
23
- }>, env?: AuthEnvironment): Promise<SystemUser | null>;
@@ -1 +0,0 @@
1
- export {};
@@ -1,55 +0,0 @@
1
- /** Structural invocation type only. The actual wire validator lives in GutTS. */
2
- type UniversalRuntimeKind = 'browser' | 'cloudflare-worker' | 'serverless' | 'server' | 'desktop' | 'android' | 'ios' | 'headless';
3
- type UniversalAuthReadiness = 'discovery' | 'unauthenticated' | 'authenticating' | 'authenticated' | 'configuring' | 'ready' | 'denied' | 'unavailable';
4
- interface UniversalDiscoveryV1 {
5
- application: {
6
- appId: string;
7
- ecosystemId: string;
8
- name: string;
9
- };
10
- issuer: string;
11
- configurationUrl: string;
12
- }
13
- interface UniversalConfigurationV1 {
14
- application: {
15
- appId: string;
16
- ecosystemId: string;
17
- name: string;
18
- };
19
- principal: {
20
- userId: string;
21
- };
22
- settings: {
23
- supportedServices: string[];
24
- };
25
- }
26
- /**
27
- * Canonical Kloks service for public discovery and least-privilege user
28
- * configuration. All schema validation, issuer pinning and retries live in
29
- * GutTS; this runtime adapter does not recreate the identity protocol.
30
- *
31
- * This is NOT a way to fetch OAuth client secrets, BFF encryption keys, or
32
- * database credentials. The existing OIDC BFF keeps its protected bootstrap
33
- * until authenticated confidential workload provisioning is implemented.
34
- */
35
- export interface UniversalLuthRuntimeAdapter {
36
- runtime: UniversalRuntimeKind;
37
- appId: string;
38
- /** Existing Luth issuer origin; pinned before accepting discovery URLs. */
39
- issuerOrigin: string;
40
- /** Adapter may supply verified session cookies or OAuth bearer transport. */
41
- authorizationHeaders?: () => Promise<HeadersInit>;
42
- /** Injectable URL for local and integration fixtures only. */
43
- discoveryUrl?: string;
44
- fetcher?: typeof fetch;
45
- onStateChange?: (state: UniversalAuthReadiness) => void;
46
- }
47
- export interface UniversalLuthRuntimeService {
48
- discover(): Promise<UniversalDiscoveryV1>;
49
- getConfiguration(): Promise<UniversalConfigurationV1>;
50
- invalidate(): void;
51
- readonly readiness: UniversalAuthReadiness;
52
- }
53
- /** Runtime privilege is never inferred from app ID or APP_URL. */
54
- export declare function createUniversalLuthRuntimeService(adapter: UniversalLuthRuntimeAdapter): UniversalLuthRuntimeService;
55
- export {};
@@ -1,78 +0,0 @@
1
- // src/auth/UnifiedAuthCore.ts
2
- import {
3
- LuthAuthClient,
4
- DEFAULT_LUTH_URL
5
- } from "@dinilmusick/gutts/auth";
6
- function tokenStore(initial = "") {
7
- let token = initial;
8
- return {
9
- get: () => token,
10
- set: (value) => {
11
- token = value;
12
- },
13
- clear: () => {
14
- token = "";
15
- }
16
- };
17
- }
18
- function createClient(_env, token = "") {
19
- return new LuthAuthClient({
20
- ecosystemId: "ultrst-armada",
21
- applicationId: "kloks-backend",
22
- luthUrl: DEFAULT_LUTH_URL,
23
- origin: process.env.APP_URL || DEFAULT_LUTH_URL,
24
- autoRegister: false,
25
- tokenStore: tokenStore(token)
26
- });
27
- }
28
- function toSystemUser(user) {
29
- return {
30
- ...user,
31
- username: user.email.split("@")[0],
32
- role: "user",
33
- status: "ACTIVE"
34
- };
35
- }
36
- async function loginSystemUser(email, rawPass, isAdmin, _queryDb, env) {
37
- if (!email?.trim() || !rawPass) return { success: false, status: 400, error: "Email and password are required" };
38
- if (isAdmin) return { success: false, status: 403, error: "Administrative authentication is not provided by canonical Luth user login." };
39
- try {
40
- const client = createClient(env);
41
- await client.signInWithEmail({ email: email.trim(), password: rawPass });
42
- const session = await client.getSession();
43
- if (!session.authenticated || !session.user || !session.session) {
44
- return { success: false, status: 401, error: "Canonical authentication service did not establish a session." };
45
- }
46
- const user = toSystemUser(session.user);
47
- const authorization = client.getAuthHeaders().Authorization || "";
48
- const token = authorization.replace(/^Bearer\s+/i, "").trim();
49
- if (!token) return { success: false, status: 502, error: "Luth did not return a usable bearer session token." };
50
- return {
51
- success: true,
52
- status: 200,
53
- user,
54
- token
55
- };
56
- } catch (error) {
57
- const status = error && typeof error === "object" && "status" in error && typeof error.status === "number" ? error.status : 503;
58
- return { success: false, status, error: error instanceof Error ? error.message : "Canonical authentication service unavailable" };
59
- }
60
- }
61
- async function resolveUserFromToken(tokenOrUserId, _queryDb, env) {
62
- if (!tokenOrUserId) return null;
63
- try {
64
- const credential = tokenOrUserId.trim().replace(/^Bearer[ \t]+/i, "").trim();
65
- if (!credential) return null;
66
- const client = createClient(env, credential);
67
- const session = await client.getSession();
68
- if (!session.authenticated || !session.user) return null;
69
- return toSystemUser(session.user);
70
- } catch {
71
- return null;
72
- }
73
- }
74
-
75
- export {
76
- loginSystemUser,
77
- resolveUserFromToken
78
- };
@@ -1,58 +0,0 @@
1
- // src/auth/CanonicalAuthClient.ts
2
- import {
3
- LuthAuthClient,
4
- createLuthAuthClient,
5
- resolveClientOrigin,
6
- resolveClientEnvironment
7
- } from "@dinilmusick/gutts/auth";
8
- import { LuthAuthError } from "@dinilmusick/gutts/auth";
9
- import { LuthAuthClient as LuthAuthClient2 } from "@dinilmusick/gutts/auth";
10
- import { createLuthAuthClient as createLuthAuthClient2 } from "@dinilmusick/gutts/auth";
11
-
12
- // src/auth/UniversalLuthInitialization.ts
13
- import * as PortableLuthAuth from "@dinilmusick/gutts/auth";
14
- function requiredGutTSFactory() {
15
- const source = PortableLuthAuth;
16
- const factory = source.createUniversalInitializationClient;
17
- if (typeof factory !== "function") {
18
- throw new Error("UNIVERSAL_INITIALIZATION_CONTRACT_UNAVAILABLE");
19
- }
20
- return factory;
21
- }
22
- function createUniversalLuthRuntimeService(adapter) {
23
- if (adapter.runtime === "headless") {
24
- throw new Error("VERIFIED_WORKLOAD_AUTHENTICATION_REQUIRED");
25
- }
26
- const client = requiredGutTSFactory()(
27
- {
28
- appId: adapter.appId,
29
- runtime: adapter.runtime,
30
- ...adapter.discoveryUrl ? { discoveryUrl: adapter.discoveryUrl } : {}
31
- },
32
- {
33
- expectedIssuerOrigin: adapter.issuerOrigin,
34
- ...adapter.authorizationHeaders ? { authorize: adapter.authorizationHeaders } : {},
35
- ...adapter.fetcher ? { fetcher: adapter.fetcher } : {},
36
- ...adapter.onStateChange ? { onStateChange: adapter.onStateChange } : {}
37
- }
38
- );
39
- return {
40
- discover: () => client.discover(),
41
- getConfiguration: () => client.configuration(),
42
- invalidate: () => client.invalidate(),
43
- get readiness() {
44
- return client.readiness;
45
- }
46
- };
47
- }
48
-
49
- export {
50
- LuthAuthClient,
51
- createLuthAuthClient,
52
- resolveClientOrigin,
53
- resolveClientEnvironment,
54
- LuthAuthError,
55
- LuthAuthClient2,
56
- createLuthAuthClient2,
57
- createUniversalLuthRuntimeService
58
- };
@@ -1,15 +0,0 @@
1
- /**
2
- * @file LuthDiscoveryService.ts
3
- * @description Universal Luth Auth Service Discovery with multi-deployment fallback and round-robin.
4
- * Runs identically in Node.js, Vercel Serverless, and Cloudflare Workers (< 200 lines).
5
- */
6
- export declare function getRegisteredLuthDeploymentUrls(queryDb?: (sql: string, params?: unknown[]) => Promise<{
7
- rows: any[];
8
- }>): Promise<string[]>;
9
- export declare function getPrimaryLuthDeploymentUrl(queryDb?: (sql: string, params?: unknown[]) => Promise<{
10
- rows: any[];
11
- }>): Promise<string>;
12
- export declare function getNextLuthDeploymentUrl(queryDb?: (sql: string, params?: unknown[]) => Promise<{
13
- rows: any[];
14
- }>): Promise<string>;
15
- export declare function clearLuthDiscoveryCache(): void;
@@ -1 +0,0 @@
1
- export * from './LuthDiscoveryService.js';
@@ -1,148 +0,0 @@
1
- // src/auth.ts
2
- import {
3
- LuthAuthClient,
4
- createLuthAuthClient,
5
- hydrateLuthTokenFromUrl,
6
- resolveClientOrigin,
7
- resolveClientEnvironment,
8
- LuthAuthError,
9
- DEFAULT_LUTH_URL as DEFAULT_LUTH_URL2,
10
- ApplicationAuthClient,
11
- createApplicationAuthClient
12
- } from "@dinilmusick/gutts/auth";
13
- import {
14
- LuthAuthClient as LuthAuthClient2,
15
- createLuthAuthClient as createLuthAuthClient2
16
- } from "@dinilmusick/gutts/auth";
17
-
18
- // src/UniversalLuthGuard.ts
19
- import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
20
- var CANONICAL_PUBLIC_ROUTES = [
21
- "/health",
22
- "/api/health",
23
- "/api/status",
24
- "/api/auth",
25
- /^\/api(\/v1)?\/auth(\/.*)?$/,
26
- /^\/api(\/v1)?\/database\/status$/,
27
- /^\/api(\/v1)?\/guest(\/.*)?$/,
28
- /^\/api(\/v1)?\/discovery(\/.*)?$/,
29
- /^\/api(\/v1)?\/spec(\/.*)?$/
30
- ];
31
- var SESSION_CACHE_TTL_MS = 6e4;
32
- var sessionCache = /* @__PURE__ */ new Map();
33
- function extractLuthToken(request) {
34
- const authorization = request.headers.get("authorization") || "";
35
- const bearer = /^Bearer\s+([^\s]+)$/i.exec(authorization.trim());
36
- if (bearer) return bearer[1];
37
- const apiKey = request.headers.get("x-api-key")?.trim();
38
- if (apiKey) return apiKey;
39
- const cookieHeader = request.headers.get("cookie") || "";
40
- const cookies = cookieHeader.split(";").map((c) => c.trim());
41
- for (const prefix of ["better-auth.session_token=", "__Secure-better-auth.session_token=", "luth_session="]) {
42
- const found = cookies.find((c) => c.startsWith(prefix));
43
- if (found) {
44
- try {
45
- return decodeURIComponent(found.slice(prefix.length));
46
- } catch {
47
- return "";
48
- }
49
- }
50
- }
51
- return "";
52
- }
53
- function isPublicRoute(pathname, extraPublicRoutes) {
54
- const routes = extraPublicRoutes ? [...CANONICAL_PUBLIC_ROUTES, ...extraPublicRoutes] : CANONICAL_PUBLIC_ROUTES;
55
- return routes.some((route) => typeof route === "string" ? pathname === route : route.test(pathname));
56
- }
57
- async function verifyLuthRequest(request, options) {
58
- const url = new URL(request.url);
59
- if (request.method === "OPTIONS") return null;
60
- if (isPublicRoute(url.pathname, options?.extraPublicRoutes)) return null;
61
- const isMcp = url.pathname.includes("/mcp");
62
- const token = extractLuthToken(request);
63
- if (!token) {
64
- const payload = isMcp ? { jsonrpc: "2.0", id: null, error: { code: -32001, message: "A verified Luth session is required." } } : { success: false, error: "A verified Luth session is required." };
65
- return new Response(JSON.stringify(payload), { status: 401, headers: { "Content-Type": "application/json" } });
66
- }
67
- const now = Date.now();
68
- const cached = sessionCache.get(token);
69
- if (cached && cached.expiresAt > now) {
70
- return cached.principal;
71
- }
72
- try {
73
- const luthUrl = options?.luthUrl || DEFAULT_LUTH_URL;
74
- const res = await fetch(`${luthUrl}/api/session`, {
75
- headers: {
76
- authorization: `Bearer ${token}`,
77
- cookie: request.headers.get("cookie") || "",
78
- origin: url.origin
79
- }
80
- });
81
- if (!res.ok) {
82
- const payload = isMcp ? { jsonrpc: "2.0", id: null, error: { code: -32001, message: "The Luth session is invalid or expired." } } : { success: false, error: "The Luth session is invalid or expired." };
83
- return new Response(JSON.stringify(payload), { status: 401, headers: { "Content-Type": "application/json" } });
84
- }
85
- const data = await res.json();
86
- const user = data?.user || (data?.authenticated ? data?.session?.user : null);
87
- if (!user || !user.id) {
88
- const payload = isMcp ? { jsonrpc: "2.0", id: null, error: { code: -32001, message: "The Luth session is invalid or expired." } } : { success: false, error: "The Luth session is invalid or expired." };
89
- return new Response(JSON.stringify(payload), { status: 401, headers: { "Content-Type": "application/json" } });
90
- }
91
- const principal = {
92
- id: String(user.id),
93
- email: String(user.email || ""),
94
- name: String(user.name || user.email?.split("@")[0] || ""),
95
- role: String(user.role || "user")
96
- };
97
- sessionCache.set(token, { principal, expiresAt: now + SESSION_CACHE_TTL_MS });
98
- return principal;
99
- } catch {
100
- const payload = isMcp ? { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Canonical Luth authentication service unavailable." } } : { success: false, error: "Canonical Luth authentication service unavailable." };
101
- return new Response(JSON.stringify(payload), { status: 503, headers: { "Content-Type": "application/json" } });
102
- }
103
- }
104
-
105
- // src/auth.ts
106
- export * from "@dinilmusick/gutts/auth";
107
- function createUniversalAuthFetch(authClient) {
108
- return async function universalAuthFetch(input, init = {}) {
109
- const headers = new Headers();
110
- if (typeof input === "object" && input !== null && "headers" in input && input.headers) {
111
- new Headers(input.headers).forEach((value, key) => {
112
- headers.set(key, value);
113
- });
114
- }
115
- if (init.headers) {
116
- new Headers(init.headers).forEach((value, key) => {
117
- headers.set(key, value);
118
- });
119
- }
120
- new Headers(authClient.getAuthHeaders()).forEach((value, key) => {
121
- if (!headers.has(key)) headers.set(key, value);
122
- });
123
- return fetch(input, {
124
- ...init,
125
- headers,
126
- credentials: init.credentials ?? "include"
127
- });
128
- };
129
- }
130
-
131
- export {
132
- CANONICAL_PUBLIC_ROUTES,
133
- extractLuthToken,
134
- isPublicRoute,
135
- verifyLuthRequest,
136
- createUniversalAuthFetch,
137
- LuthAuthClient,
138
- createLuthAuthClient,
139
- hydrateLuthTokenFromUrl,
140
- resolveClientOrigin,
141
- resolveClientEnvironment,
142
- LuthAuthError,
143
- DEFAULT_LUTH_URL2 as DEFAULT_LUTH_URL,
144
- ApplicationAuthClient,
145
- createApplicationAuthClient,
146
- LuthAuthClient2,
147
- createLuthAuthClient2
148
- };