Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a402e4f2e7 | ||
|
|
eca8aeb113 | ||
|
|
f6158f58b5 | ||
|
|
7a7e77e039 | ||
|
|
ef69be6320 |
@@ -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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 | `/api/auth/oidc/login` | **501**, client-owned Authelia integration stub |
|
||||||
| GET, POST | `/api/auth/callback/authelia` | **501**, client-owned callback stub |
|
| GET, POST | `/api/auth/callback/authelia` | **501**, client-owned callback stub |
|
||||||
|
|
||||||
The browser's NextAuth `/api/auth/*` endpoints remain on the Next server.
|
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.
|
Direct Go API consumers use the `superbrain_session` cookie from login.
|
||||||
`TIER=core|multi` (or an explicit `AUTH_MODE` override) decides which half
|
`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
|
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
|
re-opens promotion through signup. Recovery is operator-driven
|
||||||
(`ADMIN_EMAILS` + `make seed`, or promotion by an existing admin).
|
(`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)
|
### API keys (MCP / machine clients)
|
||||||
|
|
||||||
Personal long-lived Bearer credentials (`sb_` + 43 base64url characters) for
|
Personal long-lived Bearer credentials (`sb_` + 43 base64url characters) for
|
||||||
@@ -243,8 +258,11 @@ projection and UI agree. Detail responses also include
|
|||||||
| GET | `/api/bookmarks/{id}/markdown` | Markdown attachment, owned/shared only |
|
| 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/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 | `/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
|
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.
|
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.
|
`limit` must be between 1 and 200. The web proxy forwards the cursor header.
|
||||||
@@ -287,10 +305,10 @@ test-only). CardDAV keeps the configured HTTPS port.
|
|||||||
| PATCH | `/api/kanban/columns/{id}` | Updated column; body `{label?,color?}` |
|
| 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 |
|
| 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` |
|
| 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 |
|
| 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,...]}` |
|
| 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) |
|
| 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}/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 |
|
| GET | `/api/pages/{id}/revisions` | Version history metadata `[{id,version,title,icon,createdAt,length}]`, newest first; bodies fetched separately |
|
||||||
@@ -298,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 |
|
| 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 |
|
| 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 |
|
| 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)
|
### Connected pages (phase 3)
|
||||||
|
|
||||||
@@ -417,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
|
carry the footer "Managed by David's Superbrain."; paying plans and core do
|
||||||
not (`entitlements.ManagedFooter`, per-tenant override `managed_footer`).
|
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 |
|
| Method | Path | Body / Returns |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| GET | `/api/notifications/channels` | `[{id,kind,name,enabled,version,config(masked),createdAt}]` |
|
| GET | `/api/notifications/channels` | `[{id,kind,name,enabled,version,config(masked),createdAt}]` |
|
||||||
@@ -429,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 |
|
| PATCH | `/api/notifications/rules/{id}` | `{version, name?,enabled?,cooldownMinutes?,channelId?,config?}` → 200; 409 on stale version |
|
||||||
| DELETE | `/api/notifications/rules/{id}` | `{ok:true}` |
|
| 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 |
|
| 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")
|
### Agent automations ("hey superbrain")
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,34 @@ Versions correspond to git tags and to the published image set
|
|||||||
(the line was reset to 0.2.x at 0.2.14 — Superbrain is pre-beta).
|
(the line was reset to 0.2.x at 0.2.14 — Superbrain is pre-beta).
|
||||||
Dates are tag dates.
|
Dates are tag dates.
|
||||||
|
|
||||||
|
## 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
|
## 0.2.16 — 2026-11-18
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -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;
|
||||||
+6
-1
@@ -40,7 +40,12 @@ CREATE TABLE "User" (
|
|||||||
"tokenVersion" integer NOT NULL DEFAULT 1,
|
"tokenVersion" integer NOT NULL DEFAULT 1,
|
||||||
"createdAt" timestamptz NOT NULL DEFAULT now(),
|
"createdAt" timestamptz NOT NULL DEFAULT now(),
|
||||||
"updatedAt" 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).
|
-- 2.2b TenantMember, TenantEntitlement, QuotaUsage (tenancy phase 1).
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ SUPERBRAIN_APP_IP="192.168.0.94"
|
|||||||
SUPERBRAIN_MIGRATE_IP="192.168.0.95"
|
SUPERBRAIN_MIGRATE_IP="192.168.0.95"
|
||||||
# Release to install; the generic `upgrade` flow keeps .env in step with the
|
# Release to install; the generic `upgrade` flow keeps .env in step with the
|
||||||
# service file's VERSION afterwards.
|
# service file's VERSION afterwards.
|
||||||
SUPERBRAIN_IMAGE_VERSION="0.2.16"
|
SUPERBRAIN_IMAGE_VERSION="0.2.17"
|
||||||
|
|
||||||
# render_superbrain_compose writes the app-dir compose file. Called by
|
# render_superbrain_compose writes the app-dir compose file. Called by
|
||||||
# config_superbrain (install) and by deploy/federated/update.sh after a lib
|
# config_superbrain (install) and by deploy/federated/update.sh after a lib
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ NAME=superbrain
|
|||||||
DESCRIPTION="Bookmark & Knowledge Base"
|
DESCRIPTION="Bookmark & Knowledge Base"
|
||||||
DOCS=https://github.com/andrew/superbrain
|
DOCS=https://github.com/andrew/superbrain
|
||||||
CONTAINER=federatedcomputer/superbrain-app
|
CONTAINER=federatedcomputer/superbrain-app
|
||||||
VERSION=0.2.16
|
VERSION=0.2.17
|
||||||
INTERNAL_IP=192.168.0.93
|
INTERNAL_IP=192.168.0.93
|
||||||
DEPENDS="postgresql"
|
DEPENDS="postgresql"
|
||||||
PORTS=3000
|
PORTS=3000
|
||||||
|
|||||||
@@ -370,7 +370,9 @@ func fire(ctx context.Context, d *db.DB, t Task, summary string) (string, string
|
|||||||
defer release()
|
defer release()
|
||||||
sendCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
sendCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
defer cancel()
|
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()
|
return "failed", "email: " + err.Error()
|
||||||
}
|
}
|
||||||
case "bookmark":
|
case "bookmark":
|
||||||
|
|||||||
@@ -31,7 +31,8 @@ type SessionUser struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func identity(u *models.User) map[string]any {
|
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 {
|
func AuthMiddleware(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/mail"
|
"net/mail"
|
||||||
@@ -161,7 +162,29 @@ func HandleForgotPassword(w http.ResponseWriter, r *http.Request) {
|
|||||||
link + "\n\n" +
|
link + "\n\n" +
|
||||||
"If you did not request a reset, you can ignore this email; the link is\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"
|
"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)
|
log.Printf("password reset: delivery to %s failed: %v", email, e)
|
||||||
}
|
}
|
||||||
okResponse()
|
okResponse()
|
||||||
|
|||||||
@@ -36,11 +36,16 @@ func userFromObject(o Object) (*models.User, error) {
|
|||||||
Role string `json:"role"`
|
Role string `json:"role"`
|
||||||
TokenVersion int `json:"tokenVersion"`
|
TokenVersion int `json:"tokenVersion"`
|
||||||
TenantID *string `json:"tenantId"`
|
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 {
|
if err = json.Unmarshal(raw, &row); err != nil {
|
||||||
return nil, err
|
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) {
|
func findUser(ctx context.Context, q Queryer, field, value string) (*models.User, error) {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"math"
|
"math"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sort"
|
"sort"
|
||||||
@@ -652,3 +653,75 @@ func ruleProjection(row object, channelKind, channelName string) object {
|
|||||||
"lastFiredAt": row["lastFiredAt"], "version": row["version"], "createdAt": row["createdAt"],
|
"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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
// Settings → Profile: the account's particulars (display name, bio,
|
||||||
|
// location, occupation, organization, website). PATCH /api/me updates an
|
||||||
|
// allowlist of free-text fields; an empty string clears the field (NULL).
|
||||||
|
// The User row is identity, not a collaborative collection — it has no
|
||||||
|
// version column, so this follows the settings-save shape rather than the
|
||||||
|
// 409 mutation contract. View-as impersonation is already blocked for
|
||||||
|
// writes by the auth middleware.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/andrew/superbrain/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// profileTextFields maps the allowlisted column names to their rune caps.
|
||||||
|
// Keys are server-owned; values are always bind parameters.
|
||||||
|
var profileTextFields = map[string]int{
|
||||||
|
"name": 120,
|
||||||
|
"bio": 280,
|
||||||
|
"location": 120,
|
||||||
|
"occupation": 120,
|
||||||
|
"organization": 120,
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxWebsiteLen = 2048
|
||||||
|
|
||||||
|
// HandleProfileUpdate applies a partial profile edit and answers the fresh
|
||||||
|
// identity projection (the same shape GET /api/me returns under "user").
|
||||||
|
//
|
||||||
|
// PATCH /api/me
|
||||||
|
func HandleProfileUpdate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
b, ok := read(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updates := object{}
|
||||||
|
for field, maxLen := range profileTextFields {
|
||||||
|
v, present := b[field]
|
||||||
|
if !present {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
s, isStr := v.(string)
|
||||||
|
if !isStr {
|
||||||
|
respond(w, 0, nil, bad(field+" must be a string"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if len([]rune(s)) > maxLen {
|
||||||
|
respond(w, 0, nil, bad(fmt.Sprintf("%s must be at most %d characters", field, maxLen)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if s == "" {
|
||||||
|
updates[field] = nil
|
||||||
|
} else {
|
||||||
|
updates[field] = s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if v, present := b["website"]; present {
|
||||||
|
s, isStr := v.(string)
|
||||||
|
if !isStr {
|
||||||
|
respond(w, 0, nil, bad("website must be a string"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if s == "" {
|
||||||
|
updates["website"] = nil
|
||||||
|
} else {
|
||||||
|
u, e := url.Parse(s)
|
||||||
|
if len(s) > maxWebsiteLen || e != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||||
|
respond(w, 0, nil, bad("website must be an http(s) URL"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updates["website"] = s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(updates) == 0 {
|
||||||
|
respond(w, 0, nil, bad("Nothing to update"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(updates))
|
||||||
|
for k := range updates {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
sets := make([]string, 0, len(keys))
|
||||||
|
args := make([]any, 0, len(keys)+1)
|
||||||
|
for i, k := range keys {
|
||||||
|
sets = append(sets, db.Quote(k)+fmt.Sprintf("=$%d", i+1))
|
||||||
|
args = append(args, updates[k])
|
||||||
|
}
|
||||||
|
args = append(args, user(r))
|
||||||
|
row, e := db.One(r.Context(), database(r),
|
||||||
|
`UPDATE "User" SET `+strings.Join(sets, ",")+`, "updatedAt"=now() WHERE id=$`+fmt.Sprint(len(args))+` RETURNING to_jsonb("User")`, args...)
|
||||||
|
if e != nil {
|
||||||
|
respond(w, 0, nil, e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
respond(w, 200, profileProjection(row), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// profileProjection mirrors auth.identity (the GET /api/me "user" shape)
|
||||||
|
// so the client can refresh its state from the save response alone.
|
||||||
|
func profileProjection(row object) object {
|
||||||
|
return object{
|
||||||
|
"id": row["id"], "name": row["name"], "email": row["email"], "image": row["image"],
|
||||||
|
"role": row["role"], "tenantId": row["tenantId"],
|
||||||
|
"bio": row["bio"], "location": row["location"], "occupation": row["occupation"],
|
||||||
|
"organization": row["organization"], "website": row["website"],
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/cookiejar"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Settings → Profile: the identity projection carries the particulars,
|
||||||
|
// PATCH /api/me applies partial allowlisted edits (empty string clears),
|
||||||
|
// validation is rune-based, and the endpoint is session-gated.
|
||||||
|
func TestProfileUpdate(t *testing.T) {
|
||||||
|
srv, _ := testServerDB(t)
|
||||||
|
jar, _ := cookiejar.New(nil)
|
||||||
|
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||||
|
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||||
|
alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||||
|
|
||||||
|
fields := []string{"bio", "location", "occupation", "organization", "website"}
|
||||||
|
user := alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
|
||||||
|
for _, f := range fields {
|
||||||
|
if v, present := user[f]; !present || v != nil {
|
||||||
|
t.Fatalf("fresh profile field %s = %v (present=%v), want null", f, v, present)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
saved := alice.request("PATCH", "/api/me", map[string]any{
|
||||||
|
"name": "Alice Example", "bio": "Knowledge worker", "location": "Berlin, Germany",
|
||||||
|
"occupation": "Engineer", "organization": "Acme", "website": "https://alice.example.com",
|
||||||
|
}, 200)
|
||||||
|
if saved["name"] != "Alice Example" || saved["bio"] != "Knowledge worker" ||
|
||||||
|
saved["location"] != "Berlin, Germany" || saved["occupation"] != "Engineer" ||
|
||||||
|
saved["organization"] != "Acme" || saved["website"] != "https://alice.example.com" {
|
||||||
|
t.Fatalf("save response wrong: %v", saved)
|
||||||
|
}
|
||||||
|
// The session identity is reloaded per request: GET /api/me reflects it.
|
||||||
|
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
|
||||||
|
if user["name"] != "Alice Example" || user["occupation"] != "Engineer" {
|
||||||
|
t.Fatalf("GET /api/me did not reflect the save: %v", user)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Partial edit: only the submitted field moves.
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"bio": "Updated bio"}, 200)
|
||||||
|
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
|
||||||
|
if user["bio"] != "Updated bio" || user["location"] != "Berlin, Germany" || user["name"] != "Alice Example" {
|
||||||
|
t.Fatalf("partial edit clobbered other fields: %v", user)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty string clears to null; whitespace-only is empty too.
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"bio": " ", "website": ""}, 200)
|
||||||
|
user = alice.request("GET", "/api/me", nil, 200)["user"].(map[string]any)
|
||||||
|
if user["bio"] != nil || user["website"] != nil {
|
||||||
|
t.Fatalf("clear did not null the fields: %v", user)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rune-based caps: 280 multi-byte runes fit, 281 do not.
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"bio": strings.Repeat("é", 280)}, 200)
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"bio": strings.Repeat("é", 281)}, 400)
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"name": strings.Repeat("x", 121)}, 400)
|
||||||
|
|
||||||
|
// Website shape: http(s) with a host only.
|
||||||
|
for _, badURL := range []string{"javascript:alert(1)", "ftp://x.test", "not a url", "https://", "/relative"} {
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"website": badURL}, 400)
|
||||||
|
}
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"website": "http://alice.example.com/path"}, 200)
|
||||||
|
|
||||||
|
// Type and emptiness guards.
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"bio": 42}, 400)
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{"unknown": "x"}, 400)
|
||||||
|
alice.request("PATCH", "/api/me", map[string]any{}, 400)
|
||||||
|
|
||||||
|
// Session-gated like every data endpoint.
|
||||||
|
anon := apiClient{t, &http.Client{}, srv.URL}
|
||||||
|
anon.request("PATCH", "/api/me", map[string]any{"bio": "intruder"}, 401)
|
||||||
|
}
|
||||||
@@ -48,6 +48,7 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
|
|||||||
mux.HandleFunc("GET /api/auth/", auth.HandleAuth) // csrf, callbacks, session, signout
|
mux.HandleFunc("GET /api/auth/", auth.HandleAuth) // csrf, callbacks, session, signout
|
||||||
mux.HandleFunc("POST /api/auth/", auth.HandleAuth)
|
mux.HandleFunc("POST /api/auth/", auth.HandleAuth)
|
||||||
mux.HandleFunc("GET /api/me", authed(auth.HandleMe))
|
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)
|
// Authelia OIDC (stub-aware; the client drives the flow via NextAuth)
|
||||||
mux.HandleFunc("GET /api/auth/oidc/status", oidc.HandleStatus)
|
mux.HandleFunc("GET /api/auth/oidc/status", oidc.HandleStatus)
|
||||||
@@ -128,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("PATCH /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesUpdate))
|
||||||
mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete))
|
mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete))
|
||||||
mux.HandleFunc("GET /api/notifications", authed(handlers.HandleNotificationsList))
|
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
|
// 4.7c Agent automations ("hey superbrain"): compile NL into a validated
|
||||||
// proposal (never writes), then owner-confirmed task CRUD + runs.
|
// proposal (never writes), then owner-confirmed task CRUD + runs.
|
||||||
|
|||||||
@@ -0,0 +1,220 @@
|
|||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/cookiejar"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/andrew/superbrain/internal/notify"
|
||||||
|
)
|
||||||
|
|
||||||
|
var unsubTokenRx = regexp.MustCompile(`/unsubscribe\?token=([0-9a-f.]+)`)
|
||||||
|
|
||||||
|
// The unsubscribe surface end to end: footer links + RFC 8058 headers on
|
||||||
|
// owner-addressed mail, the token-credentialed one-click endpoint (no
|
||||||
|
// session), the exact blast radius (email channels + self-addressed agent
|
||||||
|
// email tasks, nothing else), idempotence, and the third-party/transactional
|
||||||
|
// exclusions.
|
||||||
|
func TestUnsubscribeFlow(t *testing.T) {
|
||||||
|
srv, d := testServerDB(t)
|
||||||
|
smtp := newFakeSMTP(t)
|
||||||
|
host, port, _ := net.SplitHostPort(smtp.ln.Addr().String())
|
||||||
|
t.Setenv("SMTP_HOST", host)
|
||||||
|
t.Setenv("SMTP_PORT", port)
|
||||||
|
t.Setenv("SMTP_FROM", "superbrain@superbrain.test")
|
||||||
|
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
|
||||||
|
|
||||||
|
jar, _ := cookiejar.New(nil)
|
||||||
|
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||||
|
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||||
|
alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||||
|
aliceID := meID(alice)
|
||||||
|
|
||||||
|
hook := newFakeWebhook(t)
|
||||||
|
selfCh := alice.request("POST", "/api/notifications/channels", map[string]any{
|
||||||
|
"kind": "email", "name": "My inbox", "config": map[string]any{"address": ""},
|
||||||
|
}, 201)
|
||||||
|
thirdCh := alice.request("POST", "/api/notifications/channels", map[string]any{
|
||||||
|
"kind": "email", "name": "Bob's inbox", "config": map[string]any{"address": "bob@superbrain.test"},
|
||||||
|
}, 201)
|
||||||
|
slackCh := alice.request("POST", "/api/notifications/channels", map[string]any{
|
||||||
|
"kind": "slack", "name": "Team", "config": map[string]any{"webhookUrl": hook.url()},
|
||||||
|
}, 201)
|
||||||
|
|
||||||
|
// Signal-condition email tasks need no AI. One addresses the owner,
|
||||||
|
// one a third party: unsubscribe must pause only the former.
|
||||||
|
selfTask := alice.request("POST", "/api/agent/tasks", map[string]any{"name": "Self mail", "spec": map[string]any{
|
||||||
|
"condition": map[string]any{"type": "signal"},
|
||||||
|
"action": map[string]any{"type": "email", "to": "alice@superbrain.test"},
|
||||||
|
}}, 201)
|
||||||
|
thirdTask := alice.request("POST", "/api/agent/tasks", map[string]any{"name": "Bob mail", "spec": map[string]any{
|
||||||
|
"condition": map[string]any{"type": "signal"},
|
||||||
|
"action": map[string]any{"type": "email", "to": "bob@superbrain.test"},
|
||||||
|
}}, 201)
|
||||||
|
|
||||||
|
// --- owner-addressed delivery carries footer links + one-click headers ---
|
||||||
|
due := time.Now().UTC().Add(6 * time.Hour).Format(time.RFC3339)
|
||||||
|
alice.request("POST", "/api/bookmarks", map[string]any{
|
||||||
|
"url": "https://example.org/unsub-due", "title": "Unsub due", "dueDate": due,
|
||||||
|
}, 201)
|
||||||
|
alice.request("POST", "/api/notifications/rules", map[string]any{
|
||||||
|
"name": "Due reminders", "trigger": "bookmark_due", "channelId": selfCh["id"],
|
||||||
|
"config": map[string]any{"leadHours": 24}, "cooldownMinutes": 60,
|
||||||
|
}, 201)
|
||||||
|
if e := notify.RunOnce(context.Background(), d); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
msg := smtp.waitForMessage(t, 1)
|
||||||
|
if msg[0] != "alice@superbrain.test" {
|
||||||
|
t.Fatalf("envelope recipient = %q", msg[0])
|
||||||
|
}
|
||||||
|
for _, want := range []string{
|
||||||
|
"List-Unsubscribe: <https://superbrain.test/api/notifications/unsubscribe?token=",
|
||||||
|
"List-Unsubscribe-Post: List-Unsubscribe=One-Click",
|
||||||
|
"https://superbrain.test/unsubscribe?token=",
|
||||||
|
"https://superbrain.test/settings?tab=notifications",
|
||||||
|
"https://superbrain.test/help",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(msg[1], want) {
|
||||||
|
t.Fatalf("owner-addressed mail missing %q:\n%s", want, msg[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m := unsubTokenRx.FindStringSubmatch(msg[1])
|
||||||
|
if m == nil {
|
||||||
|
t.Fatalf("no unsubscribe token in mail:\n%s", msg[1])
|
||||||
|
}
|
||||||
|
token := m[1]
|
||||||
|
if id, ok := notify.ParseUnsubscribeToken(token); !ok || id != aliceID {
|
||||||
|
t.Fatalf("token resolves to %q (%v), want the channel owner %q", id, ok, aliceID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- RFC 8058 one-click: no session, token in the query, form body ---
|
||||||
|
oneClick := func(tok string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
req, _ := http.NewRequest("POST", srv.URL+"/api/notifications/unsubscribe?token="+tok,
|
||||||
|
strings.NewReader("List-Unsubscribe=One-Click"))
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
res, e := (&http.Client{}).Do(req)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
raw, _ := io.ReadAll(res.Body)
|
||||||
|
if res.StatusCode != 200 {
|
||||||
|
t.Fatalf("one-click unsubscribe: wanted 200, got %d: %s", res.StatusCode, raw)
|
||||||
|
}
|
||||||
|
var v map[string]any
|
||||||
|
if e := json.Unmarshal(raw, &v); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
got := oneClick(token)
|
||||||
|
if got["ok"] != true || got["channels"].(float64) != 2 || got["tasks"].(float64) != 1 {
|
||||||
|
t.Fatalf("unsubscribe result = %v, want ok with 2 email channels + 1 self-addressed task", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Blast radius: BOTH of alice's email channels disabled (the preference
|
||||||
|
// is account-wide), slack untouched; only the self-addressed task paused.
|
||||||
|
channels := map[string]map[string]any{}
|
||||||
|
for _, row := range listGET(alice, "/api/notifications/channels") {
|
||||||
|
r := row.(map[string]any)
|
||||||
|
channels[r["id"].(string)] = r
|
||||||
|
}
|
||||||
|
if channels[selfCh["id"].(string)]["enabled"] != false || channels[thirdCh["id"].(string)]["enabled"] != false {
|
||||||
|
t.Fatalf("email channels not disabled: %v", channels)
|
||||||
|
}
|
||||||
|
if channels[slackCh["id"].(string)]["enabled"] != true {
|
||||||
|
t.Fatalf("slack channel must survive unsubscribe: %v", channels[slackCh["id"].(string)])
|
||||||
|
}
|
||||||
|
tasks := map[string]map[string]any{}
|
||||||
|
for _, row := range listGET(alice, "/api/agent/tasks") {
|
||||||
|
r := row.(map[string]any)
|
||||||
|
tasks[r["id"].(string)] = r
|
||||||
|
}
|
||||||
|
if tasks[selfTask["id"].(string)]["enabled"] != false || tasks[selfTask["id"].(string)]["status"] != "paused" {
|
||||||
|
t.Fatalf("self-addressed task not paused: %v", tasks[selfTask["id"].(string)])
|
||||||
|
}
|
||||||
|
if tasks[thirdTask["id"].(string)]["enabled"] != true {
|
||||||
|
t.Fatalf("third-party task must survive unsubscribe: %v", tasks[thirdTask["id"].(string)])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idempotent: a second click changes nothing.
|
||||||
|
got = oneClick(token)
|
||||||
|
if got["channels"].(float64) != 0 || got["tasks"].(float64) != 0 {
|
||||||
|
t.Fatalf("second unsubscribe = %v, want zero counts", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tampered and junk tokens are dead links (400, identical answers).
|
||||||
|
for _, bad := range []string{
|
||||||
|
token[:len(token)-1] + "0",
|
||||||
|
strings.Repeat("f", 32) + "." + strings.Repeat("0", 64),
|
||||||
|
"not-a-token",
|
||||||
|
} {
|
||||||
|
req, _ := http.NewRequest("POST", srv.URL+"/api/notifications/unsubscribe?token="+bad, nil)
|
||||||
|
res, e := (&http.Client{}).Do(req)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
if res.StatusCode != 400 {
|
||||||
|
t.Fatalf("bad token %q: wanted 400, got %d", bad, res.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- browser confirmation path: JSON body, no query token ---
|
||||||
|
alice.request("PATCH", "/api/notifications/channels/"+selfCh["id"].(string), map[string]any{
|
||||||
|
"enabled": true, "version": int(channels[selfCh["id"].(string)]["version"].(float64)),
|
||||||
|
}, 200)
|
||||||
|
anon := apiClient{t, &http.Client{}, srv.URL}
|
||||||
|
got = anon.request("POST", "/api/notifications/unsubscribe", map[string]any{"token": token}, 200)
|
||||||
|
if got["channels"].(float64) != 1 {
|
||||||
|
t.Fatalf("JSON-body unsubscribe = %v, want the re-enabled channel disabled again", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- third-party recipient: footer help/preferences, NO unsubscribe ---
|
||||||
|
// Unsubscribe is account-wide, so re-enable the third-party channel
|
||||||
|
// first (an owner may keep mailing other people after unsubscribing
|
||||||
|
// themselves).
|
||||||
|
alice.request("PATCH", "/api/notifications/channels/"+thirdCh["id"].(string), map[string]any{
|
||||||
|
"enabled": true, "version": int(channels[thirdCh["id"].(string)]["version"].(float64)),
|
||||||
|
}, 200)
|
||||||
|
alice.request("POST", "/api/bookmarks", map[string]any{
|
||||||
|
"url": "https://example.org/unsub-due-2", "title": "Unsub due 2", "dueDate": due,
|
||||||
|
}, 201)
|
||||||
|
alice.request("POST", "/api/notifications/rules", map[string]any{
|
||||||
|
"name": "Bob reminders", "trigger": "bookmark_due", "channelId": thirdCh["id"],
|
||||||
|
"config": map[string]any{"leadHours": 24}, "cooldownMinutes": 60,
|
||||||
|
}, 201)
|
||||||
|
if e := notify.RunOnce(context.Background(), d); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
msg = smtp.waitForMessage(t, 2)
|
||||||
|
if msg[0] != "bob@superbrain.test" {
|
||||||
|
t.Fatalf("third-party envelope recipient = %q", msg[0])
|
||||||
|
}
|
||||||
|
if !strings.Contains(msg[1], "https://superbrain.test/help") {
|
||||||
|
t.Fatalf("third-party mail lost the help footer:\n%s", msg[1])
|
||||||
|
}
|
||||||
|
if strings.Contains(msg[1], "List-Unsubscribe") || strings.Contains(msg[1], "/unsubscribe?token=") {
|
||||||
|
t.Fatalf("third-party recipient must never receive an unsubscribe link:\n%s", msg[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- transactional mail: preferences + help, never unsubscribe ---
|
||||||
|
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
|
||||||
|
msg = smtp.waitForMessage(t, 3)
|
||||||
|
if !strings.Contains(msg[1], "https://superbrain.test/settings?tab=notifications") ||
|
||||||
|
!strings.Contains(msg[1], "https://superbrain.test/help") {
|
||||||
|
t.Fatalf("reset mail missing footer links:\n%s", msg[1])
|
||||||
|
}
|
||||||
|
if strings.Contains(msg[1], "List-Unsubscribe") || strings.Contains(msg[1], "/unsubscribe?token=") {
|
||||||
|
t.Fatalf("transactional mail must not carry unsubscribe:\n%s", msg[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
+94
-14
@@ -1,5 +1,7 @@
|
|||||||
// Package mailer sends transactional email (password-reset links) through a
|
// Package mailer sends transactional email (password-reset links,
|
||||||
// configured SMTP relay.
|
// 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
|
// Like every server-initiated dial, sending is bounded by internal/outbound
|
||||||
// and guarded by internal/netguard: private/link-local relay hosts (the
|
// and guarded by internal/netguard: private/link-local relay hosts (the
|
||||||
@@ -18,7 +20,9 @@ package mailer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
@@ -74,6 +78,22 @@ func (c Config) Configured() bool { return c.Host != "" && c.From != "" }
|
|||||||
// Send delivers one plain-text message. It is synchronous: the caller owns
|
// Send delivers one plain-text message. It is synchronous: the caller owns
|
||||||
// the request context and any retry policy.
|
// the request context and any retry policy.
|
||||||
func Send(ctx context.Context, to, subject, body string) error {
|
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()
|
cfg := LoadConfig()
|
||||||
if !cfg.Configured() {
|
if !cfg.Configured() {
|
||||||
return ErrNotConfigured
|
return ErrNotConfigured
|
||||||
@@ -139,18 +159,7 @@ func Send(ctx context.Context, to, subject, body string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("mailer: DATA: %w", err)
|
return fmt.Errorf("mailer: DATA: %w", err)
|
||||||
}
|
}
|
||||||
msg := strings.Join([]string{
|
msg := buildMessage(cfg.From, to, subject, body, html, listUnsub)
|
||||||
"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")
|
|
||||||
if _, err := data.Write([]byte(msg)); err != nil {
|
if _, err := data.Write([]byte(msg)); err != nil {
|
||||||
return fmt.Errorf("mailer: write: %w", err)
|
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))
|
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
|
// dial resolves and connects through netguard: range checks apply unless
|
||||||
// INTEGRATIONS_ALLOW_PRIVATE=1 (house relays live on private networks), and
|
// INTEGRATIONS_ALLOW_PRIVATE=1 (house relays live on private networks), and
|
||||||
// only the standard SMTP ports are reachable from public ranges.
|
// only the standard SMTP ports are reachable from public ranges.
|
||||||
|
|||||||
@@ -0,0 +1,243 @@
|
|||||||
|
// Branded HTML rendering for transactional email. template.html is the
|
||||||
|
// Superbrain email design (table layout, Outlook VML button fallback,
|
||||||
|
// dark-mode overrides); it is embedded verbatim and filled here.
|
||||||
|
//
|
||||||
|
// The template uses {{placeholder}} markers rather than text/template so
|
||||||
|
// the design file stays editable as plain HTML (and Outlook conditional
|
||||||
|
// comments survive untouched). Every substituted value is HTML-escaped,
|
||||||
|
// and optional sections (CTA button + fallback link, note block, footer
|
||||||
|
// links, address line) are removed when their values are empty.
|
||||||
|
|
||||||
|
package mailer
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "embed"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed template.html
|
||||||
|
var emailTemplate string
|
||||||
|
|
||||||
|
// Content describes one branded rendering. Headline falls back to the
|
||||||
|
// subject, SignOff to "Thanks,", CTALabel to "Open Superbrain", and the
|
||||||
|
// preheader to the first body paragraph. Empty optional fields remove
|
||||||
|
// their section instead of rendering a stub.
|
||||||
|
type Content struct {
|
||||||
|
Preheader string // inbox preview line (kept under ~90 characters)
|
||||||
|
Headline string
|
||||||
|
FirstName string // optional; the greeting degrades to "Hi,"
|
||||||
|
Body string // newline-separated paragraphs
|
||||||
|
CTAURL string // optional button + fallback link
|
||||||
|
CTALabel string
|
||||||
|
Note string // optional highlighted note block
|
||||||
|
SignOff string
|
||||||
|
|
||||||
|
// Optional footer links; unset ones are omitted.
|
||||||
|
PreferencesURL string
|
||||||
|
UnsubscribeURL string
|
||||||
|
HelpURL string
|
||||||
|
CompanyAddress string
|
||||||
|
|
||||||
|
// UnsubscribePostURL is the RFC 8058 one-click endpoint (POST, token in
|
||||||
|
// the query). When set, the message carries List-Unsubscribe +
|
||||||
|
// List-Unsubscribe-Post headers so mail clients can offer native
|
||||||
|
// unsubscribe. It is independent of UnsubscribeURL (the human page).
|
||||||
|
UnsubscribePostURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Template markers. The CTA cut spans the button row AND the fallback-link
|
||||||
|
// row (both are meaningless without a URL); the note cut spans the optional
|
||||||
|
// note block. Anchors must stay in sync with template.html — Render errors
|
||||||
|
// (and the unit tests fail) if the design drifts away from them.
|
||||||
|
const (
|
||||||
|
ctaStartMarker = "<!-- Button (bulletproof, with Outlook fallback) -->"
|
||||||
|
noteStartMarker = "<!-- Note block"
|
||||||
|
signOffMarker = "<!-- Sign-off -->"
|
||||||
|
bodyStartAnchor = `<p style="margin:0 0 16px 0;">{{body_paragraph_1}}</p>`
|
||||||
|
bodyEndAnchor = `<p style="margin:0;">{{body_paragraph_2}}</p>`
|
||||||
|
addressParagraph = `<p style="margin:0;">Superbrain, {{company_address}}</p>`
|
||||||
|
footerLinkAnchor = "{{preferences_url}}"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Render fills the embedded template for one message. An error means the
|
||||||
|
// template no longer matches the renderer's anchors (a programming error,
|
||||||
|
// caught by tests); callers degrade to plain text rather than block mail.
|
||||||
|
func Render(subject string, c Content) (string, error) {
|
||||||
|
s := emailTemplate
|
||||||
|
var err error
|
||||||
|
|
||||||
|
headline := c.Headline
|
||||||
|
if headline == "" {
|
||||||
|
headline = subject
|
||||||
|
}
|
||||||
|
paras := paragraphs(c.Body)
|
||||||
|
preheader := c.Preheader
|
||||||
|
if preheader == "" && len(paras) > 0 {
|
||||||
|
preheader = paras[0]
|
||||||
|
}
|
||||||
|
if preheader == "" {
|
||||||
|
preheader = headline
|
||||||
|
}
|
||||||
|
preheader = truncateRunes(preheader, 90)
|
||||||
|
|
||||||
|
// Optional CTA: without a URL, drop the button and fallback-link rows.
|
||||||
|
if c.CTAURL == "" {
|
||||||
|
s, err = cutSpan(s, ctaStartMarker, noteStartMarker)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
label := c.CTALabel
|
||||||
|
if label == "" {
|
||||||
|
label = "Open Superbrain"
|
||||||
|
}
|
||||||
|
s = strings.ReplaceAll(s, "{{cta_url}}", html.EscapeString(c.CTAURL))
|
||||||
|
s = strings.ReplaceAll(s, "{{cta_label}}", html.EscapeString(label))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional note block.
|
||||||
|
if c.Note == "" {
|
||||||
|
s, err = cutSpan(s, noteStartMarker, signOffMarker)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
s = strings.ReplaceAll(s, "{{note_text}}", html.EscapeString(c.Note))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Greeting: a missing name must not render "Hi ,".
|
||||||
|
greeting := "Hi,"
|
||||||
|
if c.FirstName != "" {
|
||||||
|
greeting = "Hi " + html.EscapeString(c.FirstName) + ","
|
||||||
|
}
|
||||||
|
s = strings.Replace(s, "Hi {{first_name}},", greeting, 1)
|
||||||
|
|
||||||
|
// Body: replace the two placeholder paragraphs with one <p> per line.
|
||||||
|
var b strings.Builder
|
||||||
|
for i, p := range paras {
|
||||||
|
style := "margin:0 0 16px 0;"
|
||||||
|
if i == len(paras)-1 {
|
||||||
|
style = "margin:0;"
|
||||||
|
}
|
||||||
|
if i > 0 {
|
||||||
|
b.WriteString("\n ")
|
||||||
|
}
|
||||||
|
b.WriteString(`<p style="` + style + `">` + html.EscapeString(p) + `</p>`)
|
||||||
|
}
|
||||||
|
s, err = replaceSpan(s, bodyStartAnchor, bodyEndAnchor, b.String())
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
signOff := c.SignOff
|
||||||
|
if signOff == "" {
|
||||||
|
signOff = "Thanks,"
|
||||||
|
}
|
||||||
|
s = strings.ReplaceAll(s, "{{sign_off}}", html.EscapeString(signOff))
|
||||||
|
s = strings.ReplaceAll(s, "{{subject}}", html.EscapeString(subject))
|
||||||
|
s = strings.ReplaceAll(s, "{{preheader_text}}", html.EscapeString(preheader))
|
||||||
|
s = strings.ReplaceAll(s, "{{headline}}", html.EscapeString(headline))
|
||||||
|
|
||||||
|
// Footer links: keep only the ones with a URL; drop the whole paragraph
|
||||||
|
// when none are configured (the product has no preference/help pages yet).
|
||||||
|
s, err = renderFooterLinks(s, c)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if c.CompanyAddress == "" {
|
||||||
|
s = strings.Replace(s, addressParagraph, "", 1)
|
||||||
|
} else {
|
||||||
|
s = strings.ReplaceAll(s, "{{company_address}}", html.EscapeString(c.CompanyAddress))
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(s, "{{") {
|
||||||
|
return "", errors.New("mailer: template has unfilled placeholders")
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderFooterLinks(s string, c Content) (string, error) {
|
||||||
|
var links []string
|
||||||
|
for _, l := range []struct{ url, label string }{
|
||||||
|
{c.PreferencesURL, "Email preferences"},
|
||||||
|
{c.UnsubscribeURL, "Unsubscribe"},
|
||||||
|
{c.HelpURL, "Help center"},
|
||||||
|
} {
|
||||||
|
if l.url == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
links = append(links, `<a href="`+html.EscapeString(l.url)+`" class="t-accent" style="color:#3646E8; text-decoration:underline;">`+l.label+`</a>`)
|
||||||
|
}
|
||||||
|
start, end, err := paragraphSpan(s, footerLinkAnchor)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(links) == 0 {
|
||||||
|
return s[:start] + s[end:], nil
|
||||||
|
}
|
||||||
|
repl := `<p style="margin:0 0 8px 0;">` + strings.Join(links, " | ") + `</p>`
|
||||||
|
return s[:start] + repl + s[end:], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// paragraphs splits body text into trimmed, non-empty lines.
|
||||||
|
func paragraphs(body string) []string {
|
||||||
|
var out []string
|
||||||
|
for _, line := range strings.Split(body, "\n") {
|
||||||
|
if line = strings.TrimSpace(line); line != "" {
|
||||||
|
out = append(out, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncateRunes(s string, n int) string {
|
||||||
|
r := []rune(s)
|
||||||
|
if len(r) <= n {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return string(r[:n])
|
||||||
|
}
|
||||||
|
|
||||||
|
// cutSpan removes [startMarker, endMarker) — the end marker stays for the
|
||||||
|
// next cut. Both markers must exist.
|
||||||
|
func cutSpan(s, startMarker, endMarker string) (string, error) {
|
||||||
|
i := strings.Index(s, startMarker)
|
||||||
|
if i < 0 {
|
||||||
|
return "", fmt.Errorf("mailer: template marker %q not found", startMarker)
|
||||||
|
}
|
||||||
|
j := strings.Index(s[i:], endMarker)
|
||||||
|
if j < 0 {
|
||||||
|
return "", fmt.Errorf("mailer: template marker %q not found", endMarker)
|
||||||
|
}
|
||||||
|
return s[:i] + s[i+j:], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// replaceSpan swaps [startAnchor, endAnchor] (inclusive) for repl.
|
||||||
|
func replaceSpan(s, startAnchor, endAnchor, repl string) (string, error) {
|
||||||
|
i := strings.Index(s, startAnchor)
|
||||||
|
if i < 0 {
|
||||||
|
return "", fmt.Errorf("mailer: template anchor %q not found", startAnchor)
|
||||||
|
}
|
||||||
|
j := strings.Index(s[i:], endAnchor)
|
||||||
|
if j < 0 {
|
||||||
|
return "", fmt.Errorf("mailer: template anchor %q not found", endAnchor)
|
||||||
|
}
|
||||||
|
return s[:i] + repl + s[i+j+len(endAnchor):], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// paragraphSpan locates the <p>…</p> enclosing anchor.
|
||||||
|
func paragraphSpan(s, anchor string) (start, end int, err error) {
|
||||||
|
i := strings.Index(s, anchor)
|
||||||
|
if i < 0 {
|
||||||
|
return 0, 0, fmt.Errorf("mailer: template anchor %q not found", anchor)
|
||||||
|
}
|
||||||
|
start = strings.LastIndex(s[:i], "<p")
|
||||||
|
j := strings.Index(s[i:], "</p>")
|
||||||
|
if start < 0 || j < 0 {
|
||||||
|
return 0, 0, errors.New("mailer: template paragraph around anchor not found")
|
||||||
|
}
|
||||||
|
return start, i + j + len("</p>"), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
package mailer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The renderer and the embedded design file are one unit: these tests pin
|
||||||
|
// the anchors so a template edit that drops a marker fails loudly instead
|
||||||
|
// of silently shipping unfilled placeholders.
|
||||||
|
|
||||||
|
func TestRenderFull(t *testing.T) {
|
||||||
|
html, err := Render("Reset your Superbrain password", Content{
|
||||||
|
Preheader: "Choose a new password.",
|
||||||
|
Headline: "Reset your password",
|
||||||
|
FirstName: "Alice",
|
||||||
|
Body: "First paragraph.\nSecond paragraph.",
|
||||||
|
CTAURL: "https://superbrain.test/reset-password?token=abc",
|
||||||
|
CTALabel: "Choose a new password",
|
||||||
|
Note: "The link expires in 30 minutes.",
|
||||||
|
SignOff: "Cheers,",
|
||||||
|
PreferencesURL: "https://superbrain.test/settings",
|
||||||
|
UnsubscribeURL: "https://superbrain.test/unsubscribe",
|
||||||
|
HelpURL: "https://superbrain.test/help",
|
||||||
|
CompanyAddress: "1 Example Way, Testville",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, want := range []string{
|
||||||
|
"Reset your password", "Hi Alice,", "First paragraph.", "Second paragraph.",
|
||||||
|
"Choose a new password", "https://superbrain.test/reset-password?token=abc",
|
||||||
|
"v:roundrect", "If the button doesn't work", // Outlook fallback + plain link
|
||||||
|
"The link expires in 30 minutes.", "Cheers,", "The Superbrain team",
|
||||||
|
"Email preferences", "Unsubscribe", "Help center", "1 Example Way, Testville",
|
||||||
|
"Choose a new password.", // preheader
|
||||||
|
} {
|
||||||
|
if !strings.Contains(html, want) {
|
||||||
|
t.Errorf("rendered mail missing %q", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(html, "{{") {
|
||||||
|
t.Errorf("unfilled placeholder remains:\n%s", html)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderMinimal(t *testing.T) {
|
||||||
|
html, err := Render("Bookmark due: Due soon", Content{
|
||||||
|
Headline: "Bookmark due: Due soon",
|
||||||
|
Body: "Due soon is due in 6 hours.",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(html, "{{") {
|
||||||
|
t.Errorf("unfilled placeholder remains:\n%s", html)
|
||||||
|
}
|
||||||
|
// Optional sections are removed, not stubbed.
|
||||||
|
for _, absent := range []string{
|
||||||
|
"v:roundrect", "If the button doesn't work", // CTA + fallback rows
|
||||||
|
`<td class="bg-note`, // note block
|
||||||
|
"Email preferences", // footer links paragraph
|
||||||
|
"Superbrain, ", // address line
|
||||||
|
"Hi ,", // broken greeting
|
||||||
|
} {
|
||||||
|
if strings.Contains(html, absent) {
|
||||||
|
t.Errorf("minimal render still contains %q", absent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, want := range []string{"Hi,", "Bookmark due: Due soon", "Due soon is due in 6 hours.", "Thanks,"} {
|
||||||
|
if !strings.Contains(html, want) {
|
||||||
|
t.Errorf("minimal render missing %q", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderEscaping(t *testing.T) {
|
||||||
|
html, err := Render(`Subject "<x>"`, Content{
|
||||||
|
Headline: `<script>alert(1)</script>`,
|
||||||
|
FirstName: `Ann<script>`,
|
||||||
|
Body: `<img src=x onerror=alert(1)> & "quotes"`,
|
||||||
|
CTAURL: `https://x.test/"onmouseover="alert(1)`,
|
||||||
|
Note: `<b>note</b>`,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, absent := range []string{
|
||||||
|
"<script>alert(1)</script>", "Ann<script>", "<img src=x", `"onmouseover="`, "<b>note</b>",
|
||||||
|
} {
|
||||||
|
if strings.Contains(html, absent) {
|
||||||
|
t.Errorf("unescaped value %q survived rendering", absent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, want := range []string{"<script>", "&", """} {
|
||||||
|
if !strings.Contains(html, want) {
|
||||||
|
t.Errorf("expected escaped form %q", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderBodyParagraphs(t *testing.T) {
|
||||||
|
html, err := Render("s", Content{Headline: "h", Body: "one\n\n two \nthree\n"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, want := range []string{
|
||||||
|
`<p style="margin:0 0 16px 0;">one</p>`,
|
||||||
|
`<p style="margin:0 0 16px 0;">two</p>`,
|
||||||
|
`<p style="margin:0;">three</p>`, // last paragraph loses the bottom margin
|
||||||
|
} {
|
||||||
|
if !strings.Contains(html, want) {
|
||||||
|
t.Errorf("missing paragraph %q", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Empty body: greeting survives, no placeholder paragraphs remain.
|
||||||
|
html, err = Render("s", Content{Headline: "h"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(html, "{{") || !strings.Contains(html, "Hi,") {
|
||||||
|
t.Errorf("empty-body render broken:\n%s", html)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderDefaults(t *testing.T) {
|
||||||
|
html, err := Render("Fallback subject", Content{
|
||||||
|
Body: strings.Repeat("x", 120),
|
||||||
|
CTAURL: "https://superbrain.test/",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(html, "<h1") || !strings.Contains(html, "Fallback subject") {
|
||||||
|
t.Error("headline must fall back to the subject")
|
||||||
|
}
|
||||||
|
if !strings.Contains(html, "Open Superbrain") {
|
||||||
|
t.Error("CTA label must default to Open Superbrain")
|
||||||
|
}
|
||||||
|
// Preheader defaults to the first paragraph, truncated to 90 runes.
|
||||||
|
pre := html[strings.Index(html, `opacity:0;">`)+len(`opacity:0;">`):]
|
||||||
|
pre = strings.TrimSpace(pre[:strings.Index(pre, "͏")])
|
||||||
|
if pre != strings.Repeat("x", 90) {
|
||||||
|
t.Errorf("preheader = %q, want 90 x's", pre)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderTemplateDrift(t *testing.T) {
|
||||||
|
saved := emailTemplate
|
||||||
|
defer func() { emailTemplate = saved }()
|
||||||
|
emailTemplate = "<html>{{headline}} only</html>"
|
||||||
|
if _, err := Render("s", Content{Headline: "h"}); err == nil {
|
||||||
|
t.Fatal("Render must error when the template loses its anchors")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildMessagePlain(t *testing.T) {
|
||||||
|
msg := buildMessage("from@x.test", "to@x.test", "hi\r\nBcc: evil@x.test", "body", "", "")
|
||||||
|
if strings.Contains(msg, "\r\nBcc:") {
|
||||||
|
t.Fatal("header injection via subject survived")
|
||||||
|
}
|
||||||
|
if !strings.Contains(msg, "Content-Type: text/plain; charset=UTF-8") {
|
||||||
|
t.Fatal("plain message lost its content type")
|
||||||
|
}
|
||||||
|
if strings.Contains(msg, "multipart") {
|
||||||
|
t.Fatal("plain message must not be multipart")
|
||||||
|
}
|
||||||
|
if strings.Contains(msg, "List-Unsubscribe") {
|
||||||
|
t.Fatal("plain message without an unsubscribe URL must not carry the headers")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildMessageMultipart(t *testing.T) {
|
||||||
|
text := "plain alternative\nwith a link https://x.test/"
|
||||||
|
html := "<html>\n.dot line\n</html>"
|
||||||
|
msg := buildMessage("from@x.test", "to@x.test", "s", text, html, "")
|
||||||
|
if !strings.Contains(msg, "Content-Type: multipart/alternative; boundary=\"sb-") {
|
||||||
|
t.Fatalf("missing multipart header:\n%s", msg)
|
||||||
|
}
|
||||||
|
boundary := msg[strings.Index(msg, `boundary="`)+len(`boundary="`):]
|
||||||
|
boundary = boundary[:strings.Index(boundary, `"`)]
|
||||||
|
if n := strings.Count(msg, "--"+boundary); n != 3 {
|
||||||
|
t.Fatalf("boundary appears %d times, want 3 (two parts + close)", n)
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(msg, "--"+boundary+"--\r\n") {
|
||||||
|
t.Fatal("multipart close delimiter missing")
|
||||||
|
}
|
||||||
|
if strings.Index(msg, "text/plain") > strings.Index(msg, "text/html") {
|
||||||
|
t.Fatal("RFC 2046: the plain alternative must come first")
|
||||||
|
}
|
||||||
|
if !strings.Contains(msg, "\r\n..dot line") {
|
||||||
|
t.Fatal("HTML part must be dot-stuffed")
|
||||||
|
}
|
||||||
|
if !strings.Contains(msg, smtpBody(text)) {
|
||||||
|
t.Fatal("plain alternative missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSMTPBody(t *testing.T) {
|
||||||
|
got := smtpBody(".start\nmid\r\n.dot\n")
|
||||||
|
want := "..start\r\nmid\r\n..dot\r\n"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("smtpBody = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildMessageListUnsubscribe(t *testing.T) {
|
||||||
|
msg := buildMessage("from@x.test", "to@x.test", "s", "text", "<html></html>",
|
||||||
|
"https://x.test/api/notifications/unsubscribe?token=abc\r\nBcc: evil@x.test")
|
||||||
|
if !strings.Contains(msg, "List-Unsubscribe: <https://x.test/api/notifications/unsubscribe?token=abc") {
|
||||||
|
t.Fatalf("List-Unsubscribe header missing:\n%s", msg)
|
||||||
|
}
|
||||||
|
if !strings.Contains(msg, "List-Unsubscribe-Post: List-Unsubscribe=One-Click\r\n") {
|
||||||
|
t.Fatal("RFC 8058 one-click header missing")
|
||||||
|
}
|
||||||
|
if strings.Contains(msg, "\r\nBcc:") {
|
||||||
|
t.Fatal("header injection via the unsubscribe URL survived")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="x-apple-disable-message-reformatting">
|
||||||
|
<meta name="color-scheme" content="light dark">
|
||||||
|
<meta name="supported-color-schemes" content="light dark">
|
||||||
|
<title>{{subject}}</title>
|
||||||
|
<!--[if mso]>
|
||||||
|
<noscript><xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml></noscript>
|
||||||
|
<style>td,th,div,p,a,h1,span{font-family:Arial,Helvetica,sans-serif !important;}</style>
|
||||||
|
<![endif]-->
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:wght@500;700&display=swap" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
body, table, td, a { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
|
||||||
|
table, td { mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
|
||||||
|
img { border: 0; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; }
|
||||||
|
body { margin: 0 !important; padding: 0 !important; width: 100% !important; }
|
||||||
|
a[x-apple-data-detectors] { color: inherit !important; text-decoration: none !important; }
|
||||||
|
|
||||||
|
@media screen and (max-width: 620px) {
|
||||||
|
.container { width: 100% !important; }
|
||||||
|
.px { padding-left: 24px !important; padding-right: 24px !important; }
|
||||||
|
.headline { font-size: 28px !important; line-height: 34px !important; }
|
||||||
|
.btn a { display: block !important; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dark mode (Apple Mail, iOS Mail, Outlook for Mac/iOS, some Android clients) */
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.bg-outer { background-color: #0E1024 !important; }
|
||||||
|
.bg-card { background-color: #181B36 !important; }
|
||||||
|
.bg-note { background-color: #22264A !important; }
|
||||||
|
.t-ink { color: #ECEDF8 !important; }
|
||||||
|
.t-muted { color: #A3A7C9 !important; }
|
||||||
|
.t-accent { color: #9AA4FF !important; }
|
||||||
|
.rule { border-color: #2C3060 !important; }
|
||||||
|
}
|
||||||
|
[data-ogsc] .bg-outer { background-color: #0E1024 !important; }
|
||||||
|
[data-ogsc] .bg-card { background-color: #181B36 !important; }
|
||||||
|
[data-ogsc] .bg-note { background-color: #22264A !important; }
|
||||||
|
[data-ogsc] .t-ink { color: #ECEDF8 !important; }
|
||||||
|
[data-ogsc] .t-muted { color: #A3A7C9 !important; }
|
||||||
|
[data-ogsc] .t-accent { color: #9AA4FF !important; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body class="bg-outer" style="margin:0; padding:0; background-color:#ECEEF6;">
|
||||||
|
|
||||||
|
<!-- Preheader: the preview line shown in the inbox. Keep it under ~90 characters. -->
|
||||||
|
<div style="display:none; max-height:0; overflow:hidden; mso-hide:all; font-size:1px; line-height:1px; color:#ECEEF6; opacity:0;">
|
||||||
|
{{preheader_text}}͏‌ ͏‌ ͏‌ ͏‌ ͏‌
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<table role="presentation" class="bg-outer" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#ECEEF6;">
|
||||||
|
<tr>
|
||||||
|
<td align="center" style="padding:40px 12px;">
|
||||||
|
|
||||||
|
<table role="presentation" class="container" width="600" cellpadding="0" cellspacing="0" border="0" style="width:600px; max-width:600px;">
|
||||||
|
|
||||||
|
<!-- Wordmark -->
|
||||||
|
<tr>
|
||||||
|
<td class="px" style="padding:0 40px 20px 40px;">
|
||||||
|
<table role="presentation" cellpadding="0" cellspacing="0" border="0">
|
||||||
|
<tr>
|
||||||
|
<td width="14" height="14" style="width:14px; height:14px; background-color:#3646E8; border-radius:7px; font-size:0; line-height:0;"> </td>
|
||||||
|
<td width="6" style="font-size:0;"> </td>
|
||||||
|
<td width="8" height="8" style="width:8px; height:8px; background-color:#9AA4FF; border-radius:4px; font-size:0; line-height:0;"> </td>
|
||||||
|
<td style="padding-left:10px; font-family:'Bricolage Grotesque', Arial, Helvetica, sans-serif; font-size:20px; font-weight:700; letter-spacing:-0.3px; color:#1A1D3A;" class="t-ink">
|
||||||
|
superbrain
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
<!-- Card -->
|
||||||
|
<tr>
|
||||||
|
<td class="bg-card" style="background-color:#FFFFFF; border-radius:16px; border-top:6px solid #3646E8;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
|
||||||
|
|
||||||
|
<!-- Headline -->
|
||||||
|
<tr>
|
||||||
|
<td class="px" style="padding:44px 48px 12px 48px;">
|
||||||
|
<h1 class="headline t-ink" style="margin:0; font-family:'Bricolage Grotesque', Arial, Helvetica, sans-serif; font-size:34px; line-height:40px; font-weight:700; letter-spacing:-0.8px; color:#1A1D3A;">
|
||||||
|
{{headline}}
|
||||||
|
</h1>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
<!-- Body -->
|
||||||
|
<tr>
|
||||||
|
<td class="px t-ink" style="padding:12px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:16px; line-height:26px; color:#2E3254;">
|
||||||
|
<p style="margin:0 0 16px 0;">Hi {{first_name}},</p>
|
||||||
|
<p style="margin:0 0 16px 0;">{{body_paragraph_1}}</p>
|
||||||
|
<p style="margin:0;">{{body_paragraph_2}}</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
<!-- Button (bulletproof, with Outlook fallback) -->
|
||||||
|
<tr>
|
||||||
|
<td class="px btn" style="padding:32px 48px 8px 48px;">
|
||||||
|
<!--[if mso]>
|
||||||
|
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" href="{{cta_url}}" style="height:50px; v-text-anchor:middle; width:240px;" arcsize="20%" stroke="f" fillcolor="#3646E8">
|
||||||
|
<w:anchorlock/>
|
||||||
|
<center style="color:#ffffff; font-family:Arial,sans-serif; font-size:16px; font-weight:bold;">{{cta_label}}</center>
|
||||||
|
</v:roundrect>
|
||||||
|
<![endif]-->
|
||||||
|
<!--[if !mso]><!-->
|
||||||
|
<a href="{{cta_url}}" style="display:inline-block; background-color:#3646E8; color:#FFFFFF; font-family:Arial, Helvetica, sans-serif; font-size:16px; font-weight:700; line-height:50px; text-align:center; text-decoration:none; padding:0 32px; border-radius:10px;">
|
||||||
|
{{cta_label}}
|
||||||
|
</a>
|
||||||
|
<!--<![endif]-->
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
<!-- Fallback link -->
|
||||||
|
<tr>
|
||||||
|
<td class="px t-muted" style="padding:12px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:13px; line-height:20px; color:#6A6F92;">
|
||||||
|
If the button doesn't work, paste this link into your browser:<br>
|
||||||
|
<a href="{{cta_url}}" class="t-accent" style="color:#3646E8; word-break:break-all;">{{cta_url}}</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
<!-- Note block (optional — delete this row if not needed) -->
|
||||||
|
<tr>
|
||||||
|
<td class="px" style="padding:32px 48px 0 48px;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
|
||||||
|
<tr>
|
||||||
|
<td class="bg-note t-ink" style="background-color:#EEF0FF; border-radius:10px; padding:18px 20px; font-family:Arial, Helvetica, sans-serif; font-size:14px; line-height:22px; color:#2E3254;">
|
||||||
|
{{note_text}}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
<!-- Sign-off -->
|
||||||
|
<tr>
|
||||||
|
<td class="px t-ink" style="padding:32px 48px 44px 48px; font-family:Arial, Helvetica, sans-serif; font-size:16px; line-height:26px; color:#2E3254;">
|
||||||
|
{{sign_off}}<br>
|
||||||
|
The Superbrain team
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
</table>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
<!-- Footer -->
|
||||||
|
<tr>
|
||||||
|
<td class="px t-muted" style="padding:28px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:19px; color:#6A6F92;">
|
||||||
|
<p style="margin:0 0 8px 0;">You're receiving this email because you have a Superbrain account.</p>
|
||||||
|
<p style="margin:0 0 8px 0;">
|
||||||
|
<a href="{{preferences_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Email preferences</a>
|
||||||
|
|
|
||||||
|
<a href="{{unsubscribe_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Unsubscribe</a>
|
||||||
|
|
|
||||||
|
<a href="{{help_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Help center</a>
|
||||||
|
</p>
|
||||||
|
<p style="margin:0;">Superbrain, {{company_address}}</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
</table>
|
||||||
|
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -91,7 +91,7 @@ func httpClient(conn Conn) *http.Client {
|
|||||||
// ListTools connects, initializes and lists the server's tools, then closes
|
// ListTools connects, initializes and lists the server's tools, then closes
|
||||||
// the session. The context bounds the whole exchange.
|
// the session. The context bounds the whole exchange.
|
||||||
func ListTools(ctx context.Context, conn Conn) ([]Tool, error) {
|
func ListTools(ctx context.Context, conn Conn) ([]Tool, error) {
|
||||||
client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "superbrain", Version: "0.2.16"}, nil)
|
client := mcpsdk.NewClient(&mcpsdk.Implementation{Name: "superbrain", Version: "0.2.17"}, nil)
|
||||||
var transport mcpsdk.Transport
|
var transport mcpsdk.Transport
|
||||||
hc := httpClient(conn)
|
hc := httpClient(conn)
|
||||||
switch conn.Transport {
|
switch conn.Transport {
|
||||||
|
|||||||
@@ -24,6 +24,12 @@ type User struct {
|
|||||||
TenantID *string
|
TenantID *string
|
||||||
CreatedAt string
|
CreatedAt string
|
||||||
UpdatedAt 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.
|
// Account, Session, VerificationToken are auth-library tables. Porting guide 2.3.
|
||||||
|
|||||||
@@ -255,7 +255,9 @@ func Send(ctx context.Context, d *db.DB, ch Channel, title, body string) error {
|
|||||||
}
|
}
|
||||||
to = *email
|
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":
|
case "slack":
|
||||||
return postJSON(ctx, ch.Config["webhookUrl"], nil, map[string]any{"text": text}, []int{200})
|
return postJSON(ctx, ch.Config["webhookUrl"], nil, map[string]any{"text": text}, []int{200})
|
||||||
case "matrix":
|
case "matrix":
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package notify
|
||||||
|
|
||||||
|
// Email footer links and the unsubscribe token. The token is a stable,
|
||||||
|
// HMAC-signed user id (no stored row, no expiry): every notification mail
|
||||||
|
// carries the same link, and rotating AUTH_SECRET invalidates outstanding
|
||||||
|
// links exactly like sessions. Unsubscribe is a NOTIFICATION preference —
|
||||||
|
// transactional mail (password reset) is never gated by it.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/andrew/superbrain/internal/config"
|
||||||
|
"github.com/andrew/superbrain/internal/db"
|
||||||
|
"github.com/andrew/superbrain/internal/mailer"
|
||||||
|
)
|
||||||
|
|
||||||
|
// unsubscribeDomain separates these MACs from every other use of the
|
||||||
|
// signing secret (assertions, forwarded-IP attestation, ...).
|
||||||
|
const unsubscribeDomain = "superbrain-unsubscribe:"
|
||||||
|
|
||||||
|
// UnsubscribeToken returns the signed unsubscribe token for a user. IDs
|
||||||
|
// are 32-char hex (db.NewID), so the single "." separator is unambiguous.
|
||||||
|
func UnsubscribeToken(userID string) string {
|
||||||
|
mac := hmac.New(sha256.New, []byte(config.Load().Secret()))
|
||||||
|
mac.Write([]byte(unsubscribeDomain + userID))
|
||||||
|
return userID + "." + hex.EncodeToString(mac.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseUnsubscribeToken validates a token and returns the user id it
|
||||||
|
// carries. The comparison is constant-time; a tampered or foreign-secret
|
||||||
|
// token never resolves an identity.
|
||||||
|
func ParseUnsubscribeToken(token string) (string, bool) {
|
||||||
|
userID, sig, ok := strings.Cut(token, ".")
|
||||||
|
if !ok || userID == "" || sig == "" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, []byte(config.Load().Secret()))
|
||||||
|
mac.Write([]byte(unsubscribeDomain + userID))
|
||||||
|
want := hex.EncodeToString(mac.Sum(nil))
|
||||||
|
if !hmac.Equal([]byte(want), []byte(sig)) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return userID, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// FooterLinks builds the branded email footer for a message to recipient.
|
||||||
|
// Preferences and Help are offered whenever the deployment has a public
|
||||||
|
// origin (NEXTAUTH_URL). Unsubscribe is offered ONLY when recipient is the
|
||||||
|
// owner's own account email: a third-party recipient (a channel address or
|
||||||
|
// an agent task's To) must never receive a link that changes the owner's
|
||||||
|
// settings. With no origin configured every link stays empty and the
|
||||||
|
// renderer omits the footer sections.
|
||||||
|
func FooterLinks(ctx context.Context, d *db.DB, ownerID, recipient string) mailer.Content {
|
||||||
|
var c mailer.Content
|
||||||
|
base := strings.TrimRight(strings.TrimSpace(config.Load().NextAuthURL), "/")
|
||||||
|
if base == "" {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
c.PreferencesURL = base + "/settings?tab=notifications"
|
||||||
|
c.HelpURL = base + "/help"
|
||||||
|
var email *string
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT email FROM "User" WHERE id=$1`, ownerID).Scan(&email); err != nil {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
if email == nil || *email == "" || !strings.EqualFold(strings.TrimSpace(recipient), *email) {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
token := UnsubscribeToken(ownerID)
|
||||||
|
c.UnsubscribeURL = base + "/unsubscribe?token=" + token
|
||||||
|
c.UnsubscribePostURL = base + "/api/notifications/unsubscribe?token=" + token
|
||||||
|
return c
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUnsubscribeTokenRoundtrip(t *testing.T) {
|
||||||
|
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
|
||||||
|
tok := UnsubscribeToken("0123456789abcdef0123456789abcdef")
|
||||||
|
id, ok := ParseUnsubscribeToken(tok)
|
||||||
|
if !ok || id != "0123456789abcdef0123456789abcdef" {
|
||||||
|
t.Fatalf("roundtrip = %q, %v", id, ok)
|
||||||
|
}
|
||||||
|
// Stable: every mail to the same user carries the same link.
|
||||||
|
if UnsubscribeToken("0123456789abcdef0123456789abcdef") != tok {
|
||||||
|
t.Fatal("token must be stable across issuances")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnsubscribeTokenRejectsTampering(t *testing.T) {
|
||||||
|
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
|
||||||
|
const id = "0123456789abcdef0123456789abcdef"
|
||||||
|
tok := UnsubscribeToken(id)
|
||||||
|
_, mac, _ := strings.Cut(tok, ".")
|
||||||
|
|
||||||
|
// A token minted under a different secret must not verify here.
|
||||||
|
t.Setenv("AUTH_SECRET", "a-different-secret")
|
||||||
|
foreign := UnsubscribeToken(id)
|
||||||
|
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
|
||||||
|
|
||||||
|
cases := []struct{ name, token string }{
|
||||||
|
{"swapped id", "ffffffffffffffffffffffffffffffff." + mac},
|
||||||
|
{"flipped mac", id + "." + strings.Repeat("0", 63) + "1"},
|
||||||
|
{"truncated mac", tok[:len(tok)-1]},
|
||||||
|
{"no separator", strings.ReplaceAll(tok, ".", "")},
|
||||||
|
{"empty id", "." + mac},
|
||||||
|
{"empty mac", id + "."},
|
||||||
|
{"empty token", ""},
|
||||||
|
{"foreign secret", foreign},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if _, ok := ParseUnsubscribeToken(c.token); ok {
|
||||||
|
t.Errorf("%s accepted", c.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -7,7 +7,7 @@ name = "superbrain-mcp"
|
|||||||
# Versioned in lockstep with the Superbrain release it speaks to (house
|
# Versioned in lockstep with the Superbrain release it speaks to (house
|
||||||
# tooling tracks one version per app); the federated mcpserver gateway
|
# tooling tracks one version per app); the federated mcpserver gateway
|
||||||
# installs this package and spawns `superbrain-mcp` per linked instance.
|
# installs this package and spawns `superbrain-mcp` per linked instance.
|
||||||
version = "0.2.16"
|
version = "0.2.17"
|
||||||
description = "MCP server for Superbrain — bookmarks, tags and pages over the Superbrain REST API"
|
description = "MCP server for Superbrain — bookmarks, tags and pages over the Superbrain REST API"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
"""Superbrain MCP server — bookmarks, tags and pages for AI tooling."""
|
"""Superbrain MCP server — bookmarks, tags and pages for AI tooling."""
|
||||||
|
|
||||||
__version__ = "0.2.16"
|
__version__ = "0.2.17"
|
||||||
|
|||||||
+48
-2
@@ -70,6 +70,12 @@ const carddavConnections = [{
|
|||||||
lastSyncedAt: null, lastError: null, version: 1, createdAt: '2026-11-10T00:00:00Z', updatedAt: '2026-11-10T00:00:00Z',
|
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/' }]
|
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) => {
|
const api = http.createServer(async (req, res) => {
|
||||||
try {
|
try {
|
||||||
let raw = ''
|
let raw = ''
|
||||||
@@ -86,13 +92,24 @@ const api = http.createServer(async (req, res) => {
|
|||||||
const body = raw ? JSON.parse(raw) : {}
|
const body = raw ? JSON.parse(raw) : {}
|
||||||
const url = new URL(req.url, 'http://fixture')
|
const url = new URL(req.url, 'http://fixture')
|
||||||
let result = []
|
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') {
|
else if (url.pathname === '/api/auth/signout' && req.method === 'POST') {
|
||||||
signouts.push(req.headers.authorization || '')
|
signouts.push(req.headers.authorization || '')
|
||||||
if (failSignout) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end('{"error":"Fixture revocation failed"}'); return }
|
if (failSignout) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end('{"error":"Fixture revocation failed"}'); return }
|
||||||
result = { ok: true }
|
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).
|
// The list endpoint is a metadata projection: content bodies stay out (PERF-01).
|
||||||
else if (url.pathname === '/api/pages') {
|
else if (url.pathname === '/api/pages') {
|
||||||
if (req.method === 'PUT') {
|
if (req.method === 'PUT') {
|
||||||
@@ -680,6 +697,35 @@ try {
|
|||||||
await eventually(() => pages.get('a')?.position === 0 && pages.get('b')?.position === 1, 'Sidebar page drag did not reorder')
|
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')
|
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
|
// Settings → WebDAV: masked list rows render; the deployment suggestion
|
||||||
// (NEXTCLOUD_URL) prefills the connect form with the username composed into
|
// (NEXTCLOUD_URL) prefills the connect form with the username composed into
|
||||||
// the per-user DAV root;
|
// the per-user DAV root;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useState, useEffect, useCallback, Fragment } from 'react'
|
import { useState, useEffect, useCallback, Fragment } from 'react'
|
||||||
import { useSession } from 'next-auth/react'
|
import { useSearchParams } from 'next/navigation'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||||
@@ -9,6 +9,7 @@ import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, KeyRound, PlugZ
|
|||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
import { invalidateReference } from '@/lib/reference-data'
|
import { invalidateReference } from '@/lib/reference-data'
|
||||||
import { NotificationsSettings } from '@/components/notifications-settings'
|
import { NotificationsSettings } from '@/components/notifications-settings'
|
||||||
|
import { ProfileSettings } from '@/components/profile-settings'
|
||||||
import { AutomationsSettings } from '@/components/automations-settings'
|
import { AutomationsSettings } from '@/components/automations-settings'
|
||||||
import { AiSettings } from '@/components/ai-settings'
|
import { AiSettings } from '@/components/ai-settings'
|
||||||
import { ApiKeysSettings } from '@/components/api-keys-settings'
|
import { ApiKeysSettings } from '@/components/api-keys-settings'
|
||||||
@@ -49,18 +50,25 @@ const NAV_GROUPS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
|
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
|
||||||
const { data: session } = useSession()
|
// ?tab=<value> deep links (email footer "Email preferences" lands on
|
||||||
|
// notifications). Unknown values fall back to profile; the Radix tab
|
||||||
|
// values stay the canonical section ids.
|
||||||
|
const requestedTab = useSearchParams().get('tab') ?? ''
|
||||||
|
const initialSection = NAV_GROUPS.some(g => g.items.some(i => i.value === requestedTab))
|
||||||
|
? requestedTab
|
||||||
|
: 'profile'
|
||||||
const [imapConfig, setImapConfig] = useState({ host: '', port: 993, tls: true, username: '', password: '', folder: 'INBOX' })
|
const [imapConfig, setImapConfig] = useState({ host: '', port: 993, tls: true, username: '', password: '', folder: 'INBOX' })
|
||||||
const [ncConfig, setNcConfig] = useState({ nextcloudUrl: '', cardDavPath: '', username: '', password: '' })
|
const [ncConfig, setNcConfig] = useState({ nextcloudUrl: '', cardDavPath: '', username: '', password: '' })
|
||||||
const [savingImap, setSavingImap] = useState(false)
|
const [savingImap, setSavingImap] = useState(false)
|
||||||
const [testingImap, setTestingImap] = useState(false)
|
const [testingImap, setTestingImap] = useState(false)
|
||||||
const [syncingContacts, setSyncingContacts] = useState(false)
|
const [syncingContacts, setSyncingContacts] = useState(false)
|
||||||
const [section, setSection] = useState('profile')
|
const [section, setSection] = useState(initialSection)
|
||||||
// Below md the grouped nav becomes a list -> detail flow (same
|
// Below md the grouped nav becomes a list -> detail flow (same
|
||||||
// master-detail pattern as collections/tags/contacts); at md+ the
|
// master-detail pattern as collections/tags/contacts); at md+ the
|
||||||
// nav and the selected panel sit side by side.
|
// nav and the selected panel sit side by side. A deep link opens the
|
||||||
|
// detail pane directly on narrow screens.
|
||||||
const isNarrow = useMediaQuery('(max-width: 767px)')
|
const isNarrow = useMediaQuery('(max-width: 767px)')
|
||||||
const [mobileDetail, setMobileDetail] = useState(false)
|
const [mobileDetail, setMobileDetail] = useState(initialSection !== 'profile')
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch('/api/settings/imap').then(r => r.json()).then(data => {
|
fetch('/api/settings/imap').then(r => r.json()).then(data => {
|
||||||
@@ -171,15 +179,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<TabsContent value="profile" className="mt-0 space-y-4">
|
<TabsContent value="profile" className="mt-0 space-y-4">
|
||||||
<div className="flex items-center gap-4">
|
<ProfileSettings />
|
||||||
<div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-2xl font-bold text-primary">
|
|
||||||
{(session?.user?.name ?? session?.user?.email ?? '?')[0]?.toUpperCase()}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-medium">{session?.user?.name ?? 'User'}</p>
|
|
||||||
<p className="text-sm text-muted-foreground" suppressHydrationWarning>{session?.user?.email}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
<TabsContent value="oidc" className="mt-0 space-y-4">
|
<TabsContent value="oidc" className="mt-0 space-y-4">
|
||||||
<div className="rounded-lg border p-4 space-y-3">
|
<div className="rounded-lg border p-4 space-y-3">
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { SettingsClient } from './client'
|
import { SettingsClient } from './client'
|
||||||
import { getOidcStatus } from '@/lib/oidc-config'
|
import { getOidcStatus } from '@/lib/oidc-config'
|
||||||
import { headers } from 'next/headers'
|
import { headers } from 'next/headers'
|
||||||
|
import { Suspense } from 'react'
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
@@ -20,5 +21,11 @@ export default async function SettingsPage() {
|
|||||||
const proto = h.get('x-forwarded-proto') ?? 'http'
|
const proto = h.get('x-forwarded-proto') ?? 'http'
|
||||||
if (host) callbackUrl = `${proto}://${host}/api/auth/callback/authelia`
|
if (host) callbackUrl = `${proto}://${host}/api/auth/callback/authelia`
|
||||||
}
|
}
|
||||||
return <SettingsClient oidc={getOidcStatus()} callbackUrl={callbackUrl} />
|
// useSearchParams in the client (?tab= deep links, e.g. from email
|
||||||
|
// footers) needs a Suspense boundary for prerender.
|
||||||
|
return (
|
||||||
|
<Suspense>
|
||||||
|
<SettingsClient oidc={getOidcStatus()} callbackUrl={callbackUrl} />
|
||||||
|
</Suspense>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
|
||||||
|
|
||||||
|
const FAQ = [
|
||||||
|
{
|
||||||
|
q: 'How do I stop notification emails?',
|
||||||
|
a: 'Use the unsubscribe link in any notification email — it turns off your email channels and any automations that email you, without signing in. You can also toggle channels and rules in Settings → Notifications. Password resets and other account emails are not affected by unsubscribing.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'Why didn\u2019t my notification arrive?',
|
||||||
|
a: 'Check Settings → Notifications: the channel and the rule must both be enabled, and your plan must include the channel kind. History lists every delivery attempt, including suppressed ones (for example a recipient without a channel of that kind, or a plan downgrade). Email delivery also needs the operator to have configured an SMTP relay.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'Who can see a public bookmark link?',
|
||||||
|
a: 'Anyone with the link. It publishes the title, description, notes, due date, tags and preview — and deliberately no owner attribution. Treat public links as published content; revoking the public toggle stops access immediately.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'Can I use my own AI provider and key?',
|
||||||
|
a: 'Yes. Settings → AI stores your own OpenAI-compatible, Anthropic or Gemini key (encrypted, write-only). Your key is used before any server key, and the server key itself depends on your plan. Without any AI configured, AI features point you to Settings instead of failing silently.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'What happens when I delete a page or bookmark?',
|
||||||
|
a: 'Deletions are recoverable from Trash. Deleting a parent page promotes its children instead of deleting them, and page revisions let you restore earlier content. Note that restoring from Trash does not restore access grants — re-share if needed.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'How do I connect Nextcloud?',
|
||||||
|
a: 'Settings → WebDAV, CalDAV or CardDAV. On Core deployments the forms offer a prefill for your account\u2019s Nextcloud URL. Each connected share, calendar or address book becomes its own collection, synced on a schedule; files, events and contacts appear as bookmarks.',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
export function HelpFaq() {
|
||||||
|
return (
|
||||||
|
<Accordion type="single" collapsible className="mt-4">
|
||||||
|
{FAQ.map((item, i) => (
|
||||||
|
<AccordionItem key={i} value={`faq-${i}`}>
|
||||||
|
<AccordionTrigger className="text-sm font-medium">{item.q}</AccordionTrigger>
|
||||||
|
<AccordionContent className="text-sm leading-relaxed text-muted-foreground">
|
||||||
|
{item.a}
|
||||||
|
</AccordionContent>
|
||||||
|
</AccordionItem>
|
||||||
|
))}
|
||||||
|
</Accordion>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import Link from 'next/link'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { HelpFaq } from './faq'
|
||||||
|
import {
|
||||||
|
Bookmark, FolderOpen, FileText, Kanban, Radar, Bell, Bot,
|
||||||
|
FolderSync, KeyRound, ArrowRight,
|
||||||
|
} from 'lucide-react'
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
|
const SECTIONS = [
|
||||||
|
{
|
||||||
|
id: 'getting-started',
|
||||||
|
icon: ArrowRight,
|
||||||
|
title: 'Getting started',
|
||||||
|
body: [
|
||||||
|
'Sign in with your email and password, or with Authelia single sign-on if your deployment uses it. On first run, create your account from the sign-up page — then start by saving a bookmark, writing a page, or connecting a service in Settings.',
|
||||||
|
'Forgot your password? Use the "Forgot password?" link on the sign-in page; a single-use reset link is emailed to you. On single-sign-on deployments, recovery is handled by your identity provider instead.',
|
||||||
|
],
|
||||||
|
where: 'Sign in → /login · Reset → /forgot-password',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'bookmarks',
|
||||||
|
icon: Bookmark,
|
||||||
|
title: 'Bookmarks & tags',
|
||||||
|
body: [
|
||||||
|
'Every URL you save becomes a bookmark with a title, description, notes, tags and an optional due date. Open a bookmark to edit its details, attach it to pages and collections, or place it on the board.',
|
||||||
|
'Sharing a tag shares every bookmark under it with the recipients — group-wide, including bookmarks other recipients add later. A public bookmark link publishes the title, description, notes, due date, tags and preview to anyone with the link, and deliberately carries no owner attribution.',
|
||||||
|
],
|
||||||
|
where: 'Sidebar → Bookmarks · Tags',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'collections',
|
||||||
|
icon: FolderOpen,
|
||||||
|
title: 'Collections',
|
||||||
|
body: [
|
||||||
|
'Collections group bookmarks manually or by smart filters, and render as a table or a board grouped by any select property. Shared collections are read-only for recipients.',
|
||||||
|
'Connected services materialize as collections automatically: each WebDAV share, CalDAV calendar and CardDAV address book becomes its own collection whose files, events or contacts are bookmarks. Syncing mirrors the server — removed items detach, and your own removals stay removed.',
|
||||||
|
],
|
||||||
|
where: 'Sidebar → Collections · Settings → WebDAV / CalDAV / CardDAV',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'pages',
|
||||||
|
icon: FileText,
|
||||||
|
title: 'Pages',
|
||||||
|
body: [
|
||||||
|
'Pages are WYSIWYG documents stored as Markdown. Every URL you add — via the Link button, the links popover, or a bare-URL paste — is also saved as a bookmark linked to the page, reusing an existing bookmark for the same URL instead of duplicating it.',
|
||||||
|
'Pages can nest under a parent; deleting a parent promotes its children. Every save keeps a revision you can restore, and deleted pages are recoverable from Trash. Autosave pauses on a version conflict so you never clobber newer content.',
|
||||||
|
],
|
||||||
|
where: 'Sidebar → Pages · Trash',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'board',
|
||||||
|
icon: Kanban,
|
||||||
|
title: 'Kanban board',
|
||||||
|
body: [
|
||||||
|
'The board places bookmarks in columns you define. Drag cards between columns or reorder within a column; moves are saved immediately. Shared cards are read-only.',
|
||||||
|
],
|
||||||
|
where: 'Sidebar → Board',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'signals',
|
||||||
|
icon: Radar,
|
||||||
|
title: 'Signals & mailbox watches',
|
||||||
|
body: [
|
||||||
|
'Signals are events attached to bookmarks — notes, arrivals, reminders. Connect an IMAP mailbox in Settings and add a watch from a bookmark\'s Signals panel: matching emails become signals on that bookmark.',
|
||||||
|
],
|
||||||
|
where: 'Settings → IMAP · Bookmark → Signals',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'notifications',
|
||||||
|
icon: Bell,
|
||||||
|
title: 'Notifications',
|
||||||
|
body: [
|
||||||
|
'Notification rules fire on signals created, bookmarks coming due, or shares received, and deliver through your channels: email, Slack, Matrix, Telegram or Signal. Rules can target other people in your organization; each recipient gets the delivery through their own channel. History shows every delivery, including suppressed ones.',
|
||||||
|
'Email preferences live in Settings → Notifications. Every notification email also carries an unsubscribe link that turns off your email channels and any automations that email you — password resets and other account emails are not affected.',
|
||||||
|
],
|
||||||
|
where: 'Settings → Notifications',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'assistant',
|
||||||
|
icon: Bot,
|
||||||
|
title: 'Assistant & automations',
|
||||||
|
body: [
|
||||||
|
'The assistant answers questions about your data and can propose automations: stored tasks that periodically check a page and then notify you, send an email, or save a bookmark. Proposals are compiled into a validated spec and only run after you confirm them — the assistant never acts on its own.',
|
||||||
|
'AI features use your own provider key (Settings → AI) or the server key when your plan includes it. Without any AI configured, the app tells you where to add one instead of failing silently.',
|
||||||
|
],
|
||||||
|
where: 'Assistant panel · Settings → AI / Automations',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'connections',
|
||||||
|
icon: FolderSync,
|
||||||
|
title: 'Connections',
|
||||||
|
body: [
|
||||||
|
'Settings connects Superbrain to your services: WebDAV shares, CalDAV calendars, CardDAV address books, Nextcloud contacts sync, and IMAP mailboxes. Credentials are stored encrypted and are write-only — the app never shows them back to you.',
|
||||||
|
'On Core deployments with Nextcloud, the connection forms offer a one-click prefill for your account.',
|
||||||
|
],
|
||||||
|
where: 'Settings → Connections',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'developer',
|
||||||
|
icon: KeyRound,
|
||||||
|
title: 'API keys & MCP',
|
||||||
|
body: [
|
||||||
|
'Personal API keys (sb_…) authenticate machine clients against the Go API directly; the plaintext key is shown once at creation and stored hashed. The superbrain-mcp server exposes your data to MCP clients through the federated gateway.',
|
||||||
|
'You can also register external MCP servers (Settings → MCP) for Superbrain to dial as a client.',
|
||||||
|
],
|
||||||
|
where: 'Settings → API Keys / MCP',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
export default function HelpPage() {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-background">
|
||||||
|
<header className="border-b border-border">
|
||||||
|
<div className="mx-auto flex max-w-4xl items-center justify-between px-6 py-4">
|
||||||
|
<Link href="/login" className="font-display text-lg font-bold tracking-tight">
|
||||||
|
superbrain
|
||||||
|
</Link>
|
||||||
|
<Button asChild size="sm">
|
||||||
|
<Link href="/login">Open Superbrain</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main className="mx-auto max-w-4xl px-6 pb-24">
|
||||||
|
<div className="pt-16 pb-10">
|
||||||
|
<Badge variant="secondary" className="mb-4">Help center</Badge>
|
||||||
|
<h1 className="font-display text-4xl font-bold tracking-tight">
|
||||||
|
How Superbrain works
|
||||||
|
</h1>
|
||||||
|
<p className="mt-3 max-w-2xl text-base text-muted-foreground">
|
||||||
|
Bookmarks, pages, collections and automations — a quick guide to every
|
||||||
|
surface of the app. Jump to a topic below, or browse the FAQ at the end.
|
||||||
|
</p>
|
||||||
|
<nav className="mt-6 flex flex-wrap gap-2">
|
||||||
|
{SECTIONS.map(s => (
|
||||||
|
<a
|
||||||
|
key={s.id}
|
||||||
|
href={`#${s.id}`}
|
||||||
|
className="rounded-full border border-border px-3 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
|
||||||
|
>
|
||||||
|
{s.title}
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
<a
|
||||||
|
href="#faq"
|
||||||
|
className="rounded-full border border-border px-3 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
|
||||||
|
>
|
||||||
|
FAQ
|
||||||
|
</a>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-12">
|
||||||
|
{SECTIONS.map(s => (
|
||||||
|
<section key={s.id} id={s.id} className="scroll-mt-8">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
|
||||||
|
<s.icon className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
<h2 className="font-display text-2xl font-bold tracking-tight">{s.title}</h2>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 space-y-3 text-sm leading-relaxed text-foreground/90">
|
||||||
|
{s.body.map((p, i) => <p key={i}>{p}</p>)}
|
||||||
|
</div>
|
||||||
|
<p className="mt-3 font-mono text-xs text-muted-foreground">{s.where}</p>
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<section id="faq" className="scroll-mt-8">
|
||||||
|
<h2 className="font-display text-2xl font-bold tracking-tight">Frequently asked questions</h2>
|
||||||
|
<HelpFaq />
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer className="border-t border-border">
|
||||||
|
<div className="mx-auto flex max-w-4xl flex-wrap items-center justify-between gap-2 px-6 py-6 text-xs text-muted-foreground">
|
||||||
|
<span>Superbrain — your second brain, federated.</span>
|
||||||
|
<span className="flex gap-4">
|
||||||
|
<Link href="/login" className="hover:text-primary hover:underline">Sign in</Link>
|
||||||
|
<Link href="/forgot-password" className="hover:text-primary hover:underline">Reset password</Link>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -117,6 +117,9 @@ export function LoginClient({ oidcEnabled, passwordEnabled }: { oidcEnabled: boo
|
|||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
<p className="text-center text-xs text-muted-foreground">
|
||||||
|
<Link href="/help" className="hover:text-primary hover:underline">Help center</Link>
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useSearchParams } from 'next/navigation'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { BellOff, Check, Link2 } from 'lucide-react'
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
// The token in the link IS the credential (HMAC-signed user id, issued only
|
||||||
|
// in mail to the owner's own address). The page never needs a session; the
|
||||||
|
// Go endpoint validates the token and disables email notification channels
|
||||||
|
// plus self-addressed agent email tasks. Transactional mail (password
|
||||||
|
// resets) keeps flowing — the copy must say so.
|
||||||
|
export function UnsubscribeClient() {
|
||||||
|
const params = useSearchParams()
|
||||||
|
const token = params.get('token') ?? ''
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [done, setDone] = useState(false)
|
||||||
|
const [invalid, setInvalid] = useState(false)
|
||||||
|
|
||||||
|
const handleUnsubscribe = async () => {
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/notifications/unsubscribe', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
})
|
||||||
|
const data = await res.json().catch(() => null)
|
||||||
|
if (res.ok && data?.ok) {
|
||||||
|
setDone(true)
|
||||||
|
} else if (res.status === 400) {
|
||||||
|
setInvalid(true)
|
||||||
|
} else {
|
||||||
|
toast.error(data?.error ?? 'Could not unsubscribe right now')
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.error('Could not unsubscribe right now')
|
||||||
|
}
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!token || invalid) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||||
|
<div className="w-full max-w-sm space-y-8 text-center">
|
||||||
|
<div className="flex justify-center mb-4">
|
||||||
|
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||||
|
<Link2 className="h-7 w-7" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<h1 className="font-display text-3xl font-bold tracking-tight">Invalid Link</h1>
|
||||||
|
<p className="text-sm text-muted-foreground mt-2">
|
||||||
|
This unsubscribe link is invalid or has expired. Open Settings → Notifications
|
||||||
|
in the app to manage your email preferences directly.
|
||||||
|
</p>
|
||||||
|
<p className="text-center text-xs text-muted-foreground">
|
||||||
|
<Link href="/settings?tab=notifications" className="text-primary hover:underline">Email preferences</Link>
|
||||||
|
{' · '}
|
||||||
|
<Link href="/help" className="text-primary hover:underline">Help center</Link>
|
||||||
|
{' · '}
|
||||||
|
<Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (done) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||||
|
<div className="w-full max-w-sm space-y-8 text-center">
|
||||||
|
<div className="flex justify-center mb-4">
|
||||||
|
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||||
|
<Check className="h-7 w-7" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<h1 className="font-display text-3xl font-bold tracking-tight">You're Unsubscribed</h1>
|
||||||
|
<p className="text-sm text-muted-foreground mt-2">
|
||||||
|
Notification emails and automations that email you have been turned off.
|
||||||
|
You can re-enable them anytime in Settings → Notifications. Account emails
|
||||||
|
such as password resets are not affected.
|
||||||
|
</p>
|
||||||
|
<p className="text-center text-xs text-muted-foreground">
|
||||||
|
<Link href="/settings?tab=notifications" className="text-primary hover:underline">Email preferences</Link>
|
||||||
|
{' · '}
|
||||||
|
<Link href="/help" className="text-primary hover:underline">Help center</Link>
|
||||||
|
{' · '}
|
||||||
|
<Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||||
|
<div className="w-full max-w-sm space-y-8">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="flex justify-center mb-4">
|
||||||
|
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
|
||||||
|
<BellOff className="h-7 w-7" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<h1 className="font-display text-3xl font-bold tracking-tight">Unsubscribe</h1>
|
||||||
|
<p className="text-sm text-muted-foreground mt-2">
|
||||||
|
Stop notification emails and automations that email you. Password resets and
|
||||||
|
other account emails keep working, and you can re-enable notifications anytime
|
||||||
|
in Settings.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<Button className="w-full" onClick={handleUnsubscribe} loading={loading}>
|
||||||
|
Unsubscribe from notification emails
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" className="w-full" asChild>
|
||||||
|
<Link href="/settings?tab=notifications">Keep my current preferences</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<p className="text-center text-xs text-muted-foreground">
|
||||||
|
<Link href="/help" className="text-primary hover:underline">Help center</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { UnsubscribeClient } from './client'
|
||||||
|
import { Suspense } from 'react'
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
|
export default function UnsubscribePage() {
|
||||||
|
// useSearchParams in the client needs a Suspense boundary for prerender.
|
||||||
|
return (
|
||||||
|
<Suspense>
|
||||||
|
<UnsubscribeClient />
|
||||||
|
</Suspense>
|
||||||
|
)
|
||||||
|
}
|
||||||
+28
@@ -165,6 +165,34 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
|||||||
token.ver = user.tokenVersion
|
token.ver = user.tokenVersion
|
||||||
token.role = user.role
|
token.role = user.role
|
||||||
}
|
}
|
||||||
|
if (trigger === 'update' && typeof token.id === 'string' && typeof token.ver === 'number') {
|
||||||
|
// Profile edits (Settings → Profile) call useSession().update({})
|
||||||
|
// so the session identity re-syncs from Go — the top bar and
|
||||||
|
// profile header reflect a new name without a re-login. (A bare
|
||||||
|
// update() only re-fetches; the data argument is what fires this
|
||||||
|
// trigger in next-auth v5.) Same assertion the data proxy signs;
|
||||||
|
// fail-quiet keeps the old values when Go is unreachable (the save
|
||||||
|
// itself already succeeded or failed loudly).
|
||||||
|
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
|
||||||
|
if (secret) {
|
||||||
|
try {
|
||||||
|
const assertion = jwt.sign({ uid: token.id, ver: token.ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' })
|
||||||
|
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/me`, {
|
||||||
|
headers: { Authorization: `Bearer ${assertion}` },
|
||||||
|
cache: 'no-store',
|
||||||
|
signal: AbortSignal.timeout(5000),
|
||||||
|
})
|
||||||
|
if (response.ok) {
|
||||||
|
const u = (await response.json())?.user
|
||||||
|
if (u) {
|
||||||
|
token.name = u.name ?? null
|
||||||
|
token.email = u.email ?? null
|
||||||
|
token.picture = u.image ?? null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { /* keep the previous identity */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
return token
|
return token
|
||||||
},
|
},
|
||||||
async session({ session, token }) {
|
async session({ session, token }) {
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
// Settings → Profile: editable particulars (display name, bio, location,
|
||||||
|
// occupation, organization, website). Values load from GET /api/me — the
|
||||||
|
// Go identity is re-read per request, so this is always the stored truth,
|
||||||
|
// not the login-time NextAuth snapshot. After a save, useSession().update()
|
||||||
|
// re-syncs the session identity (auth.ts jwt "update" trigger) so the top
|
||||||
|
// bar and this header reflect a new name without a re-login.
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { useSession } from 'next-auth/react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { User } from 'lucide-react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
type Profile = {
|
||||||
|
name: string
|
||||||
|
bio: string
|
||||||
|
location: string
|
||||||
|
occupation: string
|
||||||
|
organization: string
|
||||||
|
website: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY: Profile = { name: '', bio: '', location: '', occupation: '', organization: '', website: '' }
|
||||||
|
|
||||||
|
function fromUser(u: Record<string, unknown> | null | undefined): Profile {
|
||||||
|
const s = (v: unknown) => (typeof v === 'string' ? v : '')
|
||||||
|
return {
|
||||||
|
name: s(u?.name), bio: s(u?.bio), location: s(u?.location),
|
||||||
|
occupation: s(u?.occupation), organization: s(u?.organization), website: s(u?.website),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProfileSettings() {
|
||||||
|
const { data: session, update } = useSession()
|
||||||
|
const [profile, setProfile] = useState<Profile>(EMPTY)
|
||||||
|
const [baseline, setBaseline] = useState<Profile>(EMPTY)
|
||||||
|
const [loaded, setLoaded] = useState(false)
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/api/me')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
const p = fromUser(data?.user)
|
||||||
|
setProfile(p)
|
||||||
|
setBaseline(p)
|
||||||
|
})
|
||||||
|
.catch(() => { /* the form stays usable; saving surfaces any outage */ })
|
||||||
|
.finally(() => setLoaded(true))
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const dirty = loaded && JSON.stringify(profile) !== JSON.stringify(baseline)
|
||||||
|
const set = (key: keyof Profile) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
|
||||||
|
setProfile(p => ({ ...p, [key]: e.target.value }))
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/me', {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(profile),
|
||||||
|
})
|
||||||
|
const data = await res.json().catch(() => null)
|
||||||
|
if (res.ok && data) {
|
||||||
|
const p = fromUser(data)
|
||||||
|
setProfile(p)
|
||||||
|
setBaseline(p)
|
||||||
|
toast.success('Profile saved')
|
||||||
|
// Refresh the NextAuth identity so the top bar picks up the name.
|
||||||
|
// The argument matters: in next-auth v5 a bare update() only
|
||||||
|
// re-fetches the session; update({}) POSTs and fires the jwt
|
||||||
|
// callback with trigger="update" (the auth.ts re-sync path).
|
||||||
|
await update({})
|
||||||
|
} else {
|
||||||
|
toast.error(data?.error ?? 'Failed to save')
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.error('Failed to save')
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const displayName = profile.name || session?.user?.name || session?.user?.email || 'User'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border p-4 space-y-4">
|
||||||
|
<h3 className="font-medium flex items-center gap-2"><User className="h-4 w-4" /> Profile</h3>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-2xl font-bold text-primary">
|
||||||
|
{displayName[0]?.toUpperCase() ?? '?'}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="font-medium truncate">{displayName}</p>
|
||||||
|
<p className="text-sm text-muted-foreground truncate" suppressHydrationWarning>{session?.user?.email}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Your name appears when you share bookmarks, tags and collections with others.
|
||||||
|
Public bookmark links never reveal your identity.
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div className="col-span-2">
|
||||||
|
<label className="text-xs font-medium text-muted-foreground">Display name</label>
|
||||||
|
<Input value={profile.name} onChange={set('name')} maxLength={120} placeholder="Your name" />
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2">
|
||||||
|
<label className="text-xs font-medium text-muted-foreground">Bio</label>
|
||||||
|
<Textarea value={profile.bio} onChange={set('bio')} maxLength={280} rows={3} placeholder="A short introduction" />
|
||||||
|
<p className="mt-1 text-right text-xs text-muted-foreground">{profile.bio.length}/280</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-medium text-muted-foreground">Location</label>
|
||||||
|
<Input value={profile.location} onChange={set('location')} maxLength={120} placeholder="City, country" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-medium text-muted-foreground">Occupation</label>
|
||||||
|
<Input value={profile.occupation} onChange={set('occupation')} maxLength={120} placeholder="Job title" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-medium text-muted-foreground">Organization</label>
|
||||||
|
<Input value={profile.organization} onChange={set('organization')} maxLength={120} placeholder="Company or team" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-medium text-muted-foreground">Website</label>
|
||||||
|
<Input value={profile.website} onChange={set('website')} maxLength={2048} type="url" placeholder="https://example.com" />
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2">
|
||||||
|
<label className="text-xs font-medium text-muted-foreground">Email</label>
|
||||||
|
<Input value={session?.user?.email ?? ''} readOnly disabled className="bg-muted" suppressHydrationWarning />
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">Your sign-in identity; it cannot be changed here.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button onClick={save} loading={saving} disabled={!dirty}>Save profile</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user