2025-09-21 19:35:41 +01:00
|
|
|
import 'dotenv/config';
|
|
|
|
|
|
2026-05-21 17:18:08 +01:00
|
|
|
import * as Sentry from '@sentry/node';
|
2026-05-20 14:32:39 +01:00
|
|
|
import { consumeHandoffPayload, storeHandoffPayload } from '@api/utils/redis/oauth-handoff';
|
2026-05-20 09:20:23 +01:00
|
|
|
import { isPublicCorsPath, sessionCors } from '@api/middlewares/cors';
|
2026-05-20 14:32:39 +01:00
|
|
|
import { randomBytes } from 'crypto';
|
2025-11-24 01:00:50 +01:00
|
|
|
|
2026-05-20 09:20:23 +01:00
|
|
|
import { API_SERVER_URL } from '@api/constants';
|
2026-07-11 06:17:26 +01:00
|
|
|
import {
|
|
|
|
|
resolveOAuthBrowserOrigin,
|
|
|
|
|
rewriteAuthRequestUrl,
|
|
|
|
|
rewriteOAuthProxyCallbackLocation,
|
|
|
|
|
shouldRewriteOAuthProxyCallbackLocation
|
|
|
|
|
} from '@api/utils/oauth-proxy-redirect';
|
2026-03-09 11:18:22 +01:00
|
|
|
import { Hono } from '@api/utils/hono';
|
2026-06-14 09:56:30 +01:00
|
|
|
import { ErrorCodes } from '@api/utils/errors';
|
2025-12-02 15:27:41 +01:00
|
|
|
import { accountRouter } from '@api/routes/account';
|
2026-05-20 09:20:23 +01:00
|
|
|
import { agentRouter } from '@api/routes/agent';
|
2026-03-09 11:18:22 +01:00
|
|
|
import { auth } from '@cio/db/auth';
|
|
|
|
|
import { communityRouter } from '@api/routes/community';
|
|
|
|
|
import { courseRouter } from '@api/routes/course';
|
2025-12-02 15:27:41 +01:00
|
|
|
import { dashAnalyticsRouter } from '@api/routes/dash';
|
2026-03-09 11:18:22 +01:00
|
|
|
import { domainRouter } from '@api/routes/domain/domain';
|
2026-05-20 09:20:23 +01:00
|
|
|
import { internalRouter } from '@api/routes/internal';
|
2026-03-09 11:18:22 +01:00
|
|
|
import { inviteRouter } from '@api/routes/invite';
|
2026-05-20 09:20:23 +01:00
|
|
|
import { jobsRouter } from '@api/routes/jobs';
|
|
|
|
|
import { licenseRouter } from '@api/routes/license';
|
2026-03-09 11:18:22 +01:00
|
|
|
import { logger } from 'hono/logger';
|
|
|
|
|
// ROUTES
|
2026-06-07 18:43:05 +01:00
|
|
|
import { hlsRouter } from '@api/routes/hls';
|
2026-03-09 11:18:22 +01:00
|
|
|
import { mailRouter } from '@api/routes/mail';
|
2025-12-02 09:54:38 +01:00
|
|
|
import { mediaRouter } from '@api/routes/media';
|
2026-06-07 18:43:05 +01:00
|
|
|
import { transcriptsRouter } from '@api/routes/transcripts';
|
2026-05-20 09:20:23 +01:00
|
|
|
import { mountQueueDashboard } from '@api/routes/admin/queues';
|
2025-11-24 01:00:50 +01:00
|
|
|
import { onboardingRouter } from '@api/routes/onboarding';
|
|
|
|
|
import { organizationRouter } from '@api/routes/organization';
|
2026-03-09 11:18:22 +01:00
|
|
|
import { organizationSsoRouter } from '@api/routes/organization/sso';
|
|
|
|
|
import { organizationTokenAuthRouter } from '@api/routes/organization/token-auth';
|
|
|
|
|
import { prettyJSON } from 'hono/pretty-json';
|
2026-07-02 12:10:31 +01:00
|
|
|
import { cohortRouter } from '@api/routes/cohort';
|
2026-07-07 22:15:11 +01:00
|
|
|
import { publicCourseRouter, orgSiteOgRouter } from '@api/routes/org-site';
|
2026-05-20 09:20:23 +01:00
|
|
|
import { publicWidgetsRouter } from '@api/routes/widgets';
|
2026-03-09 11:18:22 +01:00
|
|
|
import rateLimiter from '@api/middlewares/rate-limiter';
|
|
|
|
|
import { secureHeaders } from 'hono/secure-headers';
|
|
|
|
|
import { signupGuard } from '@api/middlewares/signup-guard';
|
2026-05-20 09:20:23 +01:00
|
|
|
import { ssoDiscoveryRouter } from '@api/routes/sso/discovery';
|
2026-03-09 11:18:22 +01:00
|
|
|
import { unsplashRouter } from '@api/routes/unsplash/unsplash';
|
2026-05-20 09:20:23 +01:00
|
|
|
import { v1Router } from '@api/routes/v1';
|
2025-09-21 19:35:41 +01:00
|
|
|
|
|
|
|
|
// Create Hono app with chaining for RPC support
|
|
|
|
|
export const app = new Hono()
|
|
|
|
|
// Middleware
|
|
|
|
|
.use('*', logger())
|
|
|
|
|
.use('*', prettyJSON())
|
2026-06-07 18:43:05 +01:00
|
|
|
// `Cross-Origin-Resource-Policy: same-origin` (Hono's default) blocks the
|
|
|
|
|
// dashboard from embedding api-served media (e.g. HLS segments via
|
|
|
|
|
// `<video>`) when the dashboard and api live on different origins in
|
|
|
|
|
// local dev / self-hosted. We're an API server — every response is
|
|
|
|
|
// designed for cross-origin consumption, so the right value is
|
|
|
|
|
// `cross-origin`. CORS still gates which origins can read the bytes.
|
|
|
|
|
.use('*', secureHeaders({ crossOriginResourcePolicy: 'cross-origin' }))
|
2026-05-19 10:24:18 +01:00
|
|
|
.use('*', async (c, next) => {
|
2026-05-19 11:23:07 +01:00
|
|
|
if (isPublicCorsPath(c.req.path)) return next();
|
2026-05-19 10:24:18 +01:00
|
|
|
|
|
|
|
|
return sessionCors(c, next);
|
|
|
|
|
})
|
2025-11-24 01:00:50 +01:00
|
|
|
.use('*', async (c, next) => {
|
2026-05-19 11:23:07 +01:00
|
|
|
if (isPublicCorsPath(c.req.path)) {
|
2026-05-19 10:24:18 +01:00
|
|
|
c.set('user', null);
|
|
|
|
|
c.set('session', null);
|
2026-05-20 15:58:43 +01:00
|
|
|
c.set('orgRoles', {});
|
2026-05-19 10:24:18 +01:00
|
|
|
|
|
|
|
|
return next();
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-19 08:15:35 +01:00
|
|
|
let session: Awaited<ReturnType<typeof auth.api.getSession>> | null = null;
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
session = await auth.api.getSession({ headers: c.req.raw.headers });
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('auth.api.getSession error:', error);
|
|
|
|
|
}
|
2025-11-24 01:00:50 +01:00
|
|
|
|
|
|
|
|
if (!session) {
|
|
|
|
|
c.set('user', null);
|
|
|
|
|
c.set('session', null);
|
2026-05-20 15:58:43 +01:00
|
|
|
c.set('orgRoles', {});
|
2025-11-24 01:00:50 +01:00
|
|
|
await next();
|
|
|
|
|
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.set('user', session.user);
|
|
|
|
|
c.set('session', session.session);
|
2026-05-20 15:58:43 +01:00
|
|
|
c.set('orgRoles', (session as { orgRoles?: Record<string, number> }).orgRoles ?? {});
|
2026-05-21 17:18:08 +01:00
|
|
|
|
|
|
|
|
Sentry.setUser({
|
|
|
|
|
id: session.user.id,
|
|
|
|
|
...(session.user.email && { email: session.user.email }),
|
|
|
|
|
...(session.user.name && { username: session.user.name })
|
|
|
|
|
});
|
|
|
|
|
|
2025-11-24 01:00:50 +01:00
|
|
|
await next();
|
|
|
|
|
})
|
2026-05-27 11:44:57 +01:00
|
|
|
.use('*', rateLimiter)
|
2025-09-21 19:35:41 +01:00
|
|
|
|
|
|
|
|
// Routes
|
|
|
|
|
.get('/', (c) =>
|
|
|
|
|
c.json({
|
2025-11-24 01:00:50 +01:00
|
|
|
message: `"Welcome to Classroomio.com API - docs are at ${API_SERVER_URL}/docs"`
|
2025-09-21 19:35:41 +01:00
|
|
|
})
|
|
|
|
|
)
|
2026-03-09 11:18:22 +01:00
|
|
|
.use('/api/auth/sign-up/*', signupGuard)
|
2026-05-20 09:20:23 +01:00
|
|
|
.on(['POST', 'GET'], '/api/auth/*', async (c) => {
|
2026-05-20 08:32:56 +01:00
|
|
|
// Behind the Cloudflare Worker proxy the raw Request URL points at the
|
|
|
|
|
// upstream `.onrender.com` host. Better Auth (and the oauth-proxy plugin)
|
|
|
|
|
// need the original tenant/admin host to construct correct OAuth callback
|
|
|
|
|
// URLs and to decide whether to engage the proxy flow. Rebuild from
|
|
|
|
|
// X-Forwarded-Host / X-Forwarded-Proto when present.
|
|
|
|
|
let request = c.req.raw;
|
|
|
|
|
const fwdHost = c.req.header('x-forwarded-host');
|
|
|
|
|
const fwdProto = c.req.header('x-forwarded-proto');
|
2026-07-11 06:17:26 +01:00
|
|
|
const browserOrigin = resolveOAuthBrowserOrigin({
|
|
|
|
|
forwardedHost: fwdHost,
|
|
|
|
|
forwardedProto: fwdProto
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-20 08:32:56 +01:00
|
|
|
if (fwdHost) {
|
2026-07-11 06:17:26 +01:00
|
|
|
request = rewriteAuthRequestUrl(request, {
|
|
|
|
|
forwardedHost: fwdHost,
|
|
|
|
|
forwardedProto: fwdProto
|
|
|
|
|
});
|
2026-05-20 08:32:56 +01:00
|
|
|
}
|
2026-05-20 09:20:23 +01:00
|
|
|
|
2026-05-20 14:32:39 +01:00
|
|
|
// Inbound: if the browser is hitting `/oauth-proxy-callback?token=…`
|
|
|
|
|
// (our short handoff token), swap the token back to the original
|
|
|
|
|
// encrypted `cookies=…` payload before handing the request to Better
|
|
|
|
|
// Auth — the oauth-proxy plugin expects the cookies query param.
|
|
|
|
|
{
|
|
|
|
|
const inUrl = new URL(request.url);
|
|
|
|
|
if (inUrl.pathname.endsWith('/oauth-proxy-callback')) {
|
|
|
|
|
const token = inUrl.searchParams.get('token');
|
|
|
|
|
if (token && !inUrl.searchParams.has('cookies')) {
|
|
|
|
|
const cookies = await consumeHandoffPayload(token);
|
|
|
|
|
if (cookies) {
|
|
|
|
|
inUrl.searchParams.set('cookies', cookies);
|
|
|
|
|
inUrl.searchParams.delete('token');
|
|
|
|
|
request = new Request(inUrl, request);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-14 09:56:30 +01:00
|
|
|
// Check if the social auth provider is configured before forwarding
|
|
|
|
|
// to Better Auth, which returns a confusing generic 500 otherwise.
|
|
|
|
|
if (c.req.method === 'POST' && c.req.path === '/api/auth/sign-in/social') {
|
|
|
|
|
if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
|
|
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
|
|
|
|
error: "This auth provider isn't enabled.",
|
|
|
|
|
code: ErrorCodes.SOCIAL_AUTH_NOT_ENABLED
|
|
|
|
|
},
|
|
|
|
|
400
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-20 09:20:23 +01:00
|
|
|
const response = await auth.handler(request);
|
|
|
|
|
|
2026-05-20 14:32:39 +01:00
|
|
|
// Outbound: if the OAuth callback redirected to
|
|
|
|
|
// `/oauth-proxy-callback?cookies=…<huge>`, stash the cookies payload
|
|
|
|
|
// in Redis under a short token and rewrite the Location header so the
|
|
|
|
|
// browser only carries the token across hosts. The companion swap on
|
|
|
|
|
// the inbound side restores the cookies before Better Auth's plugin
|
|
|
|
|
// tries to decrypt them. Without this, the encrypted cookies blob
|
|
|
|
|
// pushes the Location header past Render's response size ceiling and
|
|
|
|
|
// the redirect silently never reaches the browser.
|
|
|
|
|
if (response.status >= 300 && response.status < 400) {
|
2026-07-11 06:17:26 +01:00
|
|
|
let location = response.headers.get('location');
|
|
|
|
|
|
|
|
|
|
if (location?.includes('/oauth-proxy-callback') && location.includes('cookies=')) {
|
2026-05-20 14:32:39 +01:00
|
|
|
try {
|
|
|
|
|
const outUrl = new URL(location);
|
|
|
|
|
const cookies = outUrl.searchParams.get('cookies');
|
|
|
|
|
if (cookies && cookies.length > 500) {
|
|
|
|
|
const token = randomBytes(16).toString('hex');
|
|
|
|
|
await storeHandoffPayload(token, cookies);
|
|
|
|
|
outUrl.searchParams.delete('cookies');
|
|
|
|
|
outUrl.searchParams.set('token', token);
|
2026-07-11 06:17:26 +01:00
|
|
|
location = outUrl.toString();
|
2026-05-20 14:32:39 +01:00
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('[auth-handler] failed to swap cookies → token, falling back to inline cookies:', error);
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-07-11 06:17:26 +01:00
|
|
|
|
|
|
|
|
if (location && browserOrigin && shouldRewriteOAuthProxyCallbackLocation(location, browserOrigin)) {
|
|
|
|
|
location = rewriteOAuthProxyCallbackLocation(location, browserOrigin);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (location && location !== response.headers.get('location')) {
|
|
|
|
|
const headers = new Headers(response.headers);
|
|
|
|
|
headers.set('location', location);
|
|
|
|
|
return new Response(response.body, { status: response.status, headers });
|
|
|
|
|
}
|
2026-05-20 14:32:39 +01:00
|
|
|
}
|
|
|
|
|
|
2026-05-20 09:20:23 +01:00
|
|
|
if (response.status >= 300 && response.status < 400) {
|
2026-05-20 13:51:23 +01:00
|
|
|
const location = response.headers.get('location') ?? '';
|
|
|
|
|
console.log(
|
|
|
|
|
'[auth-handler]',
|
|
|
|
|
c.req.method,
|
|
|
|
|
c.req.path,
|
|
|
|
|
'→',
|
|
|
|
|
response.status,
|
2026-05-20 14:32:39 +01:00
|
|
|
`location.length=${location.length}`
|
2026-05-20 13:51:23 +01:00
|
|
|
);
|
2026-05-20 09:20:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return response;
|
2026-05-20 08:32:56 +01:00
|
|
|
})
|
2025-11-24 01:00:50 +01:00
|
|
|
.get('/session', async (c) => {
|
|
|
|
|
const session = c.get('session');
|
|
|
|
|
const user = c.get('user');
|
|
|
|
|
|
|
|
|
|
if (!user) return c.body(null, 401);
|
|
|
|
|
|
|
|
|
|
return c.json({
|
|
|
|
|
session,
|
|
|
|
|
user
|
|
|
|
|
});
|
|
|
|
|
})
|
|
|
|
|
.route('/onboarding', onboardingRouter)
|
|
|
|
|
.route('/account', accountRouter)
|
2025-09-21 19:35:41 +01:00
|
|
|
.route('/course', courseRouter)
|
2026-03-09 11:18:22 +01:00
|
|
|
.route('/domain', domainRouter)
|
2026-06-07 18:43:05 +01:00
|
|
|
.route('/hls', hlsRouter)
|
|
|
|
|
.route('/transcripts', transcriptsRouter)
|
2025-09-21 19:35:41 +01:00
|
|
|
.route('/mail', mailRouter)
|
2025-12-02 09:54:38 +01:00
|
|
|
.route('/media', mediaRouter)
|
2026-05-18 03:47:22 +01:00
|
|
|
.route('/jobs', jobsRouter)
|
2026-03-09 11:18:22 +01:00
|
|
|
.route('/license', licenseRouter)
|
2025-11-24 01:00:50 +01:00
|
|
|
.route('/organization', organizationRouter)
|
2026-03-09 11:18:22 +01:00
|
|
|
.route('/organization/sso', organizationSsoRouter)
|
|
|
|
|
.route('/organization/token-auth', organizationTokenAuthRouter)
|
|
|
|
|
.route('/sso', ssoDiscoveryRouter)
|
2025-12-02 15:27:41 +01:00
|
|
|
.route('/dash', dashAnalyticsRouter)
|
2025-12-22 19:57:27 +01:00
|
|
|
.route('/community', communityRouter)
|
2026-03-09 11:18:22 +01:00
|
|
|
.route('/invite', inviteRouter)
|
2026-05-09 06:05:03 +01:00
|
|
|
.route('/org-site/course', publicCourseRouter)
|
2026-07-07 22:15:11 +01:00
|
|
|
.route('/org-site/og', orgSiteOgRouter)
|
2026-04-12 08:58:41 +01:00
|
|
|
.route('/public-api/v1', v1Router)
|
2026-07-02 12:10:31 +01:00
|
|
|
.route('/cohort', cohortRouter)
|
2026-03-09 11:18:22 +01:00
|
|
|
.route('/unsplash', unsplashRouter)
|
2026-04-27 11:40:38 +01:00
|
|
|
.route('/widgets', publicWidgetsRouter)
|
2026-05-18 03:47:22 +01:00
|
|
|
.route('/internal', internalRouter)
|
2026-05-09 06:05:03 +01:00
|
|
|
.route('/agent', agentRouter)
|
2025-09-21 19:35:41 +01:00
|
|
|
|
|
|
|
|
// Error handling
|
|
|
|
|
.onError((err, c) => {
|
2026-05-21 17:18:08 +01:00
|
|
|
Sentry.captureException(err);
|
2025-09-21 19:35:41 +01:00
|
|
|
console.error('Error:', err);
|
|
|
|
|
return c.json({ error: 'Internal Server Error' }, 500);
|
|
|
|
|
});
|
2026-05-18 03:47:22 +01:00
|
|
|
|
|
|
|
|
// Dev-only BullMQ dashboard at /admin/queues. Mounted after the typed RPC
|
|
|
|
|
// chain so it doesn't pollute the client type.
|
|
|
|
|
mountQueueDashboard(app);
|