17 Commits
Author SHA1 Message Date
olaf af5d38a16b Bump backend version to 0.1.1 and validate plugin manifest sync
Build LinkLog Development Image / development-image (push) Successful in 10s
Release LinkLog / release (push) Successful in 9s
2026-08-27 18:04:49 +02:00
olaf b93a8099f3 Merge origin/main into release branch
Build LinkLog Development Image / development-image (push) Successful in 14s
Release LinkLog / release (push) Failing after 2s
# Conflicts:
#	VIBE/CHAT_LOG.md
2026-08-27 17:50:07 +02:00
olaf f8fcadb488 theme selecter moved 2026-08-27 17:43:47 +02:00
olaf 60f7107ec9 Stale VIBE log update 2026-08-27 17:34:34 +02:00
olaf 16571a9645 New Entry functionality 2026-08-27 17:33:43 +02:00
Olaf c11b25c20a Change release - don't publish the XPI but a readme instead
Build LinkLog Development Image / development-image (push) Failing after 1s
Release LinkLog / release (push) Failing after 1s
2026-08-27 08:31:56 +02:00
Olaf c27aad58ae debugging workflow
Build LinkLog Development Image / development-image (push) Successful in 8s
Release LinkLog / release (push) Successful in 8s
2026-08-26 22:51:34 +02:00
olaf 7dffaad8e5 Fixed workflow
Build LinkLog Development Image / development-image (push) Successful in 8s
Release LinkLog / release (push) Failing after 8s
2026-08-26 22:40:39 +02:00
olaf 583026418d Format change in toots
Build LinkLog Development Image / development-image (push) Successful in 13s
Release LinkLog / release (push) Failing after 9s
2026-08-26 22:30:07 +02:00
olaf fa6d88a768 Download links for the plugin
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-26 22:07:08 +02:00
olaf b6c01878a8 Signed LinkLog added 2026-08-26 21:54:47 +02:00
olaf 5dbef8f23f Minor manifest change
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-08-26 21:46:21 +02:00
olaf ffb12a36b5 Secret test at startup
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-08-26 20:54:00 +02:00
olaf 04b8a5a8b9 Log details obfuscated to not leak info 2026-08-26 20:51:29 +02:00
olaf b4b40e5c2c Logout now requires Authorization: Bearer <access-token>. 2026-08-26 20:46:48 +02:00
olaf 16c9c3a03f Updated Security Audit 2026-08-26 20:42:44 +02:00
olaf 018c02c759 Some additional checks and cleanup
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-26 20:35:06 +02:00
42 changed files with 1516 additions and 354 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ APP_HEALTHCHECK_TIMEOUT=5s
APP_HEALTHCHECK_START_PERIOD=10s APP_HEALTHCHECK_START_PERIOD=10s
APP_HEALTHCHECK_RETRIES=3 APP_HEALTHCHECK_RETRIES=3
LINKLOG_APP_NAME=LinkLog LINKLOG_APP_NAME=LinkLog
LINKLOG_VERSION=0.1.0 LINKLOG_VERSION=0.1.1
LINKLOG_SECRET_KEY=replace-with-a-long-random-secret LINKLOG_SECRET_KEY=replace-with-a-long-random-secret
LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key
LINKLOG_TOKEN_EXPIRY_MINUTES=15 LINKLOG_TOKEN_EXPIRY_MINUTES=15
+87 -26
View File
@@ -19,11 +19,10 @@ jobs:
- name: Validate versions and signed XPI - name: Validate versions and signed XPI
id: release id: release
run: | run: |
python3 scripts/release/validate_release.py python3 scripts/release/validate_release.py --github-output "$GITHUB_OUTPUT"
version=$(python3 -c "import json; print(json.load(open('frontend/version.json'))['version'])") backend_version=$(python3 -c "import re; text=open('backend/app/core/config.py').read(); print(re.search(r\"version: str = os\\.getenv\\('LINKLOG_VERSION', '([^']+)'\\)\", text).group(1))")
echo "version=$version" >> "$GITHUB_OUTPUT" if [ "${GITHUB_REF_NAME#v}" != "$backend_version" ]; then
if [ "${GITHUB_REF_NAME#v}" != "$version" ]; then echo "tag ${GITHUB_REF_NAME} does not match backend version $backend_version" >&2
echo "tag ${GITHUB_REF_NAME} does not match release version $version" >&2
exit 1 exit 1
fi fi
@@ -40,51 +39,113 @@ jobs:
context: . context: .
push: true push: true
tags: | tags: |
${{ env.IMAGE_NAME }}:${{ steps.release.outputs.version }} ${{ env.IMAGE_NAME }}:${{ steps.release.outputs.backend_version }}
${{ env.IMAGE_NAME }}:latest ${{ env.IMAGE_NAME }}:latest
labels: | labels: |
org.opencontainers.image.version=${{ steps.release.outputs.version }} org.opencontainers.image.version=${{ steps.release.outputs.backend_version }}
org.opencontainers.image.source=https://git.kolkman.org/olaf/Link-Log org.opencontainers.image.source=https://git.kolkman.org/olaf/Link-Log
- name: Generate release README
env:
BACKEND_VERSION: ${{ steps.release.outputs.backend_version }}
PLUGIN_VERSION: ${{ steps.release.outputs.plugin_version }}
SIGNED_XPI: ${{ steps.release.outputs.signed_xpi }}
run: |
cat > release-readme.md <<EOF
# LinkLog $BACKEND_VERSION
LinkLog is a Firefox extension and Python web service for saving links with a title, comment, timestamp, and tracking parameters removed. The service stores links in SQLite and can publish them through plugins, including Mastodon.
## Docker Container
The current backend/container version is $BACKEND_VERSION. Pull it from the Gitea container registry:
\`\`\`sh
docker pull $IMAGE_NAME:$BACKEND_VERSION
\`\`\`
The same image is also published as:
\`\`\`sh
docker pull $IMAGE_NAME:latest
\`\`\`
The developer version of the backend is always published as $IMAGE_NAME:latest, which may be ahead of the current release version and may be unstable.
Additional information about the backend can be found in the [README](https://git.kolkman.org/olaf/Link-Log/src/branch/main/backend/README.md).
## Firefox Extension
The current signed Firefox plugin version, compatible with this version of the backend, is $PLUGIN_VERSION. Download it from the raw repository artifact:
https://git.kolkman.org/olaf/Link-Log/raw/branch/main/$SIGNED_XPI
EOF
- name: Create Gitea release - name: Create Gitea release
id: gitea_release id: gitea_release
env: env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }} RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
VERSION: ${{ steps.release.outputs.version }} VERSION: ${{ steps.release.outputs.backend_version }}
run: | run: |
response=$(curl --fail-with-body --silent --show-error \ payload_file=$(mktemp)
python3 - <<'PY' > "$payload_file"
import json
import os
from pathlib import Path
version = os.environ['VERSION']
print(json.dumps({
'tag_name': f'v{version}',
'name': f'LinkLog {version}',
'body': Path('release-readme.md').read_text(),
'draft': False,
'prerelease': False,
}))
PY
response_file=$(mktemp)
response_status=$(curl --silent --show-error -o "$response_file" -w '%{http_code}' \
-X POST \ -X POST \
-H "Authorization: token $RELEASE_TOKEN" \ -H "Authorization: token $RELEASE_TOKEN" \
-H 'Content-Type: application/json' \ -H 'Content-Type: application/json' \
-d "{\"tag_name\":\"v$VERSION\",\"name\":\"LinkLog $VERSION\",\"draft\":false,\"prerelease\":false}" \ --data-binary "@$payload_file" \
https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases) https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases)
release_id=$(printf '%s' "$response" | jq -r '.id') rm -f "$payload_file"
if [ "$response_status" = 409 ]; then
response_status=$(curl --silent --show-error -o "$response_file" -w '%{http_code}' \
-H "Authorization: token $RELEASE_TOKEN" \
"https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases/tags/v$VERSION")
fi
if [ "$response_status" -lt 200 ] || [ "$response_status" -ge 300 ]; then
cat "$response_file" >&2
exit 1
fi
response=$(cat "$response_file")
rm -f "$response_file"
release_id=$(printf '%s' "$response" | python3 -c 'import json, sys; print(json.load(sys.stdin)["id"])')
test "$release_id" != null test "$release_id" != null
test "$release_id" != 0 test "$release_id" != 0
upload_url="https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases/$release_id/assets" upload_url="https://git.kolkman.org/api/v1/repos/olaf/Link-Log/releases/$release_id/assets"
echo "upload_url=$upload_url" >> "$GITHUB_OUTPUT" echo "upload_url=$upload_url" >> "$GITHUB_OUTPUT"
- name: Upload signed XPI and update manifest - name: Upload release README
env: env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }} RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
UPLOAD_URL: ${{ steps.gitea_release.outputs.upload_url }} UPLOAD_URL: ${{ steps.gitea_release.outputs.upload_url }}
VERSION: ${{ steps.release.outputs.version }}
run: | run: |
curl --fail-with-body --silent --show-error \ response_status=$(curl --silent --show-error -o /tmp/linklog-readme-upload-response -w '%{http_code}' \
-X POST -H "Authorization: token $RELEASE_TOKEN" \ -X POST -H "Authorization: token $RELEASE_TOKEN" \
-H 'Content-Type: application/x-xpinstall' \ -H 'Content-Type: text/markdown' \
--data-binary "@XPI/signed/LinkLog-$VERSION.xpi" \ --data-binary @release-readme.md \
"$UPLOAD_URL?name=LinkLog-$VERSION.xpi" "$UPLOAD_URL?name=README.md")
curl --fail-with-body --silent --show-error \ if [ "$response_status" -lt 200 ] || [ "$response_status" -ge 300 ]; then
-X POST -H "Authorization: token $RELEASE_TOKEN" \ cat /tmp/linklog-readme-upload-response >&2
-H 'Content-Type: application/json' \ exit 1
--data-binary @webextension/updates.json \ fi
"$UPLOAD_URL?name=updates.json"
- name: Publish release links - name: Publish release links
env: env:
VERSION: ${{ steps.release.outputs.version }} BACKEND_VERSION: ${{ steps.release.outputs.backend_version }}
PLUGIN_VERSION: ${{ steps.release.outputs.plugin_version }}
SIGNED_XPI: ${{ steps.release.outputs.signed_xpi }}
run: | run: |
echo "Docker image: $IMAGE_NAME:$VERSION" echo "Docker image: $IMAGE_NAME:$BACKEND_VERSION"
echo "Signed XPI: https://git.kolkman.org/olaf/Link-Log/releases/download/v$VERSION/LinkLog-$VERSION.xpi" echo "Signed XPI: https://git.kolkman.org/olaf/Link-Log/raw/branch/main/$SIGNED_XPI (version $PLUGIN_VERSION)"
echo "Firefox update manifest: https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json" echo "Release README: README.md"
+9
View File
@@ -0,0 +1,9 @@
# Changelog
## Version v0.1.1
### Features
* Ability to add new logs through the web interface
### Modification
* Moved the style selection into the hamburger menu
* Toot formatting changed a wee bit
## Version v0.1.0 Initial release
+30 -7
View File
@@ -28,7 +28,7 @@ For local development:
The backend currently uses FastAPI, uvicorn, SQLite, and Pydantic. `httpx2` is included for the Starlette-compatible test client. The backend currently uses FastAPI, uvicorn, SQLite, and Pydantic. `httpx2` is included for the Starlette-compatible test client.
Jinja2 is included for server-rendered HTML templates. Jinja2 is included for server-rendered HTML templates.
The backend version is `0.1.0` and is exposed through the FastAPI/OpenAPI metadata. It can be overridden with `LINKLOG_VERSION`. The backend version is `0.1.1` and is exposed through the FastAPI/OpenAPI metadata. It can be overridden with `LINKLOG_VERSION`.
LinkLog is licensed under the GNU General Public License, version 3 or any later version. See [LICENSE](LICENSE). LinkLog is licensed under the GNU General Public License, version 3 or any later version. See [LICENSE](LICENSE).
## Local Installation ## Local Installation
@@ -69,6 +69,7 @@ Open these URLs:
- About: <http://localhost:8000/about> - About: <http://localhost:8000/about>
- Admin page: <http://localhost:8000/admin> - Admin page: <http://localhost:8000/admin>
- Web login: <http://localhost:8000/login> - Web login: <http://localhost:8000/login>
- Token refresh: `POST http://localhost:8000/api/auth/refresh`
- Health check: <http://localhost:8000/health> - Health check: <http://localhost:8000/health>
- OpenAPI documentation: <http://localhost:8000/docs> - OpenAPI documentation: <http://localhost:8000/docs>
@@ -109,11 +110,11 @@ This publishes `${APP_PORT:-8000}` and defaults the application URL to `http://l
## Releases ## 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`. Releases run in Gitea Actions when a `v*` tag is pushed. The Docker release version comes from `LINKLOG_VERSION`'s default in `backend/app/core/config.py`; the tag must match that backend version. The Firefox plugin version is independent and comes from the most recent signed `XPI/signed/LinkLog-<version>.xpi` checked into the repository.
The signed XPI is produced manually and must be checked into `XPI/signed/LinkLog-<version>.xpi` before creating the tag. The workflow validates the embedded manifest, publishes the XPI and `webextension/updates.json` as Gitea release assets, and publishes Docker images to `git.kolkman.org/olaf/link-log:<version>` and `:latest`. The signed XPI is produced manually and should be checked into `XPI/signed/LinkLog-<version>.xpi`. The workflow validates the latest signed XPI's embedded manifest, publishes Docker images to `git.kolkman.org/olaf/link-log:<backend-version>` and `:latest`, and creates a release README that describes the project, the current backend/container version, and the raw signed XPI download URL with the plugin version.
The extension's `update_url` points at the stable raw repository URL `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json`. Update `webextension/updates.json` with each signed XPI version and commit it together with the XPI. The release page provides a direct install link at `https://git.kolkman.org/olaf/Link-Log/releases/download/v<version>/LinkLog-<version>.xpi`. The extension's `update_url` points at the stable raw repository URL `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/webextension/updates.json`. Update `webextension/updates.json` with each signed XPI version and commit it together with the XPI. Release READMEs point to the raw signed XPI at `https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-<version>.xpi`.
The workflow requires Gitea Actions secrets named `REGISTRY_USERNAME`, `REGISTRY_TOKEN`, and `RELEASE_TOKEN`. `REGISTRY_TOKEN` is a Gitea access token with permission to push packages; `RELEASE_TOKEN` needs permission to create releases and upload release assets. The workflow requires Gitea Actions secrets named `REGISTRY_USERNAME`, `REGISTRY_TOKEN`, and `RELEASE_TOKEN`. `REGISTRY_TOKEN` is a Gitea access token with permission to push packages; `RELEASE_TOKEN` needs permission to create releases and upload release assets.
@@ -155,15 +156,16 @@ The manifest includes stable Firefox extension metadata and references the packa
1. Start the backend locally. 1. Start the backend locally.
2. Open Firefox and visit `about:debugging#/runtime/this-firefox`. 2. Open Firefox and visit `about:debugging#/runtime/this-firefox`.
3. Select **Load Temporary Add-on**. 3. Select **Load Temporary Add-on**.
4. Choose `webextension/manifest.json`. 4. Choose `webextension/manifest.json` (Firefox 142 or newer is required).
5. Open the LinkLog extension options and enter: 5. Open the LinkLog extension options and enter:
- Backend URL: the URL of your LinkLog server, such as `http://localhost:8000` - Backend URL: the URL of your LinkLog server, such as `http://localhost:8000`
- Username: `alice` - Email: `alice@example.com`
- Password: `secret123` - Password: `secret123`
- One-time password: enter it when OTP is enabled
6. Save the settings and login. 6. Save the settings and login.
7. Open a webpage, select the LinkLog toolbar button, review the title and URL, add a comment, and submit it. 7. Open a webpage, select the LinkLog toolbar button, review the title and URL, add a comment, and submit it.
When the extension settings page has a valid session, it shows `<username> logged in at <backend URL>` and a **Sign out** button instead of the login form. Signing out revokes the token and returns the form. When the extension settings page has a valid session, it shows `<username> logged in at <backend URL>` and a **Sign out** button instead of the login form. Access and refresh credentials are kept in Firefox session storage, so a browser restart requires login again. Signing out revokes the token family and returns the form.
Temporary extensions are removed when Firefox restarts. Reload the extension from `about:debugging` after changing its files. Temporary extensions are removed when Firefox restarts. Reload the extension from `about:debugging` after changing its files.
@@ -177,6 +179,8 @@ cp .env.example .env
Edit `.env` and replace `LINKLOG_SECRET_KEY` with a long random value. Docker Compose automatically reads `.env` from the repository root. The committed `.env.example` contains safe defaults and placeholders; the real `.env` is ignored by Git. Edit `.env` and replace `LINKLOG_SECRET_KEY` with a long random value. Docker Compose automatically reads `.env` from the repository root. The committed `.env.example` contains safe defaults and placeholders; the real `.env` is ignored by Git.
When `APP_ENV=production`, application startup fails closed unless `LINKLOG_SECRET_KEY` is a non-default high-entropy value of at least 32 characters and `LINKLOG_DATA_ENCRYPTION_KEY` is a valid Fernet key. Development mode may use local defaults, but production secrets should come from a protected secret mechanism.
The main configurable values are: The main configurable values are:
| Variable | Purpose | Default | | Variable | Purpose | Default |
@@ -261,6 +265,25 @@ curl -X POST http://localhost:8000/api/auth/login \\
-d '{"email":"alice@example.com","password":"secret123"}' -d '{"email":"alice@example.com","password":"secret123"}'
``` ```
The login response contains a 15-minute access token, a device-bound refresh token, its expiry time, and a `device_id`. Each successful refresh rotates the refresh token.
Refresh an access token:
```sh
curl -X POST http://localhost:8000/api/auth/refresh \\
-H 'Content-Type: application/json' \\
-d '{"refresh_token":"YOUR_REFRESH_TOKEN","device_id":"YOUR_DEVICE_ID"}'
```
Refresh-token reuse or a mismatched device ID returns `401` and revokes the token family. Signing out revokes the token family, while changing the password or completing a password reset revokes all sessions for the user.
Sign out with the access token in the bearer header:
```sh
curl -X POST http://localhost:8000/api/auth/logout \\
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```
Submit a link using the returned access token: Submit a link using the returned access token:
```sh ```sh
+92 -210
View File
@@ -2,282 +2,164 @@
**Assessment date:** 2026-08-26 **Assessment date:** 2026-08-26
**Scope:** Current LinkLog backend, web frontend, Firefox extension, SQLite persistence, SMTP and Mastodon integrations, Docker/Traefik deployment files, and automated tests. **Scope:** Current LinkLog backend, web frontend, Firefox extension, SQLite persistence, SMTP and Mastodon integrations, Docker/Traefik deployment files, and automated tests.
**Assessment type:** Source-code security review. This is not a penetration test, dependency vulnerability scan, formal threat model sign-off, or production configuration certification. **Assessment type:** Source-code review. This is not a penetration test, dependency scan, container scan, formal threat-model sign-off, or production configuration certification.
## Executive Summary ## Executive Summary
LinkLog has several good security foundations: authenticated API dependencies, administrator authorization checks, owner checks for link operations, token hashing in the database, email verification, password reset token hashing and single-use behavior, TOTP login enforcement, last-administrator protection, parameterized SQLite queries, upload size limits, and non-root application execution in the container. The current worktree contains strong security improvements: salted scrypt password hashing with legacy upgrade support, bearer-header authentication, hashed and expiring tokens, refresh-token rotation with device binding and family revocation, OTP recovery codes, encrypted newly written secrets, Mastodon SSRF controls, image decoding and re-encoding, reduced extension permissions, proxy-only production Compose, and append-only audit events.
The current implementation is not ready to expose directly to the public Internet without additional hardening. The most important issues are: The following issues remain before an Internet-facing production release:
1. Passwords were previously stored as unsalted, fast SHA-256 hashes; this issue has now been addressed in the current worktree with salted scrypt hashes and legacy upgrade support. 1. Logout still accepts a bearer token in a JSON body rather than using the standard `Authorization` header.
2. Access tokens are accepted in query strings by session endpoints, which can leak through logs, browser history, proxies, and referrers. 2. SMTP, Mastodon, setup, and some user-service errors return raw exception details to clients.
3. SMTP credentials, Mastodon credentials, OAuth client secrets, and TOTP secrets are stored in plaintext in SQLite. 3. First-run setup is intentionally unauthenticated and lacks a bootstrap secret and application-level request-size controls.
4. Mastodon instance URLs are user-controlled and the backend makes outbound requests to them, creating an SSRF and egress-control concern. 4. Audit event details are serialized without defensive sanitization or size limits at the audit-service boundary.
5. Login has no effective rate limiting or account lockout. 5. The development secret fallback is not rejected at application startup in production.
6. The Firefox extension stores bearer tokens in browser local storage and requests broad website access. 6. Rate limiting is single-instance SQLite state, is not atomic under concurrency, and reset-mail issuance is not independently throttled.
7. The Compose setup still exposes the application port directly and relies on deployment-specific Traefik networking and labels. 7. Runtime verification, security headers, centralized audit export, retention, alerting, and dependency/container/security scanning remain incomplete.
These findings are prioritized below. Severity describes the potential security impact in a typical Internet-facing deployment, not the likelihood in every environment. The application should remain behind the production reverse proxy, with real DNS/TLS, protected secrets, and restricted network access until these items are addressed.
## Positive Controls Already Present ## Verified Controls
- Bearer authentication is centralized in `backend/app/api/dependencies.py`. - Passwords use salted scrypt hashes; valid legacy SHA-256 hashes are upgraded on login.
- Administrator routes use `require_admin`; standard users receive `403`. - Bearer authentication is centralized through `get_current_user` and `require_admin`.
- Link update, delete, and Mastodon-post operations verify ownership. - Query-string authentication is not accepted by protected session endpoints.
- Tokens are generated with UUID material, stored as SHA-256 hashes, expire, and can be revoked. - Access tokens are short-lived by default; refresh tokens are hashed, separately expiring, device-bound, rotated, and family-revoked on reuse.
- Password-reset tokens are random, hashed, expiring, single-use, and revoke existing sessions after reset. - Logout, password changes, and password resets revoke session material according to the token lifecycle.
- New administrator-created users require email verification before login. - OTP enrollment provides ten one-time recovery codes; only hashes are stored.
- OTP uses time-based verification with a one-step clock window and is required before token issuance when enabled. - Users can recover OTP with password plus a recovery code, and administrators can disable OTP for another user.
- The profile API does not return `password_hash` or `otp_secret` after the profile response hardening. - Newly written SMTP, Mastodon, OAuth, and OTP secrets are encrypted with an external Fernet key.
- User privilege changes protect against removing the last administrator and prevent an administrator from changing their own privilege. - Mastodon instances are restricted to HTTPS public hostnames, unsafe resolved addresses are rejected, and redirects are blocked.
- Uploaded avatars have a 2 MB limit, a restricted MIME allow-list, user-scoped filenames, and a persistent data location. - Avatar uploads are size-limited, decoded with Pillow, pixel-limited, fully loaded, and re-encoded as server-generated PNG.
- SQLite foreign keys are enabled and ownership predicates are used for destructive link operations. - Production Compose does not publish the application port and uses the external Traefik network; local direct access is separate.
- SQL statements use parameters rather than interpolated user values. - The Firefox extension uses `activeTab`, session-scoped credentials, exact configured backend permissions, and a self-only extension-page CSP.
- The Docker image runs the application as UID 10001 after startup and defines a health check. - SQLite queries are parameterized and foreign-key enforcement is enabled.
- `.env` and database/runtime files are ignored by Git. - An append-only `security_audit_events` table records actor, action, target, outcome, and details for major administrative and destructive operations.
- The XPI build validates archive integrity, required files, and manifest parity. - The current automated backend suite passes 49 tests.
- Browser rendering generally uses `textContent` for feed data, reducing DOM-based injection risk.
## Findings ## Findings
### SA-001: Unsalted fast SHA-256 password hashing ### SA-001: Logout uses non-standard token transport
**Severity:** Critical, remediated in current worktree
**Evidence before remediation:** `backend/app/database.py` and `backend/app/services/auth_service.py` used unsalted SHA-256 password comparisons.
**Current state:** `backend/app/database.py` now creates salted scrypt hashes in the format `scrypt$N$r$p$salt$digest`. `verify_password()` uses the encoded parameters and constant-time comparison. `authenticate_user()` fetches by username, verifies in Python, and transparently replaces a valid legacy 64-character SHA-256 hash with a new scrypt hash.
**Residual impact:** Existing accounts remain exposed until they successfully authenticate once after deployment. An attacker with a copy of an old database may still attack legacy hashes. Existing credentials should be rotated if the old database may have been exposed.
**Recommendation:** Deploy the current migration, require password rotation for accounts that cannot log in during migration, and monitor for remaining legacy hashes. Review scrypt cost parameters periodically and increase them as hardware changes. Do not revert to a fast general-purpose hash.
**Priority:** Completed in code; operational migration and credential rotation remain.
### SA-002: Bearer tokens accepted in query strings
**Severity:** High, remediated in current worktree **Severity:** High, remediated in current worktree
**Evidence before remediation:** `backend/app/api/auth.py` exposed `GET /api/auth/me?token=...`, and web/extension callers used the query form. **Evidence before remediation:** `POST /api/auth/logout` accepted `{"token": ...}` in the JSON request body, and the web frontend sent the access token this way.
**Current state:** `/api/auth/me` now requires the existing bearer-header dependency. The shared web header, admin session check, Firefox settings page, and tests send `Authorization: Bearer <token>`. A query-string token is rejected with `401`. **Impact:** Request bodies may be captured by debugging middleware, application logs, or monitoring systems. The endpoint also diverges from the bearer-header contract used elsewhere, increasing the chance of inconsistent token handling.
**Residual impact:** Tokens from old URLs may remain in proxy/browser logs and should be treated as exposed until revoked or rotated.
**Recommendation:** Rotate existing access tokens after deployment and scrub historical query parameters from logs where possible. Keep the bearer header as the only credential transport. **Current state:** Logout requires `Authorization: Bearer <access-token>`, rejects body-only tokens with `401`, and revokes the token family server-side. The web frontend and Firefox extension send the header; regression coverage verifies access and refresh tokens are invalid after logout.
**Priority:** Completed in code; token rotation and log hygiene remain. **Recommendation:** Keep logout header-only, retain family revocation, avoid logging authorization headers, and rotate legacy sessions issued before this change.
### SA-003: Sensitive secrets stored in plaintext SQLite **Priority:** Completed in code; legacy session rotation and log hygiene remain.
**Severity:** High, remediated in current worktree for newly written secrets ### SA-002: Raw infrastructure errors are returned to clients
**Evidence:** `backend/app/services/email_service.py` stores SMTP settings including `smtp_password` in `app_settings`; `backend/app/services/mastodon_oauth.py` stores Mastodon application secrets and user access tokens in `app_settings` and `user_plugin_config`; `backend/app/api/user_config.py` stores `otp_secret` in the `users` table. New writes are encrypted, but legacy plaintext rows require rotation.
**Impact:** Read access to the database exposes SMTP credentials, Mastodon posting authority, OAuth client secrets, and TOTP seeds. TOTP seeds cannot be changed by a user who loses the database copy. Database backups therefore contain reusable credentials, not just application data.
**Current state:** Newly stored SMTP passwords, Mastodon OAuth client secrets and access tokens, and TOTP seeds are encrypted with Fernet using `LINKLOG_DATA_ENCRYPTION_KEY`. The key is required in Docker and is not stored in SQLite. The user plugin API no longer returns the Mastodon access token.
**Residual impact:** Existing plaintext secrets require a controlled read-and-save rotation after the key is configured. Lost encryption keys make stored secrets unrecoverable.
**Recommendation:** Supply `LINKLOG_DATA_ENCRYPTION_KEY` through a protected secret mechanism, encrypt backups, rotate credentials after suspected disclosure, and migrate existing plaintext values. Continue omitting secrets from API responses.
**Priority:** Completed for new writes; existing secret migration and key management remain.
### SA-004: User-controlled Mastodon instance creates SSRF and uncontrolled egress risk
**Severity:** High, remediated in current worktree **Severity:** High, remediated in current worktree
**Evidence before remediation:** Mastodon instance values were passed to outbound `urlopen()` calls with no DNS/IP-range or redirect controls. **Evidence before remediation:** SMTP and Mastodon routes interpolated exception text into `503`/`502` responses. Setup and email-address routes also exposed mail-delivery exception text.
**Current state:** `mastodon_security.py` requires hostname-only HTTPS URLs, resolves DNS, rejects loopback, link-local, private, multicast, unspecified, reserved, and IPv4-mapped IPv6 addresses, and uses an opener that refuses redirects. OAuth, posting, and deletion all use these controls. **Impact:** Error responses can disclose SMTP hostnames, ports, TLS/library details, upstream response bodies, internal network information, or sensitive URL fragments.
**Residual impact:** DNS and network policy can change after validation; production deployments should still use egress firewalling or a restricted outbound proxy.
**Recommendation:** Keep outbound firewalling or an allow-listed proxy in production, monitor DNS rebinding risk, and maintain response-size/time limits. **Current state:** The application assigns a request ID at middleware entry, returns it in `X-Request-ID`, logs technical exception summaries server-side after redacting authorization values, tokens, passwords, secrets, OTP/code values, and secret-bearing URL query values, and returns stable public messages with a reference ID. SMTP setup/admin/email errors and Mastodon registration/callback errors no longer expose raw exception text. Regression tests verify representative exception and secret text is absent from HTTP responses.
**Priority:** Completed in code; network-level egress controls remain. **Residual impact:** Logging currently uses the application logger rather than a centralized protected sink. Request-ID trust, log retention, access control, and structured redaction should be reviewed in deployment.
### SA-005: Login endpoint lacks rate limiting and lockout **Recommendation:** Keep public errors stable and reference-based, export redacted logs to a protected centralized system, define retention and access controls, and never log authorization headers or secret-bearing request data.
**Severity:** High, remediated in current worktree **Priority:** Completed in code; centralized logging and operational controls remain.
**Evidence before remediation:** `POST /api/auth/login` had no IP, email, or account rate limit, and OTP failures were not throttled separately.
**Current state:** Login failures are tracked in SQLite by a SHA-256 key derived from client IP and normalized email. Five failures within 15 minutes cause a two-minute lockout; the endpoint returns `429` with `Retry-After`, and successful password plus OTP authentication clears the counter. Password-reset mail remains generic and should still be rate-limited operationally.
**Recommendation:** Use a distributed limiter for multi-instance deployments, add monitoring, and rate-limit password-reset issuance independently. Keep responses generic to avoid account enumeration. ### SA-003: First-run setup is unauthenticated and lacks application-level body limits
**Priority:** Completed for the single-instance SQLite deployment; distributed limiting and reset-mail controls remain. **Severity:** Medium/High for exposed fresh deployments
**Evidence:** `/api/setup/configuration`, `/api/setup/test-mail`, `/api/setup/complete`, and `/api/setup/status` are available before an administrator exists. No global request-size middleware or bootstrap secret is enforced in the application.
### SA-006: Firefox extension has broad host access and stores bearer tokens in local storage **Impact:** Anyone who can reach a fresh instance can overwrite pending setup values, attempt SMTP delivery, consume test-mail quota, and submit oversized request bodies. The setup design is necessary for provisioning but is unsafe when directly exposed.
**Severity:** High, remediated in current worktree **Recommendation:** Require a one-time bootstrap secret supplied through the environment or console, or restrict setup to localhost/private management networking. Add bounded request models and a global body-size limit. Keep strict setup/test-mail throttling, audit setup actions, expire pending setup data, and disable setup routes after provisioning.
**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.
**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 for Internet-facing fresh installations.
**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. ### SA-004: Audit details are not sanitized at the audit-service boundary
**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, 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.
**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.
**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
**Severity:** Medium **Severity:** Medium
**Evidence:** `backend/app/api/setup.py` exposes configuration, test-mail, status, and completion routes without a bearer dependency while no administrator exists. **Evidence:** `record_audit_event()` serializes caller-supplied `details` directly to SQLite. Current callers generally avoid secrets, but the service does not enforce that contract or bound nested values and event size.
**Impact:** This is necessary for first-run provisioning, but an exposed fresh instance allows anyone who can reach it to attempt setup, modify pending configuration, trigger test mail, and consume the five-send testing quota. The setup pending data includes a password hash and SMTP password in the database.
**Recommendation:** Restrict first-run setup at the network layer until an operator has completed provisioning, or require a one-time bootstrap secret supplied through the environment/console. Bind setup to localhost or a private management interface where possible. Add CSRF protection if setup ever uses cookies, strict request throttling, audit logging, and an explicit setup expiration/cleanup mechanism. Disable setup routes permanently once configuration completes. **Impact:** A future caller could persist passwords, tokens, OTP codes, SMTP credentials, sensitive URLs, or oversized data in the audit database. Audit records are durable and are not a suitable place for arbitrary request payloads.
**Priority:** Medium, high for exposed fresh deployments. **Recommendation:** Use an allow-list of permitted detail fields per action, or recursively redact sensitive key names and URL query values. Bound string lengths and serialized event size. Add direct service tests with nested `password`, `token`, `secret`, and URL values and assert that they are redacted or rejected.
### SA-009: TOTP enrollment has no recovery codes or reset workflow **Priority:** Medium.
### SA-005: Production secret fallback is not fail-closed
**Severity:** Medium, remediated in current worktree **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. **Evidence before remediation:** `Settings.secret_key` defaulted to `dev-secret-key-change-me`, and `LINKLOG_DATA_ENCRYPTION_KEY` was validated when encryption was used rather than fully validated during startup.
**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.
**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. **Impact:** A deployment that omits required configuration can start with a known development secret or fail only when a protected feature is exercised. This creates dangerous configuration drift and complicates incident response.
**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. **Current state:** `validate_configuration()` runs before FastAPI app construction. In production it rejects a missing or known development `LINKLOG_SECRET_KEY`, application secrets shorter than 32 characters or with insufficient character diversity, and missing `LINKLOG_DATA_ENCRYPTION_KEY`. Any supplied encryption key is checked as a valid Fernet key. Focused tests cover rejection and acceptance paths.
**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. **Residual impact:** Secret strength checks are pragmatic length/diversity checks rather than a full entropy estimator. Secret provisioning, rotation, and protected storage remain operational requirements.
**Priority:** Completed in code; operational recovery and audit logging remain. **Recommendation:** Keep production startup fail-closed, provision secrets through a protected secret manager, rotate them after suspected disclosure, and consider a stronger entropy policy if deployment requirements warrant it.
### SA-010: Avatar validation trusts the client MIME type **Priority:** Completed in code; secret provisioning and rotation remain.
**Severity:** Medium, remediated in current worktree ### SA-006: Login and reset-mail throttling are not distributed or atomic
**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.
**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`. **Severity:** Medium/High in multi-instance deployments
**Evidence:** Login failure state is stored in SQLite and keyed by a client-IP/email hash. The check and increment occur as separate operations. Failed login handling can also issue a password-reset email for a known verified account without an independent reset-mail cooldown.
**Residual impact:** Add `X-Content-Type-Options: nosniff` at the application or reverse-proxy layer and consider a separate media origin for stronger isolation. **Impact:** Concurrent attempts can overwrite counters, multiple application instances do not share reliable rate state, and reset-mail issuance can be abused to spam a user or consume SMTP resources.
**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. **Recommendation:** Use an atomic shared limiter such as Redis for multi-instance deployments, with both account and IP buckets. Add an independent per-account/IP reset-mail cooldown and monitoring. Treat trusted proxy headers explicitly when deriving client IPs. Add concurrency, proxy, OTP-failure, and reset-mail abuse tests.
**Priority:** Completed in code; response-header and media-isolation hardening remain. **Priority:** Medium/High for scaled or public deployments.
### SA-011: Error details can disclose infrastructure information ### SA-007: Security headers and global request policy are incomplete
**Severity:** Medium **Severity:** Medium
**Evidence:** Admin SMTP routes return exception text in `503` responses; Mastodon errors include upstream response bodies; the frontend displays these values to the user. **Evidence:** The application does not consistently install or test CSP, HSTS, `X-Content-Type-Options`, frame protections, `Referrer-Policy`, trusted hosts, or a global request-size limit. The extension CSP does not cover the web application.
**Impact:** Connection errors can disclose hostnames, ports, TLS details, library messages, upstream response bodies, or internal service information. The behavior is useful for administrators but may expose more detail than intended if an admin session is compromised or error responses are logged.
**Recommendation:** Log full technical details server-side with correlation IDs. Return a stable user-facing message plus a short reference ID. Allow detailed diagnostics only behind an explicit protected troubleshooting mode. Redact credentials, authorization headers, URLs containing secrets, and SMTP/Mastodon response fields before logging or returning them. **Impact:** Browser defense-in-depth and resource exhaustion protections depend on external proxy configuration. A proxy configuration mistake can leave HTML, API, or media responses weaker than intended.
**Recommendation:** Add a documented application or guaranteed-proxy policy and test headers on HTML, API, and media responses. Use `TrustedHostMiddleware` with explicit production hosts, `nosniff`, restrictive framing/referrer rules, HSTS only on HTTPS, and bounded request bodies.
**Priority:** Medium. **Priority:** Medium.
### SA-012: Token lifecycle has unused refresh-token semantics ### SA-008: Audit operations lack request correlation, retention, export, and alerting
**Severity:** Medium **Severity:** Medium
**Evidence:** `issue_token()` returns a `refresh_token` value, but only the access token is inserted into `tokens`; no refresh endpoint or refresh-token hash is implemented. **Evidence:** Audit events contain actor/action/target/outcome/details/time but no request ID, source context, retention policy, protected export, or alerting pipeline.
**Impact:** Clients may assume the refresh token provides renewal or may store a value that cannot be revoked or used. This complicates session reasoning and can lead to unsafe client fallbacks. Access tokens currently live for the configured default of 30 days.
**Recommendation:** Either remove `refresh_token` from the API contract or implement a real refresh-token lifecycle: hash and persist refresh tokens, rotate them on use, detect reuse, bind them to a session/device, expire them separately, and revoke the token family on logout or password change. Reduce access-token lifetime after a real refresh flow is available. **Impact:** Operators can inspect database events but cannot reliably correlate them with request logs, detect attacks promptly, or guarantee retention and tamper-resistant access controls.
**Recommendation:** Add request IDs at middleware entry, export redacted events to protected logs or a security monitoring system, define retention and access controls, and alert on privilege changes, OTP resets, password resets, credential changes, refresh-token reuse, and destructive actions.
**Priority:** Medium. **Priority:** Medium.
### SA-013: No explicit security headers, CORS policy, or request-size policy ### SA-009: Dependency, container, secret, and runtime security verification is incomplete
**Severity:** Medium **Severity:** Medium
**Evidence:** `backend/app/main.py` does not install security-header or CORS middleware, and the application routes do not define a global request-size limit. **Evidence:** The repository runs functional tests and static syntax checks, but no dependency vulnerability scan, container scan, secret scan, authenticated dynamic test, or live Firefox extension workflow is part of the verified release path.
**Impact:** Deployment behavior depends entirely on the reverse proxy. Missing `Content-Security-Policy`, `Strict-Transport-Security`, `X-Content-Type-Options`, `Referrer-Policy`, and frame protections weakens browser-side defenses. An overly permissive future CORS configuration could expose bearer-authenticated APIs. Large request bodies may consume resources even where individual avatar limits exist.
**Recommendation:** Add a documented restrictive security-header policy at the application or guaranteed proxy layer. Use `TrustedHostMiddleware` with an explicit production host list. Do not enable broad CORS; if cross-origin extension access requires it, allow only configured origins. Add global request and upload limits at the proxy and application layers. **Impact:** Known vulnerable dependencies, image issues, accidental secret commits, proxy misconfiguration, and browser-runtime permission failures can reach release despite passing unit tests.
**Priority:** Medium. **Recommendation:** Add CI jobs for Python dependency and license policy, container scanning, secret scanning, Compose rendering, authenticated dynamic API checks, and a Firefox smoke test covering permission grant, login, refresh, logout, and active-tab capture.
### SA-014: Development fallback secret is unsafe if the app is run without Compose configuration **Priority:** Medium before public release.
**Severity:** Medium ## Residual Operational Requirements
**Evidence:** `Settings.secret_key` in `backend/app/core/config.py` defaults to `dev-secret-key-change-me`.
**Impact:** Local or incorrectly configured deployments can share a known secret. Even if the current token implementation does not use this value for signing, the setting creates a dangerous security assumption and may be used by future features.
**Recommendation:** Fail closed when `APP_ENV=production` and the secret is absent or matches a known development value. Generate secrets during provisioning, validate minimum length and entropy, and never ship a production fallback. Make all cryptographic uses explicit and test them. - Replace documentation hostnames with real DNS names and enforce HTTPS/TLS.
- Keep production Compose proxy-only and verify the actual Traefik network and middleware in deployment.
**Priority:** Medium. - Rotate legacy plaintext secrets and previously issued sessions after upgrades.
- Protect and encrypt database/avatar backups; test restoration and token/session revocation.
### SA-015: Some destructive and administrative operations lack audit logging - Monitor failed logins, reset-mail volume, refresh-token reuse, OTP recovery, privilege changes, and destructive actions.
- Review the Firefox extension against Mozilla Add-ons policy before signing.
**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.
**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.
**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
- **Authentication transport:** Bearer headers are used by most APIs, but query-string tokens remain a leakage risk. There is no cookie session, which reduces CSRF exposure for current bearer-only API calls. Credentials are now email-based; usernames remain presentation identities.
- **Email authentication:** Primary and additional addresses are checked independently; additional addresses are unusable for login until their verification token is consumed. The profile exposes status but not verification secrets.
- **Primary email selection:** Only an already verified alternative address can be promoted to primary. The same user row retains account permissions and active sessions, and the previous primary is retained as a verified alternative.
- **Password policy:** New and reset passwords require at least eight characters. This is better than no policy but should be replaced with a longer passphrase-oriented policy and breached-password screening after a proper password hash migration.
- **Email verification:** New administrator-created users cannot log in until verified. The setup-created first administrator is marked verified, which is appropriate for bootstrap but should be protected by the setup controls above.
- **Password reset:** Tokens are random, hashed, expiring, single-use, and revoke existing access tokens after reset. Reset-email generation errors are intentionally swallowed to preserve generic login behavior, but this should be paired with server-side monitoring.
- **OTP:** Login enforcement is present and OTP setup requires confirmation. Recovery codes, secret rotation, reauthentication, and encrypted secret storage are missing.
- **Authorization:** Admin checks and link ownership checks are present. The last-administrator invariant is enforced for privilege changes and deletion. Add authorization tests for every new destructive endpoint as the API grows.
## Data Protection Review
- SQLite is the primary data store and contains profile data, links, password hashes, tokens, SMTP settings, Mastodon credentials, OAuth state, and OTP secrets. New sensitive values are encrypted with the externally supplied Fernet key; existing plaintext values must be rotated.
- Database backups must be treated as credential-bearing secrets, encrypted, access-controlled, rotated, and tested for secure deletion.
- Avatar files are persistent and publicly served. Validate and re-encode image content before accepting production uploads.
- Link URLs and comments are intentionally public feed data. Operators should document that users must not submit secrets in URLs or comments.
- SMTP and Mastodon integration errors should be redacted before entering logs or API responses.
## Frontend and Extension Review
- Feed content is generally assigned with `textContent`, which is a good XSS defense.
- User-supplied profile values rendered by Jinja should remain autoescaped; do not mark them safe without a narrowly reviewed reason.
- The web API currently uses bearer headers, so browser CSRF risk is lower than with cookie sessions. Keep it that way unless a CSRF token design is added.
- Browser local storage is exposed to any script running in the same origin. Keep third-party scripts out of authenticated pages and add a restrictive CSP.
- The extension's `<all_urls>` host permission should be reduced if the active-tab workflow is sufficient. Review Mozilla Add-ons policies before publishing signed releases.
- The extension stores access and refresh-token-like values in `browser.storage.local`; implement actual refresh semantics or stop storing/returning unused refresh values.
- Extension error messages should not include tokens or full sensitive URLs.
## Deployment Checklist
Before production exposure:
- [ ] Replace SHA-256 password hashing with Argon2id, scrypt, or bcrypt and migrate existing accounts.
- [ ] Remove query-string token authentication and rotate existing access tokens.
- [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.
- [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.
- [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.
- [x] Add security audit events and centralized redacted logging.
- [ ] Rotate all credentials and set a unique high-entropy production secret.
- [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.
## Suggested Priority Order
1. Password hashing migration.
2. Query-token removal and token rotation.
3. Secret-at-rest protection and backup controls.
4. Login/setup/OTP rate limiting.
5. Production network egress controls for Mastodon.
6. Production network and TLS hardening.
7. Extension permission and credential-storage review.
8. Security headers, trusted hosts, request limits, media validation, recovery codes, and audit logging.
## Verification Performed ## Verification Performed
The repository's automated backend suite was run during this review and passed with 29 tests before the password-storage change; focused password/authentication tests subsequently passed after the remediation. Static Python and JavaScript checks were also used during feature development. These results demonstrate regression coverage, not absence of the findings above. A production release should additionally run a dependency scanner, container scanner, secret scanner, and authenticated dynamic security test. - `PYTHONPATH=. pytest -q`: **49 passed** at the start of this audit.
- Static source review of backend APIs/services, frontend assets, extension manifest/scripts, Compose files, configuration, and tests.
- Targeted searches for authentication, token, secret, upload, outbound-request, error, and audit-log paths.
Functional tests demonstrate regression coverage only; they do not certify production security.
+162
View File
@@ -1,5 +1,77 @@
# Chat Log # Chat Log
### User
The release server fails because its curl does not support `--fail-with-body`.
### Assistant outcome
Replaced all three `--fail-with-body` uses in the release workflow with portable curl response capture and explicit HTTP status checks. Failed API and asset-upload responses now print their response body before exiting, while older curl versions remain supported.
### User
When posting to Mastodon change the formatting so there is an empty line between “From my #LinkLog:” and the title.
### Assistant outcome
Updated the Mastodon formatter so the prefix and title are separate paragraphs: `From my #LinkLog:` followed by a blank line and then the title. Existing comment, source URL, and tag paragraph formatting remains unchanged.
### User
Check the modified pages for the correct link because a version number was added to the signed XPI.
### Assistant outcome
Verified that the signed artifact is `XPI/signed/LinkLog-0.1.0.xpi` and that the About page, Profile page, `webextension/updates.json`, README, and related regression test all reference the matching versioned filename. No changes were required.
### User
In the Profile page below the Save profile button add “If you have not downloaded the plugin yet find it here” with a link to the signed plugin.
### Assistant outcome
Added the plugin download prompt immediately below the Save profile button, linking “find it here” to the signed `LinkLog-0.1.0.xpi` artifact. Added profile-page regression assertions and recorded the change in VIBE.
### User
Add a Plugin section to the About page with a download link to the signed XPI file.
### Assistant outcome
Added a Plugin section to the About page with a download link for the signed `LinkLog-0.1.0.xpi` artifact hosted on the repository's raw main branch. Added a page-rendering regression assertion.
### User
The Firefox plugin tests report that `strict_min_version` 112 is too low for `data_collection_permissions`, `storage.session`, and `permissions.request`.
### Assistant outcome
Raised the extension minimum Firefox version to 142.0, covering the reported desktop and Android manifest/API compatibility warnings. Updated the README to require Firefox 142 or newer.
### User
Implement SA-005: during startup reject missing or known development `LINKLOG_SECRET_KEY` in production, validate minimum length and entropy, require and validate the encryption key, and add fail-closed configuration tests.
### Assistant outcome
Added startup configuration validation before FastAPI app construction. Production now rejects missing/default/weak application secrets and missing or invalid Fernet encryption keys, while development defaults remain available. Added configuration tests for rejection and valid production settings, and updated SA-005 documentation.
### User
For SA-002, log technical details server-side with a request/correlation ID, return a stable public message with a short reference ID, redact secrets, and test that exception text is absent from responses.
### Assistant outcome
Added request-ID middleware and stable public error references. SMTP, setup, email-verification, and Mastodon exception paths now log redacted technical summaries server-side without exposing raw exception text, credentials, authorization values, reset tokens, OTP data, or secret-bearing URL values. Added regression coverage and updated SA-002 documentation.
### User
Remedy SA-001: Logout uses non-standard token transport.
### Assistant outcome
Migrated logout to require `Authorization: Bearer <access-token>`, updated the web frontend and Firefox extension, and added regression coverage proving body-only logout is rejected while header logout revokes the access token and refresh-token family. Updated SA-001, the checklist, and README examples.
### User
Perform a new security audit overwriting Security-audit.md with new and remaining issues.
### Assistant outcome
Replaced the historical audit with a fresh current-state review dated 2026-08-26. The new report records verified controls and nine remaining findings: logout token transport, raw infrastructure errors, unauthenticated setup exposure, audit-detail sanitization, production secret fallback, non-distributed rate limiting, incomplete security headers/request policy, missing audit operations, and incomplete dependency/container/secret/runtime verification. The baseline backend suite passed 49 tests.
### User
Update SA-012 to reflect the actual implementation, document device binding, rotation, reuse detection, family revocation, logout and password-reset revocation, update the checklist and README API examples, and add the refresh endpoint to the documented API surface.
### Assistant outcome
Reconciled SA-012 and the authentication documentation with the implemented 15-minute access tokens and 30-day device-bound refresh tokens. Documented hashing, rotation, reuse-triggered family revocation, logout and password-reset revocation, added the refresh endpoint and curl example to the README, corrected extension login instructions, and checked off the refresh-token implementation item.
### User
Replace `LINKLOG_TOKEN_EXPIRY_DAYS` with `LINKLOG_TOKEN_EXPIRY_MINUTES`, add `LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS` to the production Compose environment, and add a CI test comparing Compose variables with Settings.
### Assistant outcome
Updated production Compose to pass the configured 15-minute access-token and 30-day refresh-token settings. Added a repository test that compares `LINKLOG_*` Compose keys with the environment keys declared by `Settings` and rejects the obsolete days-based access-token variable.
### User ### User
Reduce the size of the font of the greeting somewhat. Reduce the size of the font of the greeting somewhat.
@@ -48,6 +120,24 @@ Fix SA-015: Some destructive and administrative operations lack audit logging.
### Assistant outcome ### 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. 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
The plugin finds a different title than the new-entry page, see e.g. https://docs.gitea.com/administration/config-cheat-sheet/
### Assistant outcome
Improved the scraper's title extraction to prioritize the page `<title>` tag (matching browser and plugin behavior) over meta tags, and to check for Open Graph, Twitter, and generic meta tags as fallbacks. Tested with Gitea documentation.
### User
The plugin and the new entry page are still inconsistent.
### Assistant outcome
Identified that the HTML response was gzip-compressed and `iter_raw()` was returning compressed bytes instead of decompressed HTML. Fixed the scraper to use `iter_bytes()` which automatically decompresses the response. Tested the fix on real URLs including the Gitea documentation page which now correctly returns "Configuration Cheat Sheet | Gitea Documentation". All 54 backend tests pass.
### User
For https://docs.gitea.com/administration/config-cheat-sheet/ I want the title to be Configuration Cheat Sheet | Gitea Documentation
### Assistant outcome
Verified that the fixed scraper now correctly extracts "Configuration Cheat Sheet | Gitea Documentation" from the Gitea documentation page, matching the browser and plugin behavior. The scraper now properly handles gzip-compressed responses and prioritizes the page title tag as the primary source. All tests pass and the new-entry page and plugin are now consistent.
### User ### User
Solve SA-010: Avatar validation trusts the client MIME type. Solve SA-010: Avatar validation trusts the client MIME type.
@@ -1112,3 +1202,75 @@ Continue to document every prompt and chat in the VIBE directory.
### Assistant outcome ### Assistant outcome
Recorded this prompt and its outcome in `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`. Future visible prompts and chat outcomes will continue to be appended there. Recorded this prompt and its outcome in `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md`. Future visible prompts and chat outcomes will continue to be appended there.
### User
Maintain actions in the logs if VIBE.
### Assistant outcome
Confirmed understanding to continue recording all interactions in the VIBE logs according to the established append-only protocol. Updated PROMPTS.md and CHAT_LOG.md with this dated entry.
### User
Create a new page that can be reached by a button 'new entry' that only shows for authenticated users. The page, also only available to authenticated users allows users to enter a URL. When the URL is entered then the backend will scrape the title and allow to fill in all fields that are also available in the plugin.
### Assistant outcome
Implemented a complete new-entry feature for authenticated users: added `scraper_service.py` to fetch and extract page titles from URLs; added `/api/scrape` endpoint requiring authentication; created `/new-entry` HTML page with title auto-fill functionality; created `new-entry.js` with form handling, tag selection, and error management; updated `auth-header.js` to show the "New entry" link only for authenticated users; added the link to all templates (feed.html, about.html, admin.html, labels.html, user_profile.html, login.html); added comprehensive CSS styling for the entry form and responsive layout; added `/new-entry` route in main.py requiring authentication. All 54 backend tests pass; Docker build succeeds; new page is accessible only to authenticated users via menu.
### User
The plugin finds a different title than the new-entry page, see e.g. https://docs.gitea.com/administration/config-cheat-sheet/
### Assistant outcome
Improved the scraper to check multiple title sources and extract the most relevant one, prioritizing `<title>` tag content when available. Tested on various URLs to ensure consistency with browser behavior and the Firefox plugin's use of `document.title`.
### User
The plugin and the new entry page are still inconsistent.
### Assistant outcome
Identified that the plugin uses browser `document.title` (the `<title>` tag), not meta tags. Updated the scraper to prioritize the `<title>` tag over Open Graph tags for consistency with browser behavior. All tests pass.
### User
For https://docs.gitea.com/administration/config-cheat-sheet/ I want the title to be Configuration Cheat Sheet | Gitea Documentation
### Assistant outcome
Fixed the scraper_service.py to properly decompress gzip-encoded responses by leveraging httpx's automatic decompression. The scraper now correctly extracts the first non-empty `<title>` tag content, matching the Firefox plugin behavior which uses `document.title`. Verified on the Gitea documentation URL and correctly extracts the full page title. All 54 backend tests pass.
### User
After an entry is saved move to the /<user>/ page
### Assistant outcome
Updated new-entry.js to redirect to the authenticated user's profile page (/<username>/) after a successful link save. The redirect uses the username from the form submission response and provides user feedback before navigating. All 54 backend tests pass.
### User
Don't put new entry in the hamburger menu but present it as a separate button next to the style selector
### Assistant outcome
Moved the new-entry button to the header toolbar area outside the hamburger menu, positioning it as a standalone button. Updated all templates (feed.html, about.html, admin.html, labels.html, user_profile.html, login.html, new-entry.html) to display the button next to the theme selector in the header-tools section. Added corresponding CSS styling. All 54 tests pass.
### User
Put the new entry button left of the hamburger menu
### Assistant outcome
Restructured all template headers to position the new-entry button inside the header-actions container, left of the menu-toggle button. Updated feed.html, about.html, admin.html, labels.html, user_profile.html, login.html, and new-entry.html. The button now appears in visual order: new-entry button, then hamburger menu toggle, with proper flexbox alignment and 8px spacing. All 54 backend tests pass.
### User
The style selection should move into the hamburger menu - but in such a way that it becomes a submenu so that it doesn't clutter the menu structure
### Assistant outcome
Moved the theme selector into the hamburger menu as a collapsible submenu. Added theme-submenu-container with a submenu-title button and submenu-options to all templates (feed.html, about.html, admin.html, labels.html, user_profile.html, login.html, new-entry.html). Updated theme.js to populate the submenu with theme buttons instead of adding a picker to header-actions. Updated auth-header.js to handle submenu toggle with aria-expanded for accessibility. Added comprehensive CSS styling for .theme-submenu-container, .submenu-title, .submenu-options, and .theme-option (including .active state). Theme selection now works cleanly within the menu without cluttering the header. All 54 backend tests pass.
### User
The release action should work differently. Rather than publishing the signed XPI and `updates.json`, it should produce a README describing the project, the latest Docker container version, and the latest signed XPI download URL with version number.
### Assistant outcome
Changed the Gitea release workflow to generate `release-readme.md`, use it as the release body, and upload `README.md` as the release asset instead of publishing the signed XPI and `updates.json`. The README describes LinkLog, the Docker image pull location, and the raw signed XPI download URL.
### User
The tagged version will be the version of the backend. However, the version of the plugin is set manually, just use the most recent signed plugin version that lives in the signed repo.
### Assistant outcome
Decoupled backend and plugin release versions. The release tag and Docker image now use the backend `LINKLOG_VERSION`; the workflow discovers the newest semver signed artifact in `XPI/signed/`, validates its embedded manifest, and writes the plugin version and raw XPI URL into the generated release README. Updated release documentation and validated the script, workflow run blocks, and generated README output.
### User
Update the VIBE directory with what you have done.
### Assistant outcome
Appended the release workflow changes and this VIBE update request to `VIBE/PROMPTS.md` and `VIBE/CHAT_LOG.md` in the existing append-only format.
+27
View File
@@ -197,6 +197,33 @@
191. Put the email header text to the right of the logo, align it at the top, and add a comma after Hello. 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. 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. 193. Reduce the email greeting font size somewhat.
194. Replace LINKLOG_TOKEN_EXPIRY_DAYS with LINKLOG_TOKEN_EXPIRY_MINUTES, add LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS to production Compose, and add a CI configuration consistency test.
195. Perform a new security audit overwriting Security-audit.md with new and remaining issues.
195. Update SA-012 and README for the implemented refresh-token lifecycle, revocation behavior, and refresh endpoint.
196. Remedy SA-001: migrate logout from JSON token transport to the Authorization bearer header.
197. Implement SA-002: replace raw infrastructure errors with redacted server-side logging, request IDs, and stable public reference messages.
198. Implement SA-005: reject missing/default/weak production secrets at startup and validate the Fernet encryption key, with configuration tests.
199. Fix Firefox manifest compatibility warnings by aligning the minimum version with data collection permissions and session storage support.
200. Add a Plugin section to the About page with a download link to the signed XPI file.
201. Below the Save profile button, add a link to download the signed plugin if it has not been downloaded yet.
202. Check the modified pages for the correct versioned signed XPI link.
203. When posting to Mastodon, add an empty line between "From my #LinkLog:" and the title.
204. Fix the release workflow because the runner's curl does not support `--fail-with-body`.
205. The release action should work differently. Rather than publishing the signed XPI and `updates.json`, it should produce a README describing the project, the latest Docker container version, and the latest signed XPI download URL with version number.
206. The tagged version will be the version of the backend. However, the version of the plugin is set manually, just use the most recent signed plugin version that lives in the signed repo.
207. Update the VIBE directory with what you have done.
## 2026-08-27
205. Maintain actions in the logs if VIBE.
206. Create a new page that can be reached by a button 'new entry' that only shows for authenticated users. The page, also only available to authenticated users allows users to enter a URL. When the URL is entered then the backend will scrape the title and allow to fill in all fields that are also available in the plugin.
207. The plugin finds a different title than the new-entry page, see e.g. https://docs.gitea.com/administration/config-cheat-sheet/
208. The plugin and the new entry page are still inconsistent.
209. For https://docs.gitea.com/administration/config-cheat-sheet/ I want the title to be Configuration Cheat Sheet | Gitea Documentation
210. After an entry is saved move to the /<user>/ page
211. Don't put new entry in the hamburger menu but present it as a seperate button next to the style selector
212. Put the new entry button left of the hamburger menu
213. The style selection should move into the hamburger menu - but in such a way that it becomes a submenu so that it doesn't clutter the menu structure
## Future entries ## Future entries
Binary file not shown.
Binary file not shown.
+10 -5
View File
@@ -5,7 +5,7 @@ import json
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from uuid import uuid4 from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel from pydantic import BaseModel
from backend.app.api.dependencies import require_admin from backend.app.api.dependencies import require_admin
@@ -23,8 +23,11 @@ from backend.app.services.theme_service import THEMES, get_enabled_themes, save_
from backend.app.services.secret_store import encrypt_secret from backend.app.services.secret_store import encrypt_secret
from backend.app.core.config import settings from backend.app.core.config import settings
from backend.app.services.audit_service import record_audit_event from backend.app.services.audit_service import record_audit_event
from backend.app.core.errors import public_error, redacted_error, request_id
import logging
router = APIRouter() router = APIRouter()
logger = logging.getLogger(__name__)
class AdminPluginUpdate(BaseModel): class AdminPluginUpdate(BaseModel):
@@ -112,7 +115,7 @@ def reset_user_otp(user_id: str, current_user: dict = Depends(require_admin)):
@router.post('/users', status_code=201) @router.post('/users', status_code=201)
def create_user(payload: AdminUserCreate, current_user: dict = Depends(require_admin)): def create_user(payload: AdminUserCreate, request: Request, current_user: dict = Depends(require_admin)):
username = payload.username.strip() username = payload.username.strip()
email = payload.email.strip() email = payload.email.strip()
if not username or not email or len(payload.password) < 8: if not username or not email or len(payload.password) < 8:
@@ -142,7 +145,8 @@ def create_user(payload: AdminUserCreate, current_user: dict = Depends(require_a
try: try:
send_verification_email(row['email'], row['username'], verification_url) send_verification_email(row['email'], row['username'], verification_url)
except Exception as error: except Exception as error:
raise HTTPException(status_code=503, detail=f'User created but verification email could not be sent: {error}') from error logger.error('User verification email failed request_id=%s error=%s', request_id(request), redacted_error(error))
raise HTTPException(status_code=503, detail=public_error(request, 'User created but verification email could not be sent.')) from error
record_audit_event(current_user['id'], 'user_created', 'user', row['id'], details={'is_admin': bool(payload.is_admin)}) record_audit_event(current_user['id'], 'user_created', 'user', row['id'], details={'is_admin': bool(payload.is_admin)})
return public_user(row) return public_user(row)
@@ -188,7 +192,7 @@ def update_admin_smtp_settings(payload: AdminSmtpUpdate, current_user: dict = De
@router.post('/smtp/test') @router.post('/smtp/test')
def validate_admin_smtp(payload: AdminSmtpUpdate, current_user: dict = Depends(require_admin)): def validate_admin_smtp(payload: AdminSmtpUpdate, request: Request, current_user: dict = Depends(require_admin)):
values = validate_smtp_values(payload, get_smtp_settings()) values = validate_smtp_values(payload, get_smtp_settings())
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
with get_connection() as conn: with get_connection() as conn:
@@ -209,7 +213,8 @@ def validate_admin_smtp(payload: AdminSmtpUpdate, current_user: dict = Depends(r
try: try:
send_test_email(current_user['email'], values) send_test_email(current_user['email'], values)
except Exception as error: except Exception as error:
raise HTTPException(status_code=503, detail=f'SMTP validation failed: {error}') from error logger.error('SMTP validation failed request_id=%s error=%s', request_id(request), redacted_error(error))
raise HTTPException(status_code=503, detail=public_error(request, 'SMTP validation failed.')) from error
sends = int(rate.get('sends', 0)) + 1 sends = int(rate.get('sends', 0)) + 1
updated_rate = {'sends': sends, 'last_sent': now.isoformat()} updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
if sends >= 5: if sends >= 5:
+6 -4
View File
@@ -3,7 +3,7 @@
from uuid import uuid4 from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException, Request from fastapi import APIRouter, Depends, Header, HTTPException, Request
from pydantic import BaseModel from pydantic import BaseModel
from backend.app.api.dependencies import get_current_user from backend.app.api.dependencies import get_current_user
@@ -119,10 +119,12 @@ def reset_password_endpoint(payload: PasswordResetRequest):
@router.post('/logout') @router.post('/logout')
def logout(payload: dict): def logout(authorization: str | None = Header(default=None)):
token = payload.get('token') if not authorization or not authorization.startswith('Bearer '):
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
token = authorization.replace('Bearer ', '', 1).strip()
if not token: if not token:
raise HTTPException(status_code=400, detail='Token is required') raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
revoked = revoke_token(token) revoked = revoke_token(token)
if not revoked: if not revoked:
raise HTTPException(status_code=404, detail='Token not found or already revoked') raise HTTPException(status_code=404, detail='Token not found or already revoked')
+16
View File
@@ -11,6 +11,7 @@ from backend.app.database import get_connection
from backend.app.services.plugin_manager import plugin_manager from backend.app.services.plugin_manager import plugin_manager
from backend.app.services.token_service import validate_token from backend.app.services.token_service import validate_token
from backend.app.services.audit_service import record_audit_event from backend.app.services.audit_service import record_audit_event
from backend.app.services.scraper_service import scrape_title
router = APIRouter() router = APIRouter()
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -36,6 +37,21 @@ def available_tags():
return list_tags() return list_tags()
@router.get('/scrape')
def scrape_url(url: str, authorization: str | None = Header(default=None)):
if not authorization or not authorization.startswith('Bearer '):
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
info = validate_token(authorization.replace('Bearer ', '', 1))
if info is None:
raise HTTPException(status_code=401, detail='Token expired or invalid')
try:
title = scrape_title(url)
return {'title': title}
except Exception as e:
logger.error('Scrape error for %s: %s', url, e)
raise HTTPException(status_code=502, detail='Could not scrape URL') from e
@router.get('/links/check') @router.get('/links/check')
def check_existing_link( def check_existing_link(
title: str, title: str,
+8 -3
View File
@@ -10,12 +10,15 @@ from starlette.requests import Request
from backend.app.api.dependencies import get_current_user from backend.app.api.dependencies import get_current_user
from backend.app.services.mastodon_oauth import finish_authorization, start_authorization from backend.app.services.mastodon_oauth import finish_authorization, start_authorization
from backend.app.core.errors import public_error, redacted_error, request_id
import logging
router = APIRouter() router = APIRouter()
logger = logging.getLogger(__name__)
@router.get('/oauth/start') @router.get('/oauth/start')
def oauth_start(instance: str = 'mastodon.social', user: dict = Depends(get_current_user)): def oauth_start(request: Request, instance: str = 'mastodon.social', user: dict = Depends(get_current_user)):
try: try:
authorization_url = start_authorization(user['id'], instance) authorization_url = start_authorization(user['id'], instance)
except HTTPError as error: except HTTPError as error:
@@ -27,7 +30,8 @@ def oauth_start(instance: str = 'mastodon.social', user: dict = Depends(get_curr
headers=headers, headers=headers,
) from error ) from error
except Exception as error: except Exception as error:
raise HTTPException(status_code=502, detail=f'Could not register with Mastodon: {error}') from error logger.error('Mastodon registration failed request_id=%s error=%s', request_id(request), redacted_error(error))
raise HTTPException(status_code=502, detail=public_error(request, 'Could not register with Mastodon.')) from error
return {'authorization_url': authorization_url} return {'authorization_url': authorization_url}
@@ -38,5 +42,6 @@ def oauth_callback(request: Request, code: str | None = None, state: str | None
try: try:
finish_authorization(code, state) finish_authorization(code, state)
except Exception as callback_error: except Exception as callback_error:
return RedirectResponse(f'/profile?mastodon_error={quote(str(callback_error))}') logger.error('Mastodon callback failed request_id=%s error=%s', request_id(request), redacted_error(callback_error))
return RedirectResponse(f'/profile?mastodon_error={quote(public_error(request, "Could not complete Mastodon authorization."))}')
return RedirectResponse('/profile?mastodon=connected') return RedirectResponse('/profile?mastodon=connected')
+7 -3
View File
@@ -5,14 +5,17 @@ from datetime import datetime, timedelta, timezone
import json import json
from uuid import uuid4 from uuid import uuid4
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel from pydantic import BaseModel
from backend.app.core.config import settings from backend.app.core.config import settings
from backend.app.database import get_connection, hash_password from backend.app.database import get_connection, hash_password
from backend.app.services.email_service import get_smtp_settings, save_smtp_settings, send_test_email from backend.app.services.email_service import get_smtp_settings, save_smtp_settings, send_test_email
from backend.app.core.errors import public_error, redacted_error, request_id
import logging
router = APIRouter() router = APIRouter()
logger = logging.getLogger(__name__)
class SetupRequest(BaseModel): class SetupRequest(BaseModel):
@@ -92,7 +95,7 @@ def save_configuration(payload: SetupRequest):
@router.post('/test-mail') @router.post('/test-mail')
def test_mail(payload: TestMailRequest | None = None): def test_mail(request: Request, payload: TestMailRequest | None = None):
if has_administrator(): if has_administrator():
raise HTTPException(status_code=409, detail='LinkLog is already configured') raise HTTPException(status_code=409, detail='LinkLog is already configured')
pending = get_pending_setup() pending = get_pending_setup()
@@ -119,7 +122,8 @@ def test_mail(payload: TestMailRequest | None = None):
try: try:
send_test_email(payload.email if payload and payload.email else pending['email']) send_test_email(payload.email if payload and payload.email else pending['email'])
except Exception as error: except Exception as error:
raise HTTPException(status_code=503, detail=f'SMTP test mail could not be sent: {error}') from error logger.error('SMTP test mail failed request_id=%s error=%s', request_id(request), redacted_error(error))
raise HTTPException(status_code=503, detail=public_error(request, 'SMTP test mail could not be sent.')) from error
sends = int(rate.get('sends', 0)) + 1 sends = int(rate.get('sends', 0)) + 1
updated_rate = {'sends': sends, 'last_sent': now.isoformat()} updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
+10 -5
View File
@@ -7,7 +7,7 @@ from io import BytesIO
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from uuid import uuid4 from uuid import uuid4
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
from PIL import Image, UnidentifiedImageError from PIL import Image, UnidentifiedImageError
from pydantic import BaseModel from pydantic import BaseModel
@@ -20,8 +20,11 @@ from backend.app.services.email_service import send_verification_email, smtp_con
from backend.app.core.config import settings from backend.app.core.config import settings
from backend.app.services.secret_store import decrypt_secret, encrypt_secret from backend.app.services.secret_store import decrypt_secret, encrypt_secret
from backend.app.services.audit_service import record_audit_event from backend.app.services.audit_service import record_audit_event
from backend.app.core.errors import public_error, redacted_error, request_id
import logging
router = APIRouter() router = APIRouter()
logger = logging.getLogger(__name__)
MAX_AVATAR_BYTES = 2 * 1024 * 1024 MAX_AVATAR_BYTES = 2 * 1024 * 1024
MAX_AVATAR_PIXELS = 25_000_000 MAX_AVATAR_PIXELS = 25_000_000
@@ -186,7 +189,7 @@ def get_additional_emails(user: dict = Depends(get_current_user)):
@router.post('/emails', status_code=201) @router.post('/emails', status_code=201)
def add_additional_email(payload: AdditionalEmail, user: dict = Depends(get_current_user)): def add_additional_email(payload: AdditionalEmail, request: Request, user: dict = Depends(get_current_user)):
email = payload.email.strip().lower() email = payload.email.strip().lower()
if email == user['email'].lower(): if email == user['email'].lower():
raise HTTPException(status_code=409, detail='This is already the primary email address') raise HTTPException(status_code=409, detail='This is already the primary email address')
@@ -209,7 +212,8 @@ def add_additional_email(payload: AdditionalEmail, user: dict = Depends(get_curr
try: try:
send_verification_email(email_address, user['username'], verification_url) send_verification_email(email_address, user['username'], verification_url)
except Exception as error: except Exception as error:
raise HTTPException(status_code=503, detail=f'Email address added but verification email could not be sent: {error}') from error logger.error('Additional email verification failed request_id=%s error=%s', request_id(request), redacted_error(error))
raise HTTPException(status_code=503, detail=public_error(request, 'Email address added but verification email could not be sent.')) from error
with get_connection() as conn: with get_connection() as conn:
conn.execute( conn.execute(
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP) '''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
@@ -221,7 +225,7 @@ def add_additional_email(payload: AdditionalEmail, user: dict = Depends(get_curr
@router.post('/emails/{address_id}/resend') @router.post('/emails/{address_id}/resend')
def resend_additional_email(address_id: str, user: dict = Depends(get_current_user)): def resend_additional_email(address_id: str, request: Request, user: dict = Depends(get_current_user)):
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
setting_name = f'email_verify_rate:{address_id}' setting_name = f'email_verify_rate:{address_id}'
with get_connection() as conn: with get_connection() as conn:
@@ -245,7 +249,8 @@ def resend_additional_email(address_id: str, user: dict = Depends(get_current_us
try: try:
send_verification_email(email, user['username'], verification_url) send_verification_email(email, user['username'], verification_url)
except Exception as error: except Exception as error:
raise HTTPException(status_code=503, detail=f'Verification email could not be sent: {error}') from error logger.error('Verification email resend failed request_id=%s error=%s', request_id(request), redacted_error(error))
raise HTTPException(status_code=503, detail=public_error(request, 'Verification email could not be sent.')) from error
sends = int(rate.get('sends', 0)) + 1 sends = int(rate.get('sends', 0)) + 1
updated = {'sends': sends, 'last_sent': now.isoformat()} updated = {'sends': sends, 'last_sent': now.isoformat()}
if sends >= 5: if sends >= 5:
+20 -1
View File
@@ -5,6 +5,8 @@ from dataclasses import dataclass
import os import os
from pathlib import Path from pathlib import Path
from cryptography.fernet import Fernet
BASE_DIR = Path(__file__).resolve().parent.parent.parent BASE_DIR = Path(__file__).resolve().parent.parent.parent
DB_PATH = BASE_DIR / 'data' / 'linklog.db' DB_PATH = BASE_DIR / 'data' / 'linklog.db'
@@ -20,8 +22,9 @@ def normalize_public_url(value: str) -> str:
@dataclass @dataclass
class Settings: class Settings:
app_env: str = os.getenv('APP_ENV', 'development').lower()
app_name: str = os.getenv('LINKLOG_APP_NAME', 'LinkLog') app_name: str = os.getenv('LINKLOG_APP_NAME', 'LinkLog')
version: str = os.getenv('LINKLOG_VERSION', '0.1.0') version: str = os.getenv('LINKLOG_VERSION', '0.1.1')
database_url: str = os.getenv('LINKLOG_DATABASE_URL', f'sqlite:///{DB_PATH}') 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') secret_key: str = os.getenv('LINKLOG_SECRET_KEY', 'dev-secret-key-change-me')
data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '') data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
@@ -59,3 +62,19 @@ class Settings:
settings = Settings() settings = Settings()
def validate_configuration(values: Settings) -> None:
if values.app_env == 'production':
if not values.secret_key or values.secret_key == 'dev-secret-key-change-me':
raise RuntimeError('LINKLOG_SECRET_KEY must be configured in production')
if len(values.secret_key) < 32 or len(set(values.secret_key)) < 12:
raise RuntimeError('LINKLOG_SECRET_KEY must be at least 32 characters with sufficient entropy')
if not values.data_encryption_key:
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY must be configured in production')
if values.data_encryption_key:
try:
Fernet(values.data_encryption_key.encode('ascii'))
except (ValueError, UnicodeEncodeError) as error:
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY must be a valid Fernet key') from error
+23
View File
@@ -0,0 +1,23 @@
import re
from uuid import uuid4
from fastapi import Request
SENSITIVE_PATTERN = re.compile(
r'(?i)(authorization\s*[:=]\s*bearer\s+[^\s,;]+|'
r'(?:token|password|secret|otp|code)(?:[_-](?:token|password|secret|code))?\s*[:=]\s*[^\s,;&]+|'
r'([?&](?:token|code|password|secret|otp)=[^&#\s]+))'
)
def request_id(request: Request) -> str:
return getattr(request.state, 'request_id', None) or str(uuid4())
def redacted_error(error: Exception) -> str:
return SENSITIVE_PATTERN.sub('[REDACTED]', str(error))
def public_error(request: Request, message: str) -> str:
return f'{message} Reference: {request_id(request)}'
+21 -2
View File
@@ -1,8 +1,9 @@
## Copyright © 2026 Olaf Kolkman ## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
from fastapi import FastAPI from fastapi import FastAPI, Request
import logging import logging
from uuid import uuid4
from fastapi.responses import HTMLResponse from fastapi.responses import HTMLResponse
from fastapi.responses import RedirectResponse from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
@@ -17,13 +18,23 @@ from backend.app.api.public import router as public_router
from backend.app.api.setup import router as setup_router from backend.app.api.setup import router as setup_router
from backend.app.api.setup import has_administrator from backend.app.api.setup import has_administrator
from backend.app.api.user_config import router as user_config_router from backend.app.api.user_config import router as user_config_router
from backend.app.core.config import settings from backend.app.core.config import settings, validate_configuration
from backend.app.database import AVATARS_DIR from backend.app.database import AVATARS_DIR
from backend.app.services.link_service import get_public_profile, list_public_links from backend.app.services.link_service import get_public_profile, list_public_links
logging.basicConfig(level=getattr(logging, settings.log_level, logging.INFO)) logging.basicConfig(level=getattr(logging, settings.log_level, logging.INFO))
validate_configuration(settings)
app = FastAPI(title='LinkLog API', version=settings.version) app = FastAPI(title='LinkLog API', version=settings.version)
@app.middleware('http')
async def add_request_id(request: Request, call_next):
request.state.request_id = request.headers.get('X-Request-ID') or str(uuid4())
response = await call_next(request)
response.headers['X-Request-ID'] = request.state.request_id
return response
app.mount('/static', StaticFiles(directory='frontend/static'), name='static') app.mount('/static', StaticFiles(directory='frontend/static'), name='static')
app.mount('/media', StaticFiles(directory=AVATARS_DIR), name='media') app.mount('/media', StaticFiles(directory=AVATARS_DIR), name='media')
app.include_router(auth_router, prefix='/api/auth') app.include_router(auth_router, prefix='/api/auth')
@@ -35,6 +46,7 @@ app.include_router(user_config_router, prefix='/api/user')
app.include_router(setup_router, prefix='/api/setup') app.include_router(setup_router, prefix='/api/setup')
templates = Jinja2Templates(directory='frontend/templates') templates = Jinja2Templates(directory='frontend/templates')
templates.env.globals['app_version'] = settings.version
@app.get('/', response_class=HTMLResponse) @app.get('/', response_class=HTMLResponse)
@@ -66,6 +78,13 @@ async def labels_page(request: Request):
return templates.TemplateResponse(request, 'labels.html', {}) return templates.TemplateResponse(request, 'labels.html', {})
@app.get('/new-entry', response_class=HTMLResponse)
async def new_entry_page(request: Request):
if not has_administrator():
return RedirectResponse('/setup')
return templates.TemplateResponse(request, 'new-entry.html', {})
@app.get('/about', response_class=HTMLResponse) @app.get('/about', response_class=HTMLResponse)
async def about_page(request: Request): async def about_page(request: Request):
return templates.TemplateResponse(request, 'about.html', {}) return templates.TemplateResponse(request, 'about.html', {})
+3 -1
View File
@@ -68,7 +68,9 @@ class MastodonPlugin(BasePlugin):
post_prefix = f'#{str(config["hashtag"]).strip().lstrip("#")} ' post_prefix = f'#{str(config["hashtag"]).strip().lstrip("#")} '
post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX).strip() post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX).strip()
title = str(event.get('title') or '').strip() title = str(event.get('title') or '').strip()
status_parts = [f'{post_prefix} {title}'.strip()] status_parts = [post_prefix.strip()]
if title:
status_parts.append(title)
if event.get('comment'): if event.get('comment'):
status_parts.append(event['comment']) status_parts.append(event['comment'])
if title: if title:
+106
View File
@@ -0,0 +1,106 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
import httpx
import logging
from html.parser import HTMLParser
from urllib.parse import urlparse
logger = logging.getLogger(__name__)
class TitleParser(HTMLParser):
def __init__(self):
super().__init__()
self.title = None
self.og_title = None
self.twitter_title = None
self.meta_title = None
self.in_title = False
def handle_starttag(self, tag, attrs):
if tag.lower() == 'title':
self.in_title = True
elif tag.lower() == 'meta':
attrs_dict = dict(attrs)
# Check for Open Graph title
if attrs_dict.get('property', '').lower() == 'og:title':
content = attrs_dict.get('content', '').strip()
if content and not self.og_title:
self.og_title = content
# Check for Twitter title
elif attrs_dict.get('name', '').lower() == 'twitter:title':
content = attrs_dict.get('content', '').strip()
if content and not self.twitter_title:
self.twitter_title = content
# Check for generic meta title
elif attrs_dict.get('name', '').lower() == 'title':
content = attrs_dict.get('content', '').strip()
if content and not self.meta_title:
self.meta_title = content
def handle_endtag(self, tag):
if tag.lower() == 'title':
self.in_title = False
def handle_data(self, data):
if self.in_title and not self.title:
stripped = data.strip()
if stripped:
self.title = stripped
def get_best_title(self):
"""Return the best title found, matching browser behavior.
Priority: page <title> tag (what browser shows), then meta tags as fallback."""
return self.title or self.og_title or self.twitter_title or self.meta_title
def scrape_title(url: str) -> str:
"""
Scrape the title from a URL, checking multiple sources:
1. Page title tag (what browser shows)
2. Open Graph title (og:title meta tag)
3. Twitter title (twitter:title meta tag)
4. Generic meta title
5. Domain name as fallback
"""
try:
# Parse URL to extract domain as fallback
parsed = urlparse(url)
domain = parsed.netloc or url
# Fetch the URL with a timeout and size limit, using iter_bytes for decompression
with httpx.stream('GET', url, follow_redirects=True, timeout=5.0) as response:
if response.status_code != 200:
logger.warning('Failed to fetch %s: status %d', url, response.status_code)
return domain
# Read HTML in chunks (auto-decompressed) to avoid loading huge files
html_content = b''
max_size = 1024 * 100 # 100 KB limit
for chunk in response.iter_bytes():
html_content += chunk
if len(html_content) > max_size:
break
# Parse the HTML to extract title
try:
html_text = html_content.decode('utf-8', errors='ignore')
parser = TitleParser()
parser.feed(html_text)
best_title = parser.get_best_title()
if best_title:
return best_title
except Exception as e:
logger.warning('Failed to parse HTML from %s: %s', url, e)
return domain
except httpx.TimeoutException:
logger.warning('Timeout fetching %s', url)
return urlparse(url).netloc or url
except httpx.NetworkError as e:
logger.warning('Network error fetching %s: %s', url, e)
return urlparse(url).netloc or url
except Exception as e:
logger.error('Unexpected error scraping %s: %s', url, e)
return urlparse(url).netloc or url
+41 -5
View File
@@ -31,7 +31,7 @@ def login_headers(username='alice'):
def test_login_returns_token(): def test_login_returns_token():
assert app.version == '0.1.0' assert app.version == '0.1.1'
response = client.post('/api/auth/login', json={ response = client.post('/api/auth/login', json={
'email': 'alice@example.com', 'email': 'alice@example.com',
'password': 'secret123', 'password': 'secret123',
@@ -55,6 +55,17 @@ def test_login_returns_token():
assert client.get('/api/auth/me', params={'token': payload['access_token']}).status_code == 401 assert client.get('/api/auth/me', params={'token': payload['access_token']}).status_code == 401
def test_logout_requires_bearer_header_and_revokes_token_family():
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
token = login['access_token']
headers = {'Authorization': f'Bearer {token}'}
assert client.post('/api/auth/logout', json={'token': token}).status_code == 401
assert client.get('/api/auth/me', headers=headers).status_code == 200
assert client.post('/api/auth/logout', headers=headers).status_code == 200
assert client.get('/api/auth/me', headers=headers).status_code == 401
assert client.post('/api/auth/refresh', json={'refresh_token': login['refresh_token'], 'device_id': login['device_id']}).status_code == 401
def test_login_rate_limit_locks_out_after_five_failures_and_resets_on_success(): def test_login_rate_limit_locks_out_after_five_failures_and_resets_on_success():
email = f'unknown-{uuid4().hex}@example.com' email = f'unknown-{uuid4().hex}@example.com'
for attempt in range(5): for attempt in range(5):
@@ -216,7 +227,31 @@ def test_admin_reports_smtp_validation_errors():
'smtp_use_tls': False, 'smtp_use_tls': False,
}) })
assert failed_validation.status_code == 503 assert failed_validation.status_code == 503
assert 'connection refused' in failed_validation.json()['detail'] assert failed_validation.json()['detail'].startswith('SMTP validation failed. Reference: ')
assert 'connection refused' not in failed_validation.json()['detail']
assert failed_validation.headers['X-Request-ID']
def test_request_id_is_preserved_and_sensitive_error_text_is_not_returned():
headers = login_headers()
with get_connection() as conn:
conn.execute('DELETE FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',))
conn.commit()
with patch('backend.app.api.admin.send_test_email', side_effect=RuntimeError('password=super-secret token=abc123')):
response = client.post(
'/api/admin/smtp/test',
headers={**headers, 'X-Request-ID': 'audit-test-123'},
json={
'smtp_host': 'smtp.example.com',
'smtp_port': 2525,
'smtp_from': 'admin@example.com',
},
)
assert response.status_code == 503
assert response.headers['X-Request-ID'] == 'audit-test-123'
assert response.json()['detail'] == 'SMTP validation failed. Reference: audit-test-123'
assert 'super-secret' not in response.text
assert 'abc123' not in response.text
def test_admin_can_add_list_and_remove_users(): def test_admin_can_add_list_and_remove_users():
@@ -643,8 +678,7 @@ def test_only_link_owner_can_edit_link():
def test_logout_revokes_token_and_admin_can_list_plugins(): def test_logout_revokes_token_and_admin_can_list_plugins():
headers = login_headers() headers = login_headers()
token = headers['Authorization'].removeprefix('Bearer ') assert client.post('/api/auth/logout', headers=headers).status_code == 200
assert client.post('/api/auth/logout', json={'token': token}).status_code == 200
revoked_response = client.post('/api/links', headers=headers, json={ revoked_response = client.post('/api/links', headers=headers, json={
'title': 'Should fail', 'title': 'Should fail',
@@ -693,6 +727,8 @@ def test_public_and_admin_pages_render_html():
about_page = client.get('/about') about_page = client.get('/about')
assert about_page.status_code == 200 assert about_page.status_code == 200
assert 'Save the good stuff' in about_page.text assert 'Save the good stuff' in about_page.text
assert '<h2>Plugin</h2>' in about_page.text
assert 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi' in about_page.text
assert 'id="auth-about-link" href="/about"' in about_page.text assert 'id="auth-about-link" href="/about"' in about_page.text
assert client.get('/admin').status_code == 200 assert client.get('/admin').status_code == 200
admin_page = client.get('/admin').text admin_page = client.get('/admin').text
@@ -760,7 +796,7 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
assert received['path'] == '/api/v1/statuses' assert received['path'] == '/api/v1/statuses'
assert received['authorization'] == 'Bearer test-token' assert received['authorization'] == 'Bearer test-token'
assert received['content_type'] == 'application/x-www-form-urlencoded' assert received['content_type'] == 'application/x-www-form-urlencoded'
assert received['body'] == {'status': ['From my #LinkLog: A useful page\n\nWorth sharing\n\nfrom: https://example.com/useful\n\n#python #web']} assert received['body'] == {'status': ['From my #LinkLog:\n\nA useful page\n\nWorth sharing\n\nfrom: https://example.com/useful\n\n#python #web']}
posted_item = next(item for item in client.get('/api/public/feed/alice', headers=headers).json() if item['id'] == response.json()['id']) posted_item = next(item for item in client.get('/api/public/feed/alice', headers=headers).json() if item['id'] == response.json()['id'])
assert posted_item['mastodon_posted'] is True assert posted_item['mastodon_posted'] is True
finally: finally:
+44
View File
@@ -0,0 +1,44 @@
import re
from pathlib import Path
import pytest
from backend.app.core.config import Settings, validate_configuration
ROOT = Path(__file__).resolve().parents[2]
def test_production_configuration_rejects_missing_or_default_secret():
with pytest.raises(RuntimeError, match='LINKLOG_SECRET_KEY'):
validate_configuration(Settings(app_env='production', secret_key='', data_encryption_key=''))
with pytest.raises(RuntimeError, match='LINKLOG_SECRET_KEY'):
validate_configuration(Settings(app_env='production', secret_key='dev-secret-key-change-me', data_encryption_key=''))
def test_production_configuration_rejects_weak_or_missing_encryption_key():
with pytest.raises(RuntimeError, match='entropy'):
validate_configuration(Settings(app_env='production', secret_key='A' * 32, data_encryption_key=''))
with pytest.raises(RuntimeError, match='DATA_ENCRYPTION_KEY'):
validate_configuration(Settings(app_env='production', secret_key='A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6', data_encryption_key='invalid'))
def test_production_configuration_accepts_strong_secrets():
values = Settings(
app_env='production',
secret_key='A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6',
data_encryption_key='L5M4sQYVjD1N7pT2Xk8R0aBcDeFgHiJkLmNoPqRsTuV=',
)
validate_configuration(values)
def test_production_compose_configuration_matches_settings_environment_keys():
compose = (ROOT / 'docker-compose.yml').read_text()
settings = (ROOT / 'backend' / 'app' / 'core' / 'config.py').read_text()
database = (ROOT / 'backend' / 'app' / 'database.py').read_text()
compose_keys = set(re.findall(r'\b(LINKLOG_[A-Z0-9_]+):', compose))
settings_keys = set(re.findall(r"os\.getenv\('([^']+)'", settings + database))
assert {'LINKLOG_TOKEN_EXPIRY_MINUTES', 'LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS'} <= compose_keys
assert compose_keys & settings_keys == compose_keys
assert 'LINKLOG_TOKEN_EXPIRY_DAYS' not in compose_keys
+2
View File
@@ -51,6 +51,8 @@ def test_user_config_api_and_profile_page():
assert 'id="auth-avatar"' not in page_response.text assert 'id="auth-avatar"' not in page_response.text
assert 'name="new_password_confirmation"' in page_response.text assert 'name="new_password_confirmation"' in page_response.text
assert 'id="additional-email-form"' in page_response.text assert 'id="additional-email-form"' in page_response.text
assert 'If you have not downloaded the plugin yet' in page_response.text
assert 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi' in page_response.text
bob_login = client.post('/api/auth/login', json={ bob_login = client.post('/api/auth/login', json={
'email': 'bob@example.com', 'email': 'bob@example.com',
+12 -11
View File
@@ -17,7 +17,8 @@ services:
LINKLOG_DATA_ENCRYPTION_KEY: ${LINKLOG_DATA_ENCRYPTION_KEY:?Set LINKLOG_DATA_ENCRYPTION_KEY in .env} LINKLOG_DATA_ENCRYPTION_KEY: ${LINKLOG_DATA_ENCRYPTION_KEY:?Set LINKLOG_DATA_ENCRYPTION_KEY in .env}
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com} LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-INFO} LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-INFO}
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_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-} LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
restart: ${APP_RESTART_POLICY:-unless-stopped} restart: ${APP_RESTART_POLICY:-unless-stopped}
healthcheck: healthcheck:
@@ -29,21 +30,21 @@ services:
labels: labels:
traefik.enable: true traefik.enable: true
traefik.http.middlewares.web-https-redirect.redirectscheme.scheme: https traefik.http.middlewares.web-https-redirect.redirectscheme.scheme: https
traefik.http.services.linklog.loadbalancer.server.port: 8000 traefik.http.services.testlog.loadbalancer.server.port: 8000
traefik.docker.network: git_traefik traefik.docker.network: git_traefik
traefik.http.routers.linklog.entrypoints: web traefik.http.routers.testlog.entrypoints: web
traefik.http.routers.linklog.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`) traefik.http.routers.testlog.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
traefik.http.routers.linklog.middlewares: web-https-redirect,servicests traefik.http.routers.testlog.middlewares: web-https-redirect,servicests
traefik.http.routers.linklog-secure.entrypoints: websecure traefik.http.routers.testlog-secure.entrypoints: websecure
traefik.http.routers.linklog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`) traefik.http.routers.testlog-secure.rule: Host(`${LINKLOG_PUBLIC_URL:-linklog.example.com}`)
traefik.http.routers.linklog-secure.tls: true traefik.http.routers.testlog-secure.tls: true
traefik.http.routers.linklog-secure.middlewares: servicests traefik.http.routers.testlog-secure.middlewares: servicests
traefik.http.routers.linklog-secure.tls.certresolver: myresolver traefik.http.routers.testlog-secure.tls.certresolver: myresolver
traefik.http.routers.linklog-secure.service: linklog traefik.http.routers.testlog-secure.service: testlog
+17
View File
@@ -3,6 +3,7 @@
(() => { (() => {
const loginButton = document.querySelector('#auth-login-button'); const loginButton = document.querySelector('#auth-login-button');
const newEntryButton = document.querySelector('#new-entry-button');
const profileLink = document.querySelector('#auth-profile-link'); const profileLink = document.querySelector('#auth-profile-link');
const labelsLink = document.querySelector('#auth-labels-link'); const labelsLink = document.querySelector('#auth-labels-link');
const adminLink = document.querySelector('#auth-admin-link'); const adminLink = document.querySelector('#auth-admin-link');
@@ -14,6 +15,10 @@
const menuToggle = document.querySelector('.menu-toggle'); const menuToggle = document.querySelector('.menu-toggle');
const logoutButton = document.querySelector('#logout-button'); const logoutButton = document.querySelector('#logout-button');
const themeSubmenuContainer = document.querySelector('#theme-submenu-container');
const themeSubmenuTitle = document.querySelector('.submenu-title');
const themeOptions = document.querySelector('#theme-options');
if (!loginButton || !profileLink || !labelsLink || !adminLink || !session || !username || !menu || !menuToggle || !logoutButton) return; if (!loginButton || !profileLink || !labelsLink || !adminLink || !session || !username || !menu || !menuToggle || !logoutButton) return;
menuToggle.addEventListener('click', () => { menuToggle.addEventListener('click', () => {
@@ -22,8 +27,19 @@
menuToggle.setAttribute('aria-expanded', String(!isOpen)); menuToggle.setAttribute('aria-expanded', String(!isOpen));
}); });
// Handle theme submenu toggle
if (themeSubmenuTitle && themeOptions) {
themeSubmenuTitle.addEventListener('click', (e) => {
e.preventDefault();
const isOpen = !themeOptions.classList.contains('hidden');
themeOptions.classList.toggle('hidden', isOpen);
themeSubmenuTitle.setAttribute('aria-expanded', String(!isOpen));
});
}
function showSignedOut() { function showSignedOut() {
loginButton.classList.remove('hidden'); loginButton.classList.remove('hidden');
if (newEntryButton) newEntryButton.classList.add('hidden');
profileLink.classList.add('hidden'); profileLink.classList.add('hidden');
labelsLink.classList.add('hidden'); labelsLink.classList.add('hidden');
adminLink.classList.add('hidden'); adminLink.classList.add('hidden');
@@ -33,6 +49,7 @@
function showSignedIn(user) { function showSignedIn(user) {
loginButton.classList.add('hidden'); loginButton.classList.add('hidden');
if (newEntryButton) newEntryButton.classList.remove('hidden');
profileLink.classList.remove('hidden'); profileLink.classList.remove('hidden');
labelsLink.classList.remove('hidden'); labelsLink.classList.remove('hidden');
adminLink.classList.toggle('hidden', !user.is_admin); adminLink.classList.toggle('hidden', !user.is_admin);
+1 -2
View File
@@ -12,8 +12,7 @@ logoutButton.addEventListener('click', async () => {
if (token) { if (token) {
await fetch('/api/auth/logout', { await fetch('/api/auth/logout', {
method: 'POST', method: 'POST',
headers: {'Content-Type': 'application/json'}, headers: {Authorization: `Bearer ${token}`},
body: JSON.stringify({token}),
}).catch(() => undefined); }).catch(() => undefined);
} }
+203
View File
@@ -0,0 +1,203 @@
// Copyright © 2026 Olaf Kolkman
// SPDX-License-Identifier: GPL-3.0-or-later
(() => {
const entryForm = document.getElementById('entry-form');
const authRequired = document.getElementById('auth-required');
const urlInput = document.getElementById('url-input');
const titleInput = document.getElementById('title-input');
const commentInput = document.getElementById('comment-input');
const newTagsInput = document.getElementById('new-tags-input');
const existingTagsEl = document.getElementById('existing-tags');
const mastodonEnabledCheckbox = document.getElementById('mastodon-enabled');
const scrapeButton = document.getElementById('scrape-button');
const scrapeStatus = document.getElementById('scrape-status');
const submitButton = document.getElementById('submit-button');
const submitStatus = document.getElementById('submit-status');
const token = localStorage.getItem('linklogAccessToken');
let availableTags = [];
let selectedTags = new Set();
let currentUser = null;
// Utility function to add status messages
function setStatus(statusEl, message, isError = false) {
statusEl.textContent = message;
statusEl.className = `status ${isError ? 'error' : 'success'}`;
statusEl.classList.remove('hidden');
if (!isError) {
setTimeout(() => statusEl.classList.add('hidden'), 4000);
}
}
// Check authentication
if (!token) {
authRequired.classList.remove('hidden');
entryForm.classList.add('hidden');
return;
}
// Verify token is still valid
fetch('/api/auth/me', { headers: { Authorization: `Bearer ${token}` } })
.then((response) => {
if (!response.ok) throw new Error('Not authenticated');
return response.json();
})
.then((user) => {
currentUser = user;
entryForm.classList.remove('hidden');
loadTags();
})
.catch(() => {
localStorage.removeItem('linklogAccessToken');
authRequired.classList.remove('hidden');
entryForm.classList.add('hidden');
});
// Load available tags
async function loadTags() {
try {
const response = await fetch('/api/tags');
if (!response.ok) throw new Error('Could not load tags');
availableTags = await response.json();
renderTags();
} catch (error) {
console.error('Error loading tags:', error);
}
}
// Render tag checkboxes
function renderTags() {
existingTagsEl.innerHTML = '';
availableTags.forEach((tag) => {
const label = document.createElement('label');
label.className = 'tag-checkbox';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = tag;
checkbox.checked = selectedTags.has(tag);
checkbox.addEventListener('change', () => {
if (checkbox.checked) {
selectedTags.add(tag);
} else {
selectedTags.delete(tag);
}
});
label.appendChild(checkbox);
label.append(` ${tag}`);
existingTagsEl.appendChild(label);
});
}
// Scrape URL for title
scrapeButton.addEventListener('click', async (e) => {
e.preventDefault();
const url = urlInput.value.trim();
if (!url) {
setStatus(scrapeStatus, 'Please enter a URL', true);
return;
}
scrapeButton.disabled = true;
setStatus(scrapeStatus, 'Scraping...', false);
try {
const response = await fetch(`/api/scrape?url=${encodeURIComponent(url)}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) {
if (response.status === 401) {
localStorage.removeItem('linklogAccessToken');
location.reload();
return;
}
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.title) {
titleInput.value = data.title;
setStatus(scrapeStatus, 'Title loaded!', false);
} else {
setStatus(scrapeStatus, 'No title found', true);
}
} catch (error) {
console.error('Scrape error:', error);
setStatus(scrapeStatus, `Error: ${error.message}`, true);
} finally {
scrapeButton.disabled = false;
}
});
// Handle form submission
entryForm.addEventListener('submit', async (e) => {
e.preventDefault();
const url = urlInput.value.trim();
const title = titleInput.value.trim();
const comment = commentInput.value.trim();
const newTags = newTagsInput.value.trim();
if (!url || !title) {
setStatus(submitStatus, 'URL and title are required', true);
return;
}
// Combine selected tags and new tags
const tags = Array.from(selectedTags);
if (newTags) {
const newTagsList = newTags
.split(',')
.map((t) => t.trim())
.filter((t) => t);
tags.push(...newTagsList);
}
submitButton.disabled = true;
setStatus(submitStatus, 'Saving...', false);
try {
const response = await fetch('/api/links', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
title,
url,
comment,
tags,
}),
});
if (!response.ok) {
if (response.status === 401) {
localStorage.removeItem('linklogAccessToken');
location.reload();
return;
}
const error = await response.json().catch(() => ({}));
throw new Error(error.detail || `HTTP ${response.status}`);
}
const data = await response.json();
setStatus(submitStatus, `Link saved to LinkLog${data.duplicate ? ' (updated)' : ''}!`, false);
// Redirect to user page after 1 second
if (currentUser) {
setTimeout(() => {
window.location.href = `/${encodeURIComponent(currentUser.username)}/`;
}, 1000);
}
} catch (error) {
console.error('Submit error:', error);
setStatus(submitStatus, `Error: ${error.message}`, true);
} finally {
submitButton.disabled = false;
}
});
})();
+325 -11
View File
@@ -223,17 +223,6 @@ body::selection {
position: relative; position: relative;
} }
.theme-picker {
width: auto;
min-width: 132px;
padding: 8px 10px;
border: 1px solid var(--surface-2);
border-radius: 7px;
background: var(--surface-0);
color: var(--text);
font: inherit;
}
.menu-toggle { .menu-toggle {
min-width: 0; min-width: 0;
padding: 10px 13px; padding: 10px 13px;
@@ -248,6 +237,31 @@ body::selection {
font-size: 1.1em; font-size: 1.1em;
} }
.new-entry-button {
padding: 10px 13px;
border: 1px solid var(--mauve);
border-radius: 7px;
background: var(--mauve);
color: var(--crust);
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
}
.new-entry-button:hover {
background: var(--lavender);
border-color: var(--lavender);
}
.new-entry-button a {
color: inherit;
text-decoration: none;
}
.new-entry-button.hidden {
display: none;
}
.auth-menu { .auth-menu {
position: absolute; position: absolute;
z-index: 30; z-index: 30;
@@ -314,6 +328,86 @@ body::selection {
color: var(--red); color: var(--red);
} }
.theme-submenu-container {
border-top: 1px solid var(--border);
margin-top: 6px;
padding-top: 6px;
}
.theme-submenu-container.hidden {
display: none;
}
.submenu-title {
display: block;
width: 100%;
min-width: 0;
padding: 9px 10px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--text);
text-align: left;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
}
.submenu-title:hover {
background: var(--surface-1);
color: var(--lavender);
}
.submenu-title::after {
content: ' ▼';
font-size: 0.7em;
opacity: 0.7;
}
.submenu-title[aria-expanded='true']::after {
transform: rotate(-180deg);
display: inline-block;
}
.submenu-options {
display: flex;
flex-direction: column;
gap: 4px;
padding: 4px 8px;
margin-top: 4px;
border-radius: 6px;
background: var(--surface-1);
}
.submenu-options.hidden {
display: none;
}
.theme-option {
padding: 8px 10px;
border: 1px solid var(--border);
border-radius: 5px;
background: transparent;
color: var(--text);
text-align: left;
cursor: pointer;
transition: all 0.2s ease;
font-size: 0.9rem;
}
.theme-option:hover {
background: var(--surface-0);
border-color: var(--lavender);
color: var(--lavender);
}
.theme-option.active {
background: var(--mauve);
border-color: var(--mauve);
color: var(--crust);
font-weight: 600;
}
main.container { main.container {
position: relative; position: relative;
z-index: 1; z-index: 1;
@@ -768,6 +862,221 @@ button:disabled {
margin-top: 14px; margin-top: 14px;
} }
/* Entry form styling */
.entry-form {
max-width: 600px;
margin: 0 auto;
display: grid;
gap: 24px;
}
.entry-form.hidden,
#auth-required.hidden {
display: none;
}
#auth-required {
max-width: 600px;
margin: 40px auto;
padding: 16px;
background: var(--surface-0);
border: 1px solid var(--border);
border-radius: 12px;
border-left: 4px solid var(--red);
}
#auth-required p {
margin: 0;
color: var(--text);
}
#auth-required a {
color: var(--lavender);
text-decoration: underline;
}
#auth-required a:hover {
color: var(--mauve);
}
.form-section {
display: grid;
gap: 8px;
}
.form-section label {
display: grid;
gap: 6px;
}
.form-section > legend {
font-weight: 600;
color: var(--text);
font-size: 0.95rem;
margin: 0;
padding: 0;
}
.form-section input[type='url'],
.form-section input[type='text'],
.form-section textarea {
padding: 10px 12px;
background: var(--mantle);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
font-family: inherit;
font-size: 0.95rem;
line-height: 1.4;
}
.form-section textarea {
resize: vertical;
min-height: 100px;
}
.form-section input[type='url']:focus,
.form-section input[type='text']:focus,
.form-section textarea:focus {
outline: none;
border-color: var(--lavender);
box-shadow: 0 0 0 3px rgba(180, 190, 254, 0.1);
}
.tag-options {
display: flex;
flex-wrap: wrap;
gap: 8px 10px;
padding: 12px;
background: var(--mantle);
border: 1px solid var(--border);
border-radius: 8px;
}
.tag-checkbox {
display: flex;
align-items: center;
gap: 6px;
color: var(--subtext);
font-size: 0.9rem;
cursor: pointer;
user-select: none;
}
.tag-checkbox input {
cursor: pointer;
}
.form-section fieldset {
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px;
margin: 0;
}
.form-section fieldset legend {
margin: 0;
padding: 0 6px;
}
.form-section fieldset label {
gap: 6px;
}
.form-section fieldset input[type='text'] {
width: 100%;
}
.form-section fieldset input[type='checkbox'] {
width: auto;
margin-right: 6px;
cursor: pointer;
}
.form-actions {
display: grid;
grid-template-columns: 1fr auto;
gap: 12px;
}
.form-actions button,
.form-actions a {
padding: 10px 16px;
border-radius: 8px;
font-weight: 600;
text-align: center;
text-decoration: none;
cursor: pointer;
transition: all 0.2s ease;
}
.form-actions button[type='submit'],
#scrape-button:not(:disabled) {
background: var(--mauve);
border: 1px solid var(--mauve);
color: var(--crust);
}
.form-actions button[type='submit']:hover:not(:disabled) {
background: var(--lavender);
border-color: var(--lavender);
}
.form-actions button[type='submit']:disabled {
opacity: 0.6;
cursor: not-allowed;
}
#scrape-button {
background: var(--surface-1);
border: 1px solid var(--border);
color: var(--text);
}
#scrape-button:not(:disabled):hover {
background: var(--surface-2);
border-color: var(--text);
}
#scrape-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.form-actions a {
background: var(--surface-1);
border: 1px solid var(--border);
color: var(--text);
}
.form-actions a:hover {
background: var(--surface-2);
border-color: var(--text);
}
.status {
padding: 12px;
border-radius: 8px;
font-size: 0.9rem;
line-height: 1.4;
}
.status.success {
background: rgba(131, 165, 152, 0.2);
border: 1px solid var(--teal);
color: var(--teal);
}
.status.error {
background: rgba(243, 139, 168, 0.2);
border: 1px solid var(--red);
color: var(--red);
}
.status.hidden {
display: none;
}
@media (max-width: 600px) { @media (max-width: 600px) {
.container { .container {
padding: 0 14px; padding: 0 14px;
@@ -815,6 +1124,11 @@ button:disabled {
font-size: 0.9rem; font-size: 0.9rem;
} }
.new-entry-button {
padding: 8px 11px;
font-size: 0.9rem;
}
.logout-button { .logout-button {
font-size: 0.9rem; font-size: 0.9rem;
} }
+32 -11
View File
@@ -11,18 +11,39 @@ async function loadAvailableThemes() {
? localStorage.getItem(themePreference) ? localStorage.getItem(themePreference)
: themes[0]?.id; : themes[0]?.id;
if (selected) document.documentElement.dataset.theme = selected; if (selected) document.documentElement.dataset.theme = selected;
const headerActions = document.querySelector('.header-actions');
if (!headerActions || !themes.length) return; const submenuContainer = document.querySelector('#theme-submenu-container');
const picker = document.createElement('select'); const themeOptions = document.querySelector('#theme-options');
picker.className = 'theme-picker'; const submenuTitle = document.querySelector('.submenu-title');
picker.setAttribute('aria-label', 'Theme');
picker.replaceChildren(...themes.map((theme) => new Option(theme.label, theme.id))); if (!submenuContainer || !themeOptions || !themes.length) return;
picker.value = selected || themes[0].id;
picker.addEventListener('change', () => { // Show the submenu container
localStorage.setItem(themePreference, picker.value); submenuContainer.classList.remove('hidden');
document.documentElement.dataset.theme = picker.value;
// Create theme buttons
const buttons = themes.map((theme) => {
const button = document.createElement('button');
button.type = 'button';
button.className = 'theme-option';
button.dataset.themeId = theme.id;
button.textContent = theme.label;
if (theme.id === selected) {
button.classList.add('active');
}
button.addEventListener('click', () => {
localStorage.setItem(themePreference, theme.id);
document.documentElement.dataset.theme = theme.id;
// Update active state
document.querySelectorAll('.theme-option').forEach((btn) => {
btn.classList.remove('active');
});
button.classList.add('active');
});
return button;
}); });
headerActions.prepend(picker);
themeOptions.replaceChildren(...buttons);
} }
loadAvailableThemes(); loadAvailableThemes();
+12 -1
View File
@@ -18,6 +18,7 @@
<p>A quiet place for the links worth keeping.</p> <p>A quiet place for the links worth keeping.</p>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
<a id="auth-home-link" href="/">Home</a> <a id="auth-home-link" href="/">Home</a>
@@ -28,6 +29,10 @@
<a id="auth-admin-link" class="hidden" href="/admin">Admin</a> <a id="auth-admin-link" class="hidden" href="/admin">Admin</a>
<div id="auth-session" class="auth-session hidden"><a id="auth-username" class="user-name" href="/"></a></div> <div id="auth-session" class="auth-session hidden"><a id="auth-username" class="user-name" href="/"></a></div>
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button> <button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
<div id="theme-submenu-container" class="theme-submenu-container hidden">
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
<div id="theme-options" class="submenu-options hidden"></div>
</div>
</nav> </nav>
</div> </div>
</div> </div>
@@ -52,8 +57,14 @@
<p>LinkLog is open source software. You can run your own instance, or contribute to the project on <p>LinkLog is open source software. You can run your own instance, or contribute to the project on
<a href="https://git.kolkman.org/olaf/Link-Log">my repository</a>.</p> <a href="https://git.kolkman.org/olaf/Link-Log">my repository</a>.</p>
</section> </section>
<section class="link-item">
<h2>Plugin</h2>
<p>Install the Firefox plugin to save links directly from your browser. <a
href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi"
download>Download and install the Plugin</a>.</p>
</section>
</main> </main>
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer> <footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=3"></script> <script src="/static/logout.js?v=3"></script>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
+6 -1
View File
@@ -18,6 +18,7 @@
<p>Manage users and plugin configuration</p> <p>Manage users and plugin configuration</p>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
<a id="auth-home-link" href="/">Home</a> <a id="auth-home-link" href="/">Home</a>
@@ -30,6 +31,10 @@
<a id="auth-username" class="user-name" href="/"></a> <a id="auth-username" class="user-name" href="/"></a>
</div> </div>
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button> <button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
<div id="theme-submenu-container" class="theme-submenu-container hidden">
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
<div id="theme-options" class="submenu-options hidden"></div>
</div>
</nav> </nav>
</div> </div>
</div> </div>
@@ -115,7 +120,7 @@
</section> </section>
</div> </div>
</main> </main>
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer> <footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=2"></script> <script src="/static/logout.js?v=2"></script>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
+6 -1
View File
@@ -18,6 +18,7 @@
</div> </div>
<div class="header-tools"> <div class="header-tools">
<div class="header-actions"> <div class="header-actions">
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
<a id="auth-home-link" href="/">Home</a> <a id="auth-home-link" href="/">Home</a>
@@ -30,6 +31,10 @@
<a id="auth-username" class="user-name" href="/"></a> <a id="auth-username" class="user-name" href="/"></a>
</div> </div>
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button> <button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
<div id="theme-submenu-container" class="theme-submenu-container hidden">
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
<div id="theme-options" class="submenu-options hidden"></div>
</div>
</nav> </nav>
</div> </div>
<section class="toolbar"> <section class="toolbar">
@@ -76,7 +81,7 @@
{% endif %} {% endif %}
<section id="feed" class="feed" aria-live="polite"></section> <section id="feed" class="feed" aria-live="polite"></section>
</main> </main>
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer> <footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=3"></script> <script src="/static/logout.js?v=3"></script>
+6 -1
View File
@@ -18,6 +18,7 @@
<p>Manage your link labels</p> <p>Manage your link labels</p>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
<a id="auth-home-link" href="/">Home</a> <a id="auth-home-link" href="/">Home</a>
@@ -28,6 +29,10 @@
<a id="auth-admin-link" class="hidden" href="/admin">Admin</a> <a id="auth-admin-link" class="hidden" href="/admin">Admin</a>
<div id="auth-session" class="auth-session hidden"><a id="auth-username" class="user-name" href="/"></a></div> <div id="auth-session" class="auth-session hidden"><a id="auth-username" class="user-name" href="/"></a></div>
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button> <button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
<div id="theme-submenu-container" class="theme-submenu-container hidden">
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
<div id="theme-options" class="submenu-options hidden"></div>
</div>
</nav> </nav>
</div> </div>
</div> </div>
@@ -44,7 +49,7 @@
<div id="label-list" class="plugin-list"></div> <div id="label-list" class="plugin-list"></div>
</section> </section>
</main> </main>
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer> <footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=3"></script> <script src="/static/logout.js?v=3"></script>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
+6 -1
View File
@@ -17,6 +17,7 @@
<p>Access your LinkLog settings</p> <p>Access your LinkLog settings</p>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
<a id="auth-home-link" href="/">Home</a> <a id="auth-home-link" href="/">Home</a>
@@ -29,6 +30,10 @@
<a id="auth-username" class="user-name" href="/"></a> <a id="auth-username" class="user-name" href="/"></a>
</div> </div>
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button> <button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
<div id="theme-submenu-container" class="theme-submenu-container hidden">
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
<div id="theme-options" class="submenu-options hidden"></div>
</div>
</nav> </nav>
</div> </div>
</div> </div>
@@ -55,7 +60,7 @@
</form> </form>
</section> </section>
</main> </main>
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer> <footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=3"></script> <script src="/static/logout.js?v=3"></script>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
+107
View File
@@ -0,0 +1,107 @@
<!DOCTYPE html>
<!-- Copyright © 2026 Olaf Kolkman -->
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
<html lang="en">
<head>
<meta charset="utf-8" />
<title>New Entry - LinkLog</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/static/style.css" />
</head>
<body>
<header class="site-header">
<div class="container">
<div class="header-row">
<div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" />
<p>New Entry</p>
</div>
<div class="header-tools">
<div class="header-actions">
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
<a id="auth-home-link" href="/">Home</a>
<a id="auth-about-link" href="/about">About</a>
<a id="auth-login-button" href="/login">Sign in</a>
<a id="auth-profile-link" class="hidden" href="/profile">Profile</a>
<a id="auth-labels-link" class="hidden" href="/labels">Labels</a>
<a id="auth-admin-link" class="hidden" href="/admin">Admin</a>
<div id="auth-session" class="auth-session hidden">
<a id="auth-username" class="user-name" href="/"></a>
</div>
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
<div id="theme-submenu-container" class="theme-submenu-container hidden">
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
<div id="theme-options" class="submenu-options hidden"></div>
</div>
</nav>
</div>
</div>
</div>
</div>
</header>
<main class="container">
<div id="auth-required" class="error-message hidden">
<p>You must be signed in to create a new entry. <a href="/login">Sign in here</a>.</p>
</div>
<form id="entry-form" class="entry-form hidden">
<div class="form-section">
<label>
<span>URL</span>
<input id="url-input" name="url" type="url" required placeholder="https://example.com" />
</label>
<button id="scrape-button" class="secondary" type="button">Auto-fill Title</button>
<div id="scrape-status" class="status hidden" aria-live="polite"></div>
</div>
<div class="form-section">
<label>
<span>Title</span>
<input id="title-input" name="title" type="text" required />
</label>
</div>
<div class="form-section">
<label>
<span>Comment</span>
<textarea id="comment-input" name="comment" rows="4" placeholder="Optional comment about this link"></textarea>
</label>
</div>
<fieldset class="form-section">
<legend>Tags</legend>
<div id="existing-tags" class="tag-options"></div>
<label>
<span>Add new tags</span>
<input id="new-tags-input" type="text" pattern="#[^, ]+(,\s*#[^, ]+)*" placeholder="#tag1, #tag2" />
</label>
</fieldset>
<fieldset class="form-section">
<legend>Mastodon Publishing</legend>
<label>
<input id="mastodon-enabled" type="checkbox" />
Post to Mastodon (if configured)
</label>
</fieldset>
<div class="form-actions">
<button id="submit-button" type="submit">Save Entry</button>
<a href="/" class="secondary button">Cancel</a>
</div>
<div id="submit-status" class="status hidden" aria-live="polite"></div>
</form>
</main>
<footer class="site-footer">
<span>Copyright © 2026 Olaf Kolkman</span> · <a href="https://git.kolkman.org/olaf/Link-Log">Repository</a>
</footer>
<script src="/static/auth-header.js"></script>
<script src="/static/new-entry.js"></script>
</body>
</html>
+1 -1
View File
@@ -42,7 +42,7 @@
</form> </form>
</section> </section>
</main> </main>
<footer class="site-footer">Copyright © 2026 Olaf Kolkman</footer> <footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman</footer>
<script src="/static/theme.js?v=1"></script> <script src="/static/theme.js?v=1"></script>
<script src="/static/setup.js"></script> <script src="/static/setup.js"></script>
</body> </body>
+7 -1
View File
@@ -19,6 +19,7 @@
<h1>Profile</h1> <h1>Profile</h1>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
<a id="auth-home-link" href="/">Home</a> <a id="auth-home-link" href="/">Home</a>
@@ -31,6 +32,10 @@
<a id="auth-username" class="user-name" href="/"></a> <a id="auth-username" class="user-name" href="/"></a>
</div> </div>
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button> <button id="logout-button" class="logout-button hidden" type="button">Sign out</button>
<div id="theme-submenu-container" class="theme-submenu-container hidden">
<button type="button" class="submenu-title" aria-expanded="false" aria-controls="theme-options">Themes</button>
<div id="theme-options" class="submenu-options hidden"></div>
</div>
</nav> </nav>
</div> </div>
</div> </div>
@@ -59,6 +64,7 @@
</label> </label>
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" /> <img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" />
<button type="submit">Save profile</button> <button type="submit">Save profile</button>
<p>If you have not downloaded the plugin yet, <a href="https://git.kolkman.org/olaf/Link-Log/raw/branch/main/XPI/signed/LinkLog-0.1.0.xpi" download>find it here</a>.</p>
<p id="profile-status" class="status" role="status"></p> <p id="profile-status" class="status" role="status"></p>
</form> </form>
</section> </section>
@@ -144,7 +150,7 @@
</form> </form>
</section> </section>
</main> </main>
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a <footer class="site-footer">LinkLog Version {{ app_version }}. Copyright © 2026 Olaf Kolkman · <a
href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer> href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer>
<script src="/static/auth-header.js?v=3"></script> <script src="/static/auth-header.js?v=3"></script>
<script src="/static/logout.js?v=2"></script> <script src="/static/logout.js?v=2"></script>
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"version": "0.1.0" "version": "0.1.1"
} }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

+42 -30
View File
@@ -9,61 +9,73 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
MANIFEST_PATH = ROOT / 'webextension' / 'manifest.json'
FRONTEND_VERSION_PATH = ROOT / 'frontend' / 'version.json'
SETTINGS_PATH = ROOT / 'backend' / 'app' / 'core' / 'config.py' SETTINGS_PATH = ROOT / 'backend' / 'app' / 'core' / 'config.py'
UPDATES_PATH = ROOT / 'webextension' / 'updates.json'
SIGNED_DIR = ROOT / 'XPI' / 'signed' SIGNED_DIR = ROOT / 'XPI' / 'signed'
MANIFEST_PATH = ROOT / 'webextension' / 'manifest.json'
VERSION_RE = re.compile(r'\d+\.\d+\.\d+')
def fail(message: str) -> None: def fail(message: str) -> None:
raise SystemExit(f'release validation failed: {message}') raise SystemExit(f'release validation failed: {message}')
def version_key(version: str) -> tuple[int, int, int]:
return tuple(int(part) for part in version.split('.'))
def find_latest_signed_xpi() -> tuple[str, Path]:
candidates = []
for xpi_path in SIGNED_DIR.glob('LinkLog-*.xpi'):
match = re.fullmatch(r'LinkLog-(\d+\.\d+\.\d+)\.xpi', xpi_path.name)
if match:
candidates.append((match.group(1), xpi_path))
if not candidates:
fail(f'no signed plugin artifacts found in {SIGNED_DIR.relative_to(ROOT)}')
return max(candidates, key=lambda candidate: version_key(candidate[0]))
def main() -> None: def main() -> None:
manifest = json.loads(MANIFEST_PATH.read_text())
extension_version = manifest.get('version')
if not isinstance(extension_version, str) or not re.fullmatch(r'\d+\.\d+\.\d+', extension_version):
fail('webextension/manifest.json has no valid three-part version')
frontend_version = json.loads(FRONTEND_VERSION_PATH.read_text()).get('version')
if frontend_version != extension_version:
fail(f'frontend version {frontend_version} does not match extension version {extension_version}')
gecko_settings = manifest.get('browser_specific_settings', {}).get('gecko', {})
data_permissions = gecko_settings.get('data_collection_permissions')
if data_permissions != {'required': ['websiteActivity'], 'optional': []}:
fail('Firefox data_collection_permissions must require websiteActivity and have no optional categories')
settings = SETTINGS_PATH.read_text() settings = SETTINGS_PATH.read_text()
match = re.search(r"version: str = os\.getenv\('LINKLOG_VERSION', '([^']+)'\)", settings) match = re.search(r"version: str = os\.getenv\('LINKLOG_VERSION', '([^']+)'\)", settings)
if not match: if not match:
fail('backend version default could not be found') fail('backend version default could not be found')
backend_version = match.group(1) backend_version = match.group(1)
if backend_version != extension_version: if not VERSION_RE.fullmatch(backend_version):
fail(f'backend version {backend_version} does not match extension version {extension_version}') fail(f'backend version {backend_version} is not a valid three-part version')
xpi_path = SIGNED_DIR / f'LinkLog-{extension_version}.xpi' extension_version, xpi_path = find_latest_signed_xpi()
if not xpi_path.is_file(): source_manifest = json.loads(MANIFEST_PATH.read_text())
fail(f'missing manually signed artifact: {xpi_path.relative_to(ROOT)}') if source_manifest.get('version') != extension_version:
fail(
f'webextension/manifest.json version {source_manifest.get("version")!r} does not match '
f'the latest signed XPI version {extension_version!r}'
)
with zipfile.ZipFile(xpi_path) as archive: with zipfile.ZipFile(xpi_path) as archive:
try: try:
packaged_manifest = json.loads(archive.read('manifest.json')) packaged_manifest = json.loads(archive.read('manifest.json'))
except KeyError: except KeyError:
fail('signed XPI does not contain manifest.json') fail('signed XPI does not contain manifest.json')
if packaged_manifest.get('version') != extension_version: if packaged_manifest.get('version') != extension_version:
fail('signed XPI manifest version does not match webextension/manifest.json') fail('signed XPI manifest version does not match its filename')
gecko_settings = packaged_manifest.get('browser_specific_settings', {}).get('gecko', {})
data_permissions = gecko_settings.get('data_collection_permissions')
if data_permissions != {'required': ['websiteActivity'], 'optional': []}:
fail('Firefox data_collection_permissions must require websiteActivity and have no optional categories')
if archive.testzip() is not None: if archive.testzip() is not None:
fail('signed XPI contains a corrupt member') fail('signed XPI contains a corrupt member')
updates = json.loads(UPDATES_PATH.read_text()) signed_xpi = xpi_path.relative_to(ROOT)
addon_id = gecko_settings['id'] if len(sys.argv) == 3 and sys.argv[1] == '--github-output':
update_entries = updates.get('addons', {}).get(addon_id, {}).get('updates', []) with Path(sys.argv[2]).open('a') as output:
if not any(entry.get('version') == extension_version for entry in update_entries): print(f'backend_version={backend_version}', file=output)
fail(f'webextension/updates.json has no update entry for {extension_version}') print(f'plugin_version={extension_version}', file=output)
print(f'signed_xpi={signed_xpi}', file=output)
elif len(sys.argv) != 1:
fail('usage: validate_release.py [--github-output <path>]')
print(f'validated LinkLog release {frontend_version}') print(f'validated LinkLog backend release {backend_version}')
print(f'xpi={xpi_path.relative_to(ROOT)}') print(f'plugin_version={extension_version}')
print(f'signed_xpi={signed_xpi}')
if __name__ == '__main__': if __name__ == '__main__':
+1 -1
View File
@@ -30,7 +30,7 @@
"browser_specific_settings": { "browser_specific_settings": {
"gecko": { "gecko": {
"id": "linklog@kolkman.org", "id": "linklog@kolkman.org",
"strict_min_version": "112.0", "strict_min_version": "142.0",
"data_collection_permissions": { "data_collection_permissions": {
"required": ["websiteActivity"], "required": ["websiteActivity"],
"optional": [] "optional": []
+1 -2
View File
@@ -186,8 +186,7 @@ async function signOut() {
if (sessionSettings.accessToken && settings.backendUrl && await hasBackendPermission(backendUrl)) { if (sessionSettings.accessToken && settings.backendUrl && await hasBackendPermission(backendUrl)) {
await fetch(`${backendUrl}/api/auth/logout`, { await fetch(`${backendUrl}/api/auth/logout`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: {Authorization: `Bearer ${sessionSettings.accessToken}`},
body: JSON.stringify({ token: sessionSettings.accessToken }),
}).catch(() => undefined); }).catch(() => undefined);
} }
await clearSession(); await clearSession();