89 Commits
Author SHA1 Message Date
Olaf b89d12769c Privacy assesment by AI.
Build LinkLog Development Image / development-image (push) Successful in 28s
2026-09-30 09:08:52 +02:00
Olaf 370a91b23b Privacy review, on request by a colleague
Build LinkLog Development Image / development-image (push) Successful in 43s
2026-09-15 21:09:52 +02:00
olaf 24c4753093 Profile tweaks
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-09-07 15:04:05 +02:00
olaf 17c72f89bf Comment area width
Build LinkLog Development Image / development-image (push) Successful in 29s
2026-09-07 12:41:37 +02:00
Olaf Kolkman a372b9dcc4 signed update - part 2
Build LinkLog Development Image / development-image (push) Successful in 10s
Release LinkLog / release (push) Successful in 9s
2026-09-06 11:02:48 +02:00
Olaf Kolkman 77dcf5c9bd Signed 0.3.0.xpi 2026-09-06 11:02:24 +02:00
olaf a6db9f1566 toolbar order
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-09-06 10:58:55 +02:00
olaf 0700967c30 Re-ran make xpi
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-09-06 10:50:26 +02:00
olaf 0e04c583a6 Character count in firefox plugin
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-09-06 10:48:07 +02:00
olaf 443aff8323 Unenforced character count in frontend
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-09-06 10:20:25 +02:00
olaf 71f4451b34 Pagination added and search and filtering moved to backend
Build LinkLog Development Image / development-image (push) Successful in 22s
2026-09-06 10:01:09 +02:00
olaf 9c0416f4bb Added one-off seed_demo_data.py for test functionality 2026-09-06 09:07:48 +02:00
olaf dff374649c timestamp assertion fixed in test 2026-09-06 08:48:00 +02:00
olaf bffd647a3e Toolbar layout fixed
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-09-05 08:45:39 +02:00
olaf 6ff90aae9a Rudimentary search
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-09-05 08:31:23 +02:00
olaf 48c60e00a2 Document the Database scheme
Build LinkLog Development Image / development-image (push) Successful in 24s
2026-09-05 08:05:44 +02:00
olaf 495d5c3907 Vibe generated documentation
Build LinkLog Development Image / development-image (push) Successful in 38s
2026-09-04 16:10:34 +02:00
olaf 4bf2da218c UTC indication
Build LinkLog Development Image / development-image (push) Successful in 14s
2026-08-30 22:10:53 +02:00
olaf 3891d0deb2 VIBE log updates
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-08-30 21:32:05 +02:00
olaf 5ff947d435 From line changed to Logged on <date> from
Build LinkLog Development Image / development-image (push) Successful in 12s
2026-08-30 21:25:15 +02:00
Olaf 1c307fac94 Vibe logging skill added - in order to not reinvent the wheel
Build LinkLog Development Image / development-image (push) Successful in 22s
2026-08-30 10:48:22 +02:00
olaf 381930c23f Filtering fixed
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-08-28 11:14:11 +02:00
Olaf 74b2c400c6 Fix release hash validation on older Python
Release LinkLog / release (push) Successful in 9s
Build LinkLog Development Image / development-image (push) Successful in 9s
2026-08-28 10:44:12 +02:00
Olaf 9bf9c94dd6 Versioning consistency and bump both the XPI and backend to version 0.2.0
Build LinkLog Development Image / development-image (push) Successful in 11s
Release LinkLog / release (push) Failing after 2s
2026-08-28 10:38:27 +02:00
olaf 5696c89dee Plugin follows duplicate behavior behavior of new-entry 2026-08-28 09:37:14 +02:00
olaf 50d61371e1 New Entry page improvements on link detection 2026-08-28 09:04:24 +02:00
olaf cf83c32b25 Fonts served via server
Build LinkLog Development Image / development-image (push) Successful in 22s
2026-08-28 08:19:43 +02:00
olaf 7bd64b870c Tried to fix a broke filter.
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-27 22:54:22 +02:00
olaf 9494d2b119 Red theme and regression 2026-08-27 22:22:41 +02:00
olaf 3661d0b4b7 Logo links to home page 2026-08-27 22:14:32 +02:00
olaf d433a305f5 Fixed mastodon checkbox on new entry page 2026-08-27 22:08:30 +02:00
olaf 1c2d1b71ff tag placement in new-entry page 2026-08-27 21:45:38 +02:00
olaf de916d2fc7 Eyecandy on admin page and fix of functionality on that page
Build LinkLog Development Image / development-image (push) Successful in 11s
2026-08-27 21:16:11 +02:00
olaf 89f9be5e72 Label edit functionality added
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-27 20:38:02 +02:00
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
olaf b03a241be2 Mail looks 'improved'
Build LinkLog Development Image / development-image (push) Successful in 19s
2026-08-26 20:27:54 +02:00
olaf 314959c7bf Audit trail 2026-08-26 19:52:22 +02:00
olaf ed76b35600 SA-010 Avatar validation 2026-08-26 18:35:12 +02:00
olaf b971d2ed97 Test fix 2026-08-26 18:27:32 +02:00
olaf 580c2a4257 OTP security hardened 2026-08-26 18:24:02 +02:00
olaf c3c3c8e1a6 SA-007 trivial docker compose 2026-08-26 18:20:04 +02:00
olaf 4049a197b9 token usage tightened with revocation 2026-08-26 18:17:55 +02:00
olaf 1a24d21d0a normalize Prompt.md
Build LinkLog Development Image / development-image (push) Successful in 9s
2026-08-26 18:03:52 +02:00
olaf 7e9bf81bd1 Reduced permissions in the manifest 2026-08-26 17:59:24 +02:00
olaf 27f26e615a SA-005 addressed by updateing ratelimiting
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-08-26 17:03:32 +02:00
olaf c70850b44d SA-4 SSRF protections implemented. 2026-08-26 16:52:59 +02:00
olaf 3e61302bf6 Addressed SA-3 by encrypting the sqlite content with a .env secret 2026-08-26 16:39:53 +02:00
olaf 94997752b6 disappearing interface after link safe 2026-08-26 16:30:25 +02:00
olaf 01a4ed42bd Update previous links 2026-08-26 16:22:19 +02:00
olaf 6772bf7107 Working logic to redirect to sessions
Build LinkLog Development Image / development-image (push) Successful in 12s
2026-08-26 16:11:11 +02:00
olaf 0287305884 Security advisory 2 addressed 2026-08-26 15:35:10 +02:00
olaf fec7836384 primary email change functionality
Build LinkLog Development Image / development-image (push) Successful in 12s
2026-08-26 15:25:49 +02:00
olaf 079eb146f6 Login now based on email
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-26 15:03:48 +02:00
olaf dd44b380ce Passwords stored salt and some change is password logic 2026-08-26 14:51:40 +02:00
olaf b3383e29a7 normalize user input
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-26 14:35:41 +02:00
olaf d18acf813a webplugin settings defaults 2026-08-26 14:33:11 +02:00
olaf 6f1fbaa5ea Finetuning Plugin behavior when not logged in 2026-08-26 14:25:00 +02:00
olaf f503dbaef2 Remove mastodon posts on delete and OTP 2026-08-26 14:16:29 +02:00
olaf 80a3a3d541 filter and sort moved 2026-08-26 13:58:19 +02:00
olaf 4854eb8df6 eyecandy improvements
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-26 13:46:33 +02:00
olaf 134e463a81 eyecandy 2026-08-26 13:11:10 +02:00
olaf 72a4741cac Added a theme selector 2026-08-26 12:54:38 +02:00
olaf fec4c8def5 email in admin
Build LinkLog Development Image / development-image (push) Successful in 9s
2026-08-26 12:38:38 +02:00
olaf 158bc64268 Added german, french, spanish and dutch locale (Dutch has been verified)
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-08-26 12:16:55 +02:00
olaf 3fdf146498 Added Locales to the webextention
Build LinkLog Development Image / development-image (push) Successful in 9s
2026-08-26 12:14:30 +02:00
olaf f0ae526a96 Link from avatar to user
Build LinkLog Development Image / development-image (push) Successful in 13s
2026-08-26 12:11:12 +02:00
olaf 6651ce8993 Some info on the settings page of the webplugin and mod to style.css
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-26 12:05:21 +02:00
olaf dd450ea3b5 remove chat.json 2026-08-26 10:47:52 +02:00
olaf c012f1edfa Makefile fixes
Build LinkLog Development Image / development-image (push) Successful in 8s
2026-08-26 10:42:24 +02:00
olaf c748241291 Some eye-candy changes
Build LinkLog Development Image / development-image (push) Successful in 10s
2026-08-26 10:30:33 +02:00
olaf 95accdf436 Post to mastodon from the profile page for logged in users 2026-08-26 10:20:48 +02:00
olaf 9deb28330a eyecandy and delete 2026-08-26 10:04:23 +02:00
olaf 2e5610555e Format mastodon output 2026-08-26 09:51:28 +02:00
105 changed files with 8938 additions and 683285 deletions
+8 -3
View File
@@ -8,10 +8,11 @@ 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_SECRET_KEY=replace-with-a-long-random-secret LINKLOG_SECRET_KEY=replace-with-a-long-random-secret
LINKLOG_TOKEN_EXPIRY_DAYS=30 LINKLOG_DATA_ENCRYPTION_KEY=generate-with-python-cryptography-fernet-key
LINKLOG_PUBLIC_URL=localhost LINKLOG_TOKEN_EXPIRY_MINUTES=300
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS=30
LINKLOG_PUBLIC_URL=linklog.example.com
LINKLOG_SMTP_HOST= LINKLOG_SMTP_HOST=
LINKLOG_SMTP_PORT=587 LINKLOG_SMTP_PORT=587
LINKLOG_SMTP_USERNAME= LINKLOG_SMTP_USERNAME=
@@ -22,9 +23,13 @@ LINKLOG_EMAIL_VERIFICATION_EXPIRY_HOURS=24
LINKLOG_PASSWORD_RESET_EXPIRY_HOURS=1 LINKLOG_PASSWORD_RESET_EXPIRY_HOURS=1
LINKLOG_MASTODON_CLIENT_NAME=LinkLog LINKLOG_MASTODON_CLIENT_NAME=LinkLog
LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES=10 LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES=10
# Warn on the New Entry page when the assembled post would exceed this many characters (Mastodon's default limit is 500).
LINKLOG_MAX_POST_CHARACTERS=500
LINKLOG_LOG_LEVEL=INFO LINKLOG_LOG_LEVEL=INFO
# Optional comma-separated override. Leave empty to use the built-in list. # Optional comma-separated override. Leave empty to use the built-in list.
LINKLOG_TRACKING_PARAMS= LINKLOG_TRACKING_PARAMS=
# Comma-separated feed page sizes offered to users, first value is the default. Up to 5 values are used.
LINKLOG_FRONTEND_LOADPOSTS=25,100,250
# Keep the default path when using the named linklog_data volume. # Keep the default path when using the named linklog_data volume.
LINKLOG_DATABASE_PATH=/app/backend/data/linklog.db LINKLOG_DATABASE_PATH=/app/backend/data/linklog.db
+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 json; print(json.load(open('frontend/version.json'))['version'])")
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"
@@ -0,0 +1,27 @@
---
name: changelog-maintenance
description: "Use when: completing LinkLog work that changes user-facing behavior (features, fixes, UI/UX, configuration, API responses). Update CHANGELOG.MD's current unreleased version section, and bump frontend/version.json when the user explicitly requests a version bump or release."
---
# LinkLog Changelog Maintenance
## Purpose
`CHANGELOG.MD` is LinkLog's user-facing history of releases. Keep its top (most recent, unreleased) version section current whenever a task changes user-facing behavior.
## Workflow
1. Complete the user's requested work and its relevant validation first.
2. Decide if the change is changelog-worthy (see Scope below). Skip internal-only changes.
3. Open `CHANGELOG.MD` and find the topmost `## Version vX.Y.Z` section — this is the current unreleased version being accumulated. Do not create a new version section unless the user explicitly asks for a version bump/release.
4. Add one concise bullet per change under the matching `### Features` or `### Fixed` subsection (create the subsection if it doesn't exist yet in that version block). Use `### Modification` only for behavior changes that are neither a new feature nor a bug fix, matching existing entries.
5. Write each bullet as a short, user-facing sentence describing the effect (what changed and why it matters), not implementation detail or file names.
6. Do not edit, reorder, or remove bullets from older `## Version` sections. Only append to the current unreleased section.
7. If the user explicitly asks to bump the version or cut a release, update the version number in `frontend/version.json` (valid JSON, e.g. `{"version": "0.3.1"}`) to match the `## Version vX.Y.Z` heading, and start a new top section for subsequent changes.
8. Before finalizing, re-read `CHANGELOG.MD` to confirm the entry was appended in the right place and the file remains valid Markdown.
## Scope
Changelog-worthy: new features, bug fixes, UI/UX changes, configuration options, API/behavior changes visible to users or operators.
Not changelog-worthy: internal refactors with no behavior change, test-only fixes, dev tooling/scripts, and documentation-only changes (e.g. `VIBE/`, `DATABASE.md`, skill files) — unless the user asks otherwise.
+32
View File
@@ -0,0 +1,32 @@
---
name: vibe-logging
description: "Use when: implementing, reviewing, testing, documenting, or otherwise completing LinkLog work that must be captured in the project's VIBE conversation log. Append the visible user request and concise outcome to VIBE/PROMPTS.md and VIBE/CHAT_LOG.md."
---
# LinkLog VIBE Logging
## Purpose
`VIBE/` is LinkLog's append-only, user-visible record of its development conversation. Keep it current whenever a LinkLog task is completed.
## Workflow
1. Complete the user's requested work and its relevant validation first.
2. Append the user-visible request to `VIBE/PROMPTS.md` under a `## YYYY-MM-DD` heading. Reuse today's heading when it already exists; otherwise add it at the end.
3. Append a matching entry to `VIBE/CHAT_LOG.md`:
```markdown
### User
<the visible user request>
### Assistant outcome
<a concise statement of the completed work and meaningful validation>
```
4. Do not edit, reorder, summarize, or remove earlier VIBE records. Only append.
5. Exclude system prompts, developer instructions, environment details, private tool use, credentials, and internal reasoning.
6. Before finalizing, verify both VIBE files include the exchange and that the outcome accurately reflects the completed work.
## Scope
Use this skill for visible LinkLog development interactions. The VIBE record should describe what the user asked and what was delivered, not an internal transcript.
+69
View File
@@ -0,0 +1,69 @@
# Changelog
## Version v0.3.1
### Features
### Fixed
* Made the feed profile summary visually distinct with a contrasting background and slightly smaller text
### Modification
* Made the feed profile summary collapsible under a subdued `:profile` title
## Version v0.3.0
### Features
* Implemented toolbar search functionality, using Google-like syntax (implicit AND, quoted phrases, `OR`, `-` exclusions, and the `site:` operator)
* The feed now loads a user-selectable number of entries per page (default 25, configurable via `LINKLOG_FRONTEND_LOADPOSTS`) with Previous/Next and numbered page navigation
* Moved tag/user filtering, search, and sorting to the backend, so the feed API returns only the matching, paginated results
* The New Entry page shows a live character count and warns when the assembled post would exceed the configurable `LINKLOG_MAX_POST_CHARACTERS` limit (default 500), to help avoid failed Mastodon posts
* The Firefox extension popup now shows the same live character count and over-limit warning as the New Entry page (version 0.3.0)
### Fixed
* Restored tag and user filtering on the feed: the decorative header arc no longer intercepts clicks on the filter dropdowns
* Fixed the toolbar search input being wider than its label at narrow (Firefox) widths
* Swapped the toolbar's search and tag filter positions for a more logical layout
* Mastodon posts now read "Logged on <date> from: <url>" instead of "From: <url>", with the timestamp explicitly marked as UTC
* The feed pagination control no longer overflows the page width and uses a less visually dominant, ghost-button style
## Version v0.2.0
### Features
* Users can edit or delete labels created by themselves on the labels page
* Administrators can edit labels from the admin interface
* Filter label visibility so logged-in users only see default/admin-created labels and their own
* Grandfather tags with unknown ownership as default/admin interface labels
* Ability to minimize settings panels to only show headers in the Admin and Profile interfaces for easy navigation
* Styled settings panel headers with distinct theme accent colors for visual distinction
* Settings panels are collapsed by default when opening the Admin and Profile pages
* Show checked-by-default Mastodon publishing on New Entry only for configured users
* Made every web header logo link to the home page
* Added a high-contrast Red color theme
* Brightened the Red theme surfaces and deepened its crimson accents
* Allow every user to filter the feed using every available tag or label
* Bundle required web fonts during Docker image builds and serve them from LinkLog
* Bundle required web fonts during Docker image builds and serve them from LinkLog
* New Entry page warns when the title/URL combination already exists, matching the browser extension's duplicate warning
* New Entry page warns when an existing link with the same title has a different or missing URL (after tracking parameters are stripped)
* New Entry page auto-fills the title when the URL field loses focus, instead of requiring a manual button press
* Added a "Re-fetch Title" button to manually re-scrape the title after editing the URL
* New Entry duplicate detection and submission strip known tracking parameters (utm_*, gclid, fbclid, etc.) from URLs, mirroring the browser extension
* Browser extension popup now matches the New Entry page: it warns on duplicate title/URL, notes when the stored link has a different URL, and gained a "Re-fetch title" button; bumped extension version to 0.2.0
* Generate Firefox update metadata from every signed XPI with verified SHA-256 archive hashes
### Fixed
* Fixed element ID conflict on the Admin page so Available Themes load correctly
* Positioned new-entry tag checkboxes after their label text
* Kept new-entry tag checkboxes immediately left of their labels at all viewport sizes
* Prevented the new-entry form grid from placing tag checkboxes above their labels
* Kept unconfigured New Entry Mastodon publishing controls hidden
* Restored the home-page header layout, keeping the action controls above the filter toolbar
* Made the tag filter refresh the feed directly when its selection changes
* Cache-busted the feed script to ensure browsers load the responsive tag filter
* Fixed feed initialization so tag filtering does not receive promise results as a selected tag [Still no complete fix]
## 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
+362
View File
@@ -0,0 +1,362 @@
# Database Schema
LinkLog stores its persistent state in SQLite. The schema is defined by the ordered migrations in [`backend/app/database.py`](backend/app/database.py), and the current schema version is **17** (`PRAGMA user_version`). Application startup applies migrations that are newer than the database's current version; existing migration entries must not be changed.
The default database file is `backend/data/linklog.db`. Set `LINKLOG_DATABASE_PATH` to use another path. Foreign-key enforcement is enabled for every application connection.
## Entity-relationship diagram
```mermaid
erDiagram
USERS ||--o{ TOKENS : authenticates
USERS ||--o{ LINKS : owns
USERS ||--o{ USER_PLUGIN_CONFIG : configures
USERS ||--o{ EMAIL_VERIFICATION_TOKENS : verifies
USERS ||--o{ PASSWORD_RESET_TOKENS : resets
USERS ||--o{ MASTODON_OAUTH_STATES : authorizes
USERS ||--o{ USER_EMAIL_ADDRESSES : has
USERS ||--o{ OTP_RECOVERY_CODES : recovers
USERS ||--o{ SECURITY_AUDIT_EVENTS : acts
USERS o|--o{ TAGS : creates
LINKS ||--o{ LINK_TAGS : classified_by
TAGS ||--o{ LINK_TAGS : classifies
USER_EMAIL_ADDRESSES ||--o{ EMAIL_ADDRESS_VERIFICATION_TOKENS : verifies
USERS {
TEXT id PK
TEXT username UK
TEXT email UK
TEXT password_hash
TEXT avatar_url
TEXT bio
INTEGER is_admin
INTEGER email_verified
TEXT otp_secret
INTEGER otp_enabled
TEXT created_at
TEXT updated_at
}
TOKENS {
TEXT id PK
TEXT user_id FK
TEXT token_hash UK
TEXT token_type
TEXT expires_at
TEXT device_id
TEXT token_family_id
TEXT created_at
INTEGER revoked
}
LINKS {
TEXT id PK
TEXT user_id FK
TEXT title
TEXT url
TEXT comment
TEXT timestamp
TEXT created_at
TEXT updated_at
INTEGER is_public
INTEGER mastodon_posted
TEXT mastodon_post_id
TEXT mastodon_posted_at
TEXT mastodon_post_ids
}
TAGS {
TEXT id PK
TEXT name UK
TEXT created_by FK
TEXT created_at
}
LINK_TAGS {
TEXT link_id PK_FK
TEXT tag_id PK_FK
}
PLUGINS {
TEXT id PK
TEXT name UK
TEXT version
INTEGER enabled
TEXT config
TEXT created_at
TEXT updated_at
}
USER_PLUGIN_CONFIG {
TEXT id PK
TEXT user_id FK
TEXT plugin_name
TEXT config
TEXT created_at
TEXT updated_at
}
EMAIL_VERIFICATION_TOKENS {
TEXT id PK
TEXT user_id FK
TEXT token_hash UK
TEXT expires_at
TEXT created_at
}
PASSWORD_RESET_TOKENS {
TEXT id PK
TEXT user_id FK
TEXT token_hash UK
TEXT expires_at
TEXT created_at
}
MASTODON_OAUTH_STATES {
TEXT id PK
TEXT user_id FK
TEXT state_hash UK
TEXT instance
TEXT client_id
TEXT client_secret
TEXT redirect_uri
TEXT expires_at
TEXT created_at
}
USER_EMAIL_ADDRESSES {
TEXT id PK
TEXT user_id FK
TEXT email UK
INTEGER verified
TEXT created_at
TEXT updated_at
}
EMAIL_ADDRESS_VERIFICATION_TOKENS {
TEXT id PK
TEXT email_address_id FK
TEXT token_hash UK
TEXT expires_at
TEXT created_at
}
OTP_RECOVERY_CODES {
TEXT id PK
TEXT user_id FK
TEXT code_hash UK
INTEGER used
TEXT created_at
TEXT used_at
}
SECURITY_AUDIT_EVENTS {
TEXT id PK
TEXT actor_id FK
TEXT action
TEXT target_type
TEXT target_id
TEXT outcome
TEXT details
TEXT created_at
}
APP_SETTINGS {
TEXT name PK
TEXT value
TEXT updated_at
}
```
`UK` means a unique constraint. `PK_FK` means the column participates in the composite primary key and is also a foreign key. SQLite stores timestamps as `TEXT` using its timestamp defaults. Boolean values are stored as `INTEGER` values (`0` or `1`). JSON configuration and Mastodon post ID lists are stored as `TEXT`.
## Tables
### `users`
The user account and profile table.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key, normally a UUID. |
| `username` | TEXT | no | | Unique public username. |
| `email` | TEXT | no | | Unique primary email address. |
| `password_hash` | TEXT | no | | Password hash; plaintext passwords are not stored. |
| `avatar_url` | TEXT | yes | | Stored avatar reference. |
| `bio` | TEXT | yes | | Profile biography. |
| `is_admin` | INTEGER | no | `0` | Administrator flag. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
| `email_verified` | INTEGER | no | `0` | Whether the primary email is verified. |
| `otp_secret` | TEXT | yes | | Encrypted TOTP secret when configured. |
| `otp_enabled` | INTEGER | no | `0` | Whether OTP is required at login. |
### `tokens`
Access and refresh token records. Only token hashes are persisted. `device_id` and `token_family_id` support device binding, rotation, reuse detection, and family revocation.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id`. |
| `token_hash` | TEXT | no | | Unique stored token hash. |
| `token_type` | TEXT | no | `access` | Token category. |
| `expires_at` | TEXT | no | | Expiration timestamp. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `revoked` | INTEGER | no | `0` | Revocation flag. |
| `device_id` | TEXT | yes | | Client/device identifier. |
| `token_family_id` | TEXT | yes | | Refresh-token family identifier. |
### `links`
Saved links and their publication state. `mastodon_post_ids` is a JSON array stored as text; the older `mastodon_post_id` column remains for migration compatibility.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id`. |
| `title` | TEXT | no | | Saved page title. |
| `url` | TEXT | no | | Tracking-cleaned URL. |
| `comment` | TEXT | yes | | User comment. |
| `timestamp` | TEXT | no | | User-supplied or captured link time. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
| `is_public` | INTEGER | no | `1` | Public-feed visibility flag. |
| `mastodon_posted` | INTEGER | no | `0` | Whether publication has occurred. |
| `mastodon_post_id` | TEXT | yes | | Legacy single Mastodon post ID. |
| `mastodon_posted_at` | TEXT | yes | | Publication timestamp. |
| `mastodon_post_ids` | TEXT | yes | | JSON array of publication IDs. |
### `tags` and `link_tags`
`tags` contains reusable labels. `link_tags` is the many-to-many join table between links and tags. Tag names are unique, and `tags.created_by` is nullable so a deleted creator does not remove the tag.
| Table | Columns | Constraints |
| --- | --- | --- |
| `tags` | `id` TEXT, `name` TEXT, `created_at` TEXT, `created_by` TEXT | Primary key `id`; unique `name`; `created_by` references `users.id` with `ON DELETE SET NULL`. |
| `link_tags` | `link_id` TEXT, `tag_id` TEXT | Composite primary key (`link_id`, `tag_id`); both FKs cascade on delete. |
Index: `idx_link_tags_tag_id` supports reverse tag lookups. `idx_tags_created_by` supports creator-based tag management.
### `plugins`
Installed plugin definitions and global plugin configuration. `config` is JSON text.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `name` | TEXT | no | | Unique plugin name. |
| `version` | TEXT | no | | Plugin version. |
| `enabled` | INTEGER | no | `1` | Enablement flag. |
| `config` | TEXT | yes | | Plugin JSON configuration. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
### `user_plugin_config`
Per-user plugin settings. The pair (`user_id`, `plugin_name`) is unique; `plugin_name` is a logical plugin identifier and is not a foreign key to `plugins`.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id`. |
| `plugin_name` | TEXT | no | | Plugin identifier. |
| `config` | TEXT | yes | | User-specific JSON configuration. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
### Verification, reset, and OAuth state tables
These tables store one-time or short-lived workflow state. Token and state values are persisted as hashes where applicable. All user-owned rows are deleted when their user is deleted.
| Table | Important columns | Foreign key / uniqueness |
| --- | --- | --- |
| `email_verification_tokens` | `id`, `user_id`, `token_hash`, `expires_at`, `created_at` | `user_id` -> `users.id` with `ON DELETE CASCADE`; unique `token_hash`. |
| `password_reset_tokens` | `id`, `user_id`, `token_hash`, `expires_at`, `created_at` | `user_id` -> `users.id` with `ON DELETE CASCADE`; unique `token_hash`. |
| `mastodon_oauth_states` | `id`, `user_id`, `state_hash`, `instance`, `client_id`, `client_secret`, `redirect_uri`, `expires_at`, `created_at` | `user_id` -> `users.id` with `ON DELETE CASCADE`; unique `state_hash`. OAuth client secrets are encrypted by the service layer. |
Indexes: `idx_email_verification_tokens_user_id`, `idx_password_reset_tokens_user_id`, and `idx_mastodon_oauth_states_state_hash`.
### `app_settings`
Global key/value settings, including setup and mail configuration. Sensitive values are encrypted by the service layer before storage where required.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `name` | TEXT | no | | Primary key setting name. |
| `value` | TEXT | no | | Setting value. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
### `user_email_addresses`
Verified and pending alternative email addresses. The primary address remains in `users.email`; this table holds additional addresses.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id` with `ON DELETE CASCADE`. |
| `email` | TEXT | no | | Globally unique alternative address. |
| `verified` | INTEGER | no | `0` | Verification flag. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `updated_at` | TEXT | no | `CURRENT_TIMESTAMP` | Last update timestamp. |
Index: `idx_user_email_addresses_user_id`.
### `email_address_verification_tokens`
Verification tokens for alternative addresses.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `email_address_id` | TEXT | no | | FK to `user_email_addresses.id` with `ON DELETE CASCADE`. |
| `token_hash` | TEXT | no | | Unique token hash. |
| `expires_at` | TEXT | no | | Expiration timestamp. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
Index: `idx_email_address_verification_tokens_address_id`.
### `otp_recovery_codes`
One-time recovery codes for users with OTP enabled. Only code hashes are stored.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `user_id` | TEXT | no | | FK to `users.id` with `ON DELETE CASCADE`. |
| `code_hash` | TEXT | no | | Unique recovery-code hash. |
| `used` | INTEGER | no | `0` | Consumption flag. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Creation timestamp. |
| `used_at` | TEXT | yes | | Consumption timestamp. |
Index: `idx_otp_recovery_codes_user_id`.
### `security_audit_events`
Security-relevant audit events. `actor_id` is nullable so an account deletion does not remove the audit record; it becomes `NULL` through `ON DELETE SET NULL`.
| Column | Type | Null | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | TEXT | no | | Primary key. |
| `actor_id` | TEXT | yes | | FK to `users.id`, `ON DELETE SET NULL`. |
| `action` | TEXT | no | | Action name. |
| `target_type` | TEXT | no | | Target entity type. |
| `target_id` | TEXT | yes | | Target identifier. |
| `outcome` | TEXT | no | `success` | Result classification. |
| `details` | TEXT | no | `{}` | JSON text, sanitized by the audit service. |
| `created_at` | TEXT | no | `CURRENT_TIMESTAMP` | Event timestamp. |
Indexes: `idx_security_audit_events_created_at` and `idx_security_audit_events_actor_id`.
## Migration history
| Version | Change |
| ---: | --- |
| 1 | Creates users, tokens, links, plugins, and per-user plugin configuration. |
| 2 | Adds tags and the link/tag join table. |
| 3 | Normalizes tag names with a leading `#`. |
| 4 | Adds tag ownership through `tags.created_by`. |
| 5 | Adds primary-email verification and its token table. |
| 6 | Adds global application settings. |
| 7 | Adds password-reset tokens. |
| 8 | Adds Mastodon OAuth state. |
| 9-10 | Adds Mastodon publication fields and migrates to a JSON list of post IDs. |
| 11 | Adds OTP secret and enablement fields to users. |
| 12 | Adds alternative email addresses and their verification tokens. |
| 13-14 | Temporarily adds then removes pending primary-email-change state. It is not part of the current schema. |
| 15 | Adds device and token-family fields to tokens. |
| 16 | Adds OTP recovery codes. |
| 17 | Adds security audit events. |
To inspect a live database directly:
```sh
sqlite3 backend/data/linklog.db '.schema'
sqlite3 backend/data/linklog.db 'PRAGMA user_version;'
```
+2
View File
@@ -13,6 +13,8 @@ RUN pip install --no-cache-dir -r backend/requirements.txt
COPY backend ./backend COPY backend ./backend
COPY frontend ./frontend COPY frontend ./frontend
COPY scripts/download_fonts.py ./scripts/download_fonts.py
RUN python scripts/download_fonts.py
RUN useradd --create-home --uid 10001 linklog \ RUN useradd --create-home --uid 10001 linklog \
&& mkdir -p /app/backend/data \ && mkdir -p /app/backend/data \
&& chown -R linklog:linklog /app && chown -R linklog:linklog /app
+1 -1
View File
@@ -5,7 +5,7 @@
<svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;"> <svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1,0,0,1,-669.006,-255.89)"> <g transform="matrix(1,0,0,1,-669.006,-255.89)">
<g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)"> <g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)">
<rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(88,91,112);"/> <rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(24, 24, 37);"/>
</g> </g>
<g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)"> <g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)">
<path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/> <path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/>

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

+13 -4
View File
@@ -14,16 +14,25 @@ XPI_FILE := LinkLog-$(EXTENSION_VERSION).xpi
XPI_UNSIGNED_DIR := XPI/unsigned XPI_UNSIGNED_DIR := XPI/unsigned
XPI_SIGNED_DIR := XPI/signed XPI_SIGNED_DIR := XPI/signed
XPI_OUTPUT := $(XPI_UNSIGNED_DIR)/$(XPI_FILE) XPI_OUTPUT := $(XPI_UNSIGNED_DIR)/$(XPI_FILE)
EXTENSION_FILES := manifest.json logo.svg icon-16.png icon-32.png icon-48.png icon-96.png options.css options.html options.js popup.css popup.html popup.js EXTENSION_FILES := manifest.json logo.svg icon-16.png icon-32.png icon-48.png icon-96.png options.css options.html options.js popup.css popup.html popup.js l10n.js _locales/en-US/messages.json _locales/es/messages.json _locales/de/messages.json _locales/fr/messages.json _locales/nl/messages.json
EXTENSION_SOURCES := $(addprefix webextension/,$(EXTENSION_FILES))
XPI_VALIDATOR := scripts/release/validate_xpi.py
UPDATES_GENERATOR := scripts/release/generate_updates.py
.PHONY: all logos xpi check-tools clean-generated .PHONY: all logos xpi update-updates check-tools clean-generated
all: logos all: logos
logos: check-tools $(GENERATED_LOGOS) logos: check-tools $(GENERATED_LOGOS)
xpi: logos
xpi: $(XPI_OUTPUT)
update-updates: $(UPDATES_GENERATOR) webextension/manifest.json
@python3 $(UPDATES_GENERATOR)
$(XPI_OUTPUT): $(EXTENSION_SOURCES) $(GENERATED_LOGOS) $(XPI_VALIDATOR)
@test -n "$(EXTENSION_VERSION)" || { echo "Error: extension version is missing from webextension/manifest.json" >&2; exit 1; } @test -n "$(EXTENSION_VERSION)" || { echo "Error: extension version is missing from webextension/manifest.json" >&2; exit 1; }
@mkdir -p $(XPI_UNSIGNED_DIR) $(XPI_SIGNED_DIR) @mkdir -p $(XPI_UNSIGNED_DIR) $(XPI_SIGNED_DIR)
@rm -f $(XPI_OUTPUT) @rm -f $(XPI_OUTPUT)
+84
View File
@@ -0,0 +1,84 @@
# LinkLog Privacy and Fingerprinting
## Scope
This document describes the privacy and fingerprinting characteristics of the LinkLog web service and Firefox extension as implemented in this repository. It is a source-code assessment, not a legal privacy policy, penetration test, or guarantee about a particular deployment.
## Summary
LinkLog does not contain explicit canvas, WebGL, audio, font, hardware, timezone, analytics, or third-party advertising fingerprinting code. Its main privacy risk is different: LinkLog is designed to publish link activity, and that activity can form a highly distinctive identity profile.
A deployment operator, public visitor, upstream website, Mastodon instance, or network observer may be able to correlate a user through the data and request patterns described below.
## Fingerprinting and Correlation Risks
### Public activity and identity profile
The public feed exposes usernames, profile avatars, bios, exact creation timestamps, titles, original URLs, comments, tags, and whether an entry was posted to Mastodon. Public user enumeration and per-user feed URLs make it easy to collect this information for a particular account.
A sequence of saved links, topics, tags, timestamps, writing style, and referenced websites can be distinctive enough to associate a LinkLog account with activity on other services. This is a high privacy risk for users who expect saved links to be private.
Relevant implementation: `backend/app/api/public.py` and `backend/app/services/link_service.py`.
### URL and query-parameter leakage
LinkLog removes a configurable list of common advertising and analytics parameters, including `utm_*`, `gclid`, `fbclid`, and several vendor-specific parameters. This reduces routine campaign tracking but does not make URLs anonymous.
Other query parameters, path segments, fragments that are retained by the URL cleaner, document identifiers, search terms, access codes, repository names, and user-specific URLs may still identify a person or expose sensitive information. Operators should treat saved URLs, comments, titles, and tags as potentially personal data.
The tracking-parameter list is configured through `LINKLOG_TRACKING_PARAMS`; changing it can also change the URL-normalization behavior of a deployment.
### Firefox extension website activity
The extension uses `activeTab` and requests optional HTTP/HTTPS host permissions for the configured LinkLog backend. When a user saves a page, the extension reads the active page's URL and title and sends the selected data to that backend.
The extension therefore handles website activity by design. A malicious or compromised configured backend could receive the URLs that users submit, and a user can disclose sensitive page URLs by saving them. The extension stores the backend URL and username in local extension storage and keeps session credentials in Firefox session storage.
Relevant implementation: `webextension/manifest.json`, `webextension/popup.js`, and `webextension/options.js`.
### Mastodon and external-service correlation
When enabled, the Mastodon plugin publishes the link title, comment, tags, source URL, and a UTC timestamp to the configured Mastodon instance. Posts include a recognizable `User-Agent: LinkLog/1.0` in server-to-server requests. The resulting public Mastodon post can link the user's LinkLog identity, interests, and activity times to a Mastodon account.
The plugin also makes LinkLog activity observable to the configured Mastodon server, including the instance connection and publication time.
Relevant implementation: `backend/app/services/plugin_manager.py`.
### Server-side URL fetching
The authenticated scrape endpoint fetches a user-provided URL from the LinkLog server to obtain a page title. The target website may see the LinkLog server's network address and request characteristics rather than the user's browser address. This creates server-side attribution and may reveal that a URL was submitted to LinkLog.
### Deployment fingerprinting
A deployment may be distinguishable through its public version, FastAPI/OpenAPI metadata, static asset version parameters, enabled themes, feed page sizes, maximum post length, response headers, health endpoint, public hostname, and extension update metadata. These signals generally identify an installation or software version rather than a person, but they can assist cross-site correlation and targeted attack reconnaissance.
The public configuration endpoint intentionally returns feed page sizes and the maximum post-character limit. The application also exposes `/health`, and the README documents `/docs` and OpenAPI access. Production operators should decide which of these should remain public.
### Authentication and account-state observation
Login throttling, response status differences, verification state, reset-mail behavior, response timing, and refresh-token behavior can reveal limited information about account state to a party able to make repeated requests. Current login errors are mostly generic, but verified and unverified account paths still differ, and failed login handling may trigger password-reset mail for known verified accounts when SMTP is configured.
Client IP handling and throttling are also deployment-sensitive. In a multi-instance deployment, the current SQLite-based limiter does not provide a shared, atomic privacy or abuse-control boundary.
## Recommended Mitigations
Prioritize these changes for privacy-sensitive or public deployments:
1. Make feeds and links private by default, with explicit per-link or per-profile publication controls.
2. Make public user enumeration and profile indexing opt-in, and consider requiring authentication for user lists and private feeds.
3. Strip or allow-list URL query parameters and warn users before saving URLs that contain credentials, access codes, search terms, or other sensitive identifiers.
4. Offer privacy controls for avatars, bios, tags, comments, exact timestamps, and original URLs; consider timestamp coarsening for public entries.
5. Minimize extension permissions and clearly disclose that saving a page sends its URL and title to the configured backend. Keep backend origin permissions restricted to the configured origin.
6. Make Mastodon publication an explicit opt-in, show the complete data that will be published, and allow users to disable URL and timestamp inclusion.
7. Protect or disable `/docs`, `/openapi.json`, detailed health/configuration endpoints, version disclosures, and unnecessary response metadata in production.
8. Use uniform authentication responses and timing where practical, independently throttle password-reset mail, and use a shared atomic rate limiter such as Redis for multi-instance deployments.
9. Configure strict security headers, trusted hosts, HTTPS, log retention, and access controls. Do not log authorization headers, tokens, passwords, OTP values, or secret-bearing URLs.
10. Document retention, deletion, backup, and export behavior for links, profiles, audit records, avatars, tokens, and server logs.
## User Guidance
Do not save private document links, password-reset URLs, invitation URLs, access tokens, or URLs containing sensitive query parameters to a public feed. Review titles, comments, tags, timestamps, and the Mastodon preview before publishing. Use a private deployment and disable Mastodon integration when the link history itself is sensitive.
## Assessment Limits
This document reflects the repository implementation reviewed on 2026-09-16. Reverse-proxy settings, browser privacy settings, database access, server logs, deployment networking, dependencies, and third-party Mastodon behavior can materially change the effective risk. A production deployment should supplement this review with configuration review, dependency and container scanning, authenticated dynamic tests, and a retention/access-control review.
+68 -27
View File
@@ -12,7 +12,8 @@ frontend/ Jinja templates and browser-side assets
webextension/ Firefox Manifest V3 extension webextension/ Firefox Manifest V3 extension
Logo.svg Source logo artwork used by the web and extension interfaces Logo.svg Source logo artwork used by the web and extension interfaces
Dockerfile Backend container image Dockerfile Backend container image
docker-compose.yml App with traefik reverse proxy hooks docker-compose.yml Production app with Traefik reverse proxy hooks
docker-compose.local.yml Local development app with direct port access
REQUIREMENTS.md Product requirements REQUIREMENTS.md Product requirements
VIBE/ Conversation and prompt logs VIBE/ Conversation and prompt logs
``` ```
@@ -27,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.2.0` and is exposed through the FastAPI/OpenAPI metadata. It is read from `frontend/version.json`, the single source of truth shared by the backend and frontend.
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
@@ -47,19 +48,10 @@ On Windows PowerShell, activate the environment with:
.venv\Scripts\Activate.ps1 .venv\Scripts\Activate.ps1
``` ```
The SQLite database is created automatically at `backend/data/linklog.db` when the application starts or when the auth router is imported. The starter accounts are: The SQLite database is created automatically at `backend/data/linklog.db` when the application starts. On a fresh installation, open `/setup` and create the first administrator. No default user accounts are created by the application. The setup page also collects SMTP settings and requires a successful test email before creating the administrator.
| Username | Password | Role |
| --- | --- | --- |
| `alice` | `secret123` | administrator |
| `bob` | `secret123` | standard user |
These credentials are for development only. Change the authentication and seeding design before deploying publicly.
The database schema is versioned with SQLite `PRAGMA user_version`. Application startup applies all pending migrations in order, so updating the application does not require deleting an existing database. New schema changes should be added as a new numbered migration in `backend/app/database.py`; existing migration entries must remain unchanged. The database schema is versioned with SQLite `PRAGMA user_version`. Application startup applies all pending migrations in order, so updating the application does not require deleting an existing database. New schema changes should be added as a new numbered migration in `backend/app/database.py`; existing migration entries must remain unchanged.
The current schema, table reference, migration history, and Mermaid ERD are documented in [DATABASE.md](DATABASE.md).
## Run The Backend ## Run The Backend
Activate the virtual environment, then run uvicorn from the repository root: Activate the virtual environment, then run uvicorn from the repository root:
@@ -78,13 +70,14 @@ 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>
The browser extension defaults to `http://localhost:8000`. The browser extension requires a backend URL to be entered during setup; it does not assume a default server.
The supplied `Logo.svg` is bundled as `frontend/static/logo.svg` for web pages and `webextension/logo.svg` for the Firefox popup and settings page. The supplied `Logo.svg` is bundled as `frontend/static/logo.svg` for web pages and `webextension/logo.svg` for the Firefox popup and settings page.
The visible LinkLog brand text uses the Google Foundry `Asset` font when available, with local fallbacks in the Firefox extension. The visible LinkLog brand text uses the Google Foundry `Asset` font. Docker image builds download and bundle Asset, DM Sans, and Space Grotesk under `/static/fonts`, so the web frontend loads fonts from the LinkLog server rather than Google. The Firefox extension uses its bundled assets and local fallback fonts without requesting Google Fonts.
## Regenerate Logo Assets ## Regenerate Logo Assets
@@ -104,13 +97,25 @@ make xpi
This creates `XPI/unsigned/LinkLog-0.1.0.xpi` from the `webextension/` package and excludes macOS metadata and minified artifacts. The version is read from `webextension/manifest.json`. The `XPI/signed/` directory is reserved for signed release bundles. This creates `XPI/unsigned/LinkLog-0.1.0.xpi` from the `webextension/` package and excludes macOS metadata and minified artifacts. The version is read from `webextension/manifest.json`. The `XPI/signed/` directory is reserved for signed release bundles.
## Docker Deployment
The main `docker-compose.yml` is the production deployment. It does not publish port 8000 on the host; the application is reachable through Traefik on the external `linklog_traefik` network. Set `LINKLOG_PUBLIC_URL` to the DNS hostname served by Traefik. The default is the documentation hostname `linklog.example.com`, which must be replaced for a real deployment.
For local development with direct access, use the separate file:
```sh
docker compose -f docker-compose.local.yml up --build
```
This publishes `${APP_PORT:-8000}` and defaults the application URL to `http://localhost:8000`. Do not use the local file for an Internet-facing deployment.
## Releases ## Releases
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 `frontend/version.json`; the tag must match that 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`. Run `make update-updates` after adding a signed XPI to regenerate `webextension/updates.json` from every valid signed release artifact. 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`. Commit the regenerated `webextension/updates.json` together with each signed 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.
@@ -118,10 +123,16 @@ Every push to `main` also runs `.gitea/workflows/development.yml` and publishes
Appending a username to the root URL, such as `/alice`, opens that user's public feed and profile information. Appending a username to the root URL, such as `/alice`, opens that user's public feed and profile information.
Configuration APIs require a bearer token returned by the login endpoint. User configuration uses the identity in that token. Plugin administration additionally requires an administrator account; the development `alice` account is seeded as an administrator, while `bob` is a standard user. Configuration APIs require a bearer token returned by the login endpoint. Send it in the `Authorization: Bearer ...` header; query-string tokens are not accepted. Users authenticate with their email address; the username remains the public presentation identity used in profiles and feed URLs. User configuration uses the identity in that token. Plugin administration additionally requires an administrator account.
Login failures are throttled per client IP and email. Five failures within 15 minutes trigger a two-minute lockout, including invalid OTP attempts; successful authentication clears the failure counter.
Users can change their password from the profile page. The current password is required, new passwords must contain at least 8 characters, and the endpoint is `PUT /api/user/password`. Users can change their password from the profile page. The current password is required, new passwords must contain at least 8 characters, and the endpoint is `PUT /api/user/password`.
Users can configure a time-based one-time password from the profile page using an authenticator app. The profile displays a provisioning secret and authenticator URI during setup, then requires a current six-digit code to enable or disable OTP. When OTP is enabled, both the web login and Firefox extension settings login require the code. The TOTP secret is never returned by the profile API after setup.
Users can add up to five additional email addresses from the profile page. Each additional address must be validated through a verification email before it can be used for authentication. A verified alternative can be promoted to primary; the previous primary remains as a verified alternative. The profile displays validation status and offers resend controls subject to the same 20-second interval, five-send limit, and two-minute cooldown used during initial setup.
On the profile page, the authenticated username is displayed as read-only. Users can upload a PNG, JPEG, GIF, or WebP avatar up to 2 MB; uploaded files are stored in the persistent data volume and served by the application. Bio and email fields remain empty until the user provides values. Mastodon settings default to the `mastodon.social` instance and the `From my #LinkLog: ` post prefix. On the profile page, the authenticated username is displayed as read-only. Users can upload a PNG, JPEG, GIF, or WebP avatar up to 2 MB; uploaded files are stored in the persistent data volume and served by the application. Bio and email fields remain empty until the user provides values. Mastodon settings default to the `mastodon.social` instance and the `From my #LinkLog: ` post prefix.
## Run Tests ## Run Tests
@@ -146,15 +157,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: `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.
@@ -168,14 +180,18 @@ 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 |
| --- | --- | --- | | --- | --- | --- |
| `LINKLOG_SECRET_KEY` | token signing/security secret | required in Docker | | `LINKLOG_SECRET_KEY` | token signing/security secret | required in Docker |
| `LINKLOG_DATA_ENCRYPTION_KEY` | Fernet key for encrypting SMTP, Mastodon, and OTP secrets at rest | required in Docker |
| `LINKLOG_DATABASE_PATH` | SQLite file path inside the container | `/app/backend/data/linklog.db` | | `LINKLOG_DATABASE_PATH` | SQLite file path inside the container | `/app/backend/data/linklog.db` |
| `LINKLOG_TOKEN_EXPIRY_DAYS` | access-token lifetime | `30` | | `LINKLOG_TOKEN_EXPIRY_MINUTES` | access-token lifetime | `15` |
| `LINKLOG_PUBLIC_URL` | Public hostname used by Traefik and expanded to a callback URL by the backend | `localhost` | | `LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS` | refresh-token lifetime | `30` |
| `LINKLOG_PUBLIC_URL` | Public hostname used by Traefik and expanded to a callback URL by the backend | `linklog.example.com` |
| `LINKLOG_SMTP_HOST` | SMTP server hostname; empty disables delivery in local development | empty | | `LINKLOG_SMTP_HOST` | SMTP server hostname; empty disables delivery in local development | empty |
| `LINKLOG_SMTP_PORT` | SMTP server port | `587` | | `LINKLOG_SMTP_PORT` | SMTP server port | `587` |
| `LINKLOG_SMTP_USERNAME` | SMTP login username | empty | | `LINKLOG_SMTP_USERNAME` | SMTP login username | empty |
@@ -195,6 +211,8 @@ When a verified user enters the wrong password, LinkLog keeps the response gener
The full set of supported variables is listed in `.env.example`. Application variables are passed into the container by Compose; Docker and Traefik variables are used by Compose itself. The full set of supported variables is listed in `.env.example`. Application variables are passed into the container by Compose; Docker and Traefik variables are used by Compose itself.
`LINKLOG_DATA_ENCRYPTION_KEY` must be a Fernet key kept outside the database. Generate one with a Python environment that has `cryptography` installed, for example `python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"`, then store it in `.env` or a protected deployment secret. Losing this key makes encrypted SMTP, Mastodon, and OTP values unrecoverable. Existing plaintext values from earlier versions should be rotated by saving them again after configuring the key.
Build and start the application: Build and start the application:
```sh ```sh
@@ -225,7 +243,7 @@ For a real deployment, start with the docker-compose-example.yaml file. replace
## Mastodon Configuration ## Mastodon Configuration
After logging in, open <http://localhost:8000/profile>, enter the Mastodon instance, and select **Connect Mastodon**. LinkLog registers an OAuth application on that instance, opens Mastodon authorization, and stores the returned per-user access token after the callback. The requested scopes are `read:accounts` and `write:statuses`. After logging in, open <http://localhost:8000/profile>, enter the Mastodon instance, and select **Connect Mastodon**. LinkLog registers an OAuth application on that instance, opens Mastodon authorization, and stores the returned per-user access token after the callback. The requested scopes are `read:accounts` and `write:statuses`. Posts use the configured prefix followed directly by the title, an optional comment, a `from: URL` line when a title exists, and tags on the final line, with blank lines between sections.
- **Instance**: hostname or URL such as `mastodon.social` or `https://mastodon.social` - **Instance**: hostname or URL such as `mastodon.social` or `https://mastodon.social`
- **Post prefix**: text placed immediately before the link; defaults to `From my #LinkLog: ` - **Post prefix**: text placed immediately before the link; defaults to `From my #LinkLog: `
@@ -234,6 +252,8 @@ After logging in, open <http://localhost:8000/profile>, enter the Mastodon insta
LinkLog caches the OAuth application credentials per Mastodon server in the persistent SQLite `app_settings` table, so subsequent connections do not register a new application on every attempt. If the server rate-limits application registration, the profile page reports the upstream `429` response and the user can retry after the server's cooldown. LinkLog caches the OAuth application credentials per Mastodon server in the persistent SQLite `app_settings` table, so subsequent connections do not register a new application on every attempt. If the server rate-limits application registration, the profile page reports the upstream `429` response and the user can retry after the server's cooldown.
Mastodon instances must be HTTPS hostname-only URLs that resolve to public IP addresses. Loopback, private, link-local, multicast, unspecified, reserved, and IPv4-mapped IPv6 destinations are rejected, and outbound redirects are refused.
Enable the plugin from the admin API or the admin page. New links are saved first and then posted to the configured instance at `/api/v1/statuses`. A Mastodon network failure does not undo the saved link. Enable the plugin from the admin API or the admin page. New links are saved first and then posted to the configured instance at `/api/v1/statuses`. A Mastodon network failure does not undo the saved link.
## Useful API Calls ## Useful API Calls
@@ -243,7 +263,26 @@ Login:
```sh ```sh
curl -X POST http://localhost:8000/api/auth/login \\ curl -X POST http://localhost:8000/api/auth/login \\
-H 'Content-Type: application/json' \\ -H 'Content-Type: application/json' \\
-d '{"username":"alice","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:
@@ -269,6 +308,8 @@ The inline link editor also allows multiple existing tags to be selected and new
The installation seeds these available tags: `#Internet`, `#Cybersecurity`, `#Fediverse`, `#Food`, `#Photography`, `#Music`, and `#AI`. The installation seeds these available tags: `#Internet`, `#Cybersecurity`, `#Fediverse`, `#Food`, `#Photography`, `#Music`, and `#AI`.
Users can create, edit, and delete their own labels from `/labels`. Administrators can delete any label from `/admin`; system-seeded labels have no user owner. Users can create, edit, and delete their own labels from `/labels`. Administrators can delete any label from `/admin`; system-seeded labels have no user owner.
Administrators can enable one or more backend themes from `/admin`: Plain Day, Plain Night, Catppuccin Latte, Catppuccin Frappe, Catppuccin Macchiato, Catppuccin Mocha, Dracula, Nord, and Solarized. Visitors can choose among enabled themes; their choice is stored locally in the browser. At least one theme must remain enabled.
Admin plugin requests must include the administrator's token: Admin plugin requests must include the administrator's token:
```sh ```sh
+165
View File
@@ -0,0 +1,165 @@
# LinkLog Security Audit
**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.
**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
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 following issues remain before an Internet-facing production release:
1. Logout still accepts a bearer token in a JSON body rather than using the standard `Authorization` header.
2. SMTP, Mastodon, setup, and some user-service errors return raw exception details to clients.
3. First-run setup is intentionally unauthenticated and lacks a bootstrap secret and application-level request-size controls.
4. Audit event details are serialized without defensive sanitization or size limits at the audit-service boundary.
5. The development secret fallback is not rejected at application startup in production.
6. Rate limiting is single-instance SQLite state, is not atomic under concurrency, and reset-mail issuance is not independently throttled.
7. Runtime verification, security headers, centralized audit export, retention, alerting, and dependency/container/security scanning remain incomplete.
The application should remain behind the production reverse proxy, with real DNS/TLS, protected secrets, and restricted network access until these items are addressed.
## Verified Controls
- Passwords use salted scrypt hashes; valid legacy SHA-256 hashes are upgraded on login.
- Bearer authentication is centralized through `get_current_user` and `require_admin`.
- Query-string authentication is not accepted by protected session endpoints.
- Access tokens are short-lived by default; refresh tokens are hashed, separately expiring, device-bound, rotated, and family-revoked on reuse.
- Logout, password changes, and password resets revoke session material according to the token lifecycle.
- OTP enrollment provides ten one-time recovery codes; only hashes are stored.
- Users can recover OTP with password plus a recovery code, and administrators can disable OTP for another user.
- Newly written SMTP, Mastodon, OAuth, and OTP secrets are encrypted with an external Fernet key.
- Mastodon instances are restricted to HTTPS public hostnames, unsafe resolved addresses are rejected, and redirects are blocked.
- Avatar uploads are size-limited, decoded with Pillow, pixel-limited, fully loaded, and re-encoded as server-generated PNG.
- Production Compose does not publish the application port and uses the external Traefik network; local direct access is separate.
- The Firefox extension uses `activeTab`, session-scoped credentials, exact configured backend permissions, and a self-only extension-page CSP.
- SQLite queries are parameterized and foreign-key enforcement is enabled.
- An append-only `security_audit_events` table records actor, action, target, outcome, and details for major administrative and destructive operations.
- The current automated backend suite passes 49 tests.
## Findings
### SA-001: Logout uses non-standard token transport
**Severity:** High, remediated in current worktree
**Evidence before remediation:** `POST /api/auth/logout` accepted `{"token": ...}` in the JSON request body, and the web frontend sent the access token this way.
**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.
**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.
**Recommendation:** Keep logout header-only, retain family revocation, avoid logging authorization headers, and rotate legacy sessions issued before this change.
**Priority:** Completed in code; legacy session rotation and log hygiene remain.
### SA-002: Raw infrastructure errors are returned to clients
**Severity:** High, remediated in current worktree
**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.
**Impact:** Error responses can disclose SMTP hostnames, ports, TLS/library details, upstream response bodies, internal network information, or sensitive URL fragments.
**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.
**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.
**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.
**Priority:** Completed in code; centralized logging and operational controls remain.
### SA-003: First-run setup is unauthenticated and lacks application-level body limits
**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.
**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.
**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.
**Priority:** High for Internet-facing fresh installations.
### SA-004: Audit details are not sanitized at the audit-service boundary
**Severity:** Medium
**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:** 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.
**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.
**Priority:** Medium.
### SA-005: Production secret fallback is not fail-closed
**Severity:** Medium, remediated in current worktree
**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 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.
**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.
**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.
**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.
**Priority:** Completed in code; secret provisioning and rotation remain.
### SA-006: Login and reset-mail throttling are not distributed or atomic
**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.
**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:** 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:** Medium/High for scaled or public deployments.
### SA-007: Security headers and global request policy are incomplete
**Severity:** Medium
**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:** 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.
### SA-008: Audit operations lack request correlation, retention, export, and alerting
**Severity:** Medium
**Evidence:** Audit events contain actor/action/target/outcome/details/time but no request ID, source context, retention policy, protected export, or alerting pipeline.
**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.
### SA-009: Dependency, container, secret, and runtime security verification is incomplete
**Severity:** Medium
**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:** Known vulnerable dependencies, image issues, accidental secret commits, proxy misconfiguration, and browser-runtime permission failures can reach release despite passing unit tests.
**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.
**Priority:** Medium before public release.
## Residual Operational Requirements
- 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.
- Rotate legacy plaintext secrets and previously issued sessions after upgrades.
- Protect and encrypt database/avatar backups; test restoration and token/session revocation.
- 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.
## Verification Performed
- `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.
+1002 -1
View File
File diff suppressed because it is too large Load Diff
+233 -28
View File
@@ -1,3 +1,4 @@
258. fix the Mastodon timestamp assertion to expect UTC
# Prompt Log # Prompt Log
## 2026-08-24 ## 2026-08-24
@@ -87,34 +88,238 @@
83. Add a copyright statement to source files refer to GNU license 83. Add a copyright statement to source files refer to GNU license
84. Add the version to the name of the resulting xpi 84. Add the version to the name of the resulting xpi
85. Set the version number of the backend to 0.1.0 85. Set the version number of the backend to 0.1.0
84. Add the creation of an xpi bundle for the webextention to the Makefile 86. Add the creation of an xpi bundle for the webextention to the Makefile
85. Correct: A signed XPI will be generated manually and checked into the repository under XPI/signed 87. Correct: A signed XPI will be generated manually and checked into the repository under XPI/signed
86. The "data_collection_permissions" property is missing from the plugin 88. The "data_collection_permissions" property is missing from the plugin
87. Validate the XPI during the make process of the unsigned xpi 89. Validate the XPI during the make process of the unsigned xpi
88. pressing remove still does not remove a user. 90. pressing remove still does not remove a user.
89. Trying to remove user alice: Could not remove alice: Internal Server Error 91. Trying to remove user alice: Could not remove alice: Internal Server Error
90. create a gitea action that is ran every time main is updated and that creates a docker image tagged development 92. create a gitea action that is ran every time main is updated and that creates a docker image tagged development
91. Use an access token to publish to registry, not username and password 93. Use an access token to publish to registry, not username and password
92. Add SMTP capabilities to the backend. Use it to validate the email addresses using a validation link in mail 94. Add SMTP capabilities to the backend. Use it to validate the email addresses using a validation link in mail
93. Do not configure default users at bootstrap. Instead present a configuration page (only present if no administrator is configured). The configuration page asks for the admin users credetials and allows to configure the SMTP settings and sends a test mail after configuration 95. Do not configure default users at bootstrap. Instead present a configuration page (only present if no administrator is configured). The configuration page asks for the admin users credetials and allows to configure the SMTP settings and sends a test mail after configuration
94. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent." 96. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent."
95. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down. 97. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down.
96. when running the initial config use the defaults from the .env file when available 98. when running the initial config use the defaults from the .env file when available
97. Use oauth to register with the mastodon account and obtain access to post 99. Use oauth to register with the mastodon account and obtain access to post
98. Allow user to enter the mastodon server to authenticate to 100. Allow user to enter the mastodon server to authenticate to
99. Clicking authenticate with this server (social.secret-wg.org) generates 502 error 101. Clicking authenticate with this server (social.secret-wg.org) generates 502 error
100. Log the unlogged chat and promt in the VIBE directory 102. Log the unlogged chat and promt in the VIBE directory
101. when password is mistyped send a password reset link 103. when password is mistyped send a password reset link
102. when running the initial config use the defaults from the .env file when available 104. when running the initial config use the defaults from the .env file when available
103. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent." 105. After saving the configuration - add link to home page together with "LinkLog is configured and the SMTP test mail was sent."
104. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down. 106. In the confiuration seperate the safe and send mail functionality. Allow the user to resend test mail 5 times with a 20 seconds interval and then hold back for 2 minutes - show a visual timer counting down.
105. Use oauth to register with the mastodon account and obtain access to post 107. Use oauth to register with the mastodon account and obtain access to post
106. Allow user to enter the mastodon server to authenticate to 108. Allow user to enter the mastodon server to authenticate to
107. Log the unlogged chat and promt in the VIBE directory 109. Log the unlogged chat and promt in the VIBE directory
108. Continue to log prompts and chats in VIBE 110. Continue to log prompts and chats in VIBE
109. use VIVE that is in the current directory 111. use VIVE that is in the current directory
110. Posting to mastodon seems to fail, try to fix, add debug logging 112. Posting to mastodon seems to fail, try to fix, add debug logging
111. LINKLOG_PUBLIC_URL and TRAEFIK_HOST are the same and can be merged. (use LINKLOG_PUBLIC_URL), fix docker-compose to use said variable 113. LINKLOG_PUBLIC_URL and TRAEFIK_HOST are the same and can be merged. (use LINKLOG_PUBLIC_URL), fix docker-compose to use said variable
114. Format mastodon posts like From my #LinkLog: Title, optional comment, and from: URL
115. Only print the 'from' line if there is no title. Put the title directly behind the colon, and put all tags on the last line.
116. In the frontend do not show edit buttons on the home page even when a user is logged in. On the /<user>/ page show the edit button on the right of the entry. Also add a delete button.
117. Put the buttons on the right hand side of the link item, make the buttons smaller and same color scheme
118. Put the mastodon button on the lower right corner of the log entry
119. Make sure that the makefile also rebuilds XPI if any of its source files are changed
120. Change that location to be immediately below the edit and delete button
121. When the user is authorized and on its /<user>/ page show a Mastodon post button with logo; after posting keep it functional but change its color.
122. Continue to log interactions to the VIBE directory.
123. On the home page, when clicking on the avatar or the user, show the profile information.
124. Localize the firefox plugin.
125. Create a spanish, german, french and dutch locale.
126. On the admin page add the SMTP settings (with the validation button).
127. Populate the SMTP fields with the current values except for the password. Send the testmail to the currently authenticated admin user. Only use updated fields when testing. Use the same logic as in the configuration page to restrict endless testing.
128. Report any errors that may occur from the SMTP module to the user.
129. In the admin screen allow to select multiple themes for the backend. Create at least one plain day and one night theme, and add in all catpuccin themes for good measure.
130. For the day and latte themes the contrast on the link items is too low.
131. Add 3 other of the most popular themes.
132. Show the tags in the linklog on the bottom left, move the date to the bottom right - horizontally align the tags with the date.
133. Continue todos.
134. Do not show 'no comment provided' but leave empty when no comment has been provided.
135. Decrease the space between link-log items.
136. Perform the next items on the todo list.
137. Correct: move the sort and filter toolbar underneath the theme and menu, in the header, on the home page and on the <user> pages.
138. Run frontend and style checks.
139. Keep the sort and filter bar left of the logo and pack it snug against the menu and theme selector.
140. Correction: the feed header should have the sort and filter bar to the right of the LinkLog logo, compact and underneath the theme selector and menu.
141. When a log entry is deleted then all mastodon posts are deleted too.
142. Don't forget to update the plugin to work with OTP.
143. When the user is not logged in then the plugin should just display no form fields but warn the user that they have to log in with a link to settings.
144. Remove DEFAULT_BACKEND setting in the plugin.
145. Change the title of the field "One-time password" to "One-time password (when configured)".
146. The plugin settings still show 'emailLabel'; make that 'email' as title for the email field.
147. When a URL with the same title is already in the database, warn the user, allow comment and hashtag changes, and retrigger plugins such as Mastodon reposting.
148. Display any errors that occur during posting.
149. When the plugin is activated and the link already exists, show "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered."
150. When pressing save link the plugin should display "Link saved to <url of linklog server>" and hide all other information. It should only refresh when the plugin is opened again
151. Remove any leading and trailing spaces when entering fields in the settings page of the plugin.
152. Do a full security audit document in what you have done in detail in Security-audit.md
153. Address issue 1. and improve password storage
154. The login page should ask for OTP password
155. For the new password in the user setting add a validation field to make sure they are the same before submitting
156. Change so that authentication is based on email address rather than username - maintain the username for presentation purposes
157. Make sure the web plugin follows same logic
158. Implement the recommendation for ### SA-002: Bearer tokens accepted in query strings
159. Change so that authentication is based on email address rather than username - maintain the username for presentation purposes
160. Make sure the web plugin follows same logic
161. In the plugin <span data-i18n="emailLabel">emailLabel</span> should read: <span data-i18n="emailLabel">Email</span>
162. Allow addition of secondary or tertiary email addresses; validate them before authentication and support profile status/resend controls with holdback.
163. Enable the user to change primary email address and remove the original one while maintaining access and rights.
164. Choose primary email from already verified alternative email addresses and increase the number of alternative email addresses allowed to 5.
165. Make sure an email can only be selected when it has been validated.
166. Remove the entire "New primary email address" block; keep only selecting an existing alternative as primary.
167. Remove the “New primary email address” functionality and keep only selecting an existing alternative as primary.
168. Address SA-003 by using a dedicated secret key supplied through a protected environment/secret file, encrypt sensitive values before SQLite storage
169. Address SA-004 by validating Mastodon instances as HTTPS public hostnames, rejecting unsafe DNS/IP ranges including mapped IPv6, and blocking redirects
170. Implement SA-005: login endpoint lacks rate limiting and lockout
171. Address SA-004 by validating Mastodon instances as HTTPS public hostnames, rejecting unsafe DNS/IP ranges including mapped IPv6, and blocking redirects.
172. When the user is logged in the webplugin should not display "Please sign in to use LinkLog."
173. When the user is signed in the plugin should not display "Please sign in to use LinkLog." and the link to the settings
174. The plugin still does not behave as expected. It still shows that the user should sign in.
175. In the popup show that the user has logged in.
176. Address SA-003 by using a dedicated secret key supplied through a protected environment/secret file, encrypt sensitive values before SQLite storage
## 2026-09-05
177. Document the sql schema, include an ERD
178. In the toolbar add a search functionality, which filters the log entries on keywords. use basic symbols and operators such as with google, and only 'site:' as advanced search operator
177. The popup still shows the sign-in block even though the authenticated session text is displayed; show the block only when signed out.
178. The authenticated session text and sign-in block are still shown together.
179. Use the VIBE directory to log interactions.
180. Implement SA-006: remove broad Firefox extension host access and unnecessary tabs permission, request exact configured backend origin access, and keep page capture behind activeTab.
181. Continue to document every prompt and chat in the VIBE directory.
182. Continue SA-006: store session credentials in the narrowest available extension storage, minimize token lifetime, support refresh-token rotation, and clear all session material on logout or token invalidation.
183. Also allow an admin to reset (disable) OTP for any user.
183. Fix SA-009: TOTP enrollment has no recovery codes or reset workflow.
183. Address SA-007 and use linklog.example.com as the default LINKLOG_PUBLIC_URL.
184. Run full backend and frontend test suites.
185. Solve SA-010: Avatar validation trusts the client MIME type.
186. Fix SA-015: Some destructive and administrative operations lack audit logging.
187. Format sent mail in the website style and include the logo.
188. Set the email logo to 120px wide and center it at the top.
189. Make the email logo 50px by 50px, place it top-left, and put "Hello" to its right in the Asset font.
190. Replace the email greeting with "Hello a message from <public hostname>", linking the hostname to the LinkLog server.
191. Put the email header text to the right of the logo, align it at the top, and add a comma after Hello.
192. Put the email greeting in a separate top-aligned cell to the right of the logo.
193. Reduce the email greeting font size somewhat.
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
214. I want that the users is able to edit or delete labels(tags) that were created by the user itself. Also validate that any logged in user will only see the labels created by default, in the admin panel, and those by themselves, not by any other user. If this leads to an update in the database then if ownership of labels is unknown they may be grandfathered as-if created in the admin interface
215. Make sure that in the admin interface the labels can be edited
216. Make sure that the logs in VIBE are updated
217. Update Changelog too
218. In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
219. Make sure all setting-panels are collapsed when opening the page
218. In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
219. Give the header of each setting-panel a somewhat differing color.
220. Change the background of the header too.
221. Apply exactly the same functionality to the profile page
222. On the admin page under Available Themes, the page does not load available themes
218. Give the header of each setting-panel a somewhat differing color
218. In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
219. Clicking on the collapse button doesn't toggle
218. In the Admin interface allow to minimize each settings pannel to only show its header, In order to easely navigate the page.
223. On the new-entry page the checkbox should be following the labels - now they are positioned above.
224. The checkboxes should be immediately to the left of the label not below left
225. The checkbox takes the full width of the grid which forces the label to be printed underneath instead of directly next to it.
226. Only show the Mastodon publishing on new page if the user has Mastodon posting configured. Then default the checkbox to yes
227. In the currently running contaier the user olaf has no mastodon configured but the mastodon checkbox is still visible
228. When clicking on the logo always go to the home page
229. Add a red collor theme
230. Make the theme brighter and darker red
231. Since checkin d433a305f5cd8ccdafde8a0f7764462e8c167162 on the home page the filter toolbar moved so that the menu button and new entry are not in the top left anylonger - revert to the previous layout
232. I want every user to filter on every available tag/label
233. tag filter doesn't seem to respond when pressed
234. The tag filter still does not allow me to select tags, even though the raw html contains the correct content. Also the user filter and the sort functionality work too
235. I believe tag selection was still working for v0.1.0 - it is still broken
236. Don't let the frontend and plugin pull from the google foundry but make sure any necessary fonts are served from the linklog server. I would prefer the fonts to be updated at docker image building time.
## 2026-08-28
237. On the new-entry page follow the logic for existing pages that already exists in the plugin and display "This link already exists. Comment and tags can be updated, and by submitting publishing will be retriggered." when the link exists. Also assess if the Auto-fill title button is necessary, or if the functionality can be automated while the URL is entered.
238. Also: detect as duplicate when the URL has arguments (not already stripped). And: add a button to re-fetch the title for if the URL has been fetched but the user still edits the field.
239. If the link already exist with URL arguments then also display the warning, but add that the link has been stored additional parameters.
240. I want this last change to be more precise: I do not want to be warned when parameters are stripped, but when the URL entered has arguments/parameters and the URL in the database has none or different ones (even after tracking parameters are stripped).
241. In the check duplicate I have a `<br>` tag, but that shows as formatted text on the page, I want a real break to occur at that position.
242. Update VIBE and Changelog.
243. Make sure the webplugin has the same functionality as just implemented in the new-entry page. Increase its version number to 0.2.0.
244. Add a feature to the Make file that updates the updates.json file based on available signed releases.
245. Add sha hashes to the updates.json
246. Update changelog and VIBE
247. Make sure that when the plugin is signed the version in the link it the about page is updated too
248. Release script fails because the runner's hashlib module has no file_digest attribute.
249. The filtering on tags does not work. When I click on the button I cannot select. Remember that any visitor on the site should be able to filter the tag for the link-feed.
250. Update VIBE and Changelog
251. What are the fingerprinting risks of this system?
## 2026-08-30
251. Create a skill for this project, make sure you capture the VIBE directory update
## 2026-08-30
252. In the mastodon post change the line: From:< URL>
to
Logged on <date> from: <url>
Where date format is like: 2026 August 29 - 21:10
## 2026-09-04
253. Document all code
## 2026-09-05
254. In firefox the search input field is wider (at 180px) then labe search control (at 135.5px)
255. In the toolbar switch the search and tag filter's location
## 2026-09-06
256. Use the APIs to, In the current runtime (linklog.db), add 5 random users and for each users add 500 random linklog items from different sites, each with comments and hashtags
257. the current implementation reads the whole feed at once.
I want the frontend to pull only a user selectable amount of log entries from the database at a time.
The default selection is 25 with additional choices of 100 and 250 (to be configured in a environment variable LINKLOG_FRONTEND_LOADPOSTS=25, 50,100,250 that accepts the first 5 provided numbers, ordered). The user can select the next, or previous button or click page 1, 2, 3, ... on the bottom of the current page.
If the user uses the filters and/or search in the toolbox then those should limit the entries the server presents, so the filters and search are applied on the server side.
258. Make it so that <nav id=pagination> at the bottom of the page doesn't exceed the page width and is less visually dominant
259. Make sure the CHANGELOG reflects all changes since commit 74b2c400c6
260. Add a skill to maintain the changelog.md
261. In the new-entry form, provide a warning when the total ammount of characters is over LINKLOG_MAX_POST_CHARACTERS=500 (also indicat the number of characters used/500 count). This is to prevent Mastodon posts from failing - so all characters should be counted.
262. Implement the same functionality in the firefox plugin
## 2026-09-16
263. Add these findings and recomendations to Privacy.md
## Future entries ## Future entries
-682583
View File
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+176 -7
View File
@@ -2,19 +2,32 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
import json import json
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
from backend.app.database import get_connection, hash_password from backend.app.database import get_connection, hash_password
from backend.app.services.link_service import delete_label from backend.app.services.link_service import delete_label, update_label
from backend.app.services.email_service import send_verification_email, smtp_configured from backend.app.services.email_service import (
get_smtp_settings,
save_smtp_settings,
send_test_email,
send_verification_email,
smtp_configured,
)
from backend.app.services.email_verification import create_verification_token from backend.app.services.email_verification import create_verification_token
from backend.app.services.theme_service import THEMES, get_enabled_themes, save_enabled_themes
from backend.app.services.secret_store import encrypt_secret
from backend.app.core.config import settings from backend.app.core.config import settings
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):
@@ -22,6 +35,10 @@ class AdminPluginUpdate(BaseModel):
config: dict | None = None config: dict | None = None
class AdminLabelUpdate(BaseModel):
name: str
class AdminUserCreate(BaseModel): class AdminUserCreate(BaseModel):
username: str username: str
email: str email: str
@@ -33,6 +50,36 @@ class AdminUserUpdate(BaseModel):
is_admin: bool is_admin: bool
class AdminSmtpUpdate(BaseModel):
smtp_host: str
smtp_port: int = 587
smtp_username: str = ''
smtp_password: str = ''
smtp_from: str
smtp_use_tls: bool = True
class AdminThemesUpdate(BaseModel):
themes: list[str]
def validate_smtp_values(payload: AdminSmtpUpdate, current: dict | None = None) -> dict:
smtp_host = payload.smtp_host.strip()
smtp_from = payload.smtp_from.strip()
if not smtp_host or not smtp_from:
raise HTTPException(status_code=422, detail='SMTP host and sender address are required')
if not 1 <= payload.smtp_port <= 65535:
raise HTTPException(status_code=422, detail='SMTP port must be between 1 and 65535')
return {
'smtp_host': smtp_host,
'smtp_port': payload.smtp_port,
'smtp_username': payload.smtp_username.strip(),
'smtp_password': payload.smtp_password or (current or {}).get('smtp_password', ''),
'smtp_from': smtp_from,
'smtp_use_tls': payload.smtp_use_tls,
}
def public_user(row): def public_user(row):
return { return {
'id': row['id'], 'id': row['id'],
@@ -55,8 +102,24 @@ def list_users(_: dict = Depends(require_admin)):
return [public_user(row) for row in rows] return [public_user(row) for row in rows]
@router.post('/users/{user_id}/otp/reset')
def reset_user_otp(user_id: str, current_user: dict = Depends(require_admin)):
with get_connection() as conn:
target = conn.execute('SELECT id FROM users WHERE id = ?', (user_id,)).fetchone()
if target is None:
raise HTTPException(status_code=404, detail='User not found')
conn.execute(
'UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
(user_id,),
)
conn.execute('DELETE FROM otp_recovery_codes WHERE user_id = ?', (user_id,))
conn.commit()
record_audit_event(current_user['id'], 'otp_reset', 'user', user_id)
return {'status': 'otp_reset', 'enabled': False, 'user_id': user_id}
@router.post('/users', status_code=201) @router.post('/users', status_code=201)
def create_user(payload: AdminUserCreate, _: 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:
@@ -86,10 +149,97 @@ def create_user(payload: AdminUserCreate, _: dict = Depends(require_admin)):
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)})
return public_user(row) return public_user(row)
def public_smtp_settings(values: dict) -> dict:
return {
'smtp_host': values['smtp_host'],
'smtp_port': values['smtp_port'],
'smtp_username': values['smtp_username'],
'smtp_from': values['smtp_from'],
'smtp_use_tls': values['smtp_use_tls'],
'password_configured': bool(values['smtp_password']),
}
@router.get('/smtp')
def get_admin_smtp_settings(_: dict = Depends(require_admin)):
return public_smtp_settings(get_smtp_settings())
@router.get('/themes')
def get_admin_themes(_: dict = Depends(require_admin)):
return {'themes': THEMES, 'enabled': get_enabled_themes()}
@router.put('/themes')
def update_admin_themes(payload: AdminThemesUpdate, current_user: dict = Depends(require_admin)):
try:
enabled = save_enabled_themes(payload.themes)
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error)) from error
record_audit_event(current_user['id'], 'themes_updated', 'application', details={'themes': enabled})
return {'themes': THEMES, 'enabled': enabled}
@router.put('/smtp')
def update_admin_smtp_settings(payload: AdminSmtpUpdate, current_user: dict = Depends(require_admin)):
current = get_smtp_settings()
values = validate_smtp_values(payload, current)
save_smtp_settings(values)
record_audit_event(current_user['id'], 'smtp_settings_updated', 'application', details={'host': values['smtp_host'], 'port': values['smtp_port'], 'username': values['smtp_username'], 'tls': values['smtp_use_tls']})
return public_smtp_settings(values)
@router.post('/smtp/test')
def validate_admin_smtp(payload: AdminSmtpUpdate, request: Request, current_user: dict = Depends(require_admin)):
values = validate_smtp_values(payload, get_smtp_settings())
now = datetime.now(timezone.utc)
with get_connection() as conn:
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',)).fetchone()
rate = json.loads(row['value']) if row else {}
last_sent = datetime.fromisoformat(rate['last_sent']) if rate.get('last_sent') else None
cooldown_until = datetime.fromisoformat(rate['cooldown_until']) if rate.get('cooldown_until') else None
if cooldown_until and now >= cooldown_until:
rate = {}
last_sent = None
cooldown_until = None
if cooldown_until and now < cooldown_until:
retry_after = int((cooldown_until - now).total_seconds()) + 1
raise HTTPException(status_code=429, detail=f'SMTP validation limit reached. Try again in {retry_after} seconds.', headers={'Retry-After': str(retry_after)})
if last_sent and now - last_sent < timedelta(seconds=20):
retry_after = int((timedelta(seconds=20) - (now - last_sent)).total_seconds()) + 1
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before sending another validation email.', headers={'Retry-After': str(retry_after)})
try:
send_test_email(current_user['email'], values)
except Exception as 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
updated_rate = {'sends': sends, 'last_sent': now.isoformat()}
if sends >= 5:
updated_rate['cooldown_until'] = (now + timedelta(minutes=2)).isoformat()
with get_connection() as conn:
conn.execute(
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
('admin_smtp_mail_rate', json.dumps(updated_rate)),
)
conn.commit()
next_allowed = datetime.fromisoformat(updated_rate.get('cooldown_until')) if sends >= 5 else now + timedelta(seconds=20)
return {
'status': 'sent',
'message': f'SMTP validation email sent to {current_user["email"]}.',
'sends_remaining': max(0, 5 - sends),
'cooldown_seconds': 120 if sends >= 5 else 0,
'next_allowed_at': next_allowed.isoformat(),
}
@router.put('/users/{user_id}') @router.put('/users/{user_id}')
def update_user_privileges( def update_user_privileges(
user_id: str, user_id: str,
@@ -123,6 +273,7 @@ def update_user_privileges(
'SELECT id, username, email, is_admin, avatar_url, bio, created_at, email_verified FROM users WHERE id = ?', 'SELECT id, username, email, is_admin, avatar_url, bio, created_at, email_verified FROM users WHERE id = ?',
(user_id,), (user_id,),
).fetchone() ).fetchone()
record_audit_event(current_user['id'], 'user_privileges_updated', 'user', user_id, details={'is_admin': bool(payload.is_admin)})
return public_user(row) return public_user(row)
@@ -145,16 +296,30 @@ def delete_user(user_id: str, current_user: dict = Depends(require_admin)):
conn.execute('DELETE FROM links WHERE user_id = ?', (user_id,)) conn.execute('DELETE FROM links WHERE user_id = ?', (user_id,))
conn.execute('DELETE FROM users WHERE id = ?', (user_id,)) conn.execute('DELETE FROM users WHERE id = ?', (user_id,))
conn.commit() conn.commit()
record_audit_event(current_user['id'], 'user_deleted', 'user', user_id)
return {'status': 'deleted', 'id': user_id} return {'status': 'deleted', 'id': user_id}
@router.delete('/labels/{label_id}') @router.delete('/labels/{label_id}')
def admin_delete_label(label_id: str, _: dict = Depends(require_admin)): def admin_delete_label(label_id: str, current_user: dict = Depends(require_admin)):
if not delete_label(label_id, is_admin=True): if not delete_label(label_id, is_admin=True):
raise HTTPException(status_code=404, detail='Label not found') raise HTTPException(status_code=404, detail='Label not found')
record_audit_event(current_user['id'], 'label_deleted', 'label', label_id)
return {'status': 'deleted', 'id': label_id} return {'status': 'deleted', 'id': label_id}
@router.put('/labels/{label_id}')
def admin_edit_label(label_id: str, payload: AdminLabelUpdate, current_user: dict = Depends(require_admin)):
try:
result = update_label(label_id, user_id=current_user['id'], name=payload.name, is_admin=True)
except ValueError as error:
raise HTTPException(status_code=409, detail=str(error)) from error
if result is None:
raise HTTPException(status_code=404, detail='Label not found')
record_audit_event(current_user['id'], 'label_updated', 'label', label_id)
return result
@router.get('/labels') @router.get('/labels')
def admin_list_labels(_: dict = Depends(require_admin)): def admin_list_labels(_: dict = Depends(require_admin)):
with get_connection() as conn: with get_connection() as conn:
@@ -210,7 +375,7 @@ def get_plugin(plugin_name: str, _: dict = Depends(require_admin)):
def update_plugin( def update_plugin(
plugin_name: str, plugin_name: str,
payload: AdminPluginUpdate, payload: AdminPluginUpdate,
_: dict = Depends(require_admin), current_user: dict = Depends(require_admin),
): ):
with get_connection() as conn: with get_connection() as conn:
current = conn.execute( current = conn.execute(
@@ -225,6 +390,9 @@ def update_plugin(
config = json.loads(current['config']) if current['config'] else {} config = json.loads(current['config']) if current['config'] else {}
if payload.config is not None: if payload.config is not None:
config.update(payload.config) config.update(payload.config)
for secret_name in ('access_token', 'client_secret', 'smtp_password'):
if config.get(secret_name):
config[secret_name] = encrypt_secret(config[secret_name])
conn.execute( conn.execute(
''' '''
@@ -236,6 +404,7 @@ def update_plugin(
) )
conn.commit() conn.commit()
record_audit_event(current_user['id'], 'plugin_updated', 'plugin', plugin_name, details={'enabled': enabled})
return { return {
'name': plugin_name, 'name': plugin_name,
'enabled': enabled, 'enabled': enabled,
+61 -19
View File
@@ -3,16 +3,21 @@
from uuid import uuid4 from uuid import uuid4
from fastapi import APIRouter, HTTPException 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.database import get_connection, init_db from backend.app.database import get_connection, init_db
from backend.app.core.config import settings from backend.app.core.config import settings
from backend.app.services.auth_service import authenticate_user, find_user from backend.app.services.auth_service import authenticate_user, find_user
from backend.app.services.email_service import send_password_reset_email, smtp_configured from backend.app.services.email_service import send_password_reset_email, smtp_configured
from backend.app.services.email_verification import verify_email from backend.app.services.email_verification import verify_email
from backend.app.services.password_reset import create_reset_token, reset_password from backend.app.services.password_reset import create_reset_token, reset_password
from backend.app.services.token_service import issue_token, revoke_token, validate_token from backend.app.services.token_service import issue_token, revoke_token, rotate_refresh_token, validate_token
from backend.app.services.otp_service import verify_code
from backend.app.services.secret_store import decrypt_secret
from backend.app.services.email_addresses import verify_user_email_address
from backend.app.services.login_throttle import check_login_allowed, clear_login_failures, record_login_failure
router = APIRouter() router = APIRouter()
@@ -20,8 +25,15 @@ init_db()
class LoginRequest(BaseModel): class LoginRequest(BaseModel):
username: str email: str
password: str password: str
otp: str | None = None
device_id: str | None = None
class RefreshTokenRequest(BaseModel):
refresh_token: str
device_id: str | None = None
class PasswordResetRequest(BaseModel): class PasswordResetRequest(BaseModel):
@@ -30,10 +42,17 @@ class PasswordResetRequest(BaseModel):
@router.post('/login') @router.post('/login')
def login(payload: LoginRequest): def login(payload: LoginRequest, request: Request):
user = authenticate_user(payload.username, payload.password) email = payload.email.strip()
ip_address = request.client.host if request.client else 'unknown'
retry_after = check_login_allowed(ip_address, email)
if retry_after is not None:
raise HTTPException(status_code=429, detail='Too many failed login attempts. Try again later.', headers={'Retry-After': str(retry_after)})
user = authenticate_user(email, payload.password)
if user is None: if user is None:
reset_user = find_user(payload.username) record_login_failure(ip_address, email)
reset_user = find_user(email)
if reset_user and reset_user['email_verified'] and smtp_configured(): if reset_user and reset_user['email_verified'] and smtp_configured():
try: try:
token = create_reset_token(reset_user['id']) token = create_reset_token(reset_user['id'])
@@ -44,14 +63,34 @@ def login(payload: LoginRequest):
raise HTTPException(status_code=401, detail='Invalid username or password') raise HTTPException(status_code=401, detail='Invalid username or password')
if not user['email_verified']: if not user['email_verified']:
raise HTTPException(status_code=403, detail='Email address is not verified') raise HTTPException(status_code=403, detail='Email address is not verified')
if user['otp_enabled'] and not verify_code(decrypt_secret(user['otp_secret']), payload.otp):
record_login_failure(ip_address, email)
raise HTTPException(status_code=401, detail='One-time password required or invalid')
token_data = issue_token(user['id'], user['username']) clear_login_failures(ip_address, email)
token_data = issue_token(user['id'], user['username'], payload.device_id)
return { return {
'access_token': token_data['access_token'], 'access_token': token_data['access_token'],
'token_type': 'bearer', 'token_type': 'bearer',
'expires_at': token_data['expires_at'], 'expires_at': token_data['expires_at'],
'refresh_token': token_data['refresh_token'], 'refresh_token': token_data['refresh_token'],
'user': {'id': user['id'], 'username': user['username'], 'email': user['email']} 'device_id': token_data['device_id'],
'user': {'id': user['id'], 'username': user['username'], 'email': user['email'], 'otp_enabled': bool(user['otp_enabled'])}
}
@router.post('/refresh')
def refresh_token_endpoint(payload: RefreshTokenRequest):
rotated = rotate_refresh_token(payload.refresh_token, payload.device_id)
if rotated is None:
raise HTTPException(status_code=401, detail='Refresh token is invalid, expired, or bound to another device')
return {
'access_token': rotated['access_token'],
'token_type': 'bearer',
'expires_at': rotated['expires_at'],
'refresh_token': rotated['refresh_token'],
'device_id': rotated['device_id'],
'user': {'id': rotated['user_id'], 'username': rotated['username']},
} }
@@ -62,6 +101,14 @@ def verify_email_address(token: str):
return {'status': 'verified', 'message': 'Email address verified. You can now sign in.'} return {'status': 'verified', 'message': 'Email address verified. You can now sign in.'}
@router.get('/verify-additional-email')
def verify_additional_email_address(token: str):
if not verify_user_email_address(token):
raise HTTPException(status_code=400, detail='Email verification link is invalid or expired')
return {'status': 'verified', 'message': 'Email address verified. You can now sign in.'}
@router.post('/reset-password') @router.post('/reset-password')
def reset_password_endpoint(payload: PasswordResetRequest): def reset_password_endpoint(payload: PasswordResetRequest):
if len(payload.password) < 8: if len(payload.password) < 8:
@@ -72,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')
@@ -83,14 +132,7 @@ def logout(payload: dict):
@router.get('/me') @router.get('/me')
def current_user(token: str): def current_user(user: dict = Depends(get_current_user)):
info = validate_token(token)
if info is None:
raise HTTPException(status_code=401, detail='Token expired or invalid')
with get_connection() as conn:
user = conn.execute('SELECT * FROM users WHERE id = ?', (info['user_id'],)).fetchone()
if user is None:
raise HTTPException(status_code=404, detail='User not found')
return { return {
'id': user['id'], 'id': user['id'],
'username': user['username'], 'username': user['username'],
+16
View File
@@ -38,6 +38,22 @@ def get_current_user(
return dict(user) return dict(user)
def get_optional_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
) -> dict | None:
if credentials is None or credentials.scheme.lower() != 'bearer':
return None
token_data = validate_token(credentials.credentials)
if token_data is None:
return None
with get_connection() as conn:
user = conn.execute(
'SELECT * FROM users WHERE id = ?',
(token_data['user_id'],),
).fetchone()
return dict(user) if user else None
def require_admin(user: dict = Depends(get_current_user)): def require_admin(user: dict = Depends(get_current_user)):
if not user['is_admin']: if not user['is_admin']:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Administrator access required') raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Administrator access required')
+119 -7
View File
@@ -1,13 +1,17 @@
## 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 APIRouter, Header, HTTPException, status import json
from fastapi import APIRouter, Depends, Header, HTTPException, Response, status
import logging import logging
from pydantic import BaseModel from pydantic import BaseModel
from backend.app.services.link_service import create_link, list_public_links, list_tags, update_link from backend.app.services.link_service import create_link, delete_link, find_owned_link_by_title, find_owned_link_by_title_url, get_link_tags, get_owned_link, list_public_links, list_tags, mark_mastodon_posted, update_link
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.scraper_service import scrape_title
router = APIRouter() router = APIRouter()
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -19,6 +23,7 @@ class LinkCreate(BaseModel):
comment: str = '' comment: str = ''
timestamp: str | None = None timestamp: str | None = None
tags: list[str] = [] tags: list[str] = []
post_to_mastodon: bool = True
class LinkUpdate(BaseModel): class LinkUpdate(BaseModel):
@@ -33,8 +38,43 @@ 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')
def check_existing_link(
title: str,
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')
record = find_owned_link_by_title_url(info['user_id'], title, url)
if record is not None:
return {'exists': True, 'url_matches': True, 'stored_url': record['url']}
record = find_owned_link_by_title(info['user_id'], title)
if record is not None:
return {'exists': True, 'url_matches': False, 'stored_url': record['url']}
return {'exists': False, 'url_matches': None, 'stored_url': None}
@router.post('/links', status_code=status.HTTP_201_CREATED) @router.post('/links', status_code=status.HTTP_201_CREATED)
def create_link_endpoint(payload: LinkCreate, authorization: str | None = Header(default=None)): def create_link_endpoint(payload: LinkCreate, response: Response, authorization: str | None = Header(default=None)):
if not authorization or not authorization.startswith('Bearer '): if not authorization or not authorization.startswith('Bearer '):
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header') raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
token = authorization.replace('Bearer ', '', 1) token = authorization.replace('Bearer ', '', 1)
@@ -43,13 +83,32 @@ def create_link_endpoint(payload: LinkCreate, authorization: str | None = Header
raise HTTPException(status_code=401, detail='Token expired or invalid') raise HTTPException(status_code=401, detail='Token expired or invalid')
try: try:
record = create_link(info['user_id'], payload.title, payload.url, payload.comment, payload.timestamp, payload.tags) record = find_owned_link_by_title_url(info['user_id'], payload.title, payload.url)
duplicate = record is not None
if duplicate:
record = update_link(record['id'], info['user_id'], payload.title, payload.url, payload.comment, payload.tags)
else:
record = create_link(info['user_id'], payload.title, payload.url, payload.comment, payload.timestamp, payload.tags)
except ValueError as error: except ValueError as error:
raise HTTPException(status_code=422, detail=str(error)) from error raise HTTPException(status_code=422, detail=str(error)) from error
plugin_results = plugin_manager.dispatch({'type': 'link_created', **record}) if duplicate:
response.status_code = status.HTTP_200_OK
plugin_results = plugin_manager.dispatch({
'type': 'link_created',
'post_to_mastodon': payload.post_to_mastodon,
**record,
})
mastodon_result = next((result for result in plugin_results if result.get('plugin') == 'mastodon'), None)
if mastodon_result and mastodon_result.get('status') == 'posted':
mark_mastodon_posted(record['id'], info['user_id'], mastodon_result.get('post_id'))
if any(result.get('status') == 'failed' for result in plugin_results): if any(result.get('status') == 'failed' for result in plugin_results):
logger.warning('One or more plugins failed for link_id=%s results=%s', record['id'], plugin_results) logger.warning('One or more plugins failed for link_id=%s results=%s', record['id'], plugin_results)
return record plugin_errors = [
{'plugin': result.get('plugin', 'unknown'), 'reason': result.get('reason', 'Plugin failed')}
for result in plugin_results
if result.get('status') == 'failed'
]
return {**record, 'duplicate': duplicate, 'plugin_errors': plugin_errors}
@router.put('/links/{link_id}') @router.put('/links/{link_id}')
@@ -73,6 +132,59 @@ def update_link_endpoint(
return record return record
@router.delete('/links/{link_id}')
def delete_link_endpoint(
link_id: 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')
link = get_owned_link(link_id, info['user_id'])
if link is None:
raise HTTPException(status_code=404, detail='Link not found or not owned by user')
post_ids = json.loads(link['mastodon_post_ids']) if link.get('mastodon_post_ids') else []
if not post_ids and link.get('mastodon_post_id'):
post_ids = [link['mastodon_post_id']]
if post_ids:
result = plugin_manager.delete_mastodon_posts({**link, 'mastodon_post_ids': post_ids})
if result.get('status') != 'deleted':
raise HTTPException(status_code=502, detail=result.get('reason', 'Could not delete Mastodon posts'))
if not delete_link(link_id, info['user_id']):
raise HTTPException(status_code=404, detail='Link not found or not owned by user')
record_audit_event(info['user_id'], 'link_deleted', 'link', link_id)
return {'status': 'deleted', 'id': link_id}
@router.post('/links/{link_id}/mastodon')
def post_link_to_mastodon(
link_id: 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')
with get_connection() as conn:
row = conn.execute('SELECT * FROM links WHERE id = ? AND user_id = ?', (link_id, info['user_id'])).fetchone()
if row is None:
raise HTTPException(status_code=404, detail='Link not found or not owned by user')
event = dict(row)
with get_connection() as conn:
event['tags'] = get_link_tags(conn, link_id)
result = plugin_manager.post_to_mastodon({'type': 'link_created', **event})
if result.get('status') == 'posted':
mark_mastodon_posted(link_id, info['user_id'], result.get('post_id'))
record_audit_event(info['user_id'], 'mastodon_posted', 'link', link_id)
return {'status': 'posted', 'post_id': result.get('post_id')}
if result.get('status') == 'skipped':
raise HTTPException(status_code=409, detail='Mastodon is not enabled or configured')
raise HTTPException(status_code=502, detail=result.get('reason', 'Mastodon post failed'))
@router.get('/links') @router.get('/links')
def list_links(): def list_links():
return list_public_links() return list_public_links()['items']
+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')
+40 -4
View File
@@ -1,11 +1,15 @@
## 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 APIRouter, Depends import math
from fastapi import APIRouter, Depends, Query
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from backend.app.core.config import settings
from backend.app.services.link_service import list_public_links, list_public_users from backend.app.services.link_service import list_public_links, list_public_users
from backend.app.services.token_service import validate_token from backend.app.services.token_service import validate_token
from backend.app.services.theme_service import THEMES, get_enabled_themes
router = APIRouter() router = APIRouter()
optional_bearer = HTTPBearer(auto_error=False) optional_bearer = HTTPBearer(auto_error=False)
@@ -16,10 +20,30 @@ def public_users():
return list_public_users() return list_public_users()
@router.get('/themes')
def public_themes():
enabled = get_enabled_themes()
return [{'id': theme, **THEMES[theme]} for theme in enabled]
@router.get('/config')
def public_config():
return {
'feed_page_sizes': settings.feed_page_sizes,
'default_page_size': settings.feed_page_sizes[0],
'max_post_characters': settings.max_post_characters,
}
@router.get('/feed') @router.get('/feed')
@router.get('/feed/{username}') @router.get('/feed/{username}')
def public_feed( def public_feed(
username: str | None = None, username: str | None = None,
tag: str | None = None,
search: str | None = None,
sort: str = 'newest',
page: int = Query(1, ge=1),
page_size: int | None = Query(None, ge=1),
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer), credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
): ):
current_user_id = None current_user_id = None
@@ -27,8 +51,10 @@ def public_feed(
token_data = validate_token(credentials.credentials) token_data = validate_token(credentials.credentials)
if token_data: if token_data:
current_user_id = token_data['user_id'] current_user_id = token_data['user_id']
items = list_public_links(username) allowed_sizes = settings.feed_page_sizes
return [ effective_page_size = page_size if page_size in allowed_sizes else allowed_sizes[0]
result = list_public_links(username, tag=tag, search=search, sort=sort, page=page, page_size=effective_page_size)
items = [
{ {
'id': item['id'], 'id': item['id'],
'title': item['title'], 'title': item['title'],
@@ -43,6 +69,16 @@ def public_feed(
'is_owner': item['user_id'] == current_user_id, 'is_owner': item['user_id'] == current_user_id,
'can_edit': item['user_id'] == current_user_id, 'can_edit': item['user_id'] == current_user_id,
'created_at': item['created_at'], 'created_at': item['created_at'],
'mastodon_posted': bool(item['mastodon_posted']),
} }
for item in items for item in result['items']
] ]
total = result['total']
total_pages = max(1, math.ceil(total / effective_page_size))
return {
'items': items,
'total': total,
'page': page,
'page_size': effective_page_size,
'total_pages': total_pages,
}
+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()}
+251 -20
View File
@@ -2,20 +2,35 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
import json import json
import warnings
from io import BytesIO
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 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
from backend.app.database import AVATARS_DIR, get_connection, hash_password from backend.app.database import AVATARS_DIR, get_connection, hash_password, verify_password
from backend.app.services.link_service import create_label, delete_label, list_user_labels, update_label from backend.app.services.link_service import create_label, delete_label, list_user_labels, update_label
from backend.app.services.otp_service import consume_recovery_code, create_recovery_codes, create_secret, provisioning_uri, verify_code
from backend.app.services.email_addresses import add_user_email_address, create_email_verification, list_user_email_addresses
from backend.app.services.email_service import send_verification_email, smtp_configured
from backend.app.core.config import settings
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
from backend.app.services.audit_service import record_audit_event
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_PIXELS = 25_000_000
class UserConfigUpdate(BaseModel): class UserConfigUpdate(BaseModel):
email: str | None = None
bio: str | None = None bio: str | None = None
@@ -24,6 +39,23 @@ class PasswordUpdate(BaseModel):
new_password: str new_password: str
class OtpUpdate(BaseModel):
action: str
code: str | None = None
current_password: str | None = None
recovery_code: str | None = None
class AdditionalEmail(BaseModel):
email: str
class OtpRecovery(BaseModel):
current_password: str
recovery_code: str
class UserPluginConfigUpdate(BaseModel): class UserPluginConfigUpdate(BaseModel):
instance: str | None = None instance: str | None = None
access_token: str | None = None access_token: str | None = None
@@ -44,7 +76,10 @@ def get_current_user_profile(user: dict = Depends(get_current_user)):
).fetchone() ).fetchone()
if row is None: if row is None:
raise HTTPException(status_code=404, detail='User not found') raise HTTPException(status_code=404, detail='User not found')
return dict(row) profile = dict(row)
profile.pop('otp_secret', None)
profile.pop('password_hash', None)
return profile
@router.put('/me') @router.put('/me')
@@ -57,7 +92,6 @@ def update_current_user_profile(
if current is None: if current is None:
raise HTTPException(status_code=404, detail='User not found') raise HTTPException(status_code=404, detail='User not found')
email = payload.email or current['email']
bio = payload.bio if payload.bio is not None else current['bio'] bio = payload.bio if payload.bio is not None else current['bio']
conn.execute( conn.execute(
@@ -66,7 +100,7 @@ def update_current_user_profile(
SET email = ?, bio = ?, updated_at = CURRENT_TIMESTAMP SET email = ?, bio = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ? WHERE id = ?
''', ''',
(email, bio, user['id']), (current['email'], bio, user['id']),
) )
conn.commit() conn.commit()
@@ -77,7 +111,7 @@ def update_current_user_profile(
def update_password(payload: PasswordUpdate, user: dict = Depends(get_current_user)): def update_password(payload: PasswordUpdate, user: dict = Depends(get_current_user)):
if len(payload.new_password) < 8: if len(payload.new_password) < 8:
raise HTTPException(status_code=422, detail='New password must be at least 8 characters') raise HTTPException(status_code=422, detail='New password must be at least 8 characters')
if hash_password(payload.current_password) != user['password_hash']: if not verify_password(payload.current_password, user['password_hash']):
raise HTTPException(status_code=400, detail='Current password is incorrect') raise HTTPException(status_code=400, detail='Current password is incorrect')
with get_connection() as conn: with get_connection() as conn:
@@ -86,9 +120,188 @@ def update_password(payload: PasswordUpdate, user: dict = Depends(get_current_us
(hash_password(payload.new_password), user['id']), (hash_password(payload.new_password), user['id']),
) )
conn.commit() conn.commit()
record_audit_event(user['id'], 'password_changed', 'user', user['id'])
return {'status': 'password_updated'} return {'status': 'password_updated'}
@router.get('/otp')
def get_otp(user: dict = Depends(get_current_user)):
return {'enabled': bool(user['otp_enabled'])}
@router.post('/otp/setup')
def setup_otp(user: dict = Depends(get_current_user)):
if user['otp_enabled']:
raise HTTPException(status_code=409, detail='One-time password is already enabled')
secret = create_secret()
with get_connection() as conn:
conn.execute('UPDATE users SET otp_secret = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (encrypt_secret(secret), user['id']))
conn.commit()
record_audit_event(user['id'], 'otp_enrolled', 'user', user['id'])
return {
'secret': secret,
'otpauth_url': provisioning_uri(secret, user['username']),
'recovery_codes': create_recovery_codes(user['id']),
}
@router.post('/otp')
def update_otp(payload: OtpUpdate, user: dict = Depends(get_current_user)):
if payload.action not in {'enable', 'disable'}:
raise HTTPException(status_code=422, detail='OTP action must be enable or disable')
if payload.action == 'disable' and not payload.current_password:
raise HTTPException(status_code=400, detail='Current password is required to disable one-time password')
if payload.action == 'disable' and not verify_password(payload.current_password, user['password_hash']):
raise HTTPException(status_code=400, detail='Current password is incorrect')
valid_code = verify_code(decrypt_secret(user['otp_secret']), payload.code)
valid_recovery_code = payload.action == 'disable' and payload.recovery_code and consume_recovery_code(user['id'], payload.recovery_code)
if not valid_code and not valid_recovery_code:
raise HTTPException(status_code=400, detail='Invalid one-time password')
with get_connection() as conn:
if payload.action == 'enable':
conn.execute('UPDATE users SET otp_enabled = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
else:
conn.execute('UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
conn.commit()
record_audit_event(user['id'], f'otp_{payload.action}d', 'user', user['id'])
return {'status': 'updated', 'enabled': payload.action == 'enable'}
@router.post('/otp/recover')
def recover_otp(payload: OtpRecovery, user: dict = Depends(get_current_user)):
if not verify_password(payload.current_password, user['password_hash']):
raise HTTPException(status_code=400, detail='Current password is incorrect')
if not consume_recovery_code(user['id'], payload.recovery_code):
raise HTTPException(status_code=400, detail='Recovery code is invalid or already used')
with get_connection() as conn:
conn.execute(
'UPDATE users SET otp_enabled = 0, otp_secret = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
(user['id'],),
)
conn.commit()
record_audit_event(user['id'], 'otp_recovered', 'user', user['id'])
return {'status': 'otp_recovered', 'enabled': False}
@router.get('/emails')
def get_additional_emails(user: dict = Depends(get_current_user)):
return [{'email': user['email'], 'verified': bool(user['email_verified']), 'primary': True}] + list_user_email_addresses(user['id'])
@router.post('/emails', status_code=201)
def add_additional_email(payload: AdditionalEmail, request: Request, user: dict = Depends(get_current_user)):
email = payload.email.strip().lower()
if email == user['email'].lower():
raise HTTPException(status_code=409, detail='This is already the primary email address')
with get_connection() as conn:
if conn.execute('SELECT 1 FROM users WHERE lower(email) = ?', (email,)).fetchone():
raise HTTPException(status_code=409, detail='Email address already exists')
additional_count = conn.execute(
'SELECT COUNT(*) AS count FROM user_email_addresses WHERE user_id = ?',
(user['id'],),
).fetchone()['count']
if additional_count >= 5:
raise HTTPException(status_code=422, detail='You can add at most five additional email addresses')
try:
address = add_user_email_address(user['id'], email)
except ValueError as error:
raise HTTPException(status_code=409, detail=str(error)) from error
if smtp_configured():
email_address, token = create_email_verification(user['id'], address['id'])
verification_url = f'{settings.public_url}/api/auth/verify-additional-email?token={token}'
try:
send_verification_email(email_address, user['username'], verification_url)
except Exception as 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:
conn.execute(
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
(f'email_verify_rate:{address["id"]}', json.dumps({'sends': 1, 'last_sent': datetime.now(timezone.utc).isoformat()})),
)
conn.commit()
return address
@router.post('/emails/{address_id}/resend')
def resend_additional_email(address_id: str, request: Request, user: dict = Depends(get_current_user)):
now = datetime.now(timezone.utc)
setting_name = f'email_verify_rate:{address_id}'
with get_connection() as conn:
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
address = conn.execute('SELECT email, verified FROM user_email_addresses WHERE id = ? AND user_id = ?', (address_id, user['id'])).fetchone()
if address is None:
raise HTTPException(status_code=404, detail='Email address not found')
if address['verified']:
raise HTTPException(status_code=409, detail='Email address is already verified')
rate = json.loads(row['value']) if row else {}
last_sent = datetime.fromisoformat(rate['last_sent']) if rate.get('last_sent') else None
cooldown_until = datetime.fromisoformat(rate['cooldown_until']) if rate.get('cooldown_until') else None
if cooldown_until and now < cooldown_until:
retry_after = int((cooldown_until - now).total_seconds()) + 1
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before resending verification email.', headers={'Retry-After': str(retry_after)})
if last_sent and now - last_sent < timedelta(seconds=20):
retry_after = int((timedelta(seconds=20) - (now - last_sent)).total_seconds()) + 1
raise HTTPException(status_code=429, detail=f'Please wait {retry_after} seconds before resending verification email.', headers={'Retry-After': str(retry_after)})
email, token = create_email_verification(user['id'], address_id)
verification_url = f'{settings.public_url}/api/auth/verify-additional-email?token={token}'
try:
send_verification_email(email, user['username'], verification_url)
except Exception as 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
updated = {'sends': sends, 'last_sent': now.isoformat()}
if sends >= 5:
updated['cooldown_until'] = (now + timedelta(minutes=2)).isoformat()
with get_connection() as conn:
conn.execute('''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''', (setting_name, json.dumps(updated)))
conn.commit()
return {'status': 'sent', 'message': f'Verification email sent to {email}.', 'next_allowed_at': (now + timedelta(seconds=20)).isoformat()}
@router.delete('/emails/{address_id}')
def remove_additional_email(address_id: str, user: dict = Depends(get_current_user)):
with get_connection() as conn:
cursor = conn.execute('DELETE FROM user_email_addresses WHERE id = ? AND user_id = ?', (address_id, user['id']))
conn.commit()
if cursor.rowcount == 0:
raise HTTPException(status_code=404, detail='Email address not found')
record_audit_event(user['id'], 'email_address_deleted', 'email_address', address_id)
return {'status': 'deleted', 'id': address_id}
@router.post('/emails/{address_id}/make-primary')
def make_email_primary(address_id: str, user: dict = Depends(get_current_user)):
with get_connection() as conn:
address = conn.execute(
'SELECT email, verified FROM user_email_addresses WHERE id = ? AND user_id = ?',
(address_id, user['id']),
).fetchone()
if address is None:
raise HTTPException(status_code=404, detail='Email address not found')
if not address['verified']:
raise HTTPException(status_code=400, detail='Email address must be validated before it can become primary')
old_email = user['email']
conn.execute(
'DELETE FROM user_email_addresses WHERE id = ? AND user_id = ?',
(address_id, user['id']),
)
conn.execute(
'INSERT INTO user_email_addresses (id, user_id, email, verified) VALUES (?, ?, ?, 1)',
(str(uuid4()), user['id'], old_email),
)
conn.execute(
'UPDATE users SET email = ?, email_verified = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
(address['email'], user['id']),
)
conn.commit()
record_audit_event(user['id'], 'primary_email_changed', 'user', user['id'])
return {'status': 'updated', 'email': address['email']}
@router.get('/labels') @router.get('/labels')
def get_labels(user: dict = Depends(get_current_user)): def get_labels(user: dict = Depends(get_current_user)):
return list_user_labels(user['id']) return list_user_labels(user['id'])
@@ -117,6 +330,7 @@ def edit_label(label_id: str, payload: LabelUpdate, user: dict = Depends(get_cur
def remove_label(label_id: str, user: dict = Depends(get_current_user)): def remove_label(label_id: str, user: dict = Depends(get_current_user)):
if not delete_label(label_id, user['id']): if not delete_label(label_id, user['id']):
raise HTTPException(status_code=404, detail='Label not found or not owned by user') raise HTTPException(status_code=404, detail='Label not found or not owned by user')
record_audit_event(user['id'], 'label_deleted', 'label', label_id)
return {'status': 'deleted', 'id': label_id} return {'status': 'deleted', 'id': label_id}
@@ -125,25 +339,33 @@ async def upload_avatar(
avatar: UploadFile = File(...), avatar: UploadFile = File(...),
user: dict = Depends(get_current_user), user: dict = Depends(get_current_user),
): ):
allowed_types = { if avatar.content_type not in {'image/gif', 'image/jpeg', 'image/png', 'image/webp'}:
'image/gif': '.gif',
'image/jpeg': '.jpg',
'image/png': '.png',
'image/webp': '.webp',
}
suffix = allowed_types.get(avatar.content_type or '')
if suffix is None:
raise HTTPException(status_code=415, detail='Avatar must be a PNG, JPEG, GIF, or WebP image') raise HTTPException(status_code=415, detail='Avatar must be a PNG, JPEG, GIF, or WebP image')
contents = await avatar.read(2 * 1024 * 1024 + 1) contents = await avatar.read(MAX_AVATAR_BYTES + 1)
if len(contents) > 2 * 1024 * 1024: if len(contents) > MAX_AVATAR_BYTES:
raise HTTPException(status_code=413, detail='Avatar must be 2 MB or smaller') raise HTTPException(status_code=413, detail='Avatar must be 2 MB or smaller')
avatar_path = AVATARS_DIR / f'{user["id"]}{suffix}' try:
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
with Image.open(BytesIO(contents)) as image:
if image.width * image.height > MAX_AVATAR_PIXELS:
raise HTTPException(status_code=413, detail='Avatar dimensions are too large')
image.verify()
with Image.open(BytesIO(contents)) as image:
image.load()
normalized = image.convert('RGBA')
except HTTPException:
raise
except (Image.DecompressionBombError, Image.DecompressionBombWarning, UnidentifiedImageError, OSError, ValueError) as error:
raise HTTPException(status_code=415, detail='Avatar content is not a valid image') from error
avatar_path = AVATARS_DIR / f'{user["id"]}.png'
normalized.save(avatar_path, format='PNG', optimize=True)
for existing_path in AVATARS_DIR.glob(f'{user["id"]}.*'): for existing_path in AVATARS_DIR.glob(f'{user["id"]}.*'):
if existing_path != avatar_path: if existing_path != avatar_path:
existing_path.unlink(missing_ok=True) existing_path.unlink(missing_ok=True)
avatar_path.write_bytes(contents)
avatar_url = f'/media/{avatar_path.name}' avatar_url = f'/media/{avatar_path.name}'
with get_connection() as conn: with get_connection() as conn:
@@ -152,6 +374,7 @@ async def upload_avatar(
(avatar_url, user['id']), (avatar_url, user['id']),
) )
conn.commit() conn.commit()
record_audit_event(user['id'], 'avatar_updated', 'user', user['id'])
return {'avatar_url': avatar_url} return {'avatar_url': avatar_url}
@@ -167,6 +390,10 @@ def get_user_plugin_config(plugin_name: str, user: dict = Depends(get_current_us
return {} return {}
config = json.loads(row['config']) if row['config'] else {} config = json.loads(row['config']) if row['config'] else {}
if plugin_name == 'mastodon':
config['configured'] = bool(config.get('instance') and config.get('access_token'))
if config.get('access_token'):
config.pop('access_token')
return config return config
@@ -184,6 +411,8 @@ def update_user_plugin_config(
current_config = json.loads(current['config']) if current and current['config'] else {} current_config = json.loads(current['config']) if current and current['config'] else {}
updates = payload.model_dump(exclude_none=True) updates = payload.model_dump(exclude_none=True)
if updates.get('access_token'):
updates['access_token'] = encrypt_secret(updates['access_token'])
merged = {**current_config, **updates} merged = {**current_config, **updates}
if current is None: if current is None:
@@ -206,4 +435,6 @@ def update_user_plugin_config(
conn.commit() conn.commit()
return merged public_config = dict(merged)
public_config.pop('access_token', None)
return public_config
+55 -4
View File
@@ -1,13 +1,17 @@
## 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 dataclasses import dataclass from dataclasses import dataclass, field
import json
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'
VERSION_FILE = BASE_DIR.parent / 'frontend' / 'version.json'
def normalize_public_url(value: str) -> str: def normalize_public_url(value: str) -> str:
@@ -18,14 +22,25 @@ def normalize_public_url(value: str) -> str:
return f'{scheme}://{value}' return f'{scheme}://{value}'
def load_version() -> str:
# frontend/version.json is the single source of truth for the app version, shared by backend and frontend.
try:
return json.loads(VERSION_FILE.read_text())['version']
except (OSError, KeyError, ValueError):
return '0.0.0'
@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 = field(default_factory=load_version)
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')
token_expiry_days: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_DAYS', '30')) data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
public_url: str = normalize_public_url(os.getenv('LINKLOG_PUBLIC_URL', 'http://localhost:8000')) token_expiry_minutes: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_MINUTES', '15'))
refresh_token_expiry_days: int = int(os.getenv('LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS', '30'))
public_url: str = normalize_public_url(os.getenv('LINKLOG_PUBLIC_URL', 'linklog.example.com'))
smtp_host: str = os.getenv('LINKLOG_SMTP_HOST', '') smtp_host: str = os.getenv('LINKLOG_SMTP_HOST', '')
smtp_port: int = int(os.getenv('LINKLOG_SMTP_PORT', '587')) smtp_port: int = int(os.getenv('LINKLOG_SMTP_PORT', '587'))
smtp_username: str = os.getenv('LINKLOG_SMTP_USERNAME', '') smtp_username: str = os.getenv('LINKLOG_SMTP_USERNAME', '')
@@ -36,8 +51,10 @@ class Settings:
password_reset_expiry_hours: int = int(os.getenv('LINKLOG_PASSWORD_RESET_EXPIRY_HOURS', '1')) password_reset_expiry_hours: int = int(os.getenv('LINKLOG_PASSWORD_RESET_EXPIRY_HOURS', '1'))
mastodon_client_name: str = os.getenv('LINKLOG_MASTODON_CLIENT_NAME', 'LinkLog') mastodon_client_name: str = os.getenv('LINKLOG_MASTODON_CLIENT_NAME', 'LinkLog')
mastodon_oauth_expiry_minutes: int = int(os.getenv('LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES', '10')) mastodon_oauth_expiry_minutes: int = int(os.getenv('LINKLOG_MASTODON_OAUTH_EXPIRY_MINUTES', '10'))
max_post_characters: int = int(os.getenv('LINKLOG_MAX_POST_CHARACTERS', '500'))
log_level: str = os.getenv('LINKLOG_LOG_LEVEL', 'INFO').upper() log_level: str = os.getenv('LINKLOG_LOG_LEVEL', 'INFO').upper()
tracking_params: list[str] = None tracking_params: list[str] = None
feed_page_sizes: list[int] = None
def __post_init__(self): def __post_init__(self):
if self.tracking_params is None: if self.tracking_params is None:
@@ -54,6 +71,40 @@ class Settings:
if configured_params if configured_params
else default_tracking_params else default_tracking_params
) )
if self.feed_page_sizes is None:
default_page_sizes = [25, 100, 250]
configured_sizes = os.getenv('LINKLOG_FRONTEND_LOADPOSTS')
parsed_sizes = []
if configured_sizes:
for item in configured_sizes.split(','):
item = item.strip()
if not item:
continue
try:
value = int(item)
except ValueError:
continue
if value > 0 and value not in parsed_sizes:
parsed_sizes.append(value)
if len(parsed_sizes) == 5:
break
self.feed_page_sizes = parsed_sizes or default_page_sizes
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)}'
+110 -2
View File
@@ -3,7 +3,8 @@
import sqlite3 import sqlite3
import os import os
from hashlib import sha256 from hashlib import scrypt, sha256
import hmac
from pathlib import Path from pathlib import Path
from uuid import uuid4 from uuid import uuid4
@@ -15,7 +16,28 @@ AVATARS_DIR.mkdir(parents=True, exist_ok=True)
def hash_password(password: str) -> str: def hash_password(password: str) -> str:
return sha256(password.encode('utf-8')).hexdigest() salt = os.urandom(16)
digest = scrypt(password.encode('utf-8'), salt=salt, n=16_384, r=8, p=1, dklen=32)
return f'scrypt$16384$8$1${salt.hex()}${digest.hex()}'
def verify_password(password: str, stored_hash: str) -> bool:
if stored_hash.startswith('scrypt$'):
try:
algorithm, cost, block_size, parallelism, salt_hex, digest_hex = stored_hash.split('$')
if algorithm != 'scrypt':
return False
digest = scrypt(
password.encode('utf-8'), salt=bytes.fromhex(salt_hex),
n=int(cost), r=int(block_size), p=int(parallelism), dklen=32,
)
return hmac.compare_digest(digest.hex(), digest_hex)
except (ValueError, TypeError):
return False
if len(stored_hash) == 64:
legacy_digest = sha256(password.encode('utf-8')).hexdigest()
return hmac.compare_digest(legacy_digest, stored_hash)
return False
DEFAULT_TAGS = ('#Internet', '#Cybersecurity', '#Fediverse', '#Food', '#Photography', '#Music', '#AI') DEFAULT_TAGS = ('#Internet', '#Cybersecurity', '#Fediverse', '#Food', '#Photography', '#Music', '#AI')
@@ -152,6 +174,92 @@ CREATE TABLE IF NOT EXISTS mastodon_oauth_states (
CREATE INDEX IF NOT EXISTS idx_mastodon_oauth_states_state_hash CREATE INDEX IF NOT EXISTS idx_mastodon_oauth_states_state_hash
ON mastodon_oauth_states(state_hash); ON mastodon_oauth_states(state_hash);
'''), '''),
(9, '''
ALTER TABLE links ADD COLUMN mastodon_posted INTEGER NOT NULL DEFAULT 0;
ALTER TABLE links ADD COLUMN mastodon_post_id TEXT;
ALTER TABLE links ADD COLUMN mastodon_posted_at TEXT;
'''),
(10, '''
ALTER TABLE links ADD COLUMN mastodon_post_ids TEXT;
UPDATE links
SET mastodon_post_ids = CASE
WHEN mastodon_post_id IS NOT NULL THEN json_array(mastodon_post_id)
ELSE '[]'
END
WHERE mastodon_post_ids IS NULL;
'''),
(11, '''
ALTER TABLE users ADD COLUMN otp_secret TEXT;
ALTER TABLE users ADD COLUMN otp_enabled INTEGER NOT NULL DEFAULT 0;
'''),
(12, '''
CREATE TABLE IF NOT EXISTS user_email_addresses (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
verified INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS email_address_verification_tokens (
id TEXT PRIMARY KEY,
email_address_id TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(email_address_id) REFERENCES user_email_addresses(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_user_email_addresses_user_id ON user_email_addresses(user_id);
CREATE INDEX IF NOT EXISTS idx_email_address_verification_tokens_address_id ON email_address_verification_tokens(email_address_id);
'''),
(13, '''
CREATE TABLE IF NOT EXISTS pending_primary_email_changes (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
'''),
(14, '''
DROP TABLE IF EXISTS pending_primary_email_changes;
'''),
(15, '''
ALTER TABLE tokens ADD COLUMN device_id TEXT;
ALTER TABLE tokens ADD COLUMN token_family_id TEXT;
CREATE INDEX IF NOT EXISTS idx_tokens_device_id ON tokens(device_id);
CREATE INDEX IF NOT EXISTS idx_tokens_family_id ON tokens(token_family_id);
'''),
(16, '''
CREATE TABLE IF NOT EXISTS otp_recovery_codes (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
code_hash TEXT NOT NULL UNIQUE,
used INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
used_at TEXT,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_otp_recovery_codes_user_id ON otp_recovery_codes(user_id);
'''),
(17, '''
CREATE TABLE IF NOT EXISTS security_audit_events (
id TEXT PRIMARY KEY,
actor_id TEXT,
action TEXT NOT NULL,
target_type TEXT NOT NULL,
target_id TEXT,
outcome TEXT NOT NULL DEFAULT 'success',
details TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(actor_id) REFERENCES users(id) ON DELETE SET NULL
);
CREATE INDEX IF NOT EXISTS idx_security_audit_events_created_at ON security_audit_events(created_at);
CREATE INDEX IF NOT EXISTS idx_security_audit_events_actor_id ON security_audit_events(actor_id);
''')
] ]
+25 -14
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 list_public_links from backend.app.services.link_service import get_public_profile
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,14 +46,14 @@ 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)
async def public_root(request: Request): async def public_root(request: Request):
if not has_administrator(): if not has_administrator():
return RedirectResponse('/setup') return RedirectResponse('/setup')
feed = list_public_links() return templates.TemplateResponse(request, 'feed.html', {})
return templates.TemplateResponse(request, 'feed.html', {'feed': feed})
@app.get('/admin', response_class=HTMLResponse) @app.get('/admin', response_class=HTMLResponse)
@@ -66,6 +77,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', {})
@@ -98,16 +116,9 @@ def health_check():
@app.get('/{username}', response_class=HTMLResponse) @app.get('/{username}', response_class=HTMLResponse)
@app.get('/{username}/', response_class=HTMLResponse) @app.get('/{username}/', response_class=HTMLResponse)
async def public_user_feed(request: Request, username: str): async def public_user_feed(request: Request, username: str):
feed = list_public_links(username) profile = get_public_profile(username)
profile = None
if feed:
profile = {
'username': feed[0]['username'],
'avatar_url': feed[0]['avatar_url'],
'bio': feed[0]['bio'],
}
return templates.TemplateResponse( return templates.TemplateResponse(
request, request,
'feed.html', 'feed.html',
{'feed': feed, 'profile': profile, 'user_filter': username}, {'profile': profile, 'user_filter': username},
) )
+6
View File
@@ -2,18 +2,24 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
class BasePlugin: class BasePlugin:
"""Define the interface shared by LinkLog event plugins."""
name = 'base' name = 'base'
version = '1.0.0' version = '1.0.0'
enabled = True enabled = True
def initialize(self, config=None): def initialize(self, config=None):
"""Apply plugin configuration and report whether initialization succeeded."""
return True return True
def validate_config(self, config): def validate_config(self, config):
"""Validate configuration and return a ``(valid, message)`` pair."""
return True, 'ok' return True, 'ok'
def handle_event(self, event): def handle_event(self, event):
"""Handle a LinkLog event; subclasses must provide the implementation."""
raise NotImplementedError raise NotImplementedError
def health_check(self): def health_check(self):
"""Return the plugin name and basic health status."""
return {'name': self.name, 'status': 'ok'} return {'name': self.name, 'status': 'ok'}
+23
View File
@@ -0,0 +1,23 @@
import json
from uuid import uuid4
from backend.app.database import get_connection
def record_audit_event(
actor_id: str | None,
action: str,
target_type: str,
target_id: str | None = None,
outcome: str = 'success',
details: dict | None = None,
) -> None:
safe_details = details or {}
with get_connection() as conn:
conn.execute(
'''INSERT INTO security_audit_events
(id, actor_id, action, target_type, target_id, outcome, details)
VALUES (?, ?, ?, ?, ?, ?, ?)''',
(str(uuid4()), actor_id, action, target_type, target_id, outcome, json.dumps(safe_details)),
)
conn.commit()
+31 -14
View File
@@ -2,26 +2,43 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
from datetime import datetime, timezone from datetime import datetime, timezone
from hashlib import sha256 from backend.app.database import get_connection, hash_password, verify_password
from backend.app.database import get_connection
def hash_password(password: str) -> str: def authenticate_user(email: str, password: str):
return sha256(password.encode('utf-8')).hexdigest()
def authenticate_user(username: str, password: str):
password_hash = hash_password(password)
with get_connection() as conn: with get_connection() as conn:
row = conn.execute( row = conn.execute(
'SELECT * FROM users WHERE username = ? AND password_hash = ?', '''SELECT * FROM users WHERE email = ?
(username, password_hash), UNION ALL
SELECT users.* FROM users JOIN user_email_addresses
ON user_email_addresses.user_id = users.id
WHERE user_email_addresses.email = ? AND user_email_addresses.verified = 1
LIMIT 1''',
(email, email),
).fetchone() ).fetchone()
return dict(row) if row else None if row is None or not verify_password(password, row['password_hash']):
return None
user = dict(row)
if not row['password_hash'].startswith('scrypt$'):
conn.execute(
'UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
(hash_password(password), row['id']),
)
conn.commit()
user['password_hash'] = conn.execute(
'SELECT password_hash FROM users WHERE id = ?', (row['id'],)
).fetchone()['password_hash']
return user
def find_user(username: str): def find_user(email: str):
with get_connection() as conn: with get_connection() as conn:
row = conn.execute('SELECT * FROM users WHERE username = ?', (username,)).fetchone() row = conn.execute('SELECT * FROM users WHERE email = ?', (email,)).fetchone()
if row is None:
row = conn.execute(
'''SELECT users.* FROM users JOIN user_email_addresses
ON user_email_addresses.user_id = users.id
WHERE user_email_addresses.email = ?''',
(email,),
).fetchone()
return dict(row) if row else None return dict(row) if row else None
+73
View File
@@ -0,0 +1,73 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from datetime import datetime, timedelta, timezone
from hashlib import sha256
from secrets import token_urlsafe
from uuid import uuid4
from backend.app.core.config import settings
from backend.app.database import get_connection
from backend.app.services.email_service import send_verification_email
def list_user_email_addresses(user_id: str) -> list[dict]:
with get_connection() as conn:
rows = conn.execute(
'SELECT id, email, verified, created_at FROM user_email_addresses WHERE user_id = ? ORDER BY created_at',
(user_id,),
).fetchall()
return [dict(row) | {'verified': bool(row['verified']), 'can_be_primary': bool(row['verified'])} for row in rows]
def add_user_email_address(user_id: str, email: str) -> dict:
email = email.strip().lower()
if not email:
raise ValueError('Email address is required')
with get_connection() as conn:
try:
row = conn.execute(
'INSERT INTO user_email_addresses (id, user_id, email) VALUES (?, ?, ?) RETURNING id, email, verified, created_at',
(str(uuid4()), user_id, email),
).fetchone()
conn.commit()
except Exception as error:
if 'UNIQUE constraint failed' in str(error):
raise ValueError('Email address already exists') from error
raise
return dict(row) | {'verified': bool(row['verified']), 'can_be_primary': bool(row['verified'])}
def create_email_verification(user_id: str, address_id: str) -> tuple[str, str]:
token = token_urlsafe(32)
expires_at = datetime.now(timezone.utc) + timedelta(hours=settings.email_verification_expiry_hours)
with get_connection() as conn:
address = conn.execute(
'SELECT email FROM user_email_addresses WHERE id = ? AND user_id = ?',
(address_id, user_id),
).fetchone()
if address is None:
raise ValueError('Email address not found')
conn.execute('DELETE FROM email_address_verification_tokens WHERE email_address_id = ?', (address_id,))
conn.execute(
'INSERT INTO email_address_verification_tokens (id, email_address_id, token_hash, expires_at) VALUES (?, ?, ?, ?)',
(str(uuid4()), address_id, sha256(token.encode()).hexdigest(), expires_at.isoformat()),
)
conn.commit()
return address['email'], token
def verify_user_email_address(token: str) -> bool:
now = datetime.now(timezone.utc).isoformat()
with get_connection() as conn:
row = conn.execute(
'''SELECT email_address_id FROM email_address_verification_tokens
WHERE token_hash = ? AND expires_at > ?''',
(sha256(token.encode()).hexdigest(), now),
).fetchone()
if row is None:
return False
conn.execute('UPDATE user_email_addresses SET verified = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?', (row['email_address_id'],))
conn.execute('DELETE FROM email_address_verification_tokens WHERE email_address_id = ?', (row['email_address_id'],))
conn.commit()
return True
+73 -8
View File
@@ -2,11 +2,56 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
from email.message import EmailMessage from email.message import EmailMessage
from html import escape
from pathlib import Path
from smtplib import SMTP from smtplib import SMTP
import json import json
from urllib.parse import urlparse
from backend.app.core.config import settings from backend.app.core.config import settings
from backend.app.database import get_connection from backend.app.database import get_connection
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
LOGO_PATH = Path(__file__).resolve().parents[3] / 'frontend' / 'static' / 'logo.svg'
def _html_email(body_html: str) -> str:
public_url = settings.public_url
parsed_url = urlparse(public_url)
public_hostname = parsed_url.hostname or public_url
safe_public_url = escape(public_url, quote=True)
safe_public_hostname = escape(public_hostname)
return f'''<!doctype html>
<html lang="en">
<body style="margin:0;background:#1e1e2e;color:#cdd6f4;font-family:Arial,sans-serif;line-height:1.6;">
<div style="max-width:620px;margin:32px auto;padding:0 20px;">
<div style="background:#11111b;border:1px solid #45475a;border-radius:12px;overflow:hidden;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#181825;">
<tr>
<td style="padding:20px 24px;text-align:left;vertical-align:top;width:50px;">
<img src="cid:linklog-logo" alt="LinkLog" width="50" height="50" style="display:block;width:50px;height:50px;">
</td>
<td style="padding:20px 0 20px 12px;text-align:left;vertical-align:top;">
<span style="color:#cba6f7;font-family:'Asset',Georgia,serif;font-size:18px;line-height:50px;">Hello, a message from <a href="{safe_public_url}" style="color:#cba6f7;text-decoration:underline;">{safe_public_hostname}</a></span>
</td>
</tr>
</table>
<div style="padding:28px 32px;">{body_html}</div>
</div>
<p style="margin:18px 0;text-align:center;color:#a6adc8;font-size:12px;">LinkLog</p>
</div>
</body>
</html>'''
def _add_html_body(message: EmailMessage, html_body: str) -> None:
message.add_alternative(_html_email(html_body), subtype='html')
html_part = message.get_payload()[-1]
try:
logo = LOGO_PATH.read_bytes()
except OSError:
return
html_part.add_related(logo, maintype='image', subtype='svg+xml', cid='<linklog-logo>')
def get_smtp_settings() -> dict: def get_smtp_settings() -> dict:
@@ -22,6 +67,7 @@ def get_smtp_settings() -> dict:
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone() row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone()
if row: if row:
values.update(json.loads(row['value'])) values.update(json.loads(row['value']))
values['smtp_password'] = decrypt_secret(values['smtp_password'])
return values return values
@@ -30,19 +76,20 @@ def save_smtp_settings(values: dict) -> None:
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)
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''', ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
('smtp', json.dumps(values)), ('smtp', json.dumps({**values, 'smtp_password': encrypt_secret(values['smtp_password'])})),
) )
conn.commit() conn.commit()
def smtp_configured() -> bool: def smtp_configured(smtp_values: dict | None = None) -> bool:
smtp = get_smtp_settings() smtp = smtp_values or get_smtp_settings()
return bool(smtp['smtp_host'] and smtp['smtp_from']) return bool(smtp['smtp_host'] and smtp['smtp_from'])
def send_message(email: str, subject: str, body: str) -> None: def send_message(email: str, subject: str, body: str, html_body: str | None = None,
smtp = get_smtp_settings() smtp_values: dict | None = None) -> None:
if not smtp_configured(): smtp = smtp_values or get_smtp_settings()
if not smtp_configured(smtp):
raise RuntimeError('SMTP is not configured; set LINKLOG_SMTP_HOST and LINKLOG_SMTP_FROM') raise RuntimeError('SMTP is not configured; set LINKLOG_SMTP_HOST and LINKLOG_SMTP_FROM')
message = EmailMessage() message = EmailMessage()
@@ -50,6 +97,8 @@ def send_message(email: str, subject: str, body: str) -> None:
message['From'] = smtp['smtp_from'] message['From'] = smtp['smtp_from']
message['To'] = email message['To'] = email
message.set_content(body) message.set_content(body)
if html_body:
_add_html_body(message, html_body)
with SMTP(smtp['smtp_host'], smtp['smtp_port'], timeout=10) as connection: with SMTP(smtp['smtp_host'], smtp['smtp_port'], timeout=10) as connection:
if smtp['smtp_use_tls']: if smtp['smtp_use_tls']:
@@ -60,24 +109,40 @@ def send_message(email: str, subject: str, body: str) -> None:
def send_verification_email(email: str, username: str, verification_url: str) -> None: def send_verification_email(email: str, username: str, verification_url: str) -> None:
safe_username = escape(username)
safe_url = escape(verification_url, quote=True)
send_message( send_message(
email, email,
'Verify your LinkLog email address', 'Verify your LinkLog email address',
f'Hello {username},\n\n' f'Hello {username},\n\n'
f'Verify your LinkLog email address by opening this link:\n{verification_url}\n\n' f'Verify your LinkLog email address by opening this link:\n{verification_url}\n\n'
f'This link expires in {settings.email_verification_expiry_hours} hours.\n', f'This link expires in {settings.email_verification_expiry_hours} hours.\n',
f'<p>Hello {safe_username},</p><p>Verify your LinkLog email address:</p>'
f'<p><a href="{safe_url}" style="display:inline-block;padding:10px 16px;background:#89b4fa;color:#11111b;text-decoration:none;border-radius:6px;">Verify email address</a></p>'
f'<p style="color:#a6adc8;font-size:14px;">This link expires in {settings.email_verification_expiry_hours} hours.</p>',
) )
def send_test_email(email: str) -> None: def send_test_email(email: str, smtp_values: dict | None = None) -> None:
send_message(email, 'LinkLog SMTP test', 'This is a test message from LinkLog. SMTP is configured correctly.\n') send_message(
email,
'LinkLog SMTP test',
'This is a test message from LinkLog. SMTP is configured correctly.\n',
'<p>This is a test message from LinkLog.</p><p style="color:#a6adc8;">SMTP is configured correctly.</p>',
smtp_values=smtp_values,
)
def send_password_reset_email(email: str, username: str, reset_url: str) -> None: def send_password_reset_email(email: str, username: str, reset_url: str) -> None:
safe_username = escape(username)
safe_url = escape(reset_url, quote=True)
send_message( send_message(
email, email,
'Reset your LinkLog password', 'Reset your LinkLog password',
f'Hello {username},\n\n' f'Hello {username},\n\n'
f'Reset your LinkLog password by opening this link:\n{reset_url}\n\n' f'Reset your LinkLog password by opening this link:\n{reset_url}\n\n'
f'This link expires in {settings.password_reset_expiry_hours} hours.\n', f'This link expires in {settings.password_reset_expiry_hours} hours.\n',
f'<p>Hello {safe_username},</p><p>Reset your LinkLog password:</p>'
f'<p><a href="{safe_url}" style="display:inline-block;padding:10px 16px;background:#f38ba8;color:#11111b;text-decoration:none;border-radius:6px;">Reset password</a></p>'
f'<p style="color:#a6adc8;font-size:14px;">This link expires in {settings.password_reset_expiry_hours} hours.</p>',
) )
+169 -14
View File
@@ -2,6 +2,9 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
from datetime import datetime, timezone from datetime import datetime, timezone
import json
import re
from urllib.parse import urlparse
from uuid import uuid4 from uuid import uuid4
from backend.app.core.security import clean_url from backend.app.core.security import clean_url
@@ -26,7 +29,7 @@ def normalize_tags(tags: list[str] | None) -> list[str]:
return normalized return normalized
def save_link_tags(conn, link_id: str, tags: list[str]) -> None: def save_link_tags(conn, link_id: str, tags: list[str], user_id: str | None = None) -> list[str]:
canonical_tags = [] canonical_tags = []
for tag in tags: for tag in tags:
tag_row = conn.execute( tag_row = conn.execute(
@@ -35,8 +38,8 @@ def save_link_tags(conn, link_id: str, tags: list[str]) -> None:
).fetchone() ).fetchone()
if tag_row is None: if tag_row is None:
conn.execute( conn.execute(
'INSERT INTO tags (id, name) VALUES (?, ?)', 'INSERT INTO tags (id, name, created_by) VALUES (?, ?, ?)',
(str(uuid4()), tag), (str(uuid4()), tag, user_id),
) )
tag_row = conn.execute('SELECT id FROM tags WHERE name = ?', (tag,)).fetchone() tag_row = conn.execute('SELECT id FROM tags WHERE name = ?', (tag,)).fetchone()
conn.execute( conn.execute(
@@ -102,29 +105,135 @@ def create_link(
record['is_public'], record['is_public'],
), ),
) )
stored_tags = save_link_tags(conn, record['id'], normalized_tags) stored_tags = save_link_tags(conn, record['id'], normalized_tags, user_id=user_id)
conn.commit() conn.commit()
record['tags'] = stored_tags record['tags'] = stored_tags
return record return record
def list_public_links(username: str | None = None): def find_owned_link_by_title_url(user_id: str, title: str, url: str) -> dict | None:
cleaned_url = clean_url(url)
with get_connection() as conn:
row = conn.execute(
'SELECT * FROM links WHERE user_id = ? AND title = ? AND url = ? ORDER BY created_at DESC LIMIT 1',
(user_id, title, cleaned_url),
).fetchone()
if row is None:
return None
record = dict(row)
record['tags'] = get_link_tags(conn, record['id'])
return record
def find_owned_link_by_title(user_id: str, title: str) -> dict | None:
with get_connection() as conn:
row = conn.execute(
'SELECT * FROM links WHERE user_id = ? AND title = ? ORDER BY created_at DESC LIMIT 1',
(user_id, title),
).fetchone()
if row is None:
return None
record = dict(row)
record['tags'] = get_link_tags(conn, record['id'])
return record
def _tokenize_search(value: str) -> list[str]:
return [group1 or group2 for group1, group2 in re.findall(r'"([^"]+)"|(\S+)', value or '')]
def _parse_search_query(value: str) -> dict:
groups = [[]]
excluded = []
sites = []
for token in _tokenize_search(value):
if token.upper() == 'OR':
groups.append([])
continue
is_excluded = token.startswith('-') and len(token) > 1
term = token[1:] if is_excluded else token
site_match = re.match(r'^site:(\S+)$', term, re.IGNORECASE)
if site_match and not is_excluded:
sites.append(site_match.group(1).lower())
continue
if is_excluded:
excluded.append(term.lower())
else:
groups[-1].append(term.lower())
return {'groups': [group for group in groups if group], 'excluded': excluded, 'sites': sites}
def _searchable_text(record: dict) -> str:
parts = [record.get('title'), record.get('url'), record.get('comment'), record.get('username'), *(record.get('tags') or [])]
return ' '.join(part for part in parts if part).lower()
def _matches_search(record: dict, query: str) -> bool:
if not query or not query.strip():
return True
parsed = _parse_search_query(query)
text = _searchable_text(record)
def site_matches(site: str) -> bool:
hostname = (urlparse(record.get('url') or '').hostname or '').lower()
return hostname == site or hostname.endswith(f'.{site}')
matches_site = all(site_matches(site) for site in parsed['sites'])
matches_group = not parsed['groups'] or any(all(term in text for term in group) for group in parsed['groups'])
excludes_term = any(term in text for term in parsed['excluded'])
return matches_site and matches_group and not excludes_term
def list_public_links(
username: str | None = None,
tag: str | None = None,
search: str | None = None,
sort: str = 'newest',
page: int = 1,
page_size: int | None = None,
) -> dict:
order = 'ASC' if sort == 'oldest' else 'DESC'
with get_connection() as conn: with get_connection() as conn:
rows = conn.execute( rows = conn.execute(
''' f'''
SELECT links.*, users.username, users.avatar_url, users.bio SELECT links.*, users.username, users.avatar_url, users.bio
FROM links FROM links
JOIN users ON users.id = links.user_id JOIN users ON users.id = links.user_id
WHERE links.is_public = 1 WHERE links.is_public = 1
AND (? IS NULL OR users.username = ?) AND (? IS NULL OR users.username = ?)
ORDER BY created_at DESC AND (
? IS NULL OR links.id IN (
SELECT link_tags.link_id FROM link_tags
JOIN tags ON tags.id = link_tags.tag_id
WHERE lower(tags.name) = lower(?)
)
)
ORDER BY links.created_at {order}
''', ''',
(username, username), (username, username, tag, tag),
).fetchall() ).fetchall()
records = [dict(row) for row in rows] records = [dict(row) for row in rows]
for record in records: for record in records:
record['tags'] = get_link_tags(conn, record['id']) record['tags'] = get_link_tags(conn, record['id'])
return records
if search:
records = [record for record in records if _matches_search(record, search)]
total = len(records)
if page_size:
start = max(page - 1, 0) * page_size
records = records[start:start + page_size]
return {'items': records, 'total': total}
def get_public_profile(username: str) -> dict | None:
with get_connection() as conn:
row = conn.execute(
'SELECT username, avatar_url, bio FROM users WHERE username = ?',
(username,),
).fetchone()
return dict(row) if row else None
def update_link( def update_link(
@@ -149,7 +258,7 @@ def update_link(
if cursor.rowcount == 0: if cursor.rowcount == 0:
return None return None
conn.execute('DELETE FROM link_tags WHERE link_id = ?', (link_id,)) conn.execute('DELETE FROM link_tags WHERE link_id = ?', (link_id,))
stored_tags = save_link_tags(conn, link_id, normalized_tags) stored_tags = save_link_tags(conn, link_id, normalized_tags, user_id=user_id)
conn.commit() conn.commit()
row = conn.execute('SELECT * FROM links WHERE id = ?', (link_id,)).fetchone() row = conn.execute('SELECT * FROM links WHERE id = ?', (link_id,)).fetchone()
record = dict(row) record = dict(row)
@@ -157,6 +266,44 @@ def update_link(
return record return record
def delete_link(link_id: str, user_id: str) -> bool:
with get_connection() as conn:
cursor = conn.execute(
'DELETE FROM links WHERE id = ? AND user_id = ?',
(link_id, user_id),
)
conn.commit()
return cursor.rowcount > 0
def get_owned_link(link_id: str, user_id: str) -> dict | None:
with get_connection() as conn:
row = conn.execute(
'SELECT * FROM links WHERE id = ? AND user_id = ?',
(link_id, user_id),
).fetchone()
return dict(row) if row else None
def mark_mastodon_posted(link_id: str, user_id: str, post_id: str | None) -> bool:
with get_connection() as conn:
current = conn.execute(
'SELECT mastodon_post_ids FROM links WHERE id = ? AND user_id = ?',
(link_id, user_id),
).fetchone()
post_ids = json.loads(current['mastodon_post_ids']) if current and current['mastodon_post_ids'] else []
if post_id and post_id not in post_ids:
post_ids.append(post_id)
cursor = conn.execute(
'''UPDATE links
SET mastodon_posted = 1, mastodon_post_id = ?, mastodon_post_ids = ?, mastodon_posted_at = CURRENT_TIMESTAMP
WHERE id = ? AND user_id = ?''',
(post_id, json.dumps(post_ids), link_id, user_id),
)
conn.commit()
return cursor.rowcount > 0
def list_public_users(): def list_public_users():
with get_connection() as conn: with get_connection() as conn:
rows = conn.execute( rows = conn.execute(
@@ -180,7 +327,15 @@ def list_tags():
def list_user_labels(user_id: str): def list_user_labels(user_id: str):
with get_connection() as conn: with get_connection() as conn:
rows = conn.execute( rows = conn.execute(
'SELECT id, name, created_by FROM tags WHERE created_by = ? ORDER BY name', '''
SELECT tags.id, tags.name, tags.created_by, users.username AS creator
FROM tags
LEFT JOIN users ON users.id = tags.created_by
WHERE tags.created_by IS NULL
OR tags.created_by = ?
OR users.is_admin = 1
ORDER BY tags.name
''',
(user_id,), (user_id,),
).fetchall() ).fetchall()
return [dict(row) for row in rows] return [dict(row) for row in rows]
@@ -206,7 +361,7 @@ def create_label(user_id: str, name: str):
return {'id': label_id, 'name': label, 'created_by': user_id} return {'id': label_id, 'name': label, 'created_by': user_id}
def update_label(label_id: str, user_id: str, name: str): def update_label(label_id: str, user_id: str | None = None, name: str = '', is_admin: bool = False):
normalized = normalize_tags([name]) normalized = normalize_tags([name])
if not normalized: if not normalized:
raise ValueError('Label cannot be empty') raise ValueError('Label cannot be empty')
@@ -214,7 +369,7 @@ def update_label(label_id: str, user_id: str, name: str):
current = conn.execute( current = conn.execute(
'SELECT id, name, created_by FROM tags WHERE id = ?', (label_id,) 'SELECT id, name, created_by FROM tags WHERE id = ?', (label_id,)
).fetchone() ).fetchone()
if current is None or current['created_by'] != user_id: if current is None or (not is_admin and current['created_by'] != user_id):
return None return None
duplicate = conn.execute( duplicate = conn.execute(
'SELECT id FROM tags WHERE lower(name) = lower(?) AND id != ?', 'SELECT id FROM tags WHERE lower(name) = lower(?) AND id != ?',
@@ -224,7 +379,7 @@ def update_label(label_id: str, user_id: str, name: str):
raise ValueError('Label already exists') raise ValueError('Label already exists')
conn.execute('UPDATE tags SET name = ? WHERE id = ?', (normalized[0], label_id)) conn.execute('UPDATE tags SET name = ? WHERE id = ?', (normalized[0], label_id))
conn.commit() conn.commit()
return {'id': label_id, 'name': normalized[0], 'created_by': user_id} return {'id': label_id, 'name': normalized[0], 'created_by': current['created_by']}
def delete_label(label_id: str, user_id: str | None = None, is_admin: bool = False): def delete_label(label_id: str, user_id: str | None = None, is_admin: bool = False):
+64
View File
@@ -0,0 +1,64 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from datetime import datetime, timedelta, timezone
from hashlib import sha256
import json
from backend.app.database import get_connection
MAX_FAILURES = 5
FAILURE_WINDOW = timedelta(minutes=15)
LOCKOUT_DURATION = timedelta(minutes=2)
def _setting_name(ip_address: str, email: str) -> str:
key = sha256(f'{ip_address}\0{email.casefold()}'.encode('utf-8')).hexdigest()
return f'login_rate:{key}'
def _read_rate(setting_name: str) -> dict:
with get_connection() as conn:
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
if not row:
return {}
try:
return json.loads(row['value'])
except (TypeError, json.JSONDecodeError):
return {}
def check_login_allowed(ip_address: str, email: str) -> int | None:
rate = _read_rate(_setting_name(ip_address, email))
now = datetime.now(timezone.utc)
locked_until = datetime.fromisoformat(rate['locked_until']) if rate.get('locked_until') else None
if locked_until and locked_until > now:
return int((locked_until - now).total_seconds()) + 1
return None
def record_login_failure(ip_address: str, email: str) -> None:
setting_name = _setting_name(ip_address, email)
now = datetime.now(timezone.utc)
rate = _read_rate(setting_name)
first_failure = datetime.fromisoformat(rate['first_failure']) if rate.get('first_failure') else now
if now - first_failure >= FAILURE_WINDOW:
rate = {}
first_failure = now
failures = int(rate.get('failures', 0)) + 1
updated = {'failures': failures, 'first_failure': first_failure.isoformat()}
if failures >= MAX_FAILURES:
updated['locked_until'] = (now + LOCKOUT_DURATION).isoformat()
with get_connection() as conn:
conn.execute(
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
(setting_name, json.dumps(updated)),
)
conn.commit()
def clear_login_failures(ip_address: str, email: str) -> None:
with get_connection() as conn:
conn.execute('DELETE FROM app_settings WHERE name = ?', (_setting_name(ip_address, email),))
conn.commit()
+11 -10
View File
@@ -7,18 +7,17 @@ import json
from secrets import token_urlsafe from secrets import token_urlsafe
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.error import HTTPError from urllib.error import HTTPError
from urllib.request import Request, urlopen from urllib.request import Request
from uuid import uuid4 from uuid import uuid4
from backend.app.core.config import settings from backend.app.core.config import settings
from backend.app.database import get_connection from backend.app.database import get_connection
from backend.app.services.secret_store import decrypt_secret, encrypt_secret
from backend.app.services.mastodon_security import open_no_redirect, validate_public_instance
def normalize_instance(instance: str) -> str: def normalize_instance(instance: str) -> str:
value = instance.strip().rstrip('/') return validate_public_instance(instance)
if not value:
raise ValueError('Mastodon instance is required')
return value if '://' in value else f'https://{value}'
def post_form(url: str, values: dict) -> dict: def post_form(url: str, values: dict) -> dict:
@@ -28,7 +27,7 @@ def post_form(url: str, values: dict) -> dict:
headers={'Content-Type': 'application/x-www-form-urlencoded'}, headers={'Content-Type': 'application/x-www-form-urlencoded'},
method='POST', method='POST',
) )
with urlopen(request, timeout=10) as response: with open_no_redirect(request, timeout=10) as response:
return json.loads(response.read().decode('utf-8')) return json.loads(response.read().decode('utf-8'))
@@ -39,6 +38,8 @@ def start_authorization(user_id: str, instance: str) -> str:
with get_connection() as conn: with get_connection() as conn:
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone() row = conn.execute('SELECT value FROM app_settings WHERE name = ?', (setting_name,)).fetchone()
app = json.loads(row['value']) if row else None app = json.loads(row['value']) if row else None
if app and app.get('client_secret'):
app['client_secret'] = decrypt_secret(app['client_secret'])
if not app: if not app:
app = post_form(f'{instance}/api/v1/apps', { app = post_form(f'{instance}/api/v1/apps', {
'client_name': settings.mastodon_client_name, 'client_name': settings.mastodon_client_name,
@@ -50,7 +51,7 @@ def start_authorization(user_id: str, instance: str) -> str:
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)
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''', ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
(setting_name, json.dumps(app)), (setting_name, json.dumps({**app, 'client_secret': encrypt_secret(app['client_secret'])})),
) )
conn.commit() conn.commit()
state = token_urlsafe(32) state = token_urlsafe(32)
@@ -62,7 +63,7 @@ def start_authorization(user_id: str, instance: str) -> str:
(id, user_id, state_hash, instance, client_id, client_secret, redirect_uri, expires_at) (id, user_id, state_hash, instance, client_id, client_secret, redirect_uri, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''', VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
(str(uuid4()), user_id, sha256(state.encode()).hexdigest(), instance, (str(uuid4()), user_id, sha256(state.encode()).hexdigest(), instance,
app['client_id'], app['client_secret'], redirect_uri, expires_at.isoformat()), app['client_id'], encrypt_secret(app['client_secret']), redirect_uri, expires_at.isoformat()),
) )
conn.commit() conn.commit()
return f'{instance}/oauth/authorize?' + urlencode({ return f'{instance}/oauth/authorize?' + urlencode({
@@ -90,7 +91,7 @@ def finish_authorization(code: str, state: str) -> str:
'grant_type': 'authorization_code', 'grant_type': 'authorization_code',
'code': code, 'code': code,
'client_id': record['client_id'], 'client_id': record['client_id'],
'client_secret': record['client_secret'], 'client_secret': decrypt_secret(record['client_secret']),
'redirect_uri': record['redirect_uri'], 'redirect_uri': record['redirect_uri'],
}) })
access_token = token.get('access_token') access_token = token.get('access_token')
@@ -102,7 +103,7 @@ def finish_authorization(code: str, state: str) -> str:
(record['user_id'], 'mastodon'), (record['user_id'], 'mastodon'),
).fetchone() ).fetchone()
config = json.loads(current['config']) if current and current['config'] else {} config = json.loads(current['config']) if current and current['config'] else {}
config.update({'instance': record['instance'], 'access_token': access_token}) config.update({'instance': record['instance'], 'access_token': encrypt_secret(access_token)})
if current: if current:
conn.execute( conn.execute(
'UPDATE user_plugin_config SET config = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND plugin_name = ?', 'UPDATE user_plugin_config SET config = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND plugin_name = ?',
+62
View File
@@ -0,0 +1,62 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
import ipaddress
import socket
from urllib.parse import urlsplit
from urllib.error import HTTPError
from urllib.request import HTTPRedirectHandler, Request, build_opener
class RejectRedirectHandler(HTTPRedirectHandler):
def redirect_request(self, request, file, code, msg, headers, newurl):
raise HTTPError(request.full_url, code, 'Redirects are not allowed', headers, None)
NO_REDIRECT_OPENER = build_opener(RejectRedirectHandler)
def _is_blocked_address(address: str) -> bool:
parsed = ipaddress.ip_address(address)
mapped = parsed.ipv4_mapped if isinstance(parsed, ipaddress.IPv6Address) else None
candidates = (parsed, mapped) if mapped else (parsed,)
return any(
candidate.is_loopback
or candidate.is_link_local
or candidate.is_private
or candidate.is_multicast
or candidate.is_unspecified
or candidate.is_reserved
for candidate in candidates
)
def validate_public_instance(instance: str) -> str:
value = instance.strip().rstrip('/')
if not value:
raise ValueError('Mastodon instance is required')
if '://' not in value:
value = f'https://{value}'
parsed = urlsplit(value)
if parsed.scheme.lower() != 'https' or not parsed.hostname:
raise ValueError('Mastodon instance must be an HTTPS public hostname')
if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/'):
raise ValueError('Mastodon instance must be a hostname-only HTTPS URL')
try:
port = parsed.port
except ValueError as error:
raise ValueError('Mastodon instance has an invalid port') from error
if port not in (None, 443):
raise ValueError('Mastodon instance must use HTTPS port 443')
hostname = parsed.hostname.rstrip('.').lower()
try:
addresses = {result[4][0] for result in socket.getaddrinfo(hostname, port or 443, type=socket.SOCK_STREAM)}
except socket.gaierror as error:
raise ValueError('Mastodon instance hostname could not be resolved') from error
if not addresses or any(_is_blocked_address(address) for address in addresses):
raise ValueError('Mastodon instance must resolve only to public IP addresses')
return f'https://{hostname}'
def open_no_redirect(request: Request, timeout: int = 10):
return NO_REDIRECT_OPENER.open(request, timeout=timeout)
+79
View File
@@ -0,0 +1,79 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
import base64
import hashlib
import hmac
import secrets
import time
from urllib.parse import quote
from uuid import uuid4
from backend.app.database import get_connection
def create_secret() -> str:
return base64.b32encode(secrets.token_bytes(20)).decode('ascii').rstrip('=')
def create_recovery_codes(user_id: str, count: int = 10) -> list[str]:
codes = [secrets.token_urlsafe(9) for _ in range(count)]
with get_connection() as conn:
conn.execute('DELETE FROM otp_recovery_codes WHERE user_id = ?', (user_id,))
conn.executemany(
'INSERT INTO otp_recovery_codes (id, user_id, code_hash) VALUES (?, ?, ?)',
[(str(uuid4()), user_id, hash_recovery_code(code)) for code in codes],
)
conn.commit()
return codes
def hash_recovery_code(code: str) -> str:
return hashlib.sha256(code.strip().encode('utf-8')).hexdigest()
def consume_recovery_code(user_id: str, code: str) -> bool:
with get_connection() as conn:
cursor = conn.execute(
'''UPDATE otp_recovery_codes
SET used = 1, used_at = CURRENT_TIMESTAMP
WHERE user_id = ? AND code_hash = ? AND used = 0''',
(user_id, hash_recovery_code(code)),
)
conn.commit()
return cursor.rowcount == 1
def provisioning_uri(secret: str, username: str, issuer: str = 'LinkLog') -> str:
return f'otpauth://totp/{quote(issuer)}:{quote(username)}?secret={secret}&issuer={quote(issuer)}'
def current_code(secret: str, timestamp: float | None = None) -> str:
padded_secret = secret + '=' * (-len(secret) % 8)
key = base64.b32decode(padded_secret, casefold=True)
counter = int(timestamp if timestamp is not None else time.time()) // 30
digest = hmac.new(key, counter.to_bytes(8, 'big'), hashlib.sha1).digest()
index = digest[-1] & 0x0f
value = (int.from_bytes(digest[index:index + 4], 'big') & 0x7fffffff) % 1_000_000
return f'{value:06d}'
def verify_code(secret: str | None, code: str | None) -> bool:
if not secret or not code:
return False
normalized_code = code.strip()
if len(normalized_code) != 6 or not normalized_code.isdigit():
return False
padded_secret = secret + '=' * (-len(secret) % 8)
try:
key = base64.b32decode(padded_secret, casefold=True)
except (ValueError, base64.binascii.Error):
return False
counter = int(time.time()) // 30
for offset in (-1, 0, 1):
digest = hmac.new(key, (counter + offset).to_bytes(8, 'big'), hashlib.sha1).digest()
index = digest[-1] & 0x0f
value = (int.from_bytes(digest[index:index + 4], 'big') & 0x7fffffff) % 1_000_000
if hmac.compare_digest(f'{value:06d}', normalized_code):
return True
return False
+110 -13
View File
@@ -3,35 +3,53 @@
import json import json
import logging import logging
from datetime import datetime, timezone
from urllib.error import HTTPError, URLError from urllib.error import HTTPError, URLError
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.request import Request, urlopen from urllib.request import Request
from backend.app.plugins.base import BasePlugin from backend.app.plugins.base import BasePlugin
from backend.app.services.secret_store import decrypt_secret
from backend.app.services.mastodon_security import open_no_redirect, validate_public_instance
DEFAULT_POST_PREFIX = 'From my #LinkLog: ' DEFAULT_POST_PREFIX = 'From my #LinkLog: '
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class DefaultFrontendPlugin(BasePlugin): class DefaultFrontendPlugin(BasePlugin):
"""Accept events for the built-in frontend plugin."""
name = 'default_frontend' name = 'default_frontend'
version = '1.0.0' version = '1.0.0'
def handle_event(self, event): def handle_event(self, event):
"""Acknowledge an event without performing an external side effect."""
return {'status': 'accepted', 'plugin': self.name, 'event': event.get('type')} return {'status': 'accepted', 'plugin': self.name, 'event': event.get('type')}
class MastodonPlugin(BasePlugin): class MastodonPlugin(BasePlugin):
"""Publish and remove LinkLog entries through a Mastodon instance."""
name = 'mastodon' name = 'mastodon'
version = '1.0.0' version = '1.0.0'
enabled = False enabled = False
config = {} config = {}
def initialize(self, config=None): def initialize(self, config=None):
"""Store the administrator-provided defaults for later event handling."""
self.config = config or {} self.config = config or {}
return True return True
def handle_event(self, event): def handle_event(self, event):
"""Publish a link event, returning a structured status result.
Per-user plugin settings override global settings. The access token is
decrypted only for the duration of the outbound request, and the
instance is validated before any network connection is opened.
"""
if not event.get('post_to_mastodon', True):
return {'status': 'skipped', 'plugin': self.name, 'reason': 'not_requested'}
config = dict(self.config) config = dict(self.config)
user_id = event.get('user_id') user_id = event.get('user_id')
if user_id: if user_id:
@@ -47,10 +65,12 @@ class MastodonPlugin(BasePlugin):
).fetchone() ).fetchone()
if row and row['config']: if row and row['config']:
config.update(json.loads(row['config'])) config.update(json.loads(row['config']))
config['access_token'] = decrypt_secret(config.get('access_token', ''))
instance = str(config.get('instance', '')).strip().rstrip('/') try:
if instance and '://' not in instance: instance = validate_public_instance(str(config.get('instance', '')))
instance = f'https://{instance}' except ValueError as error:
return {'status': 'failed', 'plugin': self.name, 'reason': str(error)}
access_token = str(config.get('access_token', '')).strip() access_token = str(config.get('access_token', '')).strip()
if not instance or not access_token: if not instance or not access_token:
logger.debug( logger.debug(
@@ -59,18 +79,33 @@ class MastodonPlugin(BasePlugin):
) )
return {'status': 'skipped', 'plugin': self.name, 'reason': 'not_configured'} return {'status': 'skipped', 'plugin': self.name, 'reason': 'not_configured'}
status_parts = [event.get('title') or event.get('url', '')]
if event.get('comment'):
status_parts.append(event['comment'])
post_prefix = config.get('post_prefix') post_prefix = config.get('post_prefix')
if post_prefix is None and config.get('hashtag'): if post_prefix is None and config.get('hashtag'):
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) post_prefix = str(post_prefix if post_prefix is not None else DEFAULT_POST_PREFIX).strip()
status = f'{post_prefix}{event.get("url", "")}'.strip() title = str(event.get('title') or '').strip()
status_parts = [post_prefix.strip()]
if title:
status_parts.append(title)
if event.get('comment'):
status_parts.append(event['comment'])
if title:
timestamp_value = event.get('timestamp') or event.get('created_at')
url = str(event.get('url', '') or '').strip()
if timestamp_value:
try:
parsed = datetime.fromisoformat(str(timestamp_value).replace('Z', '+00:00'))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
formatted = parsed.astimezone(timezone.utc).strftime('%Y %B %d - %H:%M')
status_parts.append(f'Logged on {formatted} UTC from: {url}')
except ValueError:
status_parts.append(f'Logged from: {url}')
else:
status_parts.append(f'Logged from: {url}')
if event.get('tags'): if event.get('tags'):
status = f'{status} {" ".join(event["tags"])}' status_parts.append(' '.join(event['tags']))
status_parts.append(status) post_body = '\n\n'.join(status_parts)
post_body = '\n'.join(status_parts)
endpoint = f'{instance}/api/v1/statuses' endpoint = f'{instance}/api/v1/statuses'
logger.debug( logger.debug(
'Posting link to Mastodon: endpoint=%s user_id=%s event_id=%s body_length=%d', 'Posting link to Mastodon: endpoint=%s user_id=%s event_id=%s body_length=%d',
@@ -89,7 +124,7 @@ class MastodonPlugin(BasePlugin):
}, },
method='POST', method='POST',
) )
with urlopen(request, timeout=5) as response: with open_no_redirect(request, timeout=5) as response:
response_body = response.read().decode('utf-8') response_body = response.read().decode('utf-8')
logger.debug( logger.debug(
'Mastodon post response: endpoint=%s status=%s body_length=%d', 'Mastodon post response: endpoint=%s status=%s body_length=%d',
@@ -121,12 +156,59 @@ class MastodonPlugin(BasePlugin):
'reason': str(error), 'reason': str(error),
} }
def delete_posts(self, event):
"""Delete all Mastodon statuses recorded for a link event."""
config = dict(self.config)
user_id = event.get('user_id')
if user_id:
from backend.app.database import get_connection
with get_connection() as conn:
row = conn.execute(
'SELECT config FROM user_plugin_config WHERE user_id = ? AND plugin_name = ?',
(user_id, self.name),
).fetchone()
if row and row['config']:
config.update(json.loads(row['config']))
config['access_token'] = decrypt_secret(config.get('access_token', ''))
try:
instance = validate_public_instance(str(config.get('instance', '')))
except ValueError as error:
return {'status': 'failed', 'plugin': self.name, 'reason': str(error)}
access_token = str(config.get('access_token', '')).strip()
post_ids = event.get('mastodon_post_ids') or []
if not post_ids and event.get('mastodon_post_id'):
post_ids = [event['mastodon_post_id']]
if not instance or not access_token:
return {'status': 'failed', 'plugin': self.name, 'reason': 'Mastodon is not configured'}
try:
for post_id in post_ids:
request = Request(
f'{instance}/api/v1/statuses/{post_id}',
headers={'Authorization': f'Bearer {access_token}', 'User-Agent': 'LinkLog/1.0'},
method='DELETE',
)
with open_no_redirect(request, timeout=5) as response:
response.read()
return {'status': 'deleted', 'plugin': self.name, 'count': len(post_ids)}
except HTTPError as error:
response_body = error.read().decode('utf-8', errors='replace')
return {'status': 'failed', 'plugin': self.name, 'reason': f'HTTP {error.code}: {response_body[:500]}'}
except (URLError, TimeoutError, OSError) as error:
return {'status': 'failed', 'plugin': self.name, 'reason': str(error)}
class PluginManager: class PluginManager:
"""Load enabled plugins and route LinkLog events to them."""
def __init__(self): def __init__(self):
"""Create the built-in plugin registry."""
self.plugins = [DefaultFrontendPlugin(), MastodonPlugin()] self.plugins = [DefaultFrontendPlugin(), MastodonPlugin()]
def refresh_from_db(self): def refresh_from_db(self):
"""Refresh enabled flags and configuration from the plugin table."""
from backend.app.database import get_connection from backend.app.database import get_connection
with get_connection() as conn: with get_connection() as conn:
@@ -140,6 +222,7 @@ class PluginManager:
return enabled_names return enabled_names
def dispatch(self, event): def dispatch(self, event):
"""Send an event to every currently enabled plugin."""
self.refresh_from_db() self.refresh_from_db()
results = [] results = []
for plugin in self.plugins: for plugin in self.plugins:
@@ -149,5 +232,19 @@ class PluginManager:
logger.debug('Plugin dispatch result: plugin=%s event_id=%s result=%s', plugin.name, event.get('id'), result) logger.debug('Plugin dispatch result: plugin=%s event_id=%s result=%s', plugin.name, event.get('id'), result)
return results return results
def post_to_mastodon(self, event):
"""Publish one event through Mastodon when that plugin is enabled."""
self.refresh_from_db()
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
if not plugin.enabled:
return {'status': 'skipped', 'plugin': 'mastodon', 'reason': 'disabled'}
return plugin.handle_event(event)
def delete_mastodon_posts(self, event):
"""Delete the Mastodon statuses associated with an event."""
self.refresh_from_db()
plugin = next(plugin for plugin in self.plugins if plugin.name == 'mastodon')
return plugin.delete_posts(event)
plugin_manager = PluginManager() plugin_manager = PluginManager()
+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
+32
View File
@@ -0,0 +1,32 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from cryptography.fernet import Fernet, InvalidToken
from backend.app.core.config import settings
def _cipher() -> Fernet:
if not settings.data_encryption_key:
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY is required to access encrypted secrets')
try:
return Fernet(settings.data_encryption_key.encode('ascii'))
except (ValueError, UnicodeEncodeError) as error:
raise RuntimeError('LINKLOG_DATA_ENCRYPTION_KEY must be a valid Fernet key') from error
def encrypt_secret(value: str) -> str:
if not value:
return value
if value.startswith('enc:v1:'):
return value
return 'enc:v1:' + _cipher().encrypt(value.encode('utf-8')).decode('ascii')
def decrypt_secret(value: str) -> str:
if not value or not value.startswith('enc:v1:'):
return value
try:
return _cipher().decrypt(value[7:].encode('ascii')).decode('utf-8')
except (InvalidToken, UnicodeEncodeError) as error:
raise RuntimeError('Encrypted secret cannot be decrypted with LINKLOG_DATA_ENCRYPTION_KEY') from error
+47
View File
@@ -0,0 +1,47 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
import json
from backend.app.database import get_connection
THEMES = {
'plain-day': {'label': 'Plain Day', 'description': 'A bright, neutral daytime theme.'},
'plain-night': {'label': 'Plain Night', 'description': 'A neutral dark nighttime theme.'},
'latte': {'label': 'Catppuccin Latte', 'description': 'Catppuccin light theme.'},
'frappe': {'label': 'Catppuccin Frappe', 'description': 'Catppuccin soft dark theme.'},
'macchiato': {'label': 'Catppuccin Macchiato', 'description': 'Catppuccin medium dark theme.'},
'mocha': {'label': 'Catppuccin Mocha', 'description': 'Catppuccin deep dark theme.'},
'dracula': {'label': 'Dracula', 'description': 'A vivid dark theme with high-contrast accents.'},
'nord': {'label': 'Nord', 'description': 'A cool, muted blue-gray theme.'},
'solarized': {'label': 'Solarized', 'description': 'A balanced theme available in a light style.'},
'red': {'label': 'Red', 'description': 'A warm crimson theme with high-contrast surfaces.'},
}
DEFAULT_ENABLED_THEMES = tuple(THEMES)
def get_enabled_themes() -> list[str]:
with get_connection() as conn:
row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('enabled_themes',)).fetchone()
if row is None:
return list(DEFAULT_ENABLED_THEMES)
try:
configured = json.loads(row['value'])
except (TypeError, json.JSONDecodeError):
return list(DEFAULT_ENABLED_THEMES)
return [theme for theme in configured if theme in THEMES] or ['mocha']
def save_enabled_themes(themes: list[str]) -> list[str]:
selected = list(dict.fromkeys(theme for theme in themes if theme in THEMES))
if not selected:
raise ValueError('At least one theme must be enabled')
with get_connection() as conn:
conn.execute(
'''INSERT INTO app_settings (name, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(name) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP''',
('enabled_themes', json.dumps(selected)),
)
conn.commit()
return selected
+86 -21
View File
@@ -1,7 +1,7 @@
## 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 datetime import datetime, timezone from datetime import datetime, timedelta, timezone
from hashlib import sha256 from hashlib import sha256
from uuid import uuid4 from uuid import uuid4
@@ -13,29 +13,42 @@ def hash_token(token: str) -> str:
return sha256(token.encode('utf-8')).hexdigest() return sha256(token.encode('utf-8')).hexdigest()
def issue_token(user_id: str, username: str) -> dict: def _token_expiry() -> datetime:
token = f'token-{username}-{uuid4().hex}' return datetime.now(timezone.utc) + timedelta(minutes=settings.token_expiry_minutes)
expires_at = datetime.now(timezone.utc).replace(microsecond=0)
expires_at = expires_at.replace(day=expires_at.day + 30 if False else expires_at.day)
# one-month expiry, held as a configured value in settings def _persist_token(conn, user_id: str, token: str, token_type: str, expires_at: datetime,
from datetime import timedelta device_id: str, family_id: str) -> None:
expires_at = datetime.now(timezone.utc) + timedelta(days=settings.token_expiry_days) conn.execute(
'''
INSERT INTO tokens
(id, user_id, token_hash, token_type, expires_at, created_at, revoked, device_id, token_family_id)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, 0, ?, ?)
''',
(str(uuid4()), user_id, hash_token(token), token_type, expires_at.isoformat(), device_id, family_id),
)
def issue_token(user_id: str, username: str, device_id: str | None = None) -> dict:
device_id = device_id.strip() if device_id and device_id.strip() else f'device-{uuid4().hex}'
family_id = str(uuid4())
access_token = f'token-{username}-{uuid4().hex}'
refresh_token = f'refresh-{username}-{uuid4().hex}'
access_expires_at = _token_expiry()
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
with get_connection() as conn: with get_connection() as conn:
conn.execute( _persist_token(conn, user_id, access_token, 'access', access_expires_at, device_id, family_id)
''' _persist_token(conn, user_id, refresh_token, 'refresh', refresh_expires_at, device_id, family_id)
INSERT INTO tokens (id, user_id, token_hash, token_type, expires_at, created_at, revoked)
VALUES (?, ?, ?, 'access', ?, CURRENT_TIMESTAMP, 0)
''',
(str(uuid4()), user_id, hash_token(token), expires_at.isoformat())
)
conn.commit() conn.commit()
return { return {
'access_token': token, 'access_token': access_token,
'token_type': 'bearer', 'token_type': 'bearer',
'expires_at': expires_at.isoformat(), 'expires_at': access_expires_at.isoformat(),
'refresh_token': f'refresh-{uuid4().hex}', 'refresh_token': refresh_token,
'device_id': device_id,
'token_family_id': family_id,
} }
@@ -45,7 +58,7 @@ def validate_token(token: str) -> dict | None:
row = conn.execute( row = conn.execute(
''' '''
SELECT * FROM tokens SELECT * FROM tokens
WHERE token_hash = ? AND revoked = 0 AND expires_at > ? WHERE token_hash = ? AND token_type = 'access' AND revoked = 0 AND expires_at > ?
''', ''',
(token_hash, datetime.now(timezone.utc).isoformat()), (token_hash, datetime.now(timezone.utc).isoformat()),
).fetchone() ).fetchone()
@@ -54,12 +67,64 @@ def validate_token(token: str) -> dict | None:
return dict(row) return dict(row)
def validate_refresh_token(token: str, device_id: str | None = None) -> dict | None:
with get_connection() as conn:
row = conn.execute(
'''
SELECT * FROM tokens
WHERE token_hash = ? AND token_type = 'refresh' AND revoked = 0 AND expires_at > ?
AND (? IS NULL OR device_id = ?)
''',
(hash_token(token), datetime.now(timezone.utc).isoformat(), device_id, device_id),
).fetchone()
return dict(row) if row else None
def rotate_refresh_token(refresh_token: str, device_id: str | None = None) -> dict | None:
current = validate_refresh_token(refresh_token, device_id)
with get_connection() as conn:
if current is None:
row = conn.execute(
'SELECT token_family_id FROM tokens WHERE token_hash = ? AND token_type = ? AND token_family_id IS NOT NULL',
(hash_token(refresh_token), 'refresh'),
).fetchone()
if row:
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (row['token_family_id'],))
conn.commit()
return None
user = conn.execute('SELECT username FROM users WHERE id = ?', (current['user_id'],)).fetchone()
if user is None:
return None
family_id = current['token_family_id']
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (family_id,))
new_access = f'token-{user["username"]}-{uuid4().hex}'
new_refresh = f'refresh-{user["username"]}-{uuid4().hex}'
access_expires_at = _token_expiry()
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
_persist_token(conn, current['user_id'], new_access, 'access', access_expires_at, current['device_id'], family_id)
_persist_token(conn, current['user_id'], new_refresh, 'refresh', refresh_expires_at, current['device_id'], family_id)
conn.commit()
return {
'access_token': new_access,
'token_type': 'bearer',
'expires_at': access_expires_at.isoformat(),
'refresh_token': new_refresh,
'device_id': current['device_id'],
'user_id': current['user_id'],
'username': user['username'],
}
def revoke_token(token: str) -> bool: def revoke_token(token: str) -> bool:
token_hash = hash_token(token) token_hash = hash_token(token)
with get_connection() as conn: with get_connection() as conn:
cursor = conn.execute( cursor = conn.execute(
'UPDATE tokens SET revoked = 1 WHERE token_hash = ?', '''UPDATE tokens SET revoked = 1
(token_hash,), WHERE token_hash = ? OR token_family_id = (
SELECT token_family_id FROM tokens WHERE token_hash = ?
)''',
(token_hash, token_hash),
) )
conn.commit() conn.commit()
return cursor.rowcount > 0 return cursor.rowcount > 0
+2
View File
@@ -3,6 +3,8 @@ uvicorn==0.52.4
pydantic==2.13.4 pydantic==2.13.4
jinja2==3.1.6 jinja2==3.1.6
python-multipart==0.0.20 python-multipart==0.0.20
Pillow==11.3.0
pytest==9.1.1 pytest==9.1.1
httpx==0.28.1 httpx==0.28.1
httpx2==2.12.0 httpx2==2.12.0
cryptography==46.0.3
+3
View File
@@ -10,6 +10,9 @@ import pytest
TEST_DATABASE_DIRECTORY = tempfile.TemporaryDirectory(prefix='linklog-tests-') TEST_DATABASE_DIRECTORY = tempfile.TemporaryDirectory(prefix='linklog-tests-')
TEST_DATABASE_PATH = os.path.join(TEST_DATABASE_DIRECTORY.name, 'linklog.db') TEST_DATABASE_PATH = os.path.join(TEST_DATABASE_DIRECTORY.name, 'linklog.db')
os.environ['LINKLOG_DATABASE_PATH'] = TEST_DATABASE_PATH os.environ['LINKLOG_DATABASE_PATH'] = TEST_DATABASE_PATH
os.environ['LINKLOG_DATA_ENCRYPTION_KEY'] = 'L5M4sQYVjD1N7pT2Xk8R0aBcDeFgHiJkLmNoPqRsTuV='
# Use a large page size so existing tests that expect the full feed keep working.
os.environ['LINKLOG_FRONTEND_LOADPOSTS'] = '1000'
@pytest.fixture(scope='session', autouse=True) @pytest.fixture(scope='session', autouse=True)
+534 -46
View File
@@ -2,16 +2,21 @@
## SPDX-License-Identifier: GPL-3.0-or-later ## SPDX-License-Identifier: GPL-3.0-or-later
import json import json
from pathlib import Path
import threading import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs from urllib.parse import parse_qs
from uuid import uuid4 from uuid import uuid4
from unittest.mock import patch from unittest.mock import MagicMock, patch
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from backend.app.main import app from backend.app.main import app
from backend.app.database import get_connection from backend.app.core.config import settings
from backend.app.database import get_connection, hash_password
from backend.app.services.email_service import get_smtp_settings
from backend.app.services.login_throttle import clear_login_failures
from backend.app.services.otp_service import current_code
from backend.app.services.password_reset import create_reset_token from backend.app.services.password_reset import create_reset_token
from backend.app.services.token_service import issue_token from backend.app.services.token_service import issue_token
@@ -21,16 +26,16 @@ client = TestClient(app)
def login_headers(username='alice'): def login_headers(username='alice'):
token = client.post('/api/auth/login', json={ token = client.post('/api/auth/login', json={
'username': username, 'email': 'alice@example.com' if username == 'alice' else f'{username}@example.com',
'password': 'secret123', 'password': 'secret123',
}).json()['access_token'] }).json()['access_token']
return {'Authorization': f'Bearer {token}'} return {'Authorization': f'Bearer {token}'}
def test_login_returns_token(): def test_login_returns_token():
assert app.version == '0.1.0' assert app.version == settings.version
response = client.post('/api/auth/login', json={ response = client.post('/api/auth/login', json={
'username': 'alice', 'email': 'alice@example.com',
'password': 'secret123', 'password': 'secret123',
}) })
assert response.status_code == 200 assert response.status_code == 200
@@ -38,17 +43,100 @@ def test_login_returns_token():
assert 'access_token' in payload assert 'access_token' in payload
assert payload['token_type'] == 'bearer' assert payload['token_type'] == 'bearer'
admin_session = client.get('/api/auth/me', params={'token': payload['access_token']}) admin_session = client.get('/api/auth/me', headers={'Authorization': f"Bearer {payload['access_token']}"})
assert admin_session.status_code == 200 assert admin_session.status_code == 200
assert admin_session.json()['is_admin'] is True assert admin_session.json()['is_admin'] is True
user_token = client.post('/api/auth/login', json={ user_token = client.post('/api/auth/login', json={
'username': 'bob', 'email': 'bob@example.com',
'password': 'secret123', 'password': 'secret123',
}).json()['access_token'] }).json()['access_token']
user_session = client.get('/api/auth/me', params={'token': user_token}) user_session = client.get('/api/auth/me', headers={'Authorization': f"Bearer {user_token}"})
assert user_session.status_code == 200 assert user_session.status_code == 200
assert user_session.json()['is_admin'] is False assert user_session.json()['is_admin'] is False
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():
email = f'unknown-{uuid4().hex}@example.com'
for attempt in range(5):
response = client.post('/api/auth/login', json={'email': email, 'password': 'wrong-password'})
assert response.status_code == 401, attempt
locked = client.post('/api/auth/login', json={'email': email, 'password': 'wrong-password'})
assert locked.status_code == 429
assert int(locked.headers['Retry-After']) > 0
clear_login_failures('testclient', email)
valid = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'})
assert valid.status_code == 200
def test_refresh_token_rotates_and_reuse_revokes_family():
device_id = f'device-{uuid4().hex}'
login = client.post('/api/auth/login', json={
'email': 'alice@example.com',
'password': 'secret123',
'device_id': device_id,
})
assert login.status_code == 200
first = login.json()
rotated = client.post('/api/auth/refresh', json={
'refresh_token': first['refresh_token'],
'device_id': device_id,
})
assert rotated.status_code == 200
second = rotated.json()
assert second['refresh_token'] != first['refresh_token']
assert client.get('/api/auth/me', headers={'Authorization': f"Bearer {second['access_token']}"}).status_code == 200
reused = client.post('/api/auth/refresh', json={
'refresh_token': first['refresh_token'],
'device_id': device_id,
})
assert reused.status_code == 401
family_revoked = client.post('/api/auth/refresh', json={
'refresh_token': second['refresh_token'],
'device_id': device_id,
})
assert family_revoked.status_code == 401
def test_password_hashes_are_salted_and_legacy_hashes_upgrade_on_login():
from hashlib import sha256
from backend.app.database import hash_password
first = hash_password('same-password')
second = hash_password('same-password')
assert first.startswith('scrypt$16384$8$1$')
assert first != second
legacy_username = f'legacy-{uuid4().hex}'
legacy_hash = sha256('legacy-password'.encode('utf-8')).hexdigest()
with get_connection() as conn:
conn.execute(
'''INSERT INTO users
(id, username, email, password_hash, is_admin, email_verified)
VALUES (?, ?, ?, ?, 0, 1)''',
(str(uuid4()), legacy_username, f'{legacy_username}@example.com', legacy_hash),
)
conn.commit()
response = client.post('/api/auth/login', json={'email': legacy_username + '@example.com', 'password': 'legacy-password'})
assert response.status_code == 200
with get_connection() as conn:
upgraded = conn.execute('SELECT password_hash FROM users WHERE username = ?', (legacy_username,)).fetchone()['password_hash']
assert upgraded.startswith('scrypt$16384$8$1$')
def test_configuration_requires_authentication_and_admin_role(): def test_configuration_requires_authentication_and_admin_role():
@@ -57,6 +145,115 @@ def test_configuration_requires_authentication_and_admin_role():
assert client.get('/api/admin/users').status_code == 401 assert client.get('/api/admin/users').status_code == 401
assert client.get('/api/admin/plugins', headers=login_headers('bob')).status_code == 403 assert client.get('/api/admin/plugins', headers=login_headers('bob')).status_code == 403
assert client.get('/api/admin/users', headers=login_headers('bob')).status_code == 403 assert client.get('/api/admin/users', headers=login_headers('bob')).status_code == 403
assert client.get('/api/admin/smtp').status_code == 401
assert client.get('/api/admin/smtp', headers=login_headers('bob')).status_code == 403
def test_admin_can_select_multiple_themes():
headers = login_headers()
response = client.put('/api/admin/themes', headers=headers, json={
'themes': ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized', 'red'],
})
assert response.status_code == 200
assert response.json()['enabled'] == ['plain-day', 'plain-night', 'latte', 'frappe', 'macchiato', 'mocha', 'dracula', 'nord', 'solarized', 'red']
public_response = client.get('/api/public/themes')
assert public_response.status_code == 200
assert [theme['id'] for theme in public_response.json()] == response.json()['enabled']
assert client.put('/api/admin/themes', headers=headers, json={'themes': []}).status_code == 422
def test_admin_can_save_and_validate_smtp_settings():
headers = login_headers()
original = get_smtp_settings()
with get_connection() as conn:
original_row = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone()
response = client.put('/api/admin/smtp', headers=headers, json={
'smtp_host': 'smtp.example.com',
'smtp_port': 587,
'smtp_username': 'mailer',
'smtp_password': 'secret',
'smtp_from': 'LinkLog <no-reply@example.com>',
'smtp_use_tls': True,
})
assert response.status_code == 200
assert response.json()['smtp_host'] == 'smtp.example.com'
assert response.json()['password_configured'] is True
assert 'smtp_password' not in response.json()
with patch('backend.app.api.admin.send_test_email') as send_test_email:
validation = client.post('/api/admin/smtp/test', headers=headers, json={
'smtp_host': 'smtp.unsaved.example.com',
'smtp_port': 2525,
'smtp_username': 'temporary-user',
'smtp_password': 'temporary-secret',
'smtp_from': 'Temporary <temporary@example.com>',
'smtp_use_tls': False,
})
assert validation.status_code == 200
send_test_email.assert_called_once_with('alice@example.com', {
'smtp_host': 'smtp.unsaved.example.com',
'smtp_port': 2525,
'smtp_username': 'temporary-user',
'smtp_password': 'temporary-secret',
'smtp_from': 'Temporary <temporary@example.com>',
'smtp_use_tls': False,
})
with get_connection() as conn:
if original_row is None:
conn.execute('DELETE FROM app_settings WHERE name = ?', ('smtp',))
else:
conn.execute(
'UPDATE app_settings SET value = ?, updated_at = CURRENT_TIMESTAMP WHERE name = ?',
(original_row['value'], 'smtp'),
)
conn.commit()
with get_connection() as conn:
conn.execute('DELETE FROM app_settings WHERE name = ?', ('admin_smtp_mail_rate',))
conn.commit()
def test_admin_reports_smtp_validation_errors():
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('connection refused')):
failed_validation = client.post('/api/admin/smtp/test', headers=headers, json={
'smtp_host': 'smtp.unsaved.example.com',
'smtp_port': 2525,
'smtp_username': 'temporary-user',
'smtp_password': 'temporary-secret',
'smtp_from': 'Temporary <temporary@example.com>',
'smtp_use_tls': False,
})
assert failed_validation.status_code == 503
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():
@@ -66,6 +263,7 @@ def test_admin_can_add_list_and_remove_users():
'email': 'charlie@example.com', 'email': 'charlie@example.com',
'password': 'charlie-secret', 'password': 'charlie-secret',
}) })
assert create_response.status_code == 201 assert create_response.status_code == 201
user = create_response.json() user = create_response.json()
assert user['username'] == 'charlie' assert user['username'] == 'charlie'
@@ -79,6 +277,52 @@ def test_admin_can_add_list_and_remove_users():
assert client.put('/api/admin/users/user-1', headers=headers, json={'is_admin': False}).status_code == 400 assert client.put('/api/admin/users/user-1', headers=headers, json={'is_admin': False}).status_code == 400
def test_admin_can_reset_another_users_otp():
admin_headers = login_headers()
user_login = client.post('/api/auth/login', json={
'email': 'bob@example.com',
'password': 'secret123',
}).json()
user_headers = {'Authorization': f"Bearer {user_login['access_token']}"}
setup = client.post('/api/user/otp/setup', headers=user_headers)
assert setup.status_code == 200
secret = setup.json()['secret']
recovery_code = setup.json()['recovery_codes'][0]
assert client.post('/api/user/otp', headers=user_headers, json={
'action': 'enable', 'code': current_code(secret),
}).status_code == 200
assert client.post('/api/admin/users/user-2/otp/reset', headers=admin_headers).json() == {
'status': 'otp_reset', 'enabled': False, 'user_id': 'user-2',
}
assert client.get('/api/user/otp', headers=user_headers).json() == {'enabled': False}
assert client.post('/api/user/otp/recover', headers=user_headers, json={
'current_password': 'secret123', 'recovery_code': recovery_code,
}).status_code == 400
assert client.post('/api/admin/users/user-2/otp/reset', headers=login_headers('bob')).status_code == 403
assert client.post('/api/admin/users/missing-user/otp/reset', headers=admin_headers).status_code == 404
def test_security_audit_events_are_append_only_and_do_not_store_secrets():
admin_headers = login_headers()
response = client.put('/api/admin/themes', headers=admin_headers, json={'themes': ['plain-day']})
assert response.status_code == 200
with get_connection() as conn:
event = conn.execute(
'''SELECT actor_id, action, target_type, outcome, details
FROM security_audit_events
WHERE action = 'themes_updated'
ORDER BY created_at DESC, rowid DESC LIMIT 1''',
).fetchone()
assert event is not None
assert event['actor_id'] == 'user-1'
assert event['target_type'] == 'application'
assert event['outcome'] == 'success'
assert 'password' not in event['details'].lower()
assert 'token' not in event['details'].lower()
assert 'secret' not in event['details'].lower()
def test_new_user_must_verify_email_before_login(): def test_new_user_must_verify_email_before_login():
headers = login_headers() headers = login_headers()
username = f'unverified-{uuid4().hex}' username = f'unverified-{uuid4().hex}'
@@ -90,7 +334,7 @@ def test_new_user_must_verify_email_before_login():
assert created.status_code == 201 assert created.status_code == 201
assert created.json()['email_verified'] is False assert created.json()['email_verified'] is False
login = client.post('/api/auth/login', json={'username': username, 'password': 'secret123'}) login = client.post('/api/auth/login', json={'email': f'{username}@example.com', 'password': 'secret123'})
assert login.status_code == 403 assert login.status_code == 403
assert login.json()['detail'] == 'Email address is not verified' assert login.json()['detail'] == 'Email address is not verified'
@@ -110,7 +354,7 @@ def test_email_verification_link_enables_login():
verified = client.get('/api/auth/verify-email', params={'token': verification_token}) verified = client.get('/api/auth/verify-email', params={'token': verification_token})
assert verified.status_code == 200 assert verified.status_code == 200
assert client.post('/api/auth/login', json={'username': username, 'password': 'secret123'}).status_code == 200 assert client.post('/api/auth/login', json={'email': f'{username}@example.com', 'password': 'secret123'}).status_code == 200
assert client.get('/api/auth/verify-email', params={'token': verification_token}).status_code == 400 assert client.get('/api/auth/verify-email', params={'token': verification_token}).status_code == 400
@@ -129,7 +373,7 @@ def test_mistyped_password_sends_reset_link_without_changing_login_error():
with patch('backend.app.api.auth.smtp_configured', return_value=True), \ with patch('backend.app.api.auth.smtp_configured', return_value=True), \
patch('backend.app.api.auth.create_reset_token', return_value='reset-token') as create_token, \ patch('backend.app.api.auth.create_reset_token', return_value='reset-token') as create_token, \
patch('backend.app.api.auth.send_password_reset_email') as send_email: patch('backend.app.api.auth.send_password_reset_email') as send_email:
response = client.post('/api/auth/login', json={'username': username, 'password': 'wrong-password'}) response = client.post('/api/auth/login', json={'email': f'{username}@example.com', 'password': 'wrong-password'})
assert response.status_code == 401 assert response.status_code == 401
assert response.json()['detail'] == 'Invalid username or password' assert response.json()['detail'] == 'Invalid username or password'
@@ -154,7 +398,7 @@ def test_password_reset_is_single_use_and_revokes_sessions():
reset = client.post('/api/auth/reset-password', json={'token': token, 'password': 'new-secret123'}) reset = client.post('/api/auth/reset-password', json={'token': token, 'password': 'new-secret123'})
assert reset.status_code == 200 assert reset.status_code == 200
assert client.post('/api/auth/reset-password', json={'token': token, 'password': 'another-secret'}).status_code == 400 assert client.post('/api/auth/reset-password', json={'token': token, 'password': 'another-secret'}).status_code == 400
assert client.post('/api/auth/login', json={'username': username, 'password': 'new-secret123'}).status_code == 200 assert client.post('/api/auth/login', json={'email': f'{username}@example.com', 'password': 'new-secret123'}).status_code == 200
def test_admin_can_remove_user_with_owned_data(): def test_admin_can_remove_user_with_owned_data():
@@ -186,7 +430,50 @@ def test_admin_can_remove_user_with_owned_data():
removed = client.delete(f'/api/admin/users/{user_id}', headers=headers) removed = client.delete(f'/api/admin/users/{user_id}', headers=headers)
assert removed.status_code == 200 assert removed.status_code == 200
assert client.get('/api/auth/me', params={'token': user_headers['Authorization'].removeprefix('Bearer ')}).status_code == 401 assert client.get('/api/auth/me', params={'token': user_token}).status_code == 401
def test_deleting_link_removes_all_mastodon_posts_first():
owner_headers = login_headers('alice')
created = client.post('/api/links', headers=owner_headers, json={
'title': 'Remote cleanup',
'url': 'https://example.com/remote-cleanup',
})
assert created.status_code == 201
link_id = created.json()['id']
with get_connection() as conn:
conn.execute(
'UPDATE links SET mastodon_posted = 1, mastodon_post_id = ?, mastodon_post_ids = ? WHERE id = ?',
('post-2', json.dumps(['post-1', 'post-2']), link_id),
)
conn.commit()
with patch('backend.app.api.links.plugin_manager.delete_mastodon_posts', return_value={'status': 'deleted', 'count': 2}) as delete_posts:
deleted = client.delete(f'/api/links/{link_id}', headers=owner_headers)
assert deleted.status_code == 200
delete_posts.assert_called_once()
assert delete_posts.call_args.args[0]['mastodon_post_ids'] == ['post-1', 'post-2']
assert client.delete(f'/api/links/{link_id}', headers=owner_headers).status_code == 404
def test_link_is_kept_when_mastodon_cleanup_fails():
owner_headers = login_headers('alice')
created = client.post('/api/links', headers=owner_headers, json={
'title': 'Failed remote cleanup',
'url': 'https://example.com/failed-remote-cleanup',
})
link_id = created.json()['id']
with get_connection() as conn:
conn.execute(
'UPDATE links SET mastodon_posted = 1, mastodon_post_id = ?, mastodon_post_ids = ? WHERE id = ?',
('post-failed', json.dumps(['post-failed']), link_id),
)
conn.commit()
with patch('backend.app.api.links.plugin_manager.delete_mastodon_posts', return_value={'status': 'failed', 'reason': 'remote refused'}):
deleted = client.delete(f'/api/links/{link_id}', headers=owner_headers)
assert deleted.status_code == 502
assert 'remote refused' in deleted.json()['detail']
assert client.get('/api/links').json()
def test_admin_can_toggle_privileges_without_removing_last_admin(): def test_admin_can_toggle_privileges_without_removing_last_admin():
@@ -205,25 +492,102 @@ def test_admin_can_toggle_privileges_without_removing_last_admin():
assert last_admin.status_code == 400 assert last_admin.status_code == 400
def test_users_manage_owned_labels_and_admin_can_delete_any_label(): def test_users_manage_owned_labels_and_admin_can_edit_and_delete_any_label():
alice_headers = login_headers('alice') alice_headers = login_headers('alice') # admin
created = client.post('/api/user/labels', headers=alice_headers, json={'name': 'My Label'}) bob_headers = login_headers('bob') # non-admin
created = client.post('/api/user/labels', headers=bob_headers, json={'name': 'Bob Label'})
assert created.status_code == 201 assert created.status_code == 201
label = created.json() label = created.json()
assert label['name'] == '#My Label' assert label['name'] == '#Bob Label'
edited = client.put(f"/api/user/labels/{label['id']}", headers=alice_headers, json={'name': '#Renamed'}) # Bob renames own label
edited = client.put(f"/api/user/labels/{label['id']}", headers=bob_headers, json={'name': '#RenamedByBob'})
assert edited.status_code == 200 assert edited.status_code == 200
assert edited.json()['name'] == '#Renamed' assert edited.json()['name'] == '#RenamedByBob'
denied = client.put(f"/api/user/labels/{label['id']}", headers=login_headers('bob'), json={'name': '#Nope'}) # Non-owner Alice can edit it via admin endpoint, but NOT user endpoint
assert denied.status_code == 404 user_denied = client.put(f"/api/user/labels/{label['id']}", headers=alice_headers, json={'name': '#NopeUser'})
assert client.delete(f"/api/user/labels/{label['id']}", headers=login_headers('bob')).status_code == 404 assert user_denied.status_code == 404
admin_edited = client.put(f"/api/admin/labels/{label['id']}", headers=alice_headers, json={'name': '#AdminRenamed'})
assert admin_edited.status_code == 200
assert admin_edited.json()['name'] == '#AdminRenamed'
# Non-admin Bob cannot access admin edit endpoint
bob_admin_denied = client.put(f"/api/admin/labels/{label['id']}", headers=bob_headers, json={'name': '#NopeAdmin'})
assert bob_admin_denied.status_code == 403
# Admin delete
admin_delete = client.delete(f"/api/admin/labels/{label['id']}", headers=alice_headers) admin_delete = client.delete(f"/api/admin/labels/{label['id']}", headers=alice_headers)
assert admin_delete.status_code == 200 assert admin_delete.status_code == 200
def test_label_visibility_isolation_and_grandfathering():
alice_headers = login_headers('alice')
bob_headers = login_headers('bob')
# Create non-admin user charlie
with get_connection() as conn:
conn.execute(
'''INSERT OR IGNORE INTO users (id, username, email, password_hash, is_admin, email_verified)
VALUES (?, ?, ?, ?, 0, 1)''',
('user-3', 'charlie', 'charlie@example.com', hash_password('secret123')),
)
conn.commit()
charlie_headers = login_headers('charlie')
# Create Bob label (non-admin)
created_bob = client.post('/api/user/labels', headers=bob_headers, json={'name': 'BobOnlyLabel'}).json()
# Create Charlie label (non-admin)
created_charlie = client.post('/api/user/labels', headers=charlie_headers, json={'name': 'CharlieOnlyLabel'}).json()
# Grandfathered label in DB with NULL created_by
from uuid import uuid4
grandfathered_id = str(uuid4())
with get_connection() as conn:
conn.execute('INSERT INTO tags (id, name, created_by) VALUES (?, ?, NULL)', (grandfathered_id, '#GrandfatheredLabel'))
conn.commit()
# Bob views /api/user/labels: sees default tags, grandfathered tag, and Bob tag, NOT Charlie tag
bob_labels = client.get('/api/user/labels', headers=bob_headers).json()
bob_label_names = [l['name'] for l in bob_labels]
assert '#BobOnlyLabel' in bob_label_names
assert '#GrandfatheredLabel' in bob_label_names
assert '#Cybersecurity' in bob_label_names
assert '#CharlieOnlyLabel' not in bob_label_names
# Charlie views /api/user/labels: sees default tags, grandfathered tag, and Charlie tag, NOT Bob tag
charlie_labels = client.get('/api/user/labels', headers=charlie_headers).json()
charlie_label_names = [l['name'] for l in charlie_labels]
assert '#CharlieOnlyLabel' in charlie_label_names
assert '#GrandfatheredLabel' in charlie_label_names
assert '#Cybersecurity' in charlie_label_names
assert '#BobOnlyLabel' not in charlie_label_names
# Every user can filter by every available tag, including another user's label.
bob_tags = client.get('/api/tags', headers=bob_headers).json()
assert '#BobOnlyLabel' in bob_tags
assert '#GrandfatheredLabel' in bob_tags
assert '#CharlieOnlyLabel' in bob_tags
# The public feed filter has the same complete tag catalog.
anon_tags = client.get('/api/tags').json()
assert '#GrandfatheredLabel' in anon_tags
assert '#BobOnlyLabel' in anon_tags
assert '#CharlieOnlyLabel' in anon_tags
# Bob cannot edit or delete grandfathered label
assert client.put(f"/api/user/labels/{grandfathered_id}", headers=bob_headers, json={'name': '#RenamedGrandfathered'}).status_code == 404
assert client.delete(f"/api/user/labels/{grandfathered_id}", headers=bob_headers).status_code == 404
# Clean up created labels
client.delete(f"/api/user/labels/{created_bob['id']}", headers=bob_headers)
client.delete(f"/api/user/labels/{created_charlie['id']}", headers=charlie_headers)
client.delete(f"/api/admin/labels/{grandfathered_id}", headers=alice_headers)
def test_labels_page_renders_authenticated_management_shell(): def test_labels_page_renders_authenticated_management_shell():
page = client.get('/labels') page = client.get('/labels')
assert page.status_code == 200 assert page.status_code == 200
@@ -243,7 +607,7 @@ def test_submit_link_stores_cleaned_url_and_public_feed():
data = response.json() data = response.json()
assert data['url'] == 'https://example.com/path?keep=yes' assert data['url'] == 'https://example.com/path?keep=yes'
feed = client.get('/api/public/feed').json() feed = client.get('/api/public/feed').json()['items']
matching = next(item for item in feed if item['id'] == data['id']) matching = next(item for item in feed if item['id'] == data['id'])
assert matching['comment'] == 'Interesting read' assert matching['comment'] == 'Interesting read'
assert matching['user']['username'] == 'alice' assert matching['user']['username'] == 'alice'
@@ -251,13 +615,64 @@ def test_submit_link_stores_cleaned_url_and_public_feed():
filtered_response = client.get('/api/public/feed/alice') filtered_response = client.get('/api/public/feed/alice')
assert filtered_response.status_code == 200 assert filtered_response.status_code == 200
assert all(item['user']['username'] == 'alice' for item in filtered_response.json()) assert all(item['user']['username'] == 'alice' for item in filtered_response.json()['items'])
assert client.get('/api/public/feed/does-not-exist').json() == [] assert client.get('/api/public/feed/does-not-exist').json()['items'] == []
users_response = client.get('/api/public/users') users_response = client.get('/api/public/users')
assert users_response.status_code == 200 assert users_response.status_code == 200
assert 'alice' in users_response.json() assert 'alice' in users_response.json()
def test_duplicate_link_updates_comment_tags_and_retriggers_plugins():
headers = login_headers()
payload = {
'title': 'Duplicate candidate',
'url': 'https://example.com/duplicate?utm_source=campaign',
'comment': 'first comment',
'tags': ['#First'],
}
first = client.post('/api/links', headers=headers, json=payload)
assert first.status_code == 201
with patch('backend.app.api.links.plugin_manager.dispatch', return_value=[]) as dispatch:
duplicate = client.post('/api/links', headers=headers, json={
**payload,
'comment': 'updated comment',
'tags': ['#Second'],
})
assert duplicate.status_code == 200
assert duplicate.json()['duplicate'] is True
assert duplicate.json()['id'] == first.json()['id']
dispatch.assert_called_once()
assert dispatch.call_args.args[0]['comment'] == 'updated comment'
assert dispatch.call_args.args[0]['tags'] == ['#Second']
feed_item = next(item for item in client.get('/api/public/feed').json()['items'] if item['id'] == first.json()['id'])
assert feed_item['comment'] == 'updated comment'
assert feed_item['tags'] == ['#Second']
def test_duplicate_link_check_is_authenticated_and_detects_existing_entry():
headers = login_headers()
payload = {'title': 'Check candidate', 'url': 'https://example.com/check-candidate'}
assert client.get('/api/links/check', params=payload).status_code == 401
created = client.post('/api/links', headers=headers, json=payload)
assert created.status_code == 201
check = client.get('/api/links/check', headers=headers, params=payload)
assert check.status_code == 200
assert check.json()['exists'] is True
def test_link_save_reports_plugin_posting_errors():
with patch('backend.app.api.links.plugin_manager.dispatch', return_value=[
{'status': 'failed', 'plugin': 'mastodon', 'reason': 'HTTP 503: unavailable'},
]):
response = client.post('/api/links', headers=login_headers(), json={
'title': 'Plugin error report',
'url': 'https://example.com/plugin-error-report',
})
assert response.status_code == 201
assert response.json()['plugin_errors'] == [{'plugin': 'mastodon', 'reason': 'HTTP 503: unavailable'}]
def test_links_support_tags_and_tag_filtering(): def test_links_support_tags_and_tag_filtering():
headers = login_headers() headers = login_headers()
response = client.post('/api/links', headers=headers, json={ response = client.post('/api/links', headers=headers, json={
@@ -274,7 +689,7 @@ def test_links_support_tags_and_tag_filtering():
assert { assert {
'#Internet', '#Cybersecurity', '#Fediverse', '#Food', '#Photography', '#Music', '#AI' '#Internet', '#Cybersecurity', '#Fediverse', '#Food', '#Photography', '#Music', '#AI'
} <= set(tags) } <= set(tags)
tagged_feed = client.get('/api/public/feed').json() tagged_feed = client.get('/api/public/feed').json()['items']
tagged_item = next(item for item in tagged_feed if item['id'] == link_id) tagged_item = next(item for item in tagged_feed if item['id'] == link_id)
assert {tag.casefold() for tag in tagged_item['tags']} == {'#casepreserved', '#web'} assert {tag.casefold() for tag in tagged_item['tags']} == {'#casepreserved', '#web'}
@@ -310,12 +725,12 @@ def test_only_link_owner_can_edit_link():
}) })
assert unauthenticated.status_code == 401 assert unauthenticated.status_code == 401
anonymous_feed = client.get('/api/public/feed').json() anonymous_feed = client.get('/api/public/feed').json()['items']
anonymous_link = next(item for item in anonymous_feed if item['id'] == link_id) anonymous_link = next(item for item in anonymous_feed if item['id'] == link_id)
assert anonymous_link['is_owner'] is False assert anonymous_link['is_owner'] is False
assert anonymous_link['can_edit'] is False assert anonymous_link['can_edit'] is False
owner_feed = client.get('/api/public/feed', headers=owner_headers).json() owner_feed = client.get('/api/public/feed', headers=owner_headers).json()['items']
owner_link = next(item for item in owner_feed if item['id'] == link_id) owner_link = next(item for item in owner_feed if item['id'] == link_id)
assert owner_link['is_owner'] is True assert owner_link['is_owner'] is True
assert owner_link['can_edit'] is True assert owner_link['can_edit'] is True
@@ -334,11 +749,15 @@ def test_only_link_owner_can_edit_link():
}) })
assert denied.status_code == 404 assert denied.status_code == 404
deleted = client.delete(f'/api/links/{link_id}', headers=owner_headers)
assert deleted.status_code == 200
assert client.delete(f'/api/links/{link_id}', headers=owner_headers).status_code == 404
assert client.delete(f'/api/links/{link_id}', headers=login_headers('bob')).status_code == 404
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',
@@ -367,6 +786,8 @@ def test_public_and_admin_pages_render_html():
assert 'id="auth-profile-link" class="hidden"' in root_page.text assert 'id="auth-profile-link" class="hidden"' in root_page.text
assert 'id="auth-admin-link" class="hidden"' in root_page.text assert 'id="auth-admin-link" class="hidden"' in root_page.text
assert '<select id="tag-filter">' in root_page.text assert '<select id="tag-filter">' in root_page.text
assert '<input id="search-input" type="search"' in root_page.text
assert root_page.text.index('class="site-logo"') < root_page.text.index('<section class="toolbar">')
assert 'logout.js?v=3' in root_page.text assert 'logout.js?v=3' in root_page.text
assert client.get('/alice').status_code == 200 assert client.get('/alice').status_code == 200
assert client.get('/alice/').status_code == 200 assert client.get('/alice/').status_code == 200
@@ -374,17 +795,23 @@ def test_public_and_admin_pages_render_html():
assert 'alice' in user_page assert 'alice' in user_page
assert 'data-user-filter="alice"' in user_page assert 'data-user-filter="alice"' in user_page
assert 'profile-summary' in user_page assert 'profile-summary' in user_page
assert '<div class="header-tools">' in user_page
feed_script = TestClient(app).get('/static/feed.js?v=4').text feed_script = TestClient(app).get('/static/feed.js?v=4').text
assert 'window.location.assign(selectedUser ? `/${encodeURIComponent(selectedUser)}/` : \'/\')' in feed_script assert 'window.location.assign(selectedUser ? `/${encodeURIComponent(selectedUser)}/` : \'/\')' in feed_script
assert client.get('/login').status_code == 200 assert client.get('/login').status_code == 200
login_page = client.get('/login').text login_page = client.get('/login').text
assert 'Sign in' in login_page assert 'Sign in' in login_page
assert 'name="otp"' in login_page
assert 'src="/static/logo.svg"' in login_page assert 'src="/static/logo.svg"' in login_page
assert 'id="auth-session" class="auth-session hidden"' in login_page assert 'id="auth-session" class="auth-session hidden"' in login_page
assert 'logout.js?v=3' in login_page assert 'logout.js?v=3' in login_page
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
updates = json.loads((Path(__file__).resolve().parents[2] / 'webextension' / 'updates.json').read_text())
latest_update = updates['addons']['linklog@kolkman.org']['updates'][0]
assert latest_update['update_link'] 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
@@ -394,14 +821,36 @@ def test_public_and_admin_pages_render_html():
assert 'id="auth-menu" class="auth-menu hidden"' in admin_page assert 'id="auth-menu" class="auth-menu hidden"' in admin_page
assert 'id="auth-home-link" href="/">Home</a>' in admin_page assert 'id="auth-home-link" href="/">Home</a>' in admin_page
assert '<a id="auth-username" class="user-name" href="/">' in admin_page assert '<a id="auth-username" class="user-name" href="/">' in admin_page
assert 'admin.js?v=5' in admin_page assert 'class="panel-toggle-btn"' in admin_page
assert 'admin.js?v=7' in admin_page
assert client.get('/profile').status_code == 200
profile_page = client.get('/profile').text
assert 'Profile' in profile_page
assert 'class="link-item settings-panel minimized"' in profile_page
assert 'class="panel-toggle-btn"' in profile_page
assert 'profile.js?v=6' in profile_page
feed_script = client.get('/static/feed.js?v=7').text feed_script = client.get('/static/feed.js?v=7').text
assert 'if (item.is_owner)' in feed_script assert 'function loadFeed()' in feed_script
assert 'tag.toLowerCase() === pref.tag.toLowerCase()' in feed_script assert 'function renderPagination(page, totalPages)' in feed_script
assert 'if (item.is_owner && !showIdentity)' in feed_script
assert 'deleteEntry(item, deleteButton)' in feed_script
assert 'postToMastodon(item, mastodonButton)' in feed_script
assert "params.set('tag', pref.tag)" in feed_script
assert 'currentPage = 1' in feed_script
assert "Promise.all([loadUsers(), loadTags()])" in feed_script
assert "fetch('/api/tags', {" in feed_script
assert 'Authorization: `Bearer ${accessToken}`' in feed_script
assert 'return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`' in feed_script assert 'return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`' in feed_script
assert "entryMeta.className = 'entry-meta'" in feed_script
assert "meta.className = 'meta'" in feed_script
assert "comment.textContent = item.comment || ''" in feed_script
assert 'profileLink.href = `/${encodeURIComponent(username)}/`' in feed_script
assert 'edit-tag-options' in feed_script assert 'edit-tag-options' in feed_script
assert 'new_tags' in feed_script assert 'new_tags' in feed_script
assert 'A link can have at most 10 tags.' in feed_script assert 'A link can have at most 10 tags.' in feed_script
style_sheet = client.get('/static/style.css').text
assert "@import url('/static/fonts/fonts.css');" in style_sheet
assert 'fonts.googleapis.com' not in style_sheet
def test_link_submission_posts_to_enabled_mastodon_plugin(): def test_link_submission_posts_to_enabled_mastodon_plugin():
@@ -427,31 +876,69 @@ def test_link_submission_posts_to_enabled_mastodon_plugin():
try: try:
headers = login_headers() headers = login_headers()
base_url = f'http://127.0.0.1:{server.server_port}' base_url = f'http://127.0.0.1:{server.server_port}'
assert client.put('/api/user/plugins/mastodon', headers=headers, json={ with patch('backend.app.services.plugin_manager.validate_public_instance', return_value=base_url):
'instance': base_url, assert client.put('/api/user/plugins/mastodon', headers=headers, json={
'access_token': 'test-token', 'instance': base_url,
'post_prefix': 'From my #LinkLog: ', 'access_token': 'test-token',
}).status_code == 200 'post_prefix': 'From my #LinkLog: ',
assert client.put('/api/admin/plugins/mastodon', headers=headers, json={'enabled': True}).status_code == 200 }).status_code == 200
assert client.put('/api/admin/plugins/mastodon', headers=headers, json={'enabled': True}).status_code == 200
response = client.post('/api/links', headers=headers, json={ response = client.post('/api/links', headers=headers, json={
'title': 'A useful page', 'title': 'A useful page',
'url': 'https://example.com/useful', 'url': 'https://example.com/useful',
'comment': 'Worth sharing', 'comment': 'Worth sharing',
'tags': ['#python', '#web'], 'timestamp': '2026-08-29T21:10:00Z',
}) 'tags': ['#python', '#web'],
})
assert response.status_code == 201 assert response.status_code == 201
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': ['A useful page\nWorth sharing\nFrom my #LinkLog: https://example.com/useful #python #web']} assert received['body'] == {'status': ['From my #LinkLog:\n\nA useful page\n\nWorth sharing\n\nLogged on 2026 August 29 - 21:10 UTC from: https://example.com/useful\n\n#python #web']}
posted_item = next(item for item in client.get('/api/public/feed/alice', headers=headers).json()['items'] if item['id'] == response.json()['id'])
assert posted_item['mastodon_posted'] is True
finally: finally:
server.shutdown() server.shutdown()
thread.join() thread.join()
server.server_close() server.server_close()
def test_link_submission_can_skip_mastodon_posting():
with patch('backend.app.api.links.plugin_manager.dispatch', return_value=[]) as dispatch:
response = client.post('/api/links', headers=login_headers(), json={
'title': 'Private share',
'url': 'https://example.com/private-share',
'post_to_mastodon': False,
})
assert response.status_code == 201
assert dispatch.call_args.args[0]['post_to_mastodon'] is False
def test_mastodon_post_without_title_omits_source_line():
from backend.app.services.plugin_manager import MastodonPlugin
response = MagicMock()
response.__enter__.return_value.read.return_value = b'{"id":"status-2"}'
plugin = MastodonPlugin()
plugin.initialize({'instance': 'https://mastodon.example', 'access_token': 'test-token'})
with patch('backend.app.services.plugin_manager.open_no_redirect', return_value=response) as open_url, \
patch('backend.app.services.plugin_manager.validate_public_instance', return_value='https://mastodon.example'):
result = plugin.handle_event({
'url': 'https://example.com/useful',
'title': '',
'comment': 'A comment',
'tags': ['#tag'],
})
body = parse_qs(open_url.call_args.args[0].data.decode())['status'][0]
assert result['status'] == 'posted'
assert body == 'From my #LinkLog:\n\nA comment\n\n#tag'
def test_plugin_config_can_be_saved_for_mastodon(): def test_plugin_config_can_be_saved_for_mastodon():
headers = login_headers() headers = login_headers()
assert client.put('/api/user/plugins/mastodon', headers=headers, json={ assert client.put('/api/user/plugins/mastodon', headers=headers, json={
@@ -463,6 +950,7 @@ def test_plugin_config_can_be_saved_for_mastodon():
payload = client.get('/api/user/plugins/mastodon', headers=headers).json() payload = client.get('/api/user/plugins/mastodon', headers=headers).json()
assert payload['instance'] == 'mastodon.social' assert payload['instance'] == 'mastodon.social'
assert payload['post_prefix'] == 'From my #LinkLog: ' assert payload['post_prefix'] == 'From my #LinkLog: '
assert payload['configured'] is True
admin_update = client.put('/api/admin/plugins/mastodon', headers=headers, json={ admin_update = client.put('/api/admin/plugins/mastodon', headers=headers, json={
'enabled': True, 'enabled': True,
+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 -2
View File
@@ -10,7 +10,7 @@ def test_database_migrations_are_versioned_and_idempotent():
connection = sqlite3.connect(':memory:') connection = sqlite3.connect(':memory:')
apply_migrations(connection) apply_migrations(connection)
assert get_schema_version(connection) == 8 assert get_schema_version(connection) == 17
tables = { tables = {
row[0] row[0]
for row in connection.execute( for row in connection.execute(
@@ -27,6 +27,6 @@ def test_database_migrations_are_versioned_and_idempotent():
assert set(DEFAULT_TAGS) <= seeded_tags assert set(DEFAULT_TAGS) <= seeded_tags
apply_migrations(connection) apply_migrations(connection)
assert get_schema_version(connection) == 8 assert get_schema_version(connection) == 17
connection.close() connection.close()
+51 -3
View File
@@ -3,7 +3,7 @@
from unittest.mock import patch from unittest.mock import patch
from backend.app.services.email_service import send_test_email, send_verification_email from backend.app.services.email_service import send_password_reset_email, send_test_email, send_verification_email
def test_send_verification_email_uses_smtp_settings(monkeypatch): def test_send_verification_email_uses_smtp_settings(monkeypatch):
@@ -15,6 +15,7 @@ def test_send_verification_email_uses_smtp_settings(monkeypatch):
monkeypatch.setattr(settings, 'smtp_username', 'mailer') monkeypatch.setattr(settings, 'smtp_username', 'mailer')
monkeypatch.setattr(settings, 'smtp_password', 'secret') monkeypatch.setattr(settings, 'smtp_password', 'secret')
monkeypatch.setattr(settings, 'smtp_use_tls', True) monkeypatch.setattr(settings, 'smtp_use_tls', True)
monkeypatch.setattr(settings, 'public_url', 'https://linklog.example')
with patch('backend.app.services.email_service.SMTP') as smtp_class: with patch('backend.app.services.email_service.SMTP') as smtp_class:
smtp = smtp_class.return_value.__enter__.return_value smtp = smtp_class.return_value.__enter__.return_value
@@ -25,7 +26,22 @@ def test_send_verification_email_uses_smtp_settings(monkeypatch):
smtp.login.assert_called_once_with('mailer', 'secret') smtp.login.assert_called_once_with('mailer', 'secret')
message = smtp.send_message.call_args.args[0] message = smtp.send_message.call_args.args[0]
assert message['To'] == 'user@example.com' assert message['To'] == 'user@example.com'
assert 'https://linklog.example/verify' in message.get_content() assert 'https://linklog.example/verify' in message.get_body(preferencelist=('plain',)).get_content()
html = message.get_body(preferencelist=('html',)).get_content()
assert 'cid:linklog-logo' in html
assert 'width="50" height="50"' in html
assert 'font-family:\'Asset\',Georgia,serif' in html
assert 'Hello, a message from' in html
assert 'vertical-align:top' in html
assert 'padding:20px 0 20px 12px' in html
assert 'font-size:18px' in html
assert 'href="https://linklog.example"' in html
assert '>linklog.example</a>' in html
assert any(
part.get_content_type() == 'image/svg+xml'
and part['Content-ID'] == '<linklog-logo>'
for part in message.walk()
)
def test_send_test_email_uses_configured_recipient(monkeypatch): def test_send_test_email_uses_configured_recipient(monkeypatch):
@@ -39,4 +55,36 @@ def test_send_test_email_uses_configured_recipient(monkeypatch):
message = smtp.send_message.call_args.args[0] message = smtp.send_message.call_args.args[0]
assert message['To'] == 'admin@example.com' assert message['To'] == 'admin@example.com'
assert message['Subject'] == 'LinkLog SMTP test' assert message['Subject'] == 'LinkLog SMTP test'
assert message.get_body(preferencelist=('html',)) is not None
def test_password_reset_email_escapes_html_and_includes_logo(monkeypatch):
from backend.app.core.config import settings
monkeypatch.setattr(settings, 'smtp_host', 'smtp.example.com')
monkeypatch.setattr(settings, 'smtp_from', 'LinkLog <no-reply@example.com>')
with patch('backend.app.services.email_service.SMTP') as smtp_class:
smtp = smtp_class.return_value.__enter__.return_value
send_password_reset_email('user@example.com', '<User>', 'https://linklog.example/reset?x=1&y=2')
message = smtp.send_message.call_args.args[0]
html = message.get_body(preferencelist=('html',)).get_content()
assert '&lt;User&gt;' in html
assert 'x=1&amp;y=2' in html
assert 'cid:linklog-logo' in html
def test_smtp_password_is_encrypted_at_rest():
from backend.app.services.email_service import get_smtp_settings, save_smtp_settings
from backend.app.database import get_connection
values = {
'smtp_host': 'smtp.example.com', 'smtp_port': 587, 'smtp_username': 'mailer',
'smtp_password': 'secret', 'smtp_from': 'LinkLog <no-reply@example.com>', 'smtp_use_tls': True,
}
save_smtp_settings(values)
with get_connection() as conn:
stored = conn.execute('SELECT value FROM app_settings WHERE name = ?', ('smtp',)).fetchone()['value']
assert 'secret' not in stored
assert get_smtp_settings()['smtp_password'] == 'secret'
+34
View File
@@ -0,0 +1,34 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from unittest.mock import patch
from urllib.error import HTTPError
from urllib.request import Request
import pytest
from backend.app.services.mastodon_security import open_no_redirect, validate_public_instance
@pytest.mark.parametrize('instance', [
'http://mastodon.example',
'https://127.0.0.1',
'https://[::ffff:127.0.0.1]',
'https://user:password@mastodon.example',
])
def test_mastodon_instance_rejects_unsafe_urls(instance):
with pytest.raises(ValueError):
validate_public_instance(instance)
def test_mastodon_instance_rejects_private_dns_result():
with patch('backend.app.services.mastodon_security.socket.getaddrinfo', return_value=[(2, 1, 6, '', ('10.0.0.5', 443))]):
with pytest.raises(ValueError, match='public IP'):
validate_public_instance('https://mastodon.example')
def test_mastodon_outbound_redirects_are_rejected():
request = Request('https://mastodon.example/api/v1/statuses')
with patch('backend.app.services.mastodon_security.NO_REDIRECT_OPENER.open', side_effect=HTTPError(request.full_url, 302, 'Redirects are not allowed', {}, None)):
with pytest.raises(HTTPError, match='Redirects are not allowed'):
open_no_redirect(request)
+117 -5
View File
@@ -1,9 +1,15 @@
## 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 io import BytesIO
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from PIL import Image
from unittest.mock import patch
from backend.app.main import app from backend.app.main import app
from backend.app.database import get_connection
from backend.app.services.otp_service import current_code
client = TestClient(app) client = TestClient(app)
@@ -11,7 +17,7 @@ client = TestClient(app)
def test_user_config_api_and_profile_page(): def test_user_config_api_and_profile_page():
login = client.post('/api/auth/login', json={ login = client.post('/api/auth/login', json={
'username': 'alice', 'email': 'alice@example.com',
'password': 'secret123', 'password': 'secret123',
}).json() }).json()
headers = {'Authorization': f"Bearer {login['access_token']}"} headers = {'Authorization': f"Bearer {login['access_token']}"}
@@ -43,9 +49,13 @@ def test_user_config_api_and_profile_page():
assert 'id="auth-profile-link" class="hidden"' in page_response.text assert 'id="auth-profile-link" class="hidden"' in page_response.text
assert '<a id="auth-username" class="user-name" href="/">' in page_response.text assert '<a id="auth-username" class="user-name" href="/">' in page_response.text
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 '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={
'username': 'bob', 'email': 'bob@example.com',
'password': 'secret123', 'password': 'secret123',
}).json() }).json()
bob_headers = {'Authorization': f"Bearer {bob_login['access_token']}"} bob_headers = {'Authorization': f"Bearer {bob_login['access_token']}"}
@@ -55,7 +65,7 @@ def test_user_config_api_and_profile_page():
}, headers=bob_headers) }, headers=bob_headers)
assert password_response.status_code == 200 assert password_response.status_code == 200
assert client.post('/api/auth/login', json={ assert client.post('/api/auth/login', json={
'username': 'bob', 'email': 'bob@example.com',
'password': 'new-secret-123', 'password': 'new-secret-123',
}).status_code == 200 }).status_code == 200
assert client.put('/api/user/password', json={ assert client.put('/api/user/password', json={
@@ -63,15 +73,117 @@ def test_user_config_api_and_profile_page():
'new_password': 'secret123', 'new_password': 'secret123',
}, headers=bob_headers).status_code == 200 }, headers=bob_headers).status_code == 200
image_buffer = BytesIO()
Image.new('RGB', (2, 2), 'red').save(image_buffer, format='JPEG')
upload_response = client.post( upload_response = client.post(
'/api/user/avatar', '/api/user/avatar',
headers=headers, headers=headers,
files={'avatar': ('avatar.png', b'fake-png-data', 'image/png')}, files={'avatar': ('avatar.jpg', image_buffer.getvalue(), 'image/jpeg')},
) )
assert upload_response.status_code == 200 assert upload_response.status_code == 200
avatar_url = upload_response.json()['avatar_url'] avatar_url = upload_response.json()['avatar_url']
assert avatar_url.startswith('/media/user-1.png') assert avatar_url.startswith('/media/user-1.png')
assert client.get(avatar_url).content == b'fake-png-data' stored_avatar = client.get(avatar_url)
assert stored_avatar.status_code == 200
assert stored_avatar.headers['content-type'] == 'image/png'
with Image.open(BytesIO(stored_avatar.content)) as image:
assert image.format == 'PNG'
assert image.size == (2, 2)
rejected_upload = client.post(
'/api/user/avatar',
headers=headers,
files={'avatar': ('avatar.png', b'fake-png-data', 'image/png')},
)
assert rejected_upload.status_code == 415
updated_profile = client.get('/api/user/me', headers=headers).json() updated_profile = client.get('/api/user/me', headers=headers).json()
assert updated_profile['avatar_url'] == avatar_url assert updated_profile['avatar_url'] == avatar_url
def test_user_can_enable_and_use_otp():
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
headers = {'Authorization': f"Bearer {login['access_token']}"}
setup = client.post('/api/user/otp/setup', headers=headers)
assert setup.status_code == 200
secret = setup.json()['secret']
assert setup.json()['otpauth_url'].startswith('otpauth://totp/')
recovery_codes = setup.json()['recovery_codes']
assert len(recovery_codes) == 10
enabled = client.post('/api/user/otp', headers=headers, json={
'action': 'enable', 'code': current_code(secret),
})
assert enabled.status_code == 200
assert enabled.json()['enabled'] is True
assert client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).status_code == 401
otp_login = client.post('/api/auth/login', json={
'email': 'alice@example.com', 'password': 'secret123', 'otp': current_code(secret),
})
assert otp_login.status_code == 200
disabled = client.post('/api/user/otp', headers=headers, json={
'action': 'disable', 'code': current_code(secret), 'current_password': 'secret123',
})
assert disabled.status_code == 200
assert disabled.json()['enabled'] is False
def test_otp_recovery_code_requires_password_and_is_single_use():
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
headers = {'Authorization': f"Bearer {login['access_token']}"}
setup = client.post('/api/user/otp/setup', headers=headers)
secret = setup.json()['secret']
recovery_code = setup.json()['recovery_codes'][0]
assert client.post('/api/user/otp', headers=headers, json={
'action': 'enable', 'code': current_code(secret),
}).status_code == 200
rejected = client.post('/api/user/otp/recover', headers=headers, json={
'current_password': 'wrong-password', 'recovery_code': recovery_code,
})
assert rejected.status_code == 400
recovered = client.post('/api/user/otp/recover', headers=headers, json={
'current_password': 'secret123', 'recovery_code': recovery_code,
})
assert recovered.status_code == 200
reused = client.post('/api/user/otp/recover', headers=headers, json={
'current_password': 'secret123', 'recovery_code': recovery_code,
})
assert reused.status_code == 400
def test_verified_alternative_can_become_primary():
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
headers = {'Authorization': f"Bearer {login['access_token']}"}
with get_connection() as conn:
address = conn.execute(
'INSERT INTO user_email_addresses (id, user_id, email, verified) VALUES (?, ?, ?, 1) RETURNING id',
('alternative-test', 'user-1', 'alice-alternative@example.com'),
).fetchone()
conn.commit()
promoted = client.post(f"/api/user/emails/{address['id']}/make-primary", headers=headers)
assert promoted.status_code == 200
assert client.post('/api/auth/login', json={'email': 'alice-alternative@example.com', 'password': 'secret123'}).status_code == 200
assert client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).status_code == 200
with get_connection() as conn:
conn.execute('DELETE FROM user_email_addresses WHERE email IN (?, ?)', ('alice@example.com', 'alice-alternative@example.com'))
conn.execute('UPDATE users SET email = ?, email_verified = 1 WHERE id = ?', ('alice@example.com', 'user-1'))
conn.commit()
def test_unverified_alternative_cannot_become_primary():
login = client.post('/api/auth/login', json={'email': 'alice@example.com', 'password': 'secret123'}).json()
headers = {'Authorization': f"Bearer {login['access_token']}"}
with get_connection() as conn:
address = conn.execute(
'INSERT INTO user_email_addresses (id, user_id, email, verified) VALUES (?, ?, ?, 0) RETURNING id',
('unverified-alternative-test', 'user-1', 'alice-unverified@example.com'),
).fetchone()
conn.commit()
rejected = client.post(f"/api/user/emails/{address['id']}/make-primary", headers=headers)
assert rejected.status_code == 400
with get_connection() as conn:
conn.execute('DELETE FROM user_email_addresses WHERE id = ?', (address['id'],))
conn.commit()
+3 -4
View File
@@ -2,10 +2,8 @@
services: services:
app: app:
image: git.kolkman.org/olaf/link-log:development # or :latest or a version-tag image: git.kolkman.org/olaf/link-log:${LINKLOG_VERSION:-latest} # or :development or a :version-tag
container_name: ${APP_CONTAINER_NAME:-linklog-app} container_name: ${APP_CONTAINER_NAME:-linklog-app}
ports:
- "${APP_PORT:-8000}:8000"
volumes: volumes:
- ./linklog_data:/app/backend/data - ./linklog_data:/app/backend/data
environment: environment:
@@ -13,7 +11,8 @@ services:
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog} LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db} LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env} LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
LINKLOG_TOKEN_EXPIRY_DAYS: ${LINKLOG_TOKEN_EXPIRY_DAYS:-30} LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com} LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-linklog.example.com}
LINKLOG_SMTP_HOST: ${LINKLOG_SMTP_HOST:-smtp.example.com} LINKLOG_SMTP_HOST: ${LINKLOG_SMTP_HOST:-smtp.example.com}
LINKLOG_SMTP_PORT: ${LINKLOG_SMTP_PORT:-587} LINKLOG_SMTP_PORT: ${LINKLOG_SMTP_PORT:-587}
+30
View File
@@ -0,0 +1,30 @@
# Local development only. The production compose file intentionally does not publish port 8000.
services:
app:
build:
context: .
dockerfile: Dockerfile
container_name: ${APP_CONTAINER_NAME:-linklog-app-local}
ports:
- "${APP_PORT:-8000}:8000"
volumes:
- ./linklog_data:/app/backend/data
environment:
APP_ENV: ${APP_ENV:-development}
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
LINKLOG_DATA_ENCRYPTION_KEY: ${LINKLOG_DATA_ENCRYPTION_KEY:?Set LINKLOG_DATA_ENCRYPTION_KEY in .env}
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-http://localhost:8000}
LINKLOG_TOKEN_EXPIRY_MINUTES: ${LINKLOG_TOKEN_EXPIRY_MINUTES:-15}
LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS: ${LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS:-30}
LINKLOG_LOG_LEVEL: ${LINKLOG_LOG_LEVEL:-DEBUG}
LINKLOG_TRACKING_PARAMS: ${LINKLOG_TRACKING_PARAMS:-}
restart: ${APP_RESTART_POLICY:-unless-stopped}
healthcheck:
test: ["CMD", "python", "-c", "from urllib.request import urlopen; urlopen('http://127.0.0.1:8000/health', timeout=3)"]
interval: ${APP_HEALTHCHECK_INTERVAL:-30s}
timeout: ${APP_HEALTHCHECK_TIMEOUT:-5s}
start_period: ${APP_HEALTHCHECK_START_PERIOD:-10s}
retries: ${APP_HEALTHCHECK_RETRIES:-3}
+14 -14
View File
@@ -7,8 +7,6 @@ services:
context: . context: .
dockerfile: Dockerfile dockerfile: Dockerfile
container_name: ${APP_CONTAINER_NAME:-linklog-app} container_name: ${APP_CONTAINER_NAME:-linklog-app}
ports:
- "${APP_PORT:-8000}:8000"
volumes: volumes:
- ./linklog_data:/app/backend/data - ./linklog_data:/app/backend/data
environment: environment:
@@ -16,9 +14,11 @@ services:
LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog} LINKLOG_APP_NAME: ${LINKLOG_APP_NAME:-LinkLog}
LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db} LINKLOG_DATABASE_PATH: ${LINKLOG_DATABASE_PATH:-/app/backend/data/linklog.db}
LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env} LINKLOG_SECRET_KEY: ${LINKLOG_SECRET_KEY:?Set LINKLOG_SECRET_KEY in .env}
LINKLOG_PUBLIC_URL: ${LINKLOG_PUBLIC_URL:-localhost} 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_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:
@@ -30,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:-localhost}`) 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:-localhost}`) 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
+286 -18
View File
@@ -8,6 +8,14 @@ const userList = document.querySelector('#user-list');
const userForm = document.querySelector('#user-form'); const userForm = document.querySelector('#user-form');
const adminControls = document.querySelector('#admin-controls'); const adminControls = document.querySelector('#admin-controls');
const adminAuthNotice = document.querySelector('#admin-auth-notice'); const adminAuthNotice = document.querySelector('#admin-auth-notice');
const smtpForm = document.querySelector('#smtp-form');
const smtpTestButton = document.querySelector('#smtp-test-button');
const smtpStatus = document.querySelector('#smtp-status');
const themesForm = document.querySelector('#themes-form');
const themeOptions = document.querySelector('#admin-theme-options');
const themeStatus = document.querySelector('#theme-status');
let smtpNextAllowedAt = null;
let smtpTimerHandle = null;
const accessToken = localStorage.getItem('linklogAccessToken'); const accessToken = localStorage.getItem('linklogAccessToken');
let currentUserId = null; let currentUserId = null;
@@ -18,6 +26,15 @@ function authHeaders(includeJson = false) {
}; };
} }
async function responseError(response, fallback) {
try {
const result = await response.json();
return result.detail || result.message || fallback;
} catch (error) {
return fallback;
}
}
function renderPlugins(plugins) { function renderPlugins(plugins) {
pluginList.replaceChildren(...plugins.map((plugin) => { pluginList.replaceChildren(...plugins.map((plugin) => {
const row = document.createElement('div'); const row = document.createElement('div');
@@ -40,27 +57,145 @@ function renderLabels(labels) {
adminLabelList.replaceChildren(...labels.map((label) => { adminLabelList.replaceChildren(...labels.map((label) => {
const row = document.createElement('div'); const row = document.createElement('div');
row.className = 'plugin-row'; row.className = 'plugin-row';
const text = document.createElement('span'); const text = document.createElement('span');
text.textContent = `${label.name}${label.creator ? ` (${label.creator})` : ' (default)'}`; text.textContent = `${label.name}${label.creator ? ` (${label.creator})` : ' (default)'}`;
const button = document.createElement('button');
button.type = 'button'; const actions = document.createElement('div');
button.className = 'danger-button'; actions.style.display = 'flex';
button.textContent = 'Delete'; actions.style.gap = '8px';
button.addEventListener('click', async () => {
const editButton = document.createElement('button');
editButton.type = 'button';
editButton.textContent = 'Edit';
editButton.addEventListener('click', () => {
showAdminInlineLabelEdit(row, label);
});
const deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.className = 'danger-button';
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', async () => {
if (!confirm(`Are you sure you want to delete "${label.name}"?`)) return;
const response = await fetch(`/api/admin/labels/${label.id}`, {method: 'DELETE', headers: authHeaders()}); const response = await fetch(`/api/admin/labels/${label.id}`, {method: 'DELETE', headers: authHeaders()});
if (response.ok) loadLabels(); if (response.ok) loadLabels();
}); });
row.append(text, button);
actions.append(editButton, deleteButton);
row.append(text, actions);
return row; return row;
})); }));
} }
function showAdminInlineLabelEdit(rowContainer, label) {
rowContainer.replaceChildren();
const editForm = document.createElement('form');
editForm.style.display = 'flex';
editForm.style.gap = '8px';
editForm.style.width = '100%';
editForm.style.alignItems = 'center';
const input = document.createElement('input');
input.type = 'text';
input.value = label.name;
input.required = true;
input.style.flex = '1';
const saveButton = document.createElement('button');
saveButton.type = 'submit';
saveButton.textContent = 'Save';
const cancelButton = document.createElement('button');
cancelButton.type = 'button';
cancelButton.textContent = 'Cancel';
cancelButton.addEventListener('click', () => {
loadLabels();
});
editForm.append(input, saveButton, cancelButton);
editForm.addEventListener('submit', async (e) => {
e.preventDefault();
const newName = input.value.trim();
if (!newName) return;
const response = await fetch(`/api/admin/labels/${label.id}`, {
method: 'PUT',
headers: authHeaders(true),
body: JSON.stringify({ name: newName }),
});
if (response.ok) {
loadLabels();
} else {
alert(await responseError(response, 'Could not update label'));
}
});
rowContainer.appendChild(editForm);
input.focus();
}
async function loadLabels() { async function loadLabels() {
const response = await fetch('/api/admin/labels', {headers: authHeaders()}); const response = await fetch('/api/admin/labels', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load labels'); if (!response.ok) throw new Error('Could not load labels');
renderLabels(await response.json()); renderLabels(await response.json());
} }
function showSmtpStatus(message, isError = false) {
smtpStatus.textContent = message;
smtpStatus.style.color = isError ? '#f38ba8' : '#94e2d5';
}
function updateSmtpTimer() {
if (smtpTimerHandle) window.clearTimeout(smtpTimerHandle);
if (!smtpNextAllowedAt) {
smtpTestButton.disabled = false;
return;
}
const seconds = Math.max(0, Math.ceil((smtpNextAllowedAt - Date.now()) / 1000));
if (seconds === 0) {
smtpNextAllowedAt = null;
updateSmtpTimer();
return;
}
const minutes = Math.floor(seconds / 60);
showSmtpStatus(`Next validation email available in ${minutes ? `${minutes}m ` : ''}${seconds % 60}s.`);
smtpTestButton.disabled = true;
smtpTimerHandle = window.setTimeout(updateSmtpTimer, 1000);
}
async function loadSmtpSettings() {
const response = await fetch('/api/admin/smtp', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load SMTP settings');
const settings = await response.json();
for (const [name, value] of Object.entries(settings)) {
const field = smtpForm.elements[name];
if (!field || name === 'password_configured') continue;
if (field.type === 'checkbox') {
field.checked = value;
} else {
field.value = value;
}
}
}
async function loadThemes() {
const response = await fetch('/api/admin/themes', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load themes');
const result = await response.json();
themeOptions.replaceChildren(...Object.entries(result.themes).map(([id, theme]) => {
const label = document.createElement('label');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'theme';
checkbox.value = id;
checkbox.checked = result.enabled.includes(id);
label.append(checkbox, document.createTextNode(` ${theme.label}`));
return label;
}));
}
function renderUsers(users) { function renderUsers(users) {
userList.replaceChildren(...users.map((user) => { userList.replaceChildren(...users.map((user) => {
const row = document.createElement('div'); const row = document.createElement('div');
@@ -81,6 +216,11 @@ function renderUsers(users) {
privilegeLabel.append(privilegeCheckbox, document.createTextNode(' Administrator')); privilegeLabel.append(privilegeCheckbox, document.createTextNode(' Administrator'));
row.append(label, privilegeLabel); row.append(label, privilegeLabel);
if (!isCurrentUser) { if (!isCurrentUser) {
const otpButton = document.createElement('button');
otpButton.type = 'button';
otpButton.textContent = 'Reset OTP';
otpButton.addEventListener('click', () => resetUserOtp(user, otpButton));
row.append(otpButton);
const button = document.createElement('button'); const button = document.createElement('button');
button.type = 'button'; button.type = 'button';
button.className = 'danger-button'; button.className = 'danger-button';
@@ -92,15 +232,78 @@ function renderUsers(users) {
})); }));
} }
async function resetUserOtp(user, button) {
if (!window.confirm(`Disable OTP for ${user.username}?`)) return;
button.disabled = true;
const status = document.querySelector('#user-status');
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(user.id)}/otp/reset`, {
method: 'POST',
headers: authHeaders(),
});
if (!response.ok) {
throw new Error(await responseError(response, `Request failed (${response.status})`));
}
status.textContent = `OTP disabled for ${user.username}.`;
status.style.color = '#94e2d5';
} catch (error) {
status.textContent = `Could not reset OTP for ${user.username}: ${error.message}`;
status.style.color = '#f38ba8';
button.disabled = false;
}
}
async function loadUsers() { async function loadUsers() {
const response = await fetch('/api/admin/users', {headers: authHeaders()}); const response = await fetch('/api/admin/users', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load users'); if (!response.ok) throw new Error('Could not load users');
renderUsers(await response.json()); renderUsers(await response.json());
} }
function initPanelToggles() {
const panels = document.querySelectorAll('#admin-controls .settings-panel');
panels.forEach((panel) => {
panel.classList.add('minimized');
const h2 = panel.querySelector('h2');
if (!h2) return;
let btn = h2.querySelector('.panel-toggle-btn');
if (!btn) {
const titleText = h2.textContent.trim();
h2.replaceChildren();
btn = document.createElement('button');
btn.type = 'button';
btn.className = 'panel-toggle-btn';
btn.setAttribute('aria-expanded', 'false');
const textSpan = document.createElement('span');
textSpan.textContent = titleText;
const iconSpan = document.createElement('span');
iconSpan.className = 'panel-toggle-icon';
iconSpan.setAttribute('aria-hidden', 'true');
iconSpan.textContent = '▼';
btn.append(textSpan, iconSpan);
h2.appendChild(btn);
} else {
btn.setAttribute('aria-expanded', 'false');
}
if (h2.dataset.initialized) return;
h2.dataset.initialized = 'true';
h2.addEventListener('click', (e) => {
e.preventDefault();
const isMinimized = panel.classList.toggle('minimized');
if (btn) {
btn.setAttribute('aria-expanded', String(!isMinimized));
}
});
});
}
function showAdminState(isAdmin) { function showAdminState(isAdmin) {
adminControls.classList.toggle('hidden', !isAdmin); adminControls.classList.toggle('hidden', !isAdmin);
adminAuthNotice.classList.toggle('hidden', isAdmin); adminAuthNotice.classList.toggle('hidden', isAdmin);
if (isAdmin) {
initPanelToggles();
}
} }
function showSignedOutState() { function showSignedOutState() {
@@ -119,7 +322,7 @@ async function loadAdminState() {
return; return;
} }
const sessionResponse = await fetch(`/api/auth/me?token=${encodeURIComponent(accessToken)}`); const sessionResponse = await fetch('/api/auth/me', {headers: authHeaders()});
if (!sessionResponse.ok) { if (!sessionResponse.ok) {
localStorage.removeItem('linklogAccessToken'); localStorage.removeItem('linklogAccessToken');
showSignedOutState(); showSignedOutState();
@@ -133,7 +336,7 @@ async function loadAdminState() {
return; return;
} }
await Promise.all([loadUsers(), loadPlugins(), loadLabels()]); await Promise.all([loadUsers(), loadPlugins(), loadLabels(), loadSmtpSettings(), loadThemes()]);
showAdminState(true); showAdminState(true);
} }
@@ -199,20 +402,80 @@ userForm.addEventListener('submit', async (event) => {
event.preventDefault(); event.preventDefault();
const values = Object.fromEntries(new FormData(userForm)); const values = Object.fromEntries(new FormData(userForm));
values.is_admin = userForm.elements.is_admin.checked; values.is_admin = userForm.elements.is_admin.checked;
const response = await fetch('/api/admin/users', {
method: 'POST',
headers: authHeaders(true),
body: JSON.stringify(values),
});
const status = document.querySelector('#user-status'); const status = document.querySelector('#user-status');
status.textContent = response.ok ? 'User added.' : 'Could not add user.'; try {
status.style.color = response.ok ? '#94e2d5' : '#f38ba8'; const response = await fetch('/api/admin/users', {
if (response.ok) { method: 'POST',
userForm.reset(); headers: authHeaders(true),
await loadUsers(); body: JSON.stringify(values),
});
status.textContent = response.ok ? 'User added.' : await responseError(response, 'Could not add user.');
status.style.color = response.ok ? '#94e2d5' : '#f38ba8';
if (response.ok) {
userForm.reset();
await loadUsers();
}
} catch (error) {
status.textContent = `Could not add user: ${error.message}`;
status.style.color = '#f38ba8';
} }
}); });
smtpForm.addEventListener('submit', async (event) => {
event.preventDefault();
const values = Object.fromEntries(new FormData(smtpForm));
values.smtp_port = Number(values.smtp_port);
values.smtp_use_tls = smtpForm.elements.smtp_use_tls.checked;
try {
const response = await fetch('/api/admin/smtp', {
method: 'PUT',
headers: authHeaders(true),
body: JSON.stringify(values),
});
showSmtpStatus(response.ok ? 'SMTP settings saved.' : await responseError(response, 'Could not save SMTP settings.'), !response.ok);
if (response.ok) smtpForm.elements.smtp_password.value = '';
} catch (error) {
showSmtpStatus(`Could not save SMTP settings: ${error.message}`, true);
}
});
smtpTestButton.addEventListener('click', async () => {
smtpTestButton.disabled = true;
const values = Object.fromEntries(new FormData(smtpForm));
values.smtp_port = Number(values.smtp_port);
values.smtp_use_tls = smtpForm.elements.smtp_use_tls.checked;
try {
const response = await fetch('/api/admin/smtp/test', {
method: 'POST',
headers: authHeaders(true),
body: JSON.stringify(values),
});
const result = response.ok ? await response.json() : {};
showSmtpStatus(response.ok ? result.message : await responseError(response, 'SMTP validation failed.'), !response.ok);
if (response.headers.get('Retry-After')) {
smtpNextAllowedAt = Date.now() + Number(response.headers.get('Retry-After')) * 1000;
} else if (result.next_allowed_at) {
smtpNextAllowedAt = Date.parse(result.next_allowed_at);
}
} catch (error) {
showSmtpStatus(`SMTP validation failed: ${error.message}`, true);
}
updateSmtpTimer();
});
themesForm.addEventListener('submit', async (event) => {
event.preventDefault();
const themes = [...themesForm.querySelectorAll('input[name="theme"]:checked')].map((input) => input.value);
const response = await fetch('/api/admin/themes', {
method: 'PUT',
headers: authHeaders(true),
body: JSON.stringify({themes}),
});
const result = await response.json();
themeStatus.textContent = response.ok ? 'Themes saved.' : (result.detail || 'Could not save themes.');
themeStatus.style.color = response.ok ? '#94e2d5' : '#f38ba8';
});
loadAdminState().catch((error) => { loadAdminState().catch((error) => {
showAdminState(false); showAdminState(false);
adminAuthNotice.textContent = accessToken adminAuthNotice.textContent = accessToken
@@ -222,5 +485,10 @@ loadAdminState().catch((error) => {
userList.textContent = ''; userList.textContent = '';
pluginList.textContent = ''; pluginList.textContent = '';
adminLabelList.textContent = ''; adminLabelList.textContent = '';
smtpForm.reset();
themesForm.reset();
}); });
document.addEventListener('DOMContentLoaded', initPanelToggles);
initPanelToggles();
})(); })();
+18 -1
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');
@@ -13,6 +14,10 @@
const menu = document.querySelector('#auth-menu'); const menu = document.querySelector('#auth-menu');
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;
@@ -21,9 +26,20 @@
menu.classList.toggle('hidden', isOpen); menu.classList.toggle('hidden', isOpen);
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);
@@ -47,7 +64,7 @@
return; return;
} }
fetch(`/api/auth/me?token=${encodeURIComponent(token)}`) fetch('/api/auth/me', {headers: {Authorization: `Bearer ${token}`}})
.then((response) => { .then((response) => {
if (!response.ok) throw new Error('Session expired'); if (!response.ok) throw new Error('Session expired');
return response.json(); return response.json();
+158 -30
View File
@@ -5,10 +5,15 @@ const feedEl = document.getElementById('feed');
const sortSelect = document.getElementById('sort-select'); const sortSelect = document.getElementById('sort-select');
const userFilter = document.getElementById('user-filter'); const userFilter = document.getElementById('user-filter');
const tagFilter = document.getElementById('tag-filter'); const tagFilter = document.getElementById('tag-filter');
const searchInput = document.getElementById('search-input');
const pageSizeSelect = document.getElementById('page-size-select');
const paginationEl = document.getElementById('pagination');
const cookieName = 'linklog-feed-preferences'; const cookieName = 'linklog-feed-preferences';
const accessToken = localStorage.getItem('linklogAccessToken'); const accessToken = localStorage.getItem('linklogAccessToken');
let availableTags = []; let availableTags = [];
let pageSizes = [25, 100, 250];
let currentPage = 1;
function createAvatar(user) { function createAvatar(user) {
const avatar = document.createElement('div'); const avatar = document.createElement('div');
@@ -63,6 +68,17 @@ function formatDate(value) {
return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`; return `${date.getFullYear()} ${months[date.getMonth()]} ${date.getDate()} - ${hours}:${minutes}`;
} }
async function loadConfig() {
const response = await fetch('/api/public/config');
if (!response.ok) throw new Error('Could not load config');
const config = await response.json();
pageSizes = config.feed_page_sizes?.length ? config.feed_page_sizes : pageSizes;
const pref = readPreferences();
const selected = pageSizes.includes(pref.pageSize) ? pref.pageSize : pageSizes[0];
pageSizeSelect.replaceChildren(...pageSizes.map((size) => new Option(`${size} per page`, String(size))));
pageSizeSelect.value = String(selected);
}
async function loadUsers() { async function loadUsers() {
const response = await fetch('/api/public/users'); const response = await fetch('/api/public/users');
if (!response.ok) throw new Error('Could not load users'); if (!response.ok) throw new Error('Could not load users');
@@ -73,7 +89,9 @@ async function loadUsers() {
} }
async function loadTags() { async function loadTags() {
const response = await fetch('/api/tags'); const response = await fetch('/api/tags', {
headers: accessToken ? {Authorization: `Bearer ${accessToken}`} : {},
});
if (!response.ok) throw new Error('Could not load tags'); if (!response.ok) throw new Error('Could not load tags');
const tags = await response.json(); const tags = await response.json();
availableTags = tags; availableTags = tags;
@@ -104,46 +122,136 @@ function renderFeed(items, showIdentity = true) {
const comment = document.createElement('div'); const comment = document.createElement('div');
comment.className = 'comment'; comment.className = 'comment';
comment.textContent = item.comment || 'No comment provided'; comment.textContent = item.comment || '';
const entryMeta = document.createElement('div');
entryMeta.className = 'entry-meta';
if (item.tags?.length) { if (item.tags?.length) {
const tags = document.createElement('div'); const tags = document.createElement('div');
tags.className = 'entry-tags'; tags.className = 'entry-tags';
tags.textContent = item.tags.join(' '); tags.textContent = item.tags.join(' ');
article.appendChild(tags); entryMeta.appendChild(tags);
} }
const meta = document.createElement('div'); const meta = document.createElement('div');
meta.className = 'meta'; meta.className = 'meta';
meta.textContent = formatDate(item.created_at); meta.textContent = formatDate(item.created_at);
entryMeta.appendChild(meta);
if (item.is_owner) { if (item.is_owner && !showIdentity) {
const actions = document.createElement('div');
actions.className = 'entry-actions';
const editButton = document.createElement('button'); const editButton = document.createElement('button');
editButton.type = 'button'; editButton.type = 'button';
editButton.className = 'edit-button'; editButton.className = 'edit-button';
editButton.textContent = 'Edit'; editButton.textContent = 'Edit';
editButton.addEventListener('click', () => showEditForm(article, item)); editButton.addEventListener('click', () => showEditForm(article, item));
article.appendChild(editButton); const deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.className = 'delete-button';
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', () => deleteEntry(item, deleteButton));
const mastodonButton = document.createElement('button');
mastodonButton.type = 'button';
mastodonButton.className = `mastodon-button${item.mastodon_posted ? ' posted' : ''}`;
const mastodonLogo = document.createElement('img');
mastodonLogo.src = '/static/mastodon.svg';
mastodonLogo.alt = '';
mastodonButton.append(mastodonLogo, document.createTextNode(item.mastodon_posted ? 'Post again' : 'Post to Mastodon'));
mastodonButton.addEventListener('click', () => postToMastodon(item, mastodonButton));
actions.append(editButton, deleteButton);
article.appendChild(actions);
article.appendChild(mastodonButton);
} }
if (showIdentity) { if (showIdentity) {
const header = document.createElement('div'); const header = document.createElement('div');
header.className = 'link-header'; header.className = 'link-header';
header.appendChild(createAvatar(item.user)); const username = item.user?.username || 'unknown';
const profileLink = document.createElement('a');
profileLink.className = 'user-link';
profileLink.href = `/${encodeURIComponent(username)}/`;
profileLink.setAttribute('aria-label', `View ${username}'s profile`);
profileLink.appendChild(createAvatar(item.user));
const userName = document.createElement('div'); const userName = document.createElement('div');
userName.className = 'user-name'; userName.className = 'user-name';
userName.textContent = item.user?.username || 'unknown'; userName.textContent = username;
header.appendChild(userName); profileLink.appendChild(userName);
header.appendChild(profileLink);
article.appendChild(header); article.appendChild(header);
} }
article.appendChild(title); article.appendChild(title);
article.appendChild(comment); article.appendChild(comment);
article.appendChild(meta); article.appendChild(entryMeta);
feedEl.appendChild(article); feedEl.appendChild(article);
}); });
} }
function renderPagination(page, totalPages) {
paginationEl.innerHTML = '';
if (totalPages <= 1) return;
const goToPage = (target) => {
currentPage = Math.min(Math.max(target, 1), totalPages);
loadFeed();
};
const makeButton = (label, target, options = {}) => {
const button = document.createElement('button');
button.type = 'button';
button.textContent = label;
if (options.active) button.classList.add('active');
if (options.disabled) button.disabled = true;
button.addEventListener('click', () => goToPage(target));
return button;
};
paginationEl.appendChild(makeButton('Previous', page - 1, {disabled: page <= 1}));
const pageNumbers = new Set([1, totalPages, page, page - 1, page + 1]);
let previous = null;
[...pageNumbers].filter((num) => num >= 1 && num <= totalPages).sort((a, b) => a - b).forEach((num) => {
if (previous !== null && num - previous > 1) {
const ellipsis = document.createElement('span');
ellipsis.className = 'pagination-ellipsis';
ellipsis.textContent = '…';
paginationEl.appendChild(ellipsis);
}
paginationEl.appendChild(makeButton(String(num), num, {active: num === page}));
previous = num;
});
paginationEl.appendChild(makeButton('Next', page + 1, {disabled: page >= totalPages}));
}
async function postToMastodon(item, button) {
button.disabled = true;
const response = await fetch(`/api/links/${encodeURIComponent(item.id)}/mastodon`, {
method: 'POST',
headers: {Authorization: `Bearer ${accessToken}`},
});
if (response.ok) {
await loadFeed();
} else {
button.disabled = false;
}
}
async function deleteEntry(item, button) {
if (!window.confirm(`Delete this link?`)) return;
button.disabled = true;
const response = await fetch(`/api/links/${encodeURIComponent(item.id)}`, {
method: 'DELETE',
headers: {Authorization: `Bearer ${accessToken}`},
});
if (response.ok) {
await loadFeed();
} else {
button.disabled = false;
}
}
function showEditForm(article, item) { function showEditForm(article, item) {
if (article.querySelector('.edit-form')) return; if (article.querySelector('.edit-form')) return;
const form = document.createElement('form'); const form = document.createElement('form');
@@ -203,30 +311,28 @@ function showEditForm(article, item) {
async function loadFeed() { async function loadFeed() {
const routeUser = document.body.dataset.userFilter; const routeUser = document.body.dataset.userFilter;
const endpoint = routeUser const pref = readPreferences();
const pageSize = pageSizes.includes(pref.pageSize) ? pref.pageSize : pageSizes[0];
const params = new URLSearchParams();
if (pref.tag) params.set('tag', pref.tag);
if (pref.search) params.set('search', pref.search);
params.set('sort', pref.sort || 'newest');
params.set('page', String(currentPage));
params.set('page_size', String(pageSize));
if (pref.user && !routeUser) params.set('username', pref.user);
const path = routeUser
? `/api/public/feed/${encodeURIComponent(routeUser)}` ? `/api/public/feed/${encodeURIComponent(routeUser)}`
: '/api/public/feed'; : '/api/public/feed';
const response = await fetch(endpoint, { const response = await fetch(`${path}?${params.toString()}`, {
headers: accessToken ? {Authorization: `Bearer ${accessToken}`} : {}, headers: accessToken ? {Authorization: `Bearer ${accessToken}`} : {},
}); });
const data = await response.json(); const data = await response.json();
let items = data || []; currentPage = data.page || 1;
const pref = readPreferences(); renderFeed(data.items || [], !routeUser);
renderPagination(currentPage, data.total_pages || 1);
if (pref.user && !routeUser) {
items = items.filter((item) => (item.user?.username || '').toLowerCase() === pref.user.toLowerCase());
}
if (pref.tag) {
items = items.filter((item) => item.tags?.some((tag) => tag.toLowerCase() === pref.tag.toLowerCase()));
}
if (pref.sort === 'oldest') {
items = [...items].reverse();
}
renderFeed(items, !routeUser);
} }
function syncPreferences() { function syncPreferences() {
@@ -234,10 +340,12 @@ function syncPreferences() {
sortSelect.value = pref.sort; sortSelect.value = pref.sort;
userFilter.value = pref.user; userFilter.value = pref.user;
tagFilter.value = pref.tag || ''; tagFilter.value = pref.tag || '';
searchInput.value = pref.search || '';
sortSelect.addEventListener('change', (event) => { sortSelect.addEventListener('change', (event) => {
const next = { ...readPreferences(), sort: event.target.value }; const next = { ...readPreferences(), sort: event.target.value };
writePreferences(next); writePreferences(next);
currentPage = 1;
loadFeed(); loadFeed();
}); });
@@ -251,9 +359,29 @@ function syncPreferences() {
tagFilter.addEventListener('change', (event) => { tagFilter.addEventListener('change', (event) => {
const next = { ...readPreferences(), tag: event.target.value }; const next = { ...readPreferences(), tag: event.target.value };
writePreferences(next); writePreferences(next);
currentPage = 1;
loadFeed();
});
let searchDebounce;
searchInput.addEventListener('input', (event) => {
const next = { ...readPreferences(), search: event.target.value };
writePreferences(next);
currentPage = 1;
clearTimeout(searchDebounce);
searchDebounce = setTimeout(() => loadFeed(), 300);
});
pageSizeSelect.addEventListener('change', (event) => {
const next = { ...readPreferences(), pageSize: Number(event.target.value) };
writePreferences(next);
currentPage = 1;
loadFeed(); loadFeed();
}); });
} }
syncPreferences(); syncPreferences();
Promise.all([loadUsers(), loadTags()]).then(loadFeed).catch(() => loadFeed()); loadConfig()
.then(() => Promise.all([loadUsers(), loadTags()]))
.then(() => loadFeed())
.catch(() => loadFeed());
+209
View File
@@ -0,0 +1,209 @@
// Copyright © 2026 Olaf Kolkman
// SPDX-License-Identifier: GPL-3.0-or-later
(() => {
const labelAuthNotice = document.querySelector('#label-auth-notice');
const labelControls = document.querySelector('#label-controls');
const labelForm = document.querySelector('#label-form');
const labelNameInput = document.querySelector('#label-name');
const labelStatus = document.querySelector('#label-status');
const labelList = document.querySelector('#label-list');
const accessToken = localStorage.getItem('linklogAccessToken');
let currentUserId = null;
function authHeaders(includeJson = false) {
return {
...(includeJson ? {'Content-Type': 'application/json'} : {}),
...(accessToken ? {Authorization: `Bearer ${accessToken}`} : {}),
};
}
function setStatus(message, isError = false) {
if (!labelStatus) return;
labelStatus.textContent = message;
labelStatus.style.color = isError ? '#b91c1c' : '#166534';
}
async function responseError(response, fallback) {
try {
const result = await response.json();
return result.detail || result.message || fallback;
} catch {
return fallback;
}
}
function renderLabels(labels) {
if (!labelList) return;
if (!labels || labels.length === 0) {
labelList.innerHTML = '<p>No labels found.</p>';
return;
}
labelList.replaceChildren(...labels.map((label) => {
const row = document.createElement('div');
row.className = 'plugin-row';
const isOwned = label.created_by === currentUserId;
const contentContainer = document.createElement('div');
contentContainer.style.display = 'flex';
contentContainer.style.alignItems = 'center';
contentContainer.style.justifySpaceBetween = 'space-between';
contentContainer.style.width = '100%';
const text = document.createElement('span');
text.textContent = `${label.name}${isOwned ? '' : (label.creator ? ` (${label.creator})` : ' (default)')}`;
contentContainer.appendChild(text);
if (isOwned) {
const actions = document.createElement('div');
actions.style.display = 'flex';
actions.style.gap = '8px';
const editButton = document.createElement('button');
editButton.type = 'button';
editButton.textContent = 'Edit';
editButton.addEventListener('click', () => {
showInlineEdit(row, label);
});
const deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.className = 'danger-button';
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', async () => {
if (!confirm(`Are you sure you want to delete "${label.name}"?`)) return;
setStatus('');
const response = await fetch(`/api/user/labels/${label.id}`, {
method: 'DELETE',
headers: authHeaders(),
});
if (response.ok) {
setStatus(`Deleted label ${label.name}`);
loadLabels();
} else {
setStatus(await responseError(response, 'Could not delete label'), true);
}
});
actions.append(editButton, deleteButton);
contentContainer.appendChild(actions);
}
row.appendChild(contentContainer);
return row;
}));
}
function showInlineEdit(rowContainer, label) {
rowContainer.replaceChildren();
const editForm = document.createElement('form');
editForm.style.display = 'flex';
editForm.style.gap = '8px';
editForm.style.width = '100%';
editForm.style.alignItems = 'center';
const input = document.createElement('input');
input.type = 'text';
input.value = label.name;
input.required = true;
input.style.flex = '1';
const saveButton = document.createElement('button');
saveButton.type = 'submit';
saveButton.textContent = 'Save';
const cancelButton = document.createElement('button');
cancelButton.type = 'button';
cancelButton.textContent = 'Cancel';
cancelButton.addEventListener('click', () => {
loadLabels();
});
editForm.append(input, saveButton, cancelButton);
editForm.addEventListener('submit', async (e) => {
e.preventDefault();
const newName = input.value.trim();
if (!newName) return;
setStatus('');
const response = await fetch(`/api/user/labels/${label.id}`, {
method: 'PUT',
headers: authHeaders(true),
body: JSON.stringify({ name: newName }),
});
if (response.ok) {
setStatus(`Updated label to ${newName}`);
loadLabels();
} else {
setStatus(await responseError(response, 'Could not update label'), true);
}
});
rowContainer.appendChild(editForm);
input.focus();
}
async function loadLabels() {
try {
const response = await fetch('/api/user/labels', { headers: authHeaders() });
if (!response.ok) throw new Error('Could not load labels');
const labels = await response.json();
renderLabels(labels);
} catch (error) {
setStatus('Error loading labels', true);
}
}
async function init() {
if (!accessToken) {
if (labelAuthNotice) labelAuthNotice.classList.remove('hidden');
if (labelControls) labelControls.classList.add('hidden');
return;
}
if (labelAuthNotice) labelAuthNotice.classList.add('hidden');
if (labelControls) labelControls.classList.remove('hidden');
try {
const meResponse = await fetch('/api/auth/me', { headers: authHeaders() });
if (meResponse.ok) {
const me = await meResponse.json();
currentUserId = me.id;
}
} catch {
// Proceed if me fails
}
await loadLabels();
if (labelForm) {
labelForm.addEventListener('submit', async (e) => {
e.preventDefault();
const name = labelNameInput.value.trim();
if (!name) return;
setStatus('');
const response = await fetch('/api/user/labels', {
method: 'POST',
headers: authHeaders(true),
body: JSON.stringify({ name }),
});
if (response.ok) {
labelNameInput.value = '';
setStatus(`Added label ${name}`);
loadLabels();
} else {
setStatus(await responseError(response, 'Could not add label'), true);
}
});
}
}
document.addEventListener('DOMContentLoaded', init);
if (document.readyState !== 'loading') {
init();
}
})();
+7 -2
View File
@@ -12,11 +12,16 @@ form.addEventListener('submit', async (event) => {
const response = await fetch('/api/auth/login', { const response = await fetch('/api/auth/login', {
method: 'POST', method: 'POST',
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
body: JSON.stringify(Object.fromEntries(new FormData(form))), body: JSON.stringify({
email: form.elements.email.value.trim(),
password: form.elements.password.value,
otp: form.elements.otp.value.trim() || null,
}),
}); });
if (!response.ok) { if (!response.ok) {
status.textContent = 'Sign-in failed.'; const result = await response.json().catch(() => ({}));
status.textContent = result.detail || 'Sign-in failed.';
status.style.color = '#b91c1c'; status.style.color = '#b91c1c';
return; return;
} }
+1 -1
View File
@@ -5,7 +5,7 @@
<svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;"> <svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1,0,0,1,-669.006,-255.89)"> <g transform="matrix(1,0,0,1,-669.006,-255.89)">
<g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)"> <g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)">
<rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(88,91,112);"/> <rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(24, 24, 37);"/>
</g> </g>
<g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)"> <g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)">
<path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/> <path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/>

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

+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);
} }
+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img" aria-label="Mastodon">
<path fill="currentColor" d="M21.6 8.2c0-4.1-2.7-5.3-2.7-5.3C17.5 2.3 14.8 2 12 2h-.1c-2.8 0-5.5.3-6.9.9 0 0-2.7 1.2-2.7 5.3 0 .9 0 2 0 3.1 0 4.2.3 8.3 1.8 9.4 1.7 1.3 4.1 1.6 6.1 1.7 1.9.1 3.6-.4 3.6-.4l-.1-1.8s-1.6.5-3.5.4c-1.8-.1-3.6-.2-3.9-2.1-.1-.5-.1-1-.1-1.5 0 0 1.7.4 3.9.5 1.3.1 2.6.1 3.9-.1 2.5-.3 4.7-.8 4.7-.8v-1.8c0-1.4 0-2.8 0-3.1 0-4.1-2.7-5.3-2.7-5.3-1.4-.6-3.8-.9-6-.9h-.1c-2.2 0-4.6.3-6 .9 0 0-2.7 1.2-2.7 5.3v.1h3.3v-.1c0-1.7.7-2.1.7-2.1.4-.2 1.1-.3 1.8-.3.7 0 1.4.2 1.8.4.7.4 1.1 1.2 1.1 2.3v.5c-1.1-.3-2.3-.4-3.5-.4-2.2 0-3.3.8-3.3.8v3.2h3.3v-1.5c.4-.2 1.1-.3 1.9-.3.8 0 1.5.1 1.9.3v1.5h3.3V9.5c0-1.1.4-1.9 1.1-2.3.4-.2 1.1-.4 1.8-.4.7 0 1.4.1 1.8.3 0 0 .7.4.7 2.1v.1h3.3V8.2z"/>
</svg>

After

Width:  |  Height:  |  Size: 803 B

+347
View File
@@ -0,0 +1,347 @@
// 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 mastodonPublishing = document.getElementById('mastodon-publishing');
const mastodonEnabledCheckbox = document.getElementById('mastodon-enabled');
const scrapeStatus = document.getElementById('scrape-status');
const duplicateStatus = document.getElementById('duplicate-status');
const refetchTitleButton = document.getElementById('refetch-title-button');
const submitButton = document.getElementById('submit-button');
const submitStatus = document.getElementById('submit-status');
const characterCount = document.getElementById('character-count');
const token = localStorage.getItem('linklogAccessToken');
let availableTags = [];
let selectedTags = new Set();
let currentUser = null;
let maxPostCharacters = 500;
let mastodonPostPrefix = 'From my #LinkLog: ';
// Utility function to add status messages; splits on \n into real <br> line breaks without using innerHTML.
function setStatus(statusEl, message, isError = false) {
const lines = message.split('\n');
statusEl.replaceChildren(
...lines.flatMap((line, index) => (
index === 0 ? [document.createTextNode(line)] : [document.createElement('br'), document.createTextNode(line)]
)),
);
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');
Promise.all([loadTags(), loadMastodonPublishing(), loadConfig()]).then(updateCharacterCount);
})
.catch(() => {
localStorage.removeItem('linklogAccessToken');
authRequired.classList.remove('hidden');
entryForm.classList.add('hidden');
});
async function loadConfig() {
try {
const response = await fetch('/api/public/config');
if (!response.ok) throw new Error('Could not load config');
const config = await response.json();
if (config.max_post_characters) maxPostCharacters = config.max_post_characters;
} catch (error) {
console.error('Could not load config:', error);
}
}
// 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);
}
}
async function loadMastodonPublishing() {
try {
const response = await fetch('/api/user/plugins/mastodon', {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) return;
const config = await response.json();
mastodonEnabledCheckbox.checked = Boolean(config.configured);
mastodonPublishing.classList.toggle('hidden', !config.configured);
if (config.post_prefix) {
mastodonPostPrefix = config.post_prefix;
} else if (config.hashtag) {
mastodonPostPrefix = `#${String(config.hashtag).trim().replace(/^#/, '')} `;
}
} catch (error) {
console.error('Could not load Mastodon configuration:', error);
}
}
// Collect the selected checkbox tags plus any typed new tags, mirroring the submit-time logic.
function collectTags() {
const tags = Array.from(selectedTags);
const newTags = newTagsInput.value.trim();
if (newTags) {
tags.push(...newTags.split(',').map((t) => t.trim()).filter(Boolean));
}
return tags;
}
// Format a UTC timestamp the same way the Mastodon plugin does, so the estimated post length matches the server.
function formatMastodonTimestamp(date) {
const months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December',
];
const pad = (value) => String(value).padStart(2, '0');
return `${date.getUTCFullYear()} ${months[date.getUTCMonth()]} ${pad(date.getUTCDate())} - ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}`;
}
// Estimate the assembled Mastodon post length, mirroring backend/app/services/plugin_manager.py.
function estimatePostLength() {
const title = titleInput.value.trim();
const comment = commentInput.value.trim();
const url = removeKnownTrackingParams(urlInput.value.trim());
const parts = [mastodonPostPrefix.trim()];
if (title) parts.push(title);
if (comment) parts.push(comment);
if (title) parts.push(`Logged on ${formatMastodonTimestamp(new Date())} UTC from: ${url}`);
const tags = collectTags();
if (tags.length) parts.push(tags.join(' '));
return parts.join('\n\n').length;
}
function updateCharacterCount() {
const length = estimatePostLength();
const overLimit = length > maxPostCharacters;
characterCount.textContent = overLimit
? `${length}/${maxPostCharacters} characters - exceeds the Mastodon post limit by ${length - maxPostCharacters}`
: `${length}/${maxPostCharacters} characters`;
characterCount.classList.toggle('over-limit', overLimit);
}
[urlInput, titleInput, commentInput, newTagsInput].forEach((input) => {
input.addEventListener('input', updateCharacterCount);
});
// 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);
}
updateCharacterCount();
});
label.appendChild(checkbox);
label.append(` ${tag}`);
existingTagsEl.appendChild(label);
});
}
// Strip known tracking parameters so duplicate detection and scraping ignore them, mirroring the browser extension.
function removeKnownTrackingParams(urlString) {
try {
const url = new URL(urlString);
const known = new Set([
'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',
'utm_id', 'utm_name', 'gclid', 'fbclid', 'dclid', 'msclkid',
]);
for (const key of known) {
url.searchParams.delete(key);
}
return url.toString();
} catch (error) {
return urlString;
}
}
// Fetch the page title for the given URL and fill it in, unless the user already typed one.
let lastScrapedUrl = null;
async function fetchTitle(url, { force = false } = {}) {
if (!url || (!force && (titleInput.value.trim() || url === lastScrapedUrl))) return;
setStatus(scrapeStatus, 'Looking up title...', 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}`);
}
lastScrapedUrl = url;
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);
}
}
urlInput.addEventListener('blur', async () => {
await fetchTitle(removeKnownTrackingParams(urlInput.value.trim()));
checkDuplicate();
});
refetchTitleButton.addEventListener('click', (e) => {
e.preventDefault();
const url = removeKnownTrackingParams(urlInput.value.trim());
if (!url) {
setStatus(scrapeStatus, 'Please enter a URL', true);
return;
}
titleInput.value = '';
fetchTitle(url, { force: true });
});
// Warn when the URL/title combination already exists for this user, mirroring the browser extension.
titleInput.addEventListener('blur', checkDuplicate);
urlInput.addEventListener('input', () => duplicateStatus.classList.add('hidden'));
titleInput.addEventListener('input', () => duplicateStatus.classList.add('hidden'));
async function checkDuplicate() {
const url = removeKnownTrackingParams(urlInput.value.trim());
const title = titleInput.value.trim();
if (!url || !title) return;
try {
const response = await fetch(`/api/links/check?${new URLSearchParams({ title, url })}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) return;
const data = await response.json();
if (data.exists) {
// Re-derive the match locally: browser URL normalization (e.g. trailing slashes) can
// make the server's raw string comparison disagree even when the URLs are equivalent.
const urlMatches = data.url_matches || (data.stored_url && removeKnownTrackingParams(data.stored_url) === url);
let message = 'This link already exists. ';
if (!urlMatches) {
message += 'But, the stored link has a different URL (missing or different parameters).';
message += '\nWhen you save the entry you risk a duplicate entry.';
} else {
message += '\nYou can still save the entry, which will update the existing entry\'s comment and or tags.';
}
setStatus(duplicateStatus, message, true);
} else {
duplicateStatus.classList.add('hidden');
}
} catch (error) {
// Duplicate checking is advisory; submission remains available.
}
}
// Handle form submission
entryForm.addEventListener('submit', async (e) => {
e.preventDefault();
const url = removeKnownTrackingParams(urlInput.value.trim());
const title = titleInput.value.trim();
const comment = commentInput.value.trim();
if (!url || !title) {
setStatus(submitStatus, 'URL and title are required', true);
return;
}
const tags = collectTags();
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,
post_to_mastodon: mastodonEnabledCheckbox.checked,
}),
});
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;
}
});
})();
+218 -2
View File
@@ -9,6 +9,20 @@ const profileLogoutButton = document.querySelector('#logout-button');
const accessToken = localStorage.getItem('linklogAccessToken'); const accessToken = localStorage.getItem('linklogAccessToken');
const defaultPostPrefix = 'From my #LinkLog: '; const defaultPostPrefix = 'From my #LinkLog: ';
const mastodonConnectButton = document.querySelector('#mastodon-connect'); const mastodonConnectButton = document.querySelector('#mastodon-connect');
const otpSetupButton = document.querySelector('#otp-setup');
const otpEnableButton = document.querySelector('#otp-enable');
const otpDisableButton = document.querySelector('#otp-disable');
const otpRecoverButton = document.querySelector('#otp-recover');
const otpProvisioning = document.querySelector('#otp-provisioning');
const otpDisabled = document.querySelector('#otp-disabled');
const otpEnabled = document.querySelector('#otp-enabled');
const otpSecret = document.querySelector('#otp-secret');
const otpUri = document.querySelector('#otp-uri');
const otpRecoveryCodes = document.querySelector('#otp-recovery-codes');
const otpStatus = document.querySelector('#otp-status');
const emailAddressList = document.querySelector('#email-address-list');
const additionalEmailForm = document.querySelector('#additional-email-form');
const emailAddressStatus = document.querySelector('#email-address-status');
function authHeaders(includeJson = false) { function authHeaders(includeJson = false) {
return { return {
@@ -23,12 +37,164 @@ function setStatus(selector, message, isError = false) {
status.style.color = isError ? '#b91c1c' : '#166534'; status.style.color = isError ? '#b91c1c' : '#166534';
} }
function setOtpStatus(message, isError = false) {
otpStatus.textContent = message;
otpStatus.style.color = isError ? '#b91c1c' : '#166534';
}
function setEmailAddressStatus(message, isError = false) {
emailAddressStatus.textContent = message;
emailAddressStatus.style.color = isError ? '#b91c1c' : '#166534';
}
function renderEmailAddresses(addresses) {
emailAddressList.replaceChildren(...addresses.map((address) => {
const row = document.createElement('div');
row.className = 'email-address-row';
const label = document.createElement('span');
label.textContent = `${address.email} - ${address.verified ? 'validated' : 'not validated'}${address.primary ? ' (primary)' : ''}`;
row.appendChild(label);
if (!address.primary) {
if (!address.verified) {
const resend = document.createElement('button');
resend.type = 'button';
resend.textContent = 'Resend validation';
resend.addEventListener('click', async () => {
resend.disabled = true;
const response = await fetch(`/api/user/emails/${encodeURIComponent(address.id)}/resend`, {method: 'POST', headers: authHeaders()});
const result = await response.json();
setEmailAddressStatus(response.ok ? result.message : (result.detail || 'Could not send validation email.'), !response.ok);
if (response.ok && result.next_allowed_at) window.setTimeout(() => { resend.disabled = false; }, Math.max(0, Date.parse(result.next_allowed_at) - Date.now()));
else if (!response.ok) resend.disabled = false;
});
row.appendChild(resend);
}
if (address.verified && address.can_be_primary) {
const makePrimary = document.createElement('button');
makePrimary.type = 'button';
makePrimary.textContent = 'Make primary';
makePrimary.addEventListener('click', async () => {
const response = await fetch(`/api/user/emails/${encodeURIComponent(address.id)}/make-primary`, {method: 'POST', headers: authHeaders()});
const result = await response.json();
setEmailAddressStatus(response.ok ? `${result.email} is now the primary email address.` : (result.detail || 'Could not change primary email.'), !response.ok);
if (response.ok) {
await loadEmailAddresses();
}
});
row.appendChild(makePrimary);
}
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = 'Remove';
remove.addEventListener('click', async () => {
const response = await fetch(`/api/user/emails/${encodeURIComponent(address.id)}`, {method: 'DELETE', headers: authHeaders()});
if (response.ok) loadEmailAddresses();
else setEmailAddressStatus('Could not remove email address.', true);
});
row.appendChild(remove);
}
return row;
}));
}
async function loadEmailAddresses() {
const response = await fetch('/api/user/emails', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load email addresses');
renderEmailAddresses(await response.json());
}
additionalEmailForm.addEventListener('submit', async (event) => {
event.preventDefault();
const response = await fetch('/api/user/emails', {
method: 'POST', headers: authHeaders(true), body: JSON.stringify({email: additionalEmailForm.elements.email.value.trim()}),
});
const result = await response.json();
setEmailAddressStatus(response.ok ? 'Email address added. Check your inbox to validate it.' : (result.detail || 'Could not add email address.'), !response.ok);
if (response.ok) {
additionalEmailForm.reset();
loadEmailAddresses();
}
});
async function loadOtp() {
const response = await fetch('/api/user/otp', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load one-time password settings');
const result = await response.json();
otpDisabled.classList.toggle('hidden', result.enabled);
otpEnabled.classList.toggle('hidden', !result.enabled);
}
otpSetupButton.addEventListener('click', async () => {
const response = await fetch('/api/user/otp/setup', {method: 'POST', headers: authHeaders()});
const result = await response.json();
if (!response.ok) {
setOtpStatus(result.detail || 'Could not start one-time password setup.', true);
return;
}
otpSecret.textContent = result.secret;
otpUri.href = result.otpauth_url;
otpRecoveryCodes.textContent = result.recovery_codes.join('\n');
otpProvisioning.classList.remove('hidden');
setOtpStatus('Enter a code from your authenticator app to confirm setup.');
});
otpEnableButton.addEventListener('click', async () => {
const code = document.querySelector('#otp-setup-code').value.trim();
const response = await fetch('/api/user/otp', {
method: 'POST', headers: authHeaders(true), body: JSON.stringify({action: 'enable', code}),
});
const result = await response.json();
if (!response.ok) {
setOtpStatus(result.detail || 'Could not enable one-time password.', true);
return;
}
otpDisabled.classList.add('hidden');
otpEnabled.classList.remove('hidden');
otpProvisioning.classList.add('hidden');
setOtpStatus('One-time password enabled.');
});
otpDisableButton.addEventListener('click', async () => {
const code = document.querySelector('#otp-disable-code').value.trim();
const currentPassword = document.querySelector('#otp-current-password').value;
const response = await fetch('/api/user/otp', {
method: 'POST', headers: authHeaders(true), body: JSON.stringify({action: 'disable', code, current_password: currentPassword}),
});
const result = await response.json();
if (!response.ok) {
setOtpStatus(result.detail || 'Could not disable one-time password.', true);
return;
}
otpDisabled.classList.remove('hidden');
otpEnabled.classList.add('hidden');
document.querySelector('#otp-disable-code').value = '';
setOtpStatus('One-time password disabled.');
});
otpRecoverButton.addEventListener('click', async () => {
const currentPassword = document.querySelector('#otp-current-password').value;
const recoveryCode = document.querySelector('#otp-recovery-code').value.trim();
const response = await fetch('/api/user/otp/recover', {
method: 'POST', headers: authHeaders(true), body: JSON.stringify({current_password: currentPassword, recovery_code: recoveryCode}),
});
const result = await response.json();
if (!response.ok) {
setOtpStatus(result.detail || 'Could not recover one-time password access.', true);
return;
}
otpDisabled.classList.remove('hidden');
otpEnabled.classList.add('hidden');
document.querySelector('#otp-current-password').value = '';
document.querySelector('#otp-recovery-code').value = '';
setOtpStatus('One-time password access recovered.');
});
async function loadProfile() { async function loadProfile() {
const response = await fetch('/api/user/me', {headers: authHeaders()}); const response = await fetch('/api/user/me', {headers: authHeaders()});
if (!response.ok) throw new Error('Could not load profile'); if (!response.ok) throw new Error('Could not load profile');
const profile = await response.json(); const profile = await response.json();
document.querySelector('#username').textContent = profile.username || ''; document.querySelector('#username').textContent = profile.username || '';
document.querySelector('#email').value = profile.email || ''; document.querySelector('#email').textContent = profile.email || '';
document.querySelector('#bio').value = profile.bio || ''; document.querySelector('#bio').value = profile.bio || '';
const avatarPreview = document.querySelector('#avatar-preview'); const avatarPreview = document.querySelector('#avatar-preview');
if (profile.avatar_url) { if (profile.avatar_url) {
@@ -125,6 +291,14 @@ if (mastodonParams.get('mastodon_error')) setStatus('#mastodon-status', mastodon
passwordForm.addEventListener('submit', async (event) => { passwordForm.addEventListener('submit', async (event) => {
event.preventDefault(); event.preventDefault();
const password = passwordForm.elements.new_password.value;
const confirmation = passwordForm.elements.new_password_confirmation.value;
if (password !== confirmation) {
const status = document.querySelector('#password-status');
status.textContent = 'New passwords do not match.';
status.style.color = '#f38ba8';
return;
}
const response = await fetch('/api/user/password', { const response = await fetch('/api/user/password', {
method: 'PUT', method: 'PUT',
headers: authHeaders(true), headers: authHeaders(true),
@@ -136,7 +310,49 @@ passwordForm.addEventListener('submit', async (event) => {
if (response.ok) passwordForm.reset(); if (response.ok) passwordForm.reset();
}); });
Promise.all([loadProfile(), loadMastodonConfig()]).catch((error) => { function initPanelToggles() {
const panels = document.querySelectorAll('.settings-panel');
panels.forEach((panel) => {
panel.classList.add('minimized');
const h2 = panel.querySelector('h2');
if (!h2) return;
let btn = h2.querySelector('.panel-toggle-btn');
if (!btn) {
const titleText = h2.textContent.trim();
h2.replaceChildren();
btn = document.createElement('button');
btn.type = 'button';
btn.className = 'panel-toggle-btn';
btn.setAttribute('aria-expanded', 'false');
const textSpan = document.createElement('span');
textSpan.textContent = titleText;
const iconSpan = document.createElement('span');
iconSpan.className = 'panel-toggle-icon';
iconSpan.setAttribute('aria-hidden', 'true');
iconSpan.textContent = '▼';
btn.append(textSpan, iconSpan);
h2.appendChild(btn);
} else {
btn.setAttribute('aria-expanded', 'false');
}
if (h2.dataset.initialized) return;
h2.dataset.initialized = 'true';
h2.addEventListener('click', (e) => {
e.preventDefault();
const isMinimized = panel.classList.toggle('minimized');
if (btn) {
btn.setAttribute('aria-expanded', String(!isMinimized));
}
});
});
}
document.addEventListener('DOMContentLoaded', initPanelToggles);
initPanelToggles();
Promise.all([loadProfile(), loadMastodonConfig(), loadOtp(), loadEmailAddresses()]).catch((error) => {
setStatus('#profile-status', accessToken ? error.message : 'Please sign in first.', true); setStatus('#profile-status', accessToken ? error.message : 'Please sign in first.', true);
}); });
})(); })();
+763 -20
View File
@@ -1,7 +1,7 @@
/* Copyright © 2026 Olaf Kolkman */ /* Copyright © 2026 Olaf Kolkman */
/* SPDX-License-Identifier: GPL-3.0-or-later */ /* SPDX-License-Identifier: GPL-3.0-or-later */
@import url('https://fonts.googleapis.com/css2?family=Asset&family=DM+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap'); @import url('/static/fonts/fonts.css');
:root { :root {
--base: #1e1e2e; --base: #1e1e2e;
@@ -23,6 +23,87 @@
--shadow: 0 18px 50px rgba(17, 17, 27, 0.28); --shadow: 0 18px 50px rgba(17, 17, 27, 0.28);
} }
:root[data-theme='plain-day'] {
--base: #f4f1ea; --mantle: #e8e3d8; --crust: #d7d0c2;
--surface-0: #fffdf8; --surface-1: #e5ded1; --surface-2: #c8beae;
--text: #2f2b27; --subtext: #514a42; --muted: #6b6258;
--mauve: #7a3d6e; --lavender: #5d4b84; --blue: #315c78;
--teal: #397c72; --peach: #a15d3d; --red: #a44250;
--border: rgba(47, 43, 39, 0.16); --shadow: 0 18px 50px rgba(47, 43, 39, 0.16);
}
:root[data-theme='plain-night'] {
--base: #181818; --mantle: #111111; --crust: #090909;
--surface-0: #262626; --surface-1: #353535; --surface-2: #4b4b4b;
--text: #eeeeee; --subtext: #c1c1c1; --muted: #929292;
--mauve: #d59acb; --lavender: #b9b4e8; --blue: #8ebbd8;
--teal: #8bc9bd; --peach: #e2ae88; --red: #ec929f;
--border: rgba(238, 238, 238, 0.14); --shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
}
:root[data-theme='latte'] {
--base: #eff1f5; --mantle: #e6e9ef; --crust: #dce0e8;
--surface-0: #ccd0da; --surface-1: #bcc0cc; --surface-2: #acb0be;
--text: #3d4058; --subtext: #51546b; --muted: #65687c;
--mauve: #7627c7; --lavender: #5946b2; --blue: #1854c7;
--teal: #179299; --peach: #fe640b; --red: #d20f39;
--border: rgba(76, 79, 105, 0.16); --shadow: 0 18px 50px rgba(76, 79, 105, 0.16);
}
:root[data-theme='frappe'] {
--base: #303446; --mantle: #292c3c; --crust: #232634;
--surface-0: #414559; --surface-1: #51576d; --surface-2: #626880;
--text: #c6d0f5; --subtext: #b5bfe2; --muted: #838ba7;
--mauve: #ca9ee6; --lavender: #babbf1; --blue: #8caaee;
--teal: #81c8be; --peach: #ef9f76; --red: #e78284;
--border: rgba(198, 208, 245, 0.12); --shadow: 0 18px 50px rgba(35, 38, 52, 0.3);
}
:root[data-theme='macchiato'] {
--base: #24273a; --mantle: #1e2030; --crust: #181926;
--surface-0: #363a4f; --surface-1: #494d64; --surface-2: #5b6078;
--text: #cad3f5; --subtext: #b8c0e0; --muted: #8087a2;
--mauve: #c6a0f6; --lavender: #b7bdf8; --blue: #8aadf4;
--teal: #8bd5ca; --peach: #f5a97f; --red: #ed8796;
--border: rgba(202, 211, 245, 0.12); --shadow: 0 18px 50px rgba(24, 25, 38, 0.34);
}
:root[data-theme='dracula'] {
--base: #282a36; --mantle: #21222c; --crust: #191a21;
--surface-0: #44475a; --surface-1: #6272a4; --surface-2: #7886b5;
--text: #f8f8f2; --subtext: #d6d6d0; --muted: #a7a7a0;
--mauve: #ff79c6; --lavender: #bd93f9; --blue: #8be9fd;
--teal: #50fa7b; --peach: #ffb86c; --red: #ff5555;
--border: rgba(248, 248, 242, 0.14); --shadow: 0 18px 50px rgba(25, 26, 33, 0.35);
}
:root[data-theme='nord'] {
--base: #2e3440; --mantle: #272c36; --crust: #242933;
--surface-0: #3b4252; --surface-1: #434c5e; --surface-2: #4c566a;
--text: #eceff4; --subtext: #d8dee9; --muted: #aeb8c8;
--mauve: #b48ead; --lavender: #d8dee9; --blue: #88c0d0;
--teal: #a3be8c; --peach: #d08770; --red: #bf616a;
--border: rgba(236, 239, 244, 0.14); --shadow: 0 18px 50px rgba(36, 41, 51, 0.35);
}
:root[data-theme='solarized'] {
--base: #fdf6e3; --mantle: #eee8d5; --crust: #e3ddc9;
--surface-0: #eee8d5; --surface-1: #ddd6c1; --surface-2: #c9c1aa;
--text: #073642; --subtext: #586e75; --muted: #657b83;
--mauve: #6c71c4; --lavender: #268bd2; --blue: #268bd2;
--teal: #2aa198; --peach: #cb4b16; --red: #dc322f;
--border: rgba(7, 54, 66, 0.18); --shadow: 0 18px 50px rgba(7, 54, 66, 0.14);
}
:root[data-theme='red'] {
--base: #fffafa; --mantle: #ffedef; --crust: #fbd6da;
--surface-0: #ffffff; --surface-1: #ffe2e6; --surface-2: #f4bbc4;
--text: #350810; --subtext: #5c1724; --muted: #8c4653;
--mauve: #9e1737; --lavender: #86132d; --blue: #216f91;
--teal: #087567; --peach: #b84324; --red: #a70d2d;
--border: rgba(83, 10, 25, 0.2); --shadow: 0 18px 50px rgba(122, 8, 33, 0.2);
}
*, *,
*::before, *::before,
*::after { *::after {
@@ -52,13 +133,14 @@ body::selection {
padding: 0 24px; padding: 0 24px;
} }
.site-header { .site-header {
position: relative; position: relative;
z-index: 20; z-index: 20;
padding: 56px 0 48px; padding: 6px 0 8px;
background: background:
linear-gradient(115deg, rgba(203, 166, 247, 0.18), transparent 45%), linear-gradient(115deg, var(--mantle), transparent 45%),
var(--mantle); rgba(203, 166, 247, 0.18);
border-bottom: 1px solid var(--border); border-bottom: 1px solid var(--border);
} }
@@ -72,6 +154,8 @@ body::selection {
border-radius: 50%; border-radius: 50%;
content: ''; content: '';
transform: rotate(-12deg); transform: rotate(-12deg);
/* decorative only: must not swallow clicks on the toolbar selects underneath */
pointer-events: none;
} }
.site-header h1, .site-header h1,
@@ -90,13 +174,13 @@ body::selection {
.site-logo { .site-logo {
display: block; display: block;
width: min(260px, 70vw); width: min(260px, 70vw);
height: 150px; height: 80px;
margin-bottom: 12px; margin-bottom: 12px;
object-fit: contain; object-fit: contain;
object-position: left center; object-position: left center;
} }
.site-header .site-logo + h1, .site-header .site-logo-link + h1,
.feed-link { .feed-link {
font-family: 'Asset', 'Space Grotesk', sans-serif; font-family: 'Asset', 'Space Grotesk', sans-serif;
} }
@@ -112,7 +196,44 @@ body::selection {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
gap: 24px; gap: 18px;
}
.header-tools {
display: grid;
flex: 1 1 auto;
justify-items: end;
gap: 8px;
}
.header-tools .toolbar {
width: min(100%, 560px);
gap: 6px;
margin: 0;
padding: 0;
border: 0;
background: transparent;
}
.header-tools .toolbar label {
min-width: 0;
flex: 1 1 110px;
font-size: 0.68rem;
}
.header-tools .toolbar .search-control {
flex-basis: 180px;
}
.header-tools .toolbar select {
min-width: 0;
padding: 6px 8px;
}
.header-tools .toolbar input {
width: 100%;
min-width: 0;
padding: 6px 8px;
} }
.header-actions { .header-actions {
@@ -137,6 +258,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;
@@ -203,6 +349,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;
@@ -236,11 +462,118 @@ main.container {
gap: 14px; gap: 14px;
margin: 0 0 24px; margin: 0 0 24px;
padding: 16px; padding: 16px;
background: rgba(24, 24, 37, 0.72); background: var(--surface-0);
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: 12px; border-radius: 12px;
} }
.site-header .toolbar {
margin-top: 18px;
margin-bottom: 0;
}
#admin-controls {
display: grid;
gap: 16px;
}
.settings-panel + .settings-panel {
margin-top: 16px;
}
.settings-panel h2 {
margin: 0 0 12px;
padding: 10px 14px;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.2s ease, margin 0.2s ease;
}
.settings-panel h2:hover {
filter: brightness(1.08);
}
.settings-panel:nth-of-type(5n+1) h2 {
color: var(--mauve);
background: var(--surface-1);
background: color-mix(in srgb, var(--mauve) 14%, transparent);
border-left: 4px solid var(--mauve);
}
.settings-panel:nth-of-type(5n+2) h2 {
color: var(--teal);
background: var(--surface-1);
background: color-mix(in srgb, var(--teal) 14%, transparent);
border-left: 4px solid var(--teal);
}
.settings-panel:nth-of-type(5n+3) h2 {
color: var(--peach);
background: var(--surface-1);
background: color-mix(in srgb, var(--peach) 14%, transparent);
border-left: 4px solid var(--peach);
}
.settings-panel:nth-of-type(5n+4) h2 {
color: var(--blue);
background: var(--surface-1);
background: color-mix(in srgb, var(--blue) 14%, transparent);
border-left: 4px solid var(--blue);
}
.settings-panel:nth-of-type(5n+5) h2 {
color: var(--lavender);
background: var(--surface-1);
background: color-mix(in srgb, var(--lavender) 14%, transparent);
border-left: 4px solid var(--lavender);
}
.settings-panel.minimized h2 {
margin: 0;
}
.panel-toggle-btn {
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
width: 100% !important;
min-width: 0 !important;
padding: 0 !important;
border: none !important;
background: transparent !important;
color: inherit !important;
font: inherit !important;
font-size: 1rem !important;
font-weight: inherit !important;
cursor: pointer !important;
text-align: left !important;
box-shadow: none !important;
}
.panel-toggle-btn > * {
pointer-events: none;
}
.panel-toggle-btn:focus-visible {
outline: 2px solid var(--lavender) !important;
outline-offset: 2px !important;
}
.panel-toggle-icon {
font-size: 0.75rem;
transition: transform 0.2s ease;
margin-left: 8px;
color: var(--subtext);
}
.settings-panel.minimized .panel-toggle-icon {
transform: rotate(-90deg);
}
.settings-panel.minimized > *:not(h2) {
display: none !important;
}
.toolbar label, .toolbar label,
.settings-panel label { .settings-panel label {
display: grid; display: grid;
@@ -274,7 +607,7 @@ textarea,
button { button {
max-width: 100%; max-width: 100%;
min-width: 180px; min-width: 180px;
padding: 11px 13px; padding: 2px 2px;
border: 1px solid var(--surface-1); border: 1px solid var(--surface-1);
border-radius: 8px; border-radius: 8px;
background: var(--surface-0); background: var(--surface-0);
@@ -301,6 +634,40 @@ button:focus-visible {
max-width: 560px; max-width: 560px;
} }
.theme-options {
display: grid;
gap: 8px;
margin: 14px 0;
}
.theme-options label {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
}
.email-address-list {
display: grid;
gap: 8px;
}
.email-address-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
padding: 8px 0;
border-bottom: 1px solid var(--border);
}
.email-address-row button {
min-width: 0;
padding: 5px 9px;
font-size: 0.82rem;
}
.settings-panel textarea { .settings-panel textarea {
min-height: 110px; min-height: 110px;
resize: vertical; resize: vertical;
@@ -373,7 +740,7 @@ button:disabled {
.plugin-list, .plugin-list,
.feed { .feed {
display: grid; display: grid;
gap: 14px; gap: 8px;
} }
.plugin-row { .plugin-row {
@@ -381,7 +748,7 @@ button:disabled {
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 16px; gap: 16px;
padding: 14px 0; padding: 4px 0;
border-bottom: 1px solid var(--border); border-bottom: 1px solid var(--border);
} }
@@ -391,7 +758,7 @@ button:disabled {
.plugin-row button { .plugin-row button {
min-width: 0; min-width: 0;
padding: 8px 12px; padding: 5px 5px;
background: var(--surface-1); background: var(--surface-1);
border-color: var(--surface-2); border-color: var(--surface-2);
color: var(--text); color: var(--text);
@@ -420,11 +787,56 @@ button:disabled {
.edit-button { .edit-button {
min-width: 0; min-width: 0;
margin-top: 14px; padding: 5px 9px;
padding: 8px 12px; border-radius: 6px;
background: var(--surface-1); background: var(--surface-1);
border-color: var(--surface-2); border-color: var(--surface-2);
color: var(--text); color: var(--text);
font-size: 0.82rem;
}
.entry-actions {
display: flex;
float: right;
gap: 8px;
margin: 0 0 8px 16px;
}
.delete-button {
min-width: 0;
padding: 5px 9px;
border-radius: 6px;
border-color: rgba(243, 139, 168, 0.45);
background: transparent;
color: var(--red);
font-size: 0.82rem;
}
.mastodon-button {
clear: right;
float: right;
margin: 0 0 8px 16px;
display: inline-flex;
align-items: center;
gap: 5px;
min-width: 0;
padding: 5px 9px;
border-radius: 6px;
background: var(--surface-1);
border-color: var(--surface-2);
color: var(--text);
font-size: 0.82rem;
}
.mastodon-button.posted {
background: var(--teal);
border-color: var(--teal);
color: var(--crust);
}
.mastodon-button img {
width: 15px;
height: 15px;
} }
.edit-form { .edit-form {
@@ -435,6 +847,11 @@ button:disabled {
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
} }
.edit-form textarea {
width: 100%;
}
.edit-tags { .edit-tags {
display: grid; display: grid;
gap: 8px; gap: 8px;
@@ -474,14 +891,76 @@ button:disabled {
padding-bottom: 40px; padding-bottom: 40px;
} }
.pagination {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 4px;
max-width: 100%;
margin: 0 0 40px;
overflow-x: auto;
}
.pagination button {
min-width: 28px;
padding: 3px 7px;
background: transparent;
border: 1px solid transparent;
border-radius: 6px;
color: var(--muted);
font-size: 0.82rem;
line-height: 1.4;
cursor: pointer;
}
.pagination button:hover:not(:disabled) {
border-color: var(--border);
color: var(--text);
}
.pagination button:disabled {
opacity: 0.4;
cursor: default;
}
.pagination button.active {
background: var(--surface-1);
color: var(--text);
border-color: var(--border);
font-weight: 600;
}
.pagination .pagination-ellipsis {
padding: 3px 2px;
color: var(--muted);
font-size: 0.82rem;
opacity: 0.6;
}
.link-item { .link-item {
padding: 22px; padding: 11px;
background: rgba(49, 50, 68, 0.84); background: var(--surface-0);
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: 12px; border-radius: 12px;
box-shadow: var(--shadow); box-shadow: var(--shadow);
} }
.profile-summary summary {
color: var(--subtext);
cursor: pointer;
font-size: 0.9rem;
font-weight: 600;
}
.profile-summary[open] summary {
margin-bottom: 8px;
}
.profile-summary-content {
font-size: 0.95rem;
}
.about-content { .about-content {
display: grid; display: grid;
gap: 14px; gap: 14px;
@@ -490,7 +969,7 @@ button:disabled {
.link-item h2 { .link-item h2 {
margin: 0 0 8px; margin: 0 0 8px;
color: var(--text); color: var(--text);
font-size: 1.2rem; font-size: 1rem;
line-height: 1.25; line-height: 1.25;
} }
@@ -499,7 +978,13 @@ button:disabled {
align-items: center; align-items: center;
float: right; float: right;
gap: 12px; gap: 12px;
margin: 0 0 12px 18px; margin: 0 0 2px 8px;
}
.user-link {
display: inline-flex;
align-items: center;
gap: 12px;
} }
.avatar { .avatar {
@@ -542,22 +1027,254 @@ button:disabled {
.profile-summary p { .profile-summary p {
margin: 12px 0 0; margin: 12px 0 0;
color: var(--subtext); color: var(--subtext);
font-size: 0.95rem;
line-height: 1.65; line-height: 1.65;
} }
.meta { .meta {
margin-top: 14px; margin-left: auto;
color: var(--muted); color: var(--muted);
font-size: 0.82rem; font-size: 0.82rem;
text-align: right;
} }
.entry-tags { .entry-tags {
margin-top: 12px;
color: var(--mauve); color: var(--mauve);
font-size: 0.85rem; font-size: 0.85rem;
font-weight: 600; font-weight: 600;
} }
.entry-meta {
display: flex;
align-items: baseline;
justify-content: space-between;
clear: both;
gap: 16px;
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.hidden {
display: none;
}
.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;
}
.form-section label.tag-checkbox {
display: inline-flex;
}
.tag-checkbox input {
width: auto;
min-width: 0;
flex: 0 0 auto;
margin: 0;
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'] {
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;
}
.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;
}
.char-count {
margin: -8px 0 0;
color: var(--muted);
font-size: 0.82rem;
text-align: right;
}
.char-count.over-limit {
color: var(--red);
font-weight: 600;
}
@media (max-width: 600px) { @media (max-width: 600px) {
.container { .container {
padding: 0 14px; padding: 0 14px;
@@ -578,9 +1295,20 @@ button:disabled {
.header-row { .header-row {
align-items: center; align-items: center;
flex-wrap: wrap;
gap: 12px; gap: 12px;
} }
.header-tools {
order: 3;
flex-basis: 100%;
justify-items: stretch;
}
.header-tools .header-actions {
justify-content: flex-end;
}
.header-actions { .header-actions {
align-items: flex-end; align-items: flex-end;
} }
@@ -594,6 +1322,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;
} }
@@ -611,6 +1344,16 @@ button:disabled {
padding: 14px; padding: 14px;
} }
.entry-meta {
align-items: flex-start;
flex-wrap: wrap;
gap: 4px 12px;
}
.meta {
margin-left: auto;
}
.toolbar label, .toolbar label,
select, select,
input, input,
+49
View File
@@ -0,0 +1,49 @@
// Copyright © 2026 Olaf Kolkman
// SPDX-License-Identifier: GPL-3.0-or-later
const themePreference = 'linklog-theme';
async function loadAvailableThemes() {
const response = await fetch('/api/public/themes');
if (!response.ok) return;
const themes = await response.json();
const selected = themes.some((theme) => theme.id === localStorage.getItem(themePreference))
? localStorage.getItem(themePreference)
: themes[0]?.id;
if (selected) document.documentElement.dataset.theme = selected;
const submenuContainer = document.querySelector('#theme-submenu-container');
const themeOptions = document.querySelector('#theme-options');
const submenuTitle = document.querySelector('.submenu-title');
if (!submenuContainer || !themeOptions || !themes.length) return;
// Show the submenu container
submenuContainer.classList.remove('hidden');
// 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;
});
themeOptions.replaceChildren(...buttons);
}
loadAvailableThemes();
+14 -2
View File
@@ -13,11 +13,12 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>About</h1> <h1>About</h1>
<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,9 +57,16 @@
<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.3.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>
</body> </body>
</html> </html>
+81 -9
View File
@@ -13,11 +13,12 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>Admin</h1> <h1>Admin</h1>
<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>
@@ -39,8 +44,13 @@
<main class="container"> <main class="container">
<p id="admin-auth-notice" class="auth-notice hidden"></p> <p id="admin-auth-notice" class="auth-notice hidden"></p>
<div id="admin-controls" class="hidden"> <div id="admin-controls" class="hidden">
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Users</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Users</span>
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
</button>
</h2>
<form id="user-form"> <form id="user-form">
<label> <label>
Username Username
@@ -64,19 +74,81 @@
<div id="user-list" class="plugin-list" aria-live="polite">Loading users...</div> <div id="user-list" class="plugin-list" aria-live="polite">Loading users...</div>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Plugins</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Plugins</span>
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
</button>
</h2>
<div id="plugin-list" class="plugin-list" aria-live="polite">Loading plugins...</div> <div id="plugin-list" class="plugin-list" aria-live="polite">Loading plugins...</div>
</section> </section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Labels</h2> <h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Labels</span>
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
</button>
</h2>
<div id="admin-label-list" class="plugin-list" aria-live="polite">Loading labels...</div> <div id="admin-label-list" class="plugin-list" aria-live="polite">Loading labels...</div>
</section> </section>
<section class="link-item settings-panel minimized">
<h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>SMTP settings</span>
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
</button>
</h2>
<form id="smtp-form">
<label>
SMTP host
<input name="smtp_host" type="text" required />
</label>
<label>
SMTP port
<input name="smtp_port" type="number" min="1" max="65535" required />
</label>
<label>
SMTP username
<input name="smtp_username" type="text" autocomplete="off" />
</label>
<label>
SMTP password
<input name="smtp_password" type="password" autocomplete="new-password" />
</label>
<label>
From address
<input name="smtp_from" type="text" required />
</label>
<label class="checkbox-label">
<input name="smtp_use_tls" type="checkbox" /> Use STARTTLS
</label>
<button type="submit">Save SMTP settings</button>
<button id="smtp-test-button" type="button">Send validation email</button>
<p id="smtp-status" class="status" role="status"></p>
</form>
</section>
<section class="link-item settings-panel minimized">
<h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Available themes</span>
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
</button>
</h2>
<p>Choose the themes visitors may use.</p>
<form id="themes-form">
<div id="admin-theme-options" class="theme-options" aria-live="polite">Loading themes...</div>
<button type="submit">Save themes</button>
<p id="theme-status" class="status" role="status"></p>
</form>
</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/admin.js?v=5"></script> <script src="/static/theme.js?v=1"></script>
<script src="/static/admin.js?v=7"></script>
</body> </body>
</html> </html>
+59 -40
View File
@@ -13,12 +13,14 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<p>Public link feed</p> <p>Public link feed</p>
</div> </div>
<div class="header-actions"> <div class="header-tools">
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> <div class="header-actions">
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <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-home-link" href="/">Home</a>
<a id="auth-about-link" href="/about">About</a> <a id="auth-about-link" href="/about">About</a>
<a id="auth-login-button" href="/login">Sign in</a> <a id="auth-login-button" href="/login">Sign in</a>
@@ -29,7 +31,41 @@
<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>
</nav> <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>
<section class="toolbar">
<label>
Tag filter
<select id="tag-filter">
<option value="">All tags</option>
</select>
</label>
<label>
Sort
<select id="sort-select">
<option value="newest">Newest first</option>
<option value="oldest">Oldest first</option>
</select>
</label>
<label>
User filter
<select id="user-filter">
<option value="">All users</option>
</select>
</label>
<label>
Per page
<select id="page-size-select"></select>
</label>
<label class="search-control">
Search
<input id="search-input" type="search" placeholder="Search links" autocomplete="off" aria-label="Search links" />
</label>
</section>
</div> </div>
</div> </div>
</div> </div>
@@ -37,48 +73,31 @@
<main class="container"> <main class="container">
{% if profile %} {% if profile %}
<section class="link-item profile-summary"> <details class="link-item profile-summary">
<div class="link-header"> <summary>Profile</summary>
<div class="avatar"> <div class="profile-summary-content">
{% if profile.avatar_url %} <div class="link-header">
<img src="{{ profile.avatar_url }}" alt="{{ profile.username }} avatar" /> <div class="avatar">
{% else %} {% if profile.avatar_url %}
{{ profile.username[:1].upper() }} <img src="{{ profile.avatar_url }}" alt="{{ profile.username }} avatar" />
{% endif %} {% else %}
{{ profile.username[:1].upper() }}
{% endif %}
</div>
<div class="user-name">{{ profile.username }}</div>
</div> </div>
<div class="user-name">{{ profile.username }}</div> <p>{{ profile.bio or 'No profile information provided.' }}</p>
</div> </div>
<p>{{ profile.bio or 'No profile information provided.' }}</p> </details>
</section>
{% endif %} {% endif %}
<section class="toolbar">
<label>
Sort
<select id="sort-select">
<option value="newest">Newest first</option>
<option value="oldest">Oldest first</option>
</select>
</label>
<label>
User filter
<select id="user-filter">
<option value="">All users</option>
</select>
</label>
<label>
Tag filter
<select id="tag-filter">
<option value="">All tags</option>
</select>
</label>
</section>
<section id="feed" class="feed" aria-live="polite"></section> <section id="feed" class="feed" aria-live="polite"></section>
<nav id="pagination" class="pagination" aria-label="Feed pages"></nav>
</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/feed.js?v=7"></script> <script src="/static/theme.js?v=1"></script>
<script src="/static/feed.js?v=14"></script>
</body> </body>
</html> </html>
+8 -2
View File
@@ -13,11 +13,12 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>Labels</h1> <h1>Labels</h1>
<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,9 +49,10 @@
<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/labels.js?v=1"></script> <script src="/static/labels.js?v=1"></script>
</body> </body>
</html> </html>
+14 -4
View File
@@ -13,10 +13,11 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<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>
@@ -38,22 +43,27 @@
<section class="link-item settings-panel"> <section class="link-item settings-panel">
<form id="login-form"> <form id="login-form">
<label> <label>
Username Email address
<input id="username" name="username" type="text" autocomplete="username" required /> <input id="email" name="email" type="email" autocomplete="username" required />
</label> </label>
<label> <label>
Password Password
<input id="password" name="password" type="password" autocomplete="current-password" required /> <input id="password" name="password" type="password" autocomplete="current-password" required />
</label> </label>
<label>
One-time password (when configured)
<input id="otp" name="otp" type="text" inputmode="numeric" autocomplete="one-time-code" placeholder="123456" />
</label>
<button type="submit">Sign in</button> <button type="submit">Sign in</button>
<p id="login-status" class="status" role="status"></p> <p id="login-status" class="status" role="status"></p>
<p><small>A mistyped password sends a reset link to your verified email address.</small></p> <p><small>A mistyped password sends a reset link to your verified email address.</small></p>
</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/login.js"></script> <script src="/static/login.js"></script>
</body> </body>
</html> </html>
+110
View File
@@ -0,0 +1,110 @@
<!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>
<a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<p>New Entry</p>
</div>
<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>
<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>
<button id="refetch-title-button" class="secondary" type="button">Re-fetch Title</button>
</div>
<div id="duplicate-status" class="status hidden" aria-live="polite"></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>
<div id="character-count" class="char-count" aria-live="polite">0/500 characters</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 id="mastodon-publishing" class="form-section hidden">
<legend>Mastodon Publishing</legend>
<label>
<input id="mastodon-enabled" type="checkbox" checked />
Post to Mastodon
</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?v=9"></script>
</body>
</html>
+1
View File
@@ -19,6 +19,7 @@
</form> </form>
</section> </section>
</main> </main>
<script src="/static/theme.js?v=1"></script>
<script src="/static/reset-password.js"></script> <script src="/static/reset-password.js"></script>
</body> </body>
</html> </html>
+3 -2
View File
@@ -13,7 +13,7 @@
<div class="container"> <div class="container">
<div class="header-row"> <div class="header-row">
<div> <div>
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<h1>Configure LinkLog</h1> <h1>Configure LinkLog</h1>
<p>Create the first administrator and test email delivery.</p> <p>Create the first administrator and test email delivery.</p>
</div> </div>
@@ -42,7 +42,8 @@
</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/setup.js"></script> <script src="/static/setup.js"></script>
</body> </body>
</html> </html>
+177 -93
View File
@@ -2,101 +2,185 @@
<!-- Copyright © 2026 Olaf Kolkman --> <!-- Copyright © 2026 Olaf Kolkman -->
<!-- SPDX-License-Identifier: GPL-3.0-or-later --> <!-- SPDX-License-Identifier: GPL-3.0-or-later -->
<html lang="en"> <html lang="en">
<head>
<meta charset="utf-8" /> <head>
<title>LinkLog Profile</title> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <title>LinkLog Profile</title>
<link rel="stylesheet" href="/static/style.css" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
</head> <link rel="stylesheet" href="/static/style.css" />
<body> </head>
<header class="site-header">
<div class="container"> <body>
<div class="header-row"> <header class="site-header">
<div> <div class="container">
<img class="site-logo" src="/static/logo.svg" alt="LinkLog" /> <div class="header-row">
<h1>Profile</h1> <div>
</div> <a class="site-logo-link" href="/" aria-label="LinkLog home"><img class="site-logo" src="/static/logo.svg" alt="LinkLog" /></a>
<div class="header-actions"> <h1>Profile</h1>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button> </div>
<nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu"> <div class="header-actions">
<a id="auth-home-link" href="/">Home</a> <button id="new-entry-button" class="new-entry-button hidden" type="button"><a href="/new-entry">New entry</a></button>
<a id="auth-about-link" href="/about">About</a> <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="auth-menu">Menu</button>
<a id="auth-login-button" href="/login">Sign in</a> <nav id="auth-menu" class="auth-menu hidden" aria-label="Account menu">
<a id="auth-profile-link" class="hidden" href="/profile">Profile</a> <a id="auth-home-link" href="/">Home</a>
<a id="auth-labels-link" class="hidden" href="/labels">Labels</a> <a id="auth-about-link" href="/about">About</a>
<a id="auth-admin-link" class="hidden" href="/admin">Admin</a> <a id="auth-login-button" href="/login">Sign in</a>
<div id="auth-session" class="auth-session hidden"> <a id="auth-profile-link" class="hidden" href="/profile">Profile</a>
<a id="auth-username" class="user-name" href="/"></a> <a id="auth-labels-link" class="hidden" href="/labels">Labels</a>
</div> <a id="auth-admin-link" class="hidden" href="/admin">Admin</a>
<button id="logout-button" class="logout-button hidden" type="button">Sign out</button> <div id="auth-session" class="auth-session hidden">
</nav> <a id="auth-username" class="user-name" href="/"></a>
</div> </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> </div>
</header>
<main class="container"> <main class="container">
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Profile Settings</h2> <h2>
<form id="profile-form"> <button type="button" class="panel-toggle-btn" aria-expanded="false">
<label> <span>Profile Settings</span>
Username <span class="panel-toggle-icon" aria-hidden="true">▼</span>
<output id="username" class="readonly-value">Loading...</output> </button>
</label> </h2>
<label> <form id="profile-form">
Email <label>
<input id="email" name="email" type="email" required /> Username
</label> <output id="username" class="readonly-value">Loading...</output>
<label> </label>
Bio <label>
<textarea id="bio" name="bio" rows="4"></textarea> Email
</label> <output id="email" class="readonly-value">Loading...</output>
<label> </label>
Avatar image <label>
<input id="avatar-file" name="avatar" type="file" accept="image/png,image/jpeg,image/gif,image/webp" /> Bio
</label> <textarea id="bio" name="bio" rows="4"></textarea>
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" /> </label>
<button type="submit">Save profile</button> <label>
<p id="profile-status" class="status" role="status"></p> Avatar image
</form> <input id="avatar-file" name="avatar" type="file" accept="image/png,image/jpeg,image/gif,image/webp" />
</section> </label>
<img id="avatar-preview" class="profile-avatar-preview hidden" alt="Avatar preview" />
<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>
</form>
</section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Password</h2> <h2>
<form id="password-form"> <button type="button" class="panel-toggle-btn" aria-expanded="false">
<label> <span>Email addresses</span>
Current password <span class="panel-toggle-icon" aria-hidden="true">▼</span>
<input name="current_password" type="password" autocomplete="current-password" required /> </button>
</label> </h2>
<label> <div id="email-address-list" class="email-address-list" aria-live="polite">Loading email addresses...</div>
New password <form id="additional-email-form">
<input name="new_password" type="password" minlength="8" autocomplete="new-password" required /> <label>
</label> Additional email address
<button type="submit">Change password</button> <input name="email" type="email" required />
<p id="password-status" class="status" role="status"></p> </label>
</form> <button type="submit">Add email address</button>
</section> <p id="email-address-status" class="status" role="status"></p>
</form>
</section>
<section class="link-item settings-panel"> <section class="link-item settings-panel minimized">
<h2>Mastodon</h2> <h2>
<form id="mastodon-form"> <button type="button" class="panel-toggle-btn" aria-expanded="false">
<label> <span>Password</span>
Mastodon server <span class="panel-toggle-icon" aria-hidden="true">▼</span>
<input id="mastodon-instance" name="instance" type="text" value="mastodon.social" placeholder="mastodon.social" required /> </button>
</label> </h2>
<label> <form id="password-form">
Post prefix <label>
<input id="mastodon-post-prefix" name="post_prefix" type="text" value="From my #LinkLog: " /> Current password
</label> <input name="current_password" type="password" autocomplete="current-password" required />
<button id="mastodon-connect" type="button">Authenticate with this server</button> </label>
<button type="submit">Save Mastodon settings</button> <label>
<p id="mastodon-status" class="status" role="status"></p> New password
</form> <input name="new_password" type="password" minlength="8" autocomplete="new-password" required />
</section> </label>
</main> <label>
<footer class="site-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">git.kolkman.org/LinkLog</a></footer> Confirm new password
<script src="/static/auth-header.js?v=3"></script> <input name="new_password_confirmation" type="password" minlength="8" autocomplete="new-password" required />
<script src="/static/logout.js?v=2"></script> </label>
<script src="/static/profile.js?v=5"></script> <button type="submit">Change password</button>
</body> <p id="password-status" class="status" role="status"></p>
</html> </form>
</section>
<section class="link-item settings-panel minimized">
<h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>One-time password</span>
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
</button>
</h2>
<p>Use an authenticator app to add a second sign-in step.</p>
<div id="otp-disabled">
<button id="otp-setup" type="button">Set up one-time password</button>
<div id="otp-provisioning" class="hidden">
<p>Scan this QR code or enter the secret in your authenticator app:</p>
<code id="otp-secret"></code>
<p><a id="otp-uri" href="" target="_blank" rel="noopener noreferrer">Open authenticator link</a></p>
<label>Verification code <input id="otp-setup-code" inputmode="numeric"
autocomplete="one-time-code" /></label>
<button id="otp-enable" type="button">Enable one-time password</button>
<p>Save these recovery codes in a secure place. They are shown only once:</p>
<code id="otp-recovery-codes"></code>
</div>
</div>
<div id="otp-enabled" class="hidden">
<p>One-time password is enabled.</p>
<label>Current password <input id="otp-current-password" type="password" autocomplete="current-password" /></label>
<label>Verification code <input id="otp-disable-code" inputmode="numeric"
autocomplete="one-time-code" /></label>
<button id="otp-disable" type="button">Disable one-time password</button>
<p>Lost access to your authenticator? Use a saved recovery code.</p>
<label>Recovery code <input id="otp-recovery-code" type="text" autocomplete="one-time-code" /></label>
<button id="otp-recover" type="button">Recover and disable one-time password</button>
</div>
<p id="otp-status" class="status" role="status"></p>
</section>
<section class="link-item settings-panel minimized">
<h2>
<button type="button" class="panel-toggle-btn" aria-expanded="false">
<span>Mastodon</span>
<span class="panel-toggle-icon" aria-hidden="true">▼</span>
</button>
</h2>
<form id="mastodon-form">
<label>
Mastodon server
<input id="mastodon-instance" name="instance" type="text" value="mastodon.social"
placeholder="mastodon.social" required />
</label>
<button id="mastodon-connect" type="button">Authenticate with this server</button>
<label>
Post prefix
<input id="mastodon-post-prefix" name="post_prefix" type="text" value="From my #LinkLog: " />
</label>
<button type="submit">Save Mastodon settings</button>
<p id="mastodon-status" class="status" role="status"></p>
</form>
</section>
</main>
<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/logout.js?v=2"></script>
<script src="/static/theme.js?v=1"></script>
<script src="/static/profile.js?v=6"></script>
</body>
</html>
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"version": "0.1.0" "version": "0.3.0"
} }
+95
View File
@@ -0,0 +1,95 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from pathlib import Path
from urllib.request import urlopen
FONT_SOURCES = {
'Asset-Regular.ttf': 'https://fonts.gstatic.com/s/asset/v30/SLXGc1na-mM4cWIm.ttf',
'DMSans-Regular.ttf': 'https://fonts.gstatic.com/s/dmsans/v17/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwAopxhTg.ttf',
'DMSans-Medium.ttf': 'https://fonts.gstatic.com/s/dmsans/v17/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwAkJxhTg.ttf',
'DMSans-SemiBold.ttf': 'https://fonts.gstatic.com/s/dmsans/v17/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwAfJthTg.ttf',
'DMSans-Bold.ttf': 'https://fonts.gstatic.com/s/dmsans/v17/rP2tp2ywxg089UriI5-g4vlH9VoD8CmcqZG40F9JadbnoEwARZthTg.ttf',
'SpaceGrotesk-Medium.ttf': 'https://fonts.gstatic.com/s/spacegrotesk/v22/V8mQoQDjQSkFtoMM3T6r8E7mF71Q-gOoraIAEj7aUUsj.ttf',
'SpaceGrotesk-SemiBold.ttf': 'https://fonts.gstatic.com/s/spacegrotesk/v22/V8mQoQDjQSkFtoMM3T6r8E7mF71Q-gOoraIAEj42Vksj.ttf',
'SpaceGrotesk-Bold.ttf': 'https://fonts.gstatic.com/s/spacegrotesk/v22/V8mQoQDjQSkFtoMM3T6r8E7mF71Q-gOoraIAEj4PVksj.ttf',
}
FONT_CSS = """@font-face {
font-family: 'Asset';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('Asset-Regular.ttf') format('truetype');
}
@font-face {
font-family: 'DM Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('DMSans-Regular.ttf') format('truetype');
}
@font-face {
font-family: 'DM Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url('DMSans-Medium.ttf') format('truetype');
}
@font-face {
font-family: 'DM Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url('DMSans-SemiBold.ttf') format('truetype');
}
@font-face {
font-family: 'DM Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('DMSans-Bold.ttf') format('truetype');
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url('SpaceGrotesk-Medium.ttf') format('truetype');
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url('SpaceGrotesk-SemiBold.ttf') format('truetype');
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('SpaceGrotesk-Bold.ttf') format('truetype');
}
"""
def main() -> None:
target_dir = Path('frontend/static/fonts')
target_dir.mkdir(parents=True, exist_ok=True)
for filename, url in FONT_SOURCES.items():
with urlopen(url, timeout=30) as response:
(target_dir / filename).write_bytes(response.read())
(target_dir / 'fonts.css').write_text(FONT_CSS, encoding='utf-8')
if __name__ == '__main__':
main()
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Generate Firefox update metadata from LinkLog signed XPI artifacts."""
import hashlib
import json
import re
import sys
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SIGNED_DIR = ROOT / 'XPI' / 'signed'
MANIFEST_PATH = ROOT / 'webextension' / 'manifest.json'
UPDATES_PATH = ROOT / 'webextension' / 'updates.json'
ABOUT_TEMPLATE_PATH = ROOT / 'frontend' / 'templates' / 'about.html'
RAW_BASE_URL = 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main'
XPI_NAME_RE = re.compile(r'LinkLog-(\d+\.\d+\.\d+)\.xpi')
ABOUT_XPI_URL_RE = re.compile(rf'{re.escape(RAW_BASE_URL)}/XPI/signed/LinkLog-\d+\.\d+\.\d+\.xpi')
def fail(message: str) -> None:
raise SystemExit(f'update metadata generation failed: {message}')
def version_key(version: str) -> tuple[int, int, int]:
return tuple(int(part) for part in version.split('.'))
def read_packaged_manifest(xpi_path: Path) -> dict:
try:
with zipfile.ZipFile(xpi_path) as archive:
if archive.testzip() is not None:
fail(f'{xpi_path.relative_to(ROOT)} contains a corrupt member')
return json.loads(archive.read('manifest.json'))
except (OSError, KeyError, json.JSONDecodeError, zipfile.BadZipFile) as error:
fail(f'could not read {xpi_path.relative_to(ROOT)}: {error}')
def sha256_digest(xpi_path: Path) -> str:
digest = hashlib.sha256()
with xpi_path.open('rb') as xpi_file:
for block in iter(lambda: xpi_file.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def update_about_plugin_link(xpi_path: Path) -> None:
about_template = ABOUT_TEMPLATE_PATH.read_text()
latest_xpi_url = f'{RAW_BASE_URL}/{xpi_path.relative_to(ROOT).as_posix()}'
updated_template, replacements = ABOUT_XPI_URL_RE.subn(latest_xpi_url, about_template)
if replacements != 1:
fail(f'expected one signed XPI link in {ABOUT_TEMPLATE_PATH.relative_to(ROOT)}; found {replacements}')
ABOUT_TEMPLATE_PATH.write_text(updated_template)
def main() -> None:
source_manifest = json.loads(MANIFEST_PATH.read_text())
addon_id = source_manifest.get('browser_specific_settings', {}).get('gecko', {}).get('id')
if not addon_id:
fail('webextension/manifest.json is missing browser_specific_settings.gecko.id')
releases = []
for xpi_path in SIGNED_DIR.glob('LinkLog-*.xpi'):
match = XPI_NAME_RE.fullmatch(xpi_path.name)
if not match:
continue
version = match.group(1)
manifest = read_packaged_manifest(xpi_path)
if manifest.get('version') != version:
fail(f'{xpi_path.relative_to(ROOT)} manifest version does not match its filename')
gecko = manifest.get('browser_specific_settings', {}).get('gecko', {})
if gecko.get('id') != addon_id:
fail(f'{xpi_path.relative_to(ROOT)} add-on id does not match webextension/manifest.json')
strict_min_version = gecko.get('strict_min_version')
if not strict_min_version:
fail(f'{xpi_path.relative_to(ROOT)} is missing browser_specific_settings.gecko.strict_min_version')
releases.append((version, xpi_path, strict_min_version, sha256_digest(xpi_path)))
if not releases:
fail(f'no signed LinkLog release artifacts found in {SIGNED_DIR.relative_to(ROOT)}')
releases.sort(key=lambda release: version_key(release[0]), reverse=True)
updates = [
{
'version': version,
'update_link': f'{RAW_BASE_URL}/{xpi_path.relative_to(ROOT).as_posix()}',
'update_hash': f'sha256:{digest}',
'applications': {
'gecko': {
'strict_min_version': strict_min_version,
},
},
}
for version, xpi_path, strict_min_version, digest in releases
]
UPDATES_PATH.write_text(json.dumps({'addons': {addon_id: {'updates': updates}}}, indent=2) + '\n')
update_about_plugin_link(releases[0][1])
print(f'updated {UPDATES_PATH.relative_to(ROOT)} with {len(updates)} signed release(s)')
if __name__ == '__main__':
main()
+112 -36
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Validate the version and checked-in artifacts for a LinkLog release.""" """Validate the version and checked-in artifacts for a LinkLog release."""
import hashlib
import json import json
import re import re
import sys import sys
@@ -9,61 +10,136 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
MANIFEST_PATH = ROOT / 'webextension' / 'manifest.json' VERSION_FILE = ROOT / 'frontend' / 'version.json'
FRONTEND_VERSION_PATH = ROOT / 'frontend' / 'version.json'
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'
UPDATES_PATH = ROOT / 'webextension' / 'updates.json'
ABOUT_TEMPLATE_PATH = ROOT / 'frontend' / 'templates' / 'about.html'
RAW_BASE_URL = 'https://git.kolkman.org/olaf/Link-Log/raw/branch/main'
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 sha256_digest(xpi_path: Path) -> str:
digest = hashlib.sha256()
with xpi_path.open('rb') as xpi_file:
for block in iter(lambda: xpi_file.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def validate_self_update(source_manifest: dict, extension_version: str, xpi_path: Path) -> None:
gecko_settings = source_manifest.get('browser_specific_settings', {}).get('gecko', {})
addon_id = gecko_settings.get('id')
strict_min_version = gecko_settings.get('strict_min_version')
if not addon_id:
fail('webextension/manifest.json is missing browser_specific_settings.gecko.id')
updates_data = json.loads(UPDATES_PATH.read_text())
addon_entry = updates_data.get('addons', {}).get(addon_id)
if not addon_entry:
fail(f'{UPDATES_PATH.relative_to(ROOT)} has no entry for add-on id {addon_id!r}')
entry = next((u for u in addon_entry.get('updates', []) if u.get('version') == extension_version), None)
if entry is None:
fail(
f'{UPDATES_PATH.relative_to(ROOT)} has no update entry for version {extension_version!r}; '
'add one alongside the signed XPI so the self-update mechanism can find it'
)
expected_link = f'{RAW_BASE_URL}/{xpi_path.relative_to(ROOT).as_posix()}'
if entry.get('update_link') != expected_link:
fail(
f'{UPDATES_PATH.relative_to(ROOT)} update_link {entry.get("update_link")!r} does not match '
f'the expected raw signed XPI URL {expected_link!r}'
)
expected_hash = f'sha256:{sha256_digest(xpi_path)}'
if entry.get('update_hash') != expected_hash:
fail(
f'{UPDATES_PATH.relative_to(ROOT)} update_hash {entry.get("update_hash")!r} does not match '
f'the SHA-256 hash of {xpi_path.relative_to(ROOT)}'
)
entry_min_version = entry.get('applications', {}).get('gecko', {}).get('strict_min_version')
if entry_min_version != strict_min_version:
fail(
f'{UPDATES_PATH.relative_to(ROOT)} applications.gecko.strict_min_version {entry_min_version!r} '
f'does not match webextension/manifest.json strict_min_version {strict_min_version!r}'
)
def validate_about_plugin_link(xpi_path: Path) -> None:
expected_link = f'{RAW_BASE_URL}/{xpi_path.relative_to(ROOT).as_posix()}'
if expected_link not in ABOUT_TEMPLATE_PATH.read_text():
fail(
f'{ABOUT_TEMPLATE_PATH.relative_to(ROOT)} does not link to the latest signed XPI '
f'{xpi_path.relative_to(ROOT)}'
)
def main() -> None: def main() -> None:
manifest = json.loads(MANIFEST_PATH.read_text()) version_data = json.loads(VERSION_FILE.read_text())
extension_version = manifest.get('version') backend_version = version_data.get('version')
if not isinstance(extension_version, str) or not re.fullmatch(r'\d+\.\d+\.\d+', extension_version): if not backend_version:
fail('webextension/manifest.json has no valid three-part version') fail(f'version could not be found in {VERSION_FILE.relative_to(ROOT)}')
if not VERSION_RE.fullmatch(backend_version):
fail(f'backend version {backend_version} is not a valid three-part version')
frontend_version = json.loads(FRONTEND_VERSION_PATH.read_text()).get('version') extension_version, xpi_path = find_latest_signed_xpi()
if frontend_version != extension_version: source_manifest = json.loads(MANIFEST_PATH.read_text())
fail(f'frontend version {frontend_version} does not match extension version {extension_version}') if source_manifest.get('version') != extension_version:
fail(
gecko_settings = manifest.get('browser_specific_settings', {}).get('gecko', {}) f'webextension/manifest.json version {source_manifest.get("version")!r} does not match '
data_permissions = gecko_settings.get('data_collection_permissions') f'the latest signed XPI version {extension_version!r}'
if data_permissions != {'required': ['websiteActivity'], 'optional': []}: )
fail('Firefox data_collection_permissions must require websiteActivity and have no optional categories')
settings = SETTINGS_PATH.read_text()
match = re.search(r"version: str = os\.getenv\('LINKLOG_VERSION', '([^']+)'\)", settings)
if not match:
fail('backend version default could not be found')
backend_version = match.group(1)
if backend_version != extension_version:
fail(f'backend version {backend_version} does not match extension version {extension_version}')
xpi_path = SIGNED_DIR / f'LinkLog-{extension_version}.xpi'
if not xpi_path.is_file():
fail(f'missing manually signed artifact: {xpi_path.relative_to(ROOT)}')
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()) validate_self_update(source_manifest, extension_version, xpi_path)
addon_id = gecko_settings['id'] validate_about_plugin_link(xpi_path)
update_entries = updates.get('addons', {}).get(addon_id, {}).get('updates', [])
if not any(entry.get('version') == extension_version for entry in update_entries):
fail(f'webextension/updates.json has no update entry for {extension_version}')
print(f'validated LinkLog release {frontend_version}') signed_xpi = xpi_path.relative_to(ROOT)
print(f'xpi={xpi_path.relative_to(ROOT)}') if len(sys.argv) == 3 and sys.argv[1] == '--github-output':
with Path(sys.argv[2]).open('a') as output:
print(f'backend_version={backend_version}', file=output)
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 backend release {backend_version}')
print(f'plugin_version={extension_version}')
print(f'signed_xpi={signed_xpi}')
if __name__ == '__main__': if __name__ == '__main__':
+6
View File
@@ -20,6 +20,12 @@ REQUIRED_FILES = {
'popup.css', 'popup.css',
'popup.html', 'popup.html',
'popup.js', 'popup.js',
'l10n.js',
'_locales/en-US/messages.json',
'_locales/es/messages.json',
'_locales/de/messages.json',
'_locales/fr/messages.json',
'_locales/nl/messages.json',
} }
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
"""One-off script: seed the running LinkLog API with random users and links.
Uses the HTTP API exclusively for user/link creation. The only direct
database access is flipping `email_verified` for freshly created accounts,
since there is no mailbox available in this environment to click the real
verification link that the API would otherwise send.
"""
import random
import string
import subprocess
import sys
from datetime import datetime, timedelta, timezone
import requests
BASE_URL = 'http://localhost:5469'
ADMIN_EMAIL = 'bootstrap_admin@example.invalid'
ADMIN_PASSWORD = 'Bootstrap-Admin-Pass1!'
CONTAINER_NAME = 'testlog-app'
NUM_USERS = 5
LINKS_PER_USER = 500
FIRST_NAMES = ['ava', 'liam', 'noah', 'emma', 'olivia', 'mia', 'ethan', 'sofia', 'lucas', 'zoe']
SITES = [
('https://news.ycombinator.com', 'Hacker News'),
('https://www.theguardian.com', 'The Guardian'),
('https://arstechnica.com', 'Ars Technica'),
('https://www.wired.com', 'Wired'),
('https://github.com', 'GitHub'),
('https://www.nature.com', 'Nature'),
('https://www.bbc.com', 'BBC'),
('https://techcrunch.com', 'TechCrunch'),
('https://www.nytimes.com', 'NY Times'),
('https://www.reddit.com', 'Reddit'),
('https://stackoverflow.com', 'Stack Overflow'),
('https://www.smithsonianmag.com', 'Smithsonian'),
('https://www.economist.com', 'The Economist'),
('https://www.nationalgeographic.com', 'Nat Geo'),
('https://www.theverge.com', 'The Verge'),
]
PATH_WORDS = ['article', 'story', 'post', 'thread', 'blog', 'notes', 'guide', 'review', 'update', 'deep-dive']
HASHTAG_POOL = ['#tech', '#science', '#news', '#opensource', '#ai', '#climate', '#music',
'#photography', '#food', '#travel', '#fediverse', '#security', '#culture', '#space']
COMMENT_TEMPLATES = [
"Interesting take on {topic}.",
"Worth a read if you're into {topic}.",
"Not sure I agree with this on {topic}, but good points.",
"Bookmarking this for later - {topic}.",
"Great deep dive into {topic}.",
"", # some links have no comment
]
session = requests.Session()
def rand_suffix(n=6):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=n))
def create_bootstrap_admin_if_needed():
resp = session.post(f'{BASE_URL}/api/auth/login', json={'email': ADMIN_EMAIL, 'password': ADMIN_PASSWORD})
if resp.status_code == 200:
return resp.json()['access_token']
raise RuntimeError(f'Bootstrap admin login failed: {resp.status_code} {resp.text}')
def mark_email_verified(user_id: str):
code = (
"from backend.app.database import get_connection\n"
f"with get_connection() as conn:\n"
f" conn.execute('UPDATE users SET email_verified = 1 WHERE id = ?', ('{user_id}',))\n"
" conn.commit()\n"
)
subprocess.run(
['docker', 'exec', '-w', '/app', CONTAINER_NAME, 'python3', '-c', code],
check=True, capture_output=True, text=True,
)
def create_user(admin_token: str, index: int) -> dict:
name = f'{random.choice(FIRST_NAMES)}{index}_{rand_suffix()}'
email = f'{name}@example-seed.invalid'
password = f'Passw0rd-{rand_suffix(8)}!'
resp = session.post(
f'{BASE_URL}/api/admin/users',
headers={'Authorization': f'Bearer {admin_token}'},
json={'username': name, 'email': email, 'password': password, 'is_admin': False},
)
if resp.status_code == 201:
user = resp.json()
elif resp.status_code == 503:
# User row was created but the verification email failed to send (no SMTP egress here).
list_resp = session.get(f'{BASE_URL}/api/admin/users', headers={'Authorization': f'Bearer {admin_token}'})
list_resp.raise_for_status()
user = next(u for u in list_resp.json() if u['username'] == name)
else:
raise RuntimeError(f'Failed to create user {name}: {resp.status_code} {resp.text}')
mark_email_verified(user['id'])
return {'id': user['id'], 'username': name, 'email': email, 'password': password}
def login_user(email: str, password: str) -> str:
resp = session.post(f'{BASE_URL}/api/auth/login', json={'email': email, 'password': password})
resp.raise_for_status()
return resp.json()['access_token']
def random_link_payload():
base_url, site_name = random.choice(SITES)
url = f'{base_url}/{random.choice(PATH_WORDS)}/{rand_suffix(8)}'
title = f'{site_name}: {random.choice(PATH_WORDS).replace("-", " ").title()} #{random.randint(1000, 9999)}'
topic = random.choice(HASHTAG_POOL).lstrip('#')
comment = random.choice(COMMENT_TEMPLATES).format(topic=topic)
tags = random.sample(HASHTAG_POOL, k=random.randint(1, 4))
timestamp = (datetime.now(timezone.utc) - timedelta(days=random.randint(0, 730),
seconds=random.randint(0, 86400))).isoformat()
return {
'title': title,
'url': url,
'comment': comment,
'tags': tags,
'timestamp': timestamp,
'post_to_mastodon': False,
}
def create_links_for_user(token: str, username: str, count: int):
headers = {'Authorization': f'Bearer {token}'}
created = 0
for i in range(count):
payload = random_link_payload()
resp = session.post(f'{BASE_URL}/api/links', headers=headers, json=payload)
if resp.status_code == 401:
# access token expired mid-run; caller handles refresh via re-login
raise PermissionError('token_expired')
if resp.status_code not in (200, 201):
print(f' ! link {i} failed for {username}: {resp.status_code} {resp.text[:200]}', file=sys.stderr)
continue
created += 1
if created % 100 == 0:
print(f' {username}: {created}/{count} links created')
return created
def main():
print('Logging in as bootstrap admin...')
admin_token = create_bootstrap_admin_if_needed()
users = []
print(f'Creating {NUM_USERS} users...')
for i in range(1, NUM_USERS + 1):
user = create_user(admin_token, i)
users.append(user)
print(f' created user: {user["username"]} <{user["email"]}>')
for user in users:
print(f'Seeding {LINKS_PER_USER} links for {user["username"]}...')
token = login_user(user['email'], user['password'])
try:
total = create_links_for_user(token, user['username'], LINKS_PER_USER)
except PermissionError:
print(f' token expired, re-logging in for {user["username"]}')
token = login_user(user['email'], user['password'])
total = create_links_for_user(token, user['username'], LINKS_PER_USER)
print(f' done: {total}/{LINKS_PER_USER} links created for {user["username"]}')
print('\nSummary:')
for user in users:
print(f' {user["username"]} / {user["email"]} / password: {user["password"]}')
if __name__ == '__main__':
main()
+59
View File
@@ -0,0 +1,59 @@
{
"extensionName": {"message": "LinkLog"},
"extensionDescription": {"message": "Webseiten-Links erfassen und an LinkLog senden."},
"settingsTitle": {"message": "LinkLog-Einstellungen"},
"titleLabel": {"message": "Titel"},
"urlLabel": {"message": "URL"},
"commentLabel": {"message": "Kommentar"},
"commentPlaceholder": {"message": "Dein Kommentar"},
"tagsLabel": {"message": "Tags"},
"loadingTags": {"message": "Tags werden geladen..."},
"newTagsPlaceholder": {"message": "#neuer-tag, #anderer-tag"},
"saveLink": {"message": "Link speichern"},
"settings": {"message": "Einstellungen"},
"authRequired": {"message": "Melde dich an, um LinkLog zu verwenden."},
"openSettings": {"message": "Einstellungen öffnen"},
"signOut": {"message": "Abmelden"},
"backendUrlLabel": {"message": "Backend-URL"},
"emailLabel": {"message": "E-Mail"},
"emailPlaceholder": {"message": "alice@example.com"},
"usernameLabel": {"message": "Benutzername"},
"usernamePlaceholder": {"message": "alice"},
"passwordLabel": {"message": "Passwort"},
"otpLabel": {"message": "Einmalpasswort (falls konfiguriert)"},
"otpPlaceholder": {"message": "123456"},
"saveAndLogIn": {"message": "Speichern und anmelden"},
"thisPlugin": {"message": "Dieses Add-on"},
"pluginDescription": {"message": "Dieses Add-on protokolliert Links auf einem LinkLog-Server, der sie auf einer Website und je nach Konfiguration der Add-ons möglicherweise auch in einem Fediverse-Dienst oder an anderen Orten veröffentlicht."},
"accountRequirement": {"message": "Nutzer dieses Add-ons benötigen ein Konto auf einem LinkLog-Server"},
"privacy": {"message": "Datenschutz"},
"privacyDescription": {"message": "Dieses Add-on respektiert deine Privatsphäre und erhebt keine personenbezogenen Daten über das hinaus, was zum Protokollieren von Links auf deinem LinkLog-Server erforderlich ist."},
"storedData": {"message": "Die URL, nach einem bestmöglichen Versuch, Tracking-Parameter zu entfernen, der Seitentitel, ein möglicher Kommentar und der Besuchszeitpunkt werden auf dem Server gespeichert und zusammen mit dem dort registrierten Nutzerprofil veröffentlicht."},
"backendHeading": {"message": "LinkLog-Backend"},
"backendDescription": {"message": "Die Backend-URL gehört zu einer selbst gehosteten LinkLog-Anwendung. Ihr"},
"backendSource": {"message": "Quellcode ist im Repository verfügbar."},
"copyright": {"message": "Copyright © 2026 Olaf Kolkman"},
"repository": {"message": "Repository"},
"signInToSelectTags": {"message": "Melde dich an, um vorhandene Tags auszuwählen."},
"loadTagsFailed": {"message": "Vorhandene Tags konnten nicht geladen werden."},
"submitting": {"message": "Wird gesendet..."},
"configureAndLogIn": {"message": "Konfiguriere die Backend-URL und melde dich zuerst an."},
"sessionExpired": {"message": "Sitzung abgelaufen. Authentifiziere dich in den Einstellungen erneut."},
"submissionFailed": {"message": "Senden fehlgeschlagen"},
"linkSaved": {"message": "Link auf $URL$ gespeichert.", "placeholders": {"url": {"content": "$1"}}},
"linkAlreadyExists": {"message": "Dieser Link existiert bereits. Kommentar und Tags wurden aktualisiert und die Veröffentlichung erneut ausgelöst."},
"duplicateLinkSameUrl": {"message": "Dieser Link existiert bereits.\nDu kannst den Eintrag trotzdem speichern; dabei werden Kommentar und Tags des bestehenden Eintrags aktualisiert."},
"duplicateLinkDifferentUrl": {"message": "Dieser Link existiert bereits. Der gespeicherte Link hat jedoch eine andere URL (fehlende oder andere Parameter).\nWenn du den Eintrag speicherst, riskierst du einen doppelten Eintrag."},
"refetchTitle": {"message": "Titel erneut abrufen"},
"titleFetchFailed": {"message": "Titel konnte nicht abgerufen werden"},
"publishingErrors": {"message": "Fehler bei der Veröffentlichung: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
"submissionFailedConnection": {"message": "Senden fehlgeschlagen. Überprüfe die Verbindung zum Backend."},
"loggedInAt": {"message": "$USERNAME$ ist bei $BACKEND$ angemeldet", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
"fillAllFields": {"message": "Fülle alle Felder aus"},
"loginFailed": {"message": "Anmeldung fehlgeschlagen"},
"loggedInSuccessfully": {"message": "Erfolgreich angemeldet"},
"unableToLogIn": {"message": "Anmeldung nicht möglich. Überprüfe Backend-URL und Zugangsdaten."},
"signedOut": {"message": "Abgemeldet"},
"characterCount": {"message": "$USED$/$LIMIT$ Zeichen", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}}},
"characterCountOverLimit": {"message": "$USED$/$LIMIT$ Zeichen - überschreitet das Mastodon-Beitragslimit um $OVER$", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}, "over": {"content": "$3"}}}
}
+210
View File
@@ -0,0 +1,210 @@
{
"extensionName": {
"message": "LinkLog"
},
"extensionDescription": {
"message": "Capture and submit page links to LinkLog."
},
"settingsTitle": {
"message": "LinkLog Settings"
},
"titleLabel": {
"message": "Title"
},
"urlLabel": {
"message": "URL"
},
"commentLabel": {
"message": "Comment"
},
"commentPlaceholder": {
"message": "Your comment"
},
"tagsLabel": {
"message": "Tags"
},
"loadingTags": {
"message": "Loading tags..."
},
"newTagsPlaceholder": {
"message": "#new-tag, #another-tag"
},
"saveLink": {
"message": "Save link"
},
"settings": {
"message": "Settings"
},
"authRequired": {
"message": "Please sign in to use LinkLog."
},
"openSettings": {
"message": "Open settings"
},
"signOut": {
"message": "Sign out"
},
"backendUrlLabel": {
"message": "Backend URL"
},
"emailLabel": {
"message": "Email"
},
"emailPlaceholder": {
"message": "alice@example.com"
},
"usernameLabel": {
"message": "Username"
},
"usernamePlaceholder": {
"message": "alice"
},
"passwordLabel": {
"message": "Password"
},
"otpLabel": {
"message": "One-time password (when configured)"
},
"otpPlaceholder": {
"message": "123456"
},
"saveAndLogIn": {
"message": "Save and log in"
},
"thisPlugin": {
"message": "This Plugin"
},
"pluginDescription": {
"message": "This plugin will log links to a backend LinkLog server which will publish them on a website and potentially as an entry on a fediverse service or other locations, depending on the plugins configured."
},
"accountRequirement": {
"message": "Users of this plugin will need an account on a LinkLog server"
},
"privacy": {
"message": "Privacy"
},
"privacyDescription": {
"message": "This plugin respects your privacy and does not collect any personal data beyond what is necessary to log links to your LinkLog server."
},
"storedData": {
"message": "The URL - after a best effort try to remove tracking parameters -, the title of the webpage, a possible comment, and a timestamp of visit will be stored on the backend server, and will be made public in combination with the user's profile as registered on the backend server."
},
"backendHeading": {
"message": "LinkLog Backend"
},
"backendDescription": {
"message": "The backend URL is a selfhosted linklog application. See its"
},
"backendSource": {
"message": "for its source."
},
"copyright": {
"message": "Copyright © 2026 Olaf Kolkman"
},
"repository": {
"message": "Repository"
},
"signInToSelectTags": {
"message": "Sign in to select existing tags."
},
"loadTagsFailed": {
"message": "Could not load existing tags."
},
"submitting": {
"message": "Submitting..."
},
"configureAndLogIn": {
"message": "Please configure the backend URL and log in first."
},
"sessionExpired": {
"message": "Session expired. Re-authenticate in settings."
},
"submissionFailed": {
"message": "Submission failed"
},
"linkSaved": {
"message": "Link saved to $URL$.",
"placeholders": {
"url": {
"content": "$1"
}
}
},
"linkAlreadyExists": {
"message": "This link already exists. Comment and tags were updated, and publishing was retriggered."
},
"duplicateLinkSameUrl": {
"message": "This link already exists.\nYou can still save the entry, which will update the existing entry's comment and or tags."
},
"duplicateLinkDifferentUrl": {
"message": "This link already exists. But, the stored link has a different URL (missing or different parameters).\nWhen you save the entry you risk a duplicate entry."
},
"refetchTitle": {
"message": "Re-fetch title"
},
"titleFetchFailed": {
"message": "Could not fetch title"
},
"publishingErrors": {
"message": "Publishing errors: $ERRORS$",
"placeholders": {
"errors": {
"content": "$1"
}
}
},
"submissionFailedConnection": {
"message": "Submission failed. Check your backend connection."
},
"loggedInAt": {
"message": "$USERNAME$ logged in at $BACKEND$",
"placeholders": {
"username": {
"content": "$1"
},
"backend": {
"content": "$2"
}
}
},
"fillAllFields": {
"message": "Please fill in all fields"
},
"loginFailed": {
"message": "Login failed"
},
"loggedInSuccessfully": {
"message": "Logged in successfully"
},
"unableToLogIn": {
"message": "Unable to log in. Check backend URL and credentials."
},
"signedOut": {
"message": "Signed out"
},
"characterCount": {
"message": "$USED$/$LIMIT$ characters",
"placeholders": {
"used": {
"content": "$1"
},
"limit": {
"content": "$2"
}
}
},
"characterCountOverLimit": {
"message": "$USED$/$LIMIT$ characters - exceeds the Mastodon post limit by $OVER$",
"placeholders": {
"used": {
"content": "$1"
},
"limit": {
"content": "$2"
},
"over": {
"content": "$3"
}
}
}
}
+59
View File
@@ -0,0 +1,59 @@
{
"extensionName": {"message": "LinkLog"},
"extensionDescription": {"message": "Captura y envía enlaces de páginas a LinkLog."},
"settingsTitle": {"message": "Configuración de LinkLog"},
"titleLabel": {"message": "Título"},
"urlLabel": {"message": "URL"},
"commentLabel": {"message": "Comentario"},
"commentPlaceholder": {"message": "Tu comentario"},
"tagsLabel": {"message": "Etiquetas"},
"loadingTags": {"message": "Cargando etiquetas..."},
"newTagsPlaceholder": {"message": "#nueva-etiqueta, #otra-etiqueta"},
"saveLink": {"message": "Guardar enlace"},
"settings": {"message": "Configuración"},
"authRequired": {"message": "Inicia sesión para usar LinkLog."},
"openSettings": {"message": "Abrir configuración"},
"signOut": {"message": "Cerrar sesión"},
"backendUrlLabel": {"message": "URL del servidor"},
"emailLabel": {"message": "Correo electrónico"},
"emailPlaceholder": {"message": "alice@example.com"},
"usernameLabel": {"message": "Nombre de usuario"},
"usernamePlaceholder": {"message": "alice"},
"passwordLabel": {"message": "Contraseña"},
"otpLabel": {"message": "Contraseña de un solo uso (cuando está configurada)"},
"otpPlaceholder": {"message": "123456"},
"saveAndLogIn": {"message": "Guardar e iniciar sesión"},
"thisPlugin": {"message": "Este complemento"},
"pluginDescription": {"message": "Este complemento registra enlaces en un servidor LinkLog, que los publicará en un sitio web y posiblemente en un servicio fediverso u otros destinos, según los complementos configurados."},
"accountRequirement": {"message": "Los usuarios de este complemento necesitan una cuenta en un servidor LinkLog"},
"privacy": {"message": "Privacidad"},
"privacyDescription": {"message": "Este complemento respeta tu privacidad y no recopila datos personales más allá de lo necesario para registrar enlaces en tu servidor LinkLog."},
"storedData": {"message": "La URL, tras intentar eliminar los parámetros de seguimiento, el título de la página, un posible comentario y la hora de visita se guardarán en el servidor y se harán públicos junto con el perfil del usuario registrado en el servidor."},
"backendHeading": {"message": "Servidor LinkLog"},
"backendDescription": {"message": "La URL del servidor es una aplicación LinkLog autoalojada. Consulta su"},
"backendSource": {"message": "para ver el código fuente."},
"copyright": {"message": "Copyright © 2026 Olaf Kolkman"},
"repository": {"message": "Repositorio"},
"signInToSelectTags": {"message": "Inicia sesión para seleccionar etiquetas existentes."},
"loadTagsFailed": {"message": "No se pudieron cargar las etiquetas existentes."},
"submitting": {"message": "Enviando..."},
"configureAndLogIn": {"message": "Configura la URL del servidor e inicia sesión primero."},
"sessionExpired": {"message": "La sesión ha caducado. Vuelve a autenticarte en la configuración."},
"submissionFailed": {"message": "Error al enviar"},
"linkSaved": {"message": "Enlace guardado en $URL$.", "placeholders": {"url": {"content": "$1"}}},
"linkAlreadyExists": {"message": "Este enlace ya existe. Se actualizaron el comentario y las etiquetas, y se volvió a activar la publicación."},
"duplicateLinkSameUrl": {"message": "Este enlace ya existe.\nAún puedes guardar la entrada, lo que actualizará el comentario y las etiquetas de la entrada existente."},
"duplicateLinkDifferentUrl": {"message": "Este enlace ya existe. Pero el enlace guardado tiene una URL diferente (parámetros ausentes o distintos).\nSi guardas la entrada, corres el riesgo de crear una entrada duplicada."},
"refetchTitle": {"message": "Volver a obtener el título"},
"titleFetchFailed": {"message": "No se pudo obtener el título"},
"publishingErrors": {"message": "Errores de publicación: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
"submissionFailedConnection": {"message": "Error al enviar. Comprueba la conexión con el servidor."},
"loggedInAt": {"message": "$USERNAME$ ha iniciado sesión en $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
"fillAllFields": {"message": "Rellena todos los campos"},
"loginFailed": {"message": "Error de inicio de sesión"},
"loggedInSuccessfully": {"message": "Sesión iniciada correctamente"},
"unableToLogIn": {"message": "No se pudo iniciar sesión. Comprueba la URL y las credenciales."},
"signedOut": {"message": "Sesión cerrada"},
"characterCount": {"message": "$USED$/$LIMIT$ caracteres", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}}},
"characterCountOverLimit": {"message": "$USED$/$LIMIT$ caracteres: supera el límite de publicación de Mastodon en $OVER$", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}, "over": {"content": "$3"}}}
}
+59
View File
@@ -0,0 +1,59 @@
{
"extensionName": {"message": "LinkLog"},
"extensionDescription": {"message": "Capturer et envoyer des liens de pages à LinkLog."},
"settingsTitle": {"message": "Paramètres de LinkLog"},
"titleLabel": {"message": "Titre"},
"urlLabel": {"message": "URL"},
"commentLabel": {"message": "Commentaire"},
"commentPlaceholder": {"message": "Votre commentaire"},
"tagsLabel": {"message": "Étiquettes"},
"loadingTags": {"message": "Chargement des étiquettes..."},
"newTagsPlaceholder": {"message": "#nouvelle-étiquette, #autre-étiquette"},
"saveLink": {"message": "Enregistrer le lien"},
"settings": {"message": "Paramètres"},
"authRequired": {"message": "Connectez-vous pour utiliser LinkLog."},
"openSettings": {"message": "Ouvrir les paramètres"},
"signOut": {"message": "Se déconnecter"},
"backendUrlLabel": {"message": "URL du serveur"},
"emailLabel": {"message": "E-mail"},
"emailPlaceholder": {"message": "alice@example.com"},
"usernameLabel": {"message": "Nom d’utilisateur"},
"usernamePlaceholder": {"message": "alice"},
"passwordLabel": {"message": "Mot de passe"},
"otpLabel": {"message": "Mot de passe à usage unique (si configuré)"},
"otpPlaceholder": {"message": "123456"},
"saveAndLogIn": {"message": "Enregistrer et se connecter"},
"thisPlugin": {"message": "Cette extension"},
"pluginDescription": {"message": "Cette extension enregistre les liens sur un serveur LinkLog, qui les publiera sur un site web et éventuellement sur un service du fédivers ou ailleurs, selon les extensions configurées."},
"accountRequirement": {"message": "Les utilisateurs de cette extension doivent avoir un compte sur un serveur LinkLog"},
"privacy": {"message": "Confidentialité"},
"privacyDescription": {"message": "Cette extension respecte votre vie privée et ne recueille aucune donnée personnelle au-delà de ce qui est nécessaire pour enregistrer des liens sur votre serveur LinkLog."},
"storedData": {"message": "L’URL, après une tentative de suppression des paramètres de suivi, le titre de la page, un éventuel commentaire et l’heure de la visite seront enregistrés sur le serveur et rendus publics avec le profil de l’utilisateur qui y est inscrit."},
"backendHeading": {"message": "Serveur LinkLog"},
"backendDescription": {"message": "L’URL du serveur correspond à une application LinkLog auto-hébergée. Consultez son"},
"backendSource": {"message": "pour voir le code source."},
"copyright": {"message": "Copyright © 2026 Olaf Kolkman"},
"repository": {"message": "Dépôt"},
"signInToSelectTags": {"message": "Connectez-vous pour sélectionner des étiquettes existantes."},
"loadTagsFailed": {"message": "Impossible de charger les étiquettes existantes."},
"submitting": {"message": "Envoi..."},
"configureAndLogIn": {"message": "Configurez l’URL du serveur et connectez-vous d’abord."},
"sessionExpired": {"message": "Session expirée. Reconnectez-vous dans les paramètres."},
"submissionFailed": {"message": "Échec de l’envoi"},
"linkSaved": {"message": "Lien enregistré sur $URL$.", "placeholders": {"url": {"content": "$1"}}},
"linkAlreadyExists": {"message": "Ce lien existe déjà. Le commentaire et les étiquettes ont été mis à jour et la publication a été relancée."},
"duplicateLinkSameUrl": {"message": "Ce lien existe déjà.\nVous pouvez tout de même enregistrer l’entrée ; le commentaire et les étiquettes de l’entrée existante seront mis à jour."},
"duplicateLinkDifferentUrl": {"message": "Ce lien existe déjà. Mais le lien enregistré a une URL différente (paramètres manquants ou différents).\nSi vous enregistrez l’entrée, vous risquez de créer un doublon."},
"refetchTitle": {"message": "Récupérer à nouveau le titre"},
"titleFetchFailed": {"message": "Impossible de récupérer le titre"},
"publishingErrors": {"message": "Erreurs de publication : $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
"submissionFailedConnection": {"message": "Échec de l’envoi. Vérifiez la connexion au serveur."},
"loggedInAt": {"message": "$USERNAME$ est connecté à $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
"fillAllFields": {"message": "Veuillez remplir tous les champs"},
"loginFailed": {"message": "Échec de la connexion"},
"loggedInSuccessfully": {"message": "Connexion réussie"},
"unableToLogIn": {"message": "Connexion impossible. Vérifiez l’URL du serveur et vos identifiants."},
"signedOut": {"message": "Déconnecté"},
"characterCount": {"message": "$USED$/$LIMIT$ caractères", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}}},
"characterCountOverLimit": {"message": "$USED$/$LIMIT$ caractères : dépasse la limite de publication Mastodon de $OVER$", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}, "over": {"content": "$3"}}}
}
+59
View File
@@ -0,0 +1,59 @@
{
"extensionName": {"message": "LinkLog"},
"extensionDescription": {"message": "Paginakoppelingen vastleggen en naar LinkLog verzenden."},
"settingsTitle": {"message": "LinkLog-instellingen"},
"titleLabel": {"message": "Titel"},
"urlLabel": {"message": "URL"},
"commentLabel": {"message": "Opmerking"},
"commentPlaceholder": {"message": "Je opmerking"},
"tagsLabel": {"message": "Tags"},
"loadingTags": {"message": "Tags worden geladen..."},
"newTagsPlaceholder": {"message": "#nieuwe-tag, #andere-tag"},
"saveLink": {"message": "Koppeling opslaan"},
"settings": {"message": "Instellingen"},
"authRequired": {"message": "Log in om LinkLog te gebruiken."},
"openSettings": {"message": "Instellingen openen"},
"signOut": {"message": "Uitloggen"},
"backendUrlLabel": {"message": "Backend-URL"},
"emailLabel": {"message": "E-mail"},
"emailPlaceholder": {"message": "alice@example.com"},
"usernameLabel": {"message": "Gebruikersnaam"},
"usernamePlaceholder": {"message": "alice"},
"passwordLabel": {"message": "Wachtwoord"},
"otpLabel": {"message": "Eenmalig wachtwoord (indien geconfigureerd)"},
"otpPlaceholder": {"message": "123456"},
"saveAndLogIn": {"message": "Opslaan en inloggen"},
"thisPlugin": {"message": "Deze plug-in"},
"pluginDescription": {"message": "Deze plug-in legt koppelingen vast op een LinkLog-server, die ze publiceert op een website en mogelijk op een fediverse-dienst of andere locaties, afhankelijk van de geconfigureerde plug-ins."},
"accountRequirement": {"message": "Gebruikers van deze plug-in hebben een account op een LinkLog-server nodig"},
"privacy": {"message": "Privacy"},
"privacyDescription": {"message": "Deze plug-in respecteert je privacy en verzamelt geen persoonsgegevens buiten wat nodig is om koppelingen op je LinkLog-server vast te leggen."},
"storedData": {"message": "De URL, na een poging om trackingparameters te verwijderen, de paginatitel, een eventuele opmerking en het tijdstip van bezoek worden op de backendserver opgeslagen en samen met het profiel van de geregistreerde gebruiker openbaar gemaakt."},
"backendHeading": {"message": "LinkLog-backend"},
"backendDescription": {"message": "De backend-URL is een zelfgehoste LinkLog-toepassing. Bekijk de"},
"backendSource": {"message": "voor de broncode."},
"copyright": {"message": "Copyright © 2026 Olaf Kolkman"},
"repository": {"message": "Repository"},
"signInToSelectTags": {"message": "Log in om bestaande tags te selecteren."},
"loadTagsFailed": {"message": "Bestaande tags konden niet worden geladen."},
"submitting": {"message": "Verzenden..."},
"configureAndLogIn": {"message": "Configureer de backend-URL en log eerst in."},
"sessionExpired": {"message": "Sessie verlopen. Verifieer opnieuw in de instellingen."},
"submissionFailed": {"message": "Verzenden mislukt"},
"linkSaved": {"message": "Koppeling opgeslagen op $URL$.", "placeholders": {"url": {"content": "$1"}}},
"linkAlreadyExists": {"message": "Deze koppeling bestaat al. De opmerking en tags zijn bijgewerkt en publiceren is opnieuw gestart."},
"duplicateLinkSameUrl": {"message": "Deze koppeling bestaat al.\nJe kunt de invoer nog steeds opslaan; de opmerking en tags van de bestaande koppeling worden dan bijgewerkt."},
"duplicateLinkDifferentUrl": {"message": "Deze koppeling bestaat al. De opgeslagen koppeling heeft echter een andere URL (ontbrekende of andere parameters).\nAls je de invoer opslaat, loop je het risico op een dubbele koppeling."},
"refetchTitle": {"message": "Titel opnieuw ophalen"},
"titleFetchFailed": {"message": "Titel kon niet worden opgehaald"},
"publishingErrors": {"message": "Publicatiefouten: $ERRORS$", "placeholders": {"errors": {"content": "$1"}}},
"submissionFailedConnection": {"message": "Verzenden mislukt. Controleer de verbinding met de backend."},
"loggedInAt": {"message": "$USERNAME$ is ingelogd op $BACKEND$", "placeholders": {"username": {"content": "$1"}, "backend": {"content": "$2"}}},
"fillAllFields": {"message": "Vul alle velden in"},
"loginFailed": {"message": "Inloggen mislukt"},
"loggedInSuccessfully": {"message": "Succesvol ingelogd"},
"unableToLogIn": {"message": "Inloggen mislukt. Controleer de backend-URL en inloggegevens."},
"signedOut": {"message": "Uitgelogd"},
"characterCount": {"message": "$USED$/$LIMIT$ tekens", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}}},
"characterCountOverLimit": {"message": "$USED$/$LIMIT$ tekens - overschrijdt de Mastodon-postlimiet met $OVER$", "placeholders": {"used": {"content": "$1"}, "limit": {"content": "$2"}, "over": {"content": "$3"}}}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 950 B

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 13 KiB

+21
View File
@@ -0,0 +1,21 @@
// Copyright © 2026 Olaf Kolkman
// SPDX-License-Identifier: GPL-3.0-or-later
function getLocalizedMessage(messageId, substitutions = []) {
const message = browser.i18n.getMessage(messageId, substitutions);
return message || messageId;
}
window.linklogI18n = getLocalizedMessage;
document.querySelectorAll('[data-i18n]').forEach((element) => {
element.textContent = getLocalizedMessage(element.dataset.i18n);
});
document.querySelectorAll('[data-i18n-placeholder]').forEach((element) => {
element.placeholder = getLocalizedMessage(element.dataset.i18nPlaceholder);
});
document.querySelectorAll('[data-i18n-alt]').forEach((element) => {
element.alt = getLocalizedMessage(element.dataset.i18nAlt);
});
+1 -1
View File
@@ -5,7 +5,7 @@
<svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;"> <svg width="100%" height="100%" viewBox="0 0 1804 1712" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1,0,0,1,-669.006,-255.89)"> <g transform="matrix(1,0,0,1,-669.006,-255.89)">
<g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)"> <g transform="matrix(0.972876,0,0,1.26057,-24.1588,-587.485)">
<rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(88,91,112);"/> <rect x="712.491" y="669.041" width="1854.11" height="1357.72" style="fill:rgb(24, 24, 37);"/>
</g> </g>
<g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)"> <g transform="matrix(5.14628,0,0,6.12686,41.2191,-8673.98)">
<path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/> <path d="M141.95,1644.94L141.95,1633.94C157.554,1633.4 169.724,1631.04 178.462,1626.86C187.2,1622.69 193.344,1615.8 196.894,1606.21C200.444,1596.61 202.218,1583.47 202.218,1566.77C202.218,1554.44 201.146,1544.16 199,1535.93C196.855,1527.7 193.285,1521.25 188.292,1516.57C185.016,1513.6 181.154,1511.26 176.707,1509.54C172.26,1507.83 167.15,1506.62 161.376,1505.92C155.603,1505.21 149.128,1504.86 141.95,1504.86L141.95,1493.86L384.076,1493.86L384.076,1504.86C373.388,1504.86 364.221,1505.7 356.575,1507.38C348.929,1509.06 342.708,1512.12 337.909,1516.57C333.111,1521.01 329.581,1527.27 327.319,1535.35C325.056,1543.42 323.925,1553.9 323.925,1566.77L323.925,1633.36C339.06,1633.36 353.532,1631.08 367.341,1626.51C381.15,1621.95 393.399,1616 404.087,1608.66C414.776,1601.41 423.299,1593.3 429.657,1584.32C436.016,1575.35 439.546,1566.61 440.248,1558.11L452.536,1558.11C452.536,1562.4 452.419,1568.35 452.185,1575.96C451.951,1583.56 451.6,1591.85 451.132,1600.82C450.586,1609.95 449.942,1618.34 449.201,1625.99C448.46,1633.63 447.582,1639.95 446.568,1644.94L141.95,1644.94Z" style="fill:rgb(245,224,220);fill-rule:nonzero;"/>

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

+13 -9
View File
@@ -1,18 +1,22 @@
{ {
"manifest_version": 3, "manifest_version": 3,
"name": "LinkLog", "name": "__MSG_extensionName__",
"version": "0.1.0", "version": "0.3.0",
"description": "Capture and submit page links to LinkLog.", "description": "__MSG_extensionDescription__",
"default_locale": "en-US",
"permissions": [ "permissions": [
"activeTab", "activeTab",
"storage", "storage"
"tabs"
], ],
"host_permissions": [ "optional_permissions": [
"<all_urls>" "http://*/*",
"https://*/*"
], ],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'none'"
},
"action": { "action": {
"default_title": "LinkLog", "default_title": "__MSG_extensionName__",
"default_popup": "popup.html", "default_popup": "popup.html",
"default_icon": { "default_icon": {
"16": "icon-16.png", "16": "icon-16.png",
@@ -26,7 +30,7 @@
"browser_specific_settings": { "browser_specific_settings": {
"gecko": { "gecko": {
"id": "linklog@kolkman.org", "id": "linklog@kolkman.org",
"strict_min_version": "109.0", "strict_min_version": "142.0",
"data_collection_permissions": { "data_collection_permissions": {
"required": ["websiteActivity"], "required": ["websiteActivity"],
"optional": [] "optional": []
+65 -34
View File
@@ -2,44 +2,75 @@
<!-- Copyright © 2026 Olaf Kolkman --> <!-- Copyright © 2026 Olaf Kolkman -->
<!-- SPDX-License-Identifier: GPL-3.0-or-later --> <!-- SPDX-License-Identifier: GPL-3.0-or-later -->
<html lang="en"> <html lang="en">
<head>
<meta charset="utf-8" />
<title>LinkLog Settings</title>
<link rel="stylesheet" href="options.css" />
</head>
<body>
<main class="options-shell">
<img class="extension-logo" src="logo.svg" alt="LinkLog" />
<h1>Settings</h1>
<div id="status" class="status hidden" aria-live="polite"></div> <head>
<meta charset="utf-8" />
<title data-i18n="settingsTitle">LinkLog Settings</title>
<link rel="stylesheet" href="options.css" />
</head>
<section id="logged-in" class="logged-in hidden" aria-live="polite"> <body>
<p id="session-summary"></p> <main class="options-shell">
<button type="button" id="sign-out">Sign out</button> <img class="extension-logo" src="logo.svg" data-i18n-alt="extensionName" alt="LinkLog" />
</section> <h1 data-i18n="settings">Settings</h1>
<form id="settings-form"> <div id="status" class="status hidden" aria-live="polite"></div>
<label>
Backend URL
<input id="backend-url" type="url" placeholder="https://example.com" />
</label>
<label> <section id="logged-in" class="logged-in hidden" aria-live="polite">
Username <p id="session-summary"></p>
<input id="username" type="text" placeholder="alice" /> <button type="button" id="sign-out" data-i18n="signOut">Sign out</button>
</label> </section>
<label> <form id="settings-form">
Password <label>
<input id="password" type="password" placeholder="********" /> <span data-i18n="backendUrlLabel">Backend URL</span>
</label> <input id="backend-url" type="url" placeholder="https://example.com" />
</label>
<button type="submit">Save and log in</button> <label>
</form> <span data-i18n="emailLabel">Email</span>
</main> <input id="email" type="email" data-i18n-placeholder="emailPlaceholder" placeholder="alice@example.com" />
<footer class="extension-footer">Copyright © 2026 Olaf Kolkman · <a href="https://git.kolkman.org/olaf/Link-Log">Repository</a></footer> </label>
<script src="options.js"></script> <label>
</body> <span data-i18n="passwordLabel">Password</span>
</html> <input id="password" type="password" />
</label>
<label>
<span data-i18n="otpLabel">One-time password</span>
<input id="otp" type="text" inputmode="numeric" autocomplete="one-time-code" data-i18n-placeholder="otpPlaceholder" placeholder="123456" />
</label>
<button type="submit" data-i18n="saveAndLogIn">Save and log in</button>
</form>
<section class="about-plugin">
<h2 data-i18n="thisPlugin">This Plugin</h2>
<p data-i18n="pluginDescription">This plugin will log links to a backend LinkLog server which will publish them on a website and potentially as
an entry
on a fediverse service or other locations, depending on the plugins configured.</p>
<p data-i18n="accountRequirement">Users of this plugin will need an account on a LinkLog server</p>
<h2 data-i18n="privacy">Privacy</h2>
<p data-i18n="privacyDescription">This plugin respects your privacy and does not collect any personal data beyond what is necessary to log links
to your LinkLog server.</p>
<p data-i18n="storedData">The URL - after a best effort try to remove tracking parameters -, the title of the webpage, a possible
comment, and a timestamp of visit will be stored on the backend server, and will be made public in combination
with
the user's profile as registered on the backend server.
</p>
<h2 data-i18n="backendHeading">LinkLog Backend</h2>
<p><span data-i18n="backendDescription">The backend URL is a selfhosted linklog application. See its</span> <a
href="https://git.kolkman.org/olaf/Link-Log" data-i18n="repository">repository</a> <span data-i18n="backendSource">for its source.</span></p>
</section>
</main>
<footer class="extension-footer"><span data-i18n="copyright">Copyright © 2026 Olaf Kolkman</span> · <a
href="https://git.kolkman.org/olaf/Link-Log" data-i18n="repository">Repository</a></footer>
<script src="l10n.js"></script>
<script src="options.js"></script>
</body>
</html>

Some files were not shown because too many files have changed in this diff Show More