forked from mirror/crumbs-original
Compare commits
@@ -44,3 +44,4 @@ todo.md
|
||||
|
||||
# Worktrees
|
||||
.worktrees/
|
||||
package-lock.json
|
||||
|
||||
@@ -163,6 +163,13 @@ GitHub Actions with two workflows:
|
||||
|
||||
**Docker**: Multi-stage Dockerfile (node:22-slim), exposes port 3000, persists data to `/data` volume.
|
||||
|
||||
## Database schema changes
|
||||
|
||||
When adding or modifying tables in `src/lib/server/db/schema.ts`:
|
||||
|
||||
- **If the table has a foreign key to `users`**: update `deleteUser()` in `src/lib/server/auth.ts` to delete from the new table before the user row is removed. Order matters — delete child rows before parent rows.
|
||||
- **If the table has a foreign key to `notes`**: either add `onDelete: 'cascade'` in the schema definition, or add explicit cleanup in the note deletion logic.
|
||||
|
||||
## Testing philosophy: BDD/TDD
|
||||
|
||||
Write tests first or alongside features. Tests serve as living documentation of expected behavior.
|
||||
@@ -180,6 +187,7 @@ Write tests first or alongside features. Tests serve as living documentation of
|
||||
- Test database: `./data/test-crumbs.db` (cleaned via `global-setup.ts`)
|
||||
- Auth fixture: `tests/e2e/helpers/fixtures.ts` provides `authenticatedPage` (handles setup/login race conditions across parallel workers)
|
||||
- Auth tests use `test.describe.serial` because they depend on sequential database state
|
||||
- **Offline/online tests**: After `setOffline(false)`, always manually dispatch the `online` event via `page.evaluate(() => window.dispatchEvent(new Event('online')))` — Playwright doesn't reliably emit it in headless/CI environments, causing flaky `waitForResponse` timeouts
|
||||
|
||||
### Gherkin-style Given/When/Then
|
||||
|
||||
|
||||
@@ -46,6 +46,21 @@ volumes:
|
||||
|
||||
Google and GitHub OAuth are also supported. See [docs/AUTH.md](docs/AUTH.md) for all providers and setup guides.
|
||||
|
||||
#### With Email Notifications (optional)
|
||||
|
||||
Add SMTP settings to enable email notifications (share alerts, welcome emails, security alerts):
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
- SMTP_HOST=smtp.example.com
|
||||
- SMTP_PORT=587
|
||||
- SMTP_USER=your-username
|
||||
- SMTP_PASS=your-password
|
||||
- SMTP_FROM=Crumbs <noreply@example.com>
|
||||
```
|
||||
|
||||
Auto-enabled when `SMTP_HOST` is set. Users can opt out in Settings > Preferences. See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md#email-notifications-optional) for details.
|
||||
|
||||
### Manual (Node.js)
|
||||
|
||||
```bash
|
||||
@@ -75,6 +90,9 @@ pnpm build # Production build
|
||||
- Rich notes with Markdown, checklists, image attachments, and 12 color themes
|
||||
- Organize with #tags, pinning, archive, and trash
|
||||
- Full-text search across titles, content, and tags
|
||||
- Note version history — browse and restore previous versions
|
||||
- Share notes with other users on the same instance
|
||||
- Email notifications for shares, security alerts, and account events (optional SMTP)
|
||||
- PWA — installable, works offline via IndexedDB + LWW CRDT sync
|
||||
- MCP server — let AI assistants (Claude Code, etc.) manage your notes
|
||||
- Multi-user auth (Argon2) with optional OAuth/SSO (Google, GitHub, OIDC)
|
||||
|
||||
+11
-1
@@ -1,6 +1,6 @@
|
||||
services:
|
||||
crumbs:
|
||||
image: ghcr.io/bretzel-app/crumbs:0.19.3
|
||||
image: ghcr.io/bretzel-app/crumbs:0.21.7
|
||||
container_name: crumbs
|
||||
ports:
|
||||
- "3000:3000"
|
||||
@@ -11,6 +11,16 @@ services:
|
||||
- DATA_DIR=/data
|
||||
- DATABASE_URL=/data/crumbs.db
|
||||
- ORIGIN=${ORIGIN:-http://localhost:3000}
|
||||
# OAuth / SSO (optional — providers auto-enable when configured)
|
||||
- AUTH_GOOGLE_CLIENT_ID=${AUTH_GOOGLE_CLIENT_ID:-}
|
||||
- AUTH_GOOGLE_CLIENT_SECRET=${AUTH_GOOGLE_CLIENT_SECRET:-}
|
||||
- AUTH_GITHUB_CLIENT_ID=${AUTH_GITHUB_CLIENT_ID:-}
|
||||
- AUTH_GITHUB_CLIENT_SECRET=${AUTH_GITHUB_CLIENT_SECRET:-}
|
||||
- AUTH_OIDC_ISSUER=${AUTH_OIDC_ISSUER:-}
|
||||
- AUTH_OIDC_CLIENT_ID=${AUTH_OIDC_CLIENT_ID:-}
|
||||
- AUTH_OIDC_CLIENT_SECRET=${AUTH_OIDC_CLIENT_SECRET:-}
|
||||
- AUTH_OIDC_DISPLAY_NAME=${AUTH_OIDC_DISPLAY_NAME:-}
|
||||
# Email notifications (optional — auto-enabled when SMTP_HOST is set)
|
||||
- SMTP_HOST=${SMTP_HOST:-}
|
||||
- SMTP_PORT=${SMTP_PORT:-587}
|
||||
- SMTP_USER=${SMTP_USER:-}
|
||||
|
||||
+1
-1
@@ -116,7 +116,7 @@ Google, GitHub, and generic OIDC (Authentik, Keycloak, Okta, etc.) are supported
|
||||
|
||||
### Email Notifications (optional)
|
||||
|
||||
Email notifications are sent when a note is shared with a user. Auto-enabled when `SMTP_HOST` is set.
|
||||
Email notifications are auto-enabled when `SMTP_HOST` is set. See [FEATURES.md](FEATURES.md#note-sharing--collaboration) for the full list of notification types.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
|
||||
+16
-1
@@ -91,7 +91,22 @@
|
||||
- Share dialog accessible from editor toolbar
|
||||
- Collaborators can leave shared notes
|
||||
- Shared notes appear mixed in main list alongside owned notes
|
||||
- Email notifications when a note is shared with you (requires SMTP config, opt-out in preferences)
|
||||
- Email notifications (requires SMTP config, opt-out in preferences):
|
||||
- Share notifications when a note is shared with you
|
||||
- Welcome email when admin creates your account
|
||||
- Password reset notification
|
||||
- Account deletion confirmation
|
||||
- Email address change notification
|
||||
- Role change notification (admin/user)
|
||||
- Removed from shared note notification
|
||||
- Shared note permanently deleted notification
|
||||
- Account locked alert (after failed login attempts)
|
||||
|
||||
### Note Version History
|
||||
- Browse previous versions of any note
|
||||
- Versions are automatically saved when content changes
|
||||
- Restore any previous version with one click
|
||||
- Version snapshots are only created when content actually changes (not on metadata-only updates)
|
||||
|
||||
### Full-Text Search
|
||||
- Search across note titles, content, and tags
|
||||
|
||||
+6
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "crumbs",
|
||||
"private": true,
|
||||
"version": "0.20.0",
|
||||
"version": "0.21.8",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"author": "Bretzel (https://bretzel.app)",
|
||||
@@ -54,6 +54,7 @@
|
||||
"idb": "^8.0.3",
|
||||
"lucide-svelte": "^0.577.0",
|
||||
"markdown-it": "^14.1.1",
|
||||
"node-diff3": "^3.2.0",
|
||||
"nodemailer": "^8.0.2",
|
||||
"svelte-dnd-action": "^0.9.69",
|
||||
"tiptap-markdown": "^0.9.0",
|
||||
@@ -83,7 +84,9 @@
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.3.1",
|
||||
"vite-plugin-istanbul": "^7.2.1",
|
||||
"vite-plugin-pwa": "^1.2.0",
|
||||
"vitest": "^3.2.4",
|
||||
"workbox-window": "^7.4.0",
|
||||
"yaml": "^2.8.2"
|
||||
},
|
||||
"pnpm": {
|
||||
@@ -95,7 +98,8 @@
|
||||
"overrides": {
|
||||
"serialize-javascript": ">=7.0.3",
|
||||
"esbuild@<0.25.0": "0.25.12",
|
||||
"cookie": ">=0.7.0"
|
||||
"cookie": ">=0.7.0",
|
||||
"hono": ">=4.12.7"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ export default defineConfig({
|
||||
use: {
|
||||
baseURL: 'http://localhost:4173',
|
||||
trace: 'on-first-retry',
|
||||
screenshot: 'only-on-failure'
|
||||
screenshot: 'only-on-failure',
|
||||
serviceWorkers: 'block'
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
|
||||
Generated
+24
-8
@@ -8,6 +8,7 @@ overrides:
|
||||
serialize-javascript: '>=7.0.3'
|
||||
esbuild@<0.25.0: 0.25.12
|
||||
cookie: '>=0.7.0'
|
||||
hono: '>=4.12.7'
|
||||
|
||||
importers:
|
||||
|
||||
@@ -79,6 +80,9 @@ importers:
|
||||
markdown-it:
|
||||
specifier: ^14.1.1
|
||||
version: 14.1.1
|
||||
node-diff3:
|
||||
specifier: ^3.2.0
|
||||
version: 3.2.0
|
||||
nodemailer:
|
||||
specifier: ^8.0.2
|
||||
version: 8.0.2
|
||||
@@ -161,9 +165,15 @@ importers:
|
||||
vite-plugin-istanbul:
|
||||
specifier: ^7.2.1
|
||||
version: 7.2.1(vite@7.3.1(@types/node@25.3.5)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vite-plugin-pwa:
|
||||
specifier: ^1.2.0
|
||||
version: 1.2.0(vite@7.3.1(@types/node@25.3.5)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))(workbox-build@7.4.0)(workbox-window@7.4.0)
|
||||
vitest:
|
||||
specifier: ^3.2.4
|
||||
version: 3.2.4(@types/node@25.3.5)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
workbox-window:
|
||||
specifier: ^7.4.0
|
||||
version: 7.4.0
|
||||
yaml:
|
||||
specifier: ^2.8.2
|
||||
version: 2.8.2
|
||||
@@ -1006,7 +1016,7 @@ packages:
|
||||
resolution: {integrity: sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==}
|
||||
engines: {node: '>=18.14.1'}
|
||||
peerDependencies:
|
||||
hono: ^4
|
||||
hono: '>=4.12.7'
|
||||
|
||||
'@isaacs/cliui@8.0.2':
|
||||
resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
|
||||
@@ -2502,8 +2512,8 @@ packages:
|
||||
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
hono@4.12.5:
|
||||
resolution: {integrity: sha512-3qq+FUBtlTHhtYxbxheZgY8NIFnkkC/MR8u5TTsr7YZ3wixryQ3cCwn3iZbg8p8B88iDBBAYSfZDS75t8MN7Vg==}
|
||||
hono@4.12.7:
|
||||
resolution: {integrity: sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw==}
|
||||
engines: {node: '>=16.9.0'}
|
||||
|
||||
html-escaper@2.0.2:
|
||||
@@ -3003,6 +3013,10 @@ packages:
|
||||
resolution: {integrity: sha512-gBVjCaqDlRUk0EwoPNKzIr9KkS9041G/q31IBShPs1Xz6UTA+EXdZADbzqAJQrpDRq71CIMnOP5VMut3SL0z5Q==}
|
||||
engines: {node: ^18 || ^20 || >= 21}
|
||||
|
||||
node-diff3@3.2.0:
|
||||
resolution: {integrity: sha512-vLh2xJFSyniBLYDEDbXKqD32fQ5vAxmYT4hco8t0EHQ4CQ4BDHhshi7kdvDc6Y1MwGSi1Mhl4unUukPbCayZdw==}
|
||||
engines: {bun: '>=1.3.0', node: '>=18'}
|
||||
|
||||
node-gyp-build@4.8.4:
|
||||
resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==}
|
||||
hasBin: true
|
||||
@@ -4833,9 +4847,9 @@ snapshots:
|
||||
'@esbuild/win32-x64@0.27.3':
|
||||
optional: true
|
||||
|
||||
'@hono/node-server@1.19.11(hono@4.12.5)':
|
||||
'@hono/node-server@1.19.11(hono@4.12.7)':
|
||||
dependencies:
|
||||
hono: 4.12.5
|
||||
hono: 4.12.7
|
||||
|
||||
'@isaacs/cliui@8.0.2':
|
||||
dependencies:
|
||||
@@ -4884,7 +4898,7 @@ snapshots:
|
||||
|
||||
'@modelcontextprotocol/sdk@1.27.1(zod@4.3.6)':
|
||||
dependencies:
|
||||
'@hono/node-server': 1.19.11(hono@4.12.5)
|
||||
'@hono/node-server': 1.19.11(hono@4.12.7)
|
||||
ajv: 8.18.0
|
||||
ajv-formats: 3.0.1(ajv@8.18.0)
|
||||
content-type: 1.0.5
|
||||
@@ -4894,7 +4908,7 @@ snapshots:
|
||||
eventsource-parser: 3.0.6
|
||||
express: 5.2.1
|
||||
express-rate-limit: 8.3.0(express@5.2.1)
|
||||
hono: 4.12.5
|
||||
hono: 4.12.7
|
||||
jose: 6.2.0
|
||||
json-schema-typed: 8.0.2
|
||||
pkce-challenge: 5.0.1
|
||||
@@ -6336,7 +6350,7 @@ snapshots:
|
||||
dependencies:
|
||||
function-bind: 1.1.2
|
||||
|
||||
hono@4.12.5: {}
|
||||
hono@4.12.7: {}
|
||||
|
||||
html-escaper@2.0.2: {}
|
||||
|
||||
@@ -6779,6 +6793,8 @@ snapshots:
|
||||
|
||||
node-addon-api@8.6.0: {}
|
||||
|
||||
node-diff3@3.2.0: {}
|
||||
|
||||
node-gyp-build@4.8.4: {}
|
||||
|
||||
node-preload@0.2.1:
|
||||
|
||||
Vendored
+3
@@ -1,3 +1,6 @@
|
||||
/// <reference types="vite-plugin-pwa/info" />
|
||||
/// <reference types="vite-plugin-pwa/vanillajs" />
|
||||
|
||||
// See https://svelte.dev/docs/kit/types#app.d.ts
|
||||
// for information about these interfaces
|
||||
declare global {
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
<link rel="shortcut icon" href="/favicon.ico" />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
|
||||
<meta name="apple-mobile-web-app-title" content="Crumbs" />
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<title>Crumbs</title>
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { NOTE_COLORS } from '$lib/utils/colors.js';
|
||||
import { renderMarkdown } from '$lib/utils/markdown.js';
|
||||
import { togglePin, trashNote, archiveNote, unarchiveNote, restoreNote, deleteNote, updateNote, leaveNote, currentFilter } from '$lib/stores/notes.js';
|
||||
import { togglePin, trashNote, archiveNote, unarchiveNote, restoreNote, deleteNote, leaveNote, currentFilter } from '$lib/stores/notes.js';
|
||||
import ImageLightbox from './ImageLightbox.svelte';
|
||||
import CollaboratorPopover from './CollaboratorPopover.svelte';
|
||||
import type { Note } from '$lib/types/index.js';
|
||||
@@ -58,20 +58,6 @@
|
||||
};
|
||||
}
|
||||
|
||||
function toggleChecklistItem(item: ChecklistItem) {
|
||||
const lines = note.content.split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const text = line.replace(/^- \[[ x]\] /, '');
|
||||
if (text === item.text && line.startsWith(item.checked ? '- [x] ' : '- [ ] ')) {
|
||||
lines[i] = item.checked
|
||||
? `- [ ] ${text}`
|
||||
: `- [x] ${text}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
updateNote(note.id, { content: lines.join('\n') });
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_to_interactive_role -->
|
||||
@@ -144,8 +130,8 @@
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={item.checked}
|
||||
onclick={(e) => { e.stopPropagation(); toggleChecklistItem(item); }}
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 rounded border-[var(--border-subtle)] text-[var(--primary)] cursor-pointer"
|
||||
disabled
|
||||
class="mt-0.5 h-3.5 w-3.5 shrink-0 rounded border-[var(--border-subtle)] text-[var(--primary)]"
|
||||
data-testid="card-checklist-checkbox"
|
||||
/>
|
||||
<span class="break-words min-w-0">{item.text}</span>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import ColorPicker from './ColorPicker.svelte';
|
||||
import Checklist from './Checklist.svelte';
|
||||
import FormattingToolbar from './FormattingToolbar.svelte';
|
||||
@@ -56,6 +57,15 @@
|
||||
// svelte-ignore state_referenced_locally
|
||||
let attachmentsList = $state<Attachment[]>(note?.attachments ?? []);
|
||||
|
||||
// Guard against mobile ghost clicks: on touch devices, a tap on the note card
|
||||
// can produce a synthetic click that lands on editor buttons rendered at the same
|
||||
// coordinates. Suppress pointer events on toolbar controls until mount completes.
|
||||
let toolbarInteractive = $state(false);
|
||||
onMount(() => {
|
||||
const timer = setTimeout(() => { toolbarInteractive = true; }, 150);
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
|
||||
let showShareDialog = $state(false);
|
||||
let showHistory = $state(false);
|
||||
// svelte-ignore state_referenced_locally
|
||||
@@ -170,36 +180,19 @@
|
||||
bgStyle = `background-color: ${colors.bg}`;
|
||||
});
|
||||
|
||||
// Track whether mousedown started on the overlay (not inside the editor).
|
||||
// Prevents closing when the user selects text inside the editor and
|
||||
// releases the mouse outside — the click event fires on the overlay,
|
||||
// but we only want to close if the press also started there.
|
||||
let mousedownOnOverlay = false;
|
||||
// Use pointer events to detect backdrop clicks. Unlike mouse events,
|
||||
// pointer events are never synthetically re-dispatched from touch, so
|
||||
// the tap that opened the editor on mobile cannot ghost-click the overlay.
|
||||
// Both pointerdown and pointerup must target the overlay itself to close.
|
||||
let pointerdownOnOverlay = false;
|
||||
|
||||
// On mobile, the tap that opens the editor produces synthetic mouse events
|
||||
// (mousedown → mouseup → click) at the original touch coordinates. If those
|
||||
// coordinates land on the overlay backdrop, the editor would close instantly.
|
||||
// Guard against this by ignoring mousedowns that arrive within the first
|
||||
// animation frame after mount.
|
||||
let overlayReady = false;
|
||||
$effect(() => {
|
||||
const id = requestAnimationFrame(() => {
|
||||
overlayReady = true;
|
||||
});
|
||||
return () => {
|
||||
overlayReady = false;
|
||||
cancelAnimationFrame(id);
|
||||
};
|
||||
});
|
||||
|
||||
function handleOverlayMousedown(e: MouseEvent) {
|
||||
if (!overlayReady) return;
|
||||
mousedownOnOverlay = e.target === e.currentTarget;
|
||||
function handleOverlayPointerdown(e: PointerEvent) {
|
||||
pointerdownOnOverlay = e.target === e.currentTarget;
|
||||
}
|
||||
|
||||
function handleOverlayClick() {
|
||||
if (mousedownOnOverlay) saveAndClose();
|
||||
mousedownOnOverlay = false;
|
||||
function handleOverlayPointerup(e: PointerEvent) {
|
||||
if (pointerdownOnOverlay && e.target === e.currentTarget) saveAndClose();
|
||||
pointerdownOnOverlay = false;
|
||||
}
|
||||
|
||||
async function saveAndClose() {
|
||||
@@ -263,8 +256,8 @@
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="fixed inset-0 z-40 flex items-start justify-center overflow-y-auto bg-black/50 pt-20 pb-10 animate-[fade-in_150ms_ease-out]"
|
||||
onmousedown={handleOverlayMousedown}
|
||||
onclick={handleOverlayClick}
|
||||
onpointerdown={handleOverlayPointerdown}
|
||||
onpointerup={handleOverlayPointerup}
|
||||
onkeydown={handleKeydown}
|
||||
data-testid="note-editor-overlay"
|
||||
>
|
||||
@@ -272,7 +265,6 @@
|
||||
<div
|
||||
class="mx-4 flex w-full max-w-xl md:max-w-2xl flex-col overflow-hidden rounded-sm border border-[var(--border)] shadow-[var(--card-shadow)] animate-[pop-in_150ms_ease-out]"
|
||||
style={bgStyle}
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => { e.stopPropagation(); handleKeydown(e); }}
|
||||
data-testid="note-editor"
|
||||
>
|
||||
@@ -334,11 +326,16 @@
|
||||
|
||||
<!-- Formatting toolbar -->
|
||||
{#if !rawMarkdownMode && !checklistMode}
|
||||
<FormattingToolbar editor={tiptapEditor} tick={editorTick} />
|
||||
<div style={toolbarInteractive ? '' : 'pointer-events: none'}>
|
||||
<FormattingToolbar editor={tiptapEditor} tick={editorTick} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Toolbar -->
|
||||
<div class="flex items-center justify-between border-t border-[var(--border-subtle)] px-2 py-2">
|
||||
<div
|
||||
class="flex items-center justify-between border-t border-[var(--border-subtle)] px-2 py-2"
|
||||
style={toolbarInteractive ? '' : 'pointer-events: none'}
|
||||
>
|
||||
<div class="flex items-center gap-1">
|
||||
<!-- Color picker toggle -->
|
||||
<div class="relative">
|
||||
|
||||
@@ -228,6 +228,12 @@ export function getUser(userId: number): User | null {
|
||||
|
||||
export async function deleteUser(userId: number): Promise<void> {
|
||||
// Cascade: delete user's data in dependency order
|
||||
sqlite.prepare('DELETE FROM user_preferences WHERE user_id = ?').run(userId);
|
||||
sqlite.prepare('DELETE FROM api_keys WHERE user_id = ?').run(userId);
|
||||
sqlite.prepare('DELETE FROM note_user_state WHERE user_id = ?').run(userId);
|
||||
sqlite
|
||||
.prepare('DELETE FROM note_collaborators WHERE user_id = ? OR added_by = ?')
|
||||
.run(userId, userId);
|
||||
sqlite.prepare('DELETE FROM sync_log WHERE user_id = ?').run(userId);
|
||||
sqlite.prepare('DELETE FROM attachments WHERE user_id = ?').run(userId);
|
||||
sqlite
|
||||
|
||||
+252
-15
@@ -65,6 +65,125 @@ export async function sendShareNotification(
|
||||
await sendEmail(toEmail, subject, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a welcome email to a newly created user.
|
||||
*/
|
||||
export async function sendWelcomeEmail(
|
||||
toEmail: string,
|
||||
toName: string,
|
||||
appUrl: string
|
||||
): Promise<void> {
|
||||
if (!toEmail) return;
|
||||
|
||||
const subject = 'Welcome to Crumbs';
|
||||
const html = buildWelcomeEmailHtml(toName, appUrl);
|
||||
await sendEmail(toEmail, subject, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a password reset notification to a user (triggered by admin reset).
|
||||
*/
|
||||
export async function sendPasswordResetEmail(
|
||||
toEmail: string,
|
||||
toName: string,
|
||||
appUrl: string
|
||||
): Promise<void> {
|
||||
if (!toEmail) return;
|
||||
|
||||
const subject = 'Your Crumbs password has been reset';
|
||||
const html = buildPasswordResetEmailHtml(toName, appUrl);
|
||||
await sendEmail(toEmail, subject, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an account deletion confirmation email.
|
||||
*/
|
||||
export async function sendAccountDeletedEmail(toEmail: string, toName: string): Promise<void> {
|
||||
if (!toEmail) return;
|
||||
|
||||
const subject = 'Your Crumbs account has been deleted';
|
||||
const html = buildAccountDeletedEmailHtml(toName);
|
||||
await sendEmail(toEmail, subject, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification to the old email when the account email address changes.
|
||||
*/
|
||||
export async function sendEmailChangedEmail(
|
||||
oldEmail: string,
|
||||
toName: string,
|
||||
newEmail: string
|
||||
): Promise<void> {
|
||||
if (!oldEmail) return;
|
||||
|
||||
const subject = 'Your Crumbs email address has been changed';
|
||||
const html = buildEmailChangedEmailHtml(toName, newEmail);
|
||||
await sendEmail(oldEmail, subject, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a role change notification to a user.
|
||||
*/
|
||||
export async function sendRoleChangedEmail(
|
||||
toEmail: string,
|
||||
toName: string,
|
||||
newRole: 'admin' | 'user',
|
||||
appUrl: string
|
||||
): Promise<void> {
|
||||
if (!toEmail) return;
|
||||
|
||||
const subject = 'Your Crumbs account role has been updated';
|
||||
const html = buildRoleChangedEmailHtml(toName, newRole, appUrl);
|
||||
await sendEmail(toEmail, subject, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification to a collaborator that they have been removed from a note.
|
||||
*/
|
||||
export async function sendCollaboratorRemovedEmail(
|
||||
toEmail: string,
|
||||
toName: string,
|
||||
ownerName: string,
|
||||
noteTitle: string,
|
||||
appUrl: string
|
||||
): Promise<void> {
|
||||
if (!toEmail) return;
|
||||
|
||||
const subject = `You've been removed from a shared note`;
|
||||
const html = buildCollaboratorRemovedEmailHtml(toName, ownerName, noteTitle, appUrl);
|
||||
await sendEmail(toEmail, subject, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification to collaborators that a shared note has been permanently deleted.
|
||||
*/
|
||||
export async function sendNotePermanentlyDeletedEmail(
|
||||
toEmail: string,
|
||||
toName: string,
|
||||
noteTitle: string
|
||||
): Promise<void> {
|
||||
if (!toEmail) return;
|
||||
|
||||
const subject = `A shared note has been deleted`;
|
||||
const html = buildNotePermanentlyDeletedEmailHtml(toName, noteTitle);
|
||||
await sendEmail(toEmail, subject, html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a security alert to a user when their account is locked due to too many failed logins.
|
||||
*/
|
||||
export async function sendAccountLockedEmail(
|
||||
toEmail: string,
|
||||
toName: string,
|
||||
retryAfterMinutes: number
|
||||
): Promise<void> {
|
||||
if (!toEmail) return;
|
||||
|
||||
const subject = 'Crumbs account temporarily locked';
|
||||
const html = buildAccountLockedEmailHtml(toName, retryAfterMinutes);
|
||||
await sendEmail(toEmail, subject, html);
|
||||
}
|
||||
|
||||
function buildShareEmailHtml(
|
||||
toName: string,
|
||||
fromName: string,
|
||||
@@ -74,7 +193,18 @@ function buildShareEmailHtml(
|
||||
const displayName = toName || 'there';
|
||||
const escapedTitle = escapeHtml(noteTitle);
|
||||
const escapedFrom = escapeHtml(fromName || 'Someone');
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Note shared with you</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${escapeHtml(displayName)},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
<strong>${escapedFrom}</strong> shared a note with you: <strong>“${escapedTitle}”</strong>
|
||||
</p>
|
||||
${buildOpenButton(appUrl)}`;
|
||||
return buildEmailLayout(content, 'You’re receiving this because someone shared a note with you on Crumbs.');
|
||||
}
|
||||
|
||||
function buildEmailLayout(content: string, footer: string): string {
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head><meta charset="utf-8"></head>
|
||||
@@ -84,21 +214,8 @@ function buildShareEmailHtml(
|
||||
<table width="500" cellpadding="0" cellspacing="0" style="background-color:#faf5eb;border:1px solid #d4cabb;box-shadow:2px 2px 0px #d4cabb;">
|
||||
<tr><td style="padding:32px;">
|
||||
<p style="margin:0 0 8px;font-size:11px;color:#C8860A;text-transform:uppercase;letter-spacing:2px;">Crumbs</p>
|
||||
<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Note shared with you</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${escapeHtml(displayName)},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
<strong>${escapedFrom}</strong> shared a note with you: <strong>“${escapedTitle}”</strong>
|
||||
</p>
|
||||
<table cellpadding="0" cellspacing="0" style="margin:0 0 24px;">
|
||||
<tr><td style="background-color:#C8860A;box-shadow:2px 2px 0px #1a1a2e;">
|
||||
<a href="${escapeHtml(appUrl)}" style="display:inline-block;padding:10px 24px;color:#faf5eb;font-size:13px;font-weight:bold;text-decoration:none;font-family:'JetBrains Mono',monospace;">Open Crumbs</a>
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="margin:0;font-size:11px;color:#6b6272;line-height:1.5;">
|
||||
You’re receiving this because someone shared a note with you on Crumbs.
|
||||
</p>
|
||||
${content}
|
||||
<p style="margin:0;font-size:11px;color:#6b6272;line-height:1.5;">${footer}</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</td></tr>
|
||||
@@ -107,6 +224,126 @@ function buildShareEmailHtml(
|
||||
</html>`;
|
||||
}
|
||||
|
||||
function buildOpenButton(appUrl: string, label = 'Open Crumbs'): string {
|
||||
return `<table cellpadding="0" cellspacing="0" style="margin:0 0 24px;">
|
||||
<tr><td style="background-color:#C8860A;box-shadow:2px 2px 0px #1a1a2e;">
|
||||
<a href="${escapeHtml(appUrl)}" style="display:inline-block;padding:10px 24px;color:#faf5eb;font-size:13px;font-weight:bold;text-decoration:none;font-family:'JetBrains Mono',monospace;">${escapeHtml(label)}</a>
|
||||
</td></tr>
|
||||
</table>`;
|
||||
}
|
||||
|
||||
function buildWelcomeEmailHtml(toName: string, appUrl: string): string {
|
||||
const displayName = escapeHtml(toName || 'there');
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Welcome to Crumbs</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${displayName},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
An admin has created an account for you on Crumbs. You can log in and start taking notes right away.
|
||||
</p>
|
||||
${buildOpenButton(appUrl)}`;
|
||||
return buildEmailLayout(content, 'You’re receiving this because an admin created an account for you on Crumbs.');
|
||||
}
|
||||
|
||||
function buildPasswordResetEmailHtml(toName: string, appUrl: string): string {
|
||||
const displayName = escapeHtml(toName || 'there');
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Password reset</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${displayName},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
An admin has reset your Crumbs password. Please log in and change it to something only you know.
|
||||
</p>
|
||||
${buildOpenButton(appUrl)}`;
|
||||
return buildEmailLayout(content, 'You’re receiving this because an admin reset your password on Crumbs. If you didn’t expect this, please contact your admin.');
|
||||
}
|
||||
|
||||
function buildAccountDeletedEmailHtml(toName: string): string {
|
||||
const displayName = escapeHtml(toName || 'there');
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Account deleted</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${displayName},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Your Crumbs account and all associated data have been permanently deleted.
|
||||
</p>`;
|
||||
return buildEmailLayout(content, 'You’re receiving this as confirmation that your Crumbs account was deleted.');
|
||||
}
|
||||
|
||||
function buildEmailChangedEmailHtml(toName: string, newEmail: string): string {
|
||||
const displayName = escapeHtml(toName || 'there');
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Email address changed</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${displayName},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Your Crumbs account email address has been changed to <strong>${escapeHtml(newEmail)}</strong>. If you did not make this change, please contact your admin immediately.
|
||||
</p>`;
|
||||
return buildEmailLayout(content, 'You’re receiving this security notice because your Crumbs account email was updated.');
|
||||
}
|
||||
|
||||
function buildRoleChangedEmailHtml(toName: string, newRole: 'admin' | 'user', appUrl: string): string {
|
||||
const displayName = escapeHtml(toName || 'there');
|
||||
const roleLabel = newRole === 'admin' ? 'Admin' : 'User';
|
||||
const detail = newRole === 'admin'
|
||||
? 'You now have admin privileges, including the ability to manage users and settings.'
|
||||
: 'Your account no longer has admin privileges.';
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Role updated: ${roleLabel}</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${displayName},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Your Crumbs account role has been updated to <strong>${escapeHtml(roleLabel)}</strong>. ${escapeHtml(detail)}
|
||||
</p>
|
||||
${buildOpenButton(appUrl)}`;
|
||||
return buildEmailLayout(content, 'You’re receiving this because your account role was changed on Crumbs.');
|
||||
}
|
||||
|
||||
function buildCollaboratorRemovedEmailHtml(
|
||||
toName: string,
|
||||
ownerName: string,
|
||||
noteTitle: string,
|
||||
appUrl: string
|
||||
): string {
|
||||
const displayName = escapeHtml(toName || 'there');
|
||||
const escapedOwner = escapeHtml(ownerName || 'Someone');
|
||||
const escapedTitle = escapeHtml(noteTitle);
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Removed from shared note</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${displayName},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
<strong>${escapedOwner}</strong> has removed you from the shared note <strong>“${escapedTitle}”</strong>. You no longer have access to this note.
|
||||
</p>
|
||||
${buildOpenButton(appUrl)}`;
|
||||
return buildEmailLayout(content, 'You’re receiving this because you were removed from a shared note on Crumbs.');
|
||||
}
|
||||
|
||||
function buildNotePermanentlyDeletedEmailHtml(toName: string, noteTitle: string): string {
|
||||
const displayName = escapeHtml(toName || 'there');
|
||||
const escapedTitle = escapeHtml(noteTitle);
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Shared note deleted</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${displayName},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
The shared note <strong>“${escapedTitle}”</strong> has been permanently deleted by its owner. You no longer have access to it.
|
||||
</p>`;
|
||||
return buildEmailLayout(content, 'You’re receiving this because a shared note you had access to was deleted on Crumbs.');
|
||||
}
|
||||
|
||||
function buildAccountLockedEmailHtml(toName: string, retryAfterMinutes: number): string {
|
||||
const displayName = escapeHtml(toName || 'there');
|
||||
const content = `<h1 style="margin:0 0 24px;font-size:18px;color:#1a1a2e;font-weight:bold;">Account temporarily locked</h1>
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Hey ${displayName},
|
||||
</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;color:#1a1a2e;line-height:1.6;">
|
||||
Too many failed login attempts were made on your Crumbs account. For your security, login has been temporarily blocked for <strong>${retryAfterMinutes} minute${retryAfterMinutes === 1 ? '' : 's'}</strong>. If this wasn’t you, please change your password once you regain access.
|
||||
</p>`;
|
||||
return buildEmailLayout(content, 'You’re receiving this security alert because of repeated failed login attempts on your Crumbs account.');
|
||||
}
|
||||
|
||||
function escapeHtml(str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { createTestDb } from './db/test-helpers.js';
|
||||
import { notes, noteCollaborators, noteUserState, users } from './db/schema.js';
|
||||
import { notes, noteCollaborators, noteUserState, noteVersions, users } from './db/schema.js';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import type { Db } from './db/index.js';
|
||||
import {
|
||||
@@ -233,6 +233,31 @@ describe('updateNote', () => {
|
||||
expect(updated!.version).toBe(2);
|
||||
});
|
||||
|
||||
it('should create a snapshot when content changes', () => {
|
||||
seedNote('n1', { title: 'Original', content: 'Hello', color: 'default', checklistMode: false });
|
||||
updateNote(db, OWNER_ID, 'n1', { title: 'Changed' });
|
||||
|
||||
const snapshots = db.select().from(noteVersions).where(eq(noteVersions.noteId, 'n1')).all();
|
||||
expect(snapshots).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should not create a snapshot when no content field actually changed', () => {
|
||||
seedNote('n1', { title: 'Same', content: 'Same', color: 'default', checklistMode: false });
|
||||
// Send the same values — nothing actually changes
|
||||
updateNote(db, OWNER_ID, 'n1', { title: 'Same', content: 'Same' });
|
||||
|
||||
const snapshots = db.select().from(noteVersions).where(eq(noteVersions.noteId, 'n1')).all();
|
||||
expect(snapshots).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should not create a snapshot when only non-content fields change (pinned, archived)', () => {
|
||||
seedNote('n1', { title: 'Note', pinned: false });
|
||||
updateNote(db, OWNER_ID, 'n1', { pinned: true });
|
||||
|
||||
const snapshots = db.select().from(noteVersions).where(eq(noteVersions.noteId, 'n1')).all();
|
||||
expect(snapshots).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should extract and sync tags on title/content change', () => {
|
||||
seedNote('n1', { title: 'Original' });
|
||||
const updated = updateNote(db, OWNER_ID, 'n1', { title: 'Now with #newtag' });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Db } from './db/index.js';
|
||||
import { notes, noteTags, tags, noteCollaborators, noteUserState } from './db/schema.js';
|
||||
import { eq, and, desc, like, or, inArray, sql } from 'drizzle-orm';
|
||||
import { notes, noteTags, tags, noteCollaborators, noteUserState, noteVersions } from './db/schema.js';
|
||||
import { eq, and, desc, like, or, inArray, sql, lte } from 'drizzle-orm';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { extractTags } from '$lib/utils/tags.js';
|
||||
import { fetchTagsForNotes, syncNoteTags } from './tags.js';
|
||||
@@ -8,6 +8,7 @@ import { fetchAttachmentsForNotes } from './attachments.js';
|
||||
import { fetchCollaboratorsForNotes } from './collaborators.js';
|
||||
import { canAccessNote } from './api-utils.js';
|
||||
import { createSnapshot } from './versions-service.js';
|
||||
import { mergeContent } from '$lib/utils/content-merge.js';
|
||||
import type { NoteFilter } from '$lib/types/index.js';
|
||||
|
||||
interface NoteRow {
|
||||
@@ -205,6 +206,7 @@ export interface UpdateNoteInput {
|
||||
trashed?: boolean;
|
||||
checklistMode?: boolean;
|
||||
sortOrder?: number;
|
||||
baseVersion?: number;
|
||||
}
|
||||
|
||||
/** Per-user fields that go to noteUserState for collaborators */
|
||||
@@ -232,7 +234,33 @@ export function updateNote(db: Db, userId: number, id: string, input: UpdateNote
|
||||
let hasSharedUpdates = false;
|
||||
|
||||
if (input.title !== undefined) { sharedUpdates.title = input.title; hasSharedUpdates = true; }
|
||||
if (input.content !== undefined) { sharedUpdates.content = input.content; hasSharedUpdates = true; }
|
||||
if (input.content !== undefined) {
|
||||
// 3-way merge to preserve concurrent edits from other users
|
||||
if (input.content !== existing.content) {
|
||||
const baseSnapshot = input.baseVersion !== undefined
|
||||
? db.select({ content: noteVersions.content })
|
||||
.from(noteVersions)
|
||||
.where(and(eq(noteVersions.noteId, id), lte(noteVersions.version, input.baseVersion)))
|
||||
.orderBy(desc(noteVersions.version))
|
||||
.limit(1)
|
||||
.get()
|
||||
: db.select({ content: noteVersions.content })
|
||||
.from(noteVersions)
|
||||
.where(eq(noteVersions.noteId, id))
|
||||
.orderBy(desc(noteVersions.version))
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
if (baseSnapshot && baseSnapshot.content !== existing.content) {
|
||||
sharedUpdates.content = mergeContent(baseSnapshot.content, input.content, existing.content);
|
||||
} else {
|
||||
sharedUpdates.content = input.content;
|
||||
}
|
||||
} else {
|
||||
sharedUpdates.content = input.content;
|
||||
}
|
||||
hasSharedUpdates = true;
|
||||
}
|
||||
if (input.color !== undefined) { sharedUpdates.color = input.color; hasSharedUpdates = true; }
|
||||
if (input.checklistMode !== undefined) { sharedUpdates.checklistMode = input.checklistMode; hasSharedUpdates = true; }
|
||||
|
||||
@@ -294,24 +322,21 @@ export function updateNote(db: Db, userId: number, id: string, input: UpdateNote
|
||||
}
|
||||
}
|
||||
|
||||
// Create a version snapshot whenever content-related fields are saved
|
||||
const hasContentUpdate =
|
||||
input.title !== undefined ||
|
||||
input.content !== undefined ||
|
||||
input.color !== undefined ||
|
||||
input.checklistMode !== undefined;
|
||||
// Create a version snapshot only when at least one content field actually changed
|
||||
const hasActualContentChange =
|
||||
(input.title !== undefined && input.title !== existing.title) ||
|
||||
(input.content !== undefined && input.content !== existing.content) ||
|
||||
(input.color !== undefined && input.color !== existing.color) ||
|
||||
(input.checklistMode !== undefined && input.checklistMode !== existing.checklistMode);
|
||||
|
||||
if (hasContentUpdate) {
|
||||
const saved = db.select().from(notes).where(eq(notes.id, id)).get();
|
||||
if (saved) {
|
||||
createSnapshot(db, id, {
|
||||
version: saved.version,
|
||||
title: saved.title,
|
||||
content: saved.content,
|
||||
checklistMode: saved.checklistMode,
|
||||
color: saved.color
|
||||
});
|
||||
}
|
||||
if (hasActualContentChange) {
|
||||
createSnapshot(db, id, {
|
||||
version: existing.version,
|
||||
title: existing.title,
|
||||
content: existing.content,
|
||||
checklistMode: existing.checklistMode,
|
||||
color: existing.color
|
||||
});
|
||||
}
|
||||
|
||||
return getNote(db, userId, id);
|
||||
|
||||
@@ -9,7 +9,7 @@ const CONTENT_PREVIEW_LENGTH = 80;
|
||||
|
||||
/**
|
||||
* Create a snapshot of a note's current state.
|
||||
* Called on every save. Prunes snapshots beyond MAX_VERSIONS_PER_NOTE.
|
||||
* Only called when content actually changed. Prunes snapshots beyond MAX_VERSIONS_PER_NOTE.
|
||||
*/
|
||||
export function createSnapshot(
|
||||
db: Db,
|
||||
|
||||
+10
-2
@@ -142,11 +142,19 @@ export async function createNote(note: NoteCreate): Promise<Note | null> {
|
||||
}
|
||||
|
||||
export async function updateNote(id: string, updates: NoteUpdate): Promise<Note | null> {
|
||||
// Read current version for 3-way merge base on the server
|
||||
let baseVersion: number | undefined;
|
||||
notes.update((list) => {
|
||||
const current = list.find((n) => n.id === id);
|
||||
if (current) baseVersion = current.version;
|
||||
return list;
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/notes/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(updates)
|
||||
body: JSON.stringify({ ...updates, baseVersion })
|
||||
});
|
||||
if (res.ok) {
|
||||
const updated: Note = await res.json();
|
||||
@@ -173,7 +181,7 @@ export async function updateNote(id: string, updates: NoteUpdate): Promise<Note
|
||||
);
|
||||
if (optimistic) {
|
||||
await putNote(optimistic);
|
||||
await addToSyncQueue({ noteId: id, operation: 'update', data: updates, timestamp: Date.now() });
|
||||
await addToSyncQueue({ noteId: id, operation: 'update', data: updates, timestamp: Date.now(), baseVersion });
|
||||
showToast('Saved offline — will sync when reconnected', 'info');
|
||||
}
|
||||
return optimistic;
|
||||
|
||||
@@ -8,13 +8,17 @@ describe('preferences defaults', () => {
|
||||
defaultNoteColor: 'default',
|
||||
hideFooter: false,
|
||||
sidebarDefaultState: 'open',
|
||||
notifyOnShare: true
|
||||
notifyOnShare: true,
|
||||
notifyOnCollabRemoved: true,
|
||||
notifyOnNoteDeleted: true
|
||||
});
|
||||
});
|
||||
|
||||
it('should identify boolean preference keys', () => {
|
||||
expect(BOOLEAN_PREF_KEYS.has('hideFooter')).toBe(true);
|
||||
expect(BOOLEAN_PREF_KEYS.has('notifyOnShare')).toBe(true);
|
||||
expect(BOOLEAN_PREF_KEYS.has('notifyOnCollabRemoved')).toBe(true);
|
||||
expect(BOOLEAN_PREF_KEYS.has('notifyOnNoteDeleted')).toBe(true);
|
||||
expect(BOOLEAN_PREF_KEYS.has('defaultNoteMode')).toBe(false);
|
||||
expect(BOOLEAN_PREF_KEYS.has('defaultNoteColor')).toBe(false);
|
||||
expect(BOOLEAN_PREF_KEYS.has('sidebarDefaultState')).toBe(false);
|
||||
|
||||
+17
-1
@@ -100,10 +100,26 @@ async function pullChanges(): Promise<Note[]> {
|
||||
const localNotes = await getAllNotes();
|
||||
const localMap = new Map(localNotes.map((n) => [n.id, n]));
|
||||
|
||||
// Build pending-fields map from sync queue to protect unpushed local changes
|
||||
let pendingFieldsMap = new Map<string, Set<string>>();
|
||||
try {
|
||||
const queue = await getSyncQueue();
|
||||
for (const item of queue) {
|
||||
if (item.data) {
|
||||
const fields = pendingFieldsMap.get(item.noteId) || new Set<string>();
|
||||
Object.keys(item.data).forEach((k) => fields.add(k));
|
||||
pendingFieldsMap.set(item.noteId, fields);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Queue unavailable — merge without protection
|
||||
}
|
||||
|
||||
for (const remote of remoteNotes) {
|
||||
const local = localMap.get(remote.id);
|
||||
if (local) {
|
||||
const merged = mergeNotes(local, remote);
|
||||
const pendingFields = pendingFieldsMap.get(remote.id);
|
||||
const merged = mergeNotes(local, remote, pendingFields);
|
||||
await putNote(merged);
|
||||
} else {
|
||||
await putNote(remote);
|
||||
|
||||
+22
-12
@@ -1,29 +1,39 @@
|
||||
import type { Note } from '$lib/types/index.js';
|
||||
|
||||
/** Fields that can be individually merged between local and remote notes */
|
||||
const MUTABLE_FIELDS = ['title', 'content', 'color', 'pinned', 'archived', 'trashed', 'checklistMode', 'sortOrder'] as const;
|
||||
|
||||
/**
|
||||
* Last-Write-Wins (LWW) merge strategy per field.
|
||||
* For a single-user app with multiple devices, this is sufficient.
|
||||
* Each field is resolved by comparing updatedAt timestamps.
|
||||
* Last-Write-Wins (LWW) merge strategy with pending-field protection.
|
||||
*
|
||||
* When remote is newer, takes remote values for all fields EXCEPT those
|
||||
* listed in `pendingFields` — these represent locally-queued changes that
|
||||
* haven't been pushed yet and must be preserved.
|
||||
*/
|
||||
export function mergeNotes(local: Note, remote: Note): Note {
|
||||
// If remote is newer overall, take remote
|
||||
export function mergeNotes(local: Note, remote: Note, pendingFields?: Set<string>): Note {
|
||||
const localTime = new Date(local.updatedAt).getTime();
|
||||
const remoteTime = new Date(remote.updatedAt).getTime();
|
||||
|
||||
if (remoteTime > localTime) {
|
||||
return { ...remote };
|
||||
}
|
||||
const remoteWins = remoteTime > localTime ||
|
||||
(remoteTime === localTime && remote.version > local.version);
|
||||
|
||||
if (localTime > remoteTime) {
|
||||
if (!remoteWins) {
|
||||
return { ...local };
|
||||
}
|
||||
|
||||
// Same timestamp - prefer higher version number
|
||||
if (remote.version > local.version) {
|
||||
// Remote wins — take remote as base, but preserve pending local fields
|
||||
if (!pendingFields || pendingFields.size === 0) {
|
||||
return { ...remote };
|
||||
}
|
||||
|
||||
return { ...local };
|
||||
const merged = { ...remote };
|
||||
for (const field of MUTABLE_FIELDS) {
|
||||
if (pendingFields.has(field)) {
|
||||
(merged as unknown as Record<string, unknown>)[field] = (local as unknown as Record<string, unknown>)[field];
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -48,6 +48,7 @@ export interface SyncQueueItem {
|
||||
operation: 'create' | 'update' | 'delete';
|
||||
data?: Partial<Note>;
|
||||
timestamp: number;
|
||||
baseVersion?: number;
|
||||
}
|
||||
|
||||
let dbPromise: Promise<IDBPDatabase<CrumbsDB>> | null = null;
|
||||
|
||||
@@ -224,21 +224,69 @@ describe('processSyncPush — shared notes', () => {
|
||||
expect(note.trashed).toBe(false);
|
||||
});
|
||||
|
||||
it('should reject changes with older timestamp than server note', async () => {
|
||||
it('should apply field changes even when timestamp is older (no timestamp gate)', async () => {
|
||||
const t2 = new Date('2024-01-02T00:00:00Z');
|
||||
seedSharedNote('n1', { updatedAt: t2, createdAt: new Date('2024-01-01T00:00:00Z') });
|
||||
|
||||
// Collaborator's change has a timestamp BEFORE the server's updatedAt
|
||||
// Collaborator's change has a timestamp BEFORE the server's updatedAt.
|
||||
// With field-level sync, the title change should still be applied because
|
||||
// the sync data only contains fields the client explicitly modified.
|
||||
const t1 = new Date('2024-01-01T12:00:00Z').getTime();
|
||||
await processSyncPush(db, [{
|
||||
noteId: 'n1',
|
||||
operation: 'update',
|
||||
timestamp: t1,
|
||||
data: { title: 'Stale edit' }
|
||||
data: { title: 'Offline edit' }
|
||||
}], COLLAB_ID);
|
||||
|
||||
const note = db.select().from(notes).where(eq(notes.id, 'n1')).get()!;
|
||||
expect(note.title).toBe('Shared Note'); // Unchanged
|
||||
expect(note.title).toBe('Offline edit');
|
||||
// updatedAt should be max of change timestamp and server timestamp
|
||||
expect(note.updatedAt.getTime()).toBe(t2.getTime());
|
||||
});
|
||||
|
||||
it('should merge checklist content when collaborator pushes concurrent content change', async () => {
|
||||
const t1 = new Date('2024-01-01T00:00:00Z');
|
||||
seedSharedNote('n1', {
|
||||
updatedAt: t1,
|
||||
createdAt: t1,
|
||||
content: '- [ ] Milk\n- [ ] Bread',
|
||||
checklistMode: true
|
||||
});
|
||||
|
||||
// Simulate owner editing content on server (checking Bread)
|
||||
const t2 = new Date('2024-01-01T12:00:00Z');
|
||||
db.update(notes)
|
||||
.set({ content: '- [ ] Milk\n- [x] Bread', updatedAt: t2, version: 2 })
|
||||
.where(eq(notes.id, 'n1'))
|
||||
.run();
|
||||
|
||||
// Create a version snapshot for the base content (version 1)
|
||||
const { noteVersions } = await import('../server/db/schema.js');
|
||||
db.insert(noteVersions).values({
|
||||
id: 'snap-1',
|
||||
noteId: 'n1',
|
||||
version: 1,
|
||||
title: 'Shared Note',
|
||||
content: '- [ ] Milk\n- [ ] Bread',
|
||||
checklistMode: true,
|
||||
color: 'default',
|
||||
createdAt: t1
|
||||
}).run();
|
||||
|
||||
// Collaborator was offline since version 1, checked Milk
|
||||
const t3 = new Date('2024-01-01T13:00:00Z').getTime();
|
||||
await processSyncPush(db, [{
|
||||
noteId: 'n1',
|
||||
operation: 'update',
|
||||
timestamp: t3,
|
||||
data: { content: '- [x] Milk\n- [ ] Bread' },
|
||||
baseVersion: 1
|
||||
}], COLLAB_ID);
|
||||
|
||||
const note = db.select().from(notes).where(eq(notes.id, 'n1')).get()!;
|
||||
// Both changes should be merged: Milk checked by collab, Bread checked by owner
|
||||
expect(note.content).toBe('- [x] Milk\n- [x] Bread');
|
||||
});
|
||||
|
||||
it('should not allow non-collaborator to update the note', async () => {
|
||||
|
||||
+88
-50
@@ -1,10 +1,37 @@
|
||||
import type { Db } from '$lib/server/db/index.js';
|
||||
import { notes, noteCollaborators, noteUserState, syncLog } from '$lib/server/db/schema.js';
|
||||
import { eq, gt, and, or, sql } from 'drizzle-orm';
|
||||
import { notes, noteCollaborators, noteUserState, noteVersions, syncLog } from '$lib/server/db/schema.js';
|
||||
import { eq, gt, and, or, sql, desc, lte } from 'drizzle-orm';
|
||||
import { extractTags } from '$lib/utils/tags.js';
|
||||
import { syncNoteTags } from '$lib/server/tags.js';
|
||||
import { canAccessNote } from '$lib/server/api-utils.js';
|
||||
import { mergeContent } from '$lib/utils/content-merge.js';
|
||||
import type { SyncQueueItem } from './idb.js';
|
||||
|
||||
/**
|
||||
* Find the base content for 3-way merge from version snapshots.
|
||||
* Returns the content from the snapshot at or before the given version,
|
||||
* or the current note content if no snapshot is found.
|
||||
*/
|
||||
function getBaseContent(tx: Parameters<Parameters<Db['transaction']>[0]>[0], noteId: string, baseVersion?: number): string | null {
|
||||
if (baseVersion !== undefined) {
|
||||
const snapshot = tx.select({ content: noteVersions.content })
|
||||
.from(noteVersions)
|
||||
.where(and(eq(noteVersions.noteId, noteId), lte(noteVersions.version, baseVersion)))
|
||||
.orderBy(desc(noteVersions.version))
|
||||
.limit(1)
|
||||
.get();
|
||||
if (snapshot) return snapshot.content;
|
||||
}
|
||||
// Fallback: get the most recent snapshot before the current version
|
||||
const latest = tx.select({ content: noteVersions.content })
|
||||
.from(noteVersions)
|
||||
.where(eq(noteVersions.noteId, noteId))
|
||||
.orderBy(desc(noteVersions.version))
|
||||
.limit(1)
|
||||
.get();
|
||||
return latest?.content ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process incoming sync changes from client.
|
||||
*/
|
||||
@@ -31,59 +58,70 @@ export async function processSyncPush(db: Db, changes: SyncQueueItem[], userId:
|
||||
|
||||
if (!isOwner && !isCollaborator) continue;
|
||||
|
||||
if (change.timestamp > note.updatedAt.getTime()) {
|
||||
// Shared fields: title, content, color, checklistMode
|
||||
const sharedData: Record<string, unknown> = {
|
||||
updatedAt: new Date(change.timestamp),
|
||||
version: note.version + 1
|
||||
};
|
||||
if (change.data.title !== undefined) sharedData.title = change.data.title;
|
||||
if (change.data.content !== undefined) sharedData.content = change.data.content;
|
||||
if (change.data.color !== undefined) sharedData.color = change.data.color;
|
||||
if (change.data.checklistMode !== undefined) sharedData.checklistMode = change.data.checklistMode;
|
||||
// Apply field-level updates unconditionally (no timestamp gate).
|
||||
// Each sync change only contains the fields the client explicitly modified,
|
||||
// so applying them won't overwrite other users' changes to different fields.
|
||||
const sharedData: Record<string, unknown> = {
|
||||
updatedAt: new Date(Math.max(change.timestamp, note.updatedAt.getTime())),
|
||||
version: note.version + 1
|
||||
};
|
||||
if (change.data.title !== undefined) sharedData.title = change.data.title;
|
||||
if (change.data.color !== undefined) sharedData.color = change.data.color;
|
||||
if (change.data.checklistMode !== undefined) sharedData.checklistMode = change.data.checklistMode;
|
||||
|
||||
if (isOwner) {
|
||||
// Owner: per-user fields go to notes table
|
||||
if (change.data.pinned !== undefined) sharedData.pinned = change.data.pinned;
|
||||
if (change.data.archived !== undefined) sharedData.archived = change.data.archived;
|
||||
if (change.data.trashed !== undefined) {
|
||||
sharedData.trashed = change.data.trashed;
|
||||
sharedData.trashedAt = change.data.trashed ? new Date(change.timestamp) : null;
|
||||
}
|
||||
if (change.data.sortOrder !== undefined) sharedData.sortOrder = change.data.sortOrder;
|
||||
// Content: 3-way merge to preserve concurrent edits from other users
|
||||
if (change.data.content !== undefined && change.data.content !== note.content) {
|
||||
const baseContent = getBaseContent(tx, change.noteId, change.baseVersion);
|
||||
if (baseContent !== null && baseContent !== note.content) {
|
||||
// 3-way merge: base, incoming (local), server current (remote)
|
||||
sharedData.content = mergeContent(baseContent, change.data.content, note.content);
|
||||
} else {
|
||||
// No base or base matches server — take incoming content
|
||||
sharedData.content = change.data.content;
|
||||
}
|
||||
}
|
||||
|
||||
tx.update(notes)
|
||||
.set(sharedData)
|
||||
.where(eq(notes.id, change.noteId))
|
||||
.run();
|
||||
if (isOwner) {
|
||||
// Owner: per-user fields go to notes table
|
||||
if (change.data.pinned !== undefined) sharedData.pinned = change.data.pinned;
|
||||
if (change.data.archived !== undefined) sharedData.archived = change.data.archived;
|
||||
if (change.data.trashed !== undefined) {
|
||||
sharedData.trashed = change.data.trashed;
|
||||
sharedData.trashedAt = change.data.trashed ? new Date(change.timestamp) : null;
|
||||
}
|
||||
if (change.data.sortOrder !== undefined) sharedData.sortOrder = change.data.sortOrder;
|
||||
}
|
||||
|
||||
// Collaborator: per-user fields go to noteUserState
|
||||
if (!isOwner) {
|
||||
const hasPerUser = change.data.pinned !== undefined ||
|
||||
change.data.archived !== undefined ||
|
||||
change.data.sortOrder !== undefined;
|
||||
if (hasPerUser) {
|
||||
const existing = tx.select().from(noteUserState)
|
||||
tx.update(notes)
|
||||
.set(sharedData)
|
||||
.where(eq(notes.id, change.noteId))
|
||||
.run();
|
||||
|
||||
// Collaborator: per-user fields go to noteUserState
|
||||
if (!isOwner) {
|
||||
const hasPerUser = change.data.pinned !== undefined ||
|
||||
change.data.archived !== undefined ||
|
||||
change.data.sortOrder !== undefined;
|
||||
if (hasPerUser) {
|
||||
const existing = tx.select().from(noteUserState)
|
||||
.where(and(eq(noteUserState.noteId, change.noteId), eq(noteUserState.userId, userId)))
|
||||
.get();
|
||||
if (existing) {
|
||||
const updates: Record<string, unknown> = {};
|
||||
if (change.data.pinned !== undefined) updates.pinned = change.data.pinned;
|
||||
if (change.data.archived !== undefined) updates.archived = change.data.archived;
|
||||
if (change.data.sortOrder !== undefined) updates.sortOrder = change.data.sortOrder;
|
||||
tx.update(noteUserState).set(updates)
|
||||
.where(and(eq(noteUserState.noteId, change.noteId), eq(noteUserState.userId, userId)))
|
||||
.get();
|
||||
if (existing) {
|
||||
const updates: Record<string, unknown> = {};
|
||||
if (change.data.pinned !== undefined) updates.pinned = change.data.pinned;
|
||||
if (change.data.archived !== undefined) updates.archived = change.data.archived;
|
||||
if (change.data.sortOrder !== undefined) updates.sortOrder = change.data.sortOrder;
|
||||
tx.update(noteUserState).set(updates)
|
||||
.where(and(eq(noteUserState.noteId, change.noteId), eq(noteUserState.userId, userId)))
|
||||
.run();
|
||||
} else {
|
||||
tx.insert(noteUserState).values({
|
||||
noteId: change.noteId,
|
||||
userId,
|
||||
pinned: change.data.pinned ?? false,
|
||||
archived: change.data.archived ?? false,
|
||||
sortOrder: change.data.sortOrder ?? 0
|
||||
}).run();
|
||||
}
|
||||
.run();
|
||||
} else {
|
||||
tx.insert(noteUserState).values({
|
||||
noteId: change.noteId,
|
||||
userId,
|
||||
pinned: change.data.pinned ?? false,
|
||||
archived: change.data.archived ?? false,
|
||||
sortOrder: change.data.sortOrder ?? 0
|
||||
}).run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,71 @@ describe('mergeNotes (LWW)', () => {
|
||||
const result = mergeNotes(local, remote);
|
||||
expect(result.title).toBe('Local');
|
||||
});
|
||||
|
||||
it('should preserve pending local fields when remote is newer', () => {
|
||||
const local = makeNote({
|
||||
title: 'Local title',
|
||||
content: 'Local content',
|
||||
color: 'coral',
|
||||
updatedAt: new Date('2024-01-01'),
|
||||
version: 1
|
||||
});
|
||||
const remote = makeNote({
|
||||
title: 'Remote title',
|
||||
content: 'Remote content',
|
||||
color: 'default',
|
||||
updatedAt: new Date('2024-01-02'),
|
||||
version: 2
|
||||
});
|
||||
|
||||
// Content has pending local changes; title and color do not
|
||||
const pendingFields = new Set(['content']);
|
||||
const result = mergeNotes(local, remote, pendingFields);
|
||||
|
||||
// Remote wins overall, but content is preserved from local
|
||||
expect(result.title).toBe('Remote title');
|
||||
expect(result.content).toBe('Local content');
|
||||
expect(result.color).toBe('default'); // remote wins for non-pending field
|
||||
expect(result.version).toBe(2); // metadata from remote
|
||||
});
|
||||
|
||||
it('should take remote values for non-pending fields when remote is newer', () => {
|
||||
const local = makeNote({
|
||||
pinned: true,
|
||||
archived: true,
|
||||
updatedAt: new Date('2024-01-01')
|
||||
});
|
||||
const remote = makeNote({
|
||||
pinned: false,
|
||||
archived: false,
|
||||
updatedAt: new Date('2024-01-02')
|
||||
});
|
||||
|
||||
const pendingFields = new Set(['pinned']);
|
||||
const result = mergeNotes(local, remote, pendingFields);
|
||||
|
||||
expect(result.pinned).toBe(true); // pending — preserved
|
||||
expect(result.archived).toBe(false); // not pending — remote wins
|
||||
});
|
||||
|
||||
it('should ignore pendingFields when local is newer', () => {
|
||||
const local = makeNote({
|
||||
title: 'Local',
|
||||
updatedAt: new Date('2024-01-02'),
|
||||
version: 2
|
||||
});
|
||||
const remote = makeNote({
|
||||
title: 'Remote',
|
||||
updatedAt: new Date('2024-01-01'),
|
||||
version: 1
|
||||
});
|
||||
|
||||
const pendingFields = new Set(['title']);
|
||||
const result = mergeNotes(local, remote, pendingFields);
|
||||
|
||||
// Local wins entirely since it's newer
|
||||
expect(result.title).toBe('Local');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasChanges', () => {
|
||||
|
||||
@@ -6,6 +6,8 @@ export interface UserPreferences {
|
||||
hideFooter: boolean;
|
||||
sidebarDefaultState: 'open' | 'collapsed';
|
||||
notifyOnShare: boolean;
|
||||
notifyOnCollabRemoved: boolean;
|
||||
notifyOnNoteDeleted: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_PREFERENCES: UserPreferences = {
|
||||
@@ -13,10 +15,14 @@ export const DEFAULT_PREFERENCES: UserPreferences = {
|
||||
defaultNoteColor: 'default',
|
||||
hideFooter: false,
|
||||
sidebarDefaultState: 'open',
|
||||
notifyOnShare: true
|
||||
notifyOnShare: true,
|
||||
notifyOnCollabRemoved: true,
|
||||
notifyOnNoteDeleted: true
|
||||
};
|
||||
|
||||
export const BOOLEAN_PREF_KEYS: ReadonlySet<keyof UserPreferences> = new Set([
|
||||
'hideFooter',
|
||||
'notifyOnShare'
|
||||
'notifyOnShare',
|
||||
'notifyOnCollabRemoved',
|
||||
'notifyOnNoteDeleted'
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mergeContent, mergeContentTwoWay } from './content-merge.js';
|
||||
|
||||
describe('mergeContent (3-way)', () => {
|
||||
it('should return remote when local is unchanged', () => {
|
||||
const base = '- [ ] Milk\n- [ ] Bread';
|
||||
const local = '- [ ] Milk\n- [ ] Bread';
|
||||
const remote = '- [x] Milk\n- [ ] Bread';
|
||||
|
||||
expect(mergeContent(base, local, remote)).toBe('- [x] Milk\n- [ ] Bread');
|
||||
});
|
||||
|
||||
it('should return local when remote is unchanged', () => {
|
||||
const base = '- [ ] Milk\n- [ ] Bread';
|
||||
const local = '- [x] Milk\n- [ ] Bread';
|
||||
const remote = '- [ ] Milk\n- [ ] Bread';
|
||||
|
||||
expect(mergeContent(base, local, remote)).toBe('- [x] Milk\n- [ ] Bread');
|
||||
});
|
||||
|
||||
it('should merge when User A checks an item and User B adds an item', () => {
|
||||
const base = '- [ ] Milk\n- [ ] Bread\n- [ ] Eggs';
|
||||
const local = '- [x] Milk\n- [ ] Bread\n- [ ] Eggs'; // User A checks Milk
|
||||
const remote = '- [ ] Milk\n- [ ] Bread\n- [ ] Eggs\n- [ ] Butter'; // User B adds Butter
|
||||
|
||||
const result = mergeContent(base, local, remote);
|
||||
expect(result).toBe('- [x] Milk\n- [ ] Bread\n- [ ] Eggs\n- [ ] Butter');
|
||||
});
|
||||
|
||||
it('should merge when both users check different items', () => {
|
||||
const base = '- [ ] Milk\n- [ ] Bread\n- [ ] Eggs';
|
||||
const local = '- [x] Milk\n- [ ] Bread\n- [ ] Eggs'; // User A checks Milk
|
||||
const remote = '- [ ] Milk\n- [x] Bread\n- [ ] Eggs'; // User B checks Bread
|
||||
|
||||
const result = mergeContent(base, local, remote);
|
||||
expect(result).toBe('- [x] Milk\n- [x] Bread\n- [ ] Eggs');
|
||||
});
|
||||
|
||||
it('should LWW (prefer remote) when both users edit the same line', () => {
|
||||
const base = '- [ ] Milk\n- [ ] Bread';
|
||||
const local = '- [ ] Whole Milk\n- [ ] Bread'; // User A renames Milk
|
||||
const remote = '- [x] Milk\n- [ ] Bread'; // User B checks Milk
|
||||
|
||||
const result = mergeContent(base, local, remote);
|
||||
// Both changed line 1 — conflict resolved by preferring remote
|
||||
expect(result).toBe('- [x] Milk\n- [ ] Bread');
|
||||
});
|
||||
|
||||
it('should handle line additions by both sides', () => {
|
||||
const base = '- [ ] Milk';
|
||||
const local = '- [ ] Milk\n- [ ] Bread'; // User A adds Bread at end
|
||||
const remote = '- [ ] Eggs\n- [ ] Milk'; // User B adds Eggs at beginning
|
||||
|
||||
const result = mergeContent(base, local, remote);
|
||||
// Both additions should be preserved
|
||||
expect(result).toContain('- [ ] Milk');
|
||||
expect(result).toContain('- [ ] Bread');
|
||||
expect(result).toContain('- [ ] Eggs');
|
||||
});
|
||||
|
||||
it('should handle line deletion by one side', () => {
|
||||
const base = '- [ ] Milk\n- [ ] Bread\n- [ ] Eggs';
|
||||
const local = '- [ ] Milk\n- [ ] Eggs'; // User A removes Bread
|
||||
const remote = '- [ ] Milk\n- [ ] Bread\n- [ ] Eggs'; // User B unchanged
|
||||
|
||||
const result = mergeContent(base, local, remote);
|
||||
expect(result).toBe('- [ ] Milk\n- [ ] Eggs');
|
||||
});
|
||||
|
||||
it('should work with non-checklist markdown (prose paragraphs)', () => {
|
||||
const base = '# Shopping\n\nBuy groceries today.\n\n## Notes\n\nNothing special.';
|
||||
const local = '# Shopping\n\nBuy groceries today.\n\n## Notes\n\nRemember coupons.'; // User A edits notes
|
||||
const remote = '# Shopping List\n\nBuy groceries today.\n\n## Notes\n\nNothing special.'; // User B edits title
|
||||
|
||||
const result = mergeContent(base, local, remote);
|
||||
expect(result).toContain('# Shopping List');
|
||||
expect(result).toContain('Remember coupons.');
|
||||
});
|
||||
|
||||
it('should handle empty content', () => {
|
||||
expect(mergeContent('', '', '')).toBe('');
|
||||
expect(mergeContent('', 'hello', '')).toBe('hello');
|
||||
expect(mergeContent('', '', 'hello')).toBe('hello');
|
||||
});
|
||||
|
||||
it('should return remote when local equals remote', () => {
|
||||
const content = '- [ ] Milk\n- [ ] Bread';
|
||||
expect(mergeContent('old', content, content)).toBe(content);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeContentTwoWay', () => {
|
||||
it('should return remote when both are identical', () => {
|
||||
expect(mergeContentTwoWay('hello', 'hello')).toBe('hello');
|
||||
});
|
||||
|
||||
it('should attempt merge when contents differ', () => {
|
||||
const local = '- [x] Milk\n- [ ] Bread';
|
||||
const remote = '- [ ] Milk\n- [ ] Bread\n- [ ] Eggs';
|
||||
|
||||
const result = mergeContentTwoWay(local, remote);
|
||||
// Without a base, conflict resolution prefers remote
|
||||
expect(result).toContain('- [ ] Bread');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { diff3Merge } from 'node-diff3';
|
||||
|
||||
/**
|
||||
* Resolve a conflict region by comparing each line against the base.
|
||||
* If only one side changed a line, take that change.
|
||||
* If both sides changed the same line, prefer remote (LWW).
|
||||
* Handles different-length regions by appending extra lines.
|
||||
*/
|
||||
function resolveConflict(
|
||||
aLines: string[],
|
||||
oLines: string[],
|
||||
bLines: string[]
|
||||
): string[] {
|
||||
const maxLen = Math.max(aLines.length, bLines.length, oLines.length);
|
||||
const result: string[] = [];
|
||||
|
||||
for (let i = 0; i < maxLen; i++) {
|
||||
const a = i < aLines.length ? aLines[i] : undefined;
|
||||
const o = i < oLines.length ? oLines[i] : undefined;
|
||||
const b = i < bLines.length ? bLines[i] : undefined;
|
||||
|
||||
const aChanged = a !== o;
|
||||
const bChanged = b !== o;
|
||||
|
||||
if (aChanged && !bChanged && a !== undefined) {
|
||||
// Only local changed this line — take local
|
||||
result.push(a);
|
||||
} else if (bChanged && !aChanged && b !== undefined) {
|
||||
// Only remote changed this line — take remote
|
||||
result.push(b);
|
||||
} else if (aChanged && bChanged) {
|
||||
// Both changed — LWW: prefer remote
|
||||
if (b !== undefined) result.push(b);
|
||||
// If remote deleted (undefined) but local has it, skip (remote wins)
|
||||
} else {
|
||||
// Neither changed, or both are the same as base
|
||||
if (o !== undefined) result.push(o);
|
||||
else if (b !== undefined) result.push(b);
|
||||
else if (a !== undefined) result.push(a);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 3-way line-level merge for note content.
|
||||
* Takes a base (common ancestor), local (incoming), and remote (server current).
|
||||
* For conflict regions, resolves line-by-line: if only one side changed a line,
|
||||
* take that change. If both changed the same line, prefer remote (LWW).
|
||||
*/
|
||||
export function mergeContent(base: string, local: string, remote: string): string {
|
||||
// If any two are identical, short-circuit
|
||||
if (local === remote) return remote;
|
||||
if (local === base) return remote;
|
||||
if (remote === base) return local;
|
||||
|
||||
const baseLines = base.split('\n');
|
||||
const localLines = local.split('\n');
|
||||
const remoteLines = remote.split('\n');
|
||||
|
||||
const regions = diff3Merge(localLines, baseLines, remoteLines);
|
||||
const merged: string[] = [];
|
||||
|
||||
for (const region of regions) {
|
||||
if (region.ok) {
|
||||
merged.push(...region.ok);
|
||||
} else if (region.conflict) {
|
||||
merged.push(...resolveConflict(
|
||||
region.conflict.a,
|
||||
region.conflict.o,
|
||||
region.conflict.b
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return merged.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 2-way merge fallback when no base is available.
|
||||
* Uses an empty string as the base, so all lines from both sides appear
|
||||
* as additions. For conflicts (same region), prefers remote.
|
||||
*/
|
||||
export function mergeContentTwoWay(local: string, remote: string): string {
|
||||
if (local === remote) return remote;
|
||||
return mergeContent('', local, remote);
|
||||
}
|
||||
@@ -66,15 +66,40 @@
|
||||
</div>
|
||||
|
||||
<!-- Email notifications -->
|
||||
<div class="flex items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="notify-on-share"
|
||||
checked={prefs.notifyOnShare}
|
||||
onchange={() => updatePreference('notifyOnShare', !prefs.notifyOnShare)}
|
||||
class="h-4 w-4 rounded-sm"
|
||||
data-testid="pref-notify-on-share"
|
||||
/>
|
||||
<label for="notify-on-share" class="text-sm text-[var(--text)]">Email me when someone shares a note with me</label>
|
||||
<div class="space-y-3">
|
||||
<span class="block text-sm font-medium text-[var(--text)]">Email notifications</span>
|
||||
<div class="flex items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="notify-on-share"
|
||||
checked={prefs.notifyOnShare}
|
||||
onchange={() => updatePreference('notifyOnShare', !prefs.notifyOnShare)}
|
||||
class="h-4 w-4 rounded-sm"
|
||||
data-testid="pref-notify-on-share"
|
||||
/>
|
||||
<label for="notify-on-share" class="text-sm text-[var(--text)]">Email me when someone shares a note with me</label>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="notify-on-collab-removed"
|
||||
checked={prefs.notifyOnCollabRemoved}
|
||||
onchange={() => updatePreference('notifyOnCollabRemoved', !prefs.notifyOnCollabRemoved)}
|
||||
class="h-4 w-4 rounded-sm"
|
||||
data-testid="pref-notify-on-collab-removed"
|
||||
/>
|
||||
<label for="notify-on-collab-removed" class="text-sm text-[var(--text)]">Email me when I'm removed from a shared note</label>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="notify-on-note-deleted"
|
||||
checked={prefs.notifyOnNoteDeleted}
|
||||
onchange={() => updatePreference('notifyOnNoteDeleted', !prefs.notifyOnNoteDeleted)}
|
||||
class="h-4 w-4 rounded-sm"
|
||||
data-testid="pref-notify-on-note-deleted"
|
||||
/>
|
||||
<label for="notify-on-note-deleted" class="text-sm text-[var(--text)]">Email me when a shared note I have access to is deleted</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,30 @@
|
||||
<script lang="ts">
|
||||
import '../app.css';
|
||||
import { onMount } from 'svelte';
|
||||
import { pwaInfo } from 'virtual:pwa-info';
|
||||
|
||||
let { children } = $props();
|
||||
|
||||
onMount(async () => {
|
||||
if (pwaInfo) {
|
||||
const { registerSW } = await import('virtual:pwa-register');
|
||||
registerSW({
|
||||
immediate: true,
|
||||
onRegistered(r: ServiceWorkerRegistration | undefined) {
|
||||
console.log('SW Registered:', r);
|
||||
},
|
||||
onRegisterError(error: Error) {
|
||||
console.log('SW registration error', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const webManifest = $derived(pwaInfo ? pwaInfo.webManifest.linkTag : '');
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
{@html webManifest}
|
||||
</svelte:head>
|
||||
|
||||
{@render children()}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types.js';
|
||||
import { requireAdmin } from '$lib/server/api-utils.js';
|
||||
import { listUsers, createUser } from '$lib/server/auth.js';
|
||||
import { isEmailConfigured, sendWelcomeEmail } from '$lib/server/email.js';
|
||||
|
||||
export const GET: RequestHandler = async (event) => {
|
||||
requireAdmin(event);
|
||||
@@ -21,5 +22,12 @@ export const POST: RequestHandler = async ({ request, ...event }) => {
|
||||
}
|
||||
|
||||
const user = await createUser(email, displayName || email.split('@')[0], password || null, role || 'user');
|
||||
|
||||
// Send welcome email (fire-and-forget)
|
||||
if (isEmailConfigured() && user.email) {
|
||||
const origin = process.env.ORIGIN || 'http://localhost:3000';
|
||||
sendWelcomeEmail(user.email, user.displayName, origin).catch(() => {});
|
||||
}
|
||||
|
||||
return json(user, { status: 201 });
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types.js';
|
||||
import { requireAdmin } from '$lib/server/api-utils.js';
|
||||
import { getUser, deleteUser, updateUserRole, resetPassword, revokeAllSessions } from '$lib/server/auth.js';
|
||||
import { isEmailConfigured, sendPasswordResetEmail, sendRoleChangedEmail } from '$lib/server/email.js';
|
||||
|
||||
export const PATCH: RequestHandler = async ({ params, request, ...event }) => {
|
||||
const admin = requireAdmin(event);
|
||||
@@ -11,12 +12,19 @@ export const PATCH: RequestHandler = async ({ params, request, ...event }) => {
|
||||
const user = getUser(userId);
|
||||
if (!user) throw error(404, 'User not found');
|
||||
|
||||
const origin = process.env.ORIGIN || 'http://localhost:3000';
|
||||
|
||||
if (body.role !== undefined) {
|
||||
// Prevent admin from demoting themselves
|
||||
if (userId === admin.id && body.role !== 'admin') {
|
||||
throw error(400, 'Cannot change your own role');
|
||||
}
|
||||
updateUserRole(userId, body.role);
|
||||
|
||||
// Notify user of role change (fire-and-forget)
|
||||
if (isEmailConfigured() && user.email) {
|
||||
sendRoleChangedEmail(user.email, user.displayName, body.role, origin).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
if (body.newPassword !== undefined) {
|
||||
@@ -24,6 +32,11 @@ export const PATCH: RequestHandler = async ({ params, request, ...event }) => {
|
||||
throw error(400, 'Password must be at least 8 characters');
|
||||
}
|
||||
await resetPassword(userId, body.newPassword);
|
||||
|
||||
// Notify user of password reset (fire-and-forget)
|
||||
if (isEmailConfigured() && user.email) {
|
||||
sendPasswordResetEmail(user.email, user.displayName, origin).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
if (body.revokeSessions) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types.js';
|
||||
import { getUserId } from '$lib/server/api-utils.js';
|
||||
import { verifyPassword, deleteUser, deleteSession, getUser } from '$lib/server/auth.js';
|
||||
import { isEmailConfigured, sendAccountDeletedEmail } from '$lib/server/email.js';
|
||||
|
||||
export const DELETE: RequestHandler = async ({ request, cookies, ...event }) => {
|
||||
const userId = getUserId(event);
|
||||
@@ -17,6 +18,9 @@ export const DELETE: RequestHandler = async ({ request, cookies, ...event }) =>
|
||||
if (!verified) throw error(401, 'Invalid password');
|
||||
}
|
||||
|
||||
// Capture email/name before deletion
|
||||
const { email: userEmail, displayName: userName } = user;
|
||||
|
||||
// Delete user and all associated data
|
||||
await deleteUser(userId);
|
||||
|
||||
@@ -27,5 +31,10 @@ export const DELETE: RequestHandler = async ({ request, cookies, ...event }) =>
|
||||
cookies.delete('session', { path: '/' });
|
||||
}
|
||||
|
||||
// Send deletion confirmation email (fire-and-forget)
|
||||
if (isEmailConfigured() && userEmail) {
|
||||
sendAccountDeletedEmail(userEmail, userName).catch(() => {});
|
||||
}
|
||||
|
||||
return json({ success: true });
|
||||
};
|
||||
|
||||
@@ -3,6 +3,9 @@ import type { RequestHandler } from './$types.js';
|
||||
import { verifyPassword, createSession } from '$lib/server/auth.js';
|
||||
import { checkRateLimit, recordLoginAttempt } from '$lib/server/rate-limit.js';
|
||||
import { db } from '$lib/server/db/index.js';
|
||||
import { users } from '$lib/server/db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { isEmailConfigured, sendAccountLockedEmail } from '$lib/server/email.js';
|
||||
|
||||
export const POST: RequestHandler = async ({ request, cookies, getClientAddress }) => {
|
||||
const ip = getClientAddress();
|
||||
@@ -23,6 +26,27 @@ export const POST: RequestHandler = async ({ request, cookies, getClientAddress
|
||||
const user = await verifyPassword(email, password);
|
||||
if (!user) {
|
||||
recordLoginAttempt(db, ip, email, false);
|
||||
|
||||
// Check if this failure just triggered a lockout — if so, notify the user
|
||||
if (isEmailConfigured()) {
|
||||
const newCheck = checkRateLimit(db, ip, email);
|
||||
if (!newCheck.allowed) {
|
||||
const retryAfterMinutes = Math.ceil((newCheck.retryAfter ?? 900) / 60);
|
||||
const accountUser = db
|
||||
.select({ email: users.email, displayName: users.displayName })
|
||||
.from(users)
|
||||
.where(eq(users.email, email))
|
||||
.get();
|
||||
if (accountUser?.email) {
|
||||
sendAccountLockedEmail(
|
||||
accountUser.email,
|
||||
accountUser.displayName,
|
||||
retryAfterMinutes
|
||||
).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw error(401, 'Invalid email or password');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types.js';
|
||||
import { getUserId } from '$lib/server/api-utils.js';
|
||||
import { updateUserProfile } from '$lib/server/auth.js';
|
||||
import { updateUserProfile, getUser } from '$lib/server/auth.js';
|
||||
import { isEmailConfigured, sendEmailChangedEmail } from '$lib/server/email.js';
|
||||
|
||||
export const PUT: RequestHandler = async ({ request, ...event }) => {
|
||||
const userId = getUserId(event);
|
||||
@@ -11,6 +12,15 @@ export const PUT: RequestHandler = async ({ request, ...event }) => {
|
||||
throw error(400, 'Email cannot be empty');
|
||||
}
|
||||
|
||||
// Capture old email before update to notify on change
|
||||
const existingUser = email !== undefined ? getUser(userId) : null;
|
||||
|
||||
updateUserProfile(userId, { displayName, email });
|
||||
|
||||
// Send notification to old email when email address changes
|
||||
if (isEmailConfigured() && existingUser?.email && email && existingUser.email !== email) {
|
||||
sendEmailChangedEmail(existingUser.email, existingUser.displayName, email).catch(() => {});
|
||||
}
|
||||
|
||||
return json({ success: true });
|
||||
};
|
||||
|
||||
@@ -3,6 +3,9 @@ import type { RequestHandler } from './$types.js';
|
||||
import { db } from '$lib/server/db/index.js';
|
||||
import { getUserId, requireNoteAccess, requireNoteOwnership } from '$lib/server/api-utils.js';
|
||||
import { getNote, updateNote, deleteNote } from '$lib/server/notes-service.js';
|
||||
import { fetchCollaboratorsForNotes } from '$lib/server/collaborators.js';
|
||||
import { isEmailConfigured, sendNotePermanentlyDeletedEmail } from '$lib/server/email.js';
|
||||
import { getPreferences } from '$lib/server/preferences.js';
|
||||
|
||||
export const GET: RequestHandler = async ({ params, ...event }) => {
|
||||
const userId = getUserId(event);
|
||||
@@ -25,8 +28,32 @@ export const DELETE: RequestHandler = async ({ params, ...event }) => {
|
||||
const userId = getUserId(event);
|
||||
requireNoteOwnership(db, params.id, userId);
|
||||
|
||||
// Fetch note and collaborators before deletion to send notifications
|
||||
let collaboratorsToNotify: Array<{ email: string; displayName: string }> = [];
|
||||
let noteTitle = 'Untitled';
|
||||
|
||||
if (isEmailConfigured()) {
|
||||
const note = getNote(db, userId, params.id);
|
||||
if (note) {
|
||||
noteTitle = note.title || 'Untitled';
|
||||
const collabMap = fetchCollaboratorsForNotes(db, [params.id]);
|
||||
const collaborators = collabMap.get(params.id) ?? [];
|
||||
for (const collab of collaborators) {
|
||||
const prefs = getPreferences(db, collab.userId);
|
||||
if (prefs.notifyOnNoteDeleted !== 'false' && collab.email) {
|
||||
collaboratorsToNotify.push({ email: collab.email, displayName: collab.displayName });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const deleted = deleteNote(db, userId, params.id);
|
||||
if (!deleted) throw error(404, 'Note not found');
|
||||
|
||||
// Notify collaborators about the deleted note (fire-and-forget)
|
||||
for (const collab of collaboratorsToNotify) {
|
||||
sendNotePermanentlyDeletedEmail(collab.email, collab.displayName, noteTitle).catch(() => {});
|
||||
}
|
||||
|
||||
return json({ success: true });
|
||||
};
|
||||
|
||||
@@ -5,7 +5,11 @@ import { addCollaborator, removeCollaborator, fetchCollaboratorsForNotes } from
|
||||
import { db } from '$lib/server/db/index.js';
|
||||
import { users, notes, noteCollaborators } from '$lib/server/db/schema.js';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { isEmailConfigured, sendShareNotification } from '$lib/server/email.js';
|
||||
import {
|
||||
isEmailConfigured,
|
||||
sendShareNotification,
|
||||
sendCollaboratorRemovedEmail
|
||||
} from '$lib/server/email.js';
|
||||
import { getPreferences } from '$lib/server/preferences.js';
|
||||
|
||||
export const GET: RequestHandler = async ({ params, ...event }) => {
|
||||
@@ -102,7 +106,50 @@ export const DELETE: RequestHandler = async ({ params, url, ...event }) => {
|
||||
throw error(403, 'Only the owner can remove other collaborators');
|
||||
}
|
||||
|
||||
// Fetch collaborator info and note title before removal for email notification
|
||||
let removedUserEmail: string | undefined;
|
||||
let removedUserName: string | undefined;
|
||||
let noteTitle: string | undefined;
|
||||
let ownerName: string | undefined;
|
||||
|
||||
if (isEmailConfigured() && isOwner && targetUserId !== userId) {
|
||||
const targetPrefs = getPreferences(db, targetUserId);
|
||||
if (targetPrefs.notifyOnCollabRemoved !== 'false') {
|
||||
const target = db
|
||||
.select({ email: users.email, displayName: users.displayName })
|
||||
.from(users)
|
||||
.where(eq(users.id, targetUserId))
|
||||
.get();
|
||||
const noteData = db
|
||||
.select({ title: notes.title })
|
||||
.from(notes)
|
||||
.where(eq(notes.id, params.id))
|
||||
.get();
|
||||
const owner = db
|
||||
.select({ displayName: users.displayName })
|
||||
.from(users)
|
||||
.where(eq(users.id, userId))
|
||||
.get();
|
||||
removedUserEmail = target?.email ?? undefined;
|
||||
removedUserName = target?.displayName ?? undefined;
|
||||
noteTitle = noteData?.title ?? undefined;
|
||||
ownerName = owner?.displayName ?? undefined;
|
||||
}
|
||||
}
|
||||
|
||||
removeCollaborator(db, params.id, targetUserId);
|
||||
|
||||
// Send notification to removed collaborator (fire-and-forget)
|
||||
if (removedUserEmail) {
|
||||
const origin = process.env.ORIGIN || 'http://localhost:3000';
|
||||
sendCollaboratorRemovedEmail(
|
||||
removedUserEmail,
|
||||
removedUserName || '',
|
||||
ownerName || 'Someone',
|
||||
noteTitle || 'Untitled',
|
||||
origin
|
||||
).catch(() => {});
|
||||
}
|
||||
|
||||
return json({ success: true });
|
||||
};
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "Crumbs by Bretzel",
|
||||
"short_name": "Crumbs",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/web-app-manifest-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
},
|
||||
{
|
||||
"src": "/web-app-manifest-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
],
|
||||
"theme_color": "#f9f4ea",
|
||||
"background_color": "#f9f4ea",
|
||||
"display": "standalone"
|
||||
}
|
||||
+4
-1
@@ -5,7 +5,10 @@ const config = {
|
||||
kit: {
|
||||
adapter: adapter({
|
||||
out: 'build'
|
||||
})
|
||||
}),
|
||||
serviceWorker: {
|
||||
register: false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -62,8 +62,11 @@ test.describe('Offline Support', () => {
|
||||
await expect(page.getByText('Survive Reload')).toBeVisible();
|
||||
|
||||
// When the network is restored and sync completes
|
||||
const syncResponse = page.waitForResponse('**/api/sync');
|
||||
const syncResponse = page.waitForResponse((resp) => resp.url().includes('/api/sync'));
|
||||
await page.context().setOffline(false);
|
||||
// Manually dispatch the online event as a safety net — in CI/headless
|
||||
// environments, setOffline(false) doesn't always emit it reliably
|
||||
await page.evaluate(() => window.dispatchEvent(new Event('online')));
|
||||
await syncResponse;
|
||||
|
||||
// And the user reloads the page
|
||||
|
||||
@@ -124,6 +124,37 @@ test.describe('Note Sharing', () => {
|
||||
expect(syncedNote.content).toBe('Owner sync update');
|
||||
});
|
||||
|
||||
test('Scenario: Both users\' edits to different fields are preserved after concurrent PATCH', async ({
|
||||
authenticatedPage: page,
|
||||
collabPage
|
||||
}) => {
|
||||
// Given a shared checklist note exists
|
||||
const note = await createSharedNote(
|
||||
page,
|
||||
collabPage,
|
||||
'Shopping List',
|
||||
'- [ ] Milk\n- [ ] Bread\n- [ ] Eggs'
|
||||
);
|
||||
|
||||
// When the owner checks Milk
|
||||
await page.request.patch(`/api/notes/${note.id}`, {
|
||||
data: { content: '- [x] Milk\n- [ ] Bread\n- [ ] Eggs', baseVersion: note.version }
|
||||
});
|
||||
|
||||
// And the collaborator adds Butter (based on the same original version)
|
||||
await collabPage.request.patch(`/api/notes/${note.id}`, {
|
||||
data: { content: '- [ ] Milk\n- [ ] Bread\n- [ ] Eggs\n- [ ] Butter', baseVersion: note.version }
|
||||
});
|
||||
|
||||
// Then both changes are preserved via content merge
|
||||
const res = await page.request.get(`/api/notes/${note.id}`);
|
||||
const merged = await res.json();
|
||||
expect(merged.content).toContain('- [x] Milk');
|
||||
expect(merged.content).toContain('- [ ] Butter');
|
||||
expect(merged.content).toContain('- [ ] Bread');
|
||||
expect(merged.content).toContain('- [ ] Eggs');
|
||||
});
|
||||
|
||||
test('Scenario: Collaborator sees leave action and can leave a shared note', async ({
|
||||
authenticatedPage: page,
|
||||
collabPage
|
||||
|
||||
+26
-5
@@ -23,6 +23,8 @@ export default defineConfig({
|
||||
]
|
||||
: []),
|
||||
SvelteKitPWA({
|
||||
scope: '/',
|
||||
buildBase: '/',
|
||||
registerType: 'autoUpdate',
|
||||
manifest: {
|
||||
name: 'Crumbs by Bretzel',
|
||||
@@ -34,16 +36,26 @@ export default defineConfig({
|
||||
theme_color: '#C8860A',
|
||||
icons: [
|
||||
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
|
||||
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
|
||||
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' }
|
||||
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' }
|
||||
]
|
||||
},
|
||||
workbox: {
|
||||
globPatterns: ['client/**/*.{js,css,ico,png,svg,webp,woff,woff2}'],
|
||||
navigateFallback: '/',
|
||||
navigateFallback: null,
|
||||
runtimeCaching: [
|
||||
{
|
||||
urlPattern: /\/api\/notes\/.*\/attachments\?attachmentId=/,
|
||||
urlPattern: ({ request }) => request.mode === 'navigate',
|
||||
handler: 'NetworkFirst',
|
||||
options: {
|
||||
cacheName: 'pages-cache',
|
||||
networkTimeoutSeconds: 3,
|
||||
expiration: { maxEntries: 50, maxAgeSeconds: 30 * 24 * 60 * 60 }
|
||||
}
|
||||
},
|
||||
{
|
||||
urlPattern: ({ request, url }) =>
|
||||
request.method === 'GET' &&
|
||||
/\/api\/notes\/.*\/attachments\?attachmentId=/.test(url.href),
|
||||
handler: 'CacheFirst',
|
||||
options: {
|
||||
cacheName: 'attachment-cache',
|
||||
@@ -51,12 +63,21 @@ export default defineConfig({
|
||||
}
|
||||
},
|
||||
{
|
||||
urlPattern: /^https?:\/\/.*\/api\//,
|
||||
urlPattern: ({ request, url }) =>
|
||||
request.method === 'GET' && /\/api\//.test(url.pathname),
|
||||
handler: 'NetworkFirst',
|
||||
options: {
|
||||
cacheName: 'api-cache',
|
||||
expiration: { maxEntries: 50, maxAgeSeconds: 300 }
|
||||
}
|
||||
},
|
||||
{
|
||||
urlPattern: /^https?:\/\/fonts\.(?:googleapis|gstatic)\.com\/.*/,
|
||||
handler: 'CacheFirst',
|
||||
options: {
|
||||
cacheName: 'google-fonts-cache',
|
||||
expiration: { maxEntries: 10, maxAgeSeconds: 365 * 24 * 60 * 60 }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+28
-1
@@ -166,6 +166,33 @@
|
||||
<h3>OAuth & SSO</h3>
|
||||
<p>Sign in with Google, GitHub, or any OIDC provider. Or just use a password — your choice.</p>
|
||||
</div>
|
||||
|
||||
<!-- Note Sharing -->
|
||||
<div class="feature-card animate-in delay-4">
|
||||
<div class="feature-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
|
||||
</div>
|
||||
<h3>Note Sharing</h3>
|
||||
<p>Share notes with other users on your instance. Full collaboration with per-user pins and archives.</p>
|
||||
</div>
|
||||
|
||||
<!-- Version History -->
|
||||
<div class="feature-card animate-in delay-5">
|
||||
<div class="feature-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
|
||||
</div>
|
||||
<h3>Version History</h3>
|
||||
<p>Browse and restore previous versions of any note. Never lose important edits again.</p>
|
||||
</div>
|
||||
|
||||
<!-- Email Notifications -->
|
||||
<div class="feature-card animate-in delay-6">
|
||||
<div class="feature-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
|
||||
</div>
|
||||
<h3>Email Alerts</h3>
|
||||
<p>Optional SMTP notifications for shares, security alerts, and account events. Opt out per user.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -253,7 +280,7 @@
|
||||
<li><a href="https://github.com/bretzel-app/crumbs/blob/main/docs/DEPLOYMENT.md" target="_blank" rel="noopener">Docs</a></li>
|
||||
<li><a href="https://github.com/bretzel-app/crumbs/blob/main/LICENSE" target="_blank" rel="noopener">License</a></li>
|
||||
</ul>
|
||||
<span class="footer-version">v0.20.0</span>
|
||||
<span class="footer-version">v0.21.8</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user