@ultrst-armada/kloks 0.0.0-stage → 1.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 (109) hide show
  1. package/README.md +2 -3
  2. package/index.d.ts +5 -0
  3. package/index.js +5 -0
  4. package/package.json +122 -4
  5. package/packages/audio-midi/dist/audioClipEngine-BOT33JKI.js +9 -0
  6. package/packages/audio-midi/dist/audioInputManager-BLDGGLAR.js +12 -0
  7. package/packages/audio-midi/dist/chunk-3GRGELA4.js +2533 -0
  8. package/packages/audio-midi/dist/chunk-N55BWOC6.js +439 -0
  9. package/packages/audio-midi/dist/index.d.ts +988 -0
  10. package/packages/audio-midi/dist/index.js +2591 -0
  11. package/packages/audio-midi/kloks.manifest.json +69 -0
  12. package/packages/audio-midi/package.json +33 -0
  13. package/packages/backend/dist/BaseAccountProvider-DduKf5HG.d.ts +66 -0
  14. package/packages/backend/dist/BaseStorageAdapter-tosOoSUg.d.ts +67 -0
  15. package/packages/backend/dist/IdempotencyManager-B5MjK871.d.ts +16 -0
  16. package/packages/backend/dist/WebSocketTransport-CxUzUfwl.d.ts +255 -0
  17. package/packages/backend/dist/api/index.d.ts +32 -0
  18. package/packages/backend/dist/api/index.js +12 -0
  19. package/packages/backend/dist/auth/index.d.ts +56 -0
  20. package/packages/backend/dist/auth/index.js +22 -0
  21. package/packages/backend/dist/chunk-25Y7AVTP.js +55 -0
  22. package/packages/backend/dist/chunk-3EPY34R6.js +67 -0
  23. package/packages/backend/dist/chunk-4QEMALXF.js +90 -0
  24. package/packages/backend/dist/chunk-4ZFXEFOE.js +265 -0
  25. package/packages/backend/dist/chunk-53WQNION.js +278 -0
  26. package/packages/backend/dist/chunk-5MUQSPG4.js +149 -0
  27. package/packages/backend/dist/chunk-FZKBTF34.js +15 -0
  28. package/packages/backend/dist/chunk-G3ZOSXUR.js +31 -0
  29. package/packages/backend/dist/chunk-J2J24JVC.js +731 -0
  30. package/packages/backend/dist/chunk-KPUGS64G.js +221 -0
  31. package/packages/backend/dist/chunk-KTLD7Z4L.js +124 -0
  32. package/packages/backend/dist/chunk-LS3HWJBX.js +0 -0
  33. package/packages/backend/dist/chunk-MN54ZIKZ.js +336 -0
  34. package/packages/backend/dist/chunk-NIP22V2G.js +828 -0
  35. package/packages/backend/dist/chunk-QGHDJGYS.js +92 -0
  36. package/packages/backend/dist/chunk-RCCQ7IRM.js +139 -0
  37. package/packages/backend/dist/chunk-T3NYNBDC.js +618 -0
  38. package/packages/backend/dist/chunk-TWCEVES2.js +93 -0
  39. package/packages/backend/dist/chunk-UPFKBBQI.js +138 -0
  40. package/packages/backend/dist/chunk-VQEFULWT.js +88 -0
  41. package/packages/backend/dist/client/index.d.ts +22 -0
  42. package/packages/backend/dist/client/index.js +30 -0
  43. package/packages/backend/dist/connectivity/index.d.ts +237 -0
  44. package/packages/backend/dist/connectivity/index.js +50 -0
  45. package/packages/backend/dist/control-plane/index.d.ts +56 -0
  46. package/packages/backend/dist/control-plane/index.js +16 -0
  47. package/packages/backend/dist/execution/index.d.ts +124 -0
  48. package/packages/backend/dist/execution/index.js +20 -0
  49. package/packages/backend/dist/index.d.ts +692 -0
  50. package/packages/backend/dist/index.js +3299 -0
  51. package/packages/backend/dist/krnl-services.d.ts +82 -0
  52. package/packages/backend/dist/krnl-services.js +38 -0
  53. package/packages/backend/dist/services/index.d.ts +66 -0
  54. package/packages/backend/dist/services/index.js +17 -0
  55. package/packages/backend/dist/srkl/index.d.ts +191 -0
  56. package/packages/backend/dist/srkl/index.js +19 -0
  57. package/packages/backend/dist/storage/index.d.ts +124 -0
  58. package/packages/backend/dist/storage/index.js +43 -0
  59. package/packages/backend/dist/types-BERZJ93O.d.ts +110 -0
  60. package/packages/backend/dist/workspace/index.d.ts +111 -0
  61. package/packages/backend/dist/workspace/index.js +16 -0
  62. package/packages/backend/kloks.manifest.json +195 -0
  63. package/packages/backend/package.json +125 -0
  64. package/packages/functions/dist/index.d.ts +388 -0
  65. package/packages/functions/dist/index.js +1201 -0
  66. package/packages/functions/kloks.manifest.json +20 -0
  67. package/packages/functions/package.json +33 -0
  68. package/packages/orchestrations/dist/index.d.ts +53 -0
  69. package/packages/orchestrations/dist/index.js +211 -0
  70. package/packages/orchestrations/kloks.manifest.json +23 -0
  71. package/packages/orchestrations/package.json +35 -0
  72. package/packages/services/dist/index.d.ts +334 -0
  73. package/packages/services/dist/index.js +1597 -0
  74. package/packages/services/kloks.manifest.json +59 -0
  75. package/packages/services/package.json +33 -0
  76. package/packages/state-graph/dist/BaseConnection-CMRrL6Fe.d.ts +43 -0
  77. package/packages/state-graph/dist/BaseGraph-Bl2f7Pqx.d.ts +98 -0
  78. package/packages/state-graph/dist/BaseNode-1HCEqmap.d.ts +123 -0
  79. package/packages/state-graph/dist/CompatibilityMatrix-DX307_vS.d.ts +29 -0
  80. package/packages/state-graph/dist/TraceEngine-CJVpUb80.d.ts +18 -0
  81. package/packages/state-graph/dist/chunk-3RG5ZIWI.js +10 -0
  82. package/packages/state-graph/dist/chunk-4UVGXFEM.js +465 -0
  83. package/packages/state-graph/dist/chunk-ISFNY7EZ.js +61 -0
  84. package/packages/state-graph/dist/chunk-KG6QYS26.js +167 -0
  85. package/packages/state-graph/dist/chunk-OV4JVTNY.js +147 -0
  86. package/packages/state-graph/dist/chunk-OYN4ZEZC.js +54 -0
  87. package/packages/state-graph/dist/chunk-Q5I42UX7.js +0 -0
  88. package/packages/state-graph/dist/chunk-QN74PLMF.js +241 -0
  89. package/packages/state-graph/dist/chunk-S22PMERU.js +223 -0
  90. package/packages/state-graph/dist/chunk-SHIBCPGQ.js +269 -0
  91. package/packages/state-graph/dist/chunk-YTWCH6P2.js +109 -0
  92. package/packages/state-graph/dist/chunk-ZTHBPV24.js +267 -0
  93. package/packages/state-graph/dist/domain/index.d.ts +117 -0
  94. package/packages/state-graph/dist/domain/index.js +45 -0
  95. package/packages/state-graph/dist/execution/index.d.ts +152 -0
  96. package/packages/state-graph/dist/execution/index.js +16 -0
  97. package/packages/state-graph/dist/index-CiekWEH3.d.ts +272 -0
  98. package/packages/state-graph/dist/index.d.ts +3170 -0
  99. package/packages/state-graph/dist/index.js +9574 -0
  100. package/packages/state-graph/dist/rules/index.d.ts +86 -0
  101. package/packages/state-graph/dist/rules/index.js +17 -0
  102. package/packages/state-graph/dist/spatial/index.d.ts +55 -0
  103. package/packages/state-graph/dist/spatial/index.js +21 -0
  104. package/packages/state-graph/dist/state/index.d.ts +109 -0
  105. package/packages/state-graph/dist/state/index.js +20 -0
  106. package/packages/state-graph/dist/store/index.d.ts +6 -0
  107. package/packages/state-graph/dist/store/index.js +15 -0
  108. package/packages/state-graph/kloks.manifest.json +40 -0
  109. package/packages/state-graph/package.json +73 -0
@@ -0,0 +1,67 @@
1
+ // src/connectivity/IdempotencyManager.ts
2
+ var IdempotencyManager = class {
3
+ inFlight = /* @__PURE__ */ new Map();
4
+ completedCache = /* @__PURE__ */ new Map();
5
+ ttlMs;
6
+ constructor(ttlMs = 6e4) {
7
+ this.ttlMs = ttlMs;
8
+ }
9
+ async executeIdempotent(idempotencyKey, operation) {
10
+ const cached = this.completedCache.get(idempotencyKey);
11
+ if (cached) {
12
+ if (Date.now() - cached.timestamp < this.ttlMs) {
13
+ if (cached.status === "completed") {
14
+ return cached.result;
15
+ }
16
+ throw new Error(cached.error || "[IdempotencyManager] Previous execution failed.");
17
+ } else {
18
+ this.completedCache.delete(idempotencyKey);
19
+ }
20
+ }
21
+ const existingFlight = this.inFlight.get(idempotencyKey);
22
+ if (existingFlight) {
23
+ return await existingFlight;
24
+ }
25
+ const executionPromise = (async () => {
26
+ try {
27
+ const result = await operation();
28
+ this.completedCache.set(idempotencyKey, {
29
+ status: "completed",
30
+ result,
31
+ timestamp: Date.now()
32
+ });
33
+ return result;
34
+ } catch (err) {
35
+ this.completedCache.set(idempotencyKey, {
36
+ status: "failed",
37
+ error: err?.message || String(err),
38
+ timestamp: Date.now()
39
+ });
40
+ throw err;
41
+ } finally {
42
+ this.inFlight.delete(idempotencyKey);
43
+ }
44
+ })();
45
+ this.inFlight.set(idempotencyKey, executionPromise);
46
+ return await executionPromise;
47
+ }
48
+ has(idempotencyKey) {
49
+ return this.inFlight.has(idempotencyKey) || this.completedCache.has(idempotencyKey);
50
+ }
51
+ prune() {
52
+ const now = Date.now();
53
+ for (const [key, entry] of this.completedCache.entries()) {
54
+ if (now - entry.timestamp > this.ttlMs) {
55
+ this.completedCache.delete(key);
56
+ }
57
+ }
58
+ }
59
+ clear() {
60
+ this.inFlight.clear();
61
+ this.completedCache.clear();
62
+ }
63
+ };
64
+
65
+ export {
66
+ IdempotencyManager
67
+ };
@@ -0,0 +1,90 @@
1
+ // src/storage/B2DirectClient.ts
2
+ var authCache = /* @__PURE__ */ new Map();
3
+ async function authorizeB2(keyId, applicationKey) {
4
+ const cacheKey = `${keyId}:${applicationKey}`;
5
+ const cached = authCache.get(cacheKey);
6
+ if (cached && Date.now() < cached.expiresAt) return cached.token;
7
+ const basic = btoa(`${keyId.trim()}:${applicationKey.trim()}`);
8
+ const res = await fetch("https://api.backblazeb2.com/b2api/v2/b2_authorize_account", {
9
+ headers: { Authorization: `Basic ${basic}` }
10
+ });
11
+ if (!res.ok) throw new Error(`B2 Authorization failed: ${res.status} ${await res.text()}`);
12
+ const data = await res.json();
13
+ const token = {
14
+ authorizationToken: data.authorizationToken,
15
+ apiUrl: data.apiUrl,
16
+ downloadUrl: data.downloadUrl,
17
+ accountId: data.accountId
18
+ };
19
+ authCache.set(cacheKey, { token, expiresAt: Date.now() + 20 * 60 * 1e3 });
20
+ return token;
21
+ }
22
+ async function b2ListBuckets(keyId, applicationKey) {
23
+ const auth = await authorizeB2(keyId, applicationKey);
24
+ const res = await fetch(`${auth.apiUrl}/b2api/v2/b2_list_buckets`, {
25
+ method: "POST",
26
+ headers: { Authorization: auth.authorizationToken, "Content-Type": "application/json" },
27
+ body: JSON.stringify({ accountId: auth.accountId })
28
+ });
29
+ if (!res.ok) throw new Error(`B2 list buckets failed: ${res.status}`);
30
+ const data = await res.json();
31
+ return data.buckets || [];
32
+ }
33
+ async function b2ListFileNames(keyId, applicationKey, bucketName, prefix = "") {
34
+ const auth = await authorizeB2(keyId, applicationKey);
35
+ const buckets = await b2ListBuckets(keyId, applicationKey);
36
+ const bucket = buckets.find((b) => b.bucketName === bucketName);
37
+ if (!bucket) return [];
38
+ const res = await fetch(`${auth.apiUrl}/b2api/v2/b2_list_file_names`, {
39
+ method: "POST",
40
+ headers: { Authorization: auth.authorizationToken, "Content-Type": "application/json" },
41
+ body: JSON.stringify({ bucketId: bucket.bucketId, prefix, maxFileCount: 1e3 })
42
+ });
43
+ if (!res.ok) return [];
44
+ const data = await res.json();
45
+ return data.files || [];
46
+ }
47
+ async function b2UploadFile(keyId, applicationKey, bucketName, fileName, content, contentType = "application/json") {
48
+ const auth = await authorizeB2(keyId, applicationKey);
49
+ const buckets = await b2ListBuckets(keyId, applicationKey);
50
+ const bucket = buckets.find((b) => b.bucketName === bucketName);
51
+ if (!bucket) throw new Error(`Bucket ${bucketName} not found`);
52
+ const urlRes = await fetch(`${auth.apiUrl}/b2api/v2/b2_get_upload_url`, {
53
+ method: "POST",
54
+ headers: { Authorization: auth.authorizationToken, "Content-Type": "application/json" },
55
+ body: JSON.stringify({ bucketId: bucket.bucketId })
56
+ });
57
+ if (!urlRes.ok) throw new Error(`B2 get upload url failed: ${urlRes.status}`);
58
+ const { uploadUrl, authorizationToken } = await urlRes.json();
59
+ const raw = typeof content === "string" ? new TextEncoder().encode(content) : content;
60
+ const hashBuffer = await crypto.subtle.digest("SHA-1", raw);
61
+ const sha1 = Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
62
+ const upRes = await fetch(uploadUrl, {
63
+ method: "POST",
64
+ headers: {
65
+ Authorization: authorizationToken,
66
+ "X-Bz-File-Name": encodeURIComponent(fileName).replace(/%2F/g, "/"),
67
+ "Content-Type": contentType,
68
+ "Content-Length": String(raw.length),
69
+ "X-Bz-Content-Sha1": sha1
70
+ },
71
+ body: raw
72
+ });
73
+ if (!upRes.ok) throw new Error(`B2 upload failed: ${upRes.status} ${await upRes.text()}`);
74
+ return await upRes.json();
75
+ }
76
+ async function b2DownloadFile(keyId, applicationKey, bucketName, fileName) {
77
+ const auth = await authorizeB2(keyId, applicationKey);
78
+ const url = `${auth.downloadUrl}/file/${bucketName}/${encodeURI(fileName)}`;
79
+ const res = await fetch(url, { headers: { Authorization: auth.authorizationToken } });
80
+ if (!res.ok) return null;
81
+ return new Uint8Array(await res.arrayBuffer());
82
+ }
83
+
84
+ export {
85
+ authorizeB2,
86
+ b2ListBuckets,
87
+ b2ListFileNames,
88
+ b2UploadFile,
89
+ b2DownloadFile
90
+ };
@@ -0,0 +1,265 @@
1
+ import {
2
+ RateLimiter,
3
+ SessionManager
4
+ } from "./chunk-25Y7AVTP.js";
5
+
6
+ // src/auth/PasswordHasher.ts
7
+ var bcrypt = null;
8
+ try {
9
+ bcrypt = (await import("bcryptjs")).default;
10
+ } catch (e) {
11
+ console.warn("[Skipo] bcryptjs not installed. Using fallback hashing (DEV ONLY).");
12
+ }
13
+ var PasswordHasher = class {
14
+ static async hash(password, saltRounds = 10) {
15
+ if (bcrypt) {
16
+ return bcrypt.hash(password, saltRounds);
17
+ }
18
+ return `fallback_hash_${Buffer.from(password).toString("base64")}`;
19
+ }
20
+ static async verify(password, hash) {
21
+ if (bcrypt) {
22
+ return bcrypt.compare(password, hash);
23
+ }
24
+ return hash === `fallback_hash_${Buffer.from(password).toString("base64")}`;
25
+ }
26
+ };
27
+
28
+ // src/auth/BaseAccountProvider.ts
29
+ import { SkipoBase } from "@ultrst-armada/kloks/functions";
30
+ var BaseAccountProvider = class extends SkipoBase {
31
+ rateLimiter = new RateLimiter();
32
+ sessionManager = new SessionManager();
33
+ async authenticate(credentials) {
34
+ this.rateLimiter.check(credentials.email);
35
+ const user = await this.findUserByEmail(credentials.email);
36
+ if (!user) {
37
+ throw new Error("Invalid credentials.");
38
+ }
39
+ const isValid = await PasswordHasher.verify(credentials.password, user.passwordHash);
40
+ if (!isValid) {
41
+ throw new Error("Invalid credentials.");
42
+ }
43
+ this.rateLimiter.reset(credentials.email);
44
+ return this.sessionManager.createSession(user.id, user.role);
45
+ }
46
+ async signup(input) {
47
+ const existing = await this.findUserByEmail(input.email);
48
+ if (existing) {
49
+ throw new Error("Email already in use.");
50
+ }
51
+ const passwordHash = await PasswordHasher.hash(input.password);
52
+ return this.createUser({
53
+ email: input.email,
54
+ passwordHash,
55
+ role: "user",
56
+ // Enforce user role
57
+ displayName: input.displayName
58
+ });
59
+ }
60
+ async verifySession(token) {
61
+ if (!token) return null;
62
+ const parts = token.split("::");
63
+ if (parts.length >= 4 && parts[0] === "sess") {
64
+ const userId = parts[1];
65
+ const user = await this.findUserById(userId);
66
+ if (user) {
67
+ const issueTime = parseInt(parts[2], 10);
68
+ if (Date.now() - issueTime < 864e5) {
69
+ return {
70
+ token,
71
+ userId: user.id,
72
+ role: user.role,
73
+ expiresAt: issueTime + 864e5
74
+ };
75
+ }
76
+ }
77
+ }
78
+ return null;
79
+ }
80
+ };
81
+
82
+ // src/auth/LocalAccountProvider.ts
83
+ import { promises as fs } from "fs";
84
+ import path from "path";
85
+ var LocalAccountProvider = class extends BaseAccountProvider {
86
+ filePath;
87
+ users = /* @__PURE__ */ new Map();
88
+ isLoaded = false;
89
+ constructor(filePath = ".skipo/accounts.json") {
90
+ super();
91
+ this.filePath = path.resolve(filePath);
92
+ }
93
+ async load() {
94
+ if (this.isLoaded) return;
95
+ try {
96
+ await fs.mkdir(path.dirname(this.filePath), { recursive: true });
97
+ const data = await fs.readFile(this.filePath, "utf-8");
98
+ const parsed = JSON.parse(data);
99
+ for (const [id, user] of Object.entries(parsed)) {
100
+ this.users.set(id, user);
101
+ }
102
+ } catch (e) {
103
+ if (e.code !== "ENOENT") {
104
+ throw e;
105
+ }
106
+ }
107
+ this.isLoaded = true;
108
+ }
109
+ async persist() {
110
+ const data = Object.fromEntries(this.users);
111
+ await fs.writeFile(this.filePath, JSON.stringify(data, null, 2), "utf-8");
112
+ }
113
+ async findUserByEmail(email) {
114
+ await this.load();
115
+ for (const user of this.users.values()) {
116
+ if (user.email === email) return user;
117
+ }
118
+ return null;
119
+ }
120
+ async findUserById(id) {
121
+ await this.load();
122
+ return this.users.get(id) || null;
123
+ }
124
+ async createUser(data) {
125
+ await this.load();
126
+ const isFirst = this.users.size === 0;
127
+ const user = {
128
+ id: `usr_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
129
+ email: data.email,
130
+ passwordHash: data.passwordHash,
131
+ role: isFirst ? "admin" : data.role,
132
+ displayName: data.displayName,
133
+ createdAt: Date.now(),
134
+ updatedAt: Date.now()
135
+ };
136
+ this.users.set(user.id, user);
137
+ await this.persist();
138
+ return user;
139
+ }
140
+ async updateUser(id, data) {
141
+ await this.load();
142
+ const user = this.users.get(id);
143
+ if (!user) throw new Error("User not found");
144
+ const updated = { ...user, ...data, updatedAt: Date.now() };
145
+ this.users.set(id, updated);
146
+ await this.persist();
147
+ return updated;
148
+ }
149
+ async listUsers() {
150
+ await this.load();
151
+ return Array.from(this.users.values());
152
+ }
153
+ };
154
+
155
+ // src/auth/AdminGuard.ts
156
+ import { SkipoBase as SkipoBase2 } from "@ultrst-armada/kloks/functions";
157
+ var AdminGuard = class _AdminGuard extends SkipoBase2 {
158
+ static async verify(authHeaderOrToken, provider) {
159
+ const session = await _AdminGuard.verifyUser(authHeaderOrToken, provider);
160
+ if (session.role !== "admin") {
161
+ throw new Error("Forbidden: Admin access required.");
162
+ }
163
+ return session;
164
+ }
165
+ static async verifyUser(authHeaderOrToken, provider) {
166
+ const token = authHeaderOrToken?.startsWith("Bearer ") ? authHeaderOrToken.substring(7).trim() : authHeaderOrToken?.trim() || null;
167
+ const session = await provider.verifySession(token);
168
+ if (!session) {
169
+ throw new Error("Unauthorized: Invalid or missing session token.");
170
+ }
171
+ return session;
172
+ }
173
+ };
174
+
175
+ // src/auth/UnifiedAuthCore.ts
176
+ import bcrypt2 from "bcryptjs";
177
+ async function loginSystemUser(email, rawPass, isAdmin, queryDb) {
178
+ const normEmail = (email || "").trim().toLowerCase();
179
+ const password = (rawPass || "").trim();
180
+ if (!normEmail || !password) {
181
+ return { success: false, status: 400, error: "Email and password are required" };
182
+ }
183
+ try {
184
+ if (isAdmin) {
185
+ const credRes = await queryDb(`SELECT * FROM "ultrst-credentials" WHERE id = 'system' LIMIT 1`, []);
186
+ if (credRes.rows.length > 0) {
187
+ const cred = credRes.rows[0];
188
+ const matchEmail = (cred.admin_email || "").toLowerCase() === normEmail;
189
+ const matchPass = cred.admin_password === password || cred.admin_password && bcrypt2.compareSync(password, cred.admin_password);
190
+ if (matchEmail && matchPass) {
191
+ return {
192
+ success: true,
193
+ status: 200,
194
+ token: `adm_${Date.now()}_${Math.random().toString(36).slice(2)}`,
195
+ user: { id: "admin_sys", email: cred.admin_email, username: "System Admin", name: "System Admin", role: "admin", status: "ACTIVE" }
196
+ };
197
+ }
198
+ }
199
+ }
200
+ const uRes = await queryDb(`SELECT * FROM "ultrst-users" WHERE LOWER(email) = $1 LIMIT 1`, [normEmail]);
201
+ if (uRes.rows.length === 0) {
202
+ return { success: false, status: 401, error: "Invalid email or password" };
203
+ }
204
+ const user = uRes.rows[0];
205
+ const hash = user.password_hash || "";
206
+ let isMatch = false;
207
+ if (hash.startsWith("$2a$") || hash.startsWith("$2b$")) {
208
+ isMatch = bcrypt2.compareSync(password, hash);
209
+ } else {
210
+ isMatch = hash === password;
211
+ }
212
+ if (!isMatch) {
213
+ return { success: false, status: 401, error: "Invalid email or password" };
214
+ }
215
+ if (isAdmin && user.role !== "admin") {
216
+ return { success: false, status: 403, error: "Insufficient administrative privileges" };
217
+ }
218
+ return {
219
+ success: true,
220
+ status: 200,
221
+ token: `usr_${Date.now()}_${Math.random().toString(36).slice(2)}`,
222
+ user: {
223
+ id: user.id,
224
+ email: user.email,
225
+ username: user.username || user.name || user.email.split("@")[0],
226
+ name: user.name || user.username || "Ecosystem User",
227
+ role: user.role || "user",
228
+ status: user.status || "ACTIVE",
229
+ appProfiles: typeof user.app_profiles === "string" ? JSON.parse(user.app_profiles) : user.app_profiles || {}
230
+ }
231
+ };
232
+ } catch (err) {
233
+ return { success: false, status: 500, error: err.message };
234
+ }
235
+ }
236
+ async function resolveUserFromToken(tokenOrUserId, queryDb) {
237
+ if (!tokenOrUserId) return null;
238
+ let targetId = tokenOrUserId;
239
+ if (targetId.startsWith("Bearer ")) targetId = targetId.slice(7).trim();
240
+ if (targetId.startsWith("sess::")) {
241
+ const parts = targetId.split("::");
242
+ if (parts[1]) targetId = parts[1];
243
+ }
244
+ const res = await queryDb(`SELECT * FROM "ultrst-users" WHERE id = $1 OR LOWER(email) = LOWER($1) LIMIT 1`, [targetId]);
245
+ if (res.rows.length === 0) return null;
246
+ const u = res.rows[0];
247
+ return {
248
+ id: u.id,
249
+ email: u.email,
250
+ username: u.username || u.name || u.email.split("@")[0],
251
+ name: u.name || u.username || "Ecosystem User",
252
+ role: u.role || "user",
253
+ status: u.status || "ACTIVE",
254
+ appProfiles: typeof u.app_profiles === "string" ? JSON.parse(u.app_profiles) : u.app_profiles || {}
255
+ };
256
+ }
257
+
258
+ export {
259
+ PasswordHasher,
260
+ BaseAccountProvider,
261
+ LocalAccountProvider,
262
+ AdminGuard,
263
+ loginSystemUser,
264
+ resolveUserFromToken
265
+ };
@@ -0,0 +1,278 @@
1
+ import {
2
+ createService,
3
+ createServiceDefinition
4
+ } from "./chunk-KPUGS64G.js";
5
+ import {
6
+ formatCanonicalWorkspaceFolderName,
7
+ sanitizeWorkspaceName
8
+ } from "./chunk-FZKBTF34.js";
9
+ import {
10
+ StorageAdapterFactory
11
+ } from "./chunk-J2J24JVC.js";
12
+ import {
13
+ RateLimiter,
14
+ SessionManager
15
+ } from "./chunk-25Y7AVTP.js";
16
+ import {
17
+ ExecutableBackendFacade,
18
+ WorkerExecutionBoundary
19
+ } from "./chunk-QGHDJGYS.js";
20
+
21
+ // src/krnl-services.ts
22
+ var AuthServiceDefinition = createServiceDefinition({
23
+ id: "kloks.backend.auth",
24
+ name: "AuthService",
25
+ version: "1.0.0",
26
+ state: {
27
+ initial: { activeSessions: 0 }
28
+ },
29
+ operations: {
30
+ createSession: {
31
+ id: "AuthService.createSession",
32
+ name: "createSession",
33
+ handler: async (input) => {
34
+ const sm = new SessionManager();
35
+ return sm.createSession(input.userId, input.role ?? "user");
36
+ }
37
+ },
38
+ checkRateLimit: {
39
+ id: "AuthService.checkRateLimit",
40
+ name: "checkRateLimit",
41
+ handler: async (input) => {
42
+ const limiter = new RateLimiter(input.windowMs ?? 6e4, input.maxRequests ?? 60);
43
+ limiter.check(input.key);
44
+ return { allowed: true, key: input.key };
45
+ }
46
+ }
47
+ }
48
+ });
49
+ var authServiceInstance = createService(AuthServiceDefinition);
50
+ var AuthServiceFacade = {
51
+ id: AuthServiceDefinition.id,
52
+ name: AuthServiceDefinition.name,
53
+ version: AuthServiceDefinition.version,
54
+ runtime: "server",
55
+ deployment: "local",
56
+ definition: AuthServiceDefinition,
57
+ createInstance: () => createService(AuthServiceDefinition),
58
+ execute: async (op, input) => {
59
+ await authServiceInstance.start();
60
+ return authServiceInstance.call(op, input);
61
+ }
62
+ };
63
+ var StorageServiceDefinition = createServiceDefinition({
64
+ id: "kloks.backend.storage",
65
+ name: "StorageService",
66
+ version: "1.0.0",
67
+ operations: {
68
+ resolveAdapterType: {
69
+ id: "StorageService.resolveAdapterType",
70
+ name: "resolveAdapterType",
71
+ handler: async (input) => {
72
+ const normalized = input.provider === "local" ? "local_fs" : input.provider;
73
+ if (normalized === "local_fs") {
74
+ const adapter = StorageAdapterFactory.create({
75
+ provider: "local_fs",
76
+ basePath: input.basePath ?? "/tmp/kloks-storage"
77
+ });
78
+ return { provider: "local", initialized: Boolean(adapter) };
79
+ }
80
+ return { provider: input.provider, initialized: true };
81
+ }
82
+ }
83
+ }
84
+ });
85
+ var storageServiceInstance = createService(StorageServiceDefinition);
86
+ var StorageServiceFacade = {
87
+ id: StorageServiceDefinition.id,
88
+ name: StorageServiceDefinition.name,
89
+ version: StorageServiceDefinition.version,
90
+ runtime: "server",
91
+ deployment: "local",
92
+ definition: StorageServiceDefinition,
93
+ createInstance: () => createService(StorageServiceDefinition),
94
+ execute: async (op, input) => {
95
+ await storageServiceInstance.start();
96
+ return storageServiceInstance.call(op, input);
97
+ }
98
+ };
99
+ var WorkspaceServiceDefinition = createServiceDefinition({
100
+ id: "kloks.backend.workspace",
101
+ name: "WorkspaceService",
102
+ version: "1.0.0",
103
+ operations: {
104
+ validateWorkspaceConfig: {
105
+ id: "WorkspaceService.validateWorkspaceConfig",
106
+ name: "validateWorkspaceConfig",
107
+ handler: async (input) => {
108
+ const sanitized = sanitizeWorkspaceName(input.name);
109
+ const folderName = formatCanonicalWorkspaceFolderName(
110
+ input.appName ?? "app",
111
+ input.userName ?? "user",
112
+ sanitized
113
+ );
114
+ return {
115
+ valid: Boolean(input.id && sanitized),
116
+ workspaceId: input.id,
117
+ name: sanitized,
118
+ folderName,
119
+ storageType: input.storageType ?? "local"
120
+ };
121
+ }
122
+ }
123
+ }
124
+ });
125
+ var workspaceServiceInstance = createService(WorkspaceServiceDefinition);
126
+ var WorkspaceServiceFacade = {
127
+ id: WorkspaceServiceDefinition.id,
128
+ name: WorkspaceServiceDefinition.name,
129
+ version: WorkspaceServiceDefinition.version,
130
+ runtime: "server",
131
+ deployment: "local",
132
+ definition: WorkspaceServiceDefinition,
133
+ createInstance: () => createService(WorkspaceServiceDefinition),
134
+ execute: async (op, input) => {
135
+ await workspaceServiceInstance.start();
136
+ return workspaceServiceInstance.call(op, input);
137
+ }
138
+ };
139
+ var ControlPlaneServiceDefinition = createServiceDefinition({
140
+ id: "kloks.backend.controlPlane",
141
+ name: "ControlPlaneService",
142
+ version: "1.0.0",
143
+ operations: {
144
+ status: {
145
+ id: "ControlPlaneService.status",
146
+ name: "status",
147
+ handler: async () => ({
148
+ healthy: true,
149
+ timestamp: Date.now()
150
+ })
151
+ }
152
+ }
153
+ });
154
+ var controlPlaneServiceInstance = createService(ControlPlaneServiceDefinition);
155
+ var ControlPlaneServiceFacade = {
156
+ id: ControlPlaneServiceDefinition.id,
157
+ name: ControlPlaneServiceDefinition.name,
158
+ version: ControlPlaneServiceDefinition.version,
159
+ runtime: "server",
160
+ deployment: "local",
161
+ definition: ControlPlaneServiceDefinition,
162
+ createInstance: () => createService(ControlPlaneServiceDefinition),
163
+ execute: async (op, input) => {
164
+ await controlPlaneServiceInstance.start();
165
+ return controlPlaneServiceInstance.call(op, input);
166
+ }
167
+ };
168
+ var ExecutionServiceDefinition = createServiceDefinition({
169
+ id: "kloks.backend.execution",
170
+ name: "ExecutionService",
171
+ version: "1.0.0",
172
+ operations: {
173
+ createWorkerBoundary: {
174
+ id: "ExecutionService.createWorkerBoundary",
175
+ name: "createWorkerBoundary",
176
+ handler: async (input) => {
177
+ const facade = new ExecutableBackendFacade(input.name);
178
+ const worker = new WorkerExecutionBoundary(`${input.name}Worker`, facade);
179
+ return {
180
+ facadeName: facade.name,
181
+ workerReady: Boolean(worker)
182
+ };
183
+ }
184
+ }
185
+ }
186
+ });
187
+ var executionServiceInstance = createService(ExecutionServiceDefinition);
188
+ var ExecutionServiceFacade = {
189
+ id: ExecutionServiceDefinition.id,
190
+ name: ExecutionServiceDefinition.name,
191
+ version: ExecutionServiceDefinition.version,
192
+ runtime: "server",
193
+ deployment: "local",
194
+ definition: ExecutionServiceDefinition,
195
+ createInstance: () => createService(ExecutionServiceDefinition),
196
+ execute: async (op, input) => {
197
+ await executionServiceInstance.start();
198
+ return executionServiceInstance.call(op, input);
199
+ }
200
+ };
201
+ var DatabaseServiceDefinition = createServiceDefinition({
202
+ id: "kloks.backend.database",
203
+ name: "DatabaseService",
204
+ version: "1.0.0",
205
+ operations: {
206
+ query: {
207
+ id: "DatabaseService.query",
208
+ name: "query",
209
+ handler: async (input) => {
210
+ return { rows: [], sql: input.sql, executedAt: Date.now() };
211
+ }
212
+ },
213
+ isHealthy: {
214
+ id: "DatabaseService.isHealthy",
215
+ name: "isHealthy",
216
+ handler: async () => ({ healthy: true })
217
+ }
218
+ }
219
+ });
220
+ var databaseServiceInstance = createService(DatabaseServiceDefinition);
221
+ var DatabaseServiceFacade = {
222
+ id: DatabaseServiceDefinition.id,
223
+ name: DatabaseServiceDefinition.name,
224
+ version: DatabaseServiceDefinition.version,
225
+ runtime: "server",
226
+ deployment: "local",
227
+ definition: DatabaseServiceDefinition,
228
+ createInstance: () => createService(DatabaseServiceDefinition),
229
+ execute: async (op, input) => {
230
+ await databaseServiceInstance.start();
231
+ return databaseServiceInstance.call(op, input);
232
+ }
233
+ };
234
+ var GeminiServiceDefinition = createServiceDefinition({
235
+ id: "kloks.backend.gemini",
236
+ name: "GeminiService",
237
+ version: "1.0.0",
238
+ operations: {
239
+ generateText: {
240
+ id: "GeminiService.generateText",
241
+ name: "generateText",
242
+ handler: async (input) => {
243
+ return { text: `[GeminiResponse] Generated response for: ${input.prompt}`, model: input.model ?? "gemini-2.5-flash", timestamp: Date.now() };
244
+ }
245
+ }
246
+ }
247
+ });
248
+ var geminiServiceInstance = createService(GeminiServiceDefinition);
249
+ var GeminiServiceFacade = {
250
+ id: GeminiServiceDefinition.id,
251
+ name: GeminiServiceDefinition.name,
252
+ version: GeminiServiceDefinition.version,
253
+ runtime: "server",
254
+ deployment: "remote",
255
+ definition: GeminiServiceDefinition,
256
+ createInstance: () => createService(GeminiServiceDefinition),
257
+ execute: async (op, input) => {
258
+ await geminiServiceInstance.start();
259
+ return geminiServiceInstance.call(op, input);
260
+ }
261
+ };
262
+
263
+ export {
264
+ AuthServiceDefinition,
265
+ AuthServiceFacade,
266
+ StorageServiceDefinition,
267
+ StorageServiceFacade,
268
+ WorkspaceServiceDefinition,
269
+ WorkspaceServiceFacade,
270
+ ControlPlaneServiceDefinition,
271
+ ControlPlaneServiceFacade,
272
+ ExecutionServiceDefinition,
273
+ ExecutionServiceFacade,
274
+ DatabaseServiceDefinition,
275
+ DatabaseServiceFacade,
276
+ GeminiServiceDefinition,
277
+ GeminiServiceFacade
278
+ };