Skip to content

Your always-on AI coworkers that move between text, calls, and Slack.

TypeScript

fix(server): allow localhost and loopback development origins (#36)

Makicdf86b96cf81
diff --git a/.env.example b/.env.example
index afc348c..dab7021 100644
--- a/.env.example
+++ b/.env.example
@@ -4,8 +4,10 @@ PORT=4310
DATABASE_PATH=data/opendots.sqlite
# Keep OWNER_ID stable: it owns the persistent Intelligence conversations.
OWNER_ID=opendots-owner
-# npm run dev allows http://127.0.0.1:5173; override for a different exact origin.
-# APP_ORIGIN=http://127.0.0.1:5173
+# npm run dev allows http://localhost:5173 and http://127.0.0.1:5173.
+# APP_ORIGIN replaces these defaults with comma-separated exact origins.
+# Include scheme, hostname and port; omit paths and trailing slashes.
+# APP_ORIGIN=http://localhost:5173,http://127.0.0.1:5173
# Required for an external HOST binding (24+ characters); enables local login too.
# OWNER_TOKEN=
diff --git a/docs/SETUP.md b/docs/SETUP.md
index dd5e096..803f9c8 100644
--- a/docs/SETUP.md
+++ b/docs/SETUP.md
@@ -14,6 +14,8 @@ npm run dev
Open http://127.0.0.1:5173. The API runs on port 4310. Without service credentials, the app shows its setup state; it does not generate simulated replies.
+During `npm run dev`, both http://localhost:5173 and http://127.0.0.1:5173 are allowed browser origins. The UI sends API requests through Vite's `/api` proxy. To use a different proxy or custom domain, set `APP_ORIGIN` to one exact origin or a comma-separated list, for example `APP_ORIGIN=http://localhost:5173,http://127.0.0.1:5173`. An explicit value replaces the development defaults. Origins must match the scheme, hostname, and port exactly; omit paths and trailing slashes. Whitespace around list entries is trimmed and empty entries are ignored. Outside development, leaving `APP_ORIGIN` unset requires the browser origin to match the request URL's origin. This setting preserves cross-site request blocking; it does not enable direct cross-origin browser access to the API.
+
For a built local app:
```sh
@@ -75,7 +77,7 @@ Edit `.env` on the server and restart after changes:
| `OWNER_ID` | Stable identity used for this deployment's conversations |
| `DATABASE_PATH` | SQLite file containing pages, workspace and work metadata |
| `OWNER_TOKEN` | Application access token; required for external bindings |
-| `APP_ORIGIN` | Exact browser origin when using a proxy or custom domain |
+| `APP_ORIGIN` | Comma-separated exact browser origins for a proxy or custom domain |
`npx copilotkit project select` deletes an `INTELLIGENCE_API_KEY` line and writes the same credential as `CPK_INTELLIGENCE_API_KEY`. The server reads either name. A non-empty `CPK_INTELLIGENCE_API_KEY` takes precedence over `INTELLIGENCE_API_KEY`.
diff --git a/src/server/app-origin.ts b/src/server/app-origin.ts
new file mode 100644
index 0000000..81bd8cd
--- /dev/null
+++ b/src/server/app-origin.ts
@@ -0,0 +1,13 @@
+export function resolveAppOrigins(
+ appOrigin: string | undefined,
+ nodeEnv: string | undefined,
+): string[] | undefined {
+ if (appOrigin)
+ return appOrigin
+ .split(',')
+ .map((value) => value.trim())
+ .filter(Boolean);
+ return nodeEnv === 'development'
+ ? ['http://localhost:5173', 'http://127.0.0.1:5173']
+ : undefined;
+}
diff --git a/src/server/app.ts b/src/server/app.ts
index fc9bae5..865f29c 100644
--- a/src/server/app.ts
+++ b/src/server/app.ts
@@ -15,7 +15,7 @@ export interface AppOptions {
runner: Runner;
config: Config;
ownerToken?: string;
- origin?: string;
+ origin?: string | string[];
platform?: Platform;
}
export function createApp({
@@ -38,17 +38,33 @@ export function createApp({
c.header('Cache-Control', 'no-store');
c.header('X-Content-Type-Options', 'nosniff');
const requestUrl = new URL(c.req.url);
+ const origins = origin
+ ? Array.isArray(origin)
+ ? origin
+ : [origin]
+ : undefined;
+ const originHostnames = origins
+ ? origins
+ .map((o) => {
+ try {
+ return new URL(o).hostname;
+ } catch {
+ return '';
+ }
+ })
+ .filter(Boolean)
+ : [];
const allowedHosts = new Set([
'localhost',
'127.0.0.1',
'[::1]',
- ...(origin ? [new URL(origin).hostname] : []),
+ ...originHostnames,
]);
if (!ownerToken && !allowedHosts.has(requestUrl.hostname))
return c.json({ error: 'Unrecognized host.' }, 403);
const requestOrigin = c.req.header('origin');
- const expectedOrigin = origin ?? new URL(c.req.url).origin;
- if (requestOrigin && requestOrigin !== expectedOrigin)
+ const allowedOrigins = new Set(origins ?? [new URL(c.req.url).origin]);
+ if (requestOrigin && !allowedOrigins.has(requestOrigin))
return c.json({ error: 'Cross-origin requests are not allowed.' }, 403);
if (c.req.header('sec-fetch-site') === 'cross-site')
return c.json({ error: 'Cross-site requests are not allowed.' }, 403);
diff --git a/src/server/index.ts b/src/server/index.ts
index 91eb421..c3e5ee8 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -6,6 +6,7 @@ import { serveStatic } from '@hono/node-server/serve-static';
import { Store } from './store.js';
import { Runner } from './runner.js';
import { createApp } from './app.js';
+import { resolveAppOrigins } from './app-origin.js';
import { WorkspaceStore } from './workspace.js';
import { Platform } from './platform.js';
import {
@@ -90,11 +91,7 @@ const app = createApp({
runner,
config: researchConfig,
ownerToken,
- origin:
- process.env.APP_ORIGIN ??
- (process.env.NODE_ENV === 'development'
- ? 'http://127.0.0.1:5173'
- : undefined),
+ origin: resolveAppOrigins(process.env.APP_ORIGIN, process.env.NODE_ENV),
platform,
});
app.use('*', async (c, next) => {
diff --git a/tests/app-origin.test.ts b/tests/app-origin.test.ts
new file mode 100644
index 0000000..09ed697
--- /dev/null
+++ b/tests/app-origin.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+import { resolveAppOrigins } from '../src/server/app-origin.js';
+
+describe('application origin configuration', () => {
+ it('allows both loopback browser origins by default in development', () => {
+ expect(resolveAppOrigins(undefined, 'development')).toEqual([
+ 'http://localhost:5173',
+ 'http://127.0.0.1:5173',
+ ]);
+ });
+
+ it.each(['production', 'test', undefined])(
+ 'preserves request-origin matching outside development (%s)',
+ (nodeEnv) => {
+ expect(resolveAppOrigins(undefined, nodeEnv)).toBeUndefined();
+ },
+ );
+
+ it.each(['development', 'production'])(
+ 'replaces defaults with an explicit single origin in %s',
+ (nodeEnv) => {
+ expect(resolveAppOrigins('https://dots.example', nodeEnv)).toEqual([
+ 'https://dots.example',
+ ]);
+ },
+ );
+
+ it('trims multiple origins and drops empty entries', () => {
+ expect(
+ resolveAppOrigins(
+ ' http://localhost:5173, ,http://127.0.0.1:5173, ',
+ 'development',
+ ),
+ ).toEqual(['http://localhost:5173', 'http://127.0.0.1:5173']);
+ });
+
+ it.each(['development', 'production'])(
+ 'treats an empty value as unset in %s',
+ (nodeEnv) => {
+ expect(resolveAppOrigins('', nodeEnv)).toEqual(
+ resolveAppOrigins(undefined, nodeEnv),
+ );
+ },
+ );
+
+ it.each([' ', ', ,'])(
+ 'keeps a nonempty all-blank list restrictive (%s)',
+ (value) => {
+ expect(resolveAppOrigins(value, 'development')).toEqual([]);
+ },
+ );
+});
diff --git a/tests/app.test.ts b/tests/app.test.ts
index 62f0bee..7c49321 100644
--- a/tests/app.test.ts
+++ b/tests/app.test.ts
@@ -3,16 +3,17 @@ import { createApp } from '../src/server/app.js';
import { Store } from '../src/server/store.js';
import { Runner } from '../src/server/runner.js';
import type { Config } from '../src/server/research.js';
+import { resolveAppOrigins } from '../src/server/app-origin.js';
const stores: Store[] = [];
const config: Config = { mode: 'sample', baseUrl: 'https://api.openai.com/v1' };
-function fixture(token?: string) {
+function fixture(token?: string, origin?: string | string[]) {
const store = new Store(':memory:');
stores.push(store);
const runner = new Runner(store, config);
return {
store,
runner,
- app: createApp({ store, runner, config, ownerToken: token }),
+ app: createApp({ store, runner, config, ownerToken: token, origin }),
};
}
const json = (body: unknown) => ({
@@ -55,6 +56,157 @@ describe('API boundaries', () => {
).status,
).toBe(415);
});
+ it.each(['http://localhost:5173', 'http://127.0.0.1:5173'])(
+ 'allows a same-origin Vite proxy mutation from %s',
+ async (origin) => {
+ const { app } = fixture(
+ undefined,
+ resolveAppOrigins(undefined, 'development'),
+ );
+ const response = await app.request(`${origin}/api/tasks`, {
+ ...json({ prompt: 'test' }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: origin,
+ 'Sec-Fetch-Site': 'same-origin',
+ },
+ });
+ expect(response.status).toBe(201);
+ },
+ );
+ it.each([
+ 'https://evil.example',
+ 'http://localhost:5174',
+ 'https://localhost:5173',
+ ])(
+ 'rejects an unlisted origin %s with multiple origins configured',
+ async (origin) => {
+ const { app } = fixture(
+ undefined,
+ resolveAppOrigins(undefined, 'development'),
+ );
+ const response = await app.request('http://localhost:5173/api/tasks', {
+ ...json({ prompt: 'test' }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: origin,
+ 'Sec-Fetch-Site': 'same-origin',
+ },
+ });
+ expect(response.status).toBe(403);
+ expect(await response.json()).toEqual({
+ error: 'Cross-origin requests are not allowed.',
+ });
+ },
+ );
+ it('rejects cross-site requests even from a configured origin', async () => {
+ const { app } = fixture(
+ undefined,
+ resolveAppOrigins(undefined, 'development'),
+ );
+ const response = await app.request('http://127.0.0.1:4310/api/tasks', {
+ ...json({ prompt: 'test' }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: 'http://localhost:5173',
+ 'Sec-Fetch-Site': 'cross-site',
+ },
+ });
+ expect(response.status).toBe(403);
+ expect(await response.json()).toEqual({
+ error: 'Cross-site requests are not allowed.',
+ });
+ });
+ it('preserves exact matching for a single configured origin', async () => {
+ const { app } = fixture(undefined, 'http://localhost:5173');
+ for (const [origin, status] of [
+ ['http://localhost:5173', 201],
+ ['http://127.0.0.1:5173', 403],
+ ] as const) {
+ const response = await app.request('http://localhost:5173/api/tasks', {
+ ...json({ prompt: 'test' }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: origin,
+ 'Sec-Fetch-Site': 'same-origin',
+ },
+ });
+ expect(response.status).toBe(status);
+ }
+ });
+ it.each(['http://localhost:5173', 'http://127.0.0.1:5173'])(
+ 'requires owner authentication for an allowed origin %s',
+ async (origin) => {
+ const { app } = fixture(
+ 'private-token',
+ resolveAppOrigins(undefined, 'development'),
+ );
+ for (const [authorization, status] of [
+ [undefined, 401],
+ ['Bearer wrong-token', 401],
+ ['Bearer private-token', 201],
+ ] as const) {
+ const response = await app.request(`${origin}/api/tasks`, {
+ ...json({ prompt: 'test' }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: origin,
+ 'Sec-Fetch-Site': 'same-origin',
+ ...(authorization ? { Authorization: authorization } : {}),
+ },
+ });
+ expect(response.status).toBe(status);
+ }
+ },
+ );
+ it('rejects unrecognized hosts even when the origin is explicitly allowed', async () => {
+ const { app } = fixture(
+ undefined,
+ resolveAppOrigins(undefined, 'development'),
+ );
+ const response = await app.request('http://attacker.example/api/tasks', {
+ ...json({ prompt: 'test' }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: 'http://localhost:5173',
+ 'Sec-Fetch-Site': 'same-origin',
+ },
+ });
+ expect(response.status).toBe(403);
+ expect(await response.json()).toEqual({ error: 'Unrecognized host.' });
+ });
+ it('does not widen access when an explicit origin list contains only blank entries', async () => {
+ const { app } = fixture(undefined, resolveAppOrigins(' , ', 'development'));
+ const response = await app.request('http://localhost:5173/api/tasks', {
+ ...json({ prompt: 'test' }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: 'http://localhost:5173',
+ 'Sec-Fetch-Site': 'same-origin',
+ },
+ });
+ expect(response.status).toBe(403);
+ });
+ it('requires the request URL origin by default in production', async () => {
+ const { app } = fixture(
+ undefined,
+ resolveAppOrigins(undefined, 'production'),
+ );
+ for (const [origin, status] of [
+ ['http://localhost:4310', 201],
+ ['http://localhost:5173', 403],
+ ] as const) {
+ const response = await app.request('http://localhost:4310/api/tasks', {
+ ...json({ prompt: 'test' }),
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: origin,
+ 'Sec-Fetch-Site': 'same-origin',
+ },
+ });
+ expect(response.status).toBe(status);
+ }
+ });
it('validates inputs and enforces research permissions on the server', async () => {
const { app, store } = fixture();
expect(