trellis 3.2.2 → 3.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.js +4 -4
- package/dist/{chunk-2W3MHTMG.js → chunk-2AACZRII.js} +122 -3
- package/dist/{chunk-H6JB3PZ3.js → chunk-5KSGGKET.js} +1 -1
- package/dist/{chunk-J2TXUFCZ.js → chunk-6RWGFC3N.js} +134 -20
- package/dist/{chunk-7ZFRVCUE.js → chunk-NWSW5YNS.js} +28 -14
- package/dist/{deploy-cli-C35HTITO.js → cli/deploy-cli.js} +5 -5
- package/dist/cli/index.js +5 -5
- package/dist/client/index.browser.js +2 -2
- package/dist/client/index.js +1 -1
- package/dist/client/sdk.browser.d.ts +28 -1
- package/dist/client/sdk.browser.d.ts.map +1 -1
- package/dist/client/sdk.browser.js +1 -1
- package/dist/client/sdk.js +1 -1
- package/dist/core/index.js +6 -6
- package/dist/db/index.js +5 -5
- package/dist/react/index.js +2 -2
- package/dist/react/schema-hooks.js +2 -2
- package/dist/server/cors.d.ts +13 -0
- package/dist/server/cors.d.ts.map +1 -0
- package/dist/server/deploy.d.ts +1 -1
- package/dist/server/deploy.d.ts.map +1 -1
- package/dist/server/deploy.js +9 -0
- package/dist/server/index.js +9 -9
- package/dist/server/server.d.ts.map +1 -1
- package/dist/{server-ZVWGLLRF.js → server-OGVWNDNK.js} +1 -1
- package/package.json +2 -2
- package/dist/chunk-FF36CQHZ.js +0 -61
- package/dist/chunk-IZX2PLIB.js +0 -1240
- package/dist/chunk-KIJITUZB.js +0 -419
- package/dist/chunk-SGMDTWJJ.js +0 -149
- package/dist/chunk-UQISRW6T.js +0 -203
- package/dist/db/trellis.css +0 -1
- package/dist/deploy-LQ7GUGJ5.js +0 -9
- package/dist/deploy-YNVG5E4E.js +0 -9
- package/dist/deploy-cli-24BCHAXY.js +0 -67
- package/dist/server-MB3OPSPI.js +0 -18
- package/dist/sprites-RU3E4XQN.js +0 -15
- package/dist/tenancy-NBLLGCNJ.js +0 -14
- /package/dist/{chunk-QB5ISE47.js → chunk-7DUMWO5L.js} +0 -0
package/dist/chunk-IZX2PLIB.js
DELETED
|
@@ -1,1240 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
DEFAULT_TENANT
|
|
3
|
-
} from "./chunk-SGMDTWJJ.js";
|
|
4
|
-
import {
|
|
5
|
-
rel
|
|
6
|
-
} from "./chunk-44FFQKQX.js";
|
|
7
|
-
import {
|
|
8
|
-
entityRecordToPlain,
|
|
9
|
-
hydrateBindings,
|
|
10
|
-
resolveRelations
|
|
11
|
-
} from "./chunk-JUEMDWLU.js";
|
|
12
|
-
import {
|
|
13
|
-
parseSimple
|
|
14
|
-
} from "./chunk-X5FLTRUB.js";
|
|
15
|
-
|
|
16
|
-
// src/server/server.ts
|
|
17
|
-
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
18
|
-
import { dirname, join as join2 } from "path";
|
|
19
|
-
import { fileURLToPath } from "url";
|
|
20
|
-
|
|
21
|
-
// src/server/auth.ts
|
|
22
|
-
var ANONYMOUS = {
|
|
23
|
-
userId: null,
|
|
24
|
-
tenantId: null,
|
|
25
|
-
roles: [],
|
|
26
|
-
claims: {},
|
|
27
|
-
authenticated: false
|
|
28
|
-
};
|
|
29
|
-
function base64UrlEncode(input) {
|
|
30
|
-
return btoa(String.fromCharCode(...input)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
31
|
-
}
|
|
32
|
-
function base64UrlDecode(input) {
|
|
33
|
-
const padded = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
34
|
-
const padLen = (4 - padded.length % 4) % 4;
|
|
35
|
-
const base64 = padded + "=".repeat(padLen);
|
|
36
|
-
const binary = atob(base64);
|
|
37
|
-
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
38
|
-
}
|
|
39
|
-
async function hmacKey(secret) {
|
|
40
|
-
return crypto.subtle.importKey(
|
|
41
|
-
"raw",
|
|
42
|
-
new TextEncoder().encode(secret),
|
|
43
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
44
|
-
false,
|
|
45
|
-
["sign", "verify"]
|
|
46
|
-
);
|
|
47
|
-
}
|
|
48
|
-
async function signJwt(payload, secret, expiresInSeconds = 86400) {
|
|
49
|
-
const header = { alg: "HS256", typ: "JWT" };
|
|
50
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
51
|
-
const claims = { iat: now, exp: now + expiresInSeconds, ...payload };
|
|
52
|
-
const enc = new TextEncoder();
|
|
53
|
-
const headerB64 = base64UrlEncode(enc.encode(JSON.stringify(header)));
|
|
54
|
-
const payloadB64 = base64UrlEncode(enc.encode(JSON.stringify(claims)));
|
|
55
|
-
const signing = `${headerB64}.${payloadB64}`;
|
|
56
|
-
const key = await hmacKey(secret);
|
|
57
|
-
const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signing));
|
|
58
|
-
const sigB64 = base64UrlEncode(new Uint8Array(sig));
|
|
59
|
-
return `${signing}.${sigB64}`;
|
|
60
|
-
}
|
|
61
|
-
async function verifyJwt(token, secret) {
|
|
62
|
-
const parts = token.split(".");
|
|
63
|
-
if (parts.length !== 3) return null;
|
|
64
|
-
const [headerB64, payloadB64, sigB64] = parts;
|
|
65
|
-
const enc = new TextEncoder();
|
|
66
|
-
const signing = `${headerB64}.${payloadB64}`;
|
|
67
|
-
try {
|
|
68
|
-
const key = await hmacKey(secret);
|
|
69
|
-
const sigRaw = base64UrlDecode(sigB64);
|
|
70
|
-
const sigBuf = sigRaw.buffer.slice(
|
|
71
|
-
sigRaw.byteOffset,
|
|
72
|
-
sigRaw.byteOffset + sigRaw.byteLength
|
|
73
|
-
);
|
|
74
|
-
const valid = await crypto.subtle.verify(
|
|
75
|
-
"HMAC",
|
|
76
|
-
key,
|
|
77
|
-
sigBuf,
|
|
78
|
-
enc.encode(signing)
|
|
79
|
-
);
|
|
80
|
-
if (!valid) return null;
|
|
81
|
-
const claims = JSON.parse(
|
|
82
|
-
new TextDecoder().decode(base64UrlDecode(payloadB64))
|
|
83
|
-
);
|
|
84
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
85
|
-
if (typeof claims.exp === "number" && claims.exp < now) return null;
|
|
86
|
-
return claims;
|
|
87
|
-
} catch {
|
|
88
|
-
return null;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
async function resolveAuth(authHeader, config) {
|
|
92
|
-
if (!authHeader) {
|
|
93
|
-
return config.allowPublic === false ? { ...ANONYMOUS, authenticated: false } : ANONYMOUS;
|
|
94
|
-
}
|
|
95
|
-
const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : authHeader;
|
|
96
|
-
if (config.apiKey && token === config.apiKey) {
|
|
97
|
-
return {
|
|
98
|
-
userId: "service",
|
|
99
|
-
tenantId: null,
|
|
100
|
-
roles: ["admin"],
|
|
101
|
-
claims: { sub: "service" },
|
|
102
|
-
authenticated: true
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
if (config.jwtSecret) {
|
|
106
|
-
const claims = await verifyJwt(token, config.jwtSecret);
|
|
107
|
-
if (claims) {
|
|
108
|
-
return {
|
|
109
|
-
userId: claims.sub ?? null,
|
|
110
|
-
tenantId: claims.tenantId ?? null,
|
|
111
|
-
roles: Array.isArray(claims.roles) ? claims.roles : typeof claims.role === "string" ? [claims.role] : [],
|
|
112
|
-
claims,
|
|
113
|
-
authenticated: true
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
return ANONYMOUS;
|
|
118
|
-
}
|
|
119
|
-
var GOOGLE_PROVIDER = {
|
|
120
|
-
name: "google",
|
|
121
|
-
authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
122
|
-
tokenUrl: "https://oauth2.googleapis.com/token",
|
|
123
|
-
userInfoUrl: "https://www.googleapis.com/oauth2/v3/userinfo",
|
|
124
|
-
scopes: ["openid", "email", "profile"]
|
|
125
|
-
};
|
|
126
|
-
var GITHUB_PROVIDER = {
|
|
127
|
-
name: "github",
|
|
128
|
-
authUrl: "https://github.com/login/oauth/authorize",
|
|
129
|
-
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
130
|
-
userInfoUrl: "https://api.github.com/user",
|
|
131
|
-
scopes: ["read:user", "user:email"]
|
|
132
|
-
};
|
|
133
|
-
function buildOAuthUrl(provider, redirectUri, state) {
|
|
134
|
-
const params = new URLSearchParams({
|
|
135
|
-
client_id: provider.clientId,
|
|
136
|
-
redirect_uri: redirectUri,
|
|
137
|
-
response_type: "code",
|
|
138
|
-
scope: provider.scopes.join(" "),
|
|
139
|
-
state
|
|
140
|
-
});
|
|
141
|
-
return `${provider.authUrl}?${params}`;
|
|
142
|
-
}
|
|
143
|
-
async function exchangeOAuthCode(provider, code, redirectUri) {
|
|
144
|
-
const tokenRes = await fetch(provider.tokenUrl, {
|
|
145
|
-
method: "POST",
|
|
146
|
-
headers: {
|
|
147
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
148
|
-
Accept: "application/json"
|
|
149
|
-
},
|
|
150
|
-
body: new URLSearchParams({
|
|
151
|
-
client_id: provider.clientId,
|
|
152
|
-
client_secret: provider.clientSecret,
|
|
153
|
-
code,
|
|
154
|
-
redirect_uri: redirectUri,
|
|
155
|
-
grant_type: "authorization_code"
|
|
156
|
-
})
|
|
157
|
-
});
|
|
158
|
-
if (!tokenRes.ok) {
|
|
159
|
-
throw new Error(`OAuth token exchange failed: ${tokenRes.status}`);
|
|
160
|
-
}
|
|
161
|
-
const tokenData = await tokenRes.json();
|
|
162
|
-
const accessToken = tokenData.access_token;
|
|
163
|
-
const userRes = await fetch(provider.userInfoUrl, {
|
|
164
|
-
headers: {
|
|
165
|
-
Authorization: `Bearer ${accessToken}`,
|
|
166
|
-
Accept: "application/json"
|
|
167
|
-
}
|
|
168
|
-
});
|
|
169
|
-
if (!userRes.ok) {
|
|
170
|
-
throw new Error(`OAuth user info fetch failed: ${userRes.status}`);
|
|
171
|
-
}
|
|
172
|
-
const user = await userRes.json();
|
|
173
|
-
return {
|
|
174
|
-
id: String(user.id ?? user.sub ?? ""),
|
|
175
|
-
email: String(user.email ?? ""),
|
|
176
|
-
name: String(user.name ?? user.login ?? ""),
|
|
177
|
-
avatarUrl: user.picture ?? user.avatar_url ?? void 0
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// src/server/permissions.ts
|
|
182
|
-
var PermissionRegistry = class {
|
|
183
|
-
rules = /* @__PURE__ */ new Map();
|
|
184
|
-
defaultRule = "authenticated";
|
|
185
|
-
/**
|
|
186
|
-
* Register permissions for an entity type.
|
|
187
|
-
*/
|
|
188
|
-
register(entityType, permissions) {
|
|
189
|
-
this.rules.set(entityType, permissions);
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Set the fallback rule used when an entity type has no declared permissions.
|
|
193
|
-
*/
|
|
194
|
-
setDefault(rule) {
|
|
195
|
-
this.defaultRule = rule;
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* Get the permission rule for a specific operation on an entity type.
|
|
199
|
-
* Falls back to the default rule if not declared.
|
|
200
|
-
*/
|
|
201
|
-
getRule(entityType, op) {
|
|
202
|
-
const def = this.rules.get(entityType);
|
|
203
|
-
return def?.[op] ?? this.defaultRule;
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Check whether an auth context is allowed to perform an operation.
|
|
207
|
-
*/
|
|
208
|
-
check(auth, entityType, op, entity = null) {
|
|
209
|
-
const rule = this.getRule(entityType, op);
|
|
210
|
-
return evaluateRule(rule, auth, entity);
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* Assert access — throws a PermissionError if denied.
|
|
214
|
-
*/
|
|
215
|
-
assert(auth, entityType, op, entity = null) {
|
|
216
|
-
if (!this.check(auth, entityType, op, entity)) {
|
|
217
|
-
throw new PermissionError(auth, entityType, op);
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
};
|
|
221
|
-
function evaluateRule(rule, auth, entity) {
|
|
222
|
-
if (rule === "public") {
|
|
223
|
-
return true;
|
|
224
|
-
}
|
|
225
|
-
if (rule === "authenticated") {
|
|
226
|
-
return auth.authenticated;
|
|
227
|
-
}
|
|
228
|
-
if (rule === "own") {
|
|
229
|
-
if (!auth.authenticated || !auth.userId) return false;
|
|
230
|
-
const ownerFact = entity?.facts.find(
|
|
231
|
-
(f) => f.a === "ownerId" || f.a === "createdBy"
|
|
232
|
-
);
|
|
233
|
-
return ownerFact?.v === auth.userId;
|
|
234
|
-
}
|
|
235
|
-
if (typeof rule === "object") {
|
|
236
|
-
if ("role" in rule) {
|
|
237
|
-
return auth.roles.includes(rule.role);
|
|
238
|
-
}
|
|
239
|
-
if ("roles" in rule) {
|
|
240
|
-
return rule.roles.some((r) => auth.roles.includes(r));
|
|
241
|
-
}
|
|
242
|
-
if ("fn" in rule) {
|
|
243
|
-
try {
|
|
244
|
-
return rule.fn(auth, entity);
|
|
245
|
-
} catch {
|
|
246
|
-
return false;
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
return false;
|
|
251
|
-
}
|
|
252
|
-
var PermissionError = class extends Error {
|
|
253
|
-
constructor(auth, entityType, op) {
|
|
254
|
-
const who = auth.authenticated ? `user:${auth.userId}` : "anonymous";
|
|
255
|
-
super(`Permission denied: ${who} cannot ${op} ${entityType}`);
|
|
256
|
-
this.auth = auth;
|
|
257
|
-
this.entityType = entityType;
|
|
258
|
-
this.op = op;
|
|
259
|
-
this.name = "PermissionError";
|
|
260
|
-
}
|
|
261
|
-
toResponse() {
|
|
262
|
-
return {
|
|
263
|
-
error: "Forbidden",
|
|
264
|
-
message: this.message,
|
|
265
|
-
code: 403
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
};
|
|
269
|
-
var PUBLIC_READ = {
|
|
270
|
-
read: "public",
|
|
271
|
-
create: "authenticated",
|
|
272
|
-
update: "authenticated",
|
|
273
|
-
delete: "authenticated"
|
|
274
|
-
};
|
|
275
|
-
var FULLY_PUBLIC = {
|
|
276
|
-
read: "public",
|
|
277
|
-
create: "public",
|
|
278
|
-
update: "public",
|
|
279
|
-
delete: "public"
|
|
280
|
-
};
|
|
281
|
-
var OWNER_ONLY = {
|
|
282
|
-
read: "own",
|
|
283
|
-
create: "authenticated",
|
|
284
|
-
update: "own",
|
|
285
|
-
delete: "own"
|
|
286
|
-
};
|
|
287
|
-
var ADMIN_ONLY = {
|
|
288
|
-
read: { role: "admin" },
|
|
289
|
-
create: { role: "admin" },
|
|
290
|
-
update: { role: "admin" },
|
|
291
|
-
delete: { role: "admin" }
|
|
292
|
-
};
|
|
293
|
-
|
|
294
|
-
// src/schema/kernel-resolve.ts
|
|
295
|
-
import { z } from "zod";
|
|
296
|
-
function ontologyTypeName(id) {
|
|
297
|
-
return id.includes(":") ? id.split(":").pop() : id;
|
|
298
|
-
}
|
|
299
|
-
function findOntologyByTypeName(kernel, typeName) {
|
|
300
|
-
return kernel.listOntologies().find((s) => {
|
|
301
|
-
const short = ontologyTypeName(s["@id"]);
|
|
302
|
-
return short === typeName || short.toLowerCase() === typeName.toLowerCase() || s.label === typeName;
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
function schemaHandleFromOntology(def, typeName) {
|
|
306
|
-
const name = typeName ?? ontologyTypeName(def["@id"]);
|
|
307
|
-
const relations = {};
|
|
308
|
-
for (const field of def.fields) {
|
|
309
|
-
if (field.valueType === "relation" && field.relation?.targetSchema) {
|
|
310
|
-
const target = ontologyTypeName(field.relation.targetSchema);
|
|
311
|
-
relations[field.name] = rel(
|
|
312
|
-
target,
|
|
313
|
-
field.relation.cardinality ?? "one"
|
|
314
|
-
);
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
return {
|
|
318
|
-
type: name,
|
|
319
|
-
zod: z.object({}),
|
|
320
|
-
relations,
|
|
321
|
-
computed: {},
|
|
322
|
-
definition: def,
|
|
323
|
-
toOntologySchema: () => {
|
|
324
|
-
throw new Error("schemaHandleFromOntology: legacy adapter not available");
|
|
325
|
-
}
|
|
326
|
-
};
|
|
327
|
-
}
|
|
328
|
-
function createSchemaLookup(kernel) {
|
|
329
|
-
const cache = /* @__PURE__ */ new Map();
|
|
330
|
-
return (typeName) => {
|
|
331
|
-
if (cache.has(typeName)) return cache.get(typeName);
|
|
332
|
-
const def = findOntologyByTypeName(kernel, typeName);
|
|
333
|
-
if (!def) return null;
|
|
334
|
-
const handle = schemaHandleFromOntology(def, typeName);
|
|
335
|
-
cache.set(typeName, handle);
|
|
336
|
-
return handle;
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
function createKernelResolveClient(kernel) {
|
|
340
|
-
return {
|
|
341
|
-
read: async (id) => {
|
|
342
|
-
const entity = kernel.getEntity(id);
|
|
343
|
-
return entity ? entityRecordToPlain(entity) : null;
|
|
344
|
-
},
|
|
345
|
-
query: async (q) => {
|
|
346
|
-
const parsed = parseSimple(q);
|
|
347
|
-
const qr = await kernel.query(parsed);
|
|
348
|
-
return {
|
|
349
|
-
bindings: hydrateBindings(
|
|
350
|
-
kernel,
|
|
351
|
-
qr.bindings
|
|
352
|
-
),
|
|
353
|
-
executionTime: qr.executionTime
|
|
354
|
-
};
|
|
355
|
-
}
|
|
356
|
-
};
|
|
357
|
-
}
|
|
358
|
-
async function hydrateAndResolve(kernel, bindings, entityType, resolve) {
|
|
359
|
-
let entities = hydrateBindings(kernel, bindings);
|
|
360
|
-
if (!entityType || !resolve || Object.keys(resolve).length === 0) {
|
|
361
|
-
return entities;
|
|
362
|
-
}
|
|
363
|
-
const def = findOntologyByTypeName(kernel, entityType);
|
|
364
|
-
if (!def) return entities;
|
|
365
|
-
const schema = schemaHandleFromOntology(def, entityType);
|
|
366
|
-
const client = createKernelResolveClient(kernel);
|
|
367
|
-
const lookup = createSchemaLookup(kernel);
|
|
368
|
-
return resolveRelations(client, schema, entities, resolve, {
|
|
369
|
-
schemaLookup: lookup
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
// src/server/usage-meter.ts
|
|
374
|
-
import { existsSync, readdirSync, statSync } from "fs";
|
|
375
|
-
import { join } from "path";
|
|
376
|
-
var EMPTY_BUCKET = () => ({
|
|
377
|
-
graph_io: 0,
|
|
378
|
-
storage_bytes: 0,
|
|
379
|
-
egress_bytes: 0
|
|
380
|
-
});
|
|
381
|
-
function resolveUsageTenantId(tenantId) {
|
|
382
|
-
return tenantId ?? DEFAULT_TENANT;
|
|
383
|
-
}
|
|
384
|
-
function dayKey(date) {
|
|
385
|
-
return date.toISOString().slice(0, 10);
|
|
386
|
-
}
|
|
387
|
-
function dirSize(dir) {
|
|
388
|
-
let total = 0;
|
|
389
|
-
for (const ent of readdirSync(dir, { withFileTypes: true })) {
|
|
390
|
-
const p = join(dir, ent.name);
|
|
391
|
-
if (ent.isDirectory()) total += dirSize(p);
|
|
392
|
-
else if (ent.isFile()) total += statSync(p).size;
|
|
393
|
-
}
|
|
394
|
-
return total;
|
|
395
|
-
}
|
|
396
|
-
function sampleTenantStorage(pool, tenantId) {
|
|
397
|
-
let total = 0;
|
|
398
|
-
const sqlitePath = pool.dbFilePath(tenantId);
|
|
399
|
-
if (existsSync(sqlitePath)) {
|
|
400
|
-
total += statSync(sqlitePath).size;
|
|
401
|
-
}
|
|
402
|
-
const blobDir = join(pool.dataPath(), "blobs");
|
|
403
|
-
if (existsSync(blobDir)) {
|
|
404
|
-
total += dirSize(blobDir);
|
|
405
|
-
}
|
|
406
|
-
return total;
|
|
407
|
-
}
|
|
408
|
-
function verifyAdminKey(req) {
|
|
409
|
-
const expected = process.env.TURTLEDB_ADMIN_KEY;
|
|
410
|
-
if (!expected) return false;
|
|
411
|
-
const auth = req.headers.get("authorization");
|
|
412
|
-
if (auth?.startsWith("Bearer ")) {
|
|
413
|
-
return auth.slice("Bearer ".length) === expected;
|
|
414
|
-
}
|
|
415
|
-
return req.headers.get("x-turtledb-admin-key") === expected;
|
|
416
|
-
}
|
|
417
|
-
var UsageMeter = class {
|
|
418
|
-
buckets = /* @__PURE__ */ new Map();
|
|
419
|
-
storageSampledAt = /* @__PURE__ */ new Map();
|
|
420
|
-
now;
|
|
421
|
-
constructor(opts = {}) {
|
|
422
|
-
this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
423
|
-
}
|
|
424
|
-
recordGraphIo(tenantId, count = 1) {
|
|
425
|
-
if (count <= 0) return;
|
|
426
|
-
const bucket = this._bucket(tenantId);
|
|
427
|
-
bucket.graph_io += count;
|
|
428
|
-
}
|
|
429
|
-
recordEgress(tenantId, bytes) {
|
|
430
|
-
if (bytes <= 0) return;
|
|
431
|
-
const bucket = this._bucket(tenantId);
|
|
432
|
-
bucket.egress_bytes += bytes;
|
|
433
|
-
}
|
|
434
|
-
/** Set storage gauge for the current day (from sampler, not incremental). */
|
|
435
|
-
recordStorage(tenantId, bytes) {
|
|
436
|
-
const bucket = this._bucket(tenantId);
|
|
437
|
-
bucket.storage_bytes = bytes;
|
|
438
|
-
this.storageSampledAt.set(`${tenantId}:${this._today()}`, this.now().toISOString());
|
|
439
|
-
}
|
|
440
|
-
sampleStorage(pool, tenantId) {
|
|
441
|
-
const id = resolveUsageTenantId(tenantId);
|
|
442
|
-
const bytes = sampleTenantStorage(pool, id);
|
|
443
|
-
this.recordStorage(id, bytes);
|
|
444
|
-
return bytes;
|
|
445
|
-
}
|
|
446
|
-
getUsage(tenantId, day) {
|
|
447
|
-
const d = day ?? this._today();
|
|
448
|
-
const tenantBuckets = this.buckets.get(tenantId);
|
|
449
|
-
const meters = tenantBuckets?.get(d) ?? EMPTY_BUCKET();
|
|
450
|
-
const sampledAt = this.storageSampledAt.get(`${tenantId}:${d}`);
|
|
451
|
-
return {
|
|
452
|
-
tenantId,
|
|
453
|
-
day: d,
|
|
454
|
-
meters: { ...meters },
|
|
455
|
-
...sampledAt ? { storageSampledAt: sampledAt } : {}
|
|
456
|
-
};
|
|
457
|
-
}
|
|
458
|
-
/** All day keys recorded for a tenant (sorted ascending). */
|
|
459
|
-
listDays(tenantId) {
|
|
460
|
-
const tenantBuckets = this.buckets.get(tenantId);
|
|
461
|
-
if (!tenantBuckets) return [];
|
|
462
|
-
return Array.from(tenantBuckets.keys()).sort();
|
|
463
|
-
}
|
|
464
|
-
_today() {
|
|
465
|
-
return dayKey(this.now());
|
|
466
|
-
}
|
|
467
|
-
_bucket(tenantId) {
|
|
468
|
-
const id = resolveUsageTenantId(tenantId);
|
|
469
|
-
const d = this._today();
|
|
470
|
-
if (!this.buckets.has(id)) {
|
|
471
|
-
this.buckets.set(id, /* @__PURE__ */ new Map());
|
|
472
|
-
}
|
|
473
|
-
const tenantBuckets = this.buckets.get(id);
|
|
474
|
-
if (!tenantBuckets.has(d)) {
|
|
475
|
-
tenantBuckets.set(d, EMPTY_BUCKET());
|
|
476
|
-
}
|
|
477
|
-
return tenantBuckets.get(d);
|
|
478
|
-
}
|
|
479
|
-
};
|
|
480
|
-
|
|
481
|
-
// src/server/realtime.ts
|
|
482
|
-
var SubscriptionManager = class {
|
|
483
|
-
clients = /* @__PURE__ */ new Map();
|
|
484
|
-
pool;
|
|
485
|
-
permissions;
|
|
486
|
-
meter;
|
|
487
|
-
constructor(pool, permissions = null, meter = null) {
|
|
488
|
-
this.pool = pool;
|
|
489
|
-
this.permissions = permissions;
|
|
490
|
-
this.meter = meter;
|
|
491
|
-
}
|
|
492
|
-
// -------------------------------------------------------------------------
|
|
493
|
-
// Client lifecycle
|
|
494
|
-
// -------------------------------------------------------------------------
|
|
495
|
-
addClient(clientId, ws, auth, tenantId) {
|
|
496
|
-
this.clients.set(clientId, {
|
|
497
|
-
id: clientId,
|
|
498
|
-
ws,
|
|
499
|
-
subscriptions: /* @__PURE__ */ new Map(),
|
|
500
|
-
auth,
|
|
501
|
-
tenantId
|
|
502
|
-
});
|
|
503
|
-
}
|
|
504
|
-
removeClient(clientId) {
|
|
505
|
-
this.clients.delete(clientId);
|
|
506
|
-
}
|
|
507
|
-
// -------------------------------------------------------------------------
|
|
508
|
-
// Message handling
|
|
509
|
-
// -------------------------------------------------------------------------
|
|
510
|
-
async handleMessage(clientId, raw) {
|
|
511
|
-
const client = this.clients.get(clientId);
|
|
512
|
-
if (!client) return;
|
|
513
|
-
let msg;
|
|
514
|
-
try {
|
|
515
|
-
msg = JSON.parse(raw);
|
|
516
|
-
} catch {
|
|
517
|
-
this._send(client, { type: "error", id: "", message: "Invalid JSON" });
|
|
518
|
-
return;
|
|
519
|
-
}
|
|
520
|
-
if (msg.type === "ping") {
|
|
521
|
-
this._send(client, { type: "pong" });
|
|
522
|
-
return;
|
|
523
|
-
}
|
|
524
|
-
if (msg.type === "subscribe") {
|
|
525
|
-
await this._handleSubscribe(client, msg.id, msg.query, {
|
|
526
|
-
tenantId: msg.tenantId,
|
|
527
|
-
entityType: msg.entityType,
|
|
528
|
-
resolve: msg.resolve
|
|
529
|
-
});
|
|
530
|
-
return;
|
|
531
|
-
}
|
|
532
|
-
if (msg.type === "unsubscribe") {
|
|
533
|
-
client.subscriptions.delete(msg.id);
|
|
534
|
-
return;
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
// -------------------------------------------------------------------------
|
|
538
|
-
// Notify — called after every mutation
|
|
539
|
-
// -------------------------------------------------------------------------
|
|
540
|
-
/**
|
|
541
|
-
* Re-evaluate all subscriptions for a given tenant and push diffs.
|
|
542
|
-
* Called after every write op lands.
|
|
543
|
-
*/
|
|
544
|
-
async notify(tenantId) {
|
|
545
|
-
const tid = tenantId ?? null;
|
|
546
|
-
const dead = [];
|
|
547
|
-
for (const [clientId, client] of this.clients) {
|
|
548
|
-
if (client.ws.readyState !== 1) {
|
|
549
|
-
dead.push(clientId);
|
|
550
|
-
continue;
|
|
551
|
-
}
|
|
552
|
-
if (client.tenantId !== tid) continue;
|
|
553
|
-
for (const [subId, sub] of client.subscriptions) {
|
|
554
|
-
if (sub.tenantId !== tid) continue;
|
|
555
|
-
await this._pushUpdate(client, sub);
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
for (const id of dead) this.clients.delete(id);
|
|
559
|
-
}
|
|
560
|
-
get clientCount() {
|
|
561
|
-
return this.clients.size;
|
|
562
|
-
}
|
|
563
|
-
// -------------------------------------------------------------------------
|
|
564
|
-
// Private
|
|
565
|
-
// -------------------------------------------------------------------------
|
|
566
|
-
async _handleSubscribe(client, subId, queryStr, opts = {}) {
|
|
567
|
-
const tid = opts.tenantId ?? client.tenantId ?? null;
|
|
568
|
-
let parsedQuery;
|
|
569
|
-
try {
|
|
570
|
-
parsedQuery = parseSimple(queryStr);
|
|
571
|
-
} catch (err) {
|
|
572
|
-
this._send(client, {
|
|
573
|
-
type: "error",
|
|
574
|
-
id: subId,
|
|
575
|
-
message: `Invalid query: ${err instanceof Error ? err.message : String(err)}`
|
|
576
|
-
});
|
|
577
|
-
return;
|
|
578
|
-
}
|
|
579
|
-
const kernel = await this.pool.preload(tid);
|
|
580
|
-
let result;
|
|
581
|
-
try {
|
|
582
|
-
const qr = await kernel.query(parsedQuery);
|
|
583
|
-
this._recordGraphIo(tid);
|
|
584
|
-
result = await hydrateAndResolve(
|
|
585
|
-
kernel,
|
|
586
|
-
qr.bindings,
|
|
587
|
-
opts.entityType,
|
|
588
|
-
opts.resolve
|
|
589
|
-
);
|
|
590
|
-
} catch (err) {
|
|
591
|
-
this._send(client, {
|
|
592
|
-
type: "error",
|
|
593
|
-
id: subId,
|
|
594
|
-
message: `Query failed: ${err instanceof Error ? err.message : String(err)}`
|
|
595
|
-
});
|
|
596
|
-
return;
|
|
597
|
-
}
|
|
598
|
-
const resolved = Boolean(opts.entityType) && Boolean(opts.resolve && Object.keys(opts.resolve).length > 0);
|
|
599
|
-
const sub = {
|
|
600
|
-
id: subId,
|
|
601
|
-
query: queryStr,
|
|
602
|
-
tenantId: tid,
|
|
603
|
-
auth: client.auth,
|
|
604
|
-
lastResult: result,
|
|
605
|
-
entityType: opts.entityType,
|
|
606
|
-
resolve: opts.resolve
|
|
607
|
-
};
|
|
608
|
-
client.subscriptions.set(subId, sub);
|
|
609
|
-
this._send(client, { type: "subscribed", id: subId });
|
|
610
|
-
this._send(client, {
|
|
611
|
-
type: "data",
|
|
612
|
-
id: subId,
|
|
613
|
-
result,
|
|
614
|
-
diff: { added: result, updated: [], removed: [] },
|
|
615
|
-
...resolved ? { resolved: true } : {}
|
|
616
|
-
});
|
|
617
|
-
}
|
|
618
|
-
async _pushUpdate(client, sub) {
|
|
619
|
-
const kernel = await this.pool.preload(sub.tenantId);
|
|
620
|
-
let newResult;
|
|
621
|
-
try {
|
|
622
|
-
const parsed = parseSimple(sub.query);
|
|
623
|
-
const qr = await kernel.query(parsed);
|
|
624
|
-
this._recordGraphIo(sub.tenantId);
|
|
625
|
-
newResult = await hydrateAndResolve(
|
|
626
|
-
kernel,
|
|
627
|
-
qr.bindings,
|
|
628
|
-
sub.entityType,
|
|
629
|
-
sub.resolve
|
|
630
|
-
);
|
|
631
|
-
} catch {
|
|
632
|
-
return;
|
|
633
|
-
}
|
|
634
|
-
const diff = computeDiff(sub.lastResult, newResult);
|
|
635
|
-
if (diff.added.length === 0 && diff.updated.length === 0 && diff.removed.length === 0) {
|
|
636
|
-
return;
|
|
637
|
-
}
|
|
638
|
-
sub.lastResult = newResult;
|
|
639
|
-
const resolved = Boolean(sub.entityType) && Boolean(sub.resolve && Object.keys(sub.resolve).length > 0);
|
|
640
|
-
this._send(client, {
|
|
641
|
-
type: "data",
|
|
642
|
-
id: sub.id,
|
|
643
|
-
result: newResult,
|
|
644
|
-
diff,
|
|
645
|
-
...resolved ? { resolved: true } : {}
|
|
646
|
-
});
|
|
647
|
-
}
|
|
648
|
-
_recordGraphIo(tenantId) {
|
|
649
|
-
this.meter?.recordGraphIo(resolveUsageTenantId(tenantId));
|
|
650
|
-
}
|
|
651
|
-
_send(client, payload) {
|
|
652
|
-
const data = JSON.stringify(payload);
|
|
653
|
-
if (this.meter) {
|
|
654
|
-
const tid = resolveUsageTenantId(client.tenantId ?? DEFAULT_TENANT);
|
|
655
|
-
this.meter.recordEgress(tid, new TextEncoder().encode(data).length);
|
|
656
|
-
}
|
|
657
|
-
try {
|
|
658
|
-
client.ws.send(data);
|
|
659
|
-
} catch {
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
};
|
|
663
|
-
function entityId(row) {
|
|
664
|
-
return String(row["?e"] ?? row.id ?? row.e ?? JSON.stringify(row));
|
|
665
|
-
}
|
|
666
|
-
function computeDiff(prev, next) {
|
|
667
|
-
const prevMap = new Map(prev.map((r) => [entityId(r), r]));
|
|
668
|
-
const nextMap = new Map(next.map((r) => [entityId(r), r]));
|
|
669
|
-
const added = [];
|
|
670
|
-
const updated = [];
|
|
671
|
-
const removed = [];
|
|
672
|
-
for (const [id, row] of nextMap) {
|
|
673
|
-
if (!prevMap.has(id)) {
|
|
674
|
-
added.push(row);
|
|
675
|
-
} else if (JSON.stringify(prevMap.get(id)) !== JSON.stringify(row)) {
|
|
676
|
-
updated.push(row);
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
for (const [id, row] of prevMap) {
|
|
680
|
-
if (!nextMap.has(id)) removed.push(row);
|
|
681
|
-
}
|
|
682
|
-
return { added, updated, removed };
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
// src/server/server.ts
|
|
686
|
-
var __moduleDir = import.meta.dir ?? dirname(fileURLToPath(import.meta.url));
|
|
687
|
-
async function startServer(opts) {
|
|
688
|
-
return startServerNode(opts);
|
|
689
|
-
}
|
|
690
|
-
var startServerCrossRuntime = startServer;
|
|
691
|
-
function buildServerContext(opts) {
|
|
692
|
-
const { pool, permissions, config } = opts;
|
|
693
|
-
const port = opts.port ?? config.port ?? 3e3;
|
|
694
|
-
const authConfig = {
|
|
695
|
-
jwtSecret: config.jwtSecret,
|
|
696
|
-
apiKey: config.apiKey,
|
|
697
|
-
allowPublic: true
|
|
698
|
-
};
|
|
699
|
-
const meter = new UsageMeter();
|
|
700
|
-
const subs = new SubscriptionManager(pool, permissions ?? null, meter);
|
|
701
|
-
const handleHttp = async (req) => {
|
|
702
|
-
const url = new URL(req.url);
|
|
703
|
-
const path = url.pathname;
|
|
704
|
-
const auth = await resolveAuth(
|
|
705
|
-
req.headers.get("authorization"),
|
|
706
|
-
authConfig
|
|
707
|
-
);
|
|
708
|
-
const tenantId = auth.tenantId ?? url.searchParams.get("tenantId") ?? null;
|
|
709
|
-
try {
|
|
710
|
-
return await route(req, url, path, auth, tenantId, {
|
|
711
|
-
pool,
|
|
712
|
-
permissions: permissions ?? null,
|
|
713
|
-
subs,
|
|
714
|
-
meter,
|
|
715
|
-
authConfig,
|
|
716
|
-
config,
|
|
717
|
-
oauthProviders: opts.oauthProviders ?? {}
|
|
718
|
-
});
|
|
719
|
-
} catch (err) {
|
|
720
|
-
if (err instanceof PermissionError) {
|
|
721
|
-
return json(err.toResponse(), 403);
|
|
722
|
-
}
|
|
723
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
724
|
-
return json({ error: "Internal Server Error", message: msg }, 500);
|
|
725
|
-
}
|
|
726
|
-
};
|
|
727
|
-
return { port, authConfig, subs, handleHttp };
|
|
728
|
-
}
|
|
729
|
-
async function startServerNode(opts) {
|
|
730
|
-
const { port, subs, handleHttp } = buildServerContext(opts);
|
|
731
|
-
const { startNodeServer } = await import("./server/node-adapter.js");
|
|
732
|
-
return startNodeServer({
|
|
733
|
-
port,
|
|
734
|
-
fetch: handleHttp,
|
|
735
|
-
websocket: {
|
|
736
|
-
open(ws) {
|
|
737
|
-
const id = crypto.randomUUID();
|
|
738
|
-
ws.__clientId = id;
|
|
739
|
-
subs.addClient(
|
|
740
|
-
id,
|
|
741
|
-
ws,
|
|
742
|
-
{
|
|
743
|
-
userId: null,
|
|
744
|
-
tenantId: null,
|
|
745
|
-
roles: [],
|
|
746
|
-
claims: {},
|
|
747
|
-
authenticated: false
|
|
748
|
-
},
|
|
749
|
-
null
|
|
750
|
-
);
|
|
751
|
-
},
|
|
752
|
-
async message(ws, raw) {
|
|
753
|
-
const id = ws.__clientId;
|
|
754
|
-
await subs.handleMessage(
|
|
755
|
-
id,
|
|
756
|
-
typeof raw === "string" ? raw : raw.toString()
|
|
757
|
-
);
|
|
758
|
-
},
|
|
759
|
-
close(ws) {
|
|
760
|
-
const id = ws.__clientId;
|
|
761
|
-
subs.removeClient(id);
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
function recordGraphIo(ctx, tenantId) {
|
|
767
|
-
ctx.meter.recordGraphIo(resolveUsageTenantId(tenantId));
|
|
768
|
-
}
|
|
769
|
-
async function route(req, url, path, auth, tenantId, ctx) {
|
|
770
|
-
const method = req.method.toUpperCase();
|
|
771
|
-
if (method === "GET" && path === "/__trellis/inspector.js") {
|
|
772
|
-
const candidates = [
|
|
773
|
-
join2(__moduleDir, "db", "inspector.js"),
|
|
774
|
-
// chunk lives in dist/, inspector in dist/db/
|
|
775
|
-
join2(__moduleDir, "inspector.js")
|
|
776
|
-
// chunk lives in dist/db/, inspector alongside
|
|
777
|
-
];
|
|
778
|
-
for (const p of candidates) {
|
|
779
|
-
if (existsSync2(p)) {
|
|
780
|
-
return new Response(readFileSync(p, "utf-8"), {
|
|
781
|
-
headers: { "Content-Type": "application/javascript; charset=utf-8" }
|
|
782
|
-
});
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
return new Response(
|
|
786
|
-
"/* Trellis DB Inspector: run `bun run build:inspector` first */",
|
|
787
|
-
{
|
|
788
|
-
headers: { "Content-Type": "application/javascript" }
|
|
789
|
-
}
|
|
790
|
-
);
|
|
791
|
-
}
|
|
792
|
-
if (method === "GET" && path === "/__trellis/trellis.css") {
|
|
793
|
-
const candidates = [
|
|
794
|
-
join2(__moduleDir, "db", "trellis.css"),
|
|
795
|
-
join2(__moduleDir, "trellis.css")
|
|
796
|
-
];
|
|
797
|
-
for (const p of candidates) {
|
|
798
|
-
if (existsSync2(p)) {
|
|
799
|
-
return new Response(readFileSync(p, "utf-8"), {
|
|
800
|
-
headers: { "Content-Type": "text/css; charset=utf-8" }
|
|
801
|
-
});
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
return new Response("/* Trellis CSS not found */", {
|
|
805
|
-
headers: { "Content-Type": "text/css" }
|
|
806
|
-
});
|
|
807
|
-
}
|
|
808
|
-
if (method === "GET" && (path === "/" || path === "/inspector")) {
|
|
809
|
-
const html = `<!DOCTYPE html>
|
|
810
|
-
<html lang="en">
|
|
811
|
-
<head>
|
|
812
|
-
<meta charset="UTF-8">
|
|
813
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
814
|
-
<title>Trellis DB Inspector</title>
|
|
815
|
-
<link rel="stylesheet" href="/__trellis/trellis.css">
|
|
816
|
-
</head>
|
|
817
|
-
<body>
|
|
818
|
-
<script src="/__trellis/inspector.js"></script>
|
|
819
|
-
</body>
|
|
820
|
-
</html>`;
|
|
821
|
-
return new Response(html, {
|
|
822
|
-
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
823
|
-
});
|
|
824
|
-
}
|
|
825
|
-
if (method === "GET" && path === "/health") {
|
|
826
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
827
|
-
const ops = kernel.readAllOps().length;
|
|
828
|
-
return json({
|
|
829
|
-
status: "ok",
|
|
830
|
-
ops,
|
|
831
|
-
tenants: ctx.pool.activeTenants().length
|
|
832
|
-
});
|
|
833
|
-
}
|
|
834
|
-
if (method === "GET" && path === "/admin/usage") {
|
|
835
|
-
return handleAdminUsage(req, url, ctx);
|
|
836
|
-
}
|
|
837
|
-
if (path === "/entities" || path === "/entities/") {
|
|
838
|
-
if (method === "POST") return handleCreate(req, auth, tenantId, ctx);
|
|
839
|
-
if (method === "GET") return handleList(url, auth, tenantId, ctx);
|
|
840
|
-
}
|
|
841
|
-
const entityMatch = path.match(/^\/entities\/([^/]+)$/);
|
|
842
|
-
if (entityMatch) {
|
|
843
|
-
const id = decodeURIComponent(entityMatch[1]);
|
|
844
|
-
if (method === "GET") return handleRead(id, auth, tenantId, ctx);
|
|
845
|
-
if (method === "PUT" || method === "PATCH")
|
|
846
|
-
return handleUpdate(req, id, auth, tenantId, ctx);
|
|
847
|
-
if (method === "DELETE") return handleDelete(id, auth, tenantId, ctx);
|
|
848
|
-
}
|
|
849
|
-
if (method === "POST" && path === "/query") {
|
|
850
|
-
return handleQuery(req, auth, tenantId, ctx);
|
|
851
|
-
}
|
|
852
|
-
if (method === "POST" && (path === "/ontologies" || path === "/ontologies/")) {
|
|
853
|
-
return handleCreateOntology(req, auth, tenantId, ctx);
|
|
854
|
-
}
|
|
855
|
-
if (method === "POST" && path === "/upload") {
|
|
856
|
-
return handleUpload(req, auth, tenantId, ctx);
|
|
857
|
-
}
|
|
858
|
-
const fileMatch = path.match(/^\/files\/([^/]+)$/);
|
|
859
|
-
if (method === "GET" && fileMatch) {
|
|
860
|
-
return handleFileDownload(fileMatch[1], ctx, tenantId);
|
|
861
|
-
}
|
|
862
|
-
if (method === "POST" && path === "/auth/register") {
|
|
863
|
-
return handleRegister(req, tenantId, ctx);
|
|
864
|
-
}
|
|
865
|
-
if (method === "POST" && path === "/auth/login") {
|
|
866
|
-
return handleLogin(req, tenantId, ctx);
|
|
867
|
-
}
|
|
868
|
-
const oauthMatch = path.match(/^\/auth\/oauth\/([^/]+)(\/callback)?$/);
|
|
869
|
-
if (oauthMatch) {
|
|
870
|
-
const providerName = oauthMatch[1];
|
|
871
|
-
const isCallback = !!oauthMatch[2];
|
|
872
|
-
if (isCallback)
|
|
873
|
-
return handleOAuthCallback(url, providerName, tenantId, ctx);
|
|
874
|
-
return handleOAuthRedirect(providerName, url, ctx);
|
|
875
|
-
}
|
|
876
|
-
return json({ error: "Not Found" }, 404);
|
|
877
|
-
}
|
|
878
|
-
async function handleCreate(req, auth, tenantId, ctx) {
|
|
879
|
-
const body = await req.json();
|
|
880
|
-
if (!body.type) return json({ error: "type is required" }, 400);
|
|
881
|
-
ctx.permissions?.assert(auth, body.type, "create");
|
|
882
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
883
|
-
const entityId2 = `${body.type.toLowerCase()}:${crypto.randomUUID()}`;
|
|
884
|
-
const attrs = {
|
|
885
|
-
...body.attributes
|
|
886
|
-
};
|
|
887
|
-
if (auth.userId) attrs.createdBy = auth.userId;
|
|
888
|
-
if (auth.tenantId) attrs.tenantId = auth.tenantId;
|
|
889
|
-
const result = await kernel.createEntity(
|
|
890
|
-
entityId2,
|
|
891
|
-
body.type,
|
|
892
|
-
attrs,
|
|
893
|
-
body.links
|
|
894
|
-
);
|
|
895
|
-
recordGraphIo(ctx, tenantId);
|
|
896
|
-
await ctx.subs.notify(tenantId);
|
|
897
|
-
return json({ id: entityId2, op: result.op.hash }, 201);
|
|
898
|
-
}
|
|
899
|
-
async function handleRead(id, auth, tenantId, ctx) {
|
|
900
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
901
|
-
const entity = kernel.getEntity(id);
|
|
902
|
-
if (!entity) return json({ error: "Not Found" }, 404);
|
|
903
|
-
ctx.permissions?.assert(auth, entity.type, "read", entity);
|
|
904
|
-
return json(entityToJson(entity));
|
|
905
|
-
}
|
|
906
|
-
async function handleUpdate(req, id, auth, tenantId, ctx) {
|
|
907
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
908
|
-
const entity = kernel.getEntity(id);
|
|
909
|
-
if (!entity) return json({ error: "Not Found" }, 404);
|
|
910
|
-
ctx.permissions?.assert(auth, entity.type, "update", entity);
|
|
911
|
-
const updates = await req.json();
|
|
912
|
-
await kernel.updateEntity(id, updates);
|
|
913
|
-
recordGraphIo(ctx, tenantId);
|
|
914
|
-
await ctx.subs.notify(tenantId);
|
|
915
|
-
return json({ id, updated: true });
|
|
916
|
-
}
|
|
917
|
-
async function handleDelete(id, auth, tenantId, ctx) {
|
|
918
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
919
|
-
const entity = kernel.getEntity(id);
|
|
920
|
-
if (!entity) return json({ error: "Not Found" }, 404);
|
|
921
|
-
ctx.permissions?.assert(auth, entity.type, "delete", entity);
|
|
922
|
-
await kernel.deleteEntity(id);
|
|
923
|
-
recordGraphIo(ctx, tenantId);
|
|
924
|
-
await ctx.subs.notify(tenantId);
|
|
925
|
-
return json({ id, deleted: true });
|
|
926
|
-
}
|
|
927
|
-
async function handleList(url, auth, tenantId, ctx) {
|
|
928
|
-
const type = url.searchParams.get("type") ?? void 0;
|
|
929
|
-
const limit = parseInt(url.searchParams.get("limit") ?? "100");
|
|
930
|
-
const offset = parseInt(url.searchParams.get("offset") ?? "0");
|
|
931
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
932
|
-
let entities = kernel.listEntities(type);
|
|
933
|
-
if (ctx.permissions && type) {
|
|
934
|
-
entities = entities.filter(
|
|
935
|
-
(e) => ctx.permissions.check(auth, e.type, "read", e)
|
|
936
|
-
);
|
|
937
|
-
}
|
|
938
|
-
const page = entities.slice(offset, offset + limit);
|
|
939
|
-
return json({
|
|
940
|
-
data: page.map(entityToJson),
|
|
941
|
-
total: entities.length,
|
|
942
|
-
limit,
|
|
943
|
-
offset
|
|
944
|
-
});
|
|
945
|
-
}
|
|
946
|
-
async function handleQuery(req, auth, tenantId, ctx) {
|
|
947
|
-
const body = await req.json();
|
|
948
|
-
if (!body.query) return json({ error: "query is required" }, 400);
|
|
949
|
-
let parsed;
|
|
950
|
-
try {
|
|
951
|
-
parsed = parseSimple(body.query);
|
|
952
|
-
} catch (err) {
|
|
953
|
-
return json({ error: "Invalid query", message: String(err) }, 400);
|
|
954
|
-
}
|
|
955
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
956
|
-
const result = await kernel.query(parsed);
|
|
957
|
-
recordGraphIo(ctx, tenantId);
|
|
958
|
-
const bindings = hydrateBindings(
|
|
959
|
-
kernel,
|
|
960
|
-
result.bindings
|
|
961
|
-
);
|
|
962
|
-
return json({
|
|
963
|
-
bindings,
|
|
964
|
-
executionTime: result.executionTime
|
|
965
|
-
});
|
|
966
|
-
}
|
|
967
|
-
async function handleCreateOntology(req, auth, tenantId, ctx) {
|
|
968
|
-
const schema = await req.json();
|
|
969
|
-
if (!schema || !schema["@id"] || !Array.isArray(schema.fields)) {
|
|
970
|
-
return json(
|
|
971
|
-
{ error: "A SchemaDefinition (with @id and fields) is required" },
|
|
972
|
-
400
|
|
973
|
-
);
|
|
974
|
-
}
|
|
975
|
-
if ((schema.tier ?? "user") === "core") {
|
|
976
|
-
return json({ error: "Core ontologies are immutable" }, 403);
|
|
977
|
-
}
|
|
978
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
979
|
-
const exists = kernel.listOntologies().some((ont) => ont["@id"] === schema["@id"]);
|
|
980
|
-
if (exists) {
|
|
981
|
-
return json({ id: schema["@id"], registered: false, existed: true }, 200);
|
|
982
|
-
}
|
|
983
|
-
try {
|
|
984
|
-
kernel.createOntology(schema);
|
|
985
|
-
recordGraphIo(ctx, tenantId);
|
|
986
|
-
} catch (err) {
|
|
987
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
988
|
-
if (msg.includes("already exists")) {
|
|
989
|
-
return json({ id: schema["@id"], registered: false, existed: true }, 200);
|
|
990
|
-
}
|
|
991
|
-
return json({ error: "Could not register schema", message: msg }, 409);
|
|
992
|
-
}
|
|
993
|
-
return json({ id: schema["@id"], registered: true }, 201);
|
|
994
|
-
}
|
|
995
|
-
async function handleUpload(req, auth, tenantId, ctx) {
|
|
996
|
-
if (!auth.authenticated && ctx.config.apiKey) {
|
|
997
|
-
return json({ error: "Unauthorized" }, 401);
|
|
998
|
-
}
|
|
999
|
-
const contentType = req.headers.get("content-type") ?? "application/octet-stream";
|
|
1000
|
-
const buffer = new Uint8Array(await req.arrayBuffer());
|
|
1001
|
-
const hashBuf = await crypto.subtle.digest("SHA-256", buffer);
|
|
1002
|
-
const hash = `blob:${Array.from(new Uint8Array(hashBuf)).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
1003
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
1004
|
-
const backend = kernel.getBackend();
|
|
1005
|
-
if (!backend.hasBlob(hash)) {
|
|
1006
|
-
backend.putBlob(hash, buffer);
|
|
1007
|
-
}
|
|
1008
|
-
return json({ hash, size: buffer.length, contentType }, 201);
|
|
1009
|
-
}
|
|
1010
|
-
async function handleFileDownload(hash, ctx, tenantId) {
|
|
1011
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
1012
|
-
const backend = kernel.getBackend();
|
|
1013
|
-
const blob = backend.getBlob(hash);
|
|
1014
|
-
if (!blob) return json({ error: "Not Found" }, 404);
|
|
1015
|
-
const cleanBuf = blob.buffer.slice(
|
|
1016
|
-
blob.byteOffset,
|
|
1017
|
-
blob.byteOffset + blob.byteLength
|
|
1018
|
-
);
|
|
1019
|
-
ctx.meter.recordEgress(resolveUsageTenantId(tenantId), blob.byteLength);
|
|
1020
|
-
return new Response(cleanBuf, {
|
|
1021
|
-
headers: { "Content-Type": "application/octet-stream" }
|
|
1022
|
-
});
|
|
1023
|
-
}
|
|
1024
|
-
async function handleRegister(req, tenantId, ctx) {
|
|
1025
|
-
if (!ctx.config.jwtSecret) {
|
|
1026
|
-
return json({ error: "Auth not configured (no jwtSecret)" }, 501);
|
|
1027
|
-
}
|
|
1028
|
-
const body = await req.json();
|
|
1029
|
-
if (!body.email || !body.password) {
|
|
1030
|
-
return json({ error: "email and password are required" }, 400);
|
|
1031
|
-
}
|
|
1032
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
1033
|
-
const existing = kernel.listEntities("User", { email: body.email });
|
|
1034
|
-
if (existing.length > 0) {
|
|
1035
|
-
return json({ error: "Email already registered" }, 409);
|
|
1036
|
-
}
|
|
1037
|
-
const userId = `user:${crypto.randomUUID()}`;
|
|
1038
|
-
const pwHash = await hashPassword(body.password);
|
|
1039
|
-
await kernel.createEntity(userId, "User", {
|
|
1040
|
-
email: body.email,
|
|
1041
|
-
name: body.name ?? "",
|
|
1042
|
-
passwordHash: pwHash,
|
|
1043
|
-
role: "user",
|
|
1044
|
-
...tenantId ? { tenantId } : {}
|
|
1045
|
-
});
|
|
1046
|
-
const token = await signJwt(
|
|
1047
|
-
{ sub: userId, email: body.email, roles: ["user"], tenantId },
|
|
1048
|
-
ctx.config.jwtSecret
|
|
1049
|
-
);
|
|
1050
|
-
return json({ token, userId }, 201);
|
|
1051
|
-
}
|
|
1052
|
-
async function handleLogin(req, tenantId, ctx) {
|
|
1053
|
-
if (!ctx.config.jwtSecret) {
|
|
1054
|
-
return json({ error: "Auth not configured (no jwtSecret)" }, 501);
|
|
1055
|
-
}
|
|
1056
|
-
const body = await req.json();
|
|
1057
|
-
if (!body.email || !body.password) {
|
|
1058
|
-
return json({ error: "email and password are required" }, 400);
|
|
1059
|
-
}
|
|
1060
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
1061
|
-
const users = kernel.listEntities("User", { email: body.email });
|
|
1062
|
-
if (users.length === 0) {
|
|
1063
|
-
return json({ error: "Invalid credentials" }, 401);
|
|
1064
|
-
}
|
|
1065
|
-
const user = users[0];
|
|
1066
|
-
const pwHashFact = user.facts.find((f) => f.a === "passwordHash");
|
|
1067
|
-
const roleFact = user.facts.find((f) => f.a === "role");
|
|
1068
|
-
if (!pwHashFact || !await verifyPassword(body.password, String(pwHashFact.v))) {
|
|
1069
|
-
return json({ error: "Invalid credentials" }, 401);
|
|
1070
|
-
}
|
|
1071
|
-
const role = String(roleFact?.v ?? "user");
|
|
1072
|
-
const token = await signJwt(
|
|
1073
|
-
{ sub: user.id, email: body.email, roles: [role], tenantId },
|
|
1074
|
-
ctx.config.jwtSecret
|
|
1075
|
-
);
|
|
1076
|
-
return json({ token, userId: user.id });
|
|
1077
|
-
}
|
|
1078
|
-
function handleOAuthRedirect(providerName, url, ctx) {
|
|
1079
|
-
const provider = ctx.oauthProviders[providerName] ?? getBuiltinProvider(providerName, ctx);
|
|
1080
|
-
if (!provider)
|
|
1081
|
-
return json({ error: `Unknown provider: ${providerName}` }, 400);
|
|
1082
|
-
const redirectUri = `${url.origin}/auth/oauth/${providerName}/callback`;
|
|
1083
|
-
const state = crypto.randomUUID();
|
|
1084
|
-
const authUrl = buildOAuthUrl(provider, redirectUri, state);
|
|
1085
|
-
return Response.redirect(authUrl, 302);
|
|
1086
|
-
}
|
|
1087
|
-
async function handleOAuthCallback(url, providerName, tenantId, ctx) {
|
|
1088
|
-
if (!ctx.config.jwtSecret) {
|
|
1089
|
-
return json({ error: "Auth not configured (no jwtSecret)" }, 501);
|
|
1090
|
-
}
|
|
1091
|
-
const code = url.searchParams.get("code");
|
|
1092
|
-
if (!code) return json({ error: "Missing code" }, 400);
|
|
1093
|
-
const provider = ctx.oauthProviders[providerName] ?? getBuiltinProvider(providerName, ctx);
|
|
1094
|
-
if (!provider)
|
|
1095
|
-
return json({ error: `Unknown provider: ${providerName}` }, 400);
|
|
1096
|
-
const redirectUri = `${url.origin}/auth/oauth/${providerName}/callback`;
|
|
1097
|
-
let profile;
|
|
1098
|
-
try {
|
|
1099
|
-
profile = await exchangeOAuthCode(provider, code, redirectUri);
|
|
1100
|
-
} catch (err) {
|
|
1101
|
-
return json({ error: "OAuth exchange failed", message: String(err) }, 400);
|
|
1102
|
-
}
|
|
1103
|
-
const kernel = await ctx.pool.preload(tenantId);
|
|
1104
|
-
const oauthId = `oauth:${providerName}:${profile.id}`;
|
|
1105
|
-
let users = kernel.listEntities("User", { oauthId });
|
|
1106
|
-
let userId;
|
|
1107
|
-
if (users.length === 0) {
|
|
1108
|
-
userId = `user:${crypto.randomUUID()}`;
|
|
1109
|
-
await kernel.createEntity(userId, "User", {
|
|
1110
|
-
email: profile.email,
|
|
1111
|
-
name: profile.name,
|
|
1112
|
-
avatarUrl: profile.avatarUrl ?? "",
|
|
1113
|
-
oauthId,
|
|
1114
|
-
oauthProvider: providerName,
|
|
1115
|
-
role: "user",
|
|
1116
|
-
...tenantId ? { tenantId } : {}
|
|
1117
|
-
});
|
|
1118
|
-
} else {
|
|
1119
|
-
userId = users[0].id;
|
|
1120
|
-
}
|
|
1121
|
-
const token = await signJwt(
|
|
1122
|
-
{ sub: userId, email: profile.email, roles: ["user"], tenantId },
|
|
1123
|
-
ctx.config.jwtSecret
|
|
1124
|
-
);
|
|
1125
|
-
return json({ token, userId });
|
|
1126
|
-
}
|
|
1127
|
-
function getBuiltinProvider(name, ctx) {
|
|
1128
|
-
if (name === "google") {
|
|
1129
|
-
const cid = process.env.GOOGLE_CLIENT_ID;
|
|
1130
|
-
const csec = process.env.GOOGLE_CLIENT_SECRET;
|
|
1131
|
-
if (!cid || !csec) return null;
|
|
1132
|
-
return { ...GOOGLE_PROVIDER, clientId: cid, clientSecret: csec };
|
|
1133
|
-
}
|
|
1134
|
-
if (name === "github") {
|
|
1135
|
-
const cid = process.env.GITHUB_CLIENT_ID;
|
|
1136
|
-
const csec = process.env.GITHUB_CLIENT_SECRET;
|
|
1137
|
-
if (!cid || !csec) return null;
|
|
1138
|
-
return { ...GITHUB_PROVIDER, clientId: cid, clientSecret: csec };
|
|
1139
|
-
}
|
|
1140
|
-
return null;
|
|
1141
|
-
}
|
|
1142
|
-
async function hashPassword(password) {
|
|
1143
|
-
const salt = crypto.randomUUID().replace(/-/g, "");
|
|
1144
|
-
const enc = new TextEncoder();
|
|
1145
|
-
const keyMat = await crypto.subtle.importKey(
|
|
1146
|
-
"raw",
|
|
1147
|
-
enc.encode(password),
|
|
1148
|
-
"PBKDF2",
|
|
1149
|
-
false,
|
|
1150
|
-
["deriveBits"]
|
|
1151
|
-
);
|
|
1152
|
-
const bits = await crypto.subtle.deriveBits(
|
|
1153
|
-
{
|
|
1154
|
-
name: "PBKDF2",
|
|
1155
|
-
salt: enc.encode(salt),
|
|
1156
|
-
iterations: 1e5,
|
|
1157
|
-
hash: "SHA-256"
|
|
1158
|
-
},
|
|
1159
|
-
keyMat,
|
|
1160
|
-
256
|
|
1161
|
-
);
|
|
1162
|
-
const hash = Array.from(new Uint8Array(bits)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1163
|
-
return `${salt}:${hash}`;
|
|
1164
|
-
}
|
|
1165
|
-
async function verifyPassword(password, stored) {
|
|
1166
|
-
const [salt, expectedHash] = stored.split(":");
|
|
1167
|
-
if (!salt || !expectedHash) return false;
|
|
1168
|
-
const enc = new TextEncoder();
|
|
1169
|
-
const keyMat = await crypto.subtle.importKey(
|
|
1170
|
-
"raw",
|
|
1171
|
-
enc.encode(password),
|
|
1172
|
-
"PBKDF2",
|
|
1173
|
-
false,
|
|
1174
|
-
["deriveBits"]
|
|
1175
|
-
);
|
|
1176
|
-
const bits = await crypto.subtle.deriveBits(
|
|
1177
|
-
{
|
|
1178
|
-
name: "PBKDF2",
|
|
1179
|
-
salt: enc.encode(salt),
|
|
1180
|
-
iterations: 1e5,
|
|
1181
|
-
hash: "SHA-256"
|
|
1182
|
-
},
|
|
1183
|
-
keyMat,
|
|
1184
|
-
256
|
|
1185
|
-
);
|
|
1186
|
-
const hash = Array.from(new Uint8Array(bits)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1187
|
-
return hash === expectedHash;
|
|
1188
|
-
}
|
|
1189
|
-
function handleAdminUsage(req, url, ctx) {
|
|
1190
|
-
if (!process.env.TURTLEDB_ADMIN_KEY) {
|
|
1191
|
-
return json({ error: "Admin usage not configured" }, 501);
|
|
1192
|
-
}
|
|
1193
|
-
if (!verifyAdminKey(req)) {
|
|
1194
|
-
return json({ error: "Unauthorized" }, 401);
|
|
1195
|
-
}
|
|
1196
|
-
const tenant = url.searchParams.get("tenant");
|
|
1197
|
-
if (!tenant) {
|
|
1198
|
-
return json({ error: "tenant query param is required" }, 400);
|
|
1199
|
-
}
|
|
1200
|
-
const refresh = url.searchParams.get("refresh") === "1";
|
|
1201
|
-
if (refresh) {
|
|
1202
|
-
ctx.meter.sampleStorage(ctx.pool, tenant);
|
|
1203
|
-
}
|
|
1204
|
-
const day = url.searchParams.get("day") ?? void 0;
|
|
1205
|
-
return json(ctx.meter.getUsage(tenant, day));
|
|
1206
|
-
}
|
|
1207
|
-
function entityToJson(entity) {
|
|
1208
|
-
return entityRecordToPlain(entity);
|
|
1209
|
-
}
|
|
1210
|
-
function json(data, status = 200) {
|
|
1211
|
-
return new Response(JSON.stringify(data), {
|
|
1212
|
-
status,
|
|
1213
|
-
headers: { "Content-Type": "application/json" }
|
|
1214
|
-
});
|
|
1215
|
-
}
|
|
1216
|
-
|
|
1217
|
-
export {
|
|
1218
|
-
ANONYMOUS,
|
|
1219
|
-
signJwt,
|
|
1220
|
-
verifyJwt,
|
|
1221
|
-
resolveAuth,
|
|
1222
|
-
GOOGLE_PROVIDER,
|
|
1223
|
-
GITHUB_PROVIDER,
|
|
1224
|
-
buildOAuthUrl,
|
|
1225
|
-
exchangeOAuthCode,
|
|
1226
|
-
PermissionRegistry,
|
|
1227
|
-
PermissionError,
|
|
1228
|
-
PUBLIC_READ,
|
|
1229
|
-
FULLY_PUBLIC,
|
|
1230
|
-
OWNER_ONLY,
|
|
1231
|
-
ADMIN_ONLY,
|
|
1232
|
-
resolveUsageTenantId,
|
|
1233
|
-
dayKey,
|
|
1234
|
-
sampleTenantStorage,
|
|
1235
|
-
verifyAdminKey,
|
|
1236
|
-
UsageMeter,
|
|
1237
|
-
SubscriptionManager,
|
|
1238
|
-
startServer,
|
|
1239
|
-
startServerCrossRuntime
|
|
1240
|
-
};
|