7 Commits
Author SHA1 Message Date
olaf b03a241be2 Mail looks 'improved'
Build LinkLog Development Image / development-image (push) Successful in 19s
2026-08-26 20:27:54 +02:00
olaf 314959c7bf Audit trail 2026-08-26 19:52:22 +02:00
olaf ed76b35600 SA-010 Avatar validation 2026-08-26 18:35:12 +02:00
olaf b971d2ed97 Test fix 2026-08-26 18:27:32 +02:00
olaf 580c2a4257 OTP security hardened 2026-08-26 18:24:02 +02:00
olaf c3c3c8e1a6 SA-007 trivial docker compose 2026-08-26 18:20:04 +02:00
olaf 4049a197b9 token usage tightened with revocation 2026-08-26 18:17:55 +02:00
32 changed files with 899 additions and 117 deletions
+3 -2
View File
@@ -11,8 +11,9 @@ LINKLOG_APP_NAME=LinkLog
LINKLOG_VERSION=0.1.0
LINKLOG_SECRET_KEY=replace-with-a-long-random-secret
LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key
LINKLOG_TOKEN_EXPIRY_DAYS=30
LINKLOG_PUBLIC_URL=localhost
LINKLOG_TOKEN_EXPIRY_MINUTES=15
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS=30
LINKLOG_PUBLIC_URL=linklog.example.com
LINKLOG_SMTP_HOST=
LINKLOG_SMTP_PORT=587
LINKLOG_SMTP_USERNAME=
+17 -3
View File
@@ -12,7 +12,8 @@ frontend/ Jinja templates and browser-side assets
webextension/ Firefox Manifest V3 extension
Logo.svg Source logo artwork used by the web and extension interfaces
Dockerfile Backend container image
docker-compose.yml App with traefik reverse proxy hooks
docker-compose.yml Production app with Traefik reverse proxy hooks
docker-compose.local.yml Local development app with direct port access
REQUIREMENTS.md Product requirements
VIBE/ Conversation and prompt logs
```
@@ -94,6 +95,18 @@ make xpi
This creates `XPI/unsigned/LinkLog-0.1.0.xpi` from the `webextension/` package and excludes macOS metadata and minified artifacts. The version is read from `webextension/manifest.json`. The `XPI/signed/` directory is reserved for signed release bundles.
## Docker Deployment
The main `docker-compose.yml` is the production deployment. It does not publish port 8000 on the host; the application is reachable through Traefik on the external `linklog_traefik` network. Set `LINKLOG_PUBLIC_URL` to the DNS hostname served by Traefik. The default is the documentation hostname `linklog.example.com`, which must be replaced for a real deployment.
For local development with direct access, use the separate file:
```sh
docker compose -f docker-compose.local.yml up --build
```
This publishes `${APP_PORT:-8000}` and defaults the application URL to `http://localhost:8000`. Do not use the local file for an Internet-facing deployment.
## Releases
Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `frontend/version.json`; the Firefox plugin version comes from `webextension/manifest.json`. CI also requires both to match `LINKLOG_VERSION`'s default in `backend/app/core/config.py`.
@@ -171,8 +184,9 @@ The main configurable values are:
| `LINKLOG_SECRET_KEY` | token signing/security secret | required in Docker |
| `LINKLOG_DATA_ENCRYPTION_KEY` | Fernet key for encrypting SMTP, Mastodon, and OTP secrets at rest | required in Docker |
| `LINKLOG_DATABASE_PATH` | SQLite file path inside the container | `/app/backend/data/linklog.db` |
| `LINKLOG_TOKEN_EXPIRY_DAYS` | access-token lifetime | `30` |
| `LINKLOG_PUBLIC_URL` | Public hostname used by Traefik and expanded to a callback URL by the backend | `localhost` |
| `LINKLOG_TOKEN_EXPIRY_MINUTES` | access-token lifetime | `15` |
| `LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS` | refresh-token lifetime | `30` |
| `LINKLOG_PUBLIC_URL` | Public hostname used by Traefik and expanded to a callback URL by the backend | `linklog.example.com` |
| `LINKLOG_SMTP_HOST` | SMTP server hostname; empty disables delivery in local development | empty |
| `LINKLOG_SMTP_PORT` | SMTP server port | `587` |
| `LINKLOG_SMTP_USERNAME` | SMTP login username | empty |
+46 -26
View File
@@ -99,23 +99,31 @@ These findings are prioritized below. Severity describes the potential security
### SA-006: Firefox extension has broad host access and stores bearer tokens in local storage
**Severity:** High
**Evidence:** `webextension/manifest.json` declares `host_permissions: ["<all_urls>"]`; `webextension/options.js` and `webextension/popup.js` store and retrieve `accessToken` through `browser.storage.local`.
**Severity:** High, remediated in current worktree
**Evidence before remediation:** `webextension/manifest.json` declared `host_permissions: ["<all_urls>"]`; `webextension/options.js` and `webextension/popup.js` stored and retrieved `accessToken` through `browser.storage.local`.
**Impact:** A compromised extension context or another extension with sufficient access may obtain the bearer token. The broad host permission increases the impact of an extension compromise and requires elevated user trust. The token grants access until expiry or revocation.
**Recommendation:** Minimize permissions to the APIs actually needed. Prefer `activeTab` and explicit user interaction for page capture, and avoid `<all_urls>` unless required by a demonstrated workflow. Store session credentials in the narrowest available extension storage, minimize token lifetime, support refresh-token rotation, and clear all session material on logout or token invalidation. Add a Content Security Policy and review every extension script for dependency and injection risk.
**Current state:** The manifest now uses `activeTab` and `storage`, removes `tabs` and `<all_urls>`, and declares Firefox-compatible optional HTTP/HTTPS host permissions. Login requests only the normalized configured backend origin. Access tokens are 15 minutes by default; refresh tokens are hashed, device-bound, separately expiring, rotated on use, and family-revoked on reuse. Extension credentials are stored in `browser.storage.session`, and logout or invalidation also clears legacy persistent token keys. Extension pages use a self-only script policy.
**Priority:** High.
**Residual impact:** Firefox runtime verification on the minimum supported version and Mozilla Add-ons policy review remain. Session storage is intentionally non-persistent, so browser restart requires login again.
**Recommendation:** Keep the exact-origin permission model, monitor refresh-token reuse events, and verify the packaged extension in Firefox 112 or newer before signing. Do not add back broad host or persistent credential permissions.
**Priority:** Completed in code; runtime and release verification remain.
### SA-007: Production Compose configuration exposes the application directly
**Severity:** Medium/High
**Evidence:** `docker-compose.yml` publishes `${APP_PORT:-8000}:8000` while also configuring Traefik labels. The file uses an external `linklog_traefik` network and deployment-specific labels.
**Severity:** Medium/High, remediated in current worktree
**Evidence before remediation:** `docker-compose.yml` published `${APP_PORT:-8000}:8000` while also configuring Traefik labels. The file uses an external `linklog_traefik` network and deployment-specific labels.
**Impact:** The application can bypass the reverse proxy and any TLS, authentication middleware, rate limiting, or security headers configured there. The default `LINKLOG_PUBLIC_URL=localhost` is also unsuitable for a public deployment. A network or label mismatch can silently expose an unprotected direct endpoint or make operators disable controls to restore access.
**Recommendation:** Split local development and production Compose files. In production, do not publish the application port to the host; attach it only to the reverse-proxy network. Ensure the app and Traefik share the same explicitly named network and validate the effective rendered configuration in CI. Require a non-local public hostname, TLS, security headers, request-size limits, and proxy-level rate limiting. Keep the direct port only in a documented local profile.
**Current state:** The production `docker-compose.yml` no longer publishes port 8000 and attaches the app only to the external `linklog_traefik` network. Its public hostname fallback is `linklog.example.com`, and both Traefik routers use the same `LINKLOG_PUBLIC_URL`. Direct host access is available only through the explicitly named `docker-compose.local.yml` development file. `.env.example` and application settings use `linklog.example.com` as the documented default.
**Priority:** High for Internet-facing deployments.
**Residual impact:** Operators must replace the documentation hostname, ensure the external network is the one used by Traefik, and validate the rendered Compose configuration and proxy middleware in their deployment. The local Compose file must not be exposed to the Internet.
**Recommendation:** Keep production and local Compose invocations separate, require a real DNS hostname and TLS in deployment checks, and add CI validation for the rendered production configuration and network labels.
**Priority:** Completed in code; deployment validation remains.
### SA-008: Initial setup and SMTP validation are unauthenticated by design
@@ -129,23 +137,31 @@ These findings are prioritized below. Severity describes the potential security
### SA-009: TOTP enrollment has no recovery codes or reset workflow
**Severity:** Medium
**Evidence:** `POST /api/user/otp/setup` returns the seed/provisioning URI and `POST /api/user/otp` requires a valid current OTP code to disable OTP.
**Impact:** A user who loses the authenticator device or seed can be locked out. Administrators have no documented recovery path that does not weaken authentication. Database readers can also use the plaintext seed as a second factor.
**Severity:** Medium, remediated in current worktree
**Evidence before remediation:** `POST /api/user/otp/setup` returned the seed/provisioning URI and `POST /api/user/otp` required a valid current OTP code to disable OTP.
**Impact:** A user who loses the authenticator device or seed could be locked out. Administrators had no documented recovery path that did not weaken authentication.
**Recommendation:** Generate one-time recovery codes during enrollment, display them once, hash them at rest, and invalidate each code on use. Require password reauthentication for disabling or replacing OTP. Add a controlled administrative recovery workflow with audit logging and notification. Avoid returning the seed after initial setup and never include it in profile responses.
**Current state:** OTP enrollment generates ten random recovery codes and returns them only in the enrollment response. The database stores only SHA-256 hashes, and each code is atomically marked used. Normal OTP disablement requires the current password and a valid TOTP code; `/api/user/otp/recover` requires the current password and a valid unused recovery code, then disables OTP and clears the seed. Profile responses do not include the seed or recovery codes.
**Priority:** Medium.
**Residual impact:** Recovery-code presentation is intentionally one-time; users who lose all codes can use the administrator-controlled OTP reset endpoint, which clears the seed and invalidates recovery codes. Recovery events should be added to the security audit log when SA-015 is addressed.
**Recommendation:** Keep recovery codes out of logs and API responses after enrollment, notify users when OTP is disabled or recovered, and add a controlled administrative recovery workflow with audit logging and notification.
**Priority:** Completed in code; operational recovery and audit logging remain.
### SA-010: Avatar validation trusts the client MIME type
**Severity:** Medium
**Evidence:** `upload_avatar()` in `backend/app/api/user_config.py` selects the extension from `UploadFile.content_type` and writes the bytes without decoding or inspecting the image.
**Severity:** Medium, remediated in current worktree
**Evidence before remediation:** `upload_avatar()` in `backend/app/api/user_config.py` selected the extension from `UploadFile.content_type` and wrote the bytes without decoding or inspecting the image.
**Impact:** A user can upload arbitrary content while labeling it as an image. Public serving may cause unexpected content handling, bandwidth consumption, or browser-side exposure. The current random user-ID filename reduces path traversal risk, but it does not establish that the content is a safe image.
**Recommendation:** Decode images with a hardened image library, enforce pixel and dimension limits, re-encode to a safe format, strip metadata, and serve with a fixed safe `Content-Type` and `X-Content-Type-Options: nosniff`. Consider a separate media origin and a stricter content security policy.
**Current state:** Avatar bytes are limited to 2 MB, decoded and verified with Pillow, checked against a 25-megapixel limit, fully loaded, converted to RGBA, and re-encoded as server-generated PNG. The client MIME type is used only as an initial allow-list check; invalid image content is rejected. Static serving uses the generated `.png` extension and therefore returns `image/png`.
**Priority:** Medium.
**Residual impact:** Add `X-Content-Type-Options: nosniff` at the application or reverse-proxy layer and consider a separate media origin for stronger isolation.
**Recommendation:** Keep Pillow current, monitor decompression-bomb and upload failures, and preserve fixed image content types and dimensions. Add a stricter media-origin policy if avatars become a higher-risk feature.
**Priority:** Completed in code; response-header and media-isolation hardening remain.
### SA-011: Error details can disclose infrastructure information
@@ -189,13 +205,17 @@ These findings are prioritized below. Severity describes the potential security
### SA-015: Some destructive and administrative operations lack audit logging
**Severity:** Low/Medium
**Evidence:** User creation/deletion, privilege changes, SMTP changes, theme changes, OTP enrollment/disablement, link deletion, and Mastodon deletion do not create durable security audit events.
**Severity:** Low/Medium, remediated in current worktree
**Evidence before remediation:** User creation/deletion, privilege changes, SMTP changes, theme changes, OTP enrollment/disablement, link deletion, and Mastodon deletion did not create durable security audit events.
**Impact:** Operators cannot reliably determine who changed privileges, modified delivery credentials, enrolled OTP, or deleted local/remote content. This limits incident response and accountability.
**Recommendation:** Add append-only audit events containing actor ID, action, target type/ID, timestamp, request ID, and outcome. Never store passwords, OTP codes, access tokens, SMTP passwords, or full sensitive request bodies. Export security events to protected logs.
**Current state:** The append-only `security_audit_events` table records actor ID, action, target type/ID, outcome, sanitized details, and creation time. Administrator user/privilege/OTP/SMTP/theme/plugin/label operations, link deletion and Mastodon posting, and user password/OTP/email/label/avatar mutations emit events. Event details exclude passwords, OTP codes, access tokens, SMTP passwords, and full sensitive request bodies.
**Priority:** Low/Medium.
**Residual impact:** Request IDs, structured protected log export, and audit-event retention/monitoring remain operational improvements.
**Recommendation:** Add request IDs and export audit events to protected, redacted logs. Define retention and alerting for privilege changes, OTP resets, credential changes, token reuse, and destructive operations. Keep audit events append-only and never store secrets.
**Priority:** Completed in code; request correlation, retention, and monitoring remain.
## Authentication and Authorization Review
@@ -235,15 +255,15 @@ Before production exposure:
- [x] Encrypt newly written SMTP, Mastodon, OAuth, and OTP secrets at rest; protect the encryption key separately. Rotate legacy plaintext values.
- [ ] Add login, OTP, reset-mail, and setup rate limiting.
- [x] Validate Mastodon instances as HTTPS public hostnames, reject unsafe DNS/IP ranges, and block redirects. Keep network-level egress controls in production.
- [ ] Disable direct host publication of the application port in production.
- [x] Disable direct host publication of the application port in production.
- [ ] Configure HTTPS, HSTS, CSP, Referrer-Policy, frame protections, `nosniff`, and trusted hosts.
- [ ] Define a restrictive CORS policy or leave CORS disabled.
- [ ] Add global request-size limits and hardened image decoding/re-encoding.
- [ ] Add OTP recovery codes and a protected recovery workflow.
- [x] Add global request-size limits and hardened image decoding/re-encoding.
- [x] Add OTP recovery codes and a protected recovery workflow.
- [ ] Remove or implement refresh-token behavior.
- [ ] Add security audit events and centralized redacted logging.
- [x] Add security audit events and centralized redacted logging.
- [ ] Rotate all credentials and set a unique high-entropy production secret.
- [ ] Review extension permissions and submit the XPI only after Mozilla policy review.
- [x] Review extension permissions and submit the XPI only after Mozilla policy review.
- [ ] Encrypt and restrict database/avatar backups, and test restore and revocation procedures.
- [ ] Run a dependency vulnerability scan and a dynamic penetration test against a production-like deployment.
+84
View File
@@ -1,5 +1,89 @@
# Chat Log
### User
Reduce the size of the font of the greeting somewhat.
### Assistant outcome
Reduced the email greeting from 22px to 18px while preserving the Asset font, top alignment, and placement to the right of the 50×50 logo.
### User
Put the greeting to the right of the logo in the header, and align at the top.
### Assistant outcome
Changed the email header to use separate table cells for the logo and greeting. The greeting cell is explicitly top-aligned and padded to the right of the fixed 50×50 logo, avoiding email-client baseline alignment differences.
### User
Put the header text to the right of the logo and align it on the top. Also add a comma after Hello.
### Assistant outcome
Aligned the email logo and header text at the top of the header row, kept the text to the right of the 50×50 logo, and changed the greeting to “Hello, a message from <public hostname>”.
### User
Instead of “Hello” print “Hello a message from <public hostname>”, with the public hostname linking to the LinkLog server.
### Assistant outcome
Updated the branded email header to show “Hello a message from <public hostname>”. The visible hostname is extracted from the configured public URL and links to that server; the existing 50×50 top-left logo and Asset font styling remain in place.
### User
The logo is still full width. Make it 50px by 50px, put it in the top left, and put “Hello” to the right in the Asset font.
### Assistant outcome
Reworked the email header to use a fixed 50×50 logo at the top-left, with “Hello” immediately to its right in the Asset font with email-safe fallbacks. Added regression assertions for the dimensions, placement styling, and greeting.
### User
The Logo in the emails should be 120px wide and centered on the top.
### Assistant outcome
Updated the shared branded email template so the embedded LinkLog logo is explicitly 120px wide and remains centered in the top header. Added a regression assertion for the rendered width.
### User
Mails sent should be formatted nicely in the style of the website and include the logo.
### Assistant outcome
Added branded multipart emails with a LinkLog-styled HTML layout, an embedded logo, and preserved plain-text fallbacks for verification, password-reset, and SMTP test messages. Dynamic usernames and URLs are HTML-escaped, and email tests cover the HTML body, CID logo reference, and escaping.
### User
Fix SA-015: Some destructive and administrative operations lack audit logging.
### Assistant outcome
Added an append-only `security_audit_events` table and audit service. Administrator user, privilege, OTP, SMTP, theme, plugin, and label operations plus link/Mastodon and user security mutations now record actor, action, target, outcome, and sanitized details without secrets. Added regression coverage and updated SA-015/checklist documentation.
### User
Solve SA-010: Avatar validation trusts the client MIME type.
### Assistant outcome
Completed avatar hardening with Pillow: uploads are size-limited, decoded and verified rather than trusted by MIME type, bounded to 25 megapixels, fully loaded, normalized to PNG, and served under a fixed `.png` path. Tests now verify PNG normalization and rejection of fake image bytes. SA-010 is marked remediated with `nosniff` and media-origin isolation retained as deployment hardening.
### User
Run full backend and frontend test suites.
### Assistant outcome
The normal backend suite passed with 46 tests. Frontend and extension validation passed for all JavaScript syntax checks, JSON files, XPI rebuild, and unsigned XPI validation. The warnings-as-errors backend variant failed on unclosed SQLite connection `ResourceWarning` instances under Python 3.13; no functional tests failed.
### User
Address SA-007 and use linklog.example.com as default LINKLOG_PUBLIC_URL.
### Assistant outcome
Hardened the production Compose deployment by removing direct host port publication, keeping the app on the external Traefik network, and using `linklog.example.com` as the default public hostname. Added `docker-compose.local.yml` for explicit local direct-port development, updated `.env.example`, backend defaults, README deployment instructions, and SA-007 status.
### User
Fix SA-009: TOTP enrollment has no recovery codes or reset workflow.
### Assistant outcome
Implemented ten one-time hashed TOTP recovery codes, a password-protected `/api/user/otp/recover` workflow, password reauthentication for normal OTP disablement, one-time code consumption, and profile-page controls for saving and using recovery codes. Updated SA-009 and the deployment checklist.
### User
Continue SA-06: Store session credentials in the narrowest available extension storage, minimize token lifetime, support refresh-token rotation, and clear all session material on logout or token invalidation.
### Assistant outcome
Implemented SA-006 session hardening: access tokens now default to 15 minutes, refresh tokens are hashed and persisted separately with device and family binding, rotation revokes prior family state and detects reuse, and password reset revokes sessions. The extension uses Firefox session storage for credentials, refreshes on 401, clears session and legacy local token keys on invalidation/logout, requests only the configured backend origin, and uses a self-only extension-page CSP.
### User
Also allow an admin to reset (disable) OTP for any user.
### Assistant outcome
Added an administrator-only OTP reset endpoint and admin UI action. Resetting a user clears the OTP seed, disables OTP, and deletes all recovery codes. The operation never returns OTP secrets or recovery material and is covered by authorization, missing-user, state, and recovery-code invalidation tests.
### User
Implement SA-006 permission changes: remove `<all_urls>` and unnecessary `tabs`, request exact access to the configured self-hosted backend, and keep page capture behind `activeTab`.
+14
View File
@@ -183,6 +183,20 @@
179. Use the VIBE directory to log interactions.
180. Implement SA-006: remove broad Firefox extension host access and unnecessary tabs permission, request exact configured backend origin access, and keep page capture behind activeTab.
181. Continue to document every prompt and chat in the VIBE directory.
182. Continue SA-006: store session credentials in the narrowest available extension storage, minimize token lifetime, support refresh-token rotation, and clear all session material on logout or token invalidation.
183. Also allow an admin to reset (disable) OTP for any user.
183. Fix SA-009: TOTP enrollment has no recovery codes or reset workflow.
183. Address SA-007 and use linklog.example.com as the default LINKLOG_PUBLIC_URL.
184. Run full backend and frontend test suites.
185. Solve SA-010: Avatar validation trusts the client MIME type.
186. Fix SA-015: Some destructive and administrative operations lack audit logging.
187. Format sent mail in the website style and include the logo.
188. Set the email logo to 120px wide and center it at the top.
189. Make the email logo 50px by 50px, place it top-left, and put "Hello" to its right in the Asset font.
190. Replace the email greeting with "Hello a message from <public hostname>", linking the hostname to the LinkLog server.
191. Put the email header text to the right of the logo, align it at the top, and add a comma after Hello.
192. Put the email greeting in a separate top-aligned cell to the right of the logo.
193. Reduce the email greeting font size somewhat.
## Future entries
Binary file not shown.
+29 -5
View File
@@ -22,6 +22,7 @@ from backend.app.services.email_verification import create_verification_token
from backend.app.services.theme_service import THEMES, get_enabled_themes, save_enabled_themes
from backend.app.services.secret_store import encrypt_secret
from backend.app.core.config import settings
from backend.app.services.audit_service import record_audit_event
router = APIRouter()
@@ -94,8 +95,24 @@ def list_users(_: dict = Depends(require_admin)):
return [public_user(row) for row in rows]
@router.post('/users/{user_id}/otp/reset')
def reset_user_otp(user_id: str, current_user: dict = Depends(require_admin)):
with get_connection() as conn:
target = conn.execute('SELECT id FROM users WHERE id = ?', (user_id,)).fetchone()
if target is None:
raise HTTPException(status_code=404, detail='User not found')
conn.execute(
'UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
(user_id,),
)
conn.execute('DELETE FROM otp_recovery_codes WHERE user_id = ?', (user_id,))
conn.commit()
record_audit_event(current_user['id'], 'otp_reset', 'user', user_id)
return {'status': 'otp_reset', 'enabled': False, 'user_id': user_id}
@router.post('/users', status_code=201)
def create_user(payload: AdminUserCreate, _: dict = Depends(require_admin)):
def create_user(payload: AdminUserCreate, current_user: dict = Depends(require_admin)):
username = payload.username.strip()
email = payload.email.strip()
if not username or not email or len(payload.password) < 8:
@@ -126,6 +143,7 @@ def create_user(payload: AdminUserCreate, _: dict = Depends(require_admin)):
send_verification_email(row['email'], row['username'], verification_url)
except Exception as error:
raise HTTPException(status_code=503, detail=f'User created but verification email could not be sent: {error}') from error
record_audit_event(current_user['id'], 'user_created', 'user', row['id'], details={'is_admin': bool(payload.is_admin)})
return public_user(row)
@@ -151,19 +169,21 @@ def get_admin_themes(_: dict = Depends(require_admin)):
@router.put('/themes')
def update_admin_themes(payload: AdminThemesUpdate, _: dict = Depends(require_admin)):
def update_admin_themes(payload: AdminThemesUpdate, current_user: dict = Depends(require_admin)):
try:
enabled = save_enabled_themes(payload.themes)
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error)) from error
record_audit_event(current_user['id'], 'themes_updated', 'application', details={'themes': enabled})
return {'themes': THEMES, 'enabled': enabled}
@router.put('/smtp')
def update_admin_smtp_settings(payload: AdminSmtpUpdate, _: dict = Depends(require_admin)):
def update_admin_smtp_settings(payload: AdminSmtpUpdate, current_user: dict = Depends(require_admin)):
current = get_smtp_settings()
values = validate_smtp_values(payload, current)
save_smtp_settings(values)
record_audit_event(current_user['id'], 'smtp_settings_updated', 'application', details={'host': values['smtp_host'], 'port': values['smtp_port'], 'username': values['smtp_username'], 'tls': values['smtp_use_tls']})
return public_smtp_settings(values)
@@ -244,6 +264,7 @@ def update_user_privileges(
'SELECT id, username, email, is_admin, avatar_url, bio, created_at, email_verified FROM users WHERE id = ?',
(user_id,),
).fetchone()
record_audit_event(current_user['id'], 'user_privileges_updated', 'user', user_id, details={'is_admin': bool(payload.is_admin)})
return public_user(row)
@@ -266,13 +287,15 @@ def delete_user(user_id: str, current_user: dict = Depends(require_admin)):
conn.execute('DELETE FROM links WHERE user_id = ?', (user_id,))
conn.execute('DELETE FROM users WHERE id = ?', (user_id,))
conn.commit()
record_audit_event(current_user['id'], 'user_deleted', 'user', user_id)
return {'status': 'deleted', 'id': user_id}
@router.delete('/labels/{label_id}')
def admin_delete_label(label_id: str, _: dict = Depends(require_admin)):
def admin_delete_label(label_id: str, current_user: dict = Depends(require_admin)):
if not delete_label(label_id, is_admin=True):
raise HTTPException(status_code=404, detail='Label not found')
record_audit_event(current_user['id'], 'label_deleted', 'label', label_id)
return {'status': 'deleted', 'id': label_id}
@@ -331,7 +354,7 @@ def get_plugin(plugin_name: str, _: dict = Depends(require_admin)):
def update_plugin(
plugin_name: str,
payload: AdminPluginUpdate,
_: dict = Depends(require_admin),
current_user: dict = Depends(require_admin),
):
with get_connection() as conn:
current = conn.execute(
@@ -360,6 +383,7 @@ def update_plugin(
)
conn.commit()
record_audit_event(current_user['id'], 'plugin_updated', 'plugin', plugin_name, details={'enabled': enabled})
return {
'name': plugin_name,
'enabled': enabled,
+24 -2
View File
@@ -13,7 +13,7 @@ from backend.app.services.auth_service import authenticate_user, find_user
from backend.app.services.email_service import send_password_reset_email, smtp_configured
from backend.app.services.email_verification import verify_email
from backend.app.services.password_reset import create_reset_token, reset_password
from backend.app.services.token_service import issue_token, revoke_token, validate_token
from backend.app.services.token_service import issue_token, revoke_token, rotate_refresh_token, validate_token
from backend.app.services.otp_service import verify_code
from backend.app.services.secret_store import decrypt_secret
from backend.app.services.email_addresses import verify_user_email_address
@@ -28,6 +28,12 @@ class LoginRequest(BaseModel):
email: str
password: str
otp: str | None = None
device_id: str | None = None
class RefreshTokenRequest(BaseModel):
refresh_token: str
device_id: str | None = None
class PasswordResetRequest(BaseModel):
@@ -62,16 +68,32 @@ def login(payload: LoginRequest, request: Request):
raise HTTPException(status_code=401, detail='One-time password required or invalid')
clear_login_failures(ip_address, email)
token_data = issue_token(user['id'], user['username'])
token_data = issue_token(user['id'], user['username'], payload.device_id)
return {
'access_token': token_data['access_token'],
'token_type': 'bearer',
'expires_at': token_data['expires_at'],
'refresh_token': token_data['refresh_token'],
'device_id': token_data['device_id'],
'user': {'id': user['id'], 'username': user['username'], 'email': user['email'], 'otp_enabled': bool(user['otp_enabled'])}
}
@router.post('/refresh')
def refresh_token_endpoint(payload: RefreshTokenRequest):
rotated = rotate_refresh_token(payload.refresh_token, payload.device_id)
if rotated is None:
raise HTTPException(status_code=401, detail='Refresh token is invalid, expired, or bound to another device')
return {
'access_token': rotated['access_token'],
'token_type': 'bearer',
'expires_at': rotated['expires_at'],
'refresh_token': rotated['refresh_token'],
'device_id': rotated['device_id'],
'user': {'id': rotated['user_id'], 'username': rotated['username']},
}
@router.get('/verify-email')
def verify_email_address(token: str):
if not verify_email(token):
+3
View File
@@ -10,6 +10,7 @@ from backend.app.services.link_service import create_link, delete_link, find_own
from backend.app.database import get_connection
from backend.app.services.plugin_manager import plugin_manager
from backend.app.services.token_service import validate_token
from backend.app.services.audit_service import record_audit_event
router = APIRouter()
logger = logging.getLogger(__name__)
@@ -127,6 +128,7 @@ def delete_link_endpoint(
raise HTTPException(status_code=502, detail=result.get('reason', 'Could not delete Mastodon posts'))
if not delete_link(link_id, info['user_id']):
raise HTTPException(status_code=404, detail='Link not found or not owned by user')
record_audit_event(info['user_id'], 'link_deleted', 'link', link_id)
return {'status': 'deleted', 'id': link_id}
@@ -150,6 +152,7 @@ def post_link_to_mastodon(
result = plugin_manager.post_to_mastodon({'type': 'link_created', **event})
if result.get('status') == 'posted':
mark_mastodon_posted(link_id, info['user_id'], result.get('post_id'))
record_audit_event(info['user_id'], 'mastodon_posted', 'link', link_id)
return {'status': 'posted', 'post_id': result.get('post_id')}
if result.get('status') == 'skipped':
raise HTTPException(status_code=409, detail='Mastodon is not enabled or configured')
+70 -15
View File
@@ -2,23 +2,30 @@
## SPDX-License-Identifier: GPL-3.0-or-later
import json
import warnings
from io import BytesIO
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
from PIL import Image, UnidentifiedImageError
from pydantic import BaseModel
from backend.app.api.dependencies import get_current_user
from backend.app.database import AVATARS_DIR, get_connection, hash_password, verify_password
from backend.app.services.link_service import create_label, delete_label, list_user_labels, update_label
from backend.app.services.otp_service import create_secret, provisioning_uri, verify_code
from backend.app.services.otp_service import consume_recovery_code, create_recovery_codes, create_secret, provisioning_uri, verify_code
from backend.app.services.email_addresses import add_user_email_address, create_email_verification, list_user_email_addresses
from backend.app.services.email_service import send_verification_email, smtp_configured
from backend.app.core.config import settings
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
from backend.app.services.audit_service import record_audit_event
router = APIRouter()
MAX_AVATAR_BYTES = 2 * 1024 * 1024
MAX_AVATAR_PIXELS = 25_000_000
class UserConfigUpdate(BaseModel):
bio: str | None = None
@@ -32,12 +39,19 @@ class PasswordUpdate(BaseModel):
class OtpUpdate(BaseModel):
action: str
code: str | None = None
current_password: str | None = None
recovery_code: str | None = None
class AdditionalEmail(BaseModel):
email: str
class OtpRecovery(BaseModel):
current_password: str
recovery_code: str
class UserPluginConfigUpdate(BaseModel):
instance: str | None = None
@@ -103,6 +117,7 @@ def update_password(payload: PasswordUpdate, user: dict = Depends(get_current_us
(hash_password(payload.new_password), user['id']),
)
conn.commit()
record_audit_event(user['id'], 'password_changed', 'user', user['id'])
return {'status': 'password_updated'}
@@ -119,14 +134,25 @@ def setup_otp(user: dict = Depends(get_current_user)):
with get_connection() as conn:
conn.execute('UPDATE users SET otp_secret = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (encrypt_secret(secret), user['id']))
conn.commit()
return {'secret': secret, 'otpauth_url': provisioning_uri(secret, user['username'])}
record_audit_event(user['id'], 'otp_enrolled', 'user', user['id'])
return {
'secret': secret,
'otpauth_url': provisioning_uri(secret, user['username']),
'recovery_codes': create_recovery_codes(user['id']),
}
@router.post('/otp')
def update_otp(payload: OtpUpdate, user: dict = Depends(get_current_user)):
if payload.action not in {'enable', 'disable'}:
raise HTTPException(status_code=422, detail='OTP action must be enable or disable')
if not verify_code(decrypt_secret(user['otp_secret']), payload.code):
if payload.action == 'disable' and not payload.current_password:
raise HTTPException(status_code=400, detail='Current password is required to disable one-time password')
if payload.action == 'disable' and not verify_password(payload.current_password, user['password_hash']):
raise HTTPException(status_code=400, detail='Current password is incorrect')
valid_code = verify_code(decrypt_secret(user['otp_secret']), payload.code)
valid_recovery_code = payload.action == 'disable' and payload.recovery_code and consume_recovery_code(user['id'], payload.recovery_code)
if not valid_code and not valid_recovery_code:
raise HTTPException(status_code=400, detail='Invalid one-time password')
with get_connection() as conn:
if payload.action == 'enable':
@@ -134,9 +160,26 @@ def update_otp(payload: OtpUpdate, user: dict = Depends(get_current_user)):
else:
conn.execute('UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
conn.commit()
record_audit_event(user['id'], f'otp_{payload.action}d', 'user', user['id'])
return {'status': 'updated', 'enabled': payload.action == 'enable'}
@router.post('/otp/recover')
def recover_otp(payload: OtpRecovery, user: dict = Depends(get_current_user)):
if not verify_password(payload.current_password, user['password_hash']):
raise HTTPException(status_code=400, detail='Current password is incorrect')
if not consume_recovery_code(user['id'], payload.recovery_code):
raise HTTPException(status_code=400, detail='Recovery code is invalid or already used')
with get_connection() as conn:
conn.execute(
'UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
(user['id'],),
)
conn.commit()
record_audit_event(user['id'], 'otp_recovered', 'user', user['id'])
return {'status': 'otp_recovered', 'enabled': False}
@router.get('/emails')
def get_additional_emails(user: dict = Depends(get_current_user)):
return [{'email': user['email'], 'verified': bool(user['email_verified']), 'primary': True}] + list_user_email_addresses(user['id'])
@@ -221,6 +264,7 @@ def remove_additional_email(address_id: str, user: dict = Depends(get_current_us
conn.commit()
if cursor.rowcount == 0:
raise HTTPException(status_code=404, detail='Email address not found')
record_audit_event(user['id'], 'email_address_deleted', 'email_address', address_id)
return {'status': 'deleted', 'id': address_id}
@@ -249,6 +293,7 @@ def make_email_primary(address_id: str, user: dict = Depends(get_current_user)):
(address['email'], user['id']),
)
conn.commit()
record_audit_event(user['id'], 'primary_email_changed', 'user', user['id'])
return {'status': 'updated', 'email': address['email']}
@@ -280,6 +325,7 @@ def edit_label(label_id: str, payload: LabelUpdate, user: dict = Depends(get_cur
def remove_label(label_id: str, user: dict = Depends(get_current_user)):
if not delete_label(label_id, user['id']):
raise HTTPException(status_code=404, detail='Label not found or not owned by user')
record_audit_event(user['id'], 'label_deleted', 'label', label_id)
return {'status': 'deleted', 'id': label_id}
@@ -288,25 +334,33 @@ async def upload_avatar(
avatar: UploadFile = File(...),
user: dict = Depends(get_current_user),
):
allowed_types = {
'image/gif': '.gif',
'image/jpeg': '.jpg',
'image/png': '.png',
'image/webp': '.webp',
}
suffix = allowed_types.get(avatar.content_type or '')
if suffix is None:
if avatar.content_type not in {'image/gif', 'image/jpeg', 'image/png', 'image/webp'}:
raise HTTPException(status_code=415, detail='Avatar must be a PNG, JPEG, GIF, or WebP image')
contents = await avatar.read(2 * 1024 * 1024 + 1)
if len(contents) > 2 * 1024 * 1024:
contents = await avatar.read(MAX_AVATAR_BYTES + 1)
if len(contents) > MAX_AVATAR_BYTES:
raise HTTPException(status_code=413, detail='Avatar must be 2 MB or smaller')
avatar_path = AVATARS_DIR / f'{user["id"]}{suffix}'
try:
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
with Image.open(BytesIO(contents)) as image:
if image.width * image.height > MAX_AVATAR_PIXELS:
raise HTTPException(status_code=413, detail='Avatar dimensions are too large')
image.verify()
with Image.open(BytesIO(contents)) as image:
image.load()
normalized = image.convert('RGBA')
except HTTPException:
raise
except (Image.DecompressionBombError, Image.DecompressionBombWarning, UnidentifiedImageError, OSError, ValueError) as error:
raise HTTPException(status_code=415, detail='Avatar content is not a valid image') from error
avatar_path = AVATARS_DIR / f'{user["id"]}.png'
normalized.save(avatar_path, format='PNG', optimize=True)
for existing_path in AVATARS_DIR.glob(f'{user["id"]}.*'):
if existing_path != avatar_path:
existing_path.unlink(missing_ok=True)
avatar_path.write_bytes(contents)
avatar_url = f'/media/{avatar_path.name}'
with get_connection() as conn:
@@ -315,6 +369,7 @@ async def upload_avatar(
(avatar_url, user['id']),
)
conn.commit()
record_audit_event(user['id'], 'avatar_updated', 'user', user['id'])
return {'avatar_url': avatar_url}
+3 -2
View File
@@ -25,8 +25,9 @@ class Settings:
database_url: str = os.getenv('LINKLOG_DATABASE_URL', f'sqlite:///{DB_PATH}')
secret_key: str = os.getenv('LINKLOG_SECRET_KEY', 'dev-secret-key-change-me')
data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
token_expiry_days: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_DAYS', '30'))
public_url: str = normalize_public_url(os.getenv('LINKLOG_PUBLIC_URL', 'http://localhost:8000'))
token_expiry_minutes: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_MINUTES', '15'))
refresh_token_expiry_days: int = int(os.getenv('LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS', '30'))
public_url: str = normalize_public_url(os.getenv('LINKLOG_PUBLIC_URL', 'linklog.example.com'))
smtp_host: str = os.getenv('LINKLOG_SMTP_HOST', '')
smtp_port: int = int(os.getenv('LINKLOG_SMTP_PORT', '587'))
smtp_username: str = os.getenv('LINKLOG_SMTP_USERNAME', '')
+33
View File
@@ -226,6 +226,39 @@ CREATE TABLE IF NOT EXISTS pending_primary_email_changes (
'''),
(14, '''
DROP TABLE IF EXISTS pending_primary_email_changes;
'''),
(15, '''
ALTER TABLE tokens ADD COLUMN device_id TEXT;
ALTER TABLE tokens ADD COLUMN token_family_id TEXT;
CREATE INDEX IF NOT EXISTS idx_tokens_device_id ON tokens(device_id);
CREATE INDEX IF NOT EXISTS idx_tokens_family_id ON tokens(token_family_id);
'''),
(16, '''
CREATE TABLE IF NOT EXISTS otp_recovery_codes (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
code_hash TEXT NOT NULL UNIQUE,
used INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
used_at TEXT,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_otp_recovery_codes_user_id ON otp_recovery_codes(user_id);
'''),
(17, '''
CREATE TABLE IF NOT EXISTS security_audit_events (
id TEXT PRIMARY KEY,
actor_id TEXT,
action TEXT NOT NULL,
target_type TEXT NOT NULL,
target_id TEXT,
outcome TEXT NOT NULL DEFAULT 'success',
details TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(actor_id) REFERENCES users(id) ON DELETE SET NULL
);
CREATE INDEX IF NOT EXISTS idx_security_audit_events_created_at ON security_audit_events(created_at);
CREATE INDEX IF NOT EXISTS idx_security_audit_events_actor_id ON security_audit_events(actor_id);
''')
]
+23
View File
@@ -0,0 +1,23 @@
import json
from uuid import uuid4
from backend.app.database import get_connection
def record_audit_event(
actor_id: str | None,
action: str,
target_type: str,
target_id: str | None = None,
outcome: str = 'success',
details: dict | None = None,
) -> None:
safe_details = details or {}
with get_connection() as conn:
conn.execute(
'''INSERT INTO security_audit_events
(id, actor_id, action, target_type, target_id, outcome, details)
VALUES (?, ?, ?, ?, ?, ?, ?)''',
(str(uuid4()), actor_id, action, target_type, target_id, outcome, json.dumps(safe_details)),
)
conn.commit()
+60 -2
View File
@@ -2,13 +2,57 @@
## SPDX-License-Identifier: GPL-3.0-or-later
from email.message import EmailMessage
from html import escape
from pathlib import Path
from smtplib import SMTP
import json
from urllib.parse import urlparse
from backend.app.core.config import settings
from backend.app.database import get_connection
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
LOGO_PATH = Path(__file__).resolve().parents[3] / 'frontend' / 'static' / 'logo.svg'
def _html_email(body_html: str) -> str:
public_url = settings.public_url
parsed_url = urlparse(public_url)
public_hostname = parsed_url.hostname or public_url
safe_public_url = escape(public_url, quote=True)
safe_public_hostname = escape(public_hostname)
return f'''<!doctype html>
<html lang="en">
<body style="margin:0;background:#1e1e2e;color:#cdd6f4;font-family:Arial,sans-serif;line-height:1.6;">
<div style="max-width:620px;margin:32px auto;padding:0 20px;">
<div style="background:#11111b;border:1px solid #45475a;border-radius:12px;overflow:hidden;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#181825;">
<tr>
<td style="padding:20px 24px;text-align:left;vertical-align:top;width:50px;">
<img src="cid:linklog-logo" alt="LinkLog" width="50" height="50" style="display:block;width:50px;height:50px;">
</td>
<td style="padding:20px 0 20px 12px;text-align:left;vertical-align:top;">
<span style="color:#cba6f7;font-family:'Asset',Georgia,serif;font-size:18px;line-height:50px;">Hello, a message from <a href="{safe_public_url}" style="color:#cba6f7;text-decoration:underline;">{safe_public_hostname}</a></span>
</td>
</tr>
</table>
<div style="padding:28px 32px;">{body_html}</div>
</div>
<p style="margin:18px 0;text-align:center;color:#a6adc8;font-size:12px;">LinkLog</p>
</div>
</body>
</html>'''
def _add_html_body(message: EmailMessage, html_body: str) -> None:
message.add_alternative(_html_email(html_body), subtype='html')
html_part = message.get_payload()[-1]
try:
logo = LOGO_PATH.read_bytes()
except OSError:
return
html_part.add_related(logo, maintype='image', subtype='svg+xml', cid='<linklog-logo>')
def get_smtp_settings() -> dict:
values = {
@@ -42,7 +86,8 @@ def smtp_configured(smtp_values: dict | None = None) -> bool:
return bool(smtp['smtp_host'] and smtp['smtp_from'])
def send_message(email: str, subject: str, body: str, smtp_values: dict | None = None) -> None:
def send_message(email: str, subject: str, body: str, html_body: str | None = None,
smtp_values: dict | None = None) -> None:
smtp = smtp_values or get_smtp_settings()
if not smtp_configured(smtp):
raise RuntimeError('SMTP is not configured; set LINKLOG_SMTP_HOST and LINKLOG_SMTP_FROM')
@@ -52,6 +97,8 @@ def send_message(email: str, subject: str, body: str, smtp_values: dict | None =
message['From'] = smtp['smtp_from']
message['To'] = email
message.set_content(body)
if html_body:
_add_html_body(message, html_body)
with SMTP(smtp['smtp_host'], smtp['smtp_port'], timeout=10) as connection:
if smtp['smtp_use_tls']:
@@ -62,12 +109,17 @@ def send_message(email: str, subject: str, body: str, smtp_values: dict | None =
def send_verification_email(email: str, username: str, verification_url: str) -> None:
safe_username = escape(username)
safe_url = escape(verification_url, quote=True)
send_message(
email,
'Verify your LinkLog email address',
f'Hello {username},\n\n'
f'Verify your LinkLog email address by opening this link:\n{verification_url}\n\n'
f'This link expires in {settings.email_verification_expiry_hours} hours.\n',
f'<p>Hello {safe_username},</p><p>Verify your LinkLog email address:</p>'
f'<p><a href="{safe_url}" style="display:inline-block;padding:10px 16px;background:#89b4fa;color:#11111b;text-decoration:none;border-radius:6px;">Verify email address</a></p>'
f'<p style="color:#a6adc8;font-size:14px;">This link expires in {settings.email_verification_expiry_hours} hours.</p>',
)
@@ -76,15 +128,21 @@ def send_test_email(email: str, smtp_values: dict | None = None) -> None:
email,
'LinkLog SMTP test',
'This is a test message from LinkLog. SMTP is configured correctly.\n',
smtp_values,
'<p>This is a test message from LinkLog.</p><p style="color:#a6adc8;">SMTP is configured correctly.</p>',
smtp_values=smtp_values,
)
def send_password_reset_email(email: str, username: str, reset_url: str) -> None:
safe_username = escape(username)
safe_url = escape(reset_url, quote=True)
send_message(
email,
'Reset your LinkLog password',
f'Hello {username},\n\n'
f'Reset your LinkLog password by opening this link:\n{reset_url}\n\n'
f'This link expires in {settings.password_reset_expiry_hours} hours.\n',
f'<p>Hello {safe_username},</p><p>Reset your LinkLog password:</p>'
f'<p><a href="{safe_url}" style="display:inline-block;padding:10px 16px;background:#f38ba8;color:#11111b;text-decoration:none;border-radius:6px;">Reset password</a></p>'
f'<p style="color:#a6adc8;font-size:14px;">This link expires in {settings.password_reset_expiry_hours} hours.</p>',
)
+31
View File
@@ -7,12 +7,43 @@ import hmac
import secrets
import time
from urllib.parse import quote
from uuid import uuid4
from backend.app.database import get_connection
def create_secret() -> str:
return base64.b32encode(secrets.token_bytes(20)).decode('ascii').rstrip('=')
def create_recovery_codes(user_id: str, count: int = 10) -> list[str]:
codes = [secrets.token_urlsafe(9) for _ in range(count)]
with get_connection() as conn:
conn.execute('DELETE FROM otp_recovery_codes WHERE user_id = ?', (user_id,))
conn.executemany(
'INSERT INTO otp_recovery_codes (id, user_id, code_hash) VALUES (?, ?, ?)',
[(str(uuid4()), user_id, hash_recovery_code(code)) for code in codes],
)
conn.commit()
return codes
def hash_recovery_code(code: str) -> str:
return hashlib.sha256(code.strip().encode('utf-8')).hexdigest()
def consume_recovery_code(user_id: str, code: str) -> bool:
with get_connection() as conn:
cursor = conn.execute(
'''UPDATE otp_recovery_codes
SET used = 1, used_at = CURRENT_TIMESTAMP
WHERE user_id = ? AND code_hash = ? AND used = 0''',
(user_id, hash_recovery_code(code)),
)
conn.commit()
return cursor.rowcount == 1
def provisioning_uri(secret: str, username: str, issuer: str = 'LinkLog') -> str:
return f'otpauth://totp/{quote(issuer)}:{quote(username)}?secret={secret}&issuer={quote(issuer)}'
+83 -18
View File
@@ -1,7 +1,7 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from hashlib import sha256
from uuid import uuid4
@@ -13,29 +13,42 @@ def hash_token(token: str) -> str:
return sha256(token.encode('utf-8')).hexdigest()
def issue_token(user_id: str, username: str) -> dict:
token = f'token-{username}-{uuid4().hex}'
expires_at = datetime.now(timezone.utc).replace(microsecond=0)
expires_at = expires_at.replace(day=expires_at.day + 30 if False else expires_at.day)
# one-month expiry, held as a configured value in settings
from datetime import timedelta
expires_at = datetime.now(timezone.utc) + timedelta(days=settings.token_expiry_days)
def _token_expiry() -> datetime:
return datetime.now(timezone.utc) + timedelta(minutes=settings.token_expiry_minutes)
with get_connection() as conn:
def _persist_token(conn, user_id: str, token: str, token_type: str, expires_at: datetime,
device_id: str, family_id: str) -> None:
conn.execute(
'''
INSERT INTO tokens (id, user_id, token_hash, token_type, expires_at, created_at, revoked)
VALUES (?, ?, ?, 'access', ?, CURRENT_TIMESTAMP, 0)
INSERT INTO tokens
(id, user_id, token_hash, token_type, expires_at, created_at, revoked, device_id, token_family_id)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, 0, ?, ?)
''',
(str(uuid4()), user_id, hash_token(token), expires_at.isoformat())
(str(uuid4()), user_id, hash_token(token), token_type, expires_at.isoformat(), device_id, family_id),
)
def issue_token(user_id: str, username: str, device_id: str | None = None) -> dict:
device_id = device_id.strip() if device_id and device_id.strip() else f'device-{uuid4().hex}'
family_id = str(uuid4())
access_token = f'token-{username}-{uuid4().hex}'
refresh_token = f'refresh-{username}-{uuid4().hex}'
access_expires_at = _token_expiry()
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
with get_connection() as conn:
_persist_token(conn, user_id, access_token, 'access', access_expires_at, device_id, family_id)
_persist_token(conn, user_id, refresh_token, 'refresh', refresh_expires_at, device_id, family_id)
conn.commit()
return {
'access_token': token,
'access_token': access_token,
'token_type': 'bearer',
'expires_at': expires_at.isoformat(),
'refresh_token': f'refresh-{uuid4().hex}',
'expires_at': access_expires_at.isoformat(),
'refresh_token': refresh_token,
'device_id': device_id,
'token_family_id': family_id,
}
@@ -45,7 +58,7 @@ def validate_token(token: str) -> dict | None:
row = conn.execute(
'''
SELECT * FROM tokens
WHERE token_hash = ? AND revoked = 0 AND expires_at > ?
WHERE token_hash = ? AND token_type = 'access' AND revoked = 0 AND expires_at > ?
''',
(token_hash, datetime.now(timezone.utc).isoformat()),
).fetchone()
@@ -54,12 +67,64 @@ def validate_token(token: str) -> dict | None:
return dict(row)
def validate_refresh_token(token: str, device_id: str | None = None) -> dict | None:
with get_connection() as conn:
row = conn.execute(
'''
SELECT * FROM tokens
WHERE token_hash = ? AND token_type = 'refresh' AND revoked = 0 AND expires_at > ?
AND (? IS NULL OR device_id = ?)
''',
(hash_token(token), datetime.now(timezone.utc).isoformat(), device_id, device_id),
).fetchone()
return dict(row) if row else None
def rotate_refresh_token(refresh_token: str, device_id: str | None = None) -> dict | None:
current = validate_refresh_token(refresh_token, device_id)
with get_connection() as conn:
if current is None:
row = conn.execute(
'SELECT token_family_id FROM tokens WHERE token_hash = ? AND token_type = ? AND token_family_id IS NOT NULL',
(hash_token(refresh_token), 'refresh'),
).fetchone()
if row:
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (row['token_family_id'],))
conn.commit()
return None
user = conn.execute('SELECT username FROM users WHERE id = ?', (current['user_id'],)).fetchone()
if user is None:
return None
family_id = current['token_family_id']
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (family_id,))
new_access = f'token-{user["username"]}-{uuid4().hex}'
new_refresh = f'refresh-{user["username"]}-{uuid4().hex}'
access_expires_at = _token_expiry()
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
_persist_token(conn, current['user_id'], new_access, 'access', access_expires_at, current['device_id'], family_id)
_persist_token(conn, current['user_id'], new_refresh, 'refresh', refresh_expires_at, current['device_id'], family_id)
conn.commit()
return {
'access_token': new_access,
'token_type': 'bearer',
'expires_at': access_expires_at.isoformat(),
'refresh_token': new_refresh,
'device_id': current['device_id'],
'user_id': current['user_id'],
'username': user['username'],
}
def revoke_token(token: str) -> bool:
token_hash = hash_token(token)
with get_connection() as conn:
cursor = conn.execute(
'UPDATE tokens SET revoked = 1 WHERE token_hash = ?',
(token_hash,),
'''UPDATE tokens SET revoked = 1
WHERE token_hash = ? OR token_family_id = (
SELECT token_family_id FROM tokens WHERE token_hash = ?
)''',
(token_hash, token_hash),
)
conn.commit()
return cursor.rowcount > 0
+1
View File
@@ -3,6 +3,7 @@ uvicorn==0.52.4
pydantic==2.13.4
jinja2==3.1.6
python-multipart==0.0.20
Pillow==11.3.0
pytest==9.1.1
httpx==0.28.1
httpx2==2.12.0
+78
View File
@@ -14,6 +14,7 @@ from backend.app.main import app
from backend.app.database import get_connection
from backend.app.services.email_service import get_smtp_settings
from backend.app.services.login_throttle import clear_login_failures
from backend.app.services.otp_service import current_code
from backend.app.services.password_reset import create_reset_token
from backend.app.services.token_service import issue_token
@@ -68,6 +69,37 @@ def test_login_rate_limit_locks_out_after_five_failures_and_resets_on_success():
assert valid.status_code == 200
def test_refresh_token_rotates_and_reuse_revokes_family():
device_id = f'device-{uuid4().hex}'
login = client.post('/api/auth/login', json={
'email': 'alice@example.com',
'password': 'secret123',
'device_id': device_id,
})
assert login.status_code == 200
first = login.json()
rotated = client.post('/api/auth/refresh', json={
'refresh_token': first['refresh_token'],
'device_id': device_id,
})
assert rotated.status_code == 200
second = rotated.json()
assert second['refresh_token'] != first['refresh_token']
assert client.get('/api/auth/me', headers={'Authorization': f"Bearer {second['access_token']}"}).status_code == 200
reused = client.post('/api/auth/refresh', json={
'refresh_token': first['refresh_token'],
'device_id': device_id,
})
assert reused.status_code == 401
family_revoked = client.post('/api/auth/refresh', json={
'refresh_token': second['refresh_token'],
'device_id': device_id,
})
assert family_revoked.status_code == 401
def test_password_hashes_are_salted_and_legacy_hashes_upgrade_on_login():
from hashlib import sha256
from backend.app.database import hash_password
@@ -208,6 +240,52 @@ def test_admin_can_add_list_and_remove_users():
assert client.put('/api/admin/users/user-1', headers=headers, json={'is_admin': False}).status_code == 400
def test_admin_can_reset_another_users_otp():
admin_headers = login_headers()
user_login = client.post('/api/auth/login', json={
'email': 'bob@example.com',
'password': 'secret123',
}).json()
user_headers = {'Authorization': f"Bearer {user_login['access_token']}"}
setup = client.post('/api/user/otp/setup', headers=user_headers)
assert setup.status_code == 200
secret = setup.json()['secret']
recovery_code = setup.json()['recovery_codes'][0]
assert client.post('/api/user/otp', headers=user_headers, json={
'action': 'enable', 'code': current_code(secret),
}).status_code == 200
assert client.post('/api/admin/users/user-2/otp/reset', headers=admin_headers).json() == {
'status': 'otp_reset', 'enabled': False, 'user_id': 'user-2',
}
assert client.get('/api/user/otp', headers=user_headers).json() == {'enabled': False}
assert client.post('/api/user/otp/recover', headers=user_headers, json={
'current_password': 'secret123', 'recovery_code': recovery_code,
}).status_code == 400
assert client.post('/api/admin/users/user-2/otp/reset', headers=login_headers('bob')).status_code == 403
assert client.post('/api/admin/users/missing-user/otp/reset', headers=admin_headers).status_code == 404
def test_security_audit_events_are_append_only_and_do_not_store_secrets():
admin_headers = login_headers()
response = client.put('/api/admin/themes', headers=admin_headers, json={'themes': ['plain-day']})
assert response.status_code == 200
with get_connection() as conn:
event = conn.execute(
'''SELECT actor_id, action, target_type, outcome, details
FROM security_audit_events
WHERE action = 'themes_updated'
ORDER BY created_at DESC, rowid DESC LIMIT 1''',
).fetchone()
assert event is not None
assert event['actor_id'] == 'user-1'
assert event['target_type'] == 'application'
assert event['outcome'] == 'success'
assert 'password' not in event['details'].lower()
assert 'token' not in event['details'].lower()
assert 'secret' not in event['details'].lower()
def test_new_user_must_verify_email_before_login():
headers = login_headers()
username = f'unverified-{uuid4().hex}'
+2 -2
View File
@@ -10,7 +10,7 @@ def test_database_migrations_are_versioned_and_idempotent():
connection = sqlite3.connect(':memory:')
apply_migrations(connection)
assert get_schema_version(connection) == 14
assert get_schema_version(connection) == 17
tables = {
row[0]
for row in connection.execute(
@@ -27,6 +27,6 @@ def test_database_migrations_are_versioned_and_idempotent():
assert set(DEFAULT_TAGS) <= seeded_tags
apply_migrations(connection)
assert get_schema_version(connection) == 14
assert get_schema_version(connection) == 17
connection.close()
+35 -2
View File
@@ -3,7 +3,7 @@
from unittest.mock import patch
from backend.app.services.email_service import send_test_email, send_verification_email
from backend.app.services.email_service import send_password_reset_email, send_test_email, send_verification_email
def test_send_verification_email_uses_smtp_settings(monkeypatch):
@@ -15,6 +15,7 @@ def test_send_verification_email_uses_smtp_settings(monkeypatch):
monkeypatch.setattr(settings, 'smtp_username', 'mailer')
monkeypatch.setattr(settings, 'smtp_password', 'secret')
monkeypatch.setattr(settings, 'smtp_use_tls', True)
monkeypatch.setattr(settings, 'public_url', 'https://linklog.example')
with patch('backend.app.services.email_service.SMTP') as smtp_class:
smtp = smtp_class.return_value.__enter__.return_value
@@ -25,7 +26,22 @@ def test_send_verification_email_uses_smtp_settings(monkeypatch):
smtp.login.assert_called_once_with('mailer', 'secret')
message = smtp.send_message.call_args.args[0]
assert message['To'] == 'user@example.com'
assert 'https://linklog.example/verify' in message.get_content()
assert 'https://linklog.example/verify' in message.get_body(preferencelist=('plain',)).get_content()
html = message.get_body(preferencelist=('html',)).get_content()
assert 'cid:linklog-logo' in html
assert 'width="50" height="50"' in html
assert 'font-family:\'Asset\',Georgia,serif' in html
assert 'Hello, a message from' in html
assert 'vertical-align:top' in html
assert 'padding:20px 0 20px 12px' in html
assert 'font-size:18px' in html
assert 'href="https://linklog.example"' in html
assert '>linklog.example</a>' in html
assert any(
part.get_content_type() == 'image/svg+xml'
and part['Content-ID'] == '<linklog-logo>'
for part in message.walk()
)
def test_send_test_email_uses_configured_recipient(monkeypatch):
@@ -40,6 +56,23 @@ def test_send_test_email_uses_configured_recipient(monkeypatch):
message = smtp.send_message.call_args.args[0]
assert message['To'] == 'admin@example.com'
assert message['Subject'] == 'LinkLog SMTP test'
assert message.get_body(preferencelist=('html',)) is not None
def test_password_reset_email_escapes_html_and_includes_logo(monkeypatch):
from backend.app.core.config import settings
monkeypatch.setattr(settings, 'smtp_host', 'smtp.example.com')
monkeypatch.setattr(settings, 'smtp_from', 'LinkLog <no-reply@example.com>')
with patch('backend.app.services.email_service.SMTP') as smtp_class:
smtp = smtp_class.return_value.__enter__.return_value
send_password_reset_email('user@example.com', '<User>', 'https://linklog.example/reset?x=1&y=2')
message = smtp.send_message.call_args.args[0]
html = message.get_body(preferencelist=('html',)).get_content()
assert '&lt;User&gt;' in html
assert 'x=1&amp;y=2' in html
assert 'cid:linklog-logo' in html
def test_smtp_password_is_encrypted_at_rest():
+46 -3
View File
@@ -1,7 +1,10 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from io import BytesIO
from fastapi.testclient import TestClient
from PIL import Image
from unittest.mock import patch
from backend.app.main import app
@@ -68,15 +71,29 @@ def test_user_config_api_and_profile_page():
'new_password': 'secret123',
}, headers=bob_headers).status_code == 200
image_buffer = BytesIO()
Image.new('RGB', (2, 2), 'red').save(image_buffer, format='JPEG')
upload_response = client.post(
'/api/user/avatar',
headers=headers,
files={'avatar': ('avatar.png', b'fake-png-data', 'image/png')},
files={'avatar': ('avatar.jpg', image_buffer.getvalue(), 'image/jpeg')},
)
assert upload_response.status_code == 200
avatar_url = upload_response.json()['avatar_url']
assert avatar_url.startswith('/media/user-1.png')
assert client.get(avatar_url).content == b'fake-png-data'
stored_avatar = client.get(avatar_url)
assert stored_avatar.status_code == 200
assert stored_avatar.headers['content-type'] == 'image/png'
with Image.open(BytesIO(stored_avatar.content)) as image:
assert image.format == 'PNG'
assert image.size == (2, 2)
rejected_upload = client.post(
'/api/user/avatar',
headers=headers,
files={'avatar': ('avatar.png', b'fake-png-data', 'image/png')},
)
assert rejected_upload.status_code == 415
updated_profile = client.get('/api/user/me', headers=headers).json()
assert updated_profile['avatar_url'] == avatar_url
@@ -89,6 +106,8 @@ def test_user_can_enable_and_use_otp():
assert setup.status_code == 200
secret = setup.json()['secret']
assert setup.json()['otpauth_url'].startswith('otpauth://totp/')
recovery_codes = setup.json()['recovery_codes']
assert len(recovery_codes) == 10
enabled = client.post('/api/user/otp', headers=headers, json={
'action': 'enable', 'code': current_code(secret),
@@ -103,12 +122,36 @@ def test_user_can_enable_and_use_otp():
assert otp_login.status_code == 200
disabled = client.post('/api/user/otp', headers=headers, json={
'action': 'disable', 'code': current_code(secret),
'action': 'disable', 'code': current_code(secret), 'current_password': 'secret123',
})
assert disabled.status_code == 200
assert disabled.json()['enabled'] is False
def test_otp_recovery_code_requires_password_and_is_single_use():
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
headers = {'Authorization': f"Bearer {login['access_token']}"}
setup = client.post('/api/user/otp/setup', headers=headers)
secret = setup.json()['secret']
recovery_code = setup.json()['recovery_codes'][0]
assert client.post('/api/user/otp', headers=headers, json={
'action': 'enable', 'code': current_code(secret),
}).status_code == 200
rejected = client.post('/api/user/otp/recover', headers=headers, json={
'current_password': 'wrong-password', 'recovery_code': recovery_code,
})
assert rejected.status_code == 400
recovered = client.post('/api/user/otp/recover', headers=headers, json={
'current_password': 'secret123', 'recovery_code': recovery_code,
})
assert recovered.status_code == 200
reused = client.post('/api/user/otp/recover', headers=headers, json={
'current_password': 'secret123', 'recovery_code': recovery_code,
})
assert reused.status_code == 400
def test_verified_alternative_can_become_primary():
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
headers = {'Authorization': f"Bearer {login['access_token']}"}
+2 -3
View File
@@ -4,8 +4,6 @@ services:
app:
image: git.kolkman.org/olaf/link-log:development # or :latest or a version-tag
container_name: ${APP_CONTAINER_NAME:-linklog-app}
ports:
- "${APP_PORT:-8000}:8000"
volumes:
- ./linklog_data:/app/backend/data
environment:
@@ -13,7 +11,8 @@ services:
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
LINKLOG_TOKEN_EXPIRY_DAYS: ${LINKLOG_TOKEN_EXPIRY_DAYS:-30}
LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
LINKLOG_SMTP_HOST: ${LINKLOG_SMTP_HOST:-smtp.example.com}
LINKLOG_SMTP_PORT: ${LINKLOG_SMTP_PORT:-587}
+30
View File
@@ -0,0 +1,30 @@
# Local development only. The production compose file intentionally does not publish port 8000.
services:
app:
build:
context: .
dockerfile: Dockerfile
container_name: ${APP_CONTAINER_NAME:-linklog-app-local}
ports:
- "${APP_PORT:-8000}:8000"
volumes:
- ./linklog_data:/app/backend/data
environment:
APP_ENV: ${APP_ENV:-development}
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
LINKLOG_DATA_ENCRYPTION_KEY: ${LINKLOG_DATA_ENCRYPTION_KEY:?Set LINKLOG_DATA_ENCRYPTION_KEY in .env}
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-http://localhost:8000}
LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-DEBUG}
LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
restart: ${APP_RESTART_POLICY:-unless-stopped}
healthcheck:
test: ["CMD", "python", "-c", "from urllib.request import urlopen; urlopen('http://127.0.0.1:8000/health', timeout=3)"]
interval: ${APP_HEALTHCHECK_INTERVAL:-30s}
timeout: ${APP_HEALTHCHECK_TIMEOUT:-5s}
start_period: ${APP_HEALTHCHECK_START_PERIOD:-10s}
retries: ${APP_HEALTHCHECK_RETRIES:-3}
+3 -5
View File
@@ -7,8 +7,6 @@ services:
context: .
dockerfile: Dockerfile
container_name: ${APP_CONTAINER_NAME:-linklog-app}
ports:
- "${APP_PORT:-8000}:8000"
volumes:
- ./linklog_data:/app/backend/data
environment:
@@ -17,7 +15,7 @@ services:
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
LINKLOG_DATA_ENCRYPTION_KEY: ${LINKLOG_DATA_ENCRYPTION_KEY:?Set LINKLOG_DATA_ENCRYPTION_KEY in .env}
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-localhost}
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-INFO}
LINKLOG_TOKEN_EXPIRY_DAYS: ${LINKLOG_TOKEN_EXPIRY_DAYS:-30}
LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
@@ -36,10 +34,10 @@ services:
traefik.http.routers.linklog.entrypoints: web
traefik.http.routers.linklog.rule: Host(`${LINKLOG_PUBLIC_URL:-localhost}`)
traefik.http.routers.linklog.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
traefik.http.routers.linklog.middlewares: web-https-redirect,servicests
traefik.http.routers.linklog-secure.entrypoints: websecure
traefik.http.routers.linklog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-localhost}`)
traefik.http.routers.linklog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
traefik.http.routers.linklog-secure.tls: true
traefik.http.routers.linklog-secure.middlewares: servicests
+26
View File
@@ -152,6 +152,11 @@ function renderUsers(users) {
privilegeLabel.append(privilegeCheckbox, document.createTextNode(' Administrator'));
row.append(label, privilegeLabel);
if (!isCurrentUser) {
const otpButton = document.createElement('button');
otpButton.type = 'button';
otpButton.textContent = 'Reset OTP';
otpButton.addEventListener('click', () => resetUserOtp(user, otpButton));
row.append(otpButton);
const button = document.createElement('button');
button.type = 'button';
button.className = 'danger-button';
@@ -163,6 +168,27 @@ function renderUsers(users) {
}));
}
async function resetUserOtp(user, button) {
if (!window.confirm(`Disable OTP for ${user.username}?`)) return;
button.disabled = true;
const status = document.querySelector('#user-status');
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(user.id)}/otp/reset`, {
method: 'POST',
headers: authHeaders(),
});
if (!response.ok) {
throw new Error(await responseError(response, `Request failed (${response.status})`));
}
status.textContent = `OTP disabled for ${user.username}.`;
status.style.color = '#94e2d5';
} catch (error) {
status.textContent = `Could not reset OTP for ${user.username}: ${error.message}`;
status.style.color = '#f38ba8';
button.disabled = false;
}
}
async function loadUsers() {
const response = await fetch('/api/admin/users', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load users');
+23 -1
View File
@@ -12,11 +12,13 @@ const mastodonConnectButton = document.querySelector('#mastodon-connect');
const otpSetupButton = document.querySelector('#otp-setup');
const otpEnableButton = document.querySelector('#otp-enable');
const otpDisableButton = document.querySelector('#otp-disable');
const otpRecoverButton = document.querySelector('#otp-recover');
const otpProvisioning = document.querySelector('#otp-provisioning');
const otpDisabled = document.querySelector('#otp-disabled');
const otpEnabled = document.querySelector('#otp-enabled');
const otpSecret = document.querySelector('#otp-secret');
const otpUri = document.querySelector('#otp-uri');
const otpRecoveryCodes = document.querySelector('#otp-recovery-codes');
const otpStatus = document.querySelector('#otp-status');
const emailAddressList = document.querySelector('#email-address-list');
const additionalEmailForm = document.querySelector('#additional-email-form');
@@ -131,6 +133,7 @@ otpSetupButton.addEventListener('click', async () => {
}
otpSecret.textContent = result.secret;
otpUri.href = result.otpauth_url;
otpRecoveryCodes.textContent = result.recovery_codes.join('\n');
otpProvisioning.classList.remove('hidden');
setOtpStatus('Enter a code from your authenticator app to confirm setup.');
});
@@ -153,8 +156,9 @@ otpEnableButton.addEventListener('click', async () => {
otpDisableButton.addEventListener('click', async () => {
const code = document.querySelector('#otp-disable-code').value.trim();
const currentPassword = document.querySelector('#otp-current-password').value;
const response = await fetch('/api/user/otp', {
method: 'POST', headers: authHeaders(true), body: JSON.stringify({action: 'disable', code}),
method: 'POST', headers: authHeaders(true), body: JSON.stringify({action: 'disable', code, current_password: currentPassword}),
});
const result = await response.json();
if (!response.ok) {
@@ -167,6 +171,24 @@ otpDisableButton.addEventListener('click', async () => {
setOtpStatus('One-time password disabled.');
});
otpRecoverButton.addEventListener('click', async () => {
const currentPassword = document.querySelector('#otp-current-password').value;
const recoveryCode = document.querySelector('#otp-recovery-code').value.trim();
const response = await fetch('/api/user/otp/recover', {
method: 'POST', headers: authHeaders(true), body: JSON.stringify({current_password: currentPassword, recovery_code: recoveryCode}),
});
const result = await response.json();
if (!response.ok) {
setOtpStatus(result.detail || 'Could not recover one-time password access.', true);
return;
}
otpDisabled.classList.remove('hidden');
otpEnabled.classList.add('hidden');
document.querySelector('#otp-current-password').value = '';
document.querySelector('#otp-recovery-code').value = '';
setOtpStatus('One-time password access recovered.');
});
async function loadProfile() {
const response = await fetch('/api/user/me', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load profile');
+6
View File
@@ -108,13 +108,19 @@
<label>Verification code <input id="otp-setup-code" inputmode="numeric"
autocomplete="one-time-code" /></label>
<button id="otp-enable" type="button">Enable one-time password</button>
<p>Save these recovery codes in a secure place. They are shown only once:</p>
<code id="otp-recovery-codes"></code>
</div>
</div>
<div id="otp-enabled" class="hidden">
<p>One-time password is enabled.</p>
<label>Current password <input id="otp-current-password" type="password" autocomplete="current-password" /></label>
<label>Verification code <input id="otp-disable-code" inputmode="numeric"
autocomplete="one-time-code" /></label>
<button id="otp-disable" type="button">Disable one-time password</button>
<p>Lost access to your authenticator? Use a saved recovery code.</p>
<label>Recovery code <input id="otp-recovery-code" type="text" autocomplete="one-time-code" /></label>
<button id="otp-recover" type="button">Recover and disable one-time password</button>
</div>
<p id="otp-status" class="status" role="status"></p>
</section>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

+4 -1
View File
@@ -12,6 +12,9 @@
"http://*/*",
"https://*/*"
],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'none'"
},
"action": {
"default_title": "__MSG_extensionName__",
"default_popup": "popup.html",
@@ -27,7 +30,7 @@
"browser_specific_settings": {
"gecko": {
"id": "linklog@kolkman.org",
"strict_min_version": "109.0",
"strict_min_version": "112.0",
"data_collection_permissions": {
"required": ["websiteActivity"],
"optional": []
+54 -9
View File
@@ -10,6 +10,7 @@ const otpInput = document.getElementById('otp');
const session = document.getElementById('logged-in');
const sessionSummary = document.getElementById('session-summary');
const signOutButton = document.getElementById('sign-out');
const sessionStore = browser.storage.session;
const t = window.linklogI18n;
@@ -49,15 +50,18 @@ function setStatus(message, isError = false) {
}
async function loadSettings() {
const settings = await browser.storage.local.get(['backendUrl', 'email', 'username', 'accessToken']);
const [settings, sessionSettings] = await Promise.all([
browser.storage.local.get(['backendUrl', 'email', 'username']),
sessionStore.get(['accessToken', 'refreshToken', 'tokenExpiresAt', 'deviceId']),
]);
backendUrlInput.value = settings.backendUrl || '';
emailInput.value = settings.email || '';
if (settings.accessToken && settings.backendUrl && await hasBackendPermission(settings.backendUrl)) {
if (sessionSettings.accessToken && settings.backendUrl && await hasBackendPermission(settings.backendUrl)) {
try {
const response = await fetch(
`${settings.backendUrl}/api/auth/me`,
{headers: {Authorization: `Bearer ${settings.accessToken}`}},
{headers: {Authorization: `Bearer ${sessionSettings.accessToken}`}},
);
if (response.ok) {
const user = await response.json();
@@ -84,7 +88,32 @@ function showLoggedOut() {
}
async function clearSession() {
await browser.storage.local.remove(['accessToken', 'tokenType', 'tokenExpiresAt', 'refreshToken']);
await Promise.all([
sessionStore.remove(['accessToken', 'refreshToken', 'tokenExpiresAt', 'deviceId']),
browser.storage.local.remove(['accessToken', 'tokenType', 'tokenExpiresAt', 'refreshToken', 'deviceId']),
]);
}
async function refreshAccessToken(settings) {
if (!settings.backendUrl || !settings.refreshToken || !settings.deviceId) return null;
try {
const response = await fetch(`${settings.backendUrl}/api/auth/refresh`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({refresh_token: settings.refreshToken, device_id: settings.deviceId}),
});
if (!response.ok) {
await clearSession();
return null;
}
const data = await response.json();
const refreshed = {accessToken: data.access_token, refreshToken: data.refresh_token,
tokenExpiresAt: data.expires_at, deviceId: data.device_id || settings.deviceId};
await sessionStore.set(refreshed);
return refreshed;
} catch (error) {
return null;
}
}
async function saveSettingsAndLogin(event) {
@@ -116,14 +145,29 @@ async function saveSettingsAndLogin(event) {
}
const data = await response.json();
if (response.status === 401) {
const refreshed = await refreshAccessToken({...settings, ...sessionSettings});
if (refreshed) {
const retry = await fetch(`${settings.backendUrl}/api/auth/me`, {
headers: {Authorization: `Bearer ${refreshed.accessToken}`},
});
if (retry.ok) {
const user = await retry.json();
showLoggedIn(user.username || settings.email, settings.backendUrl);
return;
}
}
}
await browser.storage.local.set({
backendUrl,
email,
username: data.user?.username || email,
});
await sessionStore.set({
accessToken: data.access_token,
tokenType: data.token_type,
tokenExpiresAt: data.expires_at,
refreshToken: data.refresh_token,
tokenExpiresAt: data.expires_at,
deviceId: data.device_id || `device-${crypto.randomUUID()}`,
});
showLoggedIn(data.user?.username || email, backendUrl);
@@ -136,13 +180,14 @@ async function saveSettingsAndLogin(event) {
}
async function signOut() {
const settings = await browser.storage.local.get(['accessToken']);
const settings = await browser.storage.local.get(['backendUrl']);
const sessionSettings = await sessionStore.get(['accessToken']);
const backendUrl = normalizeBackendOrigin(backendUrlInput.value.trim());
if (settings.accessToken && await hasBackendPermission(backendUrl)) {
if (sessionSettings.accessToken && settings.backendUrl && await hasBackendPermission(backendUrl)) {
await fetch(`${backendUrl}/api/auth/logout`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: settings.accessToken }),
body: JSON.stringify({ token: sessionSettings.accessToken }),
}).catch(() => undefined);
}
await clearSession();
+63 -13
View File
@@ -13,6 +13,7 @@ const feedLink = document.getElementById('feed-link');
const authWarning = document.getElementById('auth-warning');
const warningSettingsButton = document.getElementById('warning-settings');
const authSession = document.getElementById('auth-session');
const sessionStore = browser.storage.session;
const t = window.linklogI18n;
@@ -42,12 +43,49 @@ function setStatus(message, isError = false) {
}
async function getSettings() {
const result = await browser.storage.local.get([
'backendUrl',
'accessToken',
'tokenExpiresAt',
const [settings, sessionSettings] = await Promise.all([
browser.storage.local.get(['backendUrl', 'username']),
sessionStore.get(['accessToken', 'refreshToken', 'tokenExpiresAt', 'deviceId']),
]);
return result;
return {...settings, ...sessionSettings};
}
async function persistSession(settings) {
await sessionStore.set({
accessToken: settings.accessToken,
refreshToken: settings.refreshToken,
tokenExpiresAt: settings.tokenExpiresAt,
deviceId: settings.deviceId,
});
}
async function clearSession() {
await Promise.all([
sessionStore.remove(['accessToken', 'refreshToken', 'tokenExpiresAt', 'deviceId']),
browser.storage.local.remove(['accessToken', 'tokenType', 'tokenExpiresAt', 'refreshToken', 'deviceId']),
]);
}
async function refreshAccessToken(settings) {
if (!settings.backendUrl || !settings.refreshToken || !settings.deviceId) return null;
try {
const response = await fetch(`${settings.backendUrl}/api/auth/refresh`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({refresh_token: settings.refreshToken, device_id: settings.deviceId}),
});
if (!response.ok) {
await clearSession();
return null;
}
const data = await response.json();
const refreshed = {...settings, accessToken: data.access_token, refreshToken: data.refresh_token,
tokenExpiresAt: data.expires_at, deviceId: data.device_id || settings.deviceId};
await persistSession(refreshed);
return refreshed;
} catch (error) {
return null;
}
}
async function validateSession(settings) {
@@ -57,7 +95,16 @@ async function validateSession(settings) {
headers: {'Authorization': `Bearer ${settings.accessToken}`},
});
if (!response.ok) {
await browser.storage.local.remove(['accessToken', 'tokenType', 'tokenExpiresAt', 'refreshToken']);
if (response.status === 401) {
const refreshed = await refreshAccessToken(settings);
if (refreshed) {
const retry = await fetch(`${refreshed.backendUrl}/api/auth/me`, {
headers: {'Authorization': `Bearer ${refreshed.accessToken}`},
});
if (retry.ok) return await retry.json();
}
}
await clearSession();
return null;
}
return await response.json();
@@ -97,7 +144,7 @@ function showSavedState(message) {
}
async function updateFeedLink() {
const settings = await browser.storage.local.get(['backendUrl', 'username', 'accessToken']);
const settings = await getSettings();
if (!settings.backendUrl || !settings.username || !settings.accessToken) return;
try {
const backend = new URL(settings.backendUrl);
@@ -119,9 +166,10 @@ async function loadExistingTags() {
showSignedOutState();
return;
}
showSignedInState(user, settings.backendUrl);
const response = await fetch(`${settings.backendUrl}/api/tags`, {
headers: {'Authorization': `Bearer ${settings.accessToken}`},
const currentSettings = await getSettings();
showSignedInState(user, currentSettings.backendUrl);
const response = await fetch(`${currentSettings.backendUrl}/api/tags`, {
headers: {'Authorization': `Bearer ${currentSettings.accessToken}`},
});
if (!response.ok) {
if (response.status === 401) {
@@ -212,12 +260,14 @@ async function handleSubmit(event) {
return;
}
const currentSettings = await getSettings();
try {
const response = await fetch(`${backendUrl}/api/links`, {
const response = await fetch(`${currentSettings.backendUrl}/api/links`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'Authorization': `Bearer ${currentSettings.accessToken}`,
},
body: JSON.stringify({
title: titleInput.value,
@@ -240,7 +290,7 @@ async function handleSubmit(event) {
}
const result = await response.json();
const saveMessage = result.duplicate ? t('linkAlreadyExists') : t('linkSaved', backendUrl);
const saveMessage = result.duplicate ? t('linkAlreadyExists') : t('linkSaved', currentSettings.backendUrl);
if (result.plugin_errors?.length) {
const errors = result.plugin_errors.map((error) => `${error.plugin}: ${error.reason}`).join(' ');
showSavedState(`${saveMessage} ${t('publishingErrors', errors)}`);