From ef3d554b2879d36ea9bd73b4dc9a81c6b37894f6 Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 09:07:00 +0100 Subject: [PATCH 01/18] Check that there is no AI attribution info in the commit messages --- .github/workflows/commit-messages.yml | 118 ++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 .github/workflows/commit-messages.yml diff --git a/.github/workflows/commit-messages.yml b/.github/workflows/commit-messages.yml new file mode 100644 index 0000000..fc47a2e --- /dev/null +++ b/.github/workflows/commit-messages.yml @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +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@v4 + 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 < Date: Sun, 29 Nov 2026 09:21:13 +0100 Subject: [PATCH 02/18] Document how to build --- README.md | 13 +++++++++++++ docs/DEVELOPMENT.md | 10 +++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 682b87f..345662f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,16 @@ # Cnotes Licensed under AGPL-3.0-or-later. See [LICENSE](LICENSE). + +## Development + +Requires Node 22 and pnpm (`corepack enable`). + +```sh +pnpm install +pnpm dev # http://localhost:5173 +``` + +Dev mode skips the setup token and two-factor. Data is stored in `apps/server/data/`. + +Checks, builds and production: [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md). diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 38495bc..d593c45 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -9,7 +9,8 @@ pnpm dev # web app on http://localhost:5173, server on :3000 (Vite prox ``` `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 +`apps/server/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,6 +26,13 @@ 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=../web/dist/client pnpm start # http://localhost:3000 +``` + ## Layout | Path | What | From 3fd3dd51fd7fefd89754c0fb8c633049f4a87cb5 Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 09:21:33 +0100 Subject: [PATCH 03/18] Use lowercase capitalization for cnotes --- README.md | 2 +- apps/server/src/app.ts | 2 +- apps/server/src/auth.ts | 2 +- apps/server/test/app.test.ts | 4 ++-- apps/web/e2e/smoke.spec.ts | 6 +++--- apps/web/public/manifest.webmanifest | 4 ++-- apps/web/src/components/AuthScreens.tsx | 4 ++-- apps/web/src/routes/settings.tsx | 2 +- compose.yaml | 2 +- deploy/nginx.conf | 2 +- docs/DEVELOPMENT.md | 4 ++-- docs/PLAN.md | 12 ++++++------ packages/shared/src/index.ts | 2 +- 13 files changed, 24 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 345662f..f705a49 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Cnotes +# cnotes Licensed under AGPL-3.0-or-later. See [LICENSE](LICENSE). diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 40c85de..c329643 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -47,7 +47,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}`, ) } } diff --git a/apps/server/src/auth.ts b/apps/server/src/auth.ts index 26a6c87..01373e9 100644 --- a/apps/server/src/auth.ts +++ b/apps/server/src/auth.ts @@ -306,7 +306,7 @@ export class AuthService { private totp(username: string, secret: string): OTPAuth.TOTP { return new OTPAuth.TOTP({ - issuer: 'Cnotes', + issuer: 'cnotes', label: username, algorithm: 'SHA1', digits: 6, diff --git a/apps/server/test/app.test.ts b/apps/server/test/app.test.ts index eaa8c88..30891bd 100644 --- a/apps/server/test/app.test.ts +++ b/apps/server/test/app.test.ts @@ -16,7 +16,7 @@ describe('static app serving', () => { webRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cnotes-web-')) fs.writeFileSync( path.join(webRoot, '_shell.html'), - 'Cnotes', + 'cnotes', ) fs.mkdirSync(path.join(webRoot, 'assets')) fs.writeFileSync(path.join(webRoot, 'assets', 'app-abc123.js'), 'console.log(1)') @@ -39,7 +39,7 @@ describe('static app serving', () => { 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') + expect(res.body).toContain('cnotes') }) it('caches hashed assets forever', async () => { diff --git a/apps/web/e2e/smoke.spec.ts b/apps/web/e2e/smoke.spec.ts index 0de2038..fab706c 100644 --- a/apps/web/e2e/smoke.spec.ts +++ b/apps/web/e2e/smoke.spec.ts @@ -5,9 +5,9 @@ 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() + 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: '/' }) + expect(manifest).toMatchObject({ name: 'cnotes', display: 'standalone', start_url: '/' }) }) test('rejects a wrong password', async ({ page }) => { @@ -35,7 +35,7 @@ test.describe('signed in', () => { 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 page.getByRole('link', { name: 'About cnotes' }).click() await expect(page.getByRole('link', { name: 'Source code' })).toHaveAttribute( 'href', 'https://github.com/cedernaes/cnotes', diff --git a/apps/web/public/manifest.webmanifest b/apps/web/public/manifest.webmanifest index a3fe1da..49585c9 100644 --- a/apps/web/public/manifest.webmanifest +++ b/apps/web/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/src/components/AuthScreens.tsx b/apps/web/src/components/AuthScreens.tsx index bb8df97..0dae351 100644 --- a/apps/web/src/components/AuthScreens.tsx +++ b/apps/web/src/components/AuthScreens.tsx @@ -71,7 +71,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)." /> )}

- 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.

diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx index 8521d17..683e262 100644 --- a/apps/web/src/routes/settings.tsx +++ b/apps/web/src/routes/settings.tsx @@ -42,7 +42,7 @@ function Settings() { About

- About Cnotes + About cnotes {' '} ·{' '} diff --git a/compose.yaml b/compose.yaml index a20acfb..f9afc4f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,5 +1,5 @@ # 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 deploy/nginx.conf). services: cnotes: # Built from this checkout. `docker compose up -d --build` rebuilds after a `git pull`. diff --git a/deploy/nginx.conf b/deploy/nginx.conf index 65ec55a..47869a5 100644 --- a/deploy/nginx.conf +++ b/deploy/nginx.conf @@ -1,4 +1,4 @@ -# Example Nginx site for Cnotes on its own subdomain. +# 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 { diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index d593c45..1863719 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -76,8 +76,8 @@ variables, see `apps/server/.env.example`. - 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. +- 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`. diff --git a/docs/PLAN.md b/docs/PLAN.md index afbd577..0ee87d6 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. @@ -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. @@ -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 | @@ -285,7 +285,7 @@ server { - `LICENSE` (AGPL-3.0) is in the repo; source files carry `SPDX-License-Identifier: AGPL-3.0-or-later`. - 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/packages/shared/src/index.ts b/packages/shared/src/index.ts index e650790..add2152 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1,5 +1,5 @@ // 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' From ce23652b8f69946b21d01fe88729a7009047e545 Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 09:23:18 +0100 Subject: [PATCH 04/18] Mention how to pronounce it --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f705a49..76ae36c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# cnotes +# `cnotes` (pronounced _snotes_) Licensed under AGPL-3.0-or-later. See [LICENSE](LICENSE). From fcf120900adef25afdf2b8a99ef051b29f0fc15e Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 09:25:36 +0100 Subject: [PATCH 05/18] Document shortly what it's for --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 76ae36c..6edaf58 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,22 @@ # `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 From 2efc7412a50ccdcce2f8f76291e837d324adc77b Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 16:40:11 +0100 Subject: [PATCH 06/18] Remove license header from files It's already specified for the repo, so there's no point in duplicating it in each file. --- .github/workflows/ci.yml | 1 - .github/workflows/commit-messages.yml | 1 - Dockerfile | 1 - apps/server/build.js | 1 - apps/server/src/app.ts | 1 - apps/server/src/auth.ts | 1 - apps/server/src/backup.ts | 1 - apps/server/src/config.ts | 1 - apps/server/src/db.ts | 1 - apps/server/src/export.ts | 1 - apps/server/src/files.ts | 1 - apps/server/src/http.ts | 1 - apps/server/src/index.ts | 1 - apps/server/src/projection.ts | 1 - apps/server/src/routes/auth.ts | 1 - apps/server/src/routes/files.ts | 1 - apps/server/src/routes/search.ts | 1 - apps/server/src/secrets.ts | 1 - apps/server/src/sync.ts | 1 - apps/server/test/app.test.ts | 1 - apps/server/test/auth.test.ts | 1 - apps/server/test/backup.test.ts | 1 - apps/server/test/helpers.ts | 1 - apps/server/test/sync.test.ts | 1 - apps/server/vitest.config.ts | 1 - apps/web/e2e/auth.spec.ts | 1 - apps/web/e2e/global-setup.ts | 1 - apps/web/e2e/helpers.ts | 1 - apps/web/e2e/pages.spec.ts | 1 - apps/web/e2e/smoke.spec.ts | 1 - apps/web/playwright.config.ts | 1 - apps/web/scripts/generate-sw.js | 1 - apps/web/src/components/AuthScreens.tsx | 1 - apps/web/src/components/Editor.tsx | 1 - apps/web/src/components/PageLink.tsx | 1 - apps/web/src/components/SyncIndicator.tsx | 1 - apps/web/src/components/UpdatePrompt.tsx | 1 - apps/web/src/components/editorExtensions.ts | 1 - apps/web/src/components/ui.tsx | 1 - apps/web/src/lib/api.ts | 1 - apps/web/src/lib/auth.tsx | 1 - apps/web/src/lib/ids.ts | 1 - apps/web/src/lib/sync.ts | 1 - apps/web/src/lib/useCreatePage.ts | 1 - apps/web/src/lib/useDoc.ts | 1 - apps/web/src/lib/users.ts | 1 - apps/web/src/lib/workspace.ts | 1 - apps/web/src/router.tsx | 1 - apps/web/src/routes/__root.tsx | 1 - apps/web/src/routes/about.tsx | 1 - apps/web/src/routes/index.tsx | 1 - apps/web/src/routes/p.$pageId.tsx | 1 - apps/web/src/routes/pages.tsx | 1 - apps/web/src/routes/search.tsx | 1 - apps/web/src/routes/settings.tsx | 1 - apps/web/vite.config.ts | 1 - compose.yaml | 1 - docs/DEVELOPMENT.md | 2 -- docs/PLAN.md | 2 +- eslint.config.js | 1 - packages/shared/src/api.test.ts | 1 - packages/shared/src/api.ts | 1 - packages/shared/src/content.test.ts | 1 - packages/shared/src/content.ts | 1 - packages/shared/src/docs.test.ts | 1 - packages/shared/src/docs.ts | 1 - packages/shared/src/index.ts | 1 - packages/shared/vitest.config.ts | 1 - vitest.config.ts | 1 - 69 files changed, 1 insertion(+), 70 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b753b0a..17a0e37 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,3 @@ -# SPDX-License-Identifier: AGPL-3.0-or-later name: CI on: diff --git a/.github/workflows/commit-messages.yml b/.github/workflows/commit-messages.yml index fc47a2e..4bab7fe 100644 --- a/.github/workflows/commit-messages.yml +++ b/.github/workflows/commit-messages.yml @@ -1,4 +1,3 @@ -# SPDX-License-Identifier: AGPL-3.0-or-later name: Commit messages on: diff --git a/Dockerfile b/Dockerfile index 92097f2..e725f0f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,3 @@ -# SPDX-License-Identifier: AGPL-3.0-or-later # syntax=docker/dockerfile:1 FROM node:22-bookworm-slim AS base diff --git a/apps/server/build.js b/apps/server/build.js index e5d8bb8..8d2f034 100644 --- a/apps/server/build.js +++ b/apps/server/build.js @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index c329643..dedd258 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import crypto from 'node:crypto' import fs from 'node:fs' import path from 'node:path' diff --git a/apps/server/src/auth.ts b/apps/server/src/auth.ts index 01373e9..001225f 100644 --- a/apps/server/src/auth.ts +++ b/apps/server/src/auth.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/src/backup.ts b/apps/server/src/backup.ts index 425d0ed..0027bd8 100644 --- a/apps/server/src/backup.ts +++ b/apps/server/src/backup.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import fs from 'node:fs' import path from 'node:path' import type { FastifyBaseLogger } from 'fastify' diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 478dd65..05f77e3 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import path from 'node:path' export interface Config { diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts index ca0456e..91efe31 100644 --- a/apps/server/src/db.ts +++ b/apps/server/src/db.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import path from 'node:path' import Database from 'better-sqlite3' diff --git a/apps/server/src/export.ts b/apps/server/src/export.ts index 014da93..d427f28 100644 --- a/apps/server/src/export.ts +++ b/apps/server/src/export.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/src/files.ts b/apps/server/src/files.ts index 73dae46..b84009e 100644 --- a/apps/server/src/files.ts +++ b/apps/server/src/files.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import crypto from 'node:crypto' import fs from 'node:fs' import path from 'node:path' diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index b1d298d..528aedf 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index dbf57c8..8bf4a43 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { buildApp } from './app' import { loadConfig } from './config' diff --git a/apps/server/src/projection.ts b/apps/server/src/projection.ts index ee95c81..53e8ac4 100644 --- a/apps/server/src/projection.ts +++ b/apps/server/src/projection.ts @@ -1,4 +1,3 @@ -// 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. diff --git a/apps/server/src/routes/auth.ts b/apps/server/src/routes/auth.ts index 45b93e6..f9b117e 100644 --- a/apps/server/src/routes/auth.ts +++ b/apps/server/src/routes/auth.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { Type } from '@sinclair/typebox' import { ApiError, diff --git a/apps/server/src/routes/files.ts b/apps/server/src/routes/files.ts index 8a6f548..ae7ed24 100644 --- a/apps/server/src/routes/files.ts +++ b/apps/server/src/routes/files.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/src/routes/search.ts b/apps/server/src/routes/search.ts index 47818c4..0831a5f 100644 --- a/apps/server/src/routes/search.ts +++ b/apps/server/src/routes/search.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { Type } from '@sinclair/typebox' import { SearchResponse } from '@cnotes/shared' import type { FastifyInstance } from 'fastify' diff --git a/apps/server/src/secrets.ts b/apps/server/src/secrets.ts index 912acc0..8ecc800 100644 --- a/apps/server/src/secrets.ts +++ b/apps/server/src/secrets.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import crypto from 'node:crypto' import fs from 'node:fs' import path from 'node:path' diff --git a/apps/server/src/sync.ts b/apps/server/src/sync.ts index a8b4c7e..e05b807 100644 --- a/apps/server/src/sync.ts +++ b/apps/server/src/sync.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/test/app.test.ts b/apps/server/test/app.test.ts index 30891bd..9deb731 100644 --- a/apps/server/test/app.test.ts +++ b/apps/server/test/app.test.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import fs from 'node:fs' import os from 'node:os' import path from 'node:path' diff --git a/apps/server/test/auth.test.ts b/apps/server/test/auth.test.ts index 21093d8..97b424e 100644 --- a/apps/server/test/auth.test.ts +++ b/apps/server/test/auth.test.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/test/backup.test.ts b/apps/server/test/backup.test.ts index f40e02a..ad2e558 100644 --- a/apps/server/test/backup.test.ts +++ b/apps/server/test/backup.test.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/test/helpers.ts b/apps/server/test/helpers.ts index 89584d7..8963ca6 100644 --- a/apps/server/test/helpers.ts +++ b/apps/server/test/helpers.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import fs from 'node:fs' import os from 'node:os' import path from 'node:path' diff --git a/apps/server/test/sync.test.ts b/apps/server/test/sync.test.ts index c88e9e7..345d65f 100644 --- a/apps/server/test/sync.test.ts +++ b/apps/server/test/sync.test.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.ts index aede9d1..5b3e79d 100644 --- a/apps/server/vitest.config.ts +++ b/apps/server/vitest.config.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { defineConfig } from 'vitest/config' export default defineConfig({ diff --git a/apps/web/e2e/auth.spec.ts b/apps/web/e2e/auth.spec.ts index 6d9ec1d..8629c5b 100644 --- a/apps/web/e2e/auth.spec.ts +++ b/apps/web/e2e/auth.spec.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { expect, test } from '@playwright/test' import { PASSWORD, STATE, totp, unique } from './helpers' diff --git a/apps/web/e2e/global-setup.ts b/apps/web/e2e/global-setup.ts index 8c3875d..f150378 100644 --- a/apps/web/e2e/global-setup.ts +++ b/apps/web/e2e/global-setup.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/web/e2e/helpers.ts b/apps/web/e2e/helpers.ts index f5303c6..68f0501 100644 --- a/apps/web/e2e/helpers.ts +++ b/apps/web/e2e/helpers.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { expect, type Browser, type Page } from '@playwright/test' import * as OTPAuth from 'otpauth' diff --git a/apps/web/e2e/pages.spec.ts b/apps/web/e2e/pages.spec.ts index 3246209..792d293 100644 --- a/apps/web/e2e/pages.spec.ts +++ b/apps/web/e2e/pages.spec.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import path from 'node:path' import { expect, test } from '@playwright/test' import { unzipSync } from 'fflate' diff --git a/apps/web/e2e/smoke.spec.ts b/apps/web/e2e/smoke.spec.ts index fab706c..fc420df 100644 --- a/apps/web/e2e/smoke.spec.ts +++ b/apps/web/e2e/smoke.spec.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { expect, test } from '@playwright/test' import { STATE } from './helpers' diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts index 9b08f3a..00c93c1 100644 --- a/apps/web/playwright.config.ts +++ b/apps/web/playwright.config.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { defineConfig, devices } from '@playwright/test' export const PORT = 3100 diff --git a/apps/web/scripts/generate-sw.js b/apps/web/scripts/generate-sw.js index 4a7ca1b..ed77b54 100644 --- a/apps/web/scripts/generate-sw.js +++ b/apps/web/scripts/generate-sw.js @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/web/src/components/AuthScreens.tsx b/apps/web/src/components/AuthScreens.tsx index 0dae351..b8b44fb 100644 --- a/apps/web/src/components/AuthScreens.tsx +++ b/apps/web/src/components/AuthScreens.tsx @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/web/src/components/Editor.tsx b/apps/web/src/components/Editor.tsx index d46f81b..da4804a 100644 --- a/apps/web/src/components/Editor.tsx +++ b/apps/web/src/components/Editor.tsx @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/web/src/components/PageLink.tsx b/apps/web/src/components/PageLink.tsx index 7a741f7..41d7d0f 100644 --- a/apps/web/src/components/PageLink.tsx +++ b/apps/web/src/components/PageLink.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import type { PageMeta } from '@cnotes/shared' import { Link } from '@tanstack/react-router' import type { ReactNode } from 'react' diff --git a/apps/web/src/components/SyncIndicator.tsx b/apps/web/src/components/SyncIndicator.tsx index 2407ded..9e228ee 100644 --- a/apps/web/src/components/SyncIndicator.tsx +++ b/apps/web/src/components/SyncIndicator.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { useEffect, useState } from 'react' import { useSyncStatus } from '../lib/workspace' diff --git a/apps/web/src/components/UpdatePrompt.tsx b/apps/web/src/components/UpdatePrompt.tsx index 8fa4788..c5f47c9 100644 --- a/apps/web/src/components/UpdatePrompt.tsx +++ b/apps/web/src/components/UpdatePrompt.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { useEffect, useRef, useState } from 'react' import type { Workbox } from 'workbox-window' diff --git a/apps/web/src/components/editorExtensions.ts b/apps/web/src/components/editorExtensions.ts index e22be2e..42a3c4c 100644 --- a/apps/web/src/components/editorExtensions.ts +++ b/apps/web/src/components/editorExtensions.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/web/src/components/ui.tsx b/apps/web/src/components/ui.tsx index d5338c7..3ae9fe9 100644 --- a/apps/web/src/components/ui.tsx +++ b/apps/web/src/components/ui.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode } from 'react' export function Button({ diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index c41578e..639eee6 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later export class ApiError extends Error { constructor( message: string, diff --git a/apps/web/src/lib/auth.tsx b/apps/web/src/lib/auth.tsx index c86fb84..aa39dd5 100644 --- a/apps/web/src/lib/auth.tsx +++ b/apps/web/src/lib/auth.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import type { AuthState, PublicUser } from '@cnotes/shared' import { createContext, diff --git a/apps/web/src/lib/ids.ts b/apps/web/src/lib/ids.ts index 0009e55..26d3a7d 100644 --- a/apps/web/src/lib/ids.ts +++ b/apps/web/src/lib/ids.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-' /** Random URL-safe id, created on the device so pages can be made offline. */ diff --git a/apps/web/src/lib/sync.ts b/apps/web/src/lib/sync.ts index b666bea..a0fd2a3 100644 --- a/apps/web/src/lib/sync.ts +++ b/apps/web/src/lib/sync.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later // Owns the Yjs documents on this device: one WebSocket to the server shared // by all documents, and an IndexedDB copy of each document for offline use. import { HocuspocusProvider, HocuspocusProviderWebsocket } from '@hocuspocus/provider' diff --git a/apps/web/src/lib/useCreatePage.ts b/apps/web/src/lib/useCreatePage.ts index 13e74fc..3ad1ad8 100644 --- a/apps/web/src/lib/useCreatePage.ts +++ b/apps/web/src/lib/useCreatePage.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { useNavigate } from '@tanstack/react-router' import { useUser } from './auth' import { createPage } from './workspace' diff --git a/apps/web/src/lib/useDoc.ts b/apps/web/src/lib/useDoc.ts index 5d6b385..c8358ee 100644 --- a/apps/web/src/lib/useDoc.ts +++ b/apps/web/src/lib/useDoc.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { useEffect, useReducer, useState } from 'react' import { sync, type DocHandle } from './sync' diff --git a/apps/web/src/lib/users.ts b/apps/web/src/lib/users.ts index b16c65c..2c8242c 100644 --- a/apps/web/src/lib/users.ts +++ b/apps/web/src/lib/users.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import type { PublicUser } from '@cnotes/shared' import { useEffect, useState } from 'react' import { api } from './api' diff --git a/apps/web/src/lib/workspace.ts b/apps/web/src/lib/workspace.ts index 86f6cbc..54e3823 100644 --- a/apps/web/src/lib/workspace.ts +++ b/apps/web/src/lib/workspace.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { compareSiblings, listPages, diff --git a/apps/web/src/router.tsx b/apps/web/src/router.tsx index 1626c3d..90e78ed 100644 --- a/apps/web/src/router.tsx +++ b/apps/web/src/router.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index fe5b032..947beef 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later /// import { APP_NAME } from '@cnotes/shared' import { diff --git a/apps/web/src/routes/about.tsx b/apps/web/src/routes/about.tsx index 3d028db..9896078 100644 --- a/apps/web/src/routes/about.tsx +++ b/apps/web/src/routes/about.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { APP_NAME, DEFAULT_SOURCE_URL } from '@cnotes/shared' import { createFileRoute } from '@tanstack/react-router' diff --git a/apps/web/src/routes/index.tsx b/apps/web/src/routes/index.tsx index d47f598..b2750b0 100644 --- a/apps/web/src/routes/index.tsx +++ b/apps/web/src/routes/index.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { createFileRoute } from '@tanstack/react-router' import { useMemo } from 'react' import { PageRow } from '../components/PageLink' diff --git a/apps/web/src/routes/p.$pageId.tsx b/apps/web/src/routes/p.$pageId.tsx index 280ae5f..9cd4580 100644 --- a/apps/web/src/routes/p.$pageId.tsx +++ b/apps/web/src/routes/p.$pageId.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { CONTENT_FIELD, isSelfOrDescendant, diff --git a/apps/web/src/routes/pages.tsx b/apps/web/src/routes/pages.tsx index 364fb35..9592540 100644 --- a/apps/web/src/routes/pages.tsx +++ b/apps/web/src/routes/pages.tsx @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { buildTree, type TreeNode } from '@cnotes/shared' import { createFileRoute } from '@tanstack/react-router' import { useMemo, useState } from 'react' diff --git a/apps/web/src/routes/search.tsx b/apps/web/src/routes/search.tsx index 44b2d4c..e58c985 100644 --- a/apps/web/src/routes/search.tsx +++ b/apps/web/src/routes/search.tsx @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx index 683e262..6e831af 100644 --- a/apps/web/src/routes/settings.tsx +++ b/apps/web/src/routes/settings.tsx @@ -1,4 +1,3 @@ -// 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' diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 0c85416..8dbef96 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import tailwindcss from '@tailwindcss/vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' diff --git a/compose.yaml b/compose.yaml index f9afc4f..2c25409 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,4 +1,3 @@ -# SPDX-License-Identifier: AGPL-3.0-or-later # cnotes behind an existing reverse proxy (see deploy/nginx.conf). services: cnotes: diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 1863719..aa9ffa0 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -79,5 +79,3 @@ variables, see `apps/server/.env.example`. - 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`. diff --git a/docs/PLAN.md b/docs/PLAN.md index 0ee87d6..cae5d84 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -283,7 +283,7 @@ 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). - Contributions: DCO sign-off rather than a CLA. diff --git a/eslint.config.js b/eslint.config.js index 807cddd..782044f 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import js from '@eslint/js' import reactHooks from 'eslint-plugin-react-hooks' import globals from 'globals' diff --git a/packages/shared/src/api.test.ts b/packages/shared/src/api.test.ts index ee41241..af3a349 100644 --- a/packages/shared/src/api.test.ts +++ b/packages/shared/src/api.test.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/packages/shared/src/api.ts b/packages/shared/src/api.ts index f5c8e6f..801d3d7 100644 --- a/packages/shared/src/api.ts +++ b/packages/shared/src/api.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/packages/shared/src/content.test.ts b/packages/shared/src/content.test.ts index c8041a8..a743de5 100644 --- a/packages/shared/src/content.test.ts +++ b/packages/shared/src/content.test.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.ts index 99c01d9..45f49ff 100644 --- a/packages/shared/src/content.ts +++ b/packages/shared/src/content.ts @@ -1,4 +1,3 @@ -// 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. diff --git a/packages/shared/src/docs.test.ts b/packages/shared/src/docs.test.ts index 2e3f589..50edd7c 100644 --- a/packages/shared/src/docs.test.ts +++ b/packages/shared/src/docs.test.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { describe, expect, it } from 'vitest' import * as Y from 'yjs' import { diff --git a/packages/shared/src/docs.ts b/packages/shared/src/docs.ts index e45c51a..4ad5905 100644 --- a/packages/shared/src/docs.ts +++ b/packages/shared/src/docs.ts @@ -1,4 +1,3 @@ -// 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' diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index add2152..481a992 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later export const APP_NAME = 'cnotes' /** Where the source code of this instance can be found (AGPL-3.0 section 13). */ diff --git a/packages/shared/vitest.config.ts b/packages/shared/vitest.config.ts index 8a09209..1f202a5 100644 --- a/packages/shared/vitest.config.ts +++ b/packages/shared/vitest.config.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { defineConfig } from 'vitest/config' export default defineConfig({ diff --git a/vitest.config.ts b/vitest.config.ts index 2bca3d8..28c4dc3 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,4 +1,3 @@ -// SPDX-License-Identifier: AGPL-3.0-or-later import { defineConfig } from 'vitest/config' export default defineConfig({ From 7e0e8b5c7cdbd11f7e00efaa81358d9d781c790d Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 16:46:19 +0100 Subject: [PATCH 07/18] Add simple AI instructions --- AGENTS.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..045ff8a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,14 @@ +# Instructions for AI agents + +How to build, test and find your way around: [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md). + +## Commit messages + +Don't credit yourself or any other AI tool in commit messages. Leave out: + +- `Co-Authored-By:`, `Signed-off-by:` and other `*-by:` lines that name an AI tool or model, such as `Co-Authored-By: Claude Opus 5.5 ` +- `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. From aad9c34b4eea7d4cc785379e5b2a0493bcefe709 Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 16:49:49 +0100 Subject: [PATCH 08/18] Move the example NGINX configuration to a documentation file --- compose.yaml | 2 +- deploy/nginx.conf | 38 ------------------------ docs/DEVELOPMENT.md | 23 +-------------- docs/deployment.md | 70 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 61 deletions(-) delete mode 100644 deploy/nginx.conf create mode 100644 docs/deployment.md diff --git a/compose.yaml b/compose.yaml index 2c25409..ef5f7e5 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,4 +1,4 @@ -# 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`. diff --git a/deploy/nginx.conf b/deploy/nginx.conf deleted file mode 100644 index 47869a5..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/DEVELOPMENT.md b/docs/DEVELOPMENT.md index aa9ffa0..43aa872 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -42,7 +42,6 @@ WEB_ROOT=../web/dist/client pnpm start # http://localhost:3000 | `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 | | `packages/shared` | Document model (page tree, pins), content helpers (text, tasks, Markdown), API schemas | -| `deploy/` | Example Nginx config | ### How data flows @@ -58,24 +57,4 @@ WEB_ROOT=../web/dist/client pnpm start # http://localhost:3000 ## 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. +See [deployment.md](deployment.md): Docker, Nginx and backups. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..bcbb8f5 --- /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 `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`. Settings are environment +variables, see `apps/server/.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. From 0ea61694cd717f312172fbd5f1f462d24c7986c4 Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 16:52:13 +0100 Subject: [PATCH 09/18] Rename to lower-case --- AGENTS.md | 2 +- README.md | 2 +- docs/{DEVELOPMENT.md => development.md} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename docs/{DEVELOPMENT.md => development.md} (100%) diff --git a/AGENTS.md b/AGENTS.md index 045ff8a..131ff02 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Instructions for AI agents -How to build, test and find your way around: [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md). +How to build, test and find your way around: [docs/development.md](docs/development.md). ## Commit messages diff --git a/README.md b/README.md index 6edaf58..0ccec68 100644 --- a/README.md +++ b/README.md @@ -30,4 +30,4 @@ pnpm dev # http://localhost:5173 Dev mode skips the setup token and two-factor. Data is stored in `apps/server/data/`. -Checks, builds and production: [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md). +Checks and builds: [docs/development.md](docs/development.md). Running it on a server: [docs/deployment.md](docs/deployment.md). diff --git a/docs/DEVELOPMENT.md b/docs/development.md similarity index 100% rename from docs/DEVELOPMENT.md rename to docs/development.md From b9324c0c88520ce565c6b3d2f192ea4be14a37aa Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 16:55:33 +0100 Subject: [PATCH 10/18] Correct note about repo being private It's public --- compose.yaml | 3 +-- docs/deployment.md | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/compose.yaml b/compose.yaml index ef5f7e5..f681185 100644 --- a/compose.yaml +++ b/compose.yaml @@ -2,8 +2,7 @@ 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 diff --git a/docs/deployment.md b/docs/deployment.md index bcbb8f5..45ab4c7 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -9,8 +9,8 @@ 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`. +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 `apps/server/.env.example`. From e6bb53b97961ab4268c192d12c5f36308e3208ef Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 17:02:38 +0100 Subject: [PATCH 11/18] Bump and pin workflows --- .github/workflows/ci.yml | 16 ++++++++-------- .github/workflows/commit-messages.yml | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 17a0e37..ebf6708 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,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 @@ -40,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 }} @@ -50,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 index 4bab7fe..dc1d3e4 100644 --- a/.github/workflows/commit-messages.yml +++ b/.github/workflows/commit-messages.yml @@ -15,7 +15,7 @@ jobs: name: No AI attribution runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 From 4fa9704a6206a3291470b1dc8fa6d90f746e0775 Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 17:07:55 +0100 Subject: [PATCH 12/18] Stay behind latest updates To reduce the risk of getting untested versions with vulnerabilities. --- .github/dependabot.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 2fe457a..e6f8797 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,6 +4,8 @@ updates: directory: / schedule: interval: weekly + cooldown: + default-days: 14 groups: tanstack: patterns: ['@tanstack/*'] @@ -13,7 +15,11 @@ updates: directory: / schedule: interval: monthly + cooldown: + default-days: 14 - package-ecosystem: docker directory: / schedule: interval: monthly + cooldown: + default-days: 14 From 485ac71b768f45efb7f673899bf73f9a7f7e3099 Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 17:13:23 +0100 Subject: [PATCH 13/18] Bump node to 26 --- .nvmrc | 2 +- Dockerfile | 11 +++-- README.md | 2 +- apps/server/build.js | 2 +- apps/server/package.json | 2 +- docs/development.md | 2 +- package.json | 2 +- pnpm-lock.yaml | 98 ++++++++++++++++++++-------------------- 8 files changed, 61 insertions(+), 60 deletions(-) diff --git a/.nvmrc b/.nvmrc index 2bd5a0a..6f4247a 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -22 +26 diff --git a/Dockerfile b/Dockerfile index e725f0f..454d38c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,10 @@ -# 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 +# 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 ./ @@ -18,7 +19,7 @@ RUN pnpm build RUN --mount=type=cache,id=pnpm,target=/pnpm/store \ pnpm deploy --legacy --prod --filter @cnotes/server /out/server -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 \ diff --git a/README.md b/README.md index 0ccec68..01a50f7 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Licensed under AGPL-3.0-or-later. See [LICENSE](LICENSE). ## Development -Requires Node 22 and pnpm (`corepack enable`). +Requires Node 26 and pnpm (`npm install -g corepack && corepack enable`). ```sh pnpm install diff --git a/apps/server/build.js b/apps/server/build.js index 8d2f034..38e57ba 100644 --- a/apps/server/build.js +++ b/apps/server/build.js @@ -11,7 +11,7 @@ await build({ outfile: 'dist/index.js', bundle: true, platform: 'node', - target: 'node22', + target: 'node26', format: 'esm', sourcemap: true, // Also externalize subpath imports such as '@sinclair/typebox/value'. diff --git a/apps/server/package.json b/apps/server/package.json index 35d462a..31d1ce2 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -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/docs/development.md b/docs/development.md index 43aa872..38368a5 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,6 +1,6 @@ # 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 diff --git a/package.json b/package.json index 766c6f3..9fd03db 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "type": "module", "packageManager": "pnpm@10.28.0", "engines": { - "node": ">=22.12" + "node": ">=26" }, "scripts": { "dev": "pnpm --parallel --filter @cnotes/web --filter @cnotes/server dev", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ea8a5df..587bdd2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,7 +31,7 @@ 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: dependencies: @@ -76,7 +76,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 +91,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 @@ -119,7 +119,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 +177,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 +189,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,7 +201,7 @@ 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 @@ -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 From d8995453b818fc6e25577f8ae802d76bb83caa9e Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 17:20:48 +0100 Subject: [PATCH 14/18] Move apps/* to src/* --- .github/workflows/ci.yml | 2 +- .prettierignore | 2 +- Dockerfile | 20 ++++++++-------- README.md | 2 +- compose.yaml | 2 +- docs/PLAN.md | 6 ++--- docs/deployment.md | 2 +- docs/development.md | 14 +++++------ eslint.config.js | 8 +++---- package.json | 8 +++---- pnpm-lock.yaml | 22 +++++++++--------- pnpm-workspace.yaml | 2 +- {apps/server => src/backend}/.env.example | 2 +- {apps/server => src/backend}/build.js | 0 {apps/server => src/backend}/package.json | 2 +- {apps/server => src/backend}/src/app.ts | 0 {apps/server => src/backend}/src/auth.ts | 0 {apps/server => src/backend}/src/backup.ts | 0 {apps/server => src/backend}/src/config.ts | 0 {apps/server => src/backend}/src/db.ts | 0 {apps/server => src/backend}/src/export.ts | 0 {apps/server => src/backend}/src/files.ts | 0 {apps/server => src/backend}/src/http.ts | 0 {apps/server => src/backend}/src/index.ts | 0 .../server => src/backend}/src/projection.ts | 0 .../server => src/backend}/src/routes/auth.ts | 0 .../backend}/src/routes/files.ts | 0 .../backend}/src/routes/search.ts | 0 {apps/server => src/backend}/src/secrets.ts | 0 {apps/server => src/backend}/src/sync.ts | 0 {apps/server => src/backend}/test/app.test.ts | 0 .../server => src/backend}/test/auth.test.ts | 0 .../backend}/test/backup.test.ts | 0 {apps/server => src/backend}/test/helpers.ts | 0 .../server => src/backend}/test/sync.test.ts | 0 {apps/server => src/backend}/tsconfig.json | 0 {apps/server => src/backend}/vitest.config.ts | 0 {apps/web => src/frontend}/e2e/auth.spec.ts | 0 .../web => src/frontend}/e2e/global-setup.ts | 0 {apps/web => src/frontend}/e2e/helpers.ts | 0 {apps/web => src/frontend}/e2e/pages.spec.ts | 0 {apps/web => src/frontend}/e2e/smoke.spec.ts | 0 {apps/web => src/frontend}/package.json | 2 +- .../web => src/frontend}/playwright.config.ts | 2 +- .../frontend}/public/apple-touch-icon.png | Bin .../frontend}/public/icon-maskable.svg | 0 {apps/web => src/frontend}/public/icon.svg | 0 .../frontend}/public/manifest.webmanifest | 0 .../frontend}/scripts/generate-sw.js | 0 .../frontend}/src/components/AuthScreens.tsx | 0 .../frontend}/src/components/Editor.tsx | 0 .../frontend}/src/components/PageLink.tsx | 0 .../src/components/SyncIndicator.tsx | 0 .../frontend}/src/components/UpdatePrompt.tsx | 0 .../src/components/editorExtensions.ts | 0 .../frontend}/src/components/ui.tsx | 0 {apps/web => src/frontend}/src/lib/api.ts | 0 {apps/web => src/frontend}/src/lib/auth.tsx | 0 {apps/web => src/frontend}/src/lib/ids.ts | 0 {apps/web => src/frontend}/src/lib/sync.ts | 0 .../frontend}/src/lib/useCreatePage.ts | 0 {apps/web => src/frontend}/src/lib/useDoc.ts | 0 {apps/web => src/frontend}/src/lib/users.ts | 0 .../web => src/frontend}/src/lib/workspace.ts | 0 .../web => src/frontend}/src/routeTree.gen.ts | 0 {apps/web => src/frontend}/src/router.tsx | 0 .../frontend}/src/routes/__root.tsx | 0 .../web => src/frontend}/src/routes/about.tsx | 0 .../web => src/frontend}/src/routes/index.tsx | 0 .../frontend}/src/routes/p.$pageId.tsx | 0 .../web => src/frontend}/src/routes/pages.tsx | 0 .../frontend}/src/routes/search.tsx | 0 .../frontend}/src/routes/settings.tsx | 0 {apps/web => src/frontend}/src/styles.css | 0 {apps/web => src/frontend}/tsconfig.json | 0 {apps/web => src/frontend}/vite.config.ts | 2 +- vitest.config.ts | 2 +- 77 files changed, 51 insertions(+), 51 deletions(-) rename {apps/server => src/backend}/.env.example (96%) rename {apps/server => src/backend}/build.js (100%) rename {apps/server => src/backend}/package.json (97%) rename {apps/server => src/backend}/src/app.ts (100%) rename {apps/server => src/backend}/src/auth.ts (100%) rename {apps/server => src/backend}/src/backup.ts (100%) rename {apps/server => src/backend}/src/config.ts (100%) rename {apps/server => src/backend}/src/db.ts (100%) rename {apps/server => src/backend}/src/export.ts (100%) rename {apps/server => src/backend}/src/files.ts (100%) rename {apps/server => src/backend}/src/http.ts (100%) rename {apps/server => src/backend}/src/index.ts (100%) rename {apps/server => src/backend}/src/projection.ts (100%) rename {apps/server => src/backend}/src/routes/auth.ts (100%) rename {apps/server => src/backend}/src/routes/files.ts (100%) rename {apps/server => src/backend}/src/routes/search.ts (100%) rename {apps/server => src/backend}/src/secrets.ts (100%) rename {apps/server => src/backend}/src/sync.ts (100%) rename {apps/server => src/backend}/test/app.test.ts (100%) rename {apps/server => src/backend}/test/auth.test.ts (100%) rename {apps/server => src/backend}/test/backup.test.ts (100%) rename {apps/server => src/backend}/test/helpers.ts (100%) rename {apps/server => src/backend}/test/sync.test.ts (100%) rename {apps/server => src/backend}/tsconfig.json (100%) rename {apps/server => src/backend}/vitest.config.ts (100%) rename {apps/web => src/frontend}/e2e/auth.spec.ts (100%) rename {apps/web => src/frontend}/e2e/global-setup.ts (100%) rename {apps/web => src/frontend}/e2e/helpers.ts (100%) rename {apps/web => src/frontend}/e2e/pages.spec.ts (100%) rename {apps/web => src/frontend}/e2e/smoke.spec.ts (100%) rename {apps/web => src/frontend}/package.json (97%) rename {apps/web => src/frontend}/playwright.config.ts (92%) rename {apps/web => src/frontend}/public/apple-touch-icon.png (100%) rename {apps/web => src/frontend}/public/icon-maskable.svg (100%) rename {apps/web => src/frontend}/public/icon.svg (100%) rename {apps/web => src/frontend}/public/manifest.webmanifest (100%) rename {apps/web => src/frontend}/scripts/generate-sw.js (100%) rename {apps/web => src/frontend}/src/components/AuthScreens.tsx (100%) rename {apps/web => src/frontend}/src/components/Editor.tsx (100%) rename {apps/web => src/frontend}/src/components/PageLink.tsx (100%) rename {apps/web => src/frontend}/src/components/SyncIndicator.tsx (100%) rename {apps/web => src/frontend}/src/components/UpdatePrompt.tsx (100%) rename {apps/web => src/frontend}/src/components/editorExtensions.ts (100%) rename {apps/web => src/frontend}/src/components/ui.tsx (100%) rename {apps/web => src/frontend}/src/lib/api.ts (100%) rename {apps/web => src/frontend}/src/lib/auth.tsx (100%) rename {apps/web => src/frontend}/src/lib/ids.ts (100%) rename {apps/web => src/frontend}/src/lib/sync.ts (100%) rename {apps/web => src/frontend}/src/lib/useCreatePage.ts (100%) rename {apps/web => src/frontend}/src/lib/useDoc.ts (100%) rename {apps/web => src/frontend}/src/lib/users.ts (100%) rename {apps/web => src/frontend}/src/lib/workspace.ts (100%) rename {apps/web => src/frontend}/src/routeTree.gen.ts (100%) rename {apps/web => src/frontend}/src/router.tsx (100%) rename {apps/web => src/frontend}/src/routes/__root.tsx (100%) rename {apps/web => src/frontend}/src/routes/about.tsx (100%) rename {apps/web => src/frontend}/src/routes/index.tsx (100%) rename {apps/web => src/frontend}/src/routes/p.$pageId.tsx (100%) rename {apps/web => src/frontend}/src/routes/pages.tsx (100%) rename {apps/web => src/frontend}/src/routes/search.tsx (100%) rename {apps/web => src/frontend}/src/routes/settings.tsx (100%) rename {apps/web => src/frontend}/src/styles.css (100%) rename {apps/web => src/frontend}/tsconfig.json (100%) rename {apps/web => src/frontend}/vite.config.ts (92%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ebf6708..29d2cf2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,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: diff --git a/.prettierignore b/.prettierignore index f5a9bb3..83d36a6 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,6 +1,6 @@ pnpm-lock.yaml LICENSE -apps/web/src/routeTree.gen.ts +src/frontend/src/routeTree.gen.ts dist .output *.md diff --git a/Dockerfile b/Dockerfile index 454d38c..5fd6b7f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,15 +1,15 @@ # 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 -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,7 +17,7 @@ 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:26-bookworm-slim@sha256:0042e17d232a87a2cd485be1da7900fca4d10a4ad11b29e9285da1d2e54798c9 AS runtime ARG CNOTES_VERSION=0.0.0 @@ -25,13 +25,13 @@ 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 01a50f7..2253765 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,6 @@ pnpm install pnpm dev # http://localhost:5173 ``` -Dev mode skips the setup token and two-factor. Data is stored in `apps/server/data/`. +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/compose.yaml b/compose.yaml index f681185..85f4db7 100644 --- a/compose.yaml +++ b/compose.yaml @@ -15,7 +15,7 @@ services: # so logs and rate limits see real client IPs. 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/docs/PLAN.md b/docs/PLAN.md index cae5d84..26a84be 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -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 | @@ -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 ``` diff --git a/docs/deployment.md b/docs/deployment.md index 45ab4c7..2127992 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -13,7 +13,7 @@ CI also publishes the image `ghcr.io/cedernaes/cnotes` from `main`. To use it in 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 `apps/server/.env.example`. +variables, see `src/backend/.env.example`. ## Nginx diff --git a/docs/development.md b/docs/development.md index 38368a5..1921707 100644 --- a/docs/development.md +++ b/docs/development.md @@ -4,13 +4,13 @@ Requires Node 26 (see `.nvmrc`) and pnpm (`npm install -g corepack && corepack e ```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. Data is stored in -`apps/server/data/`; delete it to start over. +`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. @@ -30,17 +30,17 @@ To run the production build locally (setup token and two-factor on): ```sh pnpm build -WEB_ROOT=../web/dist/client pnpm start # http://localhost:3000 +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 | ### How data flows diff --git a/eslint.config.js b/eslint.config.js index 782044f..690224c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -17,9 +17,9 @@ export default tseslint.config( ...tseslint.configs.recommended, { files: [ - 'apps/server/**/*.{ts,js}', - 'apps/web/scripts/**/*.js', - 'apps/web/*.ts', + 'src/backend/**/*.{ts,js}', + 'src/frontend/scripts/**/*.js', + 'src/frontend/*.ts', 'packages/**/*.ts', '*.js', '*.ts', @@ -27,7 +27,7 @@ export default tseslint.config( languageOptions: { globals: globals.node }, }, { - files: ['apps/web/**/*.{ts,tsx}'], + files: ['src/frontend/**/*.{ts,tsx}'], languageOptions: { globals: globals.browser }, plugins: { 'react-hooks': reactHooks }, rules: reactHooks.configs.recommended.rules, diff --git a/package.json b/package.json index 9fd03db..5428d5c 100644 --- a/package.json +++ b/package.json @@ -8,15 +8,15 @@ "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/pnpm-lock.yaml b/pnpm-lock.yaml index 587bdd2..b96f146 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -33,7 +33,16 @@ importers: specifier: ^5.1.2 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:* @@ -106,7 +115,7 @@ importers: specifier: ^4.23.15 version: 4.23.15 - apps/web: + src/frontend: dependencies: '@cnotes/shared': specifier: workspace:* @@ -206,15 +215,6 @@ importers: 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': 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 100% rename from apps/server/build.js rename to src/backend/build.js diff --git a/apps/server/package.json b/src/backend/package.json similarity index 97% rename from apps/server/package.json rename to src/backend/package.json index 31d1ce2..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", diff --git a/apps/server/src/app.ts b/src/backend/src/app.ts similarity index 100% rename from apps/server/src/app.ts rename to src/backend/src/app.ts diff --git a/apps/server/src/auth.ts b/src/backend/src/auth.ts similarity index 100% rename from apps/server/src/auth.ts rename to src/backend/src/auth.ts diff --git a/apps/server/src/backup.ts b/src/backend/src/backup.ts similarity index 100% rename from apps/server/src/backup.ts rename to src/backend/src/backup.ts diff --git a/apps/server/src/config.ts b/src/backend/src/config.ts similarity index 100% rename from apps/server/src/config.ts rename to src/backend/src/config.ts diff --git a/apps/server/src/db.ts b/src/backend/src/db.ts similarity index 100% rename from apps/server/src/db.ts rename to src/backend/src/db.ts diff --git a/apps/server/src/export.ts b/src/backend/src/export.ts similarity index 100% rename from apps/server/src/export.ts rename to src/backend/src/export.ts diff --git a/apps/server/src/files.ts b/src/backend/src/files.ts similarity index 100% rename from apps/server/src/files.ts rename to src/backend/src/files.ts diff --git a/apps/server/src/http.ts b/src/backend/src/http.ts similarity index 100% rename from apps/server/src/http.ts rename to src/backend/src/http.ts diff --git a/apps/server/src/index.ts b/src/backend/src/index.ts similarity index 100% rename from apps/server/src/index.ts rename to src/backend/src/index.ts diff --git a/apps/server/src/projection.ts b/src/backend/src/projection.ts similarity index 100% rename from apps/server/src/projection.ts rename to src/backend/src/projection.ts diff --git a/apps/server/src/routes/auth.ts b/src/backend/src/routes/auth.ts similarity index 100% rename from apps/server/src/routes/auth.ts rename to src/backend/src/routes/auth.ts diff --git a/apps/server/src/routes/files.ts b/src/backend/src/routes/files.ts similarity index 100% rename from apps/server/src/routes/files.ts rename to src/backend/src/routes/files.ts diff --git a/apps/server/src/routes/search.ts b/src/backend/src/routes/search.ts similarity index 100% rename from apps/server/src/routes/search.ts rename to src/backend/src/routes/search.ts diff --git a/apps/server/src/secrets.ts b/src/backend/src/secrets.ts similarity index 100% rename from apps/server/src/secrets.ts rename to src/backend/src/secrets.ts diff --git a/apps/server/src/sync.ts b/src/backend/src/sync.ts similarity index 100% rename from apps/server/src/sync.ts rename to src/backend/src/sync.ts diff --git a/apps/server/test/app.test.ts b/src/backend/test/app.test.ts similarity index 100% rename from apps/server/test/app.test.ts rename to src/backend/test/app.test.ts diff --git a/apps/server/test/auth.test.ts b/src/backend/test/auth.test.ts similarity index 100% rename from apps/server/test/auth.test.ts rename to src/backend/test/auth.test.ts diff --git a/apps/server/test/backup.test.ts b/src/backend/test/backup.test.ts similarity index 100% rename from apps/server/test/backup.test.ts rename to src/backend/test/backup.test.ts diff --git a/apps/server/test/helpers.ts b/src/backend/test/helpers.ts similarity index 100% rename from apps/server/test/helpers.ts rename to src/backend/test/helpers.ts diff --git a/apps/server/test/sync.test.ts b/src/backend/test/sync.test.ts similarity index 100% rename from apps/server/test/sync.test.ts rename to src/backend/test/sync.test.ts 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/apps/server/vitest.config.ts b/src/backend/vitest.config.ts similarity index 100% rename from apps/server/vitest.config.ts rename to src/backend/vitest.config.ts diff --git a/apps/web/e2e/auth.spec.ts b/src/frontend/e2e/auth.spec.ts similarity index 100% rename from apps/web/e2e/auth.spec.ts rename to src/frontend/e2e/auth.spec.ts diff --git a/apps/web/e2e/global-setup.ts b/src/frontend/e2e/global-setup.ts similarity index 100% rename from apps/web/e2e/global-setup.ts rename to src/frontend/e2e/global-setup.ts diff --git a/apps/web/e2e/helpers.ts b/src/frontend/e2e/helpers.ts similarity index 100% rename from apps/web/e2e/helpers.ts rename to src/frontend/e2e/helpers.ts diff --git a/apps/web/e2e/pages.spec.ts b/src/frontend/e2e/pages.spec.ts similarity index 100% rename from apps/web/e2e/pages.spec.ts rename to src/frontend/e2e/pages.spec.ts diff --git a/apps/web/e2e/smoke.spec.ts b/src/frontend/e2e/smoke.spec.ts similarity index 100% rename from apps/web/e2e/smoke.spec.ts rename to src/frontend/e2e/smoke.spec.ts 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/apps/web/playwright.config.ts b/src/frontend/playwright.config.ts similarity index 92% rename from apps/web/playwright.config.ts rename to src/frontend/playwright.config.ts index 00c93c1..fcd3223 100644 --- a/apps/web/playwright.config.ts +++ b/src/frontend/playwright.config.ts @@ -21,7 +21,7 @@ export default defineConfig({ // 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', + command: 'rm -rf test-results/e2e-data && node ../backend/dist/index.js', url: `http://localhost:${PORT}/api/health`, reuseExistingServer: false, env: { 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 100% rename from apps/web/public/manifest.webmanifest rename to src/frontend/public/manifest.webmanifest diff --git a/apps/web/scripts/generate-sw.js b/src/frontend/scripts/generate-sw.js similarity index 100% rename from apps/web/scripts/generate-sw.js rename to src/frontend/scripts/generate-sw.js diff --git a/apps/web/src/components/AuthScreens.tsx b/src/frontend/src/components/AuthScreens.tsx similarity index 100% rename from apps/web/src/components/AuthScreens.tsx rename to src/frontend/src/components/AuthScreens.tsx diff --git a/apps/web/src/components/Editor.tsx b/src/frontend/src/components/Editor.tsx similarity index 100% rename from apps/web/src/components/Editor.tsx rename to src/frontend/src/components/Editor.tsx diff --git a/apps/web/src/components/PageLink.tsx b/src/frontend/src/components/PageLink.tsx similarity index 100% rename from apps/web/src/components/PageLink.tsx rename to src/frontend/src/components/PageLink.tsx diff --git a/apps/web/src/components/SyncIndicator.tsx b/src/frontend/src/components/SyncIndicator.tsx similarity index 100% rename from apps/web/src/components/SyncIndicator.tsx rename to src/frontend/src/components/SyncIndicator.tsx diff --git a/apps/web/src/components/UpdatePrompt.tsx b/src/frontend/src/components/UpdatePrompt.tsx similarity index 100% rename from apps/web/src/components/UpdatePrompt.tsx rename to src/frontend/src/components/UpdatePrompt.tsx diff --git a/apps/web/src/components/editorExtensions.ts b/src/frontend/src/components/editorExtensions.ts similarity index 100% rename from apps/web/src/components/editorExtensions.ts rename to src/frontend/src/components/editorExtensions.ts diff --git a/apps/web/src/components/ui.tsx b/src/frontend/src/components/ui.tsx similarity index 100% rename from apps/web/src/components/ui.tsx rename to src/frontend/src/components/ui.tsx diff --git a/apps/web/src/lib/api.ts b/src/frontend/src/lib/api.ts similarity index 100% rename from apps/web/src/lib/api.ts rename to src/frontend/src/lib/api.ts diff --git a/apps/web/src/lib/auth.tsx b/src/frontend/src/lib/auth.tsx similarity index 100% rename from apps/web/src/lib/auth.tsx rename to src/frontend/src/lib/auth.tsx diff --git a/apps/web/src/lib/ids.ts b/src/frontend/src/lib/ids.ts similarity index 100% rename from apps/web/src/lib/ids.ts rename to src/frontend/src/lib/ids.ts diff --git a/apps/web/src/lib/sync.ts b/src/frontend/src/lib/sync.ts similarity index 100% rename from apps/web/src/lib/sync.ts rename to src/frontend/src/lib/sync.ts diff --git a/apps/web/src/lib/useCreatePage.ts b/src/frontend/src/lib/useCreatePage.ts similarity index 100% rename from apps/web/src/lib/useCreatePage.ts rename to src/frontend/src/lib/useCreatePage.ts diff --git a/apps/web/src/lib/useDoc.ts b/src/frontend/src/lib/useDoc.ts similarity index 100% rename from apps/web/src/lib/useDoc.ts rename to src/frontend/src/lib/useDoc.ts diff --git a/apps/web/src/lib/users.ts b/src/frontend/src/lib/users.ts similarity index 100% rename from apps/web/src/lib/users.ts rename to src/frontend/src/lib/users.ts diff --git a/apps/web/src/lib/workspace.ts b/src/frontend/src/lib/workspace.ts similarity index 100% rename from apps/web/src/lib/workspace.ts rename to src/frontend/src/lib/workspace.ts diff --git a/apps/web/src/routeTree.gen.ts b/src/frontend/src/routeTree.gen.ts similarity index 100% rename from apps/web/src/routeTree.gen.ts rename to src/frontend/src/routeTree.gen.ts diff --git a/apps/web/src/router.tsx b/src/frontend/src/router.tsx similarity index 100% rename from apps/web/src/router.tsx rename to src/frontend/src/router.tsx diff --git a/apps/web/src/routes/__root.tsx b/src/frontend/src/routes/__root.tsx similarity index 100% rename from apps/web/src/routes/__root.tsx rename to src/frontend/src/routes/__root.tsx diff --git a/apps/web/src/routes/about.tsx b/src/frontend/src/routes/about.tsx similarity index 100% rename from apps/web/src/routes/about.tsx rename to src/frontend/src/routes/about.tsx diff --git a/apps/web/src/routes/index.tsx b/src/frontend/src/routes/index.tsx similarity index 100% rename from apps/web/src/routes/index.tsx rename to src/frontend/src/routes/index.tsx diff --git a/apps/web/src/routes/p.$pageId.tsx b/src/frontend/src/routes/p.$pageId.tsx similarity index 100% rename from apps/web/src/routes/p.$pageId.tsx rename to src/frontend/src/routes/p.$pageId.tsx diff --git a/apps/web/src/routes/pages.tsx b/src/frontend/src/routes/pages.tsx similarity index 100% rename from apps/web/src/routes/pages.tsx rename to src/frontend/src/routes/pages.tsx diff --git a/apps/web/src/routes/search.tsx b/src/frontend/src/routes/search.tsx similarity index 100% rename from apps/web/src/routes/search.tsx rename to src/frontend/src/routes/search.tsx diff --git a/apps/web/src/routes/settings.tsx b/src/frontend/src/routes/settings.tsx similarity index 100% rename from apps/web/src/routes/settings.tsx rename to src/frontend/src/routes/settings.tsx diff --git a/apps/web/src/styles.css b/src/frontend/src/styles.css similarity index 100% rename from apps/web/src/styles.css rename to src/frontend/src/styles.css diff --git a/apps/web/tsconfig.json b/src/frontend/tsconfig.json similarity index 100% rename from apps/web/tsconfig.json rename to src/frontend/tsconfig.json diff --git a/apps/web/vite.config.ts b/src/frontend/vite.config.ts similarity index 92% rename from apps/web/vite.config.ts rename to src/frontend/vite.config.ts index 8dbef96..73c17ff 100644 --- a/apps/web/vite.config.ts +++ b/src/frontend/vite.config.ts @@ -10,7 +10,7 @@ export default defineConfig({ preview: { host: '127.0.0.1' }, server: { proxy: { - // The Fastify server (pnpm --filter @cnotes/server dev). Keep the Host + // The Fastify server (pnpm --filter @cnotes/backend dev). Keep the Host // header (changeOrigin: false) so the server's same-origin check passes. '/api': { target: 'http://127.0.0.1:3000', changeOrigin: false }, '/sync': { target: 'ws://127.0.0.1:3000', ws: true, changeOrigin: false }, diff --git a/vitest.config.ts b/vitest.config.ts index 28c4dc3..01db976 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,6 +2,6 @@ import { defineConfig } from 'vitest/config' export default defineConfig({ test: { - projects: ['apps/server', 'packages/shared'], + projects: ['src/backend', 'packages/shared'], }, }) From 0039131d32d4b71cf61d0451cb7d1952028c1bb3 Mon Sep 17 00:00:00 2001 From: Erasmus Cedernaes Date: Sun, 29 Nov 2026 17:25:40 +0100 Subject: [PATCH 15/18] Use double-quotes --- .github/dependabot.yml | 2 +- .github/workflows/ci.yml | 2 +- .prettierrc.json | 2 +- compose.yaml | 4 +- eslint.config.js | 34 +-- packages/shared/src/api.test.ts | 20 +- packages/shared/src/api.ts | 12 +- packages/shared/src/content.test.ts | 106 ++++---- packages/shared/src/content.ts | 146 +++++------ packages/shared/src/docs.test.ts | 88 +++---- packages/shared/src/docs.ts | 44 ++-- packages/shared/src/index.ts | 10 +- packages/shared/vitest.config.ts | 6 +- src/backend/build.js | 18 +- src/backend/src/app.ts | 108 ++++---- src/backend/src/auth.ts | 120 ++++----- src/backend/src/backup.ts | 16 +- src/backend/src/config.ts | 30 +-- src/backend/src/db.ts | 18 +- src/backend/src/export.ts | 30 +-- src/backend/src/files.ts | 54 ++-- src/backend/src/http.ts | 14 +- src/backend/src/index.ts | 8 +- src/backend/src/projection.ts | 18 +- src/backend/src/routes/auth.ts | 60 ++--- src/backend/src/routes/files.ts | 42 ++-- src/backend/src/routes/search.ts | 24 +- src/backend/src/secrets.ts | 46 ++-- src/backend/src/sync.ts | 62 ++--- src/backend/test/app.test.ts | 92 +++---- src/backend/test/auth.test.ts | 176 ++++++------- src/backend/test/backup.test.ts | 22 +- src/backend/test/helpers.ts | 50 ++-- src/backend/test/sync.test.ts | 162 ++++++------ src/backend/vitest.config.ts | 8 +- src/frontend/e2e/auth.spec.ts | 52 ++-- src/frontend/e2e/global-setup.ts | 30 +-- src/frontend/e2e/helpers.ts | 24 +- src/frontend/e2e/pages.spec.ts | 234 +++++++++--------- src/frontend/e2e/smoke.spec.ts | 60 ++--- src/frontend/playwright.config.ts | 24 +- src/frontend/scripts/generate-sw.js | 16 +- src/frontend/src/components/AuthScreens.tsx | 78 +++--- src/frontend/src/components/Editor.tsx | 66 ++--- src/frontend/src/components/PageLink.tsx | 12 +- src/frontend/src/components/SyncIndicator.tsx | 22 +- src/frontend/src/components/UpdatePrompt.tsx | 14 +- .../src/components/editorExtensions.ts | 44 ++-- src/frontend/src/components/ui.tsx | 30 +-- src/frontend/src/lib/api.ts | 4 +- src/frontend/src/lib/auth.tsx | 48 ++-- src/frontend/src/lib/ids.ts | 20 +- src/frontend/src/lib/sync.ts | 24 +- src/frontend/src/lib/useCreatePage.ts | 8 +- src/frontend/src/lib/useDoc.ts | 8 +- src/frontend/src/lib/users.ts | 12 +- src/frontend/src/lib/workspace.ts | 56 ++--- src/frontend/src/router.tsx | 8 +- src/frontend/src/routes/__root.tsx | 58 ++--- src/frontend/src/routes/about.tsx | 8 +- src/frontend/src/routes/index.tsx | 16 +- src/frontend/src/routes/p.$pageId.tsx | 44 ++-- src/frontend/src/routes/pages.tsx | 20 +- src/frontend/src/routes/search.tsx | 24 +- src/frontend/src/routes/settings.tsx | 56 ++--- src/frontend/src/styles.css | 18 +- src/frontend/vite.config.ts | 14 +- vitest.config.ts | 4 +- 68 files changed, 1405 insertions(+), 1405 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index e6f8797..3cb50ce 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -8,7 +8,7 @@ updates: default-days: 14 groups: tanstack: - patterns: ['@tanstack/*'] + patterns: ["@tanstack/*"] minor-and-patch: update-types: [minor, patch] - package-ecosystem: github-actions diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 29d2cf2..46c294e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,7 @@ name: CI on: push: branches: [main] - tags: ['v*'] + tags: ["v*"] pull_request: permissions: diff --git a/.prettierrc.json b/.prettierrc.json index 0965e7e..f313bb2 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,6 +1,6 @@ { "semi": false, - "singleQuote": true, + "singleQuote": false, "trailingComma": "all", "printWidth": 100 } diff --git a/compose.yaml b/compose.yaml index 85f4db7..a00bc18 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,11 +9,11 @@ services: 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 src/backend/.env.example: # CNOTES_SETUP_TOKEN: choose-a-token-for-the-first-account diff --git a/eslint.config.js b/eslint.config.js index 690224c..a1748f3 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,35 +1,35 @@ -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: [ - 'src/backend/**/*.{ts,js}', - 'src/frontend/scripts/**/*.js', - 'src/frontend/*.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: ['src/frontend/**/*.{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/packages/shared/src/api.test.ts b/packages/shared/src/api.test.ts index af3a349..f3c025a 100644 --- a/packages/shared/src/api.test.ts +++ b/packages/shared/src/api.test.ts @@ -1,14 +1,14 @@ -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 801d3d7..0950f8b 100644 --- a/packages/shared/src/api.ts +++ b/packages/shared/src/api.ts @@ -1,13 +1,13 @@ // 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 }) @@ -43,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 a743de5..6bb80a5 100644 --- a/packages/shared/src/content.test.ts +++ b/packages/shared/src/content.test.ts @@ -1,6 +1,6 @@ -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 @@ -16,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) } @@ -32,92 +32,92 @@ 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("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 45f49ff..3cfb001 100644 --- a/packages/shared/src/content.ts +++ b/packages/shared/src/content.ts @@ -1,7 +1,7 @@ // 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 @@ -15,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 += c.toString().replace(/<[^>]*>/g, "") else if (c instanceof Y.XmlElement) { - if (c.nodeName === 'hardBreak') out += '\n' + if (c.nodeName === "hardBreak") out += "\n" else out += inlineText(c) } } @@ -38,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) @@ -55,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 } { @@ -71,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) @@ -99,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 } } @@ -120,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})` } } @@ -160,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) } } @@ -169,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)})` @@ -178,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[] { @@ -192,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: @@ -253,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 50edd7c..507a607 100644 --- a/packages/shared/src/docs.test.ts +++ b/packages/shared/src/docs.test.ts @@ -1,5 +1,5 @@ -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, @@ -10,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, } @@ -31,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) => { @@ -69,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 4ad5905..0d33d8f 100644 --- a/packages/shared/src/docs.ts +++ b/packages/shared/src/docs.ts @@ -1,10 +1,10 @@ // 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}$/ @@ -16,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 } @@ -45,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 481a992..8c9029a 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1,10 +1,10 @@ -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 1f202a5..508c780 100644 --- a/packages/shared/vitest.config.ts +++ b/packages/shared/vitest.config.ts @@ -1,8 +1,8 @@ -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/src/backend/build.js b/src/backend/build.js index 38e57ba..c266970 100644 --- a/src/backend/build.js +++ b/src/backend/build.js @@ -1,18 +1,18 @@ // 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: 'node26', - 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/src/backend/src/app.ts b/src/backend/src/app.ts index dedd258..2b03f2b 100644 --- a/src/backend/src/app.ts +++ b/src/backend/src/app.ts @@ -1,27 +1,27 @@ -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({ @@ -38,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 @@ -55,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, { @@ -70,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'"], @@ -86,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 @@ -97,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 { @@ -116,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, @@ -132,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) { @@ -153,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, { @@ -177,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() @@ -190,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}`) @@ -200,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/src/backend/src/auth.ts b/src/backend/src/auth.ts index 001225f..194f645 100644 --- a/src/backend/src/auth.ts +++ b/src/backend/src/auth.ts @@ -1,9 +1,9 @@ -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 @@ -74,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 } @@ -93,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, @@ -114,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) } @@ -140,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) @@ -158,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, { @@ -168,7 +168,7 @@ export class AuthService { pendingSecret: secret, }) return { - step: 'enroll', + step: "enroll", challenge, secret, otpauthUrl: this.totp(row.username, secret).toString(), @@ -181,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))) })() @@ -204,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 @@ -267,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 { @@ -284,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) => ({ @@ -298,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), @@ -321,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 }) @@ -334,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 } @@ -350,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/src/backend/src/backup.ts b/src/backend/src/backup.ts index 0027bd8..3f8ec2a 100644 --- a/src/backend/src/backup.ts +++ b/src/backend/src/backup.ts @@ -1,7 +1,7 @@ -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. @@ -19,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() { @@ -40,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/src/backend/src/config.ts b/src/backend/src/config.ts index 05f77e3..6b540b3 100644 --- a/src/backend/src/config.ts +++ b/src/backend/src/config.ts @@ -1,4 +1,4 @@ -import path from 'node:path' +import path from "node:path" export interface Config { host: string @@ -12,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). */ @@ -24,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 @@ -34,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/src/backend/src/db.ts b/src/backend/src/db.ts index 91efe31..8dcd3b3 100644 --- a/src/backend/src/db.ts +++ b/src/backend/src/db.ts @@ -1,5 +1,5 @@ -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 @@ -79,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/src/backend/src/export.ts b/src/backend/src/export.ts index d427f28..0fdfb60 100644 --- a/src/backend/src/export.ts +++ b/src/backend/src/export.ts @@ -1,6 +1,6 @@ // 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, @@ -9,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 { @@ -43,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), { @@ -54,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/src/backend/src/files.ts b/src/backend/src/files.ts index b84009e..316421c 100644 --- a/src/backend/src/files.ts +++ b/src/backend/src/files.ts @@ -1,18 +1,18 @@ -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 @@ -42,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 { @@ -55,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 }) } @@ -64,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, @@ -92,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 }) @@ -115,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/src/backend/src/http.ts b/src/backend/src/http.ts index 528aedf..e88bb19 100644 --- a/src/backend/src/http.ts +++ b/src/backend/src/http.ts @@ -1,10 +1,10 @@ -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 } @@ -21,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 index 8bf4a43..6e15f01 100644 --- a/src/backend/src/index.ts +++ b/src/backend/src/index.ts @@ -1,12 +1,12 @@ -import { buildApp } from './app' -import { loadConfig } from './config' +import { buildApp } from "./app" +import { loadConfig } from "./config" const config = loadConfig() const app = await buildApp(config) -for (const signal of ['SIGINT', 'SIGTERM'] as const) { +for (const signal of ["SIGINT", "SIGTERM"] as const) { process.once(signal, () => { - app.log.info({ signal }, 'shutting down') + app.log.info({ signal }, "shutting down") void app.close().then(() => process.exit(0)) }) } diff --git a/src/backend/src/projection.ts b/src/backend/src/projection.ts index 53e8ac4..b13b36a 100644 --- a/src/backend/src/projection.ts +++ b/src/backend/src/projection.ts @@ -1,9 +1,9 @@ // 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) {} @@ -13,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 @@ -64,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/src/backend/src/routes/auth.ts b/src/backend/src/routes/auth.ts index f9b117e..e751a88 100644 --- a/src/backend/src/routes/auth.ts +++ b/src/backend/src/routes/auth.ts @@ -1,4 +1,4 @@ -import { Type } from '@sinclair/typebox' +import { Type } from "@sinclair/typebox" import { ApiError, AuthState, @@ -11,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 @@ -29,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), }) @@ -48,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, @@ -58,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 @@ -100,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 @@ -110,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() @@ -139,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 @@ -149,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(), ) @@ -157,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, @@ -166,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/src/backend/src/routes/files.ts b/src/backend/src/routes/files.ts index ae7ed24..109a520 100644 --- a/src/backend/src/routes/files.ts +++ b/src/backend/src/routes/files.ts @@ -1,11 +1,11 @@ -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, @@ -14,7 +14,7 @@ export async function fileRoutes( const authed = requireSession(opts.auth) app.post<{ Querystring: { pageId: string } }>( - '/files', + "/files", { preHandler: authed, schema: { @@ -23,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, @@ -41,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/src/backend/src/routes/search.ts b/src/backend/src/routes/search.ts index 0831a5f..16e7c6b 100644 --- a/src/backend/src/routes/search.ts +++ b/src/backend/src/routes/search.ts @@ -1,21 +1,21 @@ -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) { @@ -34,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 @@ -46,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 index 8ecc800..1b237ed 100644 --- a/src/backend/src/secrets.ts +++ b/src/backend/src/secrets.ts @@ -1,6 +1,6 @@ -import crypto from 'node:crypto' -import fs from 'node:fs' -import path from 'node:path' +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 @@ -10,49 +10,49 @@ import path from 'node:path' */ 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') + 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') + const file = path.join(dataDir, "secret.key") if (fs.existsSync(file)) { - const key = Buffer.from(fs.readFileSync(file, 'utf8').trim(), 'base64') + 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' }) + 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()]) + 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('.') + "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', + 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') + return crypto.randomBytes(bytes).toString("base64url") } export function sha256(data: string | Buffer): string { - return crypto.createHash('sha256').update(data).digest('hex') + return crypto.createHash("sha256").update(data).digest("hex") } export function timingSafeEqualStr(a: string, b: string): boolean { diff --git a/src/backend/src/sync.ts b/src/backend/src/sync.ts index e05b807..4675443 100644 --- a/src/backend/src/sync.ts +++ b/src/backend/src/sync.ts @@ -1,23 +1,23 @@ // 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 @@ -33,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 @@ -70,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") } } @@ -81,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() @@ -98,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() @@ -110,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) @@ -132,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 index 9deb731..a2ed5b5 100644 --- a/src/backend/test/app.test.ts +++ b/src/backend/test/app.test.ts @@ -1,24 +1,24 @@ -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' +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', () => { +describe("static app serving", () => { let webRoot: string let app: TestApp let cleanup: () => Promise beforeAll(async () => { - webRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cnotes-web-')) + webRoot = fs.mkdtempSync(path.join(os.tmpdir(), "cnotes-web-")) fs.writeFileSync( - path.join(webRoot, '_shell.html'), - 'cnotes', + path.join(webRoot, "_shell.html"), + "cnotes", ) - fs.mkdirSync(path.join(webRoot, 'assets')) - fs.writeFileSync(path.join(webRoot, 'assets', 'app-abc123.js'), 'console.log(1)') + fs.mkdirSync(path.join(webRoot, "assets")) + fs.writeFileSync(path.join(webRoot, "assets", "app-abc123.js"), "console.log(1)") ;({ app, cleanup } = await makeApp({ webRoot })) }) @@ -27,54 +27,54 @@ describe('static app serving', () => { fs.rmSync(webRoot, { recursive: true, force: true }) }) - it('reports health', async () => { - const res = await app.inject({ method: 'GET', url: '/api/health' }) + 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' }) + 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' }) + 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') + 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' }) + 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') + 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' }) + 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' }) + 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']) + 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).toContain(inlineScriptHashes("")[0]) expect(csp).not.toMatch(/script-src[^;]*unsafe-inline/) - expect(res.headers['x-content-type-options']).toBe('nosniff') + expect(res.headers["x-content-type-options"]).toBe("nosniff") }) - it('blocks cross-origin state-changing requests', async () => { + 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' }, + 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', () => { +describe("inlineScriptHashes", () => { + it("hashes inline scripts and skips external ones", () => { const html = '' const hashes = inlineScriptHashes(html) @@ -83,15 +83,15 @@ describe('inlineScriptHashes', () => { }) }) -describe('loadConfig', () => { - it('parses TRUST_PROXY', () => { +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') + 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') + 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 index 97b424e..4f49b9b 100644 --- a/src/backend/test/auth.test.ts +++ b/src/backend/test/auth.test.ts @@ -1,6 +1,6 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { deviceNameFromUserAgent } from '../src/auth' -import { cookieFrom, makeApp, SETUP_TOKEN, signUp, totpCode, type TestApp } from './helpers' +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 @@ -10,132 +10,132 @@ beforeEach(async () => { }) afterEach(async () => cleanup()) -const PASSWORD = 'correct horse battery' +const PASSWORD = "correct horse battery" async function login(username: string, password = PASSWORD) { - return app.inject({ method: 'POST', url: '/api/auth/login', payload: { username, 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' }) +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 }, + 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 }, + 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' }) + 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 () => { + 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' }, + 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') + 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 () => { +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' }) + 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' }, + method: "POST", + url: "/api/auth/setup", + payload: { username: "sara", password: "pw" }, }) expect(res.statusCode).toBe(201) - res = await login('sara', 'wrong') + res = await login("sara", "wrong") expect(res.statusCode).toBe(401) - res = await login('sara', 'pw') + res = await login("sara", "pw") expect(res.statusCode).toBe(200) - expect(res.json()).toMatchObject({ step: 'done', user: { username: 'sara' } }) + 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') + 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 () => { +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 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 step1 = await login("sara") + expect(step1.json().step).toBe("totp") const ok = await app.inject({ - method: 'POST', - url: '/api/auth/verify', + 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) + 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 () => { + 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!!') + 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 () => { + it("rejects a reused code", async () => { const { secret } = await signUp(app) const code = totpCode(secret, 1) - const first = await login('sara') + const first = await login("sara") expect( ( await app.inject({ - method: 'POST', - url: '/api/auth/verify', + method: "POST", + url: "/api/auth/verify", payload: { challenge: first.json().challenge, code }, }) ).statusCode, ).toBe(200) - const second = await login('sara') + const second = await login("sara") const replay = await app.inject({ - method: 'POST', - url: '/api/auth/verify', + method: "POST", + url: "/api/auth/verify", payload: { challenge: second.json().challenge, code }, }) expect(replay.statusCode).toBe(401) }) - it('accepts each recovery code once', async () => { + it("accepts each recovery code once", async () => { const { recoveryCodes } = await signUp(app) const use = async () => { - const step1 = await login('sara') + const step1 = await login("sara") return app.inject({ - method: 'POST', - url: '/api/auth/verify', + method: "POST", + url: "/api/auth/verify", payload: { challenge: step1.json().challenge, code: recoveryCodes[0]!.toUpperCase() }, }) } @@ -143,17 +143,17 @@ describe('sign-in with two-factor', () => { expect((await use()).statusCode).toBe(401) }) - it('limits attempts per challenge', async () => { + it("limits attempts per challenge", async () => { await signUp(app) - const { challenge } = (await login('sara')).json() + 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' }, + method: "POST", + url: "/api/auth/verify", + payload: { challenge, code: "000000" }, }) ).statusCode, ) @@ -162,70 +162,70 @@ describe('sign-in with two-factor', () => { }) }) -describe('sessions and members', () => { - it('lists and revokes sessions', async () => { +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 } }) + 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', + 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', + 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 () => { + 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 partner = await signUp(app, "alex", "another long password", sara.cookie) const users = await app.inject({ - method: 'GET', - url: '/api/auth/users', + method: "GET", + url: "/api/auth/users", headers: { cookie: partner.cookie }, }) - expect(users.json().map((u: { username: string }) => u.username)).toEqual(['sara', 'alex']) + expect(users.json().map((u: { username: string }) => u.username)).toEqual(["sara", "alex"]) }) - it('logs out', async () => { + 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 } }) + 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 () => { + it("changes the password", async () => { const { cookie } = await signUp(app) const res = await app.inject({ - method: 'POST', - url: '/api/auth/password', + method: "POST", + url: "/api/auth/password", headers: { cookie }, - payload: { currentPassword: PASSWORD, newPassword: 'a brand new password' }, + 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) + expect((await login("sara")).statusCode).toBe(401) + expect((await login("sara", "a brand new password")).statusCode).toBe(200) }) }) -describe('deviceNameFromUserAgent', () => { - it('names common devices', () => { +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', + "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') + ).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', + "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36", ), - ).toBe('Android · Chrome') + ).toBe("Android · Chrome") }) }) diff --git a/src/backend/test/backup.test.ts b/src/backend/test/backup.test.ts index ad2e558..3845942 100644 --- a/src/backend/test/backup.test.ts +++ b/src/backend/test/backup.test.ts @@ -1,7 +1,7 @@ -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 @@ -11,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/src/backend/test/helpers.ts b/src/backend/test/helpers.ts index 8963ca6..396d238 100644 --- a/src/backend/test/helpers.ts +++ b/src/backend/test/helpers.ts @@ -1,20 +1,20 @@ -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, }, @@ -27,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 { @@ -38,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/src/backend/test/sync.test.ts b/src/backend/test/sync.test.ts index 345d65f..2c800cb 100644 --- a/src/backend/test/sync.test.ts +++ b/src/backend/test/sync.test.ts @@ -1,10 +1,10 @@ -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 @@ -14,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` }) @@ -45,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)) } } @@ -60,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) }) } @@ -72,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. @@ -123,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`, @@ -254,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/src/backend/vitest.config.ts b/src/backend/vitest.config.ts index 5b3e79d..d3f09ad 100644 --- a/src/backend/vitest.config.ts +++ b/src/backend/vitest.config.ts @@ -1,9 +1,9 @@ -import { defineConfig } from 'vitest/config' +import { defineConfig } from "vitest/config" export default defineConfig({ test: { - name: 'server', - include: ['test/**/*.test.ts'], - environment: 'node', + name: "server", + include: ["test/**/*.test.ts"], + environment: "node", }, }) diff --git a/src/frontend/e2e/auth.spec.ts b/src/frontend/e2e/auth.spec.ts index 8629c5b..ecd6999 100644 --- a/src/frontend/e2e/auth.spec.ts +++ b/src/frontend/e2e/auth.spec.ts @@ -1,44 +1,44 @@ -import { expect, test } from '@playwright/test' -import { PASSWORD, STATE, totp, unique } from './helpers' +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 }) => { +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', + baseURL: "http://localhost:3100", }) - const username = unique('kid').replace(' ', '') - const created = await sara.request.post('/api/auth/users', { - data: { username, displayName: 'Kid', password: PASSWORD }, + 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 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 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 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() + 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.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() + 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') + await expect(page.getByTestId("sync-status")).toHaveAttribute("data-state", "synced") }) diff --git a/src/frontend/e2e/global-setup.ts b/src/frontend/e2e/global-setup.ts index f150378..80aaeb7 100644 --- a/src/frontend/e2e/global-setup.ts +++ b/src/frontend/e2e/global-setup.ts @@ -1,9 +1,9 @@ // 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, @@ -13,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)) @@ -32,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/src/frontend/e2e/helpers.ts b/src/frontend/e2e/helpers.ts index 68f0501..1868840 100644 --- a/src/frontend/e2e/helpers.ts +++ b/src/frontend/e2e/helpers.ts @@ -1,10 +1,10 @@ -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 { @@ -19,11 +19,11 @@ export function unique(prefix: string): string { } 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() @@ -32,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 index 792d293..6a0246e 100644 --- a/src/frontend/e2e/pages.spec.ts +++ b/src/frontend/e2e/pages.spec.ts @@ -1,20 +1,20 @@ -import path from 'node:path' -import { expect, test } from '@playwright/test' -import { unzipSync } from 'fflate' -import { newPage, signedInPage, STATE, unique, waitForSynced } from './helpers' +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') +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') + 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 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 @@ -22,181 +22,181 @@ test('shopping list: checklist, pin, open count, clear checked', async ({ page } .nth(1) .locator('input[type="checkbox"]') .check() - await expect(page.getByRole('button', { name: 'Clear checked (1)' })).toBeVisible() + 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("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 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') + 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') +test("Markdown shortcuts, subpages, move and archive", async ({ page }) => { + const parent = unique("Home appliances") await newPage(page, parent) - const editor = page.getByTestId('editor') + 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 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 }), + 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 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() + 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') +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) + 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'), + 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') + 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 ({ +test("search finds words inside pages, including parts of Swedish compound words", async ({ page, }) => { - const title = unique('Cleaning') + const title = unique("Cleaning") await newPage(page, title) - await page.getByTestId('editor').click() + 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() + 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 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) }), + 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() + 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') +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 page.getByTestId("editor").click() + await page.keyboard.type("[ ] Passports") await waitForSynced(page) - const alex = await signedInPage(browser, 'alex', info.project.name) + 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') + 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() + 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 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') +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 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') + 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 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) + const alex = await signedInPage(browser, "alex", info.project.name) await alex.page.goto(url) - await expect(alex.page.getByTestId('editor')).toContainText('Oat milk') + 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') +test("export contains the pages as Markdown", async ({ page }) => { + const title = unique("Export check") await newPage(page, title) - const editor = page.getByTestId('editor') + 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 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 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 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 index fc420df..824e2da 100644 --- a/src/frontend/e2e/smoke.spec.ts +++ b/src/frontend/e2e/smoke.spec.ts @@ -1,48 +1,48 @@ -import { expect, test } from '@playwright/test' -import { STATE } from './helpers' +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.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("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.describe("signed in", () => { test.use({ storageState: STATE.sara }) - test('home loads without errors and navigation works', async ({ page }) => { + 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("console", (msg) => { + if (msg.type() === "error") errors.push(msg.text()) }) - page.on('pageerror', (err) => errors.push(err.message)) + 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.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', + 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() + 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/src/frontend/playwright.config.ts b/src/frontend/playwright.config.ts index fcd3223..526ae06 100644 --- a/src/frontend/playwright.config.ts +++ b/src/frontend/playwright.config.ts @@ -1,35 +1,35 @@ -import { defineConfig, devices } from '@playwright/test' +import { defineConfig, devices } from "@playwright/test" export const PORT = 3100 -export const SETUP_TOKEN = 'e2e-setup-token' +export const SETUP_TOKEN = "e2e-setup-token" export default defineConfig({ - testDir: 'e2e', + 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', + reporter: process.env.CI ? "github" : "list", + globalSetup: "./e2e/global-setup.ts", use: { baseURL: `http://localhost:${PORT}`, - trace: 'off', + trace: "off", }, projects: [ - { name: 'iphone', use: { ...devices['iPhone 15'], browserName: 'chromium' } }, - { name: 'android', use: { ...devices['Pixel 7'] } }, + { 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', + 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', + WEB_ROOT: "dist/client", + DATA_DIR: "test-results/e2e-data", CNOTES_SETUP_TOKEN: SETUP_TOKEN, - LOG_LEVEL: 'warn', + LOG_LEVEL: "warn", }, }, }) diff --git a/src/frontend/scripts/generate-sw.js b/src/frontend/scripts/generate-sw.js index ed77b54..c2c929d 100644 --- a/src/frontend/scripts/generate-sw.js +++ b/src/frontend/scripts/generate-sw.js @@ -1,15 +1,15 @@ // 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, @@ -18,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/src/frontend/src/components/AuthScreens.tsx b/src/frontend/src/components/AuthScreens.tsx index b8b44fb..5ddbf2f 100644 --- a/src/frontend/src/components/AuthScreens.tsx +++ b/src/frontend/src/components/AuthScreens.tsx @@ -1,9 +1,9 @@ -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 ( @@ -19,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) } @@ -43,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, }, @@ -98,25 +98,25 @@ export function SetupScreen({ tokenRequired }: { tokenRequired: boolean }) { } type Step = - | { kind: 'password' } - | { kind: 'totp'; challenge: string } - | { kind: 'enroll'; challenge: string; secret: string; otpauthUrl: string } - | { kind: 'recovery'; user: PublicUser; codes: string[] } + | { kind: "password" } + | { kind: "totp"; challenge: string } + | { kind: "enroll"; challenge: string; secret: string; otpauthUrl: string } + | { kind: "recovery"; user: PublicUser; codes: string[] } export function LoginScreen({ initial }: { initial?: { username: string; password: string } }) { const { signedIn } = useAuth() - const [step, setStep] = useState({ 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(() => { @@ -124,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 ( @@ -156,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) @@ -188,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 @@ -197,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 ?? [] }) }) } /> @@ -230,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]) @@ -262,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" > @@ -303,10 +303,10 @@ function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void diff --git a/src/frontend/src/components/Editor.tsx b/src/frontend/src/components/Editor.tsx index da4804a..ce2c021 100644 --- a/src/frontend/src/components/Editor.tsx +++ b/src/frontend/src/components/Editor.tsx @@ -1,13 +1,13 @@ -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 @@ -20,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 } @@ -32,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) @@ -44,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) @@ -63,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 @@ -74,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 @@ -104,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, }), }) @@ -132,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 { @@ -155,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) @@ -231,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…

} @@ -271,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 }) { @@ -25,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/src/frontend/src/components/SyncIndicator.tsx b/src/frontend/src/components/SyncIndicator.tsx index 9e228ee..b8303a3 100644 --- a/src/frontend/src/components/SyncIndicator.tsx +++ b/src/frontend/src/components/SyncIndicator.tsx @@ -1,16 +1,16 @@ -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 @@ -19,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/src/frontend/src/components/UpdatePrompt.tsx b/src/frontend/src/components/UpdatePrompt.tsx index c5f47c9..8446786 100644 --- a/src/frontend/src/components/UpdatePrompt.tsx +++ b/src/frontend/src/components/UpdatePrompt.tsx @@ -1,5 +1,5 @@ -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() { @@ -7,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/src/frontend/src/components/editorExtensions.ts b/src/frontend/src/components/editorExtensions.ts index 42a3c4c..4ab62b2 100644 --- a/src/frontend/src/components/editorExtensions.ts +++ b/src/frontend/src/components/editorExtensions.ts @@ -1,44 +1,44 @@ -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)}` : ""}`, ] }, }) @@ -48,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/src/frontend/src/components/ui.tsx b/src/frontend/src/components/ui.tsx index 3ae9fe9..3e6b309 100644 --- a/src/frontend/src/components/ui.tsx +++ b/src/frontend/src/components/ui.tsx @@ -1,19 +1,19 @@ -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/src/frontend/src/routes/search.tsx b/src/frontend/src/routes/search.tsx index e58c985..09bd28a 100644 --- a/src/frontend/src/routes/search.tsx +++ b/src/frontend/src/routes/search.tsx @@ -1,13 +1,13 @@ -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, }) @@ -20,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 ) : ( @@ -40,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/src/frontend/src/routes/settings.tsx b/src/frontend/src/routes/settings.tsx index 6e831af..8e1475a 100644 --- a/src/frontend/src/routes/settings.tsx +++ b/src/frontend/src/routes/settings.tsx @@ -1,11 +1,11 @@ -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,8 +42,8 @@ function Settings() {

About cnotes - {' '} - ·{' '} + {" "} + ·{" "} Source code @@ -58,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) => { @@ -152,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 (

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