@ultrst-armada/kloks 2.2.4 → 2.2.5
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/package.json +7 -2
- package/packages/aiko/dist/index.d.ts +37 -1
- package/packages/aiko/dist/index.js +101 -3
- package/packages/backend/dist/ai-inference/index.js +1 -1
- package/packages/backend/dist/ai-inference/inferenceExecutor.test.d.ts +1 -0
- package/packages/backend/dist/auth/OidcBff.d.ts +50 -0
- package/packages/backend/dist/auth/OidcBff.test.d.ts +1 -0
- package/packages/backend/dist/auth/OidcBffEnv.d.ts +23 -0
- package/packages/backend/dist/auth/index.d.ts +2 -0
- package/packages/backend/dist/auth/index.js +6 -1
- package/packages/backend/dist/{chunk-7RSTNQT2.js → chunk-26NAKO4V.js} +1 -1
- package/packages/backend/dist/{chunk-NIP22V2G.js → chunk-E2I7D52V.js} +22 -1
- package/packages/backend/dist/{chunk-5E6JRFUH.js → chunk-HX5TN27Y.js} +294 -4
- package/packages/backend/dist/{chunk-GCTQY24J.js → chunk-MK4ZRBFI.js} +7 -6
- package/packages/backend/dist/chunk-SEKPSCWP.js +350 -0
- package/packages/backend/dist/{chunk-N7OUR5R5.js → chunk-YDGW7PXM.js} +1 -1
- package/packages/backend/dist/client/index.js +2 -2
- package/packages/backend/dist/connectivity/FrontendSession.d.ts +1 -0
- package/packages/backend/dist/connectivity/FrontendSession.dispose.test.d.ts +1 -0
- package/packages/backend/dist/connectivity/HTTPTransport.d.ts +1 -0
- package/packages/backend/dist/connectivity/HTTPTransport.operation.test.d.ts +1 -0
- package/packages/backend/dist/connectivity/InProcessExecutor.session.test.d.ts +1 -0
- package/packages/backend/dist/connectivity/RemoteExecutor.error.test.d.ts +1 -0
- package/packages/backend/dist/connectivity/facadeInvocation.adversarial_replay.test.d.ts +1 -0
- package/packages/backend/dist/connectivity/facadeInvocation.d.ts +101 -0
- package/packages/backend/dist/connectivity/facadeInvocation.oneUseLuthContract.test.d.ts +1 -0
- package/packages/backend/dist/connectivity/facadeInvocation.test.d.ts +1 -0
- package/packages/backend/dist/connectivity/index.d.ts +2 -0
- package/packages/backend/dist/connectivity/index.js +8 -4
- package/packages/backend/dist/index.js +7 -3
- package/packages/backend/dist/krnl-ai-services.js +2 -2
- package/packages/backend/dist/node.js +16 -7
- package/packages/backend/package.json +1 -1
- package/packages/client/dist/auth.d.ts +1 -1
- package/packages/client/dist/auth.js +5 -1
- package/packages/client/dist/{chunk-ATLIA7AJ.js → chunk-WYC7RG32.js} +5 -1
- package/packages/client/dist/index.d.ts +1 -1
- package/packages/client/dist/index.js +5 -1
- package/packages/client/package.json +1 -1
- package/packages/state-graph/dist/browser.js +24 -24
- package/packages/state-graph/dist/index.js +24 -24
- package/packages/backend/dist/chunk-JQKKMUCT.js +0 -0
- package/packages/state-graph/dist/{chunk-UKTICGGV.js → chunk-YUJC367F.js} +3 -3
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// src/auth/OidcBff.ts
|
|
2
|
+
var FLOW_MS = 10 * 6e4;
|
|
3
|
+
var SESSION_MS = 7 * 24 * 60 * 6e4;
|
|
4
|
+
var ACCESS_SKEW_MS = 3e4;
|
|
5
|
+
var enc = new TextEncoder();
|
|
6
|
+
function base64url(bytes) {
|
|
7
|
+
let result = "";
|
|
8
|
+
for (const byte of bytes) result += String.fromCharCode(byte);
|
|
9
|
+
return btoa(result).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
10
|
+
}
|
|
11
|
+
function fromBase64url(value) {
|
|
12
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("INVALID_CIPHERTEXT");
|
|
13
|
+
const raw = atob(value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - value.length % 4) % 4));
|
|
14
|
+
return Uint8Array.from(raw, (c) => c.charCodeAt(0));
|
|
15
|
+
}
|
|
16
|
+
function nonce() {
|
|
17
|
+
return base64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
18
|
+
}
|
|
19
|
+
async function sha256(value) {
|
|
20
|
+
return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(value))));
|
|
21
|
+
}
|
|
22
|
+
async function keyFor(config) {
|
|
23
|
+
if (config.encryptionSecret.length < 32) throw new Error("OAUTH_BFF_SECRET_TOO_SHORT");
|
|
24
|
+
const keyBytes = await crypto.subtle.digest("SHA-256", enc.encode("kloks-oidc-bff-v1:" + config.encryptionSecret));
|
|
25
|
+
return crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
26
|
+
}
|
|
27
|
+
async function seal(value, config) {
|
|
28
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
29
|
+
const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await keyFor(config), enc.encode(value));
|
|
30
|
+
return base64url(iv) + "." + base64url(new Uint8Array(ciphertext));
|
|
31
|
+
}
|
|
32
|
+
async function unseal(value, config) {
|
|
33
|
+
const [iv, cipher, extra] = value.split(".");
|
|
34
|
+
if (!iv || !cipher || extra) throw new Error("INVALID_CIPHERTEXT");
|
|
35
|
+
const result = await crypto.subtle.decrypt(
|
|
36
|
+
{ name: "AES-GCM", iv: fromBase64url(iv) },
|
|
37
|
+
await keyFor(config),
|
|
38
|
+
fromBase64url(cipher)
|
|
39
|
+
);
|
|
40
|
+
return new TextDecoder().decode(result);
|
|
41
|
+
}
|
|
42
|
+
function exactCookie(request, name) {
|
|
43
|
+
const found = (request.headers.get("cookie") ?? "").split(";").map((x) => x.trim()).filter((x) => x.startsWith(name + "="));
|
|
44
|
+
if (found.length !== 1) return null;
|
|
45
|
+
const token = found[0].slice(name.length + 1);
|
|
46
|
+
return /^[A-Za-z0-9_-]{43}$/.test(token) ? token : null;
|
|
47
|
+
}
|
|
48
|
+
function sameValue(left, right) {
|
|
49
|
+
if (left.length !== right.length) return false;
|
|
50
|
+
let diff = 0;
|
|
51
|
+
for (let i = 0; i < left.length; i++) diff |= left.charCodeAt(i) ^ right.charCodeAt(i);
|
|
52
|
+
return diff === 0;
|
|
53
|
+
}
|
|
54
|
+
function configOrigin(config) {
|
|
55
|
+
const url = new URL(config.redirectUri);
|
|
56
|
+
const issuer = new URL(config.issuer);
|
|
57
|
+
if (issuer.protocol !== "https:" || issuer.pathname !== "/api/auth" || issuer.search || issuer.hash || !config.clientId || !config.clientSecret || !config.appId || url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
|
|
58
|
+
throw new Error("INVALID_VERIFIED_OAUTH_BFF_CONFIGURATION");
|
|
59
|
+
}
|
|
60
|
+
return url;
|
|
61
|
+
}
|
|
62
|
+
function cookieName(config, kind) {
|
|
63
|
+
const secure = configOrigin(config).protocol === "https:";
|
|
64
|
+
return (secure ? "__Host-" : "") + "ultrst_oidc_" + kind;
|
|
65
|
+
}
|
|
66
|
+
function cookie(config, kind, value, age) {
|
|
67
|
+
return cookieName(config, kind) + "=" + value + "; Path=/; HttpOnly; SameSite=Lax" + (configOrigin(config).protocol === "https:" ? "; Secure" : "") + "; Max-Age=" + age;
|
|
68
|
+
}
|
|
69
|
+
function clearCookie(config, kind) {
|
|
70
|
+
return cookie(config, kind, "", 0);
|
|
71
|
+
}
|
|
72
|
+
function localReturnTo(value, config) {
|
|
73
|
+
const target = value || "/";
|
|
74
|
+
if (!target.startsWith("/") || target.startsWith("//") || target.includes("\\") || /[\x00-\x1f\x7f]/.test(target)) return "/";
|
|
75
|
+
try {
|
|
76
|
+
const resolved = new URL(target, configOrigin(config));
|
|
77
|
+
if (resolved.origin !== configOrigin(config).origin) return "/";
|
|
78
|
+
return resolved.pathname + resolved.search + resolved.hash;
|
|
79
|
+
} catch {
|
|
80
|
+
return "/";
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function reply(body, status) {
|
|
84
|
+
return Response.json(body, { status, headers: { "cache-control": "no-store" } });
|
|
85
|
+
}
|
|
86
|
+
function clientCredentials(config) {
|
|
87
|
+
return new URLSearchParams({ client_id: config.clientId, client_secret: config.clientSecret });
|
|
88
|
+
}
|
|
89
|
+
async function exchange(config, body) {
|
|
90
|
+
const response = await (config.fetcher || fetch)(config.issuer + "/oauth2/token", {
|
|
91
|
+
method: "POST",
|
|
92
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
93
|
+
body,
|
|
94
|
+
cache: "no-store",
|
|
95
|
+
redirect: "manual"
|
|
96
|
+
});
|
|
97
|
+
if (!response.ok) throw new Error("LUTH_OAUTH_TOKEN_EXCHANGE_REJECTED");
|
|
98
|
+
const data = await response.json();
|
|
99
|
+
if (typeof data.access_token !== "string" || !data.access_token || typeof data.expires_in !== "number" || !Number.isFinite(data.expires_in) || data.expires_in <= 0 || data.expires_in > 86400) {
|
|
100
|
+
throw new Error("LUTH_OAUTH_INVALID_TOKEN_RESPONSE");
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
access_token: data.access_token,
|
|
104
|
+
expires_in: data.expires_in,
|
|
105
|
+
...typeof data.refresh_token === "string" ? { refresh_token: data.refresh_token } : {}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
async function userInfo(config, token) {
|
|
109
|
+
const response = await (config.fetcher || fetch)(config.issuer + "/oauth2/userinfo", {
|
|
110
|
+
headers: { authorization: "Bearer " + token },
|
|
111
|
+
cache: "no-store",
|
|
112
|
+
redirect: "manual"
|
|
113
|
+
});
|
|
114
|
+
if (response.status === 401 || response.status === 403) return null;
|
|
115
|
+
if (!response.ok) throw new Error("LUTH_OAUTH_USERINFO_UNAVAILABLE");
|
|
116
|
+
const data = await response.json();
|
|
117
|
+
if (typeof data.sub !== "string" || !data.sub || typeof data.email !== "string" || !data.email) throw new Error("LUTH_OAUTH_INVALID_PRINCIPAL");
|
|
118
|
+
return {
|
|
119
|
+
id: data.sub,
|
|
120
|
+
email: data.email,
|
|
121
|
+
name: typeof data.name === "string" && data.name ? data.name : data.email,
|
|
122
|
+
...typeof data.picture === "string" ? { image: data.picture } : {}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function createOAuthBff(config) {
|
|
126
|
+
configOrigin(config);
|
|
127
|
+
const now = config.now || Date.now;
|
|
128
|
+
const db = config.database;
|
|
129
|
+
async function start(request) {
|
|
130
|
+
if (request.method !== "GET") return reply({ error: "METHOD_NOT_ALLOWED" }, 405);
|
|
131
|
+
const url = new URL(request.url);
|
|
132
|
+
const state = nonce(), verifier = nonce();
|
|
133
|
+
const challenge = await sha256(verifier);
|
|
134
|
+
await db.query(
|
|
135
|
+
"INSERT INTO public.kloks_oidc_flows (state_hash,app_id,verifier_encrypted,redirect_uri,return_to,expires_at) VALUES ($1,$2,$3,$4,$5,$6)",
|
|
136
|
+
[
|
|
137
|
+
await sha256(state),
|
|
138
|
+
config.appId,
|
|
139
|
+
await seal(verifier, config),
|
|
140
|
+
config.redirectUri,
|
|
141
|
+
localReturnTo(url.searchParams.get("next"), config),
|
|
142
|
+
new Date(now() + FLOW_MS).toISOString()
|
|
143
|
+
]
|
|
144
|
+
);
|
|
145
|
+
const target = new URL(config.issuer + "/oauth2/authorize");
|
|
146
|
+
for (const [key, value] of Object.entries({
|
|
147
|
+
response_type: "code",
|
|
148
|
+
client_id: config.clientId,
|
|
149
|
+
redirect_uri: config.redirectUri,
|
|
150
|
+
scope: "openid profile email offline_access",
|
|
151
|
+
state,
|
|
152
|
+
code_challenge: challenge,
|
|
153
|
+
code_challenge_method: "S256"
|
|
154
|
+
})) target.searchParams.set(key, value);
|
|
155
|
+
return new Response(null, { status: 303, headers: {
|
|
156
|
+
location: target.toString(),
|
|
157
|
+
"set-cookie": cookie(config, "flow", state, FLOW_MS / 1e3),
|
|
158
|
+
"cache-control": "no-store",
|
|
159
|
+
"referrer-policy": "no-referrer"
|
|
160
|
+
} });
|
|
161
|
+
}
|
|
162
|
+
async function callback(request) {
|
|
163
|
+
if (request.method !== "GET") return reply({ error: "METHOD_NOT_ALLOWED" }, 405);
|
|
164
|
+
const url = new URL(request.url);
|
|
165
|
+
const state = url.searchParams.get("state") || "";
|
|
166
|
+
const code = url.searchParams.get("code") || "";
|
|
167
|
+
const expected = exactCookie(request, cookieName(config, "flow"));
|
|
168
|
+
if (!expected || !sameValue(state, expected) || !/^[A-Za-z0-9_-]{43}$/.test(state) || url.searchParams.get("iss") !== config.issuer || url.searchParams.getAll("iss").length !== 1 || url.searchParams.getAll("state").length !== 1 || url.searchParams.getAll("code").length !== 1 || !/^[A-Za-z0-9._~-]{16,2048}$/.test(code) || url.searchParams.has("error")) {
|
|
169
|
+
const response = reply({ error: "OAUTH_CALLBACK_REJECTED" }, 400);
|
|
170
|
+
response.headers.append("set-cookie", clearCookie(config, "flow"));
|
|
171
|
+
return response;
|
|
172
|
+
}
|
|
173
|
+
const flow = await db.query(
|
|
174
|
+
"UPDATE public.kloks_oidc_flows SET consumed_at=clock_timestamp() WHERE state_hash=$1 AND app_id=$2 AND redirect_uri=$3 AND consumed_at IS NULL AND expires_at>clock_timestamp() RETURNING verifier_encrypted,return_to",
|
|
175
|
+
[await sha256(state), config.appId, config.redirectUri]
|
|
176
|
+
);
|
|
177
|
+
if (flow.rows.length !== 1) return reply({ error: "OAUTH_STATE_EXPIRED_OR_REPLAYED" }, 400);
|
|
178
|
+
const verifier = await unseal(String(flow.rows[0].verifier_encrypted), config);
|
|
179
|
+
const tokens = await exchange(config, new URLSearchParams({
|
|
180
|
+
...Object.fromEntries(clientCredentials(config)),
|
|
181
|
+
grant_type: "authorization_code",
|
|
182
|
+
code,
|
|
183
|
+
redirect_uri: config.redirectUri,
|
|
184
|
+
code_verifier: verifier
|
|
185
|
+
}));
|
|
186
|
+
const principal = await userInfo(config, tokens.access_token);
|
|
187
|
+
if (!principal) return reply({ error: "OAUTH_PRINCIPAL_REJECTED" }, 401);
|
|
188
|
+
const opaque = nonce();
|
|
189
|
+
const sessionId = crypto.randomUUID();
|
|
190
|
+
await db.query(
|
|
191
|
+
"INSERT INTO public.kloks_oidc_sessions (session_hash,session_id,app_id,principal_id,email,display_name,access_encrypted,refresh_encrypted,access_expires_at,expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)",
|
|
192
|
+
[
|
|
193
|
+
await sha256(opaque),
|
|
194
|
+
sessionId,
|
|
195
|
+
config.appId,
|
|
196
|
+
principal.id,
|
|
197
|
+
principal.email,
|
|
198
|
+
principal.name ?? null,
|
|
199
|
+
await seal(tokens.access_token, config),
|
|
200
|
+
tokens.refresh_token ? await seal(tokens.refresh_token, config) : null,
|
|
201
|
+
new Date(now() + tokens.expires_in * 1e3).toISOString(),
|
|
202
|
+
new Date(now() + SESSION_MS).toISOString()
|
|
203
|
+
]
|
|
204
|
+
);
|
|
205
|
+
const location = new URL(localReturnTo(flow.rows[0].return_to, config), configOrigin(config));
|
|
206
|
+
return new Response(null, { status: 303, headers: {
|
|
207
|
+
location: location.toString(),
|
|
208
|
+
"cache-control": "no-store",
|
|
209
|
+
"referrer-policy": "no-referrer",
|
|
210
|
+
"set-cookie": cookie(config, "session", opaque, SESSION_MS / 1e3)
|
|
211
|
+
// The flow cookie is overwritten by a subsequent attempt. Never reuse a consumed state.
|
|
212
|
+
} });
|
|
213
|
+
}
|
|
214
|
+
async function getSession(request) {
|
|
215
|
+
const opaque = exactCookie(request, cookieName(config, "session"));
|
|
216
|
+
if (!opaque) return null;
|
|
217
|
+
const hash = await sha256(opaque);
|
|
218
|
+
const found = await db.query(
|
|
219
|
+
"SELECT session_id,principal_id,email,display_name,access_encrypted,refresh_encrypted,access_expires_at,expires_at,revision FROM public.kloks_oidc_sessions WHERE session_hash=$1 AND app_id=$2 AND revoked_at IS NULL AND expires_at>clock_timestamp() LIMIT 1",
|
|
220
|
+
[hash, config.appId]
|
|
221
|
+
);
|
|
222
|
+
if (found.rows.length !== 1) return null;
|
|
223
|
+
let row = found.rows[0];
|
|
224
|
+
let token = await unseal(String(row.access_encrypted), config);
|
|
225
|
+
if (new Date(row.access_expires_at).getTime() <= now() + ACCESS_SKEW_MS) {
|
|
226
|
+
if (!row.refresh_encrypted) return null;
|
|
227
|
+
const refreshed = await exchange(config, new URLSearchParams({
|
|
228
|
+
...Object.fromEntries(clientCredentials(config)),
|
|
229
|
+
grant_type: "refresh_token",
|
|
230
|
+
refresh_token: await unseal(String(row.refresh_encrypted), config)
|
|
231
|
+
}));
|
|
232
|
+
const updated = await db.query(
|
|
233
|
+
"UPDATE public.kloks_oidc_sessions SET access_encrypted=$1,refresh_encrypted=$2,access_expires_at=$3, revision=revision+1 WHERE session_hash=$4 AND app_id=$5 AND revision=$6 AND revoked_at IS NULL AND expires_at>clock_timestamp() RETURNING session_id,principal_id,email,display_name,expires_at",
|
|
234
|
+
[
|
|
235
|
+
await seal(refreshed.access_token, config),
|
|
236
|
+
await seal(refreshed.refresh_token || await unseal(String(row.refresh_encrypted), config), config),
|
|
237
|
+
new Date(now() + refreshed.expires_in * 1e3).toISOString(),
|
|
238
|
+
hash,
|
|
239
|
+
config.appId,
|
|
240
|
+
row.revision
|
|
241
|
+
]
|
|
242
|
+
);
|
|
243
|
+
if (updated.rows.length !== 1) return null;
|
|
244
|
+
row = updated.rows[0];
|
|
245
|
+
token = refreshed.access_token;
|
|
246
|
+
}
|
|
247
|
+
const current = await userInfo(config, token);
|
|
248
|
+
if (!current || current.id !== row.principal_id || current.email !== row.email) return null;
|
|
249
|
+
return {
|
|
250
|
+
authenticated: true,
|
|
251
|
+
user: current,
|
|
252
|
+
session: { id: String(row.session_id), expiresAt: new Date(row.expires_at).toISOString() }
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
async function session(request) {
|
|
256
|
+
if (request.method !== "GET") return reply({ error: "METHOD_NOT_ALLOWED" }, 405);
|
|
257
|
+
try {
|
|
258
|
+
const active = await getSession(request);
|
|
259
|
+
return active ? reply(active, 200) : reply({ authenticated: false }, 401);
|
|
260
|
+
} catch {
|
|
261
|
+
return reply({ authenticated: false, error: "LUTH_SESSION_UNAVAILABLE" }, 503);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
async function signOut(request) {
|
|
265
|
+
if (request.method !== "POST") return reply({ error: "METHOD_NOT_ALLOWED" }, 405);
|
|
266
|
+
if (request.headers.get("origin") !== configOrigin(config).origin || request.headers.get("sec-fetch-site") === "cross-site") return reply({ error: "ORIGIN_DENIED" }, 403);
|
|
267
|
+
const opaque = exactCookie(request, cookieName(config, "session"));
|
|
268
|
+
if (opaque) {
|
|
269
|
+
const hash = await sha256(opaque);
|
|
270
|
+
const active = await db.query(
|
|
271
|
+
"SELECT refresh_encrypted FROM public.kloks_oidc_sessions WHERE session_hash=$1 AND app_id=$2 AND revoked_at IS NULL AND expires_at>clock_timestamp() LIMIT 1",
|
|
272
|
+
[hash, config.appId]
|
|
273
|
+
);
|
|
274
|
+
await db.query(
|
|
275
|
+
"UPDATE public.kloks_oidc_sessions SET revoked_at=clock_timestamp() WHERE session_hash=$1 AND app_id=$2 AND revoked_at IS NULL",
|
|
276
|
+
[hash, config.appId]
|
|
277
|
+
);
|
|
278
|
+
const token = active.rows[0]?.refresh_encrypted;
|
|
279
|
+
if (typeof token === "string" && token) {
|
|
280
|
+
const revoke = await (config.fetcher || fetch)(config.issuer + "/oauth2/revoke", {
|
|
281
|
+
method: "POST",
|
|
282
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
283
|
+
body: new URLSearchParams({
|
|
284
|
+
...Object.fromEntries(clientCredentials(config)),
|
|
285
|
+
token: await unseal(token, config),
|
|
286
|
+
token_type_hint: "refresh_token"
|
|
287
|
+
}),
|
|
288
|
+
cache: "no-store",
|
|
289
|
+
redirect: "manual"
|
|
290
|
+
}).catch(() => null);
|
|
291
|
+
if (!revoke?.ok) {
|
|
292
|
+
const failed = reply({ success: false, error: "LUTH_REFRESH_TOKEN_REVOCATION_UNVERIFIED" }, 503);
|
|
293
|
+
failed.headers.append("set-cookie", clearCookie(config, "session"));
|
|
294
|
+
return failed;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const response = reply({ success: true }, 200);
|
|
299
|
+
response.headers.append("set-cookie", clearCookie(config, "session"));
|
|
300
|
+
return response;
|
|
301
|
+
}
|
|
302
|
+
async function handle(request) {
|
|
303
|
+
const path = new URL(request.url).pathname;
|
|
304
|
+
if (path === "/api/auth/oidc/start") return start(request);
|
|
305
|
+
if (path === "/api/auth/oidc/callback") return callback(request);
|
|
306
|
+
if (path === "/api/auth/oidc/session") return session(request);
|
|
307
|
+
if (path === "/api/auth/oidc/logout") return signOut(request);
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
return { start, callback, getSession, session, signOut, handle };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// src/auth/OidcBffEnv.ts
|
|
314
|
+
import { neon } from "@neondatabase/serverless";
|
|
315
|
+
import { DEFAULT_LUTH_URL } from "@dinilmusick/gutts/auth";
|
|
316
|
+
function createCanonicalApplicationOAuthBff(request, env, applicationId) {
|
|
317
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,119}$/.test(applicationId)) throw new Error("INVALID_APP_ID");
|
|
318
|
+
const origin = String(env.APP_URL || "").trim();
|
|
319
|
+
const clientId = String(env.LUTH_OAUTH_CLIENT_ID || "").trim();
|
|
320
|
+
const clientSecret = String(env.LUTH_OAUTH_CLIENT_SECRET || "").trim();
|
|
321
|
+
const secret = String(env.LUTH_OAUTH_BFF_SECRET || "");
|
|
322
|
+
const dbUrl = String(env.SYSTEM_DATABASE_URL || env.SYSTEM_DATABASE_URL_2 || env.SYSTEM_DATABASE_URL_3 || "");
|
|
323
|
+
if (!origin || !clientId || !clientSecret || secret.length < 32 || !dbUrl) {
|
|
324
|
+
throw new Error("CANONICAL_APP_AUTH_NOT_PROVISIONED");
|
|
325
|
+
}
|
|
326
|
+
const verifiedOrigin = new URL(origin);
|
|
327
|
+
if (verifiedOrigin.origin !== origin.replace(/\/$/, "") || !["http:", "https:"].includes(verifiedOrigin.protocol) || new URL(request.url).origin !== verifiedOrigin.origin) {
|
|
328
|
+
throw new Error("APPLICATION_ORIGIN_MISMATCH");
|
|
329
|
+
}
|
|
330
|
+
const sql = neon(dbUrl);
|
|
331
|
+
return createOAuthBff({
|
|
332
|
+
appId: applicationId,
|
|
333
|
+
issuer: DEFAULT_LUTH_URL.replace(/\/$/, "") + "/api/auth",
|
|
334
|
+
clientId,
|
|
335
|
+
clientSecret,
|
|
336
|
+
redirectUri: verifiedOrigin.origin + "/api/auth/oidc/callback",
|
|
337
|
+
encryptionSecret: secret,
|
|
338
|
+
database: {
|
|
339
|
+
async query(statement, values) {
|
|
340
|
+
const rows = await sql(statement, [...values]);
|
|
341
|
+
return { rows: [...rows] };
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export {
|
|
348
|
+
createOAuthBff,
|
|
349
|
+
createCanonicalApplicationOAuthBff
|
|
350
|
+
};
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
BackendProvider,
|
|
3
3
|
useBackend,
|
|
4
4
|
useBackendClient
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-YDGW7PXM.js";
|
|
6
6
|
import {
|
|
7
7
|
BackendClient,
|
|
8
8
|
BackendResolver,
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
SequenceTracker,
|
|
14
14
|
WebSocketTransport,
|
|
15
15
|
createBackendClient
|
|
16
|
-
} from "../chunk-
|
|
16
|
+
} from "../chunk-E2I7D52V.js";
|
|
17
17
|
export {
|
|
18
18
|
BackendClient,
|
|
19
19
|
BackendProvider,
|
|
@@ -18,6 +18,7 @@ export declare class FrontendSession {
|
|
|
18
18
|
readonly callbackRegistry: CallbackRegistry;
|
|
19
19
|
readonly sequenceTracker: SequenceTracker;
|
|
20
20
|
private subscriptions;
|
|
21
|
+
private disposed;
|
|
21
22
|
constructor(options?: FrontendSessionOptions);
|
|
22
23
|
setCredential(key: string, value: string): this;
|
|
23
24
|
getCredential(key: string): string | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -23,6 +23,7 @@ export declare class HTTPTransport implements ITransport {
|
|
|
23
23
|
connect(): Promise<void>;
|
|
24
24
|
disconnect(): Promise<void>;
|
|
25
25
|
isConnected(): boolean;
|
|
26
|
+
private operationEndpoint;
|
|
26
27
|
request<T = unknown, R = unknown>(message: Message<T>): Promise<Message<R>>;
|
|
27
28
|
send<T = unknown>(message: Message<T>): Promise<void>;
|
|
28
29
|
subscribe(_channel: string, handler?: MessageHandler): () => void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-owned execution guard for the existing BackendFacade.
|
|
3
|
+
* Luth credential verification, grants, deployment proof, replay storage and workflow
|
|
4
|
+
* storage are mandatory injected authorities; this module creates none of them.
|
|
5
|
+
*/
|
|
6
|
+
import type { BackendFacade } from '../architecture/types.js';
|
|
7
|
+
export type FacadeTransport = 'http' | 'mcp' | 'graph' | 'agent';
|
|
8
|
+
export type InvokerKind = 'user' | 'app-agent' | 'endpoint-agent' | 'workflow-agent';
|
|
9
|
+
export type FacadeHandleKind = 'static' | 'workflow';
|
|
10
|
+
export interface VerifiedFacadeCaller {
|
|
11
|
+
principalId: string;
|
|
12
|
+
sourceAppId: string;
|
|
13
|
+
sourceWorkspaceId: string;
|
|
14
|
+
audience: string;
|
|
15
|
+
sessionId: string;
|
|
16
|
+
invoker: {
|
|
17
|
+
kind: InvokerKind;
|
|
18
|
+
id: string;
|
|
19
|
+
};
|
|
20
|
+
chain: readonly string[];
|
|
21
|
+
depth: number;
|
|
22
|
+
maxDepth: number;
|
|
23
|
+
remainingCalls: number;
|
|
24
|
+
deadlineAt: number;
|
|
25
|
+
expiresAt: number;
|
|
26
|
+
}
|
|
27
|
+
/** Only metadata and an immutable function reference; never include graph definitions or secrets. */
|
|
28
|
+
export interface FacadeOperationDescriptor {
|
|
29
|
+
id: string;
|
|
30
|
+
version: string;
|
|
31
|
+
name: string;
|
|
32
|
+
kind: FacadeHandleKind;
|
|
33
|
+
targetWorkspaceId: string;
|
|
34
|
+
serviceId?: string;
|
|
35
|
+
serviceOperation?: string;
|
|
36
|
+
workflowId?: string;
|
|
37
|
+
}
|
|
38
|
+
export interface FacadeInvocation {
|
|
39
|
+
operationId: string;
|
|
40
|
+
version: string;
|
|
41
|
+
targetWorkspaceId: string;
|
|
42
|
+
invocationId: string;
|
|
43
|
+
input: unknown;
|
|
44
|
+
}
|
|
45
|
+
export interface FacadeDecision {
|
|
46
|
+
caller: Readonly<VerifiedFacadeCaller>;
|
|
47
|
+
operation: Readonly<FacadeOperationDescriptor>;
|
|
48
|
+
transport: FacadeTransport;
|
|
49
|
+
}
|
|
50
|
+
export interface FacadeInvocationOptions {
|
|
51
|
+
targetAppId: string;
|
|
52
|
+
facade: BackendFacade;
|
|
53
|
+
/** Must validate Luth signature, audience, session status, revocation and delegation chain at each use. */
|
|
54
|
+
verifyLuthCredential: (credential: string, targetAudience: string) => Promise<VerifiedFacadeCaller | null>;
|
|
55
|
+
/**
|
|
56
|
+
* Fresh, NON-CONSUMING Luth/session authority check for an already admitted caller.
|
|
57
|
+
* Must validate the live session, delegation/grant revocation, target app and
|
|
58
|
+
* audience against trusted state; must NEVER introspect or replay the one-use
|
|
59
|
+
* admission bearer. Return the current trusted identity or null.
|
|
60
|
+
*/
|
|
61
|
+
revalidateLuthCaller: (admitted: Readonly<VerifiedFacadeCaller>, targetAudience: string) => Promise<VerifiedFacadeCaller | null>;
|
|
62
|
+
/** Must return only current static definitions and explicitly published workflow references. */
|
|
63
|
+
listCurrentOperations: (workspaceId: string) => Promise<FacadeOperationDescriptor[]>;
|
|
64
|
+
/** Must re-read current owner, publication, ACL, grant, scopes, input and output rules. */
|
|
65
|
+
authorize: (decision: FacadeDecision, phase: 'discover' | 'invoke' | 'output', value?: unknown) => Promise<boolean>;
|
|
66
|
+
/** Must verify registry attestation, active lease, environment and target-workspace access. */
|
|
67
|
+
deploymentEligible: (decision: FacadeDecision) => Promise<boolean>;
|
|
68
|
+
/** Durable, atomic replay rejection and shared work-budget debit. No in-memory fallback. */
|
|
69
|
+
consumeInvocation: (caller: VerifiedFacadeCaller, invocationId: string) => Promise<boolean>;
|
|
70
|
+
/** Resolve the workflow from its owning workspace, then invoke via existing FOD runtime. */
|
|
71
|
+
invokePublishedWorkflow: (reference: {
|
|
72
|
+
workspaceId: string;
|
|
73
|
+
workflowId: string;
|
|
74
|
+
version: string;
|
|
75
|
+
}, input: unknown, signal: AbortSignal) => Promise<unknown>;
|
|
76
|
+
/** Issue a new Luth-verifiable, audience-scoped delegated credential after atomic budget reservation. */
|
|
77
|
+
delegateCredential: (caller: VerifiedFacadeCaller, targetAppId: string, invocationId: string, signal?: AbortSignal) => Promise<string>;
|
|
78
|
+
}
|
|
79
|
+
export declare class FacadeInvocationDenied extends Error {
|
|
80
|
+
readonly code: string;
|
|
81
|
+
readonly status: number;
|
|
82
|
+
constructor(code: string, status?: number);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* All four entry points call the same guard. No client-controlled user, app,
|
|
86
|
+
* source workspace, parent caller or grant claim is accepted as authority.
|
|
87
|
+
*/
|
|
88
|
+
export declare function createFacadeInvocationBoundary(options: FacadeInvocationOptions): {
|
|
89
|
+
discover: (credential: string, workspaceId: string, transport: FacadeTransport) => Promise<Pick<FacadeOperationDescriptor, "name" | "id" | "version" | "targetWorkspaceId" | "kind">[]>;
|
|
90
|
+
invoke: (credential: string, request: FacadeInvocation, transport: FacadeTransport, parentSignal?: AbortSignal) => Promise<{
|
|
91
|
+
output: unknown;
|
|
92
|
+
replyTo: {
|
|
93
|
+
kind: InvokerKind;
|
|
94
|
+
id: string;
|
|
95
|
+
};
|
|
96
|
+
invocationId: string;
|
|
97
|
+
}>;
|
|
98
|
+
delegate: (credential: string, targetAppId: string, request: FacadeInvocation, dispatch: (credential: string, request: FacadeInvocation, signal?: AbortSignal) => Promise<unknown>, signal?: AbortSignal) => Promise<unknown>;
|
|
99
|
+
http: (request: Request) => Promise<Response>;
|
|
100
|
+
mcp: (request: Request) => Promise<Response>;
|
|
101
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -22,3 +22,5 @@ export * from './RemoteExecutor.js';
|
|
|
22
22
|
export * from './BackendResolver.js';
|
|
23
23
|
export * from './FrontendSession.js';
|
|
24
24
|
export * from './BackendClient.js';
|
|
25
|
+
/** Target-side, host-authorized BackendFacade invocation guard (HTTP/MCP/graph/agent). */
|
|
26
|
+
export * from './facadeInvocation.js';
|
|
@@ -2,6 +2,7 @@ import {
|
|
|
2
2
|
BackendRegistry,
|
|
3
3
|
ConcurrencyConflictError,
|
|
4
4
|
ConcurrencyManager,
|
|
5
|
+
FacadeInvocationDenied,
|
|
5
6
|
HealthMonitor,
|
|
6
7
|
IdempotencyManager,
|
|
7
8
|
InProcessExecutor,
|
|
@@ -9,8 +10,9 @@ import {
|
|
|
9
10
|
LoadBalancer,
|
|
10
11
|
LockManager,
|
|
11
12
|
RemoteExecutor,
|
|
12
|
-
createEmptyContract
|
|
13
|
-
|
|
13
|
+
createEmptyContract,
|
|
14
|
+
createFacadeInvocationBoundary
|
|
15
|
+
} from "../chunk-HX5TN27Y.js";
|
|
14
16
|
import {
|
|
15
17
|
BackendClient,
|
|
16
18
|
BackendResolver,
|
|
@@ -21,7 +23,7 @@ import {
|
|
|
21
23
|
SequenceTracker,
|
|
22
24
|
WebSocketTransport,
|
|
23
25
|
createBackendClient
|
|
24
|
-
} from "../chunk-
|
|
26
|
+
} from "../chunk-E2I7D52V.js";
|
|
25
27
|
export {
|
|
26
28
|
BackendClient,
|
|
27
29
|
BackendRegistry,
|
|
@@ -30,6 +32,7 @@ export {
|
|
|
30
32
|
ConcurrencyConflictError,
|
|
31
33
|
ConcurrencyManager,
|
|
32
34
|
EventBus,
|
|
35
|
+
FacadeInvocationDenied,
|
|
33
36
|
FrontendSession,
|
|
34
37
|
HTTPTransport,
|
|
35
38
|
HealthMonitor,
|
|
@@ -42,5 +45,6 @@ export {
|
|
|
42
45
|
SequenceTracker,
|
|
43
46
|
WebSocketTransport,
|
|
44
47
|
createBackendClient,
|
|
45
|
-
createEmptyContract
|
|
48
|
+
createEmptyContract,
|
|
49
|
+
createFacadeInvocationBoundary
|
|
46
50
|
};
|
|
@@ -95,6 +95,7 @@ import {
|
|
|
95
95
|
BackendRegistry,
|
|
96
96
|
ConcurrencyConflictError,
|
|
97
97
|
ConcurrencyManager,
|
|
98
|
+
FacadeInvocationDenied,
|
|
98
99
|
HealthMonitor,
|
|
99
100
|
IdempotencyManager,
|
|
100
101
|
InProcessExecutor,
|
|
@@ -102,8 +103,9 @@ import {
|
|
|
102
103
|
LoadBalancer,
|
|
103
104
|
LockManager,
|
|
104
105
|
RemoteExecutor,
|
|
105
|
-
createEmptyContract
|
|
106
|
-
|
|
106
|
+
createEmptyContract,
|
|
107
|
+
createFacadeInvocationBoundary
|
|
108
|
+
} from "./chunk-HX5TN27Y.js";
|
|
107
109
|
import {
|
|
108
110
|
BackendClient,
|
|
109
111
|
BackendResolver,
|
|
@@ -114,7 +116,7 @@ import {
|
|
|
114
116
|
SequenceTracker,
|
|
115
117
|
WebSocketTransport,
|
|
116
118
|
createBackendClient
|
|
117
|
-
} from "./chunk-
|
|
119
|
+
} from "./chunk-E2I7D52V.js";
|
|
118
120
|
import {
|
|
119
121
|
authorizeB2,
|
|
120
122
|
b2DownloadFile,
|
|
@@ -143,6 +145,7 @@ export {
|
|
|
143
145
|
ConcurrencyConflictError,
|
|
144
146
|
ConcurrencyManager,
|
|
145
147
|
EventBus,
|
|
148
|
+
FacadeInvocationDenied,
|
|
146
149
|
FrontendSession,
|
|
147
150
|
GOOGLE_DRIVE_WORKSPACE_SCOPE,
|
|
148
151
|
GoogleDriveWorkspaceService,
|
|
@@ -175,6 +178,7 @@ export {
|
|
|
175
178
|
createCanonicalStorageService,
|
|
176
179
|
createDropboxStorageService,
|
|
177
180
|
createEmptyContract,
|
|
181
|
+
createFacadeInvocationBoundary,
|
|
178
182
|
createGitHubStorageService,
|
|
179
183
|
createGoogleDriveStorageService,
|
|
180
184
|
createLuthAuthClient,
|
|
@@ -11,11 +11,11 @@ import {
|
|
|
11
11
|
AIRoutingServiceFacade,
|
|
12
12
|
AIToolServiceDefinition,
|
|
13
13
|
AIToolServiceFacade
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-26NAKO4V.js";
|
|
15
15
|
import "./chunk-PT6J6UEU.js";
|
|
16
16
|
import "./chunk-LMWXONZG.js";
|
|
17
17
|
import "./chunk-U4HUGPRH.js";
|
|
18
|
-
import "./chunk-
|
|
18
|
+
import "./chunk-MK4ZRBFI.js";
|
|
19
19
|
import "./chunk-P7H6TIEA.js";
|
|
20
20
|
import "./chunk-SLR6SIEU.js";
|
|
21
21
|
import "./chunk-MAMK4GDH.js";
|