/admin uses the same cookie session as the app but requires users.is_admin = true.
Admin login replaces a normal user session with an admin session. A non-admin session
is redirected to /admin/login?error=notadmin; admin APIs return 401. TFA-enabled
admins must complete the normal app login first. The first admin is created only when
there are zero admins and BOOND_ADMIN_PASSWORD (12+ characters) is set, or with
boond admin create. No generated password is written to logs.
Environment values saved from the admin panel are stored in settings (secret values
are AES-GCM encrypted with the sealing key) and applied on the next startup. Only
changed keys are accepted by the UI. Database URL, JWT secret, and admin password are
deliberately not editable there.
This chapter expands SPEC §§5 and 14. It is normative. Security controls are not optional for a public deployment, even a single-user one.
- One identity per request. Cookie or bearer, never both.
- Least privilege: a token grants only the user's data; sharing narrows, never widens.
- Fail closed: absent
Origin, unknown client, expired code, unverified redirect → deny. - No custom protocol requirements that official clients do not send (no CSRF tokens,
no mandatory PKCE, no custom headers beyond
AuthorizationandContent-Type). - Secrets are hashed or encrypted at rest; never logged.
- Every state-changing request is auditable.
BOOND_JWT_SECRET is optional. When empty, 32 random bytes are generated once and
stored at $BOOND_STORAGE_PATH/secrets/jwt.key (or BOOND_SECRET_PATH), mode 0600.
Secrets shorter than 32 bytes are refused. The retired public sample value is replaced once with a new persisted key and a startup warning (sessions invalidated, TOTP re-enrolment required).
The TOTP sealing key is derived with HKDF-SHA256 using a different info string, so a
database dump cannot decrypt TOTP seeds with the JWT signing key alone. Rotating the
JWT secret invalidates sessions and makes old TOTP secrets unreadable; affected users
must re-enrol 2FA or use a recovery code.
| Secret | Storage | Notes |
|---|---|---|
| Account password | Argon2id hash | 64 MiB, t=3, p=2, 16-byte salt, 32-byte key |
| Session token | SHA-256 hash | 32 random bytes; cookie holds plaintext |
| API access token | SHA-256 hash | Prefix rdt_; 32 random bytes |
| Refresh token | SHA-256 hash | Prefix rdr_; rotated on use |
| Test token | SHA-256 hash | 24 h TTL; shown once; never stored plaintext |
| OAuth client secret | SHA-256 hash | 32 random bytes; shown once at creation/rotation |
| OAuth authorization code | SHA-256 hash | 60 s TTL; single-use |
| JWT handoff | HMAC/EdDSA signature | 60 s TTL; jti replay cache |
| TOTP secret | AES-GCM encrypted | Derived sealing key, not the JWT signing key |
| Recovery code | SHA-256 hash | Normalize punctuation/case before hashing |
| FCM device token | SHA-256 hash + encrypted copy | Needed to send push |
| Invite token | SHA-256 hash | 32 random bytes, base64url |
| Email token | SHA-256 hash | Verify/reset; single-use |
Encryption key: BOOND_ENCRYPTION_KEY (32 bytes, base64). Key rotation is out of scope
for v1; document how to re-encrypt with a maintenance command.
Hashing: use Go's crypto/subtle.ConstantTimeCompare for token comparisons. Never
compare secrets with ==.
On login/TFA/social/JWT:
- Generate 32 random bytes (base64url, no padding).
- Store
sha256(token)insessions, with user, expiry, IP, UA. - Set cookie
boond_session=<token>; Path=/; HttpOnly; Secure; SameSite=Lax. AddDomain=<BOOND_COOKIE_DOMAIN>if configured. Local HTTP development (Android cleartext,localhost) may setBOOND_INSECURE_COOKIES=trueto omitSecure; refuse that setting whenBOOND_MODE=prod. Prefer a local TLS proxy for realistic testing. - Rotate any pre-login session ID (session fixation defense): delete the old session row, set the new cookie.
- Parse cookie, hash, look up non-revoked, non-expired session.
- Check idle timeout (30 days) and absolute timeout (180 days). If idle-expired, revoke and treat as anonymous.
- Update
last_seen_atat most once per hour (write amplification control). - Load the user; if
deleted_atis set, revoke and 401. - If the session is valid but the user has TFA newly enabled, do not invalidate; TFA applies at next login.
- On password change, revoke all other sessions (keep current) and all refresh tokens.
- On email change, revoke all other sessions and require re-verification.
GET /auth/logoutrevokes current session;allrevokes all.- Clear cookie with
Max-Age=0and the same Path/Domain/Secure/SameSite. - Return JSON when
no_redirect, else 303. - Logout is idempotent: an already-invalid session returns success.
For app.example.com + api.example.com, set BOOND_COOKIE_DOMAIN=.example.com so the
cookie is sent to both. The app and API MUST share a registrable domain when a parent
cookie is used; validate this at startup and refuse a Domain that does not cover both.
For path-only deployments (https://example.com/api and https://example.com/app), a
host-only cookie works. For a single origin, host-only is safest. Never set
SameSite=None unless an embedding use case requires it; document the CSRF and
third-party-cookie consequences (Safari/ITP will block it).
Safari/ITP: third-party cookies are blocked. Deploy API and app on the same site (subdomains count as same site if the registrable domain matches). The extension's Safari profile-cookie workaround is a client-side patch; Boond should not depend on it.
POST /auth/email/login accepts:
{"email":"alice","password":"…"}or form:
email=alice&password=…&redirect=%2Fmy%2F0
email may be a username. Normalize email to lowercase; usernames are case-insensitive.
- JSON: 200
{"result":true}+Set-Cookie, or{"result":true,"tfa":"…"}. - Form: 303 to
redirectif it is a safe app-relative path or allowlisted absolute URL; otherwise toBOOND_APP_URL. On failure, 303 toBOOND_APP_URL/account/login?error=<generic message>. - The login page reads
?errorand displays it (app:src/routes/account/login/index.js#L19-L35).
- Per-IP: 20 attempts / 5 minutes.
- Per-account: 10 failures / 15 minutes, then exponential lockout (max 1 hour).
- Constant-time password check; if the user does not exist, compare against a dummy hash to equalize timing.
- Generic message:
Invalid email or password. - Do not log the submitted password or the full email.
- Optional CAPTCHA: only if configured; the client sends
recaptchaon signup, not login. Do not require it for login by default.
POST /auth/email/signup creates the account but does not log in (the client calls
login next). Steps:
- Validate username/email/password; normalize.
- Check uniqueness; 409 with field-specific message.
- Enforce
BOOND_SIGNUP(open,closed, orinvite) and rate-limit signup. - Argon2id hash.
- Transaction: insert user, default group
g1,user_statsrow, config defaults. - Generate a 32-byte verification token, store hash, send email with
BOOND_APP_URL/account/confirm/<token>. - Return the user (private fields appropriate to the creator) or
{result:true}.
Verification:
POST /auth/email/confirm {token}marks verified; token single-use, 24 h TTL.- Unverified accounts cannot log in when SMTP is configured (
BOOND_ALLOW_UNCONFIRMED_LOGIN=falseby default). The first administrator is confirmed automatically. POST /user/send_email_confirmresends, rate-limited.
Password reset:
POST /auth/email/lost {email}always succeeds. If the account exists, send a reset link (BOOND_APP_URL/account/recover/<token>) valid 1 hour.POST /auth/email/recover {token,password}verifies, updates, revokes sessions/tokens, returns{result:true,email}.- Use the same response for unknown emails to avoid enumeration.
GET /user/tfa: if no pending secret, generate 20 bytes, encrypt, storeenabled=false; return base32 secret and a QR data URI forotpauth://totp/Boond:<email>?secret=…&issuer=Boond&algorithm=SHA1&digits=6&period=30.POST /user/tfa {code}: verify ±1 step; set enabled; generate 10 recovery codes, return plaintext once; store hashes.DELETE /user/tfa {code}: verify TOTP or recovery code; disable and delete secret.
- If enabled, password success creates a
tfa_challengesrow:id,user_id,token_hash,expires_at(5 min),attempts,used_at. - Return
{"result":true,"tfa":"<challenge>"}. No session cookie. POST /auth/tfa/{challenge} {code}verifies TOTP ±1 or unused recovery code; marks used; creates session; returns success.- Form variant redirects to the app.
DELETE /auth/tfa/{challenge} {code}verifies the code, disables TFA for the challenge's user, revokes the challenge, and does not create a session (the client's "disable while logging in" flow).- Rate limit: 5 attempts per challenge, 10 per account per 15 minutes, then 429. The account counter is shared by login and disable-at-login; recovery codes are consumed atomically and TOTP steps are single-use.
- Recovery code use marks it used; users can regenerate at setup.
TOTP clock skew: accept ±1 step (30 s). Do not accept codes older than 90 s. Reject reuse of the same time step for a user (store last step).
GET /auth/google?redirect=/my/0
→ 307 accounts.google.com/o/oauth2/v2/auth?client_id=…&redirect_uri=…&state=…
→ callback /auth/google/callback?code=…&state=…
→ verify state, exchange code, verify id_token, find/create user
→ set session cookie, 303 to redirect
- State is HMAC-signed and contains the validated redirect and a nonce; 10 min TTL.
- Verify
id_tokensignature via JWKS,aud,iss,exp,email_verified. - Match by provider
subfirst, then verified email; link to an existing account only if the email is verified. Otherwise create a new user with a generated unique username. - Apple: same, with
namefrom the first authorization only; handle private relay emails. Useidentity_tokenJWKS verification.
GET /auth/google/native?access_token=…:
- Verify the access token by calling Google's userinfo endpoint (not by trusting the client).
- Require
verified_email. - Find/create user; set session cookie; return
{"result":true,"auth":true}. - If TFA enabled, return
{"result":true,"auth":false,"tfa":"…"}and no session.
GET /auth/apple/native?code=…&identity_token=…&display_name=…:
- Verify
identity_tokenwith Apple's JWKS; validateaud(bundle ID),iss,exp. - Optionally exchange
codeat Apple's token endpoint for server-side validation. display_nameis user-provided on first login only; sanitize and store as full name.- Same response shape.
The mobile app calls auth/{provider}/native + a query string
(android:src/screens/auth/native/google.js#L20-L23; apple.ios.js#L17-L20), so the
handler MUST accept query parameters, not a JSON body.
- Invalid/expired token: 401
{"result":false,"auth":false,"error":"invalid_provider_token"}. - Provider not configured: 501
not_configured. - Email already exists with a different provider: link only if verified; otherwise 409
email_existsand instruct the user to sign in with the original method. Do not create duplicate accounts.
POST /oauth/client by a logged-in user. Validate:
name1–200.siteabsolute http(s), optional.redirectsarray 1–20 of absolute URIs; allowhttp://localhost/127.0.0.1for development, otherwise requirehttps. No fragments. No wildcards.- Generate 24-hex ID and 32-byte secret.
The client secret is displayed to the owner. Treat it as a password; encrypt at rest.
GET /oauth/authorize:
- Parse
client_id,redirect_uri,response_type(defaultcode),state,scope,code_challenge,code_challenge_method. - If
client_idinvalid → 400 HTML, do not redirect. - If
redirect_urimissing or not an exact registered URI → 400 HTML, do not redirect. - If
response_typeis present and notcode→ redirect witherror=unsupported_response_type(only after validating redirect). - If not logged in → 303 to app login with
redirect= full authorize URL. After login, the app returns to the authorize URL. - Render consent page: client name/icon/site, requesting user, account email, scopes (display only), Approve/Deny buttons, CSRF token in the form.
- Approve: create
oauth_codesrow with hashed code, client, user, redirect URI, PKCE challenge/method, 60 s TTL. Redirect toredirect_uri?code=…&state=…. - Deny: redirect with
error=access_denied&state=….
The consent form POSTs to /oauth/authorize with decision=approve|deny, client_id,
redirect_uri, state, code_challenge, and a CSRF token. Validate the CSRF token and
that the client/redirect match the code request. Never accept an arbitrary redirect from
the form.
PKCE: if code_challenge is present, require S256; store it; require a matching
code_verifier at exchange. If absent, allow (public clients without PKCE still work).
state is echoed but not required.
POST /oauth/access_token:
- Parse form or JSON.
grant_typerequired. - Client auth:
client_id+client_secretin body or HTTP Basic. Compare with constant-time hash check. authorization_code:- Validate code hash, unused, unexpired, client, redirect URI exact, PKCE.
- Mark code used in the same transaction that creates tokens (prevent replay).
- Issue access (14 days) + refresh (30 days) tokens; store hashes.
- Return
{access_token,refresh_token,expires,expires_in,token_type}.
refresh_token:- Validate hash, active, client.
- Rotate: revoke old refresh, issue new access + refresh in one transaction.
- Return the same shape.
- Errors: HTTP 400
{"error":"invalid_request"|"invalid_client"|"invalid_grant"|"unsupported_grant_type"}. Do not use the standard JSON envelope for OAuth errors.
- CSRF token bound to the session and the pending authorize request.
- Escape client name/site/description (HTML).
- Frame-ancestors
'none'; no third-party scripts. - Never auto-approve; the user must click.
- If the client is owned by the same user, still show consent (or allow a
trustedflag after the first approval; default show).
- Bearer tokens are looked up by hash, checked for revocation and expiry.
- A token's user must be active.
- On password change/account deletion, revoke all tokens.
last_used_atupdate at most once per 5 minutes.- Token scopes are not enforced in v1; store
scopeif provided and expose it in connections, but do not restrict. Document this as legacy-compatible.
Flow:
- Desktop opens
https://api.example.com/v1/auth/jwt?done_uri=rnio://account/jwtin the system browser. - If not logged in, the API redirects to the app login with a
redirectback to the JWT URL. - With a session, the API mints a JWT and 302s to
rnio://account/jwt?token=<jwt>. - The OS opens the desktop app; it navigates the web app to
#/account/jwt?token=…. - The web app calls
POST /auth/jwt {token}; the API validates and sets a cookie.
JWT:
- Header
alg=EdDSA(or HS256 with a server secret),typ=JWT. - Claims:
iss=BOOND_PUBLIC_URL,sub=<user id>,aud=boond-login,iat,exp=+60s,jti=<random>,purpose=desktop. - Verify signature, issuer, audience, expiry, and
jtiunused. Store usedjtiin a table/Redis until expiry; reject replay. - The token is single-use; do not allow it to create multiple sessions.
done_uriallowlist: exact schemesrnio,raindrop,rniomacsafari, plus configured HTTPS app origins. Rejectjavascript:,data:,file:, credentials in URL, and non-allowlisted hosts.
Cookie-auth unsafe methods require:
- a valid
OriginorRefererin the allowlist; or Sec-Fetch-Site: same-originand an allowlistedHostwhen Origin is absent.
If neither is present → 403 csrf.
Native clients (the Android/iOS apps, CLI tools) send neither Origin nor
Sec-Fetch-Site. They are not browsers and cannot be CSRF'd, but they must now
identify themselves with X-Boond-Client: android or X-Boond-Client: ios.
A cookie-authenticated write with neither browser metadata nor this marker is
rejected with 403 csrf. Set BOOND_CSRF_REQUIRE_CLIENT=false only as a temporary
compatibility escape hatch for pre-marker native builds; it is insecure and not
recommended.
Allow:
- app origin(s), API origin, public site origin;
- extension origins from config (
chrome-extension://<id>,moz-extension://<uuid>,safari-web-extension://<id>).
Do not require a CSRF token for API JSON requests; the official clients do not send one. For HTML forms (login, consent, account deletion), include a CSRF token in the form and validate it, because those are top-level browser navigations.
GET requests must be safe. The legacy GET /user/remove and GET /backup violate
this; Boond keeps them for compatibility but adds confirmation/one-shot guards as
described in the API reference. GET /auth/logout is a state change but is safe enough
(logout CSRF only causes annoyance) and is required by clients; keep it.
Every outbound fetch (URL parse, archive, screenshot, iframeable, favicon, broken-link
check, OAuth provider metadata) goes through one SafeFetcher:
- Parse URL; allow only
http/https. - Resolve DNS; reject if any resolved IP is loopback, private, link-local, multicast,
unspecified, or cloud metadata (
169.254.169.254,fd00:ec2::254). - Pin the resolved IP for the request (prevent DNS rebinding) by dialing the IP with
the original
Host/SNI. - Follow at most 5 redirects, re-running the IP check on each.
- Enforce connect timeout 5 s, total 20 s, response body limit 5 MiB for metadata, 70 MB for archives, 1 MB for favicons.
- Send a descriptive User-Agent with the instance URL and a contact.
- Respect
robots.txt? For user-initiated parse, no (single fetch); for bulk scanners, rate-limit per host. Do not crawl. - Do not forward cookies, Authorization headers, or the user's IP.
- Allow an operator to permit private ranges (intranet use) via
BOOND_FETCH_ALLOW_PRIVATE=true; default false.
- Enforce
MaxBytesReaderbefore parsing multipart. - Stream to a temp file, compute SHA-256, sniff magic bytes with
http.DetectContentTypeplus format-specific checks (image decode config, PDF header, EPUB zip). - Reject polyglots where feasible; never trust the filename extension.
- Images: decode with a pixel limit (e.g. 50 MP) to prevent decompression bombs; re-encode to strip metadata/EXIF (or preserve orientation).
- PDFs: do not render server-side without sandboxing; serve as attachment.
- ZIP: reject
.., absolute paths, symlinks, >100k entries, >2 GiB expanded, and nested compression bombs. - Store with random/opaque object keys; never use user filenames as paths.
- Serve with
X-Content-Type-Options: nosniff,Content-Security-Policy: sandbox, andContent-Dispositionas appropriate. - Virus scanning: optional hook (
BOOND_UPLOAD_SCAN_CMD); document that it is the operator's responsibility.
- User-controlled HTML appears in: public pages, reader preview, article
html, collection descriptions, notes, highlights, titles, OAuth client metadata. - Use
html/templatewith autoescape for server-rendered pages. - Sanitize stored article HTML with an allowlist (
bluemonday):- allow structural tags, links (
http/https/mailto), images (http/https/data:image), tables, code, blockquotes; - strip
<script>,<style>(or sanitize),<iframe>(except explicit embeds), forms, inputs, event handlers,javascript:URLs,data:text/html.
- allow structural tags, links (
- If
?html=1returns article HTML, sanitize before storing and again before serving (defense in depth). - Public page CSP:
default-src 'self'; img-src * data:; style-src 'self' 'unsafe-inline'; script-src 'self'; frame-ancestors 'none'. - Reader iframe CSP:
default-src 'none'; img-src * data:; style-src 'unsafe-inline'; script-src 'sha256-<theme-script-hash>'; frame-ancestors <app origins>. The only allowed script is the tiny theme/font fragment handler, pinned by hash; never'unsafe-inline'for scripts. - Embed pages need
frame-ancestors *, but never combine with user HTML; only the trusted public-page template.
- All SQL through
pgxwith parameters. Never concatenate user input. - Search parser produces an AST; the SQL builder emits placeholders and safe
tsquerystrings. Tag/collection IDs are numeric and validated. ORDER BYuses an allowlist enum, not raw input.LIMIT/OFFSETare integers with bounds.- Dynamic
INlists use= ANY($1::bigint[]), not string joining.
For every endpoint, test the matrix:
| Actor | Owned | Shared viewer | Shared member | Public | Unrelated |
|---|---|---|---|---|---|
| Anonymous | 401/404 | 401/404 | 401/404 | read | 404 |
| Owner | full | full | full | full | 404 |
| Viewer | — | read | read | read | 404 |
| Member | — | read | read/write | read/write | 404 |
| Other user | 404 | 404 | 404 | read if public | 404 |
Also test nested inheritance (share parent, access child), share removal, leaving, public→private transitions, and Trash access. A 404 (not 403) for unrelated resources is required to avoid enumeration.
| Threat | Mitigation |
|---|---|
| Credential stuffing | rate limits, generic errors, optional CAPTCHA, TOTP |
| Session theft | HttpOnly/Secure, short idle/absolute expiry, revoke on password change |
| CSRF | Origin/Referer checks, SameSite=Lax, form CSRF tokens |
| XSS via notes/titles | autoescape, sanitize HTML, CSP |
| SSRF via URL parse/archive | SafeFetcher with IP pinning, private ranges blocked |
| Path traversal uploads | random keys, no user filenames, zip guards |
| IDOR | centralized policy, 404 for unrelated, tests |
| Token leakage | hashes at rest, no logs, prefixes, revocation |
| OAuth redirect hijack | exact redirect match, state, PKCE support |
| Replay of JWT/code | single-use jti/code, short TTL |
| Enumeration | generic login/reset responses, 404 policy |
| Abuse/DoS | body limits, rate limits, job concurrency, timeouts |
| Malicious archive | sandboxed renderer, sanitize, size limits, never execute scripts |
| Privilege escalation via sharing | max(inherited, explicit), owner-only manage, tests |
| Deleted account data leak | purge job, revoke tokens, audit |
| Backup leakage | owner-only download, signed short-lived URLs, encryption at rest |
For HTML responses:
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
X-Frame-Options: DENY (except /share embeds)
Content-Security-Policy: … (per route)
Permissions-Policy: camera=(), microphone=(), geolocation=()
Invite/join pages, login, password reset, and backup download pages MUST use
Referrer-Policy: no-referrer so tokens never leak via Referer. Access logs MUST
redact values of query keys token, code, state, access_token, refresh_token,
code_challenge, and email; log only the key presence.
For JSON: Cache-Control: private, no-store, X-Content-Type-Options: nosniff.
For media: X-Content-Type-Options: nosniff, Content-Security-Policy: sandbox,
Accept-Ranges: bytes, long cache for immutable objects.
Required:
BOOND_ENCRYPTION_KEY(32 bytes base64)BOOND_SESSION_SECRET(for signed CSRF/state; 32 bytes)BOOND_JWT_KEY(Ed25519 private key or 32-byte HMAC; separate from session)BOOND_DATABASE_URLBOOND_PUBLIC_URL,BOOND_API_URL,BOOND_APP_URL,BOOND_MEDIA_URLBOOND_ALLOWED_ORIGINS- SMTP settings (optional; if absent, emails are logged in dev)
BOOND_STORAGE_BACKEND=local|s3, plus local path or S3 endpoint/bucket/keys
Optional:
- Google/Apple OAuth client IDs/secrets
- FCM service account
- S3 CDN base URL
BOOND_SCREENSHOTS=off|chromedp|externalBOOND_SEARCH=postgres|meilisearchBOOND_REDIS_URLBOOND_RECAPTCHA_SECRET
Never commit real secrets. .env.example documents names with placeholders. Production
should use a secret manager or Docker secrets; environment variables are acceptable for
a single-user self-host.