server.mjs
3,631 lines 144.2 KB
Raw
sha256:c541f54879f8110bb25bb9786cdb8ff7a4aec19f9f2a2789a55bc74e6f7fe095 fix(7C-L1c): persist hosted delegation indexes in Netlify Blobs Human minor ⚠ breaking 32 days ago
1 /**
2 * Knowtation Hub Gateway — OAuth (Google/GitHub) + proxy to ICP canister with X-User-Id.
3 * For hosted product: user logs in here; all /api/* requests are proxied to canister with proof.
4 * Run: node server.mjs
5 * Env: SESSION_SECRET, CANISTER_URL, HUB_BASE_URL; optional GOOGLE_*, GITHUB_*, HUB_UI_ORIGIN, GATEWAY_PORT.
6 */
7
8 import crypto from 'crypto';
9 import fs from 'fs';
10 import path from 'path';
11 import { fileURLToPath } from 'url';
12 import dotenv from 'dotenv';
13 import express from 'express';
14 import cookieParser from 'cookie-parser';
15 import jwt from 'jsonwebtoken';
16 import passport from 'passport';
17 import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
18 import { Strategy as GitHubStrategy } from 'passport-github2';
19 import { stripeWebhookHandler, createCheckoutSession, createPortalSession } from './billing-stripe.mjs';
20 import { handleBillingSummary } from './billing-http.mjs';
21 import { isSubscriptionPriceId, isPackPriceId, priceIdFromTierShorthand, billingEnforced, MONTHLY_INCLUDED_CENTS_BY_TIER } from './billing-constants.mjs';
22 import { recordIndexingTokensAfterBridgeIndex } from './billing-index-usage.mjs';
23 import { runBillingGate } from './billing-middleware.mjs';
24 import { mergeHostedNoteBodyForCanister, isPostApiV1Notes, isNoteWriteRequest } from './apply-note-provenance.mjs';
25 import { deriveFacetsFromCanisterNotes, materializeListFrontmatter } from './note-facets.mjs';
26 import { applyGatewayCors } from './cors-middleware.mjs';
27 import { upstreamPathAndQuery, pathPartNoQuery, effectiveRequestPath } from './request-path.mjs';
28 import { applyScopeFilterToNotes } from '../lib/scope-filter.mjs';
29 import { createMetadataBulkHandlers } from './metadata-bulk-canister.mjs';
30 import { filterUpstreamResponseHeadersForDecodedBody } from './upstream-response-headers.mjs';
31 import { loadProposalRubric } from '../../lib/hub-proposal-rubric.mjs';
32 import { commitImageToRepo, validateImageExtension, validateMagicBytes } from '../../lib/github-commit-image.mjs';
33 import { parseMultipartFile } from './parse-multipart.mjs';
34 import { proposalPolicyEnvLocked } from '../../lib/hub-proposal-policy.mjs';
35 import {
36 loadHostedProposalLlmPrefs,
37 mergeHostedProposalLlmPrefs,
38 effectiveHostedEvaluationRequired,
39 effectiveHostedReviewHints,
40 effectiveHostedEnrich,
41 } from './proposal-llm-store.mjs';
42 import { augmentProposalEvaluationBodyForCanister } from './proposal-evaluation-canister-body.mjs';
43 import { augmentProposalCreateForHosted } from './proposal-create-hosted-body.mjs';
44 import { maybeScheduleHostedProposalReviewHints } from './proposal-review-hints-async.mjs';
45 import { proposalDataForHostedReviewHintsFromCreate } from './proposal-hints-create-context.mjs';
46 import { runHostedProposalEnrichAndPost } from './proposal-enrich-hosted.mjs';
47 import { isAttestationConfigured, createAttestation, verifyAttestation, verifyWithIcp, anchorPendingAttestations } from './attest-store.mjs';
48 import { loadBillingDb, mutateBillingDb } from './billing-store.mjs';
49 import { normalizeBillingUser, defaultUserRecord } from './billing-logic.mjs';
50 import {
51 mergeConsolidateRequestBodyWithBillingDefaults,
52 validateHostedSettingsConsolidationAdvanced,
53 } from '../../lib/hosted-consolidation-advanced.mjs';
54 import {
55 parseMuseConfigFromEnv,
56 resolveExternalRefForApprove,
57 proposalIdFromApprovePath,
58 fetchMuseProxiedGet,
59 } from '../../lib/muse-thin-bridge.mjs';
60 import {
61 maybeApplyHostedDelegationAfterApprove,
62 mergeDelegationApplyIntoApproveResponse,
63 } from './delegation-approve-hosted.mjs';
64 import { exportNoteRecordToContent } from '../../lib/export.mjs';
65 import { canisterAuthHeaders as canisterAuthHeadersFromEnv } from './canister-auth-headers.mjs';
66 import {
67 issueRefreshCookie,
68 createRefreshHandler,
69 createLogoutHandler,
70 refreshCookieOptions,
71 } from '../auth-session.mjs';
72 import {
73 createGatewayRefreshStore,
74 pruneRefreshTokens as pruneGatewayRefreshTokens,
75 } from './refresh-token-store.mjs';
76 import { createScoolingNoteOutlineSmokeRouter } from './scooling-note-outline-smoke.mjs';
77 import { createScoolingWriteBackSmokeRouter } from './scooling-write-back-smoke.mjs';
78 import { buildNoteOutline } from '../../lib/note-outline.mjs';
79 import { buildDocumentTree } from '../../lib/document-tree.mjs';
80 import { buildSectionSource } from '../../lib/section-source.mjs';
81 import { normalizeMetadataFacets } from '../../lib/vault.mjs';
82
83 // Safe when bundled (e.g. Netlify Functions CJS) where import.meta may be undefined
84 let projectRoot;
85 try {
86 const __dirname = path.dirname(fileURLToPath(import.meta.url));
87 projectRoot = path.resolve(__dirname, '..', '..');
88 } catch (_) {
89 projectRoot = process.cwd();
90 }
91 const envPath = path.join(projectRoot, '.env');
92 if (fs.existsSync(envPath)) dotenv.config({ path: envPath });
93
94 const PORT = parseInt(process.env.GATEWAY_PORT || process.env.PORT || '3340', 10);
95 const BASE_URL = process.env.HUB_BASE_URL || `http://localhost:${PORT}`;
96
97 // AIR Improvement D: when ATTESTATION_SECRET is set and no explicit AIR endpoint
98 // is provided, point AIR at this gateway's own /api/v1/attest route.
99 if (
100 process.env.ATTESTATION_SECRET &&
101 process.env.ATTESTATION_SECRET.length >= 32 &&
102 !process.env.KNOWTATION_AIR_ENDPOINT
103 ) {
104 process.env.KNOWTATION_AIR_ENDPOINT = `${BASE_URL}/api/v1/attest`;
105 console.log('[gateway] AIR auto-configured: KNOWTATION_AIR_ENDPOINT =', process.env.KNOWTATION_AIR_ENDPOINT);
106 }
107 const CANISTER_URL = (process.env.CANISTER_URL || '').replace(/\/$/, '');
108 const CANISTER_AUTH_SECRET = process.env.CANISTER_AUTH_SECRET || '';
109 const BRIDGE_URL = (process.env.BRIDGE_URL || '').replace(/\/$/, '');
110 if (BRIDGE_URL) {
111 try {
112 const u = new URL(BRIDGE_URL);
113 if (u.protocol !== 'http:' && u.protocol !== 'https:') {
114 throw new Error('BRIDGE_URL must use http: or https:');
115 }
116 } catch (e) {
117 console.error(
118 '[gateway] BRIDGE_URL must be an absolute URL with scheme (no path after host), e.g. https://your-bridge.netlify.app. Got:',
119 JSON.stringify(BRIDGE_URL),
120 e.message || e,
121 );
122 process.exit(1);
123 }
124 }
125 const HUB_UI_ORIGIN = (process.env.HUB_UI_ORIGIN || BASE_URL).replace(/\/$/, '');
126 const SESSION_SECRET = process.env.SESSION_SECRET || process.env.HUB_JWT_SECRET;
127 const JWT_EXPIRY = process.env.HUB_JWT_EXPIRY || '24h';
128
129 // Optional: comma-separated list of user IDs (e.g. google:123,github:456) who get role admin on hosted. Others get member.
130 const HUB_ADMIN_USER_IDS = (process.env.HUB_ADMIN_USER_IDS || '')
131 .split(',')
132 .map((s) => s.trim())
133 .filter(Boolean);
134 const adminUserIdsSet = new Set(HUB_ADMIN_USER_IDS);
135
136 function roleForSub(sub) {
137 return sub && adminUserIdsSet.has(sub) ? 'admin' : 'member';
138 }
139
140 function canisterAuthHeaders() {
141 return canisterAuthHeadersFromEnv();
142 }
143
144 passport.serializeUser((user, done) => done(null, user));
145 passport.deserializeUser((obj, done) => done(null, obj));
146
147 if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET) {
148 passport.use(
149 new GoogleStrategy(
150 {
151 clientID: process.env.GOOGLE_CLIENT_ID,
152 clientSecret: process.env.GOOGLE_CLIENT_SECRET,
153 callbackURL: `${BASE_URL}/auth/callback/google`,
154 },
155 (_accessToken, _refreshToken, profile, done) => {
156 return done(null, { provider: 'google', id: profile.id, displayName: profile.displayName ?? '' });
157 }
158 )
159 );
160 }
161 if (process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET) {
162 passport.use(
163 new GitHubStrategy(
164 {
165 clientID: process.env.GITHUB_CLIENT_ID,
166 clientSecret: process.env.GITHUB_CLIENT_SECRET,
167 callbackURL: `${BASE_URL}/auth/callback/github`,
168 },
169 (_accessToken, _refreshToken, profile, done) => {
170 return done(null, { provider: 'github', id: profile.id, displayName: profile.displayName ?? profile.username ?? '' });
171 }
172 )
173 );
174 }
175
176 function userId(user) {
177 if (!user || !user.provider || !user.id) return null;
178 return `${user.provider}:${user.id}`;
179 }
180
181 function issueToken(user) {
182 const sub = userId(user);
183 if (!sub) return null;
184 const role = roleForSub(sub);
185 return jwt.sign(
186 {
187 sub,
188 provider: user.provider,
189 id: user.id,
190 name: user.displayName ?? '',
191 role,
192 },
193 SESSION_SECRET,
194 { expiresIn: JWT_EXPIRY }
195 );
196 }
197
198 function verifyToken(token) {
199 try {
200 const payload = jwt.verify(token, SESSION_SECRET);
201 return payload.sub ?? null;
202 } catch (_) {
203 return null;
204 }
205 }
206
207 /**
208 * Verify the token and return the full decoded payload, or null if invalid/expired.
209 * Used only by the session-introspection endpoint; callers that only need `sub` use verifyToken.
210 * @param {string} token
211 * @returns {object|null}
212 */
213 function decodeVerifiedToken(token) {
214 try {
215 return jwt.verify(token, SESSION_SECRET);
216 } catch (_) {
217 return null;
218 }
219 }
220
221 /**
222 * Derive the set of API scopes from a role string.
223 * This is the C7 → C4 bridge: Scooling can read `scopes` today; when explicit per-user
224 * scope management (C4) is wired in, this function will be replaced with a real lookup
225 * without changing the C7 response shape.
226 * @param {string} role - 'admin' | 'member'
227 * @returns {string[]}
228 */
229 function scopesForRole(role) {
230 if (role === 'admin') return ['vault:read', 'vault:write', 'admin'];
231 return ['vault:read', 'vault:write'];
232 }
233
234 /**
235 * Re-mint a short-lived access token from a `sub` alone (used by POST /api/v1/auth/refresh,
236 * which only knows the user id carried by the refresh-token record). The `sub` is the canonical
237 * `provider:id`, so provider/id are reconstructed from it and the role is re-derived from the
238 * current admin allowlist — a refreshed token always reflects the latest role, exactly like
239 * login. Display name is omitted (cosmetic; the UI reads it from /settings).
240 * @param {string} sub
241 * @returns {string|null} signed JWT, or null when sub is missing
242 */
243 function issueAccessTokenForSub(sub) {
244 if (!sub || typeof sub !== 'string') return null;
245 const idx = sub.indexOf(':');
246 const provider = idx > 0 ? sub.slice(0, idx) : '';
247 const id = idx > 0 ? sub.slice(idx + 1) : sub;
248 return jwt.sign(
249 { sub, provider, id, name: '', role: roleForSub(sub) },
250 SESSION_SECRET,
251 { expiresIn: JWT_EXPIRY }
252 );
253 }
254
255 const IMAGE_PROXY_TOKEN_TTL_SECONDS = 300;
256
257 function signImageProxyToken(secret, uid) {
258 const exp = Math.floor(Date.now() / 1000) + IMAGE_PROXY_TOKEN_TTL_SECONDS;
259 const payload = `img\0${uid}\0${exp}`;
260 const sig = crypto.createHmac('sha256', secret).update(payload).digest('base64url');
261 return `${exp}.${Buffer.from(uid).toString('base64url')}.${sig}`;
262 }
263
264 function verifyImageProxyToken(secret, token) {
265 if (typeof token !== 'string') return null;
266 const parts = token.split('.');
267 if (parts.length !== 3) return null;
268 const [expStr, uidB64, sig] = parts;
269 const exp = parseInt(expStr, 10);
270 if (!exp || Math.floor(Date.now() / 1000) > exp) return null;
271 let uid;
272 try { uid = Buffer.from(uidB64, 'base64url').toString(); } catch (_) { return null; }
273 if (!uid) return null;
274 const payload = `img\0${uid}\0${exp}`;
275 const expected = crypto.createHmac('sha256', secret).update(payload).digest('base64url');
276 const sigBuf = Buffer.from(sig);
277 const expectedBuf = Buffer.from(expected);
278 if (sigBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(sigBuf, expectedBuf)) return null;
279 return uid;
280 }
281
282 const app = express();
283 // Trust the first downstream proxy so express-rate-limit (and any future IP-based middleware)
284 // reads the real client IP from X-Forwarded-For instead of the CDN/load-balancer address.
285 app.set('trust proxy', 1);
286
287 // Remove X-Powered-By: Express — leaking server technology is unnecessary attack surface.
288 app.disable('x-powered-by');
289
290 // Netlify rewrites /* -> /.netlify/functions/gateway/:splat, so the function may receive
291 // a path like /.netlify/functions/gateway/api/v1/notes. Express would not match /api/v1/* routes.
292 const NETLIFY_GW_PREFIX = '/.netlify/functions/gateway';
293 app.use((req, _res, next) => {
294 const raw = req.url || '/';
295 const q = raw.indexOf('?');
296 const pathPart = q >= 0 ? raw.slice(0, q) : raw;
297 const queryPart = q >= 0 ? raw.slice(q) : '';
298 if (pathPart === NETLIFY_GW_PREFIX || pathPart.startsWith(`${NETLIFY_GW_PREFIX}/`)) {
299 const rest =
300 pathPart === NETLIFY_GW_PREFIX ? '/' : pathPart.slice(NETLIFY_GW_PREFIX.length) || '/';
301 const nextUrl = rest + queryPart;
302 req.url = nextUrl;
303 // Express may set originalUrl to the internal function path; keep it aligned with req.path.
304 req.originalUrl = nextUrl;
305 delete req._parsedUrl;
306 delete req._parsedOriginalUrl;
307 }
308 next();
309 });
310
311 app.use(cookieParser());
312 app.post('/api/v1/billing/webhook', express.raw({ type: 'application/json' }), (req, res) => {
313 stripeWebhookHandler(req, res);
314 });
315 app.use(express.json({ limit: '10mb' }));
316 app.use(passport.initialize());
317
318 // CORS: production MUST set HUB_CORS_ORIGIN (apex + www) for credentialed-style responses.
319 // If unset, we use * and omit Allow-Credentials — otherwise browsers block (* + credentials = Failed to fetch).
320 // See hub/gateway/cors-middleware.mjs.
321 const corsOrigins = process.env.HUB_CORS_ORIGIN
322 ? process.env.HUB_CORS_ORIGIN.split(',').map((o) => o.trim()).filter(Boolean)
323 : [];
324 app.use((req, res, next) => {
325 applyGatewayCors(res, req.get('Origin'), corsOrigins);
326 next();
327 });
328
329 // Persistent sessions (refresh-token rotation), hosted edition. The durable, hashed refresh
330 // token is delivered as an HttpOnly cookie; the security logic lives in
331 // hub/lib/refresh-token-core.mjs via the blob-backed store below (shared with self-hosted).
332 const refreshStore = createGatewayRefreshStore();
333
334 /**
335 * Cookie policy for the hosted refresh token.
336 * - When the UI and gateway share an origin (HUB_CORS_ORIGIN unset), the cookie is first-party
337 * and SameSite=Lax is correct and most robust.
338 * - When HUB_CORS_ORIGIN is set the UI is on another origin, so the credentialed cross-site
339 * request requires SameSite=None (which forces Secure). NOTE: a cross-site cookie is only
340 * delivered reliably when the gateway is a subdomain of the UI's registrable domain (e.g.
341 * UI knowtation.store + gateway api.knowtation.store); browsers increasingly block
342 * unrelated third-party cookies. Same-origin (single origin for UI + API) is recommended.
343 * Scoped to the auth path so the cookie is only ever sent to /api/v1/auth endpoints.
344 */
345 function refreshCookiePolicy() {
346 const crossOrigin = corsOrigins.length > 0;
347 return refreshCookieOptions({
348 secure: crossOrigin || BASE_URL.startsWith('https://'),
349 sameSite: crossOrigin ? 'none' : 'lax',
350 maxAgeMs: 90 * 24 * 60 * 60 * 1000,
351 });
352 }
353
354 /**
355 * Issue the HttpOnly refresh cookie at the end of a successful OAuth login. Best-effort: a
356 * refresh-store write failure must never block login (the access token still works).
357 * @param {import('express').Response} res
358 * @param {import('express').Request} req
359 * @param {string|null} sub
360 */
361 async function issueRefreshCookieSafe(res, req, sub) {
362 if (!sub) {
363 console.warn('[gateway] refresh cookie skipped: no sub resolved from req.user');
364 return;
365 }
366 try {
367 await issueRefreshCookie(res, {
368 store: refreshStore,
369 sub,
370 cookieOptions: refreshCookiePolicy,
371 meta: { ua: String(req.headers['user-agent'] || '').slice(0, 256) },
372 });
373 console.info('[gateway] refresh cookie issued for sub=%s', sub);
374 } catch (err) {
375 // Login still proceeds with the access token even if the refresh store is unavailable, but
376 // the failure MUST be surfaced — swallowing it silently made a persistent-login outage
377 // undiagnosable. `authBlobPresent` distinguishes the two failure modes:
378 // false → the Netlify Blob was not provisioned for this invocation, so the store fell back
379 // to a file write that fails on the read-only function FS;
380 // true → the blob was provisioned but the read/write itself was rejected.
381 const authBlobPresent = Boolean(globalThis.__knowtation_gateway_auth_blob);
382 console.error(
383 '[gateway] refresh cookie FAILED for sub=%s authBlobPresent=%s: %s',
384 sub,
385 authBlobPresent,
386 err && err.stack ? err.stack : (err && err.message) || String(err),
387 );
388 }
389 }
390
391 // Authenticated Hub JSON must not be cached (browser 304 / CDN reuse shows stale frontmatter).
392 app.use('/api/v1', (req, res, next) => {
393 res.set('Cache-Control', 'private, no-store, must-revalidate');
394 next();
395 });
396
397 // Health (no auth) — returns { ok: true }. If a CDN or host wrapper returns usage_exceeded, that is outside this app (check Netlify site / account limits and which commit is deployed).
398 app.get('/health', (_req, res) => res.json({ ok: true }));
399 app.get('/api/v1/health', (_req, res) => res.json({ ok: true }));
400 app.use(createScoolingNoteOutlineSmokeRouter());
401 app.use(createScoolingWriteBackSmokeRouter());
402
403 // Which OAuth providers are configured (no auth)
404 app.get('/api/v1/auth/providers', (_req, res) => {
405 res.json({
406 google: Boolean(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET),
407 github: Boolean(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET),
408 });
409 });
410
411 // C7 Session introspection — returns the verified identity and derived scopes for the bearer.
412 // Designed for Scooling (cross-origin, Bearer auth) and the Hub UI alike.
413 // GET /api/v1/auth/session → { sub, provider, id, name, role, iat, exp, scopes }
414 // Only reads what is already in the signed JWT — no extra DB call, no data elevation.
415 app.options('/api/v1/auth/session', (_req, res) => res.status(204).end());
416 app.get('/api/v1/auth/session', (req, res) => {
417 const auth = req.headers.authorization;
418 if (!auth || !auth.startsWith('Bearer ')) {
419 return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
420 }
421 const token = auth.slice(7);
422 const payload = decodeVerifiedToken(token);
423 if (!payload || !payload.sub) {
424 return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
425 }
426 return res.json({
427 sub: payload.sub,
428 provider: payload.provider ?? '',
429 id: payload.id ?? '',
430 name: payload.name ?? '',
431 role: payload.role ?? 'member',
432 iat: payload.iat,
433 exp: payload.exp,
434 scopes: scopesForRole(payload.role ?? 'member'),
435 });
436 });
437
438 // Persistent sessions: exchange the HttpOnly refresh cookie for a fresh access token, and real
439 // server-side logout (revokes the refresh token, not just the client cookie). Mounted BEFORE the
440 // bridge/canister proxies so these are handled locally and never forwarded upstream.
441 //
442 // Rate limiting note: an in-memory express-rate-limit is ineffective on Netlify (each function
443 // invocation is isolated, no shared counter) and trips ERR_ERL_* under serverless proxies. Brute
444 // force is bounded instead by edge limits (see hub/gateway/README.md) and, more fundamentally, by
445 // the opaque high-entropy token + rotation/reuse detection in refresh-token-core.mjs.
446 app.options(['/api/v1/auth/refresh', '/api/v1/auth/logout'], (_req, res) => res.status(204).end());
447 app.post(
448 '/api/v1/auth/refresh',
449 createRefreshHandler({
450 store: refreshStore,
451 issueAccessToken: issueAccessTokenForSub,
452 cookieOptions: refreshCookiePolicy,
453 meta: (req) => ({ ua: String(req.headers['user-agent'] || '').slice(0, 256) }),
454 })
455 );
456 app.post(
457 '/api/v1/auth/logout',
458 createLogoutHandler({ store: refreshStore, cookieOptions: refreshCookiePolicy })
459 );
460 // On a persistent gateway (local/Docker/VPS) opportunistically prune dead refresh records at
461 // startup. Skipped on Netlify, where the blob store is provisioned per-invocation and a cold-start
462 // prune would add latency to the first request; rely on rotation/expiry to keep the store small.
463 if (!process.env.NETLIFY) {
464 Promise.resolve()
465 .then(() => pruneGatewayRefreshTokens())
466 .catch(() => { /* best effort; never fatal */ });
467 }
468
469 // Auth: login redirect — plan routes GET /auth/login, GET /auth/callback/google|github. Preserve invite in state for post-login redirect.
470 // Phase D3: mcp_state query param is passed through OAuth state for MCP authorization flow.
471 // C1/C3 (COMPANION-APP-OAUTH-SERVERSIDE-GATE §6): native_state query param is passed
472 // through OAuth state for the native client authorization flow (prefix "native:").
473 app.get('/auth/login', (req, res, next) => {
474 const provider = (req.query.provider || 'google').toLowerCase();
475 const invite = typeof req.query.invite === 'string' ? req.query.invite.trim() : '';
476 const mcpState = typeof req.query.mcp_state === 'string' ? req.query.mcp_state.trim() : '';
477 const nativeState = typeof req.query.native_state === 'string' ? req.query.native_state.trim() : '';
478 let state;
479 if (mcpState) {
480 state = `mcp:${mcpState}`;
481 } else if (nativeState) {
482 // Prefix distinguishes native auth round-trips from MCP round-trips in the IDP callback.
483 state = `native:${nativeState}`;
484 } else {
485 state = invite || undefined;
486 }
487 if (provider === 'google' && process.env.GOOGLE_CLIENT_ID) {
488 return passport.authenticate('google', { scope: ['profile'], state })(req, res, next);
489 }
490 if (provider === 'github' && process.env.GITHUB_CLIENT_ID) {
491 return passport.authenticate('github', { scope: ['user:email'], state })(req, res, next);
492 }
493 return res.status(400).json({ error: `Unknown or disabled provider: ${provider}`, code: 'BAD_REQUEST' });
494 });
495
496 function postLoginRedirect(token, req) {
497 if (!token) return HUB_UI_ORIGIN + '/hub/?auth_error=1';
498 const invite = typeof req.query.state === 'string' ? req.query.state.trim() : '';
499 let fragment = `token=${encodeURIComponent(token)}`;
500 if (invite && invite.length > 0) fragment += '&invite=' + encodeURIComponent(invite);
501 return `${HUB_UI_ORIGIN}/hub/#${fragment}`;
502 }
503
504 app.get(
505 '/auth/callback/google',
506 passport.authenticate('google', { session: false }),
507 async (req, res) => {
508 const state = typeof req.query.state === 'string' ? req.query.state : '';
509 if (state.startsWith('mcp:') && app._mcpOAuthProvider) {
510 const sub = userId(req.user);
511 if (!sub) return res.status(401).json({ error: 'auth_failed' });
512 return app._mcpOAuthProvider.completeMcpAuthorization(state.slice(4), sub, res);
513 }
514 // C1/C3: native client authorization flow (COMPANION-APP-OAUTH-SERVERSIDE-GATE §6).
515 if (state.startsWith('native:') && app._nativeOAuthProvider) {
516 const sub = userId(req.user);
517 if (!sub) return res.status(401).json({ error: 'auth_failed' });
518 return app._nativeOAuthProvider.completeNativeAuthorization(state.slice(7), sub, res);
519 }
520 const token = issueToken(req.user);
521 await issueRefreshCookieSafe(res, req, userId(req.user));
522 res.redirect(postLoginRedirect(token, req));
523 }
524 );
525 app.get(
526 '/auth/callback/github',
527 passport.authenticate('github', { session: false }),
528 async (req, res) => {
529 const state = typeof req.query.state === 'string' ? req.query.state : '';
530 if (state.startsWith('mcp:') && app._mcpOAuthProvider) {
531 const sub = userId(req.user);
532 if (!sub) return res.status(401).json({ error: 'auth_failed' });
533 return app._mcpOAuthProvider.completeMcpAuthorization(state.slice(4), sub, res);
534 }
535 // C1/C3: native client authorization flow (COMPANION-APP-OAUTH-SERVERSIDE-GATE §6).
536 if (state.startsWith('native:') && app._nativeOAuthProvider) {
537 const sub = userId(req.user);
538 if (!sub) return res.status(401).json({ error: 'auth_failed' });
539 return app._nativeOAuthProvider.completeNativeAuthorization(state.slice(7), sub, res);
540 }
541 const token = issueToken(req.user);
542 await issueRefreshCookieSafe(res, req, userId(req.user));
543 res.redirect(postLoginRedirect(token, req));
544 }
545 );
546
547 // Hub UI may call login under /api/v1/auth for consistency — redirect to /auth (preserve invite for post-login consume)
548 app.get('/api/v1/auth/login', (req, res) => {
549 const provider = (req.query.provider || 'google').toLowerCase();
550 let url = `${BASE_URL}/auth/login?provider=${encodeURIComponent(provider)}`;
551 const invite = typeof req.query.invite === 'string' ? req.query.invite.trim() : '';
552 if (invite) url += '&invite=' + encodeURIComponent(invite);
553 res.redirect(url);
554 });
555
556 // Phase D2/D3: MCP gateway + OAuth 2.1.
557 // MCP requires stateful sessions (SSE, session pool) that are incompatible with Netlify's
558 // serverless function model (26s timeout, no shared memory between invocations).
559 // On Netlify, only the OAuth discovery endpoints are mounted (lightweight, stateless).
560 // The full /mcp session endpoint requires a persistent Express server (local dev, Docker, VPS,
561 // or a dedicated MCP host like Railway/Fly.io). See docs/AGENT-INTEGRATION.md §2 (hosted MCP).
562 if (SESSION_SECRET && !process.env.NETLIFY) {
563 import('./mcp-oauth-provider.mjs').then(async ({ KnowtationOAuthProvider }) => {
564 const { mcpAuthRouter } = await import('@modelcontextprotocol/sdk/server/auth/router.js');
565 const oauthProvider = new KnowtationOAuthProvider({
566 sessionSecret: SESSION_SECRET,
567 baseUrl: BASE_URL,
568 });
569 app._mcpOAuthProvider = oauthProvider;
570 // @modelcontextprotocol/sdk OAuth routes use express-rate-limit behind Nginx. The limiter's
571 // default validations (X-Forwarded-For vs Express trust proxy) still throw ERR_ERL_* on some
572 // Express/SDK mount combinations. Disable express-rate-limit validations for these routes only;
573 // limits stay on; edge limits remain in Nginx (gateway deploy notes in hub/gateway/README.md).
574 const mcpOAuthSdkRateLimitOpts = {
575 rateLimit: { validate: false },
576 };
577 app.use(mcpAuthRouter({
578 provider: oauthProvider,
579 issuerUrl: new URL(BASE_URL),
580 scopesSupported: ['vault:read', 'vault:write', 'vault:admin'],
581 authorizationOptions: mcpOAuthSdkRateLimitOpts,
582 tokenOptions: mcpOAuthSdkRateLimitOpts,
583 clientRegistrationOptions: mcpOAuthSdkRateLimitOpts,
584 revocationOptions: mcpOAuthSdkRateLimitOpts,
585 }));
586 console.log('[gateway] MCP OAuth 2.1 endpoints mounted');
587
588 // C1–C6 (COMPANION-APP-OAUTH-SERVERSIDE-GATE §6): native client OAuth 2.1 endpoints.
589 // The native path issues web-session JWTs (issueToken shape) instead of mcp_access
590 // tokens, uses refresh-token-core for durable rotation, enforces loopback-only
591 // redirect URIs, validates redirect_uri at exchange, and applies a scope ceiling.
592 // Mounted only on the persistent gateway host — same guard as the MCP router.
593 try {
594 const { createNativeOAuthRouter } = await import('./native-oauth-provider.mjs');
595 const { router: nativeRouter, completeNativeAuthorization } = createNativeOAuthRouter({
596 baseUrl: BASE_URL,
597 loginUrl: `${BASE_URL}/auth/login`,
598 issueAccessToken: issueAccessTokenForSub,
599 // C6: grantedScopes resolves the scope ceiling via roleForSub; unknown sub → member.
600 grantedScopes: (sub) => scopesForRole(roleForSub(sub)),
601 // C2/C4: reuse the same durable refresh store as the web session so rotation +
602 // reuse-detection use the same family records. Store is file-backed on this host.
603 refreshStore,
604 });
605 // Bind completeNativeAuthorization so IDP callbacks can reach it (see /auth/callback/*).
606 app._nativeOAuthProvider = { completeNativeAuthorization };
607 app.use('/api/v1/auth/native', nativeRouter);
608 console.log('[gateway] Native OAuth 2.1 endpoints mounted at /api/v1/auth/native');
609
610 // C4: opportunistically prune expired native auth codes at startup.
611 const { pruneExpiredCodes } = await import('./native-as-store.mjs');
612 pruneExpiredCodes().catch(() => { /* best effort; never fatal */ });
613 } catch (e) {
614 console.error('[gateway] Native OAuth router failed to load:', e.message || e);
615 }
616 }).catch((e) => {
617 console.error('[gateway] MCP OAuth router failed to load:', e.message || e);
618 });
619 } else if (SESSION_SECRET && process.env.NETLIFY) {
620 console.log('[gateway] MCP OAuth/session endpoints skipped on Netlify (stateful sessions require persistent server)');
621 }
622
623 if (BRIDGE_URL && CANISTER_URL && !process.env.NETLIFY) {
624 import('./mcp-proxy.mjs').then(({ createMcpProxyRouter }) => {
625 const mcpRouter = createMcpProxyRouter({
626 getUserId,
627 getHostedAccessContext,
628 canisterUrl: CANISTER_URL,
629 canisterAuthSecret: CANISTER_AUTH_SECRET,
630 bridgeUrl: BRIDGE_URL,
631 gatewayApiBaseUrl: BASE_URL.replace(/\/$/, ''),
632 sessionSecret: SESSION_SECRET || '',
633 });
634 app.use('/mcp', mcpRouter);
635 console.log('[gateway] MCP endpoint mounted at /mcp');
636 if (!CANISTER_AUTH_SECRET) {
637 console.warn(
638 '[gateway] MCP /mcp: CANISTER_AUTH_SECRET is empty. Direct canister HTTP calls from hosted MCP (list_notes, get_note, write, enrich; summarize note fetches) send no X-Gateway-Auth and the canister returns GATEWAY_AUTH_REQUIRED. Set the same CANISTER_AUTH_SECRET as the Netlify gateway and as configured on the canister (admin_set_gateway_auth_secret), then pm2 restart with --update-env.'
639 );
640 }
641 }).catch((e) => {
642 console.error('[gateway] MCP proxy failed to load:', e.message || e);
643 });
644 } else if (process.env.NETLIFY) {
645 app.all('/mcp', (_req, res) => {
646 res.status(503).json({
647 error: 'MCP endpoint requires a persistent server. Connect to the dedicated MCP host or use self-hosted deployment.',
648 code: 'MCP_NETLIFY_UNSUPPORTED',
649 docs: 'https://github.com/aaronrene/knowtation/blob/main/docs/AGENT-INTEGRATION.md',
650 });
651 });
652 }
653
654 // Connect GitHub + Back up now: proxy to bridge when BRIDGE_URL is set (single origin for UI)
655 if (BRIDGE_URL) {
656 app.get('/api/v1/auth/github-connect', (req, res) => {
657 const q = new URLSearchParams(req.query).toString();
658 res.redirect(`${BRIDGE_URL}/auth/github-connect${q ? '?' + q : ''}`);
659 });
660 // Browsers send OPTIONS preflight before POST with Authorization + JSON body. The bridge only
661 // registers POST /api/v1/vault/sync, so proxying OPTIONS returns 404 and surfaces as "Failed to fetch".
662 app.all('/api/v1/vault/sync', async (req, res) => {
663 if (req.method === 'OPTIONS') {
664 return res.status(204).end();
665 }
666 const url = BRIDGE_URL + '/api/v1/vault/sync' + (req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '');
667 await proxyTo(BRIDGE_URL, url, req, res);
668 });
669 app.all('/api/v1/vaults/:vaultId', async (req, res) => {
670 if (req.method === 'OPTIONS') {
671 return res.status(204).end();
672 }
673 if (req.method !== 'DELETE') {
674 return res.status(405).json({ error: 'Method not allowed', code: 'METHOD_NOT_ALLOWED' });
675 }
676 if (!(await runBillingGate(req, res, getUserId))) return;
677 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
678 const url =
679 BRIDGE_URL + '/api/v1/vaults/' + encodeURIComponent(req.params.vaultId) + q;
680 await proxyTo(BRIDGE_URL, url, req, res);
681 });
682 app.get('/api/v1/vault/github-status', async (req, res) => {
683 const url = BRIDGE_URL + '/api/v1/vault/github-status' + (req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '');
684 await proxyTo(BRIDGE_URL, url, req, res);
685 });
686 app.post('/api/v1/search', async (req, res) => {
687 if (!(await runBillingGate(req, res, getUserId))) return;
688 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/search', req, res);
689 });
690 app.post('/api/v1/index', async (req, res) => {
691 if (!(await runBillingGate(req, res, getUserId))) return;
692 const uid = getUserId(req);
693 const headers = { ...req.headers, host: new URL(BRIDGE_URL).host };
694 delete headers.origin;
695 delete headers.referer;
696 const opts = { method: 'POST', headers };
697 const payload =
698 req.body === undefined ? undefined : typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
699 if (payload !== undefined) {
700 opts.body = payload;
701 stripStaleOutboundBodyHeaders(headers);
702 }
703 try {
704 const upstream = await fetch(BRIDGE_URL + '/api/v1/index', opts);
705 const body = await upstream.text();
706 if (uid) await recordIndexingTokensAfterBridgeIndex(uid, upstream.status, body);
707 const hop = filterUpstreamResponseHeadersForDecodedBody(upstream.headers.entries());
708 res.status(upstream.status).set(Object.fromEntries(hop));
709 res.send(body);
710 } catch (e) {
711 console.error('Gateway proxy (bridge) error:', e.message);
712 res.status(502).json({ error: 'Bad Gateway', code: 'BAD_GATEWAY' });
713 }
714 });
715 // GET /api/v1/index/status — read-only sidecar describing the last successful
716 // index + whether a background job is currently in flight. Added in May 2026
717 // alongside the auto-routing index path (PR #205) so the Hub UI can render
718 // `Last indexed: N minutes ago` next to the Re-index button.
719 //
720 // Auth scoping happens at the bridge (`requireBridgeAuth` + vault-scoping).
721 // We deliberately DO NOT run `runBillingGate` here — this is a passive read,
722 // not a billable index operation, and the Hub UI calls this on every page
723 // load (so charging would be both incorrect and abusive).
724 //
725 // See `test/gateway-index-status-proxy.test.mjs` for the contract test that
726 // prevents this handler from being silently removed.
727 app.get('/api/v1/index/status', async (req, res) => {
728 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/index/status', req, res);
729 });
730 // Roles & invites: proxy to bridge (bridge has persistent storage)
731 app.get('/api/v1/roles', requireAdmin, async (req, res) => {
732 await proxyTo(BRIDGE_URL, BRIDGE_URL + req.originalUrl, req, res);
733 });
734 app.post('/api/v1/roles', requireAdmin, async (req, res) => {
735 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/roles', req, res);
736 });
737 app.post('/api/v1/roles/evaluator-may-approve', requireAdmin, async (req, res) => {
738 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/roles/evaluator-may-approve', req, res);
739 });
740 app.get('/api/v1/invites', requireAdmin, async (req, res) => {
741 await proxyTo(BRIDGE_URL, BRIDGE_URL + req.originalUrl, req, res);
742 });
743 app.post('/api/v1/invites', requireAdmin, async (req, res) => {
744 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/invites', req, res);
745 });
746 app.delete('/api/v1/invites/:token', requireAdmin, async (req, res) => {
747 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/invites/' + encodeURIComponent(req.params.token), req, res);
748 });
749 app.post('/api/v1/invites/consume', (req, res, next) => {
750 const uid = getUserId(req);
751 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
752 next();
753 }, async (req, res) => {
754 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/invites/consume', req, res);
755 });
756 app.get('/api/v1/workspace', requireAdmin, async (req, res) => {
757 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/workspace', req, res);
758 });
759 app.post('/api/v1/workspace', requireAdmin, async (req, res) => {
760 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/workspace', req, res);
761 });
762 app.get('/api/v1/vault-access', requireAdmin, async (req, res) => {
763 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/vault-access', req, res);
764 });
765 app.post('/api/v1/vault-access', requireAdmin, async (req, res) => {
766 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/vault-access', req, res);
767 });
768 app.get('/api/v1/scope', requireAdmin, async (req, res) => {
769 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/scope', req, res);
770 });
771 app.post('/api/v1/scope', requireAdmin, async (req, res) => {
772 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/scope', req, res);
773 });
774 app.get('/api/v1/hosted-context', async (req, res, next) => {
775 const uid = getUserId(req);
776 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
777 next();
778 }, async (req, res) => {
779 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/hosted-context', req, res);
780 });
781
782 // Memory routes: proxy to bridge (per-user/vault isolation handled by bridge)
783 app.get('/api/v1/memory/:key', async (req, res) => {
784 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
785 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/memory/' + encodeURIComponent(req.params.key) + q, req, res);
786 });
787 app.post('/api/v1/memory/store', async (req, res) => {
788 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/memory/store', req, res);
789 });
790 app.get('/api/v1/memory', async (req, res) => {
791 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
792 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/memory' + q, req, res);
793 });
794 app.post('/api/v1/memory/search', async (req, res) => {
795 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/memory/search', req, res);
796 });
797 app.delete('/api/v1/memory/clear', async (req, res) => {
798 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/memory/clear', req, res);
799 });
800 app.get('/api/v1/memory-stats', async (req, res) => {
801 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/memory-stats', req, res);
802 });
803 // Consolidation routes: proxy to bridge with billing gate on POST
804 app.post('/api/v1/memory/consolidate', async (req, res) => {
805 if (!(await runBillingGate(req, res, getUserId))) return;
806 const uid = getUserId(req);
807 try {
808 const db = await loadBillingDb();
809 const raw = db.users?.[uid] || defaultUserRecord(uid);
810 const u = normalizeBillingUser(raw);
811 req.body = mergeConsolidateRequestBodyWithBillingDefaults(
812 req.body && typeof req.body === 'object' ? req.body : {},
813 u,
814 );
815 } catch (_) {
816 /* fail open: bridge merges with billing file / defaults */
817 }
818 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/memory/consolidate', req, res);
819 });
820 app.get('/api/v1/memory/consolidate/status', async (req, res) => {
821 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/memory/consolidate/status', req, res);
822 });
823
824 // Calendar routes (hosted parity — step 12): proxy read + toggle PATCH to bridge event store.
825 app.get('/api/v1/calendar/timeline', async (req, res) => {
826 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
827 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/calendar/timeline' + q, req, res);
828 });
829 app.get('/api/v1/calendar/agent-context', async (req, res) => {
830 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
831 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/calendar/agent-context' + q, req, res);
832 });
833 app.get('/api/v1/calendar/source-calendars', async (req, res) => {
834 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
835 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/calendar/source-calendars' + q, req, res);
836 });
837 app.patch('/api/v1/calendar/source-calendars/:id', async (req, res) => {
838 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
839 await proxyTo(
840 BRIDGE_URL,
841 BRIDGE_URL + '/api/v1/calendar/source-calendars/' + encodeURIComponent(req.params.id) + q,
842 req,
843 res,
844 );
845 });
846 app.post('/api/v1/calendar/events/import', async (req, res) => {
847 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
848 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/calendar/events/import' + q, req, res);
849 });
850
851 // Flow routes (hosted parity — 7A-L2b): proxy read projections (+ grants when gate on).
852 const isFlowHostedProjectionEnabled = () => {
853 const v = process.env.FLOW_HOSTED_PROJECTION_ENABLED;
854 return v === '1' || v === 'true';
855 };
856 app.get('/api/v1/flows/:id/projection', async (req, res) => {
857 const harness = typeof req.query.harness === 'string' ? req.query.harness.trim() : '';
858 if (harness === 'agent_bundle' && !isFlowHostedProjectionEnabled()) {
859 return res.status(403).json({
860 error: 'Hosted agent_bundle projection disabled',
861 code: 'FLOW_HOSTED_PROJECTION_DISABLED',
862 });
863 }
864 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
865 await proxyTo(
866 BRIDGE_URL,
867 BRIDGE_URL + '/api/v1/flows/' + encodeURIComponent(req.params.id) + '/projection' + q,
868 req,
869 res,
870 );
871 });
872 app.get('/api/v1/flows/external-grants', async (req, res) => {
873 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
874 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/flows/external-grants' + q, req, res);
875 });
876 app.post('/api/v1/flows/:id/external-grants', async (req, res) => {
877 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
878 await proxyTo(
879 BRIDGE_URL,
880 BRIDGE_URL + '/api/v1/flows/' + encodeURIComponent(req.params.id) + '/external-grants' + q,
881 req,
882 res,
883 );
884 });
885 app.delete('/api/v1/flows/external-grants/:grant_id', async (req, res) => {
886 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
887 await proxyTo(
888 BRIDGE_URL,
889 BRIDGE_URL + '/api/v1/flows/external-grants/' + encodeURIComponent(req.params.grant_id) + q,
890 req,
891 res,
892 );
893 });
894
895 // Agent delegation (hosted parity — 7C-L1): proxy to bridge when DELEGATION_ENABLED on bridge.
896 app.post('/api/v1/agents/identities', async (req, res) => {
897 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
898 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/agents/identities' + q, req, res);
899 });
900 app.get('/api/v1/agents/identities', async (req, res) => {
901 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
902 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/agents/identities' + q, req, res);
903 });
904 app.post('/api/v1/delegation/consents', async (req, res) => {
905 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
906 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/delegation/consents' + q, req, res);
907 });
908 app.post('/api/v1/delegation/proposals/:proposal_id/apply-approved', async (req, res) => {
909 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
910 await proxyTo(
911 BRIDGE_URL,
912 BRIDGE_URL +
913 '/api/v1/delegation/proposals/' +
914 encodeURIComponent(req.params.proposal_id) +
915 '/apply-approved' +
916 q,
917 req,
918 res,
919 );
920 });
921 app.delete('/api/v1/delegation/consents/:consent_id', async (req, res) => {
922 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
923 await proxyTo(
924 BRIDGE_URL,
925 BRIDGE_URL + '/api/v1/delegation/consents/' + encodeURIComponent(req.params.consent_id) + q,
926 req,
927 res,
928 );
929 });
930 app.post('/api/v1/delegation/grants', async (req, res) => {
931 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
932 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/delegation/grants' + q, req, res);
933 });
934 app.get('/api/v1/delegation/grants', async (req, res) => {
935 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
936 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/delegation/grants' + q, req, res);
937 });
938 app.delete('/api/v1/delegation/grants/:grant_id', async (req, res) => {
939 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
940 await proxyTo(
941 BRIDGE_URL,
942 BRIDGE_URL + '/api/v1/delegation/grants/' + encodeURIComponent(req.params.grant_id) + q,
943 req,
944 res,
945 );
946 });
947 app.post('/api/v1/delegation/audit', async (req, res) => {
948 const q = req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : '';
949 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/delegation/audit' + q, req, res);
950 });
951
952 // Phase 18: image upload — gateway buffers the file, fetches GitHub token from bridge,
953 // then commits directly to GitHub (avoids forwarding a multipart body to another Lambda).
954 app.post(/^\/api\/v1\/notes\/(.+)\/upload-image$/, async (req, res) => {
955 const uid = getUserId(req);
956 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
957
958 // 1. Get GitHub connection (token + repo) from bridge.
959 let ghToken, ghRepo;
960 try {
961 const tokenRes = await fetch(`${BRIDGE_URL}/api/v1/vault/github-token`, {
962 headers: { authorization: req.headers.authorization || '' },
963 });
964 if (!tokenRes.ok) {
965 const errData = await tokenRes.json().catch(() => ({}));
966 return res.status(tokenRes.status).json({
967 error: errData.error || 'GitHub not connected',
968 code: errData.code || 'GITHUB_NOT_CONNECTED',
969 });
970 }
971 const data = await tokenRes.json();
972 ghToken = data.token;
973 ghRepo = data.repo;
974 } catch (e) {
975 return res.status(502).json({ error: 'Could not reach bridge', code: 'BAD_GATEWAY' });
976 }
977 if (!ghToken) return res.status(400).json({ error: 'GitHub not connected', code: 'GITHUB_NOT_CONNECTED' });
978 if (!ghRepo) return res.status(400).json({ error: 'GitHub repo not set. Back up once first to set the remote.', code: 'GITHUB_NOT_CONFIGURED' });
979
980 // 2. Buffer the uploaded file from the multipart body.
981 let fileBuffer, originalName, mimeType;
982 try {
983 const raw = await bufferImportRequestBody(req);
984 const ct = req.headers['content-type'] || '';
985 const boundaryMatch = ct.match(/boundary=([^\s;]+)/i);
986 if (!boundaryMatch) return res.status(400).json({ error: 'Content-Type boundary missing', code: 'BAD_REQUEST' });
987 const boundary = boundaryMatch[1];
988 // Parse the first file part from the multipart body manually (avoids multer dependency).
989 const parsed = parseMultipartFile(raw, boundary);
990 if (!parsed) return res.status(400).json({ error: 'image file required', code: 'BAD_REQUEST' });
991 fileBuffer = parsed.data;
992 originalName = parsed.filename || 'image.jpg';
993 mimeType = parsed.contentType || 'application/octet-stream';
994 } catch (e) {
995 return res.status(500).json({ error: 'Could not read upload body', code: 'INTERNAL_ERROR' });
996 }
997
998 // 3. Validate extension, content-type, and magic bytes.
999 try { validateImageExtension(originalName); } catch (e) {
1000 return res.status(400).json({ error: e.message, code: 'BAD_REQUEST' });
1001 }
1002 if (!mimeType.toLowerCase().startsWith('image/')) {
1003 return res.status(400).json({ error: 'File content-type must be image/*', code: 'BAD_REQUEST' });
1004 }
1005 const ext = originalName.split('.').pop().toLowerCase();
1006 const magicOk = validateMagicBytes(fileBuffer, ext);
1007 if (!magicOk) {
1008 return res.status(400).json({ error: 'File content does not match declared image type', code: 'BAD_REQUEST' });
1009 }
1010
1011 // 4. Commit to GitHub directly from the gateway.
1012 try {
1013 const now = new Date();
1014 const yearMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
1015 const safeName = originalName.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 128);
1016 const uniqueName = `${Date.now()}-${safeName}`;
1017 const repoFilePath = `media/images/${yearMonth}/${uniqueName}`;
1018 const result = await commitImageToRepo({
1019 accessToken: ghToken,
1020 repoUrl: ghRepo,
1021 filePath: repoFilePath,
1022 fileBuffer,
1023 commitMessage: `Add image: ${safeName}`,
1024 });
1025 return res.json({
1026 url: result.url,
1027 inserted_markdown: `![${safeName}](${result.url})`,
1028 sha: result.sha,
1029 repo_path: repoFilePath,
1030 repo_private: result.isPrivate === true,
1031 });
1032 } catch (e) {
1033 const msg = e.message || String(e);
1034 const clientErr = /not found|not connected|lacks permission|lacks repo|Reconnect|scope|remote/i.test(msg);
1035 return res.status(clientErr ? 400 : 500).json({ error: msg, code: clientErr ? 'BAD_REQUEST' : 'RUNTIME_ERROR' });
1036 }
1037 });
1038
1039 app.get('/api/v1/vault/image-proxy-token', (req, res) => {
1040 const uid = getUserId(req);
1041 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1042 if (!SESSION_SECRET) return res.status(503).json({ error: 'Not configured', code: 'NOT_CONFIGURED' });
1043 const token = signImageProxyToken(SESSION_SECRET, uid);
1044 res.json({ token, expires_in: IMAGE_PROXY_TOKEN_TTL_SECONDS });
1045 });
1046
1047 app.get('/api/v1/vault/image-proxy', async (req, res) => {
1048 const auth = req.headers.authorization || '';
1049 const headerToken = auth.startsWith('Bearer ') ? auth.slice(7) : null;
1050 const queryToken = typeof req.query.token === 'string' ? req.query.token : null;
1051 let uid = headerToken ? getUserId({ headers: { authorization: `Bearer ${headerToken}` } }) : null;
1052 let jwtTokenForBridge = headerToken || '';
1053 if (!uid && queryToken && SESSION_SECRET) {
1054 uid = verifyImageProxyToken(SESSION_SECRET, queryToken);
1055 }
1056 // Backward compat: old hub.js sends full JWT as ?token= (pre-signed-token change).
1057 if (!uid && queryToken) {
1058 const fromJwt = getUserId({ headers: { authorization: `Bearer ${queryToken}` } });
1059 if (fromJwt) { uid = fromJwt; jwtTokenForBridge = queryToken; }
1060 }
1061 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1062
1063 // When uid is known but no JWT to forward (HMAC token auth path), mint a
1064 // short-lived gateway JWT so the bridge can identify the user.
1065 if (!jwtTokenForBridge && SESSION_SECRET) {
1066 try { jwtTokenForBridge = jwt.sign({ sub: uid }, SESSION_SECRET, { expiresIn: '5m' }); } catch (_) {}
1067 }
1068
1069 const rawUrl = typeof req.query.url === 'string' ? req.query.url : '';
1070 if (!rawUrl) return res.status(400).json({ error: 'url parameter required', code: 'BAD_REQUEST' });
1071
1072 // Only proxy raw.githubusercontent.com URLs to prevent SSRF.
1073 const rawMatch = rawUrl.match(
1074 /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)\/(.+)$/i,
1075 );
1076 if (!rawMatch) {
1077 return res.status(400).json({ error: 'Only raw.githubusercontent.com URLs are supported', code: 'BAD_REQUEST' });
1078 }
1079 const [, owner, repo, ref, filePath] = rawMatch;
1080
1081 let ghToken = null;
1082 if (jwtTokenForBridge) {
1083 try {
1084 const tokenRes = await fetch(`${BRIDGE_URL}/api/v1/vault/github-token`, {
1085 headers: { authorization: `Bearer ${jwtTokenForBridge}` },
1086 });
1087 if (tokenRes.ok) {
1088 const data = await tokenRes.json();
1089 ghToken = data.token || null;
1090 }
1091 } catch (_) { /* bridge unreachable — fall through, public repos still work */ }
1092 }
1093
1094 if (!ghToken) {
1095 // No stored GitHub token — assume the repo is public and redirect directly.
1096 return res.redirect(302, rawUrl);
1097 }
1098
1099 // Use the GitHub Contents API to get a signed, short-lived download_url for the file.
1100 // This avoids sending the PAT in the redirect URL while still letting private-repo images load.
1101 const apiUrl =
1102 `https://api.github.com/repos/${owner}/${repo}/contents/${filePath}` +
1103 `?ref=${encodeURIComponent(ref)}`;
1104 try {
1105 const apiRes = await fetch(apiUrl, {
1106 headers: {
1107 Authorization: `token ${ghToken}`,
1108 Accept: 'application/vnd.github.v3+json',
1109 'User-Agent': 'Knowtation-Hub/1.0',
1110 },
1111 });
1112 if (apiRes.ok) {
1113 const data = await apiRes.json();
1114 const dlUrl = data.download_url || rawUrl;
1115 res.setHeader('Cache-Control', 'private, max-age=300');
1116 return res.redirect(302, dlUrl);
1117 }
1118 // GitHub returned an error (e.g. 404 file missing, 403 large-file).
1119 const errBody = await apiRes.json().catch(() => ({}));
1120 return res.status(apiRes.status).json({
1121 error: errBody.message || 'Image not found on GitHub',
1122 code: 'UPSTREAM_ERROR',
1123 });
1124 } catch (e) {
1125 return res.status(502).json({ error: 'Failed to fetch image metadata from GitHub', code: 'BAD_GATEWAY' });
1126 }
1127 });
1128 }
1129
1130 /**
1131 * Safe client request headers that may be forwarded to upstream services.
1132 * Using an explicit allowlist prevents host-header injection, internal proxy header leakage,
1133 * and forwarding of security-sensitive headers (cookies, x-forwarded-for, etc.) to upstreams.
1134 */
1135 const PROXY_HEADER_ALLOWLIST = new Set([
1136 'content-type',
1137 'accept',
1138 'accept-language',
1139 'accept-encoding',
1140 ]);
1141
1142 /**
1143 * Incoming headers describe the *client* body. We often re-serialize JSON (provenance merge), so
1144 * length and transfer-related headers must not be forwarded: Undici can hang or mis-send if
1145 * Content-Length still matches the old, shorter body.
1146 */
1147 function stripStaleOutboundBodyHeaders(headers) {
1148 for (const k of Object.keys(headers)) {
1149 const l = k.toLowerCase();
1150 if (
1151 l === 'content-length' ||
1152 l === 'transfer-encoding' ||
1153 l === 'content-encoding'
1154 ) {
1155 delete headers[k];
1156 }
1157 }
1158 }
1159
1160 async function proxyTo(baseUrl, url, req, res) {
1161 const headers = { host: new URL(baseUrl).host };
1162 // Allowlist: only forward safe headers; also forward authorization for bridge JWT auth
1163 // and x-vault-id for vault routing. Never forward origin, referer, cookies, or proxy headers.
1164 for (const k of PROXY_HEADER_ALLOWLIST) {
1165 if (req.headers[k] !== undefined) headers[k] = req.headers[k];
1166 }
1167 if (req.headers.authorization) headers.authorization = req.headers.authorization;
1168 if (req.headers['x-vault-id']) headers['x-vault-id'] = req.headers['x-vault-id'];
1169 const opts = { method: req.method, headers };
1170 if (req.method !== 'GET' && req.method !== 'HEAD' && req.body !== undefined) {
1171 opts.body = typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
1172 stripStaleOutboundBodyHeaders(headers);
1173 }
1174 try {
1175 const upstream = await fetch(url, opts);
1176 const body = await upstream.text();
1177 const hop = filterUpstreamResponseHeadersForDecodedBody(upstream.headers.entries());
1178 res.status(upstream.status).set(Object.fromEntries(hop));
1179 res.send(body);
1180 } catch (e) {
1181 console.error('Gateway proxy (bridge) error:', e.message);
1182 res.status(502).json({ error: 'Bad Gateway', code: 'BAD_GATEWAY' });
1183 }
1184 }
1185
1186 /**
1187 * Read multipart/raw POST body for import proxy.
1188 * Netlify (serverless-http) attaches the Lambda body as Buffer on `req.body` and uses a synthetic stream;
1189 * `fetch(req, { duplex })` is unreliable there — always buffer then POST bytes.
1190 * @param {import('express').Request} req
1191 * @returns {Promise<Buffer>}
1192 */
1193 async function bufferImportRequestBody(req) {
1194 if (Buffer.isBuffer(req.body)) return req.body;
1195 if (req.body instanceof Uint8Array) return Buffer.from(req.body);
1196 if (typeof req.body === 'string') return Buffer.from(req.body, 'latin1');
1197 const chunks = [];
1198 for await (const chunk of req) {
1199 chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1200 }
1201 return Buffer.concat(chunks);
1202 }
1203
1204
1205 /**
1206 * Multipart import: forward body bytes to bridge (do not use proxyTo — body is not JSON in req.body).
1207 * @param {string} _baseUrl - bridge origin (reserved for diagnostics; fetch URL is `url`)
1208 * @param {string} url - full URL to bridge /api/v1/import
1209 * @param {import('express').Request} req
1210 * @param {import('express').Response} res
1211 */
1212 async function proxyImportToBridge(_baseUrl, url, req, res) {
1213 let raw;
1214 try {
1215 raw = await bufferImportRequestBody(req);
1216 } catch (e) {
1217 console.error('Gateway import proxy (read body):', e.message || e);
1218 return res.status(500).json({ error: 'Could not read upload body', code: 'INTERNAL_ERROR' });
1219 }
1220 if (!raw.length) {
1221 return res.status(400).json({ error: 'Empty upload body', code: 'BAD_REQUEST' });
1222 }
1223 // Do not set `Host` manually — undici derives it from the request URL; a wrong Host breaks some upstreams.
1224 const headers = {
1225 authorization: req.headers.authorization || '',
1226 'x-vault-id': String(req.headers['x-vault-id'] || 'default'),
1227 };
1228 const ct = req.headers['content-type'];
1229 if (ct) headers['content-type'] = ct;
1230 headers['content-length'] = String(raw.length);
1231 let upstream;
1232 try {
1233 upstream = await fetch(url, {
1234 method: 'POST',
1235 headers,
1236 body: raw,
1237 });
1238 } catch (e) {
1239 console.error('Gateway import proxy error:', e.message, e.cause);
1240 const detail = e.cause?.message || e.message || String(e);
1241 return res.status(502).json({
1242 error: 'Bad Gateway',
1243 code: 'BAD_GATEWAY',
1244 detail,
1245 });
1246 }
1247 const body = await upstream.text();
1248 const upstreamCt = upstream.headers.get('content-type') || '';
1249 if (
1250 upstream.status >= 400 &&
1251 !/application\/json/i.test(upstreamCt) &&
1252 body.trimStart().startsWith('<')
1253 ) {
1254 return res.status(upstream.status).json({
1255 error: 'Import service returned a non-JSON error (check bridge Netlify function logs).',
1256 code: 'BAD_GATEWAY',
1257 detail: `HTTP ${upstream.status}`,
1258 });
1259 }
1260 const hop = filterUpstreamResponseHeadersForDecodedBody(upstream.headers.entries());
1261 res.status(upstream.status).set(Object.fromEntries(hop));
1262 res.send(body);
1263 }
1264
1265 // Proxy /api/* to canister with X-User-Id from JWT
1266 function getUserId(req) {
1267 const auth = req.headers.authorization;
1268 const token = auth && auth.startsWith('Bearer ') ? auth.slice(7) : null;
1269 return token ? verifyToken(token) : null;
1270 }
1271
1272 /**
1273 * Validate a hosted SectionSource note path before any upstream fetch.
1274 * @param {unknown} rawPath
1275 * @returns {string}
1276 */
1277 function normalizeGatewaySectionSourcePath(rawPath) {
1278 if (typeof rawPath !== 'string' || rawPath.trim() === '') {
1279 throw new Error('Invalid path');
1280 }
1281 const forward = rawPath.trim().replace(/\\/g, '/');
1282 if (forward.startsWith('/') || /^[A-Za-z]:\//.test(forward)) {
1283 throw new Error('Invalid path');
1284 }
1285 const parts = forward.split('/').filter(Boolean);
1286 if (parts.includes('..')) {
1287 throw new Error('Invalid path');
1288 }
1289 return parts.join('/');
1290 }
1291
1292 /**
1293 * Validate a hosted NoteOutline note path before any upstream fetch.
1294 * @param {unknown} rawPath
1295 * @returns {string}
1296 */
1297 function normalizeGatewayNoteOutlinePath(rawPath) {
1298 return normalizeGatewaySectionSourcePath(rawPath);
1299 }
1300
1301 /**
1302 * Validate a hosted DocumentTree note path before any upstream fetch.
1303 * @param {unknown} rawPath
1304 * @returns {string}
1305 */
1306 function normalizeGatewayDocumentTreePath(rawPath) {
1307 return normalizeGatewaySectionSourcePath(rawPath);
1308 }
1309
1310 /**
1311 * Validate a hosted MetadataFacets note path before any upstream fetch.
1312 * @param {unknown} rawPath
1313 * @returns {string}
1314 */
1315 function normalizeGatewayMetadataFacetsPath(rawPath) {
1316 return normalizeGatewaySectionSourcePath(rawPath);
1317 }
1318
1319 /**
1320 * @param {unknown} error
1321 */
1322 function sanitizedSectionSourceGatewayError(error) {
1323 const msg = error?.message || String(error ?? '');
1324 if (/^Invalid path\b/.test(msg)) return { status: 400, error: 'Invalid path', code: 'INVALID_PATH' };
1325 return { status: 502, error: 'Bad Gateway', code: 'BAD_GATEWAY' };
1326 }
1327
1328 /**
1329 * @param {unknown} error
1330 */
1331 function sanitizedNoteOutlineGatewayError(error) {
1332 return sanitizedSectionSourceGatewayError(error);
1333 }
1334
1335 /**
1336 * @param {unknown} error
1337 */
1338 function sanitizedDocumentTreeGatewayError(error) {
1339 return sanitizedSectionSourceGatewayError(error);
1340 }
1341
1342 /**
1343 * @param {unknown} error
1344 */
1345 function sanitizedMetadataFacetsGatewayError(error) {
1346 return sanitizedSectionSourceGatewayError(error);
1347 }
1348
1349 const hostedCtxCache = new Map();
1350 const HOSTED_CTX_TTL_MS = 60_000;
1351 const HOSTED_CONTEXT_FETCH_TIMEOUT_MS = (() => {
1352 const n = parseInt(String(process.env.HOSTED_CONTEXT_FETCH_TIMEOUT_MS || ''), 10);
1353 if (!Number.isFinite(n)) return 3000;
1354 return Math.min(10_000, Math.max(250, n));
1355 })();
1356
1357 function hostedContextAbortSignal() {
1358 return typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
1359 ? AbortSignal.timeout(HOSTED_CONTEXT_FETCH_TIMEOUT_MS)
1360 : undefined;
1361 }
1362
1363 /**
1364 * Bridge-hosted team context (vault allowlist + scope + effective canister user). Cached briefly per (sub, vaultId).
1365 * @param {import('express').Request} req
1366 * @returns {Promise<Record<string, unknown>|null>}
1367 */
1368 async function getHostedAccessContext(req) {
1369 if (!BRIDGE_URL) return null;
1370 const auth = req.headers.authorization;
1371 if (!auth || !auth.startsWith('Bearer ')) return null;
1372 const sub = getUserId(req);
1373 if (!sub) return null;
1374 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
1375 const cacheKey = `${sub}\0${vaultId}`;
1376 const now = Date.now();
1377 const hit = hostedCtxCache.get(cacheKey);
1378 if (hit && hit.expires > now) return hit.data;
1379 try {
1380 const signal = hostedContextAbortSignal();
1381 const r = await fetch(BRIDGE_URL + '/api/v1/hosted-context', {
1382 method: 'GET',
1383 headers: {
1384 Authorization: auth,
1385 Accept: 'application/json',
1386 'X-Vault-Id': vaultId,
1387 },
1388 ...(signal ? { signal } : {}),
1389 });
1390 if (!r.ok) return null;
1391 const data = await r.json();
1392 if (data && data.error && !data.effective_canister_user_id) return null;
1393 hostedCtxCache.set(cacheKey, { expires: now + HOSTED_CTX_TTL_MS, data });
1394 return data;
1395 } catch (_) {
1396 return null;
1397 }
1398 }
1399
1400 /**
1401 * Hosted team context for an explicit vault (e.g. cross-vault copy source/target checks).
1402 * @param {string} authorization Bearer JWT
1403 * @param {string} vaultId
1404 * @returns {Promise<Record<string, unknown>|null>}
1405 */
1406 async function fetchHostedAccessContextForVault(authorization, vaultId) {
1407 if (!BRIDGE_URL || !authorization || !authorization.startsWith('Bearer ')) return null;
1408 const token = authorization.slice(7);
1409 const sub = verifyToken(token);
1410 if (!sub) return null;
1411 const vid = String(vaultId || 'default').trim() || 'default';
1412 const cacheKey = `${sub}\0${vid}`;
1413 const now = Date.now();
1414 const hit = hostedCtxCache.get(cacheKey);
1415 if (hit && hit.expires > now) return hit.data;
1416 try {
1417 const signal = hostedContextAbortSignal();
1418 const r = await fetch(BRIDGE_URL + '/api/v1/hosted-context', {
1419 method: 'GET',
1420 headers: {
1421 Authorization: authorization,
1422 Accept: 'application/json',
1423 'X-Vault-Id': vid,
1424 },
1425 ...(signal ? { signal } : {}),
1426 });
1427 if (!r.ok) return null;
1428 const data = await r.json();
1429 if (data && data.error && !data.effective_canister_user_id) return null;
1430 hostedCtxCache.set(cacheKey, { expires: now + HOSTED_CTX_TTL_MS, data });
1431 return data;
1432 } catch (_) {
1433 return null;
1434 }
1435 }
1436
1437 const metadataBulkHandlers = createMetadataBulkHandlers({
1438 CANISTER_URL,
1439 CANISTER_AUTH_SECRET,
1440 BRIDGE_URL,
1441 SESSION_SECRET: SESSION_SECRET || '',
1442 getUserId,
1443 getHostedAccessContext,
1444 });
1445
1446 app.get('/api/v1/billing/summary', (req, res) => handleBillingSummary(req, res, getUserId));
1447
1448 /**
1449 * POST /api/v1/admin/billing/repair
1450 *
1451 * Admin-only endpoint to directly write billing tier and Stripe linkage fields for a user.
1452 * Used to recover from missed or unprocessable Stripe webhook deliveries (e.g. webhook pointed
1453 * at old URL, checkout session never had user_id metadata, billing DB was empty on a new deploy).
1454 *
1455 * Auth: Bearer JWT with admin role (sub must be in HUB_ADMIN_USER_IDS env var).
1456 * Body: { uid?, tier, stripe_subscription_id?, stripe_customer_id?, has_active_subscription? }
1457 * - uid: target Knowtation user ID (defaults to the calling admin's own uid)
1458 * - tier: required — one of: free | beta | plus | growth | pro | starter | team
1459 * - stripe_subscription_id: if provided (non-null), also sets has_active_subscription = true
1460 * - has_active_subscription: optional boolean override; when omitted, defaults to true
1461 * whenever a non-null stripe_subscription_id is supplied, and no-op otherwise
1462 * - stripe_customer_id: if provided, links the user to their Stripe customer so future
1463 * webhook events (subscription.updated, etc.) can find them
1464 *
1465 * All mutations are logged. This endpoint does NOT create a Stripe subscription — it only
1466 * repairs the local billing DB record.
1467 */
1468 const VALID_REPAIR_TIERS = new Set(['free', 'beta', 'plus', 'growth', 'pro', 'starter', 'team']);
1469
1470 app.post('/api/v1/admin/billing/repair', async (req, res) => {
1471 const callerUid = getUserId(req);
1472 if (!callerUid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1473 if (roleForSub(callerUid) !== 'admin') return res.status(403).json({ error: 'Forbidden', code: 'FORBIDDEN' });
1474
1475 const body = req.body && typeof req.body === 'object' ? req.body : {};
1476 const targetUid = typeof body.uid === 'string' && body.uid.trim() ? body.uid.trim() : callerUid;
1477 const tier = typeof body.tier === 'string' ? body.tier.trim() : '';
1478
1479 if (!VALID_REPAIR_TIERS.has(tier)) {
1480 return res.status(400).json({
1481 error: 'Invalid or missing tier',
1482 code: 'BAD_REQUEST',
1483 valid_tiers: [...VALID_REPAIR_TIERS],
1484 });
1485 }
1486
1487 const stripeSubId =
1488 typeof body.stripe_subscription_id === 'string' ? body.stripe_subscription_id.trim() || null : undefined;
1489 const stripeCustomerId =
1490 typeof body.stripe_customer_id === 'string' ? body.stripe_customer_id.trim() || null : undefined;
1491 // Explicit override: caller may pass has_active_subscription=false to deactivate.
1492 // When stripe_subscription_id is provided: truthy value → true, null (cleared) → false.
1493 // When stripe_subscription_id is omitted entirely: no-op (undefined).
1494 const hasActiveSub =
1495 typeof body.has_active_subscription === 'boolean'
1496 ? body.has_active_subscription
1497 : stripeSubId !== undefined
1498 ? (stripeSubId !== null)
1499 : undefined;
1500
1501 let before;
1502 try {
1503 await mutateBillingDb((db) => {
1504 if (!db.users[targetUid]) db.users[targetUid] = defaultUserRecord(targetUid);
1505 const u = db.users[targetUid];
1506 before = {
1507 tier: u.tier,
1508 has_active_subscription: u.has_active_subscription,
1509 stripe_subscription_id: u.stripe_subscription_id,
1510 stripe_customer_id: u.stripe_customer_id,
1511 };
1512 u.tier = tier;
1513 if (MONTHLY_INCLUDED_CENTS_BY_TIER[tier] !== undefined) {
1514 u.monthly_included_cents = MONTHLY_INCLUDED_CENTS_BY_TIER[tier];
1515 }
1516 if (stripeSubId !== undefined) u.stripe_subscription_id = stripeSubId;
1517 if (stripeCustomerId !== undefined) u.stripe_customer_id = stripeCustomerId;
1518 if (hasActiveSub !== undefined) u.has_active_subscription = hasActiveSub;
1519 });
1520 } catch (e) {
1521 console.error('[admin/billing/repair] mutateBillingDb failed:', e?.message);
1522 return res.status(500).json({ error: 'Internal Server Error', code: 'INTERNAL' });
1523 }
1524
1525 console.log(
1526 `[admin/billing/repair] caller=${callerUid} target=${targetUid}` +
1527 ` tier: ${before?.tier} → ${tier}` +
1528 (hasActiveSub !== undefined ? ` has_active_subscription: ${before?.has_active_subscription} → ${hasActiveSub}` : '') +
1529 (stripeSubId !== undefined ? ` sub: ${before?.stripe_subscription_id} → ${stripeSubId}` : '') +
1530 (stripeCustomerId !== undefined ? ` cus: ${before?.stripe_customer_id} → ${stripeCustomerId}` : ''),
1531 );
1532
1533 return res.json({
1534 ok: true,
1535 uid: targetUid,
1536 tier,
1537 has_active_subscription: hasActiveSub !== undefined ? hasActiveSub : '(unchanged)',
1538 stripe_subscription_id: stripeSubId !== undefined ? stripeSubId : '(unchanged)',
1539 stripe_customer_id: stripeCustomerId !== undefined ? stripeCustomerId : '(unchanged)',
1540 before,
1541 });
1542 });
1543
1544 /**
1545 * POST /api/v1/billing/checkout
1546 * Body: { price_id, success_url, cancel_url } OR { tier, success_url, cancel_url }
1547 * Returns: { url } — Stripe Checkout Session URL.
1548 * mode is automatically determined: subscription for tiers, payment for token packs.
1549 */
1550 app.post('/api/v1/billing/checkout', async (req, res) => {
1551 const uid = getUserId(req);
1552 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1553
1554 const body = req.body && typeof req.body === 'object' ? req.body : {};
1555 let priceId = typeof body.price_id === 'string' ? body.price_id.trim() : null;
1556
1557 if (!priceId && typeof body.tier === 'string') {
1558 priceId = priceIdFromTierShorthand(body.tier.trim());
1559 if (!priceId) {
1560 return res.status(400).json({
1561 error: `Unknown tier '${body.tier}' or Stripe price env var not configured.`,
1562 code: 'BAD_REQUEST',
1563 });
1564 }
1565 }
1566
1567 if (!priceId && typeof body.pack_size === 'string') {
1568 const packSizeMap = {
1569 small: process.env.STRIPE_PRICE_PACK_10 || null,
1570 medium: process.env.STRIPE_PRICE_PACK_25 || null,
1571 large: process.env.STRIPE_PRICE_PACK_50 || null,
1572 };
1573 priceId = packSizeMap[body.pack_size.toLowerCase()] || null;
1574 if (!priceId) {
1575 return res.status(400).json({
1576 error: `Unknown pack_size '${body.pack_size}' or Stripe pack price env var not configured.`,
1577 code: 'BAD_REQUEST',
1578 });
1579 }
1580 }
1581
1582 if (!priceId) {
1583 return res.status(400).json({ error: 'price_id, tier, or pack_size is required', code: 'BAD_REQUEST' });
1584 }
1585
1586 const isSub = isSubscriptionPriceId(priceId);
1587 const isPack = isPackPriceId(priceId);
1588
1589 if (!isSub && !isPack) {
1590 return res.status(400).json({
1591 error: 'price_id is not a recognised Knowtation subscription or token pack price.',
1592 code: 'BAD_REQUEST',
1593 });
1594 }
1595
1596 const mode = isSub ? 'subscription' : 'payment';
1597
1598 const rawSuccessUrl = typeof body.success_url === 'string' ? body.success_url.trim() : '';
1599 const rawCancelUrl = typeof body.cancel_url === 'string' ? body.cancel_url.trim() : '';
1600
1601 const fallbackBase = HUB_UI_ORIGIN || BASE_URL;
1602 const successUrl = rawSuccessUrl || `${fallbackBase}/hub/#settings`;
1603 const cancelUrl = rawCancelUrl || `${fallbackBase}/hub/#settings`;
1604
1605 try {
1606 const { url } = await createCheckoutSession({
1607 priceId,
1608 userId: uid,
1609 successUrl,
1610 cancelUrl,
1611 mode,
1612 stripeCustomerId: null,
1613 });
1614 return res.json({ url });
1615 } catch (e) {
1616 const code = e.code || 'STRIPE_ERROR';
1617 if (code === 'NOT_CONFIGURED') {
1618 return res.status(503).json({ error: e.message, code });
1619 }
1620 console.error('[billing/checkout] Stripe error:', e.message);
1621 return res.status(502).json({ error: e.message || 'Stripe checkout failed', code });
1622 }
1623 });
1624
1625 /**
1626 * POST /api/v1/billing/portal
1627 * Body: { return_url? }
1628 * Returns: { url } — Stripe Billing Portal session URL.
1629 */
1630 app.post('/api/v1/billing/portal', async (req, res) => {
1631 const uid = getUserId(req);
1632 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1633
1634 const body = req.body && typeof req.body === 'object' ? req.body : {};
1635 const rawReturnUrl = typeof body.return_url === 'string' ? body.return_url.trim() : '';
1636 const fallbackBase = HUB_UI_ORIGIN || BASE_URL;
1637 const returnUrl = rawReturnUrl || `${fallbackBase}/hub/#settings`;
1638
1639 try {
1640 const { url } = await createPortalSession({ userId: uid, returnUrl });
1641 return res.json({ url });
1642 } catch (e) {
1643 const code = e.code || 'STRIPE_ERROR';
1644 if (code === 'NOT_CONFIGURED') {
1645 return res.status(503).json({ error: e.message, code });
1646 }
1647 console.error('[billing/portal] Stripe error:', e.message);
1648 return res.status(502).json({ error: e.message || 'Stripe portal failed', code });
1649 }
1650 });
1651
1652 // GET /api/v1/settings and GET /api/v1/setup — hosted: vault_list from canister; bridge fields when BRIDGE_URL set
1653 app.get('/api/v1/settings', async (req, res) => {
1654 const uid = getUserId(req);
1655 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1656 let vault_list = [{ id: 'default', label: 'Default' }];
1657 let allowed_vault_ids = ['default'];
1658 let canisterVaultUserId = uid;
1659 /** @type {string|null} */
1660 let workspace_owner_id = null;
1661 let hosted_delegating = false;
1662 /** @type {string[]|null} */
1663 let allowedFromBridge = null;
1664 if (BRIDGE_URL && req.headers.authorization) {
1665 try {
1666 const signal = hostedContextAbortSignal();
1667 const hRes = await fetch(BRIDGE_URL + '/api/v1/hosted-context/settings', {
1668 method: 'GET',
1669 headers: {
1670 Authorization: req.headers.authorization,
1671 Accept: 'application/json',
1672 },
1673 ...(signal ? { signal } : {}),
1674 });
1675 if (hRes.ok) {
1676 const hc = await hRes.json();
1677 if (hc.effective_canister_user_id && typeof hc.effective_canister_user_id === 'string') {
1678 canisterVaultUserId = hc.effective_canister_user_id;
1679 }
1680 if (Array.isArray(hc.allowed_vault_ids) && hc.allowed_vault_ids.length > 0) {
1681 allowedFromBridge = hc.allowed_vault_ids.map((x) => String(x));
1682 }
1683 if (hc.workspace_owner_id != null && String(hc.workspace_owner_id).trim() !== '') {
1684 workspace_owner_id = String(hc.workspace_owner_id).trim();
1685 }
1686 if (hc.delegating === true) hosted_delegating = true;
1687 } else if (hRes.status === 403) {
1688 allowedFromBridge = [];
1689 }
1690 } catch (_) {
1691 /* use uid-only fallback */
1692 }
1693 }
1694 if (CANISTER_URL) {
1695 try {
1696 const signal = hostedContextAbortSignal();
1697 const vRes = await fetch(CANISTER_URL + '/api/v1/vaults', {
1698 method: 'GET',
1699 headers: { 'X-User-Id': canisterVaultUserId, Accept: 'application/json', ...canisterAuthHeaders() },
1700 ...(signal ? { signal } : {}),
1701 });
1702 if (vRes.ok) {
1703 const data = await vRes.json();
1704 const vaults = Array.isArray(data.vaults) ? data.vaults : [];
1705 if (vaults.length > 0) {
1706 const mapped = vaults.map((v) => ({
1707 id: String(v.id || 'default'),
1708 label: String(v.label != null && v.label !== '' ? v.label : v.id || 'default'),
1709 }));
1710 if (allowedFromBridge !== null) {
1711 allowed_vault_ids = allowedFromBridge.filter((id) => mapped.some((m) => m.id === id));
1712 vault_list = allowed_vault_ids.map((id) => {
1713 const m = mapped.find((x) => x.id === id);
1714 return m || { id, label: id };
1715 });
1716 } else {
1717 vault_list = mapped;
1718 allowed_vault_ids = vault_list.map((v) => v.id);
1719 }
1720 } else if (allowedFromBridge && allowedFromBridge.length > 0) {
1721 allowed_vault_ids = [...allowedFromBridge];
1722 vault_list = allowedFromBridge.map((id) => ({ id, label: id }));
1723 }
1724 } else {
1725 console.warn('[gateway] canister vaults non-ok', vRes.status);
1726 }
1727 } catch (e) {
1728 console.warn('[gateway] canister vaults unreachable', e?.message || String(e));
1729 }
1730 }
1731 let github_connected = false;
1732 let github_repo = null;
1733 let role = roleForSub(uid);
1734 let hub_evaluator_may_approve = process.env.HUB_EVALUATOR_MAY_APPROVE === '1';
1735 if (BRIDGE_URL && req.headers.authorization) {
1736 try {
1737 const ghRes = await fetch(BRIDGE_URL + '/api/v1/vault/github-status', {
1738 method: 'GET',
1739 headers: { Authorization: req.headers.authorization, Accept: 'application/json' },
1740 });
1741 if (ghRes.ok) {
1742 const data = await ghRes.json();
1743 github_connected = Boolean(data.github_connected);
1744 github_repo = data.repo || null;
1745 } else {
1746 console.warn('[gateway] bridge github-status non-ok', ghRes.status);
1747 }
1748 const roleRes = await fetch(BRIDGE_URL + '/api/v1/role', {
1749 method: 'GET',
1750 headers: { Authorization: req.headers.authorization, Accept: 'application/json' },
1751 });
1752 if (roleRes.ok) {
1753 const data = await roleRes.json();
1754 if (data.role) role = data.role;
1755 if (typeof data.may_approve_proposals === 'boolean') hub_evaluator_may_approve = data.may_approve_proposals;
1756 }
1757 } catch (e) {
1758 console.warn('[gateway] bridge unreachable', e?.message || String(e));
1759 }
1760 }
1761 const vault_git = {
1762 enabled: github_connected,
1763 has_remote: Boolean(github_repo),
1764 auto_commit: false,
1765 auto_push: false,
1766 };
1767 const dataDir = path.join(projectRoot, 'data');
1768 const llmPrefs = await loadHostedProposalLlmPrefs();
1769 res.json({
1770 role,
1771 user_id: uid,
1772 vault_id: 'default',
1773 vault_list,
1774 allowed_vault_ids,
1775 vault_path_display: 'Canister',
1776 vault_git,
1777 github_connect_available: Boolean(BRIDGE_URL),
1778 github_connected,
1779 repo: github_repo,
1780 workspace_owner_id,
1781 hosted_delegating,
1782 embedding_display: { provider: '—', model: '—', ollama_url: '—' },
1783 proposal_enrich_enabled: effectiveHostedEnrich(llmPrefs),
1784 proposal_evaluation_required: effectiveHostedEvaluationRequired(llmPrefs, dataDir),
1785 proposal_review_hints_enabled: effectiveHostedReviewHints(llmPrefs),
1786 proposal_policy_stored: {
1787 proposal_evaluation_required: llmPrefs.proposal_evaluation_required,
1788 review_hints_enabled: llmPrefs.review_hints_enabled,
1789 enrich_enabled: llmPrefs.enrich_enabled,
1790 },
1791 proposal_policy_env_locked: proposalPolicyEnvLocked(),
1792 hub_evaluator_may_approve,
1793 proposal_rubric: loadProposalRubric(path.join(projectRoot, 'data')),
1794 daemon: await (async () => {
1795 try {
1796 const db = await loadBillingDb();
1797 const raw = db.users?.[uid] || defaultUserRecord(uid);
1798 const u = normalizeBillingUser(raw);
1799 return {
1800 enabled: false,
1801 interval_minutes: u.consolidation_interval_minutes || 120,
1802 idle_only: true,
1803 idle_threshold_minutes: 15,
1804 run_on_start: false,
1805 max_cost_per_day_usd: null,
1806 passes: u.consolidation_passes,
1807 lookback_hours: u.consolidation_lookback_hours,
1808 max_events_per_pass: u.consolidation_max_events_per_pass,
1809 max_topics_per_pass: u.consolidation_max_topics_per_pass,
1810 llm: {
1811 provider: '',
1812 model: '',
1813 base_url: '',
1814 max_tokens: u.consolidation_llm_max_tokens,
1815 },
1816 hosted_enabled: u.consolidation_enabled,
1817 };
1818 } catch (_) {
1819 return {
1820 enabled: false,
1821 interval_minutes: 120,
1822 idle_only: true,
1823 idle_threshold_minutes: 15,
1824 run_on_start: false,
1825 max_cost_per_day_usd: null,
1826 passes: { consolidate: true, verify: true, discover: false },
1827 lookback_hours: 24,
1828 max_events_per_pass: 200,
1829 max_topics_per_pass: 10,
1830 llm: { provider: '', model: '', base_url: '', max_tokens: 1024 },
1831 hosted_enabled: false,
1832 };
1833 }
1834 })(),
1835 muse_bridge: (() => {
1836 const envOverride = process.env.MUSE_URL != null && String(process.env.MUSE_URL).trim() !== '';
1837 const mc = parseMuseConfigFromEnv();
1838 let origin = null;
1839 if (mc) {
1840 try {
1841 origin = new URL(mc.baseUrl).origin;
1842 } catch (_) {
1843 /* ignore */
1844 }
1845 }
1846 return {
1847 enabled: Boolean(mc),
1848 origin,
1849 source: envOverride ? 'env' : 'none',
1850 env_override_active: envOverride,
1851 url_editable: false,
1852 yaml_url_for_edit: '',
1853 };
1854 })(),
1855 });
1856 });
1857
1858 /** Hosted: Muse base URL is operator env only (not writable from Hub Settings). */
1859 app.post('/api/v1/settings/muse', express.json(), (req, res) => {
1860 res.status(501).json({
1861 error: 'Knowtation Cloud configures the optional Muse link on the server; it cannot be set from this screen.',
1862 code: 'NOT_IMPLEMENTED',
1863 });
1864 });
1865
1866 /**
1867 * POST /api/v1/settings/consolidation
1868 * Hosted mode: save consolidation schedule + pass preferences to the billing store.
1869 * Self-hosted daemon settings are not writable here; respond with an appropriate note.
1870 */
1871 app.post('/api/v1/settings/consolidation', express.json(), async (req, res) => {
1872 const uid = getUserId(req);
1873 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1874 const body = req.body && typeof req.body === 'object' ? req.body : {};
1875 const mode = typeof body.mode === 'string' ? body.mode : (body.enabled ? 'daemon' : 'hosted');
1876 const advCheck = validateHostedSettingsConsolidationAdvanced(body);
1877 if (!advCheck.ok) {
1878 return res.status(400).json({ error: advCheck.error, code: advCheck.code });
1879 }
1880 try {
1881 let saved = {};
1882 await mutateBillingDb((db) => {
1883 if (!db.users) db.users = {};
1884 if (!db.users[uid]) db.users[uid] = defaultUserRecord(uid);
1885 const u = normalizeBillingUser(db.users[uid]);
1886 if (mode === 'off') {
1887 u.consolidation_enabled = false;
1888 } else {
1889 u.consolidation_enabled = true;
1890 const iv = Math.floor(Number(body.interval_minutes) || 120);
1891 if (iv >= 1 && iv <= 43200) u.consolidation_interval_minutes = iv;
1892 }
1893 if (body.passes && typeof body.passes === 'object') {
1894 u.consolidation_passes = {
1895 consolidate: body.passes.consolidate !== false,
1896 verify: body.passes.verify !== false,
1897 discover: Boolean(body.passes.discover),
1898 };
1899 }
1900 if (body.lookback_hours !== undefined) {
1901 u.consolidation_lookback_hours = Math.floor(Number(body.lookback_hours));
1902 }
1903 if (body.max_events_per_pass !== undefined) {
1904 u.consolidation_max_events_per_pass = Math.floor(Number(body.max_events_per_pass));
1905 }
1906 if (body.max_topics_per_pass !== undefined) {
1907 u.consolidation_max_topics_per_pass = Math.floor(Number(body.max_topics_per_pass));
1908 }
1909 if (body.llm !== undefined && typeof body.llm === 'object' && body.llm.max_tokens !== undefined) {
1910 u.consolidation_llm_max_tokens = Math.floor(Number(body.llm.max_tokens));
1911 }
1912 normalizeBillingUser(u);
1913 saved = {
1914 hosted_enabled: u.consolidation_enabled,
1915 interval_minutes: u.consolidation_interval_minutes,
1916 passes: u.consolidation_passes,
1917 lookback_hours: u.consolidation_lookback_hours,
1918 max_events_per_pass: u.consolidation_max_events_per_pass,
1919 max_topics_per_pass: u.consolidation_max_topics_per_pass,
1920 llm: {
1921 provider: '',
1922 model: '',
1923 base_url: '',
1924 max_tokens: u.consolidation_llm_max_tokens,
1925 },
1926 };
1927 });
1928 res.json({ ok: true, hosted: true, daemon: { enabled: false, ...saved } });
1929 } catch (e) {
1930 res.status(500).json({ error: e.message || 'Failed to save', code: 'RUNTIME_ERROR' });
1931 }
1932 });
1933
1934 app.post('/api/v1/settings/proposal-policy', requireAdmin, async (req, res) => {
1935 try {
1936 const body = req.body && typeof req.body === 'object' ? req.body : {};
1937 await mergeHostedProposalLlmPrefs({
1938 proposal_evaluation_required: body.proposal_evaluation_required,
1939 review_hints_enabled: body.review_hints_enabled,
1940 enrich_enabled: body.enrich_enabled,
1941 });
1942 res.json({ ok: true });
1943 } catch (e) {
1944 res.status(500).json({ error: e.message, code: 'RUNTIME_ERROR' });
1945 }
1946 });
1947
1948 app.get('/api/v1/setup', (req, res) => {
1949 const uid = getUserId(req);
1950 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1951 res.json({
1952 vault_path: '',
1953 vault_git: { enabled: false, remote: '' },
1954 });
1955 });
1956
1957 // --- Admin routes: HUB_ADMIN_USER_IDS, or bridge GET /api/v1/role → role "admin" (Team tab) ---
1958 function requireAdmin(req, res, next) {
1959 const uid = getUserId(req);
1960 if (!uid) {
1961 res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
1962 return;
1963 }
1964 if (roleForSub(uid) === 'admin') {
1965 next();
1966 return;
1967 }
1968 if (!BRIDGE_URL || !req.headers.authorization) {
1969 res.status(403).json({ error: 'Admin only', code: 'FORBIDDEN' });
1970 return;
1971 }
1972 void (async () => {
1973 try {
1974 const roleRes = await fetch(BRIDGE_URL + '/api/v1/role', {
1975 method: 'GET',
1976 headers: { Authorization: req.headers.authorization, Accept: 'application/json' },
1977 });
1978 if (!roleRes.ok) {
1979 if (!res.headersSent) res.status(403).json({ error: 'Admin only', code: 'FORBIDDEN' });
1980 return;
1981 }
1982 const data = await roleRes.json();
1983 if (data && data.role === 'admin') {
1984 next();
1985 return;
1986 }
1987 if (!res.headersSent) res.status(403).json({ error: 'Admin only', code: 'FORBIDDEN' });
1988 } catch (e) {
1989 console.warn('[gateway] requireAdmin bridge /role', e?.message || String(e));
1990 if (!res.headersSent) res.status(403).json({ error: 'Admin only', code: 'FORBIDDEN' });
1991 }
1992 })();
1993 }
1994
1995 if (!BRIDGE_URL) {
1996 app.get('/api/v1/workspace', requireAdmin, (_req, res) => {
1997 res.json({ owner_user_id: null });
1998 });
1999 app.post('/api/v1/workspace', requireAdmin, (_req, res) => {
2000 res.status(503).json({ error: 'Workspace owner requires bridge (BRIDGE_URL).', code: 'NOT_AVAILABLE' });
2001 });
2002 app.get('/api/v1/vault-access', requireAdmin, (_req, res) => {
2003 res.json({ access: {} });
2004 });
2005 app.post('/api/v1/vault-access', requireAdmin, (_req, res) => {
2006 res.status(503).json({ error: 'Vault access requires bridge (BRIDGE_URL).', code: 'NOT_AVAILABLE' });
2007 });
2008 app.get('/api/v1/scope', requireAdmin, (_req, res) => {
2009 res.json({ scope: {} });
2010 });
2011 app.post('/api/v1/scope', requireAdmin, (_req, res) => {
2012 res.status(503).json({ error: 'Scope requires bridge (BRIDGE_URL).', code: 'NOT_AVAILABLE' });
2013 });
2014 app.get('/api/v1/hosted-context', (req, res) => {
2015 const uid = getUserId(req);
2016 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2017 res.status(503).json({ error: 'Hosted context requires bridge (BRIDGE_URL).', code: 'NOT_AVAILABLE' });
2018 });
2019 }
2020
2021 // Hosted: vault list is derived from the canister; YAML vault editor is self-hosted only
2022 app.post('/api/v1/vaults', requireAdmin, (_req, res) => {
2023 res.status(501).json({
2024 error:
2025 'Editing the vault list in Settings is not available on hosted. Vaults appear when you add notes; use the vault switcher or API with X-Vault-Id.',
2026 code: 'NOT_AVAILABLE',
2027 });
2028 });
2029
2030 // GET /api/v1/roles — hosted stub: no role store; admin sees empty list (parity: only admins can open Team)
2031 app.get('/api/v1/roles', requireAdmin, (_req, res) => {
2032 res.json({ roles: [] });
2033 });
2034
2035 // POST /api/v1/roles — no-op on hosted (no persistent role store yet)
2036 app.post('/api/v1/roles', requireAdmin, (_req, res) => {
2037 res.json({ ok: true });
2038 });
2039
2040 // GET /api/v1/invites — hosted stub: no invite store
2041 app.get('/api/v1/invites', requireAdmin, (_req, res) => {
2042 res.json({ invites: [] });
2043 });
2044
2045 // POST /api/v1/invites — not supported on hosted (no invite store; full parity in Phase 2)
2046 app.post('/api/v1/invites', requireAdmin, (_req, res) => {
2047 res.status(400).json({
2048 error: 'Invites are not supported on hosted yet. Use self-hosted Hub for team invites, or wait for Phase 2.',
2049 code: 'NOT_SUPPORTED',
2050 });
2051 });
2052
2053 // Optional Muse read-only proxy (admin; Option C). 404 when MUSE_URL unset.
2054 app.get(
2055 '/api/v1/operator/muse/proxy',
2056 (req, res, next) => {
2057 if (!parseMuseConfigFromEnv()) {
2058 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2059 }
2060 requireAdmin(req, res, next);
2061 },
2062 async (req, res) => {
2063 const cfg = parseMuseConfigFromEnv();
2064 if (!cfg) return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2065 const rel = typeof req.query.path === 'string' ? req.query.path.trim() : '';
2066 if (!rel) return res.status(400).json({ error: 'path query required', code: 'BAD_REQUEST' });
2067 const result = await fetchMuseProxiedGet({ config: cfg, relativePath: rel });
2068 if (!result.ok && result.code === 'BAD_REQUEST') {
2069 return res.status(400).json({ error: 'Invalid path', code: 'BAD_REQUEST' });
2070 }
2071 if (!result.ok && !result.body) {
2072 return res.status(result.status).json({ error: 'Bad gateway', code: result.code });
2073 }
2074 if (!result.ok && result.body && result.contentType) {
2075 res.status(result.status).set('Content-Type', result.contentType);
2076 res.set('X-Content-Type-Options', 'nosniff');
2077 return res.send(result.body);
2078 }
2079 if (result.ok && result.body) {
2080 res.status(200).set('Content-Type', result.contentType);
2081 res.set('X-Content-Type-Options', 'nosniff');
2082 return res.send(result.body);
2083 }
2084 return res.status(502).json({ error: 'Bad gateway', code: 'BAD_GATEWAY' });
2085 },
2086 );
2087
2088 // DELETE /api/v1/invites/:token — no-op on hosted
2089 app.delete('/api/v1/invites/:token', requireAdmin, (_req, res) => {
2090 res.json({ ok: true });
2091 });
2092
2093 // POST /api/v1/setup — no-op on hosted (vault is canister; nothing to persist)
2094 app.post('/api/v1/setup', (req, res) => {
2095 const uid = getUserId(req);
2096 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2097 res.json({ ok: true });
2098 });
2099
2100 // POST /api/v1/import — bridge runs importers and writes notes to canister when BRIDGE_URL is set
2101 app.post('/api/v1/import', async (req, res) => {
2102 const uid = getUserId(req);
2103 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2104 if (BRIDGE_URL) {
2105 if (!(await runBillingGate(req, res, getUserId))) return;
2106 const q = req.originalUrl.includes('?') ? req.originalUrl.slice(req.originalUrl.indexOf('?')) : '';
2107 await proxyImportToBridge(BRIDGE_URL, BRIDGE_URL + '/api/v1/import' + q, req, res);
2108 return;
2109 }
2110 res.status(501).json({
2111 error: 'Import is not yet available on hosted (set BRIDGE_URL for bridge-backed import).',
2112 code: 'NOT_AVAILABLE',
2113 });
2114 });
2115
2116 // POST /api/v1/import-url — JSON body; bridge runs URL importer (same auth as import).
2117 app.post('/api/v1/import-url', async (req, res) => {
2118 const uid = getUserId(req);
2119 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2120 if (BRIDGE_URL) {
2121 if (!(await runBillingGate(req, res, getUserId))) return;
2122 await proxyTo(BRIDGE_URL, BRIDGE_URL + '/api/v1/import-url', req, res);
2123 return;
2124 }
2125 res.status(501).json({
2126 error: 'Import URL is not available on hosted (set BRIDGE_URL for bridge-backed import).',
2127 code: 'NOT_AVAILABLE',
2128 });
2129 });
2130
2131 // GET /api/v1/notes/facets — aggregate from canister list (Hub filter dropdowns / overview parity)
2132 app.get('/api/v1/notes/facets', async (req, res) => {
2133 const uid = getUserId(req);
2134 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2135 if (!CANISTER_URL) {
2136 return res.json({ projects: [], tags: [], folders: [] });
2137 }
2138 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2139 const hctx = await getHostedAccessContext(req);
2140 const effective = (hctx && hctx.effective_canister_user_id) || uid;
2141 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
2142 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
2143 }
2144 try {
2145 const url = `${CANISTER_URL}/api/v1/notes`;
2146 const upstream = await fetch(url, {
2147 method: 'GET',
2148 headers: {
2149 Accept: 'application/json',
2150 'x-user-id': effective,
2151 'x-actor-id': uid,
2152 'x-vault-id': vaultId,
2153 },
2154 });
2155 const text = await upstream.text();
2156 if (!upstream.ok) {
2157 console.warn('[gateway] facets canister list non-ok', upstream.status);
2158 return res.json({ projects: [], tags: [], folders: [] });
2159 }
2160 let data;
2161 try {
2162 data = text ? JSON.parse(text) : {};
2163 } catch (e) {
2164 console.warn('[gateway] facets canister list JSON parse', e?.message || String(e));
2165 return res.json({ projects: [], tags: [], folders: [] });
2166 }
2167 const rows = Array.isArray(data.notes) ? data.notes : [];
2168 let notesForFacets = rows;
2169 const scope = hctx && hctx.scope && typeof hctx.scope === 'object' ? hctx.scope : null;
2170 if (scope && (scope.projects?.length || scope.folders?.length)) {
2171 const withProj = rows.map((n) => ({
2172 path: n.path,
2173 project: materializeListFrontmatter(n.frontmatter).project ?? null,
2174 }));
2175 const scoped = applyScopeFilterToNotes(withProj, scope);
2176 const pathSet = new Set(scoped.map((n) => n.path).filter(Boolean));
2177 notesForFacets = rows.filter((n) => pathSet.has(n.path));
2178 }
2179 const facets = deriveFacetsFromCanisterNotes(notesForFacets);
2180 res.json(facets);
2181 } catch (e) {
2182 console.warn('[gateway] facets error', e?.message || String(e));
2183 res.json({ projects: [], tags: [], folders: [] });
2184 }
2185 });
2186
2187 // GET /api/v1/vault/folders — no canister filesystem; UI falls back to inbox + custom path
2188 app.get('/api/v1/vault/folders', async (req, res) => {
2189 const uid = getUserId(req);
2190 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2191 if (!CANISTER_URL) {
2192 return res.json({ folders: ['inbox'] });
2193 }
2194 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2195 const hctx = await getHostedAccessContext(req);
2196 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
2197 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
2198 }
2199 res.json({ folders: ['inbox'] });
2200 });
2201
2202 app.get('/api/v1/note-outline', async (req, res) => {
2203 const uid = getUserId(req);
2204 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2205 if (!CANISTER_URL) {
2206 return res.status(503).json({ error: 'Hosted NoteOutline is not configured', code: 'SERVICE_UNAVAILABLE' });
2207 }
2208
2209 let requestedPath;
2210 try {
2211 requestedPath = normalizeGatewayNoteOutlinePath(req.query.path);
2212 } catch (e) {
2213 const err = sanitizedNoteOutlineGatewayError(e);
2214 return res.status(err.status).json({ error: err.error, code: err.code });
2215 }
2216
2217 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2218 const hctx = await getHostedAccessContext(req);
2219 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
2220 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
2221 }
2222 const effective =
2223 hctx && typeof hctx.effective_canister_user_id === 'string' && hctx.effective_canister_user_id
2224 ? hctx.effective_canister_user_id
2225 : uid;
2226 const url = `${CANISTER_URL}/api/v1/notes/${encodeURIComponent(requestedPath)}`;
2227
2228 try {
2229 const upstream = await fetch(url, {
2230 method: 'GET',
2231 headers: {
2232 Accept: 'application/json',
2233 'x-user-id': effective,
2234 'x-actor-id': uid,
2235 'x-vault-id': vaultId,
2236 ...canisterAuthHeaders(),
2237 },
2238 });
2239 const text = await upstream.text();
2240 if (upstream.status === 401 || upstream.status === 403) {
2241 return res.status(403).json({ error: 'Forbidden', code: 'FORBIDDEN' });
2242 }
2243 if (upstream.status === 404) {
2244 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2245 }
2246 if (!upstream.ok) {
2247 return res.status(502).json({ error: `Upstream ${upstream.status}`, code: 'BAD_GATEWAY' });
2248 }
2249
2250 let note;
2251 try {
2252 note = text ? JSON.parse(text) : {};
2253 } catch {
2254 return res.status(502).json({ error: 'Invalid note response', code: 'BAD_GATEWAY' });
2255 }
2256
2257 const frontmatter = materializeListFrontmatter(note.frontmatter);
2258 const scope = scopeActiveForGateway(hctx) ? hctx.scope : null;
2259 if (scope) {
2260 const scoped = applyScopeFilterToNotes(
2261 [
2262 {
2263 path: requestedPath,
2264 project: frontmatter.project ?? null,
2265 },
2266 ],
2267 scope
2268 );
2269 if (scoped.length === 0) {
2270 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2271 }
2272 }
2273
2274 return res.json(
2275 buildNoteOutline({
2276 path: requestedPath,
2277 frontmatter,
2278 body: note.body != null ? String(note.body) : '',
2279 })
2280 );
2281 } catch (e) {
2282 const err = sanitizedNoteOutlineGatewayError(e);
2283 return res.status(err.status).json({ error: err.error, code: err.code });
2284 }
2285 });
2286
2287 app.get('/api/v1/document-tree', async (req, res) => {
2288 const uid = getUserId(req);
2289 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2290 if (!CANISTER_URL) {
2291 return res.status(503).json({ error: 'Hosted DocumentTree is not configured', code: 'SERVICE_UNAVAILABLE' });
2292 }
2293
2294 let requestedPath;
2295 try {
2296 requestedPath = normalizeGatewayDocumentTreePath(req.query.path);
2297 } catch (e) {
2298 const err = sanitizedDocumentTreeGatewayError(e);
2299 return res.status(err.status).json({ error: err.error, code: err.code });
2300 }
2301
2302 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2303 const hctx = await getHostedAccessContext(req);
2304 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
2305 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
2306 }
2307 const effective =
2308 hctx && typeof hctx.effective_canister_user_id === 'string' && hctx.effective_canister_user_id
2309 ? hctx.effective_canister_user_id
2310 : uid;
2311 const url = `${CANISTER_URL}/api/v1/notes/${encodeURIComponent(requestedPath)}`;
2312
2313 try {
2314 const upstream = await fetch(url, {
2315 method: 'GET',
2316 headers: {
2317 Accept: 'application/json',
2318 'x-user-id': effective,
2319 'x-actor-id': uid,
2320 'x-vault-id': vaultId,
2321 ...canisterAuthHeaders(),
2322 },
2323 });
2324 const text = await upstream.text();
2325 if (upstream.status === 401 || upstream.status === 403) {
2326 return res.status(403).json({ error: 'Forbidden', code: 'FORBIDDEN' });
2327 }
2328 if (upstream.status === 404) {
2329 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2330 }
2331 if (!upstream.ok) {
2332 return res.status(502).json({ error: `Upstream ${upstream.status}`, code: 'BAD_GATEWAY' });
2333 }
2334
2335 let note;
2336 try {
2337 note = text ? JSON.parse(text) : {};
2338 } catch {
2339 return res.status(502).json({ error: 'Invalid note response', code: 'BAD_GATEWAY' });
2340 }
2341
2342 const frontmatter = materializeListFrontmatter(note.frontmatter);
2343 const scope = scopeActiveForGateway(hctx) ? hctx.scope : null;
2344 if (scope) {
2345 const scoped = applyScopeFilterToNotes(
2346 [
2347 {
2348 path: requestedPath,
2349 project: frontmatter.project ?? null,
2350 },
2351 ],
2352 scope
2353 );
2354 if (scoped.length === 0) {
2355 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2356 }
2357 }
2358
2359 return res.json(
2360 buildDocumentTree({
2361 path: requestedPath,
2362 frontmatter,
2363 body: note.body != null ? String(note.body) : '',
2364 })
2365 );
2366 } catch (e) {
2367 const err = sanitizedDocumentTreeGatewayError(e);
2368 return res.status(err.status).json({ error: err.error, code: err.code });
2369 }
2370 });
2371
2372 app.get('/api/v1/metadata-facets', async (req, res) => {
2373 const uid = getUserId(req);
2374 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2375 if (!CANISTER_URL) {
2376 return res.status(503).json({ error: 'Hosted MetadataFacets is not configured', code: 'SERVICE_UNAVAILABLE' });
2377 }
2378
2379 let requestedPath;
2380 try {
2381 requestedPath = normalizeGatewayMetadataFacetsPath(req.query.path);
2382 } catch (e) {
2383 const err = sanitizedMetadataFacetsGatewayError(e);
2384 return res.status(err.status).json({ error: err.error, code: err.code });
2385 }
2386
2387 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2388 const hctx = await getHostedAccessContext(req);
2389 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
2390 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
2391 }
2392 const effective =
2393 hctx && typeof hctx.effective_canister_user_id === 'string' && hctx.effective_canister_user_id
2394 ? hctx.effective_canister_user_id
2395 : uid;
2396 const url = `${CANISTER_URL}/api/v1/notes/${encodeURIComponent(requestedPath)}`;
2397
2398 try {
2399 const upstream = await fetch(url, {
2400 method: 'GET',
2401 headers: {
2402 Accept: 'application/json',
2403 'x-user-id': effective,
2404 'x-actor-id': uid,
2405 'x-vault-id': vaultId,
2406 ...canisterAuthHeaders(),
2407 },
2408 });
2409 const text = await upstream.text();
2410 if (upstream.status === 401 || upstream.status === 403) {
2411 return res.status(403).json({ error: 'Forbidden', code: 'FORBIDDEN' });
2412 }
2413 if (upstream.status === 404) {
2414 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2415 }
2416 if (!upstream.ok) {
2417 return res.status(502).json({ error: `Upstream ${upstream.status}`, code: 'BAD_GATEWAY' });
2418 }
2419
2420 let note;
2421 try {
2422 note = text ? JSON.parse(text) : {};
2423 } catch {
2424 return res.status(502).json({ error: 'Invalid note response', code: 'BAD_GATEWAY' });
2425 }
2426
2427 const frontmatter = materializeListFrontmatter(note.frontmatter);
2428 const scope = scopeActiveForGateway(hctx) ? hctx.scope : null;
2429 if (scope) {
2430 const scoped = applyScopeFilterToNotes(
2431 [
2432 {
2433 path: requestedPath,
2434 project: frontmatter.project ?? null,
2435 },
2436 ],
2437 scope
2438 );
2439 if (scoped.length === 0) {
2440 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2441 }
2442 }
2443
2444 return res.json(normalizeMetadataFacets(requestedPath, frontmatter));
2445 } catch (e) {
2446 const err = sanitizedMetadataFacetsGatewayError(e);
2447 return res.status(err.status).json({ error: err.error, code: err.code });
2448 }
2449 });
2450
2451 app.get('/api/v1/section-source', async (req, res) => {
2452 const uid = getUserId(req);
2453 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2454 if (!CANISTER_URL) {
2455 return res.status(503).json({ error: 'Hosted SectionSource is not configured', code: 'SERVICE_UNAVAILABLE' });
2456 }
2457
2458 let requestedPath;
2459 try {
2460 requestedPath = normalizeGatewaySectionSourcePath(req.query.path);
2461 } catch (e) {
2462 const err = sanitizedSectionSourceGatewayError(e);
2463 return res.status(err.status).json({ error: err.error, code: err.code });
2464 }
2465
2466 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2467 const hctx = await getHostedAccessContext(req);
2468 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
2469 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
2470 }
2471 const effective =
2472 hctx && typeof hctx.effective_canister_user_id === 'string' && hctx.effective_canister_user_id
2473 ? hctx.effective_canister_user_id
2474 : uid;
2475 const url = `${CANISTER_URL}/api/v1/notes/${encodeURIComponent(requestedPath)}`;
2476
2477 try {
2478 const upstream = await fetch(url, {
2479 method: 'GET',
2480 headers: {
2481 Accept: 'application/json',
2482 'x-user-id': effective,
2483 'x-actor-id': uid,
2484 'x-vault-id': vaultId,
2485 ...canisterAuthHeaders(),
2486 },
2487 });
2488 const text = await upstream.text();
2489 if (upstream.status === 401 || upstream.status === 403) {
2490 return res.status(403).json({ error: 'Forbidden', code: 'FORBIDDEN' });
2491 }
2492 if (upstream.status === 404) {
2493 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2494 }
2495 if (!upstream.ok) {
2496 return res.status(502).json({ error: `Upstream ${upstream.status}`, code: 'BAD_GATEWAY' });
2497 }
2498
2499 let note;
2500 try {
2501 note = text ? JSON.parse(text) : {};
2502 } catch {
2503 return res.status(502).json({ error: 'Invalid note response', code: 'BAD_GATEWAY' });
2504 }
2505
2506 const frontmatter = materializeListFrontmatter(note.frontmatter);
2507 const scope = scopeActiveForGateway(hctx) ? hctx.scope : null;
2508 if (scope) {
2509 const scoped = applyScopeFilterToNotes(
2510 [
2511 {
2512 path: requestedPath,
2513 project: frontmatter.project ?? null,
2514 },
2515 ],
2516 scope
2517 );
2518 if (scoped.length === 0) {
2519 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2520 }
2521 }
2522
2523 return res.json(
2524 buildSectionSource({
2525 path: requestedPath,
2526 frontmatter,
2527 body: note.body != null ? String(note.body) : '',
2528 })
2529 );
2530 } catch (e) {
2531 const err = sanitizedSectionSourceGatewayError(e);
2532 return res.status(err.status).json({ error: err.error, code: err.code });
2533 }
2534 });
2535
2536 /**
2537 * @param {Record<string, unknown>|null} hctx
2538 */
2539 function scopeActiveForGateway(hctx) {
2540 const s = hctx && hctx.scope && typeof hctx.scope === 'object' ? hctx.scope : null;
2541 return Boolean(s && (s.projects?.length || s.folders?.length));
2542 }
2543
2544 /**
2545 * Normalize hosted canister note records before returning them to Hub clients.
2546 * The canister wire shape may store frontmatter as object JSON text; clients
2547 * should always receive the direct-read/list API contract object.
2548 * @param {unknown} note
2549 * @returns {unknown}
2550 */
2551 function normalizeGatewayNoteFrontmatter(note) {
2552 if (!note || typeof note !== 'object' || Array.isArray(note)) return note;
2553 return {
2554 ...note,
2555 frontmatter: materializeListFrontmatter(note.frontmatter),
2556 };
2557 }
2558
2559 async function gatewayProxyGetNotesList(req, res, uid, effective, hctx) {
2560 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2561 const raw = upstreamPathAndQuery(req);
2562 const qIdx = raw.indexOf('?');
2563 const searchPart = qIdx >= 0 ? raw.slice(qIdx + 1) : '';
2564 const params = new URLSearchParams(searchPart);
2565 const limit = Math.min(100, Math.max(0, parseInt(params.get('limit') || '20', 10) || 20));
2566 const offset = Math.max(0, parseInt(params.get('offset') || '0', 10) || 0);
2567 const scope = scopeActiveForGateway(hctx) ? hctx.scope : null;
2568 // Phase 12 — blockchain filters applied client-side (canister stores frontmatter as opaque JSON)
2569 const filterNetwork = (params.get('network') || '').trim().toLowerCase();
2570 const filterWallet = (params.get('wallet_address') || '').trim().toLowerCase();
2571 const filterPaymentStatus = (params.get('payment_status') || '').trim().toLowerCase();
2572 const needsClientFilter = Boolean(scope || filterNetwork || filterWallet || filterPaymentStatus);
2573 if (needsClientFilter) {
2574 params.set('limit', '10000');
2575 params.set('offset', '0');
2576 }
2577 // Remove Phase 12 params before forwarding to canister (canister ignores them, but keep URL clean)
2578 params.delete('network');
2579 params.delete('wallet_address');
2580 params.delete('payment_status');
2581 const fetchUrl = `${CANISTER_URL}/api/v1/notes${params.toString() ? `?${params.toString()}` : ''}`;
2582 try {
2583 const upstream = await fetch(fetchUrl, {
2584 method: 'GET',
2585 headers: {
2586 Accept: 'application/json',
2587 'x-user-id': effective,
2588 'x-actor-id': uid,
2589 'x-vault-id': vaultId,
2590 ...canisterAuthHeaders(),
2591 },
2592 });
2593 const text = await upstream.text();
2594 const hop = filterUpstreamResponseHeadersForDecodedBody(upstream.headers.entries()).filter(
2595 ([k]) => !['cache-control', 'etag', 'last-modified'].includes(k.toLowerCase()),
2596 );
2597 res.status(upstream.status).set(Object.fromEntries(hop));
2598 res.set('Cache-Control', 'private, no-store, must-revalidate');
2599 if (!upstream.ok || !text) {
2600 res.send(text);
2601 return;
2602 }
2603 let data;
2604 try {
2605 data = JSON.parse(text);
2606 } catch (_) {
2607 res.send(text);
2608 return;
2609 }
2610 if (Array.isArray(data.notes)) {
2611 data = { ...data, notes: data.notes.map(normalizeGatewayNoteFrontmatter) };
2612 }
2613 if (needsClientFilter && Array.isArray(data.notes)) {
2614 let filtered = data.notes;
2615 // Scope filter (project/folder access control)
2616 if (scope) {
2617 const withProj = filtered.map((n) => ({
2618 path: n.path,
2619 project: materializeListFrontmatter(n.frontmatter).project ?? null,
2620 }));
2621 const kept = applyScopeFilterToNotes(withProj, scope);
2622 const keptPaths = new Set(kept.map((r) => r.path).filter(Boolean));
2623 filtered = filtered.filter((n) => n.path && keptPaths.has(n.path));
2624 }
2625 // Phase 12 blockchain filters
2626 if (filterNetwork || filterWallet || filterPaymentStatus) {
2627 filtered = filtered.filter((n) => {
2628 const fm = materializeListFrontmatter(n.frontmatter);
2629 if (filterNetwork && String(fm.network ?? '').trim().toLowerCase() !== filterNetwork) return false;
2630 if (filterWallet && String(fm.wallet_address ?? '').trim().toLowerCase() !== filterWallet) return false;
2631 if (filterPaymentStatus && String(fm.payment_status ?? '').trim().toLowerCase() !== filterPaymentStatus) return false;
2632 return true;
2633 });
2634 }
2635 const total = filtered.length;
2636 const page = filtered.slice(offset, offset + limit);
2637 res.json({ notes: page, total });
2638 return;
2639 }
2640 if (Array.isArray(data.notes)) {
2641 res.json(data);
2642 return;
2643 }
2644 res.send(text);
2645 } catch (e) {
2646 console.error('Gateway GET notes list error:', e.message);
2647 res.status(502).json({ error: 'Bad Gateway', code: 'BAD_GATEWAY' });
2648 }
2649 }
2650
2651 async function gatewayProxyGetNoteOne(req, res, uid, effective, hctx) {
2652 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2653 const url = CANISTER_URL + upstreamPathAndQuery(req);
2654 const scope = scopeActiveForGateway(hctx) ? hctx.scope : null;
2655 try {
2656 const upstream = await fetch(url, {
2657 method: 'GET',
2658 headers: {
2659 Accept: 'application/json',
2660 'x-user-id': effective,
2661 'x-actor-id': uid,
2662 'x-vault-id': vaultId,
2663 ...canisterAuthHeaders(),
2664 },
2665 });
2666 const body = await upstream.text();
2667 if (upstream.status >= 400) {
2668 console.warn('[gateway] canister GET note:', upstream.status, 'url:', url.slice(0, 120));
2669 }
2670 const hop = filterUpstreamResponseHeadersForDecodedBody(upstream.headers.entries()).filter(
2671 ([k]) => !['cache-control', 'etag', 'last-modified'].includes(k.toLowerCase()),
2672 );
2673 res.status(upstream.status).set(Object.fromEntries(hop));
2674 res.set('Cache-Control', 'private, no-store, must-revalidate');
2675 if (!scope || upstream.status !== 200 || !body) {
2676 if (upstream.status === 200 && body) {
2677 try {
2678 const note = JSON.parse(body);
2679 res.json(normalizeGatewayNoteFrontmatter(note));
2680 return;
2681 } catch (_) {
2682 // Preserve the upstream response when it is not valid JSON.
2683 }
2684 }
2685 res.send(body);
2686 return;
2687 }
2688 let note;
2689 try {
2690 note = normalizeGatewayNoteFrontmatter(JSON.parse(body));
2691 const withProj = {
2692 path: note.path,
2693 project: materializeListFrontmatter(note.frontmatter).project ?? null,
2694 };
2695 const filtered = applyScopeFilterToNotes([withProj], scope);
2696 if (filtered.length === 0) {
2697 res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
2698 return;
2699 }
2700 } catch (_) {
2701 res.send(body);
2702 return;
2703 }
2704 res.json(note);
2705 } catch (e) {
2706 console.error('Gateway GET note error:', e.message);
2707 res.status(502).json({ error: 'Bad Gateway', code: 'BAD_GATEWAY' });
2708 }
2709 }
2710
2711 const PROPOSAL_APPROVE_OR_DISCARD_RE = /^\/api\/v1\/proposals\/[^/]+\/(approve|discard)\/?$/;
2712
2713 /**
2714 * Bridge / JWT actor role for proposal RBAC (canister only sees effective X-User-Id).
2715 * @param {import('express').Request} req
2716 * @param {Record<string, unknown>|null} hctx
2717 * @returns {Promise<{ role: string, mayApproveProposals: boolean }>}
2718 */
2719 async function resolveHostedActorRole(req, hctx) {
2720 const envFallback = process.env.HUB_EVALUATOR_MAY_APPROVE === '1';
2721 let role = 'member';
2722 let mayApproveProposals = false;
2723 if (hctx && typeof hctx.role === 'string') {
2724 role = hctx.role;
2725 if (typeof hctx.may_approve_proposals === 'boolean') {
2726 mayApproveProposals = hctx.may_approve_proposals;
2727 } else if (role === 'evaluator') {
2728 mayApproveProposals = envFallback;
2729 }
2730 } else if (BRIDGE_URL && req.headers.authorization) {
2731 let bridgeResolved = false;
2732 try {
2733 const roleRes = await fetch(BRIDGE_URL + '/api/v1/role', {
2734 method: 'GET',
2735 headers: { Authorization: req.headers.authorization, Accept: 'application/json' },
2736 });
2737 if (roleRes.ok) {
2738 const data = await roleRes.json();
2739 if (data.role) {
2740 role = data.role;
2741 bridgeResolved = true;
2742 }
2743 if (typeof data.may_approve_proposals === 'boolean') {
2744 mayApproveProposals = data.may_approve_proposals;
2745 } else if (role === 'evaluator') {
2746 mayApproveProposals = envFallback;
2747 }
2748 }
2749 } catch (_) {}
2750 // Bridge unreachable or rejected the JWT (e.g. SESSION_SECRET mismatch after a redeploy).
2751 // Fall back to the JWT payload role so the gateway owner is never locked out by bridge state.
2752 if (!bridgeResolved) {
2753 try {
2754 const auth = req.headers.authorization;
2755 const token = auth && auth.startsWith('Bearer ') ? auth.slice(7) : null;
2756 if (token && SESSION_SECRET) {
2757 const payload = jwt.verify(token, SESSION_SECRET);
2758 role = payload.role || roleForSub(payload.sub);
2759 mayApproveProposals = role === 'admin' || (role === 'evaluator' && envFallback);
2760 }
2761 } catch (_) {}
2762 }
2763 } else {
2764 try {
2765 const auth = req.headers.authorization;
2766 const token = auth && auth.startsWith('Bearer ') ? auth.slice(7) : null;
2767 if (token && SESSION_SECRET) {
2768 const payload = jwt.verify(token, SESSION_SECRET);
2769 role = payload.role || roleForSub(payload.sub);
2770 mayApproveProposals = role === 'admin' || (role === 'evaluator' && envFallback);
2771 }
2772 } catch (_) {}
2773 }
2774 // Gateway-level admin override: HUB_ADMIN_USER_IDS is the authoritative owner list.
2775 // A sub in that list is always admin — the gateway owner must never be locked out by a
2776 // bridge state reset, role-store loss, or SESSION_SECRET mismatch between gateway and bridge.
2777 const actorSub = getUserId(req);
2778 if (actorSub && role !== 'admin' && roleForSub(actorSub) === 'admin') {
2779 role = 'admin';
2780 mayApproveProposals = true;
2781 }
2782 return { role, mayApproveProposals };
2783 }
2784
2785 /**
2786 * Approve/discard: enforce actor role on gateway (canister only sees effective X-User-Id).
2787 * @param {import('express').Request} req
2788 * @param {import('express').Response} res
2789 * @param {string} pathNoQuery
2790 * @param {string} method
2791 * @param {Record<string, unknown>|null} hctx from getHostedAccessContext (null if no bridge / not delegated)
2792 */
2793 async function assertHostedProposalApproveDiscard(req, res, pathNoQuery, method, hctx) {
2794 if (method !== 'POST' || !PROPOSAL_APPROVE_OR_DISCARD_RE.test(pathNoQuery)) return true;
2795
2796 const uid = getUserId(req);
2797 if (!uid) {
2798 res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2799 return false;
2800 }
2801
2802 const { role, mayApproveProposals } = await resolveHostedActorRole(req, hctx);
2803
2804 if (/\/discard\/?$/.test(pathNoQuery)) {
2805 if (role !== 'admin') {
2806 res.status(403).json({ error: 'Discard requires admin.', code: 'FORBIDDEN' });
2807 return false;
2808 }
2809 return true;
2810 }
2811
2812 const canApprove = role === 'admin' || (role === 'evaluator' && mayApproveProposals);
2813 if (!canApprove) {
2814 res.status(403).json({
2815 error:
2816 'Approve requires admin, or an evaluator with approve permission (per-user in Team, or HUB_EVALUATOR_MAY_APPROVE=1 when no per-user value).',
2817 code: 'FORBIDDEN',
2818 });
2819 return false;
2820 }
2821 return true;
2822 }
2823
2824 /**
2825 * Fetch the current note count for a user from the canister.
2826 * Used by the billing storage cap gate before note CREATE.
2827 * Fails open — returns 0 on any error so the gate never blocks due to a canister outage.
2828 *
2829 * @param {string} userId
2830 * @param {import('express').Request} req
2831 * @returns {Promise<number>}
2832 */
2833 async function getNoteCountForUser(userId, req) {
2834 if (!CANISTER_URL) return 0;
2835 try {
2836 let vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2837 const pathOnly = effectiveRequestPath(req).replace(/\/+$/, '') || '/';
2838 if (req.method === 'POST' && pathOnly === '/api/v1/notes/copy') {
2839 const b = req.body && typeof req.body === 'object' ? req.body : {};
2840 const toV = typeof b.to_vault_id === 'string' ? b.to_vault_id.replace(/\\/g, '/').trim() : '';
2841 if (toV) vaultId = toV;
2842 }
2843 const hctx = await getHostedAccessContext(req);
2844 const effective =
2845 hctx && typeof hctx.effective_canister_user_id === 'string' && hctx.effective_canister_user_id
2846 ? hctx.effective_canister_user_id
2847 : userId;
2848 const url = `${CANISTER_URL}/api/v1/notes?limit=1&offset=0`;
2849 const upstream = await fetch(url, {
2850 method: 'GET',
2851 headers: {
2852 Accept: 'application/json',
2853 'x-user-id': effective,
2854 'x-actor-id': userId,
2855 'x-vault-id': vaultId,
2856 ...canisterAuthHeaders(),
2857 },
2858 });
2859 if (!upstream.ok) return 0;
2860 const data = await upstream.json();
2861 const total = typeof data.total === 'number' ? data.total : (Array.isArray(data.notes) ? data.notes.length : 0);
2862 return Math.max(0, Math.floor(total));
2863 } catch (_) {
2864 return 0;
2865 }
2866 }
2867
2868 async function proxyToCanister(req, res) {
2869 const uid = getUserId(req);
2870 if (!uid) {
2871 return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
2872 }
2873 const pathOnly = effectiveRequestPath(req);
2874 const pathNoQuery = pathPartNoQuery(req);
2875 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
2876 const hctx = await getHostedAccessContext(req);
2877 if (!(await assertHostedProposalApproveDiscard(req, res, pathNoQuery, req.method, hctx))) return;
2878 const effective =
2879 hctx && typeof hctx.effective_canister_user_id === 'string' && hctx.effective_canister_user_id
2880 ? hctx.effective_canister_user_id
2881 : uid;
2882 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
2883 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
2884 }
2885
2886 if (req.method === 'GET' && pathOnly === '/api/v1/notes') {
2887 return gatewayProxyGetNotesList(req, res, uid, effective, hctx);
2888 }
2889 const noteSubPrefix = '/api/v1/notes/';
2890 if (
2891 req.method === 'GET' &&
2892 pathOnly.startsWith(noteSubPrefix) &&
2893 pathOnly !== '/api/v1/notes/facets'
2894 ) {
2895 const rest = pathOnly.slice(noteSubPrefix.length);
2896 if (rest) {
2897 return gatewayProxyGetNoteOne(req, res, uid, effective, hctx);
2898 }
2899 }
2900
2901 const url = CANISTER_URL + upstreamPathAndQuery(req);
2902 const headers = {
2903 host: new URL(CANISTER_URL).host,
2904 'x-user-id': effective,
2905 'x-actor-id': uid,
2906 'x-vault-id': req.headers['x-vault-id'] || 'default',
2907 ...canisterAuthHeaders(),
2908 };
2909 // Allowlist: only forward safe body/content headers; canister auth is via x-user-id + x-gateway-auth.
2910 // Never forward origin, referer, cookies, authorization, or other proxy headers to the canister.
2911 for (const k of PROXY_HEADER_ALLOWLIST) {
2912 if (req.headers[k] !== undefined) headers[k] = req.headers[k];
2913 }
2914 const opts = { method: req.method, headers };
2915 let bodyOut = req.body;
2916 const pathOnlyForBody = pathPartNoQuery(req);
2917 const dataDir = path.join(projectRoot, 'data');
2918 let hostedLlmPrefs = null;
2919 if (
2920 req.method === 'POST' &&
2921 (pathOnlyForBody === '/api/v1/proposals' || pathOnlyForBody === '/api/v1/proposals/')
2922 ) {
2923 hostedLlmPrefs = await loadHostedProposalLlmPrefs();
2924 }
2925 // Improvement B: AIR attestation for hosted gateway note writes.
2926 // Guarded by KNOWTATION_AIR_ENDPOINT being set; always non-blocking (gateway has no air.required config).
2927 let gatewayAirId = null;
2928 if (
2929 process.env.KNOWTATION_AIR_ENDPOINT &&
2930 bodyOut !== undefined &&
2931 typeof bodyOut === 'object' &&
2932 !Buffer.isBuffer(bodyOut) &&
2933 isNoteWriteRequest(req.method, pathOnlyForBody)
2934 ) {
2935 try {
2936 const notePath =
2937 req.method === 'POST'
2938 ? (typeof bodyOut.path === 'string' ? bodyOut.path.replace(/\\/g, '/') : '')
2939 : pathOnlyForBody
2940 .slice('/api/v1/notes/'.length)
2941 .split('/')
2942 .map(decodeURIComponent)
2943 .join('/');
2944 const { attestBeforeWrite: gwAttest } = await import('../../lib/air.mjs');
2945 const airId = await gwAttest(
2946 { air: { enabled: true, required: false, endpoint: process.env.KNOWTATION_AIR_ENDPOINT } },
2947 notePath
2948 );
2949 if (airId && airId !== 'air-placeholder-write') {
2950 gatewayAirId = airId;
2951 }
2952 } catch (e) {
2953 // Never let an AIR failure block a hosted write; log and continue.
2954 console.error('[gateway] AIR attestation error (non-fatal):', e?.message || String(e));
2955 }
2956 }
2957
2958 if (
2959 bodyOut !== undefined &&
2960 typeof bodyOut === 'object' &&
2961 !Buffer.isBuffer(bodyOut) &&
2962 isPostApiV1Notes(req.method, pathOnlyForBody)
2963 ) {
2964 bodyOut = mergeHostedNoteBodyForCanister(bodyOut, uid, gatewayAirId);
2965 } else if (
2966 gatewayAirId &&
2967 bodyOut !== undefined &&
2968 typeof bodyOut === 'object' &&
2969 !Buffer.isBuffer(bodyOut) &&
2970 req.method === 'PUT' &&
2971 pathOnlyForBody.startsWith('/api/v1/notes/')
2972 ) {
2973 // PUT note write: inject air_id into frontmatter alongside existing fields
2974 bodyOut = mergeHostedNoteBodyForCanister(bodyOut, uid, gatewayAirId);
2975 }
2976 if (bodyOut !== undefined && typeof bodyOut === 'object' && !Buffer.isBuffer(bodyOut)) {
2977 bodyOut = augmentProposalEvaluationBodyForCanister(req.method, pathOnlyForBody, bodyOut);
2978 const policyOpts =
2979 hostedLlmPrefs != null
2980 ? { evaluationRequired: effectiveHostedEvaluationRequired(hostedLlmPrefs, dataDir) }
2981 : {};
2982 bodyOut = augmentProposalCreateForHosted(req.method, pathOnlyForBody, bodyOut, dataDir, policyOpts);
2983 if (req.method === 'POST') {
2984 const approveId = proposalIdFromApprovePath(pathOnlyForBody);
2985 if (approveId) {
2986 try {
2987 const museCfg = parseMuseConfigFromEnv();
2988 const resolved = await resolveExternalRefForApprove({
2989 clientRef: bodyOut.external_ref,
2990 proposalId: approveId,
2991 vaultId,
2992 config: museCfg,
2993 logWarn: (msg, extra) => console.warn(msg, extra != null ? JSON.stringify(extra) : ''),
2994 });
2995 if (resolved) {
2996 bodyOut = { ...bodyOut, external_ref: resolved };
2997 }
2998 } catch (e) {
2999 console.warn('[gateway] muse approve merge (non-fatal):', e?.message || String(e));
3000 }
3001 }
3002 }
3003 }
3004 if (req.method !== 'GET' && req.method !== 'HEAD' && bodyOut !== undefined) {
3005 opts.body = typeof bodyOut === 'string' ? bodyOut : JSON.stringify(bodyOut);
3006 stripStaleOutboundBodyHeaders(headers);
3007 }
3008 try {
3009 const upstream = await fetch(url, opts);
3010 const body = await upstream.text();
3011 // For a successful proposal CREATE, extract path+body so the hints job can skip
3012 // its own canister GET (saves one ICP round trip, ~1–3 s, from the hints path).
3013 let parsedProposalData = null;
3014 if (
3015 req.method === 'POST' &&
3016 (pathOnlyForBody === '/api/v1/proposals' || pathOnlyForBody === '/api/v1/proposals/') &&
3017 upstream.status >= 200 && upstream.status < 300
3018 ) {
3019 try {
3020 const j = JSON.parse(body);
3021 const merged = proposalDataForHostedReviewHintsFromCreate(j, bodyOut);
3022 if (merged) parsedProposalData = merged;
3023 } catch (_) {}
3024 }
3025 try {
3026 await maybeScheduleHostedProposalReviewHints({
3027 method: req.method,
3028 pathOnly: pathOnlyForBody,
3029 upstreamStatus: upstream.status,
3030 responseText: body,
3031 canisterUrl: CANISTER_URL,
3032 effectiveUserId: effective,
3033 actorUserId: uid,
3034 vaultId,
3035 hintsEnabled: hostedLlmPrefs ? effectiveHostedReviewHints(hostedLlmPrefs) : false,
3036 proposalData: parsedProposalData,
3037 });
3038 } catch (e) {
3039 // Never let a hints failure affect the primary proxy response.
3040 console.error('[gateway] hints exception (non-fatal):', e?.message || String(e));
3041 }
3042 if (upstream.status >= 400 && req.method === 'GET' && url.includes('/api/v1/notes/')) {
3043 console.warn('[gateway] canister GET note:', upstream.status, 'url:', url.slice(0, 120));
3044 }
3045 if (
3046 upstream.status === 404 &&
3047 req.method === 'POST' &&
3048 /\/api\/v1\/proposals\/[^/]+\/evaluation\/?(\?|$)/.test(pathOnlyForBody)
3049 ) {
3050 console.warn(
3051 '[gateway] canister returned 404 for POST …/evaluation. If the body is {"error":"Not found","code":"NOT_FOUND"}, the hub canister on mainnet likely predates the evaluation route or HTTP upgrade for it — redeploy `hub` from this repo (`hub/icp/README.md` §ICP HTTP gateway behavior).',
3052 );
3053 }
3054 let responseBody = body;
3055 if (
3056 BRIDGE_URL &&
3057 req.method === 'POST' &&
3058 PROPOSAL_APPROVE_OR_DISCARD_RE.test(pathOnlyForBody) &&
3059 /\/approve\/?$/.test(pathOnlyForBody) &&
3060 upstream.status >= 200 &&
3061 upstream.status < 300
3062 ) {
3063 try {
3064 const applyOutcome = await maybeApplyHostedDelegationAfterApprove({
3065 method: req.method,
3066 pathOnly: pathOnlyForBody,
3067 upstreamStatus: upstream.status,
3068 canisterUrl: CANISTER_URL,
3069 bridgeUrl: BRIDGE_URL,
3070 authorization: req.headers.authorization,
3071 vaultId,
3072 effectiveUserId: effective,
3073 actorUserId: uid,
3074 canisterAuthHeaders,
3075 });
3076 responseBody = mergeDelegationApplyIntoApproveResponse(body, applyOutcome);
3077 if (applyOutcome && !applyOutcome.applied) {
3078 console.error('[gateway] delegation index apply after approve failed:', applyOutcome.error);
3079 }
3080 } catch (e) {
3081 console.error('[gateway] delegation apply after approve (non-fatal):', e?.message || String(e));
3082 }
3083 }
3084 const hop = filterUpstreamResponseHeadersForDecodedBody(upstream.headers.entries()).filter(
3085 ([k]) => !['cache-control', 'etag', 'last-modified'].includes(k.toLowerCase()),
3086 );
3087 res.status(upstream.status).set(Object.fromEntries(hop));
3088 res.set('Cache-Control', 'private, no-store, must-revalidate');
3089 res.send(responseBody);
3090 } catch (e) {
3091 console.error('Gateway proxy error:', e.message);
3092 res.status(502).json({ error: 'Bad Gateway', code: 'BAD_GATEWAY' });
3093 }
3094 }
3095
3096 // Bulk metadata by effective project slug (canister orchestration; not a canister route)
3097 app.post('/api/v1/notes/delete-by-project', async (req, res) => {
3098 if (!(await runBillingGate(req, res, getUserId))) return;
3099 return metadataBulkHandlers.deleteByProject(req, res);
3100 });
3101 app.post('/api/v1/notes/rename-project', async (req, res) => {
3102 if (!(await runBillingGate(req, res, getUserId))) return;
3103 return metadataBulkHandlers.renameProject(req, res);
3104 });
3105
3106 /** Hosted Enrich: gateway runs LLM and POSTs to canister (not proxied as opaque POST). */
3107 app.post('/api/v1/proposals/:proposalId/enrich', async (req, res) => {
3108 // Express 4 does not auto-catch async route handler exceptions; wrap everything so a
3109 // rejected promise never leaves the request hanging until Netlify's Lambda timeout.
3110 try {
3111 if (!(await runBillingGate(req, res, getUserId))) return;
3112 const uid = getUserId(req);
3113 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
3114 const proposalId = req.params.proposalId;
3115 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
3116 const hctx = await getHostedAccessContext(req);
3117 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
3118 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
3119 }
3120 const { role } = await resolveHostedActorRole(req, hctx);
3121 if (role === 'viewer') {
3122 return res.status(403).json({ error: 'This action requires a different role.', code: 'FORBIDDEN' });
3123 }
3124 const effective =
3125 hctx && typeof hctx.effective_canister_user_id === 'string' && hctx.effective_canister_user_id
3126 ? hctx.effective_canister_user_id
3127 : uid;
3128 const llmPrefs = await loadHostedProposalLlmPrefs();
3129 const enrichEnabled = effectiveHostedEnrich(llmPrefs);
3130 // Diagnostic: log which LLM provider will be used (visible in Netlify function logs).
3131 console.log(
3132 '[gateway/enrich] proposalId=%s enrichEnabled=%s provider=%s',
3133 proposalId,
3134 enrichEnabled,
3135 process.env.OPENAI_API_KEY ? 'openai' : process.env.ANTHROPIC_API_KEY ? 'anthropic' : 'ollama(NO KEY)',
3136 );
3137 const out = await runHostedProposalEnrichAndPost({
3138 canisterUrl: CANISTER_URL,
3139 effectiveUserId: effective,
3140 actorUserId: uid,
3141 vaultId,
3142 proposalId,
3143 enrichEnabled,
3144 });
3145 if (!out.ok) {
3146 if (out.status === 404 && out.code === 'NOT_FOUND') {
3147 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
3148 }
3149 if (out.status === 404) {
3150 return res.status(404).json({ error: 'Proposal not found', code: 'NOT_FOUND' });
3151 }
3152 if (out.status === 400) {
3153 return res.status(400).json({ error: out.detail || 'Bad request', code: out.code || 'BAD_REQUEST' });
3154 }
3155 return res.status(out.status || 500).json({
3156 error: out.detail || out.code || 'Enrich failed',
3157 code: out.code || 'RUNTIME_ERROR',
3158 });
3159 }
3160 // Return immediately — the frontend calls openProposal() + loadProposals() after this
3161 // which re-fetches the updated proposal. Eliminating the extra canister GET here removes
3162 // one full ICP round trip (~1–3 s) from the critical path and prevents Netlify timeout.
3163 return res.set('Cache-Control', 'private, no-store, must-revalidate').json({ ok: true });
3164 } catch (e) {
3165 console.error('[gateway/enrich] unhandled exception:', e?.stack || e?.message || e);
3166 if (!res.headersSent) {
3167 res.status(500).json({ error: e?.message || 'Internal error', code: 'INTERNAL_ERROR' });
3168 }
3169 }
3170 });
3171
3172 // ---------------------------------------------------------------------------
3173 // AIR Improvement D — built-in attestation endpoint
3174 // ---------------------------------------------------------------------------
3175
3176 app.post('/api/v1/attest', async (req, res) => {
3177 const uid = getUserId(req);
3178 if (!uid) {
3179 return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
3180 }
3181 if (!isAttestationConfigured()) {
3182 return res.status(503).json({
3183 error: 'Attestation service not configured (ATTESTATION_SECRET missing or too short).',
3184 code: 'NOT_CONFIGURED',
3185 });
3186 }
3187 const body = req.body && typeof req.body === 'object' ? req.body : {};
3188 const action = typeof body.action === 'string' ? body.action.trim() : '';
3189 if (!action) {
3190 return res.status(400).json({ error: 'action is required', code: 'BAD_REQUEST' });
3191 }
3192 const notePath = typeof body.path === 'string' ? body.path : '';
3193 const contentHash = typeof body.content_hash === 'string' ? body.content_hash : null;
3194 try {
3195 const result = await createAttestation(action, notePath, contentHash);
3196 return res.json(result);
3197 } catch (e) {
3198 console.error('[gateway] POST /api/v1/attest error:', e?.message || e);
3199 return res.status(500).json({ error: 'Attestation failed', code: 'INTERNAL_ERROR' });
3200 }
3201 });
3202
3203 app.get('/api/v1/attest/:id', async (req, res) => {
3204 if (!isAttestationConfigured()) {
3205 return res.status(503).json({
3206 error: 'Attestation service not configured (ATTESTATION_SECRET missing or too short).',
3207 code: 'NOT_CONFIGURED',
3208 });
3209 }
3210 const id = req.params.id;
3211 if (!id || !id.startsWith('air-')) {
3212 return res.status(400).json({ error: 'Invalid attestation id format', code: 'BAD_REQUEST' });
3213 }
3214 try {
3215 const result = await verifyAttestation(id);
3216 if (!result.record) {
3217 return res.status(404).json({ error: 'Attestation not found', code: 'NOT_FOUND' });
3218 }
3219 return res.json(result);
3220 } catch (e) {
3221 console.error('[gateway] GET /api/v1/attest/:id error:', e?.message || e);
3222 return res.status(500).json({ error: 'Verification failed', code: 'INTERNAL_ERROR' });
3223 }
3224 });
3225
3226 // ---------------------------------------------------------------------------
3227 // AIR Improvement E — ICP blockchain anchor verification + reconciliation
3228 // ---------------------------------------------------------------------------
3229
3230 app.get('/api/v1/attest/:id/verify', async (req, res) => {
3231 if (!isAttestationConfigured()) {
3232 return res.status(503).json({
3233 error: 'Attestation service not configured (ATTESTATION_SECRET missing or too short).',
3234 code: 'NOT_CONFIGURED',
3235 });
3236 }
3237 const id = req.params.id;
3238 if (!id || !id.startsWith('air-')) {
3239 return res.status(400).json({ error: 'Invalid attestation id format', code: 'BAD_REQUEST' });
3240 }
3241 try {
3242 const result = await verifyWithIcp(id);
3243 if (!result.sources.blobs.found && !result.sources.icp.found) {
3244 return res.status(404).json({ error: 'Attestation not found', code: 'NOT_FOUND', ...result });
3245 }
3246 return res.json(result);
3247 } catch (e) {
3248 console.error('[gateway] GET /api/v1/attest/:id/verify error:', e?.message || e);
3249 return res.status(500).json({ error: 'Verification failed', code: 'INTERNAL_ERROR' });
3250 }
3251 });
3252
3253 app.post('/api/v1/attest/anchor-pending', requireAdmin, async (req, res) => {
3254 if (!isAttestationConfigured()) {
3255 return res.status(503).json({
3256 error: 'Attestation service not configured (ATTESTATION_SECRET missing or too short).',
3257 code: 'NOT_CONFIGURED',
3258 });
3259 }
3260 const body = req.body && typeof req.body === 'object' ? req.body : {};
3261 const ids = Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === 'string' && x.startsWith('air-')) : [];
3262 if (ids.length === 0) {
3263 return res.status(400).json({ error: 'ids array with air-* entries is required', code: 'BAD_REQUEST' });
3264 }
3265 if (ids.length > 100) {
3266 return res.status(400).json({ error: 'Maximum 100 IDs per batch', code: 'BAD_REQUEST' });
3267 }
3268 try {
3269 const result = await anchorPendingAttestations(ids);
3270 return res.json(result);
3271 } catch (e) {
3272 console.error('[gateway] POST /api/v1/attest/anchor-pending error:', e?.message || e);
3273 return res.status(500).json({ error: 'Anchor failed', code: 'INTERNAL_ERROR' });
3274 }
3275 });
3276
3277 /**
3278 * Hosted: single-note export for Hub UI (POST /api/v1/export). Self-hosted Node Hub implements
3279 * this with filesystem; the ICP canister only supports GET /api/v1/export (full vault JSON), so
3280 * POST was returning 404 from the canister. We fetch the note and build the same download payload
3281 * as lib/export.mjs.
3282 */
3283 app.post('/api/v1/export', async (req, res) => {
3284 if (!CANISTER_URL) {
3285 return res.status(503).json({ error: 'Hosted export not configured', code: 'SERVICE_UNAVAILABLE' });
3286 }
3287 if (!(await runBillingGate(req, res, getUserId, { getNoteCount: getNoteCountForUser }))) return;
3288 const uid = getUserId(req);
3289 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
3290 const body = req.body && typeof req.body === 'object' ? req.body : {};
3291 const notePath = typeof body.path === 'string' ? body.path.replace(/\\/g, '/').trim() : '';
3292 const fmt = body.format === 'html' ? 'html' : 'md';
3293 if (!notePath || notePath.includes('..') || notePath.startsWith('/')) {
3294 return res.status(400).json({ error: 'path required', code: 'BAD_REQUEST' });
3295 }
3296 const vaultId = String(req.headers['x-vault-id'] || 'default').trim() || 'default';
3297 const hctx = await getHostedAccessContext(req);
3298 if (hctx && Array.isArray(hctx.allowed_vault_ids) && !hctx.allowed_vault_ids.includes(vaultId)) {
3299 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
3300 }
3301 const effective =
3302 hctx && typeof hctx.effective_canister_user_id === 'string' && hctx.effective_canister_user_id
3303 ? hctx.effective_canister_user_id
3304 : uid;
3305 const enc = notePath.split('/').map(encodeURIComponent).join('/');
3306 const url = `${CANISTER_URL}/api/v1/notes/${enc}`;
3307 let upstream;
3308 try {
3309 upstream = await fetch(url, {
3310 method: 'GET',
3311 headers: {
3312 Accept: 'application/json',
3313 'x-user-id': effective,
3314 'x-actor-id': uid,
3315 'x-vault-id': vaultId,
3316 ...canisterAuthHeaders(),
3317 },
3318 });
3319 } catch (e) {
3320 console.error('[gateway] export fetch note:', e?.message || e);
3321 return res.status(502).json({ error: 'Bad Gateway', code: 'BAD_GATEWAY' });
3322 }
3323 const text = await upstream.text();
3324 if (upstream.status === 404) {
3325 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
3326 }
3327 if (!upstream.ok) {
3328 return res.status(upstream.status).type('application/json').send(text);
3329 }
3330 let note;
3331 try {
3332 note = JSON.parse(text);
3333 } catch {
3334 return res.status(502).json({ error: 'Invalid note response', code: 'BAD_GATEWAY' });
3335 }
3336 const scope = scopeActiveForGateway(hctx) ? hctx.scope : null;
3337 if (scope) {
3338 const withProj = {
3339 path: note.path,
3340 project: materializeListFrontmatter(note.frontmatter).project ?? null,
3341 };
3342 const filtered = applyScopeFilterToNotes([withProj], scope);
3343 if (filtered.length === 0) {
3344 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
3345 }
3346 }
3347 const fm = materializeListFrontmatter(note.frontmatter);
3348 const { content, filename } = exportNoteRecordToContent(
3349 { body: note.body != null ? String(note.body) : '', frontmatter: fm },
3350 note.path || notePath,
3351 { format: fmt },
3352 );
3353 res.set('Cache-Control', 'private, no-store, must-revalidate');
3354 return res.json({ content, filename });
3355 });
3356
3357 /**
3358 * Cross-vault copy/move (hosted gateway): GET note from canister vault A, POST to vault B, optional DELETE on A.
3359 * Conflicts: if `path` already exists in the target vault, the write **overwrites** (same as POST /notes).
3360 * After success, triggers bridge **Re-index** for the target vault and, when moving, the source vault (fire-and-forget).
3361 */
3362 app.post('/api/v1/notes/copy', async (req, res) => {
3363 if (!CANISTER_URL) {
3364 return res.status(503).json({ error: 'Hosted copy not configured', code: 'SERVICE_UNAVAILABLE' });
3365 }
3366 if (!(await runBillingGate(req, res, getUserId, { getNoteCount: getNoteCountForUser }))) return;
3367 const uid = getUserId(req);
3368 if (!uid) return res.status(401).json({ error: 'Unauthorized', code: 'UNAUTHORIZED' });
3369 const authHeader = req.headers.authorization || '';
3370 const body = req.body && typeof req.body === 'object' ? req.body : {};
3371 const fromVault = typeof body.from_vault_id === 'string' ? body.from_vault_id.replace(/\\/g, '/').trim() : '';
3372 const toVault = typeof body.to_vault_id === 'string' ? body.to_vault_id.replace(/\\/g, '/').trim() : '';
3373 const notePath = typeof body.path === 'string' ? body.path.replace(/\\/g, '/').trim() : '';
3374 const deleteSource = body.delete_source === true;
3375 if (!fromVault || !toVault || !notePath || notePath.includes('..') || notePath.startsWith('/')) {
3376 return res.status(400).json({
3377 error: 'from_vault_id, to_vault_id, and path are required (vault-relative path)',
3378 code: 'BAD_REQUEST',
3379 });
3380 }
3381 if (fromVault === toVault) {
3382 return res.status(400).json({ error: 'from_vault_id and to_vault_id must differ', code: 'BAD_REQUEST' });
3383 }
3384 /** @type {Record<string, unknown>|null} */
3385 let hctxFrom = null;
3386 if (BRIDGE_URL) {
3387 hctxFrom = await fetchHostedAccessContextForVault(authHeader, fromVault);
3388 if (!hctxFrom) {
3389 return res.status(403).json({ error: 'Hosted workspace context unavailable.', code: 'FORBIDDEN' });
3390 }
3391 if (Array.isArray(hctxFrom.allowed_vault_ids)) {
3392 if (!hctxFrom.allowed_vault_ids.includes(fromVault) || !hctxFrom.allowed_vault_ids.includes(toVault)) {
3393 return res.status(403).json({ error: 'Access to this vault is not allowed.', code: 'FORBIDDEN' });
3394 }
3395 }
3396 }
3397 const { role } = await resolveHostedActorRole(req, hctxFrom);
3398 if (role === 'viewer') {
3399 return res.status(403).json({ error: 'This action requires editor or admin.', code: 'FORBIDDEN' });
3400 }
3401 const effective =
3402 hctxFrom && typeof hctxFrom.effective_canister_user_id === 'string' && hctxFrom.effective_canister_user_id
3403 ? hctxFrom.effective_canister_user_id
3404 : uid;
3405 const enc = notePath.split('/').map(encodeURIComponent).join('/');
3406 const getUrl = `${CANISTER_URL}/api/v1/notes/${enc}`;
3407 let upstream;
3408 try {
3409 upstream = await fetch(getUrl, {
3410 method: 'GET',
3411 headers: {
3412 Accept: 'application/json',
3413 'x-user-id': effective,
3414 'x-actor-id': uid,
3415 'x-vault-id': fromVault,
3416 ...canisterAuthHeaders(),
3417 },
3418 });
3419 } catch (e) {
3420 console.error('[gateway] notes/copy fetch source:', e?.message || e);
3421 return res.status(502).json({ error: 'Bad Gateway', code: 'BAD_GATEWAY' });
3422 }
3423 const getText = await upstream.text();
3424 if (upstream.status === 404) {
3425 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
3426 }
3427 if (!upstream.ok) {
3428 return res.status(upstream.status).type('application/json').send(getText);
3429 }
3430 let note;
3431 try {
3432 note = JSON.parse(getText);
3433 } catch {
3434 return res.status(502).json({ error: 'Invalid note response', code: 'BAD_GATEWAY' });
3435 }
3436 const scope = scopeActiveForGateway(hctxFrom) ? hctxFrom.scope : null;
3437 if (scope) {
3438 const withProj = {
3439 path: note.path,
3440 project: materializeListFrontmatter(note.frontmatter).project ?? null,
3441 };
3442 const filtered = applyScopeFilterToNotes([withProj], scope);
3443 if (filtered.length === 0) {
3444 return res.status(404).json({ error: 'Not found', code: 'NOT_FOUND' });
3445 }
3446 }
3447 const outPath = note.path || notePath;
3448 let fmRaw = note.frontmatter;
3449 if (typeof fmRaw === 'string') {
3450 try {
3451 fmRaw = fmRaw.trim() ? JSON.parse(fmRaw) : {};
3452 } catch {
3453 fmRaw = {};
3454 }
3455 }
3456 if (!fmRaw || typeof fmRaw !== 'object' || Array.isArray(fmRaw)) {
3457 fmRaw = {};
3458 }
3459 let gatewayAirId = null;
3460 if (process.env.KNOWTATION_AIR_ENDPOINT) {
3461 try {
3462 const { attestBeforeWrite: gwAttest } = await import('../../lib/air.mjs');
3463 const airId = await gwAttest(
3464 { air: { enabled: true, required: false, endpoint: process.env.KNOWTATION_AIR_ENDPOINT } },
3465 outPath,
3466 );
3467 if (airId && airId !== 'air-placeholder-write') {
3468 gatewayAirId = airId;
3469 }
3470 } catch (e) {
3471 console.error('[gateway] AIR attestation (copy, non-fatal):', e?.message || String(e));
3472 }
3473 }
3474 const postBody = mergeHostedNoteBodyForCanister(
3475 {
3476 path: outPath,
3477 body: note.body != null ? String(note.body) : '',
3478 frontmatter: fmRaw,
3479 },
3480 uid,
3481 gatewayAirId,
3482 );
3483 const postHeaders = {
3484 'Content-Type': 'application/json',
3485 Accept: 'application/json',
3486 host: new URL(CANISTER_URL).host,
3487 'x-user-id': effective,
3488 'x-actor-id': uid,
3489 'x-vault-id': toVault,
3490 ...canisterAuthHeaders(),
3491 };
3492 const postOpts = { method: 'POST', headers: postHeaders, body: JSON.stringify(postBody) };
3493 stripStaleOutboundBodyHeaders(postHeaders);
3494 let postUpstream;
3495 try {
3496 postUpstream = await fetch(`${CANISTER_URL}/api/v1/notes`, postOpts);
3497 } catch (e) {
3498 console.error('[gateway] notes/copy post target:', e?.message || e);
3499 return res.status(502).json({ error: 'Bad Gateway', code: 'BAD_GATEWAY' });
3500 }
3501 const postText = await postUpstream.text();
3502 if (!postUpstream.ok) {
3503 return res.status(postUpstream.status).type('application/json').send(postText);
3504 }
3505 if (deleteSource) {
3506 let delUpstream;
3507 try {
3508 delUpstream = await fetch(getUrl, {
3509 method: 'DELETE',
3510 headers: {
3511 Accept: 'application/json',
3512 'x-user-id': effective,
3513 'x-actor-id': uid,
3514 'x-vault-id': fromVault,
3515 ...canisterAuthHeaders(),
3516 },
3517 });
3518 } catch (e) {
3519 console.error('[gateway] notes/copy delete source:', e?.message || e);
3520 return res.status(502).json({
3521 error:
3522 'Note was copied to the target vault but deleting the source failed. Remove the duplicate from the target vault if you retry.',
3523 code: 'DELETE_FAILED',
3524 });
3525 }
3526 const delText = await delUpstream.text();
3527 if (!delUpstream.ok && delUpstream.status !== 404) {
3528 return res.status(delUpstream.status).json({
3529 error: 'Note was copied to the target vault but deleting the source failed.',
3530 code: 'DELETE_FAILED',
3531 detail: typeof delText === 'string' ? delText.slice(0, 500) : '',
3532 });
3533 }
3534 }
3535 const reindexVaults = deleteSource ? [toVault, fromVault] : [toVault];
3536 void (async () => {
3537 if (!BRIDGE_URL) return;
3538 for (const vid of reindexVaults) {
3539 try {
3540 const idxRes = await fetch(BRIDGE_URL + '/api/v1/index', {
3541 method: 'POST',
3542 headers: {
3543 Authorization: authHeader,
3544 Accept: 'application/json',
3545 'Content-Type': 'application/json',
3546 'X-Vault-Id': String(vid || 'default').trim() || 'default',
3547 },
3548 body: '{}',
3549 });
3550 const idxText = await idxRes.text();
3551 await recordIndexingTokensAfterBridgeIndex(uid, idxRes.status, idxText);
3552 } catch (e) {
3553 console.warn('[gateway] notes/copy reindex:', e?.message || e);
3554 }
3555 }
3556 })();
3557 res.set('Cache-Control', 'private, no-store, must-revalidate');
3558 return res.json({
3559 ok: true,
3560 path: outPath,
3561 from_vault_id: fromVault,
3562 to_vault_id: toVault,
3563 moved: deleteSource,
3564 });
3565 });
3566
3567 app.use('/api/v1', async (req, res) => {
3568 if (req.method === 'OPTIONS') return res.status(204).end();
3569 if (!(await runBillingGate(req, res, getUserId, { getNoteCount: getNoteCountForUser }))) return;
3570 return proxyToCanister(req, res);
3571 });
3572
3573 // Health from canister if UI calls /health via same origin
3574 app.get('/api/v1/health-canister', async (_req, res) => {
3575 try {
3576 const r = await fetch(CANISTER_URL + '/health');
3577 const body = await r.text();
3578 res.status(r.status).set('Content-Type', 'application/json').send(body);
3579 } catch (e) {
3580 res.status(502).json({ ok: false, error: e.message });
3581 }
3582 });
3583
3584 app.use((err, req, res, next) => {
3585 if (res.headersSent) return next(err);
3586 console.error('[gateway] unhandled error:', err?.stack || err?.message || err);
3587 const status =
3588 typeof err.status === 'number' && err.status >= 400 && err.status < 600
3589 ? err.status
3590 : typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600
3591 ? err.statusCode
3592 : 500;
3593 res.status(status).json({
3594 error: err.message || 'Internal error',
3595 code: err.code || 'INTERNAL_ERROR',
3596 });
3597 });
3598
3599 // When running on Netlify, the app is imported by netlify/functions/gateway.mjs and not started here.
3600 if (!process.env.NETLIFY) {
3601 if (!CANISTER_URL) {
3602 console.error('Gateway: CANISTER_URL is required (e.g. https://<canister-id>.ic0.app)');
3603 process.exit(1);
3604 }
3605 if (!SESSION_SECRET) {
3606 console.error('Gateway: SESSION_SECRET or HUB_JWT_SECRET is required');
3607 process.exit(1);
3608 }
3609 if (!CANISTER_AUTH_SECRET && CANISTER_URL) {
3610 console.warn(
3611 '\x1b[33m[SECURITY] CANISTER_AUTH_SECRET is not set. ' +
3612 'The canister will not verify gateway identity. ' +
3613 'Set CANISTER_AUTH_SECRET and call admin_set_gateway_auth_secret on the canister before public launch.\x1b[0m'
3614 );
3615 }
3616 if (CANISTER_URL && !billingEnforced()) {
3617 console.warn(
3618 '\x1b[33m[SECURITY] BILLING_ENFORCE is not set to true. ' +
3619 'Billing limits (storage cap, usage gates) are not enforced. ' +
3620 'Set BILLING_ENFORCE=true before public launch on hosted deployment.\x1b[0m'
3621 );
3622 }
3623 app.listen(PORT, () => {
3624 console.log(`Knowtation Hub Gateway listening on http://localhost:${PORT}`);
3625 console.log(' Canister: ' + CANISTER_URL);
3626 console.log(' UI origin: ' + HUB_UI_ORIGIN);
3627 console.log(' Login: GET /auth/login?provider=google|github');
3628 });
3629 }
3630
3631 export { app };
File History 1 commit
sha256:c541f54879f8110bb25bb9786cdb8ff7a4aec19f9f2a2789a55bc74e6f7fe095 fix(7C-L1c): persist hosted delegation indexes in Netlify Blobs Human minor 32 days ago