@ultrst-armada/kloks 1.26.6 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/package.json +3 -7
  2. package/packages/backend/dist/{chunk-BVXGUHLZ.js → chunk-AOZSDRNY.js} +1 -1
  3. package/packages/backend/dist/chunk-G4EDIAHW.js +0 -0
  4. package/packages/backend/dist/{chunk-T6BJHFWZ.js → chunk-LMOM7CST.js} +2 -2
  5. package/packages/backend/dist/chunk-OQRQCDS6.js +109 -0
  6. package/packages/backend/dist/chunk-OWMQLML7.js +451 -0
  7. package/packages/backend/dist/{chunk-Y5ENDXU2.js → chunk-SQKG3S6P.js} +2 -10
  8. package/packages/backend/dist/{chunk-NGEB3CF5.js → chunk-Z6G32NQQ.js} +8 -3
  9. package/packages/backend/dist/core/SrklStorageService.test.d.ts +1 -0
  10. package/packages/backend/dist/krnl-services.js +5 -4
  11. package/packages/backend/dist/node.js +9 -21
  12. package/packages/backend/dist/services/node.js +4 -3
  13. package/packages/backend/dist/storage/GoogleDriveStorageService.d.ts +31 -9
  14. package/packages/backend/dist/storage/GoogleDriveWorkspaceService.d.ts +23 -6
  15. package/packages/backend/dist/storage/StorageAdapterFactory.d.ts +2 -2
  16. package/packages/backend/dist/storage/node.d.ts +0 -2
  17. package/packages/backend/dist/storage/node.js +5 -17
  18. package/packages/backend/dist/storage-workspace.js +4 -335
  19. package/packages/backend/dist/workspace/node.js +3 -2
  20. package/packages/backend/package.json +3 -7
  21. package/packages/client/dist/auth.d.ts +20 -1
  22. package/packages/client/dist/auth.js +13 -3
  23. package/packages/client/dist/chunk-5JMYSB7L.js +133 -0
  24. package/packages/client/dist/index.d.ts +1 -1
  25. package/packages/client/dist/index.js +13 -3
  26. package/packages/client/package.json +1 -1
  27. package/packages/state-graph/dist/browser.js +24 -24
  28. package/packages/state-graph/dist/index.js +24 -24
  29. package/packages/backend/dist/chunk-3FZSYSJC.js +0 -86
  30. package/packages/backend/dist/chunk-G7PPVOFP.js +0 -369
  31. package/packages/backend/dist/storage/GoogleDriveAdapter.d.ts +0 -41
  32. package/packages/backend/dist/storage/GoogleDriveOAuth.d.ts +0 -34
  33. package/packages/backend/dist/storage/googleDriveSdk.d.ts +0 -1
  34. package/packages/client/dist/chunk-B4WOPCRZ.js +0 -26
  35. package/packages/state-graph/dist/{chunk-YUJC367F.js → chunk-UKTICGGV.js} +3 -3
@@ -1,338 +1,7 @@
1
- // src/storage/GoogleDriveWorkspaceService.ts
2
- var GOOGLE_DRIVE_WORKSPACE_SCOPE = "https://www.googleapis.com/auth/drive";
3
- var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
4
- var GOOGLE_API_URL = "https://www.googleapis.com/drive/v3";
5
- var GOOGLE_UPLOAD_URL = "https://www.googleapis.com/upload/drive/v3";
6
- var FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
7
- function encodeBytes(parts) {
8
- const encoder = new TextEncoder();
9
- const buffers = parts.map((part) => typeof part === "string" ? encoder.encode(part) : part);
10
- const output = new Uint8Array(buffers.reduce((sum, item) => sum + item.length, 0));
11
- let offset = 0;
12
- for (const item of buffers) {
13
- output.set(item, offset);
14
- offset += item.length;
15
- }
16
- return output;
17
- }
18
- function quoteDriveQuery(value) {
19
- return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
20
- }
21
- async function parseJson(response) {
22
- return response.json().catch(() => ({}));
23
- }
24
- var GoogleDriveWorkspaceService = class _GoogleDriveWorkspaceService {
25
- options;
26
- fetcher;
27
- tokens;
28
- refreshPromise;
29
- constructor(options) {
30
- if (!options.clientId?.trim()) throw new Error("Google Drive OAuth client ID is required.");
31
- if (!options.redirectUri?.trim()) throw new Error("Google Drive OAuth redirect URI is required.");
32
- this.options = options;
33
- this.fetcher = options.fetcher || fetch;
34
- this.tokens = { ...options.tokens || { accessToken: "" } };
35
- }
36
- static createAuthorizationUrl(options, state, scopes = [GOOGLE_DRIVE_WORKSPACE_SCOPE]) {
37
- if (!options.clientId?.trim() || !options.redirectUri?.trim()) {
38
- throw new Error("Google Drive OAuth client ID and redirect URI are required.");
39
- }
40
- if (!state?.trim()) throw new Error("A non-empty Google Drive OAuth state is required.");
41
- const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");
42
- url.searchParams.set("client_id", options.clientId);
43
- url.searchParams.set("redirect_uri", options.redirectUri);
44
- url.searchParams.set("response_type", "code");
45
- url.searchParams.set("access_type", "offline");
46
- url.searchParams.set("prompt", "consent");
47
- url.searchParams.set("include_granted_scopes", "true");
48
- url.searchParams.set("scope", scopes.join(" "));
49
- url.searchParams.set("state", state);
50
- return url.toString();
51
- }
52
- static async exchangeAuthorizationCode(options, code, existingRefreshToken, codeVerifier) {
53
- if (!code?.trim()) throw new Error("Google Drive authorization code is required.");
54
- return _GoogleDriveWorkspaceService.requestTokens(
55
- options.fetcher || fetch,
56
- {
57
- client_id: options.clientId,
58
- client_secret: options.clientSecret || "",
59
- redirect_uri: options.redirectUri,
60
- grant_type: "authorization_code",
61
- code,
62
- ...codeVerifier ? { code_verifier: codeVerifier } : {}
63
- },
64
- existingRefreshToken
65
- );
66
- }
67
- static async requestTokens(fetcher, fields, existingRefreshToken) {
68
- const response = await fetcher(GOOGLE_TOKEN_URL, {
69
- method: "POST",
70
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
71
- body: new URLSearchParams(fields),
72
- cache: "no-store"
73
- });
74
- const data = await parseJson(response);
75
- if (!response.ok || typeof data.access_token !== "string" || !data.access_token) {
76
- const reason = typeof data.error === "string" ? data.error : "token_exchange_failed";
77
- throw new Error(`Google Drive OAuth token request failed (${reason}).`);
78
- }
79
- return {
80
- accessToken: data.access_token,
81
- ...data.refresh_token || existingRefreshToken ? { refreshToken: data.refresh_token || existingRefreshToken } : {},
82
- ...Number.isFinite(Number(data.expires_in)) ? { expiresAt: Date.now() + Number(data.expires_in) * 1e3 } : {},
83
- ...typeof data.token_type === "string" ? { tokenType: data.token_type } : {}
84
- };
85
- }
86
- async getAccessToken(forceRefresh = false) {
87
- const expiresSoon = Boolean(this.tokens.expiresAt && this.tokens.expiresAt <= Date.now() + 6e4);
88
- if (!forceRefresh && this.tokens.accessToken && !expiresSoon) return this.tokens.accessToken;
89
- if (!this.tokens.refreshToken || !this.options.clientSecret) {
90
- throw new Error("Google Drive credentials are missing or expired. Reconnect the Google account.");
91
- }
92
- if (!this.refreshPromise) {
93
- this.refreshPromise = _GoogleDriveWorkspaceService.requestTokens(
94
- this.fetcher,
95
- {
96
- client_id: this.options.clientId,
97
- client_secret: this.options.clientSecret,
98
- refresh_token: this.tokens.refreshToken,
99
- grant_type: "refresh_token"
100
- },
101
- this.tokens.refreshToken
102
- ).then(async (tokens) => {
103
- this.tokens = tokens;
104
- await this.options.persistTokens?.(tokens);
105
- return tokens;
106
- }).finally(() => {
107
- this.refreshPromise = void 0;
108
- });
109
- }
110
- const refreshed = await this.refreshPromise;
111
- return refreshed.accessToken;
112
- }
113
- async api(path, init = {}, retry = true) {
114
- const token = await this.getAccessToken();
115
- const response = await this.fetcher(
116
- path.startsWith("https://") ? path : `${GOOGLE_API_URL}/${path.replace(/^\/+/, "")}`,
117
- {
118
- ...init,
119
- headers: {
120
- ...init.headers || {},
121
- Authorization: `Bearer ${token}`
122
- },
123
- cache: "no-store"
124
- }
125
- );
126
- if (response.status === 401 && retry && this.tokens.refreshToken) {
127
- await this.getAccessToken(true);
128
- return this.api(path, init, false);
129
- }
130
- if (!response.ok) {
131
- const data = await parseJson(response);
132
- const message = typeof data.error?.message === "string" ? data.error.message : `Google Drive request failed with HTTP ${response.status}.`;
133
- throw new Error(message);
134
- }
135
- return response;
136
- }
137
- async listFiles(parentId, query = "trashed = false") {
138
- const files = [];
139
- let pageToken = "";
140
- do {
141
- const url = new URL(`${GOOGLE_API_URL}/files`);
142
- url.searchParams.set("q", `'${quoteDriveQuery(parentId)}' in parents and ${query}`);
143
- url.searchParams.set("fields", "nextPageToken,files(id,name,mimeType,size,modifiedTime,parents)");
144
- url.searchParams.set("pageSize", "1000");
145
- url.searchParams.set("supportsAllDrives", "true");
146
- url.searchParams.set("includeItemsFromAllDrives", "true");
147
- if (pageToken) url.searchParams.set("pageToken", pageToken);
148
- const data = await parseJson(await this.api(url.toString()));
149
- if (Array.isArray(data.files)) files.push(...data.files);
150
- pageToken = typeof data.nextPageToken === "string" ? data.nextPageToken : "";
151
- } while (pageToken);
152
- return files;
153
- }
154
- async findChild(parentId, name) {
155
- const matches = await this.listFiles(
156
- parentId,
157
- `name = '${quoteDriveQuery(name)}' and trashed = false`
158
- );
159
- return matches.find((item) => Boolean(item.id));
160
- }
161
- async resolveParent(relativePath, create = false) {
162
- let parent = this.options.rootFolderId || "root";
163
- for (const segment of relativePath.replace(/\\/g, "/").split("/").filter(Boolean)) {
164
- let child = await this.findChild(parent, segment);
165
- if (!child && create) {
166
- const data = await parseJson(await this.api("files", {
167
- method: "POST",
168
- headers: { "Content-Type": "application/json" },
169
- body: JSON.stringify({
170
- name: segment,
171
- mimeType: FOLDER_MIME_TYPE,
172
- parents: [parent]
173
- })
174
- }));
175
- child = data;
176
- }
177
- if (!child?.id || child.mimeType !== FOLDER_MIME_TYPE) {
178
- throw new Error(`Google Drive folder not found: ${segment}`);
179
- }
180
- parent = child.id;
181
- }
182
- return parent;
183
- }
184
- splitPath(value) {
185
- const normalized = value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
186
- const index = normalized.lastIndexOf("/");
187
- return index < 0 ? { parent: "", name: normalized } : { parent: normalized.slice(0, index), name: normalized.slice(index + 1) };
188
- }
189
- async getAccountIdentity() {
190
- const url = new URL(`${GOOGLE_API_URL}/about`);
191
- url.searchParams.set("fields", "user(permissionId,emailAddress)");
192
- const data = await parseJson(await this.api(url.toString()));
193
- const accountId = data.user?.permissionId || data.user?.emailAddress;
194
- if (typeof accountId !== "string" || !accountId) {
195
- throw new Error("Google Drive did not return a stable account identity.");
196
- }
197
- return {
198
- accountId,
199
- ...typeof data.user?.emailAddress === "string" ? { email: data.user.emailAddress } : {}
200
- };
201
- }
202
- async listFolders(parentFolderId = this.options.rootFolderId || "root") {
203
- const files = await this.listFiles(
204
- parentFolderId,
205
- `mimeType = '${FOLDER_MIME_TYPE}' and trashed = false`
206
- );
207
- return files.flatMap((file) => file.id && file.name ? [{
208
- id: file.id,
209
- name: file.name,
210
- mimeType: FOLDER_MIME_TYPE,
211
- parentIds: file.parents || [],
212
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
213
- }] : []);
214
- }
215
- async resolveFolder(folderId) {
216
- if (!folderId?.trim()) throw new Error("A Google Drive folder ID is required.");
217
- const url = new URL(`${GOOGLE_API_URL}/files/${encodeURIComponent(folderId)}`);
218
- url.searchParams.set("fields", "id,name,mimeType,parents,modifiedTime");
219
- url.searchParams.set("supportsAllDrives", "true");
220
- const file = await parseJson(await this.api(url.toString()));
221
- if (!file.id || !file.name || file.mimeType !== FOLDER_MIME_TYPE) {
222
- throw new Error("The selected Google Drive item is not a folder.");
223
- }
224
- return {
225
- id: file.id,
226
- name: file.name,
227
- mimeType: file.mimeType,
228
- parentIds: file.parents || [],
229
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
230
- };
231
- }
232
- async selectRootFolder(folderId) {
233
- const folder = await this.resolveFolder(folderId);
234
- this.options.rootFolderId = folder.id;
235
- return folder;
236
- }
237
- async read(path) {
238
- const { parent, name } = this.splitPath(path);
239
- if (!name) throw new Error("A Google Drive file path is required.");
240
- const parentId = await this.resolveParent(parent);
241
- const file = await this.findChild(parentId, name);
242
- if (!file?.id || file.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive file not found: ${path}`);
243
- const url = new URL(`${GOOGLE_API_URL}/files/${encodeURIComponent(file.id)}`);
244
- url.searchParams.set("alt", "media");
245
- return new Uint8Array(await (await this.api(url.toString())).arrayBuffer());
246
- }
247
- async write(path, bytes, contentType = "application/octet-stream") {
248
- const { parent, name } = this.splitPath(path);
249
- if (!name) throw new Error("A Google Drive file name is required.");
250
- const parentId = await this.resolveParent(parent, true);
251
- const existing = await this.findChild(parentId, name);
252
- if (existing?.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive path is a folder: ${path}`);
253
- const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
254
- const boundary = `kloks-drive-${crypto.randomUUID()}`;
255
- const body = encodeBytes([
256
- `--${boundary}\\r\\nContent-Type: application/json; charset=UTF-8\\r\\n\\r\\n`,
257
- JSON.stringify({
258
- name,
259
- mimeType: contentType,
260
- ...!existing?.id ? { parents: [parentId] } : {}
261
- }),
262
- `\\r\\n--${boundary}\\r\\nContent-Type: ${contentType}\\r\\n\\r\\n`,
263
- data,
264
- `\\r\\n--${boundary}--`
265
- ]);
266
- const endpoint = existing?.id ? `${GOOGLE_UPLOAD_URL}/files/${encodeURIComponent(existing.id)}?uploadType=multipart&supportsAllDrives=true` : `${GOOGLE_UPLOAD_URL}/files?uploadType=multipart&supportsAllDrives=true`;
267
- await this.api(endpoint, {
268
- method: existing?.id ? "PATCH" : "POST",
269
- headers: { "Content-Type": `multipart/related; boundary=${boundary}` },
270
- body: body.buffer
271
- });
272
- }
273
- async delete(path) {
274
- const { parent, name } = this.splitPath(path);
275
- const parentId = await this.resolveParent(parent);
276
- const file = await this.findChild(parentId, name);
277
- if (!file?.id) return;
278
- await this.api(`files/${encodeURIComponent(file.id)}?supportsAllDrives=true`, { method: "DELETE" });
279
- }
280
- async exists(path) {
281
- try {
282
- await this.stat(path);
283
- return true;
284
- } catch (error) {
285
- if (error instanceof Error && /not found|404/i.test(error.message)) return false;
286
- throw error;
287
- }
288
- }
289
- async list(path = "") {
290
- const parentId = await this.resolveParent(path);
291
- const files = await this.listFiles(parentId);
292
- return files.flatMap((file) => file.name ? [{
293
- path: path ? `${path.replace(/\/+$/, "")}/${file.name}` : file.name,
294
- size: Number(file.size || 0),
295
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
296
- }] : []);
297
- }
298
- async stat(path) {
299
- const { parent, name } = this.splitPath(path);
300
- const parentId = await this.resolveParent(parent);
301
- const file = await this.findChild(parentId, name);
302
- if (!file?.id) throw new Error(`Google Drive file not found: ${path}`);
303
- return {
304
- path,
305
- size: Number(file.size || 0),
306
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
307
- };
308
- }
309
- async mkdir(path) {
310
- await this.resolveParent(path, true);
311
- }
312
- async testConnection() {
313
- const started = Date.now();
314
- try {
315
- const identity = await this.getAccountIdentity();
316
- return {
317
- ok: true,
318
- latencyMs: Date.now() - started,
319
- details: { accountId: identity.accountId, email: identity.email, rootFolderId: this.options.rootFolderId || "root" }
320
- };
321
- } catch (error) {
322
- return {
323
- ok: false,
324
- latencyMs: Date.now() - started,
325
- error: error instanceof Error ? error.message : "Google Drive connection failed."
326
- };
327
- }
328
- }
329
- getConnectionMetadata() {
330
- return {
331
- provider: "google_drive",
332
- ...this.options.rootFolderId ? { googleRootFolderId: this.options.rootFolderId } : {}
333
- };
334
- }
335
- };
1
+ import {
2
+ GOOGLE_DRIVE_WORKSPACE_SCOPE,
3
+ GoogleDriveWorkspaceService
4
+ } from "./chunk-OWMQLML7.js";
336
5
  export {
337
6
  GOOGLE_DRIVE_WORKSPACE_SCOPE,
338
7
  GoogleDriveWorkspaceService
@@ -5,7 +5,7 @@ import {
5
5
  WorkspaceFS,
6
6
  remoteWorkspaceService,
7
7
  workingWorkspaceService
8
- } from "../chunk-NGEB3CF5.js";
8
+ } from "../chunk-Z6G32NQQ.js";
9
9
  import {
10
10
  WorkspaceCloneSyncEngine
11
11
  } from "../chunk-NY2SQOXI.js";
@@ -14,9 +14,10 @@ import {
14
14
  sanitizeWorkspaceName
15
15
  } from "../chunk-FZKBTF34.js";
16
16
  import "../chunk-JGUWYVOL.js";
17
- import "../chunk-G7PPVOFP.js";
17
+ import "../chunk-OQRQCDS6.js";
18
18
  import "../chunk-JCMB7BIM.js";
19
19
  import "../chunk-5F5V7NAG.js";
20
+ import "../chunk-OWMQLML7.js";
20
21
  export {
21
22
  RemoteWorkspaceService,
22
23
  SyncEngine,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kloks/backend",
3
3
  "version": "1.2.0",
4
- "description": "Kloks Backend Services — Auth, Storage, Workspace, Control Plane, API, Connectivity & Execution built on KrnlTS",
4
+ "description": "Kloks Backend Services \u2014 Auth, Storage, Workspace, Control Plane, API, Connectivity & Execution built on KrnlTS",
5
5
  "type": "module",
6
6
  "private": false,
7
7
  "publishConfig": {
@@ -145,7 +145,7 @@
145
145
  "clean": "rm -rf dist"
146
146
  },
147
147
  "dependencies": {
148
- "@dinilmusick/gutts": "^2.0.2",
148
+ "@dinilmusick/gutts": "^2.1.0",
149
149
  "@kloks/functions": "workspace:*",
150
150
  "@kloks/state-graph": "workspace:*",
151
151
  "@webcontainer/api": "^1.6.4",
@@ -157,8 +157,7 @@
157
157
  "react": "^18.0.0 || ^19.0.0",
158
158
  "zod": "^3.22.0",
159
159
  "@ultrst-armada/krnl": "^1.0.9",
160
- "@aws-sdk/client-s3": "^3.1164.0",
161
- "googleapis": "^189.0.0"
160
+ "@aws-sdk/client-s3": "^3.1164.0"
162
161
  },
163
162
  "peerDependenciesMeta": {
164
163
  "@supabase/supabase-js": {
@@ -178,9 +177,6 @@
178
177
  },
179
178
  "@aws-sdk/client-s3": {
180
179
  "optional": true
181
- },
182
- "googleapis": {
183
- "optional": true
184
180
  }
185
181
  },
186
182
  "devDependencies": {
@@ -1,6 +1,20 @@
1
1
  import { DeploymentEnvironment } from '@dinilmusick/gutts/auth';
2
2
  export { LuthAuthClient as CanonicalAuthClient, DEFAULT_LUTH_URL, DeploymentEnvironment, EmailSignInCredentials, EmailSignUpData, GoogleSignInOptions, LuthAuthClient, LuthAuthClientConfig, LuthAuthError, LuthAuthTokenStore, LuthSession, LuthSessionResult, LuthUser, RegisterApplicationResult, createLuthAuthClient as createCanonicalAuthClient, createLuthAuthClient, hydrateLuthTokenFromUrl, resolveClientEnvironment, resolveClientOrigin } from '@dinilmusick/gutts/auth';
3
3
 
4
+ interface LuthPrincipal {
5
+ id: string;
6
+ email: string;
7
+ name: string;
8
+ role: string;
9
+ }
10
+ declare const CANONICAL_PUBLIC_ROUTES: (string | RegExp)[];
11
+ declare function extractLuthToken(request: Request): string;
12
+ declare function isPublicRoute(pathname: string, extraPublicRoutes?: (string | RegExp)[]): boolean;
13
+ declare function verifyLuthRequest(request: Request, options?: {
14
+ luthUrl?: string;
15
+ extraPublicRoutes?: (string | RegExp)[];
16
+ }): Promise<LuthPrincipal | Response | null>;
17
+
4
18
  interface LuthDeploymentRecord {
5
19
  id: string;
6
20
  url: string;
@@ -11,4 +25,9 @@ interface LuthDeploymentRecord {
11
25
  priority?: number;
12
26
  }
13
27
 
14
- export type { LuthDeploymentRecord };
28
+ /** Creates an authenticated fetch function that automatically injects Luth bearer headers and credentials: 'include'. */
29
+ declare function createUniversalAuthFetch(authClient: {
30
+ getAuthHeaders: () => HeadersInit;
31
+ }): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
32
+
33
+ export { CANONICAL_PUBLIC_ROUTES, type LuthDeploymentRecord, type LuthPrincipal, createUniversalAuthFetch, extractLuthToken, isPublicRoute, verifyLuthRequest };
@@ -1,22 +1,32 @@
1
1
  import {
2
+ CANONICAL_PUBLIC_ROUTES,
2
3
  DEFAULT_LUTH_URL,
3
4
  LuthAuthClient,
4
5
  LuthAuthClient2,
5
6
  LuthAuthError,
6
7
  createLuthAuthClient,
7
8
  createLuthAuthClient2,
9
+ createUniversalAuthFetch,
10
+ extractLuthToken,
8
11
  hydrateLuthTokenFromUrl,
12
+ isPublicRoute,
9
13
  resolveClientEnvironment,
10
- resolveClientOrigin
11
- } from "./chunk-B4WOPCRZ.js";
14
+ resolveClientOrigin,
15
+ verifyLuthRequest
16
+ } from "./chunk-5JMYSB7L.js";
12
17
  export {
18
+ CANONICAL_PUBLIC_ROUTES,
13
19
  LuthAuthClient2 as CanonicalAuthClient,
14
20
  DEFAULT_LUTH_URL,
15
21
  LuthAuthClient,
16
22
  LuthAuthError,
17
23
  createLuthAuthClient2 as createCanonicalAuthClient,
18
24
  createLuthAuthClient,
25
+ createUniversalAuthFetch,
26
+ extractLuthToken,
19
27
  hydrateLuthTokenFromUrl,
28
+ isPublicRoute,
20
29
  resolveClientEnvironment,
21
- resolveClientOrigin
30
+ resolveClientOrigin,
31
+ verifyLuthRequest
22
32
  };
@@ -0,0 +1,133 @@
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
+ } from "@dinilmusick/gutts/auth";
11
+ import {
12
+ LuthAuthClient as LuthAuthClient2,
13
+ createLuthAuthClient as createLuthAuthClient2
14
+ } from "@dinilmusick/gutts/auth";
15
+
16
+ // src/UniversalLuthGuard.ts
17
+ import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
18
+ var CANONICAL_PUBLIC_ROUTES = [
19
+ "/health",
20
+ "/api/health",
21
+ "/api/status",
22
+ "/api/auth",
23
+ /^\/api(\/v1)?\/auth(\/.*)?$/,
24
+ /^\/api(\/v1)?\/database\/status$/,
25
+ /^\/api(\/v1)?\/guest(\/.*)?$/,
26
+ /^\/api(\/v1)?\/discovery(\/.*)?$/,
27
+ /^\/api(\/v1)?\/spec(\/.*)?$/
28
+ ];
29
+ var SESSION_CACHE_TTL_MS = 6e4;
30
+ var sessionCache = /* @__PURE__ */ new Map();
31
+ function extractLuthToken(request) {
32
+ const authorization = request.headers.get("authorization") || "";
33
+ const bearer = /^Bearer\s+([^\s]+)$/i.exec(authorization.trim());
34
+ if (bearer) return bearer[1];
35
+ const apiKey = request.headers.get("x-api-key")?.trim();
36
+ if (apiKey) return apiKey;
37
+ const cookieHeader = request.headers.get("cookie") || "";
38
+ const cookies = cookieHeader.split(";").map((c) => c.trim());
39
+ for (const prefix of ["better-auth.session_token=", "__Secure-better-auth.session_token=", "luth_session="]) {
40
+ const found = cookies.find((c) => c.startsWith(prefix));
41
+ if (found) {
42
+ try {
43
+ return decodeURIComponent(found.slice(prefix.length));
44
+ } catch {
45
+ return "";
46
+ }
47
+ }
48
+ }
49
+ return "";
50
+ }
51
+ function isPublicRoute(pathname, extraPublicRoutes) {
52
+ const routes = extraPublicRoutes ? [...CANONICAL_PUBLIC_ROUTES, ...extraPublicRoutes] : CANONICAL_PUBLIC_ROUTES;
53
+ return routes.some((route) => typeof route === "string" ? pathname === route : route.test(pathname));
54
+ }
55
+ async function verifyLuthRequest(request, options) {
56
+ const url = new URL(request.url);
57
+ if (request.method === "OPTIONS") return null;
58
+ if (isPublicRoute(url.pathname, options?.extraPublicRoutes)) return null;
59
+ const isMcp = url.pathname.includes("/mcp");
60
+ const token = extractLuthToken(request);
61
+ if (!token) {
62
+ 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." };
63
+ return new Response(JSON.stringify(payload), { status: 401, headers: { "Content-Type": "application/json" } });
64
+ }
65
+ const now = Date.now();
66
+ const cached = sessionCache.get(token);
67
+ if (cached && cached.expiresAt > now) {
68
+ return cached.principal;
69
+ }
70
+ try {
71
+ const luthUrl = options?.luthUrl || DEFAULT_LUTH_URL;
72
+ const res = await fetch(`${luthUrl}/api/session`, {
73
+ headers: {
74
+ authorization: `Bearer ${token}`,
75
+ cookie: request.headers.get("cookie") || "",
76
+ origin: url.origin
77
+ }
78
+ });
79
+ if (!res.ok) {
80
+ 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." };
81
+ return new Response(JSON.stringify(payload), { status: 401, headers: { "Content-Type": "application/json" } });
82
+ }
83
+ const data = await res.json();
84
+ const user = data?.user || (data?.authenticated ? data?.session?.user : null);
85
+ if (!user || !user.id) {
86
+ 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." };
87
+ return new Response(JSON.stringify(payload), { status: 401, headers: { "Content-Type": "application/json" } });
88
+ }
89
+ const principal = {
90
+ id: String(user.id),
91
+ email: String(user.email || ""),
92
+ name: String(user.name || user.email?.split("@")[0] || ""),
93
+ role: String(user.role || "user")
94
+ };
95
+ sessionCache.set(token, { principal, expiresAt: now + SESSION_CACHE_TTL_MS });
96
+ return principal;
97
+ } catch {
98
+ 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." };
99
+ return new Response(JSON.stringify(payload), { status: 503, headers: { "Content-Type": "application/json" } });
100
+ }
101
+ }
102
+
103
+ // src/auth.ts
104
+ function createUniversalAuthFetch(authClient) {
105
+ return async function universalAuthFetch(input, init = {}) {
106
+ const headers = new Headers(init.headers);
107
+ new Headers(authClient.getAuthHeaders()).forEach((value, key) => {
108
+ if (!headers.has(key)) headers.set(key, value);
109
+ });
110
+ return fetch(input, {
111
+ ...init,
112
+ headers,
113
+ credentials: init.credentials ?? "include"
114
+ });
115
+ };
116
+ }
117
+
118
+ export {
119
+ CANONICAL_PUBLIC_ROUTES,
120
+ extractLuthToken,
121
+ isPublicRoute,
122
+ verifyLuthRequest,
123
+ createUniversalAuthFetch,
124
+ LuthAuthClient,
125
+ createLuthAuthClient,
126
+ hydrateLuthTokenFromUrl,
127
+ resolveClientOrigin,
128
+ resolveClientEnvironment,
129
+ LuthAuthError,
130
+ DEFAULT_LUTH_URL2 as DEFAULT_LUTH_URL,
131
+ LuthAuthClient2,
132
+ createLuthAuthClient2
133
+ };
@@ -1,4 +1,4 @@
1
- export { LuthDeploymentRecord } from './auth.js';
1
+ export { CANONICAL_PUBLIC_ROUTES, LuthDeploymentRecord, LuthPrincipal, createUniversalAuthFetch, extractLuthToken, isPublicRoute, verifyLuthRequest } from './auth.js';
2
2
  export { LuthAuthClient as CanonicalAuthClient, DEFAULT_LUTH_URL, DeploymentEnvironment, EmailSignInCredentials, EmailSignUpData, GoogleSignInOptions, LuthAuthClient, LuthAuthClientConfig, LuthAuthError, LuthAuthTokenStore, LuthSession, LuthSessionResult, LuthUser, RegisterApplicationResult, createLuthAuthClient as createCanonicalAuthClient, createLuthAuthClient, hydrateLuthTokenFromUrl, resolveClientEnvironment, resolveClientOrigin } from '@dinilmusick/gutts/auth';
3
3
 
4
4
  /**
@@ -1,14 +1,19 @@
1
1
  import {
2
+ CANONICAL_PUBLIC_ROUTES,
2
3
  DEFAULT_LUTH_URL,
3
4
  LuthAuthClient,
4
5
  LuthAuthClient2,
5
6
  LuthAuthError,
6
7
  createLuthAuthClient,
7
8
  createLuthAuthClient2,
9
+ createUniversalAuthFetch,
10
+ extractLuthToken,
8
11
  hydrateLuthTokenFromUrl,
12
+ isPublicRoute,
9
13
  resolveClientEnvironment,
10
- resolveClientOrigin
11
- } from "./chunk-B4WOPCRZ.js";
14
+ resolveClientOrigin,
15
+ verifyLuthRequest
16
+ } from "./chunk-5JMYSB7L.js";
12
17
 
13
18
  // src/browserExecutionClient.ts
14
19
  var BrowserExecutionClient = class {
@@ -184,6 +189,7 @@ var OPFSWorkspaceStorage = class {
184
189
  };
185
190
  export {
186
191
  BrowserExecutionClient,
192
+ CANONICAL_PUBLIC_ROUTES,
187
193
  LuthAuthClient2 as CanonicalAuthClient,
188
194
  DEFAULT_LUTH_URL,
189
195
  LuthAuthClient,
@@ -193,7 +199,11 @@ export {
193
199
  createBrowserExecutionClient,
194
200
  createLuthAuthClient2 as createCanonicalAuthClient,
195
201
  createLuthAuthClient,
202
+ createUniversalAuthFetch,
203
+ extractLuthToken,
196
204
  hydrateLuthTokenFromUrl,
205
+ isPublicRoute,
197
206
  resolveClientEnvironment,
198
- resolveClientOrigin
207
+ resolveClientOrigin,
208
+ verifyLuthRequest
199
209
  };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kloks/client",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Kloks Browser-Safe Execution Client & Shared Contracts with Zero Server Closure",
5
5
  "type": "module",
6
6
  "private": false,