diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..1597400d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,19 @@ +# Changelog + +## [1.1.0] - 2026-05-23 + +### Breaking changes + +- **Client now uses relative URLs.** A reverse proxy exposing `/api/trpc`, `/ws/collab`, and `/ws/realtime` on the same origin as the client is now required. +- Removed build-time variables `APP_SERVER_URL`, `COLLAB_SERVER_URL`, and `REALTIME_SERVER_URL` from the client Docker image and environment templates. The SPA resolves API and WebSocket endpoints from `window.location` at runtime. + +### Added + +- `apps/client/src/lib/endpoints.ts` — helpers `apiUrl`, `apiWsUrl`, `collabUrl`, and `realtimeUrl`. +- `ALLOWED_ORIGINS` (comma-separated) on the app-server for additional CORS origins alongside `CLIENT_URL` and `CLIENT_APP_URL`. +- Vite dev-server proxy in `quasar.config.cjs` for local development without a separate reverse proxy. +- `docker-compose.override.yml.example` — optional localhost-only exposure of backend ports for debugging. + +### Changed + +- Client container nginx routes `/api/trpc`, `/ws/collab`, and `/ws/realtime` to internal backends (no post-build URL injection in `docker-entrypoint.sh`). diff --git a/README.md b/README.md index 74383a21..d61dae16 100644 --- a/README.md +++ b/README.md @@ -49,9 +49,93 @@ Six Docker containers: | postgres | PostgreSQL 16 | | keydb | KeyDB (Redis-compatible cache)| +The browser talks only to the **client** origin. Nginx inside the client container (or your external reverse proxy) forwards: + +| Public path | Backend | +|--------------------|----------------------| +| `/api/trpc` | app-server `:48922` | +| `/ws/collab` | collab-server `:48923` | +| `/ws/realtime` | realtime-server `:48924` | + +Backend ports are **not** published on `0.0.0.0` by default. Use `docker-compose.override.yml.example` if you need loopback-only access for debugging. + +## Reverse proxy requirement + +From v1.1.0 onward, the SPA builds API and WebSocket URLs from `window.location`. Your public URL must expose these paths on the **same origin** as the web app (HTTPS recommended). + +### Nginx example + +```nginx +location /api/trpc/ { + proxy_pass http://app-server:48922/trpc/; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; +} + +location /ws/collab/ { + proxy_pass http://collab-server:48923/; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_read_timeout 86400s; +} + +location /ws/realtime { + proxy_pass http://realtime-server:48924; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_read_timeout 86400s; +} +``` + +The included `apps/client/nginx.conf` applies the same routing when using the stock Docker client image. + +### Nginx Proxy Manager (Custom Locations) + +Create one proxy host for your app domain, forward `/` to the client container (`http://:80`), then add **Custom locations**: + +| Location | Forward scheme | Forward host:port | Websockets | +|-----------------|----------------|--------------------------|------------| +| `/api/trpc` | http | `app-server:48922` | off | +| `/ws/collab` | http | `collab-server:48923` | on | +| `/ws/realtime` | http | `realtime-server:48924` | on | + +For `/api/trpc`, set the path to strip/replace so upstream receives `/trpc` (NPM “Forward path” `/trpc` or equivalent). Enable “Block common exploits” only if it does not strip WebSocket upgrades on `/ws/*`. + ## Configuration -Copy `template.env` to `.env`. All secrets must be replaced with unique values generated via `openssl rand -hex 32` (for hex secrets) or `openssl rand -base64 32` (for base64 keys). `CLIENT_APP_URL` must match your public HTTPS URL. +Copy `template.env` to `.env`. All secrets must be replaced with unique values generated via `openssl rand -hex 32` (for hex secrets) or `openssl rand -base64 32` (for base64 keys). + +| Variable | Purpose | +|----------|---------| +| `CLIENT_APP_URL` | Public HTTPS URL of the app (cookies, CORS, emails) | +| `CLIENT_URL` | Origin used during local dev (`pnpm dev`) | +| `ALLOWED_ORIGINS` | Optional comma-separated extra CORS origins | + +## Local development + +`pnpm dev` runs the Quasar/Vite dev server with a built-in proxy: + +- `/api/trpc` → `http://127.0.0.1:48922/trpc` +- `/ws/collab` → collab-server +- `/ws/realtime` → realtime-server + +Start backends on ports `48922`, `48923`, and `48924` as before. + +## Migration from versions before 1.1.0 + +1. Pull the new version and rebuild: `docker compose up -d --build`. +2. Remove obsolete variables from `.env`: `APP_SERVER_URL`, `COLLAB_SERVER_URL`, `REALTIME_SERVER_URL` (and any Docker build `ARG` overrides for the client). +3. Configure your reverse proxy (or use the bundled client nginx) to expose `/api/trpc`, `/ws/collab`, and `/ws/realtime` on the same domain as the SPA. +4. Set `CLIENT_APP_URL` to that public URL (e.g. `https://notes.example.com`). +5. If the app is served from an additional origin, add it to `ALLOWED_ORIGINS`. +6. Stop publishing backend ports `48922–48924` on `0.0.0.0` unless you use the optional `docker-compose.override.yml` for localhost debugging. ## Update diff --git a/apps/app-server/src/env.d.ts b/apps/app-server/src/env.d.ts index f2daedfe..e5af2432 100644 --- a/apps/app-server/src/env.d.ts +++ b/apps/app-server/src/env.d.ts @@ -8,16 +8,15 @@ declare namespace NodeJS { HOST: string; APP_SERVER_PORT: string; - APP_SERVER_URL: string; CLIENT_PORT: string; CLIENT_URL: string; + CLIENT_APP_URL: string; + ALLOWED_ORIGINS?: string; REALTIME_SERVER_PORT: string; - REALTIME_SERVER_URL: string; COLLAB_SERVER_PORT: string; - COLLAB_SERVER_URL: string; ACCESS_TOKEN_SECRET: string; REFRESH_TOKEN_SECRET: string; diff --git a/apps/app-server/src/fastify/server.ts b/apps/app-server/src/fastify/server.ts index 546ff33a..3e29a46b 100644 --- a/apps/app-server/src/fastify/server.ts +++ b/apps/app-server/src/fastify/server.ts @@ -51,16 +51,9 @@ export const fastify = once(async () => { await fastify.register(import('@fastify/cors'), { origin: (requestOrigin, callback) => { - // CORS origin logged only in dev if (process.env.DEV) console.log('CORS Origin: %s', requestOrigin); - if ( - process.env.DEV || - requestOrigin === undefined || - requestOrigin === process.env.CLIENT_URL || - requestOrigin === 'capacitor://deepnotes.app' || - requestOrigin === 'http://localhost' - ) { + if (isAllowedCorsOrigin(requestOrigin)) { callback(null, true); } else { callback(new Error('Not allowed'), false); diff --git a/apps/app-server/src/utils/allowed-origins.spec.ts b/apps/app-server/src/utils/allowed-origins.spec.ts new file mode 100644 index 00000000..38262fed --- /dev/null +++ b/apps/app-server/src/utils/allowed-origins.spec.ts @@ -0,0 +1,26 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { isAllowedCorsOrigin } from './allowed-origins'; + +describe('isAllowedCorsOrigin', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('allows CLIENT_APP_URL and ALLOWED_ORIGINS when not in dev', () => { + vi.stubEnv('DEV', ''); + vi.stubEnv('CLIENT_URL', 'http://localhost:60379'); + vi.stubEnv('CLIENT_APP_URL', 'https://notes.example.com'); + vi.stubEnv('ALLOWED_ORIGINS', 'https://alt.example.com, https://other.example.com'); + + expect(isAllowedCorsOrigin('https://notes.example.com')).toBe(true); + expect(isAllowedCorsOrigin('https://alt.example.com')).toBe(true); + expect(isAllowedCorsOrigin('https://other.example.com')).toBe(true); + expect(isAllowedCorsOrigin('https://unknown.example.com')).toBe(false); + }); + + it('allows any origin in dev', () => { + vi.stubEnv('DEV', 'true'); + expect(isAllowedCorsOrigin('https://anything.example.com')).toBe(true); + }); +}); diff --git a/apps/app-server/src/utils/allowed-origins.ts b/apps/app-server/src/utils/allowed-origins.ts new file mode 100644 index 00000000..fddd3a6e --- /dev/null +++ b/apps/app-server/src/utils/allowed-origins.ts @@ -0,0 +1,29 @@ +const STATIC_ALLOWED_ORIGINS = new Set([ + 'capacitor://deepnotes.app', + 'http://localhost', +]); + +export function isAllowedCorsOrigin(requestOrigin: string | undefined): boolean { + if (process.env.DEV) { + return true; + } + + if (requestOrigin === undefined) { + return true; + } + + const allowed = new Set(STATIC_ALLOWED_ORIGINS); + + for (const value of [ + process.env.CLIENT_URL, + process.env.CLIENT_APP_URL, + ...(process.env.ALLOWED_ORIGINS?.split(',') ?? []), + ]) { + const trimmed = value?.trim(); + if (trimmed) { + allowed.add(trimmed); + } + } + + return allowed.has(requestOrigin); +} diff --git a/apps/client/Dockerfile b/apps/client/Dockerfile index ba65c891..57402bd9 100644 --- a/apps/client/Dockerfile +++ b/apps/client/Dockerfile @@ -5,14 +5,6 @@ RUN corepack enable && corepack prepare pnpm@10.30.1 --activate WORKDIR /build COPY ./ ./ -# SPA needs these at build time (inlined in bundle). Use same host as client so browser can reach backends. -ARG APP_SERVER_URL=http://localhost:48922/trpc -ARG COLLAB_SERVER_URL=ws://localhost:48923 -ARG REALTIME_SERVER_URL=ws://localhost:48924 -ENV APP_SERVER_URL=${APP_SERVER_URL} -ENV COLLAB_SERVER_URL=${COLLAB_SERVER_URL} -ENV REALTIME_SERVER_URL=${REALTIME_SERVER_URL} - RUN pnpm install RUN pnpm run repo:build RUN pnpm --filter @deepnotes/client run build:spa diff --git a/apps/client/docker-entrypoint.sh b/apps/client/docker-entrypoint.sh index b934bba8..1220d0a2 100644 --- a/apps/client/docker-entrypoint.sh +++ b/apps/client/docker-entrypoint.sh @@ -1,22 +1,8 @@ #!/bin/sh set -e -if ! echo "$CLIENT_APP_URL" | grep -qE '^https?://[a-zA-Z0-9._-]+(:[0-9]+)?$'; then +if [ -n "$CLIENT_APP_URL" ] && ! echo "$CLIENT_APP_URL" | grep -qE '^https?://[a-zA-Z0-9._-]+(:[0-9]+)?$'; then echo "[warn] CLIENT_APP_URL looks invalid: $CLIENT_APP_URL" fi -# Build absolute WebSocket URLs from CLIENT_APP_URL -if [ -n "$CLIENT_APP_URL" ]; then - # Convert http(s)://host to ws(s)://host - WS_BASE=$(echo "$CLIENT_APP_URL" | sed 's|^http|ws|') - - echo "Injecting URLs: APP=$CLIENT_APP_URL, WS_BASE=$WS_BASE" - - find /usr/share/nginx/html/assets -name '*.js' -exec sed -i \ - -e "s|http://localhost:48922/trpc|${CLIENT_APP_URL}/trpc|g" \ - -e "s|ws://localhost:48923|${WS_BASE}/collab|g" \ - -e "s|ws://localhost:48924|${WS_BASE}/realtime|g" \ - {} + -fi - exec nginx -g 'daemon off;' diff --git a/apps/client/nginx.conf b/apps/client/nginx.conf index 8a41c52b..ac24061b 100644 --- a/apps/client/nginx.conf +++ b/apps/client/nginx.conf @@ -16,11 +16,11 @@ server { try_files $uri $uri/ /index.html; } - location = /trpc { - return 301 /trpc/; + location = /api/trpc { + return 301 /api/trpc/; } - location /trpc/ { + location /api/trpc/ { proxy_pass http://app-server:48922/trpc/; proxy_http_version 1.1; proxy_set_header Host $host; @@ -29,27 +29,27 @@ server { proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; - proxy_read_timeout 86400; + proxy_read_timeout 86400s; } - location /realtime { + location /ws/realtime { + rewrite ^/ws/realtime(.*)$ $1 break; proxy_pass http://realtime-server:48924; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; - proxy_read_timeout 86400; + proxy_read_timeout 86400s; } - location /collab/ { - rewrite ^/collab/(.*)$ /$1 break; - proxy_pass http://collab-server:48923; + location /ws/collab/ { + proxy_pass http://collab-server:48923/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; - proxy_read_timeout 86400; + proxy_read_timeout 86400s; } } diff --git a/apps/client/package.json b/apps/client/package.json index 2121d98d..a4632672 100644 --- a/apps/client/package.json +++ b/apps/client/package.json @@ -2,7 +2,7 @@ "name": "@deepnotes/client", "description": "DeepNotes is an open source, end-to-end encrypted infinite canvas tool with deep page nesting and realtime collaboration. Create mind maps, diagrams, kanban boards, and more.", "homepage": "https://deepnotes.app", - "version": "1.0.25", + "version": "1.1.0", "author": "Gustavo Toyota ", "dependencies": { "@deeplib/data": "workspace:*", diff --git a/apps/client/quasar.config.cjs b/apps/client/quasar.config.cjs index 19ea2470..7c269d2f 100644 --- a/apps/client/quasar.config.cjs +++ b/apps/client/quasar.config.cjs @@ -272,6 +272,24 @@ module.exports = configure(function (ctx) { open: false, // opens browser window automatically port: port, host: '0.0.0.0', + proxy: { + '/api/trpc': { + target: 'http://127.0.0.1:48922', + changeOrigin: true, + ws: true, + rewrite: (path) => path.replace(/^\/api\/trpc/, '/trpc'), + }, + '/ws/collab': { + target: 'http://127.0.0.1:48923', + ws: true, + rewrite: (path) => path.replace(/^\/ws\/collab/, '') || '/', + }, + '/ws/realtime': { + target: 'http://127.0.0.1:48924', + ws: true, + rewrite: (path) => path.replace(/^\/ws\/realtime/, '') || '/', + }, + }, }, // https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#framework diff --git a/apps/client/src/code/areas/api-interface/groups/change-user-role.ts b/apps/client/src/code/areas/api-interface/groups/change-user-role.ts index 79ff9ecd..ae017c97 100644 --- a/apps/client/src/code/areas/api-interface/groups/change-user-role.ts +++ b/apps/client/src/code/areas/api-interface/groups/change-user-role.ts @@ -7,6 +7,7 @@ import { groupMemberNames } from 'src/code/pages/computed/group-member-names'; import { groupNames } from 'src/code/pages/computed/group-names'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -16,10 +17,7 @@ export async function changeUserRole(input: { role: GroupRoleID; }) { const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.changeUserRole`, + url: apiWsUrl('/groups.changeUserRole'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/join-invitations/accept.ts b/apps/client/src/code/areas/api-interface/groups/join-invitations/accept.ts index 0848d6bf..454c5cfc 100644 --- a/apps/client/src/code/areas/api-interface/groups/join-invitations/accept.ts +++ b/apps/client/src/code/areas/api-interface/groups/join-invitations/accept.ts @@ -6,6 +6,7 @@ import { createKeyring } from '@stdlib/crypto'; import { textToBytes } from '@stdlib/misc'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -14,10 +15,7 @@ export async function acceptJoinInvitation(input: { userName: string; }) { const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.joinInvitations.accept`, + url: apiWsUrl('/groups.joinInvitations.accept'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/join-invitations/cancel.ts b/apps/client/src/code/areas/api-interface/groups/join-invitations/cancel.ts index 5723d844..b7a1095b 100644 --- a/apps/client/src/code/areas/api-interface/groups/join-invitations/cancel.ts +++ b/apps/client/src/code/areas/api-interface/groups/join-invitations/cancel.ts @@ -7,6 +7,7 @@ import { groupMemberNames } from 'src/code/pages/computed/group-member-names'; import { groupNames } from 'src/code/pages/computed/group-names'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -22,10 +23,7 @@ export async function cancelJoinInvitation(input: { ]); const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.joinInvitations.cancel`, + url: apiWsUrl('/groups.joinInvitations.cancel'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/join-invitations/reject.ts b/apps/client/src/code/areas/api-interface/groups/join-invitations/reject.ts index 5bba3e85..00f8b4d5 100644 --- a/apps/client/src/code/areas/api-interface/groups/join-invitations/reject.ts +++ b/apps/client/src/code/areas/api-interface/groups/join-invitations/reject.ts @@ -5,6 +5,7 @@ import type { import { groupInvitationNames } from 'src/code/pages/computed/group-invitation-names'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -14,10 +15,7 @@ export async function rejectJoinInvitation(input: { groupId: string }) { ).getAsync(); const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.joinInvitations.reject`, + url: apiWsUrl('/groups.joinInvitations.reject'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/join-invitations/send.ts b/apps/client/src/code/areas/api-interface/groups/join-invitations/send.ts index 8e7366cd..b2f128d7 100644 --- a/apps/client/src/code/areas/api-interface/groups/join-invitations/send.ts +++ b/apps/client/src/code/areas/api-interface/groups/join-invitations/send.ts @@ -11,6 +11,7 @@ import { groupMemberNames } from 'src/code/pages/computed/group-member-names'; import { groupNames } from 'src/code/pages/computed/group-names'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -51,10 +52,7 @@ export async function sendJoinInvitation(input: { ]); const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.joinInvitations.send`, + url: apiWsUrl('/groups.joinInvitations.send'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/join-requests/accept.ts b/apps/client/src/code/areas/api-interface/groups/join-requests/accept.ts index 32fa6f84..f1155fa3 100644 --- a/apps/client/src/code/areas/api-interface/groups/join-requests/accept.ts +++ b/apps/client/src/code/areas/api-interface/groups/join-requests/accept.ts @@ -11,6 +11,7 @@ import { groupNames } from 'src/code/pages/computed/group-names'; import { groupRequestNames } from 'src/code/pages/computed/group-request-names'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -47,10 +48,7 @@ export async function acceptJoinRequest(input: { ]); const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.joinRequests.accept`, + url: apiWsUrl('/groups.joinRequests.accept'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/join-requests/cancel.ts b/apps/client/src/code/areas/api-interface/groups/join-requests/cancel.ts index 2b45f4f7..6ef8ecbc 100644 --- a/apps/client/src/code/areas/api-interface/groups/join-requests/cancel.ts +++ b/apps/client/src/code/areas/api-interface/groups/join-requests/cancel.ts @@ -5,6 +5,7 @@ import type { import { groupRequestNames } from 'src/code/pages/computed/group-request-names'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -14,10 +15,7 @@ export async function cancelJoinRequest(input: { groupId: string }) { ).getAsync(); const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.joinRequests.cancel`, + url: apiWsUrl('/groups.joinRequests.cancel'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/join-requests/reject.ts b/apps/client/src/code/areas/api-interface/groups/join-requests/reject.ts index fafea0bd..3553e89b 100644 --- a/apps/client/src/code/areas/api-interface/groups/join-requests/reject.ts +++ b/apps/client/src/code/areas/api-interface/groups/join-requests/reject.ts @@ -7,6 +7,7 @@ import { groupNames } from 'src/code/pages/computed/group-names'; import { groupRequestNames } from 'src/code/pages/computed/group-request-names'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -21,10 +22,7 @@ export async function rejectJoinRequest(input: { ]); const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.joinRequests.reject`, + url: apiWsUrl('/groups.joinRequests.reject'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/join-requests/send.ts b/apps/client/src/code/areas/api-interface/groups/join-requests/send.ts index 2faad432..137d2c28 100644 --- a/apps/client/src/code/areas/api-interface/groups/join-requests/send.ts +++ b/apps/client/src/code/areas/api-interface/groups/join-requests/send.ts @@ -6,6 +6,7 @@ import { createKeyring } from '@stdlib/crypto'; import { textToBytes } from '@stdlib/misc'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -14,10 +15,7 @@ export async function sendJoinRequest(input: { userName: string; }) { const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.joinRequests.send`, + url: apiWsUrl('/groups.joinRequests.send'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/key-rotation.ts b/apps/client/src/code/areas/api-interface/groups/key-rotation.ts index 45820056..10b01732 100644 --- a/apps/client/src/code/areas/api-interface/groups/key-rotation.ts +++ b/apps/client/src/code/areas/api-interface/groups/key-rotation.ts @@ -13,15 +13,13 @@ import sodium from 'libsodium-wrappers-sumo'; import { computeGroupPasswordValues } from 'src/code/crypto'; import { asyncDialog } from 'src/code/utils/misc'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} export async function rotateGroupKeys(input: { groupId: string }) { const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.rotateKeys`, + url: apiWsUrl('/groups.rotateKeys'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/privacy/make-private.ts b/apps/client/src/code/areas/api-interface/groups/privacy/make-private.ts index 10ee2c8f..59048e02 100644 --- a/apps/client/src/code/areas/api-interface/groups/privacy/make-private.ts +++ b/apps/client/src/code/areas/api-interface/groups/privacy/make-private.ts @@ -5,15 +5,13 @@ import type { import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; import { processGroupKeyRotationValues } from '../key-rotation'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} export async function makeGroupPrivate(input: { groupId: string }) { const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.privacy.makePrivate`, + url: apiWsUrl('/groups.privacy.makePrivate'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/groups/remove-user.ts b/apps/client/src/code/areas/api-interface/groups/remove-user.ts index 821d78d8..f4c25983 100644 --- a/apps/client/src/code/areas/api-interface/groups/remove-user.ts +++ b/apps/client/src/code/areas/api-interface/groups/remove-user.ts @@ -6,6 +6,7 @@ import { groupMemberNames } from 'src/code/pages/computed/group-member-names'; import { groupNames } from 'src/code/pages/computed/group-names'; import { createNotifications } from 'src/code/pages/utils'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -23,10 +24,7 @@ export async function removeGroupUser(input: { ]); const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/groups.removeUser`, + url: apiWsUrl('/groups.removeUser'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/pages/move.ts b/apps/client/src/code/areas/api-interface/pages/move.ts index 71dc3f4f..5aee9d30 100644 --- a/apps/client/src/code/areas/api-interface/pages/move.ts +++ b/apps/client/src/code/areas/api-interface/pages/move.ts @@ -47,7 +47,7 @@ export async function movePage(input: { } const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll('http', 'ws')}/pages.move`, + url: apiWsUrl('/pages.move'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/users/change-email.ts b/apps/client/src/code/areas/api-interface/users/change-email.ts index 3bc1dc66..6bea2ae6 100644 --- a/apps/client/src/code/areas/api-interface/users/change-email.ts +++ b/apps/client/src/code/areas/api-interface/users/change-email.ts @@ -5,6 +5,7 @@ import type { import { createPrivateKeyring, createSymmetricKeyring } from '@stdlib/crypto'; import { deriveUserValues } from 'src/code/crypto'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -15,10 +16,7 @@ export async function changeEmail(input: { emailVerificationCode: string; }) { const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/users.account.emailChange.finish`, + url: apiWsUrl('/users.account.emailChange.finish'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/users/change-password.ts b/apps/client/src/code/areas/api-interface/users/change-password.ts index 9b50e9a7..db32a0fb 100644 --- a/apps/client/src/code/areas/api-interface/users/change-password.ts +++ b/apps/client/src/code/areas/api-interface/users/change-password.ts @@ -5,6 +5,7 @@ import type { import { createPrivateKeyring, createSymmetricKeyring } from '@stdlib/crypto'; import { deriveUserValues } from 'src/code/crypto'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -28,10 +29,7 @@ export async function changePassword(input: { }); const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/users.account.changePassword`, + url: apiWsUrl('/users.account.changePassword'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/api-interface/users/rotate-keys.ts b/apps/client/src/code/areas/api-interface/users/rotate-keys.ts index eb60799b..cbd570f2 100644 --- a/apps/client/src/code/areas/api-interface/users/rotate-keys.ts +++ b/apps/client/src/code/areas/api-interface/users/rotate-keys.ts @@ -11,6 +11,7 @@ import { import sodium from 'libsodium-wrappers-sumo'; import { deriveUserValues } from 'src/code/crypto'; import { createWebsocketRequest } from 'src/code/utils/websocket-requests'; +import { apiWsUrl } from 'src/lib/endpoints'; function noopStep3(_input: unknown) {} @@ -33,10 +34,7 @@ export async function rotateUserKeys(input: { password: string }) { // Create websocket request const { promise } = createWebsocketRequest({ - url: `${process.env.APP_SERVER_URL.replaceAll( - 'http', - 'ws', - )}/users.account.rotateKeys`, + url: apiWsUrl('/users.account.rotateKeys'), steps: [step1, step2, noopStep3], }); diff --git a/apps/client/src/code/areas/realtime/client.ts b/apps/client/src/code/areas/realtime/client.ts index 51a3eeba..4f591c62 100644 --- a/apps/client/src/code/areas/realtime/client.ts +++ b/apps/client/src/code/areas/realtime/client.ts @@ -12,6 +12,7 @@ import * as encoding from 'lib0/encoding'; import { once, throttle } from 'lodash'; import { pack, unpack } from 'msgpackr'; +import { realtimeUrl } from 'src/lib/endpoints'; import { getNotificationInfo } from '../../pages/notifications/notifications'; import { RealtimeContext } from './context'; @@ -47,7 +48,7 @@ export const RealtimeClient = once( private _isFirstConnection = true; constructor() { - super(process.env.REALTIME_SERVER_URL); + super(realtimeUrl()); } connect() { diff --git a/apps/client/src/code/pages/page/collab/websocket.ts b/apps/client/src/code/pages/page/collab/websocket.ts index 7ca01ccf..f5c1bc6c 100644 --- a/apps/client/src/code/pages/page/collab/websocket.ts +++ b/apps/client/src/code/pages/page/collab/websocket.ts @@ -39,7 +39,7 @@ export const PageWebsocket = once( syncPromise?: Resolvable; constructor(input: { collab: PageCollab }) { - super(`${process.env.COLLAB_SERVER_URL}/page:${input.collab.page.id}`); + super(`${collabUrl()}/page:${input.collab.page.id}`); this.page = input.collab.page; this.collab = input.collab; diff --git a/apps/client/src/code/trpc.ts b/apps/client/src/code/trpc.ts index 65a2244c..fae82389 100644 --- a/apps/client/src/code/trpc.ts +++ b/apps/client/src/code/trpc.ts @@ -1,11 +1,12 @@ import type { AppRouter } from '@deepnotes/app-server/src/trpc/router'; import { createTRPCClient, httpLink } from '@trpc/client'; +import { apiUrl } from 'src/lib/endpoints'; import superjson from 'superjson'; export const trpcClient = createTRPCClient({ links: [ httpLink({ - url: process.env.APP_SERVER_URL, + url: apiUrl(), transformer: superjson, headers({ op }) { diff --git a/apps/client/src/env.d.ts b/apps/client/src/env.d.ts index 1651451c..a541610b 100644 --- a/apps/client/src/env.d.ts +++ b/apps/client/src/env.d.ts @@ -20,16 +20,13 @@ declare namespace NodeJS { HOST: string; APP_SERVER_PORT: string; - APP_SERVER_URL: string; CLIENT_PORT: string; CLIENT_URL: string; REALTIME_SERVER_PORT: string; - REALTIME_SERVER_URL: string; COLLAB_SERVER_PORT: string; - COLLAB_SERVER_URL: string; ACCESS_SECRET: string; REFRESH_SECRET: string; diff --git a/apps/client/src/lib/endpoints.spec.ts b/apps/client/src/lib/endpoints.spec.ts new file mode 100644 index 00000000..eb4f9f5a --- /dev/null +++ b/apps/client/src/lib/endpoints.spec.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, it } from 'vitest'; + +import { apiUrl, apiWsUrl, collabUrl, realtimeUrl } from './endpoints'; + +describe('endpoints', () => { + const originalLocation = globalThis.location; + + afterEach(() => { + Object.defineProperty(globalThis, 'location', { + value: originalLocation, + writable: true, + configurable: true, + }); + }); + + function mockLocation(input: { + protocol: string; + host: string; + origin: string; + }) { + Object.defineProperty(globalThis, 'location', { + value: input, + writable: true, + configurable: true, + }); + } + + it('builds HTTP API URLs from window.location.origin', () => { + mockLocation({ + protocol: 'http:', + host: 'localhost:60379', + origin: 'http://localhost:60379', + }); + + expect(apiUrl()).toBe('http://localhost:60379/api/trpc'); + expect(apiUrl('/sessions.login')).toBe( + 'http://localhost:60379/api/trpc/sessions.login', + ); + }); + + it('uses wss for WebSocket URLs when the page is served over HTTPS', () => { + mockLocation({ + protocol: 'https:', + host: 'notes.example.com', + origin: 'https://notes.example.com', + }); + + expect(apiWsUrl('/groups.rotateKeys')).toBe( + 'wss://notes.example.com/api/trpc/groups.rotateKeys', + ); + expect(collabUrl()).toBe('wss://notes.example.com/ws/collab'); + expect(realtimeUrl()).toBe('wss://notes.example.com/ws/realtime'); + }); + + it('uses ws for WebSocket URLs when the page is served over HTTP', () => { + mockLocation({ + protocol: 'http:', + host: '127.0.0.1:8080', + origin: 'http://127.0.0.1:8080', + }); + + expect(collabUrl()).toBe('ws://127.0.0.1:8080/ws/collab'); + expect(realtimeUrl()).toBe('ws://127.0.0.1:8080/ws/realtime'); + }); +}); diff --git a/apps/client/src/lib/endpoints.ts b/apps/client/src/lib/endpoints.ts new file mode 100644 index 00000000..927e2192 --- /dev/null +++ b/apps/client/src/lib/endpoints.ts @@ -0,0 +1,15 @@ +function wsProtocol(): 'ws:' | 'wss:' { + return globalThis.location.protocol === 'https:' ? 'wss:' : 'ws:'; +} + +export const apiUrl = (path = '') => + `${globalThis.location.origin}/api/trpc${path}`; + +export const apiWsUrl = (path = '') => + `${wsProtocol()}//${globalThis.location.host}/api/trpc${path}`; + +export const collabUrl = () => + `${wsProtocol()}//${globalThis.location.host}/ws/collab`; + +export const realtimeUrl = () => + `${wsProtocol()}//${globalThis.location.host}/ws/realtime`; diff --git a/docker-compose.override.yml.example b/docker-compose.override.yml.example new file mode 100644 index 00000000..1b327e1f --- /dev/null +++ b/docker-compose.override.yml.example @@ -0,0 +1,18 @@ +# Optional override for local debugging without a reverse proxy. +# Copy to docker-compose.override.yml and adjust as needed. +# +# Backends are reachable only on the Docker host loopback, not on 0.0.0.0. +# Prefer routing through the client container (port 80) in normal deployments. + +services: + app-server: + ports: + - '127.0.0.1:48922:48922' + + collab-server: + ports: + - '127.0.0.1:48923:48923' + + realtime-server: + ports: + - '127.0.0.1:48924:48924' diff --git a/template.env b/template.env index c2c69d3d..5de8a94f 100644 --- a/template.env +++ b/template.env @@ -6,18 +6,18 @@ SEND_EMAILS=false HOST=deepnotes.local APP_SERVER_PORT=48922 -APP_SERVER_URL=/trpc CLIENT_PORT=60379 CLIENT_URL=http://localhost:60379 CLIENT_APP_URL=https://deepnotes.app +# Comma-separated extra CORS origins (e.g. https://notes.example.com,http://192.168.1.10:8080) +ALLOWED_ORIGINS= + REALTIME_SERVER_PORT=48924 -REALTIME_SERVER_URL=/realtime COLLAB_SERVER_PORT=48923 -COLLAB_SERVER_URL=/collab ACCESS_TOKEN_SECRET="access_token_secret_here" REFRESH_TOKEN_SECRET="refresh_token_secret_here" diff --git a/vitest.config.ts b/vitest.config.ts index b1b780b2..297b152c 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,6 +3,10 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { globals: true, - include: ['packages/**/src/**/*.spec.ts', 'apps/**/src/**/*.spec.ts'], + include: [ + 'packages/**/src/**/*.spec.ts', + 'apps/**/src/**/*.spec.ts', + 'tests/**/*.spec.ts', + ], }, });