@knotpad/app 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +167 -0
- package/app/(app)/calendar/page.tsx +57 -0
- package/app/(app)/error.tsx +35 -0
- package/app/(app)/graph/page.tsx +32 -0
- package/app/(app)/guide/page.tsx +21 -0
- package/app/(app)/kanban/loading.tsx +24 -0
- package/app/(app)/kanban/page.tsx +59 -0
- package/app/(app)/layout.tsx +122 -0
- package/app/(app)/list/loading.tsx +21 -0
- package/app/(app)/list/page.tsx +137 -0
- package/app/(app)/loading.tsx +18 -0
- package/app/(app)/notes/[noteId]/page.tsx +84 -0
- package/app/(app)/notes/layout.tsx +30 -0
- package/app/(app)/notes/page.tsx +39 -0
- package/app/(app)/page.tsx +5 -0
- package/app/(app)/settings/agent-token/page.tsx +59 -0
- package/app/(app)/settings/backup/page.tsx +49 -0
- package/app/(app)/settings/billing/page.tsx +53 -0
- package/app/(app)/settings/calendar/page.tsx +41 -0
- package/app/(app)/settings/layout.test.tsx +39 -0
- package/app/(app)/settings/layout.tsx +71 -0
- package/app/(app)/settings/page.tsx +4 -0
- package/app/(app)/settings/security/page.tsx +43 -0
- package/app/(app)/settings/team/page.tsx +74 -0
- package/app/(app)/settings/workspace/page.tsx +27 -0
- package/app/(app)/tasks/[taskId]/page.tsx +79 -0
- package/app/(auth)/forgot-password/page.tsx +106 -0
- package/app/(auth)/guest/page.tsx +56 -0
- package/app/(auth)/layout.tsx +13 -0
- package/app/(auth)/login/page.tsx +14 -0
- package/app/(auth)/register/page.tsx +193 -0
- package/app/(auth)/reset-password/page.tsx +138 -0
- package/app/api/account/claim/route.tsx +135 -0
- package/app/api/admin/backfill-encryption/route.tsx +43 -0
- package/app/api/admin/license/route.tsx +42 -0
- package/app/api/auth/2fa/route.tsx +148 -0
- package/app/api/auth/[...nextauth]/route.tsx +3 -0
- package/app/api/auth/change-password/route.tsx +61 -0
- package/app/api/auth/check-2fa/route.tsx +19 -0
- package/app/api/auth/forgot-password/route.tsx +65 -0
- package/app/api/auth/reset-password/route.tsx +52 -0
- package/app/api/auth/verify-2fa/route.tsx +88 -0
- package/app/api/backup/download/db/route.ts +29 -0
- package/app/api/backup/download/notes/route.ts +25 -0
- package/app/api/backup/settings/route.ts +92 -0
- package/app/api/billing/checkout/route.tsx +81 -0
- package/app/api/billing/migrate/route.tsx +163 -0
- package/app/api/billing/portal/route.tsx +24 -0
- package/app/api/billing/setup-intent/route.tsx +55 -0
- package/app/api/billing/status/route.tsx +36 -0
- package/app/api/billing/subscribe/route.tsx +85 -0
- package/app/api/billing/webhook/route.tsx +199 -0
- package/app/api/calendar-feeds/[feedId]/route.tsx +67 -0
- package/app/api/calendar-feeds/[feedId]/sync/route.tsx +37 -0
- package/app/api/calendar-feeds/events/route.tsx +82 -0
- package/app/api/calendar-feeds/route.tsx +52 -0
- package/app/api/calendar-feeds/sync-all/route.tsx +34 -0
- package/app/api/cron/calendar-feeds/route.tsx +31 -0
- package/app/api/cron/stale-tasks/route.tsx +51 -0
- package/app/api/cron/sync/route.tsx +34 -0
- package/app/api/devices/[deviceId]/route.tsx +25 -0
- package/app/api/devices/route.tsx +41 -0
- package/app/api/export/route.tsx +40 -0
- package/app/api/feedback/route.tsx +54 -0
- package/app/api/folders/[folderId]/route.tsx +51 -0
- package/app/api/folders/route.tsx +37 -0
- package/app/api/graph/route.tsx +242 -0
- package/app/api/guest/route.tsx +58 -0
- package/app/api/health/route.tsx +10 -0
- package/app/api/holidays/countries/route.tsx +14 -0
- package/app/api/holidays/route.tsx +49 -0
- package/app/api/holidays/states/route.tsx +21 -0
- package/app/api/invites/[token]/route.tsx +131 -0
- package/app/api/invites/route.tsx +74 -0
- package/app/api/mcp/generate-token/route.tsx +55 -0
- package/app/api/mcp/revoke-token/[tokenId]/route.tsx +30 -0
- package/app/api/mcp/update-alias/[tokenId]/route.tsx +22 -0
- package/app/api/notes/[noteId]/export/route.tsx +45 -0
- package/app/api/notes/[noteId]/route.tsx +360 -0
- package/app/api/notes/route.tsx +112 -0
- package/app/api/notifications/route.tsx +44 -0
- package/app/api/register/route.tsx +67 -0
- package/app/api/restore/route.tsx +148 -0
- package/app/api/sync/conflicts/[conflictId]/route.tsx +134 -0
- package/app/api/sync/conflicts/route.tsx +48 -0
- package/app/api/sync/status/route.tsx +49 -0
- package/app/api/sync/trigger/route.tsx +15 -0
- package/app/api/tasks/[taskId]/detail/route.tsx +68 -0
- package/app/api/tasks/[taskId]/route.tsx +259 -0
- package/app/api/tasks/bulk/route.tsx +133 -0
- package/app/api/tasks/route.tsx +36 -0
- package/app/api/workspace/active/route.tsx +39 -0
- package/app/api/workspace/create-team/route.tsx +42 -0
- package/app/api/workspace/kanban-statuses/route.tsx +71 -0
- package/app/api/workspace/members/[memberId]/route.tsx +69 -0
- package/app/api/workspace/route.tsx +24 -0
- package/app/download/page.tsx +170 -0
- package/app/favicon.ico +0 -0
- package/app/generated/prisma/client.d.ts +1 -0
- package/app/generated/prisma/client.js +5 -0
- package/app/generated/prisma/default.d.ts +1 -0
- package/app/generated/prisma/default.js +5 -0
- package/app/generated/prisma/edge.d.ts +1 -0
- package/app/generated/prisma/edge.js +497 -0
- package/app/generated/prisma/index-browser.js +523 -0
- package/app/generated/prisma/index.d.ts +46376 -0
- package/app/generated/prisma/index.js +497 -0
- package/app/generated/prisma/package.json +144 -0
- package/app/generated/prisma/query_compiler_fast_bg.js +2 -0
- package/app/generated/prisma/query_compiler_fast_bg.wasm +0 -0
- package/app/generated/prisma/query_compiler_fast_bg.wasm-base64.js +2 -0
- package/app/generated/prisma/runtime/client.d.ts +3386 -0
- package/app/generated/prisma/runtime/client.js +86 -0
- package/app/generated/prisma/runtime/index-browser.d.ts +90 -0
- package/app/generated/prisma/runtime/index-browser.js +6 -0
- package/app/generated/prisma/runtime/wasm-compiler-edge.js +76 -0
- package/app/generated/prisma/schema.prisma +456 -0
- package/app/generated/prisma/wasm-edge-light-loader.mjs +5 -0
- package/app/generated/prisma/wasm-worker-loader.mjs +5 -0
- package/app/globals.css +54 -0
- package/app/invite/[token]/page.tsx +52 -0
- package/app/layout.tsx +90 -0
- package/app/mcp/route.tsx +430 -0
- package/app/opengraph-image.tsx +120 -0
- package/app/page.tsx +398 -0
- package/app/privacy/page.tsx +69 -0
- package/app/robots.tsx +25 -0
- package/app/sitemap.tsx +36 -0
- package/app/terms/page.tsx +69 -0
- package/app/upgrade/page.tsx +75 -0
- package/auth.config.ts +33 -0
- package/auth.ts +79 -0
- package/bin/brief.js +224 -0
- package/components/auth/login-form.tsx +302 -0
- package/components/auth/password-checklist.tsx +31 -0
- package/components/auth/password-input.tsx +36 -0
- package/components/auth/switch-account-button.test.tsx +22 -0
- package/components/auth/switch-account-button.tsx +19 -0
- package/components/auth/two-factor-input.tsx +116 -0
- package/components/billing/billing-dashboard.tsx +265 -0
- package/components/billing/card-form.tsx +210 -0
- package/components/billing/claim-account-form.tsx +99 -0
- package/components/branding/app-logo.test.tsx +20 -0
- package/components/branding/app-logo.tsx +25 -0
- package/components/calendar/calendar-agenda.tsx +150 -0
- package/components/calendar/calendar-drag.test.tsx +177 -0
- package/components/calendar/calendar-grid.tsx +357 -0
- package/components/calendar/calendar-hooks.test.tsx +27 -0
- package/components/calendar/calendar-hooks.ts +351 -0
- package/components/calendar/calendar-toolbar.test.tsx +68 -0
- package/components/calendar/calendar-toolbar.tsx +291 -0
- package/components/calendar/calendar-types.ts +148 -0
- package/components/calendar/calendar-view.test.tsx +295 -0
- package/components/calendar/calendar-view.tsx +307 -0
- package/components/calendar/day-detail-popover.tsx +174 -0
- package/components/calendar/task-chip.tsx +86 -0
- package/components/command/command-palette.test.tsx +33 -0
- package/components/command/command-palette.tsx +310 -0
- package/components/download-cta.tsx +87 -0
- package/components/feedback/feedback-popup.tsx +207 -0
- package/components/graph/graph-draw.ts +337 -0
- package/components/graph/graph-overlays.tsx +160 -0
- package/components/graph/graph-page.test.tsx +131 -0
- package/components/graph/graph-page.tsx +263 -0
- package/components/graph/graph-types.ts +47 -0
- package/components/graph/graph-view.tsx +322 -0
- package/components/guide/guide-view.tsx +522 -0
- package/components/kanban/kanban-board.test.tsx +128 -0
- package/components/kanban/kanban-board.tsx +361 -0
- package/components/kanban/kanban-card-menu.tsx +102 -0
- package/components/kanban/kanban-card.tsx +227 -0
- package/components/kanban/kanban-column.tsx +49 -0
- package/components/kanban/kanban-status-context.tsx +28 -0
- package/components/landing/calendar-sandbox.test.tsx +15 -0
- package/components/landing/calendar-sandbox.tsx +107 -0
- package/components/landing/graph-sandbox.test.tsx +27 -0
- package/components/landing/graph-sandbox.tsx +80 -0
- package/components/landing/kanban-sandbox.test.tsx +24 -0
- package/components/landing/kanban-sandbox.tsx +101 -0
- package/components/landing/landing-showcase.test.tsx +21 -0
- package/components/landing/landing-showcase.tsx +54 -0
- package/components/landing/list-sandbox.tsx +86 -0
- package/components/landing/mock-workspace.ts +168 -0
- package/components/landing/notes-sandbox.test.tsx +14 -0
- package/components/landing/notes-sandbox.tsx +88 -0
- package/components/layout/app-shell.tsx +83 -0
- package/components/layout/backup-scheduler.tsx +122 -0
- package/components/layout/bottom-nav.tsx +43 -0
- package/components/layout/icon-bar.test.tsx +29 -0
- package/components/layout/icon-bar.tsx +118 -0
- package/components/layout/mobile-top-bar.tsx +68 -0
- package/components/layout/notes-panel-folder.tsx +127 -0
- package/components/layout/notes-panel-note-item.tsx +140 -0
- package/components/layout/notes-panel-task-tab.tsx +63 -0
- package/components/layout/notes-panel-types.ts +44 -0
- package/components/layout/notes-panel.tsx +476 -0
- package/components/layout/notification-bell.tsx +251 -0
- package/components/layout/paywall-screen.tsx +41 -0
- package/components/layout/pro-banner.tsx +76 -0
- package/components/layout/sw-register.tsx +27 -0
- package/components/layout/workspace-switcher.tsx +90 -0
- package/components/notes/mobile-bottom-sheet.tsx +99 -0
- package/components/notes/note-editor-context-menu.tsx +47 -0
- package/components/notes/note-editor-dom.ts +33 -0
- package/components/notes/note-editor-dropdowns.tsx +484 -0
- package/components/notes/note-editor-hooks.ts +692 -0
- package/components/notes/note-editor-keyboard.ts +305 -0
- package/components/notes/note-editor-overlay.tsx +90 -0
- package/components/notes/note-editor.test.tsx +372 -0
- package/components/notes/note-editor.tsx +662 -0
- package/components/notes/note-preview-pane.tsx +156 -0
- package/components/notes/note-tabs.tsx +120 -0
- package/components/notes/note-types.tsx +157 -0
- package/components/settings/accept-invite.tsx +108 -0
- package/components/settings/agent-token-settings.tsx +369 -0
- package/components/settings/backup-restore-settings.test.tsx +25 -0
- package/components/settings/backup-restore-settings.tsx +327 -0
- package/components/settings/calendar-feeds-settings.tsx +489 -0
- package/components/settings/calendar-general-settings.tsx +174 -0
- package/components/settings/confirm-danger-action.test.tsx +215 -0
- package/components/settings/confirm-danger-action.tsx +65 -0
- package/components/settings/security-settings.tsx +252 -0
- package/components/settings/settings-guidance.test.tsx +98 -0
- package/components/settings/team-settings.tsx +319 -0
- package/components/settings/two-factor-auth.tsx +296 -0
- package/components/settings/workspace-settings-client.tsx +363 -0
- package/components/settings/workspace-settings-form.tsx +73 -0
- package/components/sync/conflict-viewer.tsx +247 -0
- package/components/sync/sync-indicator.tsx +171 -0
- package/components/tasks/snippet-thread.tsx +119 -0
- package/components/tasks/status-dot.tsx +47 -0
- package/components/tasks/task-badge.tsx +43 -0
- package/components/tasks/task-detail.test.tsx +187 -0
- package/components/tasks/task-detail.tsx +458 -0
- package/components/tasks/task-list-filters.test.tsx +75 -0
- package/components/tasks/task-list-filters.tsx +163 -0
- package/components/tasks/task-list-types.ts +20 -0
- package/components/tasks/task-list.test.tsx +175 -0
- package/components/tasks/task-list.tsx +481 -0
- package/components/tasks/task-row.tsx +85 -0
- package/components/tasks/task-table-row.tsx +259 -0
- package/components/ui/skeleton.tsx +3 -0
- package/components/ui/toast.test.tsx +42 -0
- package/components/ui/toast.tsx +70 -0
- package/electron/main.ts +251 -0
- package/electron/preload.ts +56 -0
- package/instrumentation.tsx +23 -0
- package/lib/api-error.ts +50 -0
- package/lib/backup/backup-runner.test.ts +32 -0
- package/lib/backup/backup-runner.ts +19 -0
- package/lib/backup/backup-schedule.test.ts +23 -0
- package/lib/backup/backup-schedule.ts +55 -0
- package/lib/backup/backup-settings.test.ts +30 -0
- package/lib/backup/backup-settings.ts +27 -0
- package/lib/backup/export-notes-zip.test.ts +26 -0
- package/lib/backup/export-notes-zip.ts +82 -0
- package/lib/backup/export-workspace-backup.test.ts +17 -0
- package/lib/backup/export-workspace-backup.ts +77 -0
- package/lib/backup/restore-workspace-from-export.test.ts +18 -0
- package/lib/backup/restore-workspace-from-export.ts +183 -0
- package/lib/backup/types.ts +14 -0
- package/lib/brand-icons.ts +1 -0
- package/lib/calendar-feed-crypto.ts +38 -0
- package/lib/calendar-feed.ts +239 -0
- package/lib/client/online-status.ts +47 -0
- package/lib/conflict-resolver.test.ts +57 -0
- package/lib/conflict-resolver.ts +240 -0
- package/lib/db-init.ts +79 -0
- package/lib/email.ts +159 -0
- package/lib/encryption.test.ts +41 -0
- package/lib/encryption.ts +98 -0
- package/lib/extract-snippet.test.ts +123 -0
- package/lib/extract-snippet.ts +69 -0
- package/lib/kanban-status.ts +55 -0
- package/lib/license.ts +21 -0
- package/lib/limits.ts +31 -0
- package/lib/mcp-auth.test.ts +58 -0
- package/lib/mcp-auth.ts +65 -0
- package/lib/mcp-contract.test.ts +25 -0
- package/lib/mcp-contract.ts +210 -0
- package/lib/mcp-handler.ts +31 -0
- package/lib/mcp-url.test.ts +12 -0
- package/lib/mcp-url.ts +7 -0
- package/lib/mentions.test.ts +45 -0
- package/lib/mentions.ts +73 -0
- package/lib/note-crypto.ts +108 -0
- package/lib/note-sync.ts +201 -0
- package/lib/note-title.ts +93 -0
- package/lib/prisma.ts +193 -0
- package/lib/pro-flush.ts +292 -0
- package/lib/rate-limit.ts +57 -0
- package/lib/stripe.ts +38 -0
- package/lib/sync-worker.ts +388 -0
- package/lib/task-parser.test.ts +91 -0
- package/lib/task-parser.ts +81 -0
- package/lib/task-utils.ts +52 -0
- package/lib/use-is-electron.ts +19 -0
- package/lib/use-is-mobile.ts +22 -0
- package/lib/validation/calendar-feed.ts +31 -0
- package/lib/validation/note.ts +27 -0
- package/lib/validation/task.ts +26 -0
- package/lib/view-preferences.test.ts +54 -0
- package/lib/view-preferences.ts +28 -0
- package/lib/workspace.ts +66 -0
- package/next.config.ts +21 -0
- package/package.json +99 -0
- package/postcss.config.mjs +7 -0
- package/prisma/migrations/20260519021916_init/migration.sql +388 -0
- package/prisma/migrations/20260519061113_drop_sync_password/migration.sql +8 -0
- package/prisma/migrations/20260520065016_add_task_start_date/migration.sql +2 -0
- package/prisma/migrations/20260529010600_remove_encryption_fields/migration.sql +12 -0
- package/prisma/migrations/20260529020000_restore_encryption_salt/migration.sql +3 -0
- package/prisma/migrations/20260529030000_add_folders/migration.sql +17 -0
- package/prisma/migrations/20260605000000_deferred_fixes/migration.sql +31 -0
- package/prisma/migrations/20260605020806_add_pending_sync_to_note_and_task/migration.sql +5 -0
- package/prisma/migrations/20260605063634_add_stripe_webhook_event_sync_lock/migration.sql +14 -0
- package/prisma/migrations/20260605100000_add_prod_indexes/migration.sql +26 -0
- package/prisma/migrations/20260608081404_add_kanban_statuses/migration.sql +23 -0
- package/prisma/migrations/20260611032723_add_calendar_feeds/migration.sql +43 -0
- package/prisma/migrations/20260611040000_add_calendar_feed_color/migration.sql +2 -0
- package/prisma/migrations/20260611050000_add_task_priority/migration.sql +14 -0
- package/prisma/migrations/20260612060000_add_critical_priority/migration.sql +2 -0
- package/prisma/migrations/20260613090000_add_backup_settings/migration.sql +25 -0
- package/prisma/migrations/20260614160000_add_feedback/migration.sql +20 -0
- package/prisma/migrations/20260614210000_add_2fa/migration.sql +4 -0
- package/prisma/migrations/migration_lock.toml +3 -0
- package/prisma/schema.prisma +457 -0
- package/public/Logo_icon.svg +1 -0
- package/public/file.svg +1 -0
- package/public/globe.svg +1 -0
- package/public/icon-192.png +0 -0
- package/public/icon-512.png +0 -0
- package/public/icon.svg +4 -0
- package/public/icon_dark.svg +1 -0
- package/public/knotpad_icon.svg +1 -0
- package/public/knotpad_logo_full.svg +1 -0
- package/public/manifest.json +14 -0
- package/public/next.svg +1 -0
- package/public/sw.js +137 -0
- package/public/vercel.svg +1 -0
- package/public/window.svg +1 -0
- package/tsconfig.json +35 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { threeWayMerge, lastWriteWins } from "@/lib/conflict-resolver";
|
|
3
|
+
|
|
4
|
+
const P = (...ps: string[]) => ps.join("\n\n");
|
|
5
|
+
|
|
6
|
+
describe("threeWayMerge", () => {
|
|
7
|
+
it("returns either side when they are equal", () => {
|
|
8
|
+
const r = threeWayMerge("base", "same", "same");
|
|
9
|
+
expect(r.merged).toBe("same");
|
|
10
|
+
expect(r.hasConflicts).toBe(false);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it("takes the changed side when the other is unchanged", () => {
|
|
14
|
+
expect(threeWayMerge("a", "a", "b").merged).toBe("b");
|
|
15
|
+
expect(threeWayMerge("a", "b", "a").merged).toBe("b");
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("unions non-overlapping additions from both sides", () => {
|
|
19
|
+
const base = P("intro");
|
|
20
|
+
const local = P("intro", "local note");
|
|
21
|
+
const cloud = P("intro", "cloud note");
|
|
22
|
+
const r = threeWayMerge(base, local, cloud);
|
|
23
|
+
expect(r.hasConflicts).toBe(false);
|
|
24
|
+
expect(r.merged).toContain("local note");
|
|
25
|
+
expect(r.merged).toContain("cloud note");
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("preserves legitimately duplicated paragraphs (no global de-dup)", () => {
|
|
29
|
+
const dup = P("repeat", "repeat", "tail");
|
|
30
|
+
const r = threeWayMerge("repeat", dup, dup);
|
|
31
|
+
expect(r.merged).toBe(dup);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("flags competing edits in the same region as a conflict", () => {
|
|
35
|
+
const base = P("anchor", "original", "end");
|
|
36
|
+
const local = P("anchor", "local edit", "end");
|
|
37
|
+
const cloud = P("anchor", "cloud edit", "end");
|
|
38
|
+
const r = threeWayMerge(base, local, cloud);
|
|
39
|
+
expect(r.hasConflicts).toBe(true);
|
|
40
|
+
expect(r.conflicts[0]).toEqual({ localVersion: "local edit", cloudVersion: "cloud edit" });
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe("lastWriteWins", () => {
|
|
45
|
+
it("prefers the newer timestamp", () => {
|
|
46
|
+
const older = { id: "a", updatedAt: new Date(1000), version: 5 };
|
|
47
|
+
const newer = { id: "a", updatedAt: new Date(2000), version: 1 };
|
|
48
|
+
expect(lastWriteWins(newer, older)).toBe("local");
|
|
49
|
+
expect(lastWriteWins(older, newer)).toBe("cloud");
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("breaks ties by version", () => {
|
|
53
|
+
const local = { id: "a", updatedAt: new Date(1000), version: 3 };
|
|
54
|
+
const cloud = { id: "a", updatedAt: new Date(1000), version: 2 };
|
|
55
|
+
expect(lastWriteWins(local, cloud)).toBe("local");
|
|
56
|
+
});
|
|
57
|
+
});
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { prisma, getCloudPrisma } from "@/lib/prisma";
|
|
2
|
+
import type { PrismaClient } from "@/app/generated/prisma/client";
|
|
3
|
+
|
|
4
|
+
// --- Types ---
|
|
5
|
+
|
|
6
|
+
export type MergeResult = {
|
|
7
|
+
merged: string;
|
|
8
|
+
hasConflicts: boolean;
|
|
9
|
+
conflicts: Array<{ localVersion: string; cloudVersion: string }>;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export type TaskSyncable = {
|
|
13
|
+
id: string;
|
|
14
|
+
updatedAt: Date;
|
|
15
|
+
version: number;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// --- Last Write Wins ---
|
|
19
|
+
|
|
20
|
+
export function lastWriteWins(
|
|
21
|
+
local: TaskSyncable,
|
|
22
|
+
cloud: TaskSyncable
|
|
23
|
+
): "local" | "cloud" {
|
|
24
|
+
if (local.updatedAt > cloud.updatedAt) return "local";
|
|
25
|
+
if (cloud.updatedAt > local.updatedAt) return "cloud";
|
|
26
|
+
return local.version >= cloud.version ? "local" : "cloud";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// --- Union Merge for task ID sets ---
|
|
30
|
+
|
|
31
|
+
export function unionMergeIds(
|
|
32
|
+
localIds: Set<string>,
|
|
33
|
+
cloudIds: Set<string>
|
|
34
|
+
): { onlyLocal: string[]; onlyCloud: string[] } {
|
|
35
|
+
const onlyLocal = [...localIds].filter((id) => !cloudIds.has(id));
|
|
36
|
+
const onlyCloud = [...cloudIds].filter((id) => !localIds.has(id));
|
|
37
|
+
return { onlyLocal, onlyCloud };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// --- Paragraph-level three-way merge ---
|
|
41
|
+
|
|
42
|
+
function splitParagraphs(text: string): string[] {
|
|
43
|
+
return text.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Longest Common Subsequence of paragraph arrays
|
|
47
|
+
function lcs(a: string[], b: string[]): string[] {
|
|
48
|
+
const m = a.length;
|
|
49
|
+
const n = b.length;
|
|
50
|
+
|
|
51
|
+
// Bail on very large inputs to avoid O(mn) blowup
|
|
52
|
+
if (m * n > 40000) return [];
|
|
53
|
+
|
|
54
|
+
const dp: number[][] = Array.from({ length: m + 1 }, () =>
|
|
55
|
+
new Array(n + 1).fill(0)
|
|
56
|
+
);
|
|
57
|
+
for (let i = 1; i <= m; i++) {
|
|
58
|
+
for (let j = 1; j <= n; j++) {
|
|
59
|
+
dp[i][j] =
|
|
60
|
+
a[i - 1] === b[j - 1]
|
|
61
|
+
? dp[i - 1][j - 1] + 1
|
|
62
|
+
: Math.max(dp[i - 1][j], dp[i][j - 1]);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const result: string[] = [];
|
|
67
|
+
let i = m, j = n;
|
|
68
|
+
while (i > 0 && j > 0) {
|
|
69
|
+
if (a[i - 1] === b[j - 1]) {
|
|
70
|
+
result.unshift(a[i - 1]);
|
|
71
|
+
i--;
|
|
72
|
+
j--;
|
|
73
|
+
} else if (dp[i - 1][j] >= dp[i][j - 1]) {
|
|
74
|
+
i--;
|
|
75
|
+
} else {
|
|
76
|
+
j--;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Three-way merge at the paragraph level.
|
|
84
|
+
*
|
|
85
|
+
* base = last synced content (stored snapshot)
|
|
86
|
+
* local = current local content
|
|
87
|
+
* cloud = current cloud content
|
|
88
|
+
*
|
|
89
|
+
* Strategy: anchor on the longest common subsequence of local↔cloud paragraphs.
|
|
90
|
+
* Between consecutive anchors, each side may contribute a "run" of paragraphs:
|
|
91
|
+
* - one side empty → take the other side's run (an add/keep)
|
|
92
|
+
* - both runs identical → take it once (same edit on both sides)
|
|
93
|
+
* - both runs differ → genuine conflict in that region (flag it,
|
|
94
|
+
* and keep the local run in the provisional
|
|
95
|
+
* merge, which is only used when nothing conflicts)
|
|
96
|
+
* Anchors are consumed in order, so legitimately repeated paragraphs are
|
|
97
|
+
* preserved (no global de-duplication). Union bias is intentional for PM notes:
|
|
98
|
+
* when in doubt we keep content rather than drop it.
|
|
99
|
+
*
|
|
100
|
+
* `base` is used for the equality fast-paths; the merge itself is local↔cloud.
|
|
101
|
+
*/
|
|
102
|
+
export function threeWayMerge(
|
|
103
|
+
base: string,
|
|
104
|
+
local: string,
|
|
105
|
+
cloud: string
|
|
106
|
+
): MergeResult {
|
|
107
|
+
// Fast paths
|
|
108
|
+
if (local === cloud) return { merged: local, hasConflicts: false, conflicts: [] };
|
|
109
|
+
if (local === base) return { merged: cloud, hasConflicts: false, conflicts: [] };
|
|
110
|
+
if (cloud === base) return { merged: local, hasConflicts: false, conflicts: [] };
|
|
111
|
+
|
|
112
|
+
const B = splitParagraphs(base);
|
|
113
|
+
const L = splitParagraphs(local);
|
|
114
|
+
const C = splitParagraphs(cloud);
|
|
115
|
+
const anchors = lcs(L, C); // shared paragraphs, in order
|
|
116
|
+
|
|
117
|
+
const conflicts: Array<{ localVersion: string; cloudVersion: string }> = [];
|
|
118
|
+
const result: string[] = [];
|
|
119
|
+
|
|
120
|
+
// baseRun = what base held in this region. Empty base region + differing runs
|
|
121
|
+
// means both sides *added* here (auto-mergeable union); a non-empty base region
|
|
122
|
+
// that both sides changed differently is a genuine conflict.
|
|
123
|
+
const flushGap = (localRun: string[], cloudRun: string[], baseRun: string[]) => {
|
|
124
|
+
if (cloudRun.length === 0) { result.push(...localRun); return; }
|
|
125
|
+
if (localRun.length === 0) { result.push(...cloudRun); return; }
|
|
126
|
+
if (
|
|
127
|
+
localRun.length === cloudRun.length &&
|
|
128
|
+
localRun.every((p, k) => p === cloudRun[k])
|
|
129
|
+
) {
|
|
130
|
+
result.push(...localRun); // both sides made the same edit
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (baseRun.length === 0) {
|
|
134
|
+
result.push(...localRun, ...cloudRun); // independent additions → union
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
conflicts.push({
|
|
138
|
+
localVersion: localRun.join("\n\n"),
|
|
139
|
+
cloudVersion: cloudRun.join("\n\n"),
|
|
140
|
+
});
|
|
141
|
+
result.push(...localRun);
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
let li = 0;
|
|
145
|
+
let ci = 0;
|
|
146
|
+
let bi = 0;
|
|
147
|
+
for (const anchor of anchors) {
|
|
148
|
+
const lNext = L.indexOf(anchor, li);
|
|
149
|
+
const cNext = C.indexOf(anchor, ci);
|
|
150
|
+
const bNext = B.indexOf(anchor, bi); // -1 if both sides added this anchor
|
|
151
|
+
flushGap(L.slice(li, lNext), C.slice(ci, cNext), bNext === -1 ? [] : B.slice(bi, bNext));
|
|
152
|
+
result.push(anchor);
|
|
153
|
+
li = lNext + 1;
|
|
154
|
+
ci = cNext + 1;
|
|
155
|
+
if (bNext !== -1) bi = bNext + 1;
|
|
156
|
+
}
|
|
157
|
+
// Trailing run after the last anchor.
|
|
158
|
+
flushGap(L.slice(li), C.slice(ci), B.slice(bi));
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
merged: result.join("\n\n"),
|
|
162
|
+
hasConflicts: conflicts.length > 0,
|
|
163
|
+
conflicts,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// --- Tombstone helpers ---
|
|
168
|
+
|
|
169
|
+
export async function isTombstoned(
|
|
170
|
+
workspaceId: string,
|
|
171
|
+
entityType: string,
|
|
172
|
+
entityId: string,
|
|
173
|
+
db: PrismaClient = prisma
|
|
174
|
+
): Promise<boolean> {
|
|
175
|
+
const record = await db.tombstone.findFirst({
|
|
176
|
+
where: { workspaceId, entityType, entityId },
|
|
177
|
+
});
|
|
178
|
+
return record !== null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function writeTombstone(
|
|
182
|
+
workspaceId: string,
|
|
183
|
+
entityType: string,
|
|
184
|
+
entityId: string
|
|
185
|
+
): Promise<void> {
|
|
186
|
+
const where = { workspaceId, entityType, entityId };
|
|
187
|
+
|
|
188
|
+
// Write to local PGlite
|
|
189
|
+
const existing = await prisma.tombstone.findFirst({ where });
|
|
190
|
+
if (!existing) {
|
|
191
|
+
await prisma.tombstone.create({ data: where });
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Mirror to Neon so syncing devices don't resurrect deleted records
|
|
195
|
+
const cloud = getCloudPrisma();
|
|
196
|
+
if (cloud) {
|
|
197
|
+
const cloudExisting = await cloud.tombstone.findFirst({ where });
|
|
198
|
+
if (!cloudExisting) {
|
|
199
|
+
await cloud.tombstone.create({ data: where });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// --- Conflict log helpers ---
|
|
205
|
+
|
|
206
|
+
export async function logConflict(
|
|
207
|
+
workspaceId: string,
|
|
208
|
+
entityType: "note" | "task",
|
|
209
|
+
entityId: string,
|
|
210
|
+
localValue: string,
|
|
211
|
+
cloudValue: string,
|
|
212
|
+
db: PrismaClient = prisma
|
|
213
|
+
): Promise<string> {
|
|
214
|
+
// Use upsert so a second conflict on the same entity (before the first is
|
|
215
|
+
// resolved) refreshes the values instead of throwing a unique-constraint error
|
|
216
|
+
// and silently killing the entire sync flush for this workspace.
|
|
217
|
+
const record = await db.conflictLog.upsert({
|
|
218
|
+
where: { workspaceId_entityType_entityId: { workspaceId, entityType, entityId } },
|
|
219
|
+
create: { workspaceId, entityType, entityId, localValue, cloudValue },
|
|
220
|
+
update: {
|
|
221
|
+
// Keep the original localValue as the baseline; update cloudValue with
|
|
222
|
+
// the latest cloud state so the user always sees the most recent divergence.
|
|
223
|
+
cloudValue,
|
|
224
|
+
resolvedBy: null,
|
|
225
|
+
resolvedAt: null,
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
return record.id;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export async function resolveConflict(
|
|
232
|
+
conflictId: string,
|
|
233
|
+
resolvedBy: "local" | "cloud" | "user",
|
|
234
|
+
db: PrismaClient = prisma
|
|
235
|
+
): Promise<void> {
|
|
236
|
+
await db.conflictLog.update({
|
|
237
|
+
where: { id: conflictId },
|
|
238
|
+
data: { resolvedBy, resolvedAt: new Date() },
|
|
239
|
+
});
|
|
240
|
+
}
|
package/lib/db-init.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PGlite startup migration runner.
|
|
3
|
+
*
|
|
4
|
+
* On every app start, reads the SQL files from prisma/migrations/ and applies
|
|
5
|
+
* any that haven't been applied to the local PGlite database yet.
|
|
6
|
+
*
|
|
7
|
+
* This replaces `prisma migrate deploy` for the local embedded DB — the
|
|
8
|
+
* migration files are generated by `prisma migrate dev` (against Neon) and
|
|
9
|
+
* bundled with the package, so local users get schema updates automatically
|
|
10
|
+
* on the next `npx @brief/app` run.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { type PGlite } from "@electric-sql/pglite";
|
|
14
|
+
import fs from "fs";
|
|
15
|
+
import path from "path";
|
|
16
|
+
import { randomUUID } from "crypto";
|
|
17
|
+
|
|
18
|
+
const MIGRATIONS_TABLE = `
|
|
19
|
+
CREATE TABLE IF NOT EXISTS "_prisma_migrations" (
|
|
20
|
+
"id" VARCHAR(36) NOT NULL PRIMARY KEY,
|
|
21
|
+
"checksum" VARCHAR(64) NOT NULL,
|
|
22
|
+
"finished_at" TIMESTAMPTZ,
|
|
23
|
+
"migration_name" VARCHAR(255) NOT NULL,
|
|
24
|
+
"logs" TEXT,
|
|
25
|
+
"rolled_back_at" TIMESTAMPTZ,
|
|
26
|
+
"started_at" TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
27
|
+
"applied_steps_count" INTEGER NOT NULL DEFAULT 0
|
|
28
|
+
);
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
export async function runLocalMigrations(db: PGlite): Promise<void> {
|
|
32
|
+
// Ensure tracking table exists
|
|
33
|
+
await db.exec(MIGRATIONS_TABLE);
|
|
34
|
+
|
|
35
|
+
const migrationsDir = path.join(process.cwd(), "prisma", "migrations");
|
|
36
|
+
|
|
37
|
+
if (!fs.existsSync(migrationsDir)) {
|
|
38
|
+
console.warn(
|
|
39
|
+
"[Brief] No migration files found. Run `prisma migrate dev --name init` to generate them."
|
|
40
|
+
);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Get already-applied migrations
|
|
45
|
+
const result = await db.query<{ migration_name: string }>(
|
|
46
|
+
`SELECT migration_name FROM "_prisma_migrations" WHERE finished_at IS NOT NULL ORDER BY started_at`
|
|
47
|
+
);
|
|
48
|
+
const applied = new Set(result.rows.map((r) => r.migration_name));
|
|
49
|
+
|
|
50
|
+
// Read migration directories sorted by name (timestamp prefix ensures order)
|
|
51
|
+
const dirs = fs
|
|
52
|
+
.readdirSync(migrationsDir)
|
|
53
|
+
.filter((d) => fs.statSync(path.join(migrationsDir, d)).isDirectory())
|
|
54
|
+
.sort();
|
|
55
|
+
|
|
56
|
+
for (const dir of dirs) {
|
|
57
|
+
if (applied.has(dir)) continue;
|
|
58
|
+
|
|
59
|
+
const sqlFile = path.join(migrationsDir, dir, "migration.sql");
|
|
60
|
+
if (!fs.existsSync(sqlFile)) continue;
|
|
61
|
+
|
|
62
|
+
const sql = fs.readFileSync(sqlFile, "utf-8");
|
|
63
|
+
const id = randomUUID();
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
await db.exec(sql);
|
|
67
|
+
await db.query(
|
|
68
|
+
`INSERT INTO "_prisma_migrations"
|
|
69
|
+
(id, checksum, finished_at, migration_name, applied_steps_count)
|
|
70
|
+
VALUES ($1, '', now(), $2, 1)`,
|
|
71
|
+
[id, dir]
|
|
72
|
+
);
|
|
73
|
+
console.log(`[Brief] Applied migration: ${dir}`);
|
|
74
|
+
} catch (err) {
|
|
75
|
+
console.error(`[Brief] Migration failed: ${dir}`, err);
|
|
76
|
+
throw err;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
package/lib/email.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transactional email service backed by Brevo (formerly Sendinblue).
|
|
3
|
+
*
|
|
4
|
+
* Identities are read from environment variables so they can be swapped
|
|
5
|
+
* without code changes:
|
|
6
|
+
*
|
|
7
|
+
* BREVO_API_KEY – shared API key
|
|
8
|
+
* EMAIL_AUTH_FROM – "Display Name <addr>" (auth emails)
|
|
9
|
+
* EMAIL_AUTH_NAME – sender display name
|
|
10
|
+
* EMAIL_AUTH_EMAIL – sender address
|
|
11
|
+
* EMAIL_NOTIFY_FROM – "Display Name <addr>" (notifications)
|
|
12
|
+
* EMAIL_NOTIFY_NAME – sender display name
|
|
13
|
+
* EMAIL_NOTIFY_EMAIL – sender address
|
|
14
|
+
*
|
|
15
|
+
* If a given identity is not configured the call is silently skipped (and a
|
|
16
|
+
* warning is logged) so local/dev environments without Brevo still work.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// Types
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
export type EmailIdentity = "auth" | "notify";
|
|
24
|
+
|
|
25
|
+
export interface SendEmailOptions {
|
|
26
|
+
/** Which sender identity to use. */
|
|
27
|
+
identity: EmailIdentity;
|
|
28
|
+
/** Recipient email address. */
|
|
29
|
+
to: string;
|
|
30
|
+
/** Email subject line. */
|
|
31
|
+
subject: string;
|
|
32
|
+
/** HTML body. */
|
|
33
|
+
html: string;
|
|
34
|
+
/** Optional plain-text body. */
|
|
35
|
+
text?: string;
|
|
36
|
+
/** Optional reply-to address. */
|
|
37
|
+
replyTo?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface BrevoSender {
|
|
41
|
+
name: string;
|
|
42
|
+
email: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
// Identity helpers
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Parse a "Display Name <addr>" string into { name, email }.
|
|
51
|
+
* Falls back to the env-provided name/email pair if FROM isn't set.
|
|
52
|
+
*/
|
|
53
|
+
function parseFromHeader(
|
|
54
|
+
fromEnv: string | undefined,
|
|
55
|
+
nameEnv: string | undefined,
|
|
56
|
+
emailEnv: string | undefined
|
|
57
|
+
): BrevoSender | null {
|
|
58
|
+
if (fromEnv) {
|
|
59
|
+
const match = /^(.+?)\s*<([^>]+)>$/.exec(fromEnv);
|
|
60
|
+
if (match) return { name: match[1].trim(), email: match[2].trim() };
|
|
61
|
+
}
|
|
62
|
+
if (nameEnv && emailEnv) return { name: nameEnv, email: emailEnv };
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function getSender(identity: EmailIdentity): BrevoSender | null {
|
|
67
|
+
if (identity === "auth") {
|
|
68
|
+
return parseFromHeader(
|
|
69
|
+
process.env.EMAIL_AUTH_FROM,
|
|
70
|
+
process.env.EMAIL_AUTH_NAME,
|
|
71
|
+
process.env.EMAIL_AUTH_EMAIL
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return parseFromHeader(
|
|
75
|
+
process.env.EMAIL_NOTIFY_FROM,
|
|
76
|
+
process.env.EMAIL_NOTIFY_NAME,
|
|
77
|
+
process.env.EMAIL_NOTIFY_EMAIL
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
// Public API
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Send a transactional email via Brevo. Returns `true` on success, `false`
|
|
87
|
+
* when the email could not be sent (missing config, API error, etc.).
|
|
88
|
+
*/
|
|
89
|
+
export async function sendEmail(opts: SendEmailOptions): Promise<boolean> {
|
|
90
|
+
const apiKey = process.env.BREVO_API_KEY;
|
|
91
|
+
if (!apiKey) {
|
|
92
|
+
console.warn("[email] BREVO_API_KEY not configured — skipping email send.");
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const sender = getSender(opts.identity);
|
|
97
|
+
if (!sender) {
|
|
98
|
+
console.warn(
|
|
99
|
+
`[email] Sender identity "${opts.identity}" not configured — skipping email send.`
|
|
100
|
+
);
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const body: Record<string, unknown> = {
|
|
105
|
+
sender,
|
|
106
|
+
to: [{ email: opts.to }],
|
|
107
|
+
subject: opts.subject,
|
|
108
|
+
htmlContent: opts.html,
|
|
109
|
+
};
|
|
110
|
+
if (opts.text) body.textContent = opts.text;
|
|
111
|
+
if (opts.replyTo) body.replyTo = { email: opts.replyTo };
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
const res = await fetch("https://api.brevo.com/v3/smtp/email", {
|
|
115
|
+
method: "POST",
|
|
116
|
+
headers: {
|
|
117
|
+
"Content-Type": "application/json",
|
|
118
|
+
accept: "application/json",
|
|
119
|
+
"api-key": apiKey,
|
|
120
|
+
},
|
|
121
|
+
body: JSON.stringify(body),
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
if (!res.ok) {
|
|
125
|
+
const detail = await res.text().catch(() => "");
|
|
126
|
+
console.error(`[email] Brevo API ${res.status}: ${detail}`);
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return true;
|
|
131
|
+
} catch (err) {
|
|
132
|
+
console.error("[email] Brevo send failed:", err);
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Convenience: send an auth-related email (magic link, password reset, etc.).
|
|
139
|
+
*/
|
|
140
|
+
export function sendAuthEmail(
|
|
141
|
+
to: string,
|
|
142
|
+
subject: string,
|
|
143
|
+
html: string,
|
|
144
|
+
text?: string
|
|
145
|
+
) {
|
|
146
|
+
return sendEmail({ identity: "auth", to, subject, html, text });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Convenience: send a system notification email (report, update, etc.).
|
|
151
|
+
*/
|
|
152
|
+
export function sendNotifyEmail(
|
|
153
|
+
to: string,
|
|
154
|
+
subject: string,
|
|
155
|
+
html: string,
|
|
156
|
+
text?: string
|
|
157
|
+
) {
|
|
158
|
+
return sendEmail({ identity: "notify", to, subject, html, text });
|
|
159
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { encryptNote, decryptNote, isEncrypted, generateSalt, ENC_PREFIX } from "@/lib/encryption";
|
|
3
|
+
|
|
4
|
+
const SECRET = "test-pepper-do-not-use-in-prod";
|
|
5
|
+
|
|
6
|
+
describe("encryption", () => {
|
|
7
|
+
it("round-trips plaintext through encrypt/decrypt", async () => {
|
|
8
|
+
const salt = generateSalt();
|
|
9
|
+
const plain = "# Title\n\n- [ ] do thing @alice 2026-01-02";
|
|
10
|
+
const cipher = await encryptNote(plain, SECRET, salt);
|
|
11
|
+
expect(cipher.startsWith(ENC_PREFIX)).toBe(true);
|
|
12
|
+
expect(cipher).not.toContain("do thing");
|
|
13
|
+
expect(await decryptNote(cipher, SECRET, salt)).toBe(plain);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it("marks ciphertext and not plaintext via isEncrypted", async () => {
|
|
17
|
+
const salt = generateSalt();
|
|
18
|
+
expect(isEncrypted("just some text")).toBe(false);
|
|
19
|
+
expect(isEncrypted(await encryptNote("hello", SECRET, salt))).toBe(true);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("is idempotent — never double-encrypts", async () => {
|
|
23
|
+
const salt = generateSalt();
|
|
24
|
+
const once = await encryptNote("hello", SECRET, salt);
|
|
25
|
+
const twice = await encryptNote(once, SECRET, salt);
|
|
26
|
+
expect(twice).toBe(once);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("returns legacy plaintext unchanged on decrypt", async () => {
|
|
30
|
+
const salt = generateSalt();
|
|
31
|
+
expect(await decryptNote("legacy plaintext", SECRET, salt)).toBe("legacy plaintext");
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("produces different ciphertext for the same input (random IV)", async () => {
|
|
35
|
+
const salt = generateSalt();
|
|
36
|
+
const a = await encryptNote("hello", SECRET, salt);
|
|
37
|
+
const b = await encryptNote("hello", SECRET, salt);
|
|
38
|
+
expect(a).not.toBe(b);
|
|
39
|
+
expect(await decryptNote(b, SECRET, salt)).toBe("hello");
|
|
40
|
+
});
|
|
41
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AES-256-GCM encryption-at-rest for Brief note content.
|
|
3
|
+
*
|
|
4
|
+
* Architecture (server-side, NOT end-to-end):
|
|
5
|
+
* - Server key: ENCRYPTION_PEPPER env var (never stored in the DB)
|
|
6
|
+
* - Workspace salt: random 16 bytes, stored in workspace.encryptionSalt (not sensitive)
|
|
7
|
+
* - Derived key: PBKDF2(pepper, salt, 100_000 iterations, SHA-256) → 256-bit AES key
|
|
8
|
+
* - Ciphertext: "enc:v1:" + base64( [IV (12 bytes)] + [GCM ciphertext+tag] )
|
|
9
|
+
*
|
|
10
|
+
* The server holds the key, so this protects against a database dump / at-rest
|
|
11
|
+
* exposure — it is deliberately NOT E2E (that was dropped to keep multi-device
|
|
12
|
+
* and team sync simple). Note content must never be persisted as plaintext.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const PBKDF2_ITERATIONS = 100_000;
|
|
16
|
+
const SALT_BYTES = 16;
|
|
17
|
+
const IV_BYTES = 12; // AES-GCM standard
|
|
18
|
+
|
|
19
|
+
// Version marker prepended to every ciphertext. Lets us detect encrypted vs
|
|
20
|
+
// plaintext content unambiguously (the old base64 heuristic mis-classified
|
|
21
|
+
// plaintext that happened to look base64-ish).
|
|
22
|
+
export const ENC_PREFIX = "enc:v1:";
|
|
23
|
+
|
|
24
|
+
export function generateSalt(): string {
|
|
25
|
+
const bytes = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
|
|
26
|
+
return Buffer.from(bytes).toString("base64");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// --- Key derivation ---
|
|
30
|
+
|
|
31
|
+
async function deriveKey(secret: string, saltBase64: string): Promise<CryptoKey> {
|
|
32
|
+
const enc = new TextEncoder();
|
|
33
|
+
const keyMaterial = await crypto.subtle.importKey(
|
|
34
|
+
"raw",
|
|
35
|
+
enc.encode(secret),
|
|
36
|
+
"PBKDF2",
|
|
37
|
+
false,
|
|
38
|
+
["deriveKey"]
|
|
39
|
+
);
|
|
40
|
+
const salt = Buffer.from(saltBase64, "base64");
|
|
41
|
+
return crypto.subtle.deriveKey(
|
|
42
|
+
{ name: "PBKDF2", salt, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" },
|
|
43
|
+
keyMaterial,
|
|
44
|
+
{ name: "AES-GCM", length: 256 },
|
|
45
|
+
false,
|
|
46
|
+
["encrypt", "decrypt"]
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// --- Encrypt / Decrypt ---
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Encrypt plaintext using the server key + workspace salt.
|
|
54
|
+
* Returns: ENC_PREFIX + base64([IV] + [ciphertext]).
|
|
55
|
+
* Returns already-encrypted input unchanged (idempotent).
|
|
56
|
+
*/
|
|
57
|
+
export async function encryptNote(plaintext: string, secret: string, saltBase64: string): Promise<string> {
|
|
58
|
+
if (isEncrypted(plaintext)) return plaintext;
|
|
59
|
+
const key = await deriveKey(secret, saltBase64);
|
|
60
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
61
|
+
const enc = new TextEncoder();
|
|
62
|
+
const ciphertext = await crypto.subtle.encrypt(
|
|
63
|
+
{ name: "AES-GCM", iv },
|
|
64
|
+
key,
|
|
65
|
+
enc.encode(plaintext)
|
|
66
|
+
);
|
|
67
|
+
const combined = new Uint8Array(IV_BYTES + ciphertext.byteLength);
|
|
68
|
+
combined.set(iv, 0);
|
|
69
|
+
combined.set(new Uint8Array(ciphertext), IV_BYTES);
|
|
70
|
+
return ENC_PREFIX + Buffer.from(combined).toString("base64");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Decrypt a value produced by encryptNote. If the input is not encrypted
|
|
75
|
+
* (legacy plaintext row), it is returned unchanged.
|
|
76
|
+
*/
|
|
77
|
+
export async function decryptNote(encrypted: string, secret: string, saltBase64: string): Promise<string> {
|
|
78
|
+
if (!isEncrypted(encrypted)) return encrypted; // legacy / plaintext safety
|
|
79
|
+
try {
|
|
80
|
+
const key = await deriveKey(secret, saltBase64);
|
|
81
|
+
const combined = Buffer.from(encrypted.slice(ENC_PREFIX.length), "base64");
|
|
82
|
+
const iv = combined.subarray(0, IV_BYTES);
|
|
83
|
+
const ciphertext = combined.subarray(IV_BYTES);
|
|
84
|
+
const dec = new TextDecoder();
|
|
85
|
+
const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
|
|
86
|
+
return dec.decode(plaintext);
|
|
87
|
+
} catch {
|
|
88
|
+
// Not genuinely our ciphertext (e.g. a note that literally starts with the
|
|
89
|
+
// marker, or a corrupted row). Return the raw value rather than throwing so
|
|
90
|
+
// a single bad row can't 500 the whole note read.
|
|
91
|
+
return encrypted;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** True if a string is Brief-encrypted ciphertext (carries the version marker). */
|
|
96
|
+
export function isEncrypted(content: string): boolean {
|
|
97
|
+
return content.startsWith(ENC_PREFIX);
|
|
98
|
+
}
|