Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2dc128a215 | ||
|
|
4ccedd1a03 | ||
|
|
e8f04a4082 | ||
|
|
d4a2ca0d0d | ||
|
|
47e0272d6c | ||
|
|
a402e4f2e7 | ||
|
|
eca8aeb113 | ||
|
|
f6158f58b5 | ||
|
|
7a7e77e039 | ||
|
|
ef69be6320 | ||
|
|
7f64cbae0b | ||
|
|
46d9044f53 | ||
|
|
da70346e45 | ||
|
|
e3d765e97b | ||
|
|
78231502f1 | ||
|
|
212d587f97 | ||
|
|
ceb4973359 | ||
|
|
200013960b | ||
|
|
a8cc95cfae | ||
|
|
298cc4efd6 |
@@ -24,13 +24,17 @@ capped (100 per bookmark/tag/collection share, 200 per shared date).
|
||||
| POST | `/api/password/reset` | `{ok:true}` — body `{token,password}`; consumes the token, sets the new password and bumps `tokenVersion` (revokes all prior sessions). **400** on invalid/expired/used tokens or policy-violating passwords; **403** in oidc mode |
|
||||
| GET | `/api/auth/session` | `{user}` or `null` for no valid cookie |
|
||||
| POST | `/api/auth/signout` | `{ok:true}` and expired cookie; same-origin `Origin` required when present |
|
||||
| GET | `/api/me` | `{user,effectiveUser,isAdmin,viewingAs}`; real and effective identities. The user projection carries `tenantId` (tenancy phase 1: every user belongs to the implicit default tenant) |
|
||||
| GET | `/api/me` | `{user,effectiveUser,isAdmin,viewingAs}`; real and effective identities. The user projection carries `tenantId` (tenancy phase 1) and the profile particulars `bio,location,occupation,organization,website` (nullable) |
|
||||
| PATCH | `/api/me` | Settings → Profile: partial `{name?,bio?,location?,occupation?,organization?,website?}` (allowlist; empty string clears to null; rune caps 120/280/120/120/120, website ≤2048 and http(s) with a host) → the fresh user projection. No version column on User (identity, not a collaborative collection); view-as writes are blocked by the middleware |
|
||||
| GET | `/api/auth/oidc/status` | `{enabled,issuerSet,clientIdSet,clientSecretSet}`; never includes secrets or the issuer URL |
|
||||
| POST | `/api/auth/oidc/identity` | Server-to-server only: requires `typ=oidc-provision` bearer token; body `{issuer,subject,email,emailVerified,name,image}`; returns the local `{user,tokenVersion}` or **409** when an existing password account needs explicit linking |
|
||||
| GET | `/api/auth/oidc/login` | **501**, client-owned Authelia integration stub |
|
||||
| GET, POST | `/api/auth/callback/authelia` | **501**, client-owned callback stub |
|
||||
|
||||
The browser's NextAuth `/api/auth/*` endpoints remain on the Next server.
|
||||
Go's `/api/auth/` catch-all implements only `GET /api/auth/session` and
|
||||
`POST /api/auth/signout`; every other subpath (`csrf`, `providers`, `signin`,
|
||||
`callback/credentials`, …) answers **404** on Go and is served by Next.
|
||||
Direct Go API consumers use the `superbrain_session` cookie from login.
|
||||
`TIER=core|multi` (or an explicit `AUTH_MODE` override) decides which half
|
||||
of the auth surface is live: in `oidc` mode login/signup/password-reset all
|
||||
@@ -55,6 +59,17 @@ of a qualifying administrator — e.g. after demoting the last one — never
|
||||
re-opens promotion through signup. Recovery is operator-driven
|
||||
(`ADMIN_EMAILS` + `make seed`, or promotion by an existing admin).
|
||||
|
||||
### Next.js server routes
|
||||
|
||||
The web server (`web/app/api/`) exposes three route families; everything else
|
||||
is proxied:
|
||||
|
||||
| Method | Path | Behavior |
|
||||
|---|---|---|
|
||||
| ALL | `/api/[...path]` | Server-side proxy to the Go API. Signs a 60s Bearer assertion from the NextAuth session, forwards the signed observed client IP, enforces the same-origin / `Sec-Fetch-Site` CSRF check and the 1 MiB streaming body cap, and passes through `X-Next-Cursor`. Does **not** forward client `Authorization` headers (so `sb_` keys only work against Go directly) |
|
||||
| GET, POST | `/api/auth/*` | NextAuth (Auth.js): `csrf`, `providers`, `signin`, `signout`, `session`, `callback/credentials`, `callback/authelia`. The browser session lives here; Go's `/api/auth/` only implements `session`/`signout` |
|
||||
| POST | `/api/session/revoke` | Explicit "sign out everywhere": calls Go `POST /api/auth/signout` with a signed assertion and reports honestly — `{revoked:true}` on success, `{revoked:false,reason}` (`no-backend-session` / `backend-error` / `unreachable`) when global revocation could not be confirmed. Same-origin `Origin` required (403 otherwise). The NextAuth `signOut` event is a fail-open backstop |
|
||||
|
||||
### API keys (MCP / machine clients)
|
||||
|
||||
Personal long-lived Bearer credentials (`sb_` + 43 base64url characters) for
|
||||
@@ -119,7 +134,10 @@ share every ~30 minutes under a global advisory lease; `WebDavConnection` +
|
||||
`WebDavItem` (migration 020) store credentials and the path↔bookmark ledger.
|
||||
On Core the deployment's `NEXTCLOUD_URL` makes the list carry a one-click
|
||||
suggestion (`https://<nextcloud>/remote.php/dav/files/`) — DATA, not a code
|
||||
fork on TIER.
|
||||
fork on TIER. The UI composes the viewer's username into the per-user DAV
|
||||
root (`/files/<username>/`), and the Core app container pins the Nextcloud
|
||||
hostname to the deployment's public IP (compose `extra_hosts`): the
|
||||
split-horizon private answer has no 443 listener and netguard stays strict.
|
||||
|
||||
| Method | Path | Returns / behavior |
|
||||
|---|---|---|
|
||||
@@ -240,8 +258,11 @@ projection and UI agree. Detail responses also include
|
||||
| GET | `/api/bookmarks/{id}/markdown` | Markdown attachment, owned/shared only |
|
||||
| GET | `/api/preview?url=...` | `{title,description,ogTitle,ogDescription,ogImage,favicon}`; nullable on fetch failure |
|
||||
| GET | `/api/public/bookmarks/{id}` | Public bookmark projection without login; private records return 404 |
|
||||
| GET | `/share/bookmark/{id}` | Go serves the same public JSON projection as `/api/public/bookmarks/{id}` at this path (per-client + per-id rate limited). The Next.js server renders the public **HTML** page at the same path for browsers |
|
||||
|
||||
Public HTML pages remain at `/share/bookmark/{id}` on the Next.js server.
|
||||
Browsers get the public **HTML** page at `/share/bookmark/{id}` from the
|
||||
Next.js server; the Go API serves the public **JSON** projection at that same
|
||||
path (table above).
|
||||
For pagination, read the `X-Next-Cursor` response header and pass that opaque
|
||||
value as `cursor` with the same filters. An absent header marks the final page.
|
||||
`limit` must be between 1 and 200. The web proxy forwards the cursor header.
|
||||
@@ -284,10 +305,10 @@ test-only). CardDAV keeps the configured HTTPS port.
|
||||
| PATCH | `/api/kanban/columns/{id}` | Updated column; body `{label?,color?}` |
|
||||
| DELETE | `/api/kanban/columns/{id}` | `{ok:true,movedTo,moved}`; moves cards, never deletes bookmarks; refuses last column |
|
||||
| PUT | `/api/kanban/cards/{id}` | Moved bookmark; body `{columnId,position,version}`. Reorders the target column (0-based position, clamped at the end) and normalizes every card's `kanbanPosition`. Owner only. `version` is REQUIRED: 400 when missing/invalid, 409 when stale; success bumps the moved card's `version` |
|
||||
| GET | `/api/pages?search=...` | Pages, pinned first, with `parentId` and `_count.{bookmarks,children}`; title/content substring search treats `%` and `_` literally and uses trigram indexes |
|
||||
| GET | `/api/pages?search=...` | Pages, pinned first, with `parentId`, `tags:[{tag}]` and `_count.{bookmarks,children}`; title/content substring search treats `%` and `_` literally and uses trigram indexes |
|
||||
| POST | `/api/pages` | 201 page; body `{title?,content?,parentId?}`. `parentId` must be an owned page; a missing/foreign parent is 400 |
|
||||
| PUT | `/api/pages` | `{ok:true}`; complete `{order:[id,...]}` |
|
||||
| GET | `/api/pages/{id}` | Page plus ordered `bookmarks:[{bookmark}]`, owner-scoped `backlinks:[{id,title,updatedAt}]`, resolved outgoing `links:[{id,title}]`, and `embeds:[{collectionId,viewId,position,collection,view}]` |
|
||||
| GET | `/api/pages/{id}` | Page plus `tags:[{tag}]`, ordered `bookmarks:[{bookmark}]`, owner-scoped `backlinks:[{id,title,updatedAt}]`, resolved outgoing `links:[{id,title}]`, and `embeds:[{collectionId,viewId,position,collection,view}]` |
|
||||
| PATCH | `/api/pages/{id}` | Updated page; `{title?,content?,pinned?,icon?,parentId?,version?,addBookmarkId?,removeBookmarkId?}`. `version` (the base revision from GET) is REQUIRED with `content`: 400 when missing, 409 when stale. Metadata-only patches (including moving a page) stay version-free and do not bump the revision. Moving under itself or a descendant is rejected 400 (no cycles) |
|
||||
| GET | `/api/pages/{id}/backlinks` | Owner-scoped `[{id,title,updatedAt}]` from `PageLink` — the pages whose Markdown links here |
|
||||
| GET | `/api/pages/{id}/revisions` | Version history metadata `[{id,version,title,icon,createdAt,length}]`, newest first; bodies fetched separately |
|
||||
@@ -295,6 +316,18 @@ test-only). CardDAV keeps the configured HTTPS port.
|
||||
| POST | `/api/pages/{id}/revisions/{revisionId}/restore` | Restores a snapshot as a **new** version; body `{version}` (current base) — 400 missing, 409 stale. The restore itself is recorded in history |
|
||||
| DELETE | `/api/pages/{id}` | Moves the page to Trash; keeps bookmarks and promotes child pages. Restoring also restores its revisions and creates a new revision |
|
||||
| GET | `/api/pages/{id}/markdown` | Markdown attachment |
|
||||
| POST | `/api/pages/{id}/tags` | Attaches a tag; body `{tagId}`; returns the refreshed page projection (with `tags`). 400 missing/invalid tag, 404 foreign page. Idempotent (`ON CONFLICT DO NOTHING`) |
|
||||
| DELETE | `/api/pages/{id}/tags/{tagId}` | Detaches a tag; returns the refreshed page projection. 404 foreign page |
|
||||
|
||||
### Page tags
|
||||
|
||||
Pages carry tags like bookmarks (`PageTag`, migration 023). A tag may be
|
||||
attached when it is owned by the caller **or shared with them** — the same
|
||||
rule as bookmark tags. Tagging is metadata: it neither requires nor bumps the
|
||||
page content `version`, and the join row cascades when the page or the tag is
|
||||
deleted. The sidebar's "Untagged Pages" list is derived client-side from the
|
||||
`tags` array on `GET /api/pages` (empty = untagged); dragging a page onto a tag
|
||||
calls `POST /api/pages/{id}/tags`.
|
||||
|
||||
### Connected pages (phase 3)
|
||||
|
||||
@@ -414,6 +447,18 @@ recipient's tenant plan gates the send. History and delivery rows carry
|
||||
carry the footer "Managed by David's Superbrain."; paying plans and core do
|
||||
not (`entitlements.ManagedFooter`, per-tenant override `managed_footer`).
|
||||
|
||||
Branded email (multipart/alternative, `internal/mailer/template.html`)
|
||||
carries footer links when `NEXTAUTH_URL` is set: Email preferences
|
||||
(`/settings?tab=notifications`), Help center (`/help`) and — ONLY when the
|
||||
recipient is the owner's own account email — Unsubscribe
|
||||
(`/unsubscribe?token=…`). The token is a stable HMAC-signed user id
|
||||
(`notify.UnsubscribeToken`, no stored row); owner-addressed mail also
|
||||
carries `List-Unsubscribe` + `List-Unsubscribe-Post` (RFC 8058 one-click).
|
||||
Unsubscribe disables the user's enabled email channels and pauses enabled
|
||||
agent email tasks addressed to the user's own email; it is idempotent and
|
||||
never touches transactional mail (password reset) or third-party
|
||||
recipients.
|
||||
|
||||
| Method | Path | Body / Returns |
|
||||
|---|---|---|
|
||||
| GET | `/api/notifications/channels` | `[{id,kind,name,enabled,version,config(masked),createdAt}]` |
|
||||
@@ -426,6 +471,7 @@ not (`entitlements.ManagedFooter`, per-tenant override `managed_footer`).
|
||||
| PATCH | `/api/notifications/rules/{id}` | `{version, name?,enabled?,cooldownMinutes?,channelId?,config?}` → 200; 409 on stale version |
|
||||
| DELETE | `/api/notifications/rules/{id}` | `{ok:true}` |
|
||||
| GET | `/api/notifications` | Last 100 deliveries for rows you own OR were targeted on: `[{id,title,body,status,attempts,ruleName,channelKind,recipientId,sentAt,createdAt}]`; status ∈ pending/sent/failed/suppressed |
|
||||
| POST | `/api/notifications/unsubscribe` | Token-credentialed, NO session: `?token=…` (RFC 8058 one-click; body ignored) or JSON `{token}` → `{ok:true,channels,tasks}`; 400 for invalid/tampered tokens; per-client rate limited |
|
||||
|
||||
### Agent automations ("hey superbrain")
|
||||
|
||||
|
||||
+111
-1
@@ -3,9 +3,119 @@
|
||||
Versions correspond to git tags and to the published image set
|
||||
(`federatedcomputer/superbrain-{app,web,migrate}` on Docker Hub); the
|
||||
`superbrain-mcp` Python package and the federated suite files
|
||||
(`service` VERSION, installer image version) move in lockstep from 1.2.0 on.
|
||||
(`service` VERSION, installer image version) move in lockstep from 1.2.0 on
|
||||
(the line was reset to 0.2.x at 0.2.14 — Superbrain is pre-beta).
|
||||
Dates are tag dates.
|
||||
|
||||
## 0.3.1 — 2026-11-21
|
||||
|
||||
### Changed
|
||||
- **Brand refresh**: the real Superbrain mark replaces the LinkOS-era
|
||||
placeholders everywhere — browser favicon, apple-touch icon, the social
|
||||
share image (previously still branded "LinkOS"), and the in-app brand
|
||||
marks (sidebar, sign-in/sign-up, password reset, unsubscribe, help
|
||||
header) via a single shared icon component.
|
||||
- **README caught up to the shipped app**: grouped settings and sidebar,
|
||||
page tags and WYSIWYG editing, calendar views and bookmark group-by,
|
||||
WebDAV/CalDAV/CardDAV connectors, Signal notifications and share
|
||||
triggers, branded email with preferences/help/unsubscribe footers,
|
||||
profile particulars, the public help center, and developer access; a
|
||||
documentation line at the top links the API reference, running guide
|
||||
and Authelia guide. The publishing section now describes the actual
|
||||
release path.
|
||||
|
||||
## 0.2.17 — 2026-11-20
|
||||
|
||||
### Added
|
||||
- **Branded email**: transactional mail (password resets, notification and
|
||||
automation emails) now uses the Superbrain HTML design with a plain-text
|
||||
fallback. Password resets get a proper "Choose a new password" button and
|
||||
an expiry note; every email carries a footer with Email preferences, Help
|
||||
center and — for mail to your own address — Unsubscribe.
|
||||
- **Help center** (`/help`): a public guide to every surface of the app
|
||||
(bookmarks, collections, pages, board, signals, notifications, assistant,
|
||||
connections, developer tools) plus an FAQ; linked from the sign-in page
|
||||
and email footers.
|
||||
- **One-click unsubscribe**: notification emails carry a secure unsubscribe
|
||||
link (and native mail-client unsubscribe support). It turns off your email
|
||||
channels and automations that email you — without signing in — and never
|
||||
affects password resets or other account emails. Re-enable anytime in
|
||||
Settings → Notifications.
|
||||
- **Profile particulars**: Settings → Profile is now a real form — display
|
||||
name, bio, location, occupation, organization and website. Your name
|
||||
appears where you share with others; public bookmark links still never
|
||||
reveal your identity. Saving refreshes the name shown in the top bar
|
||||
without a re-login.
|
||||
|
||||
### Changed
|
||||
- **Email preferences deep link**: the email footer's "Email preferences"
|
||||
opens Settings directly on the Notifications tab (`/settings?tab=…`
|
||||
deep links are now supported).
|
||||
|
||||
## 0.2.16 — 2026-11-18
|
||||
|
||||
### Added
|
||||
- **Reorganized sidebar**: Quick find at the top; a **Pages** group (All
|
||||
Pages, Pinned Pages, Untagged Pages) and a **Bookmarks** group (All
|
||||
Bookmarks, Calendar, and expandable **Tags / Kanban / Collections /
|
||||
Contacts** lists that jump straight to a specific tag, column, collection
|
||||
or contact); Trash at the bottom.
|
||||
- **Page tags**: pages can now be tagged like bookmarks. The sidebar's
|
||||
"Untagged Pages" list shows pages without tags, and **dragging a page onto
|
||||
a tag** assigns it.
|
||||
- **Bookmark group-by**: All Bookmarks gains a "Group by" control — Calendar
|
||||
(due month), Tags, Kanban, Collections or Contacts — rendering the list in
|
||||
labeled sections. The default ungrouped view is unchanged.
|
||||
- **Calendar views**: Day, Week, Month, Year and a date-sorted List, with
|
||||
navigation and a Today button that adapt to the active view.
|
||||
|
||||
### Changed
|
||||
- **Kanban no longer auto-populates**: only bookmarks explicitly placed in a
|
||||
column appear on the board; unassigned bookmarks stay off it until added.
|
||||
- The test gate's Go timeout was raised so the full race-enabled integration
|
||||
suite completes reliably.
|
||||
|
||||
## 0.2.15 — 2026-11-17
|
||||
|
||||
### Changed
|
||||
- **Settings are now grouped and fully visible.** The flat tab strip (which
|
||||
hid half the options behind a horizontal scrollbar, on desktop and mobile)
|
||||
is replaced by a grouped navigation: **Account** (Profile, Sign-in),
|
||||
**Connections** (WebDAV, CalDAV, CardDAV, Contacts sync, IMAP),
|
||||
**AI & Automation** (AI, MCP, Automations, Notifications) and
|
||||
**Developer** (API Keys). On desktop the menu sits beside the settings
|
||||
panel; on phones it's a list that opens into the selected panel with a
|
||||
back button. Two labels were clarified: "OIDC" is now **Sign-in**, and the
|
||||
Nextcloud contact import is now **Contacts sync** (distinct from the
|
||||
CardDAV connector).
|
||||
|
||||
## 0.2.14 — 2026-11-17
|
||||
|
||||
### Changed
|
||||
- **Version scheme reset to 0.x**: Superbrain is not yet beta, so releases
|
||||
move from the 1.2.x line to 0.2.x. This release is the same code as
|
||||
1.2.14 (the Nextcloud DAV connection fix) under the new number; future
|
||||
releases continue from 0.2.15. Existing 1.2.x tags and images stay
|
||||
published and untouched, and the 1.2.x entries below are kept as history.
|
||||
The outbound MCP client also now reports the real release version instead
|
||||
of a stale hardcoded one.
|
||||
|
||||
## 1.2.14 — 2026-11-17
|
||||
|
||||
### Fixed
|
||||
- **Connecting the suggested Nextcloud shares on Core now works.** Two bugs
|
||||
combined to make every attempt fail: the app container resolved
|
||||
`nextcloud.<domain>` to the split-horizon *private* container IP (where
|
||||
nothing listens on 443, and the network guard refuses private dials), and
|
||||
the WebDAV/CalDAV prefills pointed one level above Nextcloud's per-user
|
||||
DAV roots. The Core install now pins the Nextcloud hostname to the
|
||||
deployment's public IP for the app container (the same pattern already
|
||||
used for Authelia — the network guard stays fully strict), and the
|
||||
WebDAV/CalDAV suggestions compose your username into the URL
|
||||
(`…/dav/files/<username>/`, `…/dav/calendars/<username>/`), matching the
|
||||
CardDAV prefill. Existing Core installs pick up the fix through the
|
||||
standard upgrade.
|
||||
|
||||
## 1.2.13 — 2026-11-16
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -16,7 +16,7 @@ test:
|
||||
echo "warning: TEST_DATABASE_URL is unset - PostgreSQL integration tests will SKIP."; \
|
||||
echo " run 'make integration' for full coverage."; \
|
||||
fi
|
||||
go test -race ./internal/...
|
||||
go test -race -timeout 30m ./internal/...
|
||||
integration:
|
||||
docker compose run --rm tests
|
||||
# schema.sql <-> migration-chain convergence + runner atomicity proofs
|
||||
|
||||
@@ -4,6 +4,11 @@ A multi-user bookmark workspace: URLs with Markdown notes, tags, calendar
|
||||
dates, editable kanban boards, project collections with typed properties and
|
||||
saved views, pages, previews, sharing, contacts and email signals.
|
||||
|
||||
**Documentation:** [API reference](API.md) — every Go endpoint, request and
|
||||
response contract · [Running superbrain](RUNNING.md) — setup, everyday
|
||||
commands and troubleshooting · [Authelia connection guide](web/docs/AUTHELIA.md)
|
||||
— single sign-on setup.
|
||||
|
||||
## Run the whole app
|
||||
|
||||
**Client setup guide:** [Running superbrain](RUNNING.md) covers cloning, setup,
|
||||
@@ -106,24 +111,39 @@ install it); the index-backed page search depends on it.
|
||||
## Features and integrations
|
||||
|
||||
- Bookmarks: create/edit/delete, tags, contacts, previews, calendar dates,
|
||||
alerts, Markdown downloads and public read-only links.
|
||||
alerts, Markdown downloads and public read-only links. All Bookmarks can
|
||||
group by Calendar (due month), Tags, Kanban, Collections or Contacts, and
|
||||
the Calendar offers Day/Week/Month/Year and a date-sorted List view.
|
||||
- Bookmark collections use cursor pagination; the UI follows every page so
|
||||
collections larger than 200 remain visible on all organization screens.
|
||||
- Notion-style workspace shell: a Quick Find command palette (Ctrl/Cmd+K)
|
||||
jumps to any page, bookmark, tag or view and runs commands (new page, add
|
||||
bookmark, theme toggle); the slim top bar shows a breadcrumb path
|
||||
(workspace / section / page); sidebar sections collapse and page rows
|
||||
expose hover actions (pin, inline rename, delete).
|
||||
- Pages: Markdown editing/autosave with a Notion-style slash-command block
|
||||
menu (type `/` for headings, to-dos, lists, quotes, dividers and code) and
|
||||
the `[]` + space to-do shortcut, link collections, pinning, reorder/export.
|
||||
(workspace / section / page). The sidebar is grouped: Quick find, a Pages
|
||||
group (All Pages tree, Pinned Pages, Untagged Pages), a Bookmarks group
|
||||
(All Bookmarks, Calendar, and expandable Tags / Kanban / Collections /
|
||||
Contacts lists that deep-link to a specific tag, column, collection or
|
||||
contact), and Trash. Sections collapse, page rows expose hover actions
|
||||
(pin, inline rename, delete), and drag reordering persists.
|
||||
- Pages: WYSIWYG editing (Notion-style; Markdown remains the storage
|
||||
format) with autosave, a slash-command block menu (type `/` for headings,
|
||||
to-dos, lists, quotes, dividers and code) and the `[]` + space to-do
|
||||
shortcut. Every URL added to a page — Link button, links popover or a
|
||||
bare-URL paste — is also saved as a bookmark linked to the page, reusing
|
||||
an existing same-URL bookmark instead of duplicating it. Pages can be
|
||||
tagged (drag a page onto a tag), nested under a parent, pinned, reordered
|
||||
and exported; pages link each other and can embed live collections. Every
|
||||
save keeps a restorable revision, and deletions are recoverable from
|
||||
Trash (deleting a parent promotes its children).
|
||||
Saves are queued per page; unsaved drafts are kept in the current browser tab
|
||||
for recovery after a failed save, together with the server version they were
|
||||
based on. Page switching waits for pending saves. When another tab or device
|
||||
saved first, autosave pauses in an explicit conflict state — the editor
|
||||
offers overwrite, save-as-copy and discard, and typing alone never
|
||||
overwrites the newer version.
|
||||
- Kanban: custom columns, card moves, reorder; deleting a column moves cards.
|
||||
- Kanban: custom columns, card moves, reorder; deleting a column moves
|
||||
cards. Only explicitly placed bookmarks appear on the board — unassigned
|
||||
bookmarks stay off it until added.
|
||||
- Collections: per-project workflow state over your existing bookmarks. The
|
||||
same link joins many collections without duplication, each with its own
|
||||
typed properties (text, number, select, multi-select, date, checkbox, URL),
|
||||
@@ -135,6 +155,13 @@ install it); the index-backed page search depends on it.
|
||||
so concurrent editors get a conflict instead of a silent overwrite;
|
||||
reordering and property deletion advance the affected items' and views'
|
||||
revisions too, and deletions are idempotent removals.
|
||||
- Connected services: a WebDAV share, CalDAV calendar or CardDAV address
|
||||
book materializes as its own collection whose files, events or contacts
|
||||
are bookmarks (URL = the DAV location). Sync mirrors the server: vanished
|
||||
items detach but keep their bookmarks, your own removals stay removed,
|
||||
and listings are bounded so a truncated walk never reconciles deletions.
|
||||
Configure in Settings → WebDAV / CalDAV / CardDAV; on Core deployments
|
||||
with Nextcloud the forms offer a one-click prefill for your account.
|
||||
- Sharing: bookmarks, tags and calendar dates; recipients read shared content.
|
||||
Owners can revoke shares. Shared tags and dates expose the associated URLs.
|
||||
Tag sharing is group-wide: every recipient of a tag sees all bookmarks
|
||||
@@ -168,11 +195,25 @@ install it); the index-backed page search depends on it.
|
||||
including watches enabled with the original mailbox-watch switch. The
|
||||
scheduler runs users with bounded concurrency, per-user failure backoff,
|
||||
and a database-backed lease so extra instances never double-poll a mailbox.
|
||||
- Notifications: delivery channels (email via the server's SMTP relay,
|
||||
Slack webhooks, Matrix rooms, Telegram bots) and rules that fire when a
|
||||
new mailbox signal arrives or a bookmark comes due. Channel secrets are
|
||||
encrypted at rest and never echoed back; availability follows your plan.
|
||||
Configure in Settings → Notifications.
|
||||
- Notifications: delivery channels — email via the server's SMTP relay,
|
||||
Slack webhooks, Matrix rooms, Telegram bots and Signal (a signal-cli REST
|
||||
bridge) — and rules that fire when a new mailbox signal arrives, a
|
||||
bookmark comes due, or a share is received. Rules can target other people
|
||||
in your organization; each recipient gets the delivery through their own
|
||||
enabled channel, and history lists every delivery including suppressed
|
||||
ones. Channel secrets are encrypted at rest and never echoed back;
|
||||
availability follows your plan. Configure in Settings → Notifications.
|
||||
- Branded email: password resets, notification deliveries and automation
|
||||
emails use the Superbrain HTML design with a plain-text alternative
|
||||
(reset links get a proper button and an expiry note). Every email carries
|
||||
a footer: **Email preferences** (deep-links to Settings → Notifications),
|
||||
**Help center**, and — only for mail to your own account address —
|
||||
**Unsubscribe**. Unsubscribe works without signing in (the link carries a
|
||||
secure token, and mail clients get native one-click unsubscribe): it turns
|
||||
off your email channels and the automations that email you, never affects
|
||||
password resets or other account emails, and is reversible in Settings.
|
||||
Third-party recipients never receive a link that changes someone else's
|
||||
preferences.
|
||||
- **AI automations ("hey superbrain")**: describe an automation in plain
|
||||
language — *"when the round trip on https://… drops below $400, email
|
||||
david@example.com"* — and Superbrain compiles it into a task you review
|
||||
@@ -193,6 +234,21 @@ install it); the index-backed page search depends on it.
|
||||
stay server-owned) with an optional server-wide key for plans that include
|
||||
it; without any key, AI features report "not configured" and everything
|
||||
else keeps working. Details: RUNNING.md → "AI automations".
|
||||
- Profile: Settings → Profile holds your display name, bio, location,
|
||||
occupation, organization and website; your email stays the read-only
|
||||
sign-in identity. Your name appears where you share with others — public
|
||||
bookmark links never reveal it. Saving refreshes the name shown in the
|
||||
top bar without a re-login. Settings are grouped (Account, Connections,
|
||||
AI & Automation, Developer) and support `?tab=` deep links.
|
||||
- Help center: a public guide at `/help` covers every surface of the app
|
||||
(bookmarks, collections, pages, board, signals, notifications, assistant,
|
||||
connections, developer access) plus an FAQ; linked from the sign-in page
|
||||
and email footers.
|
||||
- Developer access: personal API keys (`sb_…`, Settings → API Keys)
|
||||
authenticate machine clients against the Go API directly, and the
|
||||
`superbrain-mcp` server exposes bookmarks, tags and pages to MCP clients.
|
||||
Settings → MCP also registers external MCP servers for Superbrain to dial
|
||||
as a client. Both follow your plan.
|
||||
|
||||
### Connecting Authelia (OIDC)
|
||||
|
||||
@@ -234,7 +290,7 @@ OIDC_CLIENT_SECRET=<plain-client-secret>
|
||||
Serve the web app through an HTTPS reverse proxy; the default Docker ports
|
||||
bind to localhost. Keep your existing `AUTH_SECRET` unchanged. Apply the
|
||||
environment changes with `docker compose up -d --build`, then check
|
||||
**Settings → OIDC**. When all three variables hold real values, the Authelia
|
||||
**Settings → Sign-in**. When all three variables hold real values, the Authelia
|
||||
button is enabled.
|
||||
|
||||
#### 3. How identity mapping works
|
||||
@@ -314,7 +370,9 @@ npm --prefix scripts run test:regressions
|
||||
These run an isolated Next server with API fixtures and test login CSRF,
|
||||
browser sign-out revocation, autosave switching/ordering/recovery (including
|
||||
drafts whose base version is unknown, which pause for review), pagination,
|
||||
and bookmark editing without creating or deleting application users.
|
||||
bookmark editing, the WebDAV/CalDAV/CardDAV settings walkthroughs and the
|
||||
profile save round-trip (including the session name refresh), without
|
||||
creating or deleting application users.
|
||||
|
||||
Optional operator-provisioned account: set its address in `ADMIN_EMAILS` in
|
||||
the root `.env`, run `docker compose up -d`, then:
|
||||
@@ -359,7 +417,7 @@ sudo bash -c "$(docker run --rm --pull always federatedcomputer/superbrain-migra
|
||||
|
||||
No clone and nothing to copy: the installer and the suite integration files
|
||||
ship inside the migrate image at `/deploy`. Pin a release with
|
||||
`SUPERBRAIN_VERSION=1.2.3` (default `latest`), or use a local checkout's
|
||||
`SUPERBRAIN_VERSION=0.2.17` (default `latest`), or use a local checkout's
|
||||
files instead with `SUPERBRAIN_SRC=/path/to/repo`.
|
||||
|
||||
The installer:
|
||||
@@ -412,10 +470,10 @@ files from the release's migrate image (version defaults to `latest`):
|
||||
sudo bash -c "$(docker run --rm --pull always federatedcomputer/superbrain-migrate cat /deploy/update.sh)" update.sh [version]
|
||||
```
|
||||
|
||||
Releases are semver tags without a `v` prefix (`1.0.0`); CI builds and
|
||||
pushes all three images under the same tag (plus `:latest`) for
|
||||
linux/amd64 and linux/arm64. The migrate image is self-contained: it
|
||||
detects an empty database, applies `schema.sql` as the superbrain user,
|
||||
Releases are semver tags without a `v` prefix (`0.2.17`); the three images
|
||||
are published under the same tag (plus `:latest`) for linux/amd64 and
|
||||
linux/arm64. The migrate image is self-contained: it detects an empty
|
||||
database, applies `schema.sql` as the superbrain user,
|
||||
then runs the checksummed migration ledger, and it carries
|
||||
`deploy/federated/` at `/deploy` — the host never needs the source tree.
|
||||
|
||||
@@ -437,7 +495,16 @@ matching tag. The repositories auto-create on first push under the
|
||||
without registry credentials. Never move an existing tag — cut a new
|
||||
version instead.
|
||||
|
||||
### Option A — CI (preferred): push a tag
|
||||
**How publishing works in this deployment:** a separate process triggered
|
||||
on push to `main` builds and publishes the image set — that is the path
|
||||
that has always delivered releases. The repo's own tag-triggered CI
|
||||
(Option A) runs the smoke gate on every tag, but its publish job needs the
|
||||
one-time `DOCKERHUB_*` secrets setup below; until those are set by a
|
||||
repo-owner account, the publish job fails at login and publishing falls
|
||||
back to the separate process or Option B. The smoke job is still a valid
|
||||
gate either way.
|
||||
|
||||
### Option A — CI: push a tag (publish needs the secrets setup)
|
||||
|
||||
`.github/workflows/release.yml` runs on Gitea Actions for tags matching
|
||||
`[0-9]+.[0-9]+.[0-9]+`. A smoke job first builds the migrate image and
|
||||
@@ -456,12 +523,12 @@ Then releasing is:
|
||||
|
||||
```bash
|
||||
git checkout main && git pull
|
||||
git tag -a 1.2.3 -m "release 1.2.3"
|
||||
git push origin 1.2.3
|
||||
git tag -a 0.2.17 -m "release 0.2.17"
|
||||
git push origin 0.2.17
|
||||
```
|
||||
|
||||
Watch the run under the repo's Actions tab; verify with
|
||||
`docker manifest inspect federatedcomputer/superbrain-app:1.2.3`.
|
||||
`docker manifest inspect federatedcomputer/superbrain-app:0.2.17`.
|
||||
|
||||
### Option B — manual build & push (no runner required)
|
||||
|
||||
@@ -469,7 +536,7 @@ From any Linux machine with Docker, buildx and login rights:
|
||||
|
||||
```bash
|
||||
git clone https://gitea.federated.computer/Federated_Computer/brain.git
|
||||
cd brain && git checkout 1.2.3 # always build from the tag
|
||||
cd brain && git checkout 0.2.17 # always build from the tag
|
||||
|
||||
# One-time per machine: buildx builder + cross-arch emulation
|
||||
docker buildx create --use --name multiarch
|
||||
@@ -486,7 +553,7 @@ docker run --rm --link sb-smoke-pg -e DB_HOST=sb-smoke-pg -e PGPASSWORD=x sb-mig
|
||||
docker rm -f sb-smoke-pg
|
||||
|
||||
# Build + push all three (each command pushes <version> and latest):
|
||||
V=1.2.3
|
||||
V=0.2.17
|
||||
docker buildx build --platform linux/amd64,linux/arm64 --push \
|
||||
-t federatedcomputer/superbrain-app:$V -t federatedcomputer/superbrain-app:latest .
|
||||
docker buildx build --platform linux/amd64,linux/arm64 --push \
|
||||
@@ -527,7 +594,7 @@ is off without it.
|
||||
|---|---|---|---|
|
||||
| `AUTH_SECRET` | **yes** | — | Signs NextAuth JWTs, Go session cookies, proxy assertions and service tokens. Keep stable: rotating it signs everyone out and (without `ENCRYPTION_KEY`) invalidates stored IMAP passwords. `openssl rand -base64 32` |
|
||||
| `NEXTAUTH_SECRET` | no | `AUTH_SECRET` | Alternative name; takes precedence when both are set (both sides use the same precedence) |
|
||||
| `NEXTAUTH_URL` | **yes** in production | — | Exact browser-facing origin. Drives OIDC callbacks, the proxy's origin allowlist, cookie-secure derivation and password-reset links |
|
||||
| `NEXTAUTH_URL` | **yes** in production | — | Exact browser-facing origin. Drives OIDC callbacks, the proxy's origin allowlist, cookie-secure derivation, password-reset links and the email footer links (preferences / help / unsubscribe) |
|
||||
| `ENCRYPTION_KEY` | no | derived from `AUTH_SECRET` | Dedicated key for stored credentials (IMAP passwords, notification channel secrets, BYO AI keys). Set it and rotating `AUTH_SECRET` no longer touches them. Back it up with the database |
|
||||
| `COOKIE_SECURE` | no | derived from `NEXTAUTH_URL` scheme | Set `0` explicitly only for local HTTP |
|
||||
| `DATABASE_URL` | **yes** (Go) | — | `postgres://user:pass@host:5432/db?sslmode=disable`; `DB_URL` is the Makefile fallback |
|
||||
@@ -561,7 +628,7 @@ is off without it.
|
||||
| `OIDC_CLIENT_ID` | for SSO | — | Must match the Authelia client |
|
||||
| `OIDC_CLIENT_SECRET` | for SSO | — | The **plain** secret, not the digest |
|
||||
|
||||
### Transactional mail (password reset + notification email channel)
|
||||
### Transactional mail (password reset, notification + automation email)
|
||||
|
||||
| Variable | Required | Default | Purpose |
|
||||
|---|---|---|---|
|
||||
@@ -602,11 +669,12 @@ is off without it.
|
||||
## Client test build
|
||||
|
||||
Use [RUNNING.md](RUNNING.md) for the client handoff. Test login, bookmark editing,
|
||||
tag/contact organization, calendar dates, kanban, a collections workflow
|
||||
(create a collection, add the same bookmark to two collections, give each a
|
||||
status, move a card on a board view), Markdown pages/exports,
|
||||
Quick Find (Ctrl/Cmd+K), slash commands in the page editor, and sharing with
|
||||
separate accounts.
|
||||
tag/contact organization, calendar dates and views, kanban, a collections
|
||||
workflow (create a collection, add the same bookmark to two collections, give
|
||||
each a status, move a card on a board view), Markdown pages/exports,
|
||||
Quick Find (Ctrl/Cmd+K), slash commands in the page editor, profile
|
||||
particulars (Settings → Profile), the public help center (`/help`), and
|
||||
sharing with separate accounts.
|
||||
|
||||
Current integration boundaries:
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
-- 023_page_tags.sql — pages carry tags (sidebar "Untagged Pages" + drag-to-tag).
|
||||
--
|
||||
-- Additive and idempotent; schema.sql carries the identical table, so this is
|
||||
-- a structural no-op on a fresh database (db-converge proves both paths land
|
||||
-- the same). Mirrors BookmarkTag: composite PK, cascade from both sides.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "PageTag" (
|
||||
"pageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
|
||||
"tagId" text NOT NULL REFERENCES "Tag"(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY ("pageId", "tagId")
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "PageTag_tagId_idx" ON "PageTag"("tagId");
|
||||
@@ -0,0 +1,12 @@
|
||||
-- 024_user_profile.sql — Settings → Profile: editable particulars.
|
||||
--
|
||||
-- Additive and idempotent; schema.sql carries the identical columns, so this
|
||||
-- is a structural no-op on a fresh database (db-converge proves both paths
|
||||
-- land the same). All nullable free text; the API validates lengths and the
|
||||
-- website URL shape (internal/handlers/profile.go).
|
||||
|
||||
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS bio text;
|
||||
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS location text;
|
||||
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS occupation text;
|
||||
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS organization text;
|
||||
ALTER TABLE "User" ADD COLUMN IF NOT EXISTS website text;
|
||||
+16
-1
@@ -40,7 +40,12 @@ CREATE TABLE "User" (
|
||||
"tokenVersion" integer NOT NULL DEFAULT 1,
|
||||
"createdAt" timestamptz NOT NULL DEFAULT now(),
|
||||
"updatedAt" timestamptz NOT NULL DEFAULT now(),
|
||||
"tenantId" text REFERENCES "Tenant"(id) ON DELETE SET NULL
|
||||
"tenantId" text REFERENCES "Tenant"(id) ON DELETE SET NULL,
|
||||
bio text,
|
||||
location text,
|
||||
occupation text,
|
||||
organization text,
|
||||
website text
|
||||
);
|
||||
|
||||
-- 2.2b TenantMember, TenantEntitlement, QuotaUsage (tenancy phase 1).
|
||||
@@ -278,6 +283,16 @@ CREATE INDEX "Page_parentId_idx" ON "Page"("parentId");
|
||||
CREATE INDEX "Page_title_trgm_idx" ON "Page" USING gin (title gin_trgm_ops);
|
||||
CREATE INDEX "Page_content_trgm_idx" ON "Page" USING gin (content gin_trgm_ops);
|
||||
|
||||
-- PageTag: pages carry tags like bookmarks do (owner-scoped writes; a tag
|
||||
-- shared WITH you may be attached to your own pages). Powers the sidebar's
|
||||
-- "Untagged Pages" list and drag-a-page-onto-a-tag. Cascades from both sides.
|
||||
CREATE TABLE "PageTag" (
|
||||
"pageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
|
||||
"tagId" text NOT NULL REFERENCES "Tag"(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY ("pageId", "tagId")
|
||||
);
|
||||
CREATE INDEX "PageTag_tagId_idx" ON "PageTag"("tagId");
|
||||
|
||||
-- 2.13 PageBookmark
|
||||
CREATE TABLE "PageBookmark" (
|
||||
"pageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
|
||||
|
||||
@@ -48,7 +48,7 @@ SUPERBRAIN_APP_IP="192.168.0.94"
|
||||
SUPERBRAIN_MIGRATE_IP="192.168.0.95"
|
||||
# Release to install; the generic `upgrade` flow keeps .env in step with the
|
||||
# service file's VERSION afterwards.
|
||||
SUPERBRAIN_IMAGE_VERSION="1.2.13"
|
||||
SUPERBRAIN_IMAGE_VERSION="0.3.1"
|
||||
|
||||
# render_superbrain_compose writes the app-dir compose file. Called by
|
||||
# config_superbrain (install) and by deploy/federated/update.sh after a lib
|
||||
@@ -69,6 +69,14 @@ services:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
env_file:
|
||||
- ./.env
|
||||
# Split-horizon DNS: nextcloud.$DOMAIN resolves to a private container IP
|
||||
# inside the core network, where nothing listens on 443 (traefik holds
|
||||
# TLS on the public address) and netguard refuses private dials anyway.
|
||||
# Pin the public IP - the same house pattern the web service uses for
|
||||
# authelia - so the WebDAV/CalDAV/CardDAV connectors reach the deployment's
|
||||
# Nextcloud over the public, netguard-clean route. No guard relaxation.
|
||||
extra_hosts:
|
||||
- "nextcloud.$DOMAIN:$EXTERNALIP"
|
||||
healthcheck:
|
||||
test: [CMD, /superbrain, --healthcheck]
|
||||
interval: 3s
|
||||
|
||||
@@ -2,7 +2,7 @@ NAME=superbrain
|
||||
DESCRIPTION="Bookmark & Knowledge Base"
|
||||
DOCS=https://github.com/andrew/superbrain
|
||||
CONTAINER=federatedcomputer/superbrain-app
|
||||
VERSION=1.2.13
|
||||
VERSION=0.3.1
|
||||
INTERNAL_IP=192.168.0.93
|
||||
DEPENDS="postgresql"
|
||||
PORTS=3000
|
||||
|
||||
+1
-1
@@ -148,7 +148,7 @@ services:
|
||||
TEST_DATABASE_URL: postgres://superbrain:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@db:5432/superbrain?sslmode=disable
|
||||
GOCACHE: /tmp/go-cache
|
||||
GOMODCACHE: /tmp/go-mod
|
||||
command: [go, test, -race, -count=1, -v, ./internal/...]
|
||||
command: [go, test, -race, -count=1, -v, -timeout, 30m, ./internal/...]
|
||||
networks: [backend]
|
||||
|
||||
# Fails when db/schema.sql drifts from the migration chain (review MIG-03).
|
||||
|
||||
@@ -370,7 +370,9 @@ func fire(ctx context.Context, d *db.DB, t Task, summary string) (string, string
|
||||
defer release()
|
||||
sendCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
if err := mailer.Send(sendCtx, t.Spec.Action.To, title, body); err != nil {
|
||||
c := notify.FooterLinks(sendCtx, d, t.OwnerID, t.Spec.Action.To)
|
||||
c.Headline, c.Body = title, body
|
||||
if err := mailer.SendTemplate(sendCtx, t.Spec.Action.To, title, body, c); err != nil {
|
||||
return "failed", "email: " + err.Error()
|
||||
}
|
||||
case "bookmark":
|
||||
|
||||
@@ -31,7 +31,8 @@ type SessionUser struct {
|
||||
}
|
||||
|
||||
func identity(u *models.User) map[string]any {
|
||||
return map[string]any{"id": u.ID, "name": u.Name, "email": u.Email, "image": u.Image, "role": u.Role, "tenantId": u.TenantID}
|
||||
return map[string]any{"id": u.ID, "name": u.Name, "email": u.Email, "image": u.Image, "role": u.Role, "tenantId": u.TenantID,
|
||||
"bio": u.Bio, "location": u.Location, "occupation": u.Occupation, "organization": u.Organization, "website": u.Website}
|
||||
}
|
||||
func AuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
@@ -161,7 +162,29 @@ func HandleForgotPassword(w http.ResponseWriter, r *http.Request) {
|
||||
link + "\n\n" +
|
||||
"If you did not request a reset, you can ignore this email; the link is\n" +
|
||||
"single-use and your password stays unchanged.\n"
|
||||
if e := mailer.Send(r.Context(), email, "Reset your Superbrain password", body); e != nil {
|
||||
minutes := int(resetTokenTTL.Minutes())
|
||||
firstName := ""
|
||||
if u.Name != nil {
|
||||
if fields := strings.Fields(*u.Name); len(fields) > 0 {
|
||||
firstName = fields[0]
|
||||
}
|
||||
}
|
||||
content := mailer.Content{
|
||||
Preheader: fmt.Sprintf("Choose a new password — the link expires in %d minutes.", minutes),
|
||||
Headline: "Reset your password",
|
||||
FirstName: firstName,
|
||||
Body: "We received a request to reset your Superbrain password.\nClick the button below to choose a new one.",
|
||||
CTAURL: link,
|
||||
CTALabel: "Choose a new password",
|
||||
Note: fmt.Sprintf("This link expires in %d minutes and can only be used once. "+
|
||||
"If you didn't request a reset, you can ignore this email — your password stays unchanged.", minutes),
|
||||
// Transactional mail: preferences and help, but deliberately NO
|
||||
// unsubscribe — a reset link must never depend on notification
|
||||
// preferences (base is non-empty here; checked above).
|
||||
PreferencesURL: base + "/settings?tab=notifications",
|
||||
HelpURL: base + "/help",
|
||||
}
|
||||
if e := mailer.SendTemplate(r.Context(), email, "Reset your Superbrain password", body, content); e != nil {
|
||||
log.Printf("password reset: delivery to %s failed: %v", email, e)
|
||||
}
|
||||
okResponse()
|
||||
|
||||
@@ -36,11 +36,16 @@ func userFromObject(o Object) (*models.User, error) {
|
||||
Role string `json:"role"`
|
||||
TokenVersion int `json:"tokenVersion"`
|
||||
TenantID *string `json:"tenantId"`
|
||||
Bio *string `json:"bio"`
|
||||
Location *string `json:"location"`
|
||||
Occupation *string `json:"occupation"`
|
||||
Organization *string `json:"organization"`
|
||||
Website *string `json:"website"`
|
||||
}
|
||||
if err = json.Unmarshal(raw, &row); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &models.User{ID: row.ID, Name: row.Name, Email: row.Email, EmailVerified: row.EmailVerified, Image: row.Image, Password: row.Password, Role: row.Role, TokenVersion: row.TokenVersion, TenantID: row.TenantID}, nil
|
||||
return &models.User{ID: row.ID, Name: row.Name, Email: row.Email, EmailVerified: row.EmailVerified, Image: row.Image, Password: row.Password, Role: row.Role, TokenVersion: row.TokenVersion, TenantID: row.TenantID, Bio: row.Bio, Location: row.Location, Occupation: row.Occupation, Organization: row.Organization, Website: row.Website}, nil
|
||||
}
|
||||
|
||||
func findUser(ctx context.Context, q Queryer, field, value string) (*models.User, error) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"sort"
|
||||
@@ -652,3 +653,75 @@ func ruleProjection(row object, channelKind, channelName string) object {
|
||||
"lastFiredAt": row["lastFiredAt"], "version": row["version"], "createdAt": row["createdAt"],
|
||||
}
|
||||
}
|
||||
|
||||
// HandleNotificationUnsubscribe consumes a signed unsubscribe token. There
|
||||
// is no session: the HMAC token IS the credential (it ships only in mail to
|
||||
// the owner's own address, see notify.FooterLinks), which also makes the
|
||||
// endpoint RFC 8058 one-click compatible — mail clients POST to the
|
||||
// List-Unsubscribe URL with the token in the query and a form body we
|
||||
// ignore. The browser confirmation page POSTs JSON {"token": ...} instead.
|
||||
//
|
||||
// Effect: disable the user's enabled email channels and pause enabled agent
|
||||
// tasks whose email action addresses the user's own email. Idempotent, and
|
||||
// deliberately NOT a delete — preferences are re-enableable in Settings.
|
||||
// Transactional mail (password reset) never consults this state.
|
||||
//
|
||||
// POST /api/notifications/unsubscribe?token=...
|
||||
func HandleNotificationUnsubscribe(w http.ResponseWriter, r *http.Request) {
|
||||
token := strings.TrimSpace(r.URL.Query().Get("token"))
|
||||
if token == "" {
|
||||
b, ok := read(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
token = strings.TrimSpace(str(b, "token"))
|
||||
}
|
||||
// token = 32-hex id + "." + 64-hex MAC; anything longer is junk.
|
||||
if token == "" || len(token) > 128 {
|
||||
respond(w, 0, nil, bad("Invalid unsubscribe link"))
|
||||
return
|
||||
}
|
||||
userID, ok := notify.ParseUnsubscribeToken(token)
|
||||
if !ok {
|
||||
respond(w, 0, nil, bad("Invalid unsubscribe link"))
|
||||
return
|
||||
}
|
||||
d := database(r)
|
||||
var email *string
|
||||
if e := d.QueryRowContext(r.Context(), `SELECT email FROM "User" WHERE id=$1`, userID).Scan(&email); e != nil {
|
||||
if errors.Is(e, db.ErrNotFound) {
|
||||
// A valid MAC for a deleted account is still a dead link; the
|
||||
// answer is identical to a tampered token (no oracle).
|
||||
respond(w, 0, nil, bad("Invalid unsubscribe link"))
|
||||
return
|
||||
}
|
||||
respond(w, 0, nil, e)
|
||||
return
|
||||
}
|
||||
chRes, e := d.ExecContext(r.Context(), `
|
||||
UPDATE "NotificationChannel"
|
||||
SET enabled=false, version=version+1, "updatedAt"=now()
|
||||
WHERE "ownerId"=$1 AND kind='email' AND enabled=true`, userID)
|
||||
if e != nil {
|
||||
respond(w, 0, nil, e)
|
||||
return
|
||||
}
|
||||
channels, _ := chRes.RowsAffected()
|
||||
var tasks int64
|
||||
if email != nil && *email != "" {
|
||||
taskRes, e := d.ExecContext(r.Context(), `
|
||||
UPDATE "AgentTask"
|
||||
SET enabled=false, status='paused', version=version+1, "updatedAt"=now()
|
||||
WHERE "ownerId"=$1 AND enabled=true
|
||||
AND spec->'action'->>'type'='email'
|
||||
AND lower(spec->'action'->>'to')=lower($2)`, userID, *email)
|
||||
if e != nil {
|
||||
respond(w, 0, nil, e)
|
||||
return
|
||||
}
|
||||
tasks, _ = taskRes.RowsAffected()
|
||||
}
|
||||
// Audited like other preference changes: ids and counts, no secrets.
|
||||
log.Printf("audit: email unsubscribe for user %s (channels=%d tasks=%d)", userID, channels, tasks)
|
||||
respond(w, 200, object{"ok": true, "channels": channels, "tasks": tasks}, nil)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ func pageView(ctx context.Context, q db.Queryer, id, uid string) (object, error)
|
||||
// outgoing edge set (useful for navigation); the Markdown remains the
|
||||
// source of truth and is rebuilt by syncPageGraph on every content save.
|
||||
return db.One(ctx, q, `SELECT to_jsonb(p)||jsonb_build_object(
|
||||
'tags',COALESCE((SELECT jsonb_agg(jsonb_build_object('tag',to_jsonb(t)) ORDER BY t.name) FROM "PageTag" pt JOIN "Tag" t ON t.id=pt."tagId" WHERE pt."pageId"=p.id),'[]'::jsonb),
|
||||
'bookmarks',COALESCE((SELECT jsonb_agg(to_jsonb(pb)||jsonb_build_object('bookmark',`+db.BookmarkViewerView+`) ORDER BY pb.position) FROM "PageBookmark" pb JOIN "Bookmark" b ON b.id=pb."bookmarkId" WHERE pb."pageId"=p.id AND `+db.BookmarkVisible+`),'[]'::jsonb),
|
||||
'backlinks',COALESCE((SELECT jsonb_agg(jsonb_build_object('id',s.id,'title',s.title,'updatedAt',s."updatedAt") ORDER BY s."updatedAt" DESC,s.id) FROM "PageLink" pl JOIN "Page" s ON s.id=pl."sourcePageId" WHERE pl."targetPageId"=p.id AND s."ownerId"=p."ownerId"),'[]'::jsonb),
|
||||
'links',COALESCE((SELECT jsonb_agg(jsonb_build_object('id',t.id,'title',t.title) ORDER BY t.title,t.id) FROM "PageLink" pl JOIN "Page" t ON t.id=pl."targetPageId" WHERE pl."sourcePageId"=p.id AND t."ownerId"=p."ownerId"),'[]'::jsonb),
|
||||
@@ -47,7 +48,7 @@ func HandlePagesList(w http.ResponseWriter, r *http.Request) {
|
||||
// literal characters, not patterns. The pg_trgm indexes on title/content
|
||||
// let Postgres use the same ILIKE predicate without scanning every page.
|
||||
search := "%" + likeEscaper.Replace(r.URL.Query().Get("search")) + "%"
|
||||
v, e := db.Many(r.Context(), database(r), `SELECT (to_jsonb(p)-'content')||jsonb_build_object('_count',jsonb_build_object(
|
||||
v, e := db.Many(r.Context(), database(r), `SELECT (to_jsonb(p)-'content')||jsonb_build_object('tags',COALESCE((SELECT jsonb_agg(jsonb_build_object('tag',to_jsonb(t)) ORDER BY t.name) FROM "PageTag" pt JOIN "Tag" t ON t.id=pt."tagId" WHERE pt."pageId"=p.id),'[]'::jsonb),'_count',jsonb_build_object(
|
||||
'bookmarks',(SELECT count(*) FROM "PageBookmark" pb WHERE pb."pageId"=p.id),
|
||||
'children',(SELECT count(*) FROM "Page" ch WHERE ch."parentId"=p.id AND ch."ownerId"=p."ownerId"))) FROM "Page" p WHERE "ownerId"=$1 AND (title ILIKE $2 ESCAPE '\' OR content ILIKE $2 ESCAPE '\') ORDER BY pinned DESC,position,"createdAt"`, user(r), search)
|
||||
respond(w, 200, v, e)
|
||||
@@ -324,3 +325,69 @@ func HandlePagesMarkdown(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
markdown.Send(w, markdown.PageDocument(v), str(v, "title"))
|
||||
}
|
||||
|
||||
// pageTagWritable validates a tag may be attached to the caller's own page:
|
||||
// owned by the caller or shared WITH them — the same rule as bookmark tags
|
||||
// (checkRelations). Tagging is metadata: it neither requires nor bumps the
|
||||
// page content version.
|
||||
func pageTagWritable(r *http.Request, tx *sql.Tx, tagID string) error {
|
||||
if _, e := db.One(r.Context(), tx, `SELECT to_jsonb(t) FROM "Tag" t WHERE id=$1 AND ("ownerId"=$2 OR EXISTS(SELECT 1 FROM "TagShare" s WHERE s."tagId"=t.id AND s."userId"=$2))`, tagID, user(r)); e != nil {
|
||||
return bad("Invalid tag")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandlePageTagsAdd attaches a tag to a page (sidebar drag-to-tag / picker).
|
||||
func HandlePageTagsAdd(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
b, ok := read(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
tagID := str(b, "tagId")
|
||||
if tagID == "" {
|
||||
respond(w, 0, nil, bad("tagId required"))
|
||||
return
|
||||
}
|
||||
var v object
|
||||
e := db.Transaction(r.Context(), database(r), func(tx *sql.Tx) error {
|
||||
if e := lockUser(r, tx); e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e := owned(r, tx, "Page", id, "ownerId"); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := pageTagWritable(r, tx, tagID); e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e := tx.ExecContext(r.Context(), `INSERT INTO "PageTag"("pageId","tagId") VALUES($1,$2) ON CONFLICT DO NOTHING`, id, tagID); e != nil {
|
||||
return e
|
||||
}
|
||||
var e error
|
||||
v, e = pageView(r.Context(), tx, id, user(r))
|
||||
return e
|
||||
})
|
||||
respond(w, 200, v, e)
|
||||
}
|
||||
|
||||
// HandlePageTagsRemove detaches a tag from a page.
|
||||
func HandlePageTagsRemove(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
tagID := r.PathValue("tagId")
|
||||
var v object
|
||||
e := db.Transaction(r.Context(), database(r), func(tx *sql.Tx) error {
|
||||
if e := lockUser(r, tx); e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e := owned(r, tx, "Page", id, "ownerId"); e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e := tx.ExecContext(r.Context(), `DELETE FROM "PageTag" WHERE "pageId"=$1 AND "tagId"=$2`, id, tagID); e != nil {
|
||||
return e
|
||||
}
|
||||
var e error
|
||||
v, e = pageView(r.Context(), tx, id, user(r))
|
||||
return e
|
||||
})
|
||||
respond(w, 200, v, e)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package handlers
|
||||
|
||||
// Settings → Profile: the account's particulars (display name, bio,
|
||||
// location, occupation, organization, website). PATCH /api/me updates an
|
||||
// allowlist of free-text fields; an empty string clears the field (NULL).
|
||||
// The User row is identity, not a collaborative collection — it has no
|
||||
// version column, so this follows the settings-save shape rather than the
|
||||
// 409 mutation contract. View-as impersonation is already blocked for
|
||||
// writes by the auth middleware.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
)
|
||||
|
||||
// profileTextFields maps the allowlisted column names to their rune caps.
|
||||
// Keys are server-owned; values are always bind parameters.
|
||||
var profileTextFields = map[string]int{
|
||||
"name": 120,
|
||||
"bio": 280,
|
||||
"location": 120,
|
||||
"occupation": 120,
|
||||
"organization": 120,
|
||||
}
|
||||
|
||||
const maxWebsiteLen = 2048
|
||||
|
||||
// HandleProfileUpdate applies a partial profile edit and answers the fresh
|
||||
// identity projection (the same shape GET /api/me returns under "user").
|
||||
//
|
||||
// PATCH /api/me
|
||||
func HandleProfileUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
b, ok := read(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
updates := object{}
|
||||
for field, maxLen := range profileTextFields {
|
||||
v, present := b[field]
|
||||
if !present {
|
||||
continue
|
||||
}
|
||||
s, isStr := v.(string)
|
||||
if !isStr {
|
||||
respond(w, 0, nil, bad(field+" must be a string"))
|
||||
return
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if len([]rune(s)) > maxLen {
|
||||
respond(w, 0, nil, bad(fmt.Sprintf("%s must be at most %d characters", field, maxLen)))
|
||||
return
|
||||
}
|
||||
if s == "" {
|
||||
updates[field] = nil
|
||||
} else {
|
||||
updates[field] = s
|
||||
}
|
||||
}
|
||||
if v, present := b["website"]; present {
|
||||
s, isStr := v.(string)
|
||||
if !isStr {
|
||||
respond(w, 0, nil, bad("website must be a string"))
|
||||
return
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
updates["website"] = nil
|
||||
} else {
|
||||
u, e := url.Parse(s)
|
||||
if len(s) > maxWebsiteLen || e != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
respond(w, 0, nil, bad("website must be an http(s) URL"))
|
||||
return
|
||||
}
|
||||
updates["website"] = s
|
||||
}
|
||||
}
|
||||
if len(updates) == 0 {
|
||||
respond(w, 0, nil, bad("Nothing to update"))
|
||||
return
|
||||
}
|
||||
keys := make([]string, 0, len(updates))
|
||||
for k := range updates {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
sets := make([]string, 0, len(keys))
|
||||
args := make([]any, 0, len(keys)+1)
|
||||
for i, k := range keys {
|
||||
sets = append(sets, db.Quote(k)+fmt.Sprintf("=$%d", i+1))
|
||||
args = append(args, updates[k])
|
||||
}
|
||||
args = append(args, user(r))
|
||||
row, e := db.One(r.Context(), database(r),
|
||||
`UPDATE "User" SET `+strings.Join(sets, ",")+`, "updatedAt"=now() WHERE id=$`+fmt.Sprint(len(args))+` RETURNING to_jsonb("User")`, args...)
|
||||
if e != nil {
|
||||
respond(w, 0, nil, e)
|
||||
return
|
||||
}
|
||||
respond(w, 200, profileProjection(row), nil)
|
||||
}
|
||||
|
||||
// profileProjection mirrors auth.identity (the GET /api/me "user" shape)
|
||||
// so the client can refresh its state from the save response alone.
|
||||
func profileProjection(row object) object {
|
||||
return object{
|
||||
"id": row["id"], "name": row["name"], "email": row["email"], "image": row["image"],
|
||||
"role": row["role"], "tenantId": row["tenantId"],
|
||||
"bio": row["bio"], "location": row["location"], "occupation": row["occupation"],
|
||||
"organization": row["organization"], "website": row["website"],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package http
|
||||
|
||||
import "testing"
|
||||
|
||||
// Page tags (sidebar "Untagged Pages" + drag-a-page-onto-a-tag): pages carry
|
||||
// tags like bookmarks, owner-scoped writes, metadata (no content-version
|
||||
// bump), cascade on tag/page delete, and the list/detail projections expose
|
||||
// tags so the sidebar can compute the untagged subset.
|
||||
func TestPageTags(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
alice := newAPIUser(t, srv, "page-tags@superbrain.test")
|
||||
bob := newAPIUser(t, srv, "page-tags-other@superbrain.test")
|
||||
|
||||
page := alice.request("POST", "/api/pages", map[string]any{"title": "Taggable"}, 201)["id"].(string)
|
||||
other := alice.request("POST", "/api/pages", map[string]any{"title": "Untagged"}, 201)["id"].(string)
|
||||
tag := alice.request("POST", "/api/tags", map[string]any{"name": "research", "color": "#123456"}, 201)["id"].(string)
|
||||
|
||||
tagsOf := func(c apiClient, id string) []any {
|
||||
v := c.request("GET", "/api/pages/"+id, nil, 200)
|
||||
tags, _ := v["tags"].([]any)
|
||||
return tags
|
||||
}
|
||||
listTags := func(id string) []any {
|
||||
for _, p := range alice.getJSON("/api/pages", 200) {
|
||||
if p["id"] == id {
|
||||
tags, _ := p["tags"].([]any)
|
||||
return tags
|
||||
}
|
||||
}
|
||||
t.Fatalf("page %s not in list", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Both pages start untagged in detail AND list projections.
|
||||
if len(tagsOf(alice, page)) != 0 || len(tagsOf(alice, other)) != 0 {
|
||||
t.Fatal("pages should start untagged")
|
||||
}
|
||||
if len(listTags(page)) != 0 || len(listTags(other)) != 0 {
|
||||
t.Fatal("list projection should expose empty tags for untagged pages")
|
||||
}
|
||||
|
||||
// Attach: returns the refreshed projection carrying the tag.
|
||||
v0 := pageVersion(t, alice, page)
|
||||
res := alice.request("POST", "/api/pages/"+page+"/tags", map[string]any{"tagId": tag}, 200)
|
||||
if tags, _ := res["tags"].([]any); len(tags) != 1 {
|
||||
t.Fatalf("attach should return one tag: %v", res["tags"])
|
||||
}
|
||||
if len(tagsOf(alice, page)) != 1 || len(listTags(page)) != 1 {
|
||||
t.Fatal("tag not reflected in detail/list after attach")
|
||||
}
|
||||
// Tagging is metadata: it must not bump the content version.
|
||||
if pageVersion(t, alice, page) != v0 {
|
||||
t.Fatal("tag attach bumped the page content version")
|
||||
}
|
||||
// The other page stays untagged (the sidebar's untagged subset).
|
||||
if len(listTags(other)) != 0 {
|
||||
t.Fatal("unrelated page became tagged")
|
||||
}
|
||||
|
||||
// Idempotent re-attach.
|
||||
alice.request("POST", "/api/pages/"+page+"/tags", map[string]any{"tagId": tag}, 200)
|
||||
if len(tagsOf(alice, page)) != 1 {
|
||||
t.Fatal("re-attach duplicated the tag")
|
||||
}
|
||||
|
||||
// Invalid tag and missing tagId are rejected.
|
||||
alice.request("POST", "/api/pages/"+page+"/tags", map[string]any{"tagId": "nope"}, 400)
|
||||
alice.request("POST", "/api/pages/"+page+"/tags", map[string]any{}, 400)
|
||||
|
||||
// Cross-owner: bob cannot tag alice's page (404), even with his own tag.
|
||||
bobTag := bob.request("POST", "/api/tags", map[string]any{"name": "bobtag"}, 201)["id"].(string)
|
||||
bob.request("POST", "/api/pages/"+page+"/tags", map[string]any{"tagId": bobTag}, 404)
|
||||
bob.request("DELETE", "/api/pages/"+page+"/tags/"+tag, nil, 404)
|
||||
|
||||
// Detach.
|
||||
alice.request("DELETE", "/api/pages/"+page+"/tags/"+tag, nil, 200)
|
||||
if len(tagsOf(alice, page)) != 0 {
|
||||
t.Fatal("detach left the tag attached")
|
||||
}
|
||||
|
||||
// Deleting the tag cascades the join row.
|
||||
alice.request("POST", "/api/pages/"+page+"/tags", map[string]any{"tagId": tag}, 200)
|
||||
alice.request("DELETE", "/api/tags/"+tag, nil, 200)
|
||||
if len(tagsOf(alice, page)) != 0 {
|
||||
t.Fatal("tag delete did not cascade PageTag")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Settings → Profile: the identity projection carries the particulars,
|
||||
// PATCH /api/me applies partial allowlisted edits (empty string clears),
|
||||
// validation is rune-based, and the endpoint is session-gated.
|
||||
func TestProfileUpdate(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
jar, _ := cookiejar.New(nil)
|
||||
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||
|
||||
fields := []string{"bio", "location", "occupation", "organization", "website"}
|
||||
user := alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
|
||||
for _, f := range fields {
|
||||
if v, present := user[f]; !present || v != nil {
|
||||
t.Fatalf("fresh profile field %s = %v (present=%v), want null", f, v, present)
|
||||
}
|
||||
}
|
||||
|
||||
saved := alice.request("PATCH", "/api/me", map[string]any{
|
||||
"name": "Alice Example", "bio": "Knowledge worker", "location": "Berlin, Germany",
|
||||
"occupation": "Engineer", "organization": "Acme", "website": "https://alice.example.com",
|
||||
}, 200)
|
||||
if saved["name"] != "Alice Example" || saved["bio"] != "Knowledge worker" ||
|
||||
saved["location"] != "Berlin, Germany" || saved["occupation"] != "Engineer" ||
|
||||
saved["organization"] != "Acme" || saved["website"] != "https://alice.example.com" {
|
||||
t.Fatalf("save response wrong: %v", saved)
|
||||
}
|
||||
// The session identity is reloaded per request: GET /api/me reflects it.
|
||||
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
|
||||
if user["name"] != "Alice Example" || user["occupation"] != "Engineer" {
|
||||
t.Fatalf("GET /api/me did not reflect the save: %v", user)
|
||||
}
|
||||
|
||||
// Partial edit: only the submitted field moves.
|
||||
alice.request("PATCH", "/api/me", map[string]any{"bio": "Updated bio"}, 200)
|
||||
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
|
||||
if user["bio"] != "Updated bio" || user["location"] != "Berlin, Germany" || user["name"] != "Alice Example" {
|
||||
t.Fatalf("partial edit clobbered other fields: %v", user)
|
||||
}
|
||||
|
||||
// Empty string clears to null; whitespace-only is empty too.
|
||||
alice.request("PATCH", "/api/me", map[string]any{"bio": " ", "website": ""}, 200)
|
||||
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
|
||||
if user["bio"] != nil || user["website"] != nil {
|
||||
t.Fatalf("clear did not null the fields: %v", user)
|
||||
}
|
||||
|
||||
// Rune-based caps: 280 multi-byte runes fit, 281 do not.
|
||||
alice.request("PATCH", "/api/me", map[string]any{"bio": strings.Repeat("é", 280)}, 200)
|
||||
alice.request("PATCH", "/api/me", map[string]any{"bio": strings.Repeat("é", 281)}, 400)
|
||||
alice.request("PATCH", "/api/me", map[string]any{"name": strings.Repeat("x", 121)}, 400)
|
||||
|
||||
// Website shape: http(s) with a host only.
|
||||
for _, badURL := range []string{"javascript:alert(1)", "ftp://x.test", "not a url", "https://", "/relative"} {
|
||||
alice.request("PATCH", "/api/me", map[string]any{"website": badURL}, 400)
|
||||
}
|
||||
alice.request("PATCH", "/api/me", map[string]any{"website": "http://alice.example.com/path"}, 200)
|
||||
|
||||
// Type and emptiness guards.
|
||||
alice.request("PATCH", "/api/me", map[string]any{"bio": 42}, 400)
|
||||
alice.request("PATCH", "/api/me", map[string]any{"unknown": "x"}, 400)
|
||||
alice.request("PATCH", "/api/me", map[string]any{}, 400)
|
||||
|
||||
// Session-gated like every data endpoint.
|
||||
anon := apiClient{t, &http.Client{}, srv.URL}
|
||||
anon.request("PATCH", "/api/me", map[string]any{"bio": "intruder"}, 401)
|
||||
}
|
||||
@@ -48,6 +48,7 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
|
||||
mux.HandleFunc("GET /api/auth/", auth.HandleAuth) // csrf, callbacks, session, signout
|
||||
mux.HandleFunc("POST /api/auth/", auth.HandleAuth)
|
||||
mux.HandleFunc("GET /api/me", authed(auth.HandleMe))
|
||||
mux.HandleFunc("PATCH /api/me", authed(handlers.HandleProfileUpdate))
|
||||
|
||||
// Authelia OIDC (stub-aware; the client drives the flow via NextAuth)
|
||||
mux.HandleFunc("GET /api/auth/oidc/status", oidc.HandleStatus)
|
||||
@@ -102,6 +103,8 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
|
||||
mux.HandleFunc("GET /api/pages/{id}/revisions/{revisionId}", authed(handlers.HandlePageRevisionsGet))
|
||||
mux.HandleFunc("POST /api/pages/{id}/revisions/{revisionId}/restore", authed(handlers.HandlePageRevisionsRestore))
|
||||
mux.HandleFunc("GET /api/pages/{id}/markdown", authed(handlers.HandlePagesMarkdown))
|
||||
mux.HandleFunc("POST /api/pages/{id}/tags", authed(handlers.HandlePageTagsAdd))
|
||||
mux.HandleFunc("DELETE /api/pages/{id}/tags/{tagId}", authed(handlers.HandlePageTagsRemove))
|
||||
|
||||
// Trust phase: recoverable deletions and structured export.
|
||||
mux.HandleFunc("GET /api/trash", authed(handlers.HandleTrashList))
|
||||
@@ -126,6 +129,12 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
|
||||
mux.HandleFunc("PATCH /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesUpdate))
|
||||
mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete))
|
||||
mux.HandleFunc("GET /api/notifications", authed(handlers.HandleNotificationsList))
|
||||
// Unsubscribe is token-authenticated (no session — the HMAC token in the
|
||||
// mail IS the credential), so it gets the public-endpoint treatment: a
|
||||
// per-effective-client rate limit, never the shared Next container bucket.
|
||||
unsubscribeLimiter := auth.NewLimiterStore()
|
||||
mux.HandleFunc("POST /api/notifications/unsubscribe",
|
||||
auth.Limiter(unsubscribeLimiter, 10, time.Minute)(handlers.HandleNotificationUnsubscribe))
|
||||
|
||||
// 4.7c Agent automations ("hey superbrain"): compile NL into a validated
|
||||
// proposal (never writes), then owner-confirmed task CRUD + runs.
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/notify"
|
||||
)
|
||||
|
||||
var unsubTokenRx = regexp.MustCompile(`/unsubscribe\?token=([0-9a-f.]+)`)
|
||||
|
||||
// The unsubscribe surface end to end: footer links + RFC 8058 headers on
|
||||
// owner-addressed mail, the token-credentialed one-click endpoint (no
|
||||
// session), the exact blast radius (email channels + self-addressed agent
|
||||
// email tasks, nothing else), idempotence, and the third-party/transactional
|
||||
// exclusions.
|
||||
func TestUnsubscribeFlow(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
smtp := newFakeSMTP(t)
|
||||
host, port, _ := net.SplitHostPort(smtp.ln.Addr().String())
|
||||
t.Setenv("SMTP_HOST", host)
|
||||
t.Setenv("SMTP_PORT", port)
|
||||
t.Setenv("SMTP_FROM", "superbrain@superbrain.test")
|
||||
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
|
||||
|
||||
jar, _ := cookiejar.New(nil)
|
||||
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||
aliceID := meID(alice)
|
||||
|
||||
hook := newFakeWebhook(t)
|
||||
selfCh := alice.request("POST", "/api/notifications/channels", map[string]any{
|
||||
"kind": "email", "name": "My inbox", "config": map[string]any{"address": ""},
|
||||
}, 201)
|
||||
thirdCh := alice.request("POST", "/api/notifications/channels", map[string]any{
|
||||
"kind": "email", "name": "Bob's inbox", "config": map[string]any{"address": "bob@superbrain.test"},
|
||||
}, 201)
|
||||
slackCh := alice.request("POST", "/api/notifications/channels", map[string]any{
|
||||
"kind": "slack", "name": "Team", "config": map[string]any{"webhookUrl": hook.url()},
|
||||
}, 201)
|
||||
|
||||
// Signal-condition email tasks need no AI. One addresses the owner,
|
||||
// one a third party: unsubscribe must pause only the former.
|
||||
selfTask := alice.request("POST", "/api/agent/tasks", map[string]any{"name": "Self mail", "spec": map[string]any{
|
||||
"condition": map[string]any{"type": "signal"},
|
||||
"action": map[string]any{"type": "email", "to": "alice@superbrain.test"},
|
||||
}}, 201)
|
||||
thirdTask := alice.request("POST", "/api/agent/tasks", map[string]any{"name": "Bob mail", "spec": map[string]any{
|
||||
"condition": map[string]any{"type": "signal"},
|
||||
"action": map[string]any{"type": "email", "to": "bob@superbrain.test"},
|
||||
}}, 201)
|
||||
|
||||
// --- owner-addressed delivery carries footer links + one-click headers ---
|
||||
due := time.Now().UTC().Add(6 * time.Hour).Format(time.RFC3339)
|
||||
alice.request("POST", "/api/bookmarks", map[string]any{
|
||||
"url": "https://example.org/unsub-due", "title": "Unsub due", "dueDate": due,
|
||||
}, 201)
|
||||
alice.request("POST", "/api/notifications/rules", map[string]any{
|
||||
"name": "Due reminders", "trigger": "bookmark_due", "channelId": selfCh["id"],
|
||||
"config": map[string]any{"leadHours": 24}, "cooldownMinutes": 60,
|
||||
}, 201)
|
||||
if e := notify.RunOnce(context.Background(), d); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
msg := smtp.waitForMessage(t, 1)
|
||||
if msg[0] != "alice@superbrain.test" {
|
||||
t.Fatalf("envelope recipient = %q", msg[0])
|
||||
}
|
||||
for _, want := range []string{
|
||||
"List-Unsubscribe: <https://superbrain.test/api/notifications/unsubscribe?token=",
|
||||
"List-Unsubscribe-Post: List-Unsubscribe=One-Click",
|
||||
"https://superbrain.test/unsubscribe?token=",
|
||||
"https://superbrain.test/settings?tab=notifications",
|
||||
"https://superbrain.test/help",
|
||||
} {
|
||||
if !strings.Contains(msg[1], want) {
|
||||
t.Fatalf("owner-addressed mail missing %q:\n%s", want, msg[1])
|
||||
}
|
||||
}
|
||||
m := unsubTokenRx.FindStringSubmatch(msg[1])
|
||||
if m == nil {
|
||||
t.Fatalf("no unsubscribe token in mail:\n%s", msg[1])
|
||||
}
|
||||
token := m[1]
|
||||
if id, ok := notify.ParseUnsubscribeToken(token); !ok || id != aliceID {
|
||||
t.Fatalf("token resolves to %q (%v), want the channel owner %q", id, ok, aliceID)
|
||||
}
|
||||
|
||||
// --- RFC 8058 one-click: no session, token in the query, form body ---
|
||||
oneClick := func(tok string) map[string]any {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest("POST", srv.URL+"/api/notifications/unsubscribe?token="+tok,
|
||||
strings.NewReader("List-Unsubscribe=One-Click"))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
res, e := (&http.Client{}).Do(req)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode != 200 {
|
||||
t.Fatalf("one-click unsubscribe: wanted 200, got %d: %s", res.StatusCode, raw)
|
||||
}
|
||||
var v map[string]any
|
||||
if e := json.Unmarshal(raw, &v); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return v
|
||||
}
|
||||
got := oneClick(token)
|
||||
if got["ok"] != true || got["channels"].(float64) != 2 || got["tasks"].(float64) != 1 {
|
||||
t.Fatalf("unsubscribe result = %v, want ok with 2 email channels + 1 self-addressed task", got)
|
||||
}
|
||||
|
||||
// Blast radius: BOTH of alice's email channels disabled (the preference
|
||||
// is account-wide), slack untouched; only the self-addressed task paused.
|
||||
channels := map[string]map[string]any{}
|
||||
for _, row := range listGET(alice, "/api/notifications/channels") {
|
||||
r := row.(map[string]any)
|
||||
channels[r["id"].(string)] = r
|
||||
}
|
||||
if channels[selfCh["id"].(string)]["enabled"] != false || channels[thirdCh["id"].(string)]["enabled"] != false {
|
||||
t.Fatalf("email channels not disabled: %v", channels)
|
||||
}
|
||||
if channels[slackCh["id"].(string)]["enabled"] != true {
|
||||
t.Fatalf("slack channel must survive unsubscribe: %v", channels[slackCh["id"].(string)])
|
||||
}
|
||||
tasks := map[string]map[string]any{}
|
||||
for _, row := range listGET(alice, "/api/agent/tasks") {
|
||||
r := row.(map[string]any)
|
||||
tasks[r["id"].(string)] = r
|
||||
}
|
||||
if tasks[selfTask["id"].(string)]["enabled"] != false || tasks[selfTask["id"].(string)]["status"] != "paused" {
|
||||
t.Fatalf("self-addressed task not paused: %v", tasks[selfTask["id"].(string)])
|
||||
}
|
||||
if tasks[thirdTask["id"].(string)]["enabled"] != true {
|
||||
t.Fatalf("third-party task must survive unsubscribe: %v", tasks[thirdTask["id"].(string)])
|
||||
}
|
||||
|
||||
// Idempotent: a second click changes nothing.
|
||||
got = oneClick(token)
|
||||
if got["channels"].(float64) != 0 || got["tasks"].(float64) != 0 {
|
||||
t.Fatalf("second unsubscribe = %v, want zero counts", got)
|
||||
}
|
||||
|
||||
// Tampered and junk tokens are dead links (400, identical answers).
|
||||
for _, bad := range []string{
|
||||
token[:len(token)-1] + "0",
|
||||
strings.Repeat("f", 32) + "." + strings.Repeat("0", 64),
|
||||
"not-a-token",
|
||||
} {
|
||||
req, _ := http.NewRequest("POST", srv.URL+"/api/notifications/unsubscribe?token="+bad, nil)
|
||||
res, e := (&http.Client{}).Do(req)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != 400 {
|
||||
t.Fatalf("bad token %q: wanted 400, got %d", bad, res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// --- browser confirmation path: JSON body, no query token ---
|
||||
alice.request("PATCH", "/api/notifications/channels/"+selfCh["id"].(string), map[string]any{
|
||||
"enabled": true, "version": int(channels[selfCh["id"].(string)]["version"].(float64)),
|
||||
}, 200)
|
||||
anon := apiClient{t, &http.Client{}, srv.URL}
|
||||
got = anon.request("POST", "/api/notifications/unsubscribe", map[string]any{"token": token}, 200)
|
||||
if got["channels"].(float64) != 1 {
|
||||
t.Fatalf("JSON-body unsubscribe = %v, want the re-enabled channel disabled again", got)
|
||||
}
|
||||
|
||||
// --- third-party recipient: footer help/preferences, NO unsubscribe ---
|
||||
// Unsubscribe is account-wide, so re-enable the third-party channel
|
||||
// first (an owner may keep mailing other people after unsubscribing
|
||||
// themselves).
|
||||
alice.request("PATCH", "/api/notifications/channels/"+thirdCh["id"].(string), map[string]any{
|
||||
"enabled": true, "version": int(channels[thirdCh["id"].(string)]["version"].(float64)),
|
||||
}, 200)
|
||||
alice.request("POST", "/api/bookmarks", map[string]any{
|
||||
"url": "https://example.org/unsub-due-2", "title": "Unsub due 2", "dueDate": due,
|
||||
}, 201)
|
||||
alice.request("POST", "/api/notifications/rules", map[string]any{
|
||||
"name": "Bob reminders", "trigger": "bookmark_due", "channelId": thirdCh["id"],
|
||||
"config": map[string]any{"leadHours": 24}, "cooldownMinutes": 60,
|
||||
}, 201)
|
||||
if e := notify.RunOnce(context.Background(), d); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
msg = smtp.waitForMessage(t, 2)
|
||||
if msg[0] != "bob@superbrain.test" {
|
||||
t.Fatalf("third-party envelope recipient = %q", msg[0])
|
||||
}
|
||||
if !strings.Contains(msg[1], "https://superbrain.test/help") {
|
||||
t.Fatalf("third-party mail lost the help footer:\n%s", msg[1])
|
||||
}
|
||||
if strings.Contains(msg[1], "List-Unsubscribe") || strings.Contains(msg[1], "/unsubscribe?token=") {
|
||||
t.Fatalf("third-party recipient must never receive an unsubscribe link:\n%s", msg[1])
|
||||
}
|
||||
|
||||
// --- transactional mail: preferences + help, never unsubscribe ---
|
||||
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
|
||||
msg = smtp.waitForMessage(t, 3)
|
||||
if !strings.Contains(msg[1], "https://superbrain.test/settings?tab=notifications") ||
|
||||
!strings.Contains(msg[1], "https://superbrain.test/help") {
|
||||
t.Fatalf("reset mail missing footer links:\n%s", msg[1])
|
||||
}
|
||||
if strings.Contains(msg[1], "List-Unsubscribe") || strings.Contains(msg[1], "/unsubscribe?token=") {
|
||||
t.Fatalf("transactional mail must not carry unsubscribe:\n%s", msg[1])
|
||||
}
|
||||
}
|
||||
+94
-14
@@ -1,5 +1,7 @@
|
||||
// Package mailer sends transactional email (password-reset links) through a
|
||||
// configured SMTP relay.
|
||||
// Package mailer sends transactional email (password-reset links,
|
||||
// notification and agent deliveries) through a configured SMTP relay.
|
||||
// Messages go out as the branded HTML design (template.html, see Render)
|
||||
// with a plain-text alternative; Send remains available for plain-only mail.
|
||||
//
|
||||
// Like every server-initiated dial, sending is bounded by internal/outbound
|
||||
// and guarded by internal/netguard: private/link-local relay hosts (the
|
||||
@@ -18,7 +20,9 @@ package mailer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
@@ -74,6 +78,22 @@ func (c Config) Configured() bool { return c.Host != "" && c.From != "" }
|
||||
// Send delivers one plain-text message. It is synchronous: the caller owns
|
||||
// the request context and any retry policy.
|
||||
func Send(ctx context.Context, to, subject, body string) error {
|
||||
return send(ctx, to, subject, body, "", "")
|
||||
}
|
||||
|
||||
// SendTemplate delivers one branded message as multipart/alternative: text
|
||||
// is the plain-text alternative, c describes the HTML rendering. A render
|
||||
// failure (template drift) degrades to plain text — delivery never blocks
|
||||
// on cosmetics.
|
||||
func SendTemplate(ctx context.Context, to, subject, text string, c Content) error {
|
||||
html, err := Render(subject, c)
|
||||
if err != nil {
|
||||
html = ""
|
||||
}
|
||||
return send(ctx, to, subject, text, html, c.UnsubscribePostURL)
|
||||
}
|
||||
|
||||
func send(ctx context.Context, to, subject, body, html, listUnsub string) error {
|
||||
cfg := LoadConfig()
|
||||
if !cfg.Configured() {
|
||||
return ErrNotConfigured
|
||||
@@ -139,18 +159,7 @@ func Send(ctx context.Context, to, subject, body string) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("mailer: DATA: %w", err)
|
||||
}
|
||||
msg := strings.Join([]string{
|
||||
"From: " + cfg.From,
|
||||
"To: " + to,
|
||||
"Subject: " + sanitizeHeader(subject),
|
||||
"Date: " + time.Now().UTC().Format(time.RFC1123Z),
|
||||
"MIME-Version: 1.0",
|
||||
"Content-Type: text/plain; charset=UTF-8",
|
||||
"Content-Transfer-Encoding: 8BIT",
|
||||
"",
|
||||
body,
|
||||
"",
|
||||
}, "\r\n")
|
||||
msg := buildMessage(cfg.From, to, subject, body, html, listUnsub)
|
||||
if _, err := data.Write([]byte(msg)); err != nil {
|
||||
return fmt.Errorf("mailer: write: %w", err)
|
||||
}
|
||||
@@ -168,6 +177,77 @@ func sanitizeHeader(s string) string {
|
||||
return strings.NewReplacer("\r", " ", "\n", " ").Replace(strings.TrimSpace(s))
|
||||
}
|
||||
|
||||
// buildMessage assembles the RFC 5322 payload: plain-only when html is
|
||||
// empty, otherwise multipart/alternative with the plain part first (RFC
|
||||
// 2046: least-preferred alternative first, HTML last). A non-empty
|
||||
// listUnsub adds the RFC 8058 one-click unsubscribe headers.
|
||||
func buildMessage(from, to, subject, text, html, listUnsub string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("From: " + sanitizeHeader(from) + "\r\n")
|
||||
b.WriteString("To: " + sanitizeHeader(to) + "\r\n")
|
||||
b.WriteString("Subject: " + sanitizeHeader(subject) + "\r\n")
|
||||
b.WriteString("Date: " + time.Now().UTC().Format(time.RFC1123Z) + "\r\n")
|
||||
b.WriteString("MIME-Version: 1.0\r\n")
|
||||
if listUnsub != "" {
|
||||
b.WriteString("List-Unsubscribe: <" + sanitizeHeader(listUnsub) + ">\r\n")
|
||||
b.WriteString("List-Unsubscribe-Post: List-Unsubscribe=One-Click\r\n")
|
||||
}
|
||||
if html == "" {
|
||||
b.WriteString("Content-Type: text/plain; charset=UTF-8\r\n")
|
||||
b.WriteString("Content-Transfer-Encoding: 8BIT\r\n")
|
||||
b.WriteString("\r\n")
|
||||
b.WriteString(smtpBody(text))
|
||||
b.WriteString("\r\n")
|
||||
return b.String()
|
||||
}
|
||||
boundary := newBoundary(text, html)
|
||||
b.WriteString("Content-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n")
|
||||
b.WriteString("\r\n")
|
||||
b.WriteString("--" + boundary + "\r\n")
|
||||
b.WriteString("Content-Type: text/plain; charset=UTF-8\r\n")
|
||||
b.WriteString("Content-Transfer-Encoding: 8BIT\r\n")
|
||||
b.WriteString("\r\n")
|
||||
b.WriteString(smtpBody(text))
|
||||
b.WriteString("\r\n--" + boundary + "\r\n")
|
||||
b.WriteString("Content-Type: text/html; charset=UTF-8\r\n")
|
||||
b.WriteString("Content-Transfer-Encoding: 8BIT\r\n")
|
||||
b.WriteString("\r\n")
|
||||
b.WriteString(smtpBody(html))
|
||||
b.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// newBoundary picks a random multipart boundary that does not occur in
|
||||
// either part (a collision would truncate the message at the relay).
|
||||
func newBoundary(text, html string) string {
|
||||
for {
|
||||
raw := make([]byte, 16)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
// crypto/rand never fails on the supported platforms; a fixed
|
||||
// fallback still beats an empty boundary.
|
||||
return "superbrain-boundary-0000000000000000"
|
||||
}
|
||||
b := "sb-" + hex.EncodeToString(raw)
|
||||
if !strings.Contains(text, b) && !strings.Contains(html, b) {
|
||||
return b
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// smtpBody normalizes line endings to CRLF and dot-stuffs (RFC 5321
|
||||
// §4.5.2): a line consisting of or starting with "." must be doubled so
|
||||
// the DATA terminator can never appear inside a part.
|
||||
func smtpBody(s string) string {
|
||||
s = strings.ReplaceAll(s, "\r\n", "\n")
|
||||
s = strings.ReplaceAll(s, "\r", "\n")
|
||||
s = strings.ReplaceAll(s, "\n", "\r\n")
|
||||
s = strings.ReplaceAll(s, "\r\n.", "\r\n..")
|
||||
if strings.HasPrefix(s, ".") {
|
||||
s = "." + s
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// dial resolves and connects through netguard: range checks apply unless
|
||||
// INTEGRATIONS_ALLOW_PRIVATE=1 (house relays live on private networks), and
|
||||
// only the standard SMTP ports are reachable from public ranges.
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
// Branded HTML rendering for transactional email. template.html is the
|
||||
// Superbrain email design (table layout, Outlook VML button fallback,
|
||||
// dark-mode overrides); it is embedded verbatim and filled here.
|
||||
//
|
||||
// The template uses {{placeholder}} markers rather than text/template so
|
||||
// the design file stays editable as plain HTML (and Outlook conditional
|
||||
// comments survive untouched). Every substituted value is HTML-escaped,
|
||||
// and optional sections (CTA button + fallback link, note block, footer
|
||||
// links, address line) are removed when their values are empty.
|
||||
|
||||
package mailer
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed template.html
|
||||
var emailTemplate string
|
||||
|
||||
// Content describes one branded rendering. Headline falls back to the
|
||||
// subject, SignOff to "Thanks,", CTALabel to "Open Superbrain", and the
|
||||
// preheader to the first body paragraph. Empty optional fields remove
|
||||
// their section instead of rendering a stub.
|
||||
type Content struct {
|
||||
Preheader string // inbox preview line (kept under ~90 characters)
|
||||
Headline string
|
||||
FirstName string // optional; the greeting degrades to "Hi,"
|
||||
Body string // newline-separated paragraphs
|
||||
CTAURL string // optional button + fallback link
|
||||
CTALabel string
|
||||
Note string // optional highlighted note block
|
||||
SignOff string
|
||||
|
||||
// Optional footer links; unset ones are omitted.
|
||||
PreferencesURL string
|
||||
UnsubscribeURL string
|
||||
HelpURL string
|
||||
CompanyAddress string
|
||||
|
||||
// UnsubscribePostURL is the RFC 8058 one-click endpoint (POST, token in
|
||||
// the query). When set, the message carries List-Unsubscribe +
|
||||
// List-Unsubscribe-Post headers so mail clients can offer native
|
||||
// unsubscribe. It is independent of UnsubscribeURL (the human page).
|
||||
UnsubscribePostURL string
|
||||
}
|
||||
|
||||
// Template markers. The CTA cut spans the button row AND the fallback-link
|
||||
// row (both are meaningless without a URL); the note cut spans the optional
|
||||
// note block. Anchors must stay in sync with template.html — Render errors
|
||||
// (and the unit tests fail) if the design drifts away from them.
|
||||
const (
|
||||
ctaStartMarker = "<!-- Button (bulletproof, with Outlook fallback) -->"
|
||||
noteStartMarker = "<!-- Note block"
|
||||
signOffMarker = "<!-- Sign-off -->"
|
||||
bodyStartAnchor = `<p style="margin:0 0 16px 0;">{{body_paragraph_1}}</p>`
|
||||
bodyEndAnchor = `<p style="margin:0;">{{body_paragraph_2}}</p>`
|
||||
addressParagraph = `<p style="margin:0;">Superbrain, {{company_address}}</p>`
|
||||
footerLinkAnchor = "{{preferences_url}}"
|
||||
)
|
||||
|
||||
// Render fills the embedded template for one message. An error means the
|
||||
// template no longer matches the renderer's anchors (a programming error,
|
||||
// caught by tests); callers degrade to plain text rather than block mail.
|
||||
func Render(subject string, c Content) (string, error) {
|
||||
s := emailTemplate
|
||||
var err error
|
||||
|
||||
headline := c.Headline
|
||||
if headline == "" {
|
||||
headline = subject
|
||||
}
|
||||
paras := paragraphs(c.Body)
|
||||
preheader := c.Preheader
|
||||
if preheader == "" && len(paras) > 0 {
|
||||
preheader = paras[0]
|
||||
}
|
||||
if preheader == "" {
|
||||
preheader = headline
|
||||
}
|
||||
preheader = truncateRunes(preheader, 90)
|
||||
|
||||
// Optional CTA: without a URL, drop the button and fallback-link rows.
|
||||
if c.CTAURL == "" {
|
||||
s, err = cutSpan(s, ctaStartMarker, noteStartMarker)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
label := c.CTALabel
|
||||
if label == "" {
|
||||
label = "Open Superbrain"
|
||||
}
|
||||
s = strings.ReplaceAll(s, "{{cta_url}}", html.EscapeString(c.CTAURL))
|
||||
s = strings.ReplaceAll(s, "{{cta_label}}", html.EscapeString(label))
|
||||
}
|
||||
|
||||
// Optional note block.
|
||||
if c.Note == "" {
|
||||
s, err = cutSpan(s, noteStartMarker, signOffMarker)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
s = strings.ReplaceAll(s, "{{note_text}}", html.EscapeString(c.Note))
|
||||
}
|
||||
|
||||
// Greeting: a missing name must not render "Hi ,".
|
||||
greeting := "Hi,"
|
||||
if c.FirstName != "" {
|
||||
greeting = "Hi " + html.EscapeString(c.FirstName) + ","
|
||||
}
|
||||
s = strings.Replace(s, "Hi {{first_name}},", greeting, 1)
|
||||
|
||||
// Body: replace the two placeholder paragraphs with one <p> per line.
|
||||
var b strings.Builder
|
||||
for i, p := range paras {
|
||||
style := "margin:0 0 16px 0;"
|
||||
if i == len(paras)-1 {
|
||||
style = "margin:0;"
|
||||
}
|
||||
if i > 0 {
|
||||
b.WriteString("\n ")
|
||||
}
|
||||
b.WriteString(`<p style="` + style + `">` + html.EscapeString(p) + `</p>`)
|
||||
}
|
||||
s, err = replaceSpan(s, bodyStartAnchor, bodyEndAnchor, b.String())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
signOff := c.SignOff
|
||||
if signOff == "" {
|
||||
signOff = "Thanks,"
|
||||
}
|
||||
s = strings.ReplaceAll(s, "{{sign_off}}", html.EscapeString(signOff))
|
||||
s = strings.ReplaceAll(s, "{{subject}}", html.EscapeString(subject))
|
||||
s = strings.ReplaceAll(s, "{{preheader_text}}", html.EscapeString(preheader))
|
||||
s = strings.ReplaceAll(s, "{{headline}}", html.EscapeString(headline))
|
||||
|
||||
// Footer links: keep only the ones with a URL; drop the whole paragraph
|
||||
// when none are configured (the product has no preference/help pages yet).
|
||||
s, err = renderFooterLinks(s, c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.CompanyAddress == "" {
|
||||
s = strings.Replace(s, addressParagraph, "", 1)
|
||||
} else {
|
||||
s = strings.ReplaceAll(s, "{{company_address}}", html.EscapeString(c.CompanyAddress))
|
||||
}
|
||||
|
||||
if strings.Contains(s, "{{") {
|
||||
return "", errors.New("mailer: template has unfilled placeholders")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func renderFooterLinks(s string, c Content) (string, error) {
|
||||
var links []string
|
||||
for _, l := range []struct{ url, label string }{
|
||||
{c.PreferencesURL, "Email preferences"},
|
||||
{c.UnsubscribeURL, "Unsubscribe"},
|
||||
{c.HelpURL, "Help center"},
|
||||
} {
|
||||
if l.url == "" {
|
||||
continue
|
||||
}
|
||||
links = append(links, `<a href="`+html.EscapeString(l.url)+`" class="t-accent" style="color:#3646E8; text-decoration:underline;">`+l.label+`</a>`)
|
||||
}
|
||||
start, end, err := paragraphSpan(s, footerLinkAnchor)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(links) == 0 {
|
||||
return s[:start] + s[end:], nil
|
||||
}
|
||||
repl := `<p style="margin:0 0 8px 0;">` + strings.Join(links, " | ") + `</p>`
|
||||
return s[:start] + repl + s[end:], nil
|
||||
}
|
||||
|
||||
// paragraphs splits body text into trimmed, non-empty lines.
|
||||
func paragraphs(body string) []string {
|
||||
var out []string
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func truncateRunes(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
return s
|
||||
}
|
||||
return string(r[:n])
|
||||
}
|
||||
|
||||
// cutSpan removes [startMarker, endMarker) — the end marker stays for the
|
||||
// next cut. Both markers must exist.
|
||||
func cutSpan(s, startMarker, endMarker string) (string, error) {
|
||||
i := strings.Index(s, startMarker)
|
||||
if i < 0 {
|
||||
return "", fmt.Errorf("mailer: template marker %q not found", startMarker)
|
||||
}
|
||||
j := strings.Index(s[i:], endMarker)
|
||||
if j < 0 {
|
||||
return "", fmt.Errorf("mailer: template marker %q not found", endMarker)
|
||||
}
|
||||
return s[:i] + s[i+j:], nil
|
||||
}
|
||||
|
||||
// replaceSpan swaps [startAnchor, endAnchor] (inclusive) for repl.
|
||||
func replaceSpan(s, startAnchor, endAnchor, repl string) (string, error) {
|
||||
i := strings.Index(s, startAnchor)
|
||||
if i < 0 {
|
||||
return "", fmt.Errorf("mailer: template anchor %q not found", startAnchor)
|
||||
}
|
||||
j := strings.Index(s[i:], endAnchor)
|
||||
if j < 0 {
|
||||
return "", fmt.Errorf("mailer: template anchor %q not found", endAnchor)
|
||||
}
|
||||
return s[:i] + repl + s[i+j+len(endAnchor):], nil
|
||||
}
|
||||
|
||||
// paragraphSpan locates the <p>…</p> enclosing anchor.
|
||||
func paragraphSpan(s, anchor string) (start, end int, err error) {
|
||||
i := strings.Index(s, anchor)
|
||||
if i < 0 {
|
||||
return 0, 0, fmt.Errorf("mailer: template anchor %q not found", anchor)
|
||||
}
|
||||
start = strings.LastIndex(s[:i], "<p")
|
||||
j := strings.Index(s[i:], "</p>")
|
||||
if start < 0 || j < 0 {
|
||||
return 0, 0, errors.New("mailer: template paragraph around anchor not found")
|
||||
}
|
||||
return start, i + j + len("</p>"), nil
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The renderer and the embedded design file are one unit: these tests pin
|
||||
// the anchors so a template edit that drops a marker fails loudly instead
|
||||
// of silently shipping unfilled placeholders.
|
||||
|
||||
func TestRenderFull(t *testing.T) {
|
||||
html, err := Render("Reset your Superbrain password", Content{
|
||||
Preheader: "Choose a new password.",
|
||||
Headline: "Reset your password",
|
||||
FirstName: "Alice",
|
||||
Body: "First paragraph.\nSecond paragraph.",
|
||||
CTAURL: "https://superbrain.test/reset-password?token=abc",
|
||||
CTALabel: "Choose a new password",
|
||||
Note: "The link expires in 30 minutes.",
|
||||
SignOff: "Cheers,",
|
||||
PreferencesURL: "https://superbrain.test/settings",
|
||||
UnsubscribeURL: "https://superbrain.test/unsubscribe",
|
||||
HelpURL: "https://superbrain.test/help",
|
||||
CompanyAddress: "1 Example Way, Testville",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"Reset your password", "Hi Alice,", "First paragraph.", "Second paragraph.",
|
||||
"Choose a new password", "https://superbrain.test/reset-password?token=abc",
|
||||
"v:roundrect", "If the button doesn't work", // Outlook fallback + plain link
|
||||
"The link expires in 30 minutes.", "Cheers,", "The Superbrain team",
|
||||
"Email preferences", "Unsubscribe", "Help center", "1 Example Way, Testville",
|
||||
"Choose a new password.", // preheader
|
||||
} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("rendered mail missing %q", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(html, "{{") {
|
||||
t.Errorf("unfilled placeholder remains:\n%s", html)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderMinimal(t *testing.T) {
|
||||
html, err := Render("Bookmark due: Due soon", Content{
|
||||
Headline: "Bookmark due: Due soon",
|
||||
Body: "Due soon is due in 6 hours.",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(html, "{{") {
|
||||
t.Errorf("unfilled placeholder remains:\n%s", html)
|
||||
}
|
||||
// Optional sections are removed, not stubbed.
|
||||
for _, absent := range []string{
|
||||
"v:roundrect", "If the button doesn't work", // CTA + fallback rows
|
||||
`<td class="bg-note`, // note block
|
||||
"Email preferences", // footer links paragraph
|
||||
"Superbrain, ", // address line
|
||||
"Hi ,", // broken greeting
|
||||
} {
|
||||
if strings.Contains(html, absent) {
|
||||
t.Errorf("minimal render still contains %q", absent)
|
||||
}
|
||||
}
|
||||
for _, want := range []string{"Hi,", "Bookmark due: Due soon", "Due soon is due in 6 hours.", "Thanks,"} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("minimal render missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderEscaping(t *testing.T) {
|
||||
html, err := Render(`Subject "<x>"`, Content{
|
||||
Headline: `<script>alert(1)</script>`,
|
||||
FirstName: `Ann<script>`,
|
||||
Body: `<img src=x onerror=alert(1)> & "quotes"`,
|
||||
CTAURL: `https://x.test/"onmouseover="alert(1)`,
|
||||
Note: `<b>note</b>`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, absent := range []string{
|
||||
"<script>alert(1)</script>", "Ann<script>", "<img src=x", `"onmouseover="`, "<b>note</b>",
|
||||
} {
|
||||
if strings.Contains(html, absent) {
|
||||
t.Errorf("unescaped value %q survived rendering", absent)
|
||||
}
|
||||
}
|
||||
for _, want := range []string{"<script>", "&", """} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("expected escaped form %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderBodyParagraphs(t *testing.T) {
|
||||
html, err := Render("s", Content{Headline: "h", Body: "one\n\n two \nthree\n"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`<p style="margin:0 0 16px 0;">one</p>`,
|
||||
`<p style="margin:0 0 16px 0;">two</p>`,
|
||||
`<p style="margin:0;">three</p>`, // last paragraph loses the bottom margin
|
||||
} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("missing paragraph %q", want)
|
||||
}
|
||||
}
|
||||
// Empty body: greeting survives, no placeholder paragraphs remain.
|
||||
html, err = Render("s", Content{Headline: "h"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(html, "{{") || !strings.Contains(html, "Hi,") {
|
||||
t.Errorf("empty-body render broken:\n%s", html)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderDefaults(t *testing.T) {
|
||||
html, err := Render("Fallback subject", Content{
|
||||
Body: strings.Repeat("x", 120),
|
||||
CTAURL: "https://superbrain.test/",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(html, "<h1") || !strings.Contains(html, "Fallback subject") {
|
||||
t.Error("headline must fall back to the subject")
|
||||
}
|
||||
if !strings.Contains(html, "Open Superbrain") {
|
||||
t.Error("CTA label must default to Open Superbrain")
|
||||
}
|
||||
// Preheader defaults to the first paragraph, truncated to 90 runes.
|
||||
pre := html[strings.Index(html, `opacity:0;">`)+len(`opacity:0;">`):]
|
||||
pre = strings.TrimSpace(pre[:strings.Index(pre, "͏")])
|
||||
if pre != strings.Repeat("x", 90) {
|
||||
t.Errorf("preheader = %q, want 90 x's", pre)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderTemplateDrift(t *testing.T) {
|
||||
saved := emailTemplate
|
||||
defer func() { emailTemplate = saved }()
|
||||
emailTemplate = "<html>{{headline}} only</html>"
|
||||
if _, err := Render("s", Content{Headline: "h"}); err == nil {
|
||||
t.Fatal("Render must error when the template loses its anchors")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMessagePlain(t *testing.T) {
|
||||
msg := buildMessage("from@x.test", "to@x.test", "hi\r\nBcc: evil@x.test", "body", "", "")
|
||||
if strings.Contains(msg, "\r\nBcc:") {
|
||||
t.Fatal("header injection via subject survived")
|
||||
}
|
||||
if !strings.Contains(msg, "Content-Type: text/plain; charset=UTF-8") {
|
||||
t.Fatal("plain message lost its content type")
|
||||
}
|
||||
if strings.Contains(msg, "multipart") {
|
||||
t.Fatal("plain message must not be multipart")
|
||||
}
|
||||
if strings.Contains(msg, "List-Unsubscribe") {
|
||||
t.Fatal("plain message without an unsubscribe URL must not carry the headers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMessageMultipart(t *testing.T) {
|
||||
text := "plain alternative\nwith a link https://x.test/"
|
||||
html := "<html>\n.dot line\n</html>"
|
||||
msg := buildMessage("from@x.test", "to@x.test", "s", text, html, "")
|
||||
if !strings.Contains(msg, "Content-Type: multipart/alternative; boundary=\"sb-") {
|
||||
t.Fatalf("missing multipart header:\n%s", msg)
|
||||
}
|
||||
boundary := msg[strings.Index(msg, `boundary="`)+len(`boundary="`):]
|
||||
boundary = boundary[:strings.Index(boundary, `"`)]
|
||||
if n := strings.Count(msg, "--"+boundary); n != 3 {
|
||||
t.Fatalf("boundary appears %d times, want 3 (two parts + close)", n)
|
||||
}
|
||||
if !strings.HasSuffix(msg, "--"+boundary+"--\r\n") {
|
||||
t.Fatal("multipart close delimiter missing")
|
||||
}
|
||||
if strings.Index(msg, "text/plain") > strings.Index(msg, "text/html") {
|
||||
t.Fatal("RFC 2046: the plain alternative must come first")
|
||||
}
|
||||
if !strings.Contains(msg, "\r\n..dot line") {
|
||||
t.Fatal("HTML part must be dot-stuffed")
|
||||
}
|
||||
if !strings.Contains(msg, smtpBody(text)) {
|
||||
t.Fatal("plain alternative missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTPBody(t *testing.T) {
|
||||
got := smtpBody(".start\nmid\r\n.dot\n")
|
||||
want := "..start\r\nmid\r\n..dot\r\n"
|
||||
if got != want {
|
||||
t.Fatalf("smtpBody = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMessageListUnsubscribe(t *testing.T) {
|
||||
msg := buildMessage("from@x.test", "to@x.test", "s", "text", "<html></html>",
|
||||
"https://x.test/api/notifications/unsubscribe?token=abc\r\nBcc: evil@x.test")
|
||||
if !strings.Contains(msg, "List-Unsubscribe: <https://x.test/api/notifications/unsubscribe?token=abc") {
|
||||
t.Fatalf("List-Unsubscribe header missing:\n%s", msg)
|
||||
}
|
||||
if !strings.Contains(msg, "List-Unsubscribe-Post: List-Unsubscribe=One-Click\r\n") {
|
||||
t.Fatal("RFC 8058 one-click header missing")
|
||||
}
|
||||
if strings.Contains(msg, "\r\nBcc:") {
|
||||
t.Fatal("header injection via the unsubscribe URL survived")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="x-apple-disable-message-reformatting">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="supported-color-schemes" content="light dark">
|
||||
<title>{{subject}}</title>
|
||||
<!--[if mso]>
|
||||
<noscript><xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml></noscript>
|
||||
<style>td,th,div,p,a,h1,span{font-family:Arial,Helvetica,sans-serif !important;}</style>
|
||||
<![endif]-->
|
||||
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:wght@500;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
body, table, td, a { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
|
||||
table, td { mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
|
||||
img { border: 0; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; }
|
||||
body { margin: 0 !important; padding: 0 !important; width: 100% !important; }
|
||||
a[x-apple-data-detectors] { color: inherit !important; text-decoration: none !important; }
|
||||
|
||||
@media screen and (max-width: 620px) {
|
||||
.container { width: 100% !important; }
|
||||
.px { padding-left: 24px !important; padding-right: 24px !important; }
|
||||
.headline { font-size: 28px !important; line-height: 34px !important; }
|
||||
.btn a { display: block !important; }
|
||||
}
|
||||
|
||||
/* Dark mode (Apple Mail, iOS Mail, Outlook for Mac/iOS, some Android clients) */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.bg-outer { background-color: #0E1024 !important; }
|
||||
.bg-card { background-color: #181B36 !important; }
|
||||
.bg-note { background-color: #22264A !important; }
|
||||
.t-ink { color: #ECEDF8 !important; }
|
||||
.t-muted { color: #A3A7C9 !important; }
|
||||
.t-accent { color: #9AA4FF !important; }
|
||||
.rule { border-color: #2C3060 !important; }
|
||||
}
|
||||
[data-ogsc] .bg-outer { background-color: #0E1024 !important; }
|
||||
[data-ogsc] .bg-card { background-color: #181B36 !important; }
|
||||
[data-ogsc] .bg-note { background-color: #22264A !important; }
|
||||
[data-ogsc] .t-ink { color: #ECEDF8 !important; }
|
||||
[data-ogsc] .t-muted { color: #A3A7C9 !important; }
|
||||
[data-ogsc] .t-accent { color: #9AA4FF !important; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-outer" style="margin:0; padding:0; background-color:#ECEEF6;">
|
||||
|
||||
<!-- Preheader: the preview line shown in the inbox. Keep it under ~90 characters. -->
|
||||
<div style="display:none; max-height:0; overflow:hidden; mso-hide:all; font-size:1px; line-height:1px; color:#ECEEF6; opacity:0;">
|
||||
{{preheader_text}}͏‌ ͏‌ ͏‌ ͏‌ ͏‌
|
||||
</div>
|
||||
|
||||
<table role="presentation" class="bg-outer" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#ECEEF6;">
|
||||
<tr>
|
||||
<td align="center" style="padding:40px 12px;">
|
||||
|
||||
<table role="presentation" class="container" width="600" cellpadding="0" cellspacing="0" border="0" style="width:600px; max-width:600px;">
|
||||
|
||||
<!-- Wordmark -->
|
||||
<tr>
|
||||
<td class="px" style="padding:0 40px 20px 40px;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" border="0">
|
||||
<tr>
|
||||
<td width="14" height="14" style="width:14px; height:14px; background-color:#3646E8; border-radius:7px; font-size:0; line-height:0;"> </td>
|
||||
<td width="6" style="font-size:0;"> </td>
|
||||
<td width="8" height="8" style="width:8px; height:8px; background-color:#9AA4FF; border-radius:4px; font-size:0; line-height:0;"> </td>
|
||||
<td style="padding-left:10px; font-family:'Bricolage Grotesque', Arial, Helvetica, sans-serif; font-size:20px; font-weight:700; letter-spacing:-0.3px; color:#1A1D3A;" class="t-ink">
|
||||
superbrain
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Card -->
|
||||
<tr>
|
||||
<td class="bg-card" style="background-color:#FFFFFF; border-radius:16px; border-top:6px solid #3646E8;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
|
||||
|
||||
<!-- Headline -->
|
||||
<tr>
|
||||
<td class="px" style="padding:44px 48px 12px 48px;">
|
||||
<h1 class="headline t-ink" style="margin:0; font-family:'Bricolage Grotesque', Arial, Helvetica, sans-serif; font-size:34px; line-height:40px; font-weight:700; letter-spacing:-0.8px; color:#1A1D3A;">
|
||||
{{headline}}
|
||||
</h1>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Body -->
|
||||
<tr>
|
||||
<td class="px t-ink" style="padding:12px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:16px; line-height:26px; color:#2E3254;">
|
||||
<p style="margin:0 0 16px 0;">Hi {{first_name}},</p>
|
||||
<p style="margin:0 0 16px 0;">{{body_paragraph_1}}</p>
|
||||
<p style="margin:0;">{{body_paragraph_2}}</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Button (bulletproof, with Outlook fallback) -->
|
||||
<tr>
|
||||
<td class="px btn" style="padding:32px 48px 8px 48px;">
|
||||
<!--[if mso]>
|
||||
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" href="{{cta_url}}" style="height:50px; v-text-anchor:middle; width:240px;" arcsize="20%" stroke="f" fillcolor="#3646E8">
|
||||
<w:anchorlock/>
|
||||
<center style="color:#ffffff; font-family:Arial,sans-serif; font-size:16px; font-weight:bold;">{{cta_label}}</center>
|
||||
</v:roundrect>
|
||||
<![endif]-->
|
||||
<!--[if !mso]><!-->
|
||||
<a href="{{cta_url}}" style="display:inline-block; background-color:#3646E8; color:#FFFFFF; font-family:Arial, Helvetica, sans-serif; font-size:16px; font-weight:700; line-height:50px; text-align:center; text-decoration:none; padding:0 32px; border-radius:10px;">
|
||||
{{cta_label}}
|
||||
</a>
|
||||
<!--<![endif]-->
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Fallback link -->
|
||||
<tr>
|
||||
<td class="px t-muted" style="padding:12px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:13px; line-height:20px; color:#6A6F92;">
|
||||
If the button doesn't work, paste this link into your browser:<br>
|
||||
<a href="{{cta_url}}" class="t-accent" style="color:#3646E8; word-break:break-all;">{{cta_url}}</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Note block (optional — delete this row if not needed) -->
|
||||
<tr>
|
||||
<td class="px" style="padding:32px 48px 0 48px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
|
||||
<tr>
|
||||
<td class="bg-note t-ink" style="background-color:#EEF0FF; border-radius:10px; padding:18px 20px; font-family:Arial, Helvetica, sans-serif; font-size:14px; line-height:22px; color:#2E3254;">
|
||||
{{note_text}}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Sign-off -->
|
||||
<tr>
|
||||
<td class="px t-ink" style="padding:32px 48px 44px 48px; font-family:Arial, Helvetica, sans-serif; font-size:16px; line-height:26px; color:#2E3254;">
|
||||
{{sign_off}}<br>
|
||||
The Superbrain team
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Footer -->
|
||||
<tr>
|
||||
<td class="px t-muted" style="padding:28px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:19px; color:#6A6F92;">
|
||||
<p style="margin:0 0 8px 0;">You're receiving this email because you have a Superbrain account.</p>
|
||||
<p style="margin:0 0 8px 0;">
|
||||
<a href="{{preferences_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Email preferences</a>
|
||||
|
|
||||
<a href="{{unsubscribe_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Unsubscribe</a>
|
||||
|
|
||||
<a href="{{help_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Help center</a>
|
||||
</p>
|
||||
<p style="margin:0;">Superbrain, {{company_address}}</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -91,7 +91,7 @@ func httpClient(conn Conn) *http.Client {
|
||||
// ListTools connects, initializes and lists the server's tools, then closes
|
||||
// the session. The context bounds the whole exchange.
|
||||
func ListTools(ctx context.Context, conn Conn) ([]Tool, error) {
|
||||
client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "superbrain", Version: "1.2.7"}, nil)
|
||||
client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "superbrain", Version: "0.3.1"}, nil)
|
||||
var transport mcpsdk.Transport
|
||||
hc := httpClient(conn)
|
||||
switch conn.Transport {
|
||||
|
||||
@@ -24,6 +24,12 @@ type User struct {
|
||||
TenantID *string
|
||||
CreatedAt string
|
||||
UpdatedAt string
|
||||
// Profile particulars (Settings → Profile, migration 024).
|
||||
Bio *string
|
||||
Location *string
|
||||
Occupation *string
|
||||
Organization *string
|
||||
Website *string
|
||||
}
|
||||
|
||||
// Account, Session, VerificationToken are auth-library tables. Porting guide 2.3.
|
||||
|
||||
@@ -255,7 +255,9 @@ func Send(ctx context.Context, d *db.DB, ch Channel, title, body string) error {
|
||||
}
|
||||
to = *email
|
||||
}
|
||||
return mailer.Send(ctx, to, title, text)
|
||||
c := FooterLinks(ctx, d, ch.OwnerID, to)
|
||||
c.Headline, c.Body = title, body
|
||||
return mailer.SendTemplate(ctx, to, title, text, c)
|
||||
case "slack":
|
||||
return postJSON(ctx, ch.Config["webhookUrl"], nil, map[string]any{"text": text}, []int{200})
|
||||
case "matrix":
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package notify
|
||||
|
||||
// Email footer links and the unsubscribe token. The token is a stable,
|
||||
// HMAC-signed user id (no stored row, no expiry): every notification mail
|
||||
// carries the same link, and rotating AUTH_SECRET invalidates outstanding
|
||||
// links exactly like sessions. Unsubscribe is a NOTIFICATION preference —
|
||||
// transactional mail (password reset) is never gated by it.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/mailer"
|
||||
)
|
||||
|
||||
// unsubscribeDomain separates these MACs from every other use of the
|
||||
// signing secret (assertions, forwarded-IP attestation, ...).
|
||||
const unsubscribeDomain = "superbrain-unsubscribe:"
|
||||
|
||||
// UnsubscribeToken returns the signed unsubscribe token for a user. IDs
|
||||
// are 32-char hex (db.NewID), so the single "." separator is unambiguous.
|
||||
func UnsubscribeToken(userID string) string {
|
||||
mac := hmac.New(sha256.New, []byte(config.Load().Secret()))
|
||||
mac.Write([]byte(unsubscribeDomain + userID))
|
||||
return userID + "." + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// ParseUnsubscribeToken validates a token and returns the user id it
|
||||
// carries. The comparison is constant-time; a tampered or foreign-secret
|
||||
// token never resolves an identity.
|
||||
func ParseUnsubscribeToken(token string) (string, bool) {
|
||||
userID, sig, ok := strings.Cut(token, ".")
|
||||
if !ok || userID == "" || sig == "" {
|
||||
return "", false
|
||||
}
|
||||
mac := hmac.New(sha256.New, []byte(config.Load().Secret()))
|
||||
mac.Write([]byte(unsubscribeDomain + userID))
|
||||
want := hex.EncodeToString(mac.Sum(nil))
|
||||
if !hmac.Equal([]byte(want), []byte(sig)) {
|
||||
return "", false
|
||||
}
|
||||
return userID, true
|
||||
}
|
||||
|
||||
// FooterLinks builds the branded email footer for a message to recipient.
|
||||
// Preferences and Help are offered whenever the deployment has a public
|
||||
// origin (NEXTAUTH_URL). Unsubscribe is offered ONLY when recipient is the
|
||||
// owner's own account email: a third-party recipient (a channel address or
|
||||
// an agent task's To) must never receive a link that changes the owner's
|
||||
// settings. With no origin configured every link stays empty and the
|
||||
// renderer omits the footer sections.
|
||||
func FooterLinks(ctx context.Context, d *db.DB, ownerID, recipient string) mailer.Content {
|
||||
var c mailer.Content
|
||||
base := strings.TrimRight(strings.TrimSpace(config.Load().NextAuthURL), "/")
|
||||
if base == "" {
|
||||
return c
|
||||
}
|
||||
c.PreferencesURL = base + "/settings?tab=notifications"
|
||||
c.HelpURL = base + "/help"
|
||||
var email *string
|
||||
if err := d.QueryRowContext(ctx, `SELECT email FROM "User" WHERE id=$1`, ownerID).Scan(&email); err != nil {
|
||||
return c
|
||||
}
|
||||
if email == nil || *email == "" || !strings.EqualFold(strings.TrimSpace(recipient), *email) {
|
||||
return c
|
||||
}
|
||||
token := UnsubscribeToken(ownerID)
|
||||
c.UnsubscribeURL = base + "/unsubscribe?token=" + token
|
||||
c.UnsubscribePostURL = base + "/api/notifications/unsubscribe?token=" + token
|
||||
return c
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUnsubscribeTokenRoundtrip(t *testing.T) {
|
||||
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
|
||||
tok := UnsubscribeToken("0123456789abcdef0123456789abcdef")
|
||||
id, ok := ParseUnsubscribeToken(tok)
|
||||
if !ok || id != "0123456789abcdef0123456789abcdef" {
|
||||
t.Fatalf("roundtrip = %q, %v", id, ok)
|
||||
}
|
||||
// Stable: every mail to the same user carries the same link.
|
||||
if UnsubscribeToken("0123456789abcdef0123456789abcdef") != tok {
|
||||
t.Fatal("token must be stable across issuances")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsubscribeTokenRejectsTampering(t *testing.T) {
|
||||
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
|
||||
const id = "0123456789abcdef0123456789abcdef"
|
||||
tok := UnsubscribeToken(id)
|
||||
_, mac, _ := strings.Cut(tok, ".")
|
||||
|
||||
// A token minted under a different secret must not verify here.
|
||||
t.Setenv("AUTH_SECRET", "a-different-secret")
|
||||
foreign := UnsubscribeToken(id)
|
||||
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
|
||||
|
||||
cases := []struct{ name, token string }{
|
||||
{"swapped id", "ffffffffffffffffffffffffffffffff." + mac},
|
||||
{"flipped mac", id + "." + strings.Repeat("0", 63) + "1"},
|
||||
{"truncated mac", tok[:len(tok)-1]},
|
||||
{"no separator", strings.ReplaceAll(tok, ".", "")},
|
||||
{"empty id", "." + mac},
|
||||
{"empty mac", id + "."},
|
||||
{"empty token", ""},
|
||||
{"foreign secret", foreign},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if _, ok := ParseUnsubscribeToken(c.token); ok {
|
||||
t.Errorf("%s accepted", c.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ name = "superbrain-mcp"
|
||||
# Versioned in lockstep with the Superbrain release it speaks to (house
|
||||
# tooling tracks one version per app); the federated mcpserver gateway
|
||||
# installs this package and spawns `superbrain-mcp` per linked instance.
|
||||
version = "1.2.13"
|
||||
version = "0.3.1"
|
||||
description = "MCP server for Superbrain — bookmarks, tags and pages over the Superbrain REST API"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""Superbrain MCP server — bookmarks, tags and pages for AI tooling."""
|
||||
|
||||
__version__ = "1.2.13"
|
||||
__version__ = "0.3.1"
|
||||
|
||||
+7
-2
@@ -127,11 +127,16 @@ try {
|
||||
await publicContext.close()
|
||||
await page.goto(`${base}/kanban`)
|
||||
await page.getByRole('heading', { name: 'Kanban Board' }).waitFor()
|
||||
await page.getByText('Browser QA bookmark', { exact: true }).waitFor()
|
||||
// Only explicitly-placed cards appear: a fresh bookmark is NOT auto-populated.
|
||||
assert.equal(await page.getByText('Browser QA bookmark', { exact: true }).count(), 0, 'kanban must not auto-populate unplaced bookmarks')
|
||||
const columns = await json(await context.request.get(`${base}/api/kanban/columns`))
|
||||
assert.equal(columns.length, 4)
|
||||
// Place it explicitly; now it appears on the board.
|
||||
const placed = await json(await context.request.put(`${base}/api/kanban/cards/${bookmark.id}`, { data: { columnId: columns[0].id, position: 0, version: update.version } }))
|
||||
await page.reload()
|
||||
await page.getByText('Browser QA bookmark', { exact: true }).waitFor()
|
||||
const custom = await json(await context.request.post(`${base}/api/kanban/columns`, { data: { label: 'QA done' } }), 201)
|
||||
await json(await context.request.put(`${base}/api/kanban/cards/${bookmark.id}`, { data: { columnId: custom.id, position: 0, version: update.version } }))
|
||||
await json(await context.request.put(`${base}/api/kanban/cards/${bookmark.id}`, { data: { columnId: custom.id, position: 0, version: placed.version } }))
|
||||
const moved = await json(await context.request.delete(`${base}/api/kanban/columns/${custom.id}`))
|
||||
assert.equal(moved.moved, 1)
|
||||
await page.goto(`${base}/pages`)
|
||||
|
||||
+55
-8
@@ -70,6 +70,12 @@ const carddavConnections = [{
|
||||
lastSyncedAt: null, lastError: null, version: 1, createdAt: '2026-11-10T00:00:00Z', updatedAt: '2026-11-10T00:00:00Z',
|
||||
}]
|
||||
const carddavSuggestions = [{ kind: 'nextcloud', name: 'Nextcloud contacts', url: 'https://cloud.federatedcomputer.ai/remote.php/dav/addressbooks/users/' }]
|
||||
// The identity is mutable: Settings → Profile PATCHes it, and the NextAuth
|
||||
// jwt "update" trigger re-reads it from /api/me (session name refresh).
|
||||
const fixtureUser = {
|
||||
id: 'fixture-user', name: 'Fixture', email: 'fixture@superbrain.test', role: 'USER', image: null,
|
||||
bio: null, location: null, occupation: null, organization: null, website: null,
|
||||
}
|
||||
const api = http.createServer(async (req, res) => {
|
||||
try {
|
||||
let raw = ''
|
||||
@@ -86,13 +92,24 @@ const api = http.createServer(async (req, res) => {
|
||||
const body = raw ? JSON.parse(raw) : {}
|
||||
const url = new URL(req.url, 'http://fixture')
|
||||
let result = []
|
||||
if (url.pathname === '/api/auth/login') result = { user: { id: 'fixture-user', name: 'Fixture', email: body.email, role: 'USER' }, tokenVersion: 1 }
|
||||
if (url.pathname === '/api/auth/login') result = { user: { ...fixtureUser, email: body.email }, tokenVersion: 1 }
|
||||
else if (url.pathname === '/api/auth/signout' && req.method === 'POST') {
|
||||
signouts.push(req.headers.authorization || '')
|
||||
if (failSignout) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end('{"error":"Fixture revocation failed"}'); return }
|
||||
result = { ok: true }
|
||||
}
|
||||
else if (url.pathname === '/api/me') result = { user: { id: 'fixture-user' }, effectiveUser: { id: 'fixture-user' }, isAdmin: false, viewingAs: null }
|
||||
else if (url.pathname === '/api/me') {
|
||||
if (req.method === 'PATCH') {
|
||||
// Mirror Go's allowlist + empty-string-clears semantics; the answer
|
||||
// is the flat user projection (same shape as GET /api/me's "user").
|
||||
for (const k of ['name', 'bio', 'location', 'occupation', 'organization', 'website']) {
|
||||
if (k in body) fixtureUser[k] = body[k] === '' ? null : body[k]
|
||||
}
|
||||
result = fixtureUser
|
||||
} else {
|
||||
result = { user: fixtureUser, effectiveUser: { id: fixtureUser.id, name: fixtureUser.name, email: fixtureUser.email, role: fixtureUser.role }, isAdmin: false, viewingAs: null }
|
||||
}
|
||||
}
|
||||
// The list endpoint is a metadata projection: content bodies stay out (PERF-01).
|
||||
else if (url.pathname === '/api/pages') {
|
||||
if (req.method === 'PUT') {
|
||||
@@ -680,8 +697,38 @@ try {
|
||||
await eventually(() => pages.get('a')?.position === 0 && pages.get('b')?.position === 1, 'Sidebar page drag did not reorder')
|
||||
console.log('PASS: sidebar persists drag reordering')
|
||||
|
||||
// Settings → Profile: particulars load from /api/me, the save PATCHes the
|
||||
// allowlist, and the NextAuth session re-syncs from Go (jwt update trigger)
|
||||
// so the top bar shows the new name without a re-login.
|
||||
await page.goto(`${base}/settings`)
|
||||
await page.getByRole('tab', { name: 'Profile' }).click()
|
||||
await page.getByPlaceholder('Your name').waitFor()
|
||||
assert.equal(await page.getByPlaceholder('Your name').inputValue(), 'Fixture')
|
||||
await page.getByPlaceholder('Your name').fill('Fixture Person')
|
||||
await page.getByPlaceholder('A short introduction').fill('Keeper of the second brain')
|
||||
await page.getByPlaceholder('City, country').fill('Berlin, Germany')
|
||||
await page.getByPlaceholder('Job title').fill('Knowledge worker')
|
||||
await page.getByPlaceholder('Company or team').fill('Federated Computer')
|
||||
await page.getByPlaceholder('https://example.com').fill('https://federatedcomputer.ai')
|
||||
await page.getByRole('button', { name: 'Save profile' }).click()
|
||||
await eventually(() => fixtureUser.name === 'Fixture Person' && fixtureUser.website === 'https://federatedcomputer.ai', 'Profile save PATCH did not reach the API')
|
||||
await page.getByText('Profile saved').waitFor()
|
||||
// The save response is the flat projection: the form keeps the values.
|
||||
assert.equal(await page.getByPlaceholder('Your name').inputValue(), 'Fixture Person')
|
||||
assert.equal(await page.getByPlaceholder('https://example.com').inputValue(), 'https://federatedcomputer.ai')
|
||||
assert.equal(fixtureUser.bio, 'Keeper of the second brain')
|
||||
assert.equal(fixtureUser.location, 'Berlin, Germany')
|
||||
assert.equal(fixtureUser.occupation, 'Knowledge worker')
|
||||
assert.equal(fixtureUser.organization, 'Federated Computer')
|
||||
// The top bar (header) reflects the refreshed session identity.
|
||||
await eventually(() => page.locator('header').getByText('Fixture Person', { exact: true }).isVisible(), 'top bar did not refresh the session name after the profile save')
|
||||
// Clean baseline: the save button disables again until the next edit.
|
||||
assert.ok(await page.getByRole('button', { name: 'Save profile' }).isDisabled(), 'Save stayed enabled after a clean save')
|
||||
console.log('PASS: Settings → Profile saves particulars and refreshes the session identity')
|
||||
|
||||
// Settings → WebDAV: masked list rows render; the deployment suggestion
|
||||
// (NEXTCLOUD_URL) prefills the connect form with the viewer's username;
|
||||
// (NEXTCLOUD_URL) prefills the connect form with the username composed into
|
||||
// the per-user DAV root;
|
||||
// save POSTs the form; Sync/Test surface the server's verbatim results.
|
||||
await page.goto(`${base}/settings`)
|
||||
await page.getByRole('tab', { name: 'WebDAV' }).click()
|
||||
@@ -690,13 +737,13 @@ try {
|
||||
await page.getByText('Nextcloud files detected on this server').waitFor()
|
||||
await page.getByRole('button', { name: 'Use', exact: true }).click()
|
||||
const suggestUrl = page.getByPlaceholder('https://cloud.example.com/remote.php/dav/files/username/Documents')
|
||||
assert.equal(await suggestUrl.inputValue(), 'https://cloud.federatedcomputer.ai/remote.php/dav/files/')
|
||||
assert.equal(await suggestUrl.inputValue(), 'https://cloud.federatedcomputer.ai/remote.php/dav/files/fixture/')
|
||||
assert.equal(await page.getByPlaceholder('erwin').inputValue(), 'fixture') // session email local-part
|
||||
await page.getByPlaceholder('erwin').fill('erwin')
|
||||
await page.getByPlaceholder('Account or app password').fill('app-secret')
|
||||
await page.locator('[role="dialog"]').getByRole('button', { name: 'Connect share' }).click()
|
||||
await eventually(() => webdavConnections.length === 2, 'WebDAV connect POST did not reach the API')
|
||||
assert.equal(lastWebdavCreate.url, 'https://cloud.federatedcomputer.ai/remote.php/dav/files/')
|
||||
assert.equal(lastWebdavCreate.url, 'https://cloud.federatedcomputer.ai/remote.php/dav/files/fixture/')
|
||||
assert.equal(lastWebdavCreate.username, 'erwin')
|
||||
assert.equal(lastWebdavCreate.password, 'app-secret')
|
||||
await page.getByRole('button', { name: 'Sync House docs' }).click()
|
||||
@@ -716,13 +763,13 @@ try {
|
||||
await page.getByText('Nextcloud calendars detected on this server').waitFor()
|
||||
await page.getByRole('button', { name: 'Use', exact: true }).click()
|
||||
const calSuggestUrl = page.getByPlaceholder('https://cloud.example.com/remote.php/dav/calendars/username')
|
||||
assert.equal(await calSuggestUrl.inputValue(), 'https://cloud.federatedcomputer.ai/remote.php/dav/calendars/')
|
||||
assert.equal(await calSuggestUrl.inputValue(), 'https://cloud.federatedcomputer.ai/remote.php/dav/calendars/fixture/')
|
||||
assert.equal(await page.getByPlaceholder('erwin').inputValue(), 'fixture')
|
||||
await page.getByPlaceholder('erwin').fill('erwin')
|
||||
await page.getByPlaceholder('Account or app password').fill('cal-app-secret')
|
||||
await page.locator('[role="dialog"]').getByRole('button', { name: 'Connect calendar' }).click()
|
||||
await eventually(() => caldavConnections.length === 2, 'CalDAV connect POST did not reach the API')
|
||||
assert.equal(lastCaldavCreate.url, 'https://cloud.federatedcomputer.ai/remote.php/dav/calendars/')
|
||||
assert.equal(lastCaldavCreate.url, 'https://cloud.federatedcomputer.ai/remote.php/dav/calendars/fixture/')
|
||||
assert.equal(lastCaldavCreate.username, 'erwin')
|
||||
assert.equal(lastCaldavCreate.password, 'cal-app-secret')
|
||||
await page.getByRole('button', { name: 'Sync My calendars' }).click()
|
||||
@@ -827,7 +874,7 @@ try {
|
||||
await noOverflow(path)
|
||||
}
|
||||
await mobileContext.close()
|
||||
console.log('PASS: mobile shell — drawer nav, bookmark cards, master-detail rails, scrollable settings tabs, no horizontal overflow on any screen')
|
||||
console.log('PASS: mobile shell — drawer nav, bookmark cards, master-detail rails, grouped settings nav, no horizontal overflow on any screen')
|
||||
|
||||
// Revocation failure path (review CR-02): when Go's revocation fails, the
|
||||
// local sign-out still completes, but the UI must say so — local cookie
|
||||
|
||||
@@ -4,13 +4,122 @@ import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
|
||||
import { ExternalLink, Search, Trash2, ChevronUp, ChevronDown, Inbox, Share2 } from 'lucide-react'
|
||||
import { format } from 'date-fns'
|
||||
import { toast } from 'sonner'
|
||||
import type { Bookmark } from '@/components/app-shell'
|
||||
import { fetchBookmarks } from '@/lib/bookmarks'
|
||||
import { useIsMobile } from '@/lib/use-media-query'
|
||||
|
||||
type GroupBy = 'none' | 'calendar' | 'tags' | 'kanban' | 'collections' | 'contacts'
|
||||
|
||||
const GROUP_OPTIONS: { value: GroupBy; label: string }[] = [
|
||||
{ value: 'none', label: 'None' },
|
||||
{ value: 'calendar', label: 'Calendar' },
|
||||
{ value: 'tags', label: 'Tags' },
|
||||
{ value: 'kanban', label: 'Kanban' },
|
||||
{ value: 'collections', label: 'Collections' },
|
||||
{ value: 'contacts', label: 'Contacts' },
|
||||
]
|
||||
|
||||
type BookmarkGroup = { key: string; label: string; color?: string | null; items: Bookmark[] }
|
||||
|
||||
// Legacy board statuses in board order (see superbrain_porting_guide.md);
|
||||
// unknown/custom statuses follow alphabetically, empty status lands last.
|
||||
const KANBAN_ORDER = ['INBOX', 'TODO', 'IN_PROGRESS', 'DONE', 'ARCHIVED']
|
||||
const KANBAN_LABELS: Record<string, string> = { INBOX: 'Inbox', TODO: 'To Do', IN_PROGRESS: 'In Progress', DONE: 'Done', ARCHIVED: 'Archived' }
|
||||
|
||||
function humanizeStatus(status: string) {
|
||||
return KANBAN_LABELS[status] ?? status.split('_').filter(Boolean).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ')
|
||||
}
|
||||
|
||||
// Month key taken straight from the stored ISO string so a date-only dueDate
|
||||
// never shifts across a timezone boundary (same slice discipline as the
|
||||
// calendar screen). Non-ISO values fall back to UTC components.
|
||||
function dueMonthKey(dueDate: string | null): string | null {
|
||||
if (!dueDate) return null
|
||||
const m = /^(\d{4})-(\d{2})/.exec(dueDate)
|
||||
if (m) return `${m[1]}-${m[2]}`
|
||||
const d = new Date(dueDate)
|
||||
if (Number.isNaN(d.getTime())) return null
|
||||
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
// Built from explicit local components so server and client produce the same
|
||||
// label in any runtime timezone (date-fns format, no bare locale calls).
|
||||
function monthLabel(key: string) {
|
||||
return format(new Date(Number(key.slice(0, 4)), Number(key.slice(5, 7)) - 1, 1), 'MMMM yyyy')
|
||||
}
|
||||
|
||||
// Rows arrive already filtered and sorted; pushing them in order keeps the
|
||||
// active sort inside every group. The fallback bucket always renders last.
|
||||
function groupBookmarks(rows: Bookmark[], mode: GroupBy, collectionNames: Map<string, string[]> | null): BookmarkGroup[] {
|
||||
const groups = new Map<string, BookmarkGroup>()
|
||||
const fallback: Bookmark[] = []
|
||||
const add = (key: string, label: string, b: Bookmark, color?: string | null) => {
|
||||
const existing = groups.get(key)
|
||||
if (existing) existing.items.push(b)
|
||||
else groups.set(key, { key, label, color, items: [b] })
|
||||
}
|
||||
const byLabel = (a: BookmarkGroup, b: BookmarkGroup) => a.label.localeCompare(b.label)
|
||||
const finish = (ordered: BookmarkGroup[], fallbackLabel: string) => {
|
||||
if (fallback.length) ordered.push({ key: '__none__', label: fallbackLabel, items: fallback })
|
||||
return ordered
|
||||
}
|
||||
switch (mode) {
|
||||
case 'calendar': {
|
||||
for (const b of rows) {
|
||||
const key = dueMonthKey(b.dueDate)
|
||||
if (key) add(key, monthLabel(key), b)
|
||||
else fallback.push(b)
|
||||
}
|
||||
return finish([...groups.values()].sort((a, b) => a.key.localeCompare(b.key)), 'No due date')
|
||||
}
|
||||
case 'tags': {
|
||||
for (const b of rows) {
|
||||
const seen = new Set<string>()
|
||||
for (const bt of b.tags ?? []) {
|
||||
const tag = bt?.tag
|
||||
if (!tag?.id || seen.has(tag.id)) continue
|
||||
seen.add(tag.id)
|
||||
add(`tag:${tag.id}`, tag.name || 'Unnamed tag', b, tag.color)
|
||||
}
|
||||
if (seen.size === 0) fallback.push(b)
|
||||
}
|
||||
return finish([...groups.values()].sort(byLabel), 'Untagged')
|
||||
}
|
||||
case 'kanban': {
|
||||
for (const b of rows) {
|
||||
const status = b.kanbanStatus || ''
|
||||
if (status) add(status, humanizeStatus(status), b)
|
||||
else fallback.push(b)
|
||||
}
|
||||
const rank = (key: string) => { const i = KANBAN_ORDER.indexOf(key); return i === -1 ? KANBAN_ORDER.length : i }
|
||||
return finish([...groups.values()].sort((a, b) => rank(a.key) - rank(b.key) || byLabel(a, b)), 'No status')
|
||||
}
|
||||
case 'contacts': {
|
||||
for (const b of rows) {
|
||||
const name = b.contact?.displayName
|
||||
if (name) add(`contact:${name}`, name, b)
|
||||
else fallback.push(b)
|
||||
}
|
||||
return finish([...groups.values()].sort(byLabel), 'No contact')
|
||||
}
|
||||
case 'collections': {
|
||||
for (const b of rows) {
|
||||
const names = collectionNames?.get(b.id) ?? []
|
||||
for (const name of names) add(`collection:${name}`, name, b)
|
||||
if (names.length === 0) fallback.push(b)
|
||||
}
|
||||
return finish([...groups.values()].sort(byLabel), 'Not in a collection')
|
||||
}
|
||||
default:
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function BookmarksClient({ initialSearch = null, initialOpen = null }: { initialSearch?: string | null; initialOpen?: string | null }) {
|
||||
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
|
||||
const [sharedBookmarks, setSharedBookmarks] = useState<Bookmark[]>([])
|
||||
@@ -33,6 +142,11 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
|
||||
const [sortField, setSortField] = useState<'title' | 'updatedAt' | 'kanbanStatus'>('updatedAt')
|
||||
const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')
|
||||
const isMobile = useIsMobile()
|
||||
const [groupBy, setGroupBy] = useState<GroupBy>('none')
|
||||
// Collections grouping needs membership data the bookmark rows don't carry.
|
||||
// Fetch it once on first selection and cache it for the screen's lifetime.
|
||||
const [collectionNames, setCollectionNames] = useState<Map<string, string[]> | null>(null)
|
||||
const [collectionsState, setCollectionsState] = useState<'idle' | 'loading' | 'ready' | 'error'>('idle')
|
||||
|
||||
// Debounced, abortable, sequence-guarded load: a slow response for an older
|
||||
// query can never overwrite newer results (same discipline as pages client).
|
||||
@@ -90,6 +204,47 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
|
||||
return () => clearTimeout(timer)
|
||||
}, [initialOpen])
|
||||
|
||||
// Review M-11 discipline: a retry superseded by a newer pass may not publish
|
||||
// its result. Membership is bounded to the first 200 items per collection.
|
||||
const collectionsSeq = useRef(0)
|
||||
const loadCollectionMemberships = useCallback(async () => {
|
||||
const seq = ++collectionsSeq.current
|
||||
setCollectionsState('loading')
|
||||
try {
|
||||
const res = await fetch('/api/collections')
|
||||
if (!res.ok) throw new Error('Could not load collections')
|
||||
const collections: { id: string; name: string }[] = await res.json()
|
||||
const memberships = await Promise.all(collections.map(async (c) => {
|
||||
const itemsRes = await fetch(`/api/collections/${encodeURIComponent(c.id)}/items?limit=200`)
|
||||
if (!itemsRes.ok) throw new Error('Could not load collection items')
|
||||
const items: { bookmarkId?: string; bookmark?: { id?: string } | null }[] = await itemsRes.json()
|
||||
return { name: c.name, ids: items.map(i => i?.bookmark?.id ?? i?.bookmarkId).filter((id): id is string => !!id) }
|
||||
}))
|
||||
if (seq !== collectionsSeq.current) return
|
||||
const map = new Map<string, string[]>()
|
||||
for (const { name, ids } of memberships) {
|
||||
for (const id of ids) {
|
||||
const names = map.get(id) ?? []
|
||||
if (!names.includes(name)) names.push(name)
|
||||
map.set(id, names)
|
||||
}
|
||||
}
|
||||
setCollectionNames(map)
|
||||
setCollectionsState('ready')
|
||||
} catch {
|
||||
if (seq !== collectionsSeq.current) return
|
||||
setCollectionsState('error')
|
||||
toast.error('Could not load collections')
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (groupBy === 'collections' && collectionsState === 'idle') {
|
||||
const t = setTimeout(() => void loadCollectionMemberships(), 0)
|
||||
return () => clearTimeout(t)
|
||||
}
|
||||
}, [groupBy, collectionsState, loadCollectionMemberships])
|
||||
|
||||
const displayBookmarks = tab === 'mine' ? bookmarks : sharedBookmarks
|
||||
const sorted = [...(displayBookmarks ?? [])].sort((a: any, b: any) => {
|
||||
const va = a?.[sortField] ?? ''
|
||||
@@ -97,6 +252,10 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
|
||||
return sortDir === 'asc' ? String(va).localeCompare(String(vb)) : String(vb).localeCompare(String(va))
|
||||
})
|
||||
|
||||
// Grouping operates on the already-filtered, already-sorted list, so search,
|
||||
// the mine/shared tab and the active sort all apply within each group.
|
||||
const groups = groupBy === 'none' ? [] : groupBookmarks(sorted, groupBy, collectionNames)
|
||||
|
||||
const toggleSort = (field: typeof sortField) => {
|
||||
if (sortField === field) setSortDir(d => d === 'asc' ? 'desc' : 'asc')
|
||||
else { setSortField(field); setSortDir('asc') }
|
||||
@@ -115,13 +274,146 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
|
||||
return sortDir === 'asc' ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />
|
||||
}
|
||||
|
||||
// Shared row/card/table renderers: the flat list and every grouped section
|
||||
// render the exact same markup, so selection, keyboard access, trash and
|
||||
// external-link actions stay identical in both modes.
|
||||
const renderRow = (b: Bookmark) => (
|
||||
<tr key={b.id} tabIndex={0} className="hover:bg-muted/30 cursor-pointer focus-visible:outline-2 focus-visible:outline-primary" onClick={() => setSelected(b)} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelected(b) } }}>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{b.favicon && <img src={b.favicon} alt="" referrerPolicy="no-referrer" className="h-4 w-4 rounded" onError={(e: any) => { e.target.style.display = 'none' }} />}
|
||||
<span className="truncate max-w-[200px]">{b.title ?? 'Untitled'}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<a href={b.url} target="_blank" rel="noopener noreferrer" onClick={(e: React.MouseEvent) => e.stopPropagation()} className="text-primary hover:underline truncate max-w-[200px] block">
|
||||
{(() => { try { return new URL(b.url).hostname } catch { return b.url } })()}
|
||||
</a>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex gap-1">
|
||||
{(b.tags ?? []).slice(0, 2).map((bt: any) => (
|
||||
<Badge key={bt?.tag?.id} variant="secondary" className="text-[10px] px-1.5 py-0" style={{ backgroundColor: `${bt?.tag?.color}20`, color: bt?.tag?.color }}>{bt?.tag?.name}</Badge>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3"><Badge variant="outline" className="text-[10px]">{b.kanbanStatus?.replace('_', ' ')}</Badge></td>
|
||||
<td className="px-4 py-3 text-xs text-muted-foreground">{new Date(b.updatedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })}</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex gap-1" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
|
||||
<a href={b.url} target="_blank" rel="noopener noreferrer"><ExternalLink className="h-4 w-4 text-muted-foreground hover:text-primary" /></a>
|
||||
{tab === 'mine' && (
|
||||
<button onClick={() => trashBookmark(b)} aria-label="Move to trash"><Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" /></button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
|
||||
const renderCard = (b: Bookmark) => (
|
||||
<div
|
||||
key={b.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className="rounded-lg border bg-card p-3 cursor-pointer transition-colors hover:bg-muted/30 focus-visible:outline-2 focus-visible:outline-primary"
|
||||
onClick={() => setSelected(b)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelected(b) } }}
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
{b.favicon && <img src={b.favicon} alt="" referrerPolicy="no-referrer" className="mt-0.5 h-4 w-4 shrink-0 rounded" onError={(e: any) => { e.target.style.display = 'none' }} />}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{b.title ?? 'Untitled'}</p>
|
||||
<a href={b.url} target="_blank" rel="noopener noreferrer" onClick={(e: React.MouseEvent) => e.stopPropagation()} className="block truncate text-xs text-primary hover:underline">
|
||||
{(() => { try { return new URL(b.url).hostname } catch { return b.url } })()}
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
|
||||
<a href={b.url} target="_blank" rel="noopener noreferrer" aria-label="Open link"><ExternalLink className="h-4 w-4 text-muted-foreground hover:text-primary" /></a>
|
||||
{tab === 'mine' && (
|
||||
<button onClick={() => trashBookmark(b)} aria-label="Move to trash"><Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" /></button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
<Badge variant="outline" className="text-[10px]">{b.kanbanStatus?.replace('_', ' ')}</Badge>
|
||||
{(b.tags ?? []).slice(0, 3).map((bt: any) => (
|
||||
<Badge key={bt?.tag?.id} variant="secondary" className="text-[10px] px-1.5 py-0" style={{ backgroundColor: `${bt?.tag?.color}20`, color: bt?.tag?.color }}>{bt?.tag?.name}</Badge>
|
||||
))}
|
||||
<span className="ml-auto text-[10px] text-muted-foreground">{new Date(b.updatedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const renderTable = (rows: Bookmark[]) => (
|
||||
<div className="rounded-lg border overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-muted/50 text-left">
|
||||
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('title')}>
|
||||
<span className="flex items-center gap-1">Title {sortIcon('title')}</span>
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium">URL</th>
|
||||
<th className="px-4 py-3 font-medium">Tags</th>
|
||||
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('kanbanStatus')}>
|
||||
<span className="flex items-center gap-1">Status {sortIcon('kanbanStatus')}</span>
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('updatedAt')}>
|
||||
<span className="flex items-center gap-1">Updated {sortIcon('updatedAt')}</span>
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium w-20">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{loading ? (
|
||||
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">Loading...</td></tr>
|
||||
) : rows.length === 0 ? (
|
||||
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">No bookmarks found</td></tr>
|
||||
) : rows.map(renderRow)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const renderGrouped = () => {
|
||||
if (groupBy === 'collections' && (collectionsState === 'idle' || collectionsState === 'loading')) {
|
||||
return <p className="py-8 text-center text-sm text-muted-foreground">Loading collections...</p>
|
||||
}
|
||||
if (groupBy === 'collections' && collectionsState === 'error') {
|
||||
return (
|
||||
<div className="rounded-lg border border-dashed p-8 text-center">
|
||||
<p className="text-sm text-muted-foreground">Could not load collection memberships.</p>
|
||||
<Button variant="outline" size="sm" className="mt-3" onClick={() => loadCollectionMemberships()}>Try again</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (loading) return <p className="py-8 text-center text-sm text-muted-foreground">Loading...</p>
|
||||
if (groups.length === 0) return <p className="py-8 text-center text-sm text-muted-foreground">No bookmarks found</p>
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{groups.map(g => (
|
||||
<section key={g.key} className="space-y-2">
|
||||
{/* Sticks to the top of the scrolling <main> while its section is in view. */}
|
||||
<div className="sticky top-0 z-10 flex items-center gap-2 bg-background py-2">
|
||||
{g.color && <span aria-hidden className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: g.color }} />}
|
||||
<h2 className="font-display text-sm font-semibold tracking-tight">{g.label}</h2>
|
||||
<Badge variant="outline" className="text-[10px]">{g.items.length}</Badge>
|
||||
</div>
|
||||
{isMobile ? <div className="space-y-2">{g.items.map(renderCard)}</div> : renderTable(g.items)}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="font-display text-2xl font-bold tracking-tight">All Bookmarks</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">Every saved link. Use the sidebar to filter by calendar, tags, board, or contacts.</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input placeholder="Filter..." value={search} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearch(e.target.value)} className="pl-9" />
|
||||
@@ -134,109 +426,29 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
|
||||
<Share2 className="h-3.5 w-3.5" /> Shared
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<span className="text-sm text-muted-foreground">Group by</span>
|
||||
<Select value={groupBy} onValueChange={(value) => setGroupBy(value as GroupBy)}>
|
||||
<SelectTrigger aria-label="Group by" className="w-[150px]">
|
||||
<SelectValue placeholder="None" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{GROUP_OPTIONS.map(option => (
|
||||
<SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
{isMobile ? (
|
||||
{groupBy !== 'none' ? renderGrouped() : isMobile ? (
|
||||
<div className="space-y-2">
|
||||
{loading ? (
|
||||
<p className="py-8 text-center text-sm text-muted-foreground">Loading...</p>
|
||||
) : sorted.length === 0 ? (
|
||||
<p className="py-8 text-center text-sm text-muted-foreground">No bookmarks found</p>
|
||||
) : sorted.map((b: Bookmark) => (
|
||||
<div
|
||||
key={b.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className="rounded-lg border bg-card p-3 cursor-pointer transition-colors hover:bg-muted/30 focus-visible:outline-2 focus-visible:outline-primary"
|
||||
onClick={() => setSelected(b)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelected(b) } }}
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
{b.favicon && <img src={b.favicon} alt="" referrerPolicy="no-referrer" className="mt-0.5 h-4 w-4 shrink-0 rounded" onError={(e: any) => { e.target.style.display = 'none' }} />}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{b.title ?? 'Untitled'}</p>
|
||||
<a href={b.url} target="_blank" rel="noopener noreferrer" onClick={(e: React.MouseEvent) => e.stopPropagation()} className="block truncate text-xs text-primary hover:underline">
|
||||
{(() => { try { return new URL(b.url).hostname } catch { return b.url } })()}
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
|
||||
<a href={b.url} target="_blank" rel="noopener noreferrer" aria-label="Open link"><ExternalLink className="h-4 w-4 text-muted-foreground hover:text-primary" /></a>
|
||||
{tab === 'mine' && (
|
||||
<button onClick={() => trashBookmark(b)} aria-label="Move to trash"><Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" /></button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
<Badge variant="outline" className="text-[10px]">{b.kanbanStatus?.replace('_', ' ')}</Badge>
|
||||
{(b.tags ?? []).slice(0, 3).map((bt: any) => (
|
||||
<Badge key={bt?.tag?.id} variant="secondary" className="text-[10px] px-1.5 py-0" style={{ backgroundColor: `${bt?.tag?.color}20`, color: bt?.tag?.color }}>{bt?.tag?.name}</Badge>
|
||||
))}
|
||||
<span className="ml-auto text-[10px] text-muted-foreground">{new Date(b.updatedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
) : sorted.map(renderCard)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-muted/50 text-left">
|
||||
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('title')}>
|
||||
<span className="flex items-center gap-1">Title {sortIcon('title')}</span>
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium">URL</th>
|
||||
<th className="px-4 py-3 font-medium">Tags</th>
|
||||
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('kanbanStatus')}>
|
||||
<span className="flex items-center gap-1">Status {sortIcon('kanbanStatus')}</span>
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('updatedAt')}>
|
||||
<span className="flex items-center gap-1">Updated {sortIcon('updatedAt')}</span>
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium w-20">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{loading ? (
|
||||
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">Loading...</td></tr>
|
||||
) : sorted.length === 0 ? (
|
||||
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">No bookmarks found</td></tr>
|
||||
) : sorted.map((b: Bookmark) => (
|
||||
<tr key={b.id} tabIndex={0} className="hover:bg-muted/30 cursor-pointer focus-visible:outline-2 focus-visible:outline-primary" onClick={() => setSelected(b)} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelected(b) } }}>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{b.favicon && <img src={b.favicon} alt="" referrerPolicy="no-referrer" className="h-4 w-4 rounded" onError={(e: any) => { e.target.style.display = 'none' }} />}
|
||||
<span className="truncate max-w-[200px]">{b.title ?? 'Untitled'}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<a href={b.url} target="_blank" rel="noopener noreferrer" onClick={(e: React.MouseEvent) => e.stopPropagation()} className="text-primary hover:underline truncate max-w-[200px] block">
|
||||
{(() => { try { return new URL(b.url).hostname } catch { return b.url } })()}
|
||||
</a>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex gap-1">
|
||||
{(b.tags ?? []).slice(0, 2).map((bt: any) => (
|
||||
<Badge key={bt?.tag?.id} variant="secondary" className="text-[10px] px-1.5 py-0" style={{ backgroundColor: `${bt?.tag?.color}20`, color: bt?.tag?.color }}>{bt?.tag?.name}</Badge>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3"><Badge variant="outline" className="text-[10px]">{b.kanbanStatus?.replace('_', ' ')}</Badge></td>
|
||||
<td className="px-4 py-3 text-xs text-muted-foreground">{new Date(b.updatedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })}</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex gap-1" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
|
||||
<a href={b.url} target="_blank" rel="noopener noreferrer"><ExternalLink className="h-4 w-4 text-muted-foreground hover:text-primary" /></a>
|
||||
{tab === 'mine' && (
|
||||
<button onClick={() => trashBookmark(b)} aria-label="Move to trash"><Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" /></button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
) : renderTable(sorted)}
|
||||
<BookmarkDetailSheet bookmark={selected} onClose={() => setSelected(null)} onUpdate={() => { load(); void refreshSelected() }} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -5,11 +5,12 @@ import { Button } from '@/components/ui/button'
|
||||
import { BookmarkCard } from '@/components/bookmark-card'
|
||||
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
|
||||
import { ChevronLeft, ChevronRight, Share2 } from 'lucide-react'
|
||||
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameDay, isSameMonth, addMonths, subMonths, getDay } from 'date-fns'
|
||||
import { format, startOfMonth, endOfMonth, startOfWeek, endOfWeek, eachDayOfInterval, isSameDay, isSameMonth, addDays, addMonths, addYears, getDay, parseISO } from 'date-fns'
|
||||
import type { Bookmark } from '@/components/app-shell'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { toast } from 'sonner'
|
||||
import { fetchBookmarks } from '@/lib/bookmarks'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// Review L-4: a fixed, obviously-not-current placeholder. The real month and
|
||||
// today are set after mount (to avoid an SSR/client hydration mismatch), and
|
||||
@@ -17,10 +18,24 @@ import { fetchBookmarks } from '@/lib/bookmarks'
|
||||
// this epoch as the current month.
|
||||
const INITIAL_DATE = new Date(2000, 0, 1)
|
||||
|
||||
type CalendarView = 'day' | 'week' | 'month' | 'year' | 'list'
|
||||
|
||||
// Month stays the default so the classic grid is what loads first.
|
||||
const VIEWS: { id: CalendarView; label: string }[] = [
|
||||
{ id: 'day', label: 'Day' },
|
||||
{ id: 'week', label: 'Week' },
|
||||
{ id: 'month', label: 'Month' },
|
||||
{ id: 'year', label: 'Year' },
|
||||
{ id: 'list', label: 'List' },
|
||||
]
|
||||
|
||||
export function CalendarClient() {
|
||||
// currentMonth anchors every period view (day/week/month/year); List shows
|
||||
// all due dates and ignores it.
|
||||
const [currentMonth, setCurrentMonth] = useState<Date>(INITIAL_DATE)
|
||||
const [today, setToday] = useState<Date>(INITIAL_DATE)
|
||||
const [ready, setReady] = useState(false)
|
||||
const [view, setView] = useState<CalendarView>('month')
|
||||
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
|
||||
const [selectedDay, setSelectedDay] = useState<Date | null>(null)
|
||||
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
|
||||
@@ -86,11 +101,74 @@ export function CalendarClient() {
|
||||
return map
|
||||
}, [bookmarks])
|
||||
|
||||
const selectedBookmarks = useMemo(() => {
|
||||
if (!selectedDay) return []
|
||||
const key = format(selectedDay, 'yyyy-MM-dd')
|
||||
return bookmarksByDay[key] ?? []
|
||||
}, [selectedDay, bookmarksByDay])
|
||||
const sharedDateKeys = useMemo(() => new Set(sharedDates.map(s => s.date.slice(0, 10))), [sharedDates])
|
||||
|
||||
// Week columns follow the month grid's Sun..Sat order (date-fns default).
|
||||
const weekDays = useMemo(() => eachDayOfInterval({ start: startOfWeek(currentMonth), end: endOfWeek(currentMonth) }), [currentMonth])
|
||||
|
||||
const yearMonths = useMemo(() => Array.from({ length: 12 }, (_, i) => new Date(currentMonth.getFullYear(), i, 1)), [currentMonth])
|
||||
|
||||
// List view: every day with due bookmarks or a shared date, ascending;
|
||||
// ISO date keys sort chronologically as plain strings.
|
||||
const listGroups = useMemo(() => {
|
||||
const keys = Array.from(new Set([...Object.keys(bookmarksByDay), ...sharedDateKeys])).sort()
|
||||
return keys.map(key => ({
|
||||
key,
|
||||
shared: sharedDates.filter(s => s.date.slice(0, 10) === key),
|
||||
bookmarks: [...(bookmarksByDay[key] ?? [])].sort((a, b) => (a.dueDate ?? '') < (b.dueDate ?? '') ? -1 : (a.dueDate ?? '') > (b.dueDate ?? '') ? 1 : 0),
|
||||
}))
|
||||
}, [bookmarksByDay, sharedDates, sharedDateKeys])
|
||||
|
||||
const periodLabel = useMemo(() => {
|
||||
if (view === 'day') return format(currentMonth, 'EEE, MMM d, yyyy')
|
||||
if (view === 'week') {
|
||||
const start = startOfWeek(currentMonth)
|
||||
const end = endOfWeek(currentMonth)
|
||||
return start.getFullYear() === end.getFullYear()
|
||||
? `${format(start, 'MMM d')} – ${format(end, 'MMM d, yyyy')}`
|
||||
: `${format(start, 'MMM d, yyyy')} – ${format(end, 'MMM d, yyyy')}`
|
||||
}
|
||||
if (view === 'year') return format(currentMonth, 'yyyy')
|
||||
return format(currentMonth, 'MMMM yyyy')
|
||||
}, [view, currentMonth])
|
||||
|
||||
const step = (dir: -1 | 1) => setCurrentMonth(d => {
|
||||
if (view === 'day') return addDays(d, dir)
|
||||
if (view === 'week') return addDays(d, dir * 7)
|
||||
if (view === 'year') return addYears(d, dir)
|
||||
return addMonths(d, dir)
|
||||
})
|
||||
|
||||
const goToday = () => { const now = new Date(); setCurrentMonth(now); setToday(now) }
|
||||
|
||||
// The selected-day detail panel, shared by Month/Week (below the grid) and
|
||||
// the Day view, where the anchor day is the view itself.
|
||||
const renderDayPanel = (day: Date) => {
|
||||
const key = format(day, 'yyyy-MM-dd')
|
||||
const dayBookmarks = bookmarksByDay[key] ?? []
|
||||
const dayShared = sharedDates.filter(s => s.date.slice(0, 10) === key)
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="font-medium">{format(day, 'EEEE, MMMM d, yyyy')}</h2>
|
||||
<div className="flex gap-2"><Input placeholder="Share date with user…" value={shareQuery} onChange={e => setShareQuery(e.target.value)} /></div>
|
||||
</div>
|
||||
{/* Review L-9: sharing a date is broader than the old label said. */}
|
||||
<p className="text-xs text-muted-foreground">Recipients will see your bookmarks due that day, including their notes.</p>
|
||||
{shareUsers.map(u => <Button key={u.id} size="sm" variant="outline" onClick={async () => { const res = await fetch('/api/shared-dates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ date: key, recipientIds: [u.id] }) }); if (!res.ok) { toast.error('Could not share date'); return } toast.success('Date shared'); setShareQuery(''); setShareUsers([]); load() }}>Share with {u.name || u.email}</Button>)}
|
||||
{dayShared.map(s => <div key={s.id} className="flex items-center gap-2 text-xs text-muted-foreground"><span>{s.creator.name || s.creator.email} shared with {s.recipient.name || s.recipient.email}</span><Button size="xs" variant="ghost" onClick={async () => { const res = await fetch(`/api/shared-dates/${s.id}`, { method: 'DELETE' }); if (!res.ok) { toast.error('Only the owner can stop sharing'); return } load() }}>Stop sharing</Button></div>)}
|
||||
{dayBookmarks.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No bookmarks on this date</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
{dayBookmarks.map((b: Bookmark) => (
|
||||
<BookmarkCard key={b.id} bookmark={b} compact onClick={() => setSelectedBookmark(b)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
@@ -106,23 +184,33 @@ export function CalendarClient() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="font-display text-2xl font-bold tracking-tight">Calendar</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">Bookmarks organized by due date</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="icon-sm" onClick={() => setCurrentMonth(subMonths(currentMonth, 1))}>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="font-medium text-sm min-w-[140px] text-center">{format(currentMonth, 'MMMM yyyy')}</span>
|
||||
<Button variant="outline" size="icon-sm" onClick={() => setCurrentMonth(addMonths(currentMonth, 1))}>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div role="group" aria-label="Calendar view" className="flex items-center gap-0.5 rounded-lg border border-border/60 bg-muted/30 p-0.5">
|
||||
{VIEWS.map(v => (
|
||||
<Button key={v.id} size="xs" variant={view === v.id ? 'secondary' : 'ghost'} aria-pressed={view === v.id} onClick={() => setView(v.id)}>{v.label}</Button>
|
||||
))}
|
||||
</div>
|
||||
{view !== 'list' && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="icon-sm" aria-label={`Previous ${view}`} onClick={() => step(-1)}>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="font-medium text-sm min-w-[140px] whitespace-nowrap text-center">{periodLabel}</span>
|
||||
<Button variant="outline" size="icon-sm" aria-label={`Next ${view}`} onClick={() => step(1)}>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={goToday}>Today</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
|
||||
{view === 'month' && <div className="grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
|
||||
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(d => (
|
||||
<div key={d} className="bg-muted/50 px-0.5 py-2 text-center text-xs font-medium text-muted-foreground sm:px-2"><span className="sm:hidden">{d[0]}</span><span className="hidden sm:inline">{d}</span></div>
|
||||
))}
|
||||
@@ -167,30 +255,129 @@ export function CalendarClient() {
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{selectedDay && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-medium">{format(selectedDay, 'EEEE, MMMM d, yyyy')}</h2>
|
||||
<div className="flex gap-2"><Input placeholder="Share date with user…" value={shareQuery} onChange={e => setShareQuery(e.target.value)} /></div>
|
||||
{view === 'day' && renderDayPanel(currentMonth)}
|
||||
|
||||
{view === 'week' && (
|
||||
<div className="overflow-x-auto rounded-lg">
|
||||
<div className="grid min-w-[640px] grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
|
||||
{weekDays.map(day => {
|
||||
const key = format(day, 'yyyy-MM-dd')
|
||||
return (
|
||||
<div key={`header-${key}`} className="bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground">
|
||||
{format(day, 'EEE')}{' '}
|
||||
<span className={cn('inline-flex h-5 w-5 items-center justify-center rounded-full align-middle', isSameDay(day, today) && 'bg-primary text-primary-foreground')}>{format(day, 'd')}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{weekDays.map(day => {
|
||||
const key = format(day, 'yyyy-MM-dd')
|
||||
const dayBookmarks = bookmarksByDay[key] ?? []
|
||||
const isSelected = selectedDay ? isSameDay(day, selectedDay) : false
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-pressed={isSelected}
|
||||
aria-label={format(day, 'EEEE, MMMM d, yyyy')}
|
||||
onClick={() => setSelectedDay(day)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedDay(day) } }}
|
||||
className={cn('bg-card min-h-[160px] p-1.5 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary', isSelected && 'ring-2 ring-primary ring-inset')}
|
||||
>
|
||||
<div className="space-y-0.5">
|
||||
{sharedDates.filter(s => s.date.slice(0, 10) === key).map(s => <p key={s.id} className="truncate text-[10px] text-primary" title={s.note || ''}>Shared: {s.creator.name || s.creator.email}</p>)}
|
||||
{dayBookmarks.slice(0, 4).map((b: Bookmark) => (
|
||||
<div key={b.id} role="button" tabIndex={0} className="text-[10px] truncate rounded bg-primary/10 text-primary px-1 py-0.5 cursor-pointer focus-visible:outline-1 focus-visible:outline-primary" onClick={(e: React.MouseEvent) => { e.stopPropagation(); setSelectedBookmark(b) }} onKeyDown={(e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); setSelectedBookmark(b) } }}>
|
||||
{b.title ?? 'Untitled'}
|
||||
</div>
|
||||
))}
|
||||
{dayBookmarks.length > 4 && (
|
||||
<div className="text-[10px] text-muted-foreground px-1">+{dayBookmarks.length - 4} more</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{/* Review L-9: sharing a date is broader than the old label said. */}
|
||||
<p className="text-xs text-muted-foreground">Recipients will see your bookmarks due that day, including their notes.</p>
|
||||
{shareUsers.map(u => <Button key={u.id} size="sm" variant="outline" onClick={async () => { const res = await fetch('/api/shared-dates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ date: format(selectedDay, 'yyyy-MM-dd'), recipientIds: [u.id] }) }); if (!res.ok) { toast.error('Could not share date'); return } toast.success('Date shared'); setShareQuery(''); setShareUsers([]); load() }}>Share with {u.name || u.email}</Button>)}
|
||||
{sharedDates.filter(s => s.date.slice(0, 10) === format(selectedDay, 'yyyy-MM-dd')).map(s => <div key={s.id} className="flex items-center gap-2 text-xs text-muted-foreground"><span>{s.creator.name || s.creator.email} shared with {s.recipient.name || s.recipient.email}</span><Button size="xs" variant="ghost" onClick={async () => { const res = await fetch(`/api/shared-dates/${s.id}`, { method: 'DELETE' }); if (!res.ok) { toast.error('Only the owner can stop sharing'); return } load() }}>Stop sharing</Button></div>)}
|
||||
{selectedBookmarks.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No bookmarks on this date</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
{selectedBookmarks.map((b: Bookmark) => (
|
||||
<BookmarkCard key={b.id} bookmark={b} compact onClick={() => setSelectedBookmark(b)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{view === 'year' && (
|
||||
<div className="overflow-x-auto">
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||||
{yearMonths.map(month => {
|
||||
const monthKey = format(month, 'yyyy-MM')
|
||||
const monthDays = eachDayOfInterval({ start: startOfMonth(month), end: endOfMonth(month) })
|
||||
const lead = getDay(startOfMonth(month))
|
||||
const openMonth = () => { setCurrentMonth(month); setView('month') }
|
||||
return (
|
||||
<div
|
||||
key={monthKey}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`Open ${format(month, 'MMMM yyyy')}`}
|
||||
onClick={openMonth}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openMonth() } }}
|
||||
className={cn('rounded-lg border bg-card p-2 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary', isSameMonth(month, currentMonth) ? 'border-primary/50' : 'border-border/60')}
|
||||
>
|
||||
<p className="mb-1 text-center text-xs font-medium">{format(month, 'MMMM')}</p>
|
||||
<div className="grid grid-cols-7 gap-y-0.5 text-center">
|
||||
{['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d, i) => <span key={`wd-${i}`} className="text-[9px] text-muted-foreground">{d}</span>)}
|
||||
{Array.from({ length: lead }).map((_, i) => <span key={`empty-${i}`} />)}
|
||||
{monthDays.map(day => {
|
||||
const key = format(day, 'yyyy-MM-dd')
|
||||
const hasItems = (bookmarksByDay[key]?.length ?? 0) > 0 || sharedDateKeys.has(key)
|
||||
return (
|
||||
<span key={key} className={cn('rounded-full text-[10px] leading-4', isSameDay(day, today) ? 'bg-primary text-primary-foreground' : hasItems ? 'font-semibold text-primary' : 'text-muted-foreground')}>
|
||||
{format(day, 'd')}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{view === 'list' && (
|
||||
listGroups.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No bookmarks with due dates</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border/60 bg-card">
|
||||
{listGroups.map(group => {
|
||||
const day = parseISO(group.key)
|
||||
return (
|
||||
<div key={group.key}>
|
||||
<div className="bg-muted/50 px-3 py-1.5 text-xs font-medium text-muted-foreground">
|
||||
{format(day, 'EEEE, MMMM d, yyyy')}{isSameDay(day, today) ? ' · Today' : ''}
|
||||
</div>
|
||||
{group.shared.map(s => <p key={s.id} className="truncate px-3 py-1 text-xs text-primary" title={s.note || ''}>Shared: {s.creator.name || s.creator.email}</p>)}
|
||||
{group.bookmarks.map((b: Bookmark) => (
|
||||
<div
|
||||
key={b.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={b.title ?? 'Untitled'}
|
||||
onClick={() => setSelectedBookmark(b)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedBookmark(b) } }}
|
||||
className="cursor-pointer px-3 py-2 transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary"
|
||||
>
|
||||
<span className="block truncate text-sm">{b.title ?? 'Untitled'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{selectedDay && (view === 'month' || view === 'week') && renderDayPanel(selectedDay)}
|
||||
|
||||
<BookmarkDetailSheet bookmark={selectedBookmark} onClose={() => setSelectedBookmark(null)} onUpdate={load} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -217,7 +217,7 @@ function ValueEditor({ prop, value, onSave, readOnly = false }: { prop: Collecti
|
||||
}
|
||||
}
|
||||
|
||||
export function CollectionsClient() {
|
||||
export function CollectionsClient({ initialId = null }: { initialId?: string | null }) {
|
||||
const [collections, setCollections] = useState<CollectionSummary[]>([])
|
||||
const [activeId, setActiveId] = useState<string | null>(null)
|
||||
const isMobile = useIsMobile()
|
||||
@@ -294,10 +294,15 @@ export function CollectionsClient() {
|
||||
useEffect(() => { const t = setTimeout(loadCollections, 0); return () => clearTimeout(t) }, [loadCollections])
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
if (!activeId && collections.length && !isMobile) setActiveId(collections[0].id)
|
||||
if (!activeId && collections.length) {
|
||||
// A sidebar deep-link (?id=) wins; otherwise desktop auto-selects the
|
||||
// first collection while mobile starts on the list.
|
||||
const target = initialId && collections.some((c) => c.id === initialId) ? initialId : (isMobile ? null : collections[0].id)
|
||||
if (target) setActiveId(target)
|
||||
}
|
||||
}, 0)
|
||||
return () => clearTimeout(t)
|
||||
}, [collections, activeId, isMobile])
|
||||
}, [collections, activeId, isMobile, initialId])
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
if (!activeId) { detailSeq.current++; setDetail(null); return }
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { CollectionsClient } from './client'
|
||||
|
||||
export default function CollectionsPage() {
|
||||
return <CollectionsClient />
|
||||
// Sidebar deep-link: /collections?id=<id> opens that collection.
|
||||
export default async function CollectionsPage({ searchParams }: { searchParams: Promise<{ id?: string }> }) {
|
||||
const { id } = await searchParams
|
||||
return <CollectionsClient initialId={id ?? null} />
|
||||
}
|
||||
|
||||
@@ -20,9 +20,9 @@ interface Contact {
|
||||
_count?: { bookmarks: number }
|
||||
}
|
||||
|
||||
export function ContactsClient() {
|
||||
export function ContactsClient({ initialOpen = null }: { initialOpen?: string | null }) {
|
||||
const [contacts, setContacts] = useState<Contact[]>([])
|
||||
const [selectedContact, setSelectedContact] = useState<string | null>(null)
|
||||
const [selectedContact, setSelectedContact] = useState<string | null>(initialOpen)
|
||||
const isMobile = useIsMobile()
|
||||
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
|
||||
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { ContactsClient } from './client'
|
||||
|
||||
export default function ContactsPage() {
|
||||
return <ContactsClient />
|
||||
// Sidebar deep-link: /contacts?open=<id> opens that contact's bookmarks.
|
||||
export default async function ContactsPage({ searchParams }: { searchParams: Promise<{ open?: string }> }) {
|
||||
const { open } = await searchParams
|
||||
return <ContactsClient initialOpen={open ?? null} />
|
||||
}
|
||||
|
||||
@@ -19,9 +19,11 @@ type CardDrop = { columnId: string; index: number }
|
||||
const PALETTE = ['#64748b', '#3b82f6', '#f59e0b', '#22c55e', '#8b5cf6', '#ec4899', '#ef4444', '#14b8a6']
|
||||
|
||||
function columnFor(b: Bookmark, cols: Column[]) {
|
||||
// Only explicitly-placed cards appear on the board: a bookmark with no
|
||||
// kanbanColumnId stays off-board until dragged/added (no auto-populate).
|
||||
const explicit = (b as any).kanbanColumnId as string | null
|
||||
if (explicit && cols.some(c => c.id === explicit)) return explicit
|
||||
return cols.find(c => c.key === b.kanbanStatus)?.id ?? cols[0]?.id
|
||||
return null
|
||||
}
|
||||
|
||||
function sortCards(a: Bookmark, b: Bookmark, currentUserId?: string) {
|
||||
@@ -38,11 +40,12 @@ function sortCards(a: Bookmark, b: Bookmark, currentUserId?: string) {
|
||||
return b.updatedAt.localeCompare(a.updatedAt) || b.id.localeCompare(a.id)
|
||||
}
|
||||
|
||||
export function KanbanClient() {
|
||||
export function KanbanClient({ initialColumn = null }: { initialColumn?: string | null }) {
|
||||
const { data: session } = useSession()
|
||||
const currentUserId = session?.user?.id
|
||||
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
|
||||
const [columns, setColumns] = useState<Column[]>([])
|
||||
const [focusColumn, setFocusColumn] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
|
||||
const [draggedId, setDraggedId] = useState<string | null>(null)
|
||||
@@ -71,6 +74,18 @@ export function KanbanClient() {
|
||||
|
||||
useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('superbrain:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('superbrain:bookmarks-changed', load) } }, [load])
|
||||
|
||||
// Sidebar deep-link (/kanban?column=<id>): scroll that column into view and
|
||||
// briefly ring it so the target is obvious.
|
||||
useEffect(() => {
|
||||
if (!initialColumn || columns.length === 0) return
|
||||
const el = document.querySelector(`[data-column-id="${initialColumn}"]`)
|
||||
if (!el) return
|
||||
el.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' })
|
||||
const show = setTimeout(() => setFocusColumn(initialColumn), 0)
|
||||
const hide = setTimeout(() => setFocusColumn(null), 2000)
|
||||
return () => { clearTimeout(show); clearTimeout(hide) }
|
||||
}, [initialColumn, columns.length])
|
||||
|
||||
const isOwned = useCallback((b: Bookmark) => !currentUserId || b.ownerId === currentUserId, [currentUserId])
|
||||
|
||||
const cardsByColumn = useMemo(() => {
|
||||
@@ -294,6 +309,7 @@ export function KanbanClient() {
|
||||
'rounded-lg border bg-muted/30 flex flex-col w-[85vw] max-w-72 shrink-0 transition-[box-shadow,background-color,border-color] duration-150 sm:w-72 sm:max-w-none',
|
||||
isCardTarget && 'bg-primary/[0.04] border-primary/30 shadow-sm',
|
||||
isColumnTarget && 'ring-2 ring-primary/50 border-primary/40',
|
||||
focusColumn === col.id && 'ring-2 ring-primary/60',
|
||||
)}
|
||||
style={{ borderTopColor: col.color, borderTopWidth: 3 }}
|
||||
onDragOver={e => handleColumnDragOver(e, col)}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { KanbanClient } from './client'
|
||||
|
||||
export default function KanbanPage() {
|
||||
return <KanbanClient />
|
||||
// Sidebar deep-link: /kanban?column=<id> focuses that column.
|
||||
export default async function KanbanPage({ searchParams }: { searchParams: Promise<{ column?: string }> }) {
|
||||
const { column } = await searchParams
|
||||
return <KanbanClient initialColumn={column ?? null} />
|
||||
}
|
||||
|
||||
+153
-106
@@ -1,14 +1,15 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useSession } from 'next-auth/react'
|
||||
import { useState, useEffect, useCallback, Fragment } from 'react'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, PlugZap, FolderSync, CalendarDays, BookUser, Check, X, AlertTriangle } from 'lucide-react'
|
||||
import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, PlugZap, FolderSync, CalendarDays, BookUser, ArrowLeft, Check, X, AlertTriangle } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { invalidateReference } from '@/lib/reference-data'
|
||||
import { NotificationsSettings } from '@/components/notifications-settings'
|
||||
import { ProfileSettings } from '@/components/profile-settings'
|
||||
import { AutomationsSettings } from '@/components/automations-settings'
|
||||
import { AiSettings } from '@/components/ai-settings'
|
||||
import { ApiKeysSettings } from '@/components/api-keys-settings'
|
||||
@@ -17,14 +18,57 @@ import { WebdavSettings } from '@/components/webdav-settings'
|
||||
import { CalDavSettings } from '@/components/caldav-settings'
|
||||
import { CardDavSettings } from '@/components/carddav-settings'
|
||||
import type { OidcStatus } from '@/lib/oidc-config'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useMediaQuery } from '@/lib/use-media-query'
|
||||
|
||||
|
||||
// Settings are grouped by purpose, not a flat strip: account, the external
|
||||
// services that feed your data, the assistant/automation surface, and
|
||||
// machine/developer access. Each item keeps its Radix tab value so deep
|
||||
// links and the browser suites' role="tab" locators are unchanged.
|
||||
const NAV_GROUPS = [
|
||||
{ label: 'Account', items: [
|
||||
{ value: 'profile', label: 'Profile', icon: User },
|
||||
{ value: 'oidc', label: 'Sign-in', icon: Shield },
|
||||
] },
|
||||
{ label: 'Connections', items: [
|
||||
{ value: 'webdav', label: 'WebDAV', icon: FolderSync },
|
||||
{ value: 'caldav', label: 'CalDAV', icon: CalendarDays },
|
||||
{ value: 'carddav', label: 'CardDAV', icon: BookUser },
|
||||
{ value: 'nextcloud', label: 'Contacts sync', icon: Cloud },
|
||||
{ value: 'imap', label: 'IMAP', icon: Mail },
|
||||
] },
|
||||
{ label: 'AI & Automation', items: [
|
||||
{ value: 'ai', label: 'AI', icon: Bot },
|
||||
{ value: 'mcp', label: 'MCP', icon: PlugZap },
|
||||
{ value: 'automations', label: 'Automations', icon: Sparkles },
|
||||
{ value: 'notifications', label: 'Notifications', icon: Bell },
|
||||
] },
|
||||
{ label: 'Developer', items: [
|
||||
{ value: 'api-keys', label: 'API Keys', icon: KeyRound },
|
||||
] },
|
||||
]
|
||||
|
||||
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
|
||||
const { data: session } = useSession()
|
||||
// ?tab=<value> deep links (email footer "Email preferences" lands on
|
||||
// notifications). Unknown values fall back to profile; the Radix tab
|
||||
// values stay the canonical section ids.
|
||||
const requestedTab = useSearchParams().get('tab') ?? ''
|
||||
const initialSection = NAV_GROUPS.some(g => g.items.some(i => i.value === requestedTab))
|
||||
? requestedTab
|
||||
: 'profile'
|
||||
const [imapConfig, setImapConfig] = useState({ host: '', port: 993, tls: true, username: '', password: '', folder: 'INBOX' })
|
||||
const [ncConfig, setNcConfig] = useState({ nextcloudUrl: '', cardDavPath: '', username: '', password: '' })
|
||||
const [savingImap, setSavingImap] = useState(false)
|
||||
const [testingImap, setTestingImap] = useState(false)
|
||||
const [syncingContacts, setSyncingContacts] = useState(false)
|
||||
const [section, setSection] = useState(initialSection)
|
||||
// Below md the grouped nav becomes a list -> detail flow (same
|
||||
// master-detail pattern as collections/tags/contacts); at md+ the
|
||||
// nav and the selected panel sit side by side. A deep link opens the
|
||||
// detail pane directly on narrow screens.
|
||||
const isNarrow = useMediaQuery('(max-width: 767px)')
|
||||
const [mobileDetail, setMobileDetail] = useState(initialSection !== 'profile')
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/settings/imap').then(r => r.json()).then(data => {
|
||||
@@ -92,41 +136,112 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<div className="max-w-5xl space-y-6">
|
||||
<div>
|
||||
<h1 className="font-display text-2xl font-bold tracking-tight">Settings</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">Configure your integrations and preferences</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="profile" className="w-full">
|
||||
<TabsList className="w-full justify-start overflow-x-auto flex-nowrap">
|
||||
<TabsTrigger value="profile" className="gap-1.5"><User className="h-3.5 w-3.5" /> Profile</TabsTrigger>
|
||||
<TabsTrigger value="imap" className="gap-1.5"><Mail className="h-3.5 w-3.5" /> IMAP</TabsTrigger>
|
||||
<TabsTrigger value="nextcloud" className="gap-1.5"><Cloud className="h-3.5 w-3.5" /> Nextcloud</TabsTrigger>
|
||||
<TabsTrigger value="notifications" className="gap-1.5"><Bell className="h-3.5 w-3.5" /> Notifications</TabsTrigger>
|
||||
<TabsTrigger value="automations" className="gap-1.5"><Sparkles className="h-3.5 w-3.5" /> Automations</TabsTrigger>
|
||||
<TabsTrigger value="ai" className="gap-1.5"><Bot className="h-3.5 w-3.5" /> AI</TabsTrigger>
|
||||
<TabsTrigger value="api-keys" className="gap-1.5"><KeyRound className="h-3.5 w-3.5" /> API Keys</TabsTrigger>
|
||||
<TabsTrigger value="mcp" className="gap-1.5"><PlugZap className="h-3.5 w-3.5" /> MCP</TabsTrigger>
|
||||
<TabsTrigger value="webdav" className="gap-1.5"><FolderSync className="h-3.5 w-3.5" /> WebDAV</TabsTrigger>
|
||||
<TabsTrigger value="caldav" className="gap-1.5"><CalendarDays className="h-3.5 w-3.5" /> CalDAV</TabsTrigger>
|
||||
<TabsTrigger value="carddav" className="gap-1.5"><BookUser className="h-3.5 w-3.5" /> CardDAV</TabsTrigger>
|
||||
<TabsTrigger value="oidc" className="gap-1.5"><Shield className="h-3.5 w-3.5" /> OIDC</TabsTrigger>
|
||||
</TabsList>
|
||||
<Tabs
|
||||
value={section}
|
||||
onValueChange={(v) => { setSection(v); if (isNarrow) setMobileDetail(true) }}
|
||||
orientation="vertical"
|
||||
className="w-full"
|
||||
>
|
||||
<div className="flex flex-col gap-6 md:flex-row md:gap-8">
|
||||
<TabsList
|
||||
aria-label="Settings sections"
|
||||
className={cn(
|
||||
'flex h-auto w-full flex-col items-stretch justify-start gap-0.5 rounded-lg border bg-card/50 p-2 md:w-56 md:shrink-0',
|
||||
isNarrow && mobileDetail && 'hidden'
|
||||
)}
|
||||
>
|
||||
{NAV_GROUPS.map((g) => (
|
||||
<Fragment key={g.label}>
|
||||
<div className="px-3 pb-1 pt-3 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground first:pt-1">{g.label}</div>
|
||||
{g.items.map((it) => (
|
||||
<TabsTrigger
|
||||
key={it.value}
|
||||
value={it.value}
|
||||
className="w-full justify-start gap-2 rounded-md px-3 py-2 data-[state=active]:bg-accent data-[state=active]:text-accent-foreground data-[state=active]:shadow-none"
|
||||
>
|
||||
<it.icon className="h-3.5 w-3.5 shrink-0" /> {it.label}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</Fragment>
|
||||
))}
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="profile" className="space-y-4 mt-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-2xl font-bold text-primary">
|
||||
{(session?.user?.name ?? session?.user?.email ?? '?')[0]?.toUpperCase()}
|
||||
<div className={cn('min-w-0 flex-1', isNarrow && !mobileDetail && 'hidden')}>
|
||||
{isNarrow && mobileDetail && (
|
||||
<Button variant="ghost" size="sm" className="mb-3 -ml-2 gap-1 text-muted-foreground" onClick={() => setMobileDetail(false)}>
|
||||
<ArrowLeft className="h-4 w-4" /> All settings
|
||||
</Button>
|
||||
)}
|
||||
<TabsContent value="profile" className="mt-0 space-y-4">
|
||||
<ProfileSettings />
|
||||
</TabsContent>
|
||||
<TabsContent value="oidc" className="mt-0 space-y-4">
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<h3 className="font-medium flex items-center gap-2"><Shield className="h-4 w-4" /> Sign-in (OIDC)</h3>
|
||||
<p className="text-sm text-muted-foreground">Authelia single sign-on, configured via environment variables (read-only)</p>
|
||||
<div className={`flex items-start gap-2 rounded-md p-3 text-sm ${oidc.enabled ? 'bg-green-500/10 text-green-700 dark:text-green-400' : 'bg-amber-500/10 text-amber-800 dark:text-amber-300'}`}>
|
||||
{oidc.enabled ? <Check className="h-4 w-4 mt-0.5 shrink-0" /> : <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />}
|
||||
<span>
|
||||
{oidc.enabled
|
||||
? <>Configured for <span className="font-mono break-all">{oidc.issuer}</span>. Authelia sign-in is enabled.</>
|
||||
: <>Not connected. Authelia sign-in is disabled until all three variables below hold real values. Users can sign in with email and password meanwhile. Setup guide: <span className="font-mono">docs/AUTHELIA.md</span></>}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{session?.user?.name ?? 'User'}</p>
|
||||
<p className="text-sm text-muted-foreground" suppressHydrationWarning>{session?.user?.email}</p>
|
||||
<div className="space-y-2">
|
||||
{([['OIDC_ISSUER', oidc.issuerSet], ['OIDC_CLIENT_ID', oidc.clientIdSet], ['OIDC_CLIENT_SECRET', oidc.clientSecretSet]] as const).map(([name, set]) => (
|
||||
<div key={name} className="flex items-center gap-2">
|
||||
<span className="text-xs font-mono bg-muted px-2 py-1 rounded">{name}</span>
|
||||
<span className="text-sm text-muted-foreground">{set ? 'Set' : 'Not set'}</span>
|
||||
{set ? <Check className="h-4 w-4 text-green-500" /> : <X className="h-4 w-4 text-muted-foreground" />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="space-y-1 pt-2 border-t">
|
||||
<p className="text-xs font-medium text-muted-foreground">Redirect URI to register in Authelia</p>
|
||||
<p className="text-xs font-mono bg-muted px-2 py-1.5 rounded break-all" suppressHydrationWarning>{callbackUrl}</p>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="imap" className="space-y-4 mt-4">
|
||||
<TabsContent value="webdav" className="mt-0 space-y-4">
|
||||
<WebdavSettings />
|
||||
</TabsContent>
|
||||
<TabsContent value="caldav" className="mt-0 space-y-4">
|
||||
<CalDavSettings />
|
||||
</TabsContent>
|
||||
<TabsContent value="carddav" className="mt-0 space-y-4">
|
||||
<CardDavSettings />
|
||||
</TabsContent>
|
||||
<TabsContent value="nextcloud" className="mt-0 space-y-4">
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<h3 className="font-medium flex items-center gap-2"><Cloud className="h-4 w-4" /> Contacts sync (Nextcloud)</h3>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="col-span-2">
|
||||
<label className="text-xs font-medium text-muted-foreground">Nextcloud URL</label>
|
||||
<Input value={ncConfig.nextcloudUrl} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, nextcloudUrl: e.target.value }))} placeholder="https://nextcloud.example.com" />
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<label className="text-xs font-medium text-muted-foreground">CardDAV Path (optional)</label>
|
||||
<Input value={ncConfig.cardDavPath} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, cardDavPath: e.target.value }))} placeholder="/remote.php/dav/addressbooks/users/USER/contacts/" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground">Username</label>
|
||||
<Input value={ncConfig.username} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, username: e.target.value }))} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground">App Password</label>
|
||||
<Input type="password" value={ncConfig.password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, password: e.target.value }))} />
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={syncContacts} loading={syncingContacts}>Sync Contacts Now</Button>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="imap" className="mt-0 space-y-4">
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<h3 className="font-medium flex items-center gap-2"><Server className="h-4 w-4" /> IMAP Configuration</h3>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
@@ -162,91 +277,23 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="nextcloud" className="space-y-4 mt-4">
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<h3 className="font-medium flex items-center gap-2"><Cloud className="h-4 w-4" /> Nextcloud / CardDAV</h3>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="col-span-2">
|
||||
<label className="text-xs font-medium text-muted-foreground">Nextcloud URL</label>
|
||||
<Input value={ncConfig.nextcloudUrl} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, nextcloudUrl: e.target.value }))} placeholder="https://nextcloud.example.com" />
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<label className="text-xs font-medium text-muted-foreground">CardDAV Path (optional)</label>
|
||||
<Input value={ncConfig.cardDavPath} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, cardDavPath: e.target.value }))} placeholder="/remote.php/dav/addressbooks/users/USER/contacts/" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground">Username</label>
|
||||
<Input value={ncConfig.username} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, username: e.target.value }))} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground">App Password</label>
|
||||
<Input type="password" value={ncConfig.password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, password: e.target.value }))} />
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={syncContacts} loading={syncingContacts}>Sync Contacts Now</Button>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="notifications" className="space-y-4 mt-4">
|
||||
<NotificationsSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="automations" className="space-y-4 mt-4">
|
||||
<AutomationsSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="ai" className="space-y-4 mt-4">
|
||||
<TabsContent value="ai" className="mt-0 space-y-4">
|
||||
<AiSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="api-keys" className="space-y-4 mt-4">
|
||||
<ApiKeysSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="mcp" className="space-y-4 mt-4">
|
||||
<TabsContent value="mcp" className="mt-0 space-y-4">
|
||||
<McpSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="webdav" className="space-y-4 mt-4">
|
||||
<WebdavSettings />
|
||||
<TabsContent value="automations" className="mt-0 space-y-4">
|
||||
<AutomationsSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="caldav" className="space-y-4 mt-4">
|
||||
<CalDavSettings />
|
||||
<TabsContent value="notifications" className="mt-0 space-y-4">
|
||||
<NotificationsSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="carddav" className="space-y-4 mt-4">
|
||||
<CardDavSettings />
|
||||
<TabsContent value="api-keys" className="mt-0 space-y-4">
|
||||
<ApiKeysSettings />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="oidc" className="space-y-4 mt-4">
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<h3 className="font-medium flex items-center gap-2"><Shield className="h-4 w-4" /> OIDC Configuration</h3>
|
||||
<p className="text-sm text-muted-foreground">Authelia single sign-on, configured via environment variables (read-only)</p>
|
||||
<div className={`flex items-start gap-2 rounded-md p-3 text-sm ${oidc.enabled ? 'bg-green-500/10 text-green-700 dark:text-green-400' : 'bg-amber-500/10 text-amber-800 dark:text-amber-300'}`}>
|
||||
{oidc.enabled ? <Check className="h-4 w-4 mt-0.5 shrink-0" /> : <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />}
|
||||
<span>
|
||||
{oidc.enabled
|
||||
? <>Configured for <span className="font-mono break-all">{oidc.issuer}</span>. Authelia sign-in is enabled.</>
|
||||
: <>Not connected. Authelia sign-in is disabled until all three variables below hold real values. Users can sign in with email and password meanwhile. Setup guide: <span className="font-mono">docs/AUTHELIA.md</span></>}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{([['OIDC_ISSUER', oidc.issuerSet], ['OIDC_CLIENT_ID', oidc.clientIdSet], ['OIDC_CLIENT_SECRET', oidc.clientSecretSet]] as const).map(([name, set]) => (
|
||||
<div key={name} className="flex items-center gap-2">
|
||||
<span className="text-xs font-mono bg-muted px-2 py-1 rounded">{name}</span>
|
||||
<span className="text-sm text-muted-foreground">{set ? 'Set' : 'Not set'}</span>
|
||||
{set ? <Check className="h-4 w-4 text-green-500" /> : <X className="h-4 w-4 text-muted-foreground" />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="space-y-1 pt-2 border-t">
|
||||
<p className="text-xs font-medium text-muted-foreground">Redirect URI to register in Authelia</p>
|
||||
<p className="text-xs font-mono bg-muted px-2 py-1.5 rounded break-all" suppressHydrationWarning>{callbackUrl}</p>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</div>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { SettingsClient } from './client'
|
||||
import { getOidcStatus } from '@/lib/oidc-config'
|
||||
import { headers } from 'next/headers'
|
||||
import { Suspense } from 'react'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
@@ -20,5 +21,11 @@ export default async function SettingsPage() {
|
||||
const proto = h.get('x-forwarded-proto') ?? 'http'
|
||||
if (host) callbackUrl = `${proto}://${host}/api/auth/callback/authelia`
|
||||
}
|
||||
return <SettingsClient oidc={getOidcStatus()} callbackUrl={callbackUrl} />
|
||||
// useSearchParams in the client (?tab= deep links, e.g. from email
|
||||
// footers) needs a Suspense boundary for prerender.
|
||||
return (
|
||||
<Suspense>
|
||||
<SettingsClient oidc={getOidcStatus()} callbackUrl={callbackUrl} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Link2, Mail } from 'lucide-react'
|
||||
import { Mail } from 'lucide-react'
|
||||
import { BrandIcon } from '@/components/brand-icon'
|
||||
import Link from 'next/link'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
@@ -41,9 +42,7 @@ export function ForgotPasswordClient() {
|
||||
<div className="w-full max-w-sm space-y-8">
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Link2 className="h-7 w-7" />
|
||||
</div>
|
||||
<BrandIcon className="h-14 w-14" />
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Reset Password</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
'use client'
|
||||
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
|
||||
|
||||
const FAQ = [
|
||||
{
|
||||
q: 'How do I stop notification emails?',
|
||||
a: 'Use the unsubscribe link in any notification email — it turns off your email channels and any automations that email you, without signing in. You can also toggle channels and rules in Settings → Notifications. Password resets and other account emails are not affected by unsubscribing.',
|
||||
},
|
||||
{
|
||||
q: 'Why didn\u2019t my notification arrive?',
|
||||
a: 'Check Settings → Notifications: the channel and the rule must both be enabled, and your plan must include the channel kind. History lists every delivery attempt, including suppressed ones (for example a recipient without a channel of that kind, or a plan downgrade). Email delivery also needs the operator to have configured an SMTP relay.',
|
||||
},
|
||||
{
|
||||
q: 'Who can see a public bookmark link?',
|
||||
a: 'Anyone with the link. It publishes the title, description, notes, due date, tags and preview — and deliberately no owner attribution. Treat public links as published content; revoking the public toggle stops access immediately.',
|
||||
},
|
||||
{
|
||||
q: 'Can I use my own AI provider and key?',
|
||||
a: 'Yes. Settings → AI stores your own OpenAI-compatible, Anthropic or Gemini key (encrypted, write-only). Your key is used before any server key, and the server key itself depends on your plan. Without any AI configured, AI features point you to Settings instead of failing silently.',
|
||||
},
|
||||
{
|
||||
q: 'What happens when I delete a page or bookmark?',
|
||||
a: 'Deletions are recoverable from Trash. Deleting a parent page promotes its children instead of deleting them, and page revisions let you restore earlier content. Note that restoring from Trash does not restore access grants — re-share if needed.',
|
||||
},
|
||||
{
|
||||
q: 'How do I connect Nextcloud?',
|
||||
a: 'Settings → WebDAV, CalDAV or CardDAV. On Core deployments the forms offer a prefill for your account\u2019s Nextcloud URL. Each connected share, calendar or address book becomes its own collection, synced on a schedule; files, events and contacts appear as bookmarks.',
|
||||
},
|
||||
]
|
||||
|
||||
export function HelpFaq() {
|
||||
return (
|
||||
<Accordion type="single" collapsible className="mt-4">
|
||||
{FAQ.map((item, i) => (
|
||||
<AccordionItem key={i} value={`faq-${i}`}>
|
||||
<AccordionTrigger className="text-sm font-medium">{item.q}</AccordionTrigger>
|
||||
<AccordionContent className="text-sm leading-relaxed text-muted-foreground">
|
||||
{item.a}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import Link from 'next/link'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { HelpFaq } from './faq'
|
||||
import { BrandIcon } from '@/components/brand-icon'
|
||||
import {
|
||||
Bookmark, FolderOpen, FileText, Kanban, Radar, Bell, Bot,
|
||||
FolderSync, KeyRound, ArrowRight,
|
||||
} from 'lucide-react'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const SECTIONS = [
|
||||
{
|
||||
id: 'getting-started',
|
||||
icon: ArrowRight,
|
||||
title: 'Getting started',
|
||||
body: [
|
||||
'Sign in with your email and password, or with Authelia single sign-on if your deployment uses it. On first run, create your account from the sign-up page — then start by saving a bookmark, writing a page, or connecting a service in Settings.',
|
||||
'Forgot your password? Use the "Forgot password?" link on the sign-in page; a single-use reset link is emailed to you. On single-sign-on deployments, recovery is handled by your identity provider instead.',
|
||||
],
|
||||
where: 'Sign in → /login · Reset → /forgot-password',
|
||||
},
|
||||
{
|
||||
id: 'bookmarks',
|
||||
icon: Bookmark,
|
||||
title: 'Bookmarks & tags',
|
||||
body: [
|
||||
'Every URL you save becomes a bookmark with a title, description, notes, tags and an optional due date. Open a bookmark to edit its details, attach it to pages and collections, or place it on the board.',
|
||||
'Sharing a tag shares every bookmark under it with the recipients — group-wide, including bookmarks other recipients add later. A public bookmark link publishes the title, description, notes, due date, tags and preview to anyone with the link, and deliberately carries no owner attribution.',
|
||||
],
|
||||
where: 'Sidebar → Bookmarks · Tags',
|
||||
},
|
||||
{
|
||||
id: 'collections',
|
||||
icon: FolderOpen,
|
||||
title: 'Collections',
|
||||
body: [
|
||||
'Collections group bookmarks manually or by smart filters, and render as a table or a board grouped by any select property. Shared collections are read-only for recipients.',
|
||||
'Connected services materialize as collections automatically: each WebDAV share, CalDAV calendar and CardDAV address book becomes its own collection whose files, events or contacts are bookmarks. Syncing mirrors the server — removed items detach, and your own removals stay removed.',
|
||||
],
|
||||
where: 'Sidebar → Collections · Settings → WebDAV / CalDAV / CardDAV',
|
||||
},
|
||||
{
|
||||
id: 'pages',
|
||||
icon: FileText,
|
||||
title: 'Pages',
|
||||
body: [
|
||||
'Pages are WYSIWYG documents stored as Markdown. Every URL you add — via the Link button, the links popover, or a bare-URL paste — is also saved as a bookmark linked to the page, reusing an existing bookmark for the same URL instead of duplicating it.',
|
||||
'Pages can nest under a parent; deleting a parent promotes its children. Every save keeps a revision you can restore, and deleted pages are recoverable from Trash. Autosave pauses on a version conflict so you never clobber newer content.',
|
||||
],
|
||||
where: 'Sidebar → Pages · Trash',
|
||||
},
|
||||
{
|
||||
id: 'board',
|
||||
icon: Kanban,
|
||||
title: 'Kanban board',
|
||||
body: [
|
||||
'The board places bookmarks in columns you define. Drag cards between columns or reorder within a column; moves are saved immediately. Shared cards are read-only.',
|
||||
],
|
||||
where: 'Sidebar → Board',
|
||||
},
|
||||
{
|
||||
id: 'signals',
|
||||
icon: Radar,
|
||||
title: 'Signals & mailbox watches',
|
||||
body: [
|
||||
'Signals are events attached to bookmarks — notes, arrivals, reminders. Connect an IMAP mailbox in Settings and add a watch from a bookmark\'s Signals panel: matching emails become signals on that bookmark.',
|
||||
],
|
||||
where: 'Settings → IMAP · Bookmark → Signals',
|
||||
},
|
||||
{
|
||||
id: 'notifications',
|
||||
icon: Bell,
|
||||
title: 'Notifications',
|
||||
body: [
|
||||
'Notification rules fire on signals created, bookmarks coming due, or shares received, and deliver through your channels: email, Slack, Matrix, Telegram or Signal. Rules can target other people in your organization; each recipient gets the delivery through their own channel. History shows every delivery, including suppressed ones.',
|
||||
'Email preferences live in Settings → Notifications. Every notification email also carries an unsubscribe link that turns off your email channels and any automations that email you — password resets and other account emails are not affected.',
|
||||
],
|
||||
where: 'Settings → Notifications',
|
||||
},
|
||||
{
|
||||
id: 'assistant',
|
||||
icon: Bot,
|
||||
title: 'Assistant & automations',
|
||||
body: [
|
||||
'The assistant answers questions about your data and can propose automations: stored tasks that periodically check a page and then notify you, send an email, or save a bookmark. Proposals are compiled into a validated spec and only run after you confirm them — the assistant never acts on its own.',
|
||||
'AI features use your own provider key (Settings → AI) or the server key when your plan includes it. Without any AI configured, the app tells you where to add one instead of failing silently.',
|
||||
],
|
||||
where: 'Assistant panel · Settings → AI / Automations',
|
||||
},
|
||||
{
|
||||
id: 'connections',
|
||||
icon: FolderSync,
|
||||
title: 'Connections',
|
||||
body: [
|
||||
'Settings connects Superbrain to your services: WebDAV shares, CalDAV calendars, CardDAV address books, Nextcloud contacts sync, and IMAP mailboxes. Credentials are stored encrypted and are write-only — the app never shows them back to you.',
|
||||
'On Core deployments with Nextcloud, the connection forms offer a one-click prefill for your account.',
|
||||
],
|
||||
where: 'Settings → Connections',
|
||||
},
|
||||
{
|
||||
id: 'developer',
|
||||
icon: KeyRound,
|
||||
title: 'API keys & MCP',
|
||||
body: [
|
||||
'Personal API keys (sb_…) authenticate machine clients against the Go API directly; the plaintext key is shown once at creation and stored hashed. The superbrain-mcp server exposes your data to MCP clients through the federated gateway.',
|
||||
'You can also register external MCP servers (Settings → MCP) for Superbrain to dial as a client.',
|
||||
],
|
||||
where: 'Settings → API Keys / MCP',
|
||||
},
|
||||
]
|
||||
|
||||
export default function HelpPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
<header className="border-b border-border">
|
||||
<div className="mx-auto flex max-w-4xl items-center justify-between px-6 py-4">
|
||||
<Link href="/login" className="flex items-center gap-2 font-display text-lg font-bold tracking-tight">
|
||||
<BrandIcon className="h-6 w-6" />
|
||||
superbrain
|
||||
</Link>
|
||||
<Button asChild size="sm">
|
||||
<Link href="/login">Open Superbrain</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="mx-auto max-w-4xl px-6 pb-24">
|
||||
<div className="pt-16 pb-10">
|
||||
<Badge variant="secondary" className="mb-4">Help center</Badge>
|
||||
<h1 className="font-display text-4xl font-bold tracking-tight">
|
||||
How Superbrain works
|
||||
</h1>
|
||||
<p className="mt-3 max-w-2xl text-base text-muted-foreground">
|
||||
Bookmarks, pages, collections and automations — a quick guide to every
|
||||
surface of the app. Jump to a topic below, or browse the FAQ at the end.
|
||||
</p>
|
||||
<nav className="mt-6 flex flex-wrap gap-2">
|
||||
{SECTIONS.map(s => (
|
||||
<a
|
||||
key={s.id}
|
||||
href={`#${s.id}`}
|
||||
className="rounded-full border border-border px-3 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
|
||||
>
|
||||
{s.title}
|
||||
</a>
|
||||
))}
|
||||
<a
|
||||
href="#faq"
|
||||
className="rounded-full border border-border px-3 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
|
||||
>
|
||||
FAQ
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div className="space-y-12">
|
||||
{SECTIONS.map(s => (
|
||||
<section key={s.id} id={s.id} className="scroll-mt-8">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
|
||||
<s.icon className="h-5 w-5" />
|
||||
</div>
|
||||
<h2 className="font-display text-2xl font-bold tracking-tight">{s.title}</h2>
|
||||
</div>
|
||||
<div className="mt-4 space-y-3 text-sm leading-relaxed text-foreground/90">
|
||||
{s.body.map((p, i) => <p key={i}>{p}</p>)}
|
||||
</div>
|
||||
<p className="mt-3 font-mono text-xs text-muted-foreground">{s.where}</p>
|
||||
</section>
|
||||
))}
|
||||
|
||||
<section id="faq" className="scroll-mt-8">
|
||||
<h2 className="font-display text-2xl font-bold tracking-tight">Frequently asked questions</h2>
|
||||
<HelpFaq />
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer className="border-t border-border">
|
||||
<div className="mx-auto flex max-w-4xl flex-wrap items-center justify-between gap-2 px-6 py-6 text-xs text-muted-foreground">
|
||||
<span>Superbrain — your second brain, federated.</span>
|
||||
<span className="flex gap-4">
|
||||
<Link href="/login" className="hover:text-primary hover:underline">Sign in</Link>
|
||||
<Link href="/forgot-password" className="hover:text-primary hover:underline">Reset password</Link>
|
||||
</span>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export const metadata = {
|
||||
icons: {
|
||||
icon: '/favicon.svg',
|
||||
shortcut: '/favicon.svg',
|
||||
apple: '/superbrain-icon.png',
|
||||
},
|
||||
openGraph: {
|
||||
title: 'Superbrain',
|
||||
|
||||
@@ -4,7 +4,8 @@ import { useState } from 'react'
|
||||
import { signIn } from 'next-auth/react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Link2, Shield, Mail, Lock } from 'lucide-react'
|
||||
import { Shield, Mail, Lock } from 'lucide-react'
|
||||
import { BrandIcon } from '@/components/brand-icon'
|
||||
import Link from 'next/link'
|
||||
import { toast } from 'sonner'
|
||||
import { useRouter } from 'next/navigation'
|
||||
@@ -42,9 +43,7 @@ export function LoginClient({ oidcEnabled, passwordEnabled }: { oidcEnabled: boo
|
||||
<div className="w-full max-w-sm space-y-8">
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Link2 className="h-7 w-7" />
|
||||
</div>
|
||||
<BrandIcon className="h-14 w-14" />
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Superbrain</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">Your personal binder of life on the web</p>
|
||||
@@ -117,6 +116,9 @@ export function LoginClient({ oidcEnabled, passwordEnabled }: { oidcEnabled: boo
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
<Link href="/help" className="hover:text-primary hover:underline">Help center</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,8 @@ import { useState } from 'react'
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Link2, Lock } from 'lucide-react'
|
||||
import { Lock } from 'lucide-react'
|
||||
import { BrandIcon } from '@/components/brand-icon'
|
||||
import Link from 'next/link'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
@@ -48,9 +49,7 @@ export function ResetPasswordClient() {
|
||||
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||
<div className="w-full max-w-sm space-y-8 text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Link2 className="h-7 w-7" />
|
||||
</div>
|
||||
<BrandIcon className="h-14 w-14" />
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Reset Password</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
@@ -71,9 +70,7 @@ export function ResetPasswordClient() {
|
||||
<div className="w-full max-w-sm space-y-8">
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Link2 className="h-7 w-7" />
|
||||
</div>
|
||||
<BrandIcon className="h-14 w-14" />
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Choose a New Password</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">Resetting signs out every other device.</p>
|
||||
|
||||
@@ -4,7 +4,8 @@ import { useState } from 'react'
|
||||
import { signIn } from 'next-auth/react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Link2, Mail, Lock, User } from 'lucide-react'
|
||||
import { Mail, Lock, User } from 'lucide-react'
|
||||
import { BrandIcon } from '@/components/brand-icon'
|
||||
import Link from 'next/link'
|
||||
import { toast } from 'sonner'
|
||||
import { useRouter } from 'next/navigation'
|
||||
@@ -52,9 +53,7 @@ export function SignupClient() {
|
||||
<div className="w-full max-w-sm space-y-8">
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||
<Link2 className="h-7 w-7" />
|
||||
</div>
|
||||
<BrandIcon className="h-14 w-14" />
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Create Account</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">Join Superbrain to start organizing your links</p>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { BrandIcon } from '@/components/brand-icon'
|
||||
import Link from 'next/link'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
// The token in the link IS the credential (HMAC-signed user id, issued only
|
||||
// in mail to the owner's own address). The page never needs a session; the
|
||||
// Go endpoint validates the token and disables email notification channels
|
||||
// plus self-addressed agent email tasks. Transactional mail (password
|
||||
// resets) keeps flowing — the copy must say so.
|
||||
export function UnsubscribeClient() {
|
||||
const params = useSearchParams()
|
||||
const token = params.get('token') ?? ''
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [done, setDone] = useState(false)
|
||||
const [invalid, setInvalid] = useState(false)
|
||||
|
||||
const handleUnsubscribe = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await fetch('/api/notifications/unsubscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
})
|
||||
const data = await res.json().catch(() => null)
|
||||
if (res.ok && data?.ok) {
|
||||
setDone(true)
|
||||
} else if (res.status === 400) {
|
||||
setInvalid(true)
|
||||
} else {
|
||||
toast.error(data?.error ?? 'Could not unsubscribe right now')
|
||||
}
|
||||
} catch {
|
||||
toast.error('Could not unsubscribe right now')
|
||||
}
|
||||
setLoading(false)
|
||||
}
|
||||
|
||||
if (!token || invalid) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||
<div className="w-full max-w-sm space-y-8 text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<BrandIcon className="h-14 w-14" />
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Invalid Link</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
This unsubscribe link is invalid or has expired. Open Settings → Notifications
|
||||
in the app to manage your email preferences directly.
|
||||
</p>
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
<Link href="/settings?tab=notifications" className="text-primary hover:underline">Email preferences</Link>
|
||||
{' · '}
|
||||
<Link href="/help" className="text-primary hover:underline">Help center</Link>
|
||||
{' · '}
|
||||
<Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (done) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||
<div className="w-full max-w-sm space-y-8 text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<BrandIcon className="h-14 w-14" />
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">You're Unsubscribed</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
Notification emails and automations that email you have been turned off.
|
||||
You can re-enable them anytime in Settings → Notifications. Account emails
|
||||
such as password resets are not affected.
|
||||
</p>
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
<Link href="/settings?tab=notifications" className="text-primary hover:underline">Email preferences</Link>
|
||||
{' · '}
|
||||
<Link href="/help" className="text-primary hover:underline">Help center</Link>
|
||||
{' · '}
|
||||
<Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||
<div className="w-full max-w-sm space-y-8">
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<BrandIcon className="h-14 w-14" />
|
||||
</div>
|
||||
<h1 className="font-display text-3xl font-bold tracking-tight">Unsubscribe</h1>
|
||||
<p className="text-sm text-muted-foreground mt-2">
|
||||
Stop notification emails and automations that email you. Password resets and
|
||||
other account emails keep working, and you can re-enable notifications anytime
|
||||
in Settings.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<Button className="w-full" onClick={handleUnsubscribe} loading={loading}>
|
||||
Unsubscribe from notification emails
|
||||
</Button>
|
||||
<Button variant="outline" className="w-full" asChild>
|
||||
<Link href="/settings?tab=notifications">Keep my current preferences</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
<Link href="/help" className="text-primary hover:underline">Help center</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { UnsubscribeClient } from './client'
|
||||
import { Suspense } from 'react'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export default function UnsubscribePage() {
|
||||
// useSearchParams in the client needs a Suspense boundary for prerender.
|
||||
return (
|
||||
<Suspense>
|
||||
<UnsubscribeClient />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
+28
@@ -165,6 +165,34 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
token.ver = user.tokenVersion
|
||||
token.role = user.role
|
||||
}
|
||||
if (trigger === 'update' && typeof token.id === 'string' && typeof token.ver === 'number') {
|
||||
// Profile edits (Settings → Profile) call useSession().update({})
|
||||
// so the session identity re-syncs from Go — the top bar and
|
||||
// profile header reflect a new name without a re-login. (A bare
|
||||
// update() only re-fetches; the data argument is what fires this
|
||||
// trigger in next-auth v5.) Same assertion the data proxy signs;
|
||||
// fail-quiet keeps the old values when Go is unreachable (the save
|
||||
// itself already succeeded or failed loudly).
|
||||
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
|
||||
if (secret) {
|
||||
try {
|
||||
const assertion = jwt.sign({ uid: token.id, ver: token.ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' })
|
||||
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/me`, {
|
||||
headers: { Authorization: `Bearer ${assertion}` },
|
||||
cache: 'no-store',
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (response.ok) {
|
||||
const u = (await response.json())?.user
|
||||
if (u) {
|
||||
token.name = u.name ?? null
|
||||
token.email = u.email ?? null
|
||||
token.picture = u.image ?? null
|
||||
}
|
||||
}
|
||||
} catch { /* keep the previous identity */ }
|
||||
}
|
||||
}
|
||||
return token
|
||||
},
|
||||
async session({ session, token }) {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// The Superbrain mark (public/superbrain-icon.png, transparent rounded
|
||||
// corners). One component so every brand surface — sidebar, auth pages,
|
||||
// help header — stays in sync with the asset.
|
||||
export function BrandIcon({ className }: { className?: string }) {
|
||||
return <img src="/superbrain-icon.png" alt="" className={cn('shrink-0', className)} />
|
||||
}
|
||||
@@ -74,7 +74,12 @@ export function CalDavSettings() {
|
||||
const openCreate = () => setForm({ ...emptyForm })
|
||||
const openSuggestion = (s: Suggestion) => {
|
||||
const email = session?.user?.email ?? ''
|
||||
setForm({ ...emptyForm, name: s.name, url: s.url, username: email ? email.split('@')[0] : '' })
|
||||
const username = email ? email.split('@')[0] : ''
|
||||
// Nextcloud's DAV roots are per-user (/files/<username>/,
|
||||
// /calendars/<username>/): compose the username into the URL so the
|
||||
// prefill is a working endpoint, not a 404 one level up. The URL shown
|
||||
// is the URL saved; the person can still edit both fields.
|
||||
setForm({ ...emptyForm, name: s.name, username, url: username ? s.url + username + '/' : s.url })
|
||||
}
|
||||
const openEdit = (c: CalDavConnection) => setForm({
|
||||
id: c.id, version: c.version, name: c.name, url: c.url, username: c.username,
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
'use client'
|
||||
|
||||
// Settings → Profile: editable particulars (display name, bio, location,
|
||||
// occupation, organization, website). Values load from GET /api/me — the
|
||||
// Go identity is re-read per request, so this is always the stored truth,
|
||||
// not the login-time NextAuth snapshot. After a save, useSession().update()
|
||||
// re-syncs the session identity (auth.ts jwt "update" trigger) so the top
|
||||
// bar and this header reflect a new name without a re-login.
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useSession } from 'next-auth/react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { User } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
type Profile = {
|
||||
name: string
|
||||
bio: string
|
||||
location: string
|
||||
occupation: string
|
||||
organization: string
|
||||
website: string
|
||||
}
|
||||
|
||||
const EMPTY: Profile = { name: '', bio: '', location: '', occupation: '', organization: '', website: '' }
|
||||
|
||||
function fromUser(u: Record<string, unknown> | null | undefined): Profile {
|
||||
const s = (v: unknown) => (typeof v === 'string' ? v : '')
|
||||
return {
|
||||
name: s(u?.name), bio: s(u?.bio), location: s(u?.location),
|
||||
occupation: s(u?.occupation), organization: s(u?.organization), website: s(u?.website),
|
||||
}
|
||||
}
|
||||
|
||||
export function ProfileSettings() {
|
||||
const { data: session, update } = useSession()
|
||||
const [profile, setProfile] = useState<Profile>(EMPTY)
|
||||
const [baseline, setBaseline] = useState<Profile>(EMPTY)
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/me')
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const p = fromUser(data?.user)
|
||||
setProfile(p)
|
||||
setBaseline(p)
|
||||
})
|
||||
.catch(() => { /* the form stays usable; saving surfaces any outage */ })
|
||||
.finally(() => setLoaded(true))
|
||||
}, [])
|
||||
|
||||
const dirty = loaded && JSON.stringify(profile) !== JSON.stringify(baseline)
|
||||
const set = (key: keyof Profile) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
|
||||
setProfile(p => ({ ...p, [key]: e.target.value }))
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/me', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(profile),
|
||||
})
|
||||
const data = await res.json().catch(() => null)
|
||||
if (res.ok && data) {
|
||||
const p = fromUser(data)
|
||||
setProfile(p)
|
||||
setBaseline(p)
|
||||
toast.success('Profile saved')
|
||||
// Refresh the NextAuth identity so the top bar picks up the name.
|
||||
// The argument matters: in next-auth v5 a bare update() only
|
||||
// re-fetches the session; update({}) POSTs and fires the jwt
|
||||
// callback with trigger="update" (the auth.ts re-sync path).
|
||||
await update({})
|
||||
} else {
|
||||
toast.error(data?.error ?? 'Failed to save')
|
||||
}
|
||||
} catch {
|
||||
toast.error('Failed to save')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const displayName = profile.name || session?.user?.name || session?.user?.email || 'User'
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border p-4 space-y-4">
|
||||
<h3 className="font-medium flex items-center gap-2"><User className="h-4 w-4" /> Profile</h3>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-2xl font-bold text-primary">
|
||||
{displayName[0]?.toUpperCase() ?? '?'}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium truncate">{displayName}</p>
|
||||
<p className="text-sm text-muted-foreground truncate" suppressHydrationWarning>{session?.user?.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your name appears when you share bookmarks, tags and collections with others.
|
||||
Public bookmark links never reveal your identity.
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="col-span-2">
|
||||
<label className="text-xs font-medium text-muted-foreground">Display name</label>
|
||||
<Input value={profile.name} onChange={set('name')} maxLength={120} placeholder="Your name" />
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<label className="text-xs font-medium text-muted-foreground">Bio</label>
|
||||
<Textarea value={profile.bio} onChange={set('bio')} maxLength={280} rows={3} placeholder="A short introduction" />
|
||||
<p className="mt-1 text-right text-xs text-muted-foreground">{profile.bio.length}/280</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground">Location</label>
|
||||
<Input value={profile.location} onChange={set('location')} maxLength={120} placeholder="City, country" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground">Occupation</label>
|
||||
<Input value={profile.occupation} onChange={set('occupation')} maxLength={120} placeholder="Job title" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground">Organization</label>
|
||||
<Input value={profile.organization} onChange={set('organization')} maxLength={120} placeholder="Company or team" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs font-medium text-muted-foreground">Website</label>
|
||||
<Input value={profile.website} onChange={set('website')} maxLength={2048} type="url" placeholder="https://example.com" />
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<label className="text-xs font-medium text-muted-foreground">Email</label>
|
||||
<Input value={session?.user?.email ?? ''} readOnly disabled className="bg-muted" suppressHydrationWarning />
|
||||
<p className="mt-1 text-xs text-muted-foreground">Your sign-in identity; it cannot be changed here.</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={save} loading={saving} disabled={!dirty}>Save profile</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+381
-168
@@ -10,6 +10,7 @@ import { Suspense, useCallback, useEffect, useRef, useState, useSyncExternalStor
|
||||
// identified from the UI alone.
|
||||
const APP_VERSION = process.env.NEXT_PUBLIC_SUPERBRAIN_VERSION || ''
|
||||
import { cn } from '@/lib/utils'
|
||||
import { BrandIcon } from '@/components/brand-icon'
|
||||
import {
|
||||
Calendar, Tags, Users, Kanban, Link2, Settings, ChevronLeft, ChevronRight, ChevronDown,
|
||||
FileText, Pin, PinOff, Plus, Shield, Search, MoreHorizontal, Trash2, Pencil, Layers, GripVertical, X,
|
||||
@@ -23,17 +24,14 @@ import { toast } from 'sonner'
|
||||
import { PAGES_CHANGED, nextUntitledTitle, notifyPagesChanged, type PageSummary } from '@/lib/pages'
|
||||
import { reorderPages } from '@/lib/page-order'
|
||||
|
||||
// Screens below are filters/views over the same bookmark collection, not
|
||||
// separate data types. Pages are the primary interface objects.
|
||||
const viewItems = [
|
||||
{ href: '/bookmarks', label: 'All Bookmarks', icon: Link2 },
|
||||
{ href: '/calendar', label: 'Calendar', icon: Calendar },
|
||||
{ href: '/tags', label: 'Tags', icon: Tags },
|
||||
{ href: '/kanban', label: 'Kanban', icon: Kanban },
|
||||
{ href: '/collections', label: 'Collections', icon: Layers },
|
||||
{ href: '/contacts', label: 'Contacts', icon: Users },
|
||||
{ href: '/trash', label: 'Trash', icon: Trash2 },
|
||||
]
|
||||
// Dragging a page from "Untagged Pages" onto a tag assigns that tag. A custom
|
||||
// MIME keeps this distinct from the page-reorder drag (text/plain + ref).
|
||||
const PAGE_DRAG_MIME = 'application/x-superbrain-page'
|
||||
|
||||
type TagRow = { id: string; name: string; color: string }
|
||||
type ColumnRow = { id: string; label: string; color?: string }
|
||||
type CollectionRow = { id: string; name: string; icon?: string | null }
|
||||
type ContactRow = { id: string; displayName: string }
|
||||
|
||||
// Section collapse state persists per browser. useSyncExternalStore keeps it
|
||||
// hydration-safe (server snapshot uses the default; the client snapshot reads
|
||||
@@ -94,28 +92,29 @@ export function Sidebar({ open, mobileOpen = false, onToggle, onCloseMobile, onQ
|
||||
>
|
||||
<div className="flex items-center gap-2 px-3 py-3">
|
||||
<Link href="/pages" className="flex min-w-0 items-center gap-2">
|
||||
<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-primary text-primary-foreground">
|
||||
<Link2 className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<BrandIcon className="h-6 w-6" />
|
||||
{expanded && <span className="truncate font-display text-sm font-bold tracking-tight">superbrain</span>}
|
||||
</Link>
|
||||
<Button variant="ghost" size="icon-sm" className="ml-auto lg:hidden" onClick={onCloseMobile} aria-label="Close navigation">
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Suspense fallback={<div className="flex-1" />}>
|
||||
<SidebarNav open={expanded} pathname={pathname} isAdmin={isAdmin} />
|
||||
</Suspense>
|
||||
<div className="space-y-0.5 border-t p-2">
|
||||
{/* Quick find sits at the top of the sidebar for one-tap access. */}
|
||||
<div className="px-2 pb-1">
|
||||
<button
|
||||
onClick={onQuickFind}
|
||||
title="Quick find (Ctrl/⌘ K)"
|
||||
className="flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
|
||||
className="flex w-full items-center gap-2 rounded-lg border border-border/60 bg-muted/40 px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
>
|
||||
<Search className="h-4 w-4 shrink-0" />
|
||||
{expanded && <span className="flex-1 text-left">Quick find</span>}
|
||||
{expanded && <kbd className="rounded border bg-background px-1 text-[10px] font-medium text-muted-foreground">⌘K</kbd>}
|
||||
</button>
|
||||
</div>
|
||||
<Suspense fallback={<div className="flex-1" />}>
|
||||
<SidebarNav open={expanded} pathname={pathname} isAdmin={isAdmin} />
|
||||
</Suspense>
|
||||
<div className="space-y-0.5 border-t p-2">
|
||||
<Link
|
||||
href="/settings"
|
||||
className={cn(
|
||||
@@ -139,14 +138,12 @@ export function Sidebar({ open, mobileOpen = false, onToggle, onCloseMobile, onQ
|
||||
)
|
||||
}
|
||||
|
||||
function SectionHeader({ label, open, expanded, onToggle, action }: {
|
||||
function GroupHeader({ label, expanded, onToggle, action }: {
|
||||
label: string
|
||||
open: boolean
|
||||
expanded: boolean
|
||||
onToggle: () => void
|
||||
action?: { label: string; onClick: () => void }
|
||||
}) {
|
||||
if (!open) return null
|
||||
return (
|
||||
<div className="group/header flex items-center gap-0.5 rounded-md pr-1 hover:bg-accent/40">
|
||||
<button onClick={onToggle} className="flex flex-1 items-center gap-1 px-2 py-1 text-left" aria-expanded={expanded}>
|
||||
@@ -167,15 +164,110 @@ function SectionHeader({ label, open, expanded, onToggle, action }: {
|
||||
)
|
||||
}
|
||||
|
||||
// A collapsible sub-section: caret + icon + label (optionally a link) + count,
|
||||
// with an indented child list when expanded.
|
||||
function NavSection({ icon: Icon, label, href, expanded, onToggle, count, children }: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
href?: string
|
||||
expanded: boolean
|
||||
onToggle: () => void
|
||||
count?: number
|
||||
children?: React.ReactNode
|
||||
}) {
|
||||
const inner = (
|
||||
<>
|
||||
<Icon className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{count != null && <span className="ml-auto text-[10px] text-muted-foreground/70">{count}</span>}
|
||||
</>
|
||||
)
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-1 rounded-lg pr-1 hover:bg-accent/40">
|
||||
<button onClick={onToggle} aria-expanded={expanded} aria-label={`${expanded ? 'Collapse' : 'Expand'} ${label}`} className="shrink-0 rounded p-1 text-muted-foreground hover:text-foreground">
|
||||
<ChevronDown className={cn('h-3 w-3 transition-transform', !expanded && '-rotate-90')} />
|
||||
</button>
|
||||
{href ? (
|
||||
<Link href={href} className="flex min-w-0 flex-1 items-center gap-2 px-1 py-1.5 text-sm text-muted-foreground hover:text-foreground">{inner}</Link>
|
||||
) : (
|
||||
<button onClick={onToggle} className="flex min-w-0 flex-1 items-center gap-2 px-1 py-1.5 text-sm text-muted-foreground hover:text-foreground">{inner}</button>
|
||||
)}
|
||||
</div>
|
||||
{expanded && <div className="ml-3 space-y-0.5 border-l border-border/40 pl-2">{children}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NavLink({ href, icon: Icon, label, active }: {
|
||||
href: string
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
active?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm transition-colors',
|
||||
active ? 'bg-accent font-medium text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
function ChildLink({ href, label, dot, active, onDragOver, onDragLeave, onDrop, highlight }: {
|
||||
href: string
|
||||
label: string
|
||||
dot?: string
|
||||
active?: boolean
|
||||
onDragOver?: (e: React.DragEvent) => void
|
||||
onDragLeave?: (e: React.DragEvent) => void
|
||||
onDrop?: (e: React.DragEvent) => void
|
||||
highlight?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
onDragOver={onDragOver}
|
||||
onDragLeave={onDragLeave}
|
||||
onDrop={onDrop}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground',
|
||||
active && 'bg-accent/60 font-medium text-accent-foreground',
|
||||
highlight && 'bg-accent/40 ring-1 ring-primary/60'
|
||||
)}
|
||||
>
|
||||
{dot && <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: dot }} />}
|
||||
<span className="truncate">{label}</span>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathname: string; isAdmin?: boolean }) {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [pages, setPages] = useState<PageSummary[]>([])
|
||||
const [tags, setTags] = useState<TagRow[]>([])
|
||||
const [columns, setColumns] = useState<ColumnRow[]>([])
|
||||
const [collections, setCollections] = useState<CollectionRow[]>([])
|
||||
const [contacts, setContacts] = useState<ContactRow[]>([])
|
||||
const [pagesExpanded, setPagesExpanded] = usePersistentState('superbrain:sidebar:pages', true)
|
||||
const [viewsExpanded, setViewsExpanded] = usePersistentState('superbrain:sidebar:views', true)
|
||||
const [bookmarksExpanded, setBookmarksExpanded] = usePersistentState('superbrain:sidebar:bookmarks', true)
|
||||
const [allPagesExpanded, setAllPagesExpanded] = usePersistentState('superbrain:sidebar:allpages', true)
|
||||
const [pinnedExpanded, setPinnedExpanded] = usePersistentState('superbrain:sidebar:pinned', false)
|
||||
const [untaggedExpanded, setUntaggedExpanded] = usePersistentState('superbrain:sidebar:untagged', false)
|
||||
const [tagsExpanded, setTagsExpanded] = usePersistentState('superbrain:sidebar:tags', false)
|
||||
const [kanbanExpanded, setKanbanExpanded] = usePersistentState('superbrain:sidebar:kanban', false)
|
||||
const [collectionsExpanded, setCollectionsExpanded] = usePersistentState('superbrain:sidebar:collections', false)
|
||||
const [contactsExpanded, setContactsExpanded] = usePersistentState('superbrain:sidebar:contacts', false)
|
||||
const [renamingId, setRenamingId] = useState<string | null>(null)
|
||||
const [renameValue, setRenameValue] = useState('')
|
||||
const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null)
|
||||
const [tagDrop, setTagDrop] = useState<string | null>(null)
|
||||
const [collapsedPages, setCollapsedPages] = useState<Set<string>>(() => new Set())
|
||||
const draggedPageRef = useRef<string | null>(null)
|
||||
const activePageId = pathname === '/pages' ? searchParams.get('id') : null
|
||||
@@ -193,6 +285,16 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
|
||||
return () => window.removeEventListener(PAGES_CHANGED, load)
|
||||
}, [load])
|
||||
|
||||
// The Bookmarks group's carets list live entities; load them once alongside
|
||||
// pages so expanding a caret is instant.
|
||||
useEffect(() => {
|
||||
const get = (path: string) => fetch(path).then((r) => (r.ok ? r.json() : [])).catch(() => [])
|
||||
get('/api/tags').then((d) => setTags(Array.isArray(d) ? d : []))
|
||||
get('/api/kanban/columns').then((d) => setColumns(Array.isArray(d) ? d : []))
|
||||
get('/api/collections').then((d) => setCollections(Array.isArray(d) ? d : []))
|
||||
get('/api/contacts').then((d) => setContacts(Array.isArray(d) ? d : []))
|
||||
}, [])
|
||||
|
||||
const createPage = async (parentId?: string | null) => {
|
||||
const title = nextUntitledTitle(pages.map((p) => p.title))
|
||||
try {
|
||||
@@ -266,6 +368,19 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
|
||||
if (next) void savePageOrder(next)
|
||||
}
|
||||
|
||||
// Drag-a-page-onto-a-tag: assign the tag, then refresh so the page leaves
|
||||
// the "Untagged" list.
|
||||
const assignTag = async (pageId: string, tagId: string) => {
|
||||
try {
|
||||
const res = await fetch(`/api/pages/${pageId}/tags`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tagId }),
|
||||
})
|
||||
if (!res.ok) { toast.error('Could not tag page'); return }
|
||||
toast.success('Page tagged')
|
||||
load()
|
||||
} catch { toast.error('Could not tag page') }
|
||||
}
|
||||
|
||||
const toggleCollapsed = (id: string) => {
|
||||
setCollapsedPages((current) => {
|
||||
const next = new Set(current)
|
||||
@@ -306,162 +421,260 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
|
||||
}
|
||||
}
|
||||
|
||||
const viewEntries = isAdmin ? [...viewItems, { href: '/admin', label: 'Admin', icon: Shield }] : viewItems
|
||||
const pinnedPages = pages.filter((p) => p.pinned)
|
||||
const untaggedPages = pages.filter((p) => !(p.tags && p.tags.length))
|
||||
|
||||
// Collapsed desktop rail: a flat icon list (grouping is an expanded affordance).
|
||||
if (!open) {
|
||||
const rail = [
|
||||
{ href: '/pages', icon: FileText, label: 'Pages' },
|
||||
{ href: '/bookmarks', icon: Link2, label: 'All Bookmarks' },
|
||||
{ href: '/calendar', icon: Calendar, label: 'Calendar' },
|
||||
{ href: '/tags', icon: Tags, label: 'Tags' },
|
||||
{ href: '/kanban', icon: Kanban, label: 'Kanban' },
|
||||
{ href: '/collections', icon: Layers, label: 'Collections' },
|
||||
{ href: '/contacts', icon: Users, label: 'Contacts' },
|
||||
{ href: '/trash', icon: Trash2, label: 'Trash' },
|
||||
...(isAdmin ? [{ href: '/admin', icon: Shield, label: 'Admin' }] : []),
|
||||
]
|
||||
return (
|
||||
<nav className="flex-1 space-y-0.5 overflow-y-auto p-2">
|
||||
{rail.map((it) => (
|
||||
<Link
|
||||
key={it.href}
|
||||
href={it.href}
|
||||
title={it.label}
|
||||
aria-label={it.label}
|
||||
className={cn('flex items-center justify-center rounded-lg px-2 py-1.5', pathname === it.href ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground')}
|
||||
>
|
||||
<it.icon className="h-4 w-4" />
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="flex-1 space-y-0.5 overflow-y-auto p-2">
|
||||
<SectionHeader label="Pages" open={open} expanded={pagesExpanded} onToggle={() => setPagesExpanded(!pagesExpanded)} action={{ label: 'New page', onClick: () => void createPage() }} />
|
||||
{(pagesExpanded || !open) && pageRows.map(({ page: p, depth, hasChildren }) => {
|
||||
const isActive = pathname === '/pages' && activePageId === p.id
|
||||
if (renamingId === p.id) {
|
||||
return (
|
||||
<div key={p.id} className="px-1 py-0.5" style={{ paddingLeft: depth * 12 }}>
|
||||
<Input
|
||||
autoFocus
|
||||
value={renameValue}
|
||||
onChange={(e) => setRenameValue(e.target.value)}
|
||||
onBlur={() => commitRename(p)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); (e.target as HTMLInputElement).blur() }
|
||||
if (e.key === 'Escape') setRenamingId(null)
|
||||
}}
|
||||
className="h-7 text-sm"
|
||||
aria-label={`Rename page ${p.title}`}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={p.id}
|
||||
data-page-id={p.id}
|
||||
onDragOver={(e) => {
|
||||
// Event handler, not render: reading the drag source is safe.
|
||||
// eslint-disable-next-line react-hooks/refs
|
||||
if (!draggedPageRef.current || draggedPageRef.current === p.id) return
|
||||
e.preventDefault()
|
||||
e.dataTransfer.dropEffect = 'move'
|
||||
const rect = e.currentTarget.getBoundingClientRect()
|
||||
setPageDrop({ id: p.id, after: e.clientY > rect.top + rect.height / 2 })
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setPageDrop(null)
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault()
|
||||
const rect = e.currentTarget.getBoundingClientRect()
|
||||
// Event handler, not render: reading the drag source is safe.
|
||||
// eslint-disable-next-line react-hooks/refs
|
||||
dropPage(draggedPageRef.current, p, e.clientY > rect.top + rect.height / 2)
|
||||
}}
|
||||
style={{ paddingLeft: depth * 12 }}
|
||||
className={cn(
|
||||
'group/row flex items-center rounded-lg pr-1 transition-colors',
|
||||
isActive ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',
|
||||
pageDrop?.id === p.id && 'ring-1 ring-primary/50'
|
||||
)}
|
||||
>
|
||||
{open && (hasChildren ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleCollapsed(p.id)}
|
||||
aria-label={collapsedPages.has(p.id) ? `Expand ${p.title}` : `Collapse ${p.title}`}
|
||||
aria-expanded={!collapsedPages.has(p.id)}
|
||||
className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<ChevronDown className={cn('h-3 w-3 transition-transform', collapsedPages.has(p.id) && '-rotate-90')} />
|
||||
</button>
|
||||
) : <span className="w-4 shrink-0" aria-hidden />)}
|
||||
{open && (
|
||||
<span
|
||||
data-page-drag-handle
|
||||
<GroupHeader label="Pages" expanded={pagesExpanded} onToggle={() => setPagesExpanded(!pagesExpanded)} action={{ label: 'New page', onClick: () => void createPage() }} />
|
||||
{pagesExpanded && (
|
||||
<>
|
||||
<NavSection icon={FileText} label="All Pages" href="/pages" expanded={allPagesExpanded} onToggle={() => setAllPagesExpanded(!allPagesExpanded)} count={pages.length}>
|
||||
{pageRows.map(({ page: p, depth, hasChildren }) => {
|
||||
const isActive = pathname === '/pages' && activePageId === p.id
|
||||
if (renamingId === p.id) {
|
||||
return (
|
||||
<div key={p.id} className="px-1 py-0.5" style={{ paddingLeft: depth * 12 }}>
|
||||
<Input
|
||||
autoFocus
|
||||
value={renameValue}
|
||||
onChange={(e) => setRenameValue(e.target.value)}
|
||||
onBlur={() => commitRename(p)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); (e.target as HTMLInputElement).blur() }
|
||||
if (e.key === 'Escape') setRenamingId(null)
|
||||
}}
|
||||
className="h-7 text-sm"
|
||||
aria-label={`Rename page ${p.title}`}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={p.id}
|
||||
data-page-id={p.id}
|
||||
onDragOver={(e) => {
|
||||
// Event handler, not render: reading the drag source is safe.
|
||||
// eslint-disable-next-line react-hooks/refs
|
||||
if (!draggedPageRef.current || draggedPageRef.current === p.id) return
|
||||
e.preventDefault()
|
||||
e.dataTransfer.dropEffect = 'move'
|
||||
const rect = e.currentTarget.getBoundingClientRect()
|
||||
setPageDrop({ id: p.id, after: e.clientY > rect.top + rect.height / 2 })
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setPageDrop(null)
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault()
|
||||
const rect = e.currentTarget.getBoundingClientRect()
|
||||
// Event handler, not render: reading the drag source is safe.
|
||||
// eslint-disable-next-line react-hooks/refs
|
||||
dropPage(draggedPageRef.current, p, e.clientY > rect.top + rect.height / 2)
|
||||
}}
|
||||
style={{ paddingLeft: depth * 12 }}
|
||||
className={cn(
|
||||
'group/row flex items-center rounded-lg pr-1 transition-colors',
|
||||
isActive ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',
|
||||
pageDrop?.id === p.id && 'ring-1 ring-primary/50'
|
||||
)}
|
||||
>
|
||||
{hasChildren ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleCollapsed(p.id)}
|
||||
aria-label={collapsedPages.has(p.id) ? `Expand ${p.title}` : `Collapse ${p.title}`}
|
||||
aria-expanded={!collapsedPages.has(p.id)}
|
||||
className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<ChevronDown className={cn('h-3 w-3 transition-transform', collapsedPages.has(p.id) && '-rotate-90')} />
|
||||
</button>
|
||||
) : <span className="w-4 shrink-0" aria-hidden />}
|
||||
<span
|
||||
data-page-drag-handle
|
||||
draggable
|
||||
onDragStart={(e) => {
|
||||
draggedPageRef.current = p.id
|
||||
e.dataTransfer.effectAllowed = 'move'
|
||||
e.dataTransfer.setData('text/plain', p.id)
|
||||
}}
|
||||
onDragEnd={() => { draggedPageRef.current = null; setPageDrop(null) }}
|
||||
className="ml-1 shrink-0 cursor-grab text-muted-foreground/40 opacity-0 transition-opacity hover:text-muted-foreground active:cursor-grabbing group-hover/row:opacity-100 focus-visible:opacity-100"
|
||||
title="Drag to reorder page"
|
||||
aria-label={`Drag page ${p.title}`}
|
||||
>
|
||||
<GripVertical className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
<Link href={`/pages?id=${p.id}`} className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-sm">
|
||||
{p.pinned ? <Pin className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
|
||||
<span className={cn('truncate', isActive ? 'font-medium' : 'text-muted-foreground')}>{p.title}</span>
|
||||
</Link>
|
||||
<div className="flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover/row:opacity-100">
|
||||
<button
|
||||
onClick={() => void createPage(p.id)}
|
||||
title="New subpage"
|
||||
aria-label={`New subpage under ${p.title}`}
|
||||
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button title="Page actions" aria-label={`Actions for ${p.title}`} className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground">
|
||||
<MoreHorizontal className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-44">
|
||||
<DropdownMenuItem onClick={() => patchPage(p.id, { pinned: !p.pinned })}>
|
||||
{p.pinned ? <PinOff className="mr-2 h-3.5 w-3.5" /> : <Pin className="mr-2 h-3.5 w-3.5" />}
|
||||
{p.pinned ? 'Unpin' : 'Pin to sidebar'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => startRename(p)}>
|
||||
<Pencil className="mr-2 h-3.5 w-3.5" />
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => void createPage(p.id)}>
|
||||
<Plus className="mr-2 h-3.5 w-3.5" />
|
||||
New subpage
|
||||
</DropdownMenuItem>
|
||||
{p.parentId && (
|
||||
<DropdownMenuItem onClick={() => patchPage(p.id, { parentId: null })}>
|
||||
<ChevronRight className="mr-2 h-3.5 w-3.5" />
|
||||
Move to top level
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => removePage(p)}>
|
||||
<Trash2 className="mr-2 h-3.5 w-3.5" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{pages.length === 0 && <p className="px-3 py-1 text-xs text-muted-foreground/70">No pages yet</p>}
|
||||
</NavSection>
|
||||
|
||||
<NavSection icon={Pin} label="Pinned Pages" expanded={pinnedExpanded} onToggle={() => setPinnedExpanded(!pinnedExpanded)} count={pinnedPages.length}>
|
||||
{pinnedPages.map((p) => (
|
||||
<ChildLink key={p.id} href={`/pages?id=${p.id}`} label={p.title} active={pathname === '/pages' && activePageId === p.id} />
|
||||
))}
|
||||
{pinnedPages.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No pinned pages</p>}
|
||||
</NavSection>
|
||||
|
||||
<NavSection icon={FileText} label="Untagged Pages" expanded={untaggedExpanded} onToggle={() => setUntaggedExpanded(!untaggedExpanded)} count={untaggedPages.length}>
|
||||
{untaggedPages.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
draggable
|
||||
onDragStart={(e) => {
|
||||
draggedPageRef.current = p.id
|
||||
e.dataTransfer.effectAllowed = 'move'
|
||||
e.dataTransfer.setData('text/plain', p.id)
|
||||
e.dataTransfer.setData(PAGE_DRAG_MIME, p.id)
|
||||
e.dataTransfer.effectAllowed = 'copy'
|
||||
}}
|
||||
onDragEnd={() => { draggedPageRef.current = null; setPageDrop(null) }}
|
||||
className="ml-1 shrink-0 cursor-grab text-muted-foreground/40 opacity-0 transition-opacity hover:text-muted-foreground active:cursor-grabbing group-hover/row:opacity-100 focus-visible:opacity-100"
|
||||
title="Drag to reorder page"
|
||||
aria-label={`Drag page ${p.title}`}
|
||||
className="group/un flex cursor-grab items-center rounded-md active:cursor-grabbing"
|
||||
title={`Drag ${p.title} onto a tag to tag it`}
|
||||
>
|
||||
<GripVertical className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
)}
|
||||
<Link href={`/pages?id=${p.id}`} className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-sm">
|
||||
{p.pinned ? <Pin className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
|
||||
{(open || isActive) && <span className={cn('truncate', isActive ? 'font-medium' : 'text-muted-foreground')}>{p.title}</span>}
|
||||
</Link>
|
||||
{open && (
|
||||
<div className="flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover/row:opacity-100">
|
||||
<button
|
||||
onClick={() => void createPage(p.id)}
|
||||
title="New subpage"
|
||||
aria-label={`New subpage under ${p.title}`}
|
||||
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button title="Page actions" aria-label={`Actions for ${p.title}`} className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground">
|
||||
<MoreHorizontal className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-44">
|
||||
<DropdownMenuItem onClick={() => patchPage(p.id, { pinned: !p.pinned })}>
|
||||
{p.pinned ? <PinOff className="mr-2 h-3.5 w-3.5" /> : <Pin className="mr-2 h-3.5 w-3.5" />}
|
||||
{p.pinned ? 'Unpin' : 'Pin to sidebar'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => startRename(p)}>
|
||||
<Pencil className="mr-2 h-3.5 w-3.5" />
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => void createPage(p.id)}>
|
||||
<Plus className="mr-2 h-3.5 w-3.5" />
|
||||
New subpage
|
||||
</DropdownMenuItem>
|
||||
{p.parentId && (
|
||||
<DropdownMenuItem onClick={() => patchPage(p.id, { parentId: null })}>
|
||||
<ChevronRight className="mr-2 h-3.5 w-3.5" />
|
||||
Move to top level
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => removePage(p)}>
|
||||
<Trash2 className="mr-2 h-3.5 w-3.5" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<GripVertical className="h-3 w-3 shrink-0 text-muted-foreground/40 opacity-0 group-hover/un:opacity-100" />
|
||||
<Link href={`/pages?id=${p.id}`} className="flex min-w-0 flex-1 items-center gap-2 px-1 py-1 text-sm text-muted-foreground hover:text-foreground">
|
||||
<FileText className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="truncate">{p.title}</span>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{open && pagesExpanded && pages.length === 0 && (
|
||||
<p className="px-3 py-1 text-xs text-muted-foreground/70">No pages yet</p>
|
||||
))}
|
||||
{untaggedPages.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">Every page has a tag</p>}
|
||||
</NavSection>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="pt-2">
|
||||
<SectionHeader label="Views" open={open} expanded={viewsExpanded} onToggle={() => setViewsExpanded(!viewsExpanded)} />
|
||||
{(viewsExpanded || !open) && viewEntries.map((item) => {
|
||||
const isActive = pathname === item.href || pathname?.startsWith(item.href + '/')
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm transition-colors',
|
||||
isActive ? 'bg-accent font-medium text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
<item.icon className="h-4 w-4 shrink-0" />
|
||||
{open && <span className="truncate">{item.label}</span>}
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
<GroupHeader label="Bookmarks" expanded={bookmarksExpanded} onToggle={() => setBookmarksExpanded(!bookmarksExpanded)} />
|
||||
{bookmarksExpanded && (
|
||||
<>
|
||||
<NavLink href="/bookmarks" icon={Link2} label="All Bookmarks" active={pathname === '/bookmarks'} />
|
||||
<NavLink href="/calendar" icon={Calendar} label="Calendar" active={pathname === '/calendar'} />
|
||||
<NavSection icon={Tags} label="Tags" href="/tags" expanded={tagsExpanded} onToggle={() => setTagsExpanded(!tagsExpanded)} count={tags.length}>
|
||||
{tags.map((t) => (
|
||||
<ChildLink
|
||||
key={t.id}
|
||||
href={`/tags?tag=${t.id}`}
|
||||
label={t.name}
|
||||
dot={t.color}
|
||||
highlight={tagDrop === t.id}
|
||||
onDragOver={(e) => {
|
||||
if (e.dataTransfer.types.includes(PAGE_DRAG_MIME)) {
|
||||
e.preventDefault()
|
||||
e.dataTransfer.dropEffect = 'copy'
|
||||
setTagDrop(t.id)
|
||||
}
|
||||
}}
|
||||
onDragLeave={() => setTagDrop(null)}
|
||||
onDrop={(e) => {
|
||||
const pid = e.dataTransfer.getData(PAGE_DRAG_MIME)
|
||||
setTagDrop(null)
|
||||
if (pid) { e.preventDefault(); void assignTag(pid, t.id) }
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{tags.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No tags yet</p>}
|
||||
</NavSection>
|
||||
<NavSection icon={Kanban} label="Kanban" href="/kanban" expanded={kanbanExpanded} onToggle={() => setKanbanExpanded(!kanbanExpanded)} count={columns.length}>
|
||||
{columns.map((c) => (
|
||||
<ChildLink key={c.id} href={`/kanban?column=${c.id}`} label={c.label} dot={c.color} />
|
||||
))}
|
||||
{columns.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No columns yet</p>}
|
||||
</NavSection>
|
||||
<NavSection icon={Layers} label="Collections" href="/collections" expanded={collectionsExpanded} onToggle={() => setCollectionsExpanded(!collectionsExpanded)} count={collections.length}>
|
||||
{collections.map((c) => (
|
||||
<ChildLink key={c.id} href={`/collections?id=${c.id}`} label={c.name} />
|
||||
))}
|
||||
{collections.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No collections yet</p>}
|
||||
</NavSection>
|
||||
<NavSection icon={Users} label="Contacts" href="/contacts" expanded={contactsExpanded} onToggle={() => setContactsExpanded(!contactsExpanded)} count={contacts.length}>
|
||||
{contacts.map((c) => (
|
||||
<ChildLink key={c.id} href={`/contacts?open=${c.id}`} label={c.displayName} />
|
||||
))}
|
||||
{contacts.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No contacts yet</p>}
|
||||
</NavSection>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<NavLink href="/trash" icon={Trash2} label="Trash" active={pathname === '/trash'} />
|
||||
{isAdmin && <NavLink href="/admin" icon={Shield} label="Admin" active={pathname === '/admin'} />}
|
||||
</div>
|
||||
</nav>
|
||||
)
|
||||
|
||||
@@ -72,7 +72,12 @@ export function WebdavSettings() {
|
||||
const openCreate = () => setForm({ ...emptyForm })
|
||||
const openSuggestion = (s: Suggestion) => {
|
||||
const email = session?.user?.email ?? ''
|
||||
setForm({ ...emptyForm, name: s.name, url: s.url, username: email ? email.split('@')[0] : '' })
|
||||
const username = email ? email.split('@')[0] : ''
|
||||
// Nextcloud's DAV roots are per-user (/files/<username>/,
|
||||
// /calendars/<username>/): compose the username into the URL so the
|
||||
// prefill is a working endpoint, not a 404 one level up. The URL shown
|
||||
// is the URL saved; the person can still edit both fields.
|
||||
setForm({ ...emptyForm, name: s.name, username, url: username ? s.url + username + '/' : s.url })
|
||||
}
|
||||
const openEdit = (c: WebdavConnection) => setForm({
|
||||
id: c.id, version: c.version, name: c.name, url: c.url, username: c.username,
|
||||
|
||||
@@ -15,6 +15,7 @@ export type PageSummary = {
|
||||
pinned: boolean
|
||||
position: number
|
||||
parentId: string | null
|
||||
tags?: { tag: { id: string; name: string; color: string } }[]
|
||||
_count?: { bookmarks: number; children?: number }
|
||||
}
|
||||
|
||||
|
||||
+33
-8
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 548 B After Width: | Height: | Size: 21 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 72 KiB After Width: | Height: | Size: 247 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.1 MiB |
Reference in New Issue
Block a user