trellis 3.2.0 → 3.2.2
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/CHANGELOG.md +7 -0
- package/README.md +61 -171
- package/dist/browser/index.d.ts +18 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +95 -0
- package/dist/{chunk-3ETIIPPB.js → chunk-2W3MHTMG.js} +190 -27
- package/dist/{chunk-MBNBTJCR.js → chunk-6GEZ6DN5.js} +2 -2
- package/dist/chunk-7ZFRVCUE.js +211 -0
- package/dist/chunk-CAG4FULI.js +121 -0
- package/dist/{chunk-GD5QJXSS.js → chunk-FWRS4CSC.js} +2 -2
- package/dist/{chunk-36VSSTL7.js → chunk-GU374KWZ.js} +1 -1
- package/dist/{chunk-3GDRZTAW.js → chunk-H6JB3PZ3.js} +1 -1
- package/dist/{chunk-ZHVI7BQN.js → chunk-IZX2PLIB.js} +191 -28
- package/dist/chunk-J2TXUFCZ.js +289 -0
- package/dist/{chunk-BJ7EZ7FP.js → chunk-JHHEXEDM.js} +17 -0
- package/dist/{chunk-X762XWVC.js → chunk-KIJITUZB.js} +1 -1
- package/dist/{chunk-7WQGTFVJ.js → chunk-L5N5PR2S.js} +130 -75
- package/dist/{chunk-BXSTJVE3.js → chunk-N6MYZT4O.js} +2 -1
- package/dist/{chunk-KKDRMIV6.js → chunk-QB5ISE47.js} +1 -1
- package/dist/{chunk-HO4TURXW.js → chunk-S3XLFZ27.js} +28 -11
- package/dist/{chunk-BQBUVMRN.js → chunk-S6GBJ2ZB.js} +25 -14
- package/dist/{chunk-IUWVEEOX.js → chunk-SGMDTWJJ.js} +4 -0
- package/dist/{chunk-FZVCXDYW.js → chunk-UQISRW6T.js} +65 -12
- package/dist/{chunk-B3ZIFA2O.js → chunk-VBYUTRXX.js} +1 -1
- package/dist/cli/deploy-cli.d.ts +18 -0
- package/dist/cli/deploy-cli.d.ts.map +1 -0
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +153 -100
- package/dist/client/index.browser.d.ts +29 -0
- package/dist/client/index.browser.d.ts.map +1 -0
- package/dist/client/index.browser.js +64 -0
- package/dist/client/index.js +10 -10
- package/dist/client/sdk.browser.d.ts +104 -0
- package/dist/client/sdk.browser.d.ts.map +1 -0
- package/dist/{sdk-LZ7W3EEY.js → client/sdk.browser.js} +2 -2
- package/dist/client/sdk.js +1 -1
- package/dist/core/index.js +6 -6
- package/dist/db/index.js +18 -18
- package/dist/db/inspector.js +6 -6
- package/dist/db/trellis.css +1 -1
- package/dist/decisions/index.js +2 -2
- package/dist/deploy-LQ7GUGJ5.js +9 -0
- package/dist/{deploy-66EC752W.js → deploy-YNVG5E4E.js} +1 -1
- package/dist/deploy-cli-24BCHAXY.js +67 -0
- package/dist/deploy-cli-C35HTITO.js +67 -0
- package/dist/embeddings/auto-embed.d.ts.map +1 -1
- package/dist/embeddings/index.js +1 -1
- package/dist/embeddings/store.d.ts.map +1 -1
- package/dist/engine.d.ts +27 -7
- package/dist/engine.d.ts.map +1 -1
- package/dist/index.js +6 -6
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/react/index.js +2 -2
- package/dist/react/schema-hooks.js +7 -7
- package/dist/{remote-manager-SG545WNY.js → remote-manager-ODE3T2KR.js} +5 -5
- package/dist/scaffold/seed.d.ts.map +1 -1
- package/dist/scaffold/write.d.ts +1 -1
- package/dist/scaffold/write.d.ts.map +1 -1
- package/dist/schema/index.js +4 -3
- package/dist/server/deploy-meta.d.ts +25 -0
- package/dist/server/deploy-meta.d.ts.map +1 -0
- package/dist/server/deploy.d.ts +7 -2
- package/dist/server/deploy.d.ts.map +1 -1
- package/dist/server/index.d.ts +5 -2
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +52 -18
- package/dist/server/realtime.d.ts +4 -1
- package/dist/server/realtime.d.ts.map +1 -1
- package/dist/server/server.d.ts +1 -0
- package/dist/server/server.d.ts.map +1 -1
- package/dist/server/sprites.d.ts +18 -1
- package/dist/server/sprites.d.ts.map +1 -1
- package/dist/server/tenancy.d.ts +4 -0
- package/dist/server/tenancy.d.ts.map +1 -1
- package/dist/server/usage-meter.d.ts +53 -0
- package/dist/server/usage-meter.d.ts.map +1 -0
- package/dist/{server-IGBIIJSF.js → server-MB3OPSPI.js} +6 -1
- package/dist/{server-BOH7M4TT.js → server-ZVWGLLRF.js} +7 -2
- package/dist/sprites-KQGTGM6W.js +27 -0
- package/dist/{tenancy-S676GLID.js → tenancy-NBLLGCNJ.js} +1 -1
- package/dist/{tenancy-OP34NFFS.js → tenancy-POMWQP6M.js} +5 -3
- package/dist/vcs/index.js +3 -3
- package/dist/vcs/types.d.ts +2 -0
- package/dist/vcs/types.d.ts.map +1 -1
- package/package.json +17 -6
- package/dist/better-sqlite-backend-PII64VE6.js +0 -159
- package/dist/better-sqlite-backend-VUBVQ7SN.js +0 -209
- package/dist/better-sqlite-backend-Y3AQN65E.js +0 -159
- package/dist/better-sqlite-backend-Y3M7DXOX.js +0 -159
- package/dist/boot-middleware-FJDGVUM4.js +0 -9
- package/dist/boot-middleware-MLJUTLUM.js +0 -9
- package/dist/boot-middleware-ZZPDZNYR.js +0 -9
- package/dist/chunk-276LKLZR.js +0 -359
- package/dist/chunk-2CX5UCRV.js +0 -111
- package/dist/chunk-2ESYSVXG.js +0 -48
- package/dist/chunk-2I5JU73Y.js +0 -340
- package/dist/chunk-2UNSRRNB.js +0 -171
- package/dist/chunk-335UEHQR.js +0 -907
- package/dist/chunk-4CF2L46N.js +0 -29
- package/dist/chunk-5CINODKT.js +0 -41
- package/dist/chunk-5ESGWJ5L.js +0 -45
- package/dist/chunk-5FGLQGMF.js +0 -1676
- package/dist/chunk-5IQZFITY.js +0 -357
- package/dist/chunk-5JWFAQDW.js +0 -150
- package/dist/chunk-62UHTVU3.js +0 -141
- package/dist/chunk-66UJQT2I.js +0 -35
- package/dist/chunk-6RNNVOAS.js +0 -355
- package/dist/chunk-6X23PZ6H.js +0 -969
- package/dist/chunk-7C7LL6MB.js +0 -315
- package/dist/chunk-7F4HM3JG.js +0 -394
- package/dist/chunk-7KJ7T4D3.js +0 -910
- package/dist/chunk-7QQQNUB5.js +0 -92
- package/dist/chunk-7QWJBS72.js +0 -946
- package/dist/chunk-7R36OZK3.js +0 -957
- package/dist/chunk-7UPKCOHE.js +0 -946
- package/dist/chunk-A3BONW34.js +0 -35
- package/dist/chunk-AHMDVHBL.js +0 -141
- package/dist/chunk-AW6A4OZY.js +0 -171
- package/dist/chunk-BJ5EKCJ5.js +0 -458
- package/dist/chunk-BRGYDO7D.js +0 -223
- package/dist/chunk-C5KPSEDN.js +0 -359
- package/dist/chunk-CCTNYTUC.js +0 -940
- package/dist/chunk-CYQ2OVD2.js +0 -35
- package/dist/chunk-DDAK7YOE.js +0 -299
- package/dist/chunk-DRILKBY6.js +0 -965
- package/dist/chunk-DXE24HNN.js +0 -45
- package/dist/chunk-E7ICUNW7.js +0 -945
- package/dist/chunk-EAL2PUOE.js +0 -10022
- package/dist/chunk-ELT7MLZB.js +0 -109
- package/dist/chunk-EWEIRF6G.js +0 -171
- package/dist/chunk-F5VDGQJC.js +0 -120
- package/dist/chunk-FCPL3IEQ.js +0 -98
- package/dist/chunk-FDPKYSV7.js +0 -96
- package/dist/chunk-FES3TC24.js +0 -171
- package/dist/chunk-FOWKR5TW.js +0 -129
- package/dist/chunk-G3XIHPSQ.js +0 -361
- package/dist/chunk-GKJLYLVU.js +0 -359
- package/dist/chunk-GNXHXNVQ.js +0 -113
- package/dist/chunk-GSR6ILTM.js +0 -277
- package/dist/chunk-GWRIMRSX.js +0 -45
- package/dist/chunk-H72UW2HJ.js +0 -45
- package/dist/chunk-HGI74PXB.js +0 -7417
- package/dist/chunk-HGRA37LO.js +0 -145
- package/dist/chunk-HXSRQO3L.js +0 -145
- package/dist/chunk-IG2X2BVO.js +0 -373
- package/dist/chunk-IIJVDD54.js +0 -373
- package/dist/chunk-IX4BBOIT.js +0 -394
- package/dist/chunk-IXU4RMQM.js +0 -349
- package/dist/chunk-J6OUIION.js +0 -857
- package/dist/chunk-K46RNFDE.js +0 -171
- package/dist/chunk-KAGU2XMY.js +0 -359
- package/dist/chunk-KCVYJNVX.js +0 -394
- package/dist/chunk-KYLIQ3YI.js +0 -399
- package/dist/chunk-KZYJJIRN.js +0 -946
- package/dist/chunk-LFOX744K.js +0 -96
- package/dist/chunk-LHOVJEWR.js +0 -7403
- package/dist/chunk-LOPXTPF3.js +0 -120
- package/dist/chunk-LZR3VIFU.js +0 -907
- package/dist/chunk-MCKGQKYU.js +0 -15
- package/dist/chunk-MU6EOS6F.js +0 -0
- package/dist/chunk-MWRQ2TXT.js +0 -357
- package/dist/chunk-NO73OK2I.js +0 -102
- package/dist/chunk-NPE2YJHK.js +0 -394
- package/dist/chunk-NSDXU6QX.js +0 -2213
- package/dist/chunk-NXIRDSZ6.js +0 -145
- package/dist/chunk-NZWFNHCS.js +0 -407
- package/dist/chunk-OB4CMMX6.js +0 -260
- package/dist/chunk-OBKU74FU.js +0 -7411
- package/dist/chunk-OQNDWRDE.js +0 -145
- package/dist/chunk-OVWAJMB6.js +0 -394
- package/dist/chunk-PDHLBTTD.js +0 -45
- package/dist/chunk-PEQNRKLG.js +0 -210
- package/dist/chunk-QERIS7QY.js +0 -7403
- package/dist/chunk-QHA2DM3C.js +0 -373
- package/dist/chunk-QLM4HSYC.js +0 -45
- package/dist/chunk-S2OT3TQJ.js +0 -283
- package/dist/chunk-S5PHSN5K.js +0 -907
- package/dist/chunk-SIAA4J6H.js +0 -21
- package/dist/chunk-SQBNLUIA.js +0 -171
- package/dist/chunk-STLN6A6B.js +0 -355
- package/dist/chunk-U7HV7GU2.js +0 -17
- package/dist/chunk-UGZHOGRA.js +0 -39
- package/dist/chunk-UICF66FS.js +0 -359
- package/dist/chunk-UK3EQREE.js +0 -1078
- package/dist/chunk-UPKPURVY.js +0 -394
- package/dist/chunk-URC74VCN.js +0 -959
- package/dist/chunk-V3G7Q3QQ.js +0 -102
- package/dist/chunk-VUJ6SA55.js +0 -303
- package/dist/chunk-VUJQLIML.js +0 -141
- package/dist/chunk-VWKLKLYB.js +0 -267
- package/dist/chunk-VYC3RZMK.js +0 -277
- package/dist/chunk-WMERMSWI.js +0 -154
- package/dist/chunk-WMR777PO.js +0 -2213
- package/dist/chunk-X46IECAC.js +0 -517
- package/dist/chunk-XEN3OEYY.js +0 -2234
- package/dist/chunk-XZQ66K7A.js +0 -124
- package/dist/chunk-YY3GF7DH.js +0 -7411
- package/dist/chunk-ZE5R3H4C.js +0 -907
- package/dist/chunk-ZMN5LUB7.js +0 -7411
- package/dist/chunk-ZUV4MD5U.js +0 -94
- package/dist/config-KMY6RRK3.js +0 -19
- package/dist/config-VDMK2DUJ.js +0 -19
- package/dist/deploy-SO7AFK6L.js +0 -9
- package/dist/engine-7GXBM4IT.js +0 -7
- package/dist/engine-NSR6BIF7.js +0 -7
- package/dist/factory-2P64OC7M.js +0 -34
- package/dist/factory-YP4ZZK5K.js +0 -34
- package/dist/import-AJLYHFIA.js +0 -10
- package/dist/launch-explorer-AI6L2AWJ.js +0 -91
- package/dist/query-GJL3CVGN.js +0 -31
- package/dist/query-MBJSK3EB.js +0 -31
- package/dist/query-TJHEVSKL.js +0 -31
- package/dist/query-WUIKOHPE.js +0 -524
- package/dist/remote-manager-BLJZ6KF6.js +0 -224
- package/dist/remote-manager-BPYE46SI.js +0 -223
- package/dist/remote-manager-FMESEAFA.js +0 -224
- package/dist/remote-manager-K2WZ5RHY.js +0 -223
- package/dist/remote-manager-SG5PQKCH.js +0 -224
- package/dist/remote-manager-WGP6MIQZ.js +0 -224
- package/dist/sdk-3KBB3E6V.js +0 -16
- package/dist/sdk-4ZQO6UTU.js +0 -16
- package/dist/sdk-6JA6GV3G.js +0 -16
- package/dist/sdk-6VTP5UTZ.js +0 -16
- package/dist/sdk-7VS6TYCD.js +0 -16
- package/dist/sdk-HQ3FTLRT.js +0 -16
- package/dist/sdk-HZ7NU3XE.js +0 -15
- package/dist/sdk-KBQE2OXT.js +0 -16
- package/dist/sdk-MSCDZ7JU.js +0 -15
- package/dist/sdk-WNZOGO3S.js +0 -15
- package/dist/sdk-YLV33ZCW.js +0 -9
- package/dist/sdk-ZSUD2LLJ.js +0 -16
- package/dist/server-AFXFFBWA.js +0 -11
- package/dist/server-AGHC4VUL.js +0 -11
- package/dist/server-DBUY2KY5.js +0 -11
- package/dist/server-GWBQJPRG.js +0 -11
- package/dist/server-JZZFULVU.js +0 -11
- package/dist/server-L5XAF4M5.js +0 -11
- package/dist/server-NYFUHANA.js +0 -12
- package/dist/server-OABUB2LO.js +0 -12
- package/dist/server-P2CKZWWV.js +0 -12
- package/dist/sprites-XVSMQLSI.js +0 -15
- package/dist/sql-wasm-FORCZFHZ.js +0 -2148
- package/dist/sql-wasm-JZH76RLO.js +0 -2148
- package/dist/sqljs-backend-CJQOIQYE.js +0 -266
- package/dist/sqljs-backend-KWXBUDUO.js +0 -266
- package/dist/state-demo.bundle.js +0 -1033
- package/dist/tenancy-CBWYEVUB.js +0 -11
- package/dist/tenancy-FO6WVYFN.js +0 -13
- package/dist/tenancy-FWDBESMX.js +0 -14
- package/dist/tenancy-HGPIS5QA.js +0 -13
- package/dist/tenancy-HXFALA37.js +0 -14
- package/dist/tenancy-V7ARWNNV.js +0 -14
- package/dist/tenancy-ZDN4GXK5.js +0 -13
- package/dist/tenancy-ZT5VMY7B.js +0 -14
- package/dist/vm-config-YZRJ3KUB.js +0 -21
- /package/dist/{chunk-2BRTCEHB.js → chunk-PZ4XYZ4J.js} +0 -0
- /package/dist/{chunk-EO3J7GRP.js → chunk-WXSWA3MV.js} +0 -0
package/dist/chunk-KZYJJIRN.js
DELETED
|
@@ -1,946 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
parseSimple
|
|
3
|
-
} from "./chunk-X46IECAC.js";
|
|
4
|
-
import {
|
|
5
|
-
QueryEngine
|
|
6
|
-
} from "./chunk-2I5JU73Y.js";
|
|
7
|
-
|
|
8
|
-
// src/server/server.ts
|
|
9
|
-
import { existsSync, readFileSync } from "fs";
|
|
10
|
-
import { dirname, join } from "path";
|
|
11
|
-
import { fileURLToPath } from "url";
|
|
12
|
-
|
|
13
|
-
// src/server/auth.ts
|
|
14
|
-
var ANONYMOUS = {
|
|
15
|
-
userId: null,
|
|
16
|
-
tenantId: null,
|
|
17
|
-
roles: [],
|
|
18
|
-
claims: {},
|
|
19
|
-
authenticated: false
|
|
20
|
-
};
|
|
21
|
-
function base64UrlEncode(input) {
|
|
22
|
-
return btoa(String.fromCharCode(...input)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
23
|
-
}
|
|
24
|
-
function base64UrlDecode(input) {
|
|
25
|
-
const padded = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
26
|
-
const padLen = (4 - padded.length % 4) % 4;
|
|
27
|
-
const base64 = padded + "=".repeat(padLen);
|
|
28
|
-
const binary = atob(base64);
|
|
29
|
-
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
30
|
-
}
|
|
31
|
-
async function hmacKey(secret) {
|
|
32
|
-
return crypto.subtle.importKey(
|
|
33
|
-
"raw",
|
|
34
|
-
new TextEncoder().encode(secret),
|
|
35
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
36
|
-
false,
|
|
37
|
-
["sign", "verify"]
|
|
38
|
-
);
|
|
39
|
-
}
|
|
40
|
-
async function signJwt(payload, secret, expiresInSeconds = 86400) {
|
|
41
|
-
const header = { alg: "HS256", typ: "JWT" };
|
|
42
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
43
|
-
const claims = { iat: now, exp: now + expiresInSeconds, ...payload };
|
|
44
|
-
const enc = new TextEncoder();
|
|
45
|
-
const headerB64 = base64UrlEncode(enc.encode(JSON.stringify(header)));
|
|
46
|
-
const payloadB64 = base64UrlEncode(enc.encode(JSON.stringify(claims)));
|
|
47
|
-
const signing = `${headerB64}.${payloadB64}`;
|
|
48
|
-
const key = await hmacKey(secret);
|
|
49
|
-
const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signing));
|
|
50
|
-
const sigB64 = base64UrlEncode(new Uint8Array(sig));
|
|
51
|
-
return `${signing}.${sigB64}`;
|
|
52
|
-
}
|
|
53
|
-
async function verifyJwt(token, secret) {
|
|
54
|
-
const parts = token.split(".");
|
|
55
|
-
if (parts.length !== 3) return null;
|
|
56
|
-
const [headerB64, payloadB64, sigB64] = parts;
|
|
57
|
-
const enc = new TextEncoder();
|
|
58
|
-
const signing = `${headerB64}.${payloadB64}`;
|
|
59
|
-
try {
|
|
60
|
-
const key = await hmacKey(secret);
|
|
61
|
-
const sigRaw = base64UrlDecode(sigB64);
|
|
62
|
-
const sigBuf = sigRaw.buffer.slice(
|
|
63
|
-
sigRaw.byteOffset,
|
|
64
|
-
sigRaw.byteOffset + sigRaw.byteLength
|
|
65
|
-
);
|
|
66
|
-
const valid = await crypto.subtle.verify(
|
|
67
|
-
"HMAC",
|
|
68
|
-
key,
|
|
69
|
-
sigBuf,
|
|
70
|
-
enc.encode(signing)
|
|
71
|
-
);
|
|
72
|
-
if (!valid) return null;
|
|
73
|
-
const claims = JSON.parse(
|
|
74
|
-
new TextDecoder().decode(base64UrlDecode(payloadB64))
|
|
75
|
-
);
|
|
76
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
77
|
-
if (typeof claims.exp === "number" && claims.exp < now) return null;
|
|
78
|
-
return claims;
|
|
79
|
-
} catch {
|
|
80
|
-
return null;
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
async function resolveAuth(authHeader, config) {
|
|
84
|
-
if (!authHeader) {
|
|
85
|
-
return config.allowPublic === false ? { ...ANONYMOUS, authenticated: false } : ANONYMOUS;
|
|
86
|
-
}
|
|
87
|
-
const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : authHeader;
|
|
88
|
-
if (config.apiKey && token === config.apiKey) {
|
|
89
|
-
return {
|
|
90
|
-
userId: "service",
|
|
91
|
-
tenantId: null,
|
|
92
|
-
roles: ["admin"],
|
|
93
|
-
claims: { sub: "service" },
|
|
94
|
-
authenticated: true
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
if (config.jwtSecret) {
|
|
98
|
-
const claims = await verifyJwt(token, config.jwtSecret);
|
|
99
|
-
if (claims) {
|
|
100
|
-
return {
|
|
101
|
-
userId: claims.sub ?? null,
|
|
102
|
-
tenantId: claims.tenantId ?? null,
|
|
103
|
-
roles: Array.isArray(claims.roles) ? claims.roles : typeof claims.role === "string" ? [claims.role] : [],
|
|
104
|
-
claims,
|
|
105
|
-
authenticated: true
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
return ANONYMOUS;
|
|
110
|
-
}
|
|
111
|
-
var GOOGLE_PROVIDER = {
|
|
112
|
-
name: "google",
|
|
113
|
-
authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
114
|
-
tokenUrl: "https://oauth2.googleapis.com/token",
|
|
115
|
-
userInfoUrl: "https://www.googleapis.com/oauth2/v3/userinfo",
|
|
116
|
-
scopes: ["openid", "email", "profile"]
|
|
117
|
-
};
|
|
118
|
-
var GITHUB_PROVIDER = {
|
|
119
|
-
name: "github",
|
|
120
|
-
authUrl: "https://github.com/login/oauth/authorize",
|
|
121
|
-
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
122
|
-
userInfoUrl: "https://api.github.com/user",
|
|
123
|
-
scopes: ["read:user", "user:email"]
|
|
124
|
-
};
|
|
125
|
-
function buildOAuthUrl(provider, redirectUri, state) {
|
|
126
|
-
const params = new URLSearchParams({
|
|
127
|
-
client_id: provider.clientId,
|
|
128
|
-
redirect_uri: redirectUri,
|
|
129
|
-
response_type: "code",
|
|
130
|
-
scope: provider.scopes.join(" "),
|
|
131
|
-
state
|
|
132
|
-
});
|
|
133
|
-
return `${provider.authUrl}?${params}`;
|
|
134
|
-
}
|
|
135
|
-
async function exchangeOAuthCode(provider, code, redirectUri) {
|
|
136
|
-
const tokenRes = await fetch(provider.tokenUrl, {
|
|
137
|
-
method: "POST",
|
|
138
|
-
headers: {
|
|
139
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
140
|
-
Accept: "application/json"
|
|
141
|
-
},
|
|
142
|
-
body: new URLSearchParams({
|
|
143
|
-
client_id: provider.clientId,
|
|
144
|
-
client_secret: provider.clientSecret,
|
|
145
|
-
code,
|
|
146
|
-
redirect_uri: redirectUri,
|
|
147
|
-
grant_type: "authorization_code"
|
|
148
|
-
})
|
|
149
|
-
});
|
|
150
|
-
if (!tokenRes.ok) {
|
|
151
|
-
throw new Error(`OAuth token exchange failed: ${tokenRes.status}`);
|
|
152
|
-
}
|
|
153
|
-
const tokenData = await tokenRes.json();
|
|
154
|
-
const accessToken = tokenData.access_token;
|
|
155
|
-
const userRes = await fetch(provider.userInfoUrl, {
|
|
156
|
-
headers: {
|
|
157
|
-
Authorization: `Bearer ${accessToken}`,
|
|
158
|
-
Accept: "application/json"
|
|
159
|
-
}
|
|
160
|
-
});
|
|
161
|
-
if (!userRes.ok) {
|
|
162
|
-
throw new Error(`OAuth user info fetch failed: ${userRes.status}`);
|
|
163
|
-
}
|
|
164
|
-
const user = await userRes.json();
|
|
165
|
-
return {
|
|
166
|
-
id: String(user.id ?? user.sub ?? ""),
|
|
167
|
-
email: String(user.email ?? ""),
|
|
168
|
-
name: String(user.name ?? user.login ?? ""),
|
|
169
|
-
avatarUrl: user.picture ?? user.avatar_url ?? void 0
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// src/server/permissions.ts
|
|
174
|
-
var PermissionRegistry = class {
|
|
175
|
-
rules = /* @__PURE__ */ new Map();
|
|
176
|
-
defaultRule = "authenticated";
|
|
177
|
-
/**
|
|
178
|
-
* Register permissions for an entity type.
|
|
179
|
-
*/
|
|
180
|
-
register(entityType, permissions) {
|
|
181
|
-
this.rules.set(entityType, permissions);
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Set the fallback rule used when an entity type has no declared permissions.
|
|
185
|
-
*/
|
|
186
|
-
setDefault(rule) {
|
|
187
|
-
this.defaultRule = rule;
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* Get the permission rule for a specific operation on an entity type.
|
|
191
|
-
* Falls back to the default rule if not declared.
|
|
192
|
-
*/
|
|
193
|
-
getRule(entityType, op) {
|
|
194
|
-
const def = this.rules.get(entityType);
|
|
195
|
-
return def?.[op] ?? this.defaultRule;
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* Check whether an auth context is allowed to perform an operation.
|
|
199
|
-
*/
|
|
200
|
-
check(auth, entityType, op, entity = null) {
|
|
201
|
-
const rule = this.getRule(entityType, op);
|
|
202
|
-
return evaluateRule(rule, auth, entity);
|
|
203
|
-
}
|
|
204
|
-
/**
|
|
205
|
-
* Assert access — throws a PermissionError if denied.
|
|
206
|
-
*/
|
|
207
|
-
assert(auth, entityType, op, entity = null) {
|
|
208
|
-
if (!this.check(auth, entityType, op, entity)) {
|
|
209
|
-
throw new PermissionError(auth, entityType, op);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
};
|
|
213
|
-
function evaluateRule(rule, auth, entity) {
|
|
214
|
-
if (rule === "public") {
|
|
215
|
-
return true;
|
|
216
|
-
}
|
|
217
|
-
if (rule === "authenticated") {
|
|
218
|
-
return auth.authenticated;
|
|
219
|
-
}
|
|
220
|
-
if (rule === "own") {
|
|
221
|
-
if (!auth.authenticated || !auth.userId) return false;
|
|
222
|
-
const ownerFact = entity?.facts.find(
|
|
223
|
-
(f) => f.a === "ownerId" || f.a === "createdBy"
|
|
224
|
-
);
|
|
225
|
-
return ownerFact?.v === auth.userId;
|
|
226
|
-
}
|
|
227
|
-
if (typeof rule === "object") {
|
|
228
|
-
if ("role" in rule) {
|
|
229
|
-
return auth.roles.includes(rule.role);
|
|
230
|
-
}
|
|
231
|
-
if ("roles" in rule) {
|
|
232
|
-
return rule.roles.some((r) => auth.roles.includes(r));
|
|
233
|
-
}
|
|
234
|
-
if ("fn" in rule) {
|
|
235
|
-
try {
|
|
236
|
-
return rule.fn(auth, entity);
|
|
237
|
-
} catch {
|
|
238
|
-
return false;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
return false;
|
|
243
|
-
}
|
|
244
|
-
var PermissionError = class extends Error {
|
|
245
|
-
constructor(auth, entityType, op) {
|
|
246
|
-
const who = auth.authenticated ? `user:${auth.userId}` : "anonymous";
|
|
247
|
-
super(`Permission denied: ${who} cannot ${op} ${entityType}`);
|
|
248
|
-
this.auth = auth;
|
|
249
|
-
this.entityType = entityType;
|
|
250
|
-
this.op = op;
|
|
251
|
-
this.name = "PermissionError";
|
|
252
|
-
}
|
|
253
|
-
toResponse() {
|
|
254
|
-
return {
|
|
255
|
-
error: "Forbidden",
|
|
256
|
-
message: this.message,
|
|
257
|
-
code: 403
|
|
258
|
-
};
|
|
259
|
-
}
|
|
260
|
-
};
|
|
261
|
-
var PUBLIC_READ = {
|
|
262
|
-
read: "public",
|
|
263
|
-
create: "authenticated",
|
|
264
|
-
update: "authenticated",
|
|
265
|
-
delete: "authenticated"
|
|
266
|
-
};
|
|
267
|
-
var FULLY_PUBLIC = {
|
|
268
|
-
read: "public",
|
|
269
|
-
create: "public",
|
|
270
|
-
update: "public",
|
|
271
|
-
delete: "public"
|
|
272
|
-
};
|
|
273
|
-
var OWNER_ONLY = {
|
|
274
|
-
read: "own",
|
|
275
|
-
create: "authenticated",
|
|
276
|
-
update: "own",
|
|
277
|
-
delete: "own"
|
|
278
|
-
};
|
|
279
|
-
var ADMIN_ONLY = {
|
|
280
|
-
read: { role: "admin" },
|
|
281
|
-
create: { role: "admin" },
|
|
282
|
-
update: { role: "admin" },
|
|
283
|
-
delete: { role: "admin" }
|
|
284
|
-
};
|
|
285
|
-
|
|
286
|
-
// src/server/realtime.ts
|
|
287
|
-
var SubscriptionManager = class {
|
|
288
|
-
clients = /* @__PURE__ */ new Map();
|
|
289
|
-
pool;
|
|
290
|
-
permissions;
|
|
291
|
-
constructor(pool, permissions = null) {
|
|
292
|
-
this.pool = pool;
|
|
293
|
-
this.permissions = permissions;
|
|
294
|
-
}
|
|
295
|
-
// -------------------------------------------------------------------------
|
|
296
|
-
// Client lifecycle
|
|
297
|
-
// -------------------------------------------------------------------------
|
|
298
|
-
addClient(clientId, ws, auth, tenantId) {
|
|
299
|
-
this.clients.set(clientId, {
|
|
300
|
-
id: clientId,
|
|
301
|
-
ws,
|
|
302
|
-
subscriptions: /* @__PURE__ */ new Map(),
|
|
303
|
-
auth,
|
|
304
|
-
tenantId
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
removeClient(clientId) {
|
|
308
|
-
this.clients.delete(clientId);
|
|
309
|
-
}
|
|
310
|
-
// -------------------------------------------------------------------------
|
|
311
|
-
// Message handling
|
|
312
|
-
// -------------------------------------------------------------------------
|
|
313
|
-
async handleMessage(clientId, raw) {
|
|
314
|
-
const client = this.clients.get(clientId);
|
|
315
|
-
if (!client) return;
|
|
316
|
-
let msg;
|
|
317
|
-
try {
|
|
318
|
-
msg = JSON.parse(raw);
|
|
319
|
-
} catch {
|
|
320
|
-
this._send(client, { type: "error", id: "", message: "Invalid JSON" });
|
|
321
|
-
return;
|
|
322
|
-
}
|
|
323
|
-
if (msg.type === "ping") {
|
|
324
|
-
this._send(client, { type: "pong" });
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
if (msg.type === "subscribe") {
|
|
328
|
-
await this._handleSubscribe(client, msg.id, msg.query, msg.tenantId);
|
|
329
|
-
return;
|
|
330
|
-
}
|
|
331
|
-
if (msg.type === "unsubscribe") {
|
|
332
|
-
client.subscriptions.delete(msg.id);
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
// -------------------------------------------------------------------------
|
|
337
|
-
// Notify — called after every mutation
|
|
338
|
-
// -------------------------------------------------------------------------
|
|
339
|
-
/**
|
|
340
|
-
* Re-evaluate all subscriptions for a given tenant and push diffs.
|
|
341
|
-
* Called after every write op lands.
|
|
342
|
-
*/
|
|
343
|
-
async notify(tenantId) {
|
|
344
|
-
const tid = tenantId ?? null;
|
|
345
|
-
const dead = [];
|
|
346
|
-
for (const [clientId, client] of this.clients) {
|
|
347
|
-
if (client.ws.readyState !== 1) {
|
|
348
|
-
dead.push(clientId);
|
|
349
|
-
continue;
|
|
350
|
-
}
|
|
351
|
-
if (client.tenantId !== tid) continue;
|
|
352
|
-
for (const [subId, sub] of client.subscriptions) {
|
|
353
|
-
if (sub.tenantId !== tid) continue;
|
|
354
|
-
await this._pushUpdate(client, sub);
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
for (const id of dead) this.clients.delete(id);
|
|
358
|
-
}
|
|
359
|
-
get clientCount() {
|
|
360
|
-
return this.clients.size;
|
|
361
|
-
}
|
|
362
|
-
// -------------------------------------------------------------------------
|
|
363
|
-
// Private
|
|
364
|
-
// -------------------------------------------------------------------------
|
|
365
|
-
async _handleSubscribe(client, subId, queryStr, tenantId) {
|
|
366
|
-
const tid = tenantId ?? client.tenantId ?? null;
|
|
367
|
-
let parsedQuery;
|
|
368
|
-
try {
|
|
369
|
-
parsedQuery = parseSimple(queryStr);
|
|
370
|
-
} catch (err) {
|
|
371
|
-
this._send(client, {
|
|
372
|
-
type: "error",
|
|
373
|
-
id: subId,
|
|
374
|
-
message: `Invalid query: ${err instanceof Error ? err.message : String(err)}`
|
|
375
|
-
});
|
|
376
|
-
return;
|
|
377
|
-
}
|
|
378
|
-
const kernel = this.pool.get(tid);
|
|
379
|
-
const engine = new QueryEngine(kernel.getStore());
|
|
380
|
-
let result;
|
|
381
|
-
try {
|
|
382
|
-
const qr = engine.execute(parsedQuery);
|
|
383
|
-
result = qr.bindings;
|
|
384
|
-
} catch (err) {
|
|
385
|
-
this._send(client, {
|
|
386
|
-
type: "error",
|
|
387
|
-
id: subId,
|
|
388
|
-
message: `Query failed: ${err instanceof Error ? err.message : String(err)}`
|
|
389
|
-
});
|
|
390
|
-
return;
|
|
391
|
-
}
|
|
392
|
-
const sub = {
|
|
393
|
-
id: subId,
|
|
394
|
-
query: queryStr,
|
|
395
|
-
tenantId: tid,
|
|
396
|
-
auth: client.auth,
|
|
397
|
-
lastResult: result
|
|
398
|
-
};
|
|
399
|
-
client.subscriptions.set(subId, sub);
|
|
400
|
-
this._send(client, { type: "subscribed", id: subId });
|
|
401
|
-
this._send(client, {
|
|
402
|
-
type: "data",
|
|
403
|
-
id: subId,
|
|
404
|
-
result,
|
|
405
|
-
diff: { added: result, updated: [], removed: [] }
|
|
406
|
-
});
|
|
407
|
-
}
|
|
408
|
-
async _pushUpdate(client, sub) {
|
|
409
|
-
const kernel = this.pool.get(sub.tenantId);
|
|
410
|
-
const engine = new QueryEngine(kernel.getStore());
|
|
411
|
-
let newResult;
|
|
412
|
-
try {
|
|
413
|
-
const parsed = parseSimple(sub.query);
|
|
414
|
-
const qr = engine.execute(parsed);
|
|
415
|
-
newResult = qr.bindings;
|
|
416
|
-
} catch {
|
|
417
|
-
return;
|
|
418
|
-
}
|
|
419
|
-
const diff = computeDiff(sub.lastResult, newResult);
|
|
420
|
-
if (diff.added.length === 0 && diff.updated.length === 0 && diff.removed.length === 0) {
|
|
421
|
-
return;
|
|
422
|
-
}
|
|
423
|
-
sub.lastResult = newResult;
|
|
424
|
-
this._send(client, { type: "data", id: sub.id, result: newResult, diff });
|
|
425
|
-
}
|
|
426
|
-
_send(client, payload) {
|
|
427
|
-
try {
|
|
428
|
-
client.ws.send(JSON.stringify(payload));
|
|
429
|
-
} catch {
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
};
|
|
433
|
-
function entityId(row) {
|
|
434
|
-
return String(row["?e"] ?? row.id ?? row.e ?? JSON.stringify(row));
|
|
435
|
-
}
|
|
436
|
-
function computeDiff(prev, next) {
|
|
437
|
-
const prevMap = new Map(prev.map((r) => [entityId(r), r]));
|
|
438
|
-
const nextMap = new Map(next.map((r) => [entityId(r), r]));
|
|
439
|
-
const added = [];
|
|
440
|
-
const updated = [];
|
|
441
|
-
const removed = [];
|
|
442
|
-
for (const [id, row] of nextMap) {
|
|
443
|
-
if (!prevMap.has(id)) {
|
|
444
|
-
added.push(row);
|
|
445
|
-
} else if (JSON.stringify(prevMap.get(id)) !== JSON.stringify(row)) {
|
|
446
|
-
updated.push(row);
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
for (const [id, row] of prevMap) {
|
|
450
|
-
if (!nextMap.has(id)) removed.push(row);
|
|
451
|
-
}
|
|
452
|
-
return { added, updated, removed };
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
// src/server/server.ts
|
|
456
|
-
var __moduleDir = import.meta.dir ?? dirname(fileURLToPath(import.meta.url));
|
|
457
|
-
async function startServer(opts) {
|
|
458
|
-
return startServerNode(opts);
|
|
459
|
-
}
|
|
460
|
-
var startServerCrossRuntime = startServer;
|
|
461
|
-
function buildServerContext(opts) {
|
|
462
|
-
const { pool, permissions, config } = opts;
|
|
463
|
-
const port = opts.port ?? config.port ?? 3e3;
|
|
464
|
-
const authConfig = {
|
|
465
|
-
jwtSecret: config.jwtSecret,
|
|
466
|
-
apiKey: config.apiKey,
|
|
467
|
-
allowPublic: true
|
|
468
|
-
};
|
|
469
|
-
const subs = new SubscriptionManager(pool, permissions ?? null);
|
|
470
|
-
const handleHttp = async (req) => {
|
|
471
|
-
const url = new URL(req.url);
|
|
472
|
-
const path = url.pathname;
|
|
473
|
-
const auth = await resolveAuth(
|
|
474
|
-
req.headers.get("authorization"),
|
|
475
|
-
authConfig
|
|
476
|
-
);
|
|
477
|
-
const tenantId = auth.tenantId ?? url.searchParams.get("tenantId") ?? null;
|
|
478
|
-
try {
|
|
479
|
-
return await route(req, url, path, auth, tenantId, {
|
|
480
|
-
pool,
|
|
481
|
-
permissions: permissions ?? null,
|
|
482
|
-
subs,
|
|
483
|
-
authConfig,
|
|
484
|
-
config,
|
|
485
|
-
oauthProviders: opts.oauthProviders ?? {}
|
|
486
|
-
});
|
|
487
|
-
} catch (err) {
|
|
488
|
-
if (err instanceof PermissionError) {
|
|
489
|
-
return json(err.toResponse(), 403);
|
|
490
|
-
}
|
|
491
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
492
|
-
return json({ error: "Internal Server Error", message: msg }, 500);
|
|
493
|
-
}
|
|
494
|
-
};
|
|
495
|
-
return { port, authConfig, subs, handleHttp };
|
|
496
|
-
}
|
|
497
|
-
async function startServerNode(opts) {
|
|
498
|
-
const { port, subs, handleHttp } = buildServerContext(opts);
|
|
499
|
-
const { startNodeServer } = await import("./server/node-adapter.js");
|
|
500
|
-
return startNodeServer({
|
|
501
|
-
port,
|
|
502
|
-
fetch: handleHttp,
|
|
503
|
-
websocket: {
|
|
504
|
-
open(ws) {
|
|
505
|
-
const id = crypto.randomUUID();
|
|
506
|
-
ws.__clientId = id;
|
|
507
|
-
subs.addClient(
|
|
508
|
-
id,
|
|
509
|
-
ws,
|
|
510
|
-
{
|
|
511
|
-
userId: null,
|
|
512
|
-
tenantId: null,
|
|
513
|
-
roles: [],
|
|
514
|
-
claims: {},
|
|
515
|
-
authenticated: false
|
|
516
|
-
},
|
|
517
|
-
null
|
|
518
|
-
);
|
|
519
|
-
},
|
|
520
|
-
async message(ws, raw) {
|
|
521
|
-
const id = ws.__clientId;
|
|
522
|
-
await subs.handleMessage(
|
|
523
|
-
id,
|
|
524
|
-
typeof raw === "string" ? raw : raw.toString()
|
|
525
|
-
);
|
|
526
|
-
},
|
|
527
|
-
close(ws) {
|
|
528
|
-
const id = ws.__clientId;
|
|
529
|
-
subs.removeClient(id);
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
});
|
|
533
|
-
}
|
|
534
|
-
async function route(req, url, path, auth, tenantId, ctx) {
|
|
535
|
-
const method = req.method.toUpperCase();
|
|
536
|
-
if (method === "GET" && path === "/__trellis/inspector.js") {
|
|
537
|
-
const candidates = [
|
|
538
|
-
join(__moduleDir, "db", "inspector.js"),
|
|
539
|
-
// chunk lives in dist/, inspector in dist/db/
|
|
540
|
-
join(__moduleDir, "inspector.js")
|
|
541
|
-
// chunk lives in dist/db/, inspector alongside
|
|
542
|
-
];
|
|
543
|
-
for (const p of candidates) {
|
|
544
|
-
if (existsSync(p)) {
|
|
545
|
-
return new Response(readFileSync(p, "utf-8"), {
|
|
546
|
-
headers: { "Content-Type": "application/javascript; charset=utf-8" }
|
|
547
|
-
});
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
return new Response(
|
|
551
|
-
"/* Trellis DB Inspector: run `bun run build:inspector` first */",
|
|
552
|
-
{
|
|
553
|
-
headers: { "Content-Type": "application/javascript" }
|
|
554
|
-
}
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
if (method === "GET" && path === "/__trellis/trellis.css") {
|
|
558
|
-
const candidates = [
|
|
559
|
-
join(__moduleDir, "db", "trellis.css"),
|
|
560
|
-
join(__moduleDir, "trellis.css")
|
|
561
|
-
];
|
|
562
|
-
for (const p of candidates) {
|
|
563
|
-
if (existsSync(p)) {
|
|
564
|
-
return new Response(readFileSync(p, "utf-8"), {
|
|
565
|
-
headers: { "Content-Type": "text/css; charset=utf-8" }
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
return new Response("/* Trellis CSS not found */", {
|
|
570
|
-
headers: { "Content-Type": "text/css" }
|
|
571
|
-
});
|
|
572
|
-
}
|
|
573
|
-
if (method === "GET" && (path === "/" || path === "/inspector")) {
|
|
574
|
-
const html = `<!DOCTYPE html>
|
|
575
|
-
<html lang="en">
|
|
576
|
-
<head>
|
|
577
|
-
<meta charset="UTF-8">
|
|
578
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
579
|
-
<title>Trellis DB Inspector</title>
|
|
580
|
-
<link rel="stylesheet" href="/__trellis/trellis.css">
|
|
581
|
-
</head>
|
|
582
|
-
<body>
|
|
583
|
-
<script src="/__trellis/inspector.js"></script>
|
|
584
|
-
</body>
|
|
585
|
-
</html>`;
|
|
586
|
-
return new Response(html, {
|
|
587
|
-
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
588
|
-
});
|
|
589
|
-
}
|
|
590
|
-
if (method === "GET" && path === "/health") {
|
|
591
|
-
const kernel = ctx.pool.get(tenantId);
|
|
592
|
-
const ops = kernel.readAllOps().length;
|
|
593
|
-
return json({
|
|
594
|
-
status: "ok",
|
|
595
|
-
ops,
|
|
596
|
-
tenants: ctx.pool.activeTenants().length
|
|
597
|
-
});
|
|
598
|
-
}
|
|
599
|
-
if (path === "/entities" || path === "/entities/") {
|
|
600
|
-
if (method === "POST") return handleCreate(req, auth, tenantId, ctx);
|
|
601
|
-
if (method === "GET") return handleList(url, auth, tenantId, ctx);
|
|
602
|
-
}
|
|
603
|
-
const entityMatch = path.match(/^\/entities\/([^/]+)$/);
|
|
604
|
-
if (entityMatch) {
|
|
605
|
-
const id = decodeURIComponent(entityMatch[1]);
|
|
606
|
-
if (method === "GET") return handleRead(id, auth, tenantId, ctx);
|
|
607
|
-
if (method === "PUT" || method === "PATCH")
|
|
608
|
-
return handleUpdate(req, id, auth, tenantId, ctx);
|
|
609
|
-
if (method === "DELETE") return handleDelete(id, auth, tenantId, ctx);
|
|
610
|
-
}
|
|
611
|
-
if (method === "POST" && path === "/query") {
|
|
612
|
-
return handleQuery(req, auth, tenantId, ctx);
|
|
613
|
-
}
|
|
614
|
-
if (method === "POST" && path === "/upload") {
|
|
615
|
-
return handleUpload(req, auth, tenantId, ctx);
|
|
616
|
-
}
|
|
617
|
-
const fileMatch = path.match(/^\/files\/([^/]+)$/);
|
|
618
|
-
if (method === "GET" && fileMatch) {
|
|
619
|
-
return handleFileDownload(fileMatch[1], ctx, tenantId);
|
|
620
|
-
}
|
|
621
|
-
if (method === "POST" && path === "/auth/register") {
|
|
622
|
-
return handleRegister(req, tenantId, ctx);
|
|
623
|
-
}
|
|
624
|
-
if (method === "POST" && path === "/auth/login") {
|
|
625
|
-
return handleLogin(req, tenantId, ctx);
|
|
626
|
-
}
|
|
627
|
-
const oauthMatch = path.match(/^\/auth\/oauth\/([^/]+)(\/callback)?$/);
|
|
628
|
-
if (oauthMatch) {
|
|
629
|
-
const providerName = oauthMatch[1];
|
|
630
|
-
const isCallback = !!oauthMatch[2];
|
|
631
|
-
if (isCallback)
|
|
632
|
-
return handleOAuthCallback(url, providerName, tenantId, ctx);
|
|
633
|
-
return handleOAuthRedirect(providerName, url, ctx);
|
|
634
|
-
}
|
|
635
|
-
return json({ error: "Not Found" }, 404);
|
|
636
|
-
}
|
|
637
|
-
async function handleCreate(req, auth, tenantId, ctx) {
|
|
638
|
-
const body = await req.json();
|
|
639
|
-
if (!body.type) return json({ error: "type is required" }, 400);
|
|
640
|
-
ctx.permissions?.assert(auth, body.type, "create");
|
|
641
|
-
const kernel = ctx.pool.get(tenantId);
|
|
642
|
-
const entityId2 = `${body.type.toLowerCase()}:${crypto.randomUUID()}`;
|
|
643
|
-
const attrs = {
|
|
644
|
-
...body.attributes
|
|
645
|
-
};
|
|
646
|
-
if (auth.userId) attrs.createdBy = auth.userId;
|
|
647
|
-
if (auth.tenantId) attrs.tenantId = auth.tenantId;
|
|
648
|
-
const result = await kernel.createEntity(
|
|
649
|
-
entityId2,
|
|
650
|
-
body.type,
|
|
651
|
-
attrs,
|
|
652
|
-
body.links
|
|
653
|
-
);
|
|
654
|
-
await ctx.subs.notify(tenantId);
|
|
655
|
-
return json({ id: entityId2, op: result.op.hash }, 201);
|
|
656
|
-
}
|
|
657
|
-
async function handleRead(id, auth, tenantId, ctx) {
|
|
658
|
-
const kernel = ctx.pool.get(tenantId);
|
|
659
|
-
const entity = kernel.getEntity(id);
|
|
660
|
-
if (!entity) return json({ error: "Not Found" }, 404);
|
|
661
|
-
ctx.permissions?.assert(auth, entity.type, "read", entity);
|
|
662
|
-
return json(entityToJson(entity));
|
|
663
|
-
}
|
|
664
|
-
async function handleUpdate(req, id, auth, tenantId, ctx) {
|
|
665
|
-
const kernel = ctx.pool.get(tenantId);
|
|
666
|
-
const entity = kernel.getEntity(id);
|
|
667
|
-
if (!entity) return json({ error: "Not Found" }, 404);
|
|
668
|
-
ctx.permissions?.assert(auth, entity.type, "update", entity);
|
|
669
|
-
const updates = await req.json();
|
|
670
|
-
await kernel.updateEntity(id, updates);
|
|
671
|
-
await ctx.subs.notify(tenantId);
|
|
672
|
-
return json({ id, updated: true });
|
|
673
|
-
}
|
|
674
|
-
async function handleDelete(id, auth, tenantId, ctx) {
|
|
675
|
-
const kernel = ctx.pool.get(tenantId);
|
|
676
|
-
const entity = kernel.getEntity(id);
|
|
677
|
-
if (!entity) return json({ error: "Not Found" }, 404);
|
|
678
|
-
ctx.permissions?.assert(auth, entity.type, "delete", entity);
|
|
679
|
-
await kernel.deleteEntity(id);
|
|
680
|
-
await ctx.subs.notify(tenantId);
|
|
681
|
-
return json({ id, deleted: true });
|
|
682
|
-
}
|
|
683
|
-
async function handleList(url, auth, tenantId, ctx) {
|
|
684
|
-
const type = url.searchParams.get("type") ?? void 0;
|
|
685
|
-
const limit = parseInt(url.searchParams.get("limit") ?? "100");
|
|
686
|
-
const offset = parseInt(url.searchParams.get("offset") ?? "0");
|
|
687
|
-
const kernel = ctx.pool.get(tenantId);
|
|
688
|
-
let entities = kernel.listEntities(type);
|
|
689
|
-
if (ctx.permissions && type) {
|
|
690
|
-
entities = entities.filter(
|
|
691
|
-
(e) => ctx.permissions.check(auth, e.type, "read", e)
|
|
692
|
-
);
|
|
693
|
-
}
|
|
694
|
-
const page = entities.slice(offset, offset + limit);
|
|
695
|
-
return json({
|
|
696
|
-
data: page.map(entityToJson),
|
|
697
|
-
total: entities.length,
|
|
698
|
-
limit,
|
|
699
|
-
offset
|
|
700
|
-
});
|
|
701
|
-
}
|
|
702
|
-
async function handleQuery(req, auth, tenantId, ctx) {
|
|
703
|
-
const body = await req.json();
|
|
704
|
-
if (!body.query) return json({ error: "query is required" }, 400);
|
|
705
|
-
let parsed;
|
|
706
|
-
try {
|
|
707
|
-
parsed = parseSimple(body.query);
|
|
708
|
-
} catch (err) {
|
|
709
|
-
return json({ error: "Invalid query", message: String(err) }, 400);
|
|
710
|
-
}
|
|
711
|
-
const kernel = ctx.pool.get(tenantId);
|
|
712
|
-
const engine = new QueryEngine(kernel.getStore());
|
|
713
|
-
const result = engine.execute(parsed);
|
|
714
|
-
return json({
|
|
715
|
-
bindings: result.bindings,
|
|
716
|
-
executionTime: result.executionTime
|
|
717
|
-
});
|
|
718
|
-
}
|
|
719
|
-
async function handleUpload(req, auth, tenantId, ctx) {
|
|
720
|
-
if (!auth.authenticated && ctx.config.apiKey) {
|
|
721
|
-
return json({ error: "Unauthorized" }, 401);
|
|
722
|
-
}
|
|
723
|
-
const contentType = req.headers.get("content-type") ?? "application/octet-stream";
|
|
724
|
-
const buffer = new Uint8Array(await req.arrayBuffer());
|
|
725
|
-
const hashBuf = await crypto.subtle.digest("SHA-256", buffer);
|
|
726
|
-
const hash = `blob:${Array.from(new Uint8Array(hashBuf)).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
727
|
-
const kernel = ctx.pool.get(tenantId);
|
|
728
|
-
const backend = kernel.getBackend();
|
|
729
|
-
if (!backend.hasBlob(hash)) {
|
|
730
|
-
backend.putBlob(hash, buffer);
|
|
731
|
-
}
|
|
732
|
-
return json({ hash, size: buffer.length, contentType }, 201);
|
|
733
|
-
}
|
|
734
|
-
async function handleFileDownload(hash, ctx, tenantId) {
|
|
735
|
-
const kernel = ctx.pool.get(tenantId);
|
|
736
|
-
const backend = kernel.getBackend();
|
|
737
|
-
const blob = backend.getBlob(hash);
|
|
738
|
-
if (!blob) return json({ error: "Not Found" }, 404);
|
|
739
|
-
const cleanBuf = blob.buffer.slice(
|
|
740
|
-
blob.byteOffset,
|
|
741
|
-
blob.byteOffset + blob.byteLength
|
|
742
|
-
);
|
|
743
|
-
return new Response(cleanBuf, {
|
|
744
|
-
headers: { "Content-Type": "application/octet-stream" }
|
|
745
|
-
});
|
|
746
|
-
}
|
|
747
|
-
async function handleRegister(req, tenantId, ctx) {
|
|
748
|
-
if (!ctx.config.jwtSecret) {
|
|
749
|
-
return json({ error: "Auth not configured (no jwtSecret)" }, 501);
|
|
750
|
-
}
|
|
751
|
-
const body = await req.json();
|
|
752
|
-
if (!body.email || !body.password) {
|
|
753
|
-
return json({ error: "email and password are required" }, 400);
|
|
754
|
-
}
|
|
755
|
-
const kernel = ctx.pool.get(tenantId);
|
|
756
|
-
const existing = kernel.listEntities("User", { email: body.email });
|
|
757
|
-
if (existing.length > 0) {
|
|
758
|
-
return json({ error: "Email already registered" }, 409);
|
|
759
|
-
}
|
|
760
|
-
const userId = `user:${crypto.randomUUID()}`;
|
|
761
|
-
const pwHash = await hashPassword(body.password);
|
|
762
|
-
await kernel.createEntity(userId, "User", {
|
|
763
|
-
email: body.email,
|
|
764
|
-
name: body.name ?? "",
|
|
765
|
-
passwordHash: pwHash,
|
|
766
|
-
role: "user",
|
|
767
|
-
...tenantId ? { tenantId } : {}
|
|
768
|
-
});
|
|
769
|
-
const token = await signJwt(
|
|
770
|
-
{ sub: userId, email: body.email, roles: ["user"], tenantId },
|
|
771
|
-
ctx.config.jwtSecret
|
|
772
|
-
);
|
|
773
|
-
return json({ token, userId }, 201);
|
|
774
|
-
}
|
|
775
|
-
async function handleLogin(req, tenantId, ctx) {
|
|
776
|
-
if (!ctx.config.jwtSecret) {
|
|
777
|
-
return json({ error: "Auth not configured (no jwtSecret)" }, 501);
|
|
778
|
-
}
|
|
779
|
-
const body = await req.json();
|
|
780
|
-
if (!body.email || !body.password) {
|
|
781
|
-
return json({ error: "email and password are required" }, 400);
|
|
782
|
-
}
|
|
783
|
-
const kernel = ctx.pool.get(tenantId);
|
|
784
|
-
const users = kernel.listEntities("User", { email: body.email });
|
|
785
|
-
if (users.length === 0) {
|
|
786
|
-
return json({ error: "Invalid credentials" }, 401);
|
|
787
|
-
}
|
|
788
|
-
const user = users[0];
|
|
789
|
-
const pwHashFact = user.facts.find((f) => f.a === "passwordHash");
|
|
790
|
-
const roleFact = user.facts.find((f) => f.a === "role");
|
|
791
|
-
if (!pwHashFact || !await verifyPassword(body.password, String(pwHashFact.v))) {
|
|
792
|
-
return json({ error: "Invalid credentials" }, 401);
|
|
793
|
-
}
|
|
794
|
-
const role = String(roleFact?.v ?? "user");
|
|
795
|
-
const token = await signJwt(
|
|
796
|
-
{ sub: user.id, email: body.email, roles: [role], tenantId },
|
|
797
|
-
ctx.config.jwtSecret
|
|
798
|
-
);
|
|
799
|
-
return json({ token, userId: user.id });
|
|
800
|
-
}
|
|
801
|
-
function handleOAuthRedirect(providerName, url, ctx) {
|
|
802
|
-
const provider = ctx.oauthProviders[providerName] ?? getBuiltinProvider(providerName, ctx);
|
|
803
|
-
if (!provider)
|
|
804
|
-
return json({ error: `Unknown provider: ${providerName}` }, 400);
|
|
805
|
-
const redirectUri = `${url.origin}/auth/oauth/${providerName}/callback`;
|
|
806
|
-
const state = crypto.randomUUID();
|
|
807
|
-
const authUrl = buildOAuthUrl(provider, redirectUri, state);
|
|
808
|
-
return Response.redirect(authUrl, 302);
|
|
809
|
-
}
|
|
810
|
-
async function handleOAuthCallback(url, providerName, tenantId, ctx) {
|
|
811
|
-
if (!ctx.config.jwtSecret) {
|
|
812
|
-
return json({ error: "Auth not configured (no jwtSecret)" }, 501);
|
|
813
|
-
}
|
|
814
|
-
const code = url.searchParams.get("code");
|
|
815
|
-
if (!code) return json({ error: "Missing code" }, 400);
|
|
816
|
-
const provider = ctx.oauthProviders[providerName] ?? getBuiltinProvider(providerName, ctx);
|
|
817
|
-
if (!provider)
|
|
818
|
-
return json({ error: `Unknown provider: ${providerName}` }, 400);
|
|
819
|
-
const redirectUri = `${url.origin}/auth/oauth/${providerName}/callback`;
|
|
820
|
-
let profile;
|
|
821
|
-
try {
|
|
822
|
-
profile = await exchangeOAuthCode(provider, code, redirectUri);
|
|
823
|
-
} catch (err) {
|
|
824
|
-
return json({ error: "OAuth exchange failed", message: String(err) }, 400);
|
|
825
|
-
}
|
|
826
|
-
const kernel = ctx.pool.get(tenantId);
|
|
827
|
-
const oauthId = `oauth:${providerName}:${profile.id}`;
|
|
828
|
-
let users = kernel.listEntities("User", { oauthId });
|
|
829
|
-
let userId;
|
|
830
|
-
if (users.length === 0) {
|
|
831
|
-
userId = `user:${crypto.randomUUID()}`;
|
|
832
|
-
await kernel.createEntity(userId, "User", {
|
|
833
|
-
email: profile.email,
|
|
834
|
-
name: profile.name,
|
|
835
|
-
avatarUrl: profile.avatarUrl ?? "",
|
|
836
|
-
oauthId,
|
|
837
|
-
oauthProvider: providerName,
|
|
838
|
-
role: "user",
|
|
839
|
-
...tenantId ? { tenantId } : {}
|
|
840
|
-
});
|
|
841
|
-
} else {
|
|
842
|
-
userId = users[0].id;
|
|
843
|
-
}
|
|
844
|
-
const token = await signJwt(
|
|
845
|
-
{ sub: userId, email: profile.email, roles: ["user"], tenantId },
|
|
846
|
-
ctx.config.jwtSecret
|
|
847
|
-
);
|
|
848
|
-
return json({ token, userId });
|
|
849
|
-
}
|
|
850
|
-
function getBuiltinProvider(name, ctx) {
|
|
851
|
-
if (name === "google") {
|
|
852
|
-
const cid = process.env.GOOGLE_CLIENT_ID;
|
|
853
|
-
const csec = process.env.GOOGLE_CLIENT_SECRET;
|
|
854
|
-
if (!cid || !csec) return null;
|
|
855
|
-
return { ...GOOGLE_PROVIDER, clientId: cid, clientSecret: csec };
|
|
856
|
-
}
|
|
857
|
-
if (name === "github") {
|
|
858
|
-
const cid = process.env.GITHUB_CLIENT_ID;
|
|
859
|
-
const csec = process.env.GITHUB_CLIENT_SECRET;
|
|
860
|
-
if (!cid || !csec) return null;
|
|
861
|
-
return { ...GITHUB_PROVIDER, clientId: cid, clientSecret: csec };
|
|
862
|
-
}
|
|
863
|
-
return null;
|
|
864
|
-
}
|
|
865
|
-
async function hashPassword(password) {
|
|
866
|
-
const salt = crypto.randomUUID().replace(/-/g, "");
|
|
867
|
-
const enc = new TextEncoder();
|
|
868
|
-
const keyMat = await crypto.subtle.importKey(
|
|
869
|
-
"raw",
|
|
870
|
-
enc.encode(password),
|
|
871
|
-
"PBKDF2",
|
|
872
|
-
false,
|
|
873
|
-
["deriveBits"]
|
|
874
|
-
);
|
|
875
|
-
const bits = await crypto.subtle.deriveBits(
|
|
876
|
-
{
|
|
877
|
-
name: "PBKDF2",
|
|
878
|
-
salt: enc.encode(salt),
|
|
879
|
-
iterations: 1e5,
|
|
880
|
-
hash: "SHA-256"
|
|
881
|
-
},
|
|
882
|
-
keyMat,
|
|
883
|
-
256
|
|
884
|
-
);
|
|
885
|
-
const hash = Array.from(new Uint8Array(bits)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
886
|
-
return `${salt}:${hash}`;
|
|
887
|
-
}
|
|
888
|
-
async function verifyPassword(password, stored) {
|
|
889
|
-
const [salt, expectedHash] = stored.split(":");
|
|
890
|
-
if (!salt || !expectedHash) return false;
|
|
891
|
-
const enc = new TextEncoder();
|
|
892
|
-
const keyMat = await crypto.subtle.importKey(
|
|
893
|
-
"raw",
|
|
894
|
-
enc.encode(password),
|
|
895
|
-
"PBKDF2",
|
|
896
|
-
false,
|
|
897
|
-
["deriveBits"]
|
|
898
|
-
);
|
|
899
|
-
const bits = await crypto.subtle.deriveBits(
|
|
900
|
-
{
|
|
901
|
-
name: "PBKDF2",
|
|
902
|
-
salt: enc.encode(salt),
|
|
903
|
-
iterations: 1e5,
|
|
904
|
-
hash: "SHA-256"
|
|
905
|
-
},
|
|
906
|
-
keyMat,
|
|
907
|
-
256
|
|
908
|
-
);
|
|
909
|
-
const hash = Array.from(new Uint8Array(bits)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
910
|
-
return hash === expectedHash;
|
|
911
|
-
}
|
|
912
|
-
function entityToJson(entity) {
|
|
913
|
-
const attrs = {};
|
|
914
|
-
for (const f of entity.facts) {
|
|
915
|
-
if (f.a !== "type") {
|
|
916
|
-
attrs[f.a] = f.v;
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
return { id: entity.id, type: entity.type, ...attrs };
|
|
920
|
-
}
|
|
921
|
-
function json(data, status = 200) {
|
|
922
|
-
return new Response(JSON.stringify(data), {
|
|
923
|
-
status,
|
|
924
|
-
headers: { "Content-Type": "application/json" }
|
|
925
|
-
});
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
export {
|
|
929
|
-
ANONYMOUS,
|
|
930
|
-
signJwt,
|
|
931
|
-
verifyJwt,
|
|
932
|
-
resolveAuth,
|
|
933
|
-
GOOGLE_PROVIDER,
|
|
934
|
-
GITHUB_PROVIDER,
|
|
935
|
-
buildOAuthUrl,
|
|
936
|
-
exchangeOAuthCode,
|
|
937
|
-
PermissionRegistry,
|
|
938
|
-
PermissionError,
|
|
939
|
-
PUBLIC_READ,
|
|
940
|
-
FULLY_PUBLIC,
|
|
941
|
-
OWNER_ONLY,
|
|
942
|
-
ADMIN_ONLY,
|
|
943
|
-
SubscriptionManager,
|
|
944
|
-
startServer,
|
|
945
|
-
startServerCrossRuntime
|
|
946
|
-
};
|