diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 2fe457a..3cb50ce 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,16 +4,22 @@ updates: directory: / schedule: interval: weekly + cooldown: + default-days: 14 groups: tanstack: - patterns: ['@tanstack/*'] + patterns: ["@tanstack/*"] minor-and-patch: update-types: [minor, patch] - package-ecosystem: github-actions directory: / schedule: interval: monthly + cooldown: + default-days: 14 - package-ecosystem: docker directory: / schedule: interval: monthly + cooldown: + default-days: 14 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b753b0a..46c294e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,10 +1,9 @@ -# SPDX-License-Identifier: AGPL-3.0-or-later name: CI on: push: branches: [main] - tags: ['v*'] + tags: ["v*"] pull_request: permissions: @@ -18,9 +17,9 @@ jobs: check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version-file: .nvmrc cache: pnpm @@ -31,7 +30,7 @@ jobs: - run: pnpm test - run: pnpm build - name: Install Playwright browser - run: pnpm --filter @cnotes/web exec playwright install --with-deps chromium + run: pnpm --filter @cnotes/frontend exec playwright install --with-deps chromium - run: pnpm test:e2e docker: @@ -41,9 +40,9 @@ jobs: contents: read packages: write steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 - - uses: docker/metadata-action@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + - uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 id: meta with: images: ghcr.io/${{ github.repository }} @@ -51,13 +50,13 @@ jobs: type=ref,event=branch type=semver,pattern={{version}} type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} - - uses: docker/login-action@v3 + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 if: github.event_name != 'pull_request' with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - uses: docker/build-push-action@v6 + - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . platforms: linux/amd64 diff --git a/.github/workflows/commit-messages.yml b/.github/workflows/commit-messages.yml new file mode 100644 index 0000000..dc1d3e4 --- /dev/null +++ b/.github/workflows/commit-messages.yml @@ -0,0 +1,117 @@ +name: Commit messages + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: commit-messages-${{ github.ref }} + cancel-in-progress: true + +jobs: + no-ai-attribution: + name: No AI attribution + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + - name: Reject AI sign-offs and Claude-Session trailers + env: + BASE_REF: ${{ github.event.pull_request.base.ref }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + shopt -s nocasematch + + # Names and domains that mark a trailer as written for an AI tool. + # Each must start a word, so "Haider" doesn't match "aider". + ai='\b(claude|anthropic|copilot|openai|chatgpt|gpt|codex|gemini|cursoragent|devin-ai|aider)' + # A model version: a number standing as its own word ("Claude Opus 5.5", + # "Gemini 2") or a dotted version ("Qwen2.5"). Checked against the name + # only, never the email; handles like "jsmith92" pass. + version='(^|[[:space:]])[0-9]+(\.[0-9]+)*([[:space:]]|$)|[0-9]\.[0-9]' + trailer='^[[:space:]]*[a-z-]+-by:(.*)' + session='^[[:space:]]*claude-session:' + footer='generated with \[?claude code' + + # Prints "number:line" for each attribution line of the message on stdin: + # 1. Any "*-by:" trailer (Co-Authored-By, Signed-off-by, Assisted-by, ...) + # whose name or email names an AI, or whose name has a model version. + # 2. Any Claude-Session trailer. + # 3. The "Generated with Claude Code" footer. + attribution_lines() { + local n=0 line value name + while IFS= read -r line; do + n=$((n + 1)) + if [[ $line =~ $session || $line =~ $footer ]]; then + echo "$n:$line" + elif [[ $line =~ $trailer ]]; then + value=${BASH_REMATCH[1]} + # The name is what's left after removing "" and bare emails. + name=$(sed -E 's/<[^>]*>//g; s/[^[:space:]]+@[^[:space:]]+//g' <<<"$value") + if [[ $value =~ $ai || $name =~ $version ]]; then + echo "$n:$line" + fi + fi + done + } + + total=0 + flagged=0 + report='' + # Oldest first, the same order "git rebase -i" lists them in. + for sha in $(git rev-list --reverse "${BASE_SHA}..${HEAD_SHA}"); do + total=$((total + 1)) + matches=$(git log -1 --format=%B "$sha" | attribution_lines) + [ -n "$matches" ] || continue + flagged=$((flagged + 1)) + # Every line is indented, so nothing from a commit message can + # start a workflow command. + report+=" ${sha:0:7} $(git log -1 --format=%s "$sha")"$'\n' + report+=$(sed -E 's/^([0-9]+):/ line \1: /' <<<"$matches")$'\n\n' + done + + if [ "$flagged" -eq 0 ]; then + echo "No AI attribution found in ${total} commit(s)." + exit 0 + fi + + echo "::error title=AI attribution in commit messages::${flagged} of ${total} commit(s) in this pull request credit an AI tool in the commit message. Reword those commits to delete the attribution lines, then force-push. The job log lists the lines and the exact steps." + cat <` +- `Claude-Session:` lines +- "🤖 Generated with Claude Code" footers + +This applies even when your tool adds these lines by default. The +[Commit messages](.github/workflows/commit-messages.yml) check fails any pull request with a commit that contains them. diff --git a/Dockerfile b/Dockerfile index 92097f2..5fd6b7f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,15 +1,15 @@ -# SPDX-License-Identifier: AGPL-3.0-or-later -# syntax=docker/dockerfile:1 - -FROM node:22-bookworm-slim AS base +# Base images are pinned by digest; Dependabot updates the tag and digest together. +FROM node:26-bookworm-slim@sha256:0042e17d232a87a2cd485be1da7900fca4d10a4ad11b29e9285da1d2e54798c9 AS base ENV PNPM_HOME=/pnpm PATH=/pnpm:$PATH -RUN corepack enable -WORKDIR /src +WORKDIR /app +# Node no longer bundles corepack, so install the pnpm version from package.json +COPY package.json ./ +RUN npm install --global "$(node -p 'require("./package.json").packageManager')" FROM base AS build COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./ -COPY apps/server/package.json apps/server/ -COPY apps/web/package.json apps/web/ +COPY src/backend/package.json src/backend/ +COPY src/frontend/package.json src/frontend/ COPY packages/shared/package.json packages/shared/ RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile COPY . . @@ -17,21 +17,21 @@ ARG CNOTES_VERSION=0.0.0 RUN pnpm build # Server with production dependencies only RUN --mount=type=cache,id=pnpm,target=/pnpm/store \ - pnpm deploy --legacy --prod --filter @cnotes/server /out/server + pnpm deploy --legacy --prod --filter @cnotes/backend /out/backend -FROM node:22-bookworm-slim AS runtime +FROM node:26-bookworm-slim@sha256:0042e17d232a87a2cd485be1da7900fca4d10a4ad11b29e9285da1d2e54798c9 AS runtime ARG CNOTES_VERSION=0.0.0 ENV NODE_ENV=production \ HOST=0.0.0.0 \ PORT=3000 \ DATA_DIR=/data \ - WEB_ROOT=/app/web \ + WEB_ROOT=/app/frontend \ CNOTES_VERSION=$CNOTES_VERSION -WORKDIR /app/server -COPY --from=build /out/server/node_modules ./node_modules -COPY --from=build /out/server/package.json ./package.json -COPY --from=build /src/apps/server/dist ./dist -COPY --from=build /src/apps/web/dist/client /app/web +WORKDIR /app/backend +COPY --from=build /out/backend/node_modules ./node_modules +COPY --from=build /out/backend/package.json ./package.json +COPY --from=build /app/src/backend/dist ./dist +COPY --from=build /app/src/frontend/dist/client /app/frontend RUN mkdir -p /data && chown node:node /data USER node VOLUME ["/data"] diff --git a/README.md b/README.md index 682b87f..2253765 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,33 @@ -# Cnotes +# `cnotes` (pronounced _snotes_) + +A self-hosted notes and lists app adapted for households. Several people can edit the same pages at once, and it keeps working offline. + +- Nested pages with a rich-text editor (Markdown) +- Offline edits merge when the device reconnects. +- Pinned lists (shopping, packing) stay downloaded for use without signal. +- Inline photos (location data removed) and file attachments. +- Installs to the home screen as a web app (PWA) on iPhone and Android. +- Password and two-factor sign-in. +- Daily backups and Markdown export. + +**Not a fit if you need:** +- Public sign-up +- Sharing info with guest accounts +- Separate workspaces for different users + +## License Licensed under AGPL-3.0-or-later. See [LICENSE](LICENSE). + +## Development + +Requires Node 26 and pnpm (`npm install -g corepack && corepack enable`). + +```sh +pnpm install +pnpm dev # http://localhost:5173 +``` + +Dev mode skips the setup token and two-factor. Data is stored in `src/backend/data/`. + +Checks and builds: [docs/development.md](docs/development.md). Running it on a server: [docs/deployment.md](docs/deployment.md). diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts deleted file mode 100644 index dbf57c8..0000000 --- a/apps/server/src/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { buildApp } from './app' -import { loadConfig } from './config' - -const config = loadConfig() -const app = await buildApp(config) - -for (const signal of ['SIGINT', 'SIGTERM'] as const) { - process.once(signal, () => { - app.log.info({ signal }, 'shutting down') - void app.close().then(() => process.exit(0)) - }) -} - -await app.listen({ host: config.host, port: config.port }) diff --git a/apps/server/src/secrets.ts b/apps/server/src/secrets.ts deleted file mode 100644 index 912acc0..0000000 --- a/apps/server/src/secrets.ts +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import crypto from 'node:crypto' -import fs from 'node:fs' -import path from 'node:path' - -/** - * Key used to encrypt TOTP secrets at rest. Taken from CNOTES_SECRET_KEY - * (base64, 32 bytes) or generated once into DATA_DIR/secret.key. - * Keeping it outside the database means a leaked database or backup does - * not leak the 2FA secrets. - */ -export function loadSecretKey(dataDir: string, fromEnv?: string): Buffer { - if (fromEnv) { - const key = Buffer.from(fromEnv, 'base64') - if (key.length !== 32) throw new Error('CNOTES_SECRET_KEY must be 32 bytes, base64 encoded') - return key - } - const file = path.join(dataDir, 'secret.key') - if (fs.existsSync(file)) { - const key = Buffer.from(fs.readFileSync(file, 'utf8').trim(), 'base64') - if (key.length !== 32) throw new Error(`${file} is not a valid key`) - return key - } - const key = crypto.randomBytes(32) - fs.writeFileSync(file, key.toString('base64') + '\n', { mode: 0o600, flag: 'wx' }) - return key -} - -export function encrypt(key: Buffer, plaintext: string): string { - const iv = crypto.randomBytes(12) - const cipher = crypto.createCipheriv('aes-256-gcm', key, iv) - const data = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]) - return [ - 'v1', - iv.toString('base64'), - cipher.getAuthTag().toString('base64'), - data.toString('base64'), - ].join('.') -} - -export function decrypt(key: Buffer, payload: string): string { - const [version, iv, tag, data] = payload.split('.') - if (version !== 'v1' || !iv || !tag || !data) throw new Error('Unknown ciphertext format') - const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'base64')) - decipher.setAuthTag(Buffer.from(tag, 'base64')) - return Buffer.concat([decipher.update(Buffer.from(data, 'base64')), decipher.final()]).toString( - 'utf8', - ) -} - -export function randomId(bytes = 12): string { - return crypto.randomBytes(bytes).toString('base64url') -} - -export function sha256(data: string | Buffer): string { - return crypto.createHash('sha256').update(data).digest('hex') -} - -export function timingSafeEqualStr(a: string, b: string): boolean { - const ab = Buffer.from(a) - const bb = Buffer.from(b) - return ab.length === bb.length && crypto.timingSafeEqual(ab, bb) -} diff --git a/apps/server/test/app.test.ts b/apps/server/test/app.test.ts deleted file mode 100644 index eaa8c88..0000000 --- a/apps/server/test/app.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { inlineScriptHashes } from '../src/app' -import { loadConfig } from '../src/config' -import { makeApp, type TestApp } from './helpers' - -describe('static app serving', () => { - let webRoot: string - let app: TestApp - let cleanup: () => Promise - - beforeAll(async () => { - webRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cnotes-web-')) - fs.writeFileSync( - path.join(webRoot, '_shell.html'), - 'Cnotes', - ) - fs.mkdirSync(path.join(webRoot, 'assets')) - fs.writeFileSync(path.join(webRoot, 'assets', 'app-abc123.js'), 'console.log(1)') - ;({ app, cleanup } = await makeApp({ webRoot })) - }) - - afterAll(async () => { - await cleanup() - fs.rmSync(webRoot, { recursive: true, force: true }) - }) - - it('reports health', async () => { - const res = await app.inject({ method: 'GET', url: '/api/health' }) - expect(res.statusCode).toBe(200) - expect(res.json()).toEqual({ status: 'ok', version: '1.2.3' }) - }) - - it('serves the app shell for client routes', async () => { - const res = await app.inject({ method: 'GET', url: '/pages/some-page' }) - expect(res.statusCode).toBe(200) - expect(res.headers['content-type']).toContain('text/html') - expect(res.headers['cache-control']).toBe('no-cache') - expect(res.body).toContain('Cnotes') - }) - - it('caches hashed assets forever', async () => { - const res = await app.inject({ method: 'GET', url: '/assets/app-abc123.js' }) - expect(res.statusCode).toBe(200) - expect(res.headers['cache-control']).toContain('immutable') - }) - - it('returns JSON 404 for unknown API routes', async () => { - const res = await app.inject({ method: 'GET', url: '/api/nope' }) - expect(res.statusCode).toBe(404) - expect(res.json()).toEqual({ error: 'Not Found' }) - }) - - it('sends security headers and allows the shell scripts by hash only', async () => { - const res = await app.inject({ method: 'GET', url: '/api/health' }) - const csp = String(res.headers['content-security-policy']) - expect(csp).toContain("default-src 'self'") - expect(csp).toContain(inlineScriptHashes('')[0]) - expect(csp).not.toMatch(/script-src[^;]*unsafe-inline/) - expect(res.headers['x-content-type-options']).toBe('nosniff') - }) - - it('blocks cross-origin state-changing requests', async () => { - const res = await app.inject({ - method: 'POST', - url: '/api/auth/login', - headers: { origin: 'https://evil.example', host: 'notes.example.se' }, - payload: { username: 'x', password: 'y' }, - }) - expect(res.statusCode).toBe(403) - }) -}) - -describe('inlineScriptHashes', () => { - it('hashes inline scripts and skips external ones', () => { - const html = - '' - const hashes = inlineScriptHashes(html) - expect(hashes).toHaveLength(2) - expect(hashes[0]).toMatch(/^'sha256-[A-Za-z0-9+/]+=*'$/) - }) -}) - -describe('loadConfig', () => { - it('parses TRUST_PROXY', () => { - expect(loadConfig({}).trustProxy).toBe(false) - expect(loadConfig({ TRUST_PROXY: 'true' }).trustProxy).toBe(true) - expect(loadConfig({ TRUST_PROXY: '172.16.0.0/12' }).trustProxy).toBe('172.16.0.0/12') - }) - - it('rejects invalid numbers', () => { - expect(() => loadConfig({ PORT: 'abc' })).toThrow('Invalid PORT') - expect(() => loadConfig({ BACKUP_HOUR: '25' })).toThrow('Invalid BACKUP_HOUR') - }) -}) diff --git a/apps/server/test/auth.test.ts b/apps/server/test/auth.test.ts deleted file mode 100644 index 21093d8..0000000 --- a/apps/server/test/auth.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { deviceNameFromUserAgent } from '../src/auth' -import { cookieFrom, makeApp, SETUP_TOKEN, signUp, totpCode, type TestApp } from './helpers' - -let app: TestApp -let cleanup: () => Promise - -beforeEach(async () => { - ;({ app, cleanup } = await makeApp()) -}) -afterEach(async () => cleanup()) - -const PASSWORD = 'correct horse battery' - -async function login(username: string, password = PASSWORD) { - return app.inject({ method: 'POST', url: '/api/auth/login', payload: { username, password } }) -} - -describe('first-run setup', () => { - it('requires the setup token and only works once', async () => { - let res = await app.inject({ method: 'GET', url: '/api/auth/state' }) - expect(res.json()).toEqual({ setupRequired: true, setupTokenRequired: true, user: null }) - - res = await app.inject({ - method: 'POST', - url: '/api/auth/setup', - payload: { setupToken: 'wrong', username: 'sara', displayName: 'Sara', password: PASSWORD }, - }) - expect(res.statusCode).toBe(403) - - await signUp(app) - res = await app.inject({ - method: 'POST', - url: '/api/auth/setup', - payload: { setupToken: SETUP_TOKEN, username: 'eve', displayName: 'Eve', password: PASSWORD }, - }) - expect(res.statusCode).toBe(403) - res = await app.inject({ method: 'GET', url: '/api/auth/state' }) - expect(res.json().setupRequired).toBe(false) - }) - - it('needs only a username and password, with no password rules', async () => { - let res = await app.inject({ - method: 'POST', - url: '/api/auth/setup', - payload: { setupToken: SETUP_TOKEN, username: 'sara', password: 'x' }, - }) - expect(res.statusCode).toBe(201) - expect(res.json()).toMatchObject({ username: 'sara', displayName: 'sara' }) - res = await login('sara', 'x') - expect(res.json().step).toBe('enroll') - }) -}) - -describe('dev mode', () => { - it('skips the setup token and two-factor', async () => { - await cleanup() - ;({ app, cleanup } = await makeApp({ devMode: true })) - let res = await app.inject({ method: 'GET', url: '/api/auth/state' }) - expect(res.json()).toEqual({ setupRequired: true, setupTokenRequired: false, user: null }) - - res = await app.inject({ - method: 'POST', - url: '/api/auth/setup', - payload: { username: 'sara', password: 'pw' }, - }) - expect(res.statusCode).toBe(201) - - res = await login('sara', 'wrong') - expect(res.statusCode).toBe(401) - res = await login('sara', 'pw') - expect(res.statusCode).toBe(200) - expect(res.json()).toMatchObject({ step: 'done', user: { username: 'sara' } }) - const cookie = cookieFrom(res) - res = await app.inject({ method: 'GET', url: '/api/auth/state', headers: { cookie } }) - expect(res.json().user.username).toBe('sara') - }) -}) - -describe('sign-in with two-factor', () => { - it('enrolls on first sign-in, then asks for a code', async () => { - const { cookie, secret, recoveryCodes } = await signUp(app) - expect(recoveryCodes).toHaveLength(10) - - const state = await app.inject({ method: 'GET', url: '/api/auth/state', headers: { cookie } }) - expect(state.json().user).toMatchObject({ username: 'sara' }) - - const step1 = await login('sara') - expect(step1.json().step).toBe('totp') - const ok = await app.inject({ - method: 'POST', - url: '/api/auth/verify', - payload: { challenge: step1.json().challenge, code: totpCode(secret, 1) }, - }) - expect(ok.statusCode).toBe(200) - expect(cookieFrom(ok)).toMatch(/^cnotes_session=/) - expect(String(ok.headers['set-cookie'])).toMatch(/HttpOnly/i) - expect(String(ok.headers['set-cookie'])).toMatch(/SameSite=Strict/i) - }) - - it('rejects a wrong password without saying which part was wrong', async () => { - await signUp(app) - const a = await login('sara', 'wrong password!!') - const b = await login('nobody', 'wrong password!!') - expect(a.statusCode).toBe(401) - expect(b.statusCode).toBe(401) - expect(a.json()).toEqual(b.json()) - }) - - it('rejects a reused code', async () => { - const { secret } = await signUp(app) - const code = totpCode(secret, 1) - const first = await login('sara') - expect( - ( - await app.inject({ - method: 'POST', - url: '/api/auth/verify', - payload: { challenge: first.json().challenge, code }, - }) - ).statusCode, - ).toBe(200) - const second = await login('sara') - const replay = await app.inject({ - method: 'POST', - url: '/api/auth/verify', - payload: { challenge: second.json().challenge, code }, - }) - expect(replay.statusCode).toBe(401) - }) - - it('accepts each recovery code once', async () => { - const { recoveryCodes } = await signUp(app) - const use = async () => { - const step1 = await login('sara') - return app.inject({ - method: 'POST', - url: '/api/auth/verify', - payload: { challenge: step1.json().challenge, code: recoveryCodes[0]!.toUpperCase() }, - }) - } - expect((await use()).statusCode).toBe(200) - expect((await use()).statusCode).toBe(401) - }) - - it('limits attempts per challenge', async () => { - await signUp(app) - const { challenge } = (await login('sara')).json() - const codes = [] - for (let i = 0; i < 6; i++) { - codes.push( - ( - await app.inject({ - method: 'POST', - url: '/api/auth/verify', - payload: { challenge, code: '000000' }, - }) - ).statusCode, - ) - } - expect(codes.at(-1)).toBe(429) - }) -}) - -describe('sessions and members', () => { - it('lists and revokes sessions', async () => { - const { cookie } = await signUp(app) - const list = await app.inject({ method: 'GET', url: '/api/auth/sessions', headers: { cookie } }) - expect(list.json()).toHaveLength(1) - expect(list.json()[0].current).toBe(true) - - const del = await app.inject({ - method: 'DELETE', - url: `/api/auth/sessions/${list.json()[0].id}`, - headers: { cookie }, - }) - expect(del.statusCode).toBe(204) - const after = await app.inject({ - method: 'GET', - url: '/api/auth/sessions', - headers: { cookie }, - }) - expect(after.statusCode).toBe(401) - }) - - it('lets a member add the second person, who enrolls their own 2FA', async () => { - const sara = await signUp(app) - const partner = await signUp(app, 'alex', 'another long password', sara.cookie) - const users = await app.inject({ - method: 'GET', - url: '/api/auth/users', - headers: { cookie: partner.cookie }, - }) - expect(users.json().map((u: { username: string }) => u.username)).toEqual(['sara', 'alex']) - }) - - it('logs out', async () => { - const { cookie } = await signUp(app) - await app.inject({ method: 'POST', url: '/api/auth/logout', headers: { cookie } }) - const me = await app.inject({ method: 'GET', url: '/api/auth/me', headers: { cookie } }) - expect(me.statusCode).toBe(401) - }) - - it('changes the password', async () => { - const { cookie } = await signUp(app) - const res = await app.inject({ - method: 'POST', - url: '/api/auth/password', - headers: { cookie }, - payload: { currentPassword: PASSWORD, newPassword: 'a brand new password' }, - }) - expect(res.statusCode).toBe(204) - expect((await login('sara')).statusCode).toBe(401) - expect((await login('sara', 'a brand new password')).statusCode).toBe(200) - }) -}) - -describe('deviceNameFromUserAgent', () => { - it('names common devices', () => { - expect( - deviceNameFromUserAgent( - 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1', - ), - ).toBe('iPhone · Safari') - expect( - deviceNameFromUserAgent( - 'Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36', - ), - ).toBe('Android · Chrome') - }) -}) diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.ts deleted file mode 100644 index aede9d1..0000000 --- a/apps/server/vitest.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - name: 'server', - include: ['test/**/*.test.ts'], - environment: 'node', - }, -}) diff --git a/apps/web/e2e/auth.spec.ts b/apps/web/e2e/auth.spec.ts deleted file mode 100644 index 6d9ec1d..0000000 --- a/apps/web/e2e/auth.spec.ts +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { expect, test } from '@playwright/test' -import { PASSWORD, STATE, totp, unique } from './helpers' - -test('a new household member signs in and sets up two-factor', async ({ page, browser }) => { - // Sara adds the person through the API with her session. - const sara = await browser.newContext({ - storageState: STATE.sara, - baseURL: 'http://localhost:3100', - }) - const username = unique('kid').replace(' ', '') - const created = await sara.request.post('/api/auth/users', { - data: { username, displayName: 'Kid', password: PASSWORD }, - }) - expect(created.ok()).toBe(true) - await sara.close() - - await page.goto('/') - await page.getByLabel('Username').fill(username) - await page.getByLabel('Password').fill(PASSWORD) - await page.getByRole('button', { name: 'Continue' }).click() - - await expect(page.getByRole('heading', { name: 'Set up two-factor' })).toBeVisible() - await expect(page.getByRole('img', { name: /QR code/ })).toBeVisible() - const secret = (await page.locator('p.font-mono').textContent())!.trim() - await page.getByLabel(/6-digit code/).fill(totp(secret)) - await page.getByRole('button', { name: 'Confirm' }).click() - - await expect(page.getByRole('heading', { name: 'Save your recovery codes' })).toBeVisible() - await expect(page.getByTestId('recovery-codes').locator('li')).toHaveCount(10) - await page.getByRole('button', { name: 'I have saved them' }).click() - await expect(page.getByRole('heading', { name: 'Pinned' })).toBeVisible() - - // Sign out, then back in with a code. - await page.getByRole('link', { name: 'Settings' }).click() - await page.getByRole('button', { name: 'Sign out on this device' }).click() - await page.getByLabel('Username').fill(username) - await page.getByLabel('Password').fill(PASSWORD) - await page.getByRole('button', { name: 'Continue' }).click() - await page.getByLabel(/authenticator app/).fill(totp(secret, 1)) - await page.getByRole('button', { name: 'Sign in' }).click() - // Back where they were, signed in again. - await expect(page.getByText(`Signed in as Kid (${username})`)).toBeVisible() - await expect(page.getByTestId('sync-status')).toHaveAttribute('data-state', 'synced') -}) diff --git a/apps/web/e2e/pages.spec.ts b/apps/web/e2e/pages.spec.ts deleted file mode 100644 index 3246209..0000000 --- a/apps/web/e2e/pages.spec.ts +++ /dev/null @@ -1,204 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import path from 'node:path' -import { expect, test } from '@playwright/test' -import { unzipSync } from 'fflate' -import { newPage, signedInPage, STATE, unique, waitForSynced } from './helpers' - -test.use({ storageState: STATE.sara }) - -test('shopping list: checklist, pin, open count, clear checked', async ({ page }) => { - const title = unique('Weekly shopping') - await newPage(page, title) - const editor = page.getByTestId('editor') - await editor.click() - await page.keyboard.type('[ ] Mjölk') - await page.keyboard.press('Enter') - await page.keyboard.type('Bröd') - await page.keyboard.press('Enter') - await page.keyboard.type('Diskmaskinstabletter') - await expect(editor.locator('ul[data-type="taskList"] > li')).toHaveCount(3) - - await editor - .locator('ul[data-type="taskList"] > li') - .nth(1) - .locator('input[type="checkbox"]') - .check() - await expect(page.getByRole('button', { name: 'Clear checked (1)' })).toBeVisible() - - await page.getByRole('button', { name: 'Page actions' }).click() - await page.getByRole('menuitem', { name: 'Pin to Home' }).click() - - await page.getByRole('link', { name: 'Home' }).click() - const pinned = page.getByTestId('pinned').getByRole('link', { name: new RegExp(title) }) - await expect(pinned).toContainText('2') - - await pinned.click() - await page.getByRole('button', { name: 'Clear checked (1)' }).click() - await expect(page.getByTestId('editor').locator('ul[data-type="taskList"] > li')).toHaveCount(2) - await expect(page.getByTestId('editor')).not.toContainText('Bröd') -}) - -test('Markdown shortcuts, subpages, move and archive', async ({ page }) => { - const parent = unique('Home appliances') - await newPage(page, parent) - const editor = page.getByTestId('editor') - await editor.click() - await page.keyboard.type('## Kitchen') - await page.keyboard.press('Enter') - await page.keyboard.type('- Dishwasher: **Bosch** SMS4') - await expect(editor.locator('h2')).toHaveText('Kitchen') - await expect(editor.locator('ul li strong')).toHaveText('Bosch') - - await page.getByRole('button', { name: 'Page actions' }).click() - await page.getByRole('menuitem', { name: 'Add subpage' }).click() - const child = unique('Dishwasher manual') - await page.getByLabel('Page title').fill(child) - await expect(page.getByRole('navigation', { name: 'Breadcrumb' })).toContainText(parent) - - await page.goto('/pages') - const tree = page.getByTestId('page-tree') - await expect( - tree.locator('li', { hasText: parent }).getByRole('link', { name: child }), - ).toBeVisible() - - // Move the child to the top level, then archive it. - await tree.getByRole('link', { name: child }).click() - await page.getByRole('button', { name: 'Page actions' }).click() - await page.getByRole('menuitem', { name: 'Move…' }).click() - await page.getByLabel(/Move “/).selectOption({ label: 'Top level' }) - await page.getByRole('button', { name: 'Move', exact: true }).click() - await expect(page.getByRole('navigation', { name: 'Breadcrumb' })).toHaveCount(0) - - await page.getByRole('button', { name: 'Page actions' }).click() - await page.getByRole('menuitem', { name: 'Archive' }).click() - await expect(page).toHaveURL(/\/pages$/) - await expect(page.getByTestId('page-tree').getByRole('link', { name: child })).toHaveCount(0) - await page.getByRole('button', { name: /Show archived/ }).click() - await expect(page.getByRole('link', { name: child })).toBeVisible() -}) - -test('photos inline and file attachments', async ({ page }) => { - await newPage(page, unique('Warranty')) - await page.getByTestId('editor').click() - await page.getByTestId('photo-input').setInputFiles(path.resolve('public/apple-touch-icon.png')) - const img = page.getByTestId('editor').locator('img') - await expect(img).toBeVisible() - await expect(img).toHaveJSProperty('complete', true) - expect(await img.evaluate((el: HTMLImageElement) => el.naturalWidth)).toBeGreaterThan(0) - - await page.getByTestId('file-input').setInputFiles({ - name: 'Bosch manual.pdf', - mimeType: 'application/pdf', - buffer: Buffer.from('%PDF-1.4 test'), - }) - const chip = page.getByTestId('editor').locator('a[data-file-attachment]') - await expect(chip).toContainText('Bosch manual.pdf') - const download = await (await page.request.get((await chip.getAttribute('href'))!)).text() - expect(download).toBe('%PDF-1.4 test') -}) - -test('search finds words inside pages, including parts of Swedish compound words', async ({ - page, -}) => { - const title = unique('Cleaning') - await newPage(page, title) - await page.getByTestId('editor').click() - const word = `Tvättmaskinsrengöring${Math.random().toString(36).slice(2, 6)}` - await page.keyboard.type(`Use ${word} monthly`) - await waitForSynced(page) - - await page.getByRole('link', { name: 'Search' }).click() - // The server indexes after a short debounce. - await expect(async () => { - await page.getByLabel('Search').fill('') - await page.getByLabel('Search').fill(word.slice(4, 14).replace('ö', 'o')) - await expect( - page.getByTestId('search-results').getByRole('link', { name: new RegExp(title) }), - ).toBeVisible({ - timeout: 2000, - }) - }).toPass({ timeout: 20_000 }) - await expect(page.getByTestId('search-results').locator('mark').first()).toBeVisible() -}) - -test('two people edit the same page live', async ({ page, browser }, info) => { - const title = unique('Packing list') - const url = await newPage(page, title) - await page.getByTestId('editor').click() - await page.keyboard.type('[ ] Passports') - await waitForSynced(page) - - const alex = await signedInPage(browser, 'alex', info.project.name) - await alex.page.goto(url) - const alexEditor = alex.page.getByTestId('editor') - await expect(alexEditor).toContainText('Passports') - - await alexEditor.locator('li', { hasText: 'Passports' }).click() - await alex.page.keyboard.press('End') - await alex.page.keyboard.press('Enter') - await alex.page.keyboard.type('Chargers') - await expect(page.getByTestId('editor')).toContainText('Chargers') - // Sara sees Alex's cursor. - await expect(page.locator('.collaboration-carets__label', { hasText: 'Alex' })).toBeVisible() - // And the title edit reaches Alex too. - await page.getByLabel('Page title').fill(`${title} (Italy)`) - await expect(alex.page.getByLabel('Page title')).toHaveValue(`${title} (Italy)`) - await alex.context.close() -}) - -test('edits made offline sync when back online', async ({ page, context, browser }, info) => { - const title = unique('Offline list') - const url = await newPage(page, title) - await page.getByTestId('editor').click() - await page.keyboard.type('[ ] Coffee') - await waitForSynced(page) - await page.waitForFunction(() => navigator.serviceWorker.controller !== null) - - await context.setOffline(true) - await expect(page.getByTestId('sync-status')).toHaveAttribute('data-state', 'offline') - // The app still opens offline from the cached shell and local data. - await page.reload() - await expect(page.getByTestId('editor')).toContainText('Coffee') - await page.getByTestId('editor').locator('li', { hasText: 'Coffee' }).click() - await page.keyboard.press('End') - await page.keyboard.press('Enter') - await page.keyboard.type('Oat milk') - await expect(page.getByTestId('sync-status')).toContainText('Offline') - - await context.setOffline(false) - await waitForSynced(page) - - const alex = await signedInPage(browser, 'alex', info.project.name) - await alex.page.goto(url) - await expect(alex.page.getByTestId('editor')).toContainText('Oat milk') - await alex.context.close() -}) - -test('export contains the pages as Markdown', async ({ page }) => { - const title = unique('Export check') - await newPage(page, title) - const editor = page.getByTestId('editor') - await editor.click() - await page.keyboard.type('## Week') - await page.keyboard.press('Enter') - await page.keyboard.type('[ ] Mjölk') - await page.keyboard.press('Enter') - await page.keyboard.type('Ost') - await editor - .locator('ul[data-type="taskList"] > li') - .nth(1) - .locator('input[type="checkbox"]') - .check() - await page.keyboard.press('Enter') - await page.keyboard.press('Enter') - await page.keyboard.type('Buy at ') - await page.keyboard.press('ControlOrMeta+b') - await page.keyboard.type('ICA') - await waitForSynced(page) - - const res = await page.request.get('/api/export') - expect(res.headers()['content-type']).toBe('application/zip') - const files = unzipSync(new Uint8Array(await res.body())) - const md = new TextDecoder().decode(files[`${title}.md`]) - expect(md).toBe(`# ${title}\n\n## Week\n\n- [ ] Mjölk\n- [x] Ost\n\nBuy at **ICA**\n`) -}) diff --git a/apps/web/e2e/smoke.spec.ts b/apps/web/e2e/smoke.spec.ts deleted file mode 100644 index 0de2038..0000000 --- a/apps/web/e2e/smoke.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { expect, test } from '@playwright/test' -import { STATE } from './helpers' - -test.describe('signed out', () => { - test('shows the sign-in screen and the manifest', async ({ page, request }) => { - await page.goto('/') - await expect(page.getByRole('heading', { name: 'Sign in to Cnotes' })).toBeVisible() - const manifest = await (await request.get('/manifest.webmanifest')).json() - expect(manifest).toMatchObject({ name: 'Cnotes', display: 'standalone', start_url: '/' }) - }) - - test('rejects a wrong password', async ({ page }) => { - await page.goto('/') - await page.getByLabel('Username').fill('sara') - await page.getByLabel('Password').fill('not the password') - await page.getByRole('button', { name: 'Continue' }).click() - await expect(page.getByRole('alert')).toHaveText('Wrong username or password') - }) -}) - -test.describe('signed in', () => { - test.use({ storageState: STATE.sara }) - - test('home loads without errors and navigation works', async ({ page }) => { - const errors: string[] = [] - page.on('console', (msg) => { - if (msg.type() === 'error') errors.push(msg.text()) - }) - page.on('pageerror', (err) => errors.push(err.message)) - - await page.goto('/') - await expect(page.getByRole('heading', { name: 'Pinned' })).toBeVisible() - await expect(page.getByTestId('sync-status')).toHaveAttribute('data-state', 'synced') - - await page.getByRole('link', { name: 'Settings' }).click() - await expect(page.getByText('Signed in as Sara (sara)')).toBeVisible() - await page.getByRole('link', { name: 'About Cnotes' }).click() - await expect(page.getByRole('link', { name: 'Source code' })).toHaveAttribute( - 'href', - 'https://github.com/cedernaes/cnotes', - ) - - // Deep link straight into a route. - await page.goto('/pages') - await expect(page.getByRole('heading', { name: 'Pages' })).toBeVisible() - // CSP violations, hydration errors and failed requests show up here. - expect(errors).toEqual([]) - }) -}) diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts deleted file mode 100644 index 9b08f3a..0000000 --- a/apps/web/playwright.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { defineConfig, devices } from '@playwright/test' - -export const PORT = 3100 -export const SETUP_TOKEN = 'e2e-setup-token' - -export default defineConfig({ - testDir: 'e2e', - fullyParallel: true, - forbidOnly: !!process.env.CI, - retries: process.env.CI ? 1 : 0, - reporter: process.env.CI ? 'github' : 'list', - globalSetup: './e2e/global-setup.ts', - use: { - baseURL: `http://localhost:${PORT}`, - trace: 'off', - }, - projects: [ - { name: 'iphone', use: { ...devices['iPhone 15'], browserName: 'chromium' } }, - { name: 'android', use: { ...devices['Pixel 7'] } }, - ], - // Runs the production server against the built web app (`pnpm build` first), - // with a fresh data folder each run. - webServer: { - command: 'rm -rf test-results/e2e-data && node ../server/dist/index.js', - url: `http://localhost:${PORT}/api/health`, - reuseExistingServer: false, - env: { - PORT: String(PORT), - WEB_ROOT: 'dist/client', - DATA_DIR: 'test-results/e2e-data', - CNOTES_SETUP_TOKEN: SETUP_TOKEN, - LOG_LEVEL: 'warn', - }, - }, -}) diff --git a/apps/web/src/lib/useCreatePage.ts b/apps/web/src/lib/useCreatePage.ts deleted file mode 100644 index 13e74fc..0000000 --- a/apps/web/src/lib/useCreatePage.ts +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { useNavigate } from '@tanstack/react-router' -import { useUser } from './auth' -import { createPage } from './workspace' - -export function useCreatePage() { - const user = useUser() - const navigate = useNavigate() - return (parentId: string | null = null) => { - const id = createPage({ parentId, userId: user.id }) - void navigate({ to: '/p/$pageId', params: { pageId: id }, search: { new: true } }) - } -} diff --git a/apps/web/src/router.tsx b/apps/web/src/router.tsx deleted file mode 100644 index 1626c3d..0000000 --- a/apps/web/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - defaultPreload: 'intent', - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/compose.yaml b/compose.yaml index a20acfb..a00bc18 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,23 +1,21 @@ -# SPDX-License-Identifier: AGPL-3.0-or-later -# Cnotes behind an existing reverse proxy (see deploy/nginx.conf). +# cnotes behind an existing reverse proxy (see docs/deployment.md). services: cnotes: # Built from this checkout. `docker compose up -d --build` rebuilds after a `git pull`. - # To use the published image instead (needs `docker login ghcr.io` while the - # repository is private), remove `build` and keep `image`. + # To use the published image instead, remove `build` and `pull_policy` and keep `image`. build: . image: ghcr.io/cedernaes/cnotes:latest pull_policy: build restart: unless-stopped ports: # Only reachable from the host; Nginx proxies to it. - - '127.0.0.1:3000:3000' + - "127.0.0.1:3000:3000" environment: # Address of Nginx as seen from the container (Docker bridge gateway), # so logs and rate limits see real client IPs. - TRUST_PROXY: '172.16.0.0/12' + TRUST_PROXY: "172.16.0.0/12" LOG_LEVEL: info - # Optional, see apps/server/.env.example: + # Optional, see src/backend/.env.example: # CNOTES_SETUP_TOKEN: choose-a-token-for-the-first-account # BACKUP_HOUR: '3' # BACKUP_KEEP: '14' diff --git a/deploy/nginx.conf b/deploy/nginx.conf deleted file mode 100644 index 65ec55a..0000000 --- a/deploy/nginx.conf +++ /dev/null @@ -1,38 +0,0 @@ -# Example Nginx site for Cnotes on its own subdomain. -# Put your existing TLS settings (the same as for Home Assistant) where marked. - -map $http_upgrade $connection_upgrade { - default upgrade; - '' close; -} - -server { - listen 443 ssl; - http2 on; - server_name notes.example.se; - - # ssl_certificate /etc/letsencrypt/live/notes.example.se/fullchain.pem; - # ssl_certificate_key /etc/letsencrypt/live/notes.example.se/privkey.pem; - - # Photo and file uploads - client_max_body_size 50m; - - location / { - proxy_pass http://127.0.0.1:3000; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - } - - # Live sync (WebSocket) - location /sync { - proxy_pass http://127.0.0.1:3000; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_read_timeout 1h; - } -} diff --git a/docs/PLAN.md b/docs/PLAN.md index afbd577..26a84be 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,8 +1,8 @@ -# Cnotes: architecture and roadmap plan +# cnotes: architecture and roadmap plan Status: draft for review (updated 2026-11-28 with the family's answers) -Cnotes is a self-hosted, Notion-like app for household information: shopping and packing lists, notes, manuals and anything else we want to find again. It is mobile first, works offline, lets both of us edit the same page at once, and is licensed AGPL-3.0-or-later. +cnotes is a self-hosted, Notion-like app for household information: shopping and packing lists, notes, manuals and anything else we want to find again. It is mobile first, works offline, lets both of us edit the same page at once, and is licensed AGPL-3.0-or-later. This document proposes the architecture, stack, data model and a phased roadmap. Decisions already made are listed in section 1; remaining open questions are at the end. @@ -119,7 +119,7 @@ Other server pieces: | Part | Choice | |---|---| -| Database | SQLite (`better-sqlite3`) in WAL mode, with plain SQL migrations (`apps/server/src/db.ts`); small enough that an ORM adds more than it saves | +| Database | SQLite (`better-sqlite3`) in WAL mode, with plain SQL migrations (`src/backend/src/db.ts`); small enough that an ORM adds more than it saves | | Search | SQLite FTS5 | | Passwords | Argon2id (`@node-rs/argon2`) | | 2FA | TOTP (RFC 6238, works with any authenticator app) + one-time recovery codes | @@ -128,7 +128,7 @@ Other server pieces: ### 4.3 How TanStack Start fits with a separate backend -TanStack Start can also run server code itself (SSR and "server functions"). We recommend **not** using that for Cnotes, and running Start in SPA mode with Fastify as the only backend: +TanStack Start can also run server code itself (SSR and "server functions"). We recommend **not** using that for cnotes, and running Start in SPA mode with Fastify as the only backend: - **Offline first:** the app must open with no network. A static app shell cached by the service worker does that reliably; server-rendered pages do not help offline and complicate caching. - **Stability:** Start's server runtime is young and changes quickly. Keeping all server logic in Fastify means framework churn only affects the UI build, and the security-sensitive part (auth, files) sits on a mature, stable framework. @@ -138,8 +138,8 @@ TanStack Start can also run server code itself (SSR and "server functions"). We ### 4.4 Repo layout and tooling ``` -apps/web TanStack Start app (React, TSX, Vite) -apps/server Fastify + Hocuspocus +src/frontend TanStack Start app (React, TSX, Vite) +src/backend Fastify + Hocuspocus packages/shared Shared types, schemas, document schema version, editor extensions list docs/ This plan, deployment notes ``` @@ -227,14 +227,14 @@ Two accounts also give "last edited by" on pages and authorship in history. ## 8. Mobile-first PWA, and iOS limits -Both phones install Cnotes from the browser to the home screen and run it full-screen like an app. +Both phones install cnotes from the browser to the home screen and run it full-screen like an app. | Topic | Android (Chrome) | iPhone | What we do | |---|---|---|---| | Install | Install prompt | Manual: Share → "Add to Home Screen" | One-time install hint on iOS | | Offline storage | Persistent | Can be evicted under storage pressure (home-screen apps are exempt from Safari's 7-day rule) | Request `navigator.storage.persist()`; server is the source of truth, so eviction only risks *unsynced* edits; clear "not synced yet" indicator | | Background sync | Supported | Not supported: sync only while the app is open | Sync on open, on resume and on every change | -| Share into Cnotes from other apps | Web Share Target works | Not supported | Android: share links/photos to a page (phase 3) | +| Share into cnotes from other apps | Web Share Target works | Not supported | Android: share links/photos to a page (phase 3) | | Push notifications | Supported | Supported for home-screen apps (iOS 16.4+) | Not planned for MVP | | Camera / photos | Supported | Supported | Inline photos from camera or library | | Storage isolation | | Home-screen app has separate storage from Safari | Log in once inside the installed app | @@ -283,9 +283,9 @@ server { ## 10. License: AGPL-3.0-or-later -- `LICENSE` (AGPL-3.0) is in the repo; source files carry `SPDX-License-Identifier: AGPL-3.0-or-later`. +- `LICENSE` (AGPL-3.0) is in the repo; the README and the `package.json` files state AGPL-3.0-or-later. Source files have no per-file license headers. - Planned dependencies (Yjs, Hocuspocus, TipTap open-source, React, TanStack, Fastify, SQLite, sharp) are MIT/BSD/Apache-2.0/public domain and compatible. Avoid TipTap Pro and other proprietary add-ons. -- AGPL section 13: anyone running a modified Cnotes for other users over a network must offer them the source. An "About" screen links to the repo (configurable for forks). +- AGPL section 13: anyone running a modified cnotes for other users over a network must offer them the source. An "About" screen links to the repo (configurable for forks). - Contributions: DCO sign-off rather than a CLA. --- diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..2127992 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,70 @@ +# Deployment + +cnotes runs as one Docker container behind a reverse proxy, such as Nginx, that handles TLS. + +## Running the container + +```sh +docker compose up -d --build # builds the image from this checkout +docker compose logs cnotes # first start: shows the setup token +``` + +CI also publishes the image `ghcr.io/cedernaes/cnotes` from `main`. To use it instead of building +from the checkout, see the comment in `compose.yaml`. + +The server listens on port 3000 and stores everything in `./data`. Settings are environment +variables, see `src/backend/.env.example`. + +## Nginx + +An example site for cnotes on its own subdomain. Put your TLS settings where marked. The proxy +needs to upgrade WebSocket connections on `/sync` (live sync) and accept request bodies up to 50 MB +(photo and file uploads). + +```nginx +map $http_upgrade $connection_upgrade { + default upgrade; + '' close; +} + +server { + listen 443 ssl; + http2 on; + server_name notes.example.se; + + # ssl_certificate /etc/letsencrypt/live/notes.example.se/fullchain.pem; + # ssl_certificate_key /etc/letsencrypt/live/notes.example.se/privkey.pem; + + # Photo and file uploads + client_max_body_size 50m; + + location / { + proxy_pass http://127.0.0.1:3000; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # Live sync (WebSocket) + location /sync { + proxy_pass http://127.0.0.1:3000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 1h; + } +} +``` + +## Backups + +- The database is backed up every day into `data/backups/` (14 kept by default). +- Copy `data/backups/`, `data/files/` and `data/secret.key` off the server, for example with restic + or rclone. `secret.key` is needed to read the two-factor secrets; without it, people set up + two-factor again. +- To restore: stop cnotes, copy a backup to `data/cnotes.sqlite` (remove `cnotes.sqlite-wal` and + `-shm`), restore `files/` and `secret.key`, start cnotes. +- Settings → Export everything downloads all pages as Markdown with attachments. diff --git a/docs/DEVELOPMENT.md b/docs/development.md similarity index 51% rename from docs/DEVELOPMENT.md rename to docs/development.md index 38495bc..1921707 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/development.md @@ -1,15 +1,16 @@ # Development -Requires Node 22 (see `.nvmrc`) and pnpm (`corepack enable`). +Requires Node 26 (see `.nvmrc`) and pnpm (`npm install -g corepack && corepack enable`). ```sh pnpm install -cp apps/server/.env.example apps/server/.env # optional +cp src/backend/.env.example src/backend/.env # optional pnpm dev # web app on http://localhost:5173, server on :3000 (Vite proxies /api and /sync) ``` `pnpm dev` runs the server with `DEV_MODE=true`: no setup token and no two-factor, just a -username and password. Never set `DEV_MODE` on a server others can reach. +username and password. Never set `DEV_MODE` on a server others can reach. Data is stored in +`src/backend/data/`; delete it to start over. Without it (production), the server prints a setup token in its log on first start. Open the app, enter the token and create the first account. Two-factor is set up at the first sign-in. @@ -25,16 +26,22 @@ pnpm build # builds web app + service worker, then the server pnpm test:e2e # Playwright tests against the production build (iPhone and Pixel sizes) ``` +To run the production build locally (setup token and two-factor on): + +```sh +pnpm build +WEB_ROOT=../frontend/dist/client pnpm start # http://localhost:3000 +``` + ## Layout | Path | What | |---|---| -| `apps/web` | TanStack Start app (React, TSX, Vite) in SPA mode. `scripts/generate-sw.js` builds the service worker after the Vite build | -| `apps/web/src/lib` | Sync (Yjs documents, IndexedDB, one shared WebSocket), auth state, workspace helpers | -| `apps/web/src/components/Editor.tsx` | TipTap editor bound to the page's Yjs document | -| `apps/server/src` | Fastify server: `/api` (auth, files, search, export), `/sync` (Hocuspocus), static web app | +| `src/frontend` | TanStack Start app (React, TSX, Vite) in SPA mode. `scripts/generate-sw.js` builds the service worker after the Vite build | +| `src/frontend/src/lib` | Sync (Yjs documents, IndexedDB, one shared WebSocket), auth state, workspace helpers | +| `src/frontend/src/components/Editor.tsx` | TipTap editor bound to the page's Yjs document | +| `src/backend/src` | Fastify server: `/api` (auth, files, search, export), `/sync` (Hocuspocus), static web app | | `packages/shared` | Document model (page tree, pins), content helpers (text, tasks, Markdown), API schemas | -| `deploy/` | Example Nginx config | ### How data flows @@ -50,26 +57,4 @@ pnpm test:e2e # Playwright tests against the production build (iPhone and ## Running in production -```sh -docker compose up -d --build # builds the image from this checkout -docker compose logs cnotes # first start: shows the setup token -``` - -CI also publishes `ghcr.io/cedernaes/cnotes` from `main`. While the repository is private, pulling it -needs `docker login ghcr.io` with a GitHub token that has `read:packages`. - -The server listens on port 3000 and stores everything in `./data`. Put it behind Nginx using -`deploy/nginx.conf` (WebSocket upgrade on `/sync`, 50 MB uploads). Settings are environment -variables, see `apps/server/.env.example`. - -### Backups - -- The database is backed up every day into `data/backups/` (14 kept by default). -- Copy `data/backups/`, `data/files/` and `data/secret.key` off the server, for example with restic - or rclone. `secret.key` is needed to read the two-factor secrets; without it, people set up - two-factor again. -- To restore: stop Cnotes, copy a backup to `data/cnotes.sqlite` (remove `cnotes.sqlite-wal` and - `-shm`), restore `files/` and `secret.key`, start Cnotes. -- Settings → Export everything downloads all pages as Markdown with attachments. - -All source files carry `SPDX-License-Identifier: AGPL-3.0-or-later`. +See [deployment.md](deployment.md): Docker, Nginx and backups. diff --git a/eslint.config.js b/eslint.config.js index 807cddd..a1748f3 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,36 +1,35 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import js from '@eslint/js' -import reactHooks from 'eslint-plugin-react-hooks' -import globals from 'globals' -import tseslint from 'typescript-eslint' +import js from "@eslint/js" +import reactHooks from "eslint-plugin-react-hooks" +import globals from "globals" +import tseslint from "typescript-eslint" export default tseslint.config( { ignores: [ - '**/dist/**', - '**/.output/**', - '**/.tanstack/**', - '**/routeTree.gen.ts', - '**/dev-dist/**', + "**/dist/**", + "**/.output/**", + "**/.tanstack/**", + "**/routeTree.gen.ts", + "**/dev-dist/**", ], }, js.configs.recommended, ...tseslint.configs.recommended, { files: [ - 'apps/server/**/*.{ts,js}', - 'apps/web/scripts/**/*.js', - 'apps/web/*.ts', - 'packages/**/*.ts', - '*.js', - '*.ts', + "src/backend/**/*.{ts,js}", + "src/frontend/scripts/**/*.js", + "src/frontend/*.ts", + "packages/**/*.ts", + "*.js", + "*.ts", ], languageOptions: { globals: globals.node }, }, { - files: ['apps/web/**/*.{ts,tsx}'], + files: ["src/frontend/**/*.{ts,tsx}"], languageOptions: { globals: globals.browser }, - plugins: { 'react-hooks': reactHooks }, + plugins: { "react-hooks": reactHooks }, rules: reactHooks.configs.recommended.rules, }, ) diff --git a/package.json b/package.json index 766c6f3..5428d5c 100644 --- a/package.json +++ b/package.json @@ -5,18 +5,18 @@ "type": "module", "packageManager": "pnpm@10.28.0", "engines": { - "node": ">=22.12" + "node": ">=26" }, "scripts": { - "dev": "pnpm --parallel --filter @cnotes/web --filter @cnotes/server dev", - "build": "pnpm --filter @cnotes/web build && pnpm --filter @cnotes/server build", - "start": "pnpm --filter @cnotes/server start", + "dev": "pnpm --parallel --filter @cnotes/frontend --filter @cnotes/backend dev", + "build": "pnpm --filter @cnotes/frontend build && pnpm --filter @cnotes/backend build", + "start": "pnpm --filter @cnotes/backend start", "lint": "eslint .", "format": "prettier --write .", "format:check": "prettier --check .", "typecheck": "pnpm -r typecheck", "test": "vitest run", - "test:e2e": "pnpm --filter @cnotes/web test:e2e" + "test:e2e": "pnpm --filter @cnotes/frontend test:e2e" }, "devDependencies": { "@eslint/js": "^10.0.0", diff --git a/packages/shared/src/api.test.ts b/packages/shared/src/api.test.ts index ee41241..f3c025a 100644 --- a/packages/shared/src/api.test.ts +++ b/packages/shared/src/api.test.ts @@ -1,15 +1,14 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { Value } from '@sinclair/typebox/value' -import { describe, expect, it } from 'vitest' -import { HealthResponse, Username } from './api' +import { Value } from "@sinclair/typebox/value" +import { describe, expect, it } from "vitest" +import { HealthResponse, Username } from "./api" -describe('api schemas', () => { - it('validates health responses', () => { - expect(Value.Check(HealthResponse, { status: 'ok', version: '0.0.0' })).toBe(true) - expect(Value.Check(HealthResponse, { status: 'down', version: '0.0.0' })).toBe(false) +describe("api schemas", () => { + it("validates health responses", () => { + expect(Value.Check(HealthResponse, { status: "ok", version: "0.0.0" })).toBe(true) + expect(Value.Check(HealthResponse, { status: "down", version: "0.0.0" })).toBe(false) }) - it('restricts usernames', () => { - expect(Value.Check(Username, 'sara')).toBe(true) - expect(Value.Check(Username, 'sa ra')).toBe(false) + it("restricts usernames", () => { + expect(Value.Check(Username, "sara")).toBe(true) + expect(Value.Check(Username, "sa ra")).toBe(false) }) }) diff --git a/packages/shared/src/api.ts b/packages/shared/src/api.ts index f5c8e6f..0950f8b 100644 --- a/packages/shared/src/api.ts +++ b/packages/shared/src/api.ts @@ -1,14 +1,13 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // JSON shapes of the HTTP API, shared by server (validation) and web app. -import { Type, type Static } from '@sinclair/typebox' +import { Type, type Static } from "@sinclair/typebox" export const HealthResponse = Type.Object({ - status: Type.Literal('ok'), + status: Type.Literal("ok"), version: Type.String(), }) export type HealthResponse = Static -export const Username = Type.String({ minLength: 2, maxLength: 32, pattern: '^[a-zA-Z0-9._-]+$' }) +export const Username = Type.String({ minLength: 2, maxLength: 32, pattern: "^[a-zA-Z0-9._-]+$" }) // No password rules: the household decides. The cap only protects the server. export const Password = Type.String({ minLength: 1, maxLength: 256 }) export const DisplayName = Type.String({ minLength: 1, maxLength: 64 }) @@ -44,15 +43,15 @@ export const LoginRequest = Type.Object({ export type LoginRequest = Static export const LoginResponse = Type.Union([ - Type.Object({ step: Type.Literal('totp'), challenge: Type.String() }), + Type.Object({ step: Type.Literal("totp"), challenge: Type.String() }), Type.Object({ - step: Type.Literal('enroll'), + step: Type.Literal("enroll"), challenge: Type.String(), secret: Type.String(), otpauthUrl: Type.String(), }), // Dev mode: signed in right away, no two-factor. - Type.Object({ step: Type.Literal('done'), user: PublicUser }), + Type.Object({ step: Type.Literal("done"), user: PublicUser }), ]) export type LoginResponse = Static diff --git a/packages/shared/src/content.test.ts b/packages/shared/src/content.test.ts index c8041a8..a96c113 100644 --- a/packages/shared/src/content.test.ts +++ b/packages/shared/src/content.test.ts @@ -1,7 +1,6 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { describe, expect, it } from 'vitest' -import * as Y from 'yjs' -import { attachmentIds, contentToMarkdown, contentToText, countTasks } from './content' +import { describe, expect, it } from "vitest" +import * as Y from "yjs" +import { attachmentIds, contentToMarkdown, contentToText, countTasks } from "./content" type Spec = | string @@ -17,8 +16,8 @@ function el(name: string, attrs: Record = {}, ...kids: Child[]) } function toNode(c: Child): Y.XmlElement | Y.XmlText { - if (typeof c === 'string') return new Y.XmlText(c) - if (Array.isArray(c) && typeof c[0] === 'string') { + if (typeof c === "string") return new Y.XmlText(c) + if (Array.isArray(c) && typeof c[0] === "string") { const [name, attrs, ...kids] = c as [string, Record, ...Child[]] return el(name, attrs, ...kids) } @@ -33,92 +32,112 @@ function toNode(c: Child): Y.XmlElement | Y.XmlText { function fragment(...blocks: Child[]): Y.XmlFragment { const doc = new Y.Doc() - const f = doc.getXmlFragment('content') + const f = doc.getXmlFragment("content") f.insert(0, blocks.map(toNode)) return f } const sample = () => fragment( - ['heading', { level: 2 }, 'Week 48'], + ["heading", { level: 2 }, "Week 48"], [ - 'paragraph', + "paragraph", {}, [ - { text: 'Buy ' }, - { text: 'milk', marks: { bold: {} } }, - { text: ' and ' }, - { text: 'site', marks: { link: { href: 'https://ica.se' } } }, + { text: "Buy " }, + { text: "milk", marks: { bold: {} } }, + { text: " and " }, + { text: "site", marks: { link: { href: "https://ica.se" } } }, ], ], [ - 'taskList', + "taskList", {}, - ['taskItem', { checked: false }, ['paragraph', {}, 'Mjölk']], - ['taskItem', { checked: true }, ['paragraph', {}, 'Bröd']], - ['taskItem', { checked: false }, ['paragraph', {}]], + ["taskItem", { checked: false }, ["paragraph", {}, "Mjölk"]], + ["taskItem", { checked: true }, ["paragraph", {}, "Bröd"]], + ["taskItem", { checked: false }, ["paragraph", {}]], ], [ - 'bulletList', + "bulletList", {}, [ - 'listItem', + "listItem", {}, - ['paragraph', {}, 'one'], - ['bulletList', {}, ['listItem', {}, ['paragraph', {}, 'nested']]], + ["paragraph", {}, "one"], + ["bulletList", {}, ["listItem", {}, ["paragraph", {}, "nested"]]], ], ], - ['image', { src: '/api/files/att123', alt: 'Receipt' }], - ['fileAttachment', { id: 'att456', filename: 'Manual.pdf', size: 10 }], + ["image", { src: "/api/files/att123", alt: "Receipt" }], + ["fileAttachment", { id: "att456", filename: "Manual.pdf", size: 10 }], ) -describe('content helpers', () => { - it('extracts plain text for search', () => { +describe("content helpers", () => { + it("extracts plain text for search", () => { const text = contentToText(sample()) - expect(text).toContain('Week 48') - expect(text).toContain('Buy milk and site') - expect(text).toContain('Mjölk') - expect(text).toContain('nested') - expect(text).toContain('Manual.pdf') + expect(text).toContain("Week 48") + expect(text).toContain("Buy milk and site") + expect(text).toContain("Mjölk") + expect(text).toContain("nested") + expect(text).toContain("Manual.pdf") }) - it('counts open and done tasks', () => { + it("counts open and done tasks", () => { expect(countTasks(sample())).toEqual({ open: 1, done: 1 }) }) - it('finds attachment ids', () => { - expect(attachmentIds(sample()).sort()).toEqual(['att123', 'att456']) + it("finds attachment ids", () => { + expect(attachmentIds(sample()).sort()).toEqual(["att123", "att456"]) }) - it('exports Markdown', () => { + it("exports Markdown", () => { const md = contentToMarkdown(sample(), { attachmentLink: (id) => `attachments/${id}.bin`, }) expect(md).toBe( [ - '## Week 48', - '', - 'Buy **milk** and [site](https://ica.se)', - '', - '- [ ] Mjölk', - '- [x] Bröd', - '- [ ] ', - '', - '- one', - '', - ' - nested', - '', - '![Receipt](attachments/att123.bin)', - '', - '[Manual.pdf](attachments/att456.bin)', - '', - ].join('\n'), + "## Week 48", + "", + "Buy **milk** and [site](https://ica.se)", + "", + "- [ ] Mjölk", + "- [x] Bröd", + "- [ ] ", + "", + "- one", + "", + " - nested", + "", + "![Receipt](attachments/att123.bin)", + "", + "[Manual.pdf](attachments/att456.bin)", + "", + ].join("\n"), ) }) - it('escapes Markdown characters in text', () => { - expect(contentToMarkdown(fragment(['paragraph', {}, '2 * 3 = [6]']))).toBe( - '2 \\* 3 = \\[6\\]\n', + it("keeps angle brackets that are part of the text", () => { + const f = fragment( + ["paragraph", {}, "if a < b and c > d"], + ["codeBlock", { language: "html" }, ""], + ) + expect(contentToText(f)).toBe("if a < b and c > d\n") + expect(contentToMarkdown(f)).toBe( + "if a \\< b and c \\> d\n\n```html\n\n```\n", + ) + }) + + it("leaves mark attributes out of plain text", () => { + const f = fragment([ + "paragraph", + {}, + [{ text: "site", marks: { link: { href: 'https://ica.se/?q=">' } } }], + ]) + expect(contentToText(f)).toBe("site") + }) + + it("escapes Markdown characters in text", () => { + expect(contentToMarkdown(fragment(["paragraph", {}, "2 * 3 = [6]"]))).toBe( + "2 \\* 3 = \\[6\\]\n", ) }) }) diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.ts index 99c01d9..4350eba 100644 --- a/packages/shared/src/content.ts +++ b/packages/shared/src/content.ts @@ -1,8 +1,7 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Reads page content (a Yjs XmlFragment written by TipTap through // y-prosemirror) without a browser: plain text for search, open task // counts, attachment references and Markdown export. -import * as Y from 'yjs' +import * as Y from "yjs" type Node = Y.XmlElement | Y.XmlText | Y.XmlHook @@ -16,15 +15,15 @@ function children(el: Y.XmlElement | Y.XmlFragment): Node[] { } function isTrue(v: unknown): boolean { - return v === true || v === 'true' + return v === true || v === "true" } function inlineText(el: Y.XmlElement | Y.XmlFragment): string { - let out = '' + let out = "" for (const c of children(el)) { - if (c instanceof Y.XmlText) out += c.toString().replace(/<[^>]*>/g, '') + if (c instanceof Y.XmlText) out += textOf(c) else if (c instanceof Y.XmlElement) { - if (c.nodeName === 'hardBreak') out += '\n' + if (c.nodeName === "hardBreak") out += "\n" else out += inlineText(c) } } @@ -39,12 +38,12 @@ export function contentToText(fragment: Y.XmlFragment): string { if (c instanceof Y.XmlText) { lines.push(textOf(c)) } else if (c instanceof Y.XmlElement) { - if (c.nodeName === 'paragraph' || c.nodeName === 'heading' || c.nodeName === 'codeBlock') { + if (c.nodeName === "paragraph" || c.nodeName === "heading" || c.nodeName === "codeBlock") { lines.push(inlineText(c)) - } else if (c.nodeName === 'fileAttachment') { - lines.push(String(c.getAttribute('filename') ?? '')) - } else if (c.nodeName === 'image') { - const alt = c.getAttribute('alt') + } else if (c.nodeName === "fileAttachment") { + lines.push(String(c.getAttribute("filename") ?? "")) + } else if (c.nodeName === "image") { + const alt = c.getAttribute("alt") if (alt) lines.push(String(alt)) } else { walk(c) @@ -56,13 +55,13 @@ export function contentToText(fragment: Y.XmlFragment): string { return lines .map((l) => l.trim()) .filter(Boolean) - .join('\n') + .join("\n") } function textOf(t: Y.XmlText): string { return (t.toDelta() as DeltaOp[]) - .map((op) => (typeof op.insert === 'string' ? op.insert : '')) - .join('') + .map((op) => (typeof op.insert === "string" ? op.insert : "")) + .join("") } export function countTasks(fragment: Y.XmlFragment): { open: number; done: number } { @@ -72,8 +71,8 @@ export function countTasks(fragment: Y.XmlFragment): { open: number; done: numbe for (const c of children(el)) { if (c instanceof Y.XmlElement) { // Empty items (the blank line after the last one) don't count. - if (c.nodeName === 'taskItem' && contentToText(c as unknown as Y.XmlFragment).trim()) { - if (isTrue(c.getAttribute('checked'))) done++ + if (c.nodeName === "taskItem" && contentToText(c as unknown as Y.XmlFragment).trim()) { + if (isTrue(c.getAttribute("checked"))) done++ else open++ } walk(c) @@ -100,16 +99,16 @@ export function attachmentIds(fragment: Y.XmlFragment): string[] { return [...ids] } -export const FILE_URL_PREFIX = '/api/files/' +export const FILE_URL_PREFIX = "/api/files/" function attachmentIdOf(el: Y.XmlElement): string | null { - if (el.nodeName === 'fileAttachment') { - const id = el.getAttribute('id') - return typeof id === 'string' ? id : null + if (el.nodeName === "fileAttachment") { + const id = el.getAttribute("id") + return typeof id === "string" ? id : null } - if (el.nodeName === 'image') { - const src = el.getAttribute('src') - if (typeof src === 'string' && src.startsWith(FILE_URL_PREFIX)) { + if (el.nodeName === "image") { + const src = el.getAttribute("src") + if (typeof src === "string" && src.startsWith(FILE_URL_PREFIX)) { return src.slice(FILE_URL_PREFIX.length).split(/[/?#]/)[0] || null } } @@ -121,39 +120,39 @@ export interface MarkdownOptions { attachmentLink?: (id: string) => string | null } -const MARK_ORDER = ['code', 'bold', 'italic', 'strike', 'underline', 'link'] as const +const MARK_ORDER = ["code", "bold", "italic", "strike", "underline", "link"] as const function markName(key: string): string { // y-prosemirror suffixes overlapping marks of the same type ("link--x1y2"). - return key.split('--')[0] ?? key + return key.split("--")[0] ?? key } function escapeText(s: string): string { - return s.replace(/([\\`*_[\]<>#|~])/g, '\\$1') + return s.replace(/([\\`*_[\]<>#|~])/g, "\\$1") } function inlineMarkdown(el: Y.XmlElement | Y.XmlFragment, opts: MarkdownOptions): string { - let out = '' + let out = "" for (const c of children(el)) { if (c instanceof Y.XmlText) { for (const op of c.toDelta() as DeltaOp[]) { - if (typeof op.insert !== 'string') continue + if (typeof op.insert !== "string") continue const marks = new Map() for (const [k, v] of Object.entries(op.attributes ?? {})) marks.set(markName(k), v) - let text = marks.has('code') ? op.insert : escapeText(op.insert) + let text = marks.has("code") ? op.insert : escapeText(op.insert) // Keep whitespace outside the markers so "**a **b" stays valid. - const lead = text.match(/^\s*/)?.[0] ?? '' - const trail = text.match(/\s*$/)?.[0] ?? '' + const lead = text.match(/^\s*/)?.[0] ?? "" + const trail = text.match(/\s*$/)?.[0] ?? "" text = text.slice(lead.length, text.length - trail.length) if (text) { for (const m of MARK_ORDER) { if (!marks.has(m)) continue - if (m === 'code') text = '`' + text + '`' - else if (m === 'bold') text = `**${text}**` - else if (m === 'italic') text = `*${text}*` - else if (m === 'strike') text = `~~${text}~~` - else if (m === 'link') { - const href = (marks.get('link') as { href?: string } | undefined)?.href + if (m === "code") text = "`" + text + "`" + else if (m === "bold") text = `**${text}**` + else if (m === "italic") text = `*${text}*` + else if (m === "strike") text = `~~${text}~~` + else if (m === "link") { + const href = (marks.get("link") as { href?: string } | undefined)?.href if (href) text = `[${text}](${href})` } } @@ -161,8 +160,8 @@ function inlineMarkdown(el: Y.XmlElement | Y.XmlFragment, opts: MarkdownOptions) out += lead + text + trail } } else if (c instanceof Y.XmlElement) { - if (c.nodeName === 'hardBreak') out += ' \n' - else if (c.nodeName === 'image') out += imageMarkdown(c, opts) + if (c.nodeName === "hardBreak") out += " \n" + else if (c.nodeName === "image") out += imageMarkdown(c, opts) else out += inlineMarkdown(c, opts) } } @@ -170,8 +169,8 @@ function inlineMarkdown(el: Y.XmlElement | Y.XmlFragment, opts: MarkdownOptions) } function imageMarkdown(el: Y.XmlElement, opts: MarkdownOptions): string { - const src = String(el.getAttribute('src') ?? '') - const alt = String(el.getAttribute('alt') ?? '') + const src = String(el.getAttribute("src") ?? "") + const alt = String(el.getAttribute("alt") ?? "") const id = attachmentIdOf(el) const link = id ? (opts.attachmentLink?.(id) ?? src) : src return `![${escapeText(alt)}](${encodeURI(link)})` @@ -179,9 +178,9 @@ function imageMarkdown(el: Y.XmlElement, opts: MarkdownOptions): string { function indent(text: string, prefix: string): string { return text - .split('\n') + .split("\n") .map((l, i) => (i === 0 ? l : l ? prefix + l : l)) - .join('\n') + .join("\n") } function blocksMarkdown(el: Y.XmlElement | Y.XmlFragment, opts: MarkdownOptions): string[] { @@ -193,57 +192,57 @@ function blocksMarkdown(el: Y.XmlElement | Y.XmlFragment, opts: MarkdownOptions) } if (!(c instanceof Y.XmlElement)) continue switch (c.nodeName) { - case 'paragraph': + case "paragraph": out.push(inlineMarkdown(c, opts)) break - case 'heading': { - const level = Math.min(6, Math.max(1, Number(c.getAttribute('level') ?? 1))) - out.push(`${'#'.repeat(level)} ${inlineMarkdown(c, opts)}`) + case "heading": { + const level = Math.min(6, Math.max(1, Number(c.getAttribute("level") ?? 1))) + out.push(`${"#".repeat(level)} ${inlineMarkdown(c, opts)}`) break } - case 'blockquote': + case "blockquote": out.push( blocksMarkdown(c, opts) - .join('\n\n') - .split('\n') - .map((l) => (l ? `> ${l}` : '>')) - .join('\n'), + .join("\n\n") + .split("\n") + .map((l) => (l ? `> ${l}` : ">")) + .join("\n"), ) break - case 'codeBlock': { - const lang = c.getAttribute('language') - out.push('```' + (typeof lang === 'string' ? lang : '') + '\n' + inlineText(c) + '\n```') + case "codeBlock": { + const lang = c.getAttribute("language") + out.push("```" + (typeof lang === "string" ? lang : "") + "\n" + inlineText(c) + "\n```") break } - case 'horizontalRule': - out.push('---') + case "horizontalRule": + out.push("---") break - case 'image': + case "image": out.push(imageMarkdown(c, opts)) break - case 'fileAttachment': { + case "fileAttachment": { const id = attachmentIdOf(c) - const name = String(c.getAttribute('filename') ?? 'file') - const link = (id && opts.attachmentLink?.(id)) ?? `${FILE_URL_PREFIX}${id ?? ''}` + const name = String(c.getAttribute("filename") ?? "file") + const link = (id && opts.attachmentLink?.(id)) ?? `${FILE_URL_PREFIX}${id ?? ""}` out.push(`[${escapeText(name)}](${encodeURI(link)})`) break } - case 'bulletList': - case 'orderedList': - case 'taskList': { - const start = Number(c.getAttribute('start') ?? 1) || 1 + case "bulletList": + case "orderedList": + case "taskList": { + const start = Number(c.getAttribute("start") ?? 1) || 1 const items: string[] = [] children(c).forEach((item, i) => { if (!(item instanceof Y.XmlElement)) return - let marker = '- ' - if (c.nodeName === 'orderedList') marker = `${start + i}. ` - if (item.nodeName === 'taskItem') { - marker = isTrue(item.getAttribute('checked')) ? '- [x] ' : '- [ ] ' + let marker = "- " + if (c.nodeName === "orderedList") marker = `${start + i}. ` + if (item.nodeName === "taskItem") { + marker = isTrue(item.getAttribute("checked")) ? "- [x] " : "- [ ] " } - const body = blocksMarkdown(item, opts).join('\n\n') - items.push(marker + indent(body, ' '.repeat(marker.length))) + const body = blocksMarkdown(item, opts).join("\n\n") + items.push(marker + indent(body, " ".repeat(marker.length))) }) - out.push(items.join('\n')) + out.push(items.join("\n")) break } default: @@ -254,6 +253,6 @@ function blocksMarkdown(el: Y.XmlElement | Y.XmlFragment, opts: MarkdownOptions) } export function contentToMarkdown(fragment: Y.XmlFragment, opts: MarkdownOptions = {}): string { - const md = blocksMarkdown(fragment, opts).join('\n\n').trim() - return md ? md + '\n' : '' + const md = blocksMarkdown(fragment, opts).join("\n\n").trim() + return md ? md + "\n" : "" } diff --git a/packages/shared/src/docs.test.ts b/packages/shared/src/docs.test.ts index 2e3f589..507a607 100644 --- a/packages/shared/src/docs.test.ts +++ b/packages/shared/src/docs.test.ts @@ -1,6 +1,5 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { describe, expect, it } from 'vitest' -import * as Y from 'yjs' +import { describe, expect, it } from "vitest" +import * as Y from "yjs" import { buildTree, isSelfOrDescendant, @@ -11,19 +10,19 @@ import { parseDocName, pinnedMap, type PageMeta, -} from './docs' +} from "./docs" function page(id: string, parentId: string | null, extra: Partial = {}): PageMeta { return { id, title: id, parentId, - order: 'a0', + order: "a0", archived: false, createdAt: 0, - createdBy: '', + createdBy: "", updatedAt: 0, - updatedBy: '', + updatedBy: "", openTasks: 0, ...extra, } @@ -32,37 +31,37 @@ function page(id: string, parentId: string | null, extra: Partial = {} const ids = (nodes: ReturnType): unknown => nodes.map((n) => (n.children.length ? [n.page.id, ids(n.children)] : n.page.id)) -describe('parseDocName', () => { - it('accepts workspace and page names only', () => { - expect(parseDocName('workspace')).toEqual({ kind: 'workspace' }) - expect(parseDocName('page:abcdefgh12')).toEqual({ kind: 'page', pageId: 'abcdefgh12' }) - expect(parseDocName('page:../../etc')).toBeNull() - expect(parseDocName('other')).toBeNull() +describe("parseDocName", () => { + it("accepts workspace and page names only", () => { + expect(parseDocName("workspace")).toEqual({ kind: "workspace" }) + expect(parseDocName("page:abcdefgh12")).toEqual({ kind: "page", pageId: "abcdefgh12" }) + expect(parseDocName("page:../../etc")).toBeNull() + expect(parseDocName("other")).toBeNull() }) }) -describe('buildTree', () => { - it('nests and sorts by order then title', () => { +describe("buildTree", () => { + it("nests and sorts by order then title", () => { const tree = buildTree([ - page('b', null, { order: 'a1' }), - page('a', null, { order: 'a0' }), - page('c', 'a', { title: 'zeta' }), - page('d', 'a', { title: 'alpha' }), + page("b", null, { order: "a1" }), + page("a", null, { order: "a0" }), + page("c", "a", { title: "zeta" }), + page("d", "a", { title: "alpha" }), ]) - expect(ids(tree)).toEqual([['a', ['d', 'c']], 'b']) + expect(ids(tree)).toEqual([["a", ["d", "c"]], "b"]) }) - it('shows orphans and children of archived pages at the top', () => { + it("shows orphans and children of archived pages at the top", () => { const tree = buildTree([ - page('a', 'missing'), - page('x', null, { archived: true }), - page('y', 'x'), + page("a", "missing"), + page("x", null, { archived: true }), + page("y", "x"), ]) - expect(ids(tree)).toEqual(['a', 'y']) + expect(ids(tree)).toEqual(["a", "y"]) }) - it('breaks cycles from concurrent moves without losing pages', () => { - const tree = buildTree([page('a', 'b'), page('b', 'a'), page('c', 'b')]) + it("breaks cycles from concurrent moves without losing pages", () => { + const tree = buildTree([page("a", "b"), page("b", "a"), page("c", "b")]) const all: string[] = [] const walk = (n: ReturnType) => n.forEach((x) => { @@ -70,32 +69,32 @@ describe('buildTree', () => { walk(x.children) }) walk(tree) - expect(all.sort()).toEqual(['a', 'b', 'c']) + expect(all.sort()).toEqual(["a", "b", "c"]) }) }) -describe('tree helpers', () => { - const pages = [page('a', null), page('b', 'a'), page('c', 'b')] - it('detects descendants', () => { - expect(isSelfOrDescendant(pages, 'a', 'c')).toBe(true) - expect(isSelfOrDescendant(pages, 'c', 'a')).toBe(false) - expect(isSelfOrDescendant(pages, 'a', 'a')).toBe(true) +describe("tree helpers", () => { + const pages = [page("a", null), page("b", "a"), page("c", "b")] + it("detects descendants", () => { + expect(isSelfOrDescendant(pages, "a", "c")).toBe(true) + expect(isSelfOrDescendant(pages, "c", "a")).toBe(false) + expect(isSelfOrDescendant(pages, "a", "a")).toBe(true) }) - it('builds breadcrumbs', () => { - expect(pagePath(pages, 'c').map((p) => p.id)).toEqual(['a', 'b', 'c']) + it("builds breadcrumbs", () => { + expect(pagePath(pages, "c").map((p) => p.id)).toEqual(["a", "b", "c"]) }) }) -describe('workspace doc', () => { - it('reads pages and pins', () => { +describe("workspace doc", () => { + it("reads pages and pins", () => { const doc = new Y.Doc() const entry = new Y.Map() - pagesMap(doc).set('page12345', entry) - entry.set('title', 'Shopping') - entry.set('openTasks', 3) - pinnedMap(doc).set('page12345', 'a1') - pinnedMap(doc).set('other1234', 'a0') - expect(listPages(doc)).toMatchObject([{ id: 'page12345', title: 'Shopping', openTasks: 3 }]) - expect(listPinned(doc)).toEqual(['other1234', 'page12345']) + pagesMap(doc).set("page12345", entry) + entry.set("title", "Shopping") + entry.set("openTasks", 3) + pinnedMap(doc).set("page12345", "a1") + pinnedMap(doc).set("other1234", "a0") + expect(listPages(doc)).toMatchObject([{ id: "page12345", title: "Shopping", openTasks: 3 }]) + expect(listPinned(doc)).toEqual(["other1234", "page12345"]) }) }) diff --git a/packages/shared/src/docs.ts b/packages/shared/src/docs.ts index e45c51a..0d33d8f 100644 --- a/packages/shared/src/docs.ts +++ b/packages/shared/src/docs.ts @@ -1,11 +1,10 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Shape of the Yjs documents shared by the web app and the server. -import * as Y from 'yjs' +import * as Y from "yjs" /** The single workspace document: page tree, titles and pins. */ -export const WORKSPACE_DOC = 'workspace' +export const WORKSPACE_DOC = "workspace" /** Field in a page document that holds the TipTap/ProseMirror content. */ -export const CONTENT_FIELD = 'content' +export const CONTENT_FIELD = "content" const PAGE_ID_RE = /^[A-Za-z0-9_-]{8,64}$/ @@ -17,13 +16,13 @@ export function pageDocName(pageId: string): string { return `page:${pageId}` } -export type DocRef = { kind: 'workspace' } | { kind: 'page'; pageId: string } +export type DocRef = { kind: "workspace" } | { kind: "page"; pageId: string } export function parseDocName(name: string): DocRef | null { - if (name === WORKSPACE_DOC) return { kind: 'workspace' } - if (name.startsWith('page:')) { + if (name === WORKSPACE_DOC) return { kind: "workspace" } + if (name.startsWith("page:")) { const pageId = name.slice(5) - if (isPageId(pageId)) return { kind: 'page', pageId } + if (isPageId(pageId)) return { kind: "page", pageId } } return null } @@ -46,34 +45,34 @@ export interface PageMeta { export type PageEntry = Y.Map export function pagesMap(doc: Y.Doc): Y.Map { - return doc.getMap('pages') + return doc.getMap("pages") } /** pageId -> order string. A map (not an array) so concurrent pins never duplicate. */ export function pinnedMap(doc: Y.Doc): Y.Map { - return doc.getMap('pinned') + return doc.getMap("pinned") } -function str(v: unknown, fallback = ''): string { - return typeof v === 'string' ? v : fallback +function str(v: unknown, fallback = ""): string { + return typeof v === "string" ? v : fallback } function num(v: unknown): number { - return typeof v === 'number' && Number.isFinite(v) ? v : 0 + return typeof v === "number" && Number.isFinite(v) ? v : 0 } export function readPage(id: string, entry: PageEntry): PageMeta { - const parentId = entry.get('parentId') + const parentId = entry.get("parentId") return { id, - title: str(entry.get('title')), - parentId: typeof parentId === 'string' && parentId ? parentId : null, - order: str(entry.get('order'), 'a0'), - archived: entry.get('archived') === true, - createdAt: num(entry.get('createdAt')), - createdBy: str(entry.get('createdBy')), - updatedAt: num(entry.get('updatedAt')), - updatedBy: str(entry.get('updatedBy')), - openTasks: num(entry.get('openTasks')), + title: str(entry.get("title")), + parentId: typeof parentId === "string" && parentId ? parentId : null, + order: str(entry.get("order"), "a0"), + archived: entry.get("archived") === true, + createdAt: num(entry.get("createdAt")), + createdBy: str(entry.get("createdBy")), + updatedAt: num(entry.get("updatedAt")), + updatedBy: str(entry.get("updatedBy")), + openTasks: num(entry.get("openTasks")), } } diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index e650790..8c9029a 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1,11 +1,10 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -export const APP_NAME = 'Cnotes' +export const APP_NAME = "cnotes" /** Where the source code of this instance can be found (AGPL-3.0 section 13). */ -export const DEFAULT_SOURCE_URL = 'https://github.com/cedernaes/cnotes' +export const DEFAULT_SOURCE_URL = "https://github.com/cedernaes/cnotes" export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024 -export * from './api' -export * from './content' -export * from './docs' +export * from "./api" +export * from "./content" +export * from "./docs" diff --git a/packages/shared/vitest.config.ts b/packages/shared/vitest.config.ts index 8a09209..508c780 100644 --- a/packages/shared/vitest.config.ts +++ b/packages/shared/vitest.config.ts @@ -1,9 +1,8 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { defineConfig } from 'vitest/config' +import { defineConfig } from "vitest/config" export default defineConfig({ test: { - name: 'shared', - include: ['src/**/*.test.ts'], + name: "shared", + include: ["src/**/*.test.ts"], }, }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ea8a5df..b96f146 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,9 +31,18 @@ importers: version: 8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3) vitest: specifier: ^5.1.2 - version: 5.1.2(@types/node@22.20.7)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + version: 5.1.2(@types/node@26.6.11)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) - apps/server: + packages/shared: + dependencies: + '@sinclair/typebox': + specifier: ^0.34.52 + version: 0.34.52 + yjs: + specifier: ^13.6.33 + version: 13.6.33 + + src/backend: dependencies: '@cnotes/shared': specifier: workspace:* @@ -76,7 +85,7 @@ importers: version: 0.8.3 sharp: specifier: ^0.35.5 - version: 0.35.5(@types/node@22.20.7) + version: 0.35.5(@types/node@26.6.11) ws: specifier: ^8.23.1 version: 8.23.1 @@ -91,8 +100,8 @@ importers: specifier: ^9.6.0 version: 9.6.0 '@types/node': - specifier: ^22.0.0 - version: 22.20.7 + specifier: ^26.0.0 + version: 26.6.11 '@types/ws': specifier: ^8.18.2 version: 8.18.2 @@ -106,7 +115,7 @@ importers: specifier: ^4.23.15 version: 4.23.15 - apps/web: + src/frontend: dependencies: '@cnotes/shared': specifier: workspace:* @@ -119,7 +128,7 @@ importers: version: 1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@tanstack/react-start': specifier: ^1.169.7 - version: 1.169.7(@types/react@19.3.3)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + version: 1.169.7(@types/react@19.3.3)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) '@tiptap/core': specifier: ^3.35.1 version: 3.35.1(@tiptap/pm@3.35.1) @@ -177,7 +186,7 @@ importers: version: 1.63.0 '@tailwindcss/vite': specifier: ^4.3.5 - version: 4.3.5(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + version: 4.3.5(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) '@types/qrcode': specifier: ^1.5.6 version: 1.5.6 @@ -189,7 +198,7 @@ importers: version: 19.3.0(@types/react@19.3.3) '@vitejs/plugin-react': specifier: ^6.3.0 - version: 6.3.0(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + version: 6.3.0(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) fflate: specifier: ^0.8.3 version: 0.8.3 @@ -201,20 +210,11 @@ importers: version: 4.3.5 vite: specifier: ^8.4.0 - version: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + version: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) workbox-build: specifier: ^7.4.1 version: 7.4.1 - packages/shared: - dependencies: - '@sinclair/typebox': - specifier: ^0.34.52 - version: 0.34.52 - yjs: - specifier: ^13.6.33 - version: 13.6.33 - packages: '@apideck/better-ajv-errors@0.3.7': @@ -2038,8 +2038,8 @@ packages: '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} - '@types/node@22.20.7': - resolution: {integrity: sha512-F/Mcc4pD3YwXQCG50hb8BjB5RmrOere6hge7n2XHf0V8tpkZOVEjwYv9Ql7n0MpMn8Bv7+q12P9w6UHsBm0Sfw==} + '@types/node@26.6.11': + resolution: {integrity: sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==} '@types/qrcode@1.5.6': resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==} @@ -3719,8 +3719,8 @@ packages: resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} engines: {node: '>= 0.4'} - undici-types@6.21.0: - resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} unicode-canonical-property-names-ecmascript@2.0.1: resolution: {integrity: sha512-dA8WbNeb2a6oQzAQ55YlT5vQAWGV9WXOsi3SskE3bcCdM0P4SDd+24zS/OCacdRq5BkdsRj9q3Pg6YyQoxIGqg==} @@ -5439,12 +5439,12 @@ snapshots: '@tailwindcss/oxide-win32-arm64-msvc': 4.3.5 '@tailwindcss/oxide-win32-x64-msvc': 4.3.5 - '@tailwindcss/vite@4.3.5(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': + '@tailwindcss/vite@4.3.5(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': dependencies: '@tailwindcss/node': 4.3.5 '@tailwindcss/oxide': 4.3.5 tailwindcss: 4.3.5 - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) '@tanstack/history@1.162.5': {} @@ -5469,14 +5469,14 @@ snapshots: transitivePeerDependencies: - '@types/react' - '@tanstack/react-start-rsc@0.1.68(@types/react@19.3.3)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': + '@tanstack/react-start-rsc@0.1.68(@types/react@19.3.3)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': dependencies: '@tanstack/react-router': 1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@tanstack/router-core': 1.171.39 '@tanstack/router-utils': 1.163.0 '@tanstack/start-client-core': 1.170.39 '@tanstack/start-fn-stubs': 1.162.0 - '@tanstack/start-plugin-core': 1.172.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + '@tanstack/start-plugin-core': 1.172.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) '@tanstack/start-storage-context': 1.167.41 pathe: 2.0.3 react: 19.3.1 @@ -5505,21 +5505,21 @@ snapshots: transitivePeerDependencies: - '@types/react' - '@tanstack/react-start@1.169.7(@types/react@19.3.3)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': + '@tanstack/react-start@1.169.7(@types/react@19.3.3)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': dependencies: '@tanstack/react-router': 1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@tanstack/react-start-client': 1.168.45(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@tanstack/react-start-rsc': 0.1.68(@types/react@19.3.3)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + '@tanstack/react-start-rsc': 0.1.68(@types/react@19.3.3)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) '@tanstack/react-start-server': 1.167.52(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@tanstack/router-utils': 1.163.0 '@tanstack/start-client-core': 1.170.39 - '@tanstack/start-plugin-core': 1.172.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + '@tanstack/start-plugin-core': 1.172.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) '@tanstack/start-server-core': 1.169.45 pathe: 2.0.3 react: 19.3.1 react-dom: 19.3.1(react@19.3.1) optionalDependencies: - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) transitivePeerDependencies: - '@farmfe/core' - '@rspack/core' @@ -5563,7 +5563,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@tanstack/router-plugin@1.169.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': + '@tanstack/router-plugin@1.169.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': dependencies: '@babel/core': 7.29.16 '@babel/template': 7.29.7 @@ -5572,11 +5572,11 @@ snapshots: '@tanstack/router-generator': 1.168.0 '@tanstack/router-utils': 1.163.0 chokidar: 5.0.0 - unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) zod: 4.6.7 optionalDependencies: '@tanstack/react-router': 1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) transitivePeerDependencies: - '@farmfe/core' - '@rspack/core' @@ -5609,7 +5609,7 @@ snapshots: '@tanstack/start-fn-stubs@1.162.0': {} - '@tanstack/start-plugin-core@1.172.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': + '@tanstack/start-plugin-core@1.172.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': dependencies: '@babel/code-frame': 7.29.7 '@babel/core': 7.29.16 @@ -5617,7 +5617,7 @@ snapshots: '@jridgewell/remapping': 2.3.5 '@tanstack/router-core': 1.171.39 '@tanstack/router-generator': 1.168.0 - '@tanstack/router-plugin': 1.169.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + '@tanstack/router-plugin': 1.169.0(@tanstack/react-router@1.170.46(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) '@tanstack/router-utils': 1.163.0 '@tanstack/start-server-core': 1.169.45 exsolve: 1.2.0 @@ -5629,11 +5629,11 @@ snapshots: srvx: 1.0.8 tinyglobby: 0.2.17 ufo: 1.6.4 - vitefu: 1.1.4(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + vitefu: 1.1.4(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) xmlbuilder2: 4.0.3 zod: 4.6.7 optionalDependencies: - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) transitivePeerDependencies: - '@farmfe/core' - '@rspack/core' @@ -5880,7 +5880,7 @@ snapshots: '@types/better-sqlite3@9.6.0': dependencies: - '@types/node': 22.20.7 + '@types/node': 26.6.11 '@types/chai@5.2.3': dependencies: @@ -5895,13 +5895,13 @@ snapshots: '@types/json-schema@7.0.15': {} - '@types/node@22.20.7': + '@types/node@26.6.11': dependencies: - undici-types: 6.21.0 + undici-types: 8.9.0 '@types/qrcode@1.5.6': dependencies: - '@types/node': 22.20.7 + '@types/node': 26.6.11 '@types/react-dom@19.3.0(@types/react@19.3.3)': dependencies: @@ -5919,7 +5919,7 @@ snapshots: '@types/ws@8.18.2': dependencies: - '@types/node': 22.20.7 + '@types/node': 26.6.11 '@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)': dependencies: @@ -6016,19 +6016,19 @@ snapshots: '@typescript-eslint/types': 8.74.0 eslint-visitor-keys: 5.0.1 - '@vitejs/plugin-react@6.3.0(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': + '@vitejs/plugin-react@6.3.0(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': dependencies: '@rolldown/pluginutils': 1.1.1 - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) - '@vitest/mocker@5.1.2(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': + '@vitest/mocker@5.1.2(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15))': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@vitest/spy': 5.1.2 estree-walker: 3.0.3 magic-string: 1.4.5 optionalDependencies: - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) '@vitest/spy@5.1.2': {} @@ -7491,7 +7491,7 @@ snapshots: setprototypeof@1.2.0: {} - sharp@0.35.5(@types/node@22.20.7): + sharp@0.35.5(@types/node@26.6.11): dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 @@ -7522,7 +7522,7 @@ snapshots: '@img/sharp-win32-arm64': 0.35.5 '@img/sharp-win32-ia32': 0.35.5 '@img/sharp-win32-x64': 0.35.5 - '@types/node': 22.20.7 + '@types/node': 26.6.11 shebang-command@2.0.0: dependencies: @@ -7764,7 +7764,7 @@ snapshots: has-symbols: 1.1.0 which-boxed-primitive: 1.1.1 - undici-types@6.21.0: {} + undici-types@8.9.0: {} unicode-canonical-property-names-ecmascript@2.0.1: {} @@ -7783,7 +7783,7 @@ snapshots: universalify@2.0.1: {} - unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)): + unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.68.9)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)): dependencies: '@jridgewell/remapping': 2.3.5 '@rolldown/pluginutils': 1.1.1 @@ -7793,7 +7793,7 @@ snapshots: esbuild: 0.28.2 rolldown: 1.3.4 rollup: 4.68.9 - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) upath@1.2.0: {} @@ -7811,7 +7811,7 @@ snapshots: dependencies: react: 19.3.1 - vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15): + vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -7819,7 +7819,7 @@ snapshots: rolldown: 1.3.4 tinyglobby: 0.2.17 optionalDependencies: - '@types/node': 22.20.7 + '@types/node': 26.6.11 esbuild: 0.28.2 fsevents: 2.3.3 jiti: 2.7.0 @@ -7827,14 +7827,14 @@ snapshots: terser: 5.51.4 tsx: 4.23.15 - vitefu@1.1.4(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)): + vitefu@1.1.4(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)): optionalDependencies: - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) - vitest@5.1.2(@types/node@22.20.7)(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)): + vitest@5.1.2(@types/node@26.6.11)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)): dependencies: '@types/chai': 5.2.3 - '@vitest/mocker': 5.1.2(vite@8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) + '@vitest/mocker': 5.1.2(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15)) chai: 6.3.0 es-module-lexer: 2.3.2 expect-type: 1.4.0 @@ -7845,10 +7845,10 @@ snapshots: tinybench: 6.2.5 tinyexec: 1.4.0 tinyglobby: 0.2.17 - vite: 8.4.0(@types/node@22.20.7)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) + vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.4)(tsx@4.23.15) why-is-node-running: 3.2.1 optionalDependencies: - '@types/node': 22.20.7 + '@types/node': 26.6.11 transitivePeerDependencies: - msw diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 4a4932f..de8fe78 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,5 @@ packages: - - apps/* + - src/* - packages/* onlyBuiltDependencies: - esbuild diff --git a/apps/server/.env.example b/src/backend/.env.example similarity index 96% rename from apps/server/.env.example rename to src/backend/.env.example index 03fc1b1..048bb20 100644 --- a/apps/server/.env.example +++ b/src/backend/.env.example @@ -2,7 +2,7 @@ PORT=3000 DATA_DIR=./data # Path to the built web app. Leave unset in development (Vite serves it). -# WEB_ROOT=../web/dist/client +# WEB_ROOT=../frontend/dist/client # Address or CIDR of the reverse proxy (Nginx), or true to trust any. # TRUST_PROXY=127.0.0.1 LOG_LEVEL=info diff --git a/apps/server/build.js b/src/backend/build.js similarity index 53% rename from apps/server/build.js rename to src/backend/build.js index e5d8bb8..c266970 100644 --- a/apps/server/build.js +++ b/src/backend/build.js @@ -1,19 +1,18 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Bundles the server (and the shared workspace package) into dist/index.js. // Third-party dependencies stay external and are installed in the Docker image. -import { readFileSync } from 'node:fs' -import { build } from 'esbuild' +import { readFileSync } from "node:fs" +import { build } from "esbuild" -const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')) -const external = Object.keys(pkg.dependencies).filter((name) => !name.startsWith('@cnotes/')) +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) +const external = Object.keys(pkg.dependencies).filter((name) => !name.startsWith("@cnotes/")) await build({ - entryPoints: ['src/index.ts'], - outfile: 'dist/index.js', + entryPoints: ["src/index.ts"], + outfile: "dist/index.js", bundle: true, - platform: 'node', - target: 'node22', - format: 'esm', + platform: "node", + target: "node26", + format: "esm", sourcemap: true, // Also externalize subpath imports such as '@sinclair/typebox/value'. external: external.flatMap((name) => [name, `${name}/*`]), diff --git a/apps/server/package.json b/src/backend/package.json similarity index 94% rename from apps/server/package.json rename to src/backend/package.json index 35d462a..558b32b 100644 --- a/apps/server/package.json +++ b/src/backend/package.json @@ -1,5 +1,5 @@ { - "name": "@cnotes/server", + "name": "@cnotes/backend", "version": "0.0.0", "private": true, "license": "AGPL-3.0-or-later", @@ -31,7 +31,7 @@ "devDependencies": { "@hocuspocus/provider": "^4.9.0", "@types/better-sqlite3": "^9.6.0", - "@types/node": "^22.0.0", + "@types/node": "^26.0.0", "@types/ws": "^8.18.2", "esbuild": "^0.28.2", "otpauth": "^9.6.0", diff --git a/apps/server/src/app.ts b/src/backend/src/app.ts similarity index 63% rename from apps/server/src/app.ts rename to src/backend/src/app.ts index 40c85de..2b03f2b 100644 --- a/apps/server/src/app.ts +++ b/src/backend/src/app.ts @@ -1,28 +1,27 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import crypto from 'node:crypto' -import fs from 'node:fs' -import path from 'node:path' -import cookie from '@fastify/cookie' -import helmet from '@fastify/helmet' -import multipart from '@fastify/multipart' -import rateLimit from '@fastify/rate-limit' -import fastifyStatic from '@fastify/static' -import type { TypeBoxTypeProvider } from '@fastify/type-provider-typebox' -import { HealthResponse, MAX_UPLOAD_BYTES } from '@cnotes/shared' -import Fastify from 'fastify' -import { AuthService } from './auth' -import { BackupScheduler } from './backup' -import type { Config } from './config' -import { openDb } from './db' -import { buildExport, exportZipName } from './export' -import { FileStore } from './files' -import { requireSession } from './http' -import { Projection } from './projection' -import { authRoutes } from './routes/auth' -import { fileRoutes } from './routes/files' -import { searchRoutes } from './routes/search' -import { loadSecretKey, randomId } from './secrets' -import { SYNC_PATH, SyncServer } from './sync' +import crypto from "node:crypto" +import fs from "node:fs" +import path from "node:path" +import cookie from "@fastify/cookie" +import helmet from "@fastify/helmet" +import multipart from "@fastify/multipart" +import rateLimit from "@fastify/rate-limit" +import fastifyStatic from "@fastify/static" +import type { TypeBoxTypeProvider } from "@fastify/type-provider-typebox" +import { HealthResponse, MAX_UPLOAD_BYTES } from "@cnotes/shared" +import Fastify from "fastify" +import { AuthService } from "./auth" +import { BackupScheduler } from "./backup" +import type { Config } from "./config" +import { openDb } from "./db" +import { buildExport, exportZipName } from "./export" +import { FileStore } from "./files" +import { requireSession } from "./http" +import { Projection } from "./projection" +import { authRoutes } from "./routes/auth" +import { fileRoutes } from "./routes/files" +import { searchRoutes } from "./routes/search" +import { loadSecretKey, randomId } from "./secrets" +import { SYNC_PATH, SyncServer } from "./sync" export async function buildApp(config: Config, opts: { backups?: boolean } = {}) { const app = Fastify({ @@ -39,7 +38,7 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) if (config.devMode) { app.log.warn( - 'DEV_MODE is on: no two-factor and no setup token. Never use this on a reachable server.', + "DEV_MODE is on: no two-factor and no setup token. Never use this on a reachable server.", ) } let setupToken: string | null = null @@ -47,7 +46,7 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) setupToken = config.setupToken ?? randomId(9) if (!config.setupToken) { app.log.warn( - `No accounts yet. Open Cnotes in a browser and use this setup token: ${setupToken}`, + `No accounts yet. Open cnotes in a browser and use this setup token: ${setupToken}`, ) } } @@ -56,13 +55,13 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) await app.register(cookie) await app.register(rateLimit, { global: false }) await app.register(multipart, { limits: { fileSize: MAX_UPLOAD_BYTES, files: 1, fields: 0 } }) - app.decorateRequest('session', null) + app.decorateRequest("session", null) const indexFile = config.webRoot ? findIndexFile(config.webRoot) : null // The prerendered shell contains small inline bootstrap scripts from // TanStack Router. Allow exactly those by hash instead of 'unsafe-inline'. const shellScriptHashes = indexFile - ? inlineScriptHashes(fs.readFileSync(path.join(config.webRoot, indexFile), 'utf8')) + ? inlineScriptHashes(fs.readFileSync(path.join(config.webRoot, indexFile), "utf8")) : [] await app.register(helmet, { @@ -71,7 +70,7 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) defaultSrc: ["'self'"], scriptSrc: ["'self'", ...shellScriptHashes], styleSrc: ["'self'", "'unsafe-inline'"], - imgSrc: ["'self'", 'data:', 'blob:'], + imgSrc: ["'self'", "data:", "blob:"], fontSrc: ["'self'"], connectSrc: ["'self'"], workerSrc: ["'self'"], @@ -87,8 +86,8 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) // CSRF protection on top of SameSite=Strict cookies: state-changing // requests from a browser must come from our own origin. - app.addHook('onRequest', async (req, reply) => { - if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return + app.addHook("onRequest", async (req, reply) => { + if (req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return const origin = req.headers.origin if (origin) { let host: string | null = null @@ -98,18 +97,18 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) /* invalid */ } if (host !== req.headers.host) - return reply.code(403).send({ error: 'Cross-origin request blocked' }) + return reply.code(403).send({ error: "Cross-origin request blocked" }) } else { - const site = req.headers['sec-fetch-site'] - if (site && site !== 'same-origin' && site !== 'none') { - return reply.code(403).send({ error: 'Cross-origin request blocked' }) + const site = req.headers["sec-fetch-site"] + if (site && site !== "same-origin" && site !== "none") { + return reply.code(403).send({ error: "Cross-origin request blocked" }) } } }) const sync = new SyncServer(db, auth, projection, app.log, (h) => app.parseCookie(h)) - app.server.on('upgrade', (req, socket, head) => { - const url = req.url ?? '' + app.server.on("upgrade", (req, socket, head) => { + const url = req.url ?? "" if (url === SYNC_PATH || url.startsWith(`${SYNC_PATH}?`) || url.startsWith(`${SYNC_PATH}/`)) { sync.handleUpgrade(req, socket, head) } else { @@ -117,15 +116,15 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) } }) - app.get('/api/health', { schema: { response: { 200: HealthResponse } } }, async () => ({ - status: 'ok' as const, + app.get("/api/health", { schema: { response: { 200: HealthResponse } } }, async () => ({ + status: "ok" as const, version: config.version, })) await app.register( async (api) => { await api.register(authRoutes, { - prefix: '/auth', + prefix: "/auth", auth, config, getSetupToken, @@ -133,16 +132,16 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) }) await api.register(fileRoutes, { auth, files, projection }) await api.register(searchRoutes, { auth, db }) - api.get('/export', { preHandler: requireSession(auth) }, async (_req, reply) => { + api.get("/export", { preHandler: requireSession(auth) }, async (_req, reply) => { const zip = buildExport((name) => sync.loadStored(name), files) return reply - .header('Content-Type', 'application/zip') - .header('Content-Disposition', `attachment; filename="${exportZipName()}"`) - .header('Cache-Control', 'no-store') + .header("Content-Type", "application/zip") + .header("Content-Disposition", `attachment; filename="${exportZipName()}"`) + .header("Cache-Control", "no-store") .send(Buffer.from(zip)) }) }, - { prefix: '/api' }, + { prefix: "/api" }, ) if (config.webRoot && indexFile) { @@ -154,22 +153,22 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) // Hashed build assets never change; everything else must revalidate // so new versions (and the service worker) are picked up. if (filePath.includes(`${path.sep}assets${path.sep}`)) { - reply.header('Cache-Control', 'public, max-age=31536000, immutable') + reply.header("Cache-Control", "public, max-age=31536000, immutable") } else { - reply.header('Cache-Control', 'no-cache') + reply.header("Cache-Control", "no-cache") } }, }) // Single-page app: unknown GET routes outside /api get the app shell. app.setNotFoundHandler((req, reply) => { - if (req.method === 'GET' && !req.url.startsWith('/api/')) { - return reply.header('Cache-Control', 'no-cache').sendFile(indexFile) + if (req.method === "GET" && !req.url.startsWith("/api/")) { + return reply.header("Cache-Control", "no-cache").sendFile(indexFile) } - return reply.code(404).send({ error: 'Not Found' }) + return reply.code(404).send({ error: "Not Found" }) }) } else { - app.setNotFoundHandler((_req, reply) => reply.code(404).send({ error: 'Not Found' })) + app.setNotFoundHandler((_req, reply) => reply.code(404).send({ error: "Not Found" })) } const backups = new BackupScheduler(db, config.dataDir, app.log, { @@ -178,7 +177,7 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) }) if (opts.backups !== false) backups.start() - app.addHook('onClose', async () => { + app.addHook("onClose", async () => { backups.stop() await sync.close() db.close() @@ -191,7 +190,7 @@ export async function buildApp(config: Config, opts: { backups?: boolean } = {}) /** TanStack Start's SPA mode writes the app shell as _shell.html; fall back to index.html. */ function findIndexFile(webRoot: string): string { - for (const name of ['_shell.html', 'index.html']) { + for (const name of ["_shell.html", "index.html"]) { if (fs.existsSync(path.join(webRoot, name))) return name } throw new Error(`No _shell.html or index.html found in WEB_ROOT ${webRoot}`) @@ -201,9 +200,9 @@ function findIndexFile(webRoot: string): string { export function inlineScriptHashes(html: string): string[] { const hashes = new Set() for (const match of html.matchAll(/]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)) { - const body = match[1] ?? '' + const body = match[1] ?? "" if (!body) continue - hashes.add(`'sha256-${crypto.createHash('sha256').update(body, 'utf8').digest('base64')}'`) + hashes.add(`'sha256-${crypto.createHash("sha256").update(body, "utf8").digest("base64")}'`) } return [...hashes] } diff --git a/apps/server/src/auth.ts b/src/backend/src/auth.ts similarity index 72% rename from apps/server/src/auth.ts rename to src/backend/src/auth.ts index 26a6c87..194f645 100644 --- a/apps/server/src/auth.ts +++ b/src/backend/src/auth.ts @@ -1,10 +1,9 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import crypto from 'node:crypto' -import { hash as argonHash, verify as argonVerify } from '@node-rs/argon2' -import type { PublicUser, SessionInfo } from '@cnotes/shared' -import * as OTPAuth from 'otpauth' -import type { DB } from './db' -import { decrypt, encrypt, randomId, sha256 } from './secrets' +import crypto from "node:crypto" +import { hash as argonHash, verify as argonVerify } from "@node-rs/argon2" +import type { PublicUser, SessionInfo } from "@cnotes/shared" +import * as OTPAuth from "otpauth" +import type { DB } from "./db" +import { decrypt, encrypt, randomId, sha256 } from "./secrets" export const SESSION_TTL_MS = 90 * 24 * 60 * 60 * 1000 const SESSION_TOUCH_MS = 60 * 60 * 1000 @@ -75,17 +74,17 @@ export class AuthService { } userCount(): number { - return (this.db.prepare('SELECT COUNT(*) AS n FROM users').get() as { n: number }).n + return (this.db.prepare("SELECT COUNT(*) AS n FROM users").get() as { n: number }).n } listUsers(): PublicUser[] { - return (this.db.prepare('SELECT * FROM users ORDER BY created_at').all() as UserRow[]).map( + return (this.db.prepare("SELECT * FROM users ORDER BY created_at").all() as UserRow[]).map( toPublic, ) } getUser(id: string): PublicUser | null { - const row = this.db.prepare('SELECT * FROM users WHERE id = ?').get(id) as UserRow | undefined + const row = this.db.prepare("SELECT * FROM users WHERE id = ?").get(id) as UserRow | undefined return row ? toPublic(row) : null } @@ -94,8 +93,8 @@ export class AuthService { displayName: string | undefined, password: string, ): Promise { - const exists = this.db.prepare('SELECT 1 FROM users WHERE username = ?').get(username) - if (exists) throw new AuthError('That username is taken', 409) + const exists = this.db.prepare("SELECT 1 FROM users WHERE username = ?").get(username) + if (exists) throw new AuthError("That username is taken", 409) const user: UserRow = { id: randomId(), username, @@ -115,24 +114,24 @@ export class AuthService { } async changePassword(userId: string, current: string, next: string): Promise { - const row = this.db.prepare('SELECT * FROM users WHERE id = ?').get(userId) as + const row = this.db.prepare("SELECT * FROM users WHERE id = ?").get(userId) as UserRow | undefined if (!row || !(await argonVerify(row.password_hash, current))) { - throw new AuthError('Current password is wrong', 403) + throw new AuthError("Current password is wrong", 403) } this.db - .prepare('UPDATE users SET password_hash = ? WHERE id = ?') + .prepare("UPDATE users SET password_hash = ? WHERE id = ?") .run(await argonHash(next, ARGON_OPTS), userId) } /** Checks a password only (dev mode, where there is no second step). */ async verifyPassword(username: string, password: string): Promise { - const row = this.db.prepare('SELECT * FROM users WHERE username = ?').get(username) as + const row = this.db.prepare("SELECT * FROM users WHERE username = ?").get(username) as UserRow | undefined const ok = row ? await argonVerify(row.password_hash, password) : (await argonVerify(await this.dummyHash, password), false) - if (!row || !ok) throw new AuthError('Wrong username or password', 401) + if (!row || !ok) throw new AuthError("Wrong username or password", 401) return toPublic(row) } @@ -141,15 +140,15 @@ export class AuthService { username: string, password: string, ): Promise< - | { step: 'totp'; challenge: string } - | { step: 'enroll'; challenge: string; secret: string; otpauthUrl: string } + | { step: "totp"; challenge: string } + | { step: "enroll"; challenge: string; secret: string; otpauthUrl: string } > { - const row = this.db.prepare('SELECT * FROM users WHERE username = ?').get(username) as + const row = this.db.prepare("SELECT * FROM users WHERE username = ?").get(username) as UserRow | undefined const ok = row ? await argonVerify(row.password_hash, password) : (await argonVerify(await this.dummyHash, password), false) - if (!row || !ok) throw new AuthError('Wrong username or password', 401) + if (!row || !ok) throw new AuthError("Wrong username or password", 401) this.pruneChallenges() const challenge = randomId(24) @@ -159,7 +158,7 @@ export class AuthService { expiresAt: this.now() + CHALLENGE_TTL_MS, attempts: 0, }) - return { step: 'totp', challenge } + return { step: "totp", challenge } } const secret = new OTPAuth.Secret({ size: 20 }).base32 this.challenges.set(challenge, { @@ -169,7 +168,7 @@ export class AuthService { pendingSecret: secret, }) return { - step: 'enroll', + step: "enroll", challenge, secret, otpauthUrl: this.totp(row.username, secret).toString(), @@ -182,19 +181,19 @@ export class AuthService { code: string, ): { userId: string; recoveryCodes: string[] } { const challenge = this.useChallenge(challengeId) - if (!challenge.pendingSecret) throw new AuthError('Two-factor is already set up', 400) - const row = this.db.prepare('SELECT * FROM users WHERE id = ?').get(challenge.userId) as UserRow + if (!challenge.pendingSecret) throw new AuthError("Two-factor is already set up", 400) + const row = this.db.prepare("SELECT * FROM users WHERE id = ?").get(challenge.userId) as UserRow const step = this.matchTotp(row.username, challenge.pendingSecret, code, 0) - if (step === null) throw new AuthError('That code is not valid', 401) + if (step === null) throw new AuthError("That code is not valid", 401) const recoveryCodes = Array.from({ length: RECOVERY_CODE_COUNT }, () => newRecoveryCode()) this.db.transaction(() => { this.db - .prepare('UPDATE users SET totp_secret_enc = ?, totp_last_step = ? WHERE id = ?') + .prepare("UPDATE users SET totp_secret_enc = ?, totp_last_step = ? WHERE id = ?") .run(encrypt(this.secretKey, challenge.pendingSecret!), step, row.id) - this.db.prepare('DELETE FROM recovery_codes WHERE user_id = ?').run(row.id) + this.db.prepare("DELETE FROM recovery_codes WHERE user_id = ?").run(row.id) const insert = this.db.prepare( - 'INSERT INTO recovery_codes (user_id, code_hash) VALUES (?, ?)', + "INSERT INTO recovery_codes (user_id, code_hash) VALUES (?, ?)", ) for (const c of recoveryCodes) insert.run(row.id, sha256(normalizeRecovery(c))) })() @@ -205,38 +204,38 @@ export class AuthService { /** Step 2: a code from the authenticator app, or a one-time recovery code. */ verifyCode(challengeId: string, code: string): { userId: string } { const challenge = this.useChallenge(challengeId) - if (challenge.pendingSecret) throw new AuthError('Two-factor is not set up yet', 400) - const row = this.db.prepare('SELECT * FROM users WHERE id = ?').get(challenge.userId) as UserRow + if (challenge.pendingSecret) throw new AuthError("Two-factor is not set up yet", 400) + const row = this.db.prepare("SELECT * FROM users WHERE id = ?").get(challenge.userId) as UserRow const secret = decrypt(this.secretKey, row.totp_secret_enc!) const step = this.matchTotp(row.username, secret, code, row.totp_last_step) if (step !== null) { - this.db.prepare('UPDATE users SET totp_last_step = ? WHERE id = ?').run(step, row.id) + this.db.prepare("UPDATE users SET totp_last_step = ? WHERE id = ?").run(step, row.id) this.challenges.delete(challengeId) return { userId: row.id } } const used = this.db .prepare( - 'UPDATE recovery_codes SET used_at = ? WHERE user_id = ? AND code_hash = ? AND used_at IS NULL', + "UPDATE recovery_codes SET used_at = ? WHERE user_id = ? AND code_hash = ? AND used_at IS NULL", ) .run(this.now(), row.id, sha256(normalizeRecovery(code))) if (used.changes === 1) { this.challenges.delete(challengeId) return { userId: row.id } } - throw new AuthError('That code is not valid', 401) + throw new AuthError("That code is not valid", 401) } remainingRecoveryCodes(userId: string): number { return ( this.db - .prepare('SELECT COUNT(*) AS n FROM recovery_codes WHERE user_id = ? AND used_at IS NULL') + .prepare("SELECT COUNT(*) AS n FROM recovery_codes WHERE user_id = ? AND used_at IS NULL") .get(userId) as { n: number } ).n } createSession(userId: string, deviceName: string): { token: string; sessionId: string } { - const token = crypto.randomBytes(32).toString('base64url') + const token = crypto.randomBytes(32).toString("base64url") const sessionId = randomId() const now = this.now() this.db @@ -268,12 +267,12 @@ export class AuthService { const now = this.now() if (!row) return null if (row.expires_at <= now) { - this.db.prepare('DELETE FROM sessions WHERE id = ?').run(row.id) + this.db.prepare("DELETE FROM sessions WHERE id = ?").run(row.id) return null } if (now - row.last_seen_at > SESSION_TOUCH_MS) { this.db - .prepare('UPDATE sessions SET last_seen_at = ?, expires_at = ? WHERE id = ?') + .prepare("UPDATE sessions SET last_seen_at = ?, expires_at = ? WHERE id = ?") .run(now, now + SESSION_TTL_MS, row.id) } return { @@ -285,7 +284,7 @@ export class AuthService { listSessions(userId: string, currentSessionId: string): SessionInfo[] { const rows = this.db .prepare( - 'SELECT * FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY last_seen_at DESC', + "SELECT * FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY last_seen_at DESC", ) .all(userId, this.now()) as SessionRow[] return rows.map((r) => ({ @@ -299,16 +298,16 @@ export class AuthService { revokeSession(userId: string, sessionId: string): boolean { return ( - this.db.prepare('DELETE FROM sessions WHERE id = ? AND user_id = ?').run(sessionId, userId) + this.db.prepare("DELETE FROM sessions WHERE id = ? AND user_id = ?").run(sessionId, userId) .changes > 0 ) } private totp(username: string, secret: string): OTPAuth.TOTP { return new OTPAuth.TOTP({ - issuer: 'Cnotes', + issuer: "cnotes", label: username, - algorithm: 'SHA1', + algorithm: "SHA1", digits: 6, period: TOTP_PERIOD, secret: OTPAuth.Secret.fromBase32(secret), @@ -322,7 +321,7 @@ export class AuthService { code: string, lastStep: number, ): number | null { - const token = code.replace(/\s/g, '') + const token = code.replace(/\s/g, "") if (!/^\d{6}$/.test(token)) return null const now = this.now() const delta = this.totp(username, secret).validate({ token, timestamp: now, window: 1 }) @@ -335,12 +334,12 @@ export class AuthService { const c = this.challenges.get(id) if (!c || c.expiresAt <= this.now()) { this.challenges.delete(id) - throw new AuthError('Sign-in expired, please start again', 401) + throw new AuthError("Sign-in expired, please start again", 401) } c.attempts++ if (c.attempts > CHALLENGE_MAX_ATTEMPTS) { this.challenges.delete(id) - throw new AuthError('Too many attempts, please start again', 429) + throw new AuthError("Too many attempts, please start again", 429) } return c } @@ -351,42 +350,42 @@ export class AuthService { } } -const RECOVERY_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789' +const RECOVERY_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789" function newRecoveryCode(): string { const bytes = crypto.randomBytes(10) const chars = [...bytes].map((b) => RECOVERY_ALPHABET[b % RECOVERY_ALPHABET.length]) - return `${chars.slice(0, 5).join('')}-${chars.slice(5).join('')}` + return `${chars.slice(0, 5).join("")}-${chars.slice(5).join("")}` } function normalizeRecovery(code: string): string { - return code.toLowerCase().replace(/[^a-z0-9]/g, '') + return code.toLowerCase().replace(/[^a-z0-9]/g, "") } /** A readable device name from the User-Agent, e.g. "iPhone · Safari". */ export function deviceNameFromUserAgent(ua: string | undefined): string { - if (!ua) return 'Unknown device' + if (!ua) return "Unknown device" const os = /iPhone/.test(ua) - ? 'iPhone' + ? "iPhone" : /iPad/.test(ua) - ? 'iPad' + ? "iPad" : /Android/.test(ua) - ? 'Android' + ? "Android" : /Mac OS X/.test(ua) - ? 'Mac' + ? "Mac" : /Windows/.test(ua) - ? 'Windows' + ? "Windows" : /Linux/.test(ua) - ? 'Linux' - : 'Unknown' + ? "Linux" + : "Unknown" const browser = /Edg\//.test(ua) - ? 'Edge' + ? "Edge" : /Firefox\//.test(ua) - ? 'Firefox' + ? "Firefox" : /CriOS|Chrome\//.test(ua) - ? 'Chrome' + ? "Chrome" : /Safari\//.test(ua) - ? 'Safari' - : 'Browser' + ? "Safari" + : "Browser" return `${os} · ${browser}` } diff --git a/apps/server/src/backup.ts b/src/backend/src/backup.ts similarity index 82% rename from apps/server/src/backup.ts rename to src/backend/src/backup.ts index 425d0ed..3f8ec2a 100644 --- a/apps/server/src/backup.ts +++ b/src/backend/src/backup.ts @@ -1,8 +1,7 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import fs from 'node:fs' -import path from 'node:path' -import type { FastifyBaseLogger } from 'fastify' -import type { DB } from './db' +import fs from "node:fs" +import path from "node:path" +import type { FastifyBaseLogger } from "fastify" +import type { DB } from "./db" /** * Daily online backup of the SQLite database into DATA_DIR/backups. @@ -20,7 +19,7 @@ export class BackupScheduler { private log: FastifyBaseLogger, private opts: { hour: number; keep: number }, ) { - this.dir = path.join(dataDir, 'backups') + this.dir = path.join(dataDir, "backups") } start() { @@ -41,17 +40,17 @@ export class BackupScheduler { async tick(now = new Date()) { if (this.running) return const file = this.fileFor(now) - const hasAny = fs.readdirSync(this.dir).some((f) => f.endsWith('.sqlite')) + const hasAny = fs.readdirSync(this.dir).some((f) => f.endsWith(".sqlite")) // Run at the configured hour, or right away if there is no backup at all. if (fs.existsSync(file) || (hasAny && now.getHours() < this.opts.hour)) return this.running = true try { await this.db.backup(`${file}.partial`) fs.renameSync(`${file}.partial`, file) - this.log.info({ file }, 'database backup written') + this.log.info({ file }, "database backup written") this.prune() } catch (err) { - this.log.error({ err }, 'database backup failed') + this.log.error({ err }, "database backup failed") } finally { this.running = false } diff --git a/apps/server/src/config.ts b/src/backend/src/config.ts similarity index 62% rename from apps/server/src/config.ts rename to src/backend/src/config.ts index 478dd65..6b540b3 100644 --- a/apps/server/src/config.ts +++ b/src/backend/src/config.ts @@ -1,5 +1,4 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import path from 'node:path' +import path from "node:path" export interface Config { host: string @@ -13,7 +12,7 @@ export interface Config { logLevel: string version: string /** 'auto' marks cookies Secure when the request came over HTTPS. */ - cookieSecure: boolean | 'auto' + cookieSecure: boolean | "auto" /** Fixed token for creating the first account (otherwise random, printed in the log). */ setupToken: string | null /** Base64 32-byte key for encrypting 2FA secrets (otherwise DATA_DIR/secret.key). */ @@ -25,7 +24,7 @@ export interface Config { } function int(value: string | undefined, fallback: number, name: string, min: number, max: number) { - if (value === undefined || value === '') return fallback + if (value === undefined || value === "") return fallback const n = Number(value) if (!Number.isInteger(n) || n < min || n > max) throw new Error(`Invalid ${name}: ${value}`) return n @@ -35,23 +34,23 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { const trustProxy = env.TRUST_PROXY const cookieSecure = env.COOKIE_SECURE return { - host: env.HOST ?? '0.0.0.0', - port: int(env.PORT, 3000, 'PORT', 1, 65535), - dataDir: path.resolve(env.DATA_DIR ?? './data'), - webRoot: env.WEB_ROOT === undefined || env.WEB_ROOT === '' ? '' : path.resolve(env.WEB_ROOT), + host: env.HOST ?? "0.0.0.0", + port: int(env.PORT, 3000, "PORT", 1, 65535), + dataDir: path.resolve(env.DATA_DIR ?? "./data"), + webRoot: env.WEB_ROOT === undefined || env.WEB_ROOT === "" ? "" : path.resolve(env.WEB_ROOT), trustProxy: - trustProxy === undefined || trustProxy === '' || trustProxy === 'false' + trustProxy === undefined || trustProxy === "" || trustProxy === "false" ? false - : trustProxy === 'true' + : trustProxy === "true" ? true : trustProxy, - logLevel: env.LOG_LEVEL ?? 'info', - version: env.CNOTES_VERSION ?? '0.0.0-dev', - cookieSecure: cookieSecure === 'true' ? true : cookieSecure === 'false' ? false : 'auto', + logLevel: env.LOG_LEVEL ?? "info", + version: env.CNOTES_VERSION ?? "0.0.0-dev", + cookieSecure: cookieSecure === "true" ? true : cookieSecure === "false" ? false : "auto", setupToken: env.CNOTES_SETUP_TOKEN || null, secretKey: env.CNOTES_SECRET_KEY || null, - devMode: env.DEV_MODE === 'true', - backupHour: int(env.BACKUP_HOUR, 3, 'BACKUP_HOUR', 0, 23), - backupKeep: int(env.BACKUP_KEEP, 14, 'BACKUP_KEEP', 1, 365), + devMode: env.DEV_MODE === "true", + backupHour: int(env.BACKUP_HOUR, 3, "BACKUP_HOUR", 0, 23), + backupKeep: int(env.BACKUP_KEEP, 14, "BACKUP_KEEP", 1, 365), } } diff --git a/apps/server/src/db.ts b/src/backend/src/db.ts similarity index 83% rename from apps/server/src/db.ts rename to src/backend/src/db.ts index ca0456e..8dcd3b3 100644 --- a/apps/server/src/db.ts +++ b/src/backend/src/db.ts @@ -1,6 +1,5 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import path from 'node:path' -import Database from 'better-sqlite3' +import path from "node:path" +import Database from "better-sqlite3" export type DB = Database.Database @@ -80,19 +79,19 @@ const MIGRATIONS: string[] = [ `, ] -export function openDb(dataDir: string | ':memory:'): DB { - const file = dataDir === ':memory:' ? ':memory:' : path.join(dataDir, 'cnotes.sqlite') +export function openDb(dataDir: string | ":memory:"): DB { + const file = dataDir === ":memory:" ? ":memory:" : path.join(dataDir, "cnotes.sqlite") const db = new Database(file) - db.pragma('journal_mode = WAL') - db.pragma('synchronous = NORMAL') - db.pragma('foreign_keys = ON') - db.pragma('busy_timeout = 5000') + db.pragma("journal_mode = WAL") + db.pragma("synchronous = NORMAL") + db.pragma("foreign_keys = ON") + db.pragma("busy_timeout = 5000") migrate(db) return db } export function migrate(db: DB): void { - const current = db.pragma('user_version', { simple: true }) as number + const current = db.pragma("user_version", { simple: true }) as number for (let v = current; v < MIGRATIONS.length; v++) { db.transaction(() => { db.exec(MIGRATIONS[v]!) diff --git a/apps/server/src/export.ts b/src/backend/src/export.ts similarity index 75% rename from apps/server/src/export.ts rename to src/backend/src/export.ts index 014da93..0fdfb60 100644 --- a/apps/server/src/export.ts +++ b/src/backend/src/export.ts @@ -1,7 +1,6 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Exports everything as Markdown files plus attachments in a zip, so the // household can always take its data elsewhere. -import fs from 'node:fs' +import fs from "node:fs" import { buildTree, CONTENT_FIELD, @@ -10,18 +9,18 @@ import { pageDocName, WORKSPACE_DOC, type TreeNode, -} from '@cnotes/shared' -import { zipSync, type Zippable } from 'fflate' -import type * as Y from 'yjs' -import type { FileStore } from './files' +} from "@cnotes/shared" +import { zipSync, type Zippable } from "fflate" +import type * as Y from "yjs" +import type { FileStore } from "./files" export function exportFilename(title: string): string { const name = title // eslint-disable-next-line no-control-regex - .replace(/[\u0000-\u001f\u007f<>:"/\\|?*]/g, '_') - .replace(/\s+/g, ' ') + .replace(/[\u0000-\u001f\u007f<>:"/\\|?*]/g, "_") + .replace(/\s+/g, " ") .trim() - return (name || 'Untitled').slice(0, 100) + return (name || "Untitled").slice(0, 100) } export function buildExport(loadDoc: (name: string) => Y.Doc | null, files: FileStore): Uint8Array { @@ -44,8 +43,8 @@ export function buildExport(loadDoc: (name: string) => Y.Doc | null, files: File base = `${exportFilename(node.page.title)} (${i})` used.add(base.toLowerCase()) - const depth = dir ? dir.split('/').length : 0 - const up = '../'.repeat(depth) + const depth = dir ? dir.split("/").length : 0 + const up = "../".repeat(depth) const doc = loadDoc(pageDocName(node.page.id)) const body = doc ? contentToMarkdown(doc.getXmlFragment(CONTENT_FIELD), { @@ -55,21 +54,21 @@ export function buildExport(loadDoc: (name: string) => Y.Doc | null, files: File return p ? up + p : null }, }) - : '' + : "" const header = node.page.archived ? `# ${node.page.title}\n\n_Archived_\n\n` : `# ${node.page.title}\n\n` - zip[`${dir ? dir + '/' : ''}${base}.md`] = new TextEncoder().encode(header + body) - if (node.children.length) writeLevel(node.children, `${dir ? dir + '/' : ''}${base}`) + zip[`${dir ? dir + "/" : ""}${base}.md`] = new TextEncoder().encode(header + body) + if (node.children.length) writeLevel(node.children, `${dir ? dir + "/" : ""}${base}`) } } - writeLevel(buildTree(pages, true), '') + writeLevel(buildTree(pages, true), "") for (const id of usedAttachments) { const a = attachments.get(id)! if (fs.existsSync(a.path)) zip[attachmentPath(id)!] = [fs.readFileSync(a.path), { level: 0 }] } - if (Object.keys(zip).length === 0) zip['README.md'] = new TextEncoder().encode('No pages yet.\n') + if (Object.keys(zip).length === 0) zip["README.md"] = new TextEncoder().encode("No pages yet.\n") return zipSync(zip, { level: 6 }) } diff --git a/apps/server/src/files.ts b/src/backend/src/files.ts similarity index 77% rename from apps/server/src/files.ts rename to src/backend/src/files.ts index 73dae46..316421c 100644 --- a/apps/server/src/files.ts +++ b/src/backend/src/files.ts @@ -1,19 +1,18 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import crypto from 'node:crypto' -import fs from 'node:fs' -import path from 'node:path' -import type { Attachment } from '@cnotes/shared' -import sharp from 'sharp' -import type { DB } from './db' -import { randomId } from './secrets' +import crypto from "node:crypto" +import fs from "node:fs" +import path from "node:path" +import type { Attachment } from "@cnotes/shared" +import sharp from "sharp" +import type { DB } from "./db" +import { randomId } from "./secrets" /** Images that are shown inline. Everything else is a download. */ const INLINE_IMAGE_TYPES = new Set([ - 'image/jpeg', - 'image/png', - 'image/webp', - 'image/gif', - 'image/avif', + "image/jpeg", + "image/png", + "image/webp", + "image/gif", + "image/avif", ]) const MAX_IMAGE_EDGE = 2560 @@ -43,10 +42,10 @@ function toApi(r: AttachmentRow): Attachment { } export function safeFilename(name: string): string { - const base = path.basename(name.replace(/\\/g, '/')) + const base = path.basename(name.replace(/\\/g, "/")) // eslint-disable-next-line no-control-regex - const cleaned = base.replace(/[\u0000-\u001f\u007f<>:"/\\|?*]/g, '_').trim() - return (cleaned || 'file').slice(0, 200) + const cleaned = base.replace(/[\u0000-\u001f\u007f<>:"/\\|?*]/g, "_").trim() + return (cleaned || "file").slice(0, 200) } export class FileStore { @@ -56,7 +55,7 @@ export class FileStore { private db: DB, dataDir: string, ) { - this.root = path.join(dataDir, 'files') + this.root = path.join(dataDir, "files") fs.mkdirSync(this.root, { recursive: true }) } @@ -65,13 +64,13 @@ export class FileStore { } get(id: string): (Attachment & { path: string; pageId: string }) | null { - const row = this.db.prepare('SELECT * FROM attachments WHERE id = ?').get(id) as + const row = this.db.prepare("SELECT * FROM attachments WHERE id = ?").get(id) as AttachmentRow | undefined return row ? { ...toApi(row), path: this.pathFor(row.sha256), pageId: row.page_id } : null } all(): (Attachment & { path: string; pageId: string })[] { - return (this.db.prepare('SELECT * FROM attachments').all() as AttachmentRow[]).map((r) => ({ + return (this.db.prepare("SELECT * FROM attachments").all() as AttachmentRow[]).map((r) => ({ ...toApi(r), path: this.pathFor(r.sha256), pageId: r.page_id, @@ -93,20 +92,20 @@ export class FileStore { let width: number | null = null let height: number | null = null - if (INLINE_IMAGE_TYPES.has(mime) && mime !== 'image/gif') { + if (INLINE_IMAGE_TYPES.has(mime) && mime !== "image/gif") { try { - const img = sharp(data, { failOn: 'error' }).rotate().resize({ + const img = sharp(data, { failOn: "error" }).rotate().resize({ width: MAX_IMAGE_EDGE, height: MAX_IMAGE_EDGE, - fit: 'inside', + fit: "inside", withoutEnlargement: true, }) const out = - mime === 'image/png' + mime === "image/png" ? await img.png().toBuffer({ resolveWithObject: true }) - : mime === 'image/webp' + : mime === "image/webp" ? await img.webp({ quality: 85 }).toBuffer({ resolveWithObject: true }) - : mime === 'image/avif' + : mime === "image/avif" ? await img.avif({ quality: 60 }).toBuffer({ resolveWithObject: true }) : await img .jpeg({ quality: 85, mozjpeg: true }) @@ -116,13 +115,13 @@ export class FileStore { height = out.info.height } catch { // Not a decodable image after all: keep it as a plain file. - mime = 'application/octet-stream' + mime = "application/octet-stream" } } else if (!INLINE_IMAGE_TYPES.has(mime)) { - mime = mime && /^[\w.+-]+\/[\w.+-]+$/.test(mime) ? mime : 'application/octet-stream' + mime = mime && /^[\w.+-]+\/[\w.+-]+$/.test(mime) ? mime : "application/octet-stream" } - const sha = crypto.createHash('sha256').update(data).digest('hex') + const sha = crypto.createHash("sha256").update(data).digest("hex") const dest = this.pathFor(sha) if (!fs.existsSync(dest)) { fs.mkdirSync(path.dirname(dest), { recursive: true }) diff --git a/apps/server/src/http.ts b/src/backend/src/http.ts similarity index 55% rename from apps/server/src/http.ts rename to src/backend/src/http.ts index b1d298d..e88bb19 100644 --- a/apps/server/src/http.ts +++ b/src/backend/src/http.ts @@ -1,11 +1,10 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import type { FastifyReply, FastifyRequest } from 'fastify' -import type { AuthenticatedSession, AuthService } from './auth' -import type { Config } from './config' +import type { FastifyReply, FastifyRequest } from "fastify" +import type { AuthenticatedSession, AuthService } from "./auth" +import type { Config } from "./config" -export const SESSION_COOKIE = 'cnotes_session' +export const SESSION_COOKIE = "cnotes_session" -declare module 'fastify' { +declare module "fastify" { interface FastifyRequest { session: AuthenticatedSession | null } @@ -22,10 +21,10 @@ export function sessionFromRequest( export function requireSession(auth: AuthService) { return async (req: FastifyRequest, reply: FastifyReply) => { req.session = sessionFromRequest(auth, req) - if (!req.session) return reply.code(401).send({ error: 'Not signed in' }) + if (!req.session) return reply.code(401).send({ error: "Not signed in" }) } } export function cookieSecure(config: Config, req: FastifyRequest): boolean { - return config.cookieSecure === 'auto' ? req.protocol === 'https' : config.cookieSecure + return config.cookieSecure === "auto" ? req.protocol === "https" : config.cookieSecure } diff --git a/src/backend/src/index.ts b/src/backend/src/index.ts new file mode 100644 index 0000000..6e15f01 --- /dev/null +++ b/src/backend/src/index.ts @@ -0,0 +1,14 @@ +import { buildApp } from "./app" +import { loadConfig } from "./config" + +const config = loadConfig() +const app = await buildApp(config) + +for (const signal of ["SIGINT", "SIGTERM"] as const) { + process.once(signal, () => { + app.log.info({ signal }, "shutting down") + void app.close().then(() => process.exit(0)) + }) +} + +await app.listen({ host: config.host, port: config.port }) diff --git a/apps/server/src/projection.ts b/src/backend/src/projection.ts similarity index 80% rename from apps/server/src/projection.ts rename to src/backend/src/projection.ts index ee95c81..b13b36a 100644 --- a/apps/server/src/projection.ts +++ b/src/backend/src/projection.ts @@ -1,10 +1,9 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Keeps the SQL "projection" (pages table + search index) in step with the // Yjs documents, which remain the source of truth. Everything here can be // rebuilt from the documents table. -import { CONTENT_FIELD, contentToText, listPages, type PageMeta } from '@cnotes/shared' -import * as Y from 'yjs' -import type { DB } from './db' +import { CONTENT_FIELD, contentToText, listPages, type PageMeta } from "@cnotes/shared" +import * as Y from "yjs" +import type { DB } from "./db" export class Projection { constructor(private db: DB) {} @@ -14,7 +13,7 @@ export class Projection { const now = Date.now() const existing = new Map( ( - this.db.prepare('SELECT id, title, parent_id, archived FROM pages').all() as { + this.db.prepare("SELECT id, title, parent_id, archived FROM pages").all() as { id: string title: string parent_id: string | null @@ -65,18 +64,18 @@ export class Projection { } private reindex(pageId: string) { - const row = this.db.prepare('SELECT title, body FROM pages WHERE id = ?').get(pageId) as + const row = this.db.prepare("SELECT title, body FROM pages WHERE id = ?").get(pageId) as { title: string; body: string } | undefined - this.db.prepare('DELETE FROM search_fts WHERE page_id = ?').run(pageId) + this.db.prepare("DELETE FROM search_fts WHERE page_id = ?").run(pageId) if (row) { const files = ( - this.db.prepare('SELECT filename FROM attachments WHERE page_id = ?').all(pageId) as { + this.db.prepare("SELECT filename FROM attachments WHERE page_id = ?").all(pageId) as { filename: string }[] ).map((f) => f.filename) this.db - .prepare('INSERT INTO search_fts (page_id, title, body) VALUES (?, ?, ?)') - .run(pageId, row.title, [row.body, ...files].join('\n')) + .prepare("INSERT INTO search_fts (page_id, title, body) VALUES (?, ?, ?)") + .run(pageId, row.title, [row.body, ...files].join("\n")) } } diff --git a/apps/server/src/routes/auth.ts b/src/backend/src/routes/auth.ts similarity index 82% rename from apps/server/src/routes/auth.ts rename to src/backend/src/routes/auth.ts index 45b93e6..e751a88 100644 --- a/apps/server/src/routes/auth.ts +++ b/src/backend/src/routes/auth.ts @@ -1,5 +1,4 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { Type } from '@sinclair/typebox' +import { Type } from "@sinclair/typebox" import { ApiError, AuthState, @@ -12,12 +11,12 @@ import { SessionInfo, SessionResponse, SetupRequest, -} from '@cnotes/shared' -import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify' -import { AuthError, type AuthService, deviceNameFromUserAgent, SESSION_TTL_MS } from '../auth' -import type { Config } from '../config' -import { cookieSecure, requireSession, SESSION_COOKIE, sessionFromRequest } from '../http' -import { timingSafeEqualStr } from '../secrets' +} from "@cnotes/shared" +import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify" +import { AuthError, type AuthService, deviceNameFromUserAgent, SESSION_TTL_MS } from "../auth" +import type { Config } from "../config" +import { cookieSecure, requireSession, SESSION_COOKIE, sessionFromRequest } from "../http" +import { timingSafeEqualStr } from "../secrets" export interface AuthRoutesOptions { auth: AuthService @@ -30,15 +29,15 @@ export interface AuthRoutesOptions { export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) { const { auth, config } = opts - const strict = { config: { rateLimit: { max: 10, timeWindow: '1 minute' } } } + const strict = { config: { rateLimit: { max: 10, timeWindow: "1 minute" } } } const authed = requireSession(auth) function setSessionCookie(req: FastifyRequest, reply: FastifyReply, userId: string) { - const { token } = auth.createSession(userId, deviceNameFromUserAgent(req.headers['user-agent'])) + const { token } = auth.createSession(userId, deviceNameFromUserAgent(req.headers["user-agent"])) reply.setCookie(SESSION_COOKIE, token, { - path: '/', + path: "/", httpOnly: true, - sameSite: 'strict', + sameSite: "strict", secure: cookieSecure(config, req), maxAge: Math.floor(SESSION_TTL_MS / 1000), }) @@ -49,7 +48,7 @@ export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) throw err }) - app.get('/state', { schema: { response: { 200: AuthState } } }, async (req) => { + app.get("/state", { schema: { response: { 200: AuthState } } }, async (req) => { const session = sessionFromRequest(auth, req) return { setupRequired: auth.userCount() === 0, @@ -59,38 +58,38 @@ export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) }) app.post( - '/setup', + "/setup", { ...strict, schema: { body: SetupRequest, response: { 201: PublicUser, 403: ApiError } } }, async (req, reply) => { const body = req.body as SetupRequest const token = opts.getSetupToken() const tokenOk = - config.devMode || (!!token && timingSafeEqualStr((body.setupToken ?? '').trim(), token)) + config.devMode || (!!token && timingSafeEqualStr((body.setupToken ?? "").trim(), token)) if (auth.userCount() > 0 || !tokenOk) { - return reply.code(403).send({ error: 'Setup is not available or the setup token is wrong' }) + return reply.code(403).send({ error: "Setup is not available or the setup token is wrong" }) } const user = await auth.createUser(body.username, body.displayName, body.password) - req.log.info({ username: user.username }, 'first account created') + req.log.info({ username: user.username }, "first account created") return reply.code(201).send(user) }, ) app.post( - '/login', + "/login", { ...strict, schema: { body: LoginRequest, response: { 200: LoginResponse } } }, async (req, reply) => { const { username, password } = req.body as LoginRequest if (config.devMode) { const user = await auth.verifyPassword(username, password) setSessionCookie(req, reply, user.id) - return { step: 'done' as const, user } + return { step: "done" as const, user } } return auth.startLogin(username, password) }, ) app.post( - '/enroll', + "/enroll", { ...strict, schema: { body: CodeRequest, response: { 200: SessionResponse } } }, async (req, reply) => { const { challenge, code } = req.body as CodeRequest @@ -101,7 +100,7 @@ export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) ) app.post( - '/verify', + "/verify", { ...strict, schema: { body: CodeRequest, response: { 200: SessionResponse } } }, async (req, reply) => { const { challenge, code } = req.body as CodeRequest @@ -111,28 +110,28 @@ export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) }, ) - app.post('/logout', async (req, reply) => { + app.post("/logout", async (req, reply) => { const session = sessionFromRequest(auth, req) if (session) { auth.revokeSession(session.user.id, session.sessionId) opts.onSessionRevoked(session.sessionId) } - reply.clearCookie(SESSION_COOKIE, { path: '/' }) + reply.clearCookie(SESSION_COOKIE, { path: "/" }) return reply.code(204).send() }) app.get( - '/sessions', + "/sessions", { preHandler: authed, schema: { response: { 200: Type.Array(SessionInfo) } } }, async (req) => auth.listSessions(req.session!.user.id, req.session!.sessionId), ) app.delete<{ Params: { id: string } }>( - '/sessions/:id', + "/sessions/:id", { preHandler: authed, schema: { params: Type.Object({ id: Type.String({ maxLength: 64 }) }) } }, async (req, reply) => { if (!auth.revokeSession(req.session!.user.id, req.params.id)) { - return reply.code(404).send({ error: 'No such session' }) + return reply.code(404).send({ error: "No such session" }) } opts.onSessionRevoked(req.params.id) return reply.code(204).send() @@ -140,7 +139,7 @@ export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) ) app.post( - '/password', + "/password", { ...strict, preHandler: authed, schema: { body: ChangePasswordRequest } }, async (req, reply) => { const { currentPassword, newPassword } = req.body as ChangePasswordRequest @@ -150,7 +149,7 @@ export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) ) app.get( - '/users', + "/users", { preHandler: authed, schema: { response: { 200: Type.Array(PublicUser) } } }, async () => auth.listUsers(), ) @@ -158,7 +157,7 @@ export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) // Any member can add another household member. The new person sets up // two-factor at their first sign-in. app.post( - '/users', + "/users", { ...strict, preHandler: authed, @@ -167,13 +166,13 @@ export async function authRoutes(app: FastifyInstance, opts: AuthRoutesOptions) async (req, reply) => { const { username, displayName, password } = req.body as CreateUserRequest const user = await auth.createUser(username, displayName, password) - req.log.info({ username: user.username, by: req.session!.user.username }, 'account created') + req.log.info({ username: user.username, by: req.session!.user.username }, "account created") return reply.code(201).send(user) }, ) app.get( - '/me', + "/me", { preHandler: authed, schema: { diff --git a/apps/server/src/routes/files.ts b/src/backend/src/routes/files.ts similarity index 63% rename from apps/server/src/routes/files.ts rename to src/backend/src/routes/files.ts index 8a6f548..109a520 100644 --- a/apps/server/src/routes/files.ts +++ b/src/backend/src/routes/files.ts @@ -1,12 +1,11 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import fs from 'node:fs' -import { Type } from '@sinclair/typebox' -import { Attachment, isPageId, MAX_UPLOAD_BYTES } from '@cnotes/shared' -import type { FastifyInstance } from 'fastify' -import type { AuthService } from '../auth' -import type { FileStore } from '../files' -import { requireSession } from '../http' -import type { Projection } from '../projection' +import fs from "node:fs" +import { Type } from "@sinclair/typebox" +import { Attachment, isPageId, MAX_UPLOAD_BYTES } from "@cnotes/shared" +import type { FastifyInstance } from "fastify" +import type { AuthService } from "../auth" +import type { FileStore } from "../files" +import { requireSession } from "../http" +import type { Projection } from "../projection" export async function fileRoutes( app: FastifyInstance, @@ -15,7 +14,7 @@ export async function fileRoutes( const authed = requireSession(opts.auth) app.post<{ Querystring: { pageId: string } }>( - '/files', + "/files", { preHandler: authed, schema: { @@ -24,11 +23,11 @@ export async function fileRoutes( }, }, async (req, reply) => { - if (!isPageId(req.query.pageId)) return reply.code(400).send({ error: 'Invalid page' }) + if (!isPageId(req.query.pageId)) return reply.code(400).send({ error: "Invalid page" }) const file = await req.file({ limits: { fileSize: MAX_UPLOAD_BYTES, files: 1 } }) - if (!file) return reply.code(400).send({ error: 'No file' }) + if (!file) return reply.code(400).send({ error: "No file" }) const data = await file.toBuffer() - if (file.file.truncated) return reply.code(413).send({ error: 'File is too large' }) + if (file.file.truncated) return reply.code(413).send({ error: "File is too large" }) const attachment = await opts.files.save({ pageId: req.query.pageId, filename: file.filename, @@ -42,24 +41,24 @@ export async function fileRoutes( ) app.get<{ Params: { id: string } }>( - '/files/:id', + "/files/:id", { preHandler: authed, schema: { params: Type.Object({ id: Type.String({ maxLength: 64 }) }) } }, async (req, reply) => { const file = opts.files.get(req.params.id) - if (!file || !fs.existsSync(file.path)) return reply.code(404).send({ error: 'Not found' }) - const disposition = file.isImage ? 'inline' : 'attachment' + if (!file || !fs.existsSync(file.path)) return reply.code(404).send({ error: "Not found" }) + const disposition = file.isImage ? "inline" : "attachment" reply - .header('Content-Type', file.isImage ? file.mime : file.mime || 'application/octet-stream') - .header('Content-Length', file.size) + .header("Content-Type", file.isImage ? file.mime : file.mime || "application/octet-stream") + .header("Content-Length", file.size) .header( - 'Content-Disposition', - `${disposition}; filename="${file.filename.replace(/[^\x20-\x7e]|"/g, '_')}"; filename*=UTF-8''${encodeURIComponent(file.filename)}`, + "Content-Disposition", + `${disposition}; filename="${file.filename.replace(/[^\x20-\x7e]|"/g, "_")}"; filename*=UTF-8''${encodeURIComponent(file.filename)}`, ) // Attachments never change; let the service worker and browser keep them. - .header('Cache-Control', 'private, max-age=31536000, immutable') + .header("Cache-Control", "private, max-age=31536000, immutable") // Never let an uploaded file run scripts in our origin. .header( - 'Content-Security-Policy', + "Content-Security-Policy", "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox", ) return reply.send(fs.createReadStream(file.path)) diff --git a/apps/server/src/routes/search.ts b/src/backend/src/routes/search.ts similarity index 75% rename from apps/server/src/routes/search.ts rename to src/backend/src/routes/search.ts index 47818c4..16e7c6b 100644 --- a/apps/server/src/routes/search.ts +++ b/src/backend/src/routes/search.ts @@ -1,22 +1,21 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { Type } from '@sinclair/typebox' -import { SearchResponse } from '@cnotes/shared' -import type { FastifyInstance } from 'fastify' -import type { AuthService } from '../auth' -import type { DB } from '../db' -import { requireSession } from '../http' +import { Type } from "@sinclair/typebox" +import { SearchResponse } from "@cnotes/shared" +import type { FastifyInstance } from "fastify" +import type { AuthService } from "../auth" +import type { DB } from "../db" +import { requireSession } from "../http" /** Markers around matched text in snippets; the client turns them into highlights. */ -export const HL_START = '\u0002' -export const HL_END = '\u0003' +export const HL_START = "\u0002" +export const HL_END = "\u0003" export function ftsQuery(q: string): string | null { const terms = q .split(/\s+/) - .map((t) => t.replace(/"/g, '')) + .map((t) => t.replace(/"/g, "")) .filter((t) => [...t].length >= 3) if (!terms.length) return null - return terms.map((t) => `"${t}"`).join(' ') + return terms.map((t) => `"${t}"`).join(" ") } export function search(db: DB, q: string, limit = 30) { @@ -35,7 +34,7 @@ export function search(db: DB, q: string, limit = 30) { .all(fts, limit) as { pageId: string; title: string; snippet: string }[] } // Fewer than three characters: the trigram index can't help, use LIKE. - const like = `%${query.replace(/[\\%_]/g, (c) => '\\' + c)}%` + const like = `%${query.replace(/[\\%_]/g, (c) => "\\" + c)}%` return db .prepare( `SELECT id AS pageId, title, substr(body, 1, 120) AS snippet FROM pages @@ -47,7 +46,7 @@ export function search(db: DB, q: string, limit = 30) { export async function searchRoutes(app: FastifyInstance, opts: { auth: AuthService; db: DB }) { app.get<{ Querystring: { q: string } }>( - '/search', + "/search", { preHandler: requireSession(opts.auth), schema: { diff --git a/src/backend/src/secrets.ts b/src/backend/src/secrets.ts new file mode 100644 index 0000000..1b237ed --- /dev/null +++ b/src/backend/src/secrets.ts @@ -0,0 +1,62 @@ +import crypto from "node:crypto" +import fs from "node:fs" +import path from "node:path" + +/** + * Key used to encrypt TOTP secrets at rest. Taken from CNOTES_SECRET_KEY + * (base64, 32 bytes) or generated once into DATA_DIR/secret.key. + * Keeping it outside the database means a leaked database or backup does + * not leak the 2FA secrets. + */ +export function loadSecretKey(dataDir: string, fromEnv?: string): Buffer { + if (fromEnv) { + const key = Buffer.from(fromEnv, "base64") + if (key.length !== 32) throw new Error("CNOTES_SECRET_KEY must be 32 bytes, base64 encoded") + return key + } + const file = path.join(dataDir, "secret.key") + if (fs.existsSync(file)) { + const key = Buffer.from(fs.readFileSync(file, "utf8").trim(), "base64") + if (key.length !== 32) throw new Error(`${file} is not a valid key`) + return key + } + const key = crypto.randomBytes(32) + fs.writeFileSync(file, key.toString("base64") + "\n", { mode: 0o600, flag: "wx" }) + return key +} + +export function encrypt(key: Buffer, plaintext: string): string { + const iv = crypto.randomBytes(12) + const cipher = crypto.createCipheriv("aes-256-gcm", key, iv) + const data = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]) + return [ + "v1", + iv.toString("base64"), + cipher.getAuthTag().toString("base64"), + data.toString("base64"), + ].join(".") +} + +export function decrypt(key: Buffer, payload: string): string { + const [version, iv, tag, data] = payload.split(".") + if (version !== "v1" || !iv || !tag || !data) throw new Error("Unknown ciphertext format") + const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "base64")) + decipher.setAuthTag(Buffer.from(tag, "base64")) + return Buffer.concat([decipher.update(Buffer.from(data, "base64")), decipher.final()]).toString( + "utf8", + ) +} + +export function randomId(bytes = 12): string { + return crypto.randomBytes(bytes).toString("base64url") +} + +export function sha256(data: string | Buffer): string { + return crypto.createHash("sha256").update(data).digest("hex") +} + +export function timingSafeEqualStr(a: string, b: string): boolean { + const ab = Buffer.from(a) + const bb = Buffer.from(b) + return ab.length === bb.length && crypto.timingSafeEqual(ab, bb) +} diff --git a/apps/server/src/sync.ts b/src/backend/src/sync.ts similarity index 74% rename from apps/server/src/sync.ts rename to src/backend/src/sync.ts index a8b4c7e..4675443 100644 --- a/apps/server/src/sync.ts +++ b/src/backend/src/sync.ts @@ -1,24 +1,23 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Live sync of Yjs documents over WebSocket (/sync), using Hocuspocus. // Authentication happens on the HTTP upgrade, using the session cookie. -import type { IncomingMessage } from 'node:http' -import type { Duplex } from 'node:stream' -import { Hocuspocus } from '@hocuspocus/server' -import { parseDocName, type PublicUser } from '@cnotes/shared' -import type { FastifyBaseLogger } from 'fastify' -import { WebSocketServer, type WebSocket } from 'ws' -import * as Y from 'yjs' -import type { AuthService } from './auth' -import type { DB } from './db' -import { SESSION_COOKIE } from './http' -import type { Projection } from './projection' +import type { IncomingMessage } from "node:http" +import type { Duplex } from "node:stream" +import { Hocuspocus } from "@hocuspocus/server" +import { parseDocName, type PublicUser } from "@cnotes/shared" +import type { FastifyBaseLogger } from "fastify" +import { WebSocketServer, type WebSocket } from "ws" +import * as Y from "yjs" +import type { AuthService } from "./auth" +import type { DB } from "./db" +import { SESSION_COOKIE } from "./http" +import type { Projection } from "./projection" export interface SyncContext { user: PublicUser sessionId: string } -export const SYNC_PATH = '/sync' +export const SYNC_PATH = "/sync" export class SyncServer { readonly hocuspocus: Hocuspocus @@ -34,16 +33,16 @@ export class SyncServer { private parseCookie: (header: string) => Record, ) { this.hocuspocus = new Hocuspocus({ - name: 'cnotes', + name: "cnotes", quiet: true, debounce: 2000, maxDebounce: 10000, onConnect: async ({ documentName }) => { - if (!parseDocName(documentName)) throw new Error('Unknown document') + if (!parseDocName(documentName)) throw new Error("Unknown document") }, onLoadDocument: async ({ documentName, document }) => { const row = this.db - .prepare('SELECT state FROM documents WHERE name = ?') + .prepare("SELECT state FROM documents WHERE name = ?") .get(documentName) as { state: Buffer } | undefined if (row) Y.applyUpdate(document, new Uint8Array(row.state)) return document @@ -71,10 +70,10 @@ export class SyncServer { ) .run(documentName, state, Date.now(), userId) try { - if (ref.kind === 'workspace') this.projection.applyWorkspace(document, userId) + if (ref.kind === "workspace") this.projection.applyWorkspace(document, userId) else this.projection.applyPage(ref.pageId, document, userId) } catch (err) { - this.log.error({ err, documentName }, 'failed to update search index') + this.log.error({ err, documentName }, "failed to update search index") } } @@ -82,7 +81,7 @@ export class SyncServer { loadStored(documentName: string): Y.Doc | null { const live = this.hocuspocus.documents.get(documentName) if (live) return live - const row = this.db.prepare('SELECT state FROM documents WHERE name = ?').get(documentName) as + const row = this.db.prepare("SELECT state FROM documents WHERE name = ?").get(documentName) as { state: Buffer } | undefined if (!row) return null const doc = new Y.Doc() @@ -99,7 +98,7 @@ export class SyncServer { host: req.headers.host, hasCookie: !!req.headers.cookie, }, - 'sync connection rejected', + "sync connection rejected", ) socket.write(`HTTP/1.1 ${code} ${message}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`) socket.destroy() @@ -111,21 +110,21 @@ export class SyncServer { try { originHost = new URL(origin).host } catch { - return reject(403, 'Forbidden') + return reject(403, "Forbidden") } - if (originHost !== req.headers.host) return reject(403, 'Forbidden') + if (originHost !== req.headers.host) return reject(403, "Forbidden") } - const cookies = this.parseCookie(req.headers.cookie ?? '') + const cookies = this.parseCookie(req.headers.cookie ?? "") const session = this.auth.validateSession(cookies[SESSION_COOKIE]) - if (!session) return reject(401, 'Unauthorized') + if (!session) return reject(401, "Unauthorized") this.wss.handleUpgrade(req, socket, head, (ws) => { const headers = new Headers() for (const [k, v] of Object.entries(req.headers)) { - if (typeof v === 'string') headers.set(k, v) + if (typeof v === "string") headers.set(k, v) } - headers.delete('cookie') - const request = new Request(`http://localhost${req.url ?? '/'}`, { headers }) + headers.delete("cookie") + const request = new Request(`http://localhost${req.url ?? "/"}`, { headers }) const context: SyncContext = { user: session.user, sessionId: session.sessionId } const connection = this.hocuspocus.handleConnection(ws, request, context) @@ -133,23 +132,23 @@ export class SyncServer { if (!set) this.socketsBySession.set(session.sessionId, (set = new Set())) set.add(ws) - ws.on('message', (data: Buffer | ArrayBuffer | Buffer[]) => { + ws.on("message", (data: Buffer | ArrayBuffer | Buffer[]) => { const buf = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data as ArrayBuffer) connection.handleMessage(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)) }) - ws.on('pong', () => connection.touch()) - ws.on('close', (code, reason) => { + ws.on("pong", () => connection.touch()) + ws.on("close", (code, reason) => { set!.delete(ws) if (set!.size === 0) this.socketsBySession.delete(session.sessionId) connection.handleClose({ code, reason: reason.toString() }) }) - ws.on('error', (err) => this.log.warn({ err }, 'sync socket error')) + ws.on("error", (err) => this.log.warn({ err }, "sync socket error")) }) } /** Closes live connections of a revoked session. */ closeSession(sessionId: string) { - for (const ws of this.socketsBySession.get(sessionId) ?? []) ws.close(4401, 'Session ended') + for (const ws of this.socketsBySession.get(sessionId) ?? []) ws.close(4401, "Session ended") } async close() { diff --git a/src/backend/test/app.test.ts b/src/backend/test/app.test.ts new file mode 100644 index 0000000..a2ed5b5 --- /dev/null +++ b/src/backend/test/app.test.ts @@ -0,0 +1,97 @@ +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { afterAll, beforeAll, describe, expect, it } from "vitest" +import { inlineScriptHashes } from "../src/app" +import { loadConfig } from "../src/config" +import { makeApp, type TestApp } from "./helpers" + +describe("static app serving", () => { + let webRoot: string + let app: TestApp + let cleanup: () => Promise + + beforeAll(async () => { + webRoot = fs.mkdtempSync(path.join(os.tmpdir(), "cnotes-web-")) + fs.writeFileSync( + path.join(webRoot, "_shell.html"), + "cnotes", + ) + fs.mkdirSync(path.join(webRoot, "assets")) + fs.writeFileSync(path.join(webRoot, "assets", "app-abc123.js"), "console.log(1)") + ;({ app, cleanup } = await makeApp({ webRoot })) + }) + + afterAll(async () => { + await cleanup() + fs.rmSync(webRoot, { recursive: true, force: true }) + }) + + it("reports health", async () => { + const res = await app.inject({ method: "GET", url: "/api/health" }) + expect(res.statusCode).toBe(200) + expect(res.json()).toEqual({ status: "ok", version: "1.2.3" }) + }) + + it("serves the app shell for client routes", async () => { + const res = await app.inject({ method: "GET", url: "/pages/some-page" }) + expect(res.statusCode).toBe(200) + expect(res.headers["content-type"]).toContain("text/html") + expect(res.headers["cache-control"]).toBe("no-cache") + expect(res.body).toContain("cnotes") + }) + + it("caches hashed assets forever", async () => { + const res = await app.inject({ method: "GET", url: "/assets/app-abc123.js" }) + expect(res.statusCode).toBe(200) + expect(res.headers["cache-control"]).toContain("immutable") + }) + + it("returns JSON 404 for unknown API routes", async () => { + const res = await app.inject({ method: "GET", url: "/api/nope" }) + expect(res.statusCode).toBe(404) + expect(res.json()).toEqual({ error: "Not Found" }) + }) + + it("sends security headers and allows the shell scripts by hash only", async () => { + const res = await app.inject({ method: "GET", url: "/api/health" }) + const csp = String(res.headers["content-security-policy"]) + expect(csp).toContain("default-src 'self'") + expect(csp).toContain(inlineScriptHashes("")[0]) + expect(csp).not.toMatch(/script-src[^;]*unsafe-inline/) + expect(res.headers["x-content-type-options"]).toBe("nosniff") + }) + + it("blocks cross-origin state-changing requests", async () => { + const res = await app.inject({ + method: "POST", + url: "/api/auth/login", + headers: { origin: "https://evil.example", host: "notes.example.se" }, + payload: { username: "x", password: "y" }, + }) + expect(res.statusCode).toBe(403) + }) +}) + +describe("inlineScriptHashes", () => { + it("hashes inline scripts and skips external ones", () => { + const html = + '' + const hashes = inlineScriptHashes(html) + expect(hashes).toHaveLength(2) + expect(hashes[0]).toMatch(/^'sha256-[A-Za-z0-9+/]+=*'$/) + }) +}) + +describe("loadConfig", () => { + it("parses TRUST_PROXY", () => { + expect(loadConfig({}).trustProxy).toBe(false) + expect(loadConfig({ TRUST_PROXY: "true" }).trustProxy).toBe(true) + expect(loadConfig({ TRUST_PROXY: "172.16.0.0/12" }).trustProxy).toBe("172.16.0.0/12") + }) + + it("rejects invalid numbers", () => { + expect(() => loadConfig({ PORT: "abc" })).toThrow("Invalid PORT") + expect(() => loadConfig({ BACKUP_HOUR: "25" })).toThrow("Invalid BACKUP_HOUR") + }) +}) diff --git a/src/backend/test/auth.test.ts b/src/backend/test/auth.test.ts new file mode 100644 index 0000000..4f49b9b --- /dev/null +++ b/src/backend/test/auth.test.ts @@ -0,0 +1,231 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest" +import { deviceNameFromUserAgent } from "../src/auth" +import { cookieFrom, makeApp, SETUP_TOKEN, signUp, totpCode, type TestApp } from "./helpers" + +let app: TestApp +let cleanup: () => Promise + +beforeEach(async () => { + ;({ app, cleanup } = await makeApp()) +}) +afterEach(async () => cleanup()) + +const PASSWORD = "correct horse battery" + +async function login(username: string, password = PASSWORD) { + return app.inject({ method: "POST", url: "/api/auth/login", payload: { username, password } }) +} + +describe("first-run setup", () => { + it("requires the setup token and only works once", async () => { + let res = await app.inject({ method: "GET", url: "/api/auth/state" }) + expect(res.json()).toEqual({ setupRequired: true, setupTokenRequired: true, user: null }) + + res = await app.inject({ + method: "POST", + url: "/api/auth/setup", + payload: { setupToken: "wrong", username: "sara", displayName: "Sara", password: PASSWORD }, + }) + expect(res.statusCode).toBe(403) + + await signUp(app) + res = await app.inject({ + method: "POST", + url: "/api/auth/setup", + payload: { setupToken: SETUP_TOKEN, username: "eve", displayName: "Eve", password: PASSWORD }, + }) + expect(res.statusCode).toBe(403) + res = await app.inject({ method: "GET", url: "/api/auth/state" }) + expect(res.json().setupRequired).toBe(false) + }) + + it("needs only a username and password, with no password rules", async () => { + let res = await app.inject({ + method: "POST", + url: "/api/auth/setup", + payload: { setupToken: SETUP_TOKEN, username: "sara", password: "x" }, + }) + expect(res.statusCode).toBe(201) + expect(res.json()).toMatchObject({ username: "sara", displayName: "sara" }) + res = await login("sara", "x") + expect(res.json().step).toBe("enroll") + }) +}) + +describe("dev mode", () => { + it("skips the setup token and two-factor", async () => { + await cleanup() + ;({ app, cleanup } = await makeApp({ devMode: true })) + let res = await app.inject({ method: "GET", url: "/api/auth/state" }) + expect(res.json()).toEqual({ setupRequired: true, setupTokenRequired: false, user: null }) + + res = await app.inject({ + method: "POST", + url: "/api/auth/setup", + payload: { username: "sara", password: "pw" }, + }) + expect(res.statusCode).toBe(201) + + res = await login("sara", "wrong") + expect(res.statusCode).toBe(401) + res = await login("sara", "pw") + expect(res.statusCode).toBe(200) + expect(res.json()).toMatchObject({ step: "done", user: { username: "sara" } }) + const cookie = cookieFrom(res) + res = await app.inject({ method: "GET", url: "/api/auth/state", headers: { cookie } }) + expect(res.json().user.username).toBe("sara") + }) +}) + +describe("sign-in with two-factor", () => { + it("enrolls on first sign-in, then asks for a code", async () => { + const { cookie, secret, recoveryCodes } = await signUp(app) + expect(recoveryCodes).toHaveLength(10) + + const state = await app.inject({ method: "GET", url: "/api/auth/state", headers: { cookie } }) + expect(state.json().user).toMatchObject({ username: "sara" }) + + const step1 = await login("sara") + expect(step1.json().step).toBe("totp") + const ok = await app.inject({ + method: "POST", + url: "/api/auth/verify", + payload: { challenge: step1.json().challenge, code: totpCode(secret, 1) }, + }) + expect(ok.statusCode).toBe(200) + expect(cookieFrom(ok)).toMatch(/^cnotes_session=/) + expect(String(ok.headers["set-cookie"])).toMatch(/HttpOnly/i) + expect(String(ok.headers["set-cookie"])).toMatch(/SameSite=Strict/i) + }) + + it("rejects a wrong password without saying which part was wrong", async () => { + await signUp(app) + const a = await login("sara", "wrong password!!") + const b = await login("nobody", "wrong password!!") + expect(a.statusCode).toBe(401) + expect(b.statusCode).toBe(401) + expect(a.json()).toEqual(b.json()) + }) + + it("rejects a reused code", async () => { + const { secret } = await signUp(app) + const code = totpCode(secret, 1) + const first = await login("sara") + expect( + ( + await app.inject({ + method: "POST", + url: "/api/auth/verify", + payload: { challenge: first.json().challenge, code }, + }) + ).statusCode, + ).toBe(200) + const second = await login("sara") + const replay = await app.inject({ + method: "POST", + url: "/api/auth/verify", + payload: { challenge: second.json().challenge, code }, + }) + expect(replay.statusCode).toBe(401) + }) + + it("accepts each recovery code once", async () => { + const { recoveryCodes } = await signUp(app) + const use = async () => { + const step1 = await login("sara") + return app.inject({ + method: "POST", + url: "/api/auth/verify", + payload: { challenge: step1.json().challenge, code: recoveryCodes[0]!.toUpperCase() }, + }) + } + expect((await use()).statusCode).toBe(200) + expect((await use()).statusCode).toBe(401) + }) + + it("limits attempts per challenge", async () => { + await signUp(app) + const { challenge } = (await login("sara")).json() + const codes = [] + for (let i = 0; i < 6; i++) { + codes.push( + ( + await app.inject({ + method: "POST", + url: "/api/auth/verify", + payload: { challenge, code: "000000" }, + }) + ).statusCode, + ) + } + expect(codes.at(-1)).toBe(429) + }) +}) + +describe("sessions and members", () => { + it("lists and revokes sessions", async () => { + const { cookie } = await signUp(app) + const list = await app.inject({ method: "GET", url: "/api/auth/sessions", headers: { cookie } }) + expect(list.json()).toHaveLength(1) + expect(list.json()[0].current).toBe(true) + + const del = await app.inject({ + method: "DELETE", + url: `/api/auth/sessions/${list.json()[0].id}`, + headers: { cookie }, + }) + expect(del.statusCode).toBe(204) + const after = await app.inject({ + method: "GET", + url: "/api/auth/sessions", + headers: { cookie }, + }) + expect(after.statusCode).toBe(401) + }) + + it("lets a member add the second person, who enrolls their own 2FA", async () => { + const sara = await signUp(app) + const partner = await signUp(app, "alex", "another long password", sara.cookie) + const users = await app.inject({ + method: "GET", + url: "/api/auth/users", + headers: { cookie: partner.cookie }, + }) + expect(users.json().map((u: { username: string }) => u.username)).toEqual(["sara", "alex"]) + }) + + it("logs out", async () => { + const { cookie } = await signUp(app) + await app.inject({ method: "POST", url: "/api/auth/logout", headers: { cookie } }) + const me = await app.inject({ method: "GET", url: "/api/auth/me", headers: { cookie } }) + expect(me.statusCode).toBe(401) + }) + + it("changes the password", async () => { + const { cookie } = await signUp(app) + const res = await app.inject({ + method: "POST", + url: "/api/auth/password", + headers: { cookie }, + payload: { currentPassword: PASSWORD, newPassword: "a brand new password" }, + }) + expect(res.statusCode).toBe(204) + expect((await login("sara")).statusCode).toBe(401) + expect((await login("sara", "a brand new password")).statusCode).toBe(200) + }) +}) + +describe("deviceNameFromUserAgent", () => { + it("names common devices", () => { + expect( + deviceNameFromUserAgent( + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1", + ), + ).toBe("iPhone · Safari") + expect( + deviceNameFromUserAgent( + "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36", + ), + ).toBe("Android · Chrome") + }) +}) diff --git a/apps/server/test/backup.test.ts b/src/backend/test/backup.test.ts similarity index 66% rename from apps/server/test/backup.test.ts rename to src/backend/test/backup.test.ts index f40e02a..3845942 100644 --- a/apps/server/test/backup.test.ts +++ b/src/backend/test/backup.test.ts @@ -1,8 +1,7 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import fs from 'node:fs' -import Database from 'better-sqlite3' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { makeApp, signUp, type TestApp } from './helpers' +import fs from "node:fs" +import Database from "better-sqlite3" +import { afterEach, beforeEach, describe, expect, it } from "vitest" +import { makeApp, signUp, type TestApp } from "./helpers" let app: TestApp let cleanup: () => Promise @@ -12,30 +11,30 @@ beforeEach(async () => { }) afterEach(async () => cleanup()) -describe('backups', () => { - it('writes a restorable backup and keeps only the newest ones', async () => { +describe("backups", () => { + it("writes a restorable backup and keeps only the newest ones", async () => { await signUp(app) const backups = app.cnotes.backups fs.mkdirSync(backups.dir, { recursive: true }) // Older backups that should be pruned (keep defaults to 14). for (let d = 1; d <= 15; d++) { - fs.writeFileSync(backups.fileFor(new Date(Date.UTC(2020, 0, d))), '') + fs.writeFileSync(backups.fileFor(new Date(Date.UTC(2020, 0, d))), "") } const now = new Date(2026, 10, 28, 4, 0) await backups.tick(now) const file = backups.fileFor(now) expect(fs.existsSync(file)).toBe(true) - expect(fs.readdirSync(backups.dir).filter((f) => f.endsWith('.sqlite'))).toHaveLength(14) + expect(fs.readdirSync(backups.dir).filter((f) => f.endsWith(".sqlite"))).toHaveLength(14) const copy = new Database(file, { readonly: true }) - expect(copy.prepare('SELECT username FROM users').get()).toEqual({ username: 'sara' }) + expect(copy.prepare("SELECT username FROM users").get()).toEqual({ username: "sara" }) copy.close() }) - it('waits for the configured hour once a backup exists', async () => { + it("waits for the configured hour once a backup exists", async () => { const backups = app.cnotes.backups fs.mkdirSync(backups.dir, { recursive: true }) - fs.writeFileSync(backups.fileFor(new Date(2026, 10, 27, 12)), '') + fs.writeFileSync(backups.fileFor(new Date(2026, 10, 27, 12)), "") const early = new Date(2026, 10, 28, 1, 0) await backups.tick(early) expect(fs.existsSync(backups.fileFor(early))).toBe(false) diff --git a/apps/server/test/helpers.ts b/src/backend/test/helpers.ts similarity index 65% rename from apps/server/test/helpers.ts rename to src/backend/test/helpers.ts index 89584d7..396d238 100644 --- a/apps/server/test/helpers.ts +++ b/src/backend/test/helpers.ts @@ -1,21 +1,20 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import * as OTPAuth from 'otpauth' -import { buildApp } from '../src/app' -import { loadConfig, type Config } from '../src/config' +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import * as OTPAuth from "otpauth" +import { buildApp } from "../src/app" +import { loadConfig, type Config } from "../src/config" -export const SETUP_TOKEN = 'test-setup-token' +export const SETUP_TOKEN = "test-setup-token" export async function makeApp(overrides: Partial = {}) { - const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cnotes-test-')) + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "cnotes-test-")) const app = await buildApp( { ...loadConfig({}), dataDir, - logLevel: 'silent', - version: '1.2.3', + logLevel: "silent", + version: "1.2.3", setupToken: SETUP_TOKEN, ...overrides, }, @@ -28,7 +27,7 @@ export async function makeApp(overrides: Partial = {}) { return { app, dataDir, cleanup } } -export type TestApp = Awaited>['app'] +export type TestApp = Awaited>["app"] /** TOTP code for a time step after the current one (the server rejects reuse of a step). */ export function totpCode(secret: string, offsetSteps = 0): string { @@ -39,45 +38,45 @@ export function totpCode(secret: string, offsetSteps = 0): string { } export function cookieFrom(res: { headers: Record }): string { - const raw = res.headers['set-cookie'] + const raw = res.headers["set-cookie"] const list = Array.isArray(raw) ? raw : [raw] - const c = list.find((v) => typeof v === 'string' && v.startsWith('cnotes_session=')) - if (!c) throw new Error('no session cookie') - return (c as string).split(';')[0]! + const c = list.find((v) => typeof v === "string" && v.startsWith("cnotes_session=")) + if (!c) throw new Error("no session cookie") + return (c as string).split(";")[0]! } /** Creates an account (first one via setup), enrolls 2FA and returns a session cookie. */ export async function signUp( app: TestApp, - username = 'sara', - password = 'correct horse battery', + username = "sara", + password = "correct horse battery", asCookie?: string, ) { if (!asCookie) { const setup = await app.inject({ - method: 'POST', - url: '/api/auth/setup', + method: "POST", + url: "/api/auth/setup", payload: { setupToken: SETUP_TOKEN, username, displayName: username, password }, }) if (setup.statusCode !== 201) throw new Error(setup.body) } else { const created = await app.inject({ - method: 'POST', - url: '/api/auth/users', + method: "POST", + url: "/api/auth/users", headers: { cookie: asCookie }, payload: { username, displayName: username, password }, }) if (created.statusCode !== 201) throw new Error(created.body) } const login = await app.inject({ - method: 'POST', - url: '/api/auth/login', + method: "POST", + url: "/api/auth/login", payload: { username, password }, }) const { challenge, secret } = login.json() const enroll = await app.inject({ - method: 'POST', - url: '/api/auth/enroll', + method: "POST", + url: "/api/auth/enroll", payload: { challenge, code: totpCode(secret) }, }) if (enroll.statusCode !== 200) throw new Error(enroll.body) diff --git a/apps/server/test/sync.test.ts b/src/backend/test/sync.test.ts similarity index 60% rename from apps/server/test/sync.test.ts rename to src/backend/test/sync.test.ts index c88e9e7..2c800cb 100644 --- a/apps/server/test/sync.test.ts +++ b/src/backend/test/sync.test.ts @@ -1,11 +1,10 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { HocuspocusProvider, HocuspocusProviderWebsocket } from '@hocuspocus/provider' -import { CONTENT_FIELD, listPages, pageDocName, pagesMap, WORKSPACE_DOC } from '@cnotes/shared' -import { unzipSync } from 'fflate' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import WebSocket from 'ws' -import * as Y from 'yjs' -import { makeApp, signUp, type TestApp } from './helpers' +import { HocuspocusProvider, HocuspocusProviderWebsocket } from "@hocuspocus/provider" +import { CONTENT_FIELD, listPages, pageDocName, pagesMap, WORKSPACE_DOC } from "@cnotes/shared" +import { unzipSync } from "fflate" +import { afterEach, beforeEach, describe, expect, it } from "vitest" +import WebSocket from "ws" +import * as Y from "yjs" +import { makeApp, signUp, type TestApp } from "./helpers" let app: TestApp let cleanup: () => Promise @@ -15,9 +14,9 @@ const sockets: HocuspocusProviderWebsocket[] = [] beforeEach(async () => { ;({ app, cleanup } = await makeApp()) - await app.listen({ host: '127.0.0.1', port: 0 }) + await app.listen({ host: "127.0.0.1", port: 0 }) const addr = app.server.address() - if (!addr || typeof addr === 'string') throw new Error('no address') + if (!addr || typeof addr === "string") throw new Error("no address") url = `ws://127.0.0.1:${addr.port}/sync` }) @@ -46,13 +45,13 @@ function connect(name: string, cookie: string, doc = new Y.Doc()) { } function synced(p: HocuspocusProvider) { - return new Promise((resolve) => (p.isSynced ? resolve() : p.on('synced', () => resolve()))) + return new Promise((resolve) => (p.isSynced ? resolve() : p.on("synced", () => resolve()))) } async function waitFor(check: () => boolean, ms = 5000) { const start = Date.now() while (!check()) { - if (Date.now() - start > ms) throw new Error('timed out') + if (Date.now() - start > ms) throw new Error("timed out") await new Promise((r) => setTimeout(r, 20)) } } @@ -61,10 +60,10 @@ function addPage(doc: Y.Doc, id: string, title: string) { const entry = new Y.Map() doc.transact(() => { pagesMap(doc).set(id, entry) - entry.set('title', title) - entry.set('parentId', null) - entry.set('order', 'a0') - entry.set('archived', false) + entry.set("title", title) + entry.set("parentId", null) + entry.set("order", "a0") + entry.set("archived", false) }) } @@ -73,47 +72,47 @@ function writeParagraphs(doc: Y.Doc, ...texts: string[]) { fragment.insert( fragment.length, texts.map((t) => { - const p = new Y.XmlElement('paragraph') + const p = new Y.XmlElement("paragraph") p.insert(0, [new Y.XmlText(t)]) return p }), ) } -describe('sync', () => { - it('rejects connections without a session', async () => { +describe("sync", () => { + it("rejects connections without a session", async () => { const status = await new Promise((resolve) => { const ws = new WebSocket(url) - ws.on('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0)) - ws.on('open', () => resolve(101)) + ws.on("unexpected-response", (_req, res) => resolve(res.statusCode ?? 0)) + ws.on("open", () => resolve(101)) }) expect(status).toBe(401) }) - it('rejects cross-site connections', async () => { + it("rejects cross-site connections", async () => { const { cookie } = await signUp(app) const status = await new Promise((resolve) => { - const ws = new WebSocket(url, { headers: { cookie, origin: 'https://evil.example' } }) - ws.on('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0)) - ws.on('open', () => resolve(101)) + const ws = new WebSocket(url, { headers: { cookie, origin: "https://evil.example" } }) + ws.on("unexpected-response", (_req, res) => resolve(res.statusCode ?? 0)) + ws.on("open", () => resolve(101)) }) expect(status).toBe(403) }) - it('syncs edits live between two people and persists them', async () => { + it("syncs edits live between two people and persists them", async () => { const sara = await signUp(app) - const alex = await signUp(app, 'alex', 'another long password', sara.cookie) + const alex = await signUp(app, "alex", "another long password", sara.cookie) const a = connect(WORKSPACE_DOC, sara.cookie) const b = connect(WORKSPACE_DOC, alex.cookie) await Promise.all([synced(a), synced(b)]) - addPage(a.document, 'shopping01', 'Weekly shopping') - await waitFor(() => listPages(b.document).some((p) => p.title === 'Weekly shopping')) + addPage(a.document, "shopping01", "Weekly shopping") + await waitFor(() => listPages(b.document).some((p) => p.title === "Weekly shopping")) - const page = connect(pageDocName('shopping01'), alex.cookie) + const page = connect(pageDocName("shopping01"), alex.cookie) await synced(page) - writeParagraphs(page.document, 'Diskmaskinstabletter', 'Mjölk') + writeParagraphs(page.document, "Diskmaskinstabletter", "Mjölk") await waitFor(() => !page.hasUnsyncedChanges) // Stored and indexed after the debounce; flush instead of waiting. @@ -124,126 +123,126 @@ describe('sync', () => { await waitFor(() => { const r = app.cnotes.db.prepare("SELECT body FROM pages WHERE id = 'shopping01'").get() as { body: string } | undefined - return !!r?.body.includes('Mjölk') + return !!r?.body.includes("Mjölk") }) const search = async (q: string) => ( await app.inject({ - method: 'GET', + method: "GET", url: `/api/search?q=${encodeURIComponent(q)}`, headers: { cookie: sara.cookie }, }) ).json().hits as { pageId: string; title: string; snippet: string }[] - expect((await search('maskin'))[0]).toMatchObject({ - pageId: 'shopping01', - title: 'Weekly shopping', + expect((await search("maskin"))[0]).toMatchObject({ + pageId: "shopping01", + title: "Weekly shopping", }) - expect((await search('mjolk')).length).toBe(1) - expect((await search('weekly')).length).toBe(1) - expect((await search('zz')).length).toBe(0) - expect((await search('kaffe')).length).toBe(0) + expect((await search("mjolk")).length).toBe(1) + expect((await search("weekly")).length).toBe(1) + expect((await search("zz")).length).toBe(0) + expect((await search("kaffe")).length).toBe(0) // A fresh client gets the stored content. providers.splice(0).forEach((p) => p.destroy()) sockets.splice(0).forEach((s) => s.destroy()) await new Promise((r) => setTimeout(r, 100)) - const again = connect(pageDocName('shopping01'), sara.cookie) + const again = connect(pageDocName("shopping01"), sara.cookie) await synced(again) - expect(again.document.getXmlFragment(CONTENT_FIELD).toString()).toContain('Mjölk') + expect(again.document.getXmlFragment(CONTENT_FIELD).toString()).toContain("Mjölk") }) - it('closes live connections when the session is revoked', async () => { + it("closes live connections when the session is revoked", async () => { const { cookie } = await signUp(app) const p = connect(WORKSPACE_DOC, cookie) await synced(p) let closed = false - p.on('close', () => (closed = true)) - await app.inject({ method: 'POST', url: '/api/auth/logout', headers: { cookie } }) + p.on("close", () => (closed = true)) + await app.inject({ method: "POST", url: "/api/auth/logout", headers: { cookie } }) await waitFor(() => closed) }) }) -describe('files and export', () => { - it('uploads, serves and exports attachments with Markdown', async () => { +describe("files and export", () => { + it("uploads, serves and exports attachments with Markdown", async () => { const { cookie } = await signUp(app) const ws = connect(WORKSPACE_DOC, cookie) await synced(ws) - addPage(ws.document, 'manuals001', 'Manuals') - const page = connect(pageDocName('manuals001'), cookie) + addPage(ws.document, "manuals001", "Manuals") + const page = connect(pageDocName("manuals001"), cookie) await synced(page) - const boundary = '----cnotes' + const boundary = "----cnotes" const body = Buffer.concat([ Buffer.from( `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="Bosch manual.pdf"\r\nContent-Type: application/pdf\r\n\r\n`, ), - Buffer.from('%PDF-1.4 fake'), + Buffer.from("%PDF-1.4 fake"), Buffer.from(`\r\n--${boundary}--\r\n`), ]) const up = await app.inject({ - method: 'POST', - url: '/api/files?pageId=manuals001', - headers: { cookie, 'content-type': `multipart/form-data; boundary=${boundary}` }, + method: "POST", + url: "/api/files?pageId=manuals001", + headers: { cookie, "content-type": `multipart/form-data; boundary=${boundary}` }, payload: body, }) expect(up.statusCode).toBe(201) const att = up.json() expect(att).toMatchObject({ - filename: 'Bosch manual.pdf', - mime: 'application/pdf', + filename: "Bosch manual.pdf", + mime: "application/pdf", isImage: false, }) const file = await app.inject({ - method: 'GET', + method: "GET", url: `/api/files/${att.id}`, headers: { cookie }, }) expect(file.statusCode).toBe(200) - expect(file.headers['content-disposition']).toMatch(/^attachment;/) - expect(file.headers['content-security-policy']).toContain('sandbox') - expect(file.body).toBe('%PDF-1.4 fake') - expect((await app.inject({ method: 'GET', url: `/api/files/${att.id}` })).statusCode).toBe(401) + expect(file.headers["content-disposition"]).toMatch(/^attachment;/) + expect(file.headers["content-security-policy"]).toContain("sandbox") + expect(file.body).toBe("%PDF-1.4 fake") + expect((await app.inject({ method: "GET", url: `/api/files/${att.id}` })).statusCode).toBe(401) page.document.transact(() => { - writeParagraphs(page.document, 'Dishwasher') - const chip = new Y.XmlElement('fileAttachment') - chip.setAttribute('id', att.id) - chip.setAttribute('filename', att.filename) + writeParagraphs(page.document, "Dishwasher") + const chip = new Y.XmlElement("fileAttachment") + chip.setAttribute("id", att.id) + chip.setAttribute("filename", att.filename) page.document.getXmlFragment(CONTENT_FIELD).push([chip]) }) await waitFor(() => !page.hasUnsyncedChanges && !ws.hasUnsyncedChanges) - const res = await app.inject({ method: 'GET', url: '/api/export', headers: { cookie } }) + const res = await app.inject({ method: "GET", url: "/api/export", headers: { cookie } }) expect(res.statusCode).toBe(200) const zip = unzipSync(new Uint8Array(res.rawPayload)) - const md = new TextDecoder().decode(zip['Manuals.md']) - expect(md).toContain('# Manuals') - expect(md).toContain('Dishwasher') + const md = new TextDecoder().decode(zip["Manuals.md"]) + expect(md).toContain("# Manuals") + expect(md).toContain("Dishwasher") expect(md).toContain(`[Bosch manual.pdf](attachments/${att.id}-Bosch%20manual.pdf)`) expect(new TextDecoder().decode(zip[`attachments/${att.id}-Bosch manual.pdf`])).toBe( - '%PDF-1.4 fake', + "%PDF-1.4 fake", ) }) - it('strips location data from photos', async () => { - const sharp = (await import('sharp')).default + it("strips location data from photos", async () => { + const sharp = (await import("sharp")).default const { cookie } = await signUp(app) const jpeg = await sharp({ - create: { width: 4000, height: 3000, channels: 3, background: '#c33' }, + create: { width: 4000, height: 3000, channels: 3, background: "#c33" }, }) .jpeg() - .withMetadata({ exif: { IFD0: { Copyright: 'secret-location' } } }) + .withMetadata({ exif: { IFD0: { Copyright: "secret-location" } } }) .toBuffer() - expect(jpeg.includes(Buffer.from('secret-location'))).toBe(true) + expect(jpeg.includes(Buffer.from("secret-location"))).toBe(true) - const boundary = '----cnotes' + const boundary = "----cnotes" const up = await app.inject({ - method: 'POST', - url: '/api/files?pageId=photos0001', - headers: { cookie, 'content-type': `multipart/form-data; boundary=${boundary}` }, + method: "POST", + url: "/api/files?pageId=photos0001", + headers: { cookie, "content-type": `multipart/form-data; boundary=${boundary}` }, payload: Buffer.concat([ Buffer.from( `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="IMG_0001.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`, @@ -255,11 +254,11 @@ describe('files and export', () => { expect(up.statusCode).toBe(201) expect(up.json()).toMatchObject({ isImage: true, width: 2560, height: 1920 }) const file = await app.inject({ - method: 'GET', + method: "GET", url: `/api/files/${up.json().id}`, headers: { cookie }, }) - expect(file.headers['content-disposition']).toMatch(/^inline;/) - expect(file.rawPayload.includes(Buffer.from('secret-location'))).toBe(false) + expect(file.headers["content-disposition"]).toMatch(/^inline;/) + expect(file.rawPayload.includes(Buffer.from("secret-location"))).toBe(false) }) }) diff --git a/apps/server/tsconfig.json b/src/backend/tsconfig.json similarity index 100% rename from apps/server/tsconfig.json rename to src/backend/tsconfig.json diff --git a/src/backend/vitest.config.ts b/src/backend/vitest.config.ts new file mode 100644 index 0000000..d3f09ad --- /dev/null +++ b/src/backend/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "vitest/config" + +export default defineConfig({ + test: { + name: "server", + include: ["test/**/*.test.ts"], + environment: "node", + }, +}) diff --git a/src/frontend/e2e/auth.spec.ts b/src/frontend/e2e/auth.spec.ts new file mode 100644 index 0000000..ecd6999 --- /dev/null +++ b/src/frontend/e2e/auth.spec.ts @@ -0,0 +1,44 @@ +import { expect, test } from "@playwright/test" +import { PASSWORD, STATE, totp, unique } from "./helpers" + +test("a new household member signs in and sets up two-factor", async ({ page, browser }) => { + // Sara adds the person through the API with her session. + const sara = await browser.newContext({ + storageState: STATE.sara, + baseURL: "http://localhost:3100", + }) + const username = unique("kid").replace(" ", "") + const created = await sara.request.post("/api/auth/users", { + data: { username, displayName: "Kid", password: PASSWORD }, + }) + expect(created.ok()).toBe(true) + await sara.close() + + await page.goto("/") + await page.getByLabel("Username").fill(username) + await page.getByLabel("Password").fill(PASSWORD) + await page.getByRole("button", { name: "Continue" }).click() + + await expect(page.getByRole("heading", { name: "Set up two-factor" })).toBeVisible() + await expect(page.getByRole("img", { name: /QR code/ })).toBeVisible() + const secret = (await page.locator("p.font-mono").textContent())!.trim() + await page.getByLabel(/6-digit code/).fill(totp(secret)) + await page.getByRole("button", { name: "Confirm" }).click() + + await expect(page.getByRole("heading", { name: "Save your recovery codes" })).toBeVisible() + await expect(page.getByTestId("recovery-codes").locator("li")).toHaveCount(10) + await page.getByRole("button", { name: "I have saved them" }).click() + await expect(page.getByRole("heading", { name: "Pinned" })).toBeVisible() + + // Sign out, then back in with a code. + await page.getByRole("link", { name: "Settings" }).click() + await page.getByRole("button", { name: "Sign out on this device" }).click() + await page.getByLabel("Username").fill(username) + await page.getByLabel("Password").fill(PASSWORD) + await page.getByRole("button", { name: "Continue" }).click() + await page.getByLabel(/authenticator app/).fill(totp(secret, 1)) + await page.getByRole("button", { name: "Sign in" }).click() + // Back where they were, signed in again. + await expect(page.getByText(`Signed in as Kid (${username})`)).toBeVisible() + await expect(page.getByTestId("sync-status")).toHaveAttribute("data-state", "synced") +}) diff --git a/apps/web/e2e/global-setup.ts b/src/frontend/e2e/global-setup.ts similarity index 53% rename from apps/web/e2e/global-setup.ts rename to src/frontend/e2e/global-setup.ts index 8c3875d..80aaeb7 100644 --- a/apps/web/e2e/global-setup.ts +++ b/src/frontend/e2e/global-setup.ts @@ -1,10 +1,9 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Creates the two household accounts through the API (including 2FA // enrollment) and stores their signed-in browser state for the tests. -import fs from 'node:fs' -import { request } from '@playwright/test' -import { PORT, SETUP_TOKEN } from '../playwright.config' -import { PASSWORD, STATE, totp } from './helpers' +import fs from "node:fs" +import { request } from "@playwright/test" +import { PORT, SETUP_TOKEN } from "../playwright.config" +import { PASSWORD, STATE, totp } from "./helpers" async function enroll( username: string, @@ -14,18 +13,18 @@ async function enroll( ) { const ctx = await request.newContext({ baseURL: `http://localhost:${PORT}` }) await create(ctx) - const login = await ctx.post('/api/auth/login', { data: { username, password } }) + const login = await ctx.post("/api/auth/login", { data: { username, password } }) const { challenge, secret } = await login.json() - const res = await ctx.post('/api/auth/enroll', { data: { challenge, code: totp(secret) } }) + const res = await ctx.post("/api/auth/enroll", { data: { challenge, code: totp(secret) } }) if (!res.ok()) throw new Error(await res.text()) await ctx.storageState({ path: statePath }) // Also cache who is signed in, like the app does after login. - const state = JSON.parse(fs.readFileSync(statePath, 'utf8')) + const state = JSON.parse(fs.readFileSync(statePath, "utf8")) const { user } = await res.json() state.origins = [ { origin: `http://localhost:${PORT}`, - localStorage: [{ name: 'cnotes:user', value: JSON.stringify(user) }], + localStorage: [{ name: "cnotes:user", value: JSON.stringify(user) }], }, ] fs.writeFileSync(statePath, JSON.stringify(state)) @@ -33,16 +32,16 @@ async function enroll( } export default async function globalSetup() { - fs.mkdirSync('test-results/.auth', { recursive: true }) - const sara = await enroll('sara', PASSWORD, STATE.sara, async (ctx) => { - const r = await ctx.post('/api/auth/setup', { - data: { setupToken: SETUP_TOKEN, username: 'sara', displayName: 'Sara', password: PASSWORD }, + fs.mkdirSync("test-results/.auth", { recursive: true }) + const sara = await enroll("sara", PASSWORD, STATE.sara, async (ctx) => { + const r = await ctx.post("/api/auth/setup", { + data: { setupToken: SETUP_TOKEN, username: "sara", displayName: "Sara", password: PASSWORD }, }) if (!r.ok()) throw new Error(await r.text()) }) - await enroll('alex', PASSWORD, STATE.alex, async () => { - const r = await sara.post('/api/auth/users', { - data: { username: 'alex', displayName: 'Alex', password: PASSWORD }, + await enroll("alex", PASSWORD, STATE.alex, async () => { + const r = await sara.post("/api/auth/users", { + data: { username: "alex", displayName: "Alex", password: PASSWORD }, }) if (!r.ok()) throw new Error(await r.text()) }) diff --git a/apps/web/e2e/helpers.ts b/src/frontend/e2e/helpers.ts similarity index 52% rename from apps/web/e2e/helpers.ts rename to src/frontend/e2e/helpers.ts index f5303c6..2b039bc 100644 --- a/apps/web/e2e/helpers.ts +++ b/src/frontend/e2e/helpers.ts @@ -1,11 +1,10 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { expect, type Browser, type Page } from '@playwright/test' -import * as OTPAuth from 'otpauth' +import { expect, type Browser, type Page } from "@playwright/test" +import * as OTPAuth from "otpauth" -export const PASSWORD = 'correct horse battery' +export const PASSWORD = "correct horse battery" export const STATE = { - sara: 'test-results/.auth/sara.json', - alex: 'test-results/.auth/alex.json', + sara: "test-results/.auth/sara.json", + alex: "test-results/.auth/alex.json", } export function totp(secret: string, offsetSteps = 0): string { @@ -16,15 +15,15 @@ export function totp(secret: string, offsetSteps = 0): string { } export function unique(prefix: string): string { - return `${prefix} ${Math.random().toString(36).slice(2, 7)}` + return `${prefix} ${crypto.randomUUID().slice(0, 8)}` } export async function signedInPage(browser: Browser, who: keyof typeof STATE, project: string) { - const { devices } = await import('@playwright/test') - const device = project === 'android' ? devices['Pixel 7'] : devices['iPhone 15'] + const { devices } = await import("@playwright/test") + const device = project === "android" ? devices["Pixel 7"] : devices["iPhone 15"] const context = await browser.newContext({ ...device, - baseURL: 'http://localhost:3100', + baseURL: "http://localhost:3100", storageState: STATE[who], }) const page = await context.newPage() @@ -33,15 +32,15 @@ export async function signedInPage(browser: Browser, who: keyof typeof STATE, pr /** Creates a page from Home and returns its URL. */ export async function newPage(page: Page, title: string): Promise { - await page.goto('/') - await page.getByRole('button', { name: 'New page' }).click() + await page.goto("/") + await page.getByRole("button", { name: "New page" }).click() await expect(page).toHaveURL(/\/p\//) - await page.getByLabel('Page title').fill(title) + await page.getByLabel("Page title").fill(title) return page.url() } export async function waitForSynced(page: Page) { - await expect(page.getByTestId('sync-status')).toHaveAttribute('data-state', 'synced', { + await expect(page.getByTestId("sync-status")).toHaveAttribute("data-state", "synced", { timeout: 15_000, }) } diff --git a/src/frontend/e2e/pages.spec.ts b/src/frontend/e2e/pages.spec.ts new file mode 100644 index 0000000..6a0246e --- /dev/null +++ b/src/frontend/e2e/pages.spec.ts @@ -0,0 +1,203 @@ +import path from "node:path" +import { expect, test } from "@playwright/test" +import { unzipSync } from "fflate" +import { newPage, signedInPage, STATE, unique, waitForSynced } from "./helpers" + +test.use({ storageState: STATE.sara }) + +test("shopping list: checklist, pin, open count, clear checked", async ({ page }) => { + const title = unique("Weekly shopping") + await newPage(page, title) + const editor = page.getByTestId("editor") + await editor.click() + await page.keyboard.type("[ ] Mjölk") + await page.keyboard.press("Enter") + await page.keyboard.type("Bröd") + await page.keyboard.press("Enter") + await page.keyboard.type("Diskmaskinstabletter") + await expect(editor.locator('ul[data-type="taskList"] > li')).toHaveCount(3) + + await editor + .locator('ul[data-type="taskList"] > li') + .nth(1) + .locator('input[type="checkbox"]') + .check() + await expect(page.getByRole("button", { name: "Clear checked (1)" })).toBeVisible() + + await page.getByRole("button", { name: "Page actions" }).click() + await page.getByRole("menuitem", { name: "Pin to Home" }).click() + + await page.getByRole("link", { name: "Home" }).click() + const pinned = page.getByTestId("pinned").getByRole("link", { name: new RegExp(title) }) + await expect(pinned).toContainText("2") + + await pinned.click() + await page.getByRole("button", { name: "Clear checked (1)" }).click() + await expect(page.getByTestId("editor").locator('ul[data-type="taskList"] > li')).toHaveCount(2) + await expect(page.getByTestId("editor")).not.toContainText("Bröd") +}) + +test("Markdown shortcuts, subpages, move and archive", async ({ page }) => { + const parent = unique("Home appliances") + await newPage(page, parent) + const editor = page.getByTestId("editor") + await editor.click() + await page.keyboard.type("## Kitchen") + await page.keyboard.press("Enter") + await page.keyboard.type("- Dishwasher: **Bosch** SMS4") + await expect(editor.locator("h2")).toHaveText("Kitchen") + await expect(editor.locator("ul li strong")).toHaveText("Bosch") + + await page.getByRole("button", { name: "Page actions" }).click() + await page.getByRole("menuitem", { name: "Add subpage" }).click() + const child = unique("Dishwasher manual") + await page.getByLabel("Page title").fill(child) + await expect(page.getByRole("navigation", { name: "Breadcrumb" })).toContainText(parent) + + await page.goto("/pages") + const tree = page.getByTestId("page-tree") + await expect( + tree.locator("li", { hasText: parent }).getByRole("link", { name: child }), + ).toBeVisible() + + // Move the child to the top level, then archive it. + await tree.getByRole("link", { name: child }).click() + await page.getByRole("button", { name: "Page actions" }).click() + await page.getByRole("menuitem", { name: "Move…" }).click() + await page.getByLabel(/Move “/).selectOption({ label: "Top level" }) + await page.getByRole("button", { name: "Move", exact: true }).click() + await expect(page.getByRole("navigation", { name: "Breadcrumb" })).toHaveCount(0) + + await page.getByRole("button", { name: "Page actions" }).click() + await page.getByRole("menuitem", { name: "Archive" }).click() + await expect(page).toHaveURL(/\/pages$/) + await expect(page.getByTestId("page-tree").getByRole("link", { name: child })).toHaveCount(0) + await page.getByRole("button", { name: /Show archived/ }).click() + await expect(page.getByRole("link", { name: child })).toBeVisible() +}) + +test("photos inline and file attachments", async ({ page }) => { + await newPage(page, unique("Warranty")) + await page.getByTestId("editor").click() + await page.getByTestId("photo-input").setInputFiles(path.resolve("public/apple-touch-icon.png")) + const img = page.getByTestId("editor").locator("img") + await expect(img).toBeVisible() + await expect(img).toHaveJSProperty("complete", true) + expect(await img.evaluate((el: HTMLImageElement) => el.naturalWidth)).toBeGreaterThan(0) + + await page.getByTestId("file-input").setInputFiles({ + name: "Bosch manual.pdf", + mimeType: "application/pdf", + buffer: Buffer.from("%PDF-1.4 test"), + }) + const chip = page.getByTestId("editor").locator("a[data-file-attachment]") + await expect(chip).toContainText("Bosch manual.pdf") + const download = await (await page.request.get((await chip.getAttribute("href"))!)).text() + expect(download).toBe("%PDF-1.4 test") +}) + +test("search finds words inside pages, including parts of Swedish compound words", async ({ + page, +}) => { + const title = unique("Cleaning") + await newPage(page, title) + await page.getByTestId("editor").click() + const word = `Tvättmaskinsrengöring${Math.random().toString(36).slice(2, 6)}` + await page.keyboard.type(`Use ${word} monthly`) + await waitForSynced(page) + + await page.getByRole("link", { name: "Search" }).click() + // The server indexes after a short debounce. + await expect(async () => { + await page.getByLabel("Search").fill("") + await page.getByLabel("Search").fill(word.slice(4, 14).replace("ö", "o")) + await expect( + page.getByTestId("search-results").getByRole("link", { name: new RegExp(title) }), + ).toBeVisible({ + timeout: 2000, + }) + }).toPass({ timeout: 20_000 }) + await expect(page.getByTestId("search-results").locator("mark").first()).toBeVisible() +}) + +test("two people edit the same page live", async ({ page, browser }, info) => { + const title = unique("Packing list") + const url = await newPage(page, title) + await page.getByTestId("editor").click() + await page.keyboard.type("[ ] Passports") + await waitForSynced(page) + + const alex = await signedInPage(browser, "alex", info.project.name) + await alex.page.goto(url) + const alexEditor = alex.page.getByTestId("editor") + await expect(alexEditor).toContainText("Passports") + + await alexEditor.locator("li", { hasText: "Passports" }).click() + await alex.page.keyboard.press("End") + await alex.page.keyboard.press("Enter") + await alex.page.keyboard.type("Chargers") + await expect(page.getByTestId("editor")).toContainText("Chargers") + // Sara sees Alex's cursor. + await expect(page.locator(".collaboration-carets__label", { hasText: "Alex" })).toBeVisible() + // And the title edit reaches Alex too. + await page.getByLabel("Page title").fill(`${title} (Italy)`) + await expect(alex.page.getByLabel("Page title")).toHaveValue(`${title} (Italy)`) + await alex.context.close() +}) + +test("edits made offline sync when back online", async ({ page, context, browser }, info) => { + const title = unique("Offline list") + const url = await newPage(page, title) + await page.getByTestId("editor").click() + await page.keyboard.type("[ ] Coffee") + await waitForSynced(page) + await page.waitForFunction(() => navigator.serviceWorker.controller !== null) + + await context.setOffline(true) + await expect(page.getByTestId("sync-status")).toHaveAttribute("data-state", "offline") + // The app still opens offline from the cached shell and local data. + await page.reload() + await expect(page.getByTestId("editor")).toContainText("Coffee") + await page.getByTestId("editor").locator("li", { hasText: "Coffee" }).click() + await page.keyboard.press("End") + await page.keyboard.press("Enter") + await page.keyboard.type("Oat milk") + await expect(page.getByTestId("sync-status")).toContainText("Offline") + + await context.setOffline(false) + await waitForSynced(page) + + const alex = await signedInPage(browser, "alex", info.project.name) + await alex.page.goto(url) + await expect(alex.page.getByTestId("editor")).toContainText("Oat milk") + await alex.context.close() +}) + +test("export contains the pages as Markdown", async ({ page }) => { + const title = unique("Export check") + await newPage(page, title) + const editor = page.getByTestId("editor") + await editor.click() + await page.keyboard.type("## Week") + await page.keyboard.press("Enter") + await page.keyboard.type("[ ] Mjölk") + await page.keyboard.press("Enter") + await page.keyboard.type("Ost") + await editor + .locator('ul[data-type="taskList"] > li') + .nth(1) + .locator('input[type="checkbox"]') + .check() + await page.keyboard.press("Enter") + await page.keyboard.press("Enter") + await page.keyboard.type("Buy at ") + await page.keyboard.press("ControlOrMeta+b") + await page.keyboard.type("ICA") + await waitForSynced(page) + + const res = await page.request.get("/api/export") + expect(res.headers()["content-type"]).toBe("application/zip") + const files = unzipSync(new Uint8Array(await res.body())) + const md = new TextDecoder().decode(files[`${title}.md`]) + expect(md).toBe(`# ${title}\n\n## Week\n\n- [ ] Mjölk\n- [x] Ost\n\nBuy at **ICA**\n`) +}) diff --git a/src/frontend/e2e/smoke.spec.ts b/src/frontend/e2e/smoke.spec.ts new file mode 100644 index 0000000..824e2da --- /dev/null +++ b/src/frontend/e2e/smoke.spec.ts @@ -0,0 +1,49 @@ +import { expect, test } from "@playwright/test" +import { STATE } from "./helpers" + +test.describe("signed out", () => { + test("shows the sign-in screen and the manifest", async ({ page, request }) => { + await page.goto("/") + await expect(page.getByRole("heading", { name: "Sign in to cnotes" })).toBeVisible() + const manifest = await (await request.get("/manifest.webmanifest")).json() + expect(manifest).toMatchObject({ name: "cnotes", display: "standalone", start_url: "/" }) + }) + + test("rejects a wrong password", async ({ page }) => { + await page.goto("/") + await page.getByLabel("Username").fill("sara") + await page.getByLabel("Password").fill("not the password") + await page.getByRole("button", { name: "Continue" }).click() + await expect(page.getByRole("alert")).toHaveText("Wrong username or password") + }) +}) + +test.describe("signed in", () => { + test.use({ storageState: STATE.sara }) + + test("home loads without errors and navigation works", async ({ page }) => { + const errors: string[] = [] + page.on("console", (msg) => { + if (msg.type() === "error") errors.push(msg.text()) + }) + page.on("pageerror", (err) => errors.push(err.message)) + + await page.goto("/") + await expect(page.getByRole("heading", { name: "Pinned" })).toBeVisible() + await expect(page.getByTestId("sync-status")).toHaveAttribute("data-state", "synced") + + await page.getByRole("link", { name: "Settings" }).click() + await expect(page.getByText("Signed in as Sara (sara)")).toBeVisible() + await page.getByRole("link", { name: "About cnotes" }).click() + await expect(page.getByRole("link", { name: "Source code" })).toHaveAttribute( + "href", + "https://github.com/cedernaes/cnotes", + ) + + // Deep link straight into a route. + await page.goto("/pages") + await expect(page.getByRole("heading", { name: "Pages" })).toBeVisible() + // CSP violations, hydration errors and failed requests show up here. + expect(errors).toEqual([]) + }) +}) diff --git a/apps/web/package.json b/src/frontend/package.json similarity index 97% rename from apps/web/package.json rename to src/frontend/package.json index 4128d90..fc4babb 100644 --- a/apps/web/package.json +++ b/src/frontend/package.json @@ -1,5 +1,5 @@ { - "name": "@cnotes/web", + "name": "@cnotes/frontend", "version": "0.0.0", "private": true, "license": "AGPL-3.0-or-later", diff --git a/src/frontend/playwright.config.ts b/src/frontend/playwright.config.ts new file mode 100644 index 0000000..526ae06 --- /dev/null +++ b/src/frontend/playwright.config.ts @@ -0,0 +1,35 @@ +import { defineConfig, devices } from "@playwright/test" + +export const PORT = 3100 +export const SETUP_TOKEN = "e2e-setup-token" + +export default defineConfig({ + testDir: "e2e", + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + reporter: process.env.CI ? "github" : "list", + globalSetup: "./e2e/global-setup.ts", + use: { + baseURL: `http://localhost:${PORT}`, + trace: "off", + }, + projects: [ + { name: "iphone", use: { ...devices["iPhone 15"], browserName: "chromium" } }, + { name: "android", use: { ...devices["Pixel 7"] } }, + ], + // Runs the production server against the built web app (`pnpm build` first), + // with a fresh data folder each run. + webServer: { + command: "rm -rf test-results/e2e-data && node ../backend/dist/index.js", + url: `http://localhost:${PORT}/api/health`, + reuseExistingServer: false, + env: { + PORT: String(PORT), + WEB_ROOT: "dist/client", + DATA_DIR: "test-results/e2e-data", + CNOTES_SETUP_TOKEN: SETUP_TOKEN, + LOG_LEVEL: "warn", + }, + }, +}) diff --git a/apps/web/public/apple-touch-icon.png b/src/frontend/public/apple-touch-icon.png similarity index 100% rename from apps/web/public/apple-touch-icon.png rename to src/frontend/public/apple-touch-icon.png diff --git a/apps/web/public/icon-maskable.svg b/src/frontend/public/icon-maskable.svg similarity index 100% rename from apps/web/public/icon-maskable.svg rename to src/frontend/public/icon-maskable.svg diff --git a/apps/web/public/icon.svg b/src/frontend/public/icon.svg similarity index 100% rename from apps/web/public/icon.svg rename to src/frontend/public/icon.svg diff --git a/apps/web/public/manifest.webmanifest b/src/frontend/public/manifest.webmanifest similarity index 90% rename from apps/web/public/manifest.webmanifest rename to src/frontend/public/manifest.webmanifest index a3fe1da..49585c9 100644 --- a/apps/web/public/manifest.webmanifest +++ b/src/frontend/public/manifest.webmanifest @@ -1,6 +1,6 @@ { - "name": "Cnotes", - "short_name": "Cnotes", + "name": "cnotes", + "short_name": "cnotes", "description": "Household notes and lists", "theme_color": "#1c1917", "background_color": "#fafaf9", diff --git a/apps/web/scripts/generate-sw.js b/src/frontend/scripts/generate-sw.js similarity index 74% rename from apps/web/scripts/generate-sw.js rename to src/frontend/scripts/generate-sw.js index 4a7ca1b..c2c929d 100644 --- a/apps/web/scripts/generate-sw.js +++ b/src/frontend/scripts/generate-sw.js @@ -1,16 +1,15 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Generates the service worker after `vite build`, once TanStack Start has // prerendered the SPA shell (_shell.html), so the shell is precached too. -import { generateSW } from 'workbox-build' +import { generateSW } from "workbox-build" const { count, size, warnings } = await generateSW({ - globDirectory: 'dist/client', - globPatterns: ['**/*.{js,css,html,svg,png,webmanifest}'], - swDest: 'dist/client/sw.js', + globDirectory: "dist/client", + globPatterns: ["**/*.{js,css,html,svg,png,webmanifest}"], + swDest: "dist/client/sw.js", // Hashed file names already bust caches. dontCacheBustURLsMatching: /^assets\//, // Any app route opens the cached shell when offline. - navigateFallback: '/_shell.html', + navigateFallback: "/_shell.html", navigateFallbackDenylist: [/^\/api\//, /^\/sync/], // New versions wait until the user taps "Reload" (see UpdatePrompt). skipWaiting: false, @@ -19,10 +18,10 @@ const { count, size, warnings } = await generateSW({ // Photos and files: once viewed, available offline. They never change. runtimeCaching: [ { - urlPattern: ({ url, sameOrigin }) => sameOrigin && url.pathname.startsWith('/api/files/'), - handler: 'CacheFirst', + urlPattern: ({ url, sameOrigin }) => sameOrigin && url.pathname.startsWith("/api/files/"), + handler: "CacheFirst", options: { - cacheName: 'cnotes-files', + cacheName: "cnotes-files", expiration: { maxEntries: 500, purgeOnQuotaError: true }, cacheableResponse: { statuses: [200] }, }, diff --git a/apps/web/src/components/AuthScreens.tsx b/src/frontend/src/components/AuthScreens.tsx similarity index 78% rename from apps/web/src/components/AuthScreens.tsx rename to src/frontend/src/components/AuthScreens.tsx index bb8df97..5ddbf2f 100644 --- a/apps/web/src/components/AuthScreens.tsx +++ b/src/frontend/src/components/AuthScreens.tsx @@ -1,10 +1,9 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { APP_NAME, type LoginResponse, type PublicUser, type SessionResponse } from '@cnotes/shared' -import QRCode from 'qrcode' -import { useEffect, useState, type FormEvent, type ReactNode } from 'react' -import { api } from '../lib/api' -import { useAuth } from '../lib/auth' -import { Button, Card, ErrorText, Field } from './ui' +import { APP_NAME, type LoginResponse, type PublicUser, type SessionResponse } from "@cnotes/shared" +import QRCode from "qrcode" +import { useEffect, useState, type FormEvent, type ReactNode } from "react" +import { api } from "../lib/api" +import { useAuth } from "../lib/auth" +import { Button, Card, ErrorText, Field } from "./ui" function Shell({ title, children }: { title: string; children: ReactNode }) { return ( @@ -20,14 +19,14 @@ function Shell({ title, children }: { title: string; children: ReactNode }) { function useSubmit() { const [busy, setBusy] = useState(false) - const [error, setError] = useState('') + const [error, setError] = useState("") const run = async (fn: () => Promise) => { setBusy(true) - setError('') + setError("") try { await fn() } catch (err) { - setError(err instanceof Error ? err.message : 'Something went wrong') + setError(err instanceof Error ? err.message : "Something went wrong") } finally { setBusy(false) } @@ -44,13 +43,13 @@ export function SetupScreen({ tokenRequired }: { tokenRequired: boolean }) { const onSubmit = (e: FormEvent) => { e.preventDefault() const f = new FormData(e.currentTarget) - const password = String(f.get('password')) - const username = String(f.get('username')).trim() + const password = String(f.get("password")) + const username = String(f.get("username")).trim() void run(async () => { - await api('/auth/setup', { - method: 'POST', + await api("/auth/setup", { + method: "POST", json: { - ...(tokenRequired ? { setupToken: String(f.get('setupToken')).trim() } : {}), + ...(tokenRequired ? { setupToken: String(f.get("setupToken")).trim() } : {}), username, password, }, @@ -71,7 +70,7 @@ export function SetupScreen({ tokenRequired }: { tokenRequired: boolean }) { name="setupToken" required autoComplete="off" - hint="Printed in the server log when Cnotes starts (docker compose logs cnotes)." + hint="Printed in the server log when cnotes starts (docker compose logs cnotes)." /> )} ({ kind: 'password' }) + const [step, setStep] = useState({ kind: "password" }) const { busy, error, run } = useSubmit() const startLogin = (username: string, password: string) => run(async () => { - const res = await api('/auth/login', { - method: 'POST', + const res = await api("/auth/login", { + method: "POST", json: { username, password }, }) - if (res.step === 'done') signedIn(res.user) - else if (res.step === 'totp') setStep({ kind: 'totp', challenge: res.challenge }) - else setStep({ kind: 'enroll', ...res }) + if (res.step === "done") signedIn(res.user) + else if (res.step === "totp") setStep({ kind: "totp", challenge: res.challenge }) + else setStep({ kind: "enroll", ...res }) }) useEffect(() => { @@ -125,11 +124,11 @@ export function LoginScreen({ initial }: { initial?: { username: string; passwor // eslint-disable-next-line react-hooks/exhaustive-deps }, []) - if (step.kind === 'password') { + if (step.kind === "password") { const onSubmit = (e: FormEvent) => { e.preventDefault() const f = new FormData(e.currentTarget) - void startLogin(String(f.get('username')).trim(), String(f.get('password'))) + void startLogin(String(f.get("username")).trim(), String(f.get("password"))) } return ( @@ -157,13 +156,13 @@ export function LoginScreen({ initial }: { initial?: { username: string; passwor ) } - if (step.kind === 'totp') { + if (step.kind === "totp") { const onSubmit = (e: FormEvent) => { e.preventDefault() - const code = String(new FormData(e.currentTarget).get('code')) + const code = String(new FormData(e.currentTarget).get("code")) void run(async () => { - const res = await api('/auth/verify', { - method: 'POST', + const res = await api("/auth/verify", { + method: "POST", json: { challenge: step.challenge, code }, }) signedIn(res.user) @@ -189,7 +188,7 @@ export function LoginScreen({ initial }: { initial?: { username: string; passwor type="button" variant="ghost" className="w-full" - onClick={() => setStep({ kind: 'password' })} + onClick={() => setStep({ kind: "password" })} > Back @@ -198,7 +197,7 @@ export function LoginScreen({ initial }: { initial?: { username: string; passwor ) } - if (step.kind === 'enroll') { + if (step.kind === "enroll") { return ( run(async () => { - const res = await api('/auth/enroll', { - method: 'POST', + const res = await api("/auth/enroll", { + method: "POST", json: { challenge: step.challenge, code }, }) - setStep({ kind: 'recovery', user: res.user, codes: res.recoveryCodes ?? [] }) + setStep({ kind: "recovery", user: res.user, codes: res.recoveryCodes ?? [] }) }) } /> @@ -231,7 +230,7 @@ function Enroll({ error: string onSubmit: (code: string) => void }) { - const [qr, setQr] = useState('') + const [qr, setQr] = useState("") useEffect(() => { void QRCode.toDataURL(step.otpauthUrl, { margin: 1, width: 220 }).then(setQr) }, [step.otpauthUrl]) @@ -240,7 +239,7 @@ function Enroll({

- Cnotes asks for a code from an authenticator app (for example Google Authenticator, + cnotes asks for a code from an authenticator app (for example Google Authenticator, Microsoft Authenticator, 1Password or the iPhone Passwords app) each time you sign in on a new device.

@@ -263,7 +262,7 @@ function Enroll({
{ e.preventDefault() - onSubmit(String(new FormData(e.currentTarget).get('code'))) + onSubmit(String(new FormData(e.currentTarget).get("code"))) }} className="space-y-4" > @@ -304,10 +303,10 @@ function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void diff --git a/apps/web/src/components/Editor.tsx b/src/frontend/src/components/Editor.tsx similarity index 81% rename from apps/web/src/components/Editor.tsx rename to src/frontend/src/components/Editor.tsx index d46f81b..ce2c021 100644 --- a/apps/web/src/components/Editor.tsx +++ b/src/frontend/src/components/Editor.tsx @@ -1,14 +1,13 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { CONTENT_FIELD, countTasks, FILE_URL_PREFIX, type Attachment } from '@cnotes/shared' -import type { Editor as TiptapEditor } from '@tiptap/core' -import { EditorContent, useEditor, useEditorState } from '@tiptap/react' -import { useEffect, useRef, useState, type ReactNode } from 'react' -import { ApiError } from '../lib/api' -import { userColor } from '../lib/ids' -import type { DocHandle } from '../lib/sync' -import { touchPage, updatePage } from '../lib/workspace' -import { editorExtensions, looksLikeMarkdown } from './editorExtensions' -import { ErrorText } from './ui' +import { CONTENT_FIELD, countTasks, FILE_URL_PREFIX, type Attachment } from "@cnotes/shared" +import type { Editor as TiptapEditor } from "@tiptap/core" +import { EditorContent, useEditor, useEditorState } from "@tiptap/react" +import { useEffect, useRef, useState, type ReactNode } from "react" +import { ApiError } from "../lib/api" +import { userColor } from "../lib/ids" +import type { DocHandle } from "../lib/sync" +import { touchPage, updatePage } from "../lib/workspace" +import { editorExtensions, looksLikeMarkdown } from "./editorExtensions" +import { ErrorText } from "./ui" interface Props { handle: DocHandle @@ -21,7 +20,7 @@ interface Props { export function clearCheckedItems(editor: TiptapEditor): number { const ranges: { from: number; to: number }[] = [] editor.state.doc.descendants((node, pos) => { - if (node.type.name === 'taskItem' && node.attrs.checked) { + if (node.type.name === "taskItem" && node.attrs.checked) { ranges.push({ from: pos, to: pos + node.nodeSize }) return false } @@ -33,7 +32,7 @@ export function clearCheckedItems(editor: TiptapEditor): number { const $from = tr.doc.resolve(r.from) const list = $from.parent // Removing the only item would leave an invalid empty list: remove the list. - if (list.type.name === 'taskList' && list.childCount === 1) { + if (list.type.name === "taskList" && list.childCount === 1) { tr.delete($from.before(), $from.after()) } else { tr.delete(r.from, r.to) @@ -45,18 +44,18 @@ export function clearCheckedItems(editor: TiptapEditor): number { async function upload(pageId: string, file: File): Promise { const body = new FormData() - body.append('file', file) + body.append("file", file) const res = await fetch(`/api/files?pageId=${encodeURIComponent(pageId)}`, { - method: 'POST', + method: "POST", body, }) const json = (await res.json().catch(() => ({}))) as Attachment & { error?: string } - if (!res.ok) throw new ApiError(json.error ?? 'Upload failed', res.status) + if (!res.ok) throw new ApiError(json.error ?? "Upload failed", res.status) return json } export function Editor({ handle, pageId, user, autoFocus }: Props) { - const [error, setError] = useState('') + const [error, setError] = useState("") const [uploading, setUploading] = useState(0) const photoInput = useRef(null) const fileInput = useRef(null) @@ -64,9 +63,9 @@ export function Editor({ handle, pageId, user, autoFocus }: Props) { const editor = useEditor( { extensions: editorExtensions(handle, { name: user.displayName, color: userColor(user.id) }), - autofocus: autoFocus ? 'end' : false, + autofocus: autoFocus ? "end" : false, editorProps: { - attributes: { class: 'cnotes-editor', 'data-testid': 'editor', spellcheck: 'true' }, + attributes: { class: "cnotes-editor", "data-testid": "editor", spellcheck: "true" }, handlePaste(view, event) { const data = event.clipboardData if (!data) return false @@ -75,9 +74,9 @@ export function Editor({ handle, pageId, user, autoFocus }: Props) { void insertFiles(files) return true } - const text = data.getData('text/plain') + const text = data.getData("text/plain") if ( - !data.getData('text/html') && + !data.getData("text/html") && text && looksLikeMarkdown(text) && editorRef.current?.markdown @@ -105,10 +104,10 @@ export function Editor({ handle, pageId, user, autoFocus }: Props) { const state = useEditorState({ editor, selector: ({ editor: e }) => ({ - taskList: e?.isActive('taskList') ?? false, - bulletList: e?.isActive('bulletList') ?? false, - heading: e?.isActive('heading', { level: 2 }) ?? false, - bold: e?.isActive('bold') ?? false, + taskList: e?.isActive("taskList") ?? false, + bulletList: e?.isActive("bulletList") ?? false, + heading: e?.isActive("heading", { level: 2 }) ?? false, + bold: e?.isActive("bold") ?? false, }), }) @@ -133,19 +132,19 @@ export function Editor({ handle, pageId, user, autoFocus }: Props) { } } recount() - handle.doc.on('update', onUpdate) + handle.doc.on("update", onUpdate) return () => { // Don't lose a pending count when leaving the page right after typing. if (timer) { clearTimeout(timer) recount() } - handle.doc.off('update', onUpdate) + handle.doc.off("update", onUpdate) } }, [handle, pageId, user.id]) async function insertFiles(files: File[]) { - setError('') + setError("") for (const file of files) { setUploading((n) => n + 1) try { @@ -156,17 +155,17 @@ export function Editor({ handle, pageId, user, autoFocus }: Props) { else chain .insertContent({ - type: 'fileAttachment', + type: "fileAttachment", attrs: { id: a.id, filename: a.filename, size: a.size, mime: a.mime }, }) .run() } catch (err) { setError( err instanceof TypeError - ? 'Photos and files need a connection to the server. Try again when you are online.' + ? "Photos and files need a connection to the server. Try again when you are online." : err instanceof Error ? err.message - : 'Upload failed', + : "Upload failed", ) } finally { setUploading((n) => n - 1) @@ -232,7 +231,7 @@ export function Editor({ handle, pageId, user, autoFocus }: Props) { data-testid="photo-input" onChange={(e) => { void insertFiles([...(e.target.files ?? [])]) - e.target.value = '' + e.target.value = "" }} /> { void insertFiles([...(e.target.files ?? [])]) - e.target.value = '' + e.target.value = "" }} /> {uploading > 0 &&

Uploading…

} @@ -272,7 +271,7 @@ function Tool({ aria-pressed={active} onMouseDown={(e) => e.preventDefault()} onClick={onClick} - className={`flex h-10 w-9 shrink-0 items-center justify-center rounded-lg ${active ? 'bg-stone-200 dark:bg-stone-700' : 'hover:bg-stone-200 dark:hover:bg-stone-800'}`} + className={`flex h-10 w-9 shrink-0 items-center justify-center rounded-lg ${active ? "bg-stone-200 dark:bg-stone-700" : "hover:bg-stone-200 dark:hover:bg-stone-800"}`} > ): string { - return p.title.trim() || 'Untitled' +export function pageTitle(p: Pick): string { + return p.title.trim() || "Untitled" } export function OpenTasks({ count }: { count: number }) { @@ -26,7 +25,7 @@ export function PageRow({ page, extra }: { page: PageMeta; extra?: ReactNode }) params={{ pageId: page.id }} className="flex min-h-12 items-center gap-2 rounded-lg px-3 hover:bg-stone-100 dark:hover:bg-stone-800" > - {pageTitle(page)} + {pageTitle(page)} {extra} diff --git a/apps/web/src/components/SyncIndicator.tsx b/src/frontend/src/components/SyncIndicator.tsx similarity index 50% rename from apps/web/src/components/SyncIndicator.tsx rename to src/frontend/src/components/SyncIndicator.tsx index 2407ded..b8303a3 100644 --- a/apps/web/src/components/SyncIndicator.tsx +++ b/src/frontend/src/components/SyncIndicator.tsx @@ -1,17 +1,16 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { useEffect, useState } from 'react' -import { useSyncStatus } from '../lib/workspace' +import { useEffect, useState } from "react" +import { useSyncStatus } from "../lib/workspace" function useOnline() { const [online, setOnline] = useState(() => navigator.onLine) useEffect(() => { const on = () => setOnline(true) const off = () => setOnline(false) - window.addEventListener('online', on) - window.addEventListener('offline', off) + window.addEventListener("online", on) + window.addEventListener("offline", off) return () => { - window.removeEventListener('online', on) - window.removeEventListener('offline', off) + window.removeEventListener("online", on) + window.removeEventListener("offline", off) } }, []) return online @@ -20,16 +19,16 @@ function useOnline() { export function SyncIndicator() { const { connection, unsynced } = useSyncStatus() const online = useOnline() - const connected = online && connection === 'connected' + const connected = online && connection === "connected" const [label, color] = !connected - ? [unsynced > 0 ? 'Offline · saved on this device' : 'Offline', 'bg-stone-400'] + ? [unsynced > 0 ? "Offline · saved on this device" : "Offline", "bg-stone-400"] : unsynced > 0 - ? ['Saving…', 'bg-amber-500'] - : ['Synced', 'bg-emerald-500'] + ? ["Saving…", "bg-amber-500"] + : ["Synced", "bg-emerald-500"] return ( diff --git a/apps/web/src/components/UpdatePrompt.tsx b/src/frontend/src/components/UpdatePrompt.tsx similarity index 75% rename from apps/web/src/components/UpdatePrompt.tsx rename to src/frontend/src/components/UpdatePrompt.tsx index 8fa4788..8446786 100644 --- a/apps/web/src/components/UpdatePrompt.tsx +++ b/src/frontend/src/components/UpdatePrompt.tsx @@ -1,6 +1,5 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { useEffect, useRef, useState } from 'react' -import type { Workbox } from 'workbox-window' +import { useEffect, useRef, useState } from "react" +import type { Workbox } from "workbox-window" /** Registers the service worker and offers a reload when a new version is ready. */ export function UpdatePrompt() { @@ -8,14 +7,14 @@ export function UpdatePrompt() { const [waiting, setWaiting] = useState(false) useEffect(() => { - if (import.meta.env.DEV || !('serviceWorker' in navigator)) return + if (import.meta.env.DEV || !("serviceWorker" in navigator)) return let cancelled = false - void import('workbox-window').then(({ Workbox }) => { + void import("workbox-window").then(({ Workbox }) => { if (cancelled) return - const wb = new Workbox('/sw.js') - wb.addEventListener('waiting', () => setWaiting(true)) + const wb = new Workbox("/sw.js") + wb.addEventListener("waiting", () => setWaiting(true)) // Reload only when an update takes over, not on the very first install. - wb.addEventListener('controlling', (event) => { + wb.addEventListener("controlling", (event) => { if (event.isUpdate) window.location.reload() }) wbRef.current = wb diff --git a/apps/web/src/components/editorExtensions.ts b/src/frontend/src/components/editorExtensions.ts similarity index 62% rename from apps/web/src/components/editorExtensions.ts rename to src/frontend/src/components/editorExtensions.ts index e22be2e..4ab62b2 100644 --- a/apps/web/src/components/editorExtensions.ts +++ b/src/frontend/src/components/editorExtensions.ts @@ -1,45 +1,44 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { CONTENT_FIELD, FILE_URL_PREFIX } from '@cnotes/shared' -import { mergeAttributes, Node } from '@tiptap/core' -import Collaboration from '@tiptap/extension-collaboration' -import CollaborationCaret from '@tiptap/extension-collaboration-caret' -import Image from '@tiptap/extension-image' -import { TaskItem, TaskList } from '@tiptap/extension-list' -import { Placeholder } from '@tiptap/extensions' -import { Markdown } from '@tiptap/markdown' -import StarterKit from '@tiptap/starter-kit' -import type { DocHandle } from '../lib/sync' -import { formatBytes } from './ui' +import { CONTENT_FIELD, FILE_URL_PREFIX } from "@cnotes/shared" +import { mergeAttributes, Node } from "@tiptap/core" +import Collaboration from "@tiptap/extension-collaboration" +import CollaborationCaret from "@tiptap/extension-collaboration-caret" +import Image from "@tiptap/extension-image" +import { TaskItem, TaskList } from "@tiptap/extension-list" +import { Placeholder } from "@tiptap/extensions" +import { Markdown } from "@tiptap/markdown" +import StarterKit from "@tiptap/starter-kit" +import type { DocHandle } from "../lib/sync" +import { formatBytes } from "./ui" /** A downloadable file (PDF manual, receipt…) shown as a chip in the text. */ export const FileAttachment = Node.create({ - name: 'fileAttachment', - group: 'block', + name: "fileAttachment", + group: "block", atom: true, draggable: true, addAttributes() { return { id: { default: null }, - filename: { default: 'file' }, + filename: { default: "file" }, size: { default: 0 }, - mime: { default: 'application/octet-stream' }, + mime: { default: "application/octet-stream" }, } }, parseHTML() { - return [{ tag: 'a[data-file-attachment]' }] + return [{ tag: "a[data-file-attachment]" }] }, renderHTML({ node, HTMLAttributes }) { const { id, filename, size } = node.attrs as { id: string; filename: string; size: number } return [ - 'a', + "a", mergeAttributes(HTMLAttributes, { - 'data-file-attachment': '', + "data-file-attachment": "", href: `${FILE_URL_PREFIX}${id}`, download: filename, - class: 'file-chip', - contenteditable: 'false', + class: "file-chip", + contenteditable: "false", }), - `📎 ${filename}${size ? ` · ${formatBytes(size)}` : ''}`, + `📎 ${filename}${size ? ` · ${formatBytes(size)}` : ""}`, ] }, }) @@ -49,7 +48,7 @@ export function editorExtensions(handle: DocHandle, user: { name: string; color: StarterKit.configure({ // Undo history comes from Yjs (Collaboration), so each person undoes only their own edits. undoRedo: false, - link: { openOnClick: true, autolink: true, defaultProtocol: 'https' }, + link: { openOnClick: true, autolink: true, defaultProtocol: "https" }, heading: { levels: [1, 2, 3] }, }), TaskList, diff --git a/apps/web/src/components/ui.tsx b/src/frontend/src/components/ui.tsx similarity index 74% rename from apps/web/src/components/ui.tsx rename to src/frontend/src/components/ui.tsx index d5338c7..3e6b309 100644 --- a/apps/web/src/components/ui.tsx +++ b/src/frontend/src/components/ui.tsx @@ -1,20 +1,19 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode } from 'react' +import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode } from "react" export function Button({ - variant = 'primary', - className = '', + variant = "primary", + className = "", ...props }: ButtonHTMLAttributes & { - variant?: 'primary' | 'secondary' | 'danger' | 'ghost' + variant?: "primary" | "secondary" | "danger" | "ghost" }) { const styles = { primary: - 'bg-stone-900 text-white hover:bg-stone-700 dark:bg-stone-100 dark:text-stone-900 dark:hover:bg-white', + "bg-stone-900 text-white hover:bg-stone-700 dark:bg-stone-100 dark:text-stone-900 dark:hover:bg-white", secondary: - 'border border-stone-300 bg-white hover:bg-stone-100 dark:border-stone-600 dark:bg-stone-800 dark:hover:bg-stone-700', - danger: 'bg-red-700 text-white hover:bg-red-600', - ghost: 'hover:bg-stone-200 dark:hover:bg-stone-800', + "border border-stone-300 bg-white hover:bg-stone-100 dark:border-stone-600 dark:bg-stone-800 dark:hover:bg-stone-700", + danger: "bg-red-700 text-white hover:bg-red-600", + ghost: "hover:bg-stone-200 dark:hover:bg-stone-800", }[variant] return ( {showArchived && (
diff --git a/apps/web/src/routes/search.tsx b/src/frontend/src/routes/search.tsx similarity index 85% rename from apps/web/src/routes/search.tsx rename to src/frontend/src/routes/search.tsx index 44b2d4c..09bd28a 100644 --- a/apps/web/src/routes/search.tsx +++ b/src/frontend/src/routes/search.tsx @@ -1,14 +1,13 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import type { SearchHit, SearchResponse } from '@cnotes/shared' -import { createFileRoute, Link } from '@tanstack/react-router' -import { useEffect, useMemo, useState } from 'react' -import { pageTitle } from '../components/PageLink' -import { api } from '../lib/api' -import { usePages } from '../lib/workspace' +import type { SearchHit, SearchResponse } from "@cnotes/shared" +import { createFileRoute, Link } from "@tanstack/react-router" +import { useEffect, useMemo, useState } from "react" +import { pageTitle } from "../components/PageLink" +import { api } from "../lib/api" +import { usePages } from "../lib/workspace" -export const Route = createFileRoute('/search')({ +export const Route = createFileRoute("/search")({ validateSearch: (s: Record): { q?: string } => - typeof s.q === 'string' ? { q: s.q } : {}, + typeof s.q === "string" ? { q: s.q } : {}, component: Search, }) @@ -21,14 +20,14 @@ function Snippet({ text }: { text: string }) { let last = 0 for (const m of text.matchAll(HL)) { parts.push(text.slice(last, m.index)) - parts.push({ mark: m[1] ?? '' }) + parts.push({ mark: m[1] ?? "" }) last = m.index! + m[0].length } parts.push(text.slice(last)) return ( {parts.map((p, i) => - typeof p === 'string' ? ( + typeof p === "string" ? ( p ) : ( @@ -41,11 +40,11 @@ function Snippet({ text }: { text: string }) { } function fold(s: string): string { - return s.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase() + return s.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase() } function Search() { - const { q: initial = '' } = Route.useSearch() + const { q: initial = "" } = Route.useSearch() const navigate = Route.useNavigate() const [q, setQ] = useState(initial) const [hits, setHits] = useState(null) diff --git a/apps/web/src/routes/settings.tsx b/src/frontend/src/routes/settings.tsx similarity index 85% rename from apps/web/src/routes/settings.tsx rename to src/frontend/src/routes/settings.tsx index 8521d17..8e1475a 100644 --- a/apps/web/src/routes/settings.tsx +++ b/src/frontend/src/routes/settings.tsx @@ -1,12 +1,11 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later -import { DEFAULT_SOURCE_URL, type PublicUser, type SessionInfo } from '@cnotes/shared' -import { createFileRoute, Link } from '@tanstack/react-router' -import { useCallback, useEffect, useState, type FormEvent } from 'react' -import { Button, Card, ErrorText, Field, formatRelative, SectionTitle } from '../components/ui' -import { api } from '../lib/api' -import { useAuth, useUser } from '../lib/auth' +import { DEFAULT_SOURCE_URL, type PublicUser, type SessionInfo } from "@cnotes/shared" +import { createFileRoute, Link } from "@tanstack/react-router" +import { useCallback, useEffect, useState, type FormEvent } from "react" +import { Button, Card, ErrorText, Field, formatRelative, SectionTitle } from "../components/ui" +import { api } from "../lib/api" +import { useAuth, useUser } from "../lib/auth" -export const Route = createFileRoute('/settings')({ +export const Route = createFileRoute("/settings")({ component: Settings, }) @@ -42,9 +41,9 @@ function Settings() { About

- About Cnotes - {' '} - ·{' '} + About cnotes + {" "} + ·{" "} Source code @@ -59,34 +58,34 @@ function Settings() { function useOnlineData(path: string) { const [data, setData] = useState(null) - const [error, setError] = useState('') + const [error, setError] = useState("") const reload = useCallback(() => { api(path) .then((d) => { setData(d) - setError('') + setError("") }) - .catch(() => setError('Needs a connection to the server.')) + .catch(() => setError("Needs a connection to the server.")) }, [path]) useEffect(reload, [reload]) return { data, error, reload } } function Members() { - const { data: users, error, reload } = useOnlineData('/auth/users') + const { data: users, error, reload } = useOnlineData("/auth/users") const [adding, setAdding] = useState(false) - const [formError, setFormError] = useState('') - const [added, setAdded] = useState('') + const [formError, setFormError] = useState("") + const [added, setAdded] = useState("") const onSubmit = (e: FormEvent) => { e.preventDefault() const f = new FormData(e.currentTarget) - setFormError('') - api('/auth/users', { - method: 'POST', + setFormError("") + api("/auth/users", { + method: "POST", json: { - username: String(f.get('username')).trim(), - password: String(f.get('password')), + username: String(f.get("username")).trim(), + password: String(f.get("password")), }, }) .then((u) => { @@ -153,7 +152,7 @@ function Members() { } function Sessions() { - const { data: sessions, error, reload } = useOnlineData('/auth/sessions') + const { data: sessions, error, reload } = useOnlineData("/auth/sessions") const { refresh } = useAuth() return (

@@ -176,7 +175,7 @@ function Sessions() {