Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6bb68ef323 | ||
|
|
5684757d24 | ||
|
|
2dc128a215 | ||
|
|
4ccedd1a03 | ||
|
|
e8f04a4082 | ||
|
|
d4a2ca0d0d | ||
|
|
47e0272d6c | ||
|
|
a402e4f2e7 | ||
|
|
eca8aeb113 | ||
|
|
f6158f58b5 | ||
|
|
7a7e77e039 | ||
|
|
ef69be6320 | ||
|
|
7f64cbae0b | ||
|
|
46d9044f53 | ||
|
|
da70346e45 | ||
|
|
e3d765e97b | ||
|
|
78231502f1 | ||
|
|
212d587f97 | ||
|
|
ceb4973359 | ||
|
|
200013960b | ||
|
|
a8cc95cfae | ||
|
|
298cc4efd6 | ||
|
|
35c0f5f6a3 | ||
|
|
15556239f4 | ||
|
|
3fe953c14d |
@@ -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")
|
||||
|
||||
|
||||
+137
-1
@@ -3,9 +3,145 @@
|
||||
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.2 — 2026-11-22
|
||||
|
||||
### Changed
|
||||
- **Accurate module identity**: the Go module is now
|
||||
`gitea.federated.computer/Federated_Computer/brain` — the real repository —
|
||||
instead of the placeholder `github.com/andrew/superbrain`. All internal
|
||||
imports, the agent's outbound User-Agent contact URL and the README/RUNNING
|
||||
clone URLs point at the Gitea repo. Pure identifier rename with no runtime
|
||||
behavior change; verified with the full gate (unit + database integration
|
||||
under `-race`, schema convergence and migration atomicity, web
|
||||
lint/SSR/build, browser regressions, and e2e against the rebuilt stack).
|
||||
|
||||
## 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
|
||||
- **Mobile-friendly UI**: Superbrain now works properly on phones. The
|
||||
sidebar becomes a slide-in drawer (hamburger in the top bar, closes when
|
||||
you navigate); the bookmarks table becomes tappable cards; Collections,
|
||||
Tags and Contacts switch to a list-then-detail flow with a Back button;
|
||||
the Settings tab strip scrolls instead of overflowing; kanban columns fit
|
||||
the screen with a peek of the next one; dialogs scroll within the viewport
|
||||
instead of clipping. Desktop layouts are unchanged.
|
||||
- Fixed the viewport configuration so responsive layouts actually engage on
|
||||
phones, and a connector-settings bug where the action buttons squeezed the
|
||||
connection name out of view on small screens.
|
||||
|
||||
## 1.2.12 — 2026-11-16
|
||||
|
||||
### Added
|
||||
|
||||
@@ -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,
|
||||
@@ -33,7 +38,7 @@ Details: [web/docs/AUTHELIA.md](web/docs/AUTHELIA.md) §7.
|
||||
Requires Docker with Compose v2 or newer. On a new installation:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/andrewthecodertx/superbrain.git
|
||||
git clone https://gitea.federated.computer/Federated_Computer/brain.git
|
||||
cd superbrain
|
||||
cp .env.example .env
|
||||
docker run --rm node:22-alpine node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
|
||||
@@ -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:
|
||||
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ Both commands should succeed. On Windows, Docker must be using Linux containers.
|
||||
## 1. Download the app
|
||||
|
||||
```sh
|
||||
git clone https://github.com/andrewthecodertx/superbrain.git
|
||||
git clone https://gitea.federated.computer/Federated_Computer/brain.git
|
||||
cd superbrain
|
||||
```
|
||||
|
||||
|
||||
@@ -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.12"
|
||||
SUPERBRAIN_IMAGE_VERSION="0.3.2"
|
||||
|
||||
# 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.12
|
||||
VERSION=0.3.2
|
||||
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).
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
module github.com/andrew/superbrain
|
||||
module gitea.federated.computer/Federated_Computer/brain
|
||||
|
||||
go 1.26.0
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/andrew/superbrain/internal/ai"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/ai"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// ErrCompileRejected means the model could not (or refused to) express the
|
||||
|
||||
@@ -14,13 +14,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/ai"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/mailer"
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"github.com/andrew/superbrain/internal/notify"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/ai"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/mailer"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/notify"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
"net"
|
||||
)
|
||||
|
||||
@@ -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":
|
||||
@@ -405,7 +407,7 @@ func fetchText(ctx context.Context, rawurl string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("User-Agent", "Superbrain-agent/1.0 (+https://github.com/andrew/superbrain)")
|
||||
req.Header.Set("User-Agent", "Superbrain-agent/1.0 (+https://gitea.federated.computer/Federated_Computer/brain)")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/json;q=0.9,text/plain;q=0.8")
|
||||
res, err := fetchClient.Do(req)
|
||||
if err != nil {
|
||||
|
||||
+6
-6
@@ -33,12 +33,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/entitlements"
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/entitlements"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
// DefaultModel is the fallback for the server env config (OpenRouter free
|
||||
|
||||
@@ -30,7 +30,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -3,8 +3,8 @@ package auth
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
@@ -3,9 +3,9 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/models"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/models"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
@@ -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) {
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
|
||||
@@ -25,15 +25,16 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/mailer"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/mailer"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -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()
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"net"
|
||||
"net/http"
|
||||
"sort"
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,10 +4,10 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/handlers"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/handlers"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -29,7 +29,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
)
|
||||
|
||||
// Conn is the dial-relevant projection of a stored CalDavConnection row plus
|
||||
|
||||
@@ -11,10 +11,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -31,7 +31,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
)
|
||||
|
||||
// Conn is the dial-relevant projection of a stored CardDavConnection row
|
||||
|
||||
@@ -10,10 +10,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/entitlements"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/entitlements"
|
||||
)
|
||||
|
||||
// Tenancy phase 1 (DESIGN_TENANCY_ENTITLEMENTS.md): every user belongs to
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/models"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/models"
|
||||
)
|
||||
|
||||
type UserRepo struct{ db *DB }
|
||||
@@ -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) {
|
||||
|
||||
@@ -14,10 +14,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/agent"
|
||||
"github.com/andrew/superbrain/internal/ai"
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/agent"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/ai"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// compileLimiter bounds NL compilations per user (each one is an LLM call).
|
||||
|
||||
@@ -19,13 +19,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/agent"
|
||||
"github.com/andrew/superbrain/internal/ai"
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/entitlements"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/agent"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/ai"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/entitlements"
|
||||
)
|
||||
|
||||
// aiKeyMask mirrors the notification-channel mask: write-only secrets.
|
||||
|
||||
@@ -20,8 +20,8 @@ import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// maxAPIKeys caps live keys per user — a product limit against credential
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/markdown"
|
||||
"github.com/andrew/superbrain/internal/preview"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/markdown"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/preview"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -22,12 +22,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/caldav"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/caldav"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -27,13 +27,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/carddav"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/carddav"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"math"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"io"
|
||||
"log"
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// Structured export (trust phase): a single owner-scoped JSON archive that is
|
||||
|
||||
@@ -2,8 +2,8 @@ package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/kanban"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/kanban"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -23,12 +23,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/mcpclient"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/mcpclient"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -5,12 +5,12 @@ import (
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"github.com/andrew/superbrain/internal/signals"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/signals"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"sort"
|
||||
@@ -18,10 +19,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/notify"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/notify"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
// errPlanGate answers 403 for features the tenant's plan does not include.
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// Connected pages (Notion-like upgrades phase 3).
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// Page revision history (trust phase). Every committed content version gets
|
||||
|
||||
@@ -3,8 +3,8 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/markdown"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/markdown"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -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"
|
||||
|
||||
"gitea.federated.computer/Federated_Computer/brain/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"],
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"github.com/andrew/superbrain/internal/signals"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/signals"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -2,7 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// Recoverable deletions (trust phase).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
|
||||
@@ -25,12 +25,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"github.com/andrew/superbrain/internal/webdav"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/webdav"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// machineReq calls the API with an API-key Bearer header and no cookies —
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/scripts"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/scripts"
|
||||
)
|
||||
|
||||
// AUTH_MODE=oidc (core/federated shape): Authelia exclusively. Password
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// fakeCaldav is a mutable RFC 4791 server for integration tests: a home at
|
||||
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/signals"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/signals"
|
||||
"github.com/emersion/go-imap/backend/memory"
|
||||
imapserver "github.com/emersion/go-imap/server"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
@@ -3,10 +3,10 @@ package http
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
|
||||
@@ -3,8 +3,8 @@ package http
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/signals"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/signals"
|
||||
"github.com/emersion/go-imap/backend/memory"
|
||||
imapserver "github.com/emersion/go-imap/server"
|
||||
"io"
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/notify"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/notify"
|
||||
)
|
||||
|
||||
// fakeWebhook captures one Slack-style POST for the delivery tests.
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/notify"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/notify"
|
||||
)
|
||||
|
||||
// fakeSignalBridge mimics a signal-cli REST bridge: POST /v2/send?account=...
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// fakeSMTP is a minimal loopback SMTP relay: it speaks just enough of the
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"github.com/andrew/superbrain/internal/scripts"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/scripts"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"os"
|
||||
|
||||
+15
-6
@@ -6,12 +6,12 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/authguard"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/handlers"
|
||||
"github.com/andrew/superbrain/internal/oidc"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/auth"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/authguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/handlers"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/oidc"
|
||||
)
|
||||
|
||||
// NewServer builds the HTTP server with all routes registered.
|
||||
@@ -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.
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/entitlements"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/entitlements"
|
||||
)
|
||||
|
||||
// Tenancy phase 1: every account-creation path lands the user in the
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.federated.computer/Federated_Computer/brain/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])
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/entitlements"
|
||||
"github.com/andrew/superbrain/internal/webdav"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/entitlements"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/webdav"
|
||||
)
|
||||
|
||||
// fakeShare is a mutable minimal RFC 4918 server (Basic-auth erwin/s3cret)
|
||||
|
||||
@@ -3,7 +3,7 @@ package kanban
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
var DefaultColumns = []struct{ Label, Color, Key string }{{"Inbox", "#64748b", "INBOX"}, {"To Do", "#3b82f6", "TODO"}, {"In Progress", "#f59e0b", "IN_PROGRESS"}, {"Done", "#22c55e", "DONE"}}
|
||||
|
||||
+96
-16
@@ -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"
|
||||
@@ -28,8 +32,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
// ErrNotConfigured means SMTP_HOST/SMTP_FROM are unset; callers surface a
|
||||
@@ -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>
|
||||
@@ -2,7 +2,7 @@ package markdown
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
)
|
||||
|
||||
// Review L-11: link destinations are wrapped and escaped so parentheses or
|
||||
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
|
||||
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
)
|
||||
|
||||
// Conn is the dial-relevant projection of a stored McpConnection row plus
|
||||
@@ -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.2"}, 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.
|
||||
|
||||
@@ -27,10 +27,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/mailer"
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/mailer"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
)
|
||||
|
||||
// Kinds is the phase-1 channel set (mirrors the NotificationChannel CHECK).
|
||||
@@ -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":
|
||||
|
||||
@@ -28,10 +28,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/entitlements"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/entitlements"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -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"
|
||||
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
)
|
||||
|
||||
var placeholderPatterns = []*regexp.Regexp{
|
||||
|
||||
@@ -3,8 +3,8 @@ package preview
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
"golang.org/x/net/html"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
@@ -2,7 +2,7 @@ package signals
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -6,10 +6,10 @@ import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
"github.com/emersion/go-imap"
|
||||
"github.com/emersion/go-imap/client"
|
||||
"log"
|
||||
|
||||
@@ -29,7 +29,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/netguard"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
||||
)
|
||||
|
||||
// Conn is the dial-relevant projection of a stored WebDavConnection row plus
|
||||
|
||||
@@ -12,10 +12,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/outbound"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
crypt "gitea.federated.computer/Federated_Computer/brain/internal/crypto"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -3,16 +3,16 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/andrew/superbrain/internal/agent"
|
||||
"github.com/andrew/superbrain/internal/caldav"
|
||||
"github.com/andrew/superbrain/internal/carddav"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/http"
|
||||
"github.com/andrew/superbrain/internal/notify"
|
||||
"github.com/andrew/superbrain/internal/scripts"
|
||||
"github.com/andrew/superbrain/internal/signals"
|
||||
"github.com/andrew/superbrain/internal/webdav"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/agent"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/caldav"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/carddav"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/config"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/db"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/http"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/notify"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/scripts"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/signals"
|
||||
"gitea.federated.computer/Federated_Computer/brain/internal/webdav"
|
||||
"log"
|
||||
stdhttp "net/http"
|
||||
"os"
|
||||
|
||||
+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.12"
|
||||
version = "0.3.2"
|
||||
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.12"
|
||||
__version__ = "0.3.2"
|
||||
|
||||
+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`)
|
||||
|
||||
+124
-7
@@ -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()
|
||||
@@ -759,6 +806,76 @@ try {
|
||||
assert.ok(!(await page.evaluate(() => document.body.innerText)).includes('vcf-app-secret'), 'the entered CardDAV password echoed back in the UI')
|
||||
console.log('PASS: Settings → CardDAV lists address books, prefills a username-composed Nextcloud home, and round-trips connect/sync/test without echoing secrets')
|
||||
|
||||
// Mobile pass (390x844): the shell becomes a drawer, tables become cards,
|
||||
// rail screens become master-detail, and NO screen may overflow the
|
||||
// viewport horizontally. A separate context keeps the desktop session and
|
||||
// its assertions untouched.
|
||||
const mobileContext = await browser.newContext({ viewport: { width: 390, height: 844 }, timezoneId: 'America/Chicago' })
|
||||
const mobile = await mobileContext.newPage()
|
||||
mobile.on('pageerror', error => errors.push(error.message))
|
||||
await fixtureLogin(mobileContext)
|
||||
const noOverflow = async (label) => {
|
||||
const ok = await mobile.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)
|
||||
assert.ok(ok, `${label} overflows the phone viewport horizontally`)
|
||||
}
|
||||
const drawerClosed = async () => {
|
||||
const box = await mobile.locator('aside').boundingBox()
|
||||
return box !== null && box.x + box.width <= 1
|
||||
}
|
||||
|
||||
// Drawer: off-canvas by default, hamburger opens it, navigating closes it.
|
||||
await mobile.goto(`${base}/pages`)
|
||||
await mobile.locator('[data-page-editor]').waitFor()
|
||||
assert.ok(await drawerClosed(), 'sidebar must start off-canvas on phones')
|
||||
await noOverflow('pages')
|
||||
await mobile.getByRole('button', { name: 'Open navigation' }).click()
|
||||
await eventually(async () => !await drawerClosed(), 'navigation drawer did not open')
|
||||
await mobile.getByRole('link', { name: 'All Bookmarks', exact: true }).click()
|
||||
await mobile.waitForURL('**/bookmarks')
|
||||
await eventually(drawerClosed, 'navigation drawer did not close after navigating')
|
||||
|
||||
// Bookmarks: the table swaps to tappable cards; the detail sheet still opens.
|
||||
await eventually(() => mobile.locator('tbody tr').count().then(n => n === 0), 'bookmarks table must swap to cards on phones')
|
||||
await mobile.getByText('Fixture 000', { exact: true }).first().waitFor()
|
||||
await noOverflow('bookmarks')
|
||||
await mobile.getByText('Fixture 000', { exact: true }).first().click()
|
||||
await mobile.getByLabel('URL', { exact: true }).waitFor()
|
||||
await mobile.keyboard.press('Escape')
|
||||
|
||||
// Tags: master-detail — list first, tap a tag for its bookmarks, Back returns.
|
||||
await mobile.goto(`${base}/tags`)
|
||||
await mobile.getByPlaceholder('New tag').waitFor()
|
||||
await noOverflow('tags list')
|
||||
await mobile.getByText('First tag', { exact: true }).click()
|
||||
await mobile.getByText('Bookmarks tagged:', { exact: false }).waitFor()
|
||||
await noOverflow('tag detail')
|
||||
await mobile.getByRole('button', { name: 'Back', exact: true }).click()
|
||||
await mobile.getByPlaceholder('New tag').waitFor()
|
||||
|
||||
// Settings: the 12-tab strip scrolls inside its own container; deep tabs
|
||||
// remain reachable and the page itself never overflowed.
|
||||
await mobile.goto(`${base}/settings`)
|
||||
await mobile.getByRole('tab', { name: 'WebDAV' }).scrollIntoViewIfNeeded()
|
||||
await mobile.getByRole('tab', { name: 'WebDAV' }).click()
|
||||
await mobile.getByText('House docs').first().waitFor()
|
||||
await noOverflow('settings')
|
||||
|
||||
// Kanban columns fit a phone (peek of the next column, horizontal scroll).
|
||||
await mobile.goto(`${base}/kanban`)
|
||||
await mobile.locator('[data-column-id="inbox"]').waitFor()
|
||||
const colBox = await mobile.locator('[data-column-id="inbox"]').boundingBox()
|
||||
assert.ok(colBox && colBox.width < 390, 'kanban column must fit the phone viewport')
|
||||
await noOverflow('kanban')
|
||||
|
||||
// Remaining screens: no horizontal overflow.
|
||||
for (const path of ['/calendar', '/collections', '/contacts']) {
|
||||
await mobile.goto(`${base}${path}`)
|
||||
await new Promise(resolve => setTimeout(resolve, 400))
|
||||
await noOverflow(path)
|
||||
}
|
||||
await mobileContext.close()
|
||||
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
|
||||
// removal is not confirmed global revocation, and other sessions survive.
|
||||
|
||||
@@ -4,11 +4,121 @@ 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[]>([])
|
||||
@@ -31,6 +141,12 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
|
||||
const [tab, setTab] = useState<'mine' | 'shared'>('mine')
|
||||
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).
|
||||
@@ -88,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] ?? ''
|
||||
@@ -95,61 +252,32 @@ 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') }
|
||||
}
|
||||
|
||||
const trashBookmark = async (b: Bookmark) => {
|
||||
if (!confirm('Move this bookmark to the trash? It can be restored.')) return
|
||||
try {
|
||||
const res = await fetch(`/api/bookmarks/${b.id}`, { method: 'DELETE' })
|
||||
if (res.ok) { toast.success('Moved to trash'); load() } else toast.error('Could not move bookmark to trash')
|
||||
} catch { toast.error('Could not move bookmark to trash') }
|
||||
}
|
||||
|
||||
const sortIcon = (field: typeof sortField) => {
|
||||
if (sortField !== field) return null
|
||||
return sortDir === 'asc' ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />
|
||||
}
|
||||
|
||||
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="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" />
|
||||
</div>
|
||||
<div className="flex rounded-lg border overflow-hidden">
|
||||
<button onClick={() => setTab('mine')} className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${tab === 'mine' ? 'bg-primary text-primary-foreground' : 'bg-card hover:bg-muted'}`}>
|
||||
<Inbox className="h-3.5 w-3.5" /> Mine
|
||||
</button>
|
||||
<button onClick={() => setTab('shared')} className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${tab === 'shared' ? 'bg-primary text-primary-foreground' : 'bg-card hover:bg-muted'}`}>
|
||||
<Share2 className="h-3.5 w-3.5" /> Shared
|
||||
</button>
|
||||
</div>
|
||||
</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) => (
|
||||
// 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">
|
||||
@@ -175,16 +303,152 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
|
||||
<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={async () => { if (!confirm('Move this bookmark to the trash? It can be restored.')) return; try { const res = await fetch(`/api/bookmarks/${b.id}`, { method: 'DELETE' }); if (res.ok) { toast.success('Moved to trash'); load() } else toast.error('Could not move bookmark to trash') } catch { toast.error('Could not move bookmark to trash') } }}><Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" /></button>
|
||||
<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 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" />
|
||||
</div>
|
||||
<div className="flex rounded-lg border overflow-hidden">
|
||||
<button onClick={() => setTab('mine')} className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${tab === 'mine' ? 'bg-primary text-primary-foreground' : 'bg-card hover:bg-muted'}`}>
|
||||
<Inbox className="h-3.5 w-3.5" /> Mine
|
||||
</button>
|
||||
<button onClick={() => setTab('shared')} className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${tab === 'shared' ? 'bg-primary text-primary-foreground' : 'bg-card hover:bg-muted'}`}>
|
||||
<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>
|
||||
{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(renderCard)}
|
||||
</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,25 +184,35 @@ 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 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" onClick={() => setCurrentMonth(subMonths(currentMonth, 1))}>
|
||||
<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] text-center">{format(currentMonth, 'MMMM yyyy')}</span>
|
||||
<Button variant="outline" size="icon-sm" onClick={() => setCurrentMonth(addMonths(currentMonth, 1))}>
|
||||
<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-2 py-2 text-center text-xs font-medium text-muted-foreground">{d}</div>
|
||||
<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>
|
||||
))}
|
||||
{Array.from({ length: startDayOfWeek }).map((_, i) => (
|
||||
<div key={`empty-${i}`} className="bg-card min-h-[80px]" />
|
||||
@@ -144,7 +232,7 @@ export function CalendarClient() {
|
||||
aria-label={format(day, 'EEEE, MMMM d, yyyy')}
|
||||
onClick={() => setSelectedDay(day)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedDay(day) } }}
|
||||
className={`bg-card min-h-[80px] p-1.5 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary ${
|
||||
className={`bg-card min-h-[64px] p-1 sm:min-h-[80px] sm: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' : ''
|
||||
}`}
|
||||
>
|
||||
@@ -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>
|
||||
{/* 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>
|
||||
)
|
||||
})}
|
||||
{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>
|
||||
</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="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 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>
|
||||
)
|
||||
|
||||
@@ -11,7 +11,8 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { CalendarDays, Columns3, Filter, GripVertical, Kanban, Layers, List, Plus, Share2, Table2, Trash2, X } from 'lucide-react'
|
||||
import { useIsMobile } from '@/lib/use-media-query'
|
||||
import { ArrowLeft, CalendarDays, Columns3, Filter, GripVertical, Kanban, Layers, List, Plus, Share2, Table2, Trash2, X } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { Bookmark } from '@/components/app-shell'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -216,9 +217,10 @@ 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()
|
||||
const [detail, setDetail] = useState<CollectionDetail | null>(null)
|
||||
const [items, setItems] = useState<CollectionItem[]>([])
|
||||
const [cursor, setCursor] = useState<string | null>(null)
|
||||
@@ -292,10 +294,15 @@ export function CollectionsClient() {
|
||||
useEffect(() => { const t = setTimeout(loadCollections, 0); return () => clearTimeout(t) }, [loadCollections])
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
if (!activeId && collections.length) 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])
|
||||
}, [collections, activeId, isMobile, initialId])
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
if (!activeId) { detailSeq.current++; setDetail(null); return }
|
||||
@@ -664,7 +671,7 @@ export function CollectionsClient() {
|
||||
setBoardDropKey(null)
|
||||
}}
|
||||
className={cn(
|
||||
'w-64 shrink-0 rounded-lg border border-border/60 bg-muted/30 p-2 transition-[box-shadow,background-color,border-color] duration-150',
|
||||
'w-[85vw] max-w-64 shrink-0 rounded-lg border border-border/60 bg-muted/30 p-2 transition-[box-shadow,background-color,border-color] duration-150 sm:w-64 sm:max-w-none',
|
||||
isDropTarget && 'border-primary/40 bg-primary/[0.04] ring-2 ring-primary/40',
|
||||
)}
|
||||
>
|
||||
@@ -744,7 +751,7 @@ export function CollectionsClient() {
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* Collection list */}
|
||||
<div className="flex w-60 shrink-0 flex-col border-r border-border/60 p-3">
|
||||
<div className={cn('flex w-60 shrink-0 flex-col border-r border-border/60 p-3', isMobile && (activeId ? 'hidden' : 'w-full border-r-0'))}>
|
||||
<h1 className="mb-3 flex items-center gap-2 font-display text-lg font-semibold tracking-tight">
|
||||
<Layers className="h-4 w-4" /> Collections
|
||||
</h1>
|
||||
@@ -776,7 +783,7 @@ export function CollectionsClient() {
|
||||
</div>
|
||||
|
||||
{/* Detail */}
|
||||
<div className="flex-1 overflow-y-auto px-6 py-5">
|
||||
<div className={cn('flex-1 overflow-y-auto px-3 py-4 sm:px-6 sm:py-5', isMobile && !activeId && 'hidden')}>
|
||||
{!detail ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 text-center">
|
||||
<Layers className="h-10 w-10 text-muted-foreground" />
|
||||
@@ -787,11 +794,16 @@ export function CollectionsClient() {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{isMobile && (
|
||||
<Button variant="ghost" size="sm" className="mb-2 -ml-2 gap-1 text-muted-foreground" onClick={() => setActiveId(null)}>
|
||||
<ArrowLeft className="h-4 w-4" /> Collections
|
||||
</Button>
|
||||
)}
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2">
|
||||
{readOnly ? (
|
||||
<span className="w-72 truncate font-display text-2xl font-bold tracking-tight">{detail.name}</span>
|
||||
<span className="w-full truncate font-display text-2xl font-bold tracking-tight sm:w-72">{detail.name}</span>
|
||||
) : (
|
||||
<Input value={nameDraft} onChange={(e) => setNameDraft(e.target.value)} onBlur={saveName} onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur() }} aria-label="Collection name" className="w-72 bg-transparent font-display text-2xl font-bold tracking-tight" />
|
||||
<Input value={nameDraft} onChange={(e) => setNameDraft(e.target.value)} onBlur={saveName} onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur() }} aria-label="Collection name" className="w-full bg-transparent font-display text-2xl font-bold tracking-tight sm:w-72" />
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">{detail._count?.items ?? 0} item{(detail._count?.items ?? 0) === 1 ? '' : 's'}</span>
|
||||
{readOnly ? (
|
||||
|
||||
@@ -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} />
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ import { useState, useEffect, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { BookmarkCard } from '@/components/bookmark-card'
|
||||
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
|
||||
import { Users, RefreshCw, Mail, Phone } from 'lucide-react'
|
||||
import { ArrowLeft, Users, RefreshCw, Mail, Phone } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useIsMobile } from '@/lib/use-media-query'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { Bookmark } from '@/components/app-shell'
|
||||
import { fetchBookmarks } from '@/lib/bookmarks'
|
||||
|
||||
@@ -18,9 +20,10 @@ 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)
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
@@ -51,8 +54,8 @@ export function ContactsClient() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex gap-6 h-[calc(100vh-120px)]">
|
||||
<div className="w-72 shrink-0 space-y-4 overflow-y-auto">
|
||||
<div className={cn('flex h-[calc(100dvh-120px)] gap-6', isMobile && 'gap-0')}>
|
||||
<div className={cn('w-72 shrink-0 space-y-4 overflow-y-auto', isMobile && (selectedContact ? 'hidden' : 'w-full'))}>
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="font-display text-2xl font-bold tracking-tight">Contacts</h1>
|
||||
<Button variant="outline" size="sm" onClick={syncContacts} loading={syncing} className="gap-1.5">
|
||||
@@ -95,9 +98,14 @@ export function ContactsClient() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className={cn('flex-1 overflow-y-auto', isMobile && !selectedContact && 'hidden')}>
|
||||
{selectedContact ? (
|
||||
<div className="space-y-4">
|
||||
{isMobile && (
|
||||
<Button variant="ghost" size="sm" className="-ml-2 gap-1 text-muted-foreground" onClick={() => setSelectedContact(null)}>
|
||||
<ArrowLeft className="h-4 w-4" /> Back
|
||||
</Button>
|
||||
)}
|
||||
<h2 className="font-medium">Bookmarks for {contacts.find(c => c.id === selectedContact)?.displayName}</h2>
|
||||
{bookmarks.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-8 text-center">No bookmarks linked to this contact</p>
|
||||
|
||||
@@ -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} />
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user